from core.celery import app
from celery import Celery
import json
import subprocess
import os
from .models import Node, Offer
from django.utils import timezone
import tempfile
import redis
from .serializers import NodeSerializer, OfferSerializer
import calendar
import datetime
import requests
from api.serializers import FlatNodeSerializer
from collector.models import Node as NodeV1

pool = redis.ConnectionPool(host='redis', port=6379, db=0)
r = redis.Redis(connection_pool=pool)

@ app.task
def v2_network_online_to_redis():
    data = Node.objects.filter(online=True)
    serializer = NodeSerializer(data, many=True)
    test = json.dumps(serializer.data, default=str)

    r.set("v2_online", test)

@app.task
def v2_network_online_to_redis_flatmap():
    data = NodeV1.objects.filter(online=True)
    serializer = FlatNodeSerializer(data, many=True)
    test = json.dumps(serializer.data)
    r.set("v2_online_flatmap", test)

@ app.task
def v2_cheapest_offer():
    recently = timezone.now() - timezone.timedelta(minutes=5)
    data = Offer.objects.filter(runtime="vm",
                                updated_at__range=(recently, timezone.now())).order_by('-monthly_price_glm')
    serializer = OfferSerializer(data, many=True)
    sorted_data = json.dumps(serializer.data, default=str)

    r.set("v2_cheapest_offer", sorted_data)

@ app.task
def latest_blog_posts():
    req = requests.get(
        f"https://blog.golemproject.net/ghost/api/v3/content/posts/?key={os.environ.get('BLOG_API_KEY')}&include=tags,authors&limit=3")
    data = json.dumps(req.json())
    r.set("v2_index_blog_posts", data)

@ app.task
def v2_cheapest_provider():
    req = requests.get(
        "https://api.coingecko.com/api/v3/coins/ethereum/contract/0x7DD9c5Cba05E151C895FDe1CF355C9A1D5DA6429")
    data = req.json()
    price = data['market_data']['current_price']['usd']
    obj = Offer.objects.filter(
        runtime="vm", provider__online=True).order_by("monthly_price_glm")
    serializer = OfferSerializer(obj, many=True)
    mainnet_providers = []
    for index, provider in enumerate(serializer.data):
        if "golem.com.payment.platform.erc20-mainnet-glm.address" in provider['properties']:
            mainnet_providers.append(provider)
    sorted_pricing_and_specs = sorted(mainnet_providers, key=lambda element: (
        float(element['properties']['golem.inf.cpu.threads']), float(element['monthly_price_glm'])))
    two_cores = [{'name': 'Digital Ocean', 'img': '/do-logo.svg',
                  'usd_monthly': '15',  'bandwidth': '3', 'cores': 2, 'memory': '1', 'disk': "25", "glm": float(price) * 15}, {'name': 'Amazon Web Services', 'img': '/aws-logo.svg',
                                                                                'usd_monthly': '15.23', 'bandwidth': 'Unlimited', 'cores': 2, 'memory': '1', 'disk': "25", "glm": float(price) * 15.23}, {'name': 'Google Cloud Platform', 'img': '/gcp-logo.svg',
                                                                                'usd_monthly': '10.37', 'bandwidth': 'Unlimited', 'cores': 2, 'memory': '1', 'disk': "25", "glm": float(price) * 10.37}, {'name': 'Azure', 'img': '/azure-logo.svg',
                                                                                'usd_monthly': '15.11', 'bandwidth': '6', 'cores': 2, 'memory': '1', 'disk': "25", "glm": float(price) * 15.11}, ]
    eight_cores = [{'name': 'Digital Ocean', 'img': '/do-logo.svg',
                    'usd_monthly': '80',  'bandwidth': '6', 'cores': 8, 'memory': '16', 'disk': "320", "glm": float(price) * 80}, {'name': 'Amazon Web Services', 'img': '/aws-logo.svg',
                                                                                'usd_monthly': '121.81', 'bandwidth': 'Unlimited', 'cores': 8, 'memory': '16', 'disk': "320", "glm": float(price) * 121.81}, {'name': 'Google Cloud Platform', 'img': '/gcp-logo.svg',
                                                                                'usd_monthly': '208.47', 'bandwidth': 'Unlimited', 'cores': 8, 'memory': '32', 'disk': "320", "glm": float(price) * 208.47}, {'name': 'Azure', 'img': '/azure-logo.svg',
                                                                                'usd_monthly': '121.18', 'cores': 8, 'memory': '16', 'bandwidth': '6', 'disk': "320", "glm": float(price) * 121.18}]
    thirtytwo_cores = [{'name': 'Digital Ocean', 'img': '/do-logo.svg',
                        'usd_monthly': '640',  'bandwidth': '9', 'cores': 32, 'memory': '64', 'disk': "400", "glm": float(price) * 640}, {'name': 'Amazon Web Services', 'img': '/aws-logo.svg',
                                                                                'usd_monthly': '834.24', 'bandwidth': 'Unlimited', 'cores': 32, 'memory': '64', 'disk': "400", "glm": float(price) * 834.24}, {'name': 'Google Cloud Platform', 'img': '/gcp-logo.svg',
                                                                                'usd_monthly': '746.04', 'bandwidth': 'Unlimited', 'cores': 32, 'memory': '64', 'disk': "400", "glm": float(price) * 746.04}, {'name': 'Azure', 'img': '/azure-logo.svg',
                                                                                'usd_monthly': '1310.13', 'bandwidth': '1', 'cores': 32, 'memory': '64', 'disk': "256", "glm": float(price) * 1310.13}, ]
    sixtyfour_cores = [{'name': 'Digital Ocean', 'img': '/do-logo.svg',
                        'usd_monthly': '1200',  'bandwidth': '9', 'cores': 40, 'memory': '160', 'disk': "500", "glm": float(price) * 1200}, {'name': 'Amazon Web Services', 'img': '/aws-logo.svg',
                                                                                'usd_monthly': '1638.48', 'bandwidth': 'Unlimited', 'cores': 64, 'memory': '64', 'disk': "500", "glm": float(price) * 1638.48}, {'name': 'Google Cloud Platform', 'img': '/gcp-logo.svg',
                                                                                'usd_monthly': '1914.62', 'bandwidth': 'Unlimited', 'cores': 60, 'memory': '240', 'disk': "500", "glm": float(price) * 1914.62}, {'name': 'Azure', 'img': '/azure-logo.svg',
                                                                                'usd_monthly': '2688.37', 'bandwidth': '1', 'cores': 64, 'memory': '256', 'disk': "512", "glm": float(price) * 2688.37}, ]
    for obj in sorted_pricing_and_specs:
        provider = {}
        provider['name'] = "Golem Network"
        provider['node_id'] = obj['properties']['id']
        provider['img'] = "/golem.png"
        provider['usd_monthly'] = float(
            price) * float(obj['monthly_price_glm'])
        provider['cores'] = float(
            obj['properties']['golem.inf.cpu.threads'])
        provider['memory'] = float(obj['properties']['golem.inf.mem.gib'])
        provider['bandwidth'] = "Unlimited"
        provider['disk'] = float(
            obj['properties']['golem.inf.storage.gib'])
        provider['glm'] = float(obj['monthly_price_glm'])
        if float(obj['properties']['golem.inf.cpu.threads']) == 2 and len(two_cores) == 4:
            two_cores.append(provider)
        elif float(obj['properties']['golem.inf.cpu.threads']) >= 2 and len(two_cores) == 4:

            two_cores.append(provider)
        if float(obj['properties']['golem.inf.cpu.threads']) == 8 and len(eight_cores) == 4:

            eight_cores.append(provider)
        elif float(obj['properties']['golem.inf.cpu.threads']) >= 8 and len(eight_cores) == 4:

            eight_cores.append(provider)
        if float(obj['properties']['golem.inf.cpu.threads']) == 32 and len(thirtytwo_cores) == 4:

            thirtytwo_cores.append(provider)
        elif float(obj['properties']['golem.inf.cpu.threads']) >= 32 and len(thirtytwo_cores) == 4:

            thirtytwo_cores.append(provider)
        if float(obj['properties']['golem.inf.cpu.threads']) == 64 and len(sixtyfour_cores) == 4:

            sixtyfour_cores.append(provider)
        elif float(obj['properties']['golem.inf.cpu.threads']) >= 64 and len(sixtyfour_cores) == 4:

            sixtyfour_cores.append(provider)

    sorted_two = sorted(two_cores, key=lambda element: (
        float(element['usd_monthly'])))
    sorted_eight = sorted(eight_cores, key=lambda element: (
        float(element['usd_monthly'])))
    sorted_thirtytwo = sorted(thirtytwo_cores, key=lambda element: (
        float(element['usd_monthly'])))
    sorted_sixtyfour = sorted(sixtyfour_cores, key=lambda element: (
        float(element['usd_monthly'])))
    data = json.dumps({'2': sorted_two, '8': sorted_eight,
                      '32': sorted_thirtytwo, '64': sorted_sixtyfour})
    r.set("v2_cheapest_provider", data)

@ app.task
def v2_offer_scraper():
    os.chdir("/stats-backend/yapapi/examples/low-level-api/v2")
    with open('data.config') as f:
        for line in f:
            command = line
    proc = subprocess.Popen(command, shell=True)
    proc.wait()
    content = r.get("offers_v2")
    serialized = json.loads(content)
    now = datetime.datetime.now()
    days_in_current_month = calendar.monthrange(
        now.year, now.month)[1]
    seconds_current_month = days_in_current_month*24*60*60
    for line in serialized:
        data = json.loads(line)
        provider = data['id']
        wallet = data['wallet']
        obj, created = Node.objects.get_or_create(node_id=provider)
        if created:
            offerobj = Offer.objects.create(properties=data, provider=obj,
                                            runtime=data['golem.runtime.name'])
            if data['golem.runtime.name'] == 'vm':
                vectors = {}
                for key, value in enumerate(data['golem.com.usage.vector']):
                    vectors[value] = key
                monthly_pricing = (data['golem.com.pricing.model.linear.coeffs'][vectors['golem.usage.duration_sec']] * seconds_current_month) + (
                    data['golem.com.pricing.model.linear.coeffs'][vectors['golem.usage.cpu_sec']] * seconds_current_month * data['golem.inf.cpu.cores']) + data['golem.com.pricing.model.linear.coeffs'][-1]
                offerobj.monthly_price_glm = monthly_pricing
                offerobj.save()
            obj.wallet = wallet
            obj.online = True
            obj.save()
        else:
            offerobj, offercreated = Offer.objects.get_or_create(
                provider=obj, runtime=data['golem.runtime.name'])
            if data['golem.runtime.name'] == 'vm':
                vectors = {}
                for key, value in enumerate(data['golem.com.usage.vector']):
                    vectors[value] = key
                monthly_pricing = (data['golem.com.pricing.model.linear.coeffs'][vectors['golem.usage.duration_sec']] * seconds_current_month) + (
                    data['golem.com.pricing.model.linear.coeffs'][vectors['golem.usage.cpu_sec']] * seconds_current_month * data['golem.inf.cpu.cores']) + data['golem.com.pricing.model.linear.coeffs'][-1]
                offerobj.monthly_price_glm = monthly_pricing
                offerobj.save()
            offerobj.properties = data
            offerobj.save()
            obj.runtime = data['golem.runtime.name']
            obj.wallet = wallet
            obj.online = True
            obj.save()
    # Find offline providers
    str1 = ''.join(serialized)
    fd, path = tempfile.mkstemp()
    try:
        with os.fdopen(fd, 'w') as tmp:
            # do stuff with temp file
            tmp.write(str1)
            online_nodes = Node.objects.filter(online=True)
            for node in online_nodes:
                if not node.node_id in str1:
                    node.online = False
                    node.computing_now = False
                    node.save(update_fields=[
                              'online', 'computing_now'])
    finally:
        os.remove(path)

@ app.task
def v2_offer_scraper_hybrid_testnet():
    os.chdir("/stats-backend/yapapi/examples/low-level-api/hybrid")
    proc = subprocess.Popen(
        'export YAGNA_APPKEY=$(yagna app-key list --json | jq -r .[0].key) && python3 list-offers-testnet.py', shell=True)
    proc.wait()
    content = r.get("v2_offers_hybrid_testnet")

    serialized = json.loads(content)
    now = datetime.datetime.now()
    days_in_current_month = calendar.monthrange(
        now.year, now.month)[1]
    seconds_current_month = days_in_current_month*24*60*60
    nodes_to_create = []
    nodes_to_update = []
    offers_to_create = []
    offer_to_update = []
    offline_nodes = set(Node.objects.filter(
        online=True).values_list('node_id', flat=True))

    for line in serialized:
        data = json.loads(line)
        provider = data['id']
        wallet = data['wallet']
        obj, created = Node.objects.get_or_create(node_id=provider)
        if created:
            if data['golem.runtime.name'] == 'vm':
                vectors = {}
                for key, value in enumerate(data['golem.com.usage.vector']):
                    vectors[value] = key
                monthly_pricing = (data['golem.com.pricing.model.linear.coeffs'][vectors['golem.usage.duration_sec']] * seconds_current_month) + (
                    data['golem.com.pricing.model.linear.coeffs'][vectors['golem.usage.cpu_sec']] * seconds_current_month * data['golem.inf.cpu.cores']) + data['golem.com.pricing.model.linear.coeffs'][-1]
                offers_to_create.append(
                    Offer(properties=data, provider=obj, runtime=data['golem.runtime.name'], monthly_price_glm=monthly_pricing))
            offers_to_create.append(
                Offer(properties=data, provider=obj, runtime=data['golem.runtime.name']))
            nodeobj = Node(node_id=provider, wallet=wallet, online=True)
            nodes_to_create.append(
                nodeobj)
        else:
            offerobj, offercreated = Offer.objects.get_or_create(
                provider=obj, runtime=data['golem.runtime.name'])
            if data['golem.runtime.name'] == 'vm':
                vectors = {}
                for key, value in enumerate(data['golem.com.usage.vector']):
                    vectors[value] = key
                monthly_pricing = (data['golem.com.pricing.model.linear.coeffs'][vectors['golem.usage.duration_sec']] * seconds_current_month) + (
                    data['golem.com.pricing.model.linear.coeffs'][vectors['golem.usage.cpu_sec']] * seconds_current_month * data['golem.inf.cpu.cores']) + data['golem.com.pricing.model.linear.coeffs'][-1]
                offerobj.monthly_price_glm = monthly_pricing

            offerobj.properties = data
            offerobj.runtime = data['golem.runtime.name']
            if offercreated:
                offers_to_create.append(offerobj)
            else:
                offer_to_update.append(offerobj)
            obj.wallet = wallet
            obj.online = True
            obj.updated_at = timezone.now()
            nodes_to_update.append(obj)
        if provider in offline_nodes:
            offline_nodes.remove(provider)

    Node.objects.bulk_create(nodes_to_create)
    Node.objects.bulk_update(nodes_to_update, fields=[
        'wallet', 'online', 'updated_at', ])
    Offer.objects.bulk_create(offers_to_create)
    Offer.objects.bulk_update(offer_to_update, fields=[
        'properties', 'monthly_price_glm'])
    # mark offline nodes as offline
    Node.objects.filter(node_id__in=offline_nodes, online=True).update(
        online=False, computing_now=False, updated_at=timezone.now())


import cache
import timer
import lora
import websockets
import asyncio
import threading
import keyboard
import timestamp

def thread_function():
    while (not cache.stop_thread):
        timer.countdown(cache.t)

def thread_function_killer():
    while (not cache.stop_thread):
        record = keyboard.record(until = 'q')
        record = str(record[0])

        if record == "KeyboardEvent(q down)" or record == "KeyboardEvent(q up)":
            print('\nYou terminated the program!\nGoodbye\n.')
            cache.stop_thread = True
            break

def thread_function_bdreg():
    while (not cache.stop_thread):
        if cache.time_thread == True:
            time = timestamp.timestamp()
            cache_len = len(cache.cache)
            if cache_len > 0:
                print("\n[CACHE FLUSH]")
                lora.cacheClear(time)
            else:
                print("\n[CACHE FLUSH EMPTY]")
            cache.marcos_fluxos.append(time)
            cache.numero_fluxos += 1
            cache.time_thread = False

        #if cache.expire_thread == True:
        #    time = timestamp.timestamp()
        #    cache_len = len(cache.cache)
        #    if cache_len > 0:
        #        lora.reg_expire(time)
        #    cache.expire_thread = False

        if len(cache.cache) >= cache.cache_max_size :
            time = timestamp.timestamp()
            cache_len = len(cache.cache)
            if cache_len > 0:
                print("\n[CACHE SIZE FLUSH]")
                lora.cacheClear(time)
            print("\n[CACHE SIZE FLUSH EMPTY]")
            cache.marcos_fluxos.append(time)
            cache.numero_fluxos += 1

    return

def main():
    x = threading.Thread(target=thread_function)
    #y = threading.Thread(target=thread_function_killer)
    z = threading.Thread(target = thread_function_bdreg)
    #y.start()
    z.start()
    x.start()

    #Define uma função assíncrona que se conecta ao seridor e lida com as informações que chegam.
    async def listen():
        #Conecta ao servidor.
        async with websockets.connect(cache.url, ping_interval=None) as ws:
            await ws.send("") #conexão de testes
            #Faz com que a execução seja contínua e que se escute todas as mensagens que chegam.
            while (not cache.stop_thread):
                print("Listening")
                if cache.stop_thread == True:
                    return
                msg = await ws.recv()

                #Verifica se é uma mensagem de erro. Caso não seja, criar fluxo e armazena na cache.
                fluxo = lora.createFlow(msg)

                if fluxo != None:
                    cache.cache.append(fluxo)

                print("\nFLOW UPDATED TO CACHE:\n---------------------------")
                print(f"\n Último fluxo em: {cache.marcos_fluxos} | Fluxos registrados: {cache.numero_fluxos} | Mensagens totais: {cache.numero_mensagens}\n")
    #It will run the function "listen()" and it will wait until it is completed.
    #We need a connection wich is asyn, and we need a received message wich is also async.
    asyncio.get_event_loop().run_until_complete(listen())
if __name__ == "__main__":
    main()


from permute import recursive

# @recursive
def test_single(depth: int) -> int:
    if depth == 10:
        return 0
    return test_single(depth+1) + 1

def sum_results(results: list[int]) -> int:
    result: int = 0
    for r in results:
        result += r
    return result

@recursive
def test_branching(depth: int) -> int:
    if depth == 7:
        return 1

    results: list[int] = []
    for _ in range(2):
        results.append(test_branching(depth+1))

    return sum_results(results)


'''
Minimum Multiple
Given a collection C1 of ‘n’ positive integers and a number ‘m’ write a C program to find the minimum multiple of m in C1. If no such multiple exist in C1 then print ‘No multiple found’

For example, if there are seven elements 23, 24, 25, 12, 6, 7, 11 and m is 3 then the output should be 6.

Input Format

First line contains the number of elements in the collection C1, n

Next ‘n’ lines contain the elements in the collection C1

Next line contains the value of m

Output Format

Print the minimum multiple of ‘m’ present in C1 or ‘No multiple found’

print("h")
Input
7
23
24
25
12
6
7
11
3
Expected output
6
Your Program Output
6
H
'''
#input format
n=int(input())
lst=[]

for i in range(n):
    ele=int(input())
    lst.append(ele)
check=int(input())

#driver code
lst.sort()
count=0
for i in lst:
    if(i%check==0):
        print(i)
        count+=1
        break

if(count==0):
    print("No multiple found")


class Employee:

    raise_amount = 1.04
    num_emps = 0

    def __init__(self, first, last, pay):
        self.first = first
        self.last = last
        self.pay = pay
        self.email = first + '.' + last + '@company.com'

        Employee.num_emps += 1

    def fullname(self):
        return f"{self.first} {self.last}"

    def apply_raise(self):
        self.pay = int(self.pay * self.raise_amount)

    @classmethod
    def set_raise_amount(cls, amount):
        cls.raise_amount = amount

    @classmethod
    def from_string(cls, emp_str):
        first, last, pay = emp_str.split('-')
        return cls(first, last, pay)

    """Regular methods pass the instance, 'self', as the first argument. Class methods pass
    the class, 'cls', as the first argument. Static methods do not pass anything
    automatically. They behave like regular functions but add logical connection to the class."""

    """Static methods have a limited use case, as they cannot access the properties
    of classes themselves. They are used if you need a utility function that
    doesn't access class properties but still needs to belong to the class."""

    """If the instance or class is not used anywhere within a function, it
    is a static method. Therefore, you should use a static method if the code
    is not dependant on instance creation and does not use any instance variable."""

    """Create a function that takes a date and checks if it is a workday.
    In Python, days have indexes 0-6 for Mon-Sun."""

    @staticmethod
    def is_workday(day):
        if day.weekday() == 5 or day.weekday() == 6: #checks if weekend
            return False
        else:
            return True

emp_1 = Employee("Corey", "Schafer", 50000)
emp_2 = Employee("Test", "User", 60000)

import datetime
my_date = datetime.date(2016, 7, 10) #prints false as it is a Sunday
print(Employee.is_workday(my_date))


import numpy as np
import matplotlib.pyplot as plt
from pathlib import Path

from SnapOptimizer.optimization.snap_optimizer import SNAPGateOptimizer2Qubits, SNAPGateOptimizerStatePreparation
from SnapOptimizer.optimization.snap_pulse_optimizer import SNAPPulseOptimizer
import SnapOptimizer.qubit_gates as qubit_gates
from SnapOptimizer.visualize import show_state
from SnapOptimizer.encodings import Encoding
import SnapOptimizer.paths as local_paths

def optimize_SNAP_gates(
    encoding: Encoding, gates: list[str], n_gates: list[int], Ns: list[int], epochs: int, output_folder: Path,
    show_figure: bool = False, c: float = 0.001, averages: int = 1
):
    """
    Automation for the optimization of SNAP gates

    Args:
        encoding: The encoding to use
        gates: The gates to optimize
        n_gates: How many SNAP gates to use to replicate the gate
        Ns: Size of the Hilbert space in the fock basis
        epochs: How many epochs to run the optimization for
        output_folder: folder to save the results to
        show_figure: If True the figures will pop up on screen when they are drawn. Otherwise they will only be saved
        c: Parameter to control the weight of the thetas in the optimization
        averages: Run the same optimization multiple times
    """
    fidelity_fig, fidelity_ax = plt.subplots(1, figsize=(8, 8))

    for N in Ns:
        code = encoding.get_encoding(N)
        snap_op = SNAPGateOptimizer2Qubits(code, c=c)

        for gate_name in gates:
            gate = getattr(qubit_gates, gate_name.upper(), None)
            if gate is None:
                print(f"The gate {gate_name} is not defined. Check your spelling and try again")
                continue

            for n in n_gates:
                for i in range(averages):
                    if averages == 1:
                        save_to = output_folder / f"{gate_name}-{n}-gates-{N}-fockstates"
                    else:
                        save_to = output_folder / f"{gate_name}-{n}-gates-{N}-fockstates_{i+1}"
                    alphas, thetas, _, fidelities = snap_op.optimize_gates(gate, n, epochs, output_folder=save_to)

                    # Generate figures
                    fidelity_ax.plot(range(epochs), fidelities, label=f"{gate_name} {n} gates {N} fock")

                    fig, axs = plt.subplots(2, 4, figsize=(16, 8))

                    for i, qubit_state in enumerate(['L00', 'L01', 'L10', 'L11']):
                        logic_state = getattr(snap_op, qubit_state)

                        evolved_state = snap_op.snap_gate(alphas, thetas, logic_state)
                        expected_state = snap_op.transform_gate(gate) @ logic_state

                        show_state(evolved_state, ax=axs[0][i], title=f"Gate on {qubit_state}")
                        show_state(expected_state, ax=axs[1][i], title="")

                    fig.savefig(save_to / 'wigner_plots.png', dpi=150)
                    if show_figure:
                        plt.show()
                    plt.close(fig)

    # Figure over the fidelities
    fidelity_ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
    fidelity_fig.tight_layout()
    fidelity_ax.set_ylabel("Fidelity")
    fidelity_ax.set_xlabel("Epoch")
    fidelity_ax.set_ylim([0, 1.1])
    filename = output_folder / 'fidelity_plot.png'

    # Handle the possibility of the image already existing. (Multiple processes running the optimization)
    counter = 1
    while filename.exists():
        filename = output_folder / f'fidelity_plot_{counter}.png'
        counter += 1

    fidelity_fig.savefig(filename, dpi=150)
    if show_figure:
        plt.show()

def optimize_SNAP_gates_for_state_preparation(state: np.ndarray, n: int, N: int, epochs: int = 2000, output_folder: Path = None):
    op = SNAPGateOptimizerStatePreparation(N=N)
    ground_state = np.zeros((N, 1))
    ground_state[0, 0] = 1
    alphas, thetas, cost, fidelities = op.optimize_gates(state, n_gates=n, epochs=epochs, output_folder=output_folder)

    _, (ax1, ax2) = plt.subplots(1, 2)
    fig, ax = plt.subplots(1)

    evolved_state = op.snap_gate(alphas, thetas, ground_state)

    show_state(evolved_state, ax=ax1, title=f"Evolved ground state")
    show_state(state, ax=ax2, title="Target state")

    ax.plot(range(len(fidelities)), fidelities)

    plt.show()

def optimize_SNAP_pulses(alphas: np.ndarray, thetas: np.ndarray, output_folder: Path = None):
    op = SNAPPulseOptimizer(
        dim_c = thetas.shape[-1],
        dim_t = 2,
        delta = -2.574749e6,
        xi = -2*np.pi* 2.217306e6,
        xip = -2*np.pi* 0.013763e6,
        K = -2*np.pi* 0.002692e6,
        alpha = 0,
        wt = 0,
        wc = 0,
        max_rabi_rate = 2*np.pi* 20e6,
        cutoff_frequency = 2*np.pi* 30e6,
        num_drives = 1
    )
    op.optimize_gate_pulses(thetas, alphas, 0.7e-6, output_folder=output_folder)

if __name__ == '__main__':
    # input_folder = local_paths.data('test_state_20')
    # output_folder = local_paths.pulses('test_state_20')
    # thetas = np.loadtxt(input_folder / 'thetas.csv', delimiter=',')
    # alphas = np.loadtxt(input_folder / 'alphas.csv', delimiter=',')
    # optimize_SNAP_pulses(alphas=alphas, thetas=thetas)

    output_folder = local_paths.data('fock_1')
    N = 12
    n = 1
    epochs = 3000
    fock1 = np.zeros((12, 1))
    fock1[1,:] = 1
    print(fock1)
    optimize_SNAP_gates_for_state_preparation(fock1, n, N, epochs=epochs, output_folder=output_folder)


#!/usr/bin/python

# Imports
### System
import os
import argparse

### Python
import numpy as np
import cv2 as cv
from tqdm.auto import tqdm
import matplotlib.pyplot as plt

### Pytorch
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F

### TODO: Use WandB, Pytorch Lightning & torchsummary
import wandb
import lightning.pytorch as pl
from lightning.pytorch import LightningDataModule, LightningModule, Trainer, seed_everything
from lightning.pytorch import Callback
from lightning.pytorch.callbacks import DeviceStatsMonitor, TQDMProgressBar, ModelCheckpoint, EarlyStopping, LearningRateMonitor
from lightning.pytorch.loggers import WandbLogger
from torchsummary import summary

### Timm
import timm
import timm.optim

### Custom
from custom_dataloader import get_dataloaders

# DONE_TODO 1: Import pytorch lightning, wandb(logging), timm and use it to load a pretrained model
# Done_TODO 2: Modify the model's classifier to output 3 classes instead of X (defined by the model)
# Done_TODO 3: Train the model + Logging & Saving best ckpt for 10 epochs and report test accuracy

def get_args():
    args = argparse.ArgumentParser(description='Transfer Learning')
    args.add_argument('--model', '-m', type=str, default='vgg16', required=True, help='Model to use [vgg16, vgg19, resnet50, resnet101, effb4, effb5]')
    args.add_argument('--epochs', '-e', type=int, default=10, help='Number of epochs to train for')
    args.add_argument('--batch_size', type=int, default=32, help='Batch size')
    args.add_argument('--device', '-d', type=str, default='cuda', required=True, help='Device to use [cpu, cuda:0, cuda:1, cuda]')
    args.add_argument('--mode', '-md', type=str, default='train', help='Mode to run: [train, trainX, test]. train = finetune only classifier layer. trainX = finetune last few layers including the classifier. test = test the model')
    args.add_argument('--ckpt_path', '-cp', type=str, default="", help='Path to checkpoint to load')
    args.add_argument('--lr', '-lr', type=float, default=1e-3, help='Learning rate')
    args.add_argument('--num_workers', '-nw', type=int, default=8, help='Number of workers for dataloader')
    args.add_argument('--exp_name', '-en', type=str, default='generic_exp', help='Experiment name for wandb')
    args.add_argument('--use_cam', action='store_true', help='Use Class Activation Maps Loss')
    # args.print_help()
    return args.parse_args()

def get_model(modelName):
    # VGG Fam
    if modelName == 'vgg16':
        model = timm.create_model('vgg16', pretrained=True)
    elif modelName == 'vgg19':
        model = timm.create_model('vgg19', pretrained=True)

    # Res Fam: Using catavgmax pooling to increase number of features
    elif modelName == 'resnet50':
        model = timm.create_model('resnet50', pretrained=True)
    elif modelName == 'resnet101':
        model = timm.create_model('resnet101', pretrained=True)

    # EfficientNet Fam: Using catavgmax pooling here as well
    elif modelName == 'effb4':
        model = timm.create_model('efficientnet_b4', pretrained=True)
    elif modelName == 'effb5':
        model = timm.create_model('efficientnet_b5', pretrained=True)

    return model

def check_args(args):
    if args.model not in ['vgg16', 'vgg19', 'resnet50', 'resnet101', 'effb4', 'effb5']:
        raise ValueError('[!] Invalid model')

    if 'cuda' in args.device and not torch.cuda.is_available():
        raise ValueError('[!] Cuda not available')

    if 'cuda:' in args.device:
        if int(args.device[-1]) >= torch.cuda.device_count():
            raise ValueError('[!] Invalid cuda device. You have lesser cuda devices than the one you specified')

class LIT_TL(pl.LightningModule):
    def __init__(self, model, modelName = "brrr", config: dict = None):
        super().__init__()
        self.save_hyperparameters(ignore=['model'])
        self.modelName = modelName
        self.config = config

        if "vgg" in modelName:
            self.num_filters = model.head.fc.in_features
        elif "eff" in modelName:
            self.num_filters = model.classifier.in_features
        else:
            self.num_filters = model.fc.in_features

        layers = list(model.children())[:-1]
        self.feature_extractor = nn.Sequential(*layers)
        num_target_classes = config['classes']

        if "vgg" in modelName: # custom classifier head for vggs ;)
            self.classifier = nn.Sequential(*[
                model.head.global_pool,
                model.head.drop,
                nn.Linear(in_features=4096, out_features=3, bias=True),
                model.head.flatten,
            ])
        else:
            self.classifier = nn.Linear(self.num_filters, num_target_classes)

        self.classifier.apply(self.init_xavier)
        self.ce_loss = nn.CrossEntropyLoss()

        # TODO: Apply Class-Activation-Maps Loss and visualize it
        self.use_cam = config['use_cam']
        if self.use_cam:
            self.gap_fc = nn.utils.spectral_norm(nn.Linear(self.num_filters, 1, bias=False))
            self.gmp_fc = nn.utils.spectral_norm(nn.Linear(self.num_filters, 1, bias=False))
            self.conv1x1 = nn.Conv2d(self.num_filters * 2, self.num_filters, kernel_size=1, stride=1, bias=True)
            self.conv_classifier = nn.utils.spectral_norm(
                nn.Conv2d(self.num_filters, 1, kernel_size=4, stride=1, padding=0, bias=False))
            self.cam_loss = nn.CrossEntropyLoss()

    def init_xavier(self, m):
        if type(m) == nn.Linear:
            torch.nn.init.xavier_uniform_(m.weight)
            m.bias.data.fill_(0.01)

    def calculate_accuracy(self, yhat, y):
        return 100. * torch.sum(yhat == y) / len(y)

    def forward(self, x):
        self.feature_extractor.eval()
        with torch.no_grad():
            rep = self.feature_extractor(x)

        if self.use_cam:
            gap = torch.nn.functional.adaptive_avg_pool2d(rep, 1)
            gap_logit = self.gap_fc(gap.view(rep.shape[0], -1))
            gap_weight = list(self.gap_fc.parameters())[0]
            gap = rep * gap_weight.unsqueeze(2).unsqueeze(3)

            gmp = torch.nn.functional.adaptive_max_pool2d(rep, 1)
            gmp_logit = self.gmp_fc(gmp.view(rep.shape[0], -1))
            gmp_weight = list(self.gmp_fc.parameters())[0]
            gmp = rep * gmp_weight.unsqueeze(2).unsqueeze(3)

            c_logit = torch.cat([gap_logit, gmp_logit], 1)
            rep = torch.cat([gap, gmp], 1)
            rep = self.leaky_relu(self.conv1x1(rep))

            heatmap = torch.sum(rep, dim=1, keepdim=True)

            rep = self.pad(rep)
            out = self.conv_classifier(rep)

            return out, c_logit, heatmap

        else:
            if not "vgg" in self.modelName:
                rep = rep.flatten(1)
            out = self.classifier(rep)
            return out

    def configure_optimizers(self):
        opt = timm.optim.AdamW((param for param in self.classifier.parameters() if param.requires_grad),
                               lr=self.config['lr'],
                               weight_decay=self.config['decay'])
        scheduler = torch.optim.lr_scheduler.CosineAnnealingWarmRestarts(opt,
                                                                         T_0=self.config['T_0'],
                                                                         eta_min=self.config['eta_min'])
        return [opt], [scheduler]

    def training_step(self, batch, batch_idx):
        img = batch['image'].to(self.device)
        # mask = batch['mask'] # Not Needed in classification setting
        y = batch['class_label'].to(self.device)

        if self.use_cam:
            y_hat, logits, heatmap = self.forward(img)

            if 1 + batch_idx % 100 == 0:
                plt.savefig(f"{self.config['model']}_{batch_idx}.png", heatmap.squeeze(0).cpu().numpy())

            cam_loss = self.cam_loss(logits, y)
            loss = self.ce_loss(y_hat, y) + cam_loss
        else:
            y_hat = self.forward(img)
            loss = self.ce_loss(y_hat, y)
            preds = torch.argmax(y_hat, dim=1)
        # print(f"y: {y}, y_hat: {y_hat}")

        # DONE_TODO: Log train metrics here
        train_step_acc = self.calculate_accuracy(preds, y) # DONE_TODO: Calculate train accuracy here
        self.log("train_acc", train_step_acc, on_step=True, on_epoch=True, prog_bar=True, logger=True)

        return loss

    def validation_step(self, batch, batch_idx):
        img = batch['image'].to(self.device)
        # mask = batch['mask'] # Not Needed in classification setting
        y = batch['class_label'].to(self.device)
        # print(f"{i+1} | {img.shape} | {y}")

        y_hat = self.forward(img)
        preds = torch.argmax(y_hat, dim=1)
        test_acc = self.calculate_accuracy(preds, y)

        self.log("test_acc", test_acc, on_step=True, on_epoch=True, prog_bar=True, logger=True)

        # DONE_TODO: Add images to the logger for one batch
        if (batch_idx + 1) % 10 == 0:
            id2cat = {'0': 'authentic', '1': 'copy-moved', '2': 'spliced'}
            caption_strs = []
            for i in range(len(img)):
                correct = "Misclassified" if preds[i] != y[i] else "Correct"
                caption_strs.append(f"Pred: {id2cat[str(preds[i].item())]}, Label: {id2cat[str(y[i].item())]} | {correct}")

            self.logger.log_image(
                key=f"Validation Batch: {batch_idx + 1}",
                images=[img[i] for i in range(len(img))],
                caption=caption_strs,
            )

    def test_step(self, batch, batch_idx):
        # NOTE: Same as validation loop minus the image logging
        # No image logging so that export can be done easily

        img = batch['image'].to(self.device)
        # mask = batch['mask'] # Not Needed in classification setting
        y = batch['class_label'].to(self.device)
        # print(f"{i+1} | {img.shape} | {y}")

        y_hat = self.forward(img)
        preds = torch.argmax(y_hat, dim=1)
        test_acc = self.calculate_accuracy(preds, y)

        self.log("test_acc", test_acc, on_step=True, on_epoch=True, prog_bar=True, logger=True)

def get_config(args):
    config = {
        'seed': 42,
        'model': args.model,
        'mode': args.mode,
        'lr': args.lr,
        'batch_size': args.batch_size,
        'epochs': args.epochs,
        'device': args.device,
        'num_workers': args.num_workers,
        'T_0': 50,
        'eta_min': 6e-4,
        'classes': 3,
        'decay': 1e-3,
        'exp_name': args.exp_name,
        'use_cam': args.use_cam
    }
    return config

if __name__ == '__main__':
    args = get_args()
    # print("Total devices:", torch.cuda.device_count())

    check_args(args) # will also set args.device properly
    config = get_config(args)
    seed_everything(42)
    if torch.cuda.is_available():
        device_name = torch.cuda.get_device_name(args.device)
    else:
        device_name = 'cpu'
    print("--------------------------------------------\nSelected device:", device_name,"\n--------------------------------------------")
    print(f"[+] Model Selected: {config['model']}")

    model = get_model(config['model'])

    lit_model = LIT_TL(model, config['model'], config)

    train_dataloader, test_dataloader = get_dataloaders(batch_size=config['batch_size'],
                                                        num_workers=config['num_workers'])

    # Callbacks
    checkpoint_callback = ModelCheckpoint(monitor="test_acc",
                                          mode="max",
                                          save_top_k=1,
                                          dirpath="checkpoints/",
                                          filename=f"{config['model']}" + "_{test_acc:.3f}")

    lr_monitor = LearningRateMonitor(logging_interval='step', log_momentum=True)
    # early_stop_callback = EarlyStopping(monitor="loss", patience=99)

    wandb.login()

    if config['exp_name'] == 'generic_exp':
        fnam = f"{config['model']}_GE"
    else:
        fnam = config['exp_name']

    wandb_logger = WandbLogger(project='forgery_detection',
                           name=f"TL_{fnam}",
                           config=config,
                           job_type='finetuning',
                           log_model="all")
    # call trainer
    trainer = Trainer(fast_dev_run=False,
                      inference_mode=False,  # to enable grad enabling during inference
                      max_epochs=config['epochs'],
                      accelerator="gpu" if "cuda" in config['device'] else "cpu",
                      devices=[int(config['device'].split(":")[-1])], # GPU ID that you selected
                      precision="16", # automatic mixed precision training
                      deterministic=True,
                      enable_checkpointing=True,
                      callbacks=[checkpoint_callback, lr_monitor],
                      gradient_clip_val=None,
                      log_every_n_steps=50,
                      logger=wandb_logger, # The absolute best: wandb <3
                      enable_progress_bar=True)

    # fit model
    if config['mode'] == 'train' or config['mode'] == 'trainX': # TODO: Implement trainX mode
        trainer.fit(lit_model, train_dataloader, test_dataloader)
    else:
        # DONE_TODO: Load last checkpoint and test
        if not os.exists(args.ckpt_path):
            args.ckpt_path = checkpoint_callback.best_model_path
        lit_model = LIT_TL.load_from_checkpoint(args.ckpt_path)
        lit_model.freeze()
        trainer.test(lit_model, test_dataloader)

    wandb.finish()


import torch
import numpy as np
import torch.nn as nn

class PositionalEncoding1D(nn.Module):
    def __init__(self, num_pos_feats=64, temperature=10000, normalize=False, scale=None):
        """
        :param channels: The last dimension of the tensor you want to apply pos emb to.
        """
        super().__init__()
        self.channels = num_pos_feats
        dim_t = torch.arange(0, self.channels, 2).float()
        if scale is not None and normalize is False:
            raise ValueError("normalize should be True if scale is passed")
        if scale is None:
            scale = 2 * np.pi
        self.scale = scale
        self.normalize = normalize
        inv_freq = 1. / (temperature ** (dim_t / self.channels))
        self.register_buffer('inv_freq', inv_freq)

    def forward(self, tensor):
        """
        :param tensor: A 2d tensor of size (len, c)
        :return: Positional Encoding Matrix of size (len, c)
        """
        if tensor.ndim != 2:
            raise RuntimeError("The input tensor has to be 2D!")
        x, orig_ch = tensor.shape
        pos_x = torch.arange(
            1, x + 1, device=tensor.device).type(self.inv_freq.type())

        if self.normalize:
            eps = 1e-6
            pos_x = pos_x / (pos_x[-1:] + eps) * self.scale

        sin_inp_x = torch.einsum("i,j->ij", pos_x, self.inv_freq)
        emb_x = torch.cat((sin_inp_x.sin(), sin_inp_x.cos()), dim=-1)
        emb = torch.zeros((x, self.channels),
                          device=tensor.device).type(tensor.type())
        emb[:, :self.channels] = emb_x

        return emb[:, :orig_ch]

class PositionalEncoding2D(nn.Module):
    """
    This is a more standard version of the position embedding, very similar to the one
    used by the Attention is all you need paper, generalized to work on images.
    """
    def __init__(self, num_pos_feats=64, temperature=10000, normalize=False, scale=None):
        super().__init__()
        self.num_pos_feats = num_pos_feats
        self.temperature = temperature
        self.normalize = normalize
        if scale is not None and normalize is False:
            raise ValueError("normalize should be True if scale is passed")
        if scale is None:
            scale = 2 * np.pi
        self.scale = scale

    def forward(self, tensors):
        x = tensors.tensors
        mask = tensors.mask
        assert mask is not None
        not_mask = ~mask
        y_embed = not_mask.cumsum(1, dtype=torch.float32)
        x_embed = not_mask.cumsum(2, dtype=torch.float32)
        if self.normalize:
            eps = 1e-6
            y_embed = (y_embed - 0.5) / (y_embed[:, -1:, :] + eps) * self.scale
            x_embed = (x_embed - 0.5) / (x_embed[:, :, -1:] + eps) * self.scale

        dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device)
        dim_t = self.temperature ** (2 * torch.div(dim_t, 2, rounding_mode='trunc') / self.num_pos_feats)

        pos_x = x_embed[:, :, :, None] / dim_t
        pos_y = y_embed[:, :, :, None] / dim_t
        pos_x = torch.stack((pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4).flatten(3)
        pos_y = torch.stack((pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4).flatten(3)
        pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2)
        return pos


from re import T
from django.db import models

from machine.computations.examples import victorious_payment
from django.contrib.postgres.fields import ArrayField

# Create your models here.

class Machine(models.Model):

    def empty_list():
        return list()
    # identificar la maquina que estamos usando
    name = models.CharField(max_length=200, blank=True)

    payments = models.JSONField()
    free_spins = ArrayField(
        models.IntegerField(blank=True),
        size=5,
        default=empty_list
    )

    normal_reel = ArrayField(
        models.CharField(max_length=200, blank=True),
        size=5,
        default=empty_list
    )
    bonus_reel = ArrayField(
        models.CharField(max_length=200, blank=True),
        size=5,
        default=empty_list
    )
    visible = ArrayField(
        models.IntegerField(blank=True),
        size=5,
        default=empty_list
    )
    multiplier = models.IntegerField(default=3)

    # corregir:
    # ver si se puede mejorar
    roi = models.FloatField(default=0)

    def payment(self, roll):
        return victorious_payment(self, roll)

    def save(self, *args, **kwargs):
        self.roi += 0.01
        super(Machine, self).save(*args, **kwargs)

    def __str__(self) -> str:
        return self.name


import glob
import os
import sys
try:
    sys.path.append(glob.glob('../carla/dist/carla-*%d.%d-%s.egg' % (
        sys.version_info.major,
        sys.version_info.minor,
        'win-amd64' if os.name == 'nt' else 'linux-x86_64'))[0])
except IndexError:
    pass
import carla

import random
import time
import numpy as np
import cv2

IM_WIDTH = 640
IM_HEIGHT = 480

def process_img(image, name):
    print("Frame: "+str(image.frame)+", timestamp: "+str(image.timestamp))
    i = np.array(image.raw_data)
    i2 = i.reshape((IM_HEIGHT, IM_WIDTH, 4))
    i3 = i2[:, :, :3]
    cv2.imshow(name, i3)
    cv2.waitKey(1)

    if image.frame % 20 == 0:
        image.save_to_disk('_out/%06d.png' % image.frame)
    return i3/255.0

actor_list = []
try:
    # 0. Set the cilent and the world
    client = carla.Client('localhost', 2000) # https://carla.readthedocs.io/en/latest/core_world/#client-creation
    client.set_timeout(10)

    world = client.get_world()

    # 1. Choose blueprint for the vehicle
    blueprint_library = world.get_blueprint_library() # https://carla.readthedocs.io/en/latest/core_actors/#blueprints

    vehicle = blueprint_library.find('vehicle.tesla.model3') # vehicle_bp = blueprint_library.filter('model3')[0]
    vehicle.set_attribute('color', '255,0,0')
    print(vehicle)

    # 2. Choose spawn point
    # manually
    # spawn_point = carla.Transform(carla.Location(x=, y=, z=),
    # carla.Rotation(pitch=, yaw=, roll=))

    # automatically
    spawn_point_vehicle = random.choice(world.get_map().get_spawn_points())
    print(spawn_point_vehicle)

    # 3. Spawn the vehicles
    # spawn the actor
    actor_vehicle = world.spawn_actor(vehicle, spawn_point_vehicle)

    # set control mode. https://carla.readthedocs.io/en/latest/python_api/#carla.Vehicle
    # vehicle.apply_control(carla.VehicleControl(throttle=0.1, steer=0.0))
    actor_vehicle.set_autopilot(True)  # if you just wanted some NPCs to drive.

    # append to the actor_list
    actor_list.append(actor_vehicle)

    # 4. Get the blueprint for this sensor: https://carla.readthedocs.io/en/latest/core_sensors/
    sensor = blueprint_library.find('sensor.camera.rgb')
    # Change the dimensions of the image
    sensor.set_attribute('image_size_x', f'{IM_WIDTH}')
    sensor.set_attribute('image_size_y', f'{IM_HEIGHT}')
    sensor.set_attribute('fov', '110')

    # 5. Adjust sensor relative to vehicle
    # choose the relative spawn point
    spawn_point_sensor = carla.Transform(carla.Location(x=2.5, z=1.0), carla.Rotation(pitch=-15))
    print(spawn_point_sensor)

    # spawn the sensor and attach to vehicle.
    actor_sensor = world.spawn_actor(sensor, spawn_point_sensor, attach_to=actor_vehicle)

    # add sensor to list of actors
    actor_list.append(actor_sensor)

    # 6. Process the collected images: https://carla.readthedocs.io/en/latest/core_sensors/#listening
    # Use the data collected by the sensor. The lambda function can be customized
    actor_sensor.listen(lambda data: process_img(data, "camera1"))
    # actor_sensor.listen(lambda image: image.save_to_disk('output/%06d.png' % image.frame))

finally:
    print('destroying actors')
    for actor in actor_list:
        actor.destroy()
    print('done.')


import pygame
from time import time
import os

## OPTIONS LIEES A L'AFFICHAGE

screen_width, screen_height = 1280, 720  # taille de la fenetre
show_interface = False  # afficher le classement

ticks_per_second = 60  # nombre de mise à jour par seconde

empty_ground_color = (210, 210, 210)  # couleur d'une terre inoccupée
background_color = (73, 200, 255)  # couleur du vide
port_color = (13, 143, 185)
map_height = 650  # taille de la carte en pixel

## PRECHARGEMENTS

pygame.font.init()
font = pygame.font.Font("img/Proxima Nova Font.otf", 30)
small_font = pygame.font.Font("img/Proxima Nova Font.otf", 20)
flag_img = pygame.image.load("img/flag.png")
disabled_flag_img = pygame.image.load("img/disabled_flag.png")

folder_name = "result/" + str(int(time())) + "/"
os.mkdir(folder_name)

## OPTIONS LIEES AUX MONTAGES VIDEOS

record_games = True  # enregistrement des vidéos
edit_when_finished = True  # faire le montage une fois la vidéo terminée

min_x, max_x, min_y, max_y = 99999, -1, 99999, -1
framerate = 30  # nombre d'image par seconde
duration = 60  # durée de la partie, en secondes
result_duration = 5  # durée d'affichage du gagnant, en secondes
width, height = 1080, 1920  # taille de la vidéo
source_width, source_height = 1280, 720  # taille des images d'origine
top_text = "Bataille de terrain"  # texte affiché en haut de la vidéo
bottom_text = ["Abonnez vous et", "commentez votre", "département pour", "recevoir un boost !"]  # text affiché au bas de la vidéo


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('home', '0019_auto_20150312_1008'),
    ]

    operations = [
        migrations.CreateModel(
            name='LinkCategory',
            fields=[
                ('id', models.AutoField(serialize=False, primary_key=True, verbose_name='ID', auto_created=True)),
                ('name', models.CharField(max_length=200)),
                ('description', models.TextField(default=None, blank=True, null=True)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='WebLink',
            fields=[
                ('id', models.AutoField(serialize=False, primary_key=True, verbose_name='ID', auto_created=True)),
                ('name', models.CharField(max_length=200)),
                ('url', models.URLField()),
                ('category', models.ForeignKey(to='home.LinkCategory')),
            ],
            options={
            },
            bases=(models.Model,),
        ),
    ]


from dronekit import connect,LocationGlobalRelative,APIException,VehicleMode
import time
import socket
import math
import cv2, imutils, socket
import numpy as np
import base64
import cv2, imutils
import numpy as np
import base64
import torch

def arm_and_takeoff(aTargetAltitude):
    """
    Arms vehicle and fly to aTargetAltitude.
    """

    print("Basic pre-arm checks")
    # Don't let the user try to arm until autopilot is ready
    while not vehicle.is_armable:
        print(" Waiting for vehicle to initialise...")
        time.sleep(1)

    print("Arming motors")
    # Copter should arm in GUIDED mode
    vehicle.mode = VehicleMode("GUIDED")
    vehicle.armed = True

    while not vehicle.armed:
        print(" Waiting for arming...")
        time.sleep(1)

    print("Taking off!")
    vehicle.simple_takeoff(aTargetAltitude) # Take off to target altitude

    # Wait until the vehicle reaches a safe height before processing the goto (otherwise the command
    #  after Vehicle.simple_takeoff will execute immediately).
    while True:
        print(" Altitude: ", vehicle.location.global_relative_frame.alt)
        if vehicle.location.global_relative_frame.alt>=aTargetAltitude*0.95: #Trigger just below target alt.
            print("Reached target altitude")
            break
        time.sleep(1)

def send_ned_velocity(velocity_x, velocity_y, velocity_z, duration):
    """
    Move vehicle in direction based on specified velocity vectors.
    """
    msg = vehicle.message_factory.set_position_target_local_ned_encode(
        0,       # time_boot_ms (not used)
        0, 0,    # target system, target component
        mavutil.mavlink.MAV_FRAME_LOCAL_NED, # frame
        0b0000111111000111, # type_mask (only speeds enabled)
        0, 0, 0, # x, y, z positions (not used)
        velocity_x, velocity_y, velocity_z, # x, y, z velocity in m/s
        0, 0, 0, # x, y, z acceleration (not supported yet, ignored in GCS_Mavlink)
        0, 0)    # yaw, yaw_rate (not supported yet, ignored in GCS_Mavlink)

    # send command to vehicle on 1 Hz cycle
    for x in range(0,duration):
        vehicle.send_mavlink(msg)
        time.sleep(1)

# vehicle=connectMyCopter()
connection_string="/dev/ttyAMA0"
baud_rate=57600
print("Connecting")
vehicle=connect(connection_string,baud=baud_rate,wait_ready=True)
print("Connected to drone")

vehicle.mode=VehicleMode("GUIDED")
vehicle.armed=True
print ("Autopilot Firmware version: %s" % vehicle.version)
print ("Autopilot capabilities (supports ftp): %s" % vehicle.capabilities.ftp)
print ("Global Location: %s" % vehicle.location.global_frame)

#Arm and take of to altitude of 5 meters
arm_and_takeoff(0.5)

send_ned_velocity(0.5, 0, 0, 5)
vehicle.mode=VehicleMode("LAND")


from __future__ import absolute_import, division, print_function

from collections import OrderedDict

import flask
from flask import current_app, request

class APIEndpoint(object):
    MIN_API_VERSION = 3
    LATEST_API_VERSION = 3
    HEADER_PREFIX = "application/vnd.marv.v"

    def __init__(self, name, func, url_rule, defaults=None, methods=None, version=None, acl=None):
        self.name = name
        version = self.MIN_API_VERSION if version is None else version
        self.funcs = [(version, func)]
        self.url_rules = [(url_rule, {'defaults': defaults, 'methods': methods})]
        self.acl = set(acl) if acl else set()

    def __call__(self, *args, **kw):
        authorization = request.headers.get('Authorization')
        # TODO: can authorization be '' or is None test?
        if not authorization:
            authorization = request.args.get('access_token')
        groups = current_app.um.check_authorization(self.acl, authorization)

        try:
            accepted = (x[0] for x in flask.request.accept_mimetypes
                        if x[0].startswith(self.HEADER_PREFIX)).next()
            accepted_version = int(accepted[len(self.HEADER_PREFIX):])
        except (StopIteration, ValueError):
            accepted_version = self.MIN_API_VERSION

        try:
            func = (func for version, func in self.funcs
                    if version <= accepted_version).next()
        except StopIteration:
            flask.abort(406)

        return func(*args, **kw)

    def init_app(self, app, url_prefix=None, name_prefix=None):
        name = '.'.join(filter(None, [name_prefix, self.name]))
        for url_rule, options in self.url_rules:
            url_rule = ''.join(filter(None, [url_prefix, url_rule]))
            app.add_url_rule(url_rule, name, self, **options)

class APIGroup(object):
    def __init__(self, name, func, url_prefix=None):
        self.name = name
        self.func = func
        self.url_prefix = url_prefix
        self.endpoints = OrderedDict()

    def add_endpoint(self, ep):
        """endpoints and groups are all the same (for now)"""
        assert ep.name not in self.endpoints, ep
        self.endpoints[ep.name] = ep

    def endpoint(self, *args, **kw):
        return api_endpoint(*args, registry=self.endpoints, **kw)

    def init_app(self, app, url_prefix=None, name_prefix=None):
        self.func(app)
        name_prefix = '.'.join(filter(None, [name_prefix, self.name]))
        url_prefix = '/'.join(filter(None, [url_prefix, self.url_prefix])) or None
        for ep in self.endpoints.values():
            ep.init_app(app, url_prefix=url_prefix, name_prefix=name_prefix)

    def __repr__(self):
        return '<APIGroup {} url_prefix={}>'.format(self.name, self.url_prefix)

def api_endpoint(url_rule, defaults=None, methods=None, version=None,
                 cls=APIEndpoint, registry=None, acl=None):
    def decorator(func):
        if isinstance(func, cls):
            func.url_rules.append((url_rule, {'defaults': defaults, 'methods': methods}))
            return func

        name = func.func_name
        rv = cls(name, func, url_rule=url_rule, defaults=defaults,
                 methods=methods, version=version, acl=acl)
        rv.__doc__ = func.__doc__

        if registry is not None:
            assert name not in registry, name
            registry[name] = rv
        return rv
    return decorator

def api_group(url_prefix=None, cls=APIGroup):
    def decorator(func):
        if isinstance(func, cls):
            raise TypeError('Attempted to convert function into api group twice.')

        name = func.func_name
        rv = cls(name, func, url_prefix)
        rv.__doc__ = func.__doc__
        return rv
    return decorator


#client.py
import time
import socket
import _thread as thread
from time import sleep
import connHandle

# socket wrapper class
class sockW:
    def __init__ (self, sock, ipAddr):
        self.sock = sock
        self.ipAddr = ipAddr

    def get_ip_addr(self):
        return self.ipAddr

    def get_sock(self):
        return self.sock

# List of addr to connect to
addr = ['192.168.1.100',
        '192.168.1.101',
        '192.168.1.102',
        '192.168.1.103',
        '192.168.1.104',
        '192.168.1.105',
        '192.168.1.106',
        '192.168.1.107',
        '192.168.1.108',
        '192.168.1.109',
        '192.168.1.110',
        '192.168.1.111']

#addr = ['192.168.1.100']

# List of connHandle objects
conn = []

# connect to all addr
for i in addr:
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.settimeout(1)
    try:
        sock.connect((i, 9800))
        print(i + " + [OK]")
        sock_w = sockW(sock, i)
        conn_H = connHandle.connHandle(sock_w)
        conn.append(conn_H)
    except socket.error:
        print(i + " + [BAD]")
        continue

while (True):
    msg = input()
    if msg[:4] == "all ":
        for conn_H in conn:
            conn_H.step(msg[4:])
    elif msg[:5] == "allH ":
        for i in range(int(len(conn) / 2), len(conn)):
            conn[i].step(msg[5:])
    elif msg[:5] == "allL ":
        for i in range(0, int(len(conn) / 2)):
            conn[i].step(msg[5:])
    elif msg == "ls":
        print("\tCLIENT LIST\n<------------------------->\n")
        for conn_H in conn:
       	    print("| CLIENT: [" + conn_H.ip_addr + "] |\n")
        print("<------------------------->")
    elif msg == "help":
        client = conn[0]
        client.sock.send("help".encode())
        print(client.sock.recv(1000).decode())
    elif msg[:3] == "ip ":
        msg = msg[3:]
        client_ip = msg[:msg.index(' ')]
        msg = msg[msg.index(' ') + 1:]
        for conn_H in conn:
            if conn_H.ip_addr == client_ip:
                conn_H.step(msg)
    else:
        print("UNKOWN CMD!!!")


import tkinter as tk
import json
from api import functions

class window(tk.Tk):
	def __init__(self):
		super().__init__()
		self.geometry('767x445')
		self.title('Get daily news')
		self.funcs = functions()

	def main_window(self):
		# Creating required labels and frame
		title = tk.Label(self, text="Get news", font="monospace 20")
		frame = tk.Frame(self)

		# Creating required variables
		query = tk.StringVar()
		query.set('')

		# Creating entry boxes
		query_box = tk.Entry(frame, textvariable=query)

		# Creating label for entry box
		query_label = tk.Label(frame, text="Query: ")

		# Creating buttons
		submit = tk.Button(frame, text="Submit", command=lambda: (self.window_result(query.get())))

		# Packing everything
		query_label.grid(column=1, row=1)
		query_box.grid(column=2, row=1)
		submit.grid(column=1, row=2)

		title.pack()
		frame.pack()

	def show_json(self, json_data: str):
		# Creating required frame
		frame = tk.Frame(self.slave_window)

		# Creating required variables
		data = json.loads(json_data)
		articles = data.get('articles')
		titles = []
		selected_title = tk.StringVar()
		selected_title.set('Options')

		# Functions which will be used
		def find_selected_article(title: str, articles: list):
			for article in articles:
				if article.get('title') == title:
					return article
			return False

		def see_news(selected_article: dict):
			#self.slave_window.geometry('')
			frame.pack_forget()
			frame2 = tk.Frame(self.slave_window)

			title = tk.Label(frame2, text='Title: '+selected_article.get('title'))
			author = tk.Label(frame2, text='Author: '+selected_article.get('author'))
			source = tk.Label(frame2, text="Source: "+selected_article.get('source').get('name'))
			link = tk.Label(frame2, text='Link: '+selected_article.get('url'))
			date = tk.Label(frame2, text='Published At: '+selected_article.get('publishedAt'))
			content = tk.Label(frame2, text='Content: '+selected_article.get('content'))

			title.grid(column=1, row=1)
			author.grid(column=1, row=2)
			source.grid(column=1, row=3)
			link.grid(column=1, row=4)
			date.grid(column=1, row=5)
			content.grid(column=1, row=6)

			frame2.pack()

		for article in articles:
			titles.append(article.get('title'))

		# Creating label
		label_choose = tk.Label(frame, text="Choose News: ")

		# Creating option menu
		entry_box = tk.OptionMenu(frame, selected_title, *titles)

		# Creating buttons
		submit = tk.Button(frame, text="Submit", command=lambda: (frame.pack_forget(), see_news(find_selected_article(selected_title.get(), articles))))

		# Packing Everything
		label_choose.grid(column=1, row=1)
		entry_box.grid(column=2, row=1)
		submit.grid(column=1, row=2)
		frame.pack()

	def window_result(self, query: str):
		self.slave_window = tk.Toplevel(self)

		self.slave_window.title(f'GET {query} NEWS')
		self.slave_window.geometry('700x300')

		json_text = self.funcs.get(query)

		self.show_json(json_text)

if __name__=='__main__':
	windo = window()
	windo.main_window()
	windo.mainloop()


from django.core.management.base import BaseCommand

import os
from importlib import import_module
from django.conf import settings
from django.core.management import call_command
from newapp.utils import get_app_template_path, get_app_templates

APP_TEMPLATES = [ x.get('name') for x in get_app_templates() ]

class Command(BaseCommand):
    """
    Example usage:
    python manage.py newapp mambu --template=lite --appsdir=apps
    """
    help = __doc__
    args = '<function arg arg ...>'

    def check_name_conflick(self, name):
        apps_list = next(os.walk(os.path.join(settings.BASE_DIR, "apps")))[1]
        apps_list = apps_list +['admin', 'admindocs', 'auth' ,'contenttypes' ,'flatpages','gis','humanize',
                            'messages','postgres','redirects','sessions','sitemaps','sites','staticfiles'
                            'syndication']
        if name in apps_list:
            return True
        else:
            try:
                import_module(name)
            except ImportError:
                return False
            else:
                return True

    def add_arguments(self, parser):
        parser.add_argument('name', type=str)
        parser.add_argument('--apptype', '-t', dest='apptype', default='lite',
                            help='Application type')
        parser.add_argument('--appdir', '-d', type=str, dest='appdir',  default='/',
                            help='Target directory')

    def handle(self, *args, **options):

        name = options['name']
        if self.check_name_conflick(name):
            self.stdout.write(self.style.ERROR("Sorry, but you can't use %s as name because this name already taken" % name))
            exit()

        apps_type = options['apptype']
        if apps_type not in APP_TEMPLATES:
            self.stdout.write(self.style.ERROR("no template with name %s" % apps_type))
            exit()

        if options['appdir'] == "/":
            app_dir = settings.BASE_DIR
            app_path = os.path.join(settings.BASE_DIR, name)
        else:
            app_dir = options['appdir'].strip("/")
            app_path = os.path.join(settings.BASE_DIR, "%s/%s" % (app_dir, name))

        if os.path.isdir(app_dir):
            os.mkdir(app_path)
        else:
            self.stdout.write(self.style.ERROR("Appdir %s not found" % app_dir))
            exit()

        template_path = get_app_template_path(apps_type)
        call_command("startapp", name, app_path, template=template_path)
        os.unlink(os.path.join(app_path, "desc.txt"))
        self.stdout.write(self.style.SUCCESS("Congratulation apps %s successfuly created" % name))


'''
Author - Imanpal Singh <imanpalsingh@gmail.com>
GUI application for twitter sentiment analysis
Date created :  - 02-07-2019
Date modified : - 03-07-2019
'''

#importing requierd libraries
import numpy as np
import pandas as pd

from nltk.corpus import stopwords
from nltk.stem.porter import PorterStemmer
ps = PorterStemmer()

from sklearn.naive_bayes import GaussianNB
nb = GaussianNB()

from sklearn.feature_extraction.text import CountVectorizer
cv = CountVectorizer(max_features = 8000)

import re

import tkinter as tk
from tkinter import Text

import pyperclip

#Global variable to hold score
score=0

#Machine Learning part

def Algorithm(file):

    global score
    #Loading the dataset
    dataset = pd.read_csv(file)

    #Cleaning tweets
    clean_tweets = []

    for i in range(len(dataset)):
        tw = re.sub('[^a-zA-Z]', ' ', dataset['tweet'][i])
        tw = re.sub('@[\w]*',' ',tw)
        tw = tw.lower()
        tw = tw.split()
        tw = [ps.stem(token) for token in tw if not token in set(stopwords.words('english'))]
        tw = ' '.join(tw)
        clean_tweets.append(tw)

    #textual encoding
    X = cv.fit_transform(clean_tweets)
    X = X.toarray()
    y = dataset.iloc[:, 1].values

    #splitting the data
    from sklearn.model_selection import train_test_split
    X_train,X_test,y_train,y_test = train_test_split(X,y)
    #training the data
    nb.fit(X_train,y_train)
    score = nb.score(X_test,y_test)
    print("Score is : - ",score)

#Function to handle Go button event
def forward():

    #Getting the tweet
    tw = tweet.get("1.0","end")

    #Cleaning the tweet
    tw = re.sub('[^a-zA-Z]', ' ', tw)
    tw = re.sub('@[\w]*',' ',tw)
    tw = tw.lower()
    tw = tw.split("\n")
    tw = [ps.stem(token) for token in tw if not token in set(stopwords.words('english'))]
    tw = cv.transform(tw)
    tw = tw.toarray()

    #Predicting the class
    y_pred = nb.predict(tw)

    #Clearning the Entry
    tweet.delete("1.0","end")

    #Displaying the class
    if y_pred[0] == 0:
        tweet.insert("1.0","The tweet entered is normal ( model's accuracy : {}% )".format(score*100))
    else :
        tweet.insert("1.0","The tweet entered is negative ( model's accuracy : {}% )".format(score*100))

#Function to handle Paste from clipboard button event
def clippaste():

    tweet.insert("1.0",pyperclip.paste())

 #Initialising algorithm
Algorithm('train.csv')

#GUI part

#Creating a window
Main = tk.Tk()
Main.configure(background='white')
Main.title("Twitter Sentiment analysis")
Main.geometry("1000x400+400+300")

#Adding the heading
one = tk.Label(Main,text="Twitter Sentiment analysis",fg="white",width="100",height="2")
one.configure(background="#6E97ED",font=(20))

#Adding the textbox
tweet = tk.Text(Main,height="10",width="60")
tweet.insert("1.0","Paste tweet here..")
tweet.configure(bd=0,fg="#6E97ED")

#Adding buttons
button_frame = tk.Frame(Main)
button_frame.configure(background="white")
go= tk.Button(button_frame,text="GO !",width="10",height="5",command=forward)
go.configure(background="#6E97ED",fg="white",bd=0)
paste = tk.Button(button_frame,text="Paste from clipboard",width="20",height="5",command=clippaste)
paste.configure(background="#6E97ED",fg="white",bd=0)

#Finishing up
one.pack(pady=30)
tweet.pack(side="top",padx=10,pady=20)
go.pack(side="left")
paste.pack(side="left",padx="30")
button_frame.pack(side="bottom")

#Removing resizeable feature
Main.resizable(0,0)
tk.mainloop()


import sys
from collections import deque

def div_area(q):
    while q:
        r, c = q.popleft()

        for x, y in [[r + 1, c], [r - 1, c], [r, c + 1], [r, c - 1]]:
            if 0<= x < n and 0<= y < m:
                if area[x][y] == 0:
                    area[x][y] = -1
                    q.append([x, y])

def next_hour():
    global cheese
    new_cheese = []
    new_air = deque()
    air = []

    for i, j in cheese:
        cnt = 0
        cnt2 = 0

        for x, y in [[i - 1, j], [i + 1, j], [i, j - 1], [i, j + 1]]:
            if area[x][y] == -1:
                cnt += 1
            elif area[x][y] == 0:
                cnt2 += 1
        if cnt >= 2:
            air.append([i, j])
            if cnt2 > 0:
                new_air.append([i, j])

        else:
            new_cheese.append([i, j])

    for i, j in air:
        area[i][j] = -1

    div_area(new_air)
    cheese = new_cheese

n, m = map(int, sys.stdin.readline().strip().split())
area = [list(map(int, sys.stdin.readline().strip().split())) for _ in range(n)]
cheese = []
for i in range(n):
    for j in range(m):
        if area[i][j] == 1:
            cheese.append([i, j])

area[0][0] = -1
div_area(deque([[0, 0]]))

cnt = 0

while cheese:
    next_hour()
    cnt += 1

print(cnt)


import copy
import logging
import os.path as osp

import numpy as np
import torch
from fvcore.common.file_io import PathManager
from PIL import Image
from pycocotools import mask as maskUtils

from detectron2.data import detection_utils as utils
from detectron2.data import transforms as T
from detectron2.data.dataset_mapper import DatasetMapper
from detectron2.data.detection_utils import SizeMismatchError
from detectron2.structures import BoxMode

from .augmentation import RandomCropWithInstance
from .detection_utils import (annotations_to_instances, build_augmentation,
                              transform_instance_annotations)

"""
This file contains the default mapping that's applied to "dataset dicts".
"""

__all__ = ["DatasetMapperWithBasis"]

logger = logging.getLogger(__name__)

def segmToRLE(segm, img_size):
    h, w = img_size
    if type(segm) == list:
        # polygon -- a single object might consist of multiple parts
        # we merge all parts into one mask rle code
        rles = maskUtils.frPyObjects(segm, h, w)
        rle = maskUtils.merge(rles)
    elif type(segm["counts"]) == list:
        # uncompressed RLE
        rle = maskUtils.frPyObjects(segm, h, w)
    else:
        # rle
        rle = segm
    return rle

def segmToMask(segm, img_size):
    rle = segmToRLE(segm, img_size)
    m = maskUtils.decode(rle)
    return m

def filter_empty_instances(instances):
    """
    Filter out empty instances in an `Instances` object.

    Args:
        instances (Instances):
        by_box (bool): whether to filter out instances with empty boxes
        by_mask (bool): whether to filter out instances with empty masks
        box_threshold (float): minimum width and height to be considered non-empty
        return_mask (bool): whether to return boolean mask of filtered instances

    Returns:
        Instances: the filtered instances.
        tensor[bool], optional: boolean mask of filtered instances
    """
    pass
    r = []
    r.append(instances.gt_boxes.nonempty())

    if not r:
        return instances
    m = r[0]
    for x in r[1:]:
        m = m & x

    return instances[m]

class DatasetMapperWithBasis(DatasetMapper):
    """
    This caller enables the default Detectron2 mapper to read an additional basis semantic label
    """

    def __init__(self, cfg, is_train=True):
        super().__init__(cfg, is_train)

        # Rebuild augmentations
        logger.info(
            "Rebuilding the augmentations. The previous augmentations will be overridden."
        )
        self.augmentation = build_augmentation(cfg, is_train)

        if cfg.INPUT.CROP.ENABLED and is_train and cfg.MODEL.TRANSFORMER.BOUNDARY_HEAD:
            self.augmentation.insert(
                0,
                RandomCropWithInstance(
                    cfg.INPUT.CROP.TYPE,
                    cfg.INPUT.CROP.SIZE,
                    cfg.INPUT.CROP.CROP_INSTANCE,
                ),
            )
            logging.getLogger(__name__).info(
                "Cropping used in training: " + str(self.augmentation[0])
            )
        if cfg.INPUT.ROTATE and is_train:
            if cfg.MODEL.TRANSFORMER.BOUNDARY_HEAD:
                self.augmentation.insert(0, T.RandomRotation(angle=[-45, 45]))
            else:
                self.augmentation.insert(0, T.RandomRotation(angle=[-90, 90]))

    def __call__(self, dataset_dict):
        """
        Args:
            dataset_dict (dict): Metadata of one image, in Detectron2 Dataset format.

        Returns:
            dict: a format that builtin models in detectron2 accept
        """
        dataset_dict = copy.deepcopy(dataset_dict)  # it will be modified by code below
        # USER: Write your own image loading if it's not from a file
        try:
            image = utils.read_image(
                dataset_dict["file_name"], format=self.image_format
            )
        except Exception as e:
            print(dataset_dict["file_name"])
            print(e)
            raise e
        try:
            utils.check_image_size(dataset_dict, image)
        except SizeMismatchError as e:
            expected_wh = (dataset_dict["width"], dataset_dict["height"])
            image_wh = (image.shape[1], image.shape[0])
            if (image_wh[1], image_wh[0]) == expected_wh:
                print("transposing image {}".format(dataset_dict["file_name"]))
                image = image.transpose(1, 0, 2)
            else:
                raise e

        ######################################################################
        boxes = np.asarray(
            [
                BoxMode.convert(
                    instance["bbox"], instance["bbox_mode"], BoxMode.XYXY_ABS
                )
                for instance in dataset_dict["annotations"]
            ]
        )
        ######################################################################

        # aug_input = T.StandardAugInput(image)
        aug_input = T.StandardAugInput(image, boxes=boxes)

        transforms = aug_input.apply_augmentations(self.augmentation)
        image = aug_input.image

        image_shape = image.shape[:2]  # h, w
        # Pytorch's dataloader is efficient on torch.Tensor due to shared-memory,
        # but not efficient on large generic data structures due to the use of pickle & mp.Queue.
        # Therefore it's important to use torch.Tensor.
        dataset_dict["image"] = torch.as_tensor(
            np.ascontiguousarray(image.transpose(2, 0, 1))
        )

        if not self.is_train:
            dataset_dict.pop("annotations", None)
            dataset_dict.pop("sem_seg_file_name", None)
            dataset_dict.pop("pano_seg_file_name", None)
            return dataset_dict

        if "annotations" in dataset_dict:
            # USER: Modify this if you want to keep them for some reason.
            for anno in dataset_dict["annotations"]:
                if not self.use_instance_mask:
                    anno.pop("segmentation", None)
                if not self.use_keypoint:
                    anno.pop("keypoints", None)

            # USER: Implement additional transformations if you have other types of data
            annos = [
                transform_instance_annotations(
                    obj,
                    transforms,
                    image_shape,
                    keypoint_hflip_indices=self.keypoint_hflip_indices,
                )
                for obj in dataset_dict.pop("annotations")
                if obj.get("iscrowd", 0) == 0
            ]
            instances = annotations_to_instances(
                annos, image_shape, mask_format=self.instance_mask_format
            )

            # dataset_dict["instances"] = instances
            dataset_dict["instances"] = utils.filter_empty_instances(instances)

        return dataset_dict


vocabulary = []

with open('Voca_01.txt', 'r', encoding='utf-8') as file:
    for line in file:
        line = line.strip()  # Loại bỏ khoảng trắng dư thừa từ đầu và cuối dòng
        if not line:

            continue  # Bỏ qua dòng trống

        # Tách thông tin từ dòng sử dụng dấu ngoặc đơn (') và dấu ngoặc kép (")
        parts = line.split("(")
        if len(parts) < 2:
            print("not enough infor")
            continue  # Bỏ qua dòng không đủ thông tin
        else:
            english = parts[0].strip()
            phonetic = parts[1].split(')')[0].strip()
            vietnamese = parts[1].split(')')[1].strip()
            if vietnamese == "":
              continue
            else:
              vocabulary.append((english, phonetic, vietnamese))

# In ra kết quả
for entry in vocabulary:
    print("English:", entry[0])
    print("Phonetic:", entry[1])
    print("Translation:", entry[2])
    print()


import sys
import cv2
import numpy as np
from os import listdir

PY3 = sys.version_info[0] == 3

#Define the parameters
SIZE = 32
CLASS_NUMBER = 6

#Read the traffic sign dataset and store the dataset and labels into a list
def load_traffic_dataset():
    dataset = []
    labels = []
    for sign_type in range(CLASS_NUMBER):
        sign_list = listdir("./dataset/{}".format(sign_type))
        for sign_file in sign_list:
            if '.png' in sign_file:
                path = "./dataset/{}/{}".format(sign_type,sign_file)
                print(path)
                img = cv2.imread(path,0)
                img = cv2.resize(img, (SIZE, SIZE))
                img = np.reshape(img, [SIZE, SIZE])
                dataset.append(img)
                labels.append(sign_type)
    return np.array(dataset), np.array(labels)

#Deskew the images
def deskew(img):
    m = cv2.moments(img)
    if abs(m['mu02']) < 1e-2:
        return img.copy()
    skew = m['mu11']/m['mu02']
    M = np.float32([[1, skew, -0.5*SIZE*skew], [0, 1, 0]])
    img = cv2.warpAffine(img, M, (SIZE, SIZE), flags=cv2.WARP_INVERSE_MAP | cv2.INTER_LINEAR)
    return img

#Define a class for SVM model object
class StatModel(object):
    def load(self, fn):
        self.model.load(fn)  # Known bug: https://github.com/opencv/opencv/issues/4969
    def save(self, fn):
        self.model.save(fn)

class SVM(StatModel):
    def __init__(self, C = 12.5, gamma = 0.50625):
        self.model = cv2.ml.SVM_create()
        self.model.setGamma(gamma)
        self.model.setC(C)
        self.model.setKernel(cv2.ml.SVM_RBF)
        self.model.setType(cv2.ml.SVM_C_SVC)

    def train(self, samples, responses):
        self.model.train(samples, cv2.ml.ROW_SAMPLE, responses)

    def predict(self, samples):
        return self.model.predict(samples)[1].ravel()

def preprocess_simple(data):
    return np.float32(data).reshape(-1, SIZE*SIZE) / 255.0

def get_hog() :
    winSize = (20,20)
    blockSize = (10,10)
    blockStride = (5,5)
    cellSize = (10,10)
    nbins = 9
    deriveAperture = 1
    winSigma = -1.0
    histogramNormType = 0
    L2HysThreshold = 0.2
    gammaCorrection = 1
    nlevels = 64
    signedGradient = True

    hog = cv2.HOGDescriptor(winSize,blockSize,blockStride,cellSize,nbins,deriveAperture,winSigma,histogramNormType,L2HysThreshold,gammaCorrection,nlevels, signedGradient)
    return hog

#Train the model
def training():
    print('Loading data...')
    data, labels = load_traffic_dataset()
    print(data.shape)

    print('Shuffling data...')
    rand = np.random.RandomState(10)
    shuffle = rand.permutation(len(data))
    data, labels = data[shuffle], labels[shuffle]

    print('Deskewing images...')
    data_deskewed = list(map(deskew, data))

    print('Defining HoG parameters...')
    hog = get_hog()

    print('Calculating HoG descriptor for every image...')
    hog_descriptors = []
    for img in data_deskewed:
        hog_descriptors.append(hog.compute(img))
    hog_descriptors = np.squeeze(hog_descriptors)

    print('Training SVM model...')
    model = SVM()
    model.train(hog_descriptors, labels)

    print('Saving SVM model...')
    model.save('data_svm.dat')
    return model

#Get the label of detected traffic sign using the SVM model
def getLabel(model, data):
    gray = cv2.cvtColor(data, cv2.COLOR_BGR2GRAY)
    img = [cv2.resize(gray,(SIZE,SIZE))]
    img_deskewed = list(map(deskew, img))
    hog = get_hog()
    hog_descriptors = np.array([hog.compute(img_deskewed[0])])
    hog_descriptors = np.reshape(hog_descriptors, [-1, hog_descriptors.shape[1]])
    return int(model.predict(hog_descriptors)[0])


import sys

# 북동남서
dir_y = [-1, 0, 1, 0]
dir_x = [0, 1, 0, -1]
# 대각선들 오른쪽 위부터 시계
diagonal_y = [-1, 1, 1, -1]
diagonal_x = [1, 1, -1, -1]

N, M, K, C = list(map(int, sys.stdin.readline().strip().split()))

trees = [None] * N
killer = [[0] * N for _ in range(N)]
for i in range(N):
    trees[i] = list(map(int, sys.stdin.readline().strip().split()))

def out_of_range(y,x):
    return y < 0 or x < 0 or y >= N or x >= N

def grow():
    for i in range(N):
        for j in range(N):
            if trees[i][j] > 0:
                count = 0
                for d in range(4):
                    next_i, next_j = i + dir_y[d], j + dir_x[d]
                    if out_of_range(next_i, next_j):
                        continue
                    if trees[next_i][next_j] > 0:
                        count += 1
                trees[i][j] += count

def spread():
    cand = []
    for i in range(N):
        for j in range(N):
            if trees[i][j] > 0:
                position = []
                for d in range(4):
                    next_i, next_j = i + dir_y[d], j + dir_x[d]
                    if out_of_range(next_i, next_j) or trees[next_i][next_j] != 0 or killer[next_i][next_j] > 0:
                        continue
                    position.append((next_i, next_j))
                if position:
                    cand.append((position, trees[i][j] // len(position)))

    for position, length in cand:
        for p_i, p_j in position:
            trees[p_i][p_j] += length

def kill():
    best_y, best_x = -1, -1
    best_score = 0
    for i in range(N):
        for j in range(N):
            if trees[i][j] <= 0:
                continue
            count = trees[i][j]
            for d in range(4):
                for power in range(1, K + 1):
                    next_i, next_j = i + (diagonal_y[d] * power), j + (diagonal_x[d] * power)
                    if out_of_range(next_i, next_j) or trees[next_i][next_j] <= 0:
                        break
                    count += trees[next_i][next_j]

            if best_score < count:
                best_y, best_x = i, j
                best_score = count

    trees[best_y][best_x] = 0
    killer[best_y][best_x] = C + 1
    for d in range(4):
        for power in range(1, K + 1):
            next_i, next_j = best_y + (diagonal_y[d] * power), best_x + (diagonal_x[d] * power)
            if out_of_range(next_i, next_j) or trees[next_i][next_j] == -1:
                break
            if trees[next_i][next_j] == 0:
                killer[next_i][next_j] = C + 1
                break
            trees[next_i][next_j] = 0
            killer[next_i][next_j] = C + 1

    return best_score

def disappear():
    for i in range(N):
        for j in range(N):
            if killer[i][j] > 0:
                killer[i][j] -= 1

def solution():
    count = 0
    year = 1

    while year <= M:
        # print(year)
        # for k in killer:
        #     print(k)
        # print()

        # for t in trees:
        #     print(t)
        # print()
        grow()
        spread()
        # for t in trees:
        #     print(t)
        # print()
        count += kill()
        # for t in trees:
        #     print(t)
        # print()

        disappear()
        year += 1
    return count
print(solution())

"""
5 4 4 5
1 0 0 -1 5
0 0 -1 4 0
0 0 5 4 0
0 0 5 0 0
2 0 -1 0 0
"""


# -*- coding: utf-8 -*-
#
#
#  TheVirtualBrain-Scientific Package. This package holds all simulators, and
# analysers necessary to run brain-simulations. You can use it stand alone or
# in conjunction with TheVirtualBrain-Framework Package. See content of the
# documentation-folder for more details. See also http://www.thevirtualbrain.org
#
# (c) 2012-2013, Baycrest Centre for Geriatric Care ("Baycrest")
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License version 2 as published by the Free
# Software Foundation. This program 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 General Public
# License for more details. You should have received a copy of the GNU General
# Public License along with this program; if not, you can download it here
# http://www.gnu.org/licenses/old-licenses/gpl-2.0
#
#
#   CITATION:
# When using The Virtual Brain for scientific publications, please cite it as follows:
#
#   Paula Sanz Leon, Stuart A. Knock, M. Marmaduke Woodman, Lia Domide,
#   Jochen Mersmann, Anthony R. McIntosh, Viktor Jirsa (2013)
#   The Virtual Brain: a simulator of primate brain network dynamics.
#   Frontiers in Neuroinformatics (7:10. doi: 10.3389/fninf.2013.00010)
#
#

if __name__ == "__main__":
    from tvb.tests.library import setup_test_console_env
    setup_test_console_env()

import numpy
import unittest
from tvb.tests.library.base_testcase import BaseTestCase
from tvb.simulator.monitors import MonitorTransforms
from tvb.simulator import models, coupling, integrators, simulator
from tvb.datatypes import connectivity
from tvb.simulator.monitors import Raw, TemporalAverage

class MonitorTransformsTests(BaseTestCase):

    def test_split(self):
        mt = MonitorTransforms('a,c', '1,2', delim=',')
        self.assertEqual(len(mt.pre), 2)
        self.assertEqual(len(mt.post), 2)
        mt = MonitorTransforms('a;c', 'exp(x);2.234')
        self.assertEqual(len(mt.pre), 2)
        self.assertEqual(len(mt.post), 2)

    def test_pre_1(self):
        mt = MonitorTransforms('a', 'b;c')
        self.assertEqual(1, len(mt.pre))

    def test_post_1(self):
        mt = MonitorTransforms('a;b', 'c')
        self.assertEqual(1, len(mt.post))

    # def _shape_fail(self):
    #     MonitorTransforms('1,2,3', '2;3', delim=',')
    #
    # def test_shape_fail(self):
    #     self.assertRaises(Exception, self._shape_fail)

    def _syntax_fail(self, pre, post):
        MonitorTransforms(pre, post)

    def test_syntax(self):
        self.assertRaises(SyntaxError, self._syntax_fail, 'a=3', '23.234')
        self.assertRaises(SyntaxError, self._syntax_fail, 'a+b/c*f(a,b)', 'f=23')

    def test_noop_post(self):
        mt = MonitorTransforms('a;b;c', '2.34*(pre+1.5);;')
        self.assertEqual(len(mt.post), 3)

    def _fail_noop_pre(self):
        MonitorTransforms(';;', ';;')

    def test_noop_pre_fail(self):
        self.assertRaises(SyntaxError, self._fail_noop_pre)

    def test_pre(self):
        state = numpy.r_[:4].reshape((1, -1, 1))
        # check expr correctly evaluated
        mt = MonitorTransforms('x0**2', '')
        out = mt.apply_pre(state)
        self.assertEqual(out[0, -1, 0], 9)
        # check correct shape
        n_expr = numpy.random.randint(5, 10)
        pre_expr = ';'.join([str(i) for i in range(n_expr)])
        mt = MonitorTransforms(pre_expr, '')
        out = mt.apply_pre(state)
        self.assertEqual(n_expr, out.shape[0])

    def test_post(self):
        state = numpy.tile(numpy.r_[:4], (2, 1)).reshape((2, -1, 1))
        state[1] *= 2
        # check expr eval correct
        mt = MonitorTransforms('0;0', 'mon;')
        _, out = mt.apply_post((0.0, state))
        self.assertEqual(3, out.flat[3])
        self.assertEqual(6, out.flat[7])
        mt = MonitorTransforms('0;0', 'mon;mon**2-1')
        _, out = mt.apply_post((0.0, state))
        self.assertEqual(3, out.flat[3])
        self.assertEqual(35, out.flat[7])
        # check correct shape
        n_expr = numpy.random.randint(5, 10)
        state = numpy.tile(numpy.r_[:4], (n_expr, 1)).reshape((n_expr, -1, 1))
        post_expr = ';'.join([str(i) for i in range(n_expr)])
        mt = MonitorTransforms('0', post_expr)
        _, out = mt.apply_post((0.0, state))
        self.assertEqual(n_expr, out.shape[0])

    def test_user_tags(self):
        pre = '0;0'
        post = 'mon;mon**2-1'
        raw = Raw(pre_expr=pre, post_expr=post)
        tags = raw._transform_user_tags()
        self.assertIn('user_tag_1', tags)
        self.assertIn('user_tag_2', tags)
        self.assertEqual(tags['user_tag_1'], pre)
        self.assertEqual(tags['user_tag_2'], post)

class MonitorTransformsInSimTest(BaseTestCase):

    def _run_sim(self, length, model, *mons):
        sim = simulator.Simulator(
            model=model,
            connectivity=connectivity.Connectivity(load_default=True),
            coupling=coupling.Linear(),
            integrator=integrators.EulerDeterministic(),
            monitors=mons)
        sim.configure()
        ys = []
        for (t, y), in sim(simulation_length=length):
            ys.append(y)
        return sim, numpy.array(ys)

    def test_expr_pre(self):
        sim, ys = self._run_sim(5, models.Generic2dOscillator(), Raw(pre_expr='V;W;V**2;W-V',
                                                                     post_expr='mon;mon;mon;mon'))
        self.assertTrue(hasattr(sim.monitors[0], '_transforms'))
        v, w, v2, wmv = ys.transpose((1, 0, 2, 3))
        self.assertTrue(numpy.allclose(v ** 2, v2))
        self.assertTrue(numpy.allclose(w - v, wmv))

    def test_expr_post(self):
        sim, ys = self._run_sim(5, models.Generic2dOscillator(),
                                Raw(pre_expr='V;W;V;W', post_expr=';;mon**2; exp(mon)'))
        self.assertTrue(hasattr(sim.monitors[0], '_transforms'))
        v, w, v2, ew = ys.transpose((1, 0, 2, 3))
        self.assertTrue(numpy.allclose(v ** 2, v2))
        self.assertTrue(numpy.allclose(numpy.exp(w), ew))

    def test_expr_tim(self):
        sim, ys = self._run_sim(5, models.Epileptor(), Raw(pre_expr='-y0+y3;y2', post_expr='mon;mon'))
        self.assertTrue(hasattr(sim.monitors[0], '_transforms'))
        lfp, slow = ys.transpose((1, 0, 2, 3))

    def test_period_handling(self):
        """Test that expression application working for monitors with a period."""
        sim, ys = self._run_sim(5, models.Generic2dOscillator(), TemporalAverage(pre_expr='V+W'))

def suite():
    """
    Gather all the tests in a test suite.
    """
    test_suite = unittest.TestSuite()
    test_suite.addTest(unittest.makeSuite(MonitorTransformsInSimTest))
    test_suite.addTest(unittest.makeSuite(MonitorTransformsTests))
    return test_suite

if __name__ == "__main__":
    #So you can run tests from this package individually.
    TEST_RUNNER = unittest.TextTestRunner()
    TEST_SUITE = suite()
    TEST_RUNNER.run(TEST_SUITE)


#!/usr/bin/env python3
import rospy
import sounddevice as sd
import numpy as np
import queue
import sys
import sounddevice as sd
from audio_universal.msg import AudioData

'''
~output_device: use `python3 -m sounddevice` to get device list, numerical device ID or case-insensitive substrings is ok.
~channels: 1
~refresh_rate: 30
~latency: 'high'
~blocksize: 512
~dtype: 'float32'
~samplerate: 44100 48000 88200 96000 192000
'''

class audio_play:
    def __init__(self):
        self.initROS()
        self.q = queue.Queue()
        self.q_connects = queue.Queue()
        self.q_channels = queue.Queue()
        self.stream = sd.OutputStream(device=self.output_device,
                                      samplerate=self.samplerate,
                                      blocksize=self.blocksize,
                                      dtype=self.dtype,
                                      latency=self.latency,
                                      channels=self.channels,
                                      callback=self.audio_callback)
        with self.stream:
            rospy.spin()

    def initROS(self):
        rospy.init_node('audio_record', anonymous=True)
        self.output_device = rospy.get_param("~output_device", default=None)
        self.channels = rospy.get_param("~channels", default=1)
        self.refresh_rate = rospy.get_param("~refresh_rate", default=30)
        self.latency = rospy.get_param("~latency", default='high')
        self.blocksize = rospy.get_param("~blocksize", default=512)
        self.dtype = rospy.get_param("~dtype", default='float32')
        self.samplerate = rospy.get_param("~samplerate", default=48000)
        rospy.Subscriber('/audio_record_data', AudioData, self.AudioData_callback)

    def audio_callback(self, outdata, frames, time, status):
        if status:
            rospy.logwarn(status)
        try:
            data = self.q.get_nowait()
            connects = self.q_connects.get_nowait()
            in_channels = self.q_channels.get_nowait()
            data = data.reshape(self.blocksize, in_channels)
            if len(connects) / 2 != len(connects) // 2:
                raise Exception
            for idx in range(0, len(connects) // 2):
                if (connects[idx * 2] in range(0, self.channels)) and (connects[idx * 2 + 1] in range(0, self.channels)):
                    outdata[:, connects[idx * 2 + 1]] = data[:, connects[idx * 2]]
        except queue.Empty as e:
            # rospy.logwarn('Buffer is empty: increase buffersize?')
            outdata[:] = np.zeros_like(outdata)

    def AudioData_callback(self, AudioData):
        self.q.put(np.frombuffer(AudioData.data, dtype=self.dtype))
        self.q_connects.put(np.frombuffer(AudioData.connects, dtype='uint32'))
        self.q_channels.put(AudioData.channels)

if __name__ == '__main__':
    audio_play()