from dataclasses import dataclass, field
import datetime
import io
import itertools as it
import json
from typing import Dict, Union, List

import pandas as pd
import requests
from redfin import Redfin
from dask import delayed
from dask.distributed import Client, as_completed

REDFIN_ENDPOINT='https://www.redfin.com/stingray/api/gis-csv?'

def gen_headers():
    """ Request headers"""
    headers = {
        'authority': 'www.redfin.com',
        'content-length': '0',
        'sec-ch-ua': '"Chromium";v="92", " Not A;Brand";v="99", "Google Chrome";v="92"',
        'sec-ch-ua-mobile': '?0',
        'user-agent': 'Mozilla/5.0 (X11; CrOS x86_64 13982.82.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.157 Safari/537.36',
        'content-type': 'text/plain;charset=UTF-8',
        'accept': '*/*',
        'origin': 'https://www.redfin.com',
        'sec-fetch-site': 'same-origin',
        'sec-fetch-mode': 'no-cors',
        'sec-fetch-dest': 'empty',
        'referer': 'https://www.redfin.com/city/12839/DC/Washington-DC',
        'accept-language': 'en-US,en;q=0.9',
    }
    return headers

def gen_params():
    """ Redfin search parameters"""
    params = {
        'al': 1,
        'hoa': 150,
        'market': 'dc',
        'max_listing_approx_size': 3000,
        'min_listing_approx_size': 1700,
        'max_num_beds': 4,
        'max_price': 800_000,
        'num_baths': 2,
        'num_beds': 2,
        'num_homes': 450,
        'page_number': 1,
        'region_id': 2965,
        'region_type': 5,
        'sf': '1,2,3,5,6,7',
        'status': 9,
        'uipt': '1,2,3,4,5,6,7,8',
        'v': 8
    }
    return params

def gen_cols():
    """ Columns to keep from Redfin listings"""
    relevant_columns = [
        'ADDRESS', 'CITY', 'STATE OR PROVINCE', 'ZIP OR POSTAL CODE', "PRICE",
    ]
    return relevant_columns

def gen_final_cols():
    final_columns = [
        'ADDRESS', 'CITY', 'STATE OR PROVINCE', 'ZIP OR POSTAL CODE', "PRICE",
        'tax_assessed_value', 'date'
    ]
    return final_columns

@dataclass
class Agent:
    """ Stores Redfin query parameters, runs Redfin
    query, digests output"""
    request_headers: Dict[str, str] = field(default_factory=gen_headers)
    redfin_query_params: Dict[str, Union[int, str]] = field(default_factory=gen_params)
    keep_cols: List[str] = field(default_factory=gen_cols)
    final_cols: List[str] = field(default_factory=gen_final_cols)

    def pull_listings(self):
        """ Query redfin for listings"""
        with requests.Session() as session:
            session.headers.update(self.request_headers)
            download = session.get(
                REDFIN_ENDPOINT,
                params=self.redfin_query_params,
            )
        return download

    def digest_listings(self, download: requests.Response):
        """ Convert get request into dataframe"""
        if download.status_code != 200:
            raise RuntimeError(
                "Error making listings request: " +
                f"{download.content.decode('UTF-8')}"
            )
        df = pd.read_csv(
            io.StringIO(download.content.decode("utf-8")),
            low_memory=False, error_bad_lines=False
        )

        missing_cols = [c for c in self.keep_cols if c not in df.columns]
        if len(missing_cols) > 0:
            raise RuntimeError(
                f"Redfin listings missing {len(missing_cols)} " +
                f"columns: {missing_cols}"
            )

        return df[self.keep_cols].assign(
            full_address=lambda x: x['ADDRESS'] + ', ' + x['CITY']
                + ' ' + x['STATE OR PROVINCE']
        )

    def pull_details(self, list_of_addresses: List[str]):
        """ Query for below-the-fold information"""
        daskclient = Client()
        redfinclient = Redfin()
        with requests.Session() as session:
            session.headers.update(self.request_headers)
            session_scattered = daskclient.scatter(session)
            redfinclient_scattered = daskclient.scatter(redfinclient)
            futures = [
                delayed(self.query_redfin_dask)(session_scattered,
                    redfinclient_scattered, address)
                for address in list_of_addresses
            ]
            futures = daskclient.compute(futures)
            completed_results = [
                result for a, result in
                as_completed(futures, raise_errors=False, with_results=True)
            ]
        daskclient.close()

        return completed_results

    def digest_details(
        self,
        df: pd.DataFrame,
        completed_results: List[Dict[str, float]]
    ):
        """ Process below-the-fold responses into dataframe"""
        timestamp = datetime.datetime.now().strftime("%Y-%m-%d")
        processed_df = (
            df.merge(
                self.compile_results(completed_results),
                left_on='full_address', right_index=True
            ).assign(date=timestamp)
        )

        return processed_df[self.final_cols]

    def query_redfin_dask(
        self,
        session: requests.Session,
        redfinclient: Redfin,
        address: str,
        **kwargs
    ):
        """ For a given address, query redfin and identify tax-assessed value

        This is the function we submit to the dask client
        """
        response = session.get(
            'https://redfin.com/stingray/do/location-autocomplete',
            params={
                'location': address,
                'v': 2,
                **kwargs
            },
        )
        return {address: self.process_redfin_response(response, redfinclient)}

    def process_redfin_response(
        self,
        response: requests.Response,
        redfinclient: Redfin
    ):
        """ Given a response from redfin API, return the tax-assessed value

        Notes
        -----
        This can get messy because this response is deeply-nested JSON, and
        there are many chances for us to fail at pulling tax values.
        In all the places where things can go wrong, I do a very sloppy check and
        then return -1 if something broke
        """
        if response.status_code != 200:
            return -1
        else:
            resp_dict = json.loads(response.text[4:])
            if (
                (resp_dict.get('errorMessage', None) == 'Success') &
                ('exactMatch' in resp_dict['payload'])
            ):
                # Pull property metadata
                url = resp_dict['payload']['exactMatch']['url']

                data = redfinclient.initial_info(url)['payload']
                if data['responseCode'] != 200:
                    return -1
                property_id = data['propertyId']
                listing_id = data['listingId']
                info = redfinclient.below_the_fold(property_id)
                # Pull latest tax-assessed value
                if len(info['payload']['publicRecordsInfo']['allTaxInfo']) > 0:
                    tax_assessment = (
                        pd.DataFrame(
                            info['payload']['publicRecordsInfo']['allTaxInfo']
                        ) .sort_values("rollYear", ascending=False)
                    ).iloc[0]
                    return (
                        tax_assessment.get('taxableLandValue', 0) +
                        tax_assessment.get('taxableImprovementValue', 0)
                    )
                else:
                    return -1
            else:
                return -1

    def compile_results(self, results: List[Dict[str, float]]):
        """ Aggregate the results from all the redfin requests into a single series

        Take a list of dictionaries (from the dask future objects),
        flatten them into one dictionary, then turn into a pandas series
        """
        compiled = pd.Series(
            dict(it.chain.from_iterable(a.items() for a in results)),
            name='tax_assessed_value'
        )

        return compiled


import os

from django.core.files import File
from django.db import migrations

base_path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
                         'avatars')

def save_image_from_file(field, name):
    path = os.path.join(base_path, name)
    f = open(path, 'rb')
    field.save(name, File(f), save=True)

def add_item(apps, schema_editor):
    Teacher = apps.get_model('app', 'Teacher')
    Achievement = apps.get_model('app', 'Achievement')

    teachers = Teacher.objects.all()

    for i, teacher in enumerate(teachers):
        if i > 20:
            break

        titles = ['特级教师', '全国奥数总冠军']
        for j in range(2):
            achievement = Achievement(teacher=teacher, title=titles[j])
            name = 'img%d.jpg' % ((i + j) % 8)
            save_image_from_file(achievement.img, name)
            achievement.save()

class Migration(migrations.Migration):

    dependencies = [
        ('app', '0048_highscore'),
    ]

    operations = [
        migrations.RunPython(add_item),
    ]


from flask import Blueprint, request, jsonify, make_response
from services.user_service import UserService
from common.utils.request_util import check_token
from common.utils.error_util import UserTypeError, UserNotFoundError, NoFriendsFoundError

user_controller = Blueprint("user_controller", __name__)
user_service = UserService()

@user_controller.route("/users/me", methods=["GET"])
@check_token
def get_current_user_profile(user_id):
    try:
        user_data = user_service.get_current_user_profile(user_id)
        return {'data': user_data}
    except Exception as e:
        response = make_response({'error': True, 'message': str(e)}, 500)
        return response

@user_controller.route("/users/me", methods=["PATCH"])
@check_token
def update_current_user_profile(user_id):
    try:
        data = request.json
        add_status = user_service.update_user_profile(user_id, data)
        if add_status:
            return {'ok': True}
        else:
            return {'error': True}
    except UserNotFoundError as e:
        response = make_response({'error': True, 'message': str(e)}, 401)
        return response
    except UserTypeError as e:
        response = make_response({'error': True, 'message': str(e)}, 400)
        return response

@user_controller.route("/users/<int:path_user_id>", methods=["GET"])
@check_token
def get_user_info(user_id, path_user_id):
    try:
        user_data = user_service.get_user_info(user_id, path_user_id)
        return {'data': user_data}
    except Exception as e:
        return {'error': True, 'message': str(e)}, 500

@user_controller.route("/users/me/friends", methods=["GET"])
@check_token
def get_user_friends(user_id):
    try:
        page = request.args.get('page')
        friends_list, next_page = user_service.get_user_friends(page, user_id)
        return {'data': friends_list, 'next_page': next_page}
    except NoFriendsFoundError as e:
        return {'error': True, 'message': str(e)}, 404
    except Exception as e:
        return {'error': True, 'message': str(e)}, 500

@user_controller.route("/users/me/match", methods=["GET"])
@check_token
def get_user_match(user_id):
    try:
        match_user = user_service.get_user_match(user_id)
        return {'data': match_user}
    except Exception as e:
        return {'error': True, 'message': str(e)}, 500

@user_controller.route("/users/me/invitation", methods=["POST"])
@check_token
def add_user_invitations(user_id):
    data = request.json
    is_friend = user_service.add_user_invitations(user_id, data)
    return {'IsFriend': is_friend}

@user_controller.route("/users/me/chatrooms", methods=["GET"])
@check_token
def get_user_chatrooms(user_id):
    try:
        page = request.args.get('page')
        last_chatroom = request.args.get('last')

        if last_chatroom:
            chatroom_id = user_service.get_last_chatroom(user_id)
            return {'data': chatroom_id}

        chatrooms_list = user_service.get_user_chatrooms(user_id, page)
        return {'data': chatrooms_list}

    except Exception as e:
        return {'error': True, 'message': str(e)}, 500

@user_controller.route('/users/me/chatrooms/<int:id>', methods=['GET'])
@check_token
def get_chats(user_id, id):
    try:
        page = request.args.get('page')
        messages = user_service.get_user_messages(id, user_id, page)
        return {'data': messages}
    except Exception as error:
        return {'error': str(error)}, 500

@user_controller.route('/users/me/liked_posts', methods=['GET'])
@check_token
def get_liked_posts(user_id):
    try:
        page = request.args.get('page')
        posts_list, next_page = user_service.get_liked_posts(user_id, page)
        return {"data": posts_list, "next_page": next_page}
    except Exception as error:
        return {'error': str(error)}, 500


import punkt

a = punkt.Punkt() # Instanz
b = punkt.Punkt(1.2,1.1) # Instanz

a.ausgabe(True)
b.ausgabe(False)

d1 = a.distanz(b)
d2 = b.distanz(a)
d3 = a.distanz(a)

print(d1)
print(d2)
print(d3)


# объявляем библиотеки

import pandas as pd
from openpyxl import load_workbook
from openpyxl.styles import NamedStyle, Font, Border, Side, Alignment, PatternFill
from openpyxl.styles.numbers import BUILTIN_FORMATS
from flask import send_file

from datetime import date

# Процедура обработки выписки
def v_treatment(HalykFileName, SberFileName):

    # считываем exel файл по Сбербанку

    data_sber = pd.read_excel(SberFileName, sheet_name=0, header=6)

    # проверяем, есть ли записи об операциях в файле

    if len(data_sber) > 0:

        # удаляем последние 2 строки
        data_sber = data_sber.loc[:(len(data_sber) - 3)]

        # конверируем дату в формат datetime
        data_sber['Дата валютирования'] = pd.to_datetime(data_sber['Дата валютирования'], format='%d.%m.%Y')

    # считываем exel файл по Halyk банку
    data_halyk = pd.read_excel(HalykFileName, sheet_name=0, header=10)

    # проверяем, есть ли записи об операциях в файле

    if len(data_halyk) > 0:
        # удаляем последние 2 строки
        data_halyk = data_halyk.loc[:(len(data_halyk) - 3)]

        # конверируем дату в формат datetime
        data_halyk['Дата валютирования'] = pd.to_datetime(data_halyk['Дата валютирования'], format='%d.%m.%Y')

        # дополняем в таблицу Халык Банк столбец Дата
        data_halyk.insert(0, 'Дата', '')

        # меняем местами столбцы в таблице Халык Банк

        data_halyk = data_halyk[
            ['Дата', 'Дата валютирования', 'Номер документа', 'Контрагент', 'БИН контрагента', 'Счет контрагента',
             'Банк контрагента', 'БИК банка контрагента', 'Дебет', 'Кредит', 'Назначение платежа']]

        # переименовываем столбцы в таблице Халык Банк

        data_halyk.columns = ['Дата', 'Дата валютирования', 'Номер', 'Контрагент', 'БИН', 'Счет контрагента',
                              'Банк контрагента', 'БИК', 'Дебет', 'Кредит', 'Назначение платежа']

    # соединяем таблицы Сбербанк и Халык Банк

    if len(data_sber) > 0:
        data = data_sber.copy()
        data = data.append(data_halyk)

    else:
        data = data_halyk

    # меняем типы данных и отсортируем таблицу

    data = data.reset_index(drop=True)

    data['БИН'] = data['БИН'].astype('int64')

    data['Дебет'] = data['Дебет'].str.replace(",", ".")
    data['Дебет'] = data['Дебет'].str.replace(" ", "")
    data['Дебет'] = data['Дебет'].astype('float64')

    data['Кредит'] = data['Кредит'].str.replace(",", ".")
    data['Кредит'] = data['Кредит'].str.replace(" ", "")
    data['Кредит'] = data['Кредит'].astype('float64')

    data = data.sort_values(by=['Дата валютирования','Номер'])

    data = data.reset_index(drop=True)

    # записывает полученные данные в файл

    data.to_excel('Итог.xlsx', sheet_name='KZ61914082203KZ017H9', index = False, engine='openpyxl')

    # открываем файл для изменения стиля ячеек

    wb = load_workbook('Итог.xlsx')
    sheet = wb['KZ61914082203KZ017H9']

    # фиксируем стиль для границ ячейки (рамку)

    bd = Side(style='thin', color="000000")

    # проводим передор ячеек и меняем стили

    col_name = 'ABCDEFGHIJK'

    for k in range(0, 11):
        for i in range(2, len(data) + 2):
            sheet[col_name[k] + str(i)].font = Font(name='Times New Roman', bold=False, size=8)
            sheet[col_name[k] + str(i)].border = Border(left=bd, top=bd, right=bd, bottom=bd)

            if k == 1:
                sheet[col_name[k] + str(i)].number_format = BUILTIN_FORMATS[14]

            if k == 4:
                sheet[col_name[k] + str(i)].number_format = BUILTIN_FORMATS[1]

            if (k == 8) or (k == 9):
                sheet[col_name[k] + str(i)].number_format = BUILTIN_FORMATS[4]

            if (k == 10):
                sheet[col_name[k] + str(i)].alignment = Alignment(wrap_text=True)

            if (i == 2):
                sheet[col_name[k] + str(i)].fill = PatternFill("solid", fgColor="00AAEE")

            if sheet['A' + str(i)].value == None:
                sheet[col_name[k] + str(i)].fill = PatternFill("solid", fgColor="FFFF00")

    # изменяем ширину столбцов

    sheet.column_dimensions['A'].width = 12
    sheet.column_dimensions['B'].width = 14
    sheet.column_dimensions['C'].width = 8
    sheet.column_dimensions['D'].width = 24
    sheet.column_dimensions['E'].width = 16
    sheet.column_dimensions['F'].width = 24
    sheet.column_dimensions['G'].width = 24
    sheet.column_dimensions['H'].width = 16
    sheet.column_dimensions['I'].width = 16
    sheet.column_dimensions['J'].width = 16
    sheet.column_dimensions['K'].width = 36

    print(sheet['A2'].value)

    # записываем результат в файл

    wb.save('Итог.xlsx')

    return


#취득학점 수 입력받아 졸업가능 여부 판단(while, if문 사용)

#초기화
num=0
#몇번 반복할건지
i=1

#반복문(3번 반복)
while i <= 3:
  num = input("취득학점 수: ")
  #조건문(140학점 이상이면)
  if(int(num)>=140):
    print("졸업가능")
    i=i+1
  else:
    print("졸업불가")
    i=i+1


"""
Asynchronous python demonstration.
© 2021 Craig de Stigter; https://github.com/craigds
BSD 2-clause license.

Prerequisite:
    pip install -r requirements.txt
"""
import time
import asyncio

from aiohttp_requests import requests

async def get_url(url):
    print(f"starting to get {url}")
    start_time = time.monotonic()
    response = await requests.get(url)
    time_elapsed = time.monotonic() - start_time
    print(f"got {url} in {time_elapsed:.3f}s!")
    print()
    return response

async def main():
    start_time = time.monotonic()
    awaitables = []
    awaitables.append(get_url("http://example.com"))
    awaitables.append(get_url("http://example.com/a"))
    awaitables.append(get_url("http://example.com/b"))
    awaitables.append(get_url("http://example.com/c"))

    # wait for all the above, then do something else
    responses = await asyncio.gather(*awaitables)
    await get_url("http://example.com/final_url")

    time_elapsed = time.monotonic() - start_time
    print(f"did everything in {time_elapsed:.3f}s")

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())


import re
filename = "lib.txt"
fh = open(filename)
print('Reading all hashtags from : '+ filename)
counts = dict()
templist = list()
sortlist = list()
total = 0
for line in fh:
    templist = re.findall('#\S+',line)
    for words in templist:
        total += 1
        counts[words] = counts.get(words,0)+1
for k,v in counts.items():
    sortlist.append((v,k))
sortlist = sorted(sortlist, reverse = True)

print('Total count of Hashtags read from the file is :' , total)
print('Best 30 Hastags for your post will be :-')
for v,k in sortlist[:30]:
    print(k,end=' ')

#print(sorted([(v,k) for k,v in counts.items()],reverse =True))


import os

from fairseq.data import FileAudioDataset
from . import FairseqTask, register_task

@register_task('audio_pretraining')
class AudioPretrainingTask(FairseqTask):
    """

    """

    @staticmethod
    def add_args(parser):
        """Add task-specific arguments to the parser."""
        parser.add_argument('data', help='path to data directory')
        parser.add_argument('--sample-rate', default=16000, type=int,
                            help='target sample rate. audio files will be up/down sampled to this rate')
        parser.add_argument('--max-sample-size', default=None, type=int,
                            help='max sample size to crop to for batching. default = min sample length')
        parser.add_argument('--min-sample-size', default=None, type=int,
                            help='min sample size to crop to for batching. default = same as --max-sample-size')

    def __init__(self, args):
        super().__init__(args)

    @classmethod
    def setup_task(cls, args, **kwargs):
        """Setup the task (e.g., load dictionaries).

        Args:
            args (argparse.Namespace): parsed command-line arguments
        """
        return cls(args)

    def load_dataset(self, split, **kwargs):
        """Load a given dataset split.

        Args:
            split (str): name of the split (e.g., train, valid, test)
        """

        manifest = os.path.join(self.args.data, '{}.tsv'.format(split))
        self.datasets[split] = FileAudioDataset(manifest,
                                                 sample_rate=self.args.sample_rate,
                                                 max_sample_size=self.args.max_sample_size,
                                                 min_sample_size=self.args.min_sample_size)

    @property
    def target_dictionary(self):
        """Return the :class:`~fairseq.data.Dictionary` for the language
        model."""
        return None


"""Tool for the Google Scholar"""

from typing import Optional

from langchain_core.callbacks import CallbackManagerForToolRun
from langchain_core.tools import BaseTool

from langchain_community.utilities.google_scholar import GoogleScholarAPIWrapper

class GoogleScholarQueryRun(BaseTool):
    """Tool that queries the Google search API."""

    name: str = "google_scholar"
    description: str = (
        "A wrapper around Google Scholar Search. "
        "Useful for when you need to get information about"
        "research papers from Google Scholar"
        "Input should be a search query."
    )
    api_wrapper: GoogleScholarAPIWrapper

    def _run(
        self,
        query: str,
        run_manager: Optional[CallbackManagerForToolRun] = None,
    ) -> str:
        """Use the tool."""
        return self.api_wrapper.run(query)


'''
	스택 활용: 후위 표기법을 이용한 수식 계산
		- evalPostfix		: 후위 표기법으로 수식 계산
		- InfixToPostfix	: 중위 표기법을 후위 표기법으로 변환
			중위 표기: (A + B) - C
			후위 표기: A B + C -
			전위 표기: - + A B C
'''

from LinkedStack import LinkedStack

# 연산자 여부를 판별한다.
def isOperator(op) -> bool :
    return op == '+' or op == '-' or op == '*' or op == '/'

# 연산자 우선순위를 수치로 변환
def precedence(op) -> int :
	if op == '(' : return 0
	elif op == '+' or op == '-' : return 1
	elif op == '*' or op == '/' : return 2
	else : return 3

# 후위표기법 변환(중위 표기 -> 후위 표기)
def InfixToPostfix(infix) :
    s = LinkedStack()	# 빈 스택 생성

    # split을 위해 연산자 앞 뒤에 공백을 넣어준다.
    infix = infix.replace('(', ' ( ')
    infix = infix.replace(')', ' ) ')
    infix = infix.replace('+', ' + ')
    infix = infix.replace('-', ' - ')
    infix = infix.replace('*', ' * ')
    infix = infix.replace('/', ' / ')
    infix = infix.split()

    postfix = []
    for st in infix :
        # 1) '(' 는 스택에 push
        if st == '(' :
            s.push(st)
        # 2) ')'를 만나면 '('가 나올 때까지 pop 한 후에 '('는 버린다.
        elif st == ')' :
            while s.peek() != '(' :
                postfix.append(s.pop())
            s.pop()     # '(' 를 버린다.
        # 3) 연산자인 경우...
        elif isOperator(st) :
            while not s.isEmpty() and precedence(s.peek()) >= precedence(st) :
                # 자신보다 높은 우선순위의 연산자는 스택에서 pop
                postfix.append(s.pop())
            s.push(st)    # 자신을 push
        # 4) 피연산자인 경우...
        elif str.isdigit(st) :
            postfix.append(st)
        elif st == ' ' : continue
        else :
            print('잘못된 수식!!!')
            return
    # 스택에 남은 연산자를 모두 pop 한다.
    while not s.isEmpty() :
        postfix.append(s.pop())
    return postfix

# 후위 표기법: 수식 계산
def  evalPostfix(sList) -> int :
    s = LinkedStack()	# 빈 스택 생성
    for st in sList :
        # 1) 피연산자 일 경우...
        if str.isdigit(st) :
            s.push(st)
        # 2) 연산자 일 경우...
        elif isOperator(st) :
            op2 = int(s.pop())
            op1 = int(s.pop())
            if st == '+': s.push(op1 + op2)
            elif st == '-': s.push(op1 - op2)
            elif st == '*': s.push(op1 * op2)
            elif st == '/': s.push(op1 / op2)
            elif st == ' ' : continue
            else :
                print('잘못된 수식!!!')
                return
    # 스택에 남은 최종 결과 값
    if not s.isEmpty() :
        res = s.pop()
    return res

if __name__ == '__main__':
	infix = input('수식 입력: ')

	postfix = InfixToPostfix(infix)
	print(f'후위표기법 변환: {postfix}')

	res = evalPostfix(postfix)
	print(f'연산결과: {res}')


# ============================================
# ==           GLOBAL CONSTANTS             ==
# ============================================
# Some values are used by lots of parts of the
# code and it would be helpful to be able to
# keep track of them universally or to be able
# to change them in one place. They go here.

# Directions

UP = 0
DOWN = 1
LEFT = 2
RIGHT = 3

# Buttons
# (Directions double as buttons for those directions)
JUMP = 4
ZOOM_IN = 5
ZOOM_OUT = 6
PAUSE = 7

# Physics Information
GRAVITY_STRENGTH = 0.2
TERMINAL_VELOCITY = 4

# Screen Information
SCREEN_W = 640
SCREEN_H = 480
STARTING_CAMERA_ZOOM = 1.5

# Map Information

TILESIZE = 16
BLOCK_LAYER = 2 # This is the layerID in Tiled we use for solidity checks with tiles on the map.

# Sprite IDs
PLAYER = 0
ENEMY = 100

# Sprite State Flags
# Each Sprite will have their own unique state flags, but we'll make some of them
# universal because they matter for sprite_handler things like collision checks.
DYING = -1
DEAD = -2

# Game States
MAIN_MENU = 0
PLAYING = 1
PAUSED = 2
GAME_OVER = 3

# Graphics information
TRANSPARENT_COLOR = 0


#!/usr/bin/env python3
from aws_cdk import core, aws_lambda_python, aws_lambda

class Stack(core.Stack):
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        handler = aws_lambda_python.PythonFunction(
            self,
            "MyFunction",
            entry="code",
            runtime=aws_lambda.Runtime.PYTHON_3_8,
            index="src/main.py",
            handler="handler",
        )

        function_url = handler.add_function_url(
            auth_type=aws_lambda.FunctionUrlAuthType.NONE
        )

        core.CfnOutput(
            self,
            "api-url",
            value=function_url.url,
            export_name="url",
        )

app = core.App()

Stack(app, "FastApiTest")

app.synth()


import excalibur

@excalibur.debug
def least_operation_to_edit(str1, str2, str1_length, str2_length):
    """
    Insert
    Remove
    Replace

    Input:   str1 = "geek", str2 = "gesek"
    Output:  1
    We can convert str1 into str2 by inserting a 's'.

    Input:   str1 = "cat", str2 = "cut"
    Output:  1
    We can convert str1 into str2 by replacing 'a' with 'u'.

    Input:   str1 = "sunday", str2 = "saturday"
    Output:  3
    Last three and first characters are same.  We basically
    need to convert "un" to "atur".  This can be done using
    below three operations.
    Replace 'n' with 'r', insert t, insert a

    """
    if str1_length == 0:
        return str2_length
    elif str2_length == 0:
        return str1_length

    to_add = 1

    if str1[-1] == str2[-1]:
        to_add = 0

    #insert:str1 need to insert 1 char to match to str2
    insert_operation = least_operation_to_edit(str1, str2[:-1], str1_length, str2_length - 1)
    #remove: str1 need to remove 1 char to match to str2
    remove_operation = least_operation_to_edit(str1[:-1], str2, str1_length - 1, str2_length)
    #replace
    replace_operation = least_operation_to_edit(str1[:-1], str2[:-1], str1_length - 1, str2_length - 1)

    total_edit = to_add + min(insert_operation, remove_operation, replace_operation)

    return total_edit

if __name__ == "__main__":
    print(least_operation_to_edit("geek", "gesek", 4, 5))
    print(least_operation_to_edit("sunday", "saturday", 6, 8))


# Turtle script example
import turtle

t = turtle.Turtle('turtle')

angles = input("Input the amount of angles: ")

t.width(5)
angles = int(angles)
color = ['red', 'firebrick', 'yellow', 'goldenrod', 'green', 'lime', 'blue', 'dodger blue']

for i in range(angles):
    t.color(color[i % 7])
    t.forward(500 / angles)
    t.left(360 / angles)

t.penup()

turtle.done()


import sys

itemsInBackpack = ["book", "computer", "keys", "travel mug"]

while True:
    print("Would you like to:")
    print("1. Add an item to the backpack?")
    print("2. Check if an item is in the backpack?")
    print("3. Quit")
    userChoice = input()

    if(userChoice == "1"):
        print("What item do you want to add to the backpack?")
        itemToAdd = input()

        ####### YOUR CODE HERE ######
        itemsInBackpack.append(itemToAdd)
        ####### YOUR CODE HERE ######

    if(userChoice == "2"):
        print("What item do you want to check to see if it is in the backpack?")
        itemToCheck = input()

        ####### YOUR CODE HERE ######
        # assume failiure, switch the message if we do find it
        result = "FAIL: " + itemToCheck + " not found"
        for item in itemsInBackpack:
            if item == itemToCheck:
                result = "SUCCESS: " + itemToCheck + " was found"
                break
        print(result)
        ####### YOUR CODE HERE ######

    if(userChoice == "3"):
        sys.exit()


from Solution import Solution

#Gera os vizinhos para a solução
def get_neighbors(sol):
    neighbors = []
    #Percorre cada programador
    for prog in range(sol.num_prog):
        #Percorre cada módulo do programador
        for mod in range(sol.num_mod):
            #Se o programador estiver atribuído ao módulo, tira e atribui para outro programador
            if sol.assignment[prog][mod] == 1:
                for prog_sub in range(sol.num_prog):
                    if prog_sub != prog:
                        neighbor_assignment = [row.copy() for row in sol.assignment]
                        neighbor_assignment[prog][mod] = 0
                        neighbor_assignment[prog_sub][mod] = 1
                        neighbor = Solution(neighbor_assignment, sol.costs, sol.hours, sol.availability, sol.num_prog, sol.num_mod, sol.P)
                        neighbors.append(neighbor)
    return neighbors


from datetime import date
atual = date.today().year
totalmaior = 0
totalmenor = 0
for pess in range(1,8):
    ano = int(input('Em que ano a {}° pessoa nasceu? '.format(pess)))
    idade = atual - ano
    if idade >= 18:
        totalmaior +=1
    else:
        totalmenor +=1
print("Tiivemos {} pessoas maiores de idade e {} menores de idade".format(totalmaior, totalmenor))


from openerp import api, fields, models

class ProductCategory(models.Model):
    _inherit = 'product.category'
    _parent_store = False

    @api.one
    def _get_total_taxes(self):
        categ = self
        customer_taxes = categ.taxes_id
        supplier_taxes = categ.supplier_taxes_id
        while categ.parent_id and (not customer_taxes or not supplier_taxes):
            categ = categ.parent_id
            if not customer_taxes:
                customer_taxes |= categ.taxes_id
            if not supplier_taxes:
                supplier_taxes |= categ.supplier_taxes_id
        self.total_taxes_id = customer_taxes
        self.total_supplier_taxes_id = supplier_taxes

    taxes_id = fields.Many2many('account.tax', 'product_category_taxes_rel', 'categ_id', 'tax_id', 'Customer Taxes',
                                domain=[('parent_id', '=', False), ('type_tax_use', 'in', ['sale', 'all'])],
                                help="Taxes change in product category is not propagated in existing products")
    supplier_taxes_id = fields.Many2many('account.tax', 'product_category_supplier_taxes_rel', 'categ_id', 'tax_id', 'Supplier Taxes',
                                         domain=[('parent_id', '=', False), ('type_tax_use', 'in', ['purchase', 'all'])],
                                         help="Taxes change in product category is not propagated in existing products")
    total_taxes_id = fields.Many2many('account.tax', string='Inherited Customer Taxes', compute='_get_total_taxes')
    total_supplier_taxes_id = fields.Many2many('account.tax', string='Inherited Supplier Taxes', compute='_get_total_taxes')

    @api.multi
    def write(self, vals):
        old_taxes_to_keep = {}
        company = self.env.user.company_id
        for field in ('taxes_id', 'supplier_taxes_id'):
            if field in vals:
                for categ in self.sudo():
                    old_taxes_to_keep.setdefault(field, {})
                    old_taxes_to_keep[field][categ] = getattr(categ, field).filtered(lambda tax: tax.company_id != company)
        res = super(ProductCategory, self).write(vals)
        for field in old_taxes_to_keep:
            for categ in old_taxes_to_keep[field]:
                taxes = getattr(categ, field)
                taxes |= old_taxes_to_keep[field][categ]
        return res

class ProductTemplate(models.Model):
    _inherit = 'product.template'

    @api.onchange('categ_id')
    def _onchange_categ_id(self):
        if self.categ_id:
            self.taxes_id = self.categ_id.total_taxes_id
            self.supplier_taxes_id = self.categ_id.total_supplier_taxes_id

    @api.model
    def create(self, vals):
        product_tmpl = super(ProductTemplate, self).create(vals)
        if vals.get('categ_id') and 'taxes_id' not in vals and 'supplier_taxes_id' not in vals:
            product_tmpl._onchange_categ_id()
        return product_tmpl

class ProductProduct(models.Model):
    _inherit = 'product.product'

    @api.onchange('categ_id')
    def _onchange_categ_id(self):
        self.product_tmpl_id._onchange_categ_id()


import json
import re
from multiprocessing import Pool
from multiprocessing.pool import ThreadPool

import pandas as pd
import requests
from bs4 import BeautifulSoup
from fake_useragent import UserAgent

BASE_URL = "https://finance.naver.com"
UA = UserAgent()
HEADERS = {
    "User-Agent": UA.random,
}

class Crawler:
    def __init__(self):
        self.trend_stock_df = self.get_search_trend_stock()

    @staticmethod
    def get_search_trend_stock(n: int = 30):
        """
        네이버 검생상위 n개 종목과 그 코드를 df로 출력
        :param n: 가져올 상위 종목의 갯수 (0 < n <= 30)
        :return: df(종목명, 종목코드)
        """
        if (n > 30) or (n < 0):
            raise Exception("n must be between 0 and 30")

        url = BASE_URL + "/sise/lastsearch2.naver"
        r = requests.get(url, headers=HEADERS)
        html = r.text
        soup = BeautifulSoup(html, "html.parser")
        li = soup.find_all("a", "tltle")

        symbols = []
        codes = []
        for stock in li:
            symbol = stock.text
            code = re.search(r"(?<==).*", stock["href"])[0]

            symbols.append(symbol)
            codes.append(code)

        df = pd.DataFrame(zip(symbols, codes), columns=["Symbol", "Code"])
        return df

    @staticmethod
    def fetch_comments_by_post(nid):
        comment_url = (
            "https://apis.naver.com/commentBox/cbox/"
            "web_naver_list_jsonp.json?ticket=finance"
            "&templateId=default&pool=cbox12&lang=ko&"
            f"country=KR&objectId={nid}"
        )
        headers = {
            "User-Agent": UA.random,
            "referer": "https://finance.naver.com/item/board_read.naver?"
            f"code=112040&nid={nid}&st=&sw=&page=1",
        }
        r = requests.get(comment_url, headers=headers)
        comments_list = re.findall(
            r'(?<={"commentList":).*(?=,"pageModel")', r.text
        )[0]
        comments_list = json.loads(comments_list)

        comments = []
        keys = [
            "contents",
            "replyAllCount",
            "userName",
            "modTime",
            "sympathyCount",
            "antipathyCount",
        ]
        for comment in comments_list:
            comments.append({x: comment[x] for x in keys})
        return comments

    def fetch_by_post(self, top_post, symbol):
        href = top_post.get("href")
        r = requests.get(BASE_URL + href)
        content_soup = BeautifulSoup(r.text, "lxml")

        author = content_soup.select_one(
            "th > span.gray03 > strong"
        ).text.replace(" ", "")
        date = content_soup.select_one("tr > th.gray03.p9.tah").text

        post_info = content_soup.select_one("tr > th:nth-of-type(2)")
        post_info = post_info.getText(",", strip=True).split(",")

        content = content_soup.select_one("#body")
        content = content.getText().replace("\xa0\r", "\n")
        content = content.replace("\r", "\n")
        # nid = int(re.search(r'(?<=nid=)[0-9]+', href)[0])
        # comments = self.fetch_comments_by_post(nid)

        post = {}
        post["title"] = top_post.get("title")
        post["author"] = author
        post["content"] = content
        post["stock_name"] = symbol
        post["likes"] = post_info[3]
        post["dislikes"] = post_info[5]
        post["views"] = post_info[1]
        post["reg_ts"] = date.replace(".", "-") + ":00"
        # post['nid'] = nid
        # post['comments'] = comments
        # return post
        print(post)
        r = requests.post(
            "https://hxx059yi92.execute-api.ap-northeast-2.amazonaws.com/api/crawling/posts",
            json=post,
        )
        # print(r)
        # return r

    def fetch_by_page(self, symbol: str, code: str, page: int, standard: int):
        """
        한 게시판 페이지 내의 글들을 크롤링하는 메소드
        :param code: 종목코드
        :param page: 페이지 번호
        :return: 한 페이지의 게시글들을 dict of list 로 반환.
        """
        url = BASE_URL + "/item/board.naver?code=" + code + "&page=%d" % page
        req = requests.get(url, headers=HEADERS)
        soup = BeautifulSoup(req.text, "lxml")

        title_list = soup.select("td.title > a")
        agree_list = soup.select("td:nth-child(5) > strong")
        disagree_list = soup.select("td:nth-child(6) > strong")
        idx_list = [
            idx
            for idx, agree in enumerate(agree_list)
            if int(agree.text) >= standard
        ]
        top_post_list = [title_list[x] for x in idx_list]

        pool = ThreadPool(2)
        posts = [
            pool.apply_async(
                self.fetch_by_post, args={top_post: top_post, symbol: symbol}
            )
            for top_post in top_post_list
        ]
        pool.close()
        pool.join()
        # posts = [post.get() for post in posts]
        # list of dict -> dict of list
        # posts = {k: [dic[k] for dic in posts] for k in posts[0]}


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
ODB++ surface parser components
"""
import re
from collections import namedtuple
from .Decoder import DecoderOption, run_decoder
from .Structures import *
from .Utils import try_parse_number

__all__ = ["components_decoder_options", "parse_components",
           "consolidate_component_tags", "Component", "map_components_by_name"]

_prp_re = re.compile(r"^PRP\s+(\S+)\s+'([^']+)'\s*$") # Property record
# _prp_re.search("PRP Name 'EEUFR1H470'")
_top_re = re.compile(r"^TOP\s+(\d+)\s+(-?[\.\d]+)\s+(-?[\.\d]+)\s+(-?[\.\d]+)\s+(N|M|X|Y|XY)\s+(\d+)\s+(\d+)\s+(\S+)\s*$") # Toeprint record
_cmp_re = re.compile(r"^CMP\s+(\d+)\s+(-?[\.\d]+)\s+(-?[\.\d]+)\s+(-?[\.\d]+)\s+(N|M|X|Y|XY)\s+(\S+)\s+(\S+)\s*(;\s*.+?)?$") # component record

ComponentRecordTag = namedtuple("ComponentRecordTag",[
        "package_ref", "location", "rotation", "mirror", "name", "part_name", "attributes"])
PropertyRecordTag = namedtuple("PropertyRecord", ["key", "value"])
ToeprintRecord = namedtuple("ToeprintRecord", [
        "pin_num", "location", "rotation", "mirrored", "net_num", "subnet_num", "toeprint_name"])

Component = namedtuple("Component", [
        "name", "part_name", "location", "rotation", "mirror", "attributes", "properties", "toeprints"])

def consolidate_component_tags(tags):
    component = None # Expect only one
    properties = {}
    toeprints = []
    for tag in tags:
        if isinstance(tag, ComponentRecordTag):
            if component is not None:
                raise ValueError("Multiple CMP records in section. Last one: {}".format(tag))
            component = tag
        if isinstance(tag, PropertyRecordTag):
            properties[tag.key] = tag.value
        if isinstance(tag, ToeprintRecord):
            toeprints.append(tag)
    if component is None:
        raise ValueError("No CMP record in section")
    return Component(
        component.name, component.part_name, component.location,
        component.rotation, component.mirror, component.attributes,
        properties, toeprints
    )

def _parse_prp(match):
    key, value = match.groups()
    return PropertyRecordTag(key, value)

def _parse_top(match):
    pin_num, x, y, rot, mirror, net_num, subnet_num, toeprint_name = match.groups()
    return ToeprintRecord(
        int(pin_num),
        Point(float(x), float(y)),
        float(rot),
        mirror_map[mirror],
        int(net_num),
        int(subnet_num),
        try_parse_number(toeprint_name)
    )

def _parse_cmp(match):
    pkg_ref, x, y, rot, mirror, name, part_name, attributes = match.groups()
    attributes = parse_attributes(attributes[1:]) \
                 if attributes is not None else {}
    return ComponentRecordTag(
        int(pkg_ref),
        Point(float(x), float(y)),
        float(rot),
        mirror_map[mirror],
        try_parse_number(name.strip()),
        try_parse_number(part_name.strip()),
        attributes
    )

components_decoder_options = [
    DecoderOption(_prp_re, _parse_prp),
    DecoderOption(_top_re, _parse_top),
    DecoderOption(_cmp_re, _parse_cmp)
]

def component_name_to_id(name):
    """
    Convert a section header name ("CMP 0" in DipTrace)
    to an identifier (e.g. 0)
    """
    if name.startswith("CMP"):
        return int(name[len("CMP"):].strip())
    return name

def parse_components(components):
    # Build rulesets
    return {
        component_name_to_id(name): consolidate_component_tags(
            list(run_decoder(component, components_decoder_options)))
        for name, component in components.items()
        if name is not None
    }

def map_components_by_name(components):
    """Given a dictionary or list of components, map them into a dictionary by name"""
    if isinstance(components, dict):
        components = components.values()
    return {
        component.name: component
        for component in components
    }


class Solution:
    def maxPathSum(self, root: TreeNode) -> int:
        self.ans = -float('inf')
        def helper(node):
            if not node:
                return 0
            left = max(0, helper(node.left))
            right = max(0, helper(node.right))
            #更新全局变量，由上面两个max可知，若某条路径的贡献小于0，压根就不用考虑
            self.ans = max(self.ans, left + right + node.val)
            #return的是从根节点往左，从根节点往左两条路径中大的那条
            return max(left, right) + node.val
        helper(root)
        return self.ans


import cv2
import random
import numpy as np

def draw(src, src_point):
    """
    draw feature points on source image
    """
    dst = src.copy()
    b = random.randint(0, 255)
    g = random.randint(0, 255)
    r = random.randint(0, 255)
    for i in range(src_point.shape[0]):
        cv2.circle(dst, (int(src_point[i, 0]), int(src_point[i, 1])), 5, color=(b, g, r), thickness=1)
    return dst

def draw_match(src, dst, src_point, dst_point, number=20):
    """
    draw matching lines between two images
    :param src: image 1
    :param dst: image 2
    :param src_point: matching point on image 1
    :param dst_point: matching point on image 2
    :param number: # of matching line
    :return: Drawn image
    """
    src_point = src_point.astype(np.int)
    dst_point = dst_point.astype(np.int)
    src_h, src_w, _ = src.shape
    dst_h, dst_w, _ = dst.shape
    final_height = max(src_h, dst_h)
    final_width = src_w + dst_w

    # copy
    pic = np.zeros([final_height, final_width, 3], dtype=np.uint8)
    pic[:src_h, :src_w, :] = src[:, :, :]
    pic[:dst_h, src_w:, :] = dst[:, :, :]

    # give destination offset
    dst_point[:, 0] = dst_point[:, 0] + src_w

    # matching #
    n = src_point.shape[0]
    if number > n:
        number = n

    # matching line draw
    for i in range(number):
        cv2.line(pic, (src_point[i, 0], src_point[i, 1]), (dst_point[i, 0], dst_point[i, 1]),
                 (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)), thickness=1, lineType=cv2.LINE_AA)
    return pic


import random
from pacai.core.distance import manhattan
from pacai.agents.base import BaseAgent
from pacai.agents.search.multiagent import MultiAgentSearchAgent
from pacai.core.directions import Directions

class ReflexAgent(BaseAgent):
    """
    A reflex agent chooses an action at each choice point by examining
    its alternatives via a state evaluation function.

    The code below is provided as a guide.
    You are welcome to change it in any way you see fit,
    so long as you don't touch the method headers.
    """

    def __init__(self, index, **kwargs):
        super().__init__(index, **kwargs)

    def getAction(self, gameState):
        """
        You do not need to change this method, but you're welcome to.

        `ReflexAgent.getAction` chooses among the best options according to the evaluation function.

        Just like in the previous project, this method takes a
        `pacai.core.gamestate.AbstractGameState` and returns some value from
        `pacai.core.directions.Directions`.
        """

        legalMoves = gameState.getLegalActions()

        scores = [self.evaluationFunction(gameState, action) for action in legalMoves]
        bestScore = max(scores)
        bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore]
        chosenIndex = random.choice(bestIndices)  # Pick randomly among the best.

        return legalMoves[chosenIndex]

    def evaluationFunction(self, currentGameState, action):
        """
        Design a better evaluation function here.

        The evaluation function takes in the current `pacai.bin.pacman.PacmanGameState`
        and an action, and returns a number, where higher numbers are better.
        Make sure to understand the range of different values before you combine them
        in your evaluation function.
        """
        successorGameState = currentGameState.generatePacmanSuccessor(action)
        newPosition = successorGameState.getPacmanPosition()
        closestghost = 999999
        closestfood = 9999999
        for ghost in successorGameState.getGhostPositions():
            x = manhattan(newPosition, ghost)
            if (closestghost > x):
                closestghost = x
        for food in currentGameState.getFood().asList():
            y = manhattan(newPosition, food)
            if (closestfood > y):
                closestfood = y
        if (closestfood == 0):
            closestfood = 0.0001
        if closestghost <= 2:
            evaluationScore = -99999999
        else:
            evaluationScore = (1 / closestfood) - (1 / (closestghost))
        # Useful information you can extract.
        # newPosition = successorGameState.getPacmanPosition()
        # oldFood = currentGameState.getFood()
        # newGhostStates = successorGameState.getGhostStates()
        # newScaredTimes = [ghostState.getScaredTimer() for ghostState in newGhostStates]

        # *** Your Code Here ***
        return evaluationScore

class MinimaxAgent(MultiAgentSearchAgent):
    """
    A minimax agent.

    Here are some method calls that might be useful when implementing minimax.

    `pacai.core.gamestate.AbstractGameState.getNumAgents()`:
    Get the total number of agents in the game

    `pacai.core.gamestate.AbstractGameState.getLegalActions`:
    Returns a list of legal actions for an agent.
    Pacman is always at index 0, and ghosts are >= 1.

    `pacai.core.gamestate.AbstractGameState.generateSuccessor`:
    Get the successor game state after an agent takes an action.

    `pacai.core.directions.Directions.STOP`:
    The stop direction, which is always legal, but you may not want to include in your search.

    Method to Implement:

    `pacai.agents.base.BaseAgent.getAction`:
    Returns the minimax action from the current gameState using
    `pacai.agents.search.multiagent.MultiAgentSearchAgent.getTreeDepth`
    and `pacai.agents.search.multiagent.MultiAgentSearchAgent.getEvaluationFunction`.
    """

    def getAction(self, state):
        """
        The BaseAgent will receive an `pacai.core.gamestate.AbstractGameState`,
        and must return an action from `pacai.core.directions.Directions`.
        """
        legalMoves = state.getLegalActions()
        if not legalMoves:
            return Directions.STOP
        turn = 0
        agents = state.getNumAgents()
        bestScore = float('-inf')
        bestAction = Directions.STOP
        for action in legalMoves:
            if action == Directions.STOP:
                continue
            su = state.generatePacmanSuccessor(action)
            score = self.minimax(su, (turn + 1) % agents, self.getTreeDepth() - 1)
            if score > bestScore:
                bestScore = score
                bestAction = action
        return bestAction

    def minimax(self, state, turn, depth):
        if state.isWin() or state.isLose() or depth == 0:
            return self.getEvaluationFunction()(state)
        if (turn == 0):
            depth -= 1
            return self.maxValue(state, turn, depth)
        else:
            return self.minValue(state, turn, depth)

    def maxValue(self, state, turn, depth):
        if state.isWin() or state.isLose() or depth == 0:
            return self.getEvaluationFunction()(state)
        score = float('-inf')
        legalMoves = state.getLegalActions(turn)
        for action in legalMoves:
            if action == Directions.STOP:
                continue
            su = state.generatePacmanSuccessor(action)
            score = max(score, self.minimax(su, (turn + 1) % state.getNumAgents(), depth))
        return score

    def minValue(self, state, turn, depth):
        if state.isWin() or state.isLose() or depth == 0:
            return self.getEvaluationFunction()(state)
        score = float('inf')
        legalMoves = state.getLegalActions(turn)
        for action in legalMoves:
            if action == Directions.STOP:
                continue
            su = state.generateSuccessor(turn, action)
            score = min(score, self.minimax(su, (turn + 1) % state.getNumAgents(), depth))
        return score

    def __init__(self, index, **kwargs):
        super().__init__(index, **kwargs)

class AlphaBetaAgent(MultiAgentSearchAgent):
    """
    A minimax agent with alpha-beta pruning.

    Method to Implement:

    `pacai.agents.base.BaseAgent.getAction`:
    Returns the minimax action from the current gameState using
    `pacai.agents.search.multiagent.MultiAgentSearchAgent.getTreeDepth`
    and `pacai.agents.search.multiagent.MultiAgentSearchAgent.getEvaluationFunction`.
    """

    def getAction(self, state):
        """
        The BaseAgent will receive an `pacai.core.gamestate.AbstractGameState`,
        and must return an action from `pacai.core.directions.Directions`.
        """
        legalMoves = state.getLegalActions()

        if not legalMoves:
            return Directions.STOP

        turn = 0
        agents = state.getNumAgents()
        alpha = float('-inf')
        beta = float('inf')
        bestScore = float('-inf')
        bestAction = Directions.STOP

        for action in legalMoves:
            if action == Directions.STOP:
                continue
            su = state.generatePacmanSuccessor(action)
            score = self.minimax(su, (turn + 1) % agents, self.getTreeDepth() - 1, alpha, beta)
            if score > bestScore:
                bestScore = score
                bestAction = action
        return bestAction

    def minimax(self, state, turn, depth, alpha, beta):
        if state.isWin() or state.isLose() or depth == 0:
            return self.getEvaluationFunction()(state)
        if (turn == 0):
            depth -= 1
            return self.maxValue(state, turn, depth, alpha, beta)
        else:
            return self.minValue(state, turn, depth, alpha, beta)

    def maxValue(self, state, turn, depth, alpha, beta):
        if state.isWin() or state.isLose() or depth == 0:
            return self.getEvaluationFunction()(state)
        score = float('-inf')
        legalMoves = state.getLegalActions(turn)
        for action in legalMoves:
            if action == Directions.STOP:
                continue
            su = state.generatePacmanSuccessor(action)
            score = max(score, self.minimax(su, (turn
            + 1) % state.getNumAgents(), depth, alpha, beta))
            if score >= beta:
                return score
            if score > alpha:
                alpha = score
        return score

    def minValue(self, state, turn, depth, alpha, beta):
        if state.isWin() or state.isLose() or depth == 0:
            return self.getEvaluationFunction()(state)
        score = float('inf')
        legalMoves = state.getLegalActions(turn)
        for action in legalMoves:
            if action == Directions.STOP:
                continue
            su = state.generateSuccessor(turn, action)
            score = min(score, self.minimax(su, (turn
            + 1) % state.getNumAgents(), depth, alpha, beta))
            if score <= alpha:
                return score
            if score < beta:
                beta = score
        return score

    def __init__(self, index, **kwargs):
        super().__init__(index, **kwargs)

class ExpectimaxAgent(MultiAgentSearchAgent):
    """
    An expectimax agent.

    All ghosts should be modeled as choosing uniformly at random from their legal moves.

    Method to Implement:

    `pacai.agents.base.BaseAgent.getAction`:
    Returns the expectimax action from the current gameState using
    `pacai.agents.search.multiagent.MultiAgentSearchAgent.getTreeDepth`
    and `pacai.agents.search.multiagent.MultiAgentSearchAgent.getEvaluationFunction`.
    """
    def getAction(self, state):
        """
        The BaseAgent will receive an `pacai.core.gamestate.AbstractGameState`,
        and must return an action from `pacai.core.directions.Directions`.
        """
        legalMoves = state.getLegalActions()
        if not legalMoves:
            return Directions.STOP
        turn = 0
        agents = state.getNumAgents()
        bestScore = float('-inf')
        bestAction = Directions.STOP
        for action in legalMoves:
            if action == Directions.STOP:
                continue
            su = state.generatePacmanSuccessor(action)
            score = self.expmax(su, (turn + 1) % agents, self.getTreeDepth() - 1)
            if score > bestScore:
                bestScore = score
                bestAction = action
        return bestAction

    def expmax(self, state, turn, depth):
        if state.isWin() or state.isLose() or depth == 0:
            return self.getEvaluationFunction()(state)
        if (turn == 0):
            depth -= 1
            return self.maxValue(state, turn, depth)
        else:
            return self.expValue(state, turn, depth)

    def maxValue(self, state, turn, depth):
        if state.isWin() or state.isLose() or depth == 0:
            return self.getEvaluationFunction()(state)
        score = float('-inf')
        legalMoves = state.getLegalActions(turn)
        for action in legalMoves:
            if action == Directions.STOP:
                continue
            su = state.generatePacmanSuccessor(action)
            score = max(score, self.expmax(su, (turn
            + 1) % state.getNumAgents(), depth))
        return score

    def expValue(self, state, turn, depth):
        if state.isWin() or state.isLose() or depth == 0:
            return self.getEvaluationFunction()(state)
        score = 0
        legalMoves = state.getLegalActions(turn)
        for action in legalMoves:
            if action == Directions.STOP:
                continue
            su = state.generateSuccessor(turn, action)
            prob = 1.0 / len(legalMoves)
            score += prob * self.expmax(su, (turn + 1) % state.getNumAgents(), depth)
        return score

    def __init__(self, index, **kwargs):
        super().__init__(index, **kwargs)

def betterEvaluationFunction(currentGameState):
    """
    Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable evaluation function.

    DESCRIPTION: <write something here so we know what you did>
    """
    newPosition = currentGameState.getPacmanPosition()
    closestscaredghost = float('inf')
    closestfood = float('inf')
    closestghost = float('inf')
    score = currentGameState.getScore()
    remainingFood = currentGameState.getNumFood()
    for ghostState in currentGameState.getGhostStates():
        ghostPosition = ghostState.getPosition()
        x = manhattan(newPosition, ghostPosition)
        if ghostState.getScaredTimer() > 0:
            if x < closestscaredghost:
                closestscaredghost = x
        elif x < closestghost:
            closestghost = x
    for food in currentGameState.getFood().asList():
        y = manhattan(newPosition, food)
        if (closestfood > y):
            closestfood = y
        if currentGameState.getFood()[food[0]][food[1]]:
            remainingFood -= 1
    if (closestfood == 0):
        closestfood = 0.0001
    if closestghost <= 1.5:
        evaluationScore = float('-inf')
    else:
        evaluationScore = (1.5 * score) + (1.0 / closestfood) - (1.0
        / closestghost) - (1.1 / (remainingFood + 0.01))
        if closestscaredghost < 5:
            evaluationScore += 100 / closestscaredghost
    return evaluationScore

class ContestAgent(MultiAgentSearchAgent):
    """
    Your agent for the mini-contest.

    You can use any method you want and search to any depth you want.
    Just remember that the mini-contest is timed, so you have to trade off speed and computation.

    Ghosts don't behave randomly anymore, but they aren't perfect either -- they'll usually
    just make a beeline straight towards Pacman (or away if they're scared!)

    Method to Implement:

    `pacai.agents.base.BaseAgent.getAction
    """
    def __init__(self, index, **kwargs):
        super().__init__(index, **kwargs)


import discord
from discord.ext import commands
import random
import toml

class Main(commands.Cog):

    def __init__(self, bot):
        self.bot = bot

    @commands.command(help='All commands')
    async def help(self, ctx, args=None):
        help_mes = ['Calling 911...', 'Any problem?', 'Some problem here?', 'No worries, i gotch ya']
        help_embed = discord.Embed(title=random.choice(help_mes), description='List of supported commands:')
        command_names_list = [x.name for x in self.bot.commands]

        if not args:
            for i,x in enumerate(self.bot.commands):
                help_embed.add_field(
                    name=f"`!{x.name}` {x.signature}",
                    value=f"> {x.help}",
                    inline=True
                )

        # If the argument is a command, get the help text from that command:
        elif args in command_names_list:
            help_embed.add_field(
                name=args,
                value=self.bot.get_command(args).help
            )

        # If someone is just trolling:
        else:
            help_embed.add_field(
                name="Nope.",
                value="Don't think I got that command"
            )

        await ctx.send(embed=help_embed)

    @commands.command()
    async def userinfo(self, ctx, *, member: discord.Member=None):
        """Displays information on a user"""
        if member == None:
            member = ctx.message.author
        embed = discord.Embed(color=member.color, timestamp=ctx.message.created_at)
        embed.set_author(name=f"User Info - {member}")
        embed.set_thumbnail(url=member.avatar_url)
        await ctx.send(embed=embed)

    @commands.command(help='Detailed info about the project', aliases=['project'])
    async def info(self, ctx):
        toml_open = toml.load(open('pyproject.toml'))['tool']['poetry']
        embed = discord.Embed(title='Info about the project', url='https://github.com/chalankolachtanovity/Bot_ready/blob/master/README.md')
        embed.add_field(name='Name:', value=toml_open['name'])
        embed.add_field(name='Version:', value=toml_open['version'])
        embed.add_field(name='Description:', value=toml_open['description'])
        embed.add_field(name='Authors:', value=', '.join(toml_open['authors']))
        await ctx.send(embed=embed)

    @commands.Cog.listener()
    async def on_member_join(self, member):
        embed = discord.Embed(title=f"**Hey {member.name}, welcome to Milošovy hrátky server!**", color=0x009dff)
        embed.set_author(name="by chalankolachtanovity")
        embed.add_field(name=":red_circle:Rules:", value="We don't have any rules, everything is moderated by bot **Lachtan**.\nType **!help**", inline=True)
        embed.set_thumbnail(url="https://m.smedata.sk/api-media/media/image/sme/6/30/3065226/3065226_600x400.jpeg?rev=3")
        embed.add_field(name=":red_circle:Bot Lachtan", value="Bot **Lachtan** is our unique bot with unique functions! Feel free to use him!", inline=False)
        embed.set_footer(text="enjoy!")
        await self.bot.get_channel(783670260200767488).send(content=member.mention, embed=embed)

    @commands.Cog.listener()
    async def on_command_error(self, ctx, error):
        answers = ['Huh?', 'You are trying impossible', '"Human being"', 'I just sometimes ask, why.', 'No way', 'Again?', 'Just...', 'XD', 'Wtf dude.', '2+2?', 'No comment']
        if isinstance(error, commands.CommandNotFound):
            embed = discord.Embed(title=random.choice(answers), description='Check spelling', color=0xff1414)
            await ctx.send(embed=embed)
        if isinstance(error, commands.MissingRequiredArgument):
            embed = discord.Embed(title=random.choice(answers), description=f'Missing a required argument `<{error.param.name}>`.  Do `!help <commandname>`', color=0xff1414)
            await ctx.send(embed=embed)
        raise error

    @commands.Cog.listener()
    async def on_ready(self):
        print("Discord -> connected")
        await self.bot.change_presence(
                activity=discord.Activity(
                    type=discord.ActivityType.watching,
                    name='Spaceflights')
            )

def setup(bot):
    bot.add_cog(Main(bot))


import json
import re

def checkKeywords(keywords, prompt, completion):
    checked = False
    for keyword in keywords:
        checked = checked or (keyword in prompt or keyword in completion)
    return checked

file_path = 'data.txt'

with open(file_path, 'r', encoding='utf-8') as file:
    data = file.read()

print('Length of Document', len(data))

# Split based on newline

data = data.split('. ')
# Remove redundant spaces
data = [re.sub('\s+', ' ', s) for s in data if s]
# Remove space at the beginning of the string
data = [s[1:] if s[0] == ' ' else s for s in data ]
# Remove strings that are too short
data = [s for s in data if len(s) > 20]

print('Length of List',len(data))

output_file = file_path.replace('.txt', '.jsonl').replace('data', 'dataset')

with open(output_file, 'w') as f:
    for i in range(0, len(data)):
        if i+1 >= len(data):
            break
        prompt = ''
        completion = ''
        str = data[i]
        str = str.split(' ')
        p = int(len(str) / 2)
        for j in str[:p]:
            prompt += j
            prompt += ' '
        for j in str[p:]:
            completion += j
            completion += ' '
        if checkKeywords(['dialog', 'editing', 'model'], prompt, completion):
        # if True:
            json_data = {'prompt': prompt, 'completion': completion}
            json.dump(json_data, f)
            f.write('\n')


import sys
from django.core.wsgi import get_wsgi_application

"""
Settings
========
Would normally go in project_app/settings.py
"""
from django.conf import settings

settings.configure(
    DEBUG = True,
    SECRET_KEY = 'yourrandomsecretkey',
    ROOT_URLCONF = __name__,
    MIDDLEWARE_CLASSES = (
        'django.middleware.common.CommonMiddleware',
    ),
)

"""
Views
=====
Would normally go in app/views.py
"""
from django.http import HttpResponse

def index(request):
    return HttpResponse('Hello World')

"""
URLs
====
The root URL config normally goes in project_app/urls.py
"""
from django.conf.urls import url

urlpatterns = (
    url(r'^$', index),
)

"""
Manage.py
=========
Some setup code typically found in manage.py
"""

app = get_wsgi_application()

if __name__ == '__main__':
    from gevent.wsgi import WSGIServer
    http_server = WSGIServer(('', 8080), app, log=None)
    http_server.serve_forever()


import torch
import torch.utils.data as data
import torchvision.transforms as tvtf
import csv

from PIL import Image
import os

class CIFAR10Dataset(data.Dataset):
    def __init__(self, img_dir, label_path=None):
        super().__init__()

        self.img_dir = img_dir

        self.cid2name = [
            'airplane', 'automobile', 'bird', 'cat', 'deer',
            'dog', 'frog', 'horse', 'ship', 'truck'
        ]

        if label_path is not None:
            with open(label_path, 'r') as f:
                reader = csv.reader(f)
                next(reader)
                data = [(int(_id), self.cid2name.index(name)) for _id, name in reader]
            self.ids, self.lbls = list(zip(*data))
            self.is_train = True
        else:
            self.ids = [int(os.path.splitext(x)[0]) for x in os.listdir(img_dir)]
            self.is_train = False

    def __getitem__(self, i):
        img = Image.open(os.path.join(self.img_dir, f'{self.ids[i]}.png'))
        img = tvtf.Compose([
            tvtf.ToTensor(),
        ])(img)

        if self.is_train:
            lbl = torch.Tensor([self.lbls[i]]).long().squeeze()
            return img, lbl
        else:
            return img, self.ids[i]

    def __len__(self):
        return len(self.ids)

if __name__ == "__main__":
    import matplotlib.pyplot as plt

    dataset = CIFAR10Dataset('data/CIFAR10/train',
                             'data/CIFAR10/trainLabels.csv')
    for img, lbl in dataset:
        plt.imshow(img.permute(1, 2, 0))
        plt.title(lbl.item())
        plt.show()


import os
import pyspark.sql.functions as F
output_data = "s3a://shwes3udacapstone/"

s3 = "s3a://shwes3udacapstone/"
I94_CODES_DATA_PATH = "data/raw/codes/"
AIRPORT_FILE="i94prtl.txt"
COUNTRY_FILE="i94cntyl.txt"
STATE_FILE="i94addrl.txt"
MODELFILE = "i94model.txt"
VISAFILE = "i94visa.txt"

# process and clean data from i94 label description file
def process_state_codes():
    input_data_file = os.path.join(s3, I94_CODES_DATA_PATH+STATE_FILE)
    df_state = spark.read.format("csv").option("delimiter", "=").option("header", "False").load(input_data_file)
    df_state = df_state.withColumnRenamed("_c0", "state_code").withColumnRenamed("_c1", "state_name")
    df_state = df_state.withColumn("state_code", F.regexp_replace(df_state.state_code, "[^A-Z]", ""))
    df_state = df_state.withColumn("state_name", F.regexp_replace(df_state.state_name, "'", ""))
    df_state = df_state.withColumn("state_name", F.ltrim(F.rtrim(df_state.state_name)))
    df_state.write.mode("overwrite").parquet(s3 + 'data/processed/codes/us_state')
    return df_state

def process_country_codes():
    input_data_file = os.path.join(s3, I94_CODES_DATA_PATH + COUNTRY_FILE)
    df_country = spark.read.format("csv").option("delimiter", "=").option("header", "False").load(input_data_file)
    df_country = df_country.withColumnRenamed("_c0", "country_code").withColumnRenamed("_c1", "country_name")
    df_country = df_country.withColumn("country_name", F.regexp_replace(df_country.country_name, "'", ""))
    df_country = df_country.withColumn("country_name", F.ltrim(F.rtrim(df_country.country_name)))
    df_country = df_country.withColumn("country_code", F.ltrim(F.rtrim(df_country.country_code)))
    df_country = df_country.withColumn("country_name",
                                       F.regexp_replace(df_country.country_name, "^INVALID.*|Collapsed.*|No\ Country.*",
                                                        "INVALID"))
    df_country.write.mode("overwrite").parquet(s3 + 'data/processed/codes/country')
    return df_country

def process_airport_codes():

    #transform airport codes
    input_data_file = os.path.join(s3, I94_CODES_DATA_PATH + AIRPORT_FILE)
    df_airport = spark.read.format("csv").option("delimiter", "=").option("header", "False").load(input_data_file)
    df_airport = df_airport.withColumn("_c0", F.regexp_replace(df_airport._c0, "'", "")).withColumn("_c1",
                                                                                F.regexp_replace(
                                                                                df_airport._c1,
                                                                                "'", ""))
    split_col = F.split(df_airport._c1, ",")
    df_airport = df_airport.withColumn("city", split_col.getItem(0))
    df_airport = df_airport.withColumn("state_code", split_col.getItem(1))
    df_airport = df_airport.withColumnRenamed("_c0", "port_code")
    df_airport = df_airport.drop("_c1")
    df_airport = df_airport.withColumn("port_code",
                                       F.regexp_replace(df_airport.port_code, "[^A-Z]", "")).withColumn("city",
                                                                                F.ltrim(
                                                                                F.rtrim(
                                                                                df_airport.city))).withColumn(
        "state_code", F.regexp_replace(df_airport.state_code, "[^A-Z]", ""))
    df_state = process_state_codes()
    df_airport = df_airport.join(df_state, "state_code")
    df_airport.write.mode("overwrite").parquet(s3 + 'data/processed/codes/us_ports')

def process_i94Model_codes():
    input_data_file = os.path.join(s3, I94_CODES_DATA_PATH + MODELFILE)
    df_i94mode = spark.read.format("csv").option("delimiter", "=").option("header", "False").load(input_data_file)

    df_i94mode = df_i94mode.withColumn("_c0", F.regexp_replace(df_i94mode._c0, "'", "")). \
        withColumn("_c1", F.regexp_replace(df_i94mode._c1, "[^A-Za-z]", ""))
    df_i94mode = df_i94mode.withColumnRenamed("_c0", "i94mode").withColumnRenamed("_c1", "mode")
    df_i94mode.write.mode("overwrite").parquet(s3+"data/processed/codes/i94mode")

def process_i94Visa_codes():
    input_data_file = os.path.join(s3, I94_CODES_DATA_PATH + VISAFILE)
    df_i94visa = spark.read.format("csv").option("delimiter", "=").option("header", "False").load(input_data_file)

    df_i94visa = df_i94visa.withColumn("_c0", F.regexp_replace(df_i94visa._c0, "'", "")). \
        withColumn("_c1", F.regexp_replace(df_i94visa._c1, "[^A-Za-z0-9]", ""))
    df_i94visa = df_i94visa.withColumnRenamed("_c0", "i94visa").withColumnRenamed("_c1", "visa")
    df_i94visa.write.mode("overwrite").parquet(s3+"data/processed/codes/i94visa")

process_airport_codes()
process_country_codes()
process_i94Model_codes()
process_i94Visa_codes()


from scipy.optimize import minimize
import numpy as np
from scipy.stats import norm

lb = -1
ub = 1

def transform(lb,ub): return lambda x: lb+(ub-lb)/(1+np.exp(-x/2))
f = lambda x: x*x-0.7
def choose(X):
    if (len(X)==1):
        return X(1)-X(0)
    return X[:, 1] - X[:, 0]

undefined = np.array([lb,ub])
choose(undefined)
defined = np.array([])

Xtrain = np.array([[-1],[1]])
Ytrain=np.array([f(-1),f(1)])
trshold=0
from sklearn.gaussian_process import GaussianProcessRegressor
gp = GaussianProcessRegressor(n_restarts_optimizer=20)

gp.fit(Xtrain, Ytrain)
def minimo(x):
    y_pred, sigma = gp.predict(x, return_std=True)
    return max(norm.cdf((y_pred - trshold) / sigma), 1 - norm.cdf((y_pred - trshold) / sigma))
g = lambda x: minimo(transform(-1,0)(x))
res = minimize(g, (-0.5), method='CG')
print(res.fun)
print(transform(-1,0)(res.x))


import pandas as pd
import numpy as np
import datetime
from collections import Counter
from sklearn.metrics.pairwise import cosine_similarity

movies_data = pd.read_csv("import/movies.csv")
genome_scores_data = pd.read_csv("import/genome-scores.csv")
ratings_data = pd.read_csv("import/ratings.csv")

scores_pivot = genome_scores_data.pivot_table(index =["movieId"],columns = ["tagId"],values = "relevance").reset_index()
mov_tag_df = movies_data.merge(scores_pivot, left_on="movieId",right_on="movieId", how="left")
mov_tag_df = mov_tag_df.fillna(0)
mov_tag_df = mov_tag_df.drop(['title','genres'], axis = 1)
mov_tag_df.drop(mov_tag_df.tail(18).index,inplace=True)

def set_genres(genres,col):
    if genres in col.split('|'):
        return 1
    else: return 0

mov_genres_df_Action=movies_data.apply(lambda x:set_genres("Action",x['genres']),axis=1)
mov_genres_df1=mov_genres_df_Action.to_frame()
mov_genres_df1=mov_genres_df1.rename(columns={0: 'Action'})

mov_genres_df_Adventure=movies_data.apply(lambda x:set_genres("Adventure",x['genres']),axis=1)
mov_genres_df2=mov_genres_df_Adventure.to_frame()
mov_genres_df2=mov_genres_df2.rename(columns={0: 'Adventure'})

mov_genres_df_Animation=movies_data.apply(lambda x:set_genres("Animation",x['genres']),axis=1)
mov_genres_df3=mov_genres_df_Animation.to_frame()
mov_genres_df3=mov_genres_df3.rename(columns={0: 'Animation'})

mov_genres_df_Children=movies_data.apply(lambda x:set_genres("Children",x['genres']),axis=1)
mov_genres_df4=mov_genres_df_Children.to_frame()
mov_genres_df4=mov_genres_df4.rename(columns={0: 'Children'})

mov_genres_df_Comedy=movies_data.apply(lambda x:set_genres("Comedy",x['genres']),axis=1)
mov_genres_df5=mov_genres_df_Comedy.to_frame()
mov_genres_df5=mov_genres_df5.rename(columns={0: 'Comedy'})

mov_genres_df_Crime=movies_data.apply(lambda x:set_genres("Crime",x['genres']),axis=1)
mov_genres_df6=mov_genres_df_Crime.to_frame()
mov_genres_df6=mov_genres_df6.rename(columns={0: 'Crime'})

mov_genres_df_Documentary=movies_data.apply(lambda x:set_genres("Documentary",x['genres']),axis=1)
mov_genres_df7=mov_genres_df_Documentary.to_frame()
mov_genres_df7=mov_genres_df7.rename(columns={0: 'Documentary'})

mov_genres_df_Drama=movies_data.apply(lambda x:set_genres("Drama",x['genres']),axis=1)
mov_genres_df8=mov_genres_df_Drama.to_frame()
mov_genres_df8=mov_genres_df8.rename(columns={0: 'Drama'})

mov_genres_df_Fantasy=movies_data.apply(lambda x:set_genres("Fantasy",x['genres']),axis=1)
mov_genres_df9=mov_genres_df_Fantasy.to_frame()
mov_genres_df9=mov_genres_df9.rename(columns={0: 'Fantasy'})

mov_genres_df_Film_Noir=movies_data.apply(lambda x:set_genres("Film-Noir",x['genres']),axis=1)
mov_genres_df10=mov_genres_df_Film_Noir.to_frame()
mov_genres_df10=mov_genres_df10.rename(columns={0: 'Film-Noir'})

mov_genres_df_Horror=movies_data.apply(lambda x:set_genres("Horror",x['genres']),axis=1)
mov_genres_df11=mov_genres_df_Horror.to_frame()
mov_genres_df11=mov_genres_df11.rename(columns={0: 'Horror'})

mov_genres_df_Musical=movies_data.apply(lambda x:set_genres("Musical",x['genres']),axis=1)
mov_genres_df12=mov_genres_df_Musical.to_frame()
mov_genres_df12=mov_genres_df12.rename(columns={0: 'Musical'})

mov_genres_df_Mystery=movies_data.apply(lambda x:set_genres("Mystery",x['genres']),axis=1)
mov_genres_df13=mov_genres_df_Mystery.to_frame()
mov_genres_df13=mov_genres_df13.rename(columns={0: 'Mystery'})

mov_genres_df_Romance=movies_data.apply(lambda x:set_genres("Romance",x['genres']),axis=1)
mov_genres_df14=mov_genres_df_Romance.to_frame()
mov_genres_df14=mov_genres_df14.rename(columns={0: 'Romance'})

mov_genres_df_Sci_Fi=movies_data.apply(lambda x:set_genres("Sci-Fi",x['genres']),axis=1)
mov_genres_df15=mov_genres_df_Sci_Fi.to_frame()
mov_genres_df15=mov_genres_df15.rename(columns={0: 'Sci-Fi'})

mov_genres_df_Thriller=movies_data.apply(lambda x:set_genres("Thriller",x['genres']),axis=1)
mov_genres_df16=mov_genres_df_Thriller.to_frame()
mov_genres_df16=mov_genres_df16.rename(columns={0: 'Thriller'})

mov_genres_df_War=movies_data.apply(lambda x:set_genres("War",x['genres']),axis=1)
mov_genres_df17=mov_genres_df_War.to_frame()
mov_genres_df17=mov_genres_df17.rename(columns={0: 'War'})

mov_genres_df_Western=movies_data.apply(lambda x:set_genres("Western",x['genres']),axis=1)
mov_genres_df18=mov_genres_df_Western.to_frame()
mov_genres_df18=mov_genres_df18.rename(columns={0: 'Western'})

mov_genres_df_no_genres_listed=movies_data.apply(lambda x:set_genres("(no genres listed)",x['genres']),axis=1)
mov_genres_df19=mov_genres_df_no_genres_listed.to_frame()
mov_genres_df19=mov_genres_df19.rename(columns={0: 'no genres listed'})

Prueba=pd.concat([movies_data["movieId"],
                  mov_genres_df1["Action"],
                  mov_genres_df2["Adventure"],
                  mov_genres_df3["Animation"],
                 mov_genres_df4["Children"],
                 mov_genres_df5["Comedy"],
                 mov_genres_df6["Crime"],
                 mov_genres_df7["Documentary"],
                 mov_genres_df8["Drama"],
                 mov_genres_df9["Fantasy"],
                 mov_genres_df10["Film-Noir"],
                 mov_genres_df11["Horror"],
                 mov_genres_df12["Musical"],
                 mov_genres_df13["Mystery"],
                 mov_genres_df14["Romance"],
                 mov_genres_df15["Sci-Fi"],
                 mov_genres_df16["Thriller"],
                 mov_genres_df17["War"],
                 mov_genres_df18["Western"],
                 mov_genres_df19["no genres listed"]],axis=1)

Prueba.drop(Prueba.tail(18).index,inplace=True)
mov_genres_df=Prueba

def set_year(title):
    year = title.strip()[-5:-1]
    if year.isnumeric() == True: return int(year)
    else: return 1800

eje = movies_data.apply(lambda x: set_year(x['title']),axis=1)
movies_years = movies_data.apply(lambda x: set_year(x['title']),axis=1)
movies_years = movies_years.to_frame()
movies_years = movies_years.rename(columns={0: 'year'})

def set_year_group(year):
    if (year < 1900): return 0
    elif (1900 <= year <= 1975): return 1
    elif (1976 <= year <= 1995): return 2
    elif (1996 <= year <= 2003): return 3
    elif (2004 <= year <= 2009): return 4
    elif (2010 <= year): return 5
    else: return 0

movies_year_group = movies_years[["year"]].apply(lambda x:set_year_group(x['year']), axis=1)
movies_year_group = movies_year_group.to_frame()
movies_year_group = movies_year_group.rename(columns={0: 'year_group'})

movies_rat_mean = ratings_data[["movieId","rating"]].groupby(['movieId']).mean()
movies_rat_mean = movies_rat_mean.rename(columns={"rating": 'rating_mean'}).reset_index()

movies_rat_count = ratings_data[["movieId","rating"]].groupby(['movieId']).count()
movies_rat_count = movies_rat_count.rename(columns={"rating": 'rating_counts'}).reset_index()

movieId_year_group_rating_count_mean=pd.concat([movies_rat_count[["movieId"]],
                                     movies_year_group[["year_group"]],
                                     movies_rat_mean[["rating_mean"]],
                                     movies_rat_count[["rating_counts"]],
                                    ],axis=1)

movieId_year_group_rating_count_mean.dropna(subset = ["movieId"], inplace=True)
mov_rating_df = movieId_year_group_rating_count_mean

mov_tag_df = mov_tag_df.set_index('movieId')
mov_rating_df = mov_rating_df.set_index('movieId')
mov_genres_df = mov_genres_df.set_index('movieId')

from sklearn.metrics.pairwise import cosine_similarity
import numpy as np
vec1 = np.array([[1,1,0,1,1]])
vec2 = np.array([[0,1,0,1,1]])

cos_tag = cosine_similarity(mov_tag_df.values)*0.5

cos_genres = cosine_similarity(mov_genres_df.values)*0.25
cos_rating = cosine_similarity(mov_rating_df.values)*0.25
cos = cos_tag+cos_genres+cos_rating

cols = mov_tag_df.index.values
inx = mov_tag_df.index

movies_sim = pd.DataFrame(cos, columns=cols, index=inx)

movies_sim.loc[movies_sim.index == 9].reset_index(). \
  melt(id_vars='movieId', var_name='sim_moveId',
  value_name='relevance')

movies_sim.loc[movies_sim.index == 9].reset_index(). \
  melt(id_vars='movieId', var_name='sim_moveId',
  value_name='relevance') .\
  sort_values('relevance', axis=0, ascending=False)[1:6]

def get_similar(movieId):
  df = movies_sim.loc[movies_sim.index == movieId].reset_index(). \
  melt(id_vars='movieId', var_name='sim_moveId',
  value_name='relevance'). \
  sort_values('relevance', axis=0, ascending=False)[1:6]
  return df

movies_similarity = pd.DataFrame(columns=['movieId','sim_moveId','relevance'])

for x in movies_sim.index.tolist():
  movies_similarity = movies_similarity.append(get_similar(x))

def movie_recommender(movieId):
    df = movies_sim.loc[movies_sim.index == movieId].reset_index(). \
            melt(id_vars='movieId', var_name='sim_moveId', value_name='relevance'). \
            sort_values('relevance', axis=0, ascending=False)[1:6]
    df['sim_moveId'] = df['sim_moveId'].astype(int)
    sim_df = movies_data.merge(df, left_on='movieId', right_on='sim_moveId', how='inner'). \
                sort_values('relevance', axis=0, ascending=False). \
                loc[: , ['movieId_y','title','genres']]. \
                rename(columns={ 'movieId_y': "movieId" })
    return sim_df

users_df = pd.DataFrame(ratings_data['userId'].unique(), columns=['userId'])
movies_df = movies_data.drop('genres', axis = 1)

agg_rating_avg = ratings_data.groupby(['movieId']).agg({'rating': np.mean}).reset_index()
agg_rating_avg.columns = ['movieId', 'rating_mean']

movies_df = movies_df.merge(agg_rating_avg, left_on='movieId', right_on='movieId', how='left')

genres = [
    "Action",
    "Adventure",
    "Animation",
    "Children",
    "Comedy",
    "Crime",
    "Documentary",
    "Drama",
    "Fantasy",
    "Film-Noir",
    "Horror",
    "Musical",
    "Mystery",
    "Romance",
    "Sci-Fi",
    "Thriller",
    "War",
    "Western",
    "(no genres listed)"]

genres_df = pd.DataFrame(genres, columns=['genres'])

users_movies_df = ratings_data.drop('timestamp', axis = 1)
movies_genres_df = movies_data.drop('title', axis = 1)

def get_movie_genres(movieId):
    movie = movies_genres_df[movies_genres_df['movieId']==movieId]
    genres = movie['genres'].tolist()
    df = pd.DataFrame([b for a in [i.split('|') for i in genres] for b in a], columns=['genres'])
    df.insert(loc=0, column='movieId', value=movieId)
    return df

movies_genres=pd.DataFrame(columns=['movieId','genres'])
for x in movies_genres_df['movieId'].tolist():
    movies_genres=movies_genres.append(get_movie_genres(x))

user_genres_df = ratings_data.merge(movies_data, left_on='movieId', right_on='movieId', how='left')
user_genres_df.drop(['movieId','rating','timestamp','title'], axis = 1, inplace=True)

def get_favorite_genre(userId):
    user = user_genres_df[user_genres_df['userId']==userId]
    genres = user['genres'].tolist()
    movie_list = [b for a in [i.split('|') for i in genres] for b in a]
    counter = Counter(movie_list)
    return counter.most_common(1)[0][0]

users_genres = pd.DataFrame(columns=['userId','genre'])
for x in users_df['userId'].tolist():
    users_genres = users_genres.append(pd.DataFrame([[x,get_favorite_genre(x)]], columns=['userId','genre']))

users_df.to_csv('import/users.csv', sep='|', header=True, index=False)
movies_df.to_csv('import/movies_new.csv', sep='|', header=True, index=False)
genres_df.to_csv('import/genres.csv', sep='|', header=True, index=False)
users_movies_df.to_csv('import/users_movies.csv', sep='|', header=True, index=False)
movies_genres.to_csv('import/movies_genres.csv', sep='|', header=True, index=False)
users_genres.to_csv('import/users_genres.csv', sep='|', header=True, index=False)
movies_similarity.to_csv('import/movies_similarity.csv', sep='|', header=True, index=False)


from PyQt5.QtWidgets import QWidget, QLabel, QPushButton, QLineEdit, QVBoxLayout, QSizePolicy, QDateEdit

class User_input(QWidget):
    def __init__(self):
        super().__init__()

        central = QVBoxLayout()
        name_lbl = QLabel('Name:')
        name_lbl.setSizePolicy(QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed))
        # move
        self.name_line = QLineEdit()
        self.name_line.textChanged.connect(self.check_name_correctness)
        # move
        date_birth_lbl = QLabel('Date of birth:')
        self.date_birth_line = QDateEdit()
        self.date_birth_line.setCalendarPopup(True)

        self.start_btn = QPushButton('Start')
        #self.start_btn.clicked.connect(self.start_pressed)
        self.start_btn.setEnabled(False)

        central.addStretch()
        central.addWidget(name_lbl)
        central.addWidget(self.name_line)
        self.name_line.setMaximumWidth(200)
        central.addWidget(date_birth_lbl)
        central.addWidget(self.date_birth_line)
        self.date_birth_line.setMaximumWidth(200)
        central.addWidget(self.start_btn)
        self.start_btn.setMaximumWidth(200)
        central.addStretch()
        self.setLayout(central)

    def check_name_correctness(self):
        self.start_btn.setEnabled(self.name_line.text() != '')

    def start_pressed(self):
        self.start_btn.setEnabled(False)

    def user_data(self):
        return self.name_line.text(), self.date_birth_line.date().toString('yyyy-MM-dd')


from os import linesep
import numpy
import pandas as pd

class Calculo():
    def funcao(Matriz,Termos):
        Deter = []
        aux = []
        temp = []
        temp1 = []
        for i in range(len(Matriz)):
            s = str(i+1)
            temp.append("X"+s+" =")
            temp1.append(" ")

        Deter.append(numpy.linalg.det(Matriz))
        if Deter[0] != 0:
            print("\nCoeficientes:")
            print(pd.DataFrame(Matriz, columns=[temp1], index=[temp]))
            temp.clear()
            temp1.clear()

            for i in range(len(Termos)):
                s = str(i+1)
                temp.append("T"+s+" =")

            print("\nTermos independentes:")
            print(pd.DataFrame(Termos, columns=[" "], index=[temp]))

            t = 0
            for i in range(len(Matriz)):
                for j in range(len(Matriz[0])):
                    if t == j:
                        aux.append(Termos)
                    else:
                        aux.append(Matriz[j])

                Deter.append(numpy.linalg.det(aux))
                t = t + 1
                aux.clear()
            for i in range(8):
                print("=",end="")
                print("-",end="")
            print("=",end="")

            print("\nValores Reais:")
            for i in range(len(Matriz)):
                print("X",i+1,"=", round(Deter[i+1]/Deter[0],2))
        else:
            print('Sistema Indeterminado ou Impossível')


##########################################################################################
### FileName: compileResult.py
### Author: Zhuozheng Shi
### Date: 10/25/2023
### Affiliation: UCLA Bogdan Lab
### Description: compile results from all chromosomes, draw association figure, draw Q-Q
###              plot, draw histogram, and compute a row for table
### Input: [out] output file path and name for figures and one row of table
###        [inputPath] input file path and prefix name for chromosomes pd.DataFrame file,
###                    generated by computeChrom.py
###        [name] name displayed in figure title
### Output: association list of pd.DataFrame, "{out}.csv.gz", containing "L1_BETA","L1_SE",
###         "N", and "P"
###         association plot, "{out}.png"
###         Q-Q plot, "{out}_qqplot.png"
###         histogram, "{out}_histo.png"
##          row of table (conclusion), "{out}.npy", including lambda_gc and #hits
##########################################################################################

import matplotlib.pyplot as plt
import admix
import numpy as np
from admix.plot import compare_pval
from os.path import join
import pandas as pd
import math
import sys
import argparse
import openpyxl
import os
import statsmodels.api as sm
import statsmodels.formula.api as smf
import copy
import statsmodels
import time
import dask.array as da
import qtl
from qtl.plot import qqplot
import matplotlib.image as mpimg
from scipy import stats
import re
import structlog

logger = structlog.get_logger()
parser = argparse.ArgumentParser()
parser.add_argument("-o", "--out",dest = "out")
parser.add_argument("-i", "--inputPath",dest = "inputPath")
parser.add_argument("-n", "--name",dest = "name")

args = parser.parse_args()

out = args.out
inputPath = args.inputPath
name = args.name
logger.info(
        f"Currently compiling chromosomes in {inputPath}"
    )

# read 22 separate chromosomes
chrCount = 22
dfs = []
for i in range(1,chrCount+1):

    dfs.append(pd.read_csv(f"{inputPath}.{i}.csv.gz",index_col="id"))

df = pd.concat(dfs)
# save combined chromosomes
df.to_csv(f"{out}.csv.gz", index=True, index_label='id')
logger.info(
        f"Total of {df.shape[0]} lanc segments"
    )

# construction list for making two-colored plot
chrn = []
for i in range(0,chrCount):
    for j in range(dfs[i].shape[0]):
        chrn.append(i+1)

# plot association mapping and save
fig, ax = plt.subplots( figsize=(5, 3), dpi=150)
admix.plot.manhattan(np.array(df.P), ax=ax, s=2,chrom=np.array(chrn),axh_y=-np.log10(5e-5))
plt.tight_layout()

plt.title(f"Association of {name}")
plt.savefig(f"{out}.png",bbox_inches='tight')
plt.close(fig)
logger.info(
        f"Saving association to {out}.csv.gz and {out}.png"
    )

# check whether association p values are nan
if np.isnan(np.array(df.sort_values(by=['P']).P)[0]) and np.isnan(np.array(df.sort_values(by=['P']).P)[-1]):
    # save wrong message if p values are nan
    with open(f'{out}_qqplot.txt', 'a') as the_file:
        the_file.write('Wrong')
    with open(f'{out}_histo.txt', 'a') as the_file:
        the_file.write('Wrong')
    logger.info(
            f"Nan found in association p values, .txt files wrote"
        )

else:
    #plot qqplot
    SNPs = df
    fig, ax = plt.subplots(figsize=(5, 5), dpi=150)
    ret = qqplot(list(SNPs["P"]),ax=ax,title=F"Q-Q plot of {name}")
    fig.savefig(f"{out}_qqplot.png",bbox_inches='tight')

    #plot histogram
    zscore = np.array(df["L1_BETA"])/np.array(df["L1_SE"])

    plt.figure(figsize=(15,10))
    plt.rcParams.update({'font.size': 22})
    plt.hist(zscore, bins=500,density=True)
    x=np.linspace(-4,4,10000)
    y=stats.norm.pdf(x, 0, 1)
    plt.plot(x,y,color="orange")
    plt.title(f"Histogram of {name}")

    plt.savefig(f"{out}_histo.png",bbox_inches='tight')
    plt.close(fig)
    logger.info(
            f"Saving to {out}_qqplot.png and {out}_histo.png"
        )

# construct single row of table
temp = [name]

gc = admix.data.lambda_gc(np.array(list(SNPs.P)))
temp.append(gc)

t1 = df.P[df.P<5e-5]

temp.append(len(t1))

t2 = df.P[df.P<5e-4]

temp.append(len(t2))

np.save(f"{out}_tableRow",temp)

logger.info(
        f"Saving row of table to {out}_tableRow.npy"
    )


class Solution:
    def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
        """
        TC : O(N+E)
        SC : O(N)
        N --> # rooms
        E --> # keys
        """
        visited = [False] * len(rooms)
        self.dfs(rooms, visited, 0)
        return all(visited)

    def dfs(self, rooms, visited, room_key):
        if not visited[room_key]:
            visited[room_key] = True
        else:
            return
        for new_room_key in rooms[room_key]:
            self.dfs(rooms, visited, new_room_key)


from pytube import YouTube

def download_video():
    print("Welcome to Youtube Downloader.\n Type Q to exit.")
    while True:
        link = input(">> Copy paste YT link: ")
        if link.lower() == "q":
            break

        yt = YouTube(f'{link}')
        print(link, yt)
        stream = yt.streams.get_by_itag(22)
        size = round(stream.filesize / 10 ** 6, 2)

        print(f"Downloading {yt.title}, \n Length: {yt.length} seconds, \n Size: {size}MBs")

        stream.download()
        print("Download Complete :)")

    print("Exiting program.\nThank You :D\n")

download_video()


'''
Q10. Maximum Subarray

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

sample i/p --> [-2,1,-3,4,-1,2,1,-5,4]
sample o/p --> 6

leetcode --> https://leetcode.com/problems/maximum-subarray/

Difficulty --> Easy

Reference --> Kadane's Algorithm --> https://www.youtube.com/watch?v=86CQq3pKSUw
'''

def max_subarry(arr):
    curr_sum = max_ = arr[0]
    for i in range(1, len(arr)):
        curr_sum = max(arr[i], curr_sum + arr[i])
        if curr_sum > max_:
            max_ = curr_sum
    return max_

print(max_subarry([-2, 1, -3, 4, -1, 2, 1, -5, 4]))


import os

from setuptools import setup, find_namespace_packages

with open("README.md", "r") as fh:
    long_description = fh.read()

requirements = []
if os.path.exists('requirements.txt'):
    with open('requirements.txt') as req:
        requirements = list(filter(None, req.read().splitlines()))

setup(
    name="{package_name}",
    version="0.0.1",
    author="{author}",
    author_email="{email}",
    description="{package_description}",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://github.com/pypa/sampleproject",
    packages=find_namespace_packages(include=['radiome.*']),
    package_data={{
        'radiome.workflows.{package_name}': ['spec.yml']
    }},
    install_requires=requirements,
    classifiers=[
        "Programming Language :: Python :: 3",
        "Operating System :: OS Independent",
    ],
    python_requires='>=3.6',
    include_package_data=True,
    zip_safe=False,
)