import discord
from discord.ext import commands
from discord.ext.commands import cooldown
from discord.ext.commands.cooldowns import BucketType
import time
import asyncio
import asyncpg
from datetime import datetime, timedelta, timezone
from random import randint
from random import choice
import psutil
import os
import sys

colors = [0xE56B6B, 0xDD5151, 0xBA3434, 0xAB1F1F, 0x940808]
online = "<:online_status:506963324391653387>"
offline = "<:offline_status:506963324521414661>"
dnd = "<:dnd_status:506963324634791936>"
idle = "<:idle_status:506963324529803264>"

# git fix again again again

class misc(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command(
        description="Give someone a slap", brief="Slap", usage="slap [user]"
    )
    async def slap(self, ctx, *, user: discord.Member):
        embed = discord.Embed(colour=choice(colors))
        embed.set_author(name=f"{ctx.author.name} slapped {user.name}! Ouchy!")
        embed.set_image(url="https://media.giphy.com/media/RXGNsyRb1hDJm/giphy.gif")
        await ctx.send(embed=embed)

    @commands.command(
        description="Give someone a hug! Awwww", brief="Hug", usage="hug [user]"
    )
    async def hug(self, ctx, *, user: discord.Member):
        embed = discord.Embed(colour=choice(colors))
        embed.set_author(name=f"{ctx.author.name} gave {user.name} hug! How cute!")
        embed.set_image(url="https://media.giphy.com/media/lXiRKBj0SAA0EWvbG/giphy.gif")
        await ctx.send(embed=embed)

    @commands.command(
        aliases=["pong"],
        description="Check the bots latency to Discord Websockets",
        brief="Check the bots ping",
        usage="ping",
    )
    async def ping(self, ctx):
        t_1 = time.perf_counter()
        await ctx.trigger_typing()
        t_2 = time.perf_counter()
        time_delta = round((t_2 - t_1) * 1000)
        await ctx.send(
            f":ping_pong: Websocket: `{round(self.bot.latency*1000)}` ms. Typing: `{time_delta}` ms"
        )

    @commands.command(
        aliases=["avy"],
        description="Get a users or your avatar",
        usage="avatar [user]",
        brief="Get a users or your avatar",
    )
    async def avatar(self, ctx, *, user: discord.Member = None):
        user = user or ctx.author
        embed = discord.Embed(colour=0x7289DA, description=f"[Link]({user.avatar_url})")
        embed.set_author(name=f"{user.name}'s avatar", url=user.avatar_url)
        embed.set_image(url=user.avatar_url_as(static_format="png"))
        await ctx.send(embed=embed)

    @commands.command(
        aliases=["about"],
        description="Get stats about the bot",
        brief="Check bot stats",
        usage="info",
    )
    async def info(self, ctx):
        cmds_used = await self.bot.pool.fetchval("""SELECT * FROM commands_used;""")
        uwulonian = await self.bot.pool.fetchval(
            "SELECT count(user_id) FROM user_settings;"
        )
        delta_uptime = datetime.utcnow() - self.bot.launch_time
        hours, remainder = divmod(int(delta_uptime.total_seconds()), 3600)
        minutes, seconds = divmod(remainder, 60)
        days, hours = divmod(hours, 24)
        cpu_usage = self.bot.process.cpu_percent()
        cpu_count = psutil.cpu_count()
        memory_usage = self.bot.process.memory_full_info().uss / (1024 ** 2)
        version = sys.version_info
        user_count = len(self.bot.users)
        embed = discord.Embed(color=0x7289DA)
        embed.set_author(name="Bot Stats")
        embed.add_field(
            name="Owner", value=f"<@300088143422685185> (mellowmarshe#0001)"
        )
        embed.add_field(
            name="Library",
            value=f"[discord.py\\[rewrite\\]](https://github.com/Rapptz/discord.py/tree/rewrite)",
        )
        embed.add_field(
            name="Language",
            value=f"Python {version.major}.{version.minor}.{version.micro}",
        )
        embed.add_field(name="Uptime", value=f"{days}d {hours}h {minutes}m")
        embed.add_field(name="Servers", value=len(self.bot.guilds))
        embed.add_field(
            name="Process",
            value=f"Memory {round(memory_usage, 2)}MiB\nCPU {cpu_usage/cpu_count}%",
        )
        embed.add_field(
            name="Bot Usage",
            value=f"{self.bot.commands_ran} commands used since boot\n{cmds_used + self.bot.commands_ran} commands used\n{uwulonian} uwulonians",
        )
        embed.add_field(name="Members", value=f"{user_count}")
        embed.add_field(
            name="Links",
            value="[Invite](https://discordapp.com/oauth2/authorize?client_id=508725128427995136&scope=bot&permissions=67501248) | [Support](https://discord.gg/733URZq) | [Donate](https://www.patreon.com/mellOwO) | [Vote](https://discordbots.org/bot/508725128427995136/vote) | [Website](https://uwu-bot.xyz/)",
        )
        await ctx.send(embed=embed)

    @commands.command(
        description="Get the link to the support server",
        brief="Get a link to support server.",
    )
    async def support(self, ctx):
        await ctx.send("The link to the support server is https://discord.gg/733URZq")

    @commands.command(
        description="Check our lovely Patrons!", brief="Check out our lovely patrons."
    )
    async def patrons(self, ctx):
        patrons = await self.bot.pool.fetch("SELECT * FROM p_users")
        e = discord.Embed(
            color=0x7289DA, description="Patreon https://www.patreon.com/mellOwO"
        )
        for i in range(len(patrons)):
            user = self.bot.get_user(patrons[i]["user_id"])
            time_p = datetime.now(timezone.utc) - patrons[i]["patron_time"]
            e.add_field(
                name=user.name,
                value=f"{patrons[i]['tier']} | Has been a patron for `{int(time_p.days)}` days!",
            )
        e.set_author(name="Our awesome Patrons")
        await ctx.send(embed=e)

    @commands.command(description="Send voting link", brief="Send a link to vote")
    async def upvote(self, ctx):
        await ctx.send(
            "You can vote for me here! https://discordbots.org/bot/508725128427995136/vote or <https://botsfordiscord.com/bot/508725128427995136/vote> I greatly appreciate voting as it helps the bot a lot"
        )

    @commands.command(description="Bot rules", aliases=["tos"], brief="Our bot rules")
    async def rules(self, ctx):
        await ctx.send(
            """
uwu rules. You must follow these or we will take action
`-` Don't spam or abuse commands with the intent to harm or slow the bot down. We want the best experience for our users anything to harm this is a problem.
`-` Don't rename or create an uwulonian with a harmful, racist, or any name that can offend someone. We will most likely delete your uwulonian if you do this.
`-` The use of scripts or anything to gain an advantage is forbidden.
`-` DM staff if you are having problems with the bot don't DM regular members unless they say you can.
"""
        )

    @commands.command(description="Get bot invite link", brief="Get invite for bot")
    async def invite(self, ctx):
        permissions = discord.Permissions()

        permissions.update(
            add_reactions=True,
            attach_files=True,
            change_nickname=True,
            embed_links=True,
            external_emojis=True,
            manage_messages=True,
            read_messages=True,
            read_message_history=True,
            send_messages=True,
            send_tts_messages=True,
            view_audit_log=True,
        )

        await ctx.send(
            f"<{discord.utils.oauth_url(self.bot.user.id, permissions=permissions)}>"
        )

    @commands.command(description="Snipe a deleted message", aliases=["snipsnop"])
    async def snipe(self, ctx, channel: discord.TextChannel = None):
        if channel is None:
            channel = ctx.channel
        snop = await self.bot.pool.fetchrow(
            "SELECT * FROM del_snipe WHERE channel_id = $1 AND guild_id = $2",
            channel.id,
            ctx.guild.id,
        )
        if snop is None:
            return await ctx.send("Nothing to snipe", delete_after=30)
        if channel.is_nsfw() is True and ctx.channel.is_nsfw() is False:
            return await ctx.send(
                "No sniping NSFW outside of NSFW channel.", delete_after=30
            )
        user = self.bot.get_user(snop["user_id"])
        guild = self.bot.get_guild(snop["guild_id"])
        chnl = discord.utils.get(guild.text_channels, id=snop["channel_id"])
        del_time = datetime.now(timezone.utc) - snop["msg_time"]
        if snop["msg_type"] == 1:
            e = discord.Embed(
                colour=0x7289DA, description="The image may not be visible"
            )
            e.set_author(name=f"{user.name} sent in {chnl.name}")
            e.set_image(url=snop["message"])
            e.set_footer(text=f"sniped!")
            await ctx.send(embed=e)
        else:
            user = self.bot.get_user(snop["user_id"])
            guild = self.bot.get_guild(snop["guild_id"])
            chnl = discord.utils.get(guild.text_channels, id=snop["channel_id"])
            e = discord.Embed(colour=0x7289DA, description=snop["message"])
            e.set_author(name=f"{user.name} said in {chnl.name}")
            e.set_footer(text=f"sniped!")
            await ctx.send(embed=e)

    @commands.command(description="Report a bug or user")
    async def report(
        self,
        ctx,
        *,
        report: commands.clean_content(
            fix_channel_mentions=False, use_nicknames=False, escape_markdown=True
        ),
    ):
        if len(report) > 512:
            return await ctx.send("Your report was too long")

        supp = self.bot.get_channel(529_722_574_301_560_842)
        e = discord.Embed(
            color=0xFF0000, description=f"```{report}```", timestamp=datetime.utcnow()
        )
        e.set_author(
            name=f"Report by {ctx.author}({ctx.author.id}) in {ctx.guild.name}({ctx.guild.id})"
        )
        e.set_footer(text="Report at")
        await ctx.send(
            "Your report was sent. Join the support server for news on your report!"
        )
        await supp.send(embed=e)

    # Sourced mainly from NekoBot https://github.com/hibikidesu/NekoBot/blob/master/modules/fun.py
    @commands.command()
    async def minesweeper(self, ctx, size: int = 5):
        m_offsets = [
            (-1, -1),
            (0, -1),
            (1, -1),
            (-1, 0),
            (1, 0),
            (-1, 1),
            (0, 1),
            (1, 1),
        ]
        m_numbers = [":one:", ":two:", ":three:", ":four:", ":five:", ":six:"]
        size = max(min(size, 8), 2)
        bombs = [
            [randint(0, size - 1), randint(0, size - 1)] for x in range(int(size - 1))
        ]
        is_on_board = lambda x, y: 0 <= x < size and 0 <= y < size
        has_bomb = lambda x, y: [i for i in bombs if i[0] == x and i[1] == y]
        embed = discord.Embed(color=0x7289DA, description="")
        embed.set_author(name="Press to play")
        for y in range(size):
            for x in range(size):
                tile = f"||{chr(11036)}||"
                if has_bomb(x, y):
                    tile = f"||{chr(128163)}||"
                else:
                    count = 0
                    for xmod, ymod in m_offsets:
                        if is_on_board(x + xmod, y + ymod) and has_bomb(
                            x + xmod, y + ymod
                        ):
                            count += 1
                    if count != 0:
                        tile = f"||{m_numbers[count - 1]}||"
                embed.description += tile
            embed.description += "\n"
        await ctx.send(embed=embed)

    @commands.command(aliases=["8ball"])
    async def eightball(self, ctx, *, question):
        responses = [
            "It is certain.",
            "It is decidedly so.",
            "Without a doubt.",
            "Yes - definitely.",
            "You may rely on it.",
            "As I see it, yes.",
            "Most likely.",
            "Outlook good.",
            "Yes.",
            "Signs point to yes.",
            "Reply hazy, try again.",
            "Ask again later.",
            "Better not tell you now.",
            "Cannot predict now.",
            "Concentrate and ask again.",
            "Don't count on it.",
            "My reply is no.",
            "My sources say no.",
            "Outlook not so good.",
            "Very doubtful.",
        ]
        msg = await ctx.send(f"Q: **{question}...**")
        await asyncio.sleep(3)
        await msg.edit(content=f"A: **{choice(responses)}**")

    @commands.command(aliases=["lovedar"])
    async def love(self, ctx, lover: discord.Member, lovee: discord.Member):
        msg = await ctx.send("**Calculating...**")
        await asyncio.sleep(3)
        seed(int(str(lover.id) + str(lovee.id)))
        if lover == lovee:
            love = 0
        else:
            love = randint(1, 10000) / 100
        await msg.edit(
            content=f"The love calculator says {lover.name} loves {lovee.name} **{love}**%"
        )

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


import torch
from einops import rearrange

import padertorch as pt

class RCNN1d(pt.Module):

    def __init__(
        self, rnn=None, cnn=None, linear=None, reverse=False,
    ):
        super().__init__()
        self.cnn = cnn
        self.rnn = rnn
        self.linear = linear

        self.reverse = reverse

    def conv(self, x, sequence_lengths):
        if self.cnn is None:
            return x, sequence_lengths
        h = rearrange(x, 'b t f -> b f t')
        h, seq_len_h = self.cnn(h, sequence_lengths)
        h = rearrange(h, 'b f t -> b t f')
        return h, seq_len_h

    def forward(
        self, x, sequence_lengths=None, segment_starts=None, segment_stops=None
    ):
        assert x.ndim == 3, x.shape
        h = x
        if self.reverse:
            h = torch.flip(x, (1,))
        if self.rnn is not None:
            h, _ = self.rnn(h)
        if self.linear is not None:
            h = self.linear(h)
        h, seq_len_h = self.conv(h, sequence_lengths)
        return h, seq_len_h


import matplotlib.pyplot as plt
from tabulate import tabulate
from art import *

print(logo)
print("*" * 200)

def func(x, y):
    """
    :return: returns function value by putting value of x and y.
    """
    res = (1 + y)
    return res

def predictor(y3, h, f3, f2, f1, f0):
    """
    :return: returns predictor value by putting values in formula -> y3 + (h / 24) * ((55 * f3) - (59 * f2) + (37 * f1)
    - (9 * f0))
    """
    y4p = round(y3 + (h / 24) * ((55 * f3) - (59 * f2) + (37 * f1) - (9 * f0)), 4)
    # y4p1 = round(y4p,4)
    print(f"Predictor Value , y4p = {y4p}\n")
    return y4p

def corrector(y3, h, f4p, f3, f2, f1):
    """
    :return: returns corrector value by putting values in formula -> y3 + (h / 24) * ((9 * f4p) + (19 * f3) - (5 * f2)
    + f1)
    """
    y4c = round(y3 + (h / 24) * ((9 * f4p) + (19 * f3) - (5 * f2) + f1), 4)
    # y4c1 = round(y4c,4)
    # print(f"Corrector Value, y4c = {y4c1}")
    return y4c

# Taking User inputs
x0 = float(input("Enter Value of x0: "))
x1 = float(input("Enter Value of x1: "))
x2 = float(input("Enter Value of x2: "))
x3 = float(input("Enter Value of x3: "))
x4 = float(input("Enter Value of x4: "))
y0 = float(input("Enter Value of y0: "))
y1 = float(input("Enter Value of y1: "))
y2 = float(input("Enter Value of y2: "))
y3 = float(input("Enter Value of y3: "))

# Tabulating the given data.
data = [[x0, y0],
        [x1, y1],
        [x2, y2],
        [x3, y3],
        [x4, "?"]]
print("\nGiven Values in tabulated form: ")
print(tabulate(data, headers=["x", "y"]))

print(f"\nWe have to find y({x4})\n")
h = round((x1 - x0), 4)
print(f"Value of h i.e.(x1-x0) is: {h}\n")

f0 = round(func(x0, y0), 4)
print(f"f0 = {f0}")
f1 = round(func(x1, y1), 4)
print(f"f1 = {f1}")
f2 = round(func(x2, y2), 4)
print(f"f2 = {f2}")
f3 = round(func(x3, y3), 4)
print(f"f3 = {f3}\n")

y4p = predictor(y3, h, f3, f2, f1, f0)
f4p = round(func(x4, y4p), 4)
print(f"f4p1 = {f4p}")
y4c = corrector(y3, h, f4p, f3, f2, f1)
print(f"Corrector Value, y4c1 = {y4c}\n")
count = 2
# While loop to check previous corector value is not equal to current value.
while y4c != y4p:
    y4p = y4c
    f4p = round(func(x4, y4p), 4)
    print(f"f4p{count} = {f4p}")
    y4c = corrector(y3, h, f4p, f3, f2, f1)
    print(f"Corrector Value, y4c{count} = {y4c}\n")

    count += 1

print(f"\nAs y4c{count - 1} = y4c{count - 2}.Therefore, y({x4}) = {y4c}\n\n\n")
print(end)

# Graph Plotting of the given function.
x_axis = [x0, x1, x2, x3, x4]
y_axis = [y0, y1, y2, y3, y4c]
plt.plot(x_axis, y_axis)
plt.xlabel("X")
plt.ylabel("Y")
plt.title("x-y graph of given function")
plt.show()


import numpy as np
import torch
import sys
sys.path.append("./")
from azureml.core.model import Model
import os
import model as model_classes
from transformers import AutoTokenizer, AutoModel, AutoConfig
from general_utils import read_yaml_file
from dataset_utils import parse_classes_list, convert_examples_to_features
import json

def init():
    global classes_list, tokenizer, model, configs
    model_name_id_AML = "neural_model_registration_2" # After you register the model to AML
    model_name_path = Model.get_model_path(model_name_id_AML)
    print("PATH TO MODEL")
    print(model_name_path)
    config_file_path = os.path.join(model_name_path, "config_model.yaml")
    data_classes_path = "/var/azureml-app/NeuralDialectDetectorWebApp/dataset_dummy"
    classes_list = parse_classes_list(data_classes_path)
    classes_list.sort()
    configs = read_yaml_file(config_file_path)
    configs["num_labels"] = len(classes_list)
    configs["device"] = "cpu"
    configs["use_vert_att"] = True
    configs["model_name_path"] = model_name_path
    tokenizer = AutoTokenizer.from_pretrained(model_name_path)
    model_config = AutoConfig.from_pretrained(model_name_path)
    configs["mask_id"] = tokenizer.convert_tokens_to_ids(tokenizer.mask_token)
    model = getattr(model_classes, configs["model_class"]).from_pretrained(model_name_path,
                                                            config=model_config,
                                                            args=configs)

def run(data):
    data_loaded = json.loads(data)
    input_sentence = data_loaded["input"]
    input_example = ("PREDICT_0", input_sentence, "None")
    max_seq_len = configs["max_sequence_length"]
    feats = convert_examples_to_features([input_example], classes_list, max_seq_len, tokenizer)[0]
    feats = [torch.tensor(x).unsqueeze(0) for x in feats]
    model_out = model(input_ids=feats[0], attention_mask=feats[1], token_type_ids=feats[2], class_label_ids=None, input_ids_masked=feats[4])
    logits_softmaxed = torch.nn.functional.softmax(model_out[1][0], dim=-1).detach().cpu().numpy()
    return {"country_prediction": str(classes_list[np.argmax(logits_softmaxed)]), "province_prediction": "None"}


def cal(x, y):
    plus = x + y
    minus = x - y
    multi = x * y
    try:
        div = x // y
    except ZeroDivisionError:
        div=0
    return [plus, minus, multi, div]

result = [ [5], [ 5+ 5, 5-5, 5* 5, 5 // 5]]
cnt = 2
number=12

while cnt<8:
    input = []
    for i in range(len(result[cnt-1])):
        for j in range(len(result[cnt-2])):
            input.append(cal(result[cnt-2][j],result[cnt-1][i]))
    result.append(input)
    if number in result[cnt] :
        print(cnt)
        break
    else:
        cnt+=1


# coding=utf-8
import logger
import re
import sys
import time

import InventoryUtils
import AgentUtils

from com.hp.ucmdb.discovery.library.clients import ClientsConsts
from com.hp.ucmdb.discovery.probe.agents.probemgr.workflow.state import WorkflowStepStatus

def StepMain(Framework):
    InventoryUtils.executeStep(Framework, checkAgentUnInstalledRoutine, InventoryUtils.STEP_REQUIRES_CONNECTION, InventoryUtils.STEP_DOESNOT_REQUIRES_LOCK)

#It will try to connect remote agent with all credentials:
#1. If the connected credential is UDA, we will show error code for debugging, the job will be parking.
#2. If the connected credential is non-UDA, we will check error code and decide whether the job will return with SUCCESS/FAILURE/FATAL_FAILURE
#3. If no credential can be connected, the job will return with SUCCESS.
def checkAgentUnInstalledRoutine(Framework):
    Framework.setStepExecutionStatus(WorkflowStepStatus.FAILURE)
    protocolName = Framework.getProperty(InventoryUtils.STATE_PROPERTY_CONNECTED_SHELL_PROTOCOL_NAME)
    logger.debug('Protocal name: ', protocolName)

    if protocolName != ClientsConsts.DDM_AGENT_PROTOCOL_NAME:
        # Wait for 5 secs to let agent to be uninstalled.
        time.sleep(5)
        errorCode = AgentUtils.getUninstallErrorCode(Framework)
        if errorCode:
            if errorCode.isSuccess():
                logger.debug('Agent is uninstalled!!!!')
                Framework.setStepExecutionStatus(WorkflowStepStatus.SUCCESS)
            elif errorCode.isInProgress():
                logger.debug('Can not get error code from agent. Maybe the UDA is uninstalling. It will check again after parking.')
            else:
                logger.debug('Failed to uninstall agent according to error code.')
                Framework.setStepExecutionStatus(WorkflowStepStatus.FATAL_FAILURE)
                Framework.reportError(errorCode.getMessage())
        else:
            logger.debug('Can not get error code now. It will check again after parking.')
    else:
        logger.debug('The connected credential is UDA. Maybe the UDA is uninstalling. It will check again after parking.')


import sys
from PyQt4 import QtCore, QtGui

class MiVentana(QtGui.QDialog):
    def __init__(self, parent = None):
        QtGui.QWidget.__init__(self, parent)
        self.setWindowTitle("Testeo")
        self.setGeometry(100,100,600,400)

        quit = QtGui.QPushButton("Cerrar", self)
        quit.setGeometry(460,330,80,30)
        self.connect(quit, QtCore.SIGNAL("clicked()"), QtGui.qApp, QtCore.SLOT("quit()"))

        acepta = QtGui.QPushButton("Aceptar", self)
        acepta.setGeometry(370,330,80,30)
        self.connect(acepta, QtCore.SIGNAL("clicked()"), self.calcula)

        etiquetavalor1 = QtGui.QLabel("Ingresa el primer valor: ", self)
        etiquetavalor1.setGeometry(50,30,150,30)
        self.lineavalor1 = QtGui.QLineEdit(self)
        self.lineavalor1.setGeometry(210,30,150,30)
        etiquetavalor2 = QtGui.QLabel("Ingresa el segundo valor: ", self)
        etiquetavalor2.setGeometry(50,70,150,30)
        self.lineavalor2 = QtGui.QLineEdit(self)
        self.lineavalor2.setGeometry(210,70,150,30)

        self.etiquetaresultado = QtGui.QLabel("Resultado: ",self)
        self.etiquetaresultado.setGeometry(135,110,150,30)

        self.botonsumar = QtGui.QRadioButton("Sumar", self)
        self.botonsumar.setGeometry(180,170,70,30)
        self.botonsumar.setChecked(True)
        self.botonrestar = QtGui.QRadioButton("Restar", self)
        self.botonrestar.setGeometry(180,200,70,30)
        self.botonmultiplicar = QtGui.QRadioButton("Multiplicar", self)
        self.botonmultiplicar.setGeometry(180,230,90,30)
        self.botondividir = QtGui.QRadioButton("Dividir", self)
        self.botondividir.setGeometry(180,260,70,30)

    def calcula(self):
        if len(self.lineavalor1.text()) != 0:
            a = int(self.lineavalor1.text())
        else:
            a = 0
        if len(self.lineavalor2.text()) != 0:
            b = int(self.lineavalor2.text())
        else:
            b = 0

        if self.botonsumar.isChecked() == True:
            res = a + b
        if self.botonrestar.isChecked() == True:
            res = a - b
        if self.botonmultiplicar.isChecked() == True:
            res = a * b
        if self.botondividir.isChecked() == True:
            res = a / b

        self.etiquetaresultado.setText("Resultado:  " + str(res))

app = QtGui.QApplication(sys.argv)
myapp = MiVentana()
myapp.show()
sys.exit(app.exec_())


import json
from contracts_api_test.unit.test_base import BaseTestCase
from contracts_api.api.models import Stage, Flow

class FlowsResourceTest(BaseTestCase):
    def setUp(self):
        super(FlowsResourceTest, self).setUp()

        # create fixture stages and flows
        Stage.create(name='stage1').save()
        Stage.create(name='stage2').save()
        self.flow = Flow.create(flow_name='flow1', stage_order=[1,2]).save()

    render_templates = False

    def test_list_get(self):
        flows = json.loads(self.client.get('/api/v1/flows').data)
        self.assertEquals(flows['meta']['count'], 1)

    def test_detail_get(self):
        flow = json.loads(self.client.get('/api/v1/flow/{id}'.format(id=self.flow)).data)
        self.assertEquals(flow['flow_name'], 'flow1')
        self.assertEquals(type(flow), dict)

        bad_flow = self.client.get('/api/v1/flow/10000000')
        self.assertEquals(bad_flow.status_code, 404)

    def test_create(self):
        # test good flow create
        flow = self.client.post('/api/v1/flows', data=json.dumps({
            'flow_name': 'flow2',
            'stage_order': [2,1]
        }))
        self.assertEquals(flow.status_code, 201)

        # test duplicate name
        dupe_flow = self.client.post('/api/v1/flows', data=json.dumps({
            'flow_name': 'flow2',
            'stage_order': []
        }))
        self.assertEquals(dupe_flow.status_code, 400)

        # test bad stages
        bad_stages = self.client.post('/api/v1/flows', data=json.dumps({
            'flow_name': 'flow3',
            'stage_order': [1, 2, 100, 101]
        }))
        self.assertEquals(bad_stages.status_code, 400)
        self.assertTrue('100, 101' in bad_stages.data)
        self.assertTrue('1, 2' not in bad_stages.data)

        # test bad data format
        bad_format = self.client.post('/api/v1/flows', data=json.dumps([]))
        self.assertEquals(bad_format.status_code, 403)

    def test_update(self):
        update_url = '/api/v1/flow/{id}'.format(id=self.flow)

        flow = self.client.put(update_url, data=json.dumps({
            'stage_order': [2,1]
        }))
        self.assertEquals(flow.status_code, 200)

        # test bad stages
        bad_stages = self.client.put(update_url, data=json.dumps({
            'stage_order': [100, 101]
        }))
        self.assertEquals(bad_stages.status_code, 400)

        # test 404 for bad stage id
        no_stage = self.client.put('/api/v1/flow/10000000')
        self.assertEquals(no_stage.status_code, 404)

    def test_delete(self):
        flow = self.client.delete('/api/v1/flow/{id}'.format(id=self.flow))
        self.assertEquals(flow.status_code, 204)

        bad_flow = self.client.delete('/api/v1/flow/10000000')
        self.assertEquals(bad_flow.status_code, 404)


import cv2

img = cv2.imread('image/hinhanh.jpg', 0)
img = cv2.medianBlur(img, 5)

ret, th1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
th2 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C,
                            cv2.THRESH_BINARY, 11, 2)
th3 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                            cv2.THRESH_BINARY, 11, 2)
th4 = cv2.adaptiveThreshold(img, 255,
                            cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 21, 4)
th5 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                            cv2.THRESH_BINARY, 71, 2)
th6 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                            cv2.THRESH_BINARY, 101, 4)
titles = ['Original Image', 'Global Thresholding (v = 127)',
          'Adaptive Mean Thresholding', 'Adaptive Gaussian Thresholding', 'AdaptiveGaussianThresholding 20', 'AdaptiveGaussianThresholding 30', 'AdaptiveGaussianThresholding 40']
images = [img, th1, th2, th3, th4, th5, th6]
xrange = [0, 1, 2, 3, 4, 5, 6]

for i in xrange:
    # plt.subplot(3, 3, i+1), plt.imshow(images[i], 'gray')
    # plt.title(titles[i])
    # plt.xticks([]), plt.yticks([])
    cv2.imshow(titles[i], images[i])
cv2.waitKey(0)
cv2.destroyAllWindows()


import string

from PIL import ImageFont
from PIL import Image
from PIL import ImageDraw
import numpy as np

FONT_NAME = "MTRXHeadline-Regular.ttf"
FONT_COLOURS = ["#000000", "#ff0000", "#a00041", "#ff9e1c", "#ffffff"]

font = ImageFont.truetype(f"fonts/{FONT_NAME}", 200)

def save_image(img: Image, letter: str, colour: str, height: int):
    height_percent = (height / float(img.size[1]))
    width_size = int((float(img.size[0]) * float(height_percent)))
    new_image = img.resize((width_size, height), Image.ANTIALIAS)
    new_image.save(f"output/{height}/{FONT_NAME.split('.')[0]}-{colour[1:]}-{letter}.png")

def get_image(letter: chr, colour: str):
    image = Image.new("RGBA", (500, 300), (255, 255, 255, 0))
    draw = ImageDraw.Draw(image)
    draw.text((0, 0), letter, colour, font=font)
    ImageDraw.Draw(image)

    image_data = np.asarray(image)
    image_data_columns = image_data.max(axis=0, initial=0)
    image_data_rows = image_data.max(axis=1, initial=0)
    non_empty_columns = [col[3] for col in image_data_columns]
    non_empty_rows = [row[3] for row in image_data_rows]

    column_0 = next((i for i, x in enumerate(non_empty_columns) if x != 0), 0)
    column_1 = len(non_empty_columns) - next((i for i, x in enumerate(reversed(non_empty_columns)) if x != 0), -1)

    # row_0 = next((i for i, x in enumerate(non_empty_rows) if x != 0), 0)
    # row_1 = len(non_empty_rows) - next((i for i, x in enumerate(reversed(non_empty_rows)) if x != 0), -1)

    crop_box = (0, 275, column_0, column_1)

    image_data_new = image_data[crop_box[0]:crop_box[1]+1, crop_box[2]:crop_box[3]+1, :]
    new_image = Image.fromarray(image_data_new)

    for height in [25, 50, 100, 250]:
        save_image(img=new_image, letter=letter, colour=colour, height=height)

for c in string.ascii_letters + string.digits + "!-:.,+åÅöÖäÄøØæÆ%&()=;*€$<>":
    for colour in FONT_COLOURS:
        get_image(letter=c, colour=colour)


"""
    create indes for the project
"""

from os import listdir
from pickle import dump as save_to_pickle_file
from typing import Counter, Dict, List
# from pandas import DataFrame
from methods import process_document, INDEX_DIR, ARTICLES_DIR

# df = DataFrame()

def create_language_model_from_collection(collection: List[str]) -> Dict[str, float]:
    """
        generate language model from collection

    Args:
        collection (List[str]): [description]

    Returns:
        Dict[str, float]: [description]
    """
    language_model = {}
    counter = 0

    for doc in collection:
        counter += len(doc)
        for word in doc.split():
            if word not in language_model:
                language_model[word] = 1
            else:
                language_model[word] += 1

    # calculate probability of a word in the collection
    for word in language_model:
        language_model[word] = round(language_model[word] / counter*100, 7)
        # language_model[word] / counter

    return language_model

res: Dict[str, float] = None

def main():
    global res
    articels = listdir(ARTICLES_DIR)
    collection = []
    for art in articels[:2]:
        with open(f"{ARTICLES_DIR}/{art}", "r") as file:
            collection.append(file.read())
    res = create_language_model_from_collection(collection)

    # res = process_document(f"{ARTICLES_DIR}/art")
    # index_pickle = open(f"{INDEX_DIR}indexPickleAfterDoc{art}", "w")
    # df = df.append(res, ignore_index=True)
    # with open(f"{INDEX_DIR}indexPickleAfterDoc{art}", "w+") as index_pickle:
    # save_to_pickle_file(df, index_pickle)

main()


import json

def point_to_wkt(point):
    return str(point["latitude"]) + " " + str(point["longitude"]) + ", "

def route_to_wkt_from_string(route):
    parsed = json.loads(route)
    route_to_wkt(parsed)

def route_to_wkt(parsed):
    routes = parsed["routes"]
    first_route = routes[0]
    legs = first_route["legs"]
    first_leg = legs[0]
    points = first_leg["points"]

    transformed = list(map(point_to_wkt, points))

    linestring = "LINESTRING ("
    for point in transformed:
        linestring = linestring + point
    linestring = linestring[:-2] + ")"

    return linestring


from common.constants import PubSubTopic
from common.event_handler import pubsub_publish
from common.logs import logger
from fastapi import FastAPI, HTTPException, status
from models import Editor, Source, Topic
from provider import Provider

app = FastAPI(
    version="0.1.0",
    title="[timgiuptui] Platform Service",
    description="Platform service documentation",
    swagger_ui_parameters={"displayRequestDuration": True},
)

provider = Provider()

@app.get("/", status_code=status.HTTP_200_OK)
def health():
    return "OK"

@app.get("/topics", status_code=status.HTTP_200_OK, response_model=list[Topic])
def get_topics():
    try:
        topics = provider.get_topics()
        return topics
    except Exception as e:
        logger.error(e)
        return []

@app.get("/editors", status_code=status.HTTP_200_OK, response_model=list[Editor])
def get_editors():
    try:
        editors = provider.get_editors()
        return editors
    except Exception as e:
        logger.error(e)
        return []

@app.post("/crawler/sources", status_code=status.HTTP_200_OK, include_in_schema=False)
def get_sources():
    sources: list[Source] = []
    try:
        sources = provider.get_sources()
    except Exception as e:
        logger.error(e)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Cannot get sources",
        )
    sources_json = [source.dict() for source in sources]
    pubsub_publish(topic=PubSubTopic.START_CRAWLING, data=sources_json)
    return sources_json


# Risk On or Risk Off Leveraged S&P 500
from blankly import Alpaca, Strategy, StrategyState
from blankly.metrics import cum_returns
from blankly import trunc

def price_event(price, symbol, state: StrategyState):
    '''Buy and hold 'SPY' '''
    state.variables['history'].append(price)
    if state.variables['own_position'] == False:
        qty = int(state.interface.cash / price)
        state.interface.market_order(symbol, 'buy', qty)
        state.variables['own_position'] = True

def init(symbol, state: StrategyState):
    # Download price data of the 'SPY'
    state.variables['history'] =  state.interface.history(symbol, 150, resolution=state.resolution, return_as='deque')['close']
    state.variables['own_position'] = False

if __name__ == "__main__":
    # Authenticate Alpaca strategy
    exchange = Alpaca()

    # Use our strategy helper on Alpaca
    strategy = Strategy(exchange)

    # Run the compare price event function every time we check for a new price - by default that is 15 seconds
    strategy.add_price_event(price_event, 'SPY', resolution='1d', init=init)

    # Start the strategy. This will begin each of the price event ticks
    # strategy.start()
    # Or backtest using this
    results = strategy.backtest(to='2y', initial_values={'USD': 10000})
    print(results)


import numpy as np
import random
# Grid generator
# Initial Grid
grid = []
visited = []
neighbor = []
mode = 'random'
# Change the range to change the size of the grid
gridsize = 101
for i in range(gridsize):
    grid.append([])
    for j in range(gridsize):
        grid[i].append(0)
# Create Walls for grid
# There are different modes to generate the mazes
# Walls are represented as 1
'''
Figure3 mode
Note that this mode should only run when the grid size is 5
This mode will generate a maze from the assignment
'''
if(mode == 'figure3'):
    print(mode)
    grid[1][2] = 1
    grid[2][2] = 1
    grid[3][2] = 1
    grid[2][3] = 1
    grid[3][3] = 1
    grid[4][3] = 1
    grid[4][2] = 2
    grid[4][4] = 3
'''
Easy Mode:
Just go through the grid and set a 30% chance that a section will be blocked
This is a easy way to just to start off the project
'''
if(mode == 'random'):
    for i in range(gridsize):
        for j in range(gridsize):
            # If number is less then 30 then mark the grid space as a wall
            if(random.randint(1, 100) <= 30):
                grid[i][j] = 1
    # Set start and end point (top left -> bottom right)
    grid[0][0] = 2
    grid[gridsize-1][gridsize-1] = 3
'''
Hard Algorithm:
while(len of visited is not gridsize^2):
    check neighbor list for avaliable point
    if there is no valid point pick a random point on the grid
        check if point is in the visited list
        if the point is valid set the wall value depending on random int
        then get the neighbors
        check if neighbors are valid or already have been visited
    if there is a valid neighbor
        select one of the neighbors by random
        set wall value depending on random int

'''
if(mode == 'hard'):
    # start at a random point
    wallx = random.randint(0, gridsize-1)
    wally = random.randint(0, gridsize-1)
    # Add point to visited heap
    grid[wallx][wally] = 1
    visited.append((wallx, wally))
    # From this point check for valid neighbors
'''
# Random start and end point code, might not be needed
# Getting the start point of agent represented by 2
startx = random.randint(0, gridsize-1)
starty = random.randint(0, gridsize-1)
grid[startx][starty] = 2
# Getting the end point target for the agent
endx = random.randint(0, gridsize-1)
endy = random.randint(0, gridsize-1)
# Need to make sure that the end target doesn't equal the start point
# End point is represented by 3
while(endx == startx & endy == starty):
    endx = random.randint(0, gridsize-1)
    endy = random.randint(0, gridsize-1)
grid[endx][endy] = 3
'''
# Take grid and save it to a text file
'''
with open('test.txt', 'w') as filehandle:
    for x in grid:
        filehandle.write('%s\n' % x)
'''
np.savetxt('Grids/test.txt', grid, delimiter=",", newline="\n", fmt='%i')
# Print final grid to check output
for x in range(50):
    grid = []
    for i in range(gridsize):
        grid.append([])
        for j in range(gridsize):
            grid[i].append(0)
    for i in range(gridsize):
        for j in range(gridsize):
            # If number is less then 30 then mark the grid space as a wall
            if(random.randint(1, 100) <= 30):
                grid[i][j] = 1
    # Set start and end point (top left -> bottom right)
    grid[0][0] = 2
    grid[gridsize-1][gridsize-1] = 3
    filename = 'grid'+str(x)+'.txt'
    np.savetxt('Grids/'+filename, grid, delimiter=",", newline="\n", fmt='%i')


from multiprocessing import Pool, cpu_count
from ReconnectingRTSPGear.ReconnectingRTSPGear import ReconnectingRTSPGear
from vidgear.gears import StreamGear
from vidgear.gears.helper import reducer
import logging
import os

logging.basicConfig(level=logging.INFO)

def start_stream(cameras: dict[int, str]):
    camera_gears: dict[int, ReconnectingRTSPGear] = {}

    # Синхронно захватываем видео в процессе
    for key in cameras.keys():
        print(cameras[key])
        camera_gears[key] = ReconnectingRTSPGear(
            cam_address=cameras[key],
            reset_attempts=20,
            reset_delay=5,
            is_logging=True
        )

    stream_gears: dict[int, StreamGear] = {}

    #  Синхронно стримим на фронт
    for key in cameras.keys():
        stream_params = {"-vf": "scale=1280:-2", "-profile:v": "high444", "-livestream": True, "-streams": [
            {"-resolution": "640x360"}]}
        stream_gears[key] = StreamGear(output=f"streams/hls{key}/cam{key}.m3u8", format="hls",
                                       logging=True, **stream_params)

    while True:
        is_error = False
        for cam_key in cameras.keys():
            frame = camera_gears[cam_key].read()
            if frame is None:
                is_error = True
                break

            reduce_frame = reducer(frame, percentage=50)
            for key in stream_gears.keys():
                stream_gears[key].stream(reduce_frame)

        if is_error:
            for cam_key in cameras.keys():
                camera_gears[cam_key].stop()
                stream_gears[cam_key].terminate()
            break

def process(cameras: dict[int, str]):
    start_stream(cameras)

if __name__ == '__main__':
    num_workers = cpu_count()

    # get this from database
    sources = [({1: "./test_violence_videos/violence2.mp4"},)]

    for t in sources:
        for d in t:
            for cam_id in d.keys():
                if os.path.exists(f'streams/hls{cam_id}'):
                    try:
                        os.rmdir(f'streams/hls{cam_id}')
                        os.mkdir(f'streams/hls{cam_id}')
                        logging.info(f'Made new directory to save stream: streams/hls{cam_id}')
                    except OSError:
                        logging.error('Unable to recreate directory')
                else:
                    try:
                        os.mkdir(f'streams/hls{cam_id}')
                        logging.info(f'Made new directory to save stream: streams/hls{cam_id}')
                    except OSError:
                        logging.error('Unable to create directory')

    with Pool(processes=num_workers) as pool:
        pool.starmap(process,
                     [s for s in sources])


# -*- coding: utf-8 -*-
"""
Created on Fri Oct  5 18:56:30 2018

@author: Andrei ROG
"""
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np
from sklearn.decomposition import PCA
from random import seed
from random import random
from random import gauss
import random
import copy
from scipy import stats

def data_rand(N,M,sigma,Groups=2):

    # create the data container
    data_rand = []
    Labels = []
    # seed random number generator

    # generate random numbers between 0-1
    for _ in range(M):
        mean_random  = random.randint(50,150)#create one mean value
        v = []#create the sample points for each variable
        for k in range(N):
            v.append(gauss(mean_random, random.randint(sigma,2*sigma)))
        data_rand.append(v)
    for _ in range(N):
        Labels.append(random.randint(0,Groups-1))
    return data_rand,Labels

def add_signifficance(data,Labels,Groups,averageSig,sigma,sigvars):
    sig = []
    for j in Groups:
        if j>0:
            for v in sigvars:
                k = random.randint(averageSig-2*sigma,averageSig+2*sigma) + gauss(0, random.randint(sigma,2*sigma))
                sig.append(k)
                data[Labels==j,v] = data[Labels==j,v] + k
    return data,sig

def JSDe(X,Y,w,k):
    #project the data to k
    N,M = np.shape(X)
    T = np.repeat([k],N,0)
    xp = np.sort(np.sum(X*T,1)/np.linalg.norm(k)**2)
    j = 0
    JSDe = 0
    C = np.unique(Y)
    for c in C:
        Xc = X[Y==c,:]
        n,m = np.shape(Xc)
        T = np.repeat([k],n,0)
        xc = np.sort(np.sum(Xc*T,1)/np.linalg.norm(k)**2)
        nc = np.shape(xc)[0]
        jsd = 0
        for i in np.arange(1,nc-1,1):
#            sx = np.min([xp[i]-xp[i-1],xp[i+1]-xp[i]])
#            rx = np.min(np.abs(xc[xc!=xp[i]]-xp[i]))
            sx = np.min(np.abs(xp[xp!=xc[i]]-xc[i]))
            rx = np.min(np.abs([xc[i]-xc[i-1],xc[i+1]-xc[i]]))
            if rx == 0 or sx == 0:
                jsd += (0 + np.log2(N/(nc-1)))
            else:
                jsd += (np.log2(sx/rx) + np.log2(N/(nc-1)))
        JSDe += (w[j]/nc)*jsd
        j += 1
    return JSDe
def JSD(X,Y,w,k,nr_pts,hist = False):
    N,M = np.shape(X)
    T = np.repeat([k],N,0)
    xp = np.sort(np.sum(X*T,1)/np.linalg.norm(k)**2)

#    print(np.log2(Slack*nr_pts))
    pts = np.linspace(np.min(xp),np.max(xp),nr_pts)
    C = np.unique(Y)
    j = 0
    Hc = 0
    jsd = 0
    fmix = np.zeros(np.shape(pts)[0])
#    plt.figure()
    if hist == False:
        for c in C:
            Xc = X[Y==c,:]
            n,m = np.shape(Xc)
            T = np.repeat([k],n,0)
            xc = np.sort(np.sum(Xc*T,1)/np.linalg.norm(k)**2)
            KernelD = stats.gaussian_kde(xc,bw_method='scott')
            f = KernelD.evaluate(pts)
            fmix = fmix + w[c]*f
    #        plt.plot(pts,f)
            Fx = (f[0:-1] + 0.5*np.diff(f))
            Fx = Fx/np.sum(Fx)

            Hc = Hc - w[c]*(np.sum(Fx[Fx>0]*np.log2(Fx[Fx>0])))
    #        Hc = Hc - w[c]*np.trapz(f[f>0]*np.log2(f[f>0]),pts[f>0])
            j+=1
    #    plt.plot(pts,fmix)
        Fmix = (fmix[0:-1] + 0.5*np.diff(fmix))
        H = Fmix/np.sum(Fmix)
        Hmix = -(np.sum(H[H>0]*np.log2(H[H>0])))
    else:
        for c in C:
            Xc = X[Y==c,:]
            n,m = np.shape(Xc)
            T = np.repeat([k],n,0)
            xc = np.sort(np.sum(Xc*T,1)/np.linalg.norm(k)**2)
            f,_ = np.histogram(xc,bins = nr_pts,range=[pts[0],pts[-1]])

    #        plt.plot(pts,f)
            f = f/np.sum(f)

            Hc = Hc - w[c]*(np.sum(f[f>0]*np.log2(f[f>0])))
    #        Hc = Hc - w[c]*np.trapz(f[f>0]*np.log2(f[f>0]),pts[f>0])
            j+=1
    #    plt.plot(pts,fmix)
        n,m = np.shape(X)
        T = np.repeat([k],n,0)
        Xc = np.sort(np.sum(X*T,1)/np.linalg.norm(k)**2)

        Fmix,_ = np.histogram(Xc,bins = nr_pts,range=[pts[0],pts[-1]])
        H = Fmix/np.sum(Fmix)
        Hmix = -(np.sum(H[H>0]*np.log2(H[H>0])))
    jsd = Hmix - Hc
    if jsd<0:
        print('negative')
    return jsd

def gradJSDe(X,Y,w,k):
    dG = None
    N,M = np.shape(X)
    T = np.repeat([k],N,0)
    xp = np.sort(np.sum(X*T,1)/np.linalg.norm(k)**2)

    dG = 0
    C = np.unique(Y)
    for j,c in enumerate(C):
        Xc = X[Y==c,:]
        n,m = np.shape(Xc)
        T = np.repeat([k],n,0)
        xc = np.sort(np.sum(Xc*T,1)/np.linalg.norm(k)**2)
        nc = np.shape(xc)[0]
        jsd = 0
        for i in np.arange(1,nc-1,1):
#            sx = np.min([xp[i]-xp[i-1],xp[i+1]-xp[i]])
#            rx = np.min(np.abs(xc[xc!=xp[i]]-xp[i]))

            sx = np.min(np.abs(xp[xp!=xc[i]]-xc[i]))
            dvc = [xc[i]-xc[i-1],xc[i+1]-xc[i]]

            rx = np.min(np.abs(dvc))
            if np.abs(dvc[0])<np.abs(dvc[1]):
                id_xc = i-1
            else:
                id_xc = i+1
            id_xp = np.where(np.abs(xp[xp!=xc[i]]-xc[i]) == np.min(np.abs(xp[xp!=xc[i]]-xc[i])))
            redX = X[xp!=xc[i],:]
            red_xp = xp[xp!=xc[i]]
            aq = np.squeeze(redX[id_xp,:])
            ai = Xc[id_xc,:]
            aj = Xc[i]
            delta_xi = xc[i] - xc[id_xc]
            delta_xp = xc[i] - red_xp[id_xp]
            if rx == 0 or sx == 0:
                jsd += 0
            else:
#                jsd += (xc[i]*ai + red_xp[id_xp]*aq)/sx**2 - (xc[i]*ai + xc[id_xc]*aj)/rx**2
                jsd += ((np.abs(delta_xi)*delta_xp*[ai-aq] - np.abs(delta_xp)*delta_xi*[ai-aj])/(np.abs(delta_xp)*np.abs(delta_xi)))
        dG += (w[j]/nc/np.log(2))*jsd
    dG = np.squeeze(dG)
    dx = dG[0]
    dy = dG[1]

    return dx,dy,dG

if __name__ == '__main__':
    __spec__ = "ModuleSpec(name='builtins', loader=<class '_frozen_importlib.BuiltinImporter'>)"
    N = 200
    M = 2
    CLASSES = 2
    random.seed
    data_rand,Labels = data_rand(N,M,20,Groups=CLASSES)
    data_rand = np.array(data_rand, dtype='float32').T
    Labels = np.array(Labels,dtype='int32')
    j = 0
    varSig = []
    while j< M:
        v = random.randint(0,M-1)
        if v not in varSig:
            varSig.append(v)
            j += 1

    averageSig = 350
    sigma = 10
    data_sig,sig = add_signifficance(copy.deepcopy(data_rand),Labels,np.arange(0,CLASSES,1),averageSig,sigma,varSig)
    w = (1/CLASSES)*np.ones(CLASSES)
#    #######PCA####
#    pca = PCA(n_components=1)#create an instance of PCA
#    pca.fit(data_sig)
#    L_pca = pca.components_
#    Xp_train_pca = np.dot(np.dot(data_sig,L_pca.T),np.linalg.pinv(np.dot(L_pca,L_pca.T)))

    Span = np.arange(-1,1,0.01)
    JS_es1 = np.zeros([np.shape(Span)[0],np.shape(Span)[0]])
    JS_es2 = copy.deepcopy(JS_es1)
    JS_es3 = copy.deepcopy(JS_es1)
    dX = np.zeros([np.shape(Span)[0],np.shape(Span)[0]])
    dY = np.zeros([np.shape(Span)[0],np.shape(Span)[0]])
    p =0

    for p,i in enumerate(Span):
        q = 0
        for q,j in enumerate(Span):
            k = np.array([i,j])/np.linalg.norm([i,j])
#            k =  [0.01*random.randint(1,100) for _ in range(M)]
#            k = k-np.mean(k)

#            JS_estim = JSDe(data_rand,Labels,w,k)
#            JS_kdens = JSD(data_rand,Labels,w,k,100)
            dx,dy,_ = gradJSDe(data_sig,Labels,w,k)
            JS1 = JSDe(data_sig,Labels,w,k)
            JS2 = JSD(data_sig,Labels,w,k,100)
            JS3 = JSD(data_sig,Labels,w,k,100,hist=True)
            JS_es1[p,q] = JS1
            JS_es2[p,q] = JS2
            JS_es3[p,q] = JS3
            dX[p,q] = dx
            dY[p,q] = dy
            q = q+1

    X, Y = np.meshgrid(Span, Span)
    fig = plt.figure()
    ax = fig.gca(projection='3d')
    # Plot the surface.
    surf = ax.plot_surface(X, Y, JS_es1, cmap=cm.coolwarm, linewidth=0, antialiased=False)
    plt.title('Eucliden dist JSd')
    fig.colorbar(surf, shrink=0.5, aspect=5)

    fig = plt.figure()
    ax = fig.gca(projection='3d')
    # Plot the surface.
    surf = ax.plot_surface(X, Y, JS_es2, cmap=cm.coolwarm, linewidth=0, antialiased=False)
    plt.title('Gauss kernel JSd')
    fig.colorbar(surf, shrink=0.5, aspect=5)
    plt.show()

    fig = plt.figure()
    ax = fig.gca(projection='3d')
    # Plot the surface.
    surf = ax.plot_surface(X, Y, JS_es3, cmap=cm.coolwarm, linewidth=0, antialiased=False)
    plt.title('Histogram JSd')
    fig.colorbar(surf, shrink=0.5, aspect=5)
    plt.show()
#    np.delete(data_sig)
    # quiver from the smoothed version
    dy, dx = np.gradient(JS_es2, X[0,:], Y[:,0])
#    fig, ax = plt.subplots()
#    ax.quiver(X, Y, dx, dy, JS_es2)
#    ax.set(aspect=1, title='Quiver Plot of the kernel density')
#    plt.show()

    skip = (slice(None, None, 3), slice(None, None, 3))
    fig, ax = plt.subplots()
    ax.quiver(X[skip], Y[skip], dx[skip], dy[skip], JS_es2[skip])
    ax.set(aspect=1, title='Quiver Plot of the kernel')
    plt.show()

    fig, ax = plt.subplots()
    im = ax.imshow(JS_es2, extent=[X.min(), X.max(), Y.min(), Y.max()],origin='lower')
    ax.quiver(X[skip], Y[skip], dx[skip], dy[skip])

    fig.colorbar(im)
    ax.set(aspect=1, title='Quiver Plot of the kernel')
    plt.show()

    fig, ax = plt.subplots()
    ax.streamplot(X, Y, dx, dy, color=JS_es2, density=0.5, cmap='gist_earth')
    cont = ax.contour(X, Y, JS_es2, cmap='gist_earth')
    ax.clabel(cont)
    ax.set(aspect=1, title='Streamplot with contours kernel density')
    plt.show()

    #theoretical gradient from the k-nn
#    fig, ax = plt.subplots()
#    ax.quiver(X, Y, dX, dY, JS_es1)
#    ax.set(aspect=1, title='Quiver Plot from the theoretical k-nn')
#    plt.show()

    skip = (slice(None, None, 3), slice(None, None, 3))
    fig, ax = plt.subplots()
    ax.quiver(X[skip], Y[skip], dX[skip], dY[skip], JS_es1[skip])
    ax.set(aspect=1, title='Quiver Plot from theoretical k-nn')
    plt.show()

    fig, ax = plt.subplots()
    im = ax.imshow(JS_es1, extent=[X.min(), X.max(), Y.min(), Y.max()],origin='lower')
    ax.quiver(X[skip], Y[skip], dX[skip], dY[skip])

    fig.colorbar(im)
    ax.set(aspect=1, title='Quiver Plot from theoretical k-nn')
    plt.show()

    fig, ax = plt.subplots()
    ax.streamplot(X, Y, dX, dY, color=JS_es1, density=0.5, cmap='gist_earth')
    cont = ax.contour(X, Y, JS_es1, cmap='gist_earth')
    ax.clabel(cont)
    ax.set(aspect=1, title='Streamplot with contours from theoretical k-nn')
    plt.show()

    #gradient from the k-nn surface
    dYe, dXe = np.gradient(JS_es1, X[0,:], Y[:,0])
#    fig, ax = plt.subplots()
#    ax.quiver(X, Y, dX, dY, JS_es1)
#    ax.set(aspect=1, title='Quiver Plot from k-nn surface')
#    plt.show()

    skip = (slice(None, None, 3), slice(None, None, 3))
    fig, ax = plt.subplots()
    ax.quiver(X[skip], Y[skip], dXe[skip], dYe[skip], JS_es1[skip])
    ax.set(aspect=1, title='Quiver Plot from k-nn surface')
    plt.show()

    fig, ax = plt.subplots()
    im = ax.imshow(JS_es1, extent=[X.min(), X.max(), Y.min(), Y.max()],origin='lower')
    ax.quiver(X[skip], Y[skip], dXe[skip], dYe[skip])

    fig.colorbar(im)
    ax.set(aspect=1, title='Quiver Plot')
    plt.show()
    ax.set(title='K-nn surface quiver')

    fig, ax = plt.subplots()
    ax.streamplot(X, Y, dXe, dYe, color=JS_es1, density=0.5, cmap='gist_earth')
    cont = ax.contour(X, Y, JS_es1, cmap='gist_earth')
    ax.clabel(cont)
    ax.set(aspect=1, title='Streamplot with contours from k-nn surface')
    plt.show()
    #gradient estimation from histogram entropy
    dYh, dXh = np.gradient(JS_es3, X[0,:], Y[:,0])
#    fig, ax = plt.subplots()
#    ax.quiver(X, Y, dXe, dYe, JS_es3)
#    ax.set(aspect=1, title='Quiver Plot')
#    plt.show()

    skip = (slice(None, None, 3), slice(None, None, 3))
    fig, ax = plt.subplots()
    ax.quiver(X[skip], Y[skip], dXh[skip], dYh[skip], JS_es3[skip])
    ax.set(aspect=1, title='Quiver Plot histogram entropy')
    plt.show()
    fig, ax = plt.subplots()
    im = ax.imshow(JS_es3, extent=[X.min(), X.max(), Y.min(), Y.max()],origin='lower')
    ax.quiver(X[skip], Y[skip], dXh[skip], dYh[skip])

    fig.colorbar(im)
    ax.set(aspect=1, title='Quiver Plot histogram entropy')
    plt.show()

    fig, ax = plt.subplots()
    ax.streamplot(X, Y, dXh, dYh, color=JS_es3, density=0.5, cmap='gist_earth')


from pi_model import Model
#from speak import speak
from api_handler import AzureHandler, VoiceitHandler
import record
import speech_recognition as sr
from text_to_speech import tts
import os

model = Model("localhost", 'admin', 'silverserver2020?', 'voiceauth')
voiceit = VoiceitHandler("key_d79251d085214874b7479cdf67cd40b8", "tok_3f628df367944320a359510086825836")
r = sr.Recognizer()
m = sr.Microphone()

talkback = {
    'countdown': "Please say the selected phrase, starting recording in 3 ... 2 ... 1. ... Go. ",
    'startedRegistration': "Started registration process",
    'startedVerification': "started verification process"
}

def start_voiceit_registration():
    try:
        voiceit_resp = voiceit.create_user()
        if voiceit_resp['responseCode'] == 'SUCC':
            voiceit_userId = voiceit_resp['userId']

        voiceit_phrases_resp = voiceit.get_supported_phrases()
        if voiceit_phrases_resp['responseCode'] == 'SUCC':
            voiceit_phrases = [x['text'] for x in voiceit_phrases_resp['phrases']]

        resp_dic = {
            'voiceitUserId': voiceit_userId,
            'voiceitPhrases': voiceit_phrases
        }

        return resp_dic
    except Exception as e:
        return "Error: {0}".format(e)

def voiceit_enrollment(uid, phrases):
    iterations = 3
    audio_length = 5
    tts("please say your name", 'name')
    os.system("mpg321 ttsfiles/name.mp3")
    record.record(audio_length, "name.wav")
    name = file_to_text("name.wav")
    print(name)
    model.save_user(name = name, voiceit_id = uid)
    model.add_user_to_group(uid, groupId = 1)
    voiceit.add_user_to_group("grp_bc595294f94341568dc66dd7a09790bc", uid)
    print("user id: ", uid)
    print("supported phrases: \n", pretty_list(phrases))
    count = 1
    while count <= iterations:
        #speak("Please say the selected phrase, starting recording in 3 ... 2 ... 1. ... Go. ")
        os.system("mpg321 ttsfiles/countdown.mp3")
        record.record(audio_length, "test.wav")
        phrase = file_to_text("test.wav")
        res = voiceit.enroll_user(uid, phrase, "test.wav")
        print("response message: ",res['message'])
        print(phrase)
        print("")
        if res['responseCode'] == 'SUCC':
            st = "attempt {0} of enrollment successful".format(count)
            tts(st, 'response')
            count += 1
        else:
            msg = res['message']
            if 'grp_' in msg:
                position = msg.index("grp_")
                gid = msg[position: position+36]
                st = msg.replace(gid, "")
            else:
                st = msg
            tts(st, 'response')
        os.system("mpg321 ttsfiles/response.mp3")

    os.system("mpg321 ttsfiles/EnrollmentSuccess.mp3")

def voiceit_verification(groupId):
    audio_length = 5
    try:
        tts('started verification process', 'startedVerification')
        os.system('mpg321 ttsfiles/startedVerification')
        os.system("mpg321 ttsfiles/countdown.mp3")

        record.record(audio_length, "verify.wav")
        phrase = file_to_text("verify.wav")
        identification_response = voiceit.identify(groupId, phrase, 'verify.wav')
        if identification_response['responseCode'] == 'SUCC':
            print(identification_response)
            uid = identification_response['userId']
            db_response = model.get_user(uid)
            if len(db_response) > 1:
                name = db_response[1]
                s = "First step completed, {0} was successfully identified. Please wait for the complete verification".format(name)
            else:
                s = "First step completed, user was successfully identified. Please wait for the complete verification"

            tts(s, 'response')
            os.system('mpg321 ttsfiles/response.mp3')
            verification_response = voiceit.verify(uid, phrase, 'verify.wav')
            if verification_response['responseCode'] == 'SUCC':
                print(verification_responses)
                confidence = verification_response['confidence']
                st = "successfully verified user with confidence: {0}".format(confidence)
                tts(st, 'response')
            else:
                msg = verification_response['message']
                if 'grp_' in msg:
                    position = msg.index("grp_")
                    gid = msg[position: position+36]
                    st = msg.replace(gid, "")
                else:
                    st = msg

                tts(st, 'response')

            os.system('mpg321 ttsfiles/response.mp3')
        else:
            msg = identification_response['message']
            if 'grp_' in msg:
                position = msg.index("grp_")
                gid = msg[position: position+36]
                st = msg.replace(gid, "")
            else:
                st = msg

            tts(st, 'response')
            os.system('mpg321 ttsfiles/response.mp3')
    except Exception as e:
        return str(e)

def file_to_text(filename):
    with sr.AudioFile(filename) as source:
        audio = r.record(source)

    try:
        s = r.recognize_google(audio)
        return s
    except Exception as e:
        return str(e)

def pretty_list(ls):
    s = ""
    for item in ls:
        s += "\t"+ item +"\n"
    return s


"""
问题链接：
https://www.lintcode.com/en/old/problem/first-position-of-target/

问题描述：
给定一个排序的整数数组（升序）和一个要查找的整数target，用O(logn)的时间查找到target第一次出现的下标（从0开始），如果target不存在于数组中，返回-1。

您在真实的面试中是否遇到过这个题？
样例
在数组 [1, 2, 3, 3, 4, 5, 10] 中二分查找3，返回2。

"""

#思路：
#二分查找也即折半查找，是一种效率较高的查找方法
#给定下标为中间位置，判断中间位置的值与目标值的大小，然后更改low或者high的位置
#因返回的是第一次出现下标的位置，所以不仅需要判断中间位置的值是否与目标值大小相等 还需要判断其前一位的值是不是也与目标值大小相等

class Solution:
    """
    @param nums: The integer array.
    @param target: Target to find.
    @return: The first position of target. Position starts from 0.
    """
    def binarySearch(self, nums, target):
        # write your code here
        low = 0
        high = len(nums) -1
        while low <= high:
            mid = (low+high)//2
            if nums[mid] == target and nums[mid-1] != target:
                return mid
            elif nums[mid] > target or nums[mid-1] == target:
                high = mid - 1
            else:
                low = mid + 1
        return -1
#测试用例
if __name__ == '__main__':
    solution = Solution()
    nums = [1, 2, 3, 3, 4, 5, 10]
    target = 3
    print(solution.binarySearch(nums,target))

    nums = [1, 3, 3, 3, 4, 5, 5, 10]
    target = 5
    print(solution.binarySearch(nums,target))


import heapq
import sys

input = sys.stdin.readline
INF = int(1e9)

# 노드 n개, 간선 m개
n, m = map(int, input().split())
# 시작 노드
start = int(input())
# 노드에 연결되어 있는 노드에 대한 정보를 담는 리스트
graph = [[] for _ in range(n+1)]
# 최단 거리 테이블
distance = [INF] * (n+1)

# 간선 정보 입력
for _ in range(m):
    # a번 노드에서 b번 노드로 가는 비용이 c
    a, b, c = map(int, input().split())
    graph[a].append((b, c))

def dijkstra(start):
    q = []
    heapq.heappush(q, (0, start))
    distance[start] = 0
    while q:
        dist, now = heapq.heappop(q)
        # 현재 노드가 이미 처리된 적이 있으면 무시
        if distance[now] < dist:
            continue
        # 현재 노드와 인접한 노드들을 확인
        for i in graph[now]:
            cost = dist + i[1]
            # 현재 노드를 거쳐서 이동하는 거리가 더 짧은 경우
            if cost < distance[i[0]]:
                distance[i[0]] = cost
                heapq.heappush(q, (cost, i[0]))

dijkstra(start)

for i in range(1, n+1):
    if distance[i] == INF:
        print("INFINITY")
    else:
        print(distance[i])

# 6 11
# 1
# 1 2 2
# 1 3 5
# 1 4 1
# 2 3 3
# 2 4 2
# 3 2 3
# 3 6 5
# 4 3 3
# 4 5 1
# 5 3 1
# 5 6 2

# 0
# 2
# 3
# 1
# 2
# 4


# Importing the OpenCV library
import cv2
# Reading the image using imread() function
image = cv2.imread('road.jpg')

# Extracting the height and width of an image
# h, w = image.shape[:2]
# # Displaying the height and width
# print("Height = {}, Width = {}".format(h, w))
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

cv2.imwrite('image.jpg', gray_image)
cv2.waitKey(0)
cv2.destroyAllWindows()


# -*- coding: utf-8 -*-
"""
Created on Tue Dec 11 16:42:57 2018

@author: amkle
"""
import cv2
import numpy as np

def dark(img):
    shape_img = np.shape(img)
    for i in range(0, shape_img[0], 1):    # Alle farger under 80,80,80(rgb) blir gjort om til svart
        for j in range(0, shape_img[1], 1):
            a = img[i,j]
            if (80 >= a[0] and  80 >= a[1] and 80 >= a[2]):
                img[i,j]=[0,0,0]
    kernel = np.ones((12,12),np.uint8)
    img = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)      #Fjerner alle flekker som er mindre enn 12,12 utenfor objektet.
    kernel = np.ones((7,7),np.uint8)
    img = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)      #Fjerner alle flekker som er mindre enn 7,7 innfor objektet (https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_morphological_ops/py_morphological_ops.html)

    return(img)


def main():
    f = open('input.txt', 'r')
    lines = f.readlines()
    best = 0
    for i in range(1, len(lines)-1):
        for j in range(1, len(lines[0])-2):
            height = lines[i][j]
            vis = [1, 1, 1, 1]
            # left
            for x in range(j-1, 0, -1):
                if lines[i][x] < height:
                    vis[0] += 1
                else: break
            # right
            for x in range(j+1, len(lines)-1):
                if lines[i][x] < height:
                    vis[1] += 1
                else: break
            # up
            for y in range(i-1, 0, -1):
                if lines[y][j] < height:
                    vis[2] += 1
                else: break
            # down
            for y in range(i+1, len(lines[0])-2):
                if lines[y][j] < height:
                    vis[3] += 1
                else: break

            scenicScore = vis[0] * vis[1] * vis[2] * vis[3]
            if scenicScore >= best:
                best = scenicScore
    print(best)
    return

main()


#수 이어 쓰기 1
import sys
input = sys.stdin.readline

n = int(input())
start = 1
len = 1
ans = 0
while start <= n:

  end = start*10 - 1
  if end > n:
    end = n
  ans += (end - start + 1) * len

  len += 1
  start *= 10

print(ans)


import numpy as np
import matplotlib.pyplot as plt
from math import factorial
import os
from pathlib import Path

# Building piecewise constant basis functions
def build_phi_piecewise(param):
    index_list = np.linspace(0, param["nbData"], param["nbFct"]+1)
    phi = np.zeros((param["nbData"],param["nbFct"]))
    for i in range(param["nbFct"]):
        phi[int(index_list[i]):int(index_list[i+1]), i] = 1
    return phi

# Building radial basis functions (RBFs)
def build_phi_rbf(param):
    Ts = np.arange(0,param["nbData"],1)
    bw = param["nbData"] / param["nbFct"]
    avg = bw // 2
    sig = bw
    phi = []
    for i in range(param["nbFct"]):
        phi_k = 1 / (2*np.pi * sig) * np.exp(-1*(Ts-avg)**2 / (2*sig**2))
        phi += [phi_k]
        avg += bw
    return np.asarray(phi).T

# Building Bernstein basis functions
def build_phi_bernstein(param):
    t = np.linspace(0,1,param["nbData"])
    phi = np.zeros((param["nbData"],param["nbFct"]))
    for i in range(param["nbFct"]):
        phi[:,i] = factorial(param["nbFct"]-1) / (factorial(i) * factorial(param["nbFct"]-1-i)) * (1-t)**(param["nbFct"]-1-i) * t**i
    return phi

# Building Fourier basis functions
def build_phi_fourier(param):
    d = np.ceil((param["nbFct"]-1)/2)
    k = np.arange(-d,d+1,1).reshape((-1,1))
    param["nbFct"] = len(k)
    t = np.linspace(0,1,param["nbData"]).reshape((-1,1))
    phi = np.exp( t.T * k * 2 * np.pi * 1j ) / (param["nbData"])
    return phi.T

# General param parameters
# ===============================
param = {
    "nbFct" : 10, # Number of basis functions
    "nbVar" : 2, # Dimension of position data
    "nbData" : 200, # Number of datapoints in a trajectory
    "nbDemos" : 5, # Number of demonstrations
}

# Load handwriting data
FILE_PATH = os.path.dirname(os.path.realpath(__file__))
DATASET_LETTER_FILE = "data/2Dletters/S.npy"
# x = np.load(str(Path(FILE_PATH,DATASET_LETTER_FILE)))[0,:,:2].flatten() #Load single demonstration
X = np.load(str(Path(FILE_PATH,DATASET_LETTER_FILE)))[:param["nbDemos"],:,:2].reshape((param["nbDemos"],param["nbData"]*2)).T #Load multiple demonstrations

t = np.linspace(0,1,param["nbData"]) # Time range

# Fourier basis functions require additional symmetrization (mirroring) if the signal is a discrete motion
# x = np.hstack(( x , x[::-1] ))
# param["nbData"] *= 2

# Generate MP with various basis functions
# ============================================
# phi = build_phi_piecewise(param) #Piecewise constant
# phi = build_phi_rbf(param) #Radial basis functions
phi = build_phi_bernstein(param) #Bernstein polynomials
# phi = build_phi_fourier(param) #Fourier basis functions

psi = np.kron(phi, np.identity(param["nbVar"])) # Transform to multidimensional basis functions

# w = np.linalg.solve(psi.T @ psi + np.identity(param["nbVar"] * param["nbFct"]) * 1e-8, psi.T @ x) # Estimation of superposition weights from data
# w = np.linalg.pinv(psi) @ x # Estimation of superposition weights from data
# w = np.linalg.inv(psi.T @ psi) @ psi.T @ x # Estimation of superposition weights from data
W = np.linalg.pinv(psi) @ X # Estimation of superposition weights from data (for multiple demonstrations)
w = np.mean(W, 1) # Average w

x_hat = psi @ w # Reconstruction data

# Fourier basis functions require de-symmetrization of the signal after processing (for visualization)
# param["nbData"] /= 2
# x = x[:int(param["nbData"]*param["nbVar"])]
# x_hat = x_hat[:int(param["nbData"]*param["nbVar"])]

# Plotting
# =========
fig,axs = plt.subplots(2,1)
# axs[0].plot(x[::2], x[1::2], c='black', label='Demonstration')
axs[0].plot(X[::2], X[1::2], c='black', label='Demonstration')
axs[0].plot(x_hat[::2], x_hat[1::2], c='r', label='Reproduction')
axs[0].axis("off")
axs[0].axis("equal")
axs[0].legend()

axs[1].set_xticks([0,param["nbData"]])
axs[1].set_xticklabels(["0","T"])
for j in range(param["nbFct"]):
    axs[1].plot(phi[:,j])
axs[1].set_ylabel("$\phi_k$")

plt.show()


import datasets
from sklearn import linear_model

reg = linear_model.LogisticRegression(C=1e5, max_iter=1000)
reg.fit(datasets.X_TRAIN, datasets.Y_TRAIN)

pred = reg.predict(datasets.X_TEST)

print("Prediction:\n", pred, end="\n\n")
print("Test:\n", datasets.Y_TEST, end="\n\n")


import cv2
from matplotlib import pyplot as plt
from ..utils.media import get_image_path

path = get_image_path('ronaldo.jpg')
img = cv2.imread(path, 0)
edges = cv2.Canny(img, 100, 200)

plt.subplot(121), plt.imshow(img, cmap='gray')
plt.title('Original Image'), plt.xticks([]), plt.yticks([])
plt.subplot(122), plt.imshow(edges, cmap='gray')
plt.title('Edge Image'), plt.xticks([]), plt.yticks([])
plt.show()


from random import randint, random

def inputNum(inputText):
    flag = False
    while not flag:
        try:
            number = int(input(f"{inputText}"))
            flag = True
        except ValueError:
            print("Это не число!")
    return number

def myList(num):

    arr_list = []

    for i in range(num):
        rand = randint(0, 10)
        arr_list.append(rand)

    return arr_list

def myFloatList(num):

    arr_list = []

    for i in range(num):
        rand = randint(0, 10) + round(random(), 2)
        arr_list.append(rand)

    return arr_list

'''1. Задайте список из нескольких чисел. Напишите программу, которая найдёт сумму элементов списка, стоящих на нечётной позиции.
*Пример: - [2, 3, 5, 9, 3] -> на нечётных позициях элементы 3 и 9, ответ: 12'''

def findPosition(lst):
    sum = 0
    print(lst)
    for i in range(1, len(lst), 2):
        sum += lst[i]
    return sum

print(f'Сумма чисел на нечетных позициях = {findPosition(myList(inputNum("Введите число: ")))}')

'''2. Напишите программу, которая найдёт произведение пар чисел списка. Парой считаем первый и последний элемент, второй и предпоследний и т.д.
*Пример:*
- [2, 3, 4, 5, 6] => [12, 15, 16];
- [2, 3, 5, 6] => [12, 15]'''

def findSumPosition(lst):
    sum_lst = []
    print(lst)
    length = int(len(lst))

    if length % 2 == 0:
        for i in range(0, (length // 2)):
            sum_lst.append(lst[i] * lst[length - i - 1])
    else:
        length = int(len(lst) + 1)
        for i in range(0, (length // 2)):
            sum_lst.append(lst[i] * lst[length - i - 2])
    return sum_lst
print(f'Произведение = {findSumPosition(myList(inputNum("Введите число: ")))}')

'''3. Задайте список из вещественных чисел. Напишите программу, которая найдёт разницу между максимальным и минимальным значением дробной части элементов.
*Пример:*
- [1.1, 1.2, 3.1, 5, 10.01] => 0.19'''

def minMaxList(lst):

    print(lst)
    new_lst = [round(i % 1, 2) for i in lst if i % 1 != 0]

    print(f'Разница между максимальным и минимальным значением дробной части элементов = {max(new_lst) - min(new_lst)}')

minMaxList(myFloatList(inputNum("Введите число: ")))

'''4. Напишите программу, которая будет преобразовывать десятичное число в двоичное.
*Пример:*
- 45 -> 101101
- 3 -> 11
- 2 -> 10'''

def numToTen(num):

    string = ""
    while num != 0:
        string = str(num % 2) + string
        num //=2
    print(f'В десятичной системе = {string} ')

numToTen(inputNum("Введите число для преобразовывания десятичного числа в двоичное :"))

'''5. Задайте число. Составьте список чисел Фибоначчи, в том числе для отрицательных индексов.
*Пример:*- для k = 8 список будет выглядеть так: [-21 ,13, -8, 5, −3, 2, −1, 1, 0, 1, 1, 2, 3, 5, 8, 13, 21] [Негафибоначчи]'''

def fibonacciMod(n):
    if n >= 0:
       idx = range(n+1)
       x = [0,1]
       for k in idx[2:]:
           x.append(x[k-1] + x[k-2])
       return x[n]
    else:
       n=-(n-1)
       idx = range(n+1)
       x = [1,0]
       for k in idx[2:]:
           x.append(x[k-2] - x[k-1])
       x.reverse()
    return x[0]

n = inputNum('Enter namber : ')
fib_list = []

for i in range(-n, n+1):
   fib_list.append(fibonacciMod(i))
print(fib_list)


from config import *
from math import sqrt, e, pi, factorial, log, sin, cos, tan, radians

class Calculator:
    def __init__(self):
        self.value = "0"
        self.memory = "0"
        self.angle_unit = 1

    def mem(self, mode):
        if mode == "MC":
            self.memory = "0"
        elif mode == "M+":
            self.calc()
            self.memory = float(self.value) + float(self.memory)
            if self.memory == int(self.memory): self.memory = str(int(self.memory))
        elif mode == "M-":
            self.calc()
            self.memory = float(self.value) - float(self.memory)
            if self.memory == int(self.memory): self.memory = str(int(self.memory))
        elif mode == "MS":
            self.calc()
            self.memory = self.value
            if self.memory == int(self.memory): self.memory = str(int(self.memory))
        elif mode == "MRC":
            self.value = self.memory

    def check_value(self, item):
        print(item, self.value[-1])
        if item in [
                "(", "√", "-", "1/", "[i]e[/i]", "π", "10^",
                "log(", "ln(", "abs(", "sin(", "cos(", "tan(", "sec(", "csc(", "cot(",
                *numbers
                ] and self.value == "0":
            return True
        if item == "(" and self.value[-1] not in ["+", "−", "×", "÷", "√", "^", "%", "("]: return False
        elif item == ")" and self.value[-1] not in numbers + [")"]: return False
        elif item == "e" and self.value[-1] not in numbers: return False
        elif item == "^" and self.value[-1] not in numbers + [")"]: return False
        elif item == "√" and self.value[-1] not in ["+", "−", "×", "÷", "^", "%", "("]: return False
        elif item == "+" and self.value[-1] not in numbers + ["e", ")", "π" "E"]: return False
        elif item == "−" and self.value[-1] not in numbers + [")", "π" "E"]: return False
        elif item == "×" and self.value[-1] not in numbers + [")", "π" "E"]: return False
        elif item == "÷" and self.value[-1] not in numbers + [")", "π" "E"]: return False
        elif item == "-" and self.value[-1] not in ["e", "(", "+", "−", "×", "÷", "^", "%"]: return False
        elif item == "." and self.value[-1] not in numbers: return False
        elif item in numbers and (self.value[-1] in [")", "π" "E"]): return False
        elif item == "π" and self.value[-1] not in ["+", "−", "×", "÷", "√", "^", "%", "("]: return False
        elif item == "[i]e[/i]" and self.value[-1] not in ["+", "−", "×", "÷", "√", "^", "%", "("]: return False
        elif item == "^2" and self.value[-1] not in numbers + [")"]: return False
        elif item == "1/" and self.value[-1] not in ["+", "−", "×", "÷", "√", "^"]: return False
        elif item == "%" and self.value[-1] not in numbers + [")"]: return False
        elif item == "!" and self.value[-1] not in numbers + [")"]: return False
        elif item == "10^" and self.value[-1] not in ["+", "−", "×", "÷", "√", "^"]: return False
        elif item == "log(" and self.value[-1] not in ["+", "−", "×", "÷", "√", "^"]: return False
        elif item == "ln(" and self.value[-1] not in ["+", "−", "×", "÷", "√", "^"]: return False
        elif item == "abs(" and self.value[-1] not in ["+", "−", "×", "÷", "√", "^"]: return False
        elif item == "sin(" and self.value[-1] not in ["+", "−", "×", "÷", "√", "^"]: return False
        elif item == "cos(" and self.value[-1] not in ["+", "−", "×", "÷", "√", "^"]: return False
        elif item == "tan(" and self.value[-1] not in ["+", "−", "×", "÷", "√", "^"]: return False
        elif item == "sec(" and self.value[-1] not in ["+", "−", "×", "÷", "√", "^"]: return False
        elif item == "csc(" and self.value[-1] not in ["+", "−", "×", "÷", "√", "^"]: return False
        elif item == "cot(" and self.value[-1] not in ["+", "−", "×", "÷", "√", "^"]: return False
        return True

    def add_value(self, item):
        if self.check_value(item):
            if self.value == "0" and item not in ["+", "−", "×", ".", "^", "÷", "!", "^", "%", "e"]: self.value = item
            else: self.value += item

    def parse(self, exp):
        l = []
        string = ""
        for char in exp:
            if char not in ["√", "(", "÷", "×", "−", "+" , ")", "^", "%", "!"] or (len(string) and ((char == "+" or char == "-") and string[-1] == "e")):
                string += char
            else:
                if string != "":
                    l.append(string)
                    string = ""
                l.append(char)
        if string != "": l.append(string)

        if "(" in l:
            while "(" in l or ")" in l:
                close = l.index(")")
                open = max(idx for idx, val in enumerate(l[:close]) if val == "(")
                middle = l[open + 1:close]
                del l[open + 1:close + 1]
                l[open] = middle
        print(l)
        return l

    def calc(self):
        if self.value.count("(") != self.value.count(")") or ("(" in self.value and self.value.index("(") > self.value.index(")")):
            self.value = "Bracket Error"
            return

        operations = self.parse(self.value)
        try: self.value = self.eval(operations)
        except OverflowError: self.value = "Overflow Error"
        except ZeroDivisionError: self.value = "Zero Division Error"
        except ValueError: self.value = "Syntax Error"
        except Exception as e: raise e

    def eval(self, exp):
        operations = exp.copy()

        # Brackets
        if any(type(item) is list for item in operations):
            for i in range(len(operations)):
                if type(operations[i]) is list:
                    answer = self.eval(operations[i])
                    if "Error" in answer:
                        return answer
                    operations[i] = answer

        print(operations)

        # Constants
        while "π" in operations: operations[operations.index("π")] = str(pi)
        while "E" in operations: operations[operations.index("E")] = str(e)

        # Functions
        while "log" in operations:
            i = operations.index("log")
            del operations[i]
            operations[i] = str(log(float(operations[i]), 10))

        while "ln" in operations:
            i = operations.index("ln")
            del operations[i]
            operations[i] = str(log(float(operations[i])))

        while "abs" in operations:
            i = operations.index("abs")
            del operations[i]
            operations[i] = str(abs(float(operations[i])))

        while "sin" in operations:
            i = operations.index("sin")
            del operations[i]
            if self.angle_unit: operations[i] = str(radians(float(operations[i])))
            operations[i] = str(sin(float(operations[i])))
            if float(operations[i]) < float("1e-10"): operations[i] = "0"

        while "cos" in operations:
            i = operations.index("cos")
            del operations[i]
            if self.angle_unit: operations[i] = str(radians(float(operations[i])))
            operations[i] = str(cos(float(operations[i])))
            if float(operations[i]) < float("1e-10"): operations[i] = "0"

        while "tan" in operations:
            i = operations.index("tan")
            del operations[i]
            if self.angle_unit: operations[i] = str(radians(float(operations[i])))
            operations[i] = str(tan(float(operations[i])))
            if float(operations[i]) < float("1e-10"): operations[i] = "0"

        while "sec" in operations:
            i = operations.index("sec")
            del operations[i]
            if self.angle_unit: operations[i] = str(radians(float(operations[i])))
            operations[i] = str(1 / cos(float(operations[i])))
            if float(operations[i]) < float("1e-10"): operations[i] = "0"

        while "csc" in operations:
            i = operations.index("csc")
            del operations[i]
            if self.angle_unit: operations[i] = str(radians(float(operations[i])))
            operations[i] = str(1 / sin(float(operations[i])))
            if float(operations[i]) < float("1e-10"): operations[i] = "0"

        while "cot" in operations:
            i = operations.index("cot")
            del operations[i]
            if self.angle_unit: operations[i] = str(radians(float(operations[i])))
            operations[i] = str(1 / tan(float(operations[i])))
            if float(operations[i]) < float("1e-10"): operations[i] = "0"

        # Sqrt
        while "√" in operations:
            i = operations.index("√")
            del operations[i]
            operations[i] = str(sqrt(float(operations[i])))

        # Indices
        while "^" in operations:
            i = max(idx for idx, val in enumerate(operations) if val == "^")
            if i == 0:
                return "Syntax Error"
            del operations[i]
            operations[i - 1] = str(float(operations[i - 1]) ** float(operations[i]))
            del operations[i]

        # Factorial
        while "!" in operations:
            i = operations.index("!")
            if i == 0:
                return "Syntax Error"
            del operations[i]
            operations[i - 1] = str(factorial(float(operations[i - 1])))

        # /*%
        while "×" in operations or "÷" in operations or "%" in operations:
            i = operations.index("×") if "×" in operations else len(operations)
            j = operations.index("÷") if "÷" in operations else len(operations)
            k = operations.index("%") if "%" in operations else len(operations)
            op = "×" if min([i, j, k]) == i else "÷" if min([i, j, k]) == j else "%"
            index = min([i, j, k])
            del operations[index]
            if op == "×": operations[index - 1] = str(float(operations[index - 1]) * float(operations[index]))
            elif op == "÷": operations[index - 1] = str(float(operations[index - 1]) / float(operations[index]))
            elif op == "%": operations[index - 1] = str(float(operations[index - 1]) % float(operations[index]))
            del operations[index]

        # +-
        while "+" in operations or "−" in operations:
            i = operations.index("+") if "+" in operations else len(operations)
            j = operations.index("−") if "−" in operations else len(operations)
            op = "+" if i < j else "−"
            index = i if i < j else j
            del operations[index]
            if op == "+": operations[index - 1] = str(float(operations[index - 1]) + float(operations[index]))
            else: operations[index - 1] = str(float(operations[index - 1]) - float(operations[index]))
            del operations[index]

        ending = ""
        if "e" in operations[0]:
            index = operations[0].index("e")
            ending = operations[0][index:]
            operations[0] = operations[0][:index]
        print(operations[0])
        if operations[0] == "inf": return "Overflow Error"
        if operations[0] == "nan": return "Math Error"
        if int(float(operations[0])) == float(operations[0]): operations[0] = str(int(float(operations[0])))
        operations[0] += ending
        return operations[0]

    def clear(self):
        self.value = "0"

    def delete(self):
        if len(self.value) == 1:
            self.clear()
        else:
            self.value = self.value[:-1]


import cv2
import argparse
import os

import torch
from torch.utils.data import DataLoader

from apex import amp
from apex.parallel import (
    DistributedDataParallel, convert_syncbn_model)

from ignite.engine import Events
from ignite.handlers import ModelCheckpoint, global_step_from_engine
from ignite.contrib.handlers import (
    create_lr_scheduler_with_warmup, CosineAnnealingScheduler)
from ignite.contrib.handlers import ProgressBar

import albumentations as albu
from albumentations.pytorch import ToTensorV2 as ToTensor

from neural.models.segmentation.contextnet import ContextNet
from neural.engines.segmentation import (
    create_segmentation_trainer, create_segmentation_evaluator)
from neural.data.cityscapes import Cityscapes

from neural.losses import OHEMLoss

from neural.utils.training import (
    setup_distributed, get_datasets_root, create_sampler)

parser = argparse.ArgumentParser()
parser.add_argument('--batch_size', type=int, required=True)
parser.add_argument('--learning_rate', type=float, required=True)
parser.add_argument('--weight_decay', type=float, default=4e-5)
parser.add_argument('--epochs', type=int, required=True)
parser.add_argument('--crop_size', type=int, default=768)
parser.add_argument('--state_dict', type=str, required=False)
parser.add_argument('--width_multiplier', type=int, default=1)

parser.add_argument('--distributed', action='store_true')
parser.add_argument('--local_rank', type=int, default=0)
args = parser.parse_args()

distributed = args.distributed
world_size, world_rank, local_rank = setup_distributed(
    distributed, args.local_rank)

device = torch.device('cuda')

crop_size = args.crop_size

train_tfms = albu.Compose([
    albu.RandomScale([-0.5, 1.0], interpolation=cv2.INTER_CUBIC, always_apply=True),
    albu.RandomCrop(512, 1024),
    albu.HorizontalFlip(),
    albu.HueSaturationValue(),
    albu.Normalize(),
    ToTensor(),
])
val_tfms = albu.Compose([
    albu.Normalize(),
    ToTensor(),
])

dataset_dir = get_datasets_root('cityscapes')
train_dataset = Cityscapes(dataset_dir, split='train', transforms=train_tfms)
val_dataset = Cityscapes(dataset_dir, split='val', transforms=val_tfms)

sampler_args = dict(world_size=world_size,
                    local_rank=local_rank,
                    enable=distributed)

train_loader = DataLoader(
    train_dataset,
    batch_size=args.batch_size,
    drop_last=True,
    num_workers=8,
    sampler=create_sampler(train_dataset, **sampler_args),
    shuffle=not distributed,
)
val_loader = DataLoader(
    val_dataset,
    batch_size=4,
    shuffle=False,
    drop_last=False,
    num_workers=8,
    sampler=create_sampler(val_dataset, training=False, **sampler_args),
)

model = ContextNet(3, 19,
                   scale_factor=4,
                   width_multiplier=args.width_multiplier)

if args.state_dict is not None:
    state_dict = torch.load(args.state_dict, map_location='cpu')
    model.load_state_dict(state_dict, strict=True)

model = model.to(device)

optimizer = torch.optim.AdamW(
    [
        {'params': (p for p in model.parameters() if len(p.shape) != 1),
         'weight_decay': args.weight_decay, },
        {'params': (p for p in model.parameters() if len(p.shape) == 1), },
    ],
    lr=args.learning_rate,
)

loss_fn = OHEMLoss(ignore_index=255)
loss_fn = loss_fn.cuda()

scheduler = CosineAnnealingScheduler(
    optimizer, 'lr',
    args.learning_rate, args.learning_rate / 1000,
    args.epochs * len(train_loader) - 1000,
)
scheduler = create_lr_scheduler_with_warmup(
    scheduler, 0, args.learning_rate, 1000)

model, optimizer = amp.initialize(model, optimizer, opt_level="O2")
if args.distributed:
    model = convert_syncbn_model(model)
    model = DistributedDataParallel(model)

trainer = create_segmentation_trainer(
    model, optimizer, loss_fn,
    device=device,
    use_f16=True,
)
trainer.add_event_handler(Events.ITERATION_COMPLETED, scheduler)

evaluator = create_segmentation_evaluator(
    model,
    device=device,
    num_classes=19,
)

if local_rank == 0:
    ProgressBar(persist=True).attach(trainer, ['loss'])
    ProgressBar(persist=True).attach(evaluator)

@trainer.on(Events.EPOCH_COMPLETED(every=5))
def evaluate(engine):
    evaluator.run(val_loader)

if local_rank == 0:
    checkpointer = ModelCheckpoint(
        dirname=os.path.join('checkpoints', 'contextnet14'),
        filename_prefix='contextnet',
        score_name='miou',
        score_function=lambda engine: engine.state.metrics['miou'],
        n_saved=5,
        global_step_transform=global_step_from_engine(trainer),
    )
    evaluator.add_event_handler(
        Events.COMPLETED, checkpointer,
        to_save={'model': model if not args.distributed else model.module},
    )

trainer.run(train_loader, max_epochs=args.epochs)


import network
import espnow

# A WLAN interface must be active to send()/recv()
sta = network.WLAN(network.STA_IF)  # Or network.AP_IF
sta.active(True)

e = espnow.ESPNow()
e.active(True)
peer = b'\xbb\xbb\xbb\xbb\xbb\xbb'   # MAC address of peer's wifi interface
e.add_peer(peer)      # Must add_peer() before send()

e.send(peer, "Starting...")
for i in range(100):
    e.send(peer, str(i)*20, True)
e.send(peer, b'end')


# presaved_param.py

from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier
from catboost import CatBoostRegressor, CatBoostClassifier
import xgboost as xgb
import lightgbm as lgb

param_rf_cla = {'n_estimators': 100, 'max_depth': 5}
param_catboost_cla = {'depth': 7, 'learning_rate': 0.1}
param_xgb_cla = {'eta': 0.09997487669624248, 'max_depth': 9, 'subsample': 0.4503180982597529, 'colsample_bytree': 0.28852184628909433, 'gamma': 0.048619898711735665, 'alpha': 1.037873925072671, 'lambda':
2.2991082165191634, 'min_child_weight': 18} #{'n_estimators': 100, 'max_depth': 5}
param_lgbm_cla = {'n_estimators': 100, 'max_depth': 5}

param_rf_reg = {'n_estimators': 100, 'max_depth': 5}
param_catboost_reg = {'depth': 7, 'learning_rate': 0.1}
param_xgb_reg = {'n_estimators': 3000,
        'max_depth': 4,
        'learning_rate': 0.4,
        'subsample': 0.8,
        'colsample_bytree': 1,
        'objective': 'reg:squarederror',
        'random_state': 42,
        'n_jobs': -1,
        'eval_metric': 'rmse',
        'verbosity': 0,
        'early_stopping_rounds': 100
        }
param_lgbm_reg = {'n_estimators': 100, 'max_depth': 5}

model_dict = {
    "classification": {
        "RF": RandomForestClassifier(**param_rf_cla),
        "CatBoost": CatBoostClassifier(**param_catboost_cla),
        "XGBoost": xgb.XGBClassifier(**param_xgb_cla),
        "LGBM": lgb.LGBMClassifier(**param_lgbm_cla),
    },
    "regression": {
        "RF": RandomForestRegressor(**param_rf_reg),
        "CatBoost": CatBoostRegressor(**param_catboost_reg),
        "XGBoost": xgb.XGBRegressor(**param_xgb_reg),
        "LGBM": lgb.LGBMRegressor(**param_lgbm_reg),
    },
}


# 329. Longest Increasing Subarray - 2d - dfs memoization
DIRECTIONS = [(0, -1), (-1, 0), (0, 1), (1, 0)]
class Solution:
    def longestIncreasingPath(self, matrix):
        if not matrix:
            return 0

        n, m = len(matrix), len(matrix[0])
        record = [[1 for _ in range(m)] for _ in range(n)]
        memo = {}
        longest = 0
        for i in range(n):
            for j in range(m):
                record[i][j] = self.dfs(matrix, i, j, memo)

        return max(map(max, record))

    def dfs(self, matrix, x, y, memo):
        if (x, y) in memo:
            return memo[(x, y)]

        longest = 1
        for delta_x, delta_y in DIRECTIONS:
            x_next, y_next = x + delta_x, y + delta_y
            if self.isValid(matrix, x_next, y_next) and matrix[x][y] < matrix[x_next][y_next]:
                longest = max(longest, self.dfs(matrix, x_next, y_next, memo) + 1)

        memo[(x, y)] = longest
        return longest

    def isValid(self, matrix, x, y):
        return 0 <= x < len(matrix) and 0 <= y < len(matrix[0])

01-Array/05-subarray/329. Longest Increasing Subarray.py