from rest_framework import viewsets, mixins, status
from rest_framework.response import Response
from django_filters.rest_framework import DjangoFilterBackend
from django.contrib.auth import get_user_model
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.permissions import IsAuthenticated

from .models import UserFav, UseFollow
from users.models import UserProfile
from .serializers import UserFavSerialzers, UserFollowSerialzers, UserFavRetriveSerialzers, UserFollowRetrieveSerialzers

User = get_user_model()

class UserFavViewset(viewsets.GenericViewSet, mixins.DestroyModelMixin, mixins.ListModelMixin, mixins.CreateModelMixin):
    """用户收藏功能"""
    # queryset = UserFav.objects.all()
    authentication_classes = (JSONWebTokenAuthentication,)
    permission_classes = (IsAuthenticated,)

    filter_backends = (DjangoFilterBackend,)
    filterset_fields = ('user', )

    def get_serializer_class(self):
        if self.action == "create":
            return UserFavSerialzers
        else:
            return UserFavRetriveSerialzers

    def get_queryset(self):
        if self.action == "create":
            return UserFav.objects.all()
        else:
            return UserFavRetriveSerialzers.data_preloading(UserFav.objects.all())

    def create(self, request, *args, **kwargs):

        data = request.data

        data["user"] = self.request.user.id

        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)

        data1 = serializer.data
        data1["content"] = "收藏成功"

        headers = self.get_success_headers(serializer.data)
        return Response(data1, status=status.HTTP_201_CREATED, headers=headers)

    def perform_create(self, serializer):
        serializer.save()

class UserFollowViewset(viewsets.GenericViewSet, mixins.DestroyModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.CreateModelMixin):
    """用户关注功能"""
    # queryset = UseFollow.objects.all()
    # serializer_class = UserFollowSerialzers
    authentication_classes = (JSONWebTokenAuthentication,)
    permission_classes = (IsAuthenticated,)

    filter_backends = (DjangoFilterBackend,)
    filterset_fields = ('user', 'follow')

    def get_serializer_class(self):
        if self.action == "create":
            return UserFollowSerialzers
        else:
            return UserFollowRetrieveSerialzers

    def get_queryset(self):
        if self.action == "create":
            return UseFollow.objects.all()
        else:
            return UserFollowRetrieveSerialzers.data_preloading(UseFollow.objects.all())

    def create(self, request, *args, **kwargs):

        data = request.data
        data["user"] = self.request.user.id
        if "user_name" in data:
            data["follow"] = User.objects.filter(username=data["user_name"])[0].id

        resu = UseFollow.objects.filter(user_id=int(data["user"]), follow_id=int(data["follow"]))
        if len(resu):
            return Response({
                "content": '您已经关注过该用户了'
            }, status=status.HTTP_200_OK)

        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)

        data1 = serializer.data
        data1["content"] = "关注成功"

        headers = self.get_success_headers(data1)
        return Response(data1, status=status.HTTP_201_CREATED, headers=headers)

    def perform_create(self, serializer):
        serializer.save()
        # 修改用户的关注数
        user = self.request.user
        user.attention += 1
        user.save()
        # 修改用户的粉丝数
        user_follow = User.objects.filter(id=serializer.data['follow'])[0]
        user_follow.fans += 1
        user_follow.save()

    def perform_destroy(self, instance):
        # 修改用户的关注数
        user = self.request.user
        user.attention -= 1
        user.save()

        # 修改用户的粉丝数
        follow_id = int(instance.follow_id)
        user_follow = UserProfile.objects.filter(id=follow_id)[0]
        user_follow.fans -= 1
        user_follow.save()

        instance.delete()


# -*- coding:utf-8 -*-
import requests
import json
from textwrap import dedent

# 通过两个API获取信息。
# 获取基础天气信息
def fetch_weather(location):
    result = requests.get(
        'https://api.seniverse.com/v3/weather/daily.json',
        params={
        'key': 'mbghskqqeagdjdqt',
        'location': location,
        'language': 'zh-Hans',
        'unit': 'c'
    }, timeout=60)
    return result.text

# 获取基于天气状况的关于生活的信息
def fetch_life(location):
    result = requests.get(
        'https://api.seniverse.com/v3/life/suggestion.json',
        params={
        'key': 'mbghskqqeagdjdqt',
        'location': location,
        'language': 'zh-Hans',
        'unit': 'c'
    }, timeout=60)
    return result.text

# 对获取的天气信息进行解析
def process_weather(result):
    weather_data = json.loads(result)
    location = weather_data['results'][0]['location']['name']
    date = weather_data['results'][0]['daily'][0]['date']
    text_day = weather_data['results'][0]['daily'][0]['text_day']
    text_night = weather_data['results'][0]['daily'][0]['text_night']
    wind_direction = weather_data['results'][0]['daily'][0]['wind_direction']
    high = weather_data['results'][0]['daily'][0]['high']
    low = weather_data['results'][0]['daily'][0]['low']
    weather_info = '{}{}的天气情况如下：\n白天天气：{}，晚间天气：{}，最高气温：{}摄氏度，最低气温：{}摄氏度，风向：{}\n'.format(
        location, date, text_day, text_night, high, low, wind_direction)
    return weather_info

# 对获取的生活信息进行解析
def process_life(result):
    life_data = json.loads(result)
    sport = life_data['results'][0]['suggestion']['sport']['brief']
    uv = life_data['results'][0]['suggestion']['uv']['brief']
    life_info = '运动适宜度：{}，紫外线强度：{}\n'.format(sport, uv)
    return life_info

# 合并从多个API获取的信息
def show_info(user_input):
    user_info = process_weather(fetch_weather(user_input)) + process_life(
        fetch_life(user_input))
    return(user_info)

# 定义退出程序函数
def out(history_info):
    if len(history_info) > 0:
        print('即将退出本程序，谢谢使用，以下是你的查询历史：')
        print(history_info)
    else:
        print('你没有进行城市查询，即将退出本程序，谢谢使用')

    quit(0)

# 主函数
def main():
    history_info = ''
    help_doc = dedent('''
        输入城市名或拼音，查询该城市的天气情况；
            比如：北京，四川成都，beijing，sichuan chengdu
        输入help或h，获取帮助文档；
        输入history或his，获取查询历史；
        输入quit或q，退出天气查询系统。''')
    print('----该程序数据由心知天气提供----')
    while True:
        print('请输入城市名称或拼音查询天气；如需获取帮助，请输入help或h。')
        user_input = input('>>>')
        if user_input in ['help', 'h']:
            print(help_doc)
        elif user_input in ['quit', 'q']:
            out(history_info)
        elif user_input in ['history', 'his']:
            if len(history_info) > 0:
                print('这是你的搜索记录：')
                print(history_info)
            else:
                print('你还没有查询过天气')
        else:
            try:
                history_data = show_info(user_input)
                print(history_data)
                history_info += '\n' + history_data
            except Exception as exc:
                print('你输入的城市名有误或包含多余空格，或暂不能提供该城市天气信息，请重新输入\n')

if __name__ == '__main__':
    main()


def añobisiesto(año):
    return not año % 4 and (año % 100 or not año % 400)
def meses(año,mes):
    if año >= 0 and mes >= 1 and mes <= 12:
        dia=[31,28,31,30,31,30,31,31,30,31,30,31]
        añob=[31,29,31,30,31,30,31,31,30,31,30,31]

        if añobisiesto(año)== True:
            return añob[mes-1]
        else:
            return dia[mes-1]

    else:
            return None

def tdod(dia,mes,año):
    if año >= 0 and mes >= 1 and mes <= 12 and dia >= 1 and dia <= 31:
        suma = 0
        for i in range (mes-1):
            suma+=meses(año,i+1)
            suma+=dia
            return suma
        else:
            return None

print(tdod(31,12,2000))
print(tdod(25,3,2015))

PYTHON/Ejercicio en clases/Nueva carpeta (5)/final.py


import traceback
from khl import (Bot, Message, PrivateMessage, requester, Channel)
from khl.card import Card, CardMessage, Element, Module, Types, Struct

from ..utils.log import BotLog
from ..utils.file.FileManage import write_file
from ..utils.file.Files import UserAuthCache,ValMissionDict,_log
from ..utils.valorant.EzAuth import EzAuth,EzAuthExp
from ..utils.valorant import Reauth
from ..utils.valorant.api import Riot
from ..utils import Gtime,KookApi

def get_sub_text(text:str):
    """提供 用户任务日志信息，返回提示用户的sub_text"""
    sub_text = f"[说明](https://img.kookapp.cn/assets/2023-03/bOHjyLGtAc10f0sm.png) -> "
    sub_text+= "请转到[金山表单](https://f.wps.cn/g/Fipjms3w/)填写相关信息\n"
    sub_text+= "填写表单时，提供下方=右侧编号即可，感谢！\n"
    sub_text+= f"```\n{text}\n```"
    return sub_text

def init(bot:Bot,debug_ch:Channel):
    @bot.command(name='mission',case_sensitive=False)
    async def mission(msg:Message,*arg):
        BotLog.log_msg(msg)
        send_msg = {'msg_id':''}
        cm = CardMessage()
        try:
            # 1.如果用户不在Authdict里面，代表没有登录，直接退出
            if msg.author_id not in UserAuthCache['kook']:
                await msg.reply(await KookApi.get_card_msg("您尚未登陆！请「私聊」使用login命令进行登录操作", f"「/login 账户 密码」请确认您知晓这是一个风险操作", KookApi.icon_cm.whats_that)) # type:ignore
                return

            # 2.直接使用for循环来获取不同用户的信息
            mission_cm = CardMessage()
            log_m_text = "" # 记录save到本地的用户战绩信息，用于收集id
            save_flag = False # 是否要保存到本地（如果存在未录入的就保存）
            for riot_user_id in UserAuthCache['kook'][msg.author_id]:
                try:
                    # 3.执行cookie重登
                    reau = await Reauth.check_reauth("玩家任务",msg.author_id,riot_user_id,debug_ch,msg)
                    if reau == False: return  #如果为假说明重新登录失败
                    # 3.2 获取玩家id成功了，再提示正在获取商店
                    cm = await KookApi.get_card_msg("正在尝试获取您的每日任务", "阿狸正在施法，很快就好啦！", KookApi.icon_cm.duck)
                    # 3.2.1 如果reauth函数return的是dict，说明重新登录成功且发送了消息，则更新卡片
                    if isinstance(reau, dict):
                        await KookApi.upd_card(reau['msg_id'], cm, channel_type=msg.channel_type)
                        send_msg = reau
                    # 3.2.1 不是dict，说明不需要重登，也没有发送提示信息
                    else:
                        send_msg = await msg.reply(cm)  #记录消息id用于后续更新

                    auth = UserAuthCache['data'][riot_user_id]['auth']
                    assert isinstance(auth, EzAuth)
                    # 获取玩家任务
                    ret = await Riot.fetch_player_contract(auth.get_riotuser_token())
                    mission_list = ret["Missions"] # 任务列表
                    mission_meta = ret["MissionMetadata"] # 任务重置信息
                    # 构造任务信息
                    save_flag = False
                    m_text = ""
                    for m in mission_list:
                        if m["ID"] not in ValMissionDict:
                            save_flag = True
                            continue
                        m_info = ValMissionDict[m["ID"]]
                        m_text+=f"[{m_info['MissionType']}] {m_info['DisplayName']}\n"
                        m_text+=f"[进度] {m['Objectives'][m_info['ObjectivesID']]}/{m_info['Total']}\n"

                    # 构造卡片(只要m_text不为空就构造)
                    if m_text:
                        c = Card(Module.Header(f"玩家「{auth.Name}#{auth.Tag}」的任务"))
                        c.append(Module.Section(Element.Text(f"```\n{m_text}```\n",Types.Text.KMD)))
                        c.append(Module.Context(Element.Text(f"每周任务重制时间 {mission_meta['WeeklyRefillTime']}",Types.Text.KMD)))
                        mission_cm.append(c)

                    # 保存到本地（记录未录入的任务）
                    if save_flag:
                        id_text = f"{auth.user_id}_{int(Gtime.time.time())}"
                        log_m_text += f"{auth.Name}#{auth.Tag} = {id_text}\n"
                        write_file(f'./log/mission/{id_text}.json',ret)
                    # 结束
                    _log.info(f"Au:{msg.author_id} | get {riot_user_id} mission success")
                except KeyError as result:
                    if "Missions" in str(result):
                        _log.exception(f"KeyErr while Au:{msg.author_id} | Ru:{riot_user_id}")
                        cm2 = await KookApi.get_card_msg(f"键值错误，需要重新登录",
                                                         f"KeyError:{result}, please re-login", KookApi.icon_cm.lagging)
                        await KookApi.upd_card(send_msg['msg_id'], cm2, channel_type=msg.channel_type)
                    else:raise result

            # 多个账户都获取完毕，发送卡片并输出结果
            cm = mission_cm
            if save_flag: # 该用户尚有未处理的任务id
                cm.append(await KookApi.get_card("您账户的任务尚未完全收录!", get_sub_text(log_m_text)))
            await KookApi.upd_card(send_msg['msg_id'], cm, channel_type=msg.channel_type)
            _log.info(f"Au:{msg.author_id} | mission reply successful!")
        except requester.HTTPRequester.APIRequestFailed as result:
            await BotLog.api_request_failed_handler("mission",traceback.format_exc(),msg,bot,cm)
        except Exception as result:
            await BotLog.base_exception_handler("mission",traceback.format_exc(),msg)

    _log.info("[plugins] load Mission.py")


import unittest

import numpy as np

from som import SOM
from som_evaluator import SOMEvaluator
from visualizer.som_visualizer import SOMVisualizer

class TestSOMEvaluator(unittest.TestCase):
    def setUp(self):
        # Create a fixed dataset
        self.data = np.array([
            [1, 1],
            [1, 0],
            [0, 1],
            [0, 0],
            [0.5, 0.5]
        ])

        # Create a fixed SOM instance with pre-defined weights
        self.som = SOM(data=self.data, x_size=2, y_size=2, input_dim=2,
                       epochs=10, learning_rate=0.1, initial_radius=1.0, final_radius=0.1)
        self.som.weights = np.array([
            [
                [1, 1],
                [1, 0]
            ],
            [
                [0, 1],
                [0, 0]
            ]
        ])

        self.evaluator = SOMEvaluator(self.som)

    def test_a(self):

        self.assertTrue(-1 <= 0.5 <= 1)

    def test_calculate_wcss(self):
        expected_wcss = 0.5
        actual_wcss = self.evaluator.calculate_wcss()
        self.assertAlmostEqual(expected_wcss, actual_wcss, places=6)

    def test_calculate_silhouette_score(self):
        expected_silhouette_score = 0.0  # Updated manually calculated silhouette
        actual_silhouette_score = self.evaluator.calculate_silhouette_score()

        # Check if the silhouette score is close to the expected value
        self.assertAlmostEqual(expected_silhouette_score, actual_silhouette_score, places=6)

    def test_calculate_topological_error(self):
        expected_error = 0.2  # Manually calculated topological error for the fixed dataset
        actual_error = self.evaluator.calculate_topological_error()
        self.assertAlmostEqual(expected_error, actual_error, places=6)

if __name__ == '__main__':
    unittest.main()


# This file is aimed to be a very simple example on how to:
#  * Establish a websocket connection
#  * Create async tasks and control them properly. In this example we have two tasks:
#    - Task that prints every incoming message (Messages returned from the echo server)
#    - Task that sends a message to the echo server every 15 seconds
import asyncio
import logging

from aiohttp import ClientSession, ClientWebSocketResponse
from aiohttp.http_websocket import WSMessage

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('client')

async def subscribe_to_messages(websocket: ClientWebSocketResponse) -> None:
    """
    A subscription handler to subscribe to messages. Simply logs them.

    :param websocket: Websocket connection
    :return: None, forever living task
    """
    async for message in websocket:
        if isinstance(message, WSMessage):
            logger.info('> Message from server received: %s', message.json())

async def send_hello_world_message(websocket: ClientWebSocketResponse) -> None:
    """
    A function that sends a Hello World message every 15 seconds.

    :param websocket: Websocket connection
    :return: None, forever living task
    """
    while True:
        message = {'message': 'Hello world!'}
        logger.info('< Sending message: %s', message)
        await websocket.send_json(message)
        await asyncio.sleep(15)

async def echo_handler() -> None:
    """
    Does the following:

     * Open a websocket connection
     * Creates two tasks, one that sends a message, one that prints the messages that gets back
     * Every 60 seconds it sends a "Hello world!" message to the echo endpoint (`/`)
    :return: None
    """
    # Create a session
    async with ClientSession() as session:
        # Connect with websocket to the echo endpoint
        async with session.ws_connect('ws://0.0.0.0:8080/echo', ssl=False) as ws:
            send_message_task = asyncio.create_task(send_hello_world_message(websocket=ws))
            subscribe_to_messages_task = asyncio.create_task(subscribe_to_messages(websocket=ws))

            # This function returns two variables, a list of `done` and a list of `pending` tasks.
            # We can ask it to return when all tasks are completed, first task is completed or on first exception
            done, pending = await asyncio.wait(
                [send_message_task, subscribe_to_messages_task], return_when=asyncio.FIRST_COMPLETED,
            )
            # When this line of line is hit, we know that one of the tasks has been completed.
            # In this program, this can happen when:
            #   * we (the client) or the server is closing the connection. (websocket.close() in aiohttp)
            #   * an exception is raised

            # First, we want to close the websocket connection
            if not ws.closed:
                await ws.close()
            # Then, we cancel each task which is pending:
            for task in pending:
                task.cancel()
            # At this point, everything is shut down. The program will exit.

if __name__ == '__main__':
    asyncio.run(echo_handler())


def reverse_string(text: str):
    letter_list = [word for word in text]
    return ''.join(reversed(letter_list))

text1 = "This code uses a defaultdict(int), which is a subclass of the built-in dict class in Python that returns a default value of 0 for nonexistent keys. This allows us to increment the count for a word without first having to check if it's already in the hash table. The code takes a string of text, split it into list of words and count the occurrences of each word by keeping track of the count in the hash table and finally it prints the result."

print(reverse_string(text1))

def letter_count2(text: str,):
    word_list = []
    for i in text:
        if i != ' ':
            word_list.append(i)
    return word_list

print(letter_count2(text1))

def word_count(text: str):
    words = 0
    word_list = text.split()
    for i in word_list:
        words += 1
    return word_list

print(word_count(text1))


# coding:utf-8

class Node:

    def __init__(self, x):
        self. val = x

    def __str__(self):
        return str(self.val)

class ListNode(Node):

    def __init__(self, x):
        super().__init__(x)
        self.next = None

    def __str__(self):
        result = f'{self.val}'
        if self.next:
            result = f'{result} -> {self.next}'
        return result

    def __eq__(self, node):
        if not isinstance(node, self.__class__):
            return False
        return self.val.__eq__(node.val) and self.next.__eq__(node.next)

    @classmethod
    def init_with_list(cls, value_list):
        if not value_list:
            return None
        if not isinstance(value_list, list):
            return ListNode(value_list)
        root_node = ListNode(value_list[0])
        pre_node = root_node
        for value in value_list[1:]:
            pre_node.next = ListNode(value)
            pre_node = pre_node.next
        return root_node


def prep(n, p, q):
    pq = p**q
    fact = [1]*(n+1)
    for i in range(2, n+1):
        if i % p:
            fact[i] = fact[i-1]*i % pq
        else:
            fact[i] = fact[i-1]
    return fact

def modpow(c, n, d):
    r = 1
    while n:
        if n & 1:
            r = r*c % d
        c = c*c % d
        n >>= 1
    return r

def comb(n, r, p, q):
    pq = p**q
    fact = prep(pq-1, p, q)

    def em(n):
        if n < pq:
            k = n//p
            return k, fact[n]
        k = n//p
        t, s = divmod(n, pq)
        ne, nm = em(k)
        e = k+ne
        m = nm*modpow(fact[pq-1], t, pq)*fact[s] % pq
        return e, m

    e1, m1 = em(n)
    e2, m2 = em(r)
    e3, m3 = em(n-r)
    e = e1-e2-e3
    if e:
        return 0
    for i in range(pq):
        if m2*m3*i % pq == 1:
            break
    return m1*i % pq

n, k = map(int, input().split())
print(comb(n, k, 2, 32))


"""Stormpath VerificationEmail resource mappings."""

from .account import Account
from .base import (
    CollectionResource,
    Resource,
)

class VerificationEmail(Resource):
    pass

class VerificationEmailList(CollectionResource):
    """List of email verfication requests."""
    resource_class = VerificationEmail

    def _ensure_data(self):
        raise ValueError("It is not possible to access verification_emails!")

    def resend(self, account=None, account_store=None):
        """Resend the Email Verification Token.

        :param account:  An :class:`stormpath.resources.account.Account`
        :param account_store: A :class:`stormpath.resources.directory.Directory` or :class:`stormpath.resources.group.Group`.
        """
        if account is None or account_store is None:
            raise ValueError('You must specify the Account and Account Store')

        if isinstance(account_store, Resource):
            account_store = account_store.href

        if isinstance(account, Account):
            account = account.email

        data = self._store.create_resource(self._get_create_path(), {
            'login': account,
            'account_store': account_store
        })

        return self.resource_class(client=self._client, properties=data)


import speedtest

def get_speed():

    try:
        speedtester = speedtest.Speedtest()
        speedtester.get_best_server()
        download = speedtester.download()
        upload = speedtester.upload()
        tmpD = bytesto(download, 'm')
        tmpU = bytesto(upload, 'm')
        speed =   str(round(tmpD, 2) ) + " / " + str( round(tmpU,2) ) +" MB/s"
        return speed
    except:
    	pass

def bytesto(bytes, to, bsize=1024):
    """convert bytes to megabytes, etc.
       sample code:
           print('mb= ' + str(bytesto(314575262000000, 'm')))
       sample output:
           mb= 300002347.946
    """

    a = {'k' : 1, 'm': 2, 'g' : 3, 't' : 4, 'p' : 5, 'e' : 6 }
    r = float(bytes)
    for i in range(a[to]):
        r = r / bsize

    return(r)

speed = get_speed()
print(speed)


# Jinhao Cao, NAOCE, SJTU, 20200501
# SLSQP

import math, scipy.optimize

def RandomAxisRandomBeta(Axis, Beta):
	# rotate beta at origin around axis and return matrix
	Beta = math.pi / 180 * Beta;
	u, v, w = Axis[0], Axis[1], Axis[2]
	d = u * u + v * v + w * w
	h = d ** 0.5
	m11 = (u * u + (v * v + w * w) * math.cos(Beta)) / d
	m21 = (u * v * (1 - math.cos(Beta)) + w * h * math.sin(Beta)) / d
	m31 = (u * w * (1 - math.cos(Beta)) - v * h * math.sin(Beta)) / d
	m12 = (u * v * (1 - math.cos(Beta)) - w * h * math.sin(Beta)) / d
	m22 = (v * v + (u * u + w * w) * math.cos(Beta)) / d
	m32 = (v * w * (1 - math.cos(Beta)) + u * h * math.sin(Beta)) / d
	m13 = (u * w * (1 - math.cos(Beta)) + v * h * math.sin(Beta)) / d
	m23 = (v * w * (1 - math.cos(Beta)) - u * h * math.sin(Beta)) / d
	m33 = (w * w + (u * u + v * v) * math.cos(Beta)) / d
	return [m11, m21, m31, 0, m12, m22, m32, 0, m13, m23, m33, 0, 0, 0, 0, 1]

def MatrixMultiply(Axis, TR):
	# axis times matrix and return axis
	Newer = [0, 0, 0]
	Newer[0] = Axis[0] * TR[0] +  Axis[1] * TR[1] +  Axis[2] * TR[2] + 1 * TR[3];
	Newer[1] = Axis[0] * TR[4] +  Axis[1] * TR[5] +  Axis[2] * TR[6] + 1 * TR[7];
	Newer[2] = Axis[0] * TR[8] +  Axis[1] * TR[9] +  Axis[2] * TR[10] + 1 * TR[11];
	return Newer

# example for PlanePlaneParallel
def SequentialLeastSquaresProgramming(Part1_Plane=[0, 1, 0],
									  Part2_Plane=[-1, 0, 0],
									  Part3_Plane1=[math.sqrt(2)/2, -math.sqrt(2)/2, 0],
									  Part3_Plane2=[math.sqrt(2)/2, math.sqrt(2)/2, 0]):
	def Objective(Rotate):
		return Rotate[3]

	def Constraint1(Rotate):
		Newer = MatrixMultiply(Part3_Plane1, RandomAxisRandomBeta([Rotate[0], Rotate[1], Rotate[2]], Rotate[3]))
		return abs((Newer[0] * Part1_Plane[0] + Newer[1] * Part1_Plane[1] + Newer[2] * Part1_Plane[2]) / (Newer[0] ** 2 + Newer[1] ** 2 + Newer[2] ** 2) ** 0.5) - 1

	def Constraint2(Rotate):
	 	Newer = MatrixMultiply(Part3_Plane2, RandomAxisRandomBeta([Rotate[0], Rotate[1], Rotate[2]], Rotate[3]))
	 	return abs((Newer[0] * Part2_Plane[0] + Newer[1] * Part2_Plane[1] + Newer[2] * Part2_Plane[2]) / (Newer[0] ** 2 + Newer[1] ** 2 + Newer[2] ** 2) ** 0.5) - 1

	def Constraint3(Rotate):
		return (math.pow(Rotate[0], 2) + math.pow(Rotate[1], 2) + math.pow(Rotate[2], 2))**0.5 - 1

	Bound = ((-1.0, 1.0), (-1.0, 1.0), (-1.0, 1.0), (-180, 180))

	Con1 = {'type':'eq', 'fun':Constraint1}
	Con2 = {'type':'eq', 'fun':Constraint2}
	Con3 = {'type':'eq', 'fun':Constraint3}
	Cons = ([Con1, Con2, Con3])

	InitialSolution = [1.0, 1.0, 1.0, 90.0]

	OptimalSolution = scipy.optimize.minimize(Objective, InitialSolution, method='SLSQP', bounds=Bound, constraints=Cons, tol=1e-2, options={'maxiter':100})
	return OptimalSolution

print(SequentialLeastSquaresProgramming())


import utils
import models
import datasets
import numpy as np
import tensorflow as tf
from tensorflow.keras import metrics
from tensorflow.keras.datasets import mnist
from tensorflow.keras.utils import to_categorical
import pickle

def compile_model(model, loss='ce'):
    loss = models.get_loss(loss, model.output_shape[1])
    model.compile(optimizer='adam',
                  loss=[loss],
                  metrics=[metrics.sparse_categorical_accuracy])

def train_model_source(model, split_data, epochs=1000):
    model.fit(split_data.src_train_x, split_data.src_train_y, epochs=epochs, verbose=False)
    print("Source accuracy:")
    _, src_acc = model.evaluate(split_data.src_val_x, split_data.src_val_y)
    print("Target accuracy:")
    _, target_acc = model.evaluate(split_data.target_val_x, split_data.target_val_y)
    return src_acc, target_acc

def run_experiment(
    dataset_func, n_classes, input_shape, save_file, model_func=models.simple_softmax_conv_model,
    interval=2000, epochs=10, loss='ce', soft=False, conf_q=0.1, num_runs=20, num_repeats=None):
    (src_tr_x, src_tr_y, src_val_x, src_val_y, inter_x, inter_y, dir_inter_x, dir_inter_y,
        trg_val_x, trg_val_y, trg_test_x, trg_test_y) = dataset_func()
    if soft:
        src_tr_y = to_categorical(src_tr_y)
        src_val_y = to_categorical(src_val_y)
        trg_eval_y = to_categorical(trg_eval_y)
        dir_inter_y = to_categorical(dir_inter_y)
        inter_y = to_categorical(inter_y)
        trg_test_y = to_categorical(trg_test_y)
    if num_repeats is None:
        num_repeats = int(inter_x.shape[0] / interval)
    def new_model():
        model = model_func(n_classes, input_shape=input_shape)
        compile_model(model, loss)
        return model
    def student_func(teacher):
        return teacher
    def run(seed):
        utils.rand_seed(seed)
        trg_eval_x = trg_val_x
        trg_eval_y = trg_val_y
        # Train source model.
        source_model = new_model()
        source_model.fit(src_tr_x, src_tr_y, epochs=epochs, verbose=False)
        _, src_acc = source_model.evaluate(src_val_x, src_val_y)
        _, target_acc = source_model.evaluate(trg_eval_x, trg_eval_y)
        # Gradual self-training.
        print("\n\n Gradual self-training:")
        teacher = new_model()
        teacher.set_weights(source_model.get_weights())
        gradual_accuracies, student = utils.gradual_self_train(
            student_func, teacher, inter_x, inter_y, interval, epochs=epochs, soft=soft,
            confidence_q=conf_q)
        _, acc = student.evaluate(trg_eval_x, trg_eval_y)
        gradual_accuracies.append(acc)
        # Train to target.
        print("\n\n Direct boostrap to target:")
        teacher = new_model()
        teacher.set_weights(source_model.get_weights())
        target_accuracies, _ = utils.self_train(
            student_func, teacher, dir_inter_x, epochs=epochs, target_x=trg_eval_x,
            target_y=trg_eval_y, repeats=num_repeats, soft=soft, confidence_q=conf_q)
        print("\n\n Direct boostrap to all unsup data:")
        teacher = new_model()
        teacher.set_weights(source_model.get_weights())
        all_accuracies, _ = utils.self_train(
            student_func, teacher, inter_x, epochs=epochs, target_x=trg_eval_x,
            target_y=trg_eval_y, repeats=num_repeats, soft=soft, confidence_q=conf_q)
        return src_acc, target_acc, gradual_accuracies, target_accuracies, all_accuracies
    results = []
    for i in range(num_runs):
        results.append(run(i))
    print('Saving to ' + save_file)
    pickle.dump(results, open(save_file, "wb"))

def experiment_results(save_name):
    results = pickle.load(open(save_name, "rb"))
    src_accs, target_accs = [], []
    final_graduals, final_targets, final_alls = [], [], []
    best_targets, best_alls = [], []
    for src_acc, target_acc, gradual_accuracies, target_accuracies, all_accuracies in results:
        src_accs.append(100 * src_acc)
        target_accs.append(100 * target_acc)
        final_graduals.append(100 * gradual_accuracies[-1])
        final_targets.append(100 * target_accuracies[-1])
        final_alls.append(100 * all_accuracies[-1])
        best_targets.append(100 * np.max(target_accuracies))
        best_alls.append(100 * np.max(all_accuracies))
    num_runs = len(src_accs)
    mult = 1.645  # For 90% confidence intervals
    print("\nNon-adaptive accuracy on source (%): ", np.mean(src_accs),
          mult * np.std(src_accs) / np.sqrt(num_runs))
    print("Non-adaptive accuracy on target (%): ", np.mean(target_accs),
          mult * np.std(target_accs) / np.sqrt(num_runs))
    print("Gradual self-train accuracy (%): ", np.mean(final_graduals),
          mult * np.std(final_graduals) / np.sqrt(num_runs))
    print("Target self-train accuracy (%): ", np.mean(final_targets),
          mult * np.std(final_targets) / np.sqrt(num_runs))
    print("All self-train accuracy (%): ", np.mean(final_alls),
          mult * np.std(final_alls) / np.sqrt(num_runs))
    print("Best of Target self-train accuracies (%): ", np.mean(best_targets),
          mult * np.std(best_targets) / np.sqrt(num_runs))
    print("Best of All self-train accuracies (%): ", np.mean(best_alls),
          mult * np.std(best_alls) / np.sqrt(num_runs))

def rotated_mnist_60_conv_experiment():
    run_experiment(
        dataset_func=datasets.rotated_mnist_60_data_func, n_classes=10, input_shape=(28, 28, 1),
        save_file='saved_files/rot_mnist_60_conv.dat',
        model_func=models.simple_softmax_conv_model, interval=2000, epochs=10, loss='ce',
        soft=False, conf_q=0.1, num_runs=5)

def portraits_conv_experiment():
    run_experiment(
        dataset_func=datasets.portraits_data_func, n_classes=2, input_shape=(32, 32, 1),
        save_file='saved_files/portraits.dat',
        model_func=models.simple_softmax_conv_model, interval=2000, epochs=20, loss='ce',
        soft=False, conf_q=0.1, num_runs=5)

def gaussian_linear_experiment():
    d = 100
    run_experiment(
        dataset_func=lambda: datasets.gaussian_data_func(d), n_classes=2, input_shape=(d,),
        save_file='saved_files/gaussian.dat',
        model_func=models.linear_softmax_model, interval=500, epochs=100, loss='ce',
        soft=False, conf_q=0.1, num_runs=5)

# Ablations below.

def rotated_mnist_60_conv_experiment_noconf():
    run_experiment(
        dataset_func=datasets.rotated_mnist_60_data_func, n_classes=10, input_shape=(28, 28, 1),
        save_file='saved_files/rot_mnist_60_conv_noconf.dat',
        model_func=models.simple_softmax_conv_model, interval=2000, epochs=10, loss='ce',
        soft=False, conf_q=0.0, num_runs=5)

def portraits_conv_experiment_noconf():
    run_experiment(
        dataset_func=datasets.portraits_data_func, n_classes=2, input_shape=(32, 32, 1),
        save_file='saved_files/portraits_noconf.dat',
        model_func=models.simple_softmax_conv_model, interval=2000, epochs=20, loss='ce',
        soft=False, conf_q=0.0, num_runs=5)

def gaussian_linear_experiment_noconf():
    d = 100
    run_experiment(
        dataset_func=lambda: datasets.gaussian_data_func(d), n_classes=2, input_shape=(d,),
        save_file='saved_files/gaussian_noconf.dat',
        model_func=models.linear_softmax_model, interval=500, epochs=100, loss='ce',
        soft=False, conf_q=0.0, num_runs=5)

def portraits_64_conv_experiment():
    run_experiment(
        dataset_func=datasets.portraits_64_data_func, n_classes=2, input_shape=(64, 64, 1),
        save_file='saved_files/portraits_64.dat',
        model_func=models.simple_softmax_conv_model, interval=2000, epochs=20, loss='ce',
        soft=False, conf_q=0.1, num_runs=5)

def dialing_ratios_mnist_experiment():
    run_experiment(
        dataset_func=datasets.rotated_mnist_60_dialing_ratios_data_func,
        n_classes=10, input_shape=(28, 28, 1),
        save_file='saved_files/dialing_rot_mnist_60_conv.dat',
        model_func=models.simple_softmax_conv_model, interval=2000, epochs=10, loss='ce',
        soft=False, conf_q=0.1, num_runs=5)

def portraits_conv_experiment_more():
    run_experiment(
        dataset_func=datasets.portraits_data_func_more, n_classes=2, input_shape=(32, 32, 1),
        save_file='saved_files/portraits_more.dat',
        model_func=models.simple_softmax_conv_model, interval=2000, epochs=20, loss='ce',
        soft=False, conf_q=0.1, num_runs=5)

def rotated_mnist_60_conv_experiment_smaller_interval():
    run_experiment(
        dataset_func=datasets.rotated_mnist_60_data_func, n_classes=10, input_shape=(28, 28, 1),
        save_file='saved_files/rot_mnist_60_conv_smaller_interval.dat',
        model_func=models.simple_softmax_conv_model, interval=1000, epochs=10, loss='ce',
        soft=False, conf_q=0.1, num_runs=5, num_repeats=7)

def portraits_conv_experiment_smaller_interval():
    run_experiment(
        dataset_func=datasets.portraits_data_func, n_classes=2, input_shape=(32, 32, 1),
        save_file='saved_files/portraits_smaller_interval.dat',
        model_func=models.simple_softmax_conv_model, interval=1000, epochs=20, loss='ce',
        soft=False, conf_q=0.1, num_runs=5, num_repeats=7)

def gaussian_linear_experiment_smaller_interval():
    d = 100
    run_experiment(
        dataset_func=lambda: datasets.gaussian_data_func(d), n_classes=2, input_shape=(d,),
        save_file='saved_files/gaussian_smaller_interval.dat',
        model_func=models.linear_softmax_model, interval=250, epochs=100, loss='ce',
        soft=False, conf_q=0.1, num_runs=5, num_repeats=7)

def rotated_mnist_60_conv_experiment_more_epochs():
    run_experiment(
        dataset_func=datasets.rotated_mnist_60_data_func, n_classes=10, input_shape=(28, 28, 1),
        save_file='saved_files/rot_mnist_60_conv_more_epochs.dat',
        model_func=models.simple_softmax_conv_model, interval=2000, epochs=15, loss='ce',
        soft=False, conf_q=0.1, num_runs=5)

def portraits_conv_experiment_more_epochs():
    run_experiment(
        dataset_func=datasets.portraits_data_func, n_classes=2, input_shape=(32, 32, 1),
        save_file='saved_files/portraits_more_epochs.dat',
        model_func=models.simple_softmax_conv_model, interval=2000, epochs=30, loss='ce',
        soft=False, conf_q=0.1, num_runs=5)

def gaussian_linear_experiment_more_epochs():
    d = 100
    run_experiment(
        dataset_func=lambda: datasets.gaussian_data_func(d), n_classes=2, input_shape=(d,),
        save_file='saved_files/gaussian_more_epochs.dat',
        model_func=models.linear_softmax_model, interval=500, epochs=150, loss='ce',
        soft=False, conf_q=0.1, num_runs=5)

if __name__ == "__main__":
    # Main paper experiments.
    portraits_conv_experiment()
    print("Portraits conv experiment")
    experiment_results('saved_files/portraits.dat')
    rotated_mnist_60_conv_experiment()
    print("Rot MNIST conv experiment")
    experiment_results('saved_files/rot_mnist_60_conv.dat')
    gaussian_linear_experiment()
    print("Gaussian linear experiment")
    experiment_results('saved_files/gaussian.dat')
    print("Dialing MNIST ratios conv experiment")
    dialing_ratios_mnist_experiment()
    experiment_results('saved_files/dialing_rot_mnist_60_conv.dat')

    # Without confidence thresholding.
    portraits_conv_experiment_noconf()
    print("Portraits conv experiment no confidence thresholding")
    experiment_results('saved_files/portraits_noconf.dat')
    rotated_mnist_60_conv_experiment_noconf()
    print("Rot MNIST conv experiment no confidence thresholding")
    experiment_results('saved_files/rot_mnist_60_conv_noconf.dat')
    gaussian_linear_experiment_noconf()
    print("Gaussian linear experiment no confidence thresholding")
    experiment_results('saved_files/gaussian_noconf.dat')

    # Try predicting for next set of data points on portraits.
    portraits_conv_experiment_more()
    print("Portraits next datapoints conv experiment")
    experiment_results('saved_files/portraits_more.dat')

    # Try smaller window sizes.
    portraits_conv_experiment_smaller_interval()
    print("Portraits conv experiment smaller window")
    experiment_results('saved_files/portraits_smaller_interval.dat')
    rotated_mnist_60_conv_experiment_smaller_interval()
    print("Rot MNIST conv experiment smaller window")
    experiment_results('saved_files/rot_mnist_60_conv_smaller_interval.dat')
    gaussian_linear_experiment_smaller_interval()
    print("Gaussian linear experiment smaller window")
    experiment_results('saved_files/gaussian_smaller_interval.dat')

    # Try training more epochs.
    portraits_conv_experiment_more_epochs()
    print("Portraits conv experiment train longer")
    experiment_results('saved_files/portraits_more_epochs.dat')
    rotated_mnist_60_conv_experiment_more_epochs()
    print("Rot MNIST conv experiment train longer")
    experiment_results('saved_files/rot_mnist_60_conv_more_epochs.dat')
    gaussian_linear_experiment_more_epochs()
    print("Gaussian linear experiment train longer")
    experiment_results('saved_files/gaussian_more_epochs.dat')


from collections import defaultdict
from time import perf_counter

IN_FILE = "17/input.txt"

ROCK_COUNT = 1000000000000

BLOCKS = [
    # height, width, [list of tiles]
    [4, 1, [(0, 0), (1, 0), (2, 0), (3, 0)]],
    [3, 3, [(1, 0), (0, 1), (1, 1), (2, 1), (1, 2)]],
    [3, 3, [(0, 0), (1, 0), (2, 0), (2, 1), (2, 2)]],
    [1, 4, [(0, 0), (0, 1), (0, 2), (0, 3)]],
    [2, 2, [(0, 0), (0, 1), (1, 0), (1, 1)]],
]

def do_fall(well, highest, wind_pattern, wind_idx, i, old, rock_set, idx_dict):
    x = 2
    y = highest + 3
    block = BLOCKS[i % len(BLOCKS)]
    falling = True

    while falling:
        # get the current wind
        wind = wind_pattern[wind_idx]
        if wind == ">" and x + block[0] < 7:
            new_x = x + 1
        elif wind == "<" and x > 0:
            new_x = x - 1
        else:
            new_x = x

            # increment wind_idx
        wind_idx = (wind_idx + 1) % len(wind_pattern)

        # check if wind move can happen
        for tile in block[2]:
            if well[(tile[0] + new_x, tile[1] + y)]:
                new_x = x
                break

            # apply wind move, and check fall
        x = new_x
        new_y = y - 1

        # check if we're at the bottom
        if new_y < 0:
            falling = False
            break

            # check if any of the tiles are occupied
        for tile in block[2]:
            if well[(tile[0] + x, tile[1] + new_y)]:
                falling = False
                break
        if not falling:
            break

            # if neither, do the move and keep iterating
        y = new_y

    top = y + block[1]
    if top > highest:
        highest = top
    for tile in block[2]:
        well[(tile[0] + x, tile[1] + y)] = True

    # checking for cycles
    cycle_tuple = (None, None)

    # when at block 0
    if i % len(BLOCKS) == 0:
        # if this pair of block and wind_idx have appeared before, maybe a cycle?
        if wind_idx in rock_set:
            # return the length and height of the cycle
            cycle_tuple = (i - idx_dict[wind_idx][0], highest - idx_dict[wind_idx][1])
        else:
            # otherwise add to the cycle
            rock_set.add(wind_idx)

        # update the dictionary of indexes
        idx_dict[wind_idx] = (i, highest)
        old = highest
    return wind_idx, highest, old, cycle_tuple

if __name__ == "__main__":
    start_time = perf_counter()
    rock_set = set()
    idx_dict = {}

    well = defaultdict(lambda: False)
    highest = 0
    wind_pattern = []
    with open(IN_FILE) as f:
        wind_pattern = f.readline()

    wind_idx = 0
    old = 0
    i = -1  # hacky
    cycle_found = False
    cycle_tuple = (None, None)
    cycle_tuple_set = set()

    # find a cycle
    while not cycle_found:
        i += 1
        wind_idx, highest, old, cycle_tuple = do_fall(
            well, highest, wind_pattern, wind_idx, i, old, rock_set, idx_dict
        )
        if cycle_tuple[0]:
            # check if this cycle length and height have appeared before
            # if so, this is the real cycle
            if cycle_tuple in cycle_tuple_set:
                cycle_found = True
            cycle_tuple_set.add(cycle_tuple)

    print(f"Cycle found at iteration {i}")
    print(f"Height after first cycle is {highest}")
    print(f"cycle length is {cycle_tuple[0]}, increases height by {cycle_tuple[1]}")

    remaining = ROCK_COUNT - i
    full_cycles = int(remaining / cycle_tuple[0])
    extra_iter = remaining % cycle_tuple[0]
    height_post_full = highest + (full_cycles * cycle_tuple[1])
    print(f"After {full_cycles} more cycles, height {height_post_full}")

    extra_base_height = highest
    i += 1
    end = i + extra_iter
    for extra_i in range(i, end):
        wind_idx, highest, old, cycle_tuple = do_fall(
            well, highest, wind_pattern, wind_idx, extra_i, old, rock_set, idx_dict
        )

    print(f"{extra_iter} more rocks adds {highest-extra_base_height}")
    print(f"total: {height_post_full+(highest-extra_base_height-1)}")
    end_time = perf_counter()
    print(f"Execution time: {end_time-start_time:.3f}s")


import string
from functools import reduce
from time import time

start = time()

INPUT = open("./input_files/input_15", "r").read().strip("\n")

class Pair:
    DIGITS = string.digits + '-'

    def __init__(self, contruct):
        _s, _b = contruct.split(': ')
        self.sensor = tuple(int(''.join(y for y in x if y in self.DIGITS)) for x in _s.split(', '))
        self.beacon = tuple(int(''.join(y for y in x if y in self.DIGITS)) for x in _b.split(', '))
        self.distance = self.get_distance(self.sensor, self.beacon)

    def blocked_at_y(self, y):
        range_distance = self.distance - abs(self.sensor[1] - y)
        if range_distance < 0:
            return None
        return self.sensor[0] - range_distance, self.sensor[0] + range_distance

    @staticmethod
    def get_distance(sensor, beacon):
        s_x, s_y = sensor
        b_x, b_y = beacon
        return abs(s_x - b_x) + abs(s_y - b_y)

PAIRS = [Pair(x) for x in INPUT.split('\n')]

def join(ranges, range_x):
    if range_x is None:
        return ranges

    untouched = set(r for r in ranges if r[0] > range_x[1] or r[1] < range_x[0])

    if len(untouched) == len(ranges):
        untouched.add(range_x)
        return untouched

    touched = set(r for r in ranges if r not in untouched)
    touched.add(range_x)
    untouched.add((min(s for s, e in touched), max(e for s, e in touched)))
    return untouched

def run_1():
    y = 2000000
    blocked_space = sum(e - s + 1 for s, e in reduce(join, map(lambda p: p.blocked_at_y(y), PAIRS), set()))
    beacon_space = len(set(p.beacon[0] for p in PAIRS if p.beacon[1] == y))
    return blocked_space - beacon_space

def run_2():
    for y in range(0, 4000001):
        blocked = reduce(join, map(lambda p: p.blocked_at_y(y), PAIRS), set())
        if len(blocked) > 1:
            return (sorted(blocked, key=lambda i: i[0])[0][1] + 1) * 4000000 + y

print(run_1())
print((time() - start) * 10 ** 3)
print(run_2())
print((time() - start) * 10 ** 3)


import torch.nn as nn
from harl.utils.models_tools import init, get_active_func, get_init_method

"""MLP modules."""

class MLPLayer(nn.Module):
    def __init__(self, input_dim, hidden_sizes, initialization_method, activation_func):
        """Initialize the MLP layer.
        Args:
            input_dim: (int) input dimension.
            hidden_sizes: (list) list of hidden layer sizes.
            initialization_method: (str) initialization method.
            activation_func: (str) activation function.
        """
        super(MLPLayer, self).__init__()

        active_func = get_active_func(activation_func)
        init_method = get_init_method(initialization_method)
        gain = nn.init.calculate_gain(activation_func)

        def init_(m):
            return init(m, init_method, lambda x: nn.init.constant_(x, 0), gain=gain)

        layers = [
            init_(nn.Linear(input_dim, hidden_sizes[0])),
            active_func,
            nn.LayerNorm(hidden_sizes[0]),
        ]

        for i in range(1, len(hidden_sizes)):
            layers += [
                init_(nn.Linear(hidden_sizes[i - 1], hidden_sizes[i])),
                active_func,
                nn.LayerNorm(hidden_sizes[i]),
            ]

        self.fc = nn.Sequential(*layers)

    def forward(self, x):
        return self.fc(x)

class MLPBase(nn.Module):
    """A MLP base module."""

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

        self.use_feature_normalization = args["use_feature_normalization"]
        self.initialization_method = args["initialization_method"]
        self.activation_func = args["activation_func"]
        self.hidden_sizes = args["hidden_sizes"]

        obs_dim = obs_shape[0]

        if self.use_feature_normalization:
            self.feature_norm = nn.LayerNorm(obs_dim)

        self.mlp = MLPLayer(
            obs_dim, self.hidden_sizes, self.initialization_method, self.activation_func
        )

    def forward(self, x):
        if self.use_feature_normalization:
            x = self.feature_norm(x)

        x = self.mlp(x)

        return x


# !/usr/bin/python
# -*- coding: UTF-8 -*-
import os, subprocess, platform, io
import socket

from pyqrcode import QRCode

OS = platform.system()
"""方便将本地文件传输到手机端

日常工作中更多中地用于安卓、iOS多设备安装本地测试包。

前提
-- 1. 本地电脑上安装并配置了python开发环境
-- 2. 本地电脑开启代理，手机端配置了该代理IP

使用场景：

-- 1. 将该脚本下载到 .apk 或.ipa 文件 相同目录下
-- 2. 执行该.py   python file.py
-- 3. 手机扫描二维码即可访问   或者 直接在浏览器访问 本地IP:8000

"""

def get_host_ip():
    """
    查询本机ip地址
    :return: ip
    """
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('8.8.8.8', 80))
        ip = s.getsockname()[0]
    finally:
        s.close()
        return ip

def run_server():
    cmd2 = "python -m SimpleHTTPServer 8000"
    cwd = os.getcwd()
    tmp = subprocess.Popen(cmd2, cwd=cwd)
    tmp.wait()

def get_QR(picDir=None):
    picDir = picDir or 'QR.png'
    qr_storage = io.BytesIO()
    ip = get_host_ip()
    ip_address = ip + ":8000"
    qr_code = QRCode(ip_address)
    qr_code.png(qr_storage, scale=10)
    with open(picDir, 'wb') as f:
        f.write(qr_storage.getvalue())
        print_qr(picDir)

def print_qr(fileDir):
    if OS == 'Darwin':
        subprocess.call(['open', fileDir])
    elif OS == 'Linux':
        subprocess.call(['xdg-open', fileDir])
    else:
        os.startfile(fileDir)

def env():
    count = 3
    while count:
        try:
            import pyqrcode
            break
        except:
            os.system("pip install pyqrcode")
            count -= 1
            continue

if __name__ == '__main__':
    env()
    run_server()
    get_QR()


import os
import argparse

from BasicTools.parse_file import file2dict
from BasicTools import plot_tools

def plot_loc_log(log_path, file_name, fig_path):

    logger = file2dict(log_path, numeric=True)

    file_paths = list(logger.keys())
    value = None
    for file_path in file_paths:
        if os.path.basename(file_path).find(file_name) > -1:
            value = logger[file_path]

    if value is not None:
        fig, ax = plot_tools.subplots(1, 1)
        plot_tools.plot_matrix(value.T, ax=ax, fig=fig)
        fig.savefig(fig_path)
    else:
        print(f'{file_name} not found')

def parse_args():
    parser = argparse.ArgumentParser(description='parse argments')
    parser.add_argument('--log_path', type=str, required=True)
    parser.add_argument('--file_name', type=str, required=True)
    parser.add_argument('--fig_path', type=str, required=True)
    args = parser.parse_args()
    return args

if __name__ == '__main__':
    args = parse_args()

    plot_loc_log(args.log_path, args.file_name, args.fig_path)


import os
import sys
import pandas as pd
import warnings

warnings.simplefilter(action='ignore', category=FutureWarning)

os.chdir(os.path.dirname(sys.argv[0]))

def merge():
    # Load the outputs of the inventory
    df_items = pd.read_csv('outputs/MHS2_output_items.csv')
    df_weapons = pd.read_csv('outputs/MHS2_output_weapons.csv')
    df_armor = pd.read_csv('outputs/MHS2_output_armor.csv')
    df_talismans = pd.read_csv('outputs/MHS2_output_talismans.csv')
    df_general = pd.DataFrame(data={'Name':0,'Quantity':0,'Level':0,'Category':0,'Subcategory':0},index=(0,1))

    # Fill in the items
    for i in range(len(df_items)):
        s = {'Name':df_items.iloc[i,1],'Quantity':df_items.iloc[i,2],'Level':0,'Category':df_items.iloc[i,3],'Subcategory':df_items.iloc[i,4]}
        df_general = df_general.append(s,ignore_index=True)

    # Fill in the weapons
    for i in range(len(df_weapons)):
        s = {'Name':df_weapons.iloc[i,2],'Quantity':df_weapons.iloc[i,4],'Level':df_weapons.iloc[i,3],'Category':'Weapons','Subcategory':df_weapons.iloc[i,6]}
        df_general = df_general.append(s,ignore_index=True)

    # Fill in the armor
    for i in range(len(df_armor)):
        s = {'Name':df_armor.iloc[i,1],'Quantity':df_armor.iloc[i,3],'Level':df_armor.iloc[i,2],'Category':'Armor','Subcategory':'Armor'}
        df_general = df_general.append(s,ignore_index=True)

    # Fill in the talismans
    for i in range(len(df_talismans)):
        s = {'Name':df_talismans.iloc[i,3],'Quantity':df_talismans.iloc[i,4],'Level':0,'Category':'Talismans','Subcategory':df_talismans.iloc[i,7]}
        df_general = df_general.append(s,ignore_index=True)

    # Clean and output the data
    df_general = df_general.groupby(df_general['Name']).aggregate({'Quantity':'sum','Level':'max','Category':'first','Subcategory':'first'})
    df_general.to_csv(r'outputs/MHS2_output.csv',encoding='utf-8')


import sys
sys.stdin = open('input.txt')

input = sys.stdin.readline

numbers = list(map(int, input().split()))
L = 8

result = ""
if numbers[0] == 1 and numbers[L - 1] == 8:
    l = 0
    is_ascending = True
    while l < L - 1:
        if numbers[l] + 1 == numbers[l + 1]:
            l += 1
        else:
            is_ascending = False
            result = 'mixed'
            break

    if is_ascending: result = "ascending"

elif numbers[0] == 8 and numbers[L - 1] == 1:
    l = 0
    is_descending = True
    while l < L - 1:
        if numbers[l] - 1 == numbers[l + 1]:
            l += 1
        else:
            is_descending = False
            result = 'mixed'
            break

    if is_descending: result = "descending"
else:
    result = 'mixed'

print(result)


#!/usr/bin/env python3
import sys

def escape(char):
    c = ord(char)
    if c <= 0xff:
        return r'\x%02x' % c
    else:
        if c <= 0xffff:
            return r'\u%04x' % c
        else:
            return r'\U%08x' % c

def convert(stream):
    for line in stream:
        print(''.join(map(escape, line)), end='')

errors = 0

if len(sys.argv) == 1:
    try:
        convert(sys.stdin)
    except IOError as e:
        print(e.strerror, file=sys.stderr)
        errors += 1
else:
    for file in sys.argv[1:]:
        try:
            with open(file) as input:
                convert(input)
        except IOError as e:
            print(e.filename+':', e.strerror, file=sys.stderr)
            errors += 1

if errors > 0:
    sys.exit(1)


#!/usr/bin/env python
import sys
import socket
import dns.resolver
import re

email_count = len(sys.argv)

for i in range(1, email_count):
    email = sys.argv[i]
    if not re.match(r"^[A-Za-z0-9\.\+_-]+@[A-Za-z0-9\._-]+\.[a-zA-Z]*$", email):
        print(email, "is not valid e-mail.")
        continue

    print(email, "is valid e-mail.")
    domain = email.rsplit('@', 1)[-1]
    for x in dns.resolver.query(domain, 'MX'):

        host_name = str(x.exchange)
        host = socket.gethostbyname(host_name)
        port = 25
        address = (host, port)
        print("\nHost:", host_name, "IP:", host)

        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.connect(address)
            msg = s.recv(1024)
            s.close()

        print("--begin of server output--\n")
        print(msg.decode('ascii'))
        print("--end of server output--\n")


import requests, json
import from_tab

# used when you don't need to caculate the gender of debaters (calculate aff bias or how often a judge agrees with the majority) and want to concerve API calls
USE_API = True

# if the API returns a certinnty level (how likely the given first name belongs to the gender it predicts) below this value then the function will dismiss the entire round it is working on
SERTAINTY_THREASHOLD = 0.7

# The MIT License (MIT)
# Copyright (c) 2013 block8437/acceptable-security
# https://github.com/acceptable-security/gender.py
def getGenders(names):
	print("api call")
	url = ""
	cnt = 0
	if not isinstance(names,list):
		names = [names,]

	for name in names:
		if url == "":
			url = "name[0]=" + name
		else:
			cnt += 1
			url = url + "&name[" + str(cnt) + "]=" + name

	req = requests.get("https://api.genderize.io?" + url)
	results = json.loads(req.text)

	retrn = []
	for result in results:
		print(result)
		if result == 'error':
			print('max api calls reached')
			retrn.append((u'None',u'0.0',0.0))

		elif result["gender"] is not None:
			retrn.append((result["gender"], result["probability"], result["count"]))
		else:
			retrn.append((u'None',u'0.0',0.0))
	return retrn

# Example usage
# print(getGenderBalance(['Aimen', 'Harini', 'Felix', 'Ethan'], 'Neg'))
# [('male', 0.95, 1007), ('female', 0.94, 2752), ('female', 0.96, 1251), ('male', 0.99, 6598)

# Round score table
#MM vs MM and FF vs FF and F? vs MM... are thrown out (0)
#if FF win over FM then +.5	if MM win over FM then -.5
#if FF win over MM then +1	if MM win over FF then -1

# given the url to the TABROOM page for a specifc debate team, scrape the names of competitors, run the names through the gender API then caculate a round score
def vote_for_more_woman(aff_url, neg_url, vote):

	#if statment to account for test files
	if isinstance(aff_url, list):
		print('is list    vote is"'+vote+'"')
		print('\n\n         gender ballance is ', getGenderBalance(aff_url + neg_url, vote))
		return getGenderBalance(aff_url + neg_url, vote)

	else:
		print('not list')
		aff_names = from_tab.getCompetitors(aff_url)
		neg_names = from_tab.getCompetitors(neg_url)
		if USE_API:
			return getGenderBalance(getGenders(aff_names+neg_names), vote)
		else: return 100

def getGenderBalance(genders_of_names=list(), vote=None):
	print('gender of names is', genders_of_names)
	number_of_debators = len(genders_of_names)

	#put winning team first and remove rounds that don't end in normal ballot
	if "Neg" in vote or 'Con' in vote:
		count_step=-1
		count_start = number_of_debators
		count_end = 0
		print("neg win")
	elif 'Aff' in vote or 'Pro' in vote:
		count_step=1
		count_start = -1
		count_end = number_of_debators-1
		print("aff win")
	else:
		print('else case triggered')
		return 0

	print(number_of_debators)

	# removes names that are not clearly femine or masculine
	for i in genders_of_names:
		if float(i[1])<SERTAINTY_THREASHOLD:
			print(i, "doesn't meet the sertainty threashold")
			return 0
	print('finished unsertanty filter\n\n')
	# handles Lincon Douglas Debate, Big Questions, etc.
	print(count_start)
	print('gender of names ', genders_of_names[count_start])
	if number_of_debators == 2 :
		if genders_of_names[count_start][0] == 'male':
			return -1
		else:
			return 1
	#handle policy, pofo, etc.
	elif number_of_debators == 4:
		counter = count_start
		gender_list = list()
		while counter != count_end:
			counter += count_step
			if genders_of_names[counter][0] == 'male':
				gender_list.append(-1)
			else:
				gender_list.append(1)
		print(gender_list)
		print((gender_list[0]+gender_list[1]-gender_list[2]-gender_list[3])/4)
		return (gender_list[0]+gender_list[1]-gender_list[2]-gender_list[3])/4 #this won't make any sence until you write out all the possibilites
	else: #debate forms with any other number of debaters get ignored
		print('reached a round with a number of participants not equal to 2 or 4')
		return 0


'''
Just like the balloon with multiple ribbons, if we change the attribute of an object
through one reference variable, it immediately reflects in other reference variable as
there is only one balloon ultimately!
'''

class Mobile:
    def __init__(self, price, brand):
        self.price = price
        self.brand = brand

mob1=Mobile(1000, "Apple")
print("Price of mobile 1 :", mob1.price)

mob2=mob1
mob2.price=3000

print("Price of mobile 1 :", mob1.price)
print("Price of mobile 2 :", mob2.price)


import re

f = open('test.txt', 'r').read()  # We open the file here

pattern = re.compile(
    "[a-zA-Z0-9]+[\.!\?]+[a-zA-Z0-9]+")  # Here we create a pattern for a later check statement
# if the writer of the story made a mistake
# and didn't leave a blank space after a "."
f = f.split()  # we split the txt file into a string list ( the split happens whenever we meet a space)
list_outside = []  # we create the outside list that contains inside a list of sentences
list_inside = []  # this is the inside list that contains all the words inside a list

for x in f:  # here we create a loop so we can check every word in the text

    if x.__contains__(".") or x.__contains__("!") or x.__contains__("?"):  # if statement to check if the word is the
        # last one of the sentence ( that's why we check for the "." , "!" , "?" symbols

        if pattern.match(x):  # if the word matches the pattern that we gave above.

            x = re.sub('[.!?]', ' ', x)  # we replace every "." "!" "?" symbol with a blank space
            x = re.sub('[\'\[\],:;)(\-]', '', x)  # we delete every symbol ( the ones that are included
            # in the regex) from the word
            x = x.split()  # here we split the two words based on the blank space that we created earlier
            list_inside.append(x[0])  # we first put the first word from the split function and insert it to our list
            list_outside.append(list_inside)  # we append the list_inside to the list_outside

            list_inside = []  # we empty the list inside so that we can append the next sentence
            x = re.sub('[\'\[\],:;)(\-]', '', x[-1])  # we take the second word ( and last word ) of the split
            # and we delete every symbol that the word has.
            list_inside.append(x)  # we take the x that we modified from above and we put it as a starter to our list.

        else:  # if the word doesnt match the pattern.
            x = re.sub('[.!?]', '', x)  # we delete every "." , "!" , or "?" that exists as a symbol inside the word
            x = re.sub('[\'\[\],:;)(\-]', '', x)  # we delete every symbol ( the ones that are included
            # in the regex) from the word
            list_inside.append(x)  # we append the inside list with x
            list_outside.append(list_inside)  # we append list_inside to the list_outside

            list_inside = []  # we empty the list inside so that we can append the next sentence

    else:
        x = re.sub('[\'\[\],:;)(\-]', '', x)  # if the word is not the last word of the
        # sentence then we delete every symbol that is inside that word

        list_inside.append(x)  # we append the word to the list inside

print(list_outside)  # we print the final list that is the list outside


import pytest

from baserow.contrib.database.table.handler import TableHandler
from baserow.contrib.database.views.models import SORT_ORDER_DESC
from baserow.contrib.integrations.local_baserow.models import (
    LocalBaserowTableServiceFilter,
    LocalBaserowTableServiceSort,
)

@pytest.mark.django_db
def test_local_baserow_table_service_refinement_manager(data_fixture):
    user = data_fixture.create_user()
    builder = data_fixture.create_builder_application(user=user)
    database = data_fixture.create_database_application(workspace=builder.workspace)
    integration = data_fixture.create_local_baserow_integration(
        application=builder, user=user
    )
    table = TableHandler().create_table_and_fields(
        user=user,
        database=database,
        name=data_fixture.fake.name(),
        fields=[
            ("Ingredient", "text", {}),
            ("Cost", "number", {}),
        ],
    )

    service = data_fixture.create_local_baserow_list_rows_service(
        table=table, integration=integration
    )

    cost = table.field_set.get(name="Cost")
    ingredient = table.field_set.get(name="Ingredient")

    data_fixture.create_local_baserow_table_service_filter(
        service=service, field=cost, value="25", order=0
    )
    data_fixture.create_local_baserow_table_service_filter(
        service=service, field=ingredient, value="Cheese", order=1
    )

    data_fixture.create_local_baserow_table_service_sort(
        service=service, field=cost, order_by=SORT_ORDER_DESC, order=0
    )
    data_fixture.create_local_baserow_table_service_sort(
        service=service, field=ingredient, order_by=SORT_ORDER_DESC, order=1
    )

    ingredient.trashed = True
    ingredient.save()

    assert LocalBaserowTableServiceFilter.objects.filter(service=service).count() == 1
    assert (
        LocalBaserowTableServiceFilter.objects_and_trash.filter(service=service).count()
        == 2
    )

    assert LocalBaserowTableServiceSort.objects.filter(service=service).count() == 1
    assert (
        LocalBaserowTableServiceSort.objects_and_trash.filter(service=service).count()
        == 2
    )


from myTUI import Form, Edit, Text, cls
import sys
from time import sleep, time,strftime,gmtime
import serial
from serial.tools.list_ports import comports
from datetime import datetime

cls()
#HELP KEYS FORM##############################################
  #KEYS
def HelpForm():
  HotKeys = [  '1..9 - select port',
        's - rescan ports',
        '------------------',
        'v - set voltage',
        'i - set current',
        'o - set I cut off',
        '------------------',
        'r - Run KORAD',
        't - Stop KORAD',
        '------------------',
        'q - exit',
        ]
  h = Form('Hot Keys',80,2,28,len(HotKeys)+4)
  t_Keys = []
  for n in range(0, len(HotKeys)):
    t_Keys.append(Text(HotKeys[n],h.x+3,h.y+n+2))

#PORT GENERATOR FORM ##############################################
  #check for different ports and fill up
def ScanPorts():
  ports = []
  for n, (port, desc, hwid) in enumerate(sorted(comports()), 1):
      ports.append(port)
  #From za izpis availabele ports
  Form_ports = Form('Serial Ports',3,2 ,28,len(ports)+9)
  global e
  e = []
  for n in range(0, len(ports)):
    e.append(Edit('(' + str(n+1) + ')', Form_ports.x+3 ,Form_ports.y + n + 5))
    e[n].new_value(ports[n])

  global Set_port
  Set_port = Edit('Port', Form_ports.x+3 ,Form_ports.y + 2)
  Set_port.new_value(e[0].value)

def KoradOutpuForm():
#KORAD OUTPUT FORM ##############################################
  f_k = Form('Korad OUTPUT', 35, 2, 40, 9)
  global Vout
  global Iout
  global Charge
  global Time_r
  global Power
  global eEng
  Vout = Edit('Vout [V]', f_k.x + 3, f_k.y +2)
  Vout.enabled  = False
  #Vout.new_value('00.00')

  Iout = Edit('Iout [A]', f_k.x + 3, f_k.y +3)
  Iout.enabled  = False
  #Iout.new_value('0.000')

  #On time_r [h:m:s] =
  Time_r = Edit('Time', Vout.x+20, Vout.y)
  Time_r.enabled = False

  Power =  Edit('Power [W]', f_k.x+3, f_k.y+4)
  Power.enabled = False
  Power.value = '0.0'
  eEng =   Edit('Energy [Wh]', f_k.x+3, f_k.y+5)
  eEng.enabled = False
  eEng.value = '0.0'
  Charge = Edit('Charge [mAh]', f_k.x+3, f_k.y+6)
  Charge.enabled = False
  Charge.value = '0.0'

def KoradSettingsForm():
#KORAD settings FORM ##############################################
  f_s = Form('Korad SETUP', 35, 11, 40, 6)
  global Vset
  global Iset
  global Ioff
  Vset = Edit('Vset [V]', f_s.x + 3, f_s.y +2)
  Vset.new_value('04.30')

  Iset = Edit('Iset [A]', f_s.x + 3, f_s.y +3)
  Iset.new_value('0.900')

  Ioff = Edit('Ioff [A]', f_s.x + 3, f_s.y +4)
  Ioff.new_value('0.010')

def Run():
  #--- clear file data ---
  now = datetime.now()
  dt_str = now.strftime("%Y%m%d-%H%M%S")
  dataFile = open("./"+dt_str+"-TUI.csv", "w")
  dataFile.write("Time [h:m:sr], Voltage [V], Current [A]\n")
  ser = serial.Serial(Set_port.value)
  ser.write(('VSET1:'+Vset.value).encode('utf-8'))
  sleep(0.1)
  ser.write(('ISET1:'+Iset.value).encode('utf-8'))
  sleep(0.1)
  ser.write(('OUT1').encode('utf-8'))
  sleep(0.1)
  Charge_out = 0.0
  eEng_out = 0.0
  Start_time = time()
  while True:
    Time_r.new_value(strftime('%H:%M:%S',gmtime(time()-Start_time)))
    ser.write(('VOUT1?').encode('utf-8'))
    text = ser.read(5)
    Vout.new_value(text.decode('utf-8'))
    ser.write(('IOUT1?').encode('utf-8'))
    text = ser.read(5)
    Iout.new_value(text.decode('utf-8'))
    #------- DATA ----------------------------
    Power.new_value('{:.2f}'.format(float(Vout.value)*float(Iout.value)))
    eEng_out += float(Power.value) /3600
    eEng.new_value('{:.2f}'.format(eEng_out))
    Charge_out += float(Iout.value)*1000/60/60
    Charge.new_value('{:.2f}'.format(Charge_out,))
    #------- FILE ----------------------------
    dataFile = open("./data.csv", "a")
    dataFile.write(Time_r.value + ", " + Vout.value + ", " + Iout.value + "\n")
    dataFile.close()
    #------- STOP ----------------------------
    if float(Iout.value)< float(Ioff.value):
      ser.write(('OUT0').encode('utf-8'))
      break

    sleep(1)

def SetVoltage():
  Vset.new_value('')
  key = input('')
  Vset.new_value(key)
  if float(key) > 30:
    Vset.new_value('00.00')

def SetCurrent():
  Iset.new_value('')
  key = input('')
  Iset.new_value(key)
  if float(key) > 5.0:
    Iset.new_value('5.000')
  elif float(key) < 0.001:
    Ioff.new_value('0.001')

def SetCutOff():
  Ioff.new_value('')
  key = input('')
  Ioff.new_value(key)
  if float(key) > 5.0:
    Ioff.new_value('5.000')
  elif float(key) < 0.001:
    Ioff.new_value('0.001')

# MAIN PROGRAM ##############################################
HelpForm()
ScanPorts()
KoradSettingsForm()
KoradOutpuForm()

cmd = Edit('Cmd',2,20)
cmd.value = ''
while (cmd.value != 'q'):
  cmd.new_value('')
  key = input('')
  cmd.new_value(key)
  #preveri tipko in naredikar je treba.
  if key == 'r':
    Run()
  elif key == '1':
    Set_port.new_value(e[0].value)
  elif key == '2':
    Set_port.new_value(e[1].value)
  elif key == '3':
    Set_port.new_value(e[2].value)
  elif key == '4':
    Set_port.new_value(e[3].value)
  elif key == '5':
    Set_port.new_value(e[4].value)
  elif key == 'v':
    SetVoltage()
  elif key == 'i':
    SetCurrent()
  elif key == 'o':
    SetCutOff()
  elif key == 's':
    ScanPorts()

cls()
#g = Form('Test-2', f.x+f.dx , f.y , 28, 6)

#e = Edit('Vout', f.x+2, f.y+3)
#e.new_value('Hoj!')

#t = Text('V', e.x + len(e.value) + len(e.text)+2, e.y)