# -*- coding: utf-8 -*-
"""
***************************************************************************
*   Copyright (c) 2013, 2014, 2015                                        *
*   Original code by:                                                     *
*   Ulrich Brammer <ulrich1a[at]users.sourceforge.net>                    *
*                                                                         *
*   This file is a supplement to the FreeCAD CAx development system.      *
*                                                                         *
*   This program is free software; you can redistribute it and/or modify  *
*   it under the terms of the GNU Lesser General Public License (LGPL)    *
*   as published by the Free Software Foundation; either version 2 of     *
*   the License, or (at your option) any later version.                   *
*   for detail see the LICENCE text file.                                 *
*                                                                         *
*   This software is distributed in the hope that it will be useful,      *
*   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
*   GNU Library General Public License for more details.                  *
*                                                                         *
*   You should have received a copy of the GNU Library General Public     *
*   License along with this macro; if not, write to the Free Software     *
*   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  *
*   USA                                                                   *
*                                                                         *
***************************************************************************
"""
from screw_maker import *

def makeSetScrew(self, fa):
    """Creates a set screw or grub screw

    Supported types:
    - ISO 4026 Hexagon socket set screws with flat point
    - ISO 4027 Hexagon socket set screws with cone point
    - ISO 4028 Hexagon socket set screws with dog point
    - ISO 4029 Hexagon socket set screws with cup point
    - ASMEB18.3.5A UNC Hexagon socket set screws with flat point
    - ASMEB18.3.5B UNC Hexagon socket set screws with cone point
    - ASMEB18.3.5C UNC Hexagon socket set screws with dog point
    - ASMEB18.3.5D UNC Hexagon socket set screws with cup point
    """
    SType = fa.type
    length = fa.calc_len
    if SType == 'ISO4026' or SType == 'ISO4027' or SType == 'ISO4029':
        P, t, dp, dt, df, s = fa.dimTable
    elif SType == 'ISO4028':
        P, t, dp, df, z, s = fa.dimTable
    elif SType[:-1] == 'ASMEB18.3.5':
        P, t, dp, dt, df, s, z = fa.dimTable
    dia = self.getDia(fa.calc_diam, False)
    # generate the profile of the set-screw
    fm = FSFaceMaker()
    if SType == 'ISO4026' or SType == 'ASMEB18.3.5A':
        fm.AddPoint(0, 0)
        fm.AddPoint(df / 2, 0)
        fm.AddPoint(dia / 2, -1 * ((dia - df) / 2))
        fm.AddPoint(dia / 2, -1 * length + ((dia - dp) / 2))
        fm.AddPoint(dp / 2, -1 * length)
        fm.AddPoint(0, -1 * length)
    elif SType == 'ISO4027' or SType == 'ASMEB18.3.5B':
        fm.AddPoint(0, 0)
        fm.AddPoint(df / 2, 0)
        fm.AddPoint(dia / 2, -1 * ((dia - df) / 2))
        fm.AddPoint(dia / 2, -1 * length + ((dia - dt) / 2))
        fm.AddPoint(dt / 2, -1 * length)
        fm.AddPoint(0, -1 * length)
    elif SType == 'ISO4028' or SType == 'ASMEB18.3.5C':
        # the shortest available dog-point set screws often have
        # shorter dog-points. There  is not much hard data accessible for this
        # approximate by halving the dog length for short screws
        if length < 1.5 * dia:
            z = z * 0.5
        fm.AddPoint(0, 0)
        fm.AddPoint(df / 2, 0)
        fm.AddPoint(dia / 2, -1 * ((dia - df) / 2))
        fm.AddPoint(dia / 2, -1 * length + ((dia - dp) / 2 + z))
        fm.AddPoint(dp / 2, -1 * length + z)
        fm.AddPoint(dp / 2, -1 * length)
        fm.AddPoint(0, -1 * length)
    elif SType == 'ISO4029' or SType == 'ASMEB18.3.5D':
        fm.AddPoint(0, 0)
        fm.AddPoint(df / 2, 0)
        fm.AddPoint(dia / 2, -1 * ((dia - df) / 2))
        fm.AddPoint(dia / 2, -1 * length + ((dia - dp) / 2))
        fm.AddPoint(dp / 2, -1 * length)
        fm.AddPoint(0, -1 * length + math.sqrt(3) / 6 * dp)
    screw = self.RevolveZ(fm.GetFace())
    recess = self.makeHexRecess(s, t - 1, True)
    screw = screw.cut(recess)
    # produce a modelled thread if necessary
    if fa.thread:
        thread_cutter = self.CreateThreadCutter(dia, P, length)
        screw = screw.cut(thread_cutter)
    return screw


from datetime import datetime, timedelta, time
import logging
import sqlite3
import time as tm
import warnings
import pytz

from telegram import Update, ReplyKeyboardMarkup, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import (CommandHandler, Filters, MessageHandler, Filters,
                          Updater, CallbackContext, CallbackQueryHandler)

import settings

cold_last_value = 0
hot_last_value = 0
was_sent = False
keyboard_list = [
    ['/help', '/consumption', '/stat', '/subscribe']
]
keyboard_stat_list = [
    ['Month', 'Week', 'Graph']
]

# Logging settings
logging.basicConfig(handlers=[logging.FileHandler('bot.log', 'w', 'utf-8')],
                    format='%(asctime)s - %(levelname)s - %(message)s',
                    level=logging.INFO
                    )

def main():
    '''
    Main function.
    '''
    mybot = Updater(settings.API_KEY)
    logging.info('Bot is starting...')
    dp = mybot.dispatcher
    dp.add_handler(CommandHandler("help", talk_greet_user))
    # dp.add_handler(CommandHandler("sql", read_water_cons))
    dp.add_handler(CommandHandler("stat", get_stats))
    dp.add_handler(CommandHandler("subscribe", subscribe))
    dp.add_handler(CommandHandler('consumption', read_water_cons))
    # dp.add_handler(RegexHandler('^(Stat)$', get_stats))
    # dp.add_handler(RegexHandler('^(Month)$', get_month_stats))
    # dp.add_handler(RegexHandler('^(Week)$', get_week_stats))
    dp.add_handler(MessageHandler(Filters.regex(r'^(Month)$'), get_month_stats))
    dp.add_handler(MessageHandler(Filters.regex(r'^(Week)$'), get_week_stats))
    dp.add_handler(MessageHandler(Filters.text & ~Filters.command, talk_to_me))
    dp.add_handler(CallbackQueryHandler(set_was_sent, pattern="^(sent|)"))

    mybot.job_queue.run_repeating(check_health, interval=settings.HEALTH_CHECK_TIME_SEC)
    mybot.job_queue.run_daily(get_cons_update, time=time(hour=settings.SEND_UPDATE_HOUR, tzinfo=pytz.timezone('Europe/Moscow')))

    mybot.start_polling()
    mybot.idle()

def check_health(context: CallbackContext):
    '''
    Checks that values in database are actual.
    '''
    logging.info('Launching health check function.')
    cur_date = datetime.now()
    cold_date, cold_value, hot_date, hot_value = get_water(datetime.now())
    sec_from_last_cold_date = cur_date - cold_date
    sec_from_last_hot_date = cur_date - hot_date
    answer = ''
    if sec_from_last_cold_date.total_seconds() > settings.HEALTH_CHECK_DELAY_THRESHOLD:
        answer = 'WARNING!\nХОЛОДНАЯ вода обновлено более 2 часов назад\n({0}, значение: {1})'\
            .format(cold_date.strftime('%d.%m.%Y %H:%M:%S'), cold_value)
    if sec_from_last_hot_date.total_seconds() > settings.HEALTH_CHECK_DELAY_THRESHOLD:
        answer += '\nГОРЯЧАЯ вода обновлено более 2 часов назад\n({0}, значение: {1})'\
            .format(hot_date.strftime('%d.%m.%Y %H:%M:%S'), hot_value)
    if answer:
        logging.info(answer)
        subscribers_list = []

        connection = sqlite3.connect(settings.DB_PATH)
        cursor = connection.cursor()
        cursor.execute("SELECT ID FROM SUBSCRIBERS ORDER BY 1 ASC")
        rows = cursor.fetchall()
        for row in rows:
            subscribers_list.append(row[0])
        for client_id in subscribers_list:
            context.bot.sendMessage(chat_id=client_id, text=answer)

        cursor.close()
        connection.close()

    else:
        logging.info('Health check - OK!')

def get_cons_update(context: CallbackContext):
    '''
    Periodic function to get latest info about water consumption.
    '''
    logging.info('Launching getting consumption from database.')
    cur_date = datetime.now()
    global cold_last_value
    global hot_last_value
    global was_sent
    if cur_date.day in settings.SEND_UPDATE_DAYS_LIST and was_sent == False:
        cold_date, cold_value, hot_date, hot_value = get_water(datetime.now())
        if cold_value != cold_last_value or hot_value != hot_last_value:
            answer = 'ХОЛОДНАЯ вода:\nОбновлено: {0}, значение: {1}'\
                .format(cold_date.strftime('%d.%m.%Y %H:%M:%S'), cold_value)
            answer += '\nГОРЯЧАЯ вода:\nОбновлено: {0}, значение: {1}'\
                .format(hot_date.strftime('%d.%m.%Y %H:%M:%S'), hot_value)
            logging.info(answer)
            subscribers_list = []

            connection = sqlite3.connect(settings.DB_PATH)
            cursor = connection.cursor()
            cursor.execute("SELECT ID FROM SUBSCRIBERS ORDER BY 1 ASC")
            rows = cursor.fetchall()
            for row in rows:
                subscribers_list.append(row[0])
            for client_id in subscribers_list:
                context.bot.sendMessage(chat_id=client_id, text=answer)
                tm.sleep(0.5)
                context.bot.sendMessage(chat_id=client_id, text='Отправьте данные на сайте:\nhttps://mos.ru/services/pokazaniya-vodi-i-tepla/new/\
                                            \n\nДанные отправлены?', reply_markup=cons_send_inline_keyboard())

            cold_last_value = cold_value
            hot_last_value = hot_value

            cursor.close()
            connection.close()

        else:
            logging.info('Nothing changed.')
    elif cur_date.day not in settings.SEND_UPDATE_DAYS_LIST:
        was_sent = False
        logging.info('Consumption data will be send on dates: {}.'.format(settings.SEND_UPDATE_DAYS_LIST))

def talk_greet_user(update: Update, context: CallbackContext):
    '''
    /help handler function.
    Greets user and provide to him breaf info about bot usage.
    '''
    text = 'Command /help launched.'
    logging.info(text)
    # update.message.reply_text('Бот, кажется, работает...')
    my_keyboard = ReplyKeyboardMarkup(keyboard_list, resize_keyboard=True)
    update.message.reply_text('/consumption - последние данные о потреблении;\n/stat - статистика потребления за период; \
        \n/subscribe - подписаться на автоматические уведомления о потреблении воды.', reply_markup=my_keyboard)

def get_stats(update: Update, context: CallbackContext):
    '''
    /stat handler function.
    Asks user to select period for water consumption.
    '''
    text = 'Command /stat launched.'
    logging.info(text)
    my_keyboard_stat = ReplyKeyboardMarkup(keyboard_stat_list, resize_keyboard=True)
    update.message.reply_text('Выберите период', reply_markup=my_keyboard_stat)

def get_month_stats(update: Update, context: CallbackContext):
    '''
    Sends to user month stat of water consumption.
    '''
    text = 'Month statistics launched.'
    logging.info(text)
    cold_date, cold_value, hot_date, hot_value = get_water(datetime.now(), 30)
    # print('Month cons: ', cold_value, hot_value)
    answer = 'Сумма потребления за месяц:\nхолодная: {0},\nгорячая: {1}.'.format(cold_value, hot_value)
    logging.info(answer)
    my_keyboard = ReplyKeyboardMarkup(keyboard_list, resize_keyboard=True)
    update.message.reply_text(answer, reply_markup=my_keyboard)

def get_week_stats(update: Update, context: CallbackContext):
    '''
    Sends to user week stat of water consumption.
    '''
    text = 'Week statistics launched.'
    logging.info(text)
    cold_date, cold_value, hot_date, hot_value = get_water(datetime.now(), 7)
    # print('Week cons: ', cold_value, hot_value)
    answer = 'Сумма потребления за неделю:\nхолодная: {0},\nгорячая: {1}.'.format(cold_value, hot_value)
    logging.info(answer)
    my_keyboard = ReplyKeyboardMarkup(keyboard_list, resize_keyboard=True)
    update.message.reply_text(answer, reply_markup=my_keyboard)

def select_max_value(target_date):
    '''
    Get latest amount of water usage and date of last measures.
    '''
    connection = sqlite3.connect(settings.DB_PATH)
    cursor = connection.cursor()
    # data_items=[]
    logging.debug('SQL called. Target date: {}'.format(target_date))
    cursor.execute('WITH \
        max_cold AS (SELECT MAX(DATE) AS DATE_COLD, VALUE AS VALUE_COLD \
            FROM "WATER_VW" WHERE WATER_TYPE = 1 AND DATE <= "{0}"), \
                max_hot AS (SELECT MAX(DATE) AS DATE_HOT, VALUE AS VALUE_HOT \
                    FROM "WATER_VW" WHERE WATER_TYPE = 2 AND DATE <= "{0}") \
                        SELECT * FROM max_cold, max_hot  \
                                        '.format(target_date))
    rows = cursor.fetchall()
    cursor.close()
    connection.close()
    # print(rows)
    cold_date, cold_value, hot_date, hot_value = rows[-1]
    return cold_date, cold_value, hot_date, hot_value

def get_water(date, delta=0):
    '''
    Calculates consumption for a given period: [date-delta; date].
    Returns consumption for both cold and hot water for analiyzed period and dates for last measures.
    '''
    end_period_date = datetime.strftime(date, '%Y-%m-%dT%H:%M:%S')
    cold_date_1, cold_value_1, hot_date_1, hot_value_1 = select_max_value(end_period_date)
    logging.info(str(cold_date_1) + '; ' + str(cold_value_1) + '; ' + str(hot_date_1) + '; ' + str(hot_value_1))
    # print(cold1, hot1, date1)
    cold_value_2, hot_value_2 = 0, 0

    if delta > 0:
        start_period_date = datetime.strftime(date-timedelta(days=delta), '%Y-%m-%dT%H:%M:%S')
        cold_date_2, cold_value_2, hot_date_2, hot_value_2 = select_max_value(start_period_date)
        logging.info(str(cold_date_2) + '; ' + str(cold_value_2) + '; ' + str(hot_date_2) + '; ' + str(hot_value_2))

    return datetime.strptime(cold_date_1, '%Y-%m-%dT%H:%M:%S.%fZ'), cold_value_1 - cold_value_2, datetime.strptime(hot_date_1, '%Y-%m-%dT%H:%M:%S.%fZ'), hot_value_1 - hot_value_2

def talk_to_me(update: Update, context: CallbackContext):
    '''
    Returns to user his own's message.
    '''
    user_text = update.message.text
    # print(user_text)
    logging.info(user_text)
    update.message.reply_text(user_text)

def read_water_cons(update: Update, context: CallbackContext):
    '''
    /consumption handler function.
    Sends to user latest data abust consumption and date of last measures.
    '''
    text = 'Command /consumption launched.'
    logging.info(text)
    cold_date, cold_value, hot_date, hot_value = get_water(datetime.now())
    answer = 'ХОЛОДНАЯ вода:\nОбновлено: {0}, значение: {1}'\
        .format(cold_date.strftime('%d.%m.%Y %H:%M:%S'), cold_value)
    answer += '\nГОРЯЧАЯ вода:\nОбновлено: {0}, значение: {1}'\
        .format(hot_date.strftime('%d.%m.%Y %H:%M:%S'), hot_value)
    logging.info(answer)
    subscribers_list = []
    connection = sqlite3.connect(settings.DB_PATH)
    cursor = connection.cursor()
    cursor.execute("SELECT ID FROM SUBSCRIBERS ORDER BY 1 ASC")
    rows = cursor.fetchall()
    for row in rows:
        subscribers_list.append(row[0])
    for client_id in subscribers_list:
        context.bot.sendMessage(chat_id=client_id, text=answer)

    cursor.close()
    connection.close()

def subscribe(update: Update, context: CallbackContext):
    '''
    /subscribe handler function.
    Adds user to subscribers list.
    '''
    text = 'Command /subscribe launched.'
    logging.info(text)
    subscribers_list = []
    connection = sqlite3.connect(settings.DB_PATH)
    cursor = connection.cursor()
    cursor.execute("SELECT ID FROM SUBSCRIBERS ORDER BY 1 ASC")
    rows = cursor.fetchall()
    for row in rows:
        subscribers_list.append(row[0])

    if update.message.chat_id not in subscribers_list:
        cursor.execute('INSERT INTO SUBSCRIBERS VALUES({}, "{}")'.format(update.message.chat_id, str(datetime.now())))
        connection.commit()
        logging.info('Добавлен новый chat_id: {}, от {}'.format(update.message.chat_id, str(datetime.now())))
        update.message.reply_text('Вы добавлены в список рассылки уведомлений о новых данных потребления воды.')
    else:
        update.message.reply_text('Вы уже в списке рассылки о новых данных потребления воды.')

    cursor.close()
    connection.close()

def cons_send_inline_keyboard():
    inlinekeyboard = [
        [
            InlineKeyboardButton('Да', callback_data='sent|1'),
            InlineKeyboardButton('Нет', callback_data='sent|0')
        ]
    ]
    return InlineKeyboardMarkup(inlinekeyboard)

def set_was_sent(update: Update, context: CallbackContext):
    global was_sent
    update.callback_query.answer()
    callback_type, was_sent_str = update.callback_query.data.split("|")
    was_sent = bool(int(was_sent_str))
    if was_sent:
        text = 'Данные отправлены на mos.ru'
        logging.info('Variable was_sent is set to True.')
    else:
        text = 'Данные НЕ отправлены на mos.ru'
        logging.info('Variable was_sent is set to False.')
    # update.callback_query.edit_message_caption(caption=text)
    update.callback_query.edit_message_text(text=text, reply_markup=None)

if __name__ == '__main__':
    main()


def makeprefixsum(nums):
    prefixsum = [0] * (len(nums) + 1)
    for i in range(1, len(nums)+1):
        prefixsum[i] = prefixsum[i-1] + nums[i-1]
    return prefixsum

def rsq(prefixsum, l, r): # Range Sum Query
    return prefixsum[r] - prefixsum[l]

def countzeroes(nums, l, r):
    cnt = 0 # complexity O(NM) N - lenght of array, M - number of requests
    for i in range(i, r):
        if nums[i] == 0:
            cnt += 1
    return cnt

# Faster solution O(N+M)
def makeprefixsum(nums):
    prefixsum = [0] * (len(nums) + 1)
    for i in range(1, len(nums)+1):
        if nums[i-1] == 0:
            prefixsum[i] = prefixsum[i-1] + 1
        else:
            prefixsum[i] = prefixsum[i-1]
    return prefixsum

def countzeroes(nums, l, r):
    return prefixsum[r] - prefixsum[l]

# O(n**3)
def countzerossumranges(nums):
    cntranges = 0
    for i in range(len(nums)): # Left boundary
        for j in range(i+1, len(nums)+1): # Right boundary
            rangesum = 0
            for k in range(i, j):
                rangesum += nums[k]
            if rangesum == 0:
                cntranges += 1
    return cntranges

# O(n)
def countprefixsum(nums):
    prefixsumbyvalue = {0: 1}
    nowsum = 0
    for now in nums:
        nowsum += now
        if nowsum not in prefixsumbyvalue:
            prefixsumbyvalue[nowsum] = 0
        prefixsumbyvalue[nowsum] += 1
    return prefixsumbyvalue

def countzerossumrange(prefixsumbyvalue):
    cntranges = 0
    for nowsum in prefixsumbyvalue:
        cntsum = prefixsumbyvalue[nowsum]
        cntranges += cntsum * (cntsum - 1) // 2
    return cntranges

# O(n*n)
def cntpairswithdiffgtk(sortednums, k):
    contpairs = 0
    for first in range(len(sortednums)):
        for last in range(first, len(sortednums)):
            if sortednums[last] - sortednums[first] > k:
                contpairs += 1
    return contpairs
# cntpairswithdiffgtk([1,3,5,6], 3) -> 2

# O(n)
def cntpairswithdiffgtk(sortednums, k):
    contpairs = 0
    last = 0
    for first in range(len(sortednums)):
        while last < len(sortednums) and sortednums[last] - sortednums[first] <= k:
            last += 1
        contpairs += len(sortednums) - last
    return contpairs

def merge(nums1, nums2):
    merged = [0] * len(nums1) + [0] * len(nums2)
    first1 = first2 = 0
    inf = max(nums1[-1], nums2[-1]) + 1
    nums1.append(inf)
    nums2.append(inf)
    for k in range(len(nums1) + len(nums2) - 2):
        if nums1[first1] <= nums2[first2]:
            merged[k] = nums1[first1]
            first1 += 1
        else:
            merged[k] = nums2[first2]
            first2 += 1
    nums1.pop()
    nums2.pop()
    return merged

# O(N+M)
def mergebetter(nums1, nums2):
    merged = [0] * len(nums1) + [0] * len(nums2)
    first1 = first2 = 0
    for k in range(len(nums1) + len(nums2)):
        if (first1 != len(nums1)) and (first2 == len(nums2) or nums1[first1] < nums2[first2]):
            merged[k] = nums1[first1]
            first1 += 1
        else:
            merged[k] = nums2[first2]
            first2 += 1
    return merged


nums = [str(x) for x in range(10) if x != 1] + ['j', 'q', 'k', 'a']
suits = ['d', 'h', 'c', 's']

out = []
label = 0
for s in suits:
    for n in nums:
        out.append(s + n)
        print(f"{label}: {s + n}")
        label += 1


"""
Overview:
    AI image corrupt evaluation metrics.
"""
import json
from functools import lru_cache
from typing import Tuple, Optional, Mapping

import numpy as np
from PIL import Image
from huggingface_hub import hf_hub_download
from imgutils.data import rgb_encode, ImageTyping, load_image
from imgutils.utils import open_onnx_model

from ..utils import ImagesTyping, load_images, tqdm

_DEFAULT_MODEL_NAME = 'caformer_s36_v0_focal'

@lru_cache()
def _open_anime_aicop_model(model_name: str):
    """
    Open the AI image corrupted detection model.

    This function downloads and opens the AI image corrupted detection model specified by the given model name using Hugging Face Hub.

    :param model_name: The name of the AI image corrupted detection model.
    :type model_name: str

    :return: The opened AI image corrupted detection model.
    :rtype: Model
    """
    return open_onnx_model(hf_hub_download(
        f'deepghs/ai_image_corrupted',
        f'{model_name}/model.onnx',
    ))

@lru_cache()
def _open_anime_aicop_meta(model_name: str):
    """
    Open the meta information of the AI image corrupted detection model.

    This function downloads and opens the meta information of the AI image corrupted detection model specified by the given model name using Hugging Face Hub.

    :param model_name: The name of the AI image corrupted detection model.
    :type model_name: str

    :return: The opened meta information of the AI image corrupted detection model.
    :rtype: dict
    """
    with open(hf_hub_download(
            f'deepghs/ai_image_corrupted',
            f'{model_name}/meta.json',
    ), 'r', encoding='utf-8') as f:
        return json.load(f)

@lru_cache()
def _open_anime_aicop_labels(model_name: str):
    """
    Open the labels of the AI image corrupted detection model.

    This function opens the labels of the AI image corrupted detection model specified by the given model name.

    :param model_name: The name of the AI image corrupted detection model.
    :type model_name: str

    :return: The labels of the AI image corrupted detection model.
    :rtype: List[str]
    """
    return _open_anime_aicop_meta(model_name)['labels']

def _img_encode(image: Image.Image, size: Tuple[int, int] = (384, 384),
                normalize: Optional[Tuple[float, float]] = (0.5, 0.5)):
    """
    Encode the image for AI image corrupted detection.

    This function resizes and encodes the image for AI image corrupted detection.

    :param image: The input image.
    :type image: Image.Image
    :param size: The target size for encoding. Default is (384, 384).
    :type size: Tuple[int, int]
    :param normalize: The normalization parameters. Default is (0.5, 0.5).
    :type normalize: Optional[Tuple[float, float]]

    :return: The encoded image data.
    :rtype: np.ndarray
    """
    image = image.resize(size, Image.BILINEAR)
    data = rgb_encode(image, order_='CHW')

    if normalize is not None:
        mean_, std_ = normalize
        mean = np.asarray([mean_]).reshape((-1, 1, 1))
        std = np.asarray([std_]).reshape((-1, 1, 1))
        data = (data - mean) / std

    return data.astype(np.float32)

def get_ai_corrupted(image: ImageTyping, model_name: str = _DEFAULT_MODEL_NAME) -> Mapping[str, float]:
    """
    Get AI image corrupted detection scores for an image.

    This function calculates AI image corrupted detection scores for a given image using the specified model.

    :param image: The input image.
    :type image: ImageTyping
    :param model_name: The name of the AI image corrupted detection model. Default is 'caformer_s36_v0_focal'.
    :type model_name: str

    :return: A dictionary containing the corrupted score.
    :rtype: Mapping[str, float]
    """
    image = load_image(image, force_background='white', mode='RGB')
    input_ = _img_encode(image)[None, ...]
    output, = _open_anime_aicop_model(model_name).run(['output'], {'input': input_})
    return dict(zip(_open_anime_aicop_labels(model_name), output[0].tolist()))

class AICorruptMetrics:
    """
    Class for calculating an AI image corruptness score.

    The `AICorruptMetrics` class allows you to calculate an AI image corruptness score using the AI image corrupted detection model.

    :param model_name: The name of the AI image corrupted detection model. Default is 'caformer_s36_v0_focal'.
    :type model_name: str
    :param silent: If True, suppresses progress bars and additional output during calculation.
    :type silent: bool
    :param tqdm_desc: Description for the tqdm progress bar during calculation.
    :type tqdm_desc: str
    """

    def __init__(self, model_name: str = _DEFAULT_MODEL_NAME,
                 silent: bool = False, tqdm_desc: str = None):
        self._model_name = model_name
        self.silent = silent
        self.tqdm_desc = tqdm_desc or self.__class__.__name__

    def score(self, images: ImagesTyping, silent: bool = None):
        """
        Calculate the AI image corruptness score for a set of images.

        This method calculates the AI image corruptness score for a set of input images using the AI image corrupted detection model.

        :param images: The set of input images for calculating the AI image corruptness score.
        :type images: ImagesTyping
        :param silent: If True, suppresses progress bars and additional output during calculation.
        :type silent: bool

        :return: The AI image corruptness score.
        :rtype: float
        """
        image_list = load_images(images)
        if not image_list:
            raise FileNotFoundError(f'Images for calculating AI corrupt score not provided - {images}.')

        scores = np.array([
            get_ai_corrupted(image, model_name=self._model_name)['corrupted']
            for image in tqdm(image_list, silent=self.silent if silent is None else silent, desc=self.tqdm_desc)
        ])
        return 1.0 - scores.mean().item()


import sqlite3

connection = sqlite3.connect("books.db")

c = connection.cursor()

print("\n ***** All books in database *****\n")
c.execute("SELECT * FROM books")

# Returns data in tuple
# for result in c:
#     print(result)

# Returns data in list
print(c.fetchall())

print("\n ***** 4 or more rated books *****\n")
c.execute("SELECT * FROM books WHERE rating >= 4")
print(c.fetchall())

connection.commit()
connection.close()


from django.conf.urls import patterns, include, url

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('PyTweetApp.views',
	url(r'^admin', include(admin.site.urls)),
	url(r'^SignUp$', 'signup'),
	url(r'^LogOut$', 'logout'),
	url(r'^TweetLine$', 'tweetline'),
	url(r'^Hashtag$', 'hashtaglist'),
	url(r'^Hashtag/(?P<hashtag>.+)$', 'hashtag', name="hashtag"),
	url(r'^Retweet/(?P<idtweet>.+)$', 'retweet', name="retweet"),
	url(r'^Follow/(?P<username>.+)$', 'follow', name="follow"),
	url(r'^Unfollow/(?P<username>.+)$', 'unfollow', name="unfollow"),
	url(r'^(?P<username>.+)/Followers$', 'followerlist', name="followers"),
	url(r'^(?P<username>.+)/Followed$', 'followedlist', name="followed"),
	url(r'^(?P<username>.+)$', 'profil'),
	url(r'^$', 'home', name="home"),
)


# -*- coding: utf-8 -*-
"""
Created on Sun Mar  8 12:58:48 2020

@author: cheerag.verma
"""

"""
Problem : Given a string, remove all the consecutive duplicates that are present in the given string.
            That means, if 'aaa' is present in the string then it should become 'a' in the output string

Input : aabccbaa
Output: abcba

"""

def removeConsecutiveDuplicates(str_):
    arr=[]
    for i in str_:
        arr.append(i)

    if len(arr)>1:
        i = 0
        j = 1
        new_arr = []
        while i < len(arr) and j< len(arr):

            if arr[i] !=arr[j]:
                new_arr.append(arr[i])
                i = j
                j+=1
                #print(j)
                if j == len(arr):
                    #print("asdf")
                    new_arr.append(arr[i])
                    break

            elif arr[i] == arr[j]:
                j+=1

                if j == len(arr):
                    new_arr.append(arr[i])
                    break

        return new_arr

    else:
        return str_

inputString = input()
result = removeConsecutiveDuplicates(inputString)
for data in result:
    print("".join(data),end = "")


##Definimos el precio regular

precio = 4500

dia_semana = input('Introduzca el dia de la semana: ')

## Si es miercoles, redefine el precio a la mitad
if dia_semana == 'miercoles' or 'miércoles':
    precio = precio/2

#Imprime precio
print(precio)


from flask import Flask, render_template, request,redirect,url_for
import pyodbc
app = Flask(__name__)

def connection():
    s = 'NITRVSP158LT' #Your server name
    d = 'bidDB'
    u = 'REVENUEMED\haji001' #Your login
    p = 'Guide@297105' #Your login password
    cstr = 'DRIVER={ODBC Driver 17 for SQL Server};SERVER='+s+';DATABASE='+d+';trusted_connection=yes;UID='+u+';PWD='+ p
    conn = pyodbc.connect(cstr)
    return conn

@app.route('/')
def home():
    return render_template('bid_main.html')

@app.route('/auction-details/<int:course_id>',methods=['POST', 'GET'])
def auction(course_id):
    auctions = []
    conn = connection()
    cursor = conn.cursor()
    if request.method == 'GET':
        cursor.execute("select * from course where course_id=?",course_id)
        for row in cursor.fetchall():
            auctions.append({"course_id": row[0], "c_title": row[1], "c_description": row[2], "image_url": row[3]})
        conn.close()
    return render_template('bid_auctiondetails.html',auctions = auctions )

@app.route('/auction-details/vendor-registration-form/<int:course_id>',methods=['POST', 'GET'])
def form(course_id):
    forms = []
    conn = connection()
    cursor = conn.cursor()
    if request.method == 'GET':
        cursor.execute("select * from course where Course_id=?",course_id)
        for row in cursor.fetchall():
            forms.append({"course_id": row[0], "c_title": row[1], "c_description": row[2], "image_url": row[3]})
        conn.close()
        return render_template('bid_v_form.html',forms = forms)

    if request.method == 'POST':
        V_title = request.form["V_title"]
        Vendor_ID = request.form["Vendor_ID"]
        Vendor_Name = request.form["Vendor_Name"]
        Duration = request.form["Duration"]
        Experience = request.form["Experience"]
        Expected_Cost = request.form["Expected_Cost"]
        Demo = request.form["Demo"]
        Skills = request.form["Skills"]
        Bid_ID = request.form["BID_ID"]
        Description = request.form["Description"]
        conn = connection()
        cursor = conn.cursor()
        cursor.execute("INSERT INTO dbo.vendor(V_title, Vendor_ID, Vendor_Name, Duration, Experience, Expected_Cost, Demo, Skills, BID_ID, Description) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", V_title, Vendor_ID, Vendor_Name, Duration, Experience, Expected_Cost, Demo, Skills, Bid_ID, Description)
        conn.commit()
        conn.close()
        return render_template("bid_v_dashboard.html")

@app.route('/vendor-dashboard')
def vdash():
    vds = []
    conn = connection()
    cursor = conn.cursor()
    cursor.execute("SELECT V_title,Expected_Cost,Duration FROM dbo.vendor")
    for row in cursor.fetchall():
        vds.append({"V_title": row[0], "Expected_Cost": row[1],"Duration": row[2]})
        # vendors.append({"title": row[0], "duration": row[1], "experience": row[2], "expectedCost": row[3],"demo": row[4], "skills": row[5], "bidno": row[6], "description": row[7]})
    conn.close()
    return render_template("bid_v_dashboard.html",vds=vds)

@app.route('/approver-active-bid')
def activebid():
    return  render_template('bid_approver_activeBid.html')

@app.route('/approver-dashboard')
def adash():
    return  render_template('bid_approver_dashboard.html')

if __name__=='__main__':
    app.run(debug=True)


with open('input2.txt', 'r') as f:
    input_list = f.read()

input_list = input_list.replace("\n", "").split(',')

print(input_list)

def format_input(inp):
    inp = inp.split(" ")
    minmax = inp[0].split('-')
    mini, maxi = int(minmax[0]), int(minmax[1])
    letter = inp[1][0]
    string = inp[2]

    return {'min': mini, 'max': maxi, 'letter': letter, 'string': string}

valid_count = 0
# Part 1
for i in range(len(input_list)):
    curr = input_list[i]
    obj = format_input(curr)
    if obj['string'].count(obj['letter']) <= obj['max'] and obj['string'].count(obj['letter']) >= obj['min']:
        valid_count += 1
print(valid_count)
valid_count = 0
# Part 2
for i in range(len(input_list)):
    curr = input_list[i]
    obj = format_input(curr)
    if bool(obj['string'][obj['min']-1] == obj['letter']) != bool(obj['string'][obj['max']-1] == obj['letter']):
        valid_count += 1

print(valid_count)


g_posTypes = None
g_fullWords = None
g_stemmedWords = None

def _read_data_set():
    global g_posTypes
    global g_fullWords
    global g_stemmedWords
    g_posTypes = set()
    g_fullWords = dict()
    g_stemmedWords = dict()

    file = open("all.conllu", "r")
    for line in file:
        if line.startswith("#"):
            continue
        if len(line) == 0:
            continue
        values = line.split("\t")
        values.pop(0)
        if len(values) == 0:
            continue
        values.pop(2)
        values.pop(3)
        values.pop(3)
        values.pop(3)
        values.pop(3)
        values.pop(3)
        g_posTypes.add(values[2])
        g_fullWords[values[0]] = values[2]
        g_stemmedWords[values[1]] = values[2]

def get_pos(token):
    if token in g_fullWords:
        return g_fullWords[token]
    elif token in g_stemmedWords:
        return g_stemmedWords[token]
    else:
        return "_"

_read_data_set()

def convert_pos(tokens):
    return [get_pos(token) for token in tokens]

def get_column_names():
    row = []
    for column in g_posTypes:
        row.append(column)
    row.sort()
    return row[:len(row)-1] # sonuncu olan "_" çıkarılıyor

def extract_feature(tokens):
    tokens = convert_pos(tokens)
    row = []
    for column in get_column_names():
        count = 0
        for token in tokens:
            if token == column:
                count = count + 1
        row.append(count)
    return row


__author__ = 'xingyezhi'
# encoding: utf-8

# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution(object):
    def deleteDuplicates(self, head):
        result=addead=ListNode(0)
        temp=addead.next=head
        while temp!=None:
            value,flag=temp.val,False
            while temp.next!=None and temp.next.val==value:
                temp,flag=temp.next,True
            addead.next=temp;addead=temp
            temp=temp.next
        return result.next


"""
Author: Himel Das
"""

import requests

from utilities.logger import logging

def get_country(country_name: str) -> dict:
    api_url = "https://restcountries.com/v3.1/name"
    response = requests.get(url=f"{api_url}/{country_name}")

    if response.status_code == 200:
        country_data = response.json()[0]
        reply = {
            "success": True,
            "body": {
                "name": country_data["name"]["common"],
                "currencies": list(country_data["currencies"].keys()),
                "region": country_data["region"],
                "population": country_data["population"],
            },
        }
    else:
        reply = {"success": False, "body": response.text}

    return reply

def get_countries_with_population(country_names: [str]) -> list:
    res = []
    for country_name in country_names:
        response = get_country(country_name=country_name)
        data = response["body"]

        if response["success"]:
            country = {
                "name": data["name"],
                "population": data["population"],
            }
            res.append(country)
    return res

if __name__ == "__main__":
    logging.info(get_country(country_name="usa"))
    countries = ["usa", "canada", "australia", "unknown"]
    logging.info(
        msg=f"Countries with population: {get_countries_with_population(country_names=countries)}"
    )


class Solution:
    def makeSmallestPalindrome(self, s: str) -> str:
        s = list(s)
        length = len(s)
        mid = length // 2

        for i in range(mid):
            j = length - 1 - i
            if s[i] == s[j]:
                continue

            if ord(s[i]) < ord(s[j]):
                s[j] = s[i]
            else:
                s[i] = s[j]

        return "".join(s)

print(Solution().makeSmallestPalindrome("escape"))


import math

import backtrader as bt

from backtrader.indicators import Highest
from backtrader.indicators import Lowest

from matplotlib.pyplot import subplot

import symbol_data

class DonchianChannel(bt.Indicator):

    lines = (
        'basis',
        'high', 'low',
        'high_volume', 'low_volume'
    )
    params = (
        ('period', 21),
    )

    plotinfo = dict(
        # Add extra margins above and below the 1s and -1s
        # plotymargin=0.15,

        # Plot a reference horizontal line at 1.0 and -1.0
        # plothlines=[0, 1, 2, 3],

        # Simplify the y scale to 1.0 and -1.0
        # plotyticks=[1.0, -1.0],

        subplot=False,
    )

    plotlines = dict(
        high_volume=dict(_plotskip=True,),
        low_volume=dict(_plotskip=True,),
    )

    def __init__(self):

        self.l.high     = Highest(self.data.high, period=self.p.period)
        self.l.low      = Lowest(self.data.low, period=self.p.period)
        self.l.basis    = (self.l.high + self.l.low) / 2

        self.l.high_volume  = Highest(self.data.volume, period=self.p.period)
        self.l.low_volume   = Lowest(self.data.volume, period=self.p.period)


#!/usr/bin/env python

import sys
import numpy as np
import math
import logging
import re

import matplotlib
matplotlib.use('Agg')

import matplotlib.pyplot as plt
import matplotlib.transforms as mtrans

from matplotlib import rc
rc('text', usetex=True)
rc('font', family='serif', size = 12)

import iterutils

def fill_between_steps(ax, x, y1, y2=0, step_where='pre', **kwargs):
    ''' fill between a step plot and

    source: https://github.com/matplotlib/matplotlib/issues/643/

    Parameters
    ----------
    ax : Axes
       The axes to draw to

    x : array-like
        Array/vector of index values.

    y1 : array-like or float
        Array/vector of values to be filled under.
    y2 : array-Like or float, optional
        Array/vector or bottom values for filled area. Default is 0.

    step_where : {'pre', 'post', 'mid'}
        where the step happens, same meanings as for `step`

    **kwargs will be passed to the matplotlib fill_between() function.

    Returns
    -------
    ret : PolyCollection
       The added artist

    '''
    if step_where not in {'pre', 'post', 'mid'}:
        raise ValueError("where must be one of {{'pre', 'post', 'mid'}} "
                         "You passed in {wh}".format(wh=step_where))

    # make sure y values are up-converted to arrays
    if np.isscalar(y1):
        y1 = np.ones_like(x) * y1

    if np.isscalar(y2):
        y2 = np.ones_like(x) * y2

    # temporary array for up-converting the values to step corners
    # 3 x 2N - 1 array

    vertices = np.vstack((x, y1, y2))

    # this logic is lifted from lines.py
    # this should probably be centralized someplace
    if step_where == 'pre':
        steps = np.zeros((3, 2 * len(x) - 1), np.float)
        steps[0, 0::2], steps[0, 1::2] = vertices[0, :], vertices[0, :-1]
        steps[1:, 0::2], steps[1:, 1:-1:2] = vertices[1:, :], vertices[1:, 1:]

    elif step_where == 'post':
        steps = np.zeros((3, 2 * len(x) - 1), np.float)
        steps[0, ::2], steps[0, 1:-1:2] = vertices[0, :], vertices[0, 1:]
        steps[1:, 0::2], steps[1:, 1::2] = vertices[1:, :], vertices[1:, :-1]

    elif step_where == 'mid':
        steps = np.zeros((3, 2 * len(x)), np.float)
        steps[0, 1:-1:2] = 0.5 * (vertices[0, :-1] + vertices[0, 1:])
        steps[0, 2::2] = 0.5 * (vertices[0, :-1] + vertices[0, 1:])
        steps[0, 0] = vertices[0, 0]
        steps[0, -1] = vertices[0, -1]
        steps[1:, 0::2], steps[1:, 1::2] = vertices[1:, :], vertices[1:, :]
    else:
        raise RuntimeError("should never hit end of if-elif block for validated input")

    # un-pack
    xx, yy1, yy2 = steps

    # now to the plotting part:
    return ax.fill_between(xx, yy1, y2=yy2, **kwargs)

def all_relations(a, filename, labels = None, classes = None, figsize = None, lim = None, colormap = plt.cm.Paired):
    """
    a: np array, rows for data, columns for features/axes
    """

    plt.clf()
    features = a.shape[1]
    f, axs = plt.subplots(features - 1, features - 1, squeeze=False) #, sharex=True, sharey=True)

    classes = np.array(classes)

    if figsize is not None:
        f.set_size_inches(figsize)

    if labels is None:
        labels = [str(x) for x in range(features)]

    if classes is not None:
        cm = colormap(np.linspace(0, 1, len(np.unique(classes)))) #plt.cm.Set1(len(classes))

    #if not shapeclasses:
        #shapeclasses = np.zeros(a.shape[0])

    shapes = ['^', 'o', 's', 'x']

    for row in range(1, features):
        for column in range(features - 1):
            ax = axs[row - 1, column]
            #ax.tick_params(labeltop=False, labelright=False)

            if column < row:
                if classes is not None:
                    logging.debug(classes.dtype)
                    ax.scatter(a[:,column], a[:,row], alpha = 0.2, c=cm[classes])
                else:
                    ax.scatter(a[:,column], a[:,row], alpha = 0.2, c=np.arange(a.shape[0]))

                if column > 0:
                    ax.get_yaxis().set_ticks([])
                else:
                    ax.set_ylabel(labels[row])

                if row < features - 1:
                    ax.get_xaxis().set_ticks([])
                else:
                    ax.set_xlabel(labels[column])

                if lim:
                    ax.set_xlim(lim)
                    ax.set_ylim(lim)

                else:
                    if len(a[:,column]):
                        min_, max_ = np.min(a[:,column]), np.max(a[:,column])
                        eps = (max_ - min_) * 0.1
                        ax.set_xlim((min_ - eps, max_ + eps))

                    if len(a[:,row]):
                        min_, max_ = np.min(a[:,row]), np.max(a[:,row])
                        eps = (max_ - min_) * 0.1
                        ax.set_ylim((min_ - eps, max_ + eps))
            else:
                ax.axis('off')

    #plt.autoscale()

    f.set_size_inches((2*features, 2*features))
    f.savefig(filename, dpi=100, bbox_inches='tight')
    plt.close(f)

def relation(xs, ys, filename, xlabel=None, ylabel=None, pointlabels = [],
        xlim = None, xlog = False, vertical_line = None):
    xsl = list(xs)
    ysl = list(ys)

    plt.clf()
    fig = plt.figure()
    ax = plt.subplot(111)

    trans_offset = mtrans.offset_copy(ax.transData, fig=fig, x = 0.05, y = 0.1, units='inches')

    ax.scatter(xsl, ysl, c = plt.cm.Set1(np.linspace(0, 1, len(xsl))), alpha=0.5)
    if xlabel:
        ax.set_xlabel(xlabel)
    if ylabel:
        ax.set_ylabel(ylabel)

    if xlim is not None:
        ax.set_xlim(xlim)

    if xlog:
        ax.set_xscale('log')

    if pointlabels:
        for x, y, l in zip(xsl, ysl, pointlabels):
            ax.text(x, y, l, transform = trans_offset, fontsize=8)

    if vertical_line:
        ax.axvline(vertical_line, color='red')

    ax.grid(True)

    fig.savefig(filename, dpi=100)
    plt.close(fig)

def relations(xss, yss, filename, xlabel=None, ylabel=None, pointlabels = [],
        xlim = None, labels = []):
    xss = list(xss)
    yss = list(yss)

    plt.clf()
    fig = plt.figure()
    ax = plt.subplot(111)

    trans_offset = mtrans.offset_copy(ax.transData, fig=fig, x = 0.05, y = 0.1, units='inches')

    if len(labels) < len(xss):
        labels += [''] * (len(xss) - len(labels))

    for xsl, ysl, c, label in zip(xss, yss, plt.cm.Dark2(np.linspace(0, 1, len(xss))), labels):
        ax.scatter(xsl, ysl, c = c, alpha=0.5, label=label)
        if pointlabels:
            for x, y, l in zip(xsl, ysl, pointlabels):
                ax.text(x, y, l, transform = trans_offset, fontsize=8)

    if xlabel:
        ax.set_xlabel(xlabel)
    if ylabel:
        ax.set_ylabel(ylabel)

    if xlim is not None:
        ax.set_xlim(xlim)

    plt.legend(loc='upper center', prop={'size': 10}, bbox_to_anchor=(0.5,1.1), ncol=int(math.ceil(len(xss)/2.0)), fancybox=True)

    ax.grid(True)

    fig.savefig(filename, dpi=100)
    plt.close(fig)

def curves(xss, yss,
           filename,
           yss_min = [], yss_max = [],
           labels = [],
           invert_x = False,
           xlabel = None, ylabel = None,
           xoffsets = None,
           yoffsets = None,
           xlog = False, ylog = False,
           xlim = None, ylim = None,
           step = False,
           closeups_x = [],
           linestyle = '-',
           legendrows = 2,
           cm = plt.cm.Dark2,
           minmax_style = 'filled',
           markers = '^os',
           markeverys = [],
           grid = False,
           figsize = None,
          ):

    xlim_ = xlim
    filename_ = filename
    if len(labels) < len(xss):
        labels += [''] * (len(xss) - len(labels))

    if len(yss_min) < len(yss):
        yss_min += [None] * (len(yss) - len(yss_min))

    if len(yss_max) < len(yss):
        yss_max += [None] * (len(yss) - len(yss_max))

    if xoffsets is None:
        xoffsets = 0

    if yoffsets is None:
        yoffsets = 0

    if len(markeverys) < len(xss):
        markeverys += [ None ] * (len(xss) - len(markeverys))

    if isinstance(linestyle, str):
        linestyle = [linestyle]

    for i, xlim in enumerate([xlim_] + closeups_x):
        fig, ax = plt.subplots(1, 1, figsize = figsize)

        if i == 0:
            filename = filename_
        else:
            m = re.match(r'(.*)(\.[^.]*)$', filename_)
            if m is None:
                filename + filename_ + '_closeup{}'.format(i) + '.pdf'
            else:
                filename = m.groups()[0] + '_closeup{}'.format(i) + m.groups()[1]

        if xlog:
            ax.set_xscale('log', basex=xlog)

        if ylog:
            ax.set_yscale('log', basey=ylog)

        if invert_x:
            ax.invert_xaxis()

        ax.yaxis.grid(grid, which = 'major', linestyle='-', color='.8')
        ax.yaxis.grid(grid, which = 'minor', linestyle=':', color='.8')

        offsx = 0
        offsy = 0
        for xs, ys, ys_min, ys_max, c, label, marker, markevery, ls in zip(
            xss,
            yss,
            yss_min,
            yss_max,
            cm(np.linspace(0, 1, len(yss))),
            labels,
            iterutils.repeat_to(markers, len(xss)),
            markeverys,
            iterutils.repeat_to(linestyle, len(xss)),
        ):
            ys = np.array(ys)
            xs = np.array(xs)

            if ys_min is not None:
                ys_min = np.array(ys_min)

            if ys_max is not None:
                ys_max = np.array(ys_max)

            aox = np.full((len(xs), ), offsx)
            aoy = np.full((len(ys), ), offsy)

            offsx += xoffsets
            offsy += yoffsets

            if step:
                ax.step(xs + aox, ys + aoy, ls, where = 'post', c = c, label = label, markeredgewidth = 0.0)

            else:
                if minmax_style == 'error' and ys_min is not None and ys_max is not None:
                    ax.plot(xs + aox, ys + aoy, ls, marker = marker, c = c, label = label, markeredgewidth = 0.0, markevery = markevery, markersize=8)
                    ax.errorbar(
                        xs + aox, ys + aoy,
                        yerr = [-(ys_min - ys + aoy), ys_max - ys + aoy],
                        alpha = 0.8,
                        #lolims = True,
                        #uplims = True,
                        capsize = 1.5,
                        linestyle = '',
                        linewidth = 0,
                        elinewidth = 0.5,
                        c = c,
                        markeredgecolor = c,
                        color = c,
                    )
                else:
                    ax.plot(xs + aox, ys + aoy, ls, marker = marker, c = c, label = label, markeredgewidth = 0.0)

            if ys_min is not None and ys_max is not None and minmax_style == 'filled':
                if step:
                    fill_between_steps(ax, xs + aox, ys_min + aoy, ys_max + aoy, color = c, alpha = 0.1, linestyle = '--', step_where = 'post')

                else:
                    ax.fill_between(xs + aox, ys_min + aoy, ys_max + aoy, color = c, alpha = 0.1)

            # "Special" markers

            #saox = np.full((len(sxs), ), offsx)
            #saoy = np.full((len(sys), ), offsy)
            #ax.plot(sxs + saox, sys + saoy, '', marker = '*', c = c)

        if xlabel:
            ax.set_xlabel(xlabel)

        if ylabel:
            ax.set_ylabel(ylabel)

        if xlim is not None:
            ax.set_xlim(xlim)

        if ylim is not None:
            ax.set_ylim(ylim)

        logging.debug('len(yss)={} legendrows={}'.format(len(yss), legendrows))
        try:
            ax.legend(
                loc='upper center',
                prop={'size': 8},
                bbox_to_anchor=(0.5, 1.2),
                ncol=int(math.ceil(len(yss) / legendrows)),
                fancybox=True,
                frameon=False
            )
        except IndexError:
            pass
        logging.debug('creating {}'.format(filename))
        fig.savefig(filename, bbox_inches='tight')
        plt.close(fig)

def percentile_curves(xss, ysss, filename, low = 10, high = 90, **kws):

    yss = [ np.array([np.median(s[i:]) for i in range(len(s))]) for s in ysss ]
    yss_min = [ np.array([np.percentile(s[i:], q = low) for i in range(len(s))]) for s in ysss ]
    yss_max = [ np.array([np.percentile(s[i:], q = high) for i in range(len(s))]) for s in ysss ]

    curves(
            xss = xss,
            yss = yss,
            filename = filename,
            yss_min = yss_min,
            yss_max = yss_max,
            **kws
            )

def cdfs(a, filename):
    """
    a: [ { 'label': 'foo', 'values': [ ... ] }, ... ]
    """

    plt.clf()
    plt.cla()
    for i, (d, c) in enumerate(zip(a, plt.cm.Paired(np.linspace(0, 1, len(a))))):
        values = d['values']

        if len(values) == 0:
            values = [0]

        values = np.sort(values)
        avg = np.sum(values)/len(values)
        median = np.median(values)

        def indices_to_counts(xs, indices):
            counts = indices[1:] - indices[:-1]
            l = len(values) - sum(counts)
            return xs, np.hstack((counts, np.array([l])))

        #xs, counts = np.unique(values, return_counts = True)
        xs, counts = indices_to_counts( *np.unique(values, return_index = True) )
        ys = np.cumsum(counts)

        plt.plot(xs, ys, c=c, label=d['label'], linewidth=i/5+1)
        plt.axvline(x = avg, color=c, linestyle=':', linewidth=i/5+1)
        plt.axvline(x = median, color=c, linestyle='--', linewidth=i/5+1)

    plt.legend(loc='best', prop={'size': 8})
    plt.savefig(filename, dpi=100, bbox_inches='tight')

def boxplots(xs, yss, filename):
    plt.clf()
    plt.cla()
    #fig, axes = plt.subplots(1, 1)

    plt.boxplot(yss, vert = True)
    plt.setp(plt.axes(), xticklabels=xs)

    plt.autoscale()

    plt.savefig(filename, dpi=100, bbox_inches='tight')

def multi_boxplots(xs, ysss, filename, ylim = (-0.05, 1.05), labels = [], toplabels = [], points = True, xlabel = '', ylabel = '', legendrows = 2, cm = plt.cm.Dark2, showfliers = False):
    """
    ysss = [
            [ [ x x x x ], ... ],
            [ [ x x x x ], ... ],
            ....
        ]

    toplabels = [
        [ 'color1box1', 'color1box2', ... ],
        [ 'color2box1', 'color2box2', ... ],
        ]

    labels = ['color1', 'color2', 'color3', ...]

    innermost list = data for 1 box
    list of boxlists = data row (same color)
    """

    #dot_spread = 0.1
    dot_spread = 0.6

    fig, axes = plt.subplots(1, 1, figsize=(14, 7))

    if ylim is None:
        elems = iterutils.flatten(ysss)
        if len(elems):
            ylim = (min(elems), max(elems))

            delta = (ylim[1] - ylim[0]) * 0.05
            ylim = (ylim[0] - delta, ylim[1] + delta)

        else:
            ylim = (0, 1)

    top = ylim[1] + (ylim[1] - ylim[0]) * 0.1

    k = len(ysss) + 1
    dummylines = []
    maxlen = 0
    if len(labels) < len(ysss):
        labels += [str(i) for i in range(len(ysss) - len(labels))]

    if not toplabels:
        toplabels = [ [] ] * len(ysss)

    for yss, c, offset, tlables in zip(
            ysss,
            #plt.cm.Dark2(np.linspace(0, 1, len(ysss))),
            cm(np.linspace(0, 1, len(ysss))),
            range(1, 1 + len(ysss)),
            toplabels
            ):
        maxlen = max(maxlen, len(yss))

        # each yss is a data set and gets one color
        ps = range(offset, len(yss) * k + offset, k)

        if len(yss):
            bp = axes.boxplot(yss,
                              vert = True,
                              boxprops={'color': c},
                              widths = 0.6,
                              positions = ps,
                              #notch = True, # crashes w/ empty plots, so no notch :(
                              showfliers = showfliers)

            # Style the box
            for key, v in bp.items():
                for e in v:
                    plt.setp(e, color = c)

        # dummy line for legend
        h, = plt.plot([1, 1], c = c, color = c, linestyle='-')
        dummylines.append(h)

        for ys, p in zip(yss, ps):
            #rxs = np.linspace(p - dot_spread / 2, p + dot_spread / 2, len(ys))
            rxs = np.random.uniform(p - dot_spread / 2, p + dot_spread / 2, size = len(ys))
            #rxs = np.random.normal(p, dot_spread, size = len(ys))
            plt.plot(rxs, ys, '.', c = c, alpha = 0.5)

        if tlables:
            for p, label in zip(ps, tlables):
                axes.text(p, top * 0.95, label, horizontalalignment='center', size=12, weight='bold', color = c)

    axes.yaxis.grid(True)
    axes.set_xlabel(xlabel)
    axes.set_ylabel(ylabel)

    if len(dummylines) > 1:
        plt.legend(dummylines, labels, loc='upper center', prop={'size': 10}, bbox_to_anchor=(0.5,1.1), ncol=int(math.ceil(len(dummylines)/legendrows)), fancybox=True)
    for l in dummylines:
        l.set_visible(False)

    plt.setp(axes, xticks = np.arange(k/2.0, k/2.0 + maxlen * k, k), xticklabels=xs)
    axes.set_xlim((0, maxlen * k))

    if ylim is not None:
        ylim = (ylim[0], top)
        axes.set_ylim(ylim)

    fig.savefig(filename, dpi=100, bbox_inches = 'tight')
    plt.close(fig)

def matrix(a, filename):
    plt.clf()

    aspect_ratio = a.shape[1] / float(a.shape[0])
    print(4 * aspect_ratio, 4)

    fig, ax = plt.subplots(dpi=100)
    cs = ax.matshow(a)
    fig.colorbar(cs)
    fig.savefig(filename, dpi=100, bbox_inches = 'tight')
    plt.close(fig)

def kde1d(xs_plot, estimators, filename, xss_data = [], labels = None,
        xlabel = None, xlim = None, lines = [], grid = True):

    plt.clf()
    fig, ax = plt.subplots(dpi=100)

    if labels is None:
        labels = ['KDE {}'.format(x) for x in range(len(estimators))]

    cm = plt.cm.Set2(np.linspace(0, 1, len(estimators)))
    alpha = 0.5
    offs = 0.01
    spread = 0.005

    for i, (kde, label, xs_data, c) in enumerate(zip(estimators, labels, xss_data, cm)):
        log_dens = kde.score_samples(xs_plot.reshape(len(xs_plot), 1))
        ax.fill(xs_plot, np.exp(log_dens), '-', label = label, alpha = alpha, fc
                = c)

        ax.legend(loc='best', prop={'size': 8})
        ax.plot(xs_data, -(i+1) * offs + spread/2 - spread * np.random.random(len(xs_data)), 'o', c=c,
                alpha=alpha)

    if xlabel is not None:
        ax.set_xlabel(xlabel)

    if xlim is not None:
        ax.set_xlim(xlim)

    for line in lines:
        ax.axvline(c = 'grey', linestyle = '-', x = line)

    ax.grid(grid)
    fig.savefig(filename, dpi=100, bbox_inches='tight')

    plt.close(fig)

if __name__ == '__main__':

    a = [
        { 'label': 'foo00', 'values': np.random.rand(10) },
        { 'label': 'foo01', 'values': np.random.rand(10) },
        { 'label': 'foo02', 'values': np.random.rand(10) },
        { 'label': 'foo03', 'values': np.random.rand(10) },
        { 'label': 'foo04', 'values': np.random.rand(10) },
        { 'label': 'foo05', 'values': np.random.rand(10) },
        { 'label': 'foo06', 'values': np.random.rand(10) },
        { 'label': 'foo07', 'values': np.random.rand(10) },
        { 'label': 'foo08', 'values': np.random.rand(10) },
        { 'label': 'foo09', 'values': np.random.rand(10) },
        { 'label': 'foo10', 'values': np.random.rand(10) },
        { 'label': 'foo11', 'values': np.random.rand(10) },
        { 'label': 'foo12', 'values': np.random.rand(10) },
        { 'label': 'foo13', 'values': np.random.rand(10) },
        { 'label': 'foo14', 'values': np.random.rand(10) },
        { 'label': 'foo15', 'values': np.random.rand(10) },
        { 'label': 'foo16', 'values': np.random.rand(10) },
        { 'label': 'foo17', 'values': np.random.rand(10) },
        { 'label': 'foo18', 'values': np.random.rand(10) },
        { 'label': 'foo19', 'values': np.random.rand(10) },

        ]

    cdfs(a, '/tmp/test.pdf')

    xs = [1.23, 4.56, 7.89]
    ysss = [
            [ [1, 1, 3, 8, 15], [6, 8, 7], [9, 0, 6, 7] ],
            [ [2, 2, 3, 8, 6], [10, 10, 10, 6], [1,2,3,4,5] ],
           ]
    multi_boxplots(xs, ysss, '/tmp/multi_boxplots.pdf', labels=['foo', 'bar'])


# -*- encoding: utf-8 -*-
"""
@file: isPerfectSquare.py
@time: 2020/9/21 下午4:18
@author: shenpinggang
@contact: 1285456152@qq.com
@desc:  367.有效的完全平方数

给定一个正整数 num，编写一个函数，如果 num 是一个完全平方数，则返回 True，否则返回 False。
说明：不要使用任何内置的库函数，如  sqrt。

示例 1：
输入：16
输出：True

示例 2：
输入：14
输出：False

来源：力扣（LeetCode）
链接：https://leetcode-cn.com/problems/valid-perfect-square
"""

def is_perfect_square1(num):
    """
    二分法
    :param num: (int)
    :return: (bool)
    """
    if num < 2:
        return True

    left, right = 1, num // 2
    while left <= right:
        mid = int(left + (right - left) / 2)
        value = mid * mid
        if value == num:
            return True
        elif value < num:
            left = mid + 1
        else:
            right = mid - 1

    return False

def is_perfect_square(num):
    """
    牛顿迭代法. xi = (x0 + C / x0) / 2
    :param num: (int)
    :return: (bool)
    """
    if num < 2:
        return True

    x0, c = num / 2, num
    while x0 * x0 > num:
        x0 = (x0 + c // x0) // 2
    return x0 * x0 == num

def test(inputs, answer):
    outputs = is_perfect_square(inputs)
    print("Inputs:{}, Outputs:{}, Except:{}".format(inputs, outputs, answer))
    assert outputs == answer, print("Answer Failed")

def main():
    inputs, answer = 16, True
    test(inputs, answer)

    inputs, answer = 14, False
    test(inputs, answer)

if __name__ == '__main__':
    main()


# -*- coding: utf-8 -*-
# Created on Fri May 10 2019 9:22:54
# Author: WuLC
# EMail: liangchaowu5@gmail.com

# dp,O(n) time
# for each split point, find the max L elements on the left + max M elements on the right
# or max M elements on the left + max L elements on the right

class Solution(object):
    def maxSumTwoNoOverlap(self, A, L, M):
        """
        :type A: List[int]
        :type L: int
        :type M: int
        :rtype: int
        """
        return max(self.helper(A, L, M), self.helper(A, M, L))

    def helper(self, A, L, M):
        n = len(A)
        left, right = [0] * (n + 1), [0] * (n + 1)
        curr = 0
        for i in xrange(n):
            curr += A[i]
            if i >= L:
                curr -= A[i-L]
            left[i+1] = max(left[i], curr)
        curr = 0
        for i in xrange(n - 1, -1, -1):
            curr += A[i]
            if i <= n - M - 1:
                curr -= A[i+M]
            right[i] = max(right[i+1], curr)
        return max(max(left[i+1] + right[i+1], left[i] + right[i]) for i in xrange(n))

Algorithm/Python/1000+/Maximum Sum of Two Non-Overlapping Subarrays.py


from typing import List, Union

from asyncpg.exceptions import UniqueViolationError

from blockchain.services.coingecko import get_token_price_from_cg
from bot.models import TokenContract
from settings import settings

async def get_tokens_price(tokens: List[dict], chain: str, currency: str):
    addresses = ''
    for token in tokens:
        addresses += f'{token["token_address"]},'
    prices = await get_token_price_from_cg(addresses, chain, [currency])
    for token in tokens:
        price = prices.get(token["token_address"].lower())
        if price:
            token['price'] = price[currency]
        try:
            contract = TokenContract(token_address=token['token_address'], name=token.get('name'),
                                     chain=chain, symbol=token.get('symbol'),
                                     decimals=token.get('decimals', settings.chain_decimals[chain]))
            if price:
                contract.price = price[currency]
            await contract.save()
        except UniqueViolationError:
            contract = await TokenContract.objects.get_or_none(token_address=token['token_address'], chain=chain)
            if contract and price:
                await contract.update(price=price[currency], name=token.get('name'), symbol=token.get('symbol'),
                                      decimals=token.get('decimals', settings.chain_decimals[chain]))

def convert_balance(value: Union[str, int], decimal: Union[str, int]) -> float:
    return int(value) / 10 ** int(decimal)


import json

from flask import jsonify, Blueprint, abort, url_for, g, make_response
from flask_restful import (Resource, Api, reqparse, inputs, fields,
                           marshal, marshal_with)
from auth import auth
import models

review_fields = {
    'id': fields.Integer,
    'for_course': fields.String,
    'rating': fields.Integer,
    'comment': fields.String(default=''),
    'create_on': fields.DateTime
}

def review_or_404(review_id):
    try:
        review = models.Review.get(models.Review.id == review_id)
    except models.Review.DoesNotExist:
        abort(404)
    else:
        return review

def add_course(review):
    review.for_course = url_for('resources.courses.course', id=review.course.id)
    return review

class ReviewList(Resource):
    def __init__(self):
        self.reqparse = reqparse.RequestParser()
        self.reqparse.add_argument(
            'course',
            required=True,
            help='course must be provided',
            location=['form', 'json'],
            type=inputs.positive
        )
        self.reqparse.add_argument(
            'rating',
            required=True,
            help='please provide rating',
            location=['form', 'json'],
            type=inputs.int_range(1, 5)
        )
        self.reqparse.add_argument(
            'comment',
            required=False,
            nullable=True,
            default='',
            location=['form', 'json']
        )
        super(ReviewList, self).__init__()

    def get(self):
        return {'reviews': [
            marshal(add_course(review), review_fields)
            for review in models.Review.select()
        ]}

    @auth.login_required
    def post(self):
        args = self.reqparse.parse_args()
        # the arguments are parsed and output as dictionary
        review = models.Review.create(
            created_by=g.user,
            **args
        )
        return add_course(review)

class Review(Resource):
    def __init__(self):
        self.reqparse = reqparse.RequestParser()
        self.reqparse.add_argument(
            'course',
            required=True,
            help='course must be provided',
            location=['form', 'json'],
            type=inputs.positive
        )
        self.reqparse.add_argument(
            'rating',
            required=True,
            help='please provide rating',
            location=['form', 'json'],
            type=inputs.int_range(1, 5)
        )
        self.reqparse.add_argument(
            'comment',
            required=False,
            nullable=True,
            default='',
            location=['form', 'json']
        )
        super().__init__()

    @marshal_with(review_fields)
    def get(self, id):
        return add_course(review_or_404(id))

    @marshal_with(review_fields)
    @auth.login_required
    def put(self, id):
        args = self.reqparse.parse_args()
        try:
            review = models.Review.select().where(
                models.Review.created_by == g.user,
                models.Review.id == id
            ).get()
        except models.Review.DoesNotExist:
            return make_response(
                json.dumps({
                    'error': 'you have no permission to edit here'
                }),403
            )
        query = review.update(**args)
        query.execute()
        review = add_course(review_or_404(id))
        return (review, 200,
                {'location': url_for('resources.reviews.review', id=id)})

    @auth.login_required
    def delete(self, id):
        try:
            review = models.Review.select().where(
                models.Review.created_by == g.user,
                models.Review.id == id
            ).get()
        except models.Review.DoesNotExist:
            return make_response(
                json.dumps({
                    'error': 'you have no permission to edit here'
                }),403
            )
        query = review.delete()
        query.execute()
        return '', 204, {'location': url_for('resources.reviews.reviews')}

reviews_api = Blueprint("resources.reviews", __name__)
api = Api(reviews_api)
api.add_resource(
    ReviewList,
    '/reviews',
    endpoint='reviews'
)
api.add_resource(
    Review,
    '/reviews/<int:id>',
    endpoint='review'
)


import hopsworks
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.model_selection import KFold
from xgboost import XGBRegressor
from hsml.schema import Schema
from hsml.model_schema import ModelSchema
import os
import joblib

project = hopsworks.login()
fs = project.get_feature_store()

data = fs.get_feature_group('aqi_prediction', version=1)

query = data.select(["pm25", "pm10", "o3", "no2", "so2", "co", "aqi"])

feature_view = fs.get_or_create_feature_view(
    name='aqi_prediction_fv',
    version=1,
    query=query,
    labels=["aqi"]
)

TEST_SIZE = 0.25

td_version, td_job = feature_view.create_train_test_split(
    description = 'pollution dataset',
    data_format = 'csv',
    test_size = TEST_SIZE,
    write_options = {'wait_for_job': True}
)

X_train, X_test, y_train, y_test = feature_view.get_train_test_split(td_version)

losses = []
r2_scores = []

model = XGBRegressor(
    n_estimators = 933,
    max_depth = 3,
    learning_rate = 0.0659553078597774,
    reg_lambda = 0.49527985837464644
)

kfold = KFold(n_splits=5, shuffle=True, random_state=42)

for train_index, val_index in kfold.split(X_train):
    X_train_fold, X_val_fold = X_train.iloc[train_index], X_train.iloc[val_index]
    y_train_fold, y_val_fold = y_train.iloc[train_index], y_train.iloc[val_index]

    model.fit(X_train_fold, y_train_fold)

input_schema = Schema(X_train.values)
output_schema = Schema(y_train)
model_schema = ModelSchema(input_schema=input_schema, output_schema=output_schema)

model_schema.to_dict()

model_dir="aqi_prediction_model"
if os.path.isdir(model_dir) == False:
    os.mkdir(model_dir)

joblib.dump(model, model_dir + '/xgboost_aqi_prediction_model.pkl')

mr = project.get_model_registry()

aqi_prediction_model = mr.python.create_model(
    name="aqi_prediction_model",
    model_schema=model_schema,
    input_example=X_train.sample(),
    description="AQI predictor")

aqi_prediction_model.save(model_dir)


#!/usr/bin/python
# -*- coding: utf-8 -*-

import configparser
import socket
import time
import serial
import threading
import rtcmproxy

# load settings from config file
config = configparser.SafeConfigParser()
config.read('config.cfg')

# serial port
bufsize  = config.getint('Serial', 'bufsize')
baudrate = config.getint('Serial', 'baudrate')
serport  = config.get('Serial', 'port')

print("trying to open", serport, "at", baudrate, "speed...")
ser = serial.Serial(serport, baudrate, timeout = 0.5)
print("  success!")

class SerialToQgc(threading.Thread):#{{{
    def __init__(self, ser, tcpconn):
        threading.Thread.__init__(self)
        self.__stop = threading.Event()
        self.ser = ser
        self.conn = tcpconn

    def stop(self):
        self.__stop.set()

    def run(self):
        while True:
            if self.__stop.is_set():
                print("SerialToQgc: terminating")
                return

            data = self.ser.read(bufsize)
            try:
                if data:
                    sent = self.conn.sendall(data)
                else:
                    sent = self.conn.sendall(bytearray(1)) # keep alive
            except BrokenPipeError:
                print ("SerialToQgc: connection closed")
                return;
    #}}}
class QgcToSerial(threading.Thread):#{{{
    def __init__(self, ser, tcpconn):
        threading.Thread.__init__(self)
        self.__stop = threading.Event()
        self.ser = ser
        self.conn = tcpconn

    def stop(self):
        self.__stop.set()

    def run(self):
        while True:
            if self.__stop.is_set():
                print("QgcToSerial: terminating")
                return

            data = self.conn.recv(1024)
            if not data:
                print("QgcToSerial: connection closed")
                return
            else:
                self.ser.write(data)
    #}}}
class ConnListener(threading.Thread):#{{{
    def __init__(self, ser):
        threading.Thread.__init__(self)
        self.__stop = threading.Event()
        self.ser = ser

    def stop(self):
        self.__stop.set()

    def run(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.bind(('', 5760))
        sock.settimeout(0.5)
        sock.listen(5)
        conn = None
        addr = None
        print("Starting ConnListener")

        while True:
            if self.__stop.is_set():
                print ("ConnListener: terminating")
                return

            try:
                (conn, addr) = sock.accept()
            except socket.timeout:
                pass

            if conn:
                print ("Connected by", addr)
                q2s = QgcToSerial(ser, conn)
                s2q = SerialToQgc(ser, conn)
                q2s.start()
                s2q.start()
                q2s.join()
                s2q.join()

                print("--- socket closed")
                conn.close()
                conn = None
                addr = None
    #}}}

listener = ConnListener(ser)
listener.start()
rtcm = rtcmproxy.RtcmProxy(ser)
rtcm.start()

while True:
    try:
        time.sleep(0.5)
    except KeyboardInterrupt:
        print("\nKeyboard Interrupt caught")
        listener.stop()
        rtcm.stop()
        listener.join()
        rtcm.join()
        ser.close()
        exit()


# 借鉴网友的答案，思路就是用一个新的list，每次比较一个，然后连接小的node

# 注意在c + +实现中，返回函数内部生成的指针可能因函数的销毁才失效。
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        if not l1:
            return l2
        if not l2:
            return l1
        head = ListNode(-100)
        temp = head
        while l1 and l2:
            if l1.val < l2.val:
                temp.next = l1
                l1 = l1.next
            else:
                temp.next = l2
                l2 = l2.next
            temp = temp.next
        if l1 is None:  # l2是有序链表，把剩下的直接链接上就可以了
            temp.next = l2
        if l2 is None:
            temp.next = l1
        head = head.next
        del temp
        return head


from __future__ import division

import numpy as np
import contextlib
with contextlib.redirect_stdout(None):
    import pygame
import pygame.locals
import numpy as np
import pygame
import sys
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
from robot_arm.arm_part import ArmPart
import helpers

'''Global Variables'''
red = (255, 0, 0)
white = (255, 255, 255)

pygame.init()
pygame.display.set_caption('Learning and PCA')

width = 1000
height = 1000
display = pygame.display.set_mode((width, height))
frame_clock = pygame.time.Clock()

upperarm = ArmPart('./robot_arm/upperarm.png', scale=.8)
lowerarm = ArmPart('./robot_arm/lowerarm.png', scale=.9)

origin = (width / 2.0, height / 2.0)

num_steps_0 = 0
num_steps_1 = 0
cur_radians_0 = 0
cur_radians_1 = 0
rotate_rte_0 = 0
rotate_rte_1 = 0

#Use PyTorch to do SVD and return principle components
def calculate_pca(data, k=2):
    #extract mean of the data
    data = torch.from_numpy(data)
    data_mean = torch.mean(data,0) #columnwise mean
    data = data - data_mean.expand_as(data)

    U,S,V = torch.svd(torch.t(data))
    return U[:,:k], data_mean[0], data_mean[1]

basicfont = pygame.font.SysFont(None, 48)

half_circle_bool = False
current_state = 0
trajectories_to_collect = 0 #This will collect one trajectory
joint_data = []
lamda = 0

def rot_it(rad_current, rad_desired):
    #this is how many radians I need to move in total
    desired_transform = rad_desired - rad_current
    oneeighty = 180/57.2958

    #This is to make sure the direction I am turning is the most efficient way to turn
    if desired_transform < 0:
        if abs(desired_transform) <= oneeighty: #Decide whether to turn clockwise or counter clockwise
            rotation_rte = 1 #1 degree per frame
        else:
            rotation_rte = -1 #1 degree per frame
    else:
        if abs(desired_transform) <= oneeighty: #Decide whether to turn clockwise or counter clockwise
            rotation_rte = -1
        else:
            rotation_rte = 1 #1 degree per frame

    desired_transform = (abs(desired_transform))
    if desired_transform > (np.pi):
        desired_transform = 2*np.pi - desired_transform

    return 1, rotation_rte * desired_transform

'''Main Script Logic'''
while True:
    display.fill(white)

    #Check if arm is in desired starting position
    if current_state == 0 and num_steps_0 == 0 and num_steps_1 == 0 and cur_radians_0 != 0:
        if half_circle_bool:
            goal = (0, upperarm.scale + lowerarm.scale)
        else:
            goal = (0, upperarm.scale - lowerarm.scale)

        theta_0, theta_1 = helpers.inv_kin_2arm(goal[0], goal[1], upperarm.scale, lowerarm.scale)
        theta_0, theta_1 = helpers.convert_normal_angle(theta_0, theta_1)

        if (goal[0] >=0):
            theta_add = (theta_1 + theta_0)% (2 * np.pi)
        else:
            theta_add = (theta_1 - theta_0)% (2 * np.pi)

        num_steps_0, rotate_rte_0 = helpers.calc_rot(cur_radians_0, theta_0)
        num_steps_1, rotate_rte_1 = helpers.calc_rot(cur_radians_1, theta_add)

    #current_state = 1 (data collection)
    #-- move arm to stretched out position movement type 1
    if current_state == 1 and num_steps_0 == 0 and num_steps_1 == 0:
        goal = (upperarm.scale + lowerarm.scale, 0)
        trajectories_to_collect += -1

        theta_0, theta_1 = helpers.inv_kin_2arm(goal[0], goal[1], upperarm.scale, lowerarm.scale)
        theta_0, theta_1 = helpers.convert_normal_angle(theta_0, theta_1)

        if (goal[0] >=0):
            theta_add = (theta_1 + theta_0)% (2 * np.pi)
        else:
            theta_add = (theta_1 - theta_0)% (2 * np.pi)

        num_steps_0, rotate_rte_0 = helpers.calc_rot(cur_radians_0, theta_0)
        num_steps_1, rotate_rte_1 = helpers.calc_rot(cur_radians_1, theta_add)

    #current_state = 2 (data collection)
    #-- move arm to starting position movement type 2
    if current_state == 2 and num_steps_0 == 0 and num_steps_1 == 0:
        if half_circle_bool:
            goal = (0, -upperarm.scale - lowerarm.scale)
        else:
            goal = (0, upperarm.scale - lowerarm.scale)
        theta_0, theta_1 = helpers.inv_kin_2arm(goal[0], goal[1], upperarm.scale, lowerarm.scale)
        theta_0, theta_1 = helpers.convert_normal_angle(theta_0, theta_1)

        if (goal[0] >=0):
            theta_add = (theta_1 + theta_0)% (2 * np.pi)
        else:
            theta_add = (theta_1 - theta_0)% (2 * np.pi)

        num_steps_0, rotate_rte_0 = helpers.calc_rot(cur_radians_0, theta_0)
        num_steps_1, rotate_rte_1 = helpers.calc_rot(cur_radians_1, theta_add)

    #current state = 3 -- train PCA and then change current_state to 4
    if current_state ==3 and num_steps_0 == 0 and num_steps_1 == 0:
        #calc PCA
        pc, m_0, m_1 = calculate_pca(np.asarray(joint_data))
        current_state = 4

    #Moving arm using only one priciple component
    if current_state == 4:
        theta_0 = m_0 + lamda * pc[0][0]
        theta_add = m_1 + lamda * pc[0][1]

        num_steps_0, rotate_rte_0 = rot_it(cur_radians_0, theta_0)
        num_steps_1, rotate_rte_1 = rot_it(cur_radians_1, theta_add)
        lamda += .05

    #Rotate upper arm
    if num_steps_0 > 0 and num_steps_1 == 0:
        ua_image, ua_rect = upperarm.rotate(rotate_rte_0)
        fa_image, fa_rect = lowerarm.rotate(0.0)
        num_steps_0 +=-1

    #Rotate lower arm
    elif num_steps_1 > 0 and num_steps_0 == 0:
        fa_image, fa_rect = lowerarm.rotate(rotate_rte_1)
        ua_image, ua_rect = upperarm.rotate(0.0)
        num_steps_1 += -1

    #Rotate upper and lower arm
    elif num_steps_0 > 0 and num_steps_1 > 0:
        fa_image, fa_rect = lowerarm.rotate(rotate_rte_1)
        ua_image, ua_rect = upperarm.rotate(rotate_rte_0)
        num_steps_0 += -1
        num_steps_1 += -1

    #Arm has reached end point, pop sprite from sprites list
    else:
        fa_image, fa_rect = lowerarm.rotate(0.000)
        ua_image, ua_rect = upperarm.rotate(0.000)
        if current_state == 0 and cur_radians_0 != 0:
            current_state = 1
        elif current_state == 1:
            current_state = 2
        elif current_state == 2:
            if half_circle_bool:
                current_state = 3
            else:
                current_state = 1
                if trajectories_to_collect < 0:
                    current_state = 3

    if half_circle_bool:
        if current_state == 1 or current_state == 2:
            joint_data.append([cur_radians_0, cur_radians_1])
    else:
        if current_state == 1:
            joint_data.append([cur_radians_0, cur_radians_1])

    #Update location of joints
    joints_x = np.cumsum([0,
                          upperarm.scale * np.cos(upperarm.rot_angle),
                          lowerarm.scale * np.cos(lowerarm.rot_angle)]) + origin[0]
    joints_y = np.cumsum([0,
                          upperarm.scale * np.sin(upperarm.rot_angle),
                          lowerarm.scale * np.sin(lowerarm.rot_angle)]) * -1 + origin[1]

    joints = [(int(x), int(y)) for x,y in zip(joints_x, joints_y)]

    #Reposition upper arm and lower arm
    helpers.transform(ua_rect, joints[0], upperarm)
    helpers.transform(fa_rect, joints[1], lowerarm)

    #Draw upper and lower arm
    display.blit(ua_image, ua_rect)
    display.blit(fa_image, fa_rect)

    #Get current location of arm parts
    cur_radians_0 = helpers.print_angle(ua_rect.center[0], ua_rect.center[1], (500, 500))
    cur_radians_1 = helpers.print_angle(fa_rect.center[0], fa_rect.center[1], (joints[1][0], joints[1][1]))

    if current_state == 0:
        f=0
    elif current_state != 4:
        text = basicfont.render('Collecting Data', True, (0, 0, 0), (255, 255, 255))
        textrect = text.get_rect()
        display.blit(text, textrect)
    else:
        text = basicfont.render("Executing PCA Lambda " + str(round(lamda, 1)), True, (0, 0, 0), (255, 255, 255))
        textrect = text.get_rect()
        display.blit(text, textrect)

    #Check for quit
    for event in pygame.event.get():
        if event.type == pygame.locals.QUIT:
            pygame.quit()
            sys.exit()

    if lamda > 20 and current_state == 4:
        current_state = 0
        lamda = 0
        if half_circle_bool:
            half_circle_bool = False
        else:
            half_circle_bool = True
        del(joint_data[:])

    pygame.display.update()
    frame_clock.tick(30)


# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function

import warnings
import numpy as np

__all__ = ['polyval2d', 'polygrid2d', 'polyfit2d']

class RankWarning(UserWarning):
    pass

def _polyvander2d(x, y, deg):
    """Return the pseudo-Vandermonde matrix for a given degree.

    [[1, x[0], y[0], ... , x[0]*y[0]^(n-1), y[0]^n]
     [1, x[1], y[1], ... , x[1]*y[1]^(n-1), y[1]^n]
     ...                                       ...
     [1, x[M], y[M], ... , x[M]*y[M]^(n-1), y[M]^n]]

    where `n` is `deg`.

    Parameters
    ----------
    x, y : array_like, shape (M,)
        Array of points. `x` and `y` must have the same shape.
    deg : int
        Degree of the resulting matrix.

    Returns
    -------
    v : ndarray
        The Vandermonde matrix. The shape of the matrix is ``x.shape +
        ((deg+1)*(deg+2) // 2, ))``.
    """
    x = np.array(x, copy=False, ndmin=1) + 0.0
    y = np.array(y, copy=False, ndmin=1) + 0.0
    if x.ndim != 1:
        raise ValueError("x must be 1-dim.")
    if y.ndim != 1:
        raise ValueError("y must be 1-dim.")

    dims = ((deg+1)*(deg+2) // 2, ) + x.shape
    v = np.empty(dims, dtype=x.dtype)
    v[0] = x * 0 + 1.0
    i = 1
    for j in range(1, deg+1):
        v[i:i+j] = x * v[i-j:i]
        v[i+j] = y * v[i-1]
        i += j + 1
    return np.rollaxis(v, 0, v.ndim)

def polyfit2d(x, y, z, deg=1, rcond=None, full_output=False):
    """Return the coefficients of a polynomial of degree `deg`.

    The coefficients are determined by the least square fit to given data values
    `z` at given points ``(x, y)``.  The fitting assumes the polynomial in a
    form::

    .. math:: p(x,y) = \\sum_{i,j} c_{i,j} * x^i * y^j

    with a constraint of ``i + j <= n`` where `n` is `deg`.

    Parameters
    ----------
    x, y : array_like, shape (M,)
        x- and y-oordinates of the M data points ``(x[i], y[i])``.
    z : array_like, shape (M,)
        z-coordinates of the M data points.
    deg : int, optional
        Degree of the polynomial to be fit.
    rcond : float, optional
        Relative condition of the fit.  Singular values smaller than
        `rcond`, relative to the largest singular value, will be
        ignored.  The default value is ``len(x)*eps``, where `eps` is
        the relative precision of the platform's float type, about 2e-16
        in most cases.
    full_output : {True, False}, optional
        Just the coefficients are returned if False, and diagnostic
        information from the SVD is also returned if True.

    Returns
    -------
    coef : ndarray
        Array of coefficients.
    [residuals, rank, singular_values, rcond] : if `full_output` = True
        Sum of the squared residuals of the least-squares fit; the
        effective rank of the scaled pseudo-Vandermonde matrix; its
        singular values, and the specified value of `rcond`. For more
        details, see `numpy.linalg.lstsq`.

    Warns
    -----
    RankWarning
        The rank of the coefficient matrix in the least-squares fit is
        deficient.  The warning is only raised if `full_output` = False.

    See Also
    --------
    polyval2d, polygrid2d
    """
    x = np.asarray(x) + 0.0
    y = np.asarray(y) + 0.0
    z = np.asarray(z) + 0.0

    deg = int(deg)
    if deg < 1:
        raise ValueError("deg must be larger than 1.")

    # Check inputs.
    if x.ndim != 1:
        raise ValueError("x must be 1-dim.")
    if y.ndim != 1:
        raise ValueError("y must be 1-dim.")
    if z.ndim != 1:
        raise ValueError("z must be 1-dim.")
    if x.size != y.size or x.size != z.size:
        raise ValueError("x, y, and z must have the same size.")

    # Set up the matrices for the problem in transposed form.
    lhs = _polyvander2d(x, y, deg).T
    rhs = z.T

    # Set rcond.
    if rcond is None:
        rcond = x.size * np.finfo(x.dtype).eps

    # Determine the norms of the design maxtirx columns.
    if issubclass(lhs.dtype.type, np.complexfloating):
        scl = np.sqrt((np.square(lhs.real) + np.square(lhs.imag)).sum(1))
    else:
        scl = np.sqrt(np.square(lhs).sum(1))
    scl[scl == 0] = 1

    # Solve the least squares problem.
    c1, resids, rank, s = np.linalg.lstsq(lhs.T / scl, rhs.T, rcond)
    c1 = (c1.T / scl).T

    # Warn on rank reduction.
    if rank != lhs.shape[0] and not full_output:
        msg = "The fit may be poorly conditioned."
        warnings.warn(msg, RankWarning)

    # Allocate the coefficients in a 2-dim array.
    inds = []
    for m in range(deg + 1):
        for j in range(m + 1):
            for i in range(m + 1):
                if i + j != m:
                    continue
                inds.append((i, j))
    c2 = np.zeros((deg + 1, deg + 1))
    c2[zip(*inds)] = c1

    if full_output:
        return c2, [resids, rank, s, rcond]
    else:
        return c2

def polygrid2d(x, y, c):
    """
    Evaluate a 2-D polynomial on the Cartesian product of x and y.

    This function returns the values:

    .. math:: p(a,b) = \sum_{i,j} c_{i,j} * a^i * b^j

    where the points `(a, b)` consist of all pairs formed by taking
    `a` from `x` and `b` from `y`. The resulting points form a grid with
    `x` in the first dimension and `y` in the second.

    The parameters `x` and `y` are converted to arrays only if they are
    tuples or a lists, otherwise they are treated as a scalars. In either
    case, either `x` and `y` or their elements must support multiplication
    and addition both with themselves and with the elements of `c`.

    If `c` has fewer than two dimensions, ones are implicitly appended to
    its shape to make it 2-D. The shape of the result will be c.shape[2:] +
    x.shape + y.shape.

    Parameters
    ----------
    x, y : array_like, compatible objects
        The two dimensional series is evaluated at the points in the
        Cartesian product of `x` and `y`.  If `x` or `y` is a list or
        tuple, it is first converted to an ndarray, otherwise it is left
        unchanged and, if it isn't an ndarray, it is treated as a scalar.
    c : array_like
        Array of coefficients ordered so that the coefficients for terms of
        degree i,j are contained in ``c[i,j]``. If `c` has dimension
        greater than two the remaining indices enumerate multiple sets of
        coefficients.

    Returns
    -------
    values : ndarray, compatible object
        The values of the two dimensional polynomial at points in the Cartesian
        product of `x` and `y`.

    See Also
    --------
    polyval2d, polyfit2d
    numpy.polynomial.polynomial.polygrid2d
    """
    from numpy.polynomial.polynomial import polygrid2d

    c = np.asarray(c)
    if c.ndim != 2 or c.shape[0] != c.shape[1]:
        raise ValueError("c must be a squard 2-dim array.")
    return polygrid2d(x, y, c)

def polyval2d(x, y, c):
    """Evaluate a 2-D polynomial at points (x, y).

    This function returns the value

    .. math:: p(x,y) = \\sum_{i,j} c_{i,j} * x^i * y^j

    Parameters
    ----------
    x, y : array_like, compatible objects
        The two dimensional series is evaluated at the points (x, y), where x
        and y must have the same shape. If x or y is a list or tuple, it is
        first converted to an ndarray, otherwise it is left unchanged and, if it
        is not an ndarray, it is treated as a scalar.
    c : array_like
        Array of coefficients ordered so that the coefficient of the term of
        multi-degree i,j is contained in `c[i,j]`.

    Returnes
    --------
    values : ndarray, compatible object
        The values of the two dimensional polynomial at points formed with pairs
        of corresponding values from x and y.

    See Also
    --------
    polygrid2d, polyfit2d
    numpy.polynomial.polynomial.polyval2d
    """
    from numpy.polynomial.polynomial import polyval2d

    c = np.asarray(c)
    if c.ndim != 2 or c.shape[0] != c.shape[1]:
        raise ValueError("c must be a squared 2-dim array.")
    return polyval2d(x, y, c)


import turtle as t
STARTING_POSITION = (0, -280)
MOVE_DISTANCE = 10
FINISH_LINE_Y = 280

class Player(t.Turtle):
    def __init__(self) -> None:
        super().__init__()
        self.shape("turtle")
        self.penup()
        self.restart()
        self.setheading(90)

    def restart(self):
        self.goto(STARTING_POSITION)

    def up(self):
        new_y = self.ycor() + 10
        self.goto(self.xcor(),new_y)

    def is_at_finish(self):
        if self.ycor() > FINISH_LINE_Y:
            return True
        else:
            return False


import numpy as np
import matplotlib.pyplot as plt

class PointData(object):
    def __init__(self,x,y):
        self.x = x
        self.y = y
    def getPoint(self):
        return (self.x, self.y)

def GongZhenFunc(n):
    y=1.08722 * (70000*20 - n*n - (float)(n/3.0)*(n/3.0) - (float)(n/5.0)*(n/5.0) -
    (float)(n/8.0)*(n/8.0) - (float)(250000-(n-499)*(n-499))*2.2)
    return (n,y)

def eocgongzhen(n ):
    return 0.945 * (40000*20 - n*n - (float)(n/3)*(n/3) - (float)(n/5)*(n/5) -
    (float)(n/8)*(n/8) - (float)(250000-(n-499)*(n-499))*2.2)

if __name__ == "__main__":
    '''
    x = np.linspace(0, 2 * np.pi, 100)
    y1, y2 = np.sin(x), np.cos(x)

    plt.plot(x, y1)
    plt.plot(x, y2)

    plt.title('line chart')
    plt.xlabel('x')
    plt.ylabel('y')

    plt.show()
    '''
    '''
    sum = 0.0
    xslice = []
    yslice = []
    for i in range(1000):
        res = GongZhenFunc(i)
        sum = sum + res[1]
        yslice.append(res[1])
        xslice.append(i)
        print("tokennum is %f,  totalnum is %f" %(res[1], sum))

    plt.plot(xslice, yslice)
    plt.title('gognzhen chart')
    plt.xlabel('x')
    plt.ylabel('y')
    #plt.legend()
    plt.show()
    '''

    sum = 0.0
    xslice = []
    yslice = []
    for i in range(465):
        res = eocgongzhen(i)
        sum = sum + res
        yslice.append(res)
        xslice.append(i)
        print("tokennum is %f,  totalnum is %f" %(res, sum))

    plt.plot(xslice, yslice)
    plt.title('gognzhen chart')
    plt.xlabel('x')
    plt.ylabel('y')
    #plt.legend()
    plt.show()


import argparse
from sklearn.pipeline import Pipeline
from pathlib import Path
import pandas as pd
from importlib import reload
import sys
import shutil

import processers as procs

reload(procs)

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

    parser.add_argument(
        "-i",
        "--input",
        default="./input",
        help="Path to input directory w/ data in input/houses or input/floods/ subdirs",
    )
    parser.add_argument(
        "-e",
        "--exclude",
        choices=["houses", "floods"],
        help="Exclude either input/floods/ or input/houses from processing",
    )
    parser.add_argument(
        "-o", "--output", default="./output", help="Path to output directory"
    )
    parser.add_argument(
        "-f",
        "--format",
        default="png",
        help="Format in which skimage.io.imsave will store final processed images",
    )
    parser.add_argument(
        "-p",
        "--flip",
        default=0.0,
        type=float,
        help="Proportion of inputs to flip l/r (in addition to original image)",
    )
    parser.add_argument(
        "-x",
        "--force",
        action="store_true",
        default=False,
        help="Force overwrite potentially existing output dir",
    )

    args = parser.parse_args()
    print(args)

    dirs = [
        d
        for d in Path(args.input).iterdir()
        if d.is_dir() and (args.exclude is None or args.exclude not in d.name)
    ]

    if not Path(args.output).exists():
        Path(args.output).mkdir()

    for input_dir in dirs:

        print(f"\n### Processing {str(input_dir)} ###")

        out = Path(args.output) / input_dir.name

        if out.exists():
            print("Output destination not empty | overwrite?")
            if args.force or "y" in input("[y/n] : "):
                print("Cleaning", str(out))
                shutil.rmtree(str(out))
                out.mkdir()
            else:
                print("Stopping here")
                sys.exit()
        else:
            out.mkdir()

        pipe = Pipeline(
            steps=[
                ("Loader", procs.Loader(input_dir)),
                ("Flipper", procs.Flipper(args.flip)),
                ("Saver", procs.Saver(out, args.format)),
            ]
        )

        df = pd.DataFrame({"path": [f for f in input_dir.iterdir() if f.is_file()]})
        pipe.fit_transform(df)


import requests
from django.conf import settings

from loguru import logger

from collector.models import City, WeatherData

logger.add("collector_logs_{time}.log")

CITIES = City.objects.all()

def collect_weather_data():
    logger.info("Функция сбора данных о погоде collect_weather_data запущена.")

    weather_objects = []

    for city in CITIES:
        url = f"https://api.openweathermap.org/data/2.5/weather?q={city.name}&appid={settings.OPENWEAWERMAP_API_KEY}"

        try:
            response = requests.get(url)
            response.raise_for_status()
            data = response.json()
            weather = WeatherData(
                city=city,
                temperature=data["main"]["temp"],
                humidity=data["main"]["humidity"],
                wind_speed=data["wind"]["speed"],
                dt=data["dt"],
                timezone=data["timezone"],
            )
            weather_objects.append(weather)

        except requests.RequestException as error:
            logger.exception(
                f"Произошла ошибка при выполнении запроса для города {city}:",
                error,
            )
        except (KeyError, ValueError) as error:
            logger.exception(
                f"Произошла ошибка парсинга для города {city}:",
                error,
            )
        except Exception as error:
            logger.exception(
                f"Ой, неизвестная ошибка для города {city}:",
                error,
            )

    WeatherData.objects.bulk_create(weather_objects)