import json
import datetime
import re
import telebot
from dictionary import language
from authentication import is_login
from config import db, bot
from keyboards import *
from xml_parser import add_new_order, ParseCS, get_Nomenclature, ParseDoubleCS

class Keybord(object):
    list_keyboard = []
    value = {}

class KeybordUZ(object):
    list_keyboard = []
    value = {}

def get_orderHistory(mes,user,lang="ru"):
    try:
        dateFrom = mes.text.split("-")[0].split(".")
        dateTo = mes.text.split("-")[1].split(".")
        dateFromTS= int(datetime.datetime.timestamp(datetime.datetime(int(dateFrom[2]),
                                                                      int(dateFrom[1]),
                                                                      int(dateFrom[0]))))
        dateToTS = int(datetime.datetime.timestamp(datetime.datetime(int(dateTo[2]),
                                                                     int(dateTo[1]),
                                                                     int(dateTo[0]),23,59,59)))
        order = db.order_history.find({"code_partner":user['code'],"date_timestamp":{"$gte": dateFromTS, "$lt": dateToTS}})
        if order.count() == 0:
            bot.send_message(mes.chat.id, text=language[lang]['Нет заказов'])
            return
        list_order = f"{language[lang]['История заказов']}:\n"
        for post in order:

            list_order += f'{datetime.datetime.fromtimestamp(post["date_timestamp"]).strftime("%Y-%m-%d %H:%M:%S")}\n'
            for items in post['order']:
                list_order += f'{items["name"]}-{items["amount"]}\n'
        bot.send_message(mes.chat.id, text=list_order)
        return
    except:
        bot.send_message(mes.chat.id, text=language[lang]['Повторите запрос'])
        return

def orderHistory(message):
    if message.text == "Назад в главное меню":
        bot.send_message(message.chat.id, text=message.text, reply_markup=keyboardStartRU)
        return

    user = db.users.find_one({"name":message.text})
    if user:
        mes = bot.send_message(message.chat.id, text='Введите временной период ДД.ММ.ГГГГ-ДД.ММ.ГГГГ\n'
                                               'Например: 01.01.2021-01.02.2021')
        bot.register_next_step_handler(mes, get_orderHistory,user)

    bot.register_next_step_handler(message,orderHistory)

def get_text(list_lens,find,lang = "ru"):
    if find == 0:
        return f'{language[lang]["На складе нет таких линз"]}\n'
    else:
        if find == -1:
            return f'{language[lang]["Cклад обновляется, проведите запрос чуть позже"]}\n'
        else:
            if list_lens:
                text = ""
                for post in list_lens:
                    text = text + post+"\n"
                return text
    return

def get_KeyboardShoppingCart(current_user,lang = "ru"):
    shopping_cart = db.users.find_one({"name": current_user['user']})['shopping cart']
    if not shopping_cart:
        return
    keyboardSC = telebot.types.ReplyKeyboardMarkup(True)
    for index in range(len(shopping_cart)):
        keyboardSC.row(f'{index+1}. {shopping_cart[index]["name"]}')
    keyboardSC.row(language[lang]['Очистить все'])
    keyboardSC.row(language[lang]['Вернуться в корзину'])
    return keyboardSC

def delete_item(item:str,current_user):
    try:
        shopping_cart = db.users.find_one({"name": current_user['user']})['shopping cart']
        del_item = shopping_cart[int(item[:item.find('.')])-1]
        if del_item['name'] == item[item.find('.')+2:]:
            amount = del_item['amount'] - 1
            if amount == 0:
                db.users.update_one({"name": current_user['user']},
                                   {"$pull":{'shopping cart':{"Code":del_item['Code']}}})

            else:
                db.users.update_one({"name": current_user['user'], "shopping cart.Code": del_item['Code']},
                                    {"$set": {"shopping cart.$.amount": amount}})
            return 1
        return 0
    except:
        return 0

def get_shopping_cart(current_user,lang = "ru"):
    s_cart = db.users.find_one({"name": current_user['user']})
    if len(s_cart['shopping cart']) == 0:
        return language[lang]['Корзина пуста']
    if lang == "ru":
        offer = f"Заказчик {current_user['user']} \nВ корзине \n"
    else:
        offer = f"Буюртмачи {current_user['user']} \nСаватда жами \n"
    shopping_cart = s_cart['shopping cart']
    for index in range(len(shopping_cart)):
        offer += f"{index+1}. {shopping_cart[index]['name']} {language[lang]['количество']}: {shopping_cart[index]['amount']} \n"
    return offer

def add_offer(message,lang="ru"):
    if message.text == "Назад в главное меню":
        bot.send_message(message.chat.id, text=message.text, reply_markup=keyboardStartRU)
        return
    if message.text == "Бош менюга қайтиш":
        bot.send_message(message.chat.id, text=message.text, reply_markup=keyboardStartUZ)
        return

    current_user = is_login(message.chat.id)

    if message.text == "Убрать товары из корзины" or message.text =="Маҳсулотни саватдан олиб ташлаш":
        KeyboardShoppingCart = get_KeyboardShoppingCart(current_user,lang)
        bot.send_message(message.chat.id, text=language[lang]['Какой товар убрать из корзины?'], reply_markup=KeyboardShoppingCart)

    if message.text == "Оформить заказ" or message.text == "Буюртмани расмийлаштириш":
        if current_user:
            shopping_cart = db.users.find_one({"name":current_user['user']})['shopping cart']
            order = {"user":current_user['user'],
                    "order":shopping_cart,
                    "code_partner":current_user['code'],
                    "date":datetime.datetime.now().strftime('%H:%M - %d.%m.%Y'),
                    'date_timestamp': int((datetime.datetime.now()+datetime.timedelta(hours=5)).timestamp())}
            db.order_history.insert_one(order)
            db.users.update_one({"name": current_user['user']},
                                 {"$set": {"shopping cart": []}})
            add_new_order(order)
            moderator = db.subscribers.find_one({"user_name":"FaustGet"})
            if moderator:
                user_order = ""
                for item in shopping_cart:
                    user_order += f'{item.get("name")} - {item.get("amount")}\n '
                moderator_text = f'{current_user["user"]} оформили заказ \n{user_order}'
                bot.send_message(moderator['id_user'], text=moderator_text)
            if lang == "ru":
                bot.send_message(message.chat.id, text="Заказ оформлен", reply_markup=keyboardStartRU)
            else:
                bot.send_message(message.chat.id, text="Буюртма расмийлаштирилди", reply_markup=keyboardStartUZ)
        return

    if message.text == "Вернуться в корзину" or message.text == "Саватга қайтиш":
        offer = get_shopping_cart(current_user)
        if lang == "ru":
            bot.send_message(message.chat.id, offer,reply_markup=keyboardOfferRU)
        else:
            bot.send_message(message.chat.id, offer, reply_markup=keyboardOfferUZ)
        if offer == 'Корзина пуста' or offer == 'Сават бўш':
            return

    if message.text == "Очистить все" or message.text == 'Ҳаммасини тозалаш':
        if current_user:
            db.users.update_one({"name": current_user['user']},
                            {"$set": {"shopping cart": []}})
        if lang == "ru":
            bot.send_message(message.chat.id, "Корзина отчищена", reply_markup=keyboardStartRU)
        else:
            bot.send_message(message.chat.id, "Сават бўш", reply_markup=keyboardStartUZ)

        return

    message_text = check_lens(message,lang)
    if message_text:
        bot.send_message(message.chat.id, text=message_text,parse_mode="Markdown")

    if delete_item(message.text,current_user) == 1:
        bot.send_message(message.chat.id, text=language[lang]['Товар был удален из корзины'])
        offer = get_shopping_cart(current_user,lang)
        if offer == 'Корзина пуста':
            bot.send_message(message.chat.id, offer, reply_markup=keyboardStartRU)
            return
        if offer == 'Сават бўш':
            bot.send_message(message.chat.id, offer, reply_markup=keyboardStartUZ)
            return
        if lang =="ru":
            bot.send_message(message.chat.id, offer, reply_markup=keyboardOfferRU)
        else:
            bot.send_message(message.chat.id,  offer, reply_markup=keyboardOfferUZ)
        KeyboardShoppingCart = get_KeyboardShoppingCart(current_user,lang)
        bot.send_message(message.chat.id, text=language[lang]['Какой товар убрать из корзины?'], reply_markup=KeyboardShoppingCart)
    bot.register_next_step_handler(message,add_offer,lang)

def get_stock_availability(message,lang = "ru",keyb = None,list_keyb ={}):

    if keyb == None:
        keyb = telebot.types.ReplyKeyboardMarkup(True)
    try:
        message_text = f"{language[lang]['На складе были найдены следующие линзы']}:\n"
        message.text = message.text.replace("-0.00", "+0.00")
        message.text = message.text.replace("-0,00", "+0.00")
        message.text = message.text.replace(" 0,00", " +0.00")
        message.text = message.text.replace(" 0.00", " +0.00")
        if message.text[0:4] in ["0.00","0,00"]:
            message.text = "+0.00" + message.text[4:]
        if message.text[0:1] == "0":
            message.text = "+0.00" + message.text[1:]

        if " 0" in message.text:
            message.text = message.text.replace(" 0", " +0.00")
        if message.text == "0" or message.text == "0.00" or message.text == "0,00":
            message.text = "+0.00"

        if re.match('^[+-]\d[,.]\d\d? [+-]\d[,.]\d\d?$',message.text):
            text = message.text.replace(",", ".")
            value = text.split()
            keyb = telebot.types.ReplyKeyboardMarkup(True)
            list_lens, find, keyb,list_keyb = ParseCS(value[0], value[1],keyb,lang)
            message_text += get_text(list_lens, find)

            keyb.row(language[lang]['Назад в главное меню'])

        if re.match('^[+-]\d[,.]\d\d?$',message.text):
            text = message.text.replace(",", ".")
            value = text.split()
            keyb = telebot.types.ReplyKeyboardMarkup(True)
            list_lens, find, keyb,list_keyb = ParseCS(value[0], "+0.00",keyb,lang)
            message_text += get_text(list_lens, find)
            keyb.row(language[lang]['Назад в главное меню'])

        if re.match('[+-]\d[,.]\d\d? [+-]\d[,.]\d\d? [+-]\d[,.]\d\d?$', message.text):
            text = message.text.replace(",", ".")
            value = text.split()
            keyb = telebot.types.ReplyKeyboardMarkup(True)
            list_lens, find, keyb,list_keyb = ParseDoubleCS(value[0], value[1], value[2], "+0.00", keyb,lang)
            message_text +=  get_text(list_lens, find)
            keyb.row(language[lang]['Назад в главное меню'])

        if re.match('[+-]\d[,.]\d\d? [+-]\d[,.]\d\d? [+-]\d[,.]\d\d? [+-]\d[,.]\d\d?$', message.text):
            text = message.text.replace(",", ".")
            value = text.split()
            keyb = telebot.types.ReplyKeyboardMarkup(True)
            list_lens, find, keyb,list_keyb = ParseDoubleCS(value[0], value[1], value[2], value[3], keyb,lang)

            message_text +=  get_text(list_lens, find)
            keyb.row(language[lang]['Назад в главное меню'])

        if message.text == "Назад в главное меню":
            bot.send_message(message.chat.id, text=message.text, reply_markup=keyboardStartRU)
            return

        if message.text == "Бош менюга қайтиш":
            bot.send_message(message.chat.id, text=message.text, reply_markup=keyboardStartUZ)
            return

        list_nomenclature_info = get_Nomenclature(message.text,list_keyb)
        list_nomenclature_info=sorted(list_nomenclature_info,key=lambda x:x['Amount'])
        message_text_order = ""
        flag_amount = True

        for nomenclature_info in list_nomenclature_info:
            current_user = is_login(message.from_user.id)
            if current_user:
                partners = db.users.find_one({"name":current_user['user']})
                flag = False

                for post in partners['shopping cart']:
                    if post.get('Code') == nomenclature_info.get('Code') and flag_amount:
                        if int(nomenclature_info.get("Amount")) >= int(post.get('amount') + 1):
                            db.users.update_one({"name":current_user['user'], "shopping cart.Code":nomenclature_info.get("Code")},
                                                {"$set":{"shopping cart.$.amount":post.get('amount') + 1}})
                            flag = True
                            message_text_order += f"{language[lang]['В корзину были добавлены']}:\n{nomenclature_info.get('name')}\n" \
                                                  f"{language[lang]['Всего в корзине']}: {post.get('amount') + 1}\n "

                        else:
                            flag = True
                            flag_amount = False
                            message_text_order = language[lang]['В корзине максимальное количество линз данной модели']
                if not flag and flag_amount:
                    items = {"name": nomenclature_info.get("name"),
                             "Code": nomenclature_info.get('Code'),
                             "amount":1}
                    db.users.update_one({"name": current_user['user']},
                                        {"$push": {"shopping cart": items}})
                    message_text_order += f"{language[lang]['В корзину были добавлены']}:\n{nomenclature_info.get('name')}\n" \
                                          f"{language[lang]['Всего в корзине']}: 1\n"

            else:
                message_text_order = language[lang]['Вы не авторизованны']
        if message_text_order !="":
            message_text = message_text_order
        if message_text == f"{language[lang]['На складе были найдены следующие линзы']}:\n":
            message_text = language[lang]["Введен неправильный формат данных"]

        mes = bot.send_message(message.chat.id,message_text, reply_markup=keyb,parse_mode="Markdown")
        bot.register_next_step_handler(mes,get_stock_availability,lang,keyb,list_keyb)
    except:

        message_text = language[lang]["Введен неправильный формат данных"]

        mes = bot.send_message(message.chat.id, message_text, reply_markup=keyb)
        bot.register_next_step_handler(mes, get_stock_availability,lang, keyb,list_keyb)

def add_new_post(message):
    try:
        if message.text == "Меню":
            return
        if message.content_type == 'photo':
            fileID = message.photo[-1].file_id
            file_info = bot.get_file(fileID)
            downloaded_file = bot.download_file(file_info.file_path)
            for user in db.subscribers.find():
              bot.send_photo(user['id_user'],downloaded_file,caption=message.caption)
        if message.content_type == 'text':
            for user in db.subscribers.find():
              bot.send_message(user['id_user'],message.text)
        return
    except:
        return

def parsJson(data,lang = 'ru'):
    keyboard = telebot.types.ReplyKeyboardMarkup(True)
    list_obj = []
    for post in data:
        if "value" in data.get(post):
            k,l = parsJson(data.get(post).get("value"),lang)
            if lang == 'uz':
                KeybordUZ.list_keyboard.append({"name":post,"value":k,"message":l})

            else:
                Keybord.list_keyboard.append({"name": post, "value": k, "message": l})
        keyboard.row(post)
        list_obj.append({"name":post,"value":data.get(post)})
        if len(data.get(post)) != 2:
            if lang == 'uz':
                KeybordUZ.value[post] = data.get(post)
            else:
                Keybord.value[post] = data.get(post)
        if "message" in data.get(post):
            if data.get(post).get('message') != "":
               if lang == 'uz':
                   KeybordUZ.value[post] = data.get(post).get('message')
               else:
                   Keybord.value[post] = data.get(post).get('message')
    return keyboard,list_obj

def LoadInfo():
    with open('JsonLense.json', 'r', encoding='utf-8') as fh:  # открываем файл на чтение
        data = json.load(fh)
    parsJson(data)
    with open('JsonLenseUZ.json', 'r', encoding='utf-8') as fh:  # открываем файл на чтение
        data = json.load(fh)

    parsJson(data,'uz')
    return Keybord.list_keyboard

def LensInfo(message,lang='ru'):
    try:
        if lang == 'uz':
            kb = KeybordUZ
        else:
            kb = Keybord
        if message.text == 'Назад в главное меню':
            bot.send_message(message.chat.id, text="В главное меню", reply_markup=keyboardStartRU)
            return
        if message.text == 'Бош менюга қайтиш':
            bot.send_message(message.chat.id, text="Бош менюга ўтиш", reply_markup=keyboardStartUZ)
            return
        fl = False
        for post in kb.list_keyboard:
            if post.get('name') == message.text and not fl:
                if message.text in kb.value:
                    mes = bot.send_message(message.chat.id, text=kb.value.get(message.text), reply_markup=post.get('value'))
                    fl = True
                else:
                    mes = bot.send_message(message.chat.id,text=message.text, reply_markup=post.get('value'))
                    fl = True

        if message.text in kb.value:
            for post in kb.list_keyboard:
                if post.get('name') == kb.value.get(message.text) and not fl:
                    mes = bot.send_message(message.chat.id, text=kb.value.get(message.text),reply_markup=post.get('value'))
                    fl = True
            if not fl:
                mes = bot.send_message(message.chat.id, text=kb.value.get(message.text))
        message_text = check_lens(message,lang)
        if message_text:
            mes = bot.send_message(message.chat.id, text=message_text,parse_mode="Markdown")
        bot.register_next_step_handler(mes,LensInfo,lang)
    except:
        bot.register_next_step_handler(message,LensInfo,lang)

def check_lens(message,lang):
    try:
        message_text = f"{language[lang]['На складе были найдены следующие линзы']}:\n"
        message.text = message.text.replace("-0.00", "+0.00")
        message.text = message.text.replace("-0,00", "+0.00")
        message.text = message.text.replace(" 0,00", " +0.00")
        message.text = message.text.replace(" 0.00", " +0.00")
        if message.text[0:4] in ["0.00","0,00"]:
            message.text = "+0.00" + message.text[4:]
        if message.text[0:1] == "0":
            message.text = "+0.00" + message.text[1:]

        if " 0" in message.text:
            message.text = message.text.replace(" 0", " +0.00")
        if message.text == "0" or message.text == "0.00" or message.text == "0,00":
            message.text = "+0.00"

        keyb = telebot.types.ReplyKeyboardMarkup(True)
        find = 0
        if re.match('^[+-]\d[,.]\d\d? [+-]\d[,.]\d\d?$',message.text):
            text = message.text.replace(",", ".")
            value = text.split()
            list_lens, find, keyb,list_keyb = ParseCS(value[0], value[1],keyb,lang)
            message_text += get_text(list_lens, find)
            if find != 1:
                return f'{language[lang]["На складе нет таких линз"]}\n'

        if re.match('^[+-]\d[,.]\d\d?$',message.text):
            text = message.text.replace(",", ".")
            value = text.split()
            list_lens, find, keyb,list_keyb = ParseCS(value[0], "+0.00",keyb,lang)
            message_text += get_text(list_lens, find)
            if find != 1:
                return f'{language[lang]["На складе нет таких линз"]}\n'

        if re.match('[+-]\d[,.]\d\d? [+-]\d[,.]\d\d? [+-]\d[,.]\d\d?$', message.text):
            text = message.text.replace(",", ".")
            value = text.split()
            list_lens, find, keyb,list_keyb = ParseDoubleCS(value[0], value[1], value[2], "+0.00", keyb,lang)
            message_text +=  get_text(list_lens, find)
            if find != 1:
                return f'{language[lang]["На складе нет таких линз"]}\n'

        if re.match('[+-]\d[,.]\d\d? [+-]\d[,.]\d\d? [+-]\d[,.]\d\d? [+-]\d[,.]\d\d?$', message.text):
            text = message.text.replace(",", ".")
            value = text.split()
            list_lens, find, keyb,list_keyb = ParseDoubleCS(value[0], value[1], value[2], value[3], keyb,lang)
            message_text +=  get_text(list_lens, find)
            if find != 1:
                return f'{language[lang]["На складе нет таких линз"]}\n'
        if find == 1:
            return message_text
        return False
    except:
        return False


from __future__ import absolute_import

import asyncio
import functools

import aiohttp  # type: ignore
import six
import urllib3  # type: ignore

from google.auth import exceptions
from google.auth import transport
from google.auth.transport import requests

# Timeout can be re-defined depending on async requirement. Currently made 60s more than
# sync timeout.
_DEFAULT_TIMEOUT = 180  # in seconds

class _CombinedResponse(transport.Response):
    """
    In order to more closely resemble the `requests` interface, where a raw
    and deflated content could be accessed at once, this class lazily reads the
    stream in `transport.Response` so both return forms can be used.

    The gzip and deflate transfer-encodings are automatically decoded for you
    because the default parameter for autodecompress into the ClientSession is set
    to False, and therefore we add this class to act as a wrapper for a user to be
    able to access both the raw and decoded response bodies - mirroring the sync
    implementation.
    """

    def __init__(self, response):
        self._response = response
        self._raw_content = None

    def _is_compressed(self):
        headers = self._response.headers
        return "Content-Encoding" in headers and (
            headers["Content-Encoding"] == "gzip"
            or headers["Content-Encoding"] == "deflate"
        )

    @property
    def status(self):
        return self._response.status

    @property
    def headers(self):
        return self._response.headers

    @property
    def data(self):
        return self._response.content

    async def raw_content(self):
        if self._raw_content is None:
            self._raw_content = await self._response.content.read()
        return self._raw_content

    async def content(self):
        # Load raw_content if necessary
        await self.raw_content()
        if self._is_compressed():
            decoder = urllib3.response.MultiDecoder(
                self._response.headers["Content-Encoding"]
            )
            decompressed = decoder.decompress(self._raw_content)
            return decompressed

        return self._raw_content

class _Response(transport.Response):
    """
    Requests transport response adapter.

    Args:
        response (requests.Response): The raw Requests response.
    """

    def __init__(self, response):
        self._response = response

    @property
    def status(self):
        return self._response.status

    @property
    def headers(self):
        return self._response.headers

    @property
    def data(self):
        return self._response.content

class Request(transport.Request):
    """Requests request adapter.

    This class is used internally for making requests using asyncio transports
    in a consistent way. If you use :class:`AuthorizedSession` you do not need
    to construct or use this class directly.

    This class can be useful if you want to manually refresh a
    :class:`~google.auth.credentials.Credentials` instance::

        import google.auth.transport.aiohttp_requests

        request = google.auth.transport.aiohttp_requests.Request()

        credentials.refresh(request)

    Args:
        session (aiohttp.ClientSession): An instance :class:`aiohttp.ClientSession` used
            to make HTTP requests. If not specified, a session will be created.

    .. automethod:: __call__
    """

    def __init__(self, session=None):
        # TODO: Use auto_decompress property for aiohttp 3.7+
        if session is not None and session._auto_decompress:
            raise exceptions.InvalidOperation(
                "Client sessions with auto_decompress=True are not supported."
            )
        self.session = session

    async def __call__(
        self,
        url,
        method="GET",
        body=None,
        headers=None,
        timeout=_DEFAULT_TIMEOUT,
        **kwargs,
    ):
        """
        Make an HTTP request using aiohttp.

        Args:
            url (str): The URL to be requested.
            method (Optional[str]):
                The HTTP method to use for the request. Defaults to 'GET'.
            body (Optional[bytes]):
                The payload or body in HTTP request.
            headers (Optional[Mapping[str, str]]):
                Request headers.
            timeout (Optional[int]): The number of seconds to wait for a
                response from the server. If not specified or if None, the
                requests default timeout will be used.
            kwargs: Additional arguments passed through to the underlying
                requests :meth:`requests.Session.request` method.

        Returns:
            google.auth.transport.Response: The HTTP response.

        Raises:
            google.auth.exceptions.TransportError: If any exception occurred.
        """

        try:
            if self.session is None:  # pragma: NO COVER
                self.session = aiohttp.ClientSession(
                    auto_decompress=False
                )  # pragma: NO COVER
            requests._LOGGER.debug("Making request: %s %s", method, url)
            response = await self.session.request(
                method, url, data=body, headers=headers, timeout=timeout, **kwargs
            )
            return _CombinedResponse(response)

        except aiohttp.ClientError as caught_exc:
            new_exc = exceptions.TransportError(caught_exc)
            six.raise_from(new_exc, caught_exc)

        except asyncio.TimeoutError as caught_exc:
            new_exc = exceptions.TransportError(caught_exc)
            six.raise_from(new_exc, caught_exc)

class AuthorizedSession(aiohttp.ClientSession):
    """This is an async implementation of the Authorized Session class. We utilize an
    aiohttp transport instance, and the interface mirrors the google.auth.transport.requests
    Authorized Session class, except for the change in the transport used in the async use case.

    A Requests Session class with credentials.

    This class is used to perform requests to API endpoints that require
    authorization::

        from google.auth.transport import aiohttp_requests

        async with aiohttp_requests.AuthorizedSession(credentials) as authed_session:
            response = await authed_session.request(
                'GET', 'https://www.googleapis.com/storage/v1/b')

    The underlying :meth:`request` implementation handles adding the
    credentials' headers to the request and refreshing credentials as needed.

    Args:
        credentials (google.auth._credentials_async.Credentials):
            The credentials to add to the request.
        refresh_status_codes (Sequence[int]): Which HTTP status codes indicate
            that credentials should be refreshed and the request should be
            retried.
        max_refresh_attempts (int): The maximum number of times to attempt to
            refresh the credentials and retry the request.
        refresh_timeout (Optional[int]): The timeout value in seconds for
            credential refresh HTTP requests.
        auth_request (google.auth.transport.aiohttp_requests.Request):
            (Optional) An instance of
            :class:`~google.auth.transport.aiohttp_requests.Request` used when
            refreshing credentials. If not passed,
            an instance of :class:`~google.auth.transport.aiohttp_requests.Request`
            is created.
        kwargs: Additional arguments passed through to the underlying
            ClientSession :meth:`aiohttp.ClientSession` object.
    """

    def __init__(
        self,
        credentials,
        refresh_status_codes=transport.DEFAULT_REFRESH_STATUS_CODES,
        max_refresh_attempts=transport.DEFAULT_MAX_REFRESH_ATTEMPTS,
        refresh_timeout=None,
        auth_request=None,
        auto_decompress=False,
        **kwargs,
    ):
        super(AuthorizedSession, self).__init__(**kwargs)
        self.credentials = credentials
        self._refresh_status_codes = refresh_status_codes
        self._max_refresh_attempts = max_refresh_attempts
        self._refresh_timeout = refresh_timeout
        self._is_mtls = False
        self._auth_request = auth_request
        self._auth_request_session = None
        self._loop = asyncio.get_event_loop()
        self._refresh_lock = asyncio.Lock()
        self._auto_decompress = auto_decompress

    async def request(
        self,
        method,
        url,
        data=None,
        headers=None,
        max_allowed_time=None,
        timeout=_DEFAULT_TIMEOUT,
        auto_decompress=False,
        **kwargs,
    ):

        """Implementation of Authorized Session aiohttp request.

        Args:
            method (str):
                The http request method used (e.g. GET, PUT, DELETE)
            url (str):
                The url at which the http request is sent.
            data (Optional[dict]): Dictionary, list of tuples, bytes, or file-like
                object to send in the body of the Request.
            headers (Optional[dict]): Dictionary of HTTP Headers to send with the
                Request.
            timeout (Optional[Union[float, aiohttp.ClientTimeout]]):
                The amount of time in seconds to wait for the server response
                with each individual request. Can also be passed as an
                ``aiohttp.ClientTimeout`` object.
            max_allowed_time (Optional[float]):
                If the method runs longer than this, a ``Timeout`` exception is
                automatically raised. Unlike the ``timeout`` parameter, this
                value applies to the total method execution time, even if
                multiple requests are made under the hood.

                Mind that it is not guaranteed that the timeout error is raised
                at ``max_allowed_time``. It might take longer, for example, if
                an underlying request takes a lot of time, but the request
                itself does not timeout, e.g. if a large file is being
                transmitted. The timout error will be raised after such
                request completes.
        """
        # Headers come in as bytes which isn't expected behavior, the resumable
        # media libraries in some cases expect a str type for the header values,
        # but sometimes the operations return these in bytes types.
        if headers:
            for key in headers.keys():
                if type(headers[key]) is bytes:
                    headers[key] = headers[key].decode("utf-8")

        async with aiohttp.ClientSession(
            auto_decompress=self._auto_decompress
        ) as self._auth_request_session:
            auth_request = Request(self._auth_request_session)
            self._auth_request = auth_request

            # Use a kwarg for this instead of an attribute to maintain
            # thread-safety.
            _credential_refresh_attempt = kwargs.pop("_credential_refresh_attempt", 0)
            # Make a copy of the headers. They will be modified by the credentials
            # and we want to pass the original headers if we recurse.
            request_headers = headers.copy() if headers is not None else {}

            # Do not apply the timeout unconditionally in order to not override the
            # _auth_request's default timeout.
            auth_request = (
                self._auth_request
                if timeout is None
                else functools.partial(self._auth_request, timeout=timeout)
            )

            remaining_time = max_allowed_time

            with requests.TimeoutGuard(remaining_time, asyncio.TimeoutError) as guard:
                await self.credentials.before_request(
                    auth_request, method, url, request_headers
                )

            with requests.TimeoutGuard(remaining_time, asyncio.TimeoutError) as guard:
                response = await super(AuthorizedSession, self).request(
                    method,
                    url,
                    data=data,
                    headers=request_headers,
                    timeout=timeout,
                    **kwargs,
                )

            remaining_time = guard.remaining_timeout

            if (
                response.status in self._refresh_status_codes
                and _credential_refresh_attempt < self._max_refresh_attempts
            ):

                requests._LOGGER.info(
                    "Refreshing credentials due to a %s response. Attempt %s/%s.",
                    response.status,
                    _credential_refresh_attempt + 1,
                    self._max_refresh_attempts,
                )

                # Do not apply the timeout unconditionally in order to not override the
                # _auth_request's default timeout.
                auth_request = (
                    self._auth_request
                    if timeout is None
                    else functools.partial(self._auth_request, timeout=timeout)
                )

                with requests.TimeoutGuard(
                    remaining_time, asyncio.TimeoutError
                ) as guard:
                    async with self._refresh_lock:
                        await self._loop.run_in_executor(
                            None, self.credentials.refresh, auth_request
                        )

                remaining_time = guard.remaining_timeout

                return await self.request(
                    method,
                    url,
                    data=data,
                    headers=headers,
                    max_allowed_time=remaining_time,
                    timeout=timeout,
                    _credential_refresh_attempt=_credential_refresh_attempt + 1,
                    **kwargs,
                )

        return response


def premik(ukaz, x, y, smer):
    smeri = "NESW"
    premiki = [(0, -1), (1, 0), (0, 1), (-1, 0)]
    ismer = smeri.index(smer)
    if ukaz == "R":
        smer = smeri[(ismer + 1) % 4]
    elif ukaz == "L":
        smer = smeri[(ismer - 1) % 4]
    else:
        dx, dy = premiki[ismer]
        x += dx * ukaz
        y += dy * ukaz
    return x, y, smer

def izvedi(ime_datoteke):
    sky="NESW"
    x=y=smer=0
    r = [(x, y,sky[0])]
    dat = open(ime_datoteke)
    ukazi = dat.read().split("\n")
    dat.close()
    for ukaz in ukazi:
        if ukaz == "LEVO":
            smer = (smer + 3) % 4
            r.append((x, y, sky[smer]))
        elif ukaz == "DESNO":
            smer = (smer + 1) % 4
            r.append((x, y, sky[smer]))
        elif ukaz.split(" ")[0] == "NAPREJ":
            razdalja = int(ukaz.split(" ")[1])
            x += (smer % 2) * (2 - smer) * razdalja
            y += (1 - smer % 2) * (smer - 1) * razdalja
            r.append((x, y, sky[smer]))
    return r

def opisi_stanje(x, y, smer):
    pos = {"N":"^","E":">","S":"v","W":"<"}
    ret = "{:>3}:{:<3} {}"
    return ret.format(x,y,pos[smer])

def prevedi(ime_vhoda, ime_izhoda):
    r = izvedi(ime_vhoda)
    s = open(ime_izhoda,"w")
    for x,y,z in r:
        s.write(opisi_stanje(x,y,z)+"\n")

def opisi_stanje_2(x, y, smer):
    pos = {"N":"^","E":">","S":"v","W":"<"}
    ret = "{}{}({}:{})"
    return ret.format(pos[smer],(4-len(str(x)))*" ",x,y)

import unittest
class TestObvezna(unittest.TestCase):
    def test_branje(self):
        self.assertEqual(
            izvedi("primer.txt"),
            [(0, 0, 'N'), (0, 0, 'E'), (12, 0, 'E'), (12, 0, 'S'), (12, 2, 'S'),
             (12, 2, 'E'), (15, 2, 'E'), (15, 2, 'N'), (15, 2, 'W')]
        )
        self.assertEqual(
            izvedi("ukazi.txt"),
            [(0, 0, 'N'), (0, 0, 'E'), (1, 0, 'E'), (1, 0, 'S'), (1, 0, 'W'),
             (0, 0, 'W'), (0, 0, 'S'), (0, 0, 'E'), (1, 0, 'E'), (1, 0, 'S'),
             (1, 3, 'S'), (1, 3, 'E'), (2, 3, 'E'), (2, 3, 'S'), (2, 3, 'W')]
        )

    def test_opisi_stanje(self):
        self.assertEqual(opisi_stanje(0, 12, "N"), "  0:12  ^")
        self.assertEqual(opisi_stanje(111, 0, "E"), "111:0   >")
        self.assertEqual(opisi_stanje(-2, 111, "S"), " -2:111 v")
        self.assertEqual(opisi_stanje(0, 0, "W"), "  0:0   <")

    def test_prevedi(self):
        from random import randint
        import os
        ime = "izhod{:05}.txt".format(randint(0, 99999))
        try:
            self.assertIsNone(prevedi("primer.txt", ime))
            self.assertEqual(open(ime).read().rstrip(), """  0:0   ^
  0:0   >
 12:0   >
 12:0   v
 12:2   v
 12:2   >
 15:2   >
 15:2   ^
 15:2   <""")

            self.assertIsNone(prevedi("ukazi.txt", ime))
            self.assertEqual(open(ime).read().rstrip(), """  0:0   ^
  0:0   >
  1:0   >
  1:0   v
  1:0   <
  0:0   <
  0:0   v
  0:0   >
  1:0   >
  1:0   v
  1:3   v
  1:3   >
  2:3   >
  2:3   v
  2:3   <""")
        finally:
            os.remove(ime)

        vime = "vhod{:05}.txt".format(randint(0, 99999))
        open(vime, "wt").write("NAPREJ 23\nLEVO\nNAPREJ 17\n")
        try:
            self.assertIsNone(prevedi(vime, ime))
            self.assertEqual(open(ime).read().rstrip(), """  0:0   ^
  0:-23 ^
  0:-23 <
-17:-23 <""")
        finally:
            os.remove(ime)
            os.remove(vime)

class TestDodatna(unittest.TestCase):
    def test_opisi_stanje(self):
        self.assertEqual(opisi_stanje_2(0, 12, "N"),   "^   (0:12)")
        self.assertEqual(opisi_stanje_2(111, 0, "E"),  "> (111:0)")
        self.assertEqual(opisi_stanje_2(-2, 111, "S"), "v  (-2:111)")
        self.assertEqual(opisi_stanje_2(0, 0, "W"),    "<   (0:0)")

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


from pytrends.request import TrendReq
from pandas import DataFrame
import requests
import pandas as pd
import math
import sys
import os
import django
path = os.getcwd() #현재 파일 위치 문자열로 반환
path = os.path.split(path) #상위폴더위치 찾기 위한 스플릿
sys.path.append(path[0])#상위폴더위치 sys.path에 등록
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mainix.settings")
django.setup()
import time
from bigdata_crypto.models import Tredn_Sig_Table

coinNames = ['ATOM', 'XEM', 'BAT', 'BSV', 'ETH', 'XLM', 'BTC',
             'DCR', 'ADA', 'ETC', 'XMR', 'ONT', 'XRP', 'TRX', 'BCH', 'EOS', 'ZEC', 'NEO', 'DASH', 'LTC']
#가격함수

def H_Price(coinName):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}

    count = "168";  # 기간
    url = 'https://crix-api-endpoint.upbit.com/v1/crix/candles/minutes/60?code=CRIX.UPBIT.KRW-' + coinName + '&count=' + count + '';

    res = requests.get(url, headers=headers)
    data = res.json()
    upbit_prices = []
    price_date = []
    data.reverse()
    #data2 = data[1]["tradePrice"]
    #date = data[1]["candleDateTime"]

    for a in range(len(data)):
        data1 = data[a]['tradePrice']
        upbit_prices.append(data1)

    for i in range(len(data)):
        date = data[i]["candleDateTime"]
        date = date.split('+')
        del date[1]
        date = date[0]
        price_date.append(date)

    price_df = DataFrame({"price": upbit_prices}, index=price_date)
    return price_df

BTC_price_df = H_Price('BTC')

def BTC_Signals():
    # BTC 트랜드 시그널 생성
    Period = 2;
    BTC_signals = []
    pytrends = TrendReq(hl='en-US', tz=360)
    kw_list = ["Bitcoin"]  # 키워드 설정
    pytrends.build_payload(kw_list, cat=0, timeframe='now 7-d', geo='US', gprop='')  # 트랜드 기간 설정 , 지역설정, 예외설정
    cointrenddf = pytrends.interest_over_time()
    trends_df = cointrenddf["Bitcoin"]  # Bitcoin 트랜트만
    trends_dfma5 = trends_df.rolling(window=Period).mean()  # Bitcoin 트랜드 기간평균

    trends_df = trends_df.iloc[1:]  # 트랜드의 초기값 삭제
    trends_dfma5 = trends_dfma5.iloc[:-1]  # 기간평균의 마지막값 삭제

    for trd, ma5 in zip(trends_df, trends_dfma5):
        if ma5 == 0:
            BTC_signals.append('None')
        else:
            BTC_signals.append(trd - ma5)
    return  BTC_signals
 # 코인별 신호갑 부여 함수

def H_Signals() :
    statecont =1
    signals_list = []
    signals = BTC_Signals()
    BTC_price_df = H_Price('BTC')
    error0001=["0001Error"]
    for coinName in coinNames:
        try:
            price = H_Price(coinName)
            def Corr(coinName):
                Alt_price_df =price
                Total_Price_df = pd.concat([Alt_price_df, BTC_price_df], axis=1, sort=True)
                corr_value = Total_Price_df.corr(method='pearson')
                return corr_value.values[0][1]

            if -0.2 < Corr(coinName) < 0.2:
                corr = 1
            else:
                corr = Corr(coinName)
            corr_signals = signals[-2] * (1 /corr)  # 코인별 상관계수 부여
            corr_signals = round(corr_signals,3)
            corr_signals = corr_signals * statecont
            corr_signaled = signals[-4]*(1/corr)*statecont
            if corr_signaled > 0:
                profit = math.log((price['price'][-2] / price['price'][-4])) * 100
            else:
                profit = math.log((price['price'][-4] / price['price'][-2])) * 100
            if abs(168 - len(pd.concat([price,BTC_price_df], axis=1, sort=True))) < 30:
                status = "0000"
                last_price = price['price'][-2]
                last_profit = profit
                corr_signals = corr_signals
            else:
                status = "0001"
                last_price = "Nan"
                last_profit = "Nan"
                corr_signals = "Nan"
                error0001.append(coinName)

            signals_list.append({"Status":status,"Date": price.index[-1] + "+" "09:00:00""KST", "Price": last_price,
                 "CoinName": coinName, "Signal": corr_signals, "Profit":last_profit})

        except:
            signals_list.append({"Status":"0010","Date": price.index[-1] + "+" "09:00:00KST","Price":"Nan",
                                 "CoinName":coinName,"Signal":"Nan","Profit":"Nan"})

    return signals_list

if __name__=='__main__':
    print(H_Signals())

'''
#request 받아 json으로 전송
def Signals(request) :
    signals_list = ["Trend Signal Data"]
    signals = BTC_Signals()
    BTC_price_df = H_Price('BTC')
    error0001=["0001Error"]
    for coinName in coinNames:
        try:
            price = H_Price(coinName)
            def Corr(coinName):
                Alt_price_df =price
                Total_Price_df = pd.concat([Alt_price_df, BTC_price_df], axis=1, sort=True)
                corr_value = Total_Price_df.corr(method='pearson')
                return corr_value.values[0][1]

            if -0.2 < Corr(coinName) < 0.2:
                corr = 1
            else:
                corr = Corr(coinName)
            corr_signals = signals[-2] * (1 /corr)  # 코인별 상관계수 부여
            corr_signals = round(corr_signals,3)
            corr_signals = corr_signals * statecont
            corr_signaled = signals[-4]*(1/corr)*statecont
            if corr_signaled > 0:
                profit = math.log((price['price'][-2] / price['price'][-4])) * 100
            else:
                profit = math.log((price['price'][-4] / price['price'][-2])) * 100
            if abs(168 - len(pd.concat([price,BTC_price_df], axis=1, sort=True))) < 30:
                status = "0000"
                last_price = price['price'][-2]
                last_profit = profit
                corr_signals = corr_signals
            else:
                status = "0001"
                last_price = "Nan"
                last_profit = "Nan"
                corr_signals = "Nan"
                error0001.append(coinName)

            signals_list.append({"Status":status,"Date": price.index[-1] + "+" "09:00:00""KST", "Price": last_price,
                 "CoinName": coinName, "Signal": corr_signals, "Profit":last_profit})

        except:
            signals_list.append({"Status":"0010","Date": price.index[-1] + "+" "09:00:00KST","Price":"Nan",
                                 "CoinName":coinName,"Signal":"Nan","Profit":"Nan"})

    signals_list.append(error0001)
    j_signals_list = json.dumps(signals_list,ensure_ascii = False)
    #return signals_list
    return  HttpResponse(j_signals_list, content_type='application/json')
'''


import random

def matrix_25():
	array = [
	[],[],[],[],[]
	]

def gen_row():
	row = []
	for i in range(0,5):
		value = random.randint(0,255)
		row.append(value)
	print(row)
	return row

if __name__ == "__main__":
	while True:
		gen_row()


from flask import Blueprint, jsonify, request
from app.models import Pizza, db, Cart, Saved_order, Topping

cart_routes = Blueprint('cart', __name__)

@cart_routes.route('/<int:id>')
def getcarts(id):
    cart = Cart.query.filter(id == Cart.userId).first()
    pizzas = Pizza.query.filter(Pizza.cartId == id).order_by(Pizza.id)
    pizza_list = []
    for pizza in pizzas:
        toppings = Topping.query.filter(
            pizza.id == Topping.pizzaId).order_by(Topping.id)
        pizza_list.append({"id": pizza.id, "price": pizza.price,
                           "cartId": pizza.cartId, 'orderId': pizza.orderId, 'total': pizza.total, 'toppings': [{"id": topping.id, "name": topping.name,
                                                                                "pizzaId": topping.pizzaId} for topping in toppings]})
    # pizza_list = [{"id": pizza.id, "price": pizza.price,
    #                "cartId": pizza.cartId, 'orderId': pizza.orderId, 'total': pizza.total} for pizza in pizzas]

    return jsonify({'cart': cart.to_dict(), 'pizzas': pizza_list})

@cart_routes.route('/<int:id>/checkout/', methods=['PUT'])
def Checkout(id):
    data = request.json
    pizzas = Pizza.query.filter(Pizza.cartId == id)
    length = Pizza.query.filter(Pizza.cartId == id).count()
    cart = Cart.query.filter(Cart.id == id).first()
    cart.total = 0
    Order = Saved_order(
        total=data['price'],
        userId=cart.userId,
    )
    db.session.add(Order)
    db.session.commit()
    for pizza in pizzas:
        print(pizza)
        pizza.cartId = None
        pizza.orderId = Order.id
    if length:
        pizza_list = [{"id": pizza.id, "price": pizza.price,
                       "cartId": pizza.cartId, 'orderId': pizza.orderId} for pizza in pizzas]
    db.session.commit()
    return jsonify({'cart': cart.to_dict(), 'pizzas': pizza_list})


from django.db.migrations import serializer
from django.http import JsonResponse
from rest_framework import serializers
from rest_framework.authtoken.admin import User

from .models import Category, Story, Reply, ReplyComment, StoryLike

class UserSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    username = serializers.CharField()

    class Meta:
        model = User
        fields = ['username', 'id']

# class SubCommentSerializer(serializers.Serializer):
#     sub_comments = serializers.SerializerMethodField()
#     class Meta:
#         fields = ['sub_comments']

class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields = [
            'name',
            'slug',
            'desc_safe',
            'order',
            'color_code',
        ]

class StorySerializer(serializers.ModelSerializer):
    user = UserSerializer()
    category = serializers.SerializerMethodField()

    class Meta:
        model = Story
        fields = [
            'code',
            'user',
            'content',
            'content_safe',
            'title',
            'category',
            'last_activity_by',
            'last_activity_at',
            'created_at',
            'updated_at',
            # 'scheduled_at',
            'published_at',
            'STORY_STATUS_CHOICES',
            'status',
            'closed',
            # 'featured_until',
            'featured',
            # 'edited_at',
            # 'edited_by',
            'num_views',
            'num_likes',
            'num_replies',
            'num_comments',
            'num_participants',
            # 'ip_address',
            'user_agent',
        ]
    def get_category(self, obj):
        categories = []
        for x in obj['category']:
            categories.append(CategorySerializer(x).data)
        return categories

class ReplySerializer(serializers.ModelSerializer):
    user = UserSerializer()
    sub_comments = serializers.SerializerMethodField()
    num_reply_comments = serializers.SerializerMethodField()

    class Meta:
        model = Reply
        fields = [
            'user',
            'reply_order',
            'content',
            'content_safe',
            'removed',
            'created_at',
            'updated_at',
            # 'ip_address',
            'user_agent',
            # 'edited_at',
            # 'edited_by',
            'sub_comments',
            'num_reply_comments',
        ]

    def get_sub_comments(self, obj):
        list = []
        print('nam')
        for x in obj['sub_comments']:
            list.append({
                'Content': x.content,
                'user': UserSerializer(x.user).data,
            })
        return {
            'data': list
        }

    def get_num_reply_comments(self, obj):
        return obj['num_reply_comments']

class ReplyCommentSerializer(serializers.ModelSerializer):
    user = UserSerializer()

    class Meta:
        model = ReplyComment
        fields = [
            'user',
            'reply',
            'content',
            'mention_to',
            'removed',
            'ip_address',
            'user_agent',
        ]

class StoryLikeSerializer(serializers.ModelSerializer):
    class Meta:
        model = StoryLike
        fields = [
            'user',
            'story',
            'created_at',
        ]


from openerp.osv import fields, osv

class stock_picking_out(osv.osv):
    _inherit = "stock.picking.out"

    def open_sales_order(self, cr, user, ids, context=None):
        delivery_datas = self.browse(cr, user, ids[0])
        sale_order_id = delivery_datas.sale_id and delivery_datas.sale_id.id
        view_id = self.pool.get('ir.model.data').get_object_reference(cr, user, 'sale', 'view_order_form')[1]
        return {
            'res_id':sale_order_id,
            'view_id':[view_id],
            'view_type':'form',
            'view_mode':'form',
            'res_model':'sale.order',
            'type':'ir.actions.act_window',
            'target':'current',
        }
stock_picking_out()

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:


import argparse
import os
import re
import shutil
from pathlib import Path

import img2dataset
from cloudpathlib import CloudPath
from huggingface_hub import snapshot_download

from scale_configs import available_scales

def path_or_cloudpath(s):
    if re.match(r"^\w+://", s):
        return CloudPath(s)
    return Path(s)

def cleanup_dir(path):
    assert isinstance(path, Path) or isinstance(path, CloudPath)
    if isinstance(path, Path):
        shutil.rmtree(path)
    else:
        path.rmtree()

if __name__ == "__main__":
    parser = argparse.ArgumentParser()

    parser.add_argument(
        "--scale",
        type=str,
        required=False,
        choices=available_scales(simple_names=True)[1:] + ["datacomp_1b"],
        default="small",
        help="Competition scale.",
    )
    parser.add_argument(
        "--data_dir",
        type=path_or_cloudpath,
        required=True,
        help="Path to directory where the data (webdataset shards) will be stored.",
    )
    parser.add_argument(
        "--metadata_dir",
        type=path_or_cloudpath,
        default=None,
        help="Path to directory where the metadata will be stored. If not set, infer from data_dir.",
    )
    parser.add_argument(
        "--download_npz",
        help="If true, also download npz files.",
        action="store_true",
        default=False,
    )
    parser.add_argument(
        "--skip_shards",
        help="If true, only download metadata.",
        action="store_true",
        default=False,
    )
    parser.add_argument(
        "--overwrite_metadata",
        help="If true, force re-download of the metadata files.",
        action="store_true",
        default=False,
    )
    parser.add_argument(
        "--skip_bbox_blurring",
        help="If true, skip bounding box blurring on images while downloading.",
        action="store_true",
        default=False,
    )
    parser.add_argument(
        "--processes_count",
        type=int,
        required=False,
        default=16,
        help="Number of processes for download.",
    )
    parser.add_argument(
        "--thread_count",
        type=int,
        required=False,
        default=128,
        help="Number of threads for download.",
    )
    parser.add_argument(
        "--image_size",
        type=int,
        required=False,
        default=512,
        help="Size images need to be downloaded to.",
    )
    parser.add_argument(
        "--resize_mode",
        type=str,
        required=False,
        choices=["no", "border", "keep_ratio", "keep_ratio_largest", "center_crop"],
        default="keep_ratio_largest",
        help="Resizing mode used by img2dataset when downloading images.",
    )
    parser.add_argument(
        "--no_resize_only_if_bigger",
        help="If true, do not resize only if images are bigger than target size.",
        action="store_true",
        default=False,
    )
    parser.add_argument(
        "--encode_format",
        type=str,
        required=False,
        choices=["png", "jpg", "webp"],
        default="jpg",
        help="Images encoding format.",
    )
    parser.add_argument(
        "--output_format",
        type=str,
        required=False,
        choices=["webdataset", "tfrecord", "parquet", "files"],
        default="webdataset",
        help="Output format used by img2dataset when downloading images.",
    )
    parser.add_argument(
        "--retries",
        type=int,
        required=False,
        default=2,
        help="Number of time a download should be retried (default 2)",
    )
    parser.add_argument(
        "--enable_wandb",
        action="store_true",
        default=False,
        help="Whether to enable wandb logging (default False)",
    )
    parser.add_argument(
        "--wandb_project",
        type=str,
        required=False,
        default="datacomp",
        help="Name of W&B project used (default datacomp)",
    )

    args = parser.parse_args()

    hf_repo = (
        f"mlfoundations/datacomp_{args.scale}"
        if args.scale != "datacomp_1b"
        else "mlfoundations/datacomp_1b"
    )

    metadata_dir = args.metadata_dir
    if metadata_dir is None:
        metadata_dir = args.data_dir / "metadata"

    # Download the metadata files if needed.
    if args.overwrite_metadata or not metadata_dir.exists():
        if metadata_dir.exists():
            print(f"Cleaning up {metadata_dir}")
            shutil.rmtree(metadata_dir)
        metadata_dir.mkdir(parents=True)

        print(f"Downloading metadata to {metadata_dir}...")

        cache_dir = metadata_dir.parent / f"hf"
        hf_snapshot_args = dict(
            repo_id=hf_repo,
            allow_patterns=f"*.parquet",
            local_dir=metadata_dir,
            cache_dir=cache_dir,
            local_dir_use_symlinks=False,
            repo_type="dataset",
        )

        if args.scale == "xlarge":
            hf_snapshot_args["allow_patterns"] = f"*/*.parquet"

        snapshot_download(**hf_snapshot_args)
        if args.download_npz:
            hf_snapshot_args["allow_patterns"] = hf_snapshot_args[
                "allow_patterns"
            ].replace(".parquet", ".npz")
            print("\nDownloading npz files")
            snapshot_download(**hf_snapshot_args)

        # Flatten directory structure in case of xlarge
        if args.scale == "xlarge":
            filenames = list(metadata_dir.rglob("*.parquet")) + list(
                metadata_dir.rglob("*.npz")
            )
            for filename in filenames:
                basename = filename.name
                filename.replace(metadata_dir / basename)

            empty_dirs = list(metadata_dir.glob("part_*"))
            for empty_dir in empty_dirs:
                empty_dir.rmdir()

        cleanup_dir(cache_dir)

        print("Done downloading metadata.")
    else:
        print(
            f"Skipping download of metadata because {metadata_dir} exists. Use --overwrite_metadata to force re-downloading."
        )

    if not args.skip_shards:
        # Download images.
        shard_dir = args.data_dir / "shards"
        shard_dir.mkdir(parents=True, exist_ok=True)
        print(f"Downloading images to {shard_dir}")

        bbox_col = None if args.skip_bbox_blurring else "face_bboxes"

        img2dataset.download(
            url_list=str(metadata_dir),
            image_size=args.image_size,
            output_folder=str(shard_dir),
            processes_count=args.processes_count,
            thread_count=args.thread_count,
            resize_mode=args.resize_mode,
            resize_only_if_bigger=not args.no_resize_only_if_bigger,
            encode_format=args.encode_format,
            output_format=args.output_format,
            input_format="parquet",
            url_col="url",
            caption_col="text",
            bbox_col=bbox_col,
            save_additional_columns=["uid"],
            number_sample_per_shard=10000,
            oom_shard_count=8,
            retries=args.retries,
            enable_wandb=args.enable_wandb,
            wandb_project=args.wandb_project,
        )
    else:
        print(f"Skipping image data download.")

    print("Done!")


import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import random

class Perceptron:
    def __init__(self, data_values, labels, n, learning_rate, dimension, iterations):
        self.data = data_values
        self.label = labels
        self.dataset_size = n
        self.learning_rate = learning_rate
        self.weights = np.random.rand(1, dimension+1)
        # self.weights = np.zeros((1, dimension+1))
        self.misclassified = []
        self.iterations = iterations

    def train(self):
        misclassified = []
        '''
        signal = wT.x(i) --> sign(signal)=output
        '''
        print(self.weights)
        for i in range(self.dataset_size):
            signal = np.dot(self.data[i, :], self.weights.T)
            if signal > 0:
                summation = 1
            else:
                summation = -1
            # while there is some mis-classifed point
            if summation != self.label[i]:  # y=-1, signal=1 or y=1, signal=-1
                self.misclassified.append(i)

        converged = False
        iteration = 0
        while not converged and iteration < self.iterations:
            if len(self.misclassified) == 0:
                converged = True
                continue
            else:
                print("==================================================")
                print("Initial misclassification", len(self.misclassified))
                random_index = random.randint(0, len(self.misclassified)-1)
                misclassified_constraint_index = self.misclassified[random_index]
                print(misclassified_constraint_index)
                print(self.data[misclassified_constraint_index, :])
                # Now fetch that data point from numpy set and update it with weight
                # self.weights = self.weights + (self.learning_rate * label[misclassified_constraint_index]*self.data[misclassified_constraint_index])
                if label[misclassified_constraint_index] == -1:  # y=0, signal=1
                    self.weights = self.weights - (self.learning_rate * self.data[misclassified_constraint_index])
                elif label[misclassified_constraint_index] == 1:
                    self.weights = self.weights + (self.learning_rate * self.data[misclassified_constraint_index])

                self.misclassified = []

                for i in range(self.dataset_size):
                    signal = np.dot(self.data[i, :], self.weights.T)
                    # while there is some mis-classifed point
                    if signal > 0:
                        summation = 1
                    else:
                        summation = -1
                    # while there is some mis-classifed point
                    if summation != self.label[i]:  # y=-1, signal=1
                        self.misclassified.append(i)
                print("Later: ", len(self.misclassified))

                iteration += 1

        print(self.weights)

if __name__ == "__main__":
    # Process the Data
    print("Processing the data")
    dataframe = pd.read_csv("classification.txt", names=["x", "y", "z", "label", "label2"])
    dataf = dataframe.iloc[:, 0:4]
    data = dataf[['x', 'y', 'z']]
    label = dataf[['label']].to_numpy()
    d = pd.DataFrame(np.ones((len(dataframe), 1)))
    data.insert(0, 'x0', d)
    data = data.to_numpy()
    x = Perceptron(data, label, len(data), 0.5, 3, 100)
    x.train()


from vnpy.app.cta_strategy import (
    CtaTemplate,
    StopOrder,
    TickData,
    BarData,
    TradeData,
    OrderData,
    BarGenerator,
    ArrayManager,
)
from vnpy.trader.database import database_manager
from vnpy.trader.constant import Exchange, Interval

class tickTobar(CtaTemplate):
    author = "liuxd"

    window_size = 15
    interval_type = "MINUTE"

    interval = Interval.MINUTE

    parameters = ["window_size", "interval_type"]

    number = 0

    def __init__(self, cta_engine, strategy_name, vt_symbol, setting):
        """"""
        super().__init__(cta_engine, strategy_name, vt_symbol, setting)

        if self.interval_type == "MINUTE":
            self.interval = Interval.MINUTE
        elif self.interval_type == "HOUR":
            self.interval = Interval.HOUR
        elif self.interval_type == "DAY":
            self.interval = Interval.DAILY

        self.bg = BarGenerator(self.on_bar, self.window_size, self.on_transfer_bar, self.interval)
        self.am = ArrayManager()

    def on_init(self):
        """
        Callback when strategy is inited.
        """
        self.write_log("策略初始化")
        self.load_tick(10)

    def on_start(self):
        """
        Callback when strategy is started.
        """
        self.write_log("策略启动")
        self.put_event()

    def on_stop(self):
        """
        Callback when strategy is stopped.
        """
        self.write_log("策略停止")

        self.put_event()

    def on_save_bar(self, bar: BarData):
        # self.number = self.number + 1
        # print("135 on_save_bar: {}, {}, {}".format(self.number, self.interval, bar))
        bar.interval = self.interval
        if self.interval == Interval.MINUTE:
            bar.interval = Interval.MINUTE
            if self.window_size == 15:
                bar.interval = Interval.MINUTE15
        elif self.interval == Interval.HOUR:
            bar.interval = Interval.HOUR
            if self.window_size == 4:
                bar.interval = Interval.HOUR4
            elif self.window_size == 6:
                bar.interval = Interval.HOUR6
        elif self.interval == Interval.DAILY:
            bar.interval = Interval.DAILY

        database_manager.save_bar_data([bar], bar.symbol+"_bar")

    def on_tick(self, tick: TickData):
        """
        Callback of new tick data update.
        """
        self.bg.update_tick(tick)

    def on_bar(self, bar: BarData):
        """
        Callback of new bar data update.
        """
        self.bg.update_bar(bar)

    def on_transfer_bar(self, bar: BarData):
        """"""

        am = self.am
        am.update_bar(bar)
        if not am.inited:
            return

        self.on_save_bar(bar)

    def on_order(self, order: OrderData):
        """
        Callback of new order data update.
        """
        pass

    def on_trade(self, trade: TradeData):
        """
        Callback of new trade data update.
        """
        self.put_event()

    def on_stop_order(self, stop_order: StopOrder):
        """
        Callback of stop order update.
        """
        pass


# Practicing with the Math Operations
# Author: Sloane Luckiewicz

import math

# Age predictor
age = float(input("Enter age: "))
decade = 10
futureAge = age + decade

print(f"""You are {age} years old.
In a decade you will be {futureAge}""")

# / float division, will be precise and result in a decimal
# // integer division, will cut off the decimal
# round (variable, decimal places) ... round(3.75,1) = 3.8
# Pizza Party
numGuests = int(input("Enter Num Guests: "))
slicesPerGuest = 2.5
totalSlices = numGuests * slicesPerGuest
numPizzas = totalSlices // 6
# numPizzas = math.ceil(numPizzas)
numPizzas = round(numPizzas,0)
# math.ceil is not working for me!

print(f"""You are having {numGuests} people to your party.
You will need {totalSlices} number of pizza slices,
and {numPizzas} pizzas.""")

# chickens
numEggs = 57
numCartons = numEggs // 12

print(f"You need {numCartons} cartons of eggs.")

# travelling
miles = float(input("Enter Miles: "))
pricePerMile = float(input("Enter Price Per Mile: "))
totalCost = round(miles * pricePerMile,2)

print(f"You will be charged ${totalCost}")


#! /usr/bin/env python3

from sys import argv
from i2c_puppet import I2CPuppet, _REG_RST
from usb import USBError # pyusb module
from os import uname

if uname().sysname == 'Darwin' and uname().machine == 'arm64':
    import usb.backend.libusb1
    usbBackend = usb.backend.libusb1.get_backend(find_library=lambda x: "/opt/homebrew/lib/libusb-1.0.dylib")
else:
    usbBackend = None

if __name__ == "__main__":
    if (len(argv) == 1) or ((len(argv) == 2) and (argv[1] == "uf2")):
        device = I2CPuppet(backend = usbBackend)
        UF2Boot = ((len(argv) == 2) and (argv[1] == "uf2"))

        if UF2Boot:
            device._write_register(_REG_RST, 0x99)
        else:
            try:
                device._read_register(_REG_RST)
            except USBError:
                pass

    else:
        print(f"""
Usage: {argv[0]} [uf2]

Resets the BBQ2KBD. If the optional 'uf2' argument is provided, resets into
programer mode allowing you to mount 'RPI-RP2' to load new uf2 files.
""")


# coding=utf-8
from langconv import Converter
import pandas as pd
import csv
import xlrd
import math

import re
import argparse

def rmSymbol(sent):
    return re.sub("|／\n", "", sent)

if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    parser.add_argument("input_file")
    parser.add_argument("output_directory")
    args = parser.parse_args()

    data = pd.read_excel(args.input_file, sheet_name='測試集', header=0)
    data2 = pd.read_excel(args.input_file, sheet_name='問題', header=0)
    n = len(data)  #5000 測試集內'測試題'與'正確標準問題'
    m = len(data2)  #1000 問題內 '標準問題'
    stdQuestion = data2['標準問題']  #All 標準問題  1000

    # 5000 * 0.2 * 1000 = 100,0000
    with open(args.output_directory + '/test.csv',
              'w',
              newline='',
              encoding="utf8") as testCSV:

        testCSVW = csv.writer(testCSV, lineterminator='\n')
        for i in range(int(n * 0.8), n, 1):
            customerQuestion = data['測試題'][i]
            for j in range(m):
                testCSVW.writerow(
                    [0,
                     rmSymbol(customerQuestion),
                     rmSymbol(stdQuestion[j])])


"""Small helper functions.

:author: Shay Hill
:created: 2022-05-12
"""

from __future__ import annotations

import bisect
from typing import TYPE_CHECKING, Protocol, TypeVar

import numpy as np

if TYPE_CHECKING:
    from simplify_polyline.type_hints import Vector, Vertex, Vertices

_T = TypeVar("_T")

class Comparable(Protocol):
    """Protocol for annotating comparable types."""

    def __lt__(self: _T, other: _T) -> bool:
        ...

_ComparableT = TypeVar("_ComparableT", bound=Comparable)

def remsort(sorted_list: list[_ComparableT], value: _ComparableT) -> None:
    """Remove a value from a sorted list in place.

    This is the inverse of bisect.insort
    """
    index = bisect.bisect_left(sorted_list, value)
    del sorted_list[index]

def get_line_seg_dists(points: Vertices, seg_a: Vertex, seg_b: Vertex) -> Vector:
    """Calculate the Euclidean distance between an array of points to a line segment.

    :param pnt: a point in 2d space
    :param seg_a: beginning of line segment in 2d space
    :param seg_b: end of line segment in 2d space
    :return: a distance from p to segment ab for each p

    by [meowgoesthedog](https://stackoverflow.com/users/10265365/meowgoesthedog)

    https://stackoverflow.com/questions/54442057/calculate-the-euclidian-distance-
    between-an-array-of-points-to-a-line-segment-in
    """
    # Handle case where p is a single point, i.e. 1d array.
    points = np.atleast_2d(points)

    if np.all(seg_a == seg_b):
        return np.linalg.norm(points - seg_a, axis=1)

    # normalized tangent vector
    d = np.divide(seg_b - seg_a, np.linalg.norm(seg_b - seg_a))

    # signed parallel distance components
    s = np.dot(seg_a - points, d)
    t = np.dot(points - seg_b, d)

    # clamped parallel distance
    h = np.maximum.reduce([s, t, np.zeros(len(points))])

    # perpendicular distance component
    c = np.cross(points - seg_a, d)

    # use hypot for Pythagoras to improve accuracy
    return np.hypot(h, c)


import re
from common_libs.ansible_driver.classes.AnsrConstClass import AnscConst
"""
  指定文字列からの変数抜出及び変数具体値置き換モジュール
"""

class WrappedStringReplaceAdmin:
    """
      指定文字列からの変数抜出及び変数具体値置き換えクラス
    """
    def __init__(self, objdbca=None):
        AnscObj = AnscConst()
        self.strReplacedString = ''
        self.UnmngRows = []
        if objdbca:
            # 管理対象外変数取得
            sql = "SELECT VAR_NAME FROM T_ANSC_UNMANAGED_VARLIST WHERE DISUSE_FLAG='0'"
            Rows = objdbca.sql_execute(sql, [])
            for row in Rows:
                self.UnmngRows.append(row["VAR_NAME"])
            self.UnmngRows.extend(AnscObj.Unmanaged_ITA_sp_varlist)

    def stringReplace(self, strSourceString, aryReplaceSource):
        """
          変数を具体値に置き換え
          Arguments:
            strSourceString:(in)   置き換え対象の文字列
            aryReplaceSource:(in)  置換えする変数と具体値の辞書リスト
                                    [{変数名:具体値} , ...]
          Returns:
            True(bool)
        """
        boolRet = True

        strHeadPattern = "{{ "
        strTailPattern = " }}"
        self.strReplacedString = ""

        if strSourceString is None:
            strSourceString = ""

        # 入力データを行単位に分解
        arry_list = strSourceString.split("\n")
        for lineString in arry_list:
            lineString = lineString + "\n"
            if lineString.find("#") == 0:
                self.strReplacedString += lineString
            else:
                # エスケープコード付きの#を一時的に改行に置換
                wstr = lineString
                rpstr = wstr.replace("\\\#", "\n\n")
                # コメント( #)マーク以降の文字列を削除した文字列で変数の具体値置換
                # #の前の文字がスペースの場合にコメントとして扱う
                splitList = rpstr.split(' #')
                lineString = splitList[0]
                splitList.pop(0)
                # 各変数を具体値に置換
                for dectReplace in aryReplaceSource:
                    for strVar, strVal in dectReplace.items():
                        # 具体値が空の場合
                        if not strVal:
                            strVal = ""
                        # 変数を具体値に置換
                        strVarName = strHeadPattern + strVar + strTailPattern
                        strReplace = lineString.replace(strVarName, strVal)
                        lineString = strReplace
                # コメント(#)以降の文字列を元に戻す。
                for strLine in splitList:
                    lineString += " #" + strLine
                # エスケープコード付きの#を元に戻す。
                rpstr = lineString.replace("\n\n", "\#")
                self.strReplacedString += rpstr
        return boolRet

    def getReplacedString(self):
        """
          stringReplaceで変数を具体値に置き換えた結果取得
          Arguments:
            None
          Returns:
            変数を具体値に置き換えた結果文字列
        """
        return self.strReplacedString

    def SimpleFillterVerSearch(self, var_heder_id, strSourceString, mt_varsLineArray, mt_varsArray, arryLocalMnageVars, FillterVars=False):
        """
          指定された文字列から指定された変数を抜出す。
          Arguments:
            var_heder_id:(in)            変数名の先頭文字列　TPF_, ""
            in_strSourceString:(in)      変数を抜出す文字列
            mt_varsLineArray:(out)       抜出した変数リスト       呼出元で空リストで初期化必須
                                         [{行番号:変数名}, ...]
            mt_varsarray:(out)           抜出した変数リスト       呼出元で空リストで初期化必須
                                         [変数名, .....]
            arryLocalMnageVars:               管理対象外変数のリストから除外したい変数リスト
            FillterVars:(in)             Fillter設定されている変数抜出有無(bool)
          Returns:
            True(bool)
        """
        # Fillter定義されている変数も抜出すか判定
        tailmarke = []
        if FillterVars is True:
            tailmarke.append("[\s]}}")
            tailmarke.append("[\s]+\|")
        else:
            tailmarke.append("[\s]}}")

        if strSourceString is None:
            strSourceString = ""

        # 入力データを行単位に分解
        arry_list = strSourceString.split("\n")
        line = 0
        for lineString in arry_list:
            # 行番号
            line += 1

            lineString += "\n"
            # コメント行は読み飛ばす
            if lineString.find("#") == 0:
                continue

            # エスケープコード付きの#を一時的に改行に置換
            wstr = lineString
            # コメント( #)マーク以降の文字列を削除する。
            # #の前の文字がスペースの場合にコメントとして扱う
            splitList = wstr.split(' #')
            strRemainString = splitList[0]
            if len(str.strip(strRemainString)) == 0:
                # 空行は読み飛ばす
                continue
            # 変数名　{{ ???_[a-zA-Z0-9_] | Fillter function }} または{{ ???_[a-zA-Z0-9_] }}　を取出す
            match_list = []
            for key in tailmarke:
                keyFilter = "{{[\s]" + var_heder_id + "[a-zA-Z0-9_]*" + key
                match = re.findall(keyFilter, strRemainString)
                for row in match:
                    # 変数名を抜出す
                    keyFilter = "[\s]" + var_heder_id + "[a-zA-Z0-9_]*" + "[\s]"
                    var_name = re.findall(keyFilter, row)
                    var_name = var_name[0].strip()
                    # 管理対象外変数確認
                    ret = self.chkUnmanagedVarname(var_heder_id, var_name, [])
                    if ret is False:
                        match_list.append(var_name)
            if len(match_list) != 0:
                # 重複値を除外
                unique_set = set(match_list)
            else:
                unique_set = []
            for var_name in unique_set:
                # 変数位置退避
                var_dict = {}
                var_dict[line] = var_name
                mt_varsLineArray.append(var_dict)

                # 変数名の重複チェック
                if mt_varsArray.count(var_name) == 0:
                    mt_varsArray.append(var_name)

            # --- 予約変数　{{ 予約変数 | Fillter function }}　の抜き出し
            for localvarname in arryLocalMnageVars:
                match_list = []
                for key in tailmarke:
                    keyFilter = "{{[\s]" + localvarname + key
                    match = re.findall(keyFilter, strRemainString)

                    for row in match:
                        # 変数名を抜出す
                        keyFilter = "[\s]" + localvarname + "[\s]"
                        var_name = re.findall(keyFilter, row)
                        if len(var_name) == 0:
                            continue
                        match_list.append(var_name[0].strip())

                if len(match_list) != 0:
                    # 重複値を除外
                    unique_set = set(match_list)
                else:
                    unique_set = []

                for var_name in unique_set:

                    # 変数位置退避
                    var_dict = {}
                    var_dict[line] = var_name
                    mt_varsLineArray.append(var_dict)

                    # 変数名の重複チェック
                    if mt_varsArray.count(var_name) == 0:
                        mt_varsArray.append(var_name)

            # 予約変数　{{ 予約変数 | Fillter function }}　の抜き出し ---
        return True, mt_varsLineArray

    def chkUnmanagedVarname(self, var_heder_id, var_name, arryLocalMnageVars=[]):
        """
          指定された変数名が管理対象外か判定する。
          Arguments:
            var_heder_id:(in)  変数名の先頭文字列　VAR_, ""
            var_name: 変数名
            arryLocalMnageVars: 管理対象外変数のリストから除外したい変数リスト
          Returns:
            True:   除外
            False:  適用
        """
        AnscObj = AnscConst()
        # VAR変数以外の場合は除外判定はしない
        if var_heder_id != AnscObj.DF_HOST_VAR_HED:
            return False
        # 除外リストに含まれる変数か判定
        retBool = False
        for key in self.UnmngRows:
            keyFilter = "^" + key + "$"
            match = re.findall(keyFilter, var_name)
            if len(match) != 0:
                # 管理対象外変数のリストから除外したい変数か判定
                if key in arryLocalMnageVars:
                    retBool = False
                else:
                    retBool = True
                break
        return retBool


# coding=utf-8
'''
描述：翻转一个链表
样例：
    样例1:
        对于链表 1->2->3, 翻转链表为 3->2->1
    样例2:
        对于链表 1->2->3->4, 翻转链表为 4->3->2->1
挑战：在原地一次翻转完成
'''

class Solution:
    """
    @param head: n
    @return: The new head of reversed linked list.
    """
    def reverse(self, head):
        # write your code here
        curt = None
        while head != None:
            temp = head.next
            head.next = curt
            curt = head
            head = temp
        return curt


class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution:
    def buildTree(self, preorder,  inorder):
        if not preorder or not inorder:
            return None
        head = TreeNode(preorder[0])
        # 因为没有重复元素，所以可以直接根据值来查找根节点在中序遍历中的位置
        mid = inorder.index(head.val)

        # 左右子树的中序遍历
        in_left = inorder[:mid]
        in_right = inorder[mid+1:]

        # 左右子树的前序遍历
        pre_left = preorder[1:mid+1]
        pre_right = preorder[mid+1:]

        head.right = self.buildTree(pre_right, in_right)
        head.left = self.buildTree(pre_left, in_left)

        return head


import time
from acts import utils
import acts_contrib.test_utils.bt.BleEnum as bleenum
import acts_contrib.test_utils.bt.bt_power_test_utils as btputils
import acts_contrib.test_utils.bt.bt_test_utils as btutils
import acts_contrib.test_utils.power.PowerBTBaseTest as PBtBT
from acts_contrib.test_utils.bt.bt_test_utils import setup_multiple_devices_for_bt_test

BLE_LOCATION_SCAN_ENABLE = 'settings put secure location_mode 3'
EXTRA_CON_TIME = 3
SCAN_TAIL = 5

class PowerBLEconnectionidleTest(PBtBT.PowerBTBaseTest):
    def __init__(self, configs):
        super().__init__(configs)
        req_params = ['BLE_Connection_Priority']
        self.unpack_userparams(req_params)
        for con_priority in self.BLE_Connection_Priority:
            self.generate_test_case_ble_idle_connection(con_priority)

    def setup_class(self):
        super().setup_class()
        self.client_ad = self.android_devices[0]
        utils.set_location_service(self.client_ad, True)
        self.server_ad = self.android_devices[1]
        self.Connection_duration = self.mon_info.duration + self.mon_offset + SCAN_TAIL + EXTRA_CON_TIME
        setup_multiple_devices_for_bt_test(self.android_devices)

    def setup_test(self):
        super().setup_test()
        time.sleep(5)
        self.client_ad.adb.shell(BLE_LOCATION_SCAN_ENABLE)
        btutils.enable_bluetooth(self.client_ad.droid, self.client_ad.ed)
        if not self.server_ad.droid.bluetoothSetLocalName('advertiser'):
            self.log.error("Failed rename the device")
            return False
        self.log.info("Renamed the BT device")
        self.client_ad.droid.goToSleepNow()

    def teardown_test(self):
        self.client_ad.droid.bluetoothFactoryReset()
        btutils.disable_bluetooth(self.client_ad.droid)
        self.server_ad.droid.bluetoothFactoryReset()
        btutils.disable_bluetooth(self.server_ad.droid)

    def generate_test_case_ble_idle_connection(self, con_priority):
        def test_case_fn():
            self.measure_ble_connection_idle_power(con_priority)

        test_case_name = ('test_BLE_{}_IDLE_CONNECTION'.format(
            bleenum.BLEConnectionPriority(con_priority).name))
        setattr(self, test_case_name, test_case_fn)

    def measure_ble_connection_idle_power(self, con_priority):
        btputils.establish_ble_connection(self.client_ad, self.server_ad,
                                          con_priority)
        time.sleep(EXTRA_CON_TIME)
        self.measure_power_and_validate()


#!/usr/bin/env python3
def main():
    N, W = map(int,input().split())

    ws, vs = [], []
    for i in range(N):
        w, v = list(map(int, input().split()))
        ws.append(w)
        vs.append(v)

    # dp[i][j]: i番目までの品物を、価値がjになるように選んだときの最小の重さ。
    vmax = 10**5
    dp = [[float("inf")]*(vmax+1) for _ in range(N+1)]
    dp[0][0] = 0

    for i in range(1, N+1):
        for j in range(vmax+1):
            # 品物iを使う場合
            if j - vs[i-1] >= 0:
                dp[i][j] = min(dp[i][j], dp[i-1][j - vs[i-1]] + ws[i-1])

            # 品物iを使わない場合
            dp[i][j] = min(dp[i][j], dp[i-1][j])

    for i, wmin in enumerate(dp[N]):
        if wmin <= W:
            ans = i

    return ans

print(main())

# not self AC
# pythonだとTLEになる。


import sys

def readFile(FileName):

    with open(FileName) as file:
        data = file.read()
    return data

def writeFile(FileName, text):

    with open(FileName,'w') as file:
        data = file.write(text)

def appendFile(FileName, text):

    with open(FileName,'a') as file:
        data = file.write(text)

def Encrypt(msg, key):
    result=""
    for i in range(len(msg)):
        ch = msg[i]
        if(ch >= 'a' and ch <= 'z'):
            ch = (ord(ch) - ord('a') + key) % 26 + ord('a')
            result += chr(ch)
        elif(ch >= 'A' and ch <= 'Z'):
            ch = (ord(ch) - ord('A') + key) % 26 + ord('A')
            result += chr(ch)

    return result

def Decrypt(msg, key):
    result=""
    for i in range(len(msg)):
        ch = msg[i]
        if(ch >= 'a' and ch <= 'z'):
            ch = (ord(ch) - ord('a') - key + 26) % 26 + ord('a')
            result += chr(ch)
        elif(ch >= 'A' and ch <= 'Z'):
            ch = (ord(ch) - ord('A') - key + 26) % 26 + ord('A')
            result += chr(ch)

    return result

def CryptAnalysis():
    PT=readFile("sample.txt")
    CT=readFile("encrypted.txt")

    for i in range(1,27):
        decrypted=Decrypt(CT,i)
        appendFile("BruteForce.txt",decrypted+"\t "+str(i)+"\n")
        if(decrypted==PT):
            print(f"Hacker will get message in {i} attempt")
            print(decrypted)
            break

def main():
    FileName = input("Enter File Name: ")
    msg = readFile(FileName)

    print("\nPlain Text is :", msg, end='\n')

    key = int(input("Enter the Key: "))

    print("\nEnter your choice \n0. Exit \n1. Encryption \n2. Decryption \n3. Crypt Analysis\n")
    choice = int(input("Enter your choice: "))

    if(choice == 1):
        encrypted = Encrypt(msg, key)
        print("\nEncrypted Message is: ", encrypted, end="\n")
        writeFile('encrypted.txt',encrypted)
    elif(choice == 2):
        msg = readFile("encrypted.txt")
        decrypted = Decrypt(msg, key)
        print("\nDecrypted Message is: ", decrypted, end="\n")
        writeFile('decrypted.txt',decrypted)
    elif(choice==3):
        CryptAnalysis()
    elif(choice==0):
        sys.exit()
    else:
        print("\nSelect Valid Option!")

if __name__ == '__main__':
    main()

INS Practicals/Caesar and Playfair/Security_Ceasar.py


from kevin_toolbox.computer_science.data_structure import Executor
from .along_axis import get_executor_ls_by_block_along_axis

def get_executor_ls_by_block_of_all(factory, chunk_step, need_to_generate, **kwargs):
    """
        通过调用 verification.Factory 中的 generate_by_block() 函数，
            来对整个矩阵，
            生成一系列的执行器 executor_ls，
            每个执行器在被 executor() 调用后都将返回一个数据集
        参数：
            factory:                verification.Factory 实例
            chunk_step:             每个分块的大小
            need_to_generate:       需要生成的字段
                                        （参见 Factory.generate_by_block() 中的介绍）
    """

    width = len(factory.paras["features"])  # 矩阵的宽度
    assert width > 0, \
        Exception("Error: the length of features in the input factory should be larger than 0!")

    # block的数量
    chunk_nums = (width - 1) // chunk_step + 1

    """
    执行器
    """
    executor_ls, size_ls = [], []

    # 对于完整的 block（去除最后一行、列上的block）
    #     将整个block作为一个dataset
    #     dataset_size = chunk_step * chunk_step
    for i in range(chunk_nums - 1):
        i_0 = i * chunk_step
        i_1 = i_0 + chunk_step
        for j in range(chunk_nums - 1):
            j_0 = j * chunk_step
            j_1 = j_0 + chunk_step
            # 计算
            paras = dict(i_0=i_0, i_1=i_1, j_0=j_0, j_1=j_1,
                         pick_triangle=False, need_to_generate=need_to_generate)
            executor_ls.append(Executor(func=factory.generate_by_block,
                                        kwargs=paras))
            size_ls.append(factory.cal_size_of_block(**paras))

    # 对于最后一行
    #     对于完整的矩形有
    #     chunk_step * chunk_step < dataset_size <= chunk_step * (chunk_step + 1)
    # 注意：
    #     对于最后一个可能残缺的矩阵（亦即大小不满足下界），
    #     该部分将与接下来的最后一列的部分头部组成一个dataset
    executor_ls_temp, size_ls_temp = get_executor_ls_by_block_along_axis(factory,
                                                                         i_0=(chunk_nums - 1) * chunk_step,
                                                                         i_1=width,
                                                                         j_0=0,
                                                                         j_1=width,
                                                                         axis_to_split="j", size_upper=size_upper,
                                                                         need_to_generate=need_to_generate)
    executor_ls.extend(executor_ls_temp)
    size_ls.extend(size_ls_temp)

    # 对于最后一列
    #     第一个矩形将与前面残缺的部分整合为一个dataset，该矩形的行数将根据缺少部分的数量计算得到，从而保证
    #     chunk_step * chunk_step <= dataset_size <= chunk_step * (chunk_step + 1)
    #     接下来的矩形将调整行数以尽量贴近上界，
    #     对于完整的矩形有
    #     chunk_step * chunk_step < dataset_size <= chunk_step * (chunk_step + 1)
    #     对于最后一个可能残缺的矩阵，有
    #     dataset_size <= chunk_step * (chunk_step + 1)
    # 这里承接上面的  res
    if chunk_nums > 1:
        executor_ls_temp, size_ls_temp = get_executor_ls_by_block_along_axis(factory,
                                                                             i_0=0,
                                                                             i_1=(chunk_nums - 1) * chunk_step,
                                                                             j_0=(chunk_nums - 1) * chunk_step,
                                                                             j_1=width,
                                                                             axis_to_split="i", size_upper=size_upper,
                                                                             need_to_generate=need_to_generate,
                                                                             pre_executor=executor_ls.pop(-1),
                                                                             pre_size=size_ls.pop(-1))
        executor_ls.extend(executor_ls_temp)
        size_ls.extend(size_ls_temp)

    # 综合而言，
    #     除最后一个dataset以外，都有
    #     chunk_step * chunk_step <= dataset_size <= chunk_step * (chunk_step + 1)
    #     最后一个dataset可能是残缺的，有
    #     0 < dataset_size <= chunk_step * (chunk_step + 1)
    return executor_ls, size_ls