import os, shutil, random

# preparing the folder structure

full_data_path = 'data/obj/'
extension_allowed = '.png'
split_percentage = 80

# Create the directory for all the images
images_path = 'data/images/'
if os.path.exists(images_path):
    shutil.rmtree(images_path)
os.mkdir(images_path)

# Create the directory for all the images annotations
labels_path = 'data/labels/'
if os.path.exists(labels_path):
    shutil.rmtree(labels_path)
os.mkdir(labels_path)

# # Create the directory for the training and validation sets and their annotations files
training_images_path = images_path + 'training/'
validation_images_path = images_path + 'validation/'
training_labels_path = labels_path + 'training/'
validation_labels_path = labels_path + 'validation/'

os.mkdir(training_images_path)
os.mkdir(validation_images_path)
os.mkdir(training_labels_path)
os.mkdir(validation_labels_path)

files = []

ext_len = len(extension_allowed)

# Open the obj folder and select all the images with .jpg extension
for r, d, f in os.walk(full_data_path):
    for file in f:
        if file.endswith(extension_allowed):
            strip = file[0:len(file) - ext_len]
            files.append(strip)

random.shuffle(files)

size = len(files)

split = int(split_percentage * size / 100) # split the data

print("copying training data")
for i in range(split):
    strip = files[i]

    image_file = strip + extension_allowed
    src_image = full_data_path + image_file
    shutil.copy(src_image, training_images_path) # Copy the image into the training set folder for images

    annotation_file = strip + '.txt'
    src_label = full_data_path + annotation_file  #Take it corresponding annotation file
    shutil.copy(src_label, training_labels_path)  # Copy the annotation file in the training dataset folder for annotation

# Copy the remaining images and their annotations into the corresponding folders inside the validation directory
print("copying validation data")
for i in range(split, size):
    strip = files[i]
    image_file = strip + extension_allowed
    src_image = full_data_path + image_file
    shutil.copy(src_image, validation_images_path)

    annotation_file = strip + '.txt'
    src_label = full_data_path + annotation_file
    shutil.copy(src_label, validation_labels_path)

print("finished")


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

class Solution(object):
   def isSameTree(self,p,q):
      if not p and not q: #如果两个都能最后取到没有数值的情况。
         return True
      if p and q and p.val == q.val:
         x = self.isSameTree(p.left,q.left)#p和q所有的左子节点进行比较
         y = self.isSameTree(p.right,q.right)#p和q所有的右子节点进行比较
         return x and y #当x和y都为true的时候才是true
      else:
         return False


import matplotlib.pyplot as plt
import torch.nn.functional as F
import argparse
import torch
import os

def calc_accuracy(model, data_loader, device):
    correct_pred = 0
    instance_count = 0

    with torch.no_grad():
        model.eval()
        for x, y in data_loader:
            x, y = x.to(device), y.to(device)

            pred = model(x)
            _, pred_labels = torch.max(F.softmax(pred, dim=1), 1)

            instance_count += y.size(0)
            correct_pred += (pred_labels == y).sum().item()

    acc = correct_pred / instance_count
    return acc

def parse_train_args():
    parser = argparse.ArgumentParser(description="Training argument parser")

    parser.add_argument("-ne", "--num_epoch", type=int, required=False, default=10, help="number of epochs")
    parser.add_argument("-bs", "--batch_size", type=int, required=False, default=50, help="batch size")
    parser.add_argument("-ms", "--manual_seed", type=int, required=False, default=0, help="random seed")
    parser.add_argument("-d", "--device", type=str, required=False, default="cuda", help="device: cuda/cpu")
    parser.add_argument("-lr", "--learning_rate", type=float, required=False, default=0.001, help="learning rate")
    parser.add_argument("-nc", "--num_classes", type=int, required=False, default=10, help="number of classes")
    parser.add_argument("-tr", "--training_set_ratio", type=float, required=False, default=0.8,
                        help="the ratio between training and validation set")
    parser.add_argument("-mp", "--model_dir", type=str, required=False, default="./checkpoints",
                        help="model path to save")
    parser.add_argument("-pf", "--plot_flag", type=bool, required=False, default=True, help="plot all test results")
    parser.add_argument("-sc", "--save_checkpoint", type=int, required=False, default=10,
                        help="saving checkpoint every save_checkpoint epochs")
    parser.add_argument("-lm", "--load_model", type=bool, required=False, default=False,
                        help="load pretrained model, on restart case")
    parser.add_argument("-lmp", "--load_model_path", type=str, required=False,
                        help="path of the pretrained model to load, on restart case")

    args = parser.parse_args()
    return args

def parse_test_args():
    parser = argparse.ArgumentParser(description="Testing argument parser")

    parser.add_argument("-d", "--device", type=str, required=False, default="cpu", help="device: cuda/cpu")
    parser.add_argument("-nc", "--num_classes", type=int, required=False, default=10, help="number of classes")
    parser.add_argument("-ms", "--manual_seed", type=int, required=False, default=0, help="random seed")
    parser.add_argument("-bs", "--batch_size", type=int, required=False, default=1, help="batch size")
    parser.add_argument("-mp", "--model_path", type=str, required=True, help="model path to load")
    parser.add_argument("-pf", "--plot_flag", type=bool, required=False, default=False, help="plot all test results")

    args = parser.parse_args()
    return args

def plot_loss_accuracy(train_loss_lst: list, valid_loss_lst: list, train_acc_lst: list, valid_acc_lst: list):
    fig = plt.figure()
    plt.plot(train_loss_lst, '-bo')
    plt.plot(valid_loss_lst, '-go')
    plt.xlabel('epoch')
    plt.ylabel('loss')
    plt.legend(['Training', 'Validation'])
    fig.suptitle('Loss')

    fig = plt.figure()
    plt.plot(train_acc_lst, '-bo')
    plt.plot(valid_acc_lst, '-go')
    plt.xlabel('epoch')
    plt.ylabel('accuracy')
    plt.legend(['Training', 'Validation'])
    fig.suptitle('Accuracy')

    plt.show()

def save_checkpoint(dir_path, epoch, model, optim, loss):
    if not os.path.isdir(dir_path):
        os.mkdir(dir_path)

    path = f"{dir_path}/checkpoint_{epoch}.pt"

    torch.save({'epoch': epoch,
                'model_state_dict': model.state_dict(),
                'optimizer_state_dict': optim.state_dict(),
                'loss': loss
                },
               path)

def load_checkpoint(path, model, optim):
    checkpoint = torch.load(path)
    model.load_state_dict(checkpoint['model_state_dict'])
    optim.load_state_dict(checkpoint['optimizer_state_dict'])
    epoch = checkpoint['epoch']
    loss = checkpoint['loss']
    return epoch, loss


# All Submatrices Sum - From Top-Left
# The program must accept an integer matrix of size R*C as the input. The program must find all possible submatrices starting from the top-left cell of the given matrix. Then the program must print the sum of each submatrix as shown in the Example Input/Output section.

# Hint: Optimize your logic to avoid Time Limit Exceeded Error.

# Boundary Condition(s):
# 2 <= R, C <= 500
# 1 <= Matrix element value <= 10^4

# Input Format:
# The first line contains R and C separated by a space.
# The next R lines, each contains C integers separated by a space representing the R*C matrix.

# Output Format:
# The first R lines, each contains C integers separated by a space representing the of submatrices sum based on the given conditions.

# Example Input/Output 1:
# Input:
# 3 3
# 1 2 3
# 4 5 6
# 7 8 9

# Output:
# 1 3 6
# 5 12 21
# 12 27 45

# Explanation:
# 1 -> (1)
# 3 -> (1+2)
# 6 -> (1+2+3)
# 5 -> (1+4)
# 12 -> (1+2+4+5)
# 21 -> (1+2+3+4+5+6)
# 12 -> (1+4+7)
# 27 -> (1+2+4+5+7+8)
# 45 -> (1+2+3+4+5+6+7+8+9)

# Example Input/Output 2:
# Input:
# 4 5
# 70 40 20 50 20
# 30 10 60 50 90
# 80 60 20 60 70
# 10 30 30 10 10

# Output:
# 70 110 130 180 200
# 100 150 230 330 440
# 180 290 390 550 730
# 190 330 460 630 820

r,c=map(int,input().split())
mat=[list(map(int,input().split())) for _ in range(r)]
for i in range(r):
    p=0
    for j in range(c):
        if i!=0:
            mat[i][j]+=mat[i-1][j]

        p += mat[i][j]
        print(p,end=' ')
    print()


from django.shortcuts import render
from django.contrib import messages
from .models import Contact

def home(request):
    return render(request, 'home/home.html')

def about(request):
    name = 'Foyez Ahammad'
    skill = ' Git & Github, Django, MySQL, Basic Front-End (HTML, CSS, JS, Bootstrap), Django REST Framework'
    skill_know = '1. Python 2. Git & Github 3. Django 4. MySQL 5. A little bit (HTML, CSS, Bootstrap). '
    gpa = 'GPA: 5.00'

    # For Template tag condition
    num = 10
    knowledge = {'knowledge': ['Python', 'Git & Github', 'Django', 'MySQL']}
    context = {'name': name, 'skill': skill,
               'skill_know': skill_know, 'gpa': gpa, 'num': num}

    return render(request, 'home/about.html', context=context)
    return render(request, 'home/about.html', context=knowledge)

def contact(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        email = request.POST.get('email')
        phone = request.POST.get('phone')
        desc = request.POST.get('desc')
        contact = Contact(name=name, email=email, phone=phone, desc=desc)
        contact.save()
        messages.success(request, 'Successfully, ')
    return render(request, 'home/contact.html')


from django.core.paginator import Paginator, EmptyPage
from django.core.serializers import serialize
from django.shortcuts import render, redirect, reverse, get_object_or_404
from django.views import View
from django.contrib.auth.mixins import LoginRequiredMixin
from .forms import CreateOfferForm
from companies.models import Companies, Countries
from .models import OffersImages, Offers
from django.views.generic import DeleteView
from users.models import User
from django.http import Http404, JsonResponse, HttpResponse, HttpResponseRedirect
from funcy import omit
from django.dispatch import receiver
import os
from django.db.models.signals import post_delete, pre_save
from users.views import get_profile_ph
from users.models import Profile
import json
from users.mixins import AccessForCompletesOnlyMixin, AccessForMembersOnlyMixin
# from users.views import is_allowed

class CreateOfferView(AccessForMembersOnlyMixin, View):
    template_name = 'offers/create_offer.html'

    def get(self, request, **kwargs):

        # try:
        #     is_allowed(request)
        # except PermissionError:
        #     return redirect('set-profile-info')

        context = {
            'form': CreateOfferForm(),
            'profile_ph': get_profile_ph(request),
        }
        return render(request, self.template_name, context)

    def post(self, request, **kwargs):

        # try:
        #     is_allowed(request)
        # except PermissionError:
        #     return redirect('set-profile-info')

        form = CreateOfferForm(request.POST, request.FILES)
        company_id = kwargs['pk']
        images = request.FILES.getlist('image')

        company = Companies.objects.filter(id=company_id, owner=request.user).first()
        if not company:
            raise Http404

        if form.is_valid():

            obj = form.save(commit=False)
            obj.company = company
            obj.save()
            for i in images:
                OffersImages(offer=obj, image=i).save()

            nexty = request.POST.get('next')
            if nexty:
                try:
                    return HttpResponseRedirect(nexty)
                except:
                    raise Http404
            else:
                return redirect('offers:my-offers')

        context = {
            'form': form,
            'profile_ph': get_profile_ph(request),
        }
        return render(request, self.template_name, context)

class DeleteOfferView(AccessForMembersOnlyMixin, View):
    def post(self, request, **kwargs):
        obj = get_object_or_404(Offers, id=request.POST.get('id'))

        if obj.company.owner != self.request.user:
            raise Http404

        obj.delete()
        data = {'deleted': True, 'success': True}
        return JsonResponse(data)

class UpdateOfferView(AccessForMembersOnlyMixin, View):
    template_name = 'offers/update_offer.html'

    def get(self, request, **kwargs):

        # try:
        #     is_allowed(request)
        # except PermissionError:
        #     return redirect('set-profile-info')

        obj = get_object_or_404(Offers, id=kwargs['pk'])

        if obj.company.owner != request.user:
            raise Http404

        context = {
            'form': CreateOfferForm(initial={
                'type': obj.type,
                'coupon_price': obj.coupon_price,
                'currency': obj.currency,
                'retail_price': obj.retail_price,
                'title': obj.title,
                'amount_min': obj.amount_min,
                'amount_max': obj.amount_max
            }),
            'images': OffersImages.objects.filter(offer=obj).all(),
            'profile_ph': get_profile_ph(request),
        }
        return render(request, self.template_name, context)

    def post(self, request, **kwargs):

        # try:
        #     is_allowed(request)
        # except PermissionError:
        #     return redirect('set-profile-info')

        instance = get_object_or_404(Offers, id=kwargs['pk'])

        if instance.company.owner != request.user:
            raise Http404

        form = CreateOfferForm(request.POST, request.FILES, instance=instance)
        images = request.FILES.getlist('image')

        if form.is_valid():
            obj = form.save()
            for i in images:
                OffersImages(offer=obj, image=i).save()

            nexty = request.POST.get('next')
            if nexty:
                try:
                    return HttpResponseRedirect(nexty)
                except:
                    raise Http404
            else:
                return redirect('offers:my-offers')

        context = {
            'form': form,
            'profile_ph': get_profile_ph(request),
        }
        return render(request, self.template_name, context)

class OfferImageDeleteView(AccessForMembersOnlyMixin, View):
    def get(self, request, **kwargs):
        post = get_object_or_404(OffersImages, id=request.GET.get('id'))
        if post.offer.company.owner == request.user:
            post.delete()
            return JsonResponse({'success': True})
        else:
            return Http404

@receiver(post_delete, sender=OffersImages)
def post_save_image(sender, instance, *args, **kwargs):
    """ Clean Old Image file """
    try:
        instance.image.delete(save=False)
    except:
        pass

class MyOffersPageView(AccessForMembersOnlyMixin, View):
    template_name = 'offers/my_offers.html'

    def get(self, request, **kwargs):

        # try:
        #     is_allowed(request)
        # except PermissionError:
        #     return redirect('set-profile-info')

        objects = Companies.objects.filter(owner=request.user).prefetch_related('offers_set',
                                                                                'owner__profile_set').all()
        context = {
            'objects': objects,
            'profile_ph': get_profile_ph(request),
        }
        return render(request, self.template_name, context)

class SendImagesView(AccessForMembersOnlyMixin, View):
    def get(self, request, **kwargs):
        images = OffersImages.objects.filter(offer=request.GET.get('id')).all()
        res = []
        for image in images:
            res.append(image.image.url)
        return JsonResponse({'images': res})

class CatalogPageView(View):
    catalog_template = 'offers/catalog.html'
    catalog_template_hidden = 'offers/catalog-hidden.html'

    def get_template(self):
        if self.request.user.is_authenticated:
            if self.request.user.role >= User.INVITED:
                return self.catalog_template
        return self.catalog_template_hidden

    def get(self, request, **kwargs):
        offers = Offers.objects.prefetch_related('offersimages_set', 'company__owner__profile_set').order_by(
            '-id').all()
        currencies = Offers.objects.values('currency').distinct()
        niches = Companies.objects.values('niche').distinct()

        # niche = request.GET.get('niche')
        # if niche:
        #     initial_offers = initial_offers.filter(company__niche=niche)
        #
        # amount_min = request.GET.get('amount_min')
        # amount_max = request.GET.get('amount_max')
        # if amount_min and amount_max:
        #     initial_offers = initial_offers.filter(amount_min__lte=amount_max, amount_max__gte=amount_min)
        # elif amount_min:
        #     initial_offers = initial_offers.filter(amount_max__gte=amount_min)
        # elif amount_max:
        #     initial_offers = initial_offers.filter(amount_min__lte=amount_max)
        #
        # currency = request.GET.get('currency')
        # if currency:
        #     initial_offers = initial_offers.filter(currency=currency)
        #
        # retail_price_min = request.GET.get('retail_price_min')
        # retail_price_max = request.GET.get('retail_price_max')
        # if retail_price_min and retail_price_max:
        #     initial_offers = initial_offers.filter(retail_price__gte=retail_price_min,
        #                                            retail_price__lte=retail_price_max)
        # elif retail_price_min:
        #     initial_offers = initial_offers.filter(retail_price__gte=retail_price_min)
        # elif retail_price_max:
        #     initial_offers = initial_offers.filter(retail_price__lte=retail_price_max)
        #
        # coupon_price_min = request.GET.get('coupon_price_min')
        # coupon_price_max = request.GET.get('retail_price_max')
        # if coupon_price_min and coupon_price_max:
        #     initial_offers = initial_offers.filter(retail_price__gte=coupon_price_min,
        #                                            retail_price__lte=coupon_price_max)
        # elif coupon_price_min:
        #     initial_offers = initial_offers.filter(retail_price__gte=coupon_price_min)
        # elif coupon_price_max:
        #     initial_offers = initial_offers.filter(retail_price__lte=coupon_price_max)
        #
        # country = request.GET.get('country')
        # if country:
        #     initial_offers = initial_offers.filter(company__country_of_res=country)
        #
        # phone_num_show = request.GET.get('phone_num_show')
        # #phone_num_show = 1
        # if phone_num_show:
        #     suitable_users = Profile.objects.filter(phone_num_show=True).values_list('user_id', flat=True)
        #     initial_offers = initial_offers.filter(company__owner__id__in=suitable_users)
        #
        # print(initial_offers)
        #
        # p = Paginator(initial_offers, 2)
        #
        # page = request.GET.get('page')
        #
        # try:
        #     res = p.page(page)
        # except EmptyPage:
        #     raise Http404
        #
        # serialized_data = serialize("json", res, use_natural_foreign_keys=True, use_natural_primary_keys=True)
        # print(serialized_data)
        #
        # if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
        #     return JsonResponse(serialized_data, safe=False)
        try:
            profile_ph = get_profile_ph(request)
        except TypeError:
            profile_ph = None

        context = {
            'offers': offers,
            'profile_ph': profile_ph,
            'currencies': currencies,
            'niches': niches,
        }
        return render(request, self.get_template(), context)

@receiver(post_delete, sender=OffersImages)
def post_save_image(sender, instance, *args, **kwargs):
    """ Clean Old Image file """
    try:
        img = OffersImages.objects.filter(offer=instance.offer).first()
        obj = Offers.objects.get(id=instance.offer.id)
        if not img:
            obj.has_photo = False
            obj.save()
    except:
        pass

@receiver(pre_save, sender=OffersImages)
def pre_save_image(sender, instance, *args, **kwargs):
    """ instance old image file will delete from os """
    try:
        obj = Offers.objects.get(id=instance.offer.id)
        if not obj.has_photo:
            obj.has_photo = True
            obj.save()
    except:
        pass


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

class Solution:
	# @param A : root node of tree
	# @param B : integer
	# @return an integer
    def hasPathSum(self, root, B):
        if root:
            if not root.left and not root.right and root.val == B:
                return 1
            return Solution.hasPathSum(Solution, root.left, B - root.val) or Solution.hasPathSum(Solution, root.right, B - root.val)
        return 0

if __name__ == '__main__':
    root = TreeNode(5)
    root.left = TreeNode(4)
    root.right = TreeNode(8)
    root.left.left = TreeNode(11)
    root.left.left.left = TreeNode(7)
    root.left.left.right = TreeNode(2)
    root.right.left = TreeNode(13)
    root.right.right = TreeNode(4)
    root.right.right.right = TreeNode(1)
    B = 22

    # root = TreeNode(1000)
    # root.left = TreeNode(2000)
    # root.left.left = TreeNode(-3001)
    # B = -1
    print(Solution.hasPathSum(Solution,root, B))


#!/usr/bin/env python
# GoodFET SPI and SPIFlash Client Library
#
# (C) 2009 Travis Goodspeed <travis at radiantmachines.com>
#
# This code is being rewritten and refactored.  You've been warned!

import sys, time, string, cStringIO, struct, glob, serial, os;

from GoodFET import GoodFET;

class GoodFETSPI(GoodFET):
    def SPIsetup(self):
        """Move the FET into the SPI application."""
        self.writecmd(0x01,0x10,0,self.data); #SPI/SETUP

    def SPItrans8(self,byte):
        """Read and write 8 bits by SPI."""
        data=self.SPItrans([byte]);
        return ord(data[0]);

    def SPItrans(self,data):
        """Exchange data by SPI."""
        self.data=data;
        self.writecmd(0x01,0x00,len(data),data);
        return self.data;

class GoodFETSPIFlash(GoodFETSPI):
    JEDECmanufacturers={0xFF: "MISSING",
                        0xEF: "Winbond",
                        0xC2: "MXIC",
                        0x20: "Numonyx/ST",
                        0x1F: "Atmel",
                        0x01: "AMD/Spansion"
                        };

    JEDECdevices={0xFFFFFF: "MISSING",
                  0xEF3015: "W25X16L",
                  0xEF3014: "W25X80L",
                  0xEF3013: "W25X40L",
                  0xEF3012: "W25X20L",
                  0xEF3011: "W25X10L",
                  0xC22017: "MX25L6405D",
                  0xC22016: "MX25L3205D",
                  0xC22015: "MX25L1605D",
                  0xC22014: "MX25L8005",
                  0xC22013: "MX25L4005",
                  0x204011: "M45PE10"
                  };

    JEDECsizes={0x17: 0x800000,
                0x16: 0x400000,
                0x15: 0x200000,
                0x14: 0x100000,
                0x13: 0x080000,
                0x12: 0x040000,
                0x11: 0x020000
                };

    JEDECsize=0;

    def SPIjedec(self):
        """Grab an SPI Flash ROM's JEDEC bytes."""
        data=[0x9f, 0, 0, 0];
        data=self.SPItrans(data);

        self.JEDECmanufacturer=ord(data[1]);
        self.JEDECtype=ord(data[2]);
        self.JEDECcapacity=ord(data[3]);
        self.JEDECsize=self.JEDECsizes.get(self.JEDECcapacity);
        if self.JEDECsize==None:
            self.JEDECsize=0;
        self.JEDECdevice=(ord(data[1])<<16)+(ord(data[2])<<8)+ord(data[3]);
        return data;
    def SPIpeek(self,adr):
        """Grab a byte from an SPI Flash ROM."""
        data=[0x03,
              (adr&0xFF0000)>>16,
              (adr&0xFF00)>>8,
              adr&0xFF,
              0];
        self.SPItrans(data);
        return ord(self.data[4]);
    def SPIpeekblock(self,adr):
        """Grab a few block from an SPI Flash ROM.  Block size is unknown"""
        data=[(adr&0xFF0000)>>16,
              (adr&0xFF00)>>8,
              adr&0xFF];

        self.writecmd(0x01,0x02,3,data);
        return self.data;

    def SPIpokebyte(self,adr,val):
        self.SPIpokebytes(adr,[val]);
    def SPIpokebytes(self,adr,data):
        #Used to be 24 bits, BE, not 32 bits, LE.
        adranddata=[adr&0xFF,
                    (adr&0xFF00)>>8,
                    (adr&0xFF0000)>>16,
                    0, #MSB
                    ]+data;
        #print "%06x: poking %i bytes" % (adr,len(data));
        self.writecmd(0x01,0x03,
                      len(adranddata),adranddata);

    def SPIchiperase(self):
        """Mass erase an SPI Flash ROM."""
        self.writecmd(0x01,0x81);
    def SPIwriteenable(self):
        """SPI Flash Write Enable"""
        data=[0x06];
        self.SPItrans(data);

    def SPIjedecmanstr(self):
        """Grab the JEDEC manufacturer string.  Call after SPIjedec()."""
        man=self.JEDECmanufacturers.get(self.JEDECmanufacturer)
        if man==0:
            man="UNKNOWN";
        return man;

    def SPIjedecstr(self):
        """Grab the JEDEC manufacturer string.  Call after SPIjedec()."""
        man=self.JEDECmanufacturers.get(self.JEDECmanufacturer);
        if man==0:
            man="UNKNOWN";
        device=self.JEDECdevices.get(self.JEDECdevice);
        if device==0:
            device="???"
        return "%s %s" % (man,device);


from django.conf import settings
from django.utils.translation import ugettext_lazy as _

def robots(request):
    return {'ROBOTS_NOINDEX': getattr(settings, 'ROBOTS_NOINDEX', False)}

def google_analytics(request):
    key = 'GOOGLE_ANALYTICS_TRACKING_ID'
    return {key: getattr(settings, key, False)}

def ribbon(request):
    enabled = getattr(settings, 'RIBBON_ENABLED', True)
    if not enabled:
        return {'ribbon': False}

    url = 'http://github.com/colab/colab'
    text = _('Fork me!')

    return {
        'ribbon': {
            'text': getattr(settings, 'RIBBON_TEXT', text),
            'url': getattr(settings, 'RIBBON_URL', url),
        }
    }


"""The Number Guess Game:
Randomly roll a pair of dice
Add the values of the roll
Ask the user to guess a number
Compare the user's guess to the total value
Decide a winner (the user or the program)
Inform the user who the winner is"""

from random import randint
from time import sleep
from sys import stdout

def loading(message):
    """displaying the loading animation"""
    stdout.write(message)
    sleep(0.5)
    for i in range(4):
        stdout.write('.')
        sleep(0.2)
    print('.\n')

def get_user_guess():
  """prompt the user for their guess"""
  #prompt user for guess
  guess = raw_input("\nGuess a number: ")
  #repeat prompt if input is invalid
  while (not guess.isdigit()):
    print("Invalid entry. The input has to be an integer.")
    guess = raw_input("Please enter a valid number: ")
  #convert user guess to int and return it
  return int(guess)

def roll_dice(number_of_sides):
  """function will be used to simulate the rolling of a pair of dice."""
  #simulate the first die roll by generating a random integer between 1 and number_of_sides
  first_roll = randint(1, number_of_sides)
  #simulate the second die roll
  second_roll = randint(1, number_of_sides)
  #calculate the maximum value the program can possibly roll
  max_val = number_of_sides * 2
  #let the user know what the maximum possible value is
  print("\nThe maximum possible total value of the dice rolls is " +str(max_val) + ".")
  #sleep the program for 1 second
  sleep(1)
  #prompt the user for their guess
  user_guess = get_user_guess()
  #if the user guesses a number that is larger than the total possible value of the dice roll
  #keep inputting a guess until the entry is no longer invalid
  while user_guess>max_val:
    print("Your guess is larger than the total possible value of the dice roll.")
    user_guess = get_user_guess()
  else:
    #rolling effects
    loading("\nRolling")
    sleep(0.5)
    #announce first die roll
    print("The first die roll reads.. %d" % (first_roll))
    sleep(1)
    #announce second die roll
    print("The second die roll reads.. %d" % (second_roll))
    sleep(1)
    #sum the first and second die rolls
    total_roll = first_roll + second_roll
    #announce the roll
    print("The total roll is %d\n" % (total_roll))
    #result effects
    loading("Result")
    sleep(0.5)
    #announce winner
    if user_guess>total_roll:
      print("It looks like the computer won this round! You guessed a number bigger than the total roll.\
 \nDon't give up. Try again!\n")
    if user_guess==total_roll:
      print("Congrats! You guessed the right number.\
 You are the winner!\n")
    else:
      print("It looks like the computer won this round! You guessed a number smaller than the total roll.\
 \nDon't give up. Try again!\n")

def main():
  #Welcome message
  print("Welcome to the Number Guess game!\n")
  sleep(1)
  #game description
  print("In this game, we will roll a pair of dice and ask you to guess a number.\
 Based on your guess, the program should determine a winner.\
 If you guess the exact total value of the dice roll, you win!\
 Otherwise, the computer wins.\n")
  sleep(1.5)
  play_on = True
  while(play_on):
    #prompt user for number of sides on each die
    number_of_sides = raw_input("Let's start by specifying the number of sides on each die.\
 But remember, the higher the number of sides, the harder it gets!\
 Enter the number of sides each dice has: ")
    while (not number_of_sides.isdigit()):
      print("Invalid entry. The input has to be an integer.")
      number_of_sides = raw_input("Please enter the number of sides of the dice: ")
    #roll the dice
    roll_dice(int(number_of_sides))
    sleep(1.5)
    #prompt user to continue or exit the game
    play_message = raw_input('Would you like to play another round? Press \'Y\' to play on. Press \'N\' to exit: ')
    #prompt user to input a response if it's not valid
    while (play_message.lower()!='n' and play_message.lower()!='y'):
      play_message = raw_input('\nWe could not recognize your answer. Please pess \'Y\' to play on. Press \'N\' to exit: ')
    #exit the game in case user presses 'Y'
    if (play_message.lower() == 'n'):
      play_on = False
    #if user inputs 'Y'
    else:
      print('Let\'s try another roll!')
  print('\nThank you for playing the Number Guessing game.\nSee you next time!')

main()


from datetime import datetime, timezone
import json
import logging
from math import ceil
from slugify import slugify

from flask import Response, request
from flask_camp import current_api, allow
from sqlalchemy.sql.functions import func
from werkzeug.exceptions import BadRequest

from c2corg_api.search import DocumentSearch, DocumentLocaleSearch
from c2corg_api.models import USERPROFILE_TYPE, ROUTE_TYPE, models as document_types

log = logging.getLogger(__name__)

# Search engines accept not more than 50000 urls per sitemap,
# and the sitemap files may not exceed 10 MB. With 50000 urls the sitemaps
# are not bigger than 9MB, but to be safe we are using 45000 urls per sitemap.
# see http://www.sitemaps.org/protocol.html
PAGES_PER_SITEMAP = 45000

class _Sitemaps:
    @staticmethod
    def get_locales_per_type():
        return (
            current_api.database.session.query(DocumentSearch.document_type, func.count().label("count"))
            .join(DocumentLocaleSearch, DocumentSearch.id == DocumentLocaleSearch.id)
            .filter(DocumentSearch.document_type != USERPROFILE_TYPE)
            .group_by(DocumentSearch.document_type)
            .all()
        )

class _Sitemap:
    @staticmethod
    def get_locales(document_type, page):
        fields = [
            DocumentSearch.id,
            DocumentLocaleSearch.lang,
            DocumentLocaleSearch.title_prefix,
            DocumentLocaleSearch.title,
            DocumentSearch.timestamp,
        ]

        query = (
            current_api.database.session.query(*fields)
            .select_from(DocumentLocaleSearch)
            .join(DocumentSearch, DocumentSearch.id == DocumentLocaleSearch.id)
            .filter(DocumentSearch.document_type == document_type)
            .order_by(DocumentLocaleSearch.id, DocumentLocaleSearch.lang)
            .limit(PAGES_PER_SITEMAP)
            .offset(PAGES_PER_SITEMAP * page)
        )

        return query.all()

class SitemapsRest(_Sitemaps):
    rule = "/sitemaps"

    @allow("anonymous")
    def get(self):

        """Returns the information needed to generate a sitemap index file.
        See: http://www.sitemaps.org/protocol.html

        The response consists of a list of URLs to request the information
        needed to generate the sitemap linked from the sitemap index.

        E.g.

            {
                "sitemaps": [
                    "/sitemaps/w/0",
                    "/sitemaps/a/0",
                    "/sitemaps/i/0",
                    "/sitemaps/i/1",
                    "/sitemaps/i/2",
                    "/sitemaps/i/3",
                    "/sitemaps/i/4",
                    "/sitemaps/i/5",
                    ...
                ]
            }
        """

        document_locales_per_type = self.get_locales_per_type()

        sitemaps = []
        for doc_type, doc_count in document_locales_per_type:
            num_sitemaps = ceil(doc_count / PAGES_PER_SITEMAP)
            sitemaps += [
                {"url": f"/sitemaps/{doc_type}/{i}", "doc_type": doc_type, "i": i} for i in range(0, num_sitemaps)
            ]

        result = Response(response=json.dumps({"sitemaps": sitemaps}), content_type="application/json")
        result.add_etag()  # TODO : compute it only one time per day
        result.make_conditional(request)

        return result

class SitemapRest(_Sitemap):
    rule = "/sitemaps/<string:document_type>/<int:page>"

    @allow("anonymous")
    def get(self, document_type, page):
        """Returns the information needed to generate a sitemap for a given type and sitemap page number."""

        if document_type not in document_types:
            raise BadRequest("Invalid document type")

        document_locales = self.get_locales(document_type, page)

        # include `title_prefix` for routes
        is_route = document_type == ROUTE_TYPE
        data = {"pages": [self.format_page(is_route, *locale) for locale in document_locales]}

        result = Response(response=json.dumps(data), content_type="application/json")
        result.add_etag()  # TODO : compute it only one time per day
        result.make_conditional(request)

        return result

    @staticmethod
    def format_page(is_route, doc_id, lang, title, title_prefix, last_updated):
        page = {"document_id": doc_id, "lang": lang, "title": title, "lastmod": last_updated.isoformat()}

        if is_route:
            page["title_prefix"] = title_prefix

        return page

class SitemapsXml(_Sitemaps):
    rule = "/sitemaps.xml"

    @allow("anonymous")
    def get(self):
        """Returns a sitemap index file.
        See: http://www.sitemaps.org/protocol.html

        The response consists of a list of URLs of sitemaps.

        <?xml version="1.0" encoding="UTF-8"?>
            <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
                <sitemap>
                    <loc>https://api.camptocamp.org/sitemaps.xml/w/0.xml</loc>
                    <lastmod>2019-02-11T18:01:49.193770+00:00</lastmod>
                </sitemap>
                <sitemap>
                    <loc>https://api.camptocamp.org/sitemaps.xml/a/0.xml</loc>
                    <lastmod>2019-02-11T18:01:49.193770+00:00</lastmod>
                </sitemap>
                <sitemap>
                    <loc>https://api.camptocamp.org/sitemaps.xml/i/0.xml</loc>
                    <lastmod>2019-02-11T18:01:49.193770+00:00</lastmod>
                </sitemap>
                <sitemap>
                    <loc>https://api.camptocamp.org/sitemaps.xml/i/1.xml</loc>
                    <lastmod>2019-02-11T18:01:49.193770+00:00</lastmod>
                </sitemap>
            </sitemap>
        """

        document_locales_per_type = self.get_locales_per_type()

        sitemaps = []

        now = datetime.utcnow().replace(tzinfo=timezone.utc)
        lastmod = now.isoformat()

        template = """<sitemap>
        <loc>https://api.camptocamp.org/sitemaps.xml/{doc_type}/{i}.xml</loc>
        <lastmod>{lastmod}</lastmod>
        </sitemap>"""

        for doc_type, count in document_locales_per_type:
            num_sitemaps = ceil(count / PAGES_PER_SITEMAP)
            sitemaps_for_type = [
                template.format(doc_type=doc_type, i=i, lastmod=lastmod) for i in range(0, num_sitemaps)
            ]
            sitemaps.extend(sitemaps_for_type)

        body = """<?xml version="1.0" encoding="UTF-8"?>
        <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
        {}
        </sitemapindex>""".format(
            "\n".join(sitemaps)
        )

        result = Response(response=body, content_type="text/xml")
        result.add_etag()  # TODO : compute it only one time per day
        result.make_conditional(request)

        return result

class SitemapXml(_Sitemap):
    rule = "/sitemaps.xml/<string:document_type>/<int:page>.xml"

    @allow("anonymous")
    def get(self, document_type, page):
        """Returns a sitemap file for a given type and sitemap page number."""

        if document_type not in document_types:
            raise BadRequest("Invalid document type")

        document_locales = self.get_locales(document_type, page)

        body = """<?xml version="1.0" encoding="UTF-8"?>
        <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
        {}
        </urlset>""".format(
            "\n".join([self.format_page(document_type, *locale) for locale in document_locales])
        )

        result = Response(response=body, content_type="text/xml")
        result.add_etag()  # TODO : compute it only one time per day
        result.make_conditional(request)

        return result

    @staticmethod
    def format_page(document_type, doc_id, lang, title_prefix, title, last_updated):

        page = {
            "document_id": doc_id,
            "lang": lang,
            "lastmod": last_updated.isoformat(),
            "document_type": document_type,
        }

        if title_prefix:
            page["title"] = slugify(f"{title_prefix} {title}")
        else:
            page["title"] = slugify(title)

        return """<url>
    <loc>https://www.camptocamp.org/{document_type}/{document_id}/{lang}/{title}</loc>
    <lastmod>{lastmod}</lastmod>
    <changefreq>weekly</changefreq>
    </url>""".format(
            **page
        )


import numpy as np
from sklearn import metrics
import matplotlib.pyplot as plt
from kmeans import *
from minibatchkmeans import *
from gmm import *
from Dense_AutoEncoder import *
from CNN_AutoEncoder_TSNE import *

# load the data
data1 = np.load(r'kmnist-train-imgs.npz')
data2 = np.load(r'kmnist-train-labels.npz')
train_imgs = data1['arr_0']
train_labels = data2['arr_0']

NMI = []
ARI = []
n_clusters=10

#### Clustering with unprocessed data ####
train_imgs1=train_imgs.reshape(60000,28*28)

# kmeans
pred1 = kmeans(n_clusters,train_imgs1)
NMI1 = metrics.normalized_mutual_info_score(pred1, train_labels)
ARI1 = metrics.adjusted_rand_score(pred1, train_labels)
NMI.append(NMI1)
ARI.append(ARI1)

# gmm
pred2 = gmm(train_imgs1,n_clusters,1)
NMI2 = metrics.normalized_mutual_info_score(pred2, train_labels)
ARI2 = metrics.adjusted_rand_score(pred2, train_labels)
NMI.append(NMI2)
ARI.append(ARI2)

# minibatchkmeans
pred3 = minibatchkmeans(n_clusters,train_imgs1)
NMI3 = metrics.normalized_mutual_info_score(pred3, train_labels)
ARI3 = metrics.adjusted_rand_score(pred3, train_labels)
NMI.append(NMI3)
ARI.append(ARI3)

#### Clustering with data after dimensionality reduction using Dense Autoencoder ####
train_imgs2 = dense_AE(train_imgs,2)

# kmeans
pred4 = kmeans(n_clusters,train_imgs2)
NMI4 = metrics.normalized_mutual_info_score(pred4, train_labels)
ARI4 = metrics.adjusted_rand_score(pred4, train_labels)
NMI.append(NMI4)
ARI.append(ARI4)

# gmm
pred5 = gmm(train_imgs2,n_clusters,30)
NMI5 = metrics.normalized_mutual_info_score(pred5, train_labels)
ARI5 = metrics.adjusted_rand_score(pred5, train_labels)
NMI.append(NMI5)
ARI.append(ARI5)

# minibatchkmeans
pred6 = minibatchkmeans(n_clusters,train_imgs2)
NMI6 = metrics.normalized_mutual_info_score(pred6, train_labels)
ARI6 = metrics.adjusted_rand_score(pred6, train_labels)
NMI.append(NMI6)
ARI.append(ARI6)

#### Clustering with data after dimensionality reduction using Convolutional Autoencoder and T-sne ####
train_imgs3 = cnn_AE_Tsne(train_imgs)

# kmeans
pred7 = kmeans(n_clusters,train_imgs3)
NMI7 = metrics.normalized_mutual_info_score(pred7, train_labels)
ARI7 = metrics.adjusted_rand_score(pred7, train_labels)
NMI.append(NMI7)
ARI.append(ARI7)

# gmm
pred8 = gmm(train_imgs3,n_clusters,2)
NMI8 = metrics.normalized_mutual_info_score(pred8, train_labels)
ARI8 = metrics.adjusted_rand_score(pred8, train_labels)
NMI.append(NMI8)
ARI.append(ARI8)

# minibatchkmeans
pred9 = minibatchkmeans(n_clusters,train_imgs3)
NMI9 = metrics.normalized_mutual_info_score(pred9, train_labels)
ARI9 = metrics.adjusted_rand_score(pred9, train_labels)
NMI.append(NMI9)
ARI.append(ARI9)

#### Results Visualization ####

NMI_1=[round(x1,3) for x1 in NMI]
ARI_1=[round(x2,3) for x2 in ARI]

size = 9
x = np.arange(size)
total_width, n = 0.8, 3
width = total_width / n
x = x - (total_width - width) / 2

plt.figure(dpi=300,figsize=(13,6))
p1=plt.bar(x, NMI_1, width=width, label="NMI")
plt.bar_label(p1, label_type='edge',fontsize=8)
p2=plt.bar(x + width, ARI_1,  width=width, label="ARI")
plt.bar_label(p2, label_type='edge',fontsize=8)
x_labels = ['kmeans', 'GMM', 'Mkmeans', 'pre1_kmeans', 'pre1_GMM','pre1_Mkmeans', 'pre2_kmeans', 'pre2_GMM','pre2_Mkmeans']
plt.xticks(x, x_labels)
plt.title('NMI and ARI in different algorithms')
plt.legend()
plt.show()


from chinese_reconstructions.baxter_sagart.reconstructions import reconstructions
from chinese_reconstructions.cjk_punctuations import puncutation_dict

def get_reconstruction(char):
    if char in puncutation_dict:
        converted = puncutation_dict[char]
        return converted, converted, converted, converted
    elif char in reconstructions:
        tuple_list = reconstructions[char]
        first_entry = tuple_list[-1]
        pinyin, mc, oc_bax, gloss = first_entry
        oc_bax = oc_bax.split(" (")[0].strip()
        return pinyin, mc, oc_bax, gloss
    else:
        return "n/a", "n/a", "n/a", "n/a"


import xml.etree.ElementTree as ET
from capas_proyecto.acceso_a_datos.comprobar_long_dict import contar_canciones_xml

def crear_dicc_nombre_ruta(RUTA_XML):
    try:
        arbol = ET.parse(RUTA_XML)
    except FileNotFoundError:
        exit("El nombre del archivo XML no es correcto.")
    except ET.ParseError:
        exit("El archivo XML está mal formado.")
    else:
        raiz = arbol.getroot()
        diccionario = {}
        for canciones in raiz:
            for cancion in canciones:
                nombre_y_ruta = {}
                nombre_y_ruta[cancion.find('name').text] = cancion.find("path").text
                diccionario.update(nombre_y_ruta)
        num_canciones = contar_canciones_xml(raiz)
        assert len(diccionario) == num_canciones
        return diccionario, num_canciones


from apple import Apple
from board import Board
from snake import Snake
from algorthim import DFS
import pygame
from constants import GAME,SNAKE,APPLE,COLOR,SCALE
import time
import random
from a import *

#GAMELOOP
class Game:

    def __init__(self, display):
        self.display = display #instance
        self.score = 0

    def loop(self):
        #TIME
        clock = pygame.time.Clock()

        #INSTANCE
        board = Board(self.display)
        apple = Apple(self.display)
        snake = Snake(self.display)

        #ACTUAL GAMELOOP
        while True:
            path = astar(board.returnBoard(), snake.snake_pos(),apple.apple_Position())
            print(path)
            for i in range(1,len(path)):

                #if next move is not orthogonal
                if snake.changeDirectionTo(snake.CoordinateToDirection(path[i])):
                    path = astar(board.returnBoard(), snake.snake_pos(),apple.apple_Position())

                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        print("exit pressed!")
                        return 0

                # DRAW BACKGROUND
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_UP:
                        snake.changeDirectionTo('UP')
                    elif event.key == pygame.K_DOWN:
                        snake.changeDirectionTo('DOWN')
                    elif event.key == pygame.K_LEFT:
                        snake.changeDirectionTo('LEFT')
                    elif event.key == pygame.K_RIGHT:
                        snake.changeDirectionTo('RIGHT')

                # MOVE SNAKE and record position of SNAKE
                snake.move()

                # Collision Detection
                if snake.collision():
                    return 0

                #eating
                if snake.ate(apple.apple_Position()):
                    self.score += 1
                    pygame.display.set_caption(GAME['CAPTION']+ str(self.score))
                    apple.randomize()

                #DRAW
                board.drawBoard(self.display,snake.snake_body(),apple.apple_Position())
                apple.draw()
                snake.draw_body()

                #DRAW UPDATE
                pygame.display.update()
                clock.tick(GAME['FPS'])

def main():
    display = pygame.display.set_mode((GAME['WIDTH'],GAME['HEIGHT']))
    pygame.display.set_caption(GAME['CAPTION'])

    game = Game(display)
    value = game.loop()

    #LINUX EXIT COMMANDS
    if value != 0:
        print("Game ended wrong: ", value)
        exit(1)

if __name__ == '__main__':
	main()


def two_sum_ii(nums, target):
    # since the array is sorted, our task is easier
    # 2 pointer approach

    left = 0
    right = len(nums)-1

    while left <= right:
        if nums[left] + nums[right] < target:
            left += 1
        elif nums[left] + nums[right] > target:
            right -= 1
        else:
            return [left+1, right+1]    # +1 bec look at example... weird

# Space: O(1)
# Time: O(N)


#!/usr/bin/env python

"""
Using the spectrum graph to infer peptides.
  Given: a list L (of length at most 100) containing positive real numbers.
  Return: the longest protein string that matches the spectrum graph of L (if
          multiple solutions exist, you may output any one of them). Consult
          the monoisotopic masses table.

Sample dataset:
3524.8542
3623.5245
3710.9335
3841.974
3929.00603
3970.0326
4026.05879
4057.0646
4083.08025
Sample output:
WMSPG

Usage: sgra <FILE>
"""

from prtm import monoisotopic_masses

epsilon = 0.001

def traverse(edges, next_node = 0, protein = "", proteins = []):
  """
  Traverse the edges list and produce all possible protein strings.
  """
  if len(edges[next_node]) == 0:
    proteins.append(protein)
  else:
    for edge in edges[next_node]:
      nn, sym = edge
      traverse(edges, nn, protein + sym, proteins)
  return proteins

def sgra(L):
  """
  Creates list of edges of graph of protein amino acids that can be created from
  the given spectrum L. Edges are then traversed and the longest protein string
  is returned.
  """
  node = 0
  edges = {}
  for i in range(len(L)):
    edges[i] = []
  for u, i in zip(L, list(range(len(L)))):
    for v, j in zip(L, list(range(len(L)))):
      if v > u:
        mass = v - u
        for aa, aa_mass in monoisotopic_masses.items():
          if abs(mass - aa_mass) <= epsilon:
            edges[i].append((j, aa))

  proteins = traverse(edges)
  # Return longest possible protein string
  return max(proteins, key = len)

if __name__ == "__main__":
  import sys
  if len(sys.argv) < 2:
    print(__doc__)
    sys.exit(1)

  try:
    with open(sys.argv[1]) as f:
      L = list(float(i) for i in f.readlines())
  except ValueError:
    print("Invalid values for L in file", sys.argv[1])
    sys.exit(1)
  except IOError:
    print("Unable to open/read file", sys.argv[1])
    sys.exit(1)

  print(sgra(L))


from direct.gui.OnscreenImage import OnscreenImage
from pandac.PandaModules import TransparencyAttrib
from direct.gui.OnscreenText import OnscreenText
from direct.showbase.DirectObject import DirectObject
from pandac.PandaModules import TextNode

from gui.GUIOrder import GUIOrder
from event.InventoryEvent import AmmoChangeEvent, SelectedItemChangeEvent
import Globals

class HUDBottomRight(DirectObject):

    def __init__(self):
        self.node = base.a2dBottomRight.attachNewNode('hudBottomRight')#GUIOrder.ORDER[GUIOrder.HUD])
        self.node.setBin('fixed', GUIOrder.ORDER[GUIOrder.HUD])

        self.ammoIcon = OnscreenImage(image = 'Assets/Images/HUD/HUDBottomRight.png', scale = 512.0 / 1024, pos = (-0.5, 0, 0.5))
        self.ammoIcon.setTransparency(TransparencyAttrib.MAlpha)
        self.ammoIcon.reparentTo(self.node)

        self.ammoTextClip = OnscreenText(text = '30', pos = (-0.35, 0.09), scale = 0.12, fg = (1, 1, 1, 1), shadow = (0, 0, 0, 1), mayChange = True, align=TextNode.ARight, font = Globals.FONT_SAF)
        self.ammoTextClip.reparentTo(self.node)
        self.ammoTextClip.setBin('fixed', GUIOrder.ORDER[GUIOrder.HUD])

        self.ammoTextLeft = OnscreenText(text = '90', pos = (-0.23, 0.05), scale = 0.07, fg = (1, 1, 1, 1), shadow = (0, 0, 0, 1), mayChange = True, align=TextNode.ARight, font = Globals.FONT_SAF)
        self.ammoTextLeft.reparentTo(self.node)
        self.ammoTextLeft.setBin('fixed', GUIOrder.ORDER[GUIOrder.HUD])

        self.accept(AmmoChangeEvent.EventName, self.OnAmmoChangeEvent)
        self.accept(SelectedItemChangeEvent.EventName, self.OnSelectedItemChangeEvent)

    def OnAmmoChangeEvent(self, event):
        item = event.GetItem()
        if(item and item.GetCurrentClipAmmo() == ''):
            self.ChangeAmmoText('', '')
        else:
            self.ChangeAmmoText(str(item.GetCurrentClipAmmo()), str(item.GetTotalRemainingAmmo()))

    def ChangeAmmoText(self, clip, total):
        self.ammoTextClip.setText(clip)
        self.ammoTextLeft.setText(total)

    def OnSelectedItemChangeEvent(self, event):
        if(event.GetItemStack() and event.GetItemStack().GetItem()):
            self.OnAmmoChangeEvent(AmmoChangeEvent(None, event.GetItemStack().GetItem()))
        else:
            self.ChangeAmmoText('', '')

    def Destroy(self):
        self.ignoreAll()
        self.ammoIcon.removeNode()
        self.ammoTextClip.removeNode()
        self.ammoTextLeft.removeNode()
        self.node.removeNode()


# -*- coding: cp1252 -*-

import io
import os
import sys
import time

import misctools
import stringtools

class Apho:
    def __init__( self ):
        self.thous = [] # list of pair (sentence, author)
        self.aCountSaid = [] # for each sentence, number of said time
        self.aLastSaid = [] # time of last said

        self.embed = None # when using it

    def load( self ):
        """
        Charge les pensees: un fichier avec des pensées, puis sur la derniere ligne l'auteur. séparé par des lignes vides.
        eg:
Je ne pense pas à toute la misère, je pense à la beauté qui reste.
Anne Frank

Fais de ta vie un rêve et d’un rêve une réalité.
Antoine de Saint-Exupery
        """
        """
        TODO a l'occasion: prendre un gros roman puis chercher des phrases assez courte sans prénom et les définir comme des pensee avec nom de l'auteur, livre et année.
        cf D:\books avec des pdfs
        """
        f = io.open(misctools.getThisFilePath()+"datas/pensee.txt","r",encoding='cp1252')
        blob = [] # un bloc de ligne de texte séparé par une ligne vide
        bContinue = 1
        while bContinue:
            line = f.readline()
            if len(line)<1:
                bContinue = 0
            if bContinue and line[-1] == '\n': line = line[:-1]
            if len(line)<1:
                if len(blob)>1:
                    # end of blob
                    citation = " ".join(blob[:-1])
                    auth = blob[-1]
                    self.thous.append( (citation,auth) )
                    self.aCountSaid.append(0)
                    self.aLastSaid.append(0)
                blob = []
            else:
                blob.append(line)
        #~ print("DBG: load: blob: %s" % str(blob))
        #~ print(self.thous)
        print("INF: Apho.load: %d loaded apho(s))" % len(self.thous))

    def getThoughts( self, sentence ):
        """
        find a thoughts not said a lot, relative to sentence.
        return a pair, (thought,author) or None if none
        """
        bVerbose = 1
        #~ bVerbose = 0

        bMatchShort = 0
        bMatchShort = 1

        bUseWordMatching = 1
        #~ bUseWordMatching = 0 # use camembert

        if bUseWordMatching:
            if 0:
                sentence = sentence.replace('.', ' ').replace(',', ' ')
                words = sentence.split()
                words = stringtools.lowerList(words)
            else:
                import usual_words
                words = usual_words.filterSentences(sentence,bVerbose=0)
                words = stringtools.lowerList(words)

            # add also words without '
            i = 0
            while i < len(words):
                if "'" in words[i]:
                    words.extend(words[i].split("'"))
                i += 1
            if bVerbose: print("DBG: getThoughts: words: %s" % words)

            # find radical style
            i = 0
            while i < len(words):
                if len(words[i])<3:
                    del words[i]
                    continue
                # on le fera plus tard pour essayer de matcher sur le mot reel
                #~ if len(words[i])>5:
                    #~ words[i] = words[i][:-3] # travailler => travail
                i += 1

            # remove usual words
            if 0:
                import usual_words
                i = 0
                while i < len(words):
                    if usual_words.isUsualWord(words[i]):
                        del words[i]
                        continue
                    i += 1

            print("match word: %s" % words)
            match = []
            for t in self.thous:
                cit = t[0]
                cit = cit.lower()
                n = 0
                for w in words:
                    #~ print("compare with cit: %s" % cit)
                    if w in cit:
                        if bVerbose or 0: print( "match: '%s' in '%s'" % (w,cit) )
                        #~ n += 1
                        n += len(w) # count more point if word is long!
                    if bMatchShort and len(w)>5:
                        # lemmatisation du pauvre
                        if "er" == w[-2:]:
                            ws = w[:-3]
                        else:
                            ws = w[:-2]
                        if ws in cit:
                            # pb: ecoute => eco can match with recommencer
                            if bVerbose: print( "match short: '%s' in '%s'" % (ws,cit) )
                            n += len(ws)

                match.append(n*30/len(cit))
        else:
            # camembert
            import numpy as np
            sys.path.append("../camembert")
            import sentence_embedding

            # generating for all apho
            if self.embed == None:
                timeBegin = time.time()
                if 0:
                    # 6s
                    listEmb = []
                    for t in self.thous:
                        cit = t[0]
                        v = sentence_embedding.camEmbedList([cit])[0]
                        listEmb.append(v)
                else:
                    # once precomputed: 0.12s
                    list_s = [x[0] for x in self.thous]
                    listEmb = sentence_embedding.precomputeList(list_s,"apho_embed.txt")
                    # le 7ieme chiffre après la virgule est différent quand on sauve dans un fichier
                print("listEmb takes %.2fs" % (time.time()-timeBegin))
                #~ print(listEmb[0])
                #~ print(listEmb[1])
                #~ print(listEmb[2])
                self.embed = listEmb

            e = sentence_embedding.camEmbedList(sentence)
            match = []
            for v in self.embed:
                simi = np.dot(e,v)/0.4 # 0.4 is a good threshold for simi
                 #reglage pour ne pas prendre ceux qui sont trop loin (on a ensuite un filtre >=1)
                #~ simi *= 2.35 # un peu trop sympa, 19 hits: laisse passer 'c'est bien fait peur. tu es un bon petit gars. eh mon petit gnocchi est-ce qu'il a." => Gaïa, c'est l'heure d'aller te coucher.
                simi *= 2.2 # plus limité: 14 hits
                match.append(simi)

        # at this point we have a list of match for each thou (the greater the better)

        print("match: %s" % match)
        #~ [x for _, x in sorted(zip(Y, X))]
        # both are working, but second seems faster, todolater: measures
        #~ index_order = [x for _, x in sorted(zip(match, range(len(match))),reverse=True)]
        index_order = sorted(range(len(match)), key=lambda k: match[k],reverse=True)
        #~ print("index_order: %s" % index_order)
        # etais ce vraiment la peine de les trier, alors qu'on va les parcourir ensuite ?
        less_said_idx = index_order[0]
        for idx in index_order[1:]:
            if match[idx]<1:
                break
            if time.time()-self.aLastSaid[idx]<5*60:
                continue
            if self.aCountSaid[less_said_idx] > self.aCountSaid[idx]:
                less_said_idx = idx
        print("less_said_idx: %d" % less_said_idx )

        if match[less_said_idx] < 1:
            return None

        if self.aCountSaid[less_said_idx] > 0 and 0:
            # decide to say already said or not ?
            return None

        # first sentence of the list can be selected by default
        if time.time()-self.aLastSaid[less_said_idx]<5*60:
            return None

        self.aCountSaid[less_said_idx] += 1
        self.aLastSaid[less_said_idx] = time.time()
        print("match: %.2f" % match[less_said_idx] )
        return self.thous[less_said_idx]

# class Apho - end

apho = Apho()
apho.load()

global_tts = None
def say(txt):
    global global_tts
    if global_tts == None:
        import pyttsx3
        global_tts = pyttsx3.init()
    if 1:
        txt = txt.replace("Gaia", "Gaïa")
    print("INF: say: '%s'" % txt)
    global_tts.say(txt)
    global_tts.runAndWait()

def sayGoogle(txt):
    sys.path.append("../scripts")
    import tts_say
    tts_say.say(txt)

def wordsCallback(words,confidence):
    if confidence<0.6:
        return
    if len(words)<4:
        return
    print("INF: heard: '%s'" % words)
    #~ say(phrase)
    ret = apho.getThoughts(words)
    if ret != None:
        saymethod = say
        if 1:
            saymethod = sayGoogle
        saymethod(ret[0])
        saymethod(ret[1])

def test_loop_asr():

    if 0:
        from pocketsphinx import LiveSpeech, get_model_path
        import os
        model_path = get_model_path()
        print("model_path: %s" % model_path )
        # good model path:
        model_path = "C:\\Python39\\Lib\\site-packages\\speech_recognition\\pocketsphinx-data\\"
        strAnsiLang = "fr-FR"
        for phrase in LiveSpeech(
            hmm=(os.path.join(model_path, strAnsiLang)+"\\acoustic-model\\"),
            lm=os.path.join(model_path, strAnsiLang+'\\language-model.lm.bin'),
            dic=os.path.join(model_path, strAnsiLang+'\\pronounciation-dictionary.dict')
        ):
            phrase = str(phrase)
            wordsCallback( phrase, 0.5)

    else:
        # my own one
        import microphone
        microphone.loopProcess(wordsCallback)

"""
# probleme actuel, les mots banals hits trop:
+ mettre malus sur longueur de la phrase!

INF: heard: 'c'est cool'
less_said_idx: 3
INF: say: 'Le plus difficile, ce n'est pas de sortir de Polytechnique, c'est de sortir de l'ordinaire.'

INF: heard: 'je suis bien d'accord'
less_said_idx: 115
INF: say: 'Je ne comprends pas qu'on achète du vin sans l'avoir goûté au préalable. Il ne viendrait à personne l'idée d'acheter un pantalon sans l'essayer avant. Alors, Dieu me tire-bouchonne, ne refusez pas à votre bouche ce que vous accordez à vos fesses.'

INF: heard: 'un bon petit vin rouge'
less_said_idx: 8
INF: say: 'Le bonheur est une petite chose que l'on grignote, assis par terre, au soleil.'
"""

def strToPrint(s):
    if sys.version_info[0] >= 3:
        return s

    o = ""
    for c in s:
        #~ print( ord(c) )
        if ord(c) <= 127:
            o += c
    return o

global_testApho_nbr_hit = 0
def testApho(s):
    global global_testApho_nbr_hit
    ret = apho.getThoughts(s)
    print("\n%s" % strToPrint(s))
    print("=>")

    if ret != None:
        s = ret[0]
        #~ print(str(s)) # UnicodeEncodeError: 'ascii' codec can't encode character u'\xe0'
        print(strToPrint(s)) # cette ligne bloque en python 2.7,  LookupError: unknown encoding: cp65001 # corriger en faisant dans le shell: set PYTHONIOENCODING=UTF-8
        global_testApho_nbr_hit += 1
    print("")

def autoTest():
    testApho("j'aime pas travailler")
    testApho("j'aime pas travailler")
    testApho("j'aime pas travailler")
    testApho("j'aime pas travailler")
    print("")

    #~ testApho("j'ai la volonté de t'aider"))
    #~ testApho("j'ai la volonté de t'aider"))
    #~ testApho("j'ai la volonté de t'aider"))
    testApho("j'ai la volonté de t'aider")
    testApho("j'ai la volonté de t'aider")
    testApho("j'ai la volonté de t'aider")
    print("")

    testApho("Il me faudrait du courage")
    testApho("Il me faudrait du courage")
    testApho("J'aime le ChamPagne.")
    testApho("J'aime le ChamPagne.")
    testApho("J'aime le vin.")
    testApho("J'aime le vin.")
    testApho("d'attendre la pluie")
    testApho("d'attendre la pluie")
    testApho("attendre la pluie")
    print("")

    testApho("Dis moi une phrase")
    testApho("Ecoute moi")
    testApho("Dis moi un truc intelligent!")
    testApho("Dis moi un truc intelligent!")
    print("")

    testApho("Dis moi, tu connais des gens célèbres?")
    testApho("Dis moi, tu connais des gens célèbres?")
    testApho("travailler moins c'est cool ou pas ?")
    testApho("travailler moins c'est cool ou pas ?")
    testApho("Consommer moins c'est cool ou pas ?")

    testApho("c'est bien fait peur. tu es un bon petit gars. eh mon petit gnocchi est-ce qu'il a.")
    # => "Gourmandise : source inépuisable de bonheur. a cause de bonheur" bon match bonheur, c'est moche.
    # => maintenant donne, Quand vous êtes à Rome, faites comme les Romains. fait => faites
    # => Le seul fait d’exister est un véritable bonheur
    testApho("ambulance") # => Ben par exemple, c'est un mec qui va a une soirée genre bien habillé
    print("")

    print("global_testApho_nbr_hit: %s" % global_testApho_nbr_hit )
    assert(global_testApho_nbr_hit >= 20)

    if 0:
        # test sur python 2.7
        print(stringtools.accentToHtml("un élève"))
        for i,a in enumerate(apho.thous):
            print(i)
            #~ print(stringtools.accentToHtml(a[0]))
            s1 = stringtools.cp1252ToHtml(a[0])
            s2 = stringtools.cp1252ToHtml(a[1])
            print(s1)
            print(s2)
            print(stringtools.transformAccentToUtf8(a[0]))
            print(stringtools.transformAccentToUtf8(a[1]))
            #~ if i>80:
                #~ break

if __name__ == "__main__":
    #~ autoTest()
    test_loop_asr()


from aws_cdk import core

from aws_cdk import aws_ecs, aws_ec2

class LoadTestStack(core.Stack):

    def __init__(self, scope: core.Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        vpc = aws_ec2.Vpc(self, "CDK_loadtester", max_azs=2)

        cluster = aws_ecs.Cluster(self, 'Cluster', vpc=vpc)

        taskdef = aws_ecs.FargateTaskDefinition(self, 'PingerTask')
        taskdef.add_container('Pinger',
                              image=aws_ecs.ContainerImage.from_asset('./pinger'),
                              environment={
                                  'URL': 'sample-elb-886491630.us-east-1.elb.amazonaws.com'
                              })
        aws_ecs.FargateService(self, 'PingerService',
                               cluster=cluster,
                               task_definition=taskdef,
                               desired_count=10
                              )


import tvm
import tvm.relay as relay
import tvm.relay.testing as testing

from graphviz import Digraph
import os
from collage.utils import get_backend_from_backend_pattern_annotation

def _traverse_expr(node, node_dict):
    if node in node_dict:
        return
    if isinstance(node, tvm.ir.op.Op):
        return

    node_dict[node] = len(node_dict)

def get_node_color(node):
    backend_name = get_backend_from_backend_pattern_annotation(node.backend)

    # If this is default (no backend op assignment)
    color = "greenyellow"

    if backend_name == "tensorrt":
        color = "orange"
    elif backend_name[:3] == "tvm":
        color = "greenyellow"
    elif backend_name[:5] == "cudnn":
        color = "yellow"
    elif backend_name[:6] == "cublas":
        color = "grey60"

    return color

def visualize_backend_placement(expr, file_name, expr2node=None):

    dot = Digraph(format='pdf')
    dot.attr(rankdir='BT')

    node_dict = {}
    relay.analysis.post_order_visit(expr, lambda node: _traverse_expr(node, node_dict))

    for node, node_idx in node_dict.items():
        if not isinstance(node, relay.Let):
            node_idx_backend_str = f"[{node_idx}, {node.backend}]"
        else:
            node_idx_backend_str = f"[{node_idx}, NO_BACKEND]"

        # Debug for DP: print node_dfs_order
        if expr2node is not None and hash(node) in expr2node:
            node_dfs_order = expr2node[hash(node)]._topological_order
            node_idx_backend_str = f"[{node_dfs_order}, {node_idx}, {node.backend}]"

        node_color = get_node_color(node)

        if isinstance(node, relay.Function):
            dot.node(str(node_idx), f'Function ({node_idx})', shape='doubleoctagon')
            dot.edge(str(node_dict[node.body]), str(node_idx))

        elif isinstance(node, relay.expr.Var):
            if isinstance(node.type_annotation, tvm.ir.type.TupleType):
                type_info = node.type_annotation.fields
                tensor_info = f'Tensor[TupleType{tuple(type_info)}]'
            elif not hasattr(node.type_annotation, 'shape'):
                tensor_info = f'NoType'
            else:
                type_info = node.type_annotation.shape
                tensor_info = f'Tensor[{tuple(type_info)}, {node.type_annotation.dtype}]'

            dot.node(str(node_idx), \
                     f'{node.name_hint} {node_idx_backend_str}:\n{tensor_info}', \
                     shape='rectangle'
                     )
        elif isinstance(node, relay.expr.GlobalVar):
            dot.node(str(node_idx), \
                     f'{node.name_hint} {node_idx_backend_str}', \
                     shape='rectangle'
                     )

        elif isinstance(node, relay.Constant):
            dot.node(str(node_idx), \
                     f'Constant {node_idx_backend_str}:\nTensor[{tuple(node.data.shape)}, {node.data.dtype}]', \
                     shape='rectangle'
                     )

        elif isinstance(node, relay.expr.Call):
            args = [node_dict[arg] for arg in node.args]
            if isinstance(node.op, tvm.relay.Function):
                dot.node(str(node_idx), f'Call {node_idx_backend_str}(Function({node_dict[node.op.body]}))', shape='ellipse',
                         style='filled', color=node_color)
            else:
                if isinstance(node.op, relay.expr.GlobalVar):
                    dot.node(str(node_idx), f'Call{node_idx_backend_str}(GlobalVar={node.op.name_hint})', shape='ellipse', style='filled', color=node_color)
                elif isinstance(node.op, relay.Var):
                    dot.node(str(node_idx), f'Call {node_idx_backend_str}(Var={node.op.name_hint})', shape='ellipse', style='filled', color=node_color)
                else:
                    dot.node(str(node_idx), f'Call {node_idx_backend_str}(op={node.op.name})', shape='ellipse', style='filled', color=node_color)

            for arg in args:
                dot.edge(str(arg), str(node_idx))
        elif isinstance(node, relay.expr.TupleGetItem):
            dot.node(str(node_idx), f'TupleGetItem {node_idx_backend_str}(idx={node.index})', shape='ellipse', style='filled', color=node_color)
            dot.edge(str(node_dict[node.tuple_value]), str(node_idx))
        elif isinstance(node, relay.expr.Tuple):
            args = [node_dict[field] for field in node.fields]
            dot.node(str(node_idx), f'Tuple {node_idx_backend_str}(fileds=none)', shape='ellipse', style='filled', color=node_color)
            for arg in args:
                dot.edge(str(arg), str(node_idx))
        else:
            raise RuntimeError(f'Unknown node type. node_idx: {node_idx}, node: {type(node)}')

    dot.render(f'{file_name}.gv')
    os.remove(f'{file_name}.gv')


import numpy as np
from pathlib import Path
import numpy
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.layers import Dense, Activation, Bidirectional, Reshape, Conv2D, MaxPooling2D,TimeDistributed, LSTM

class SelfAttention(tf.keras.layers.Layer):
    def __init__(self, embed_size, heads):
        super(SelfAttention, self).__init__()
        self.embed_size = embed_size
        self.heads = heads
        self.head_dim = embed_size // heads

        assert (
            self.head_dim * heads == embed_size
        ), "Embedding size needs to be divisible by heads"

        self.wq = tf.keras.layers.Dense(self.head_dim)
        self.wk = tf.keras.layers.Dense(self.head_dim)
        self.wv = tf.keras.layers.Dense(self.head_dim)
        self.dense = tf.keras.layers.Dense(self.embed_size)

    def call(self, v, k, q, mask):
        # Get number of training examples
        batch_size = q.shape[0]

        seq_len_v, seq_len_k, seq_len_q = v.shape[1], k.shape[1], q.shape[1]

        # Split the embedding into self.heads different pieces
        v = tf.reshape(v,(batch_size,seq_len_v, self.heads, self.head_dim))
        k = tf.reshape(k,(batch_size,seq_len_k, self.heads, self.head_dim))
        q = tf.reshape(q,(batch_size,seq_len_q, self.heads, self.head_dim))

        values = self.wv(v)  # (batch_size, value_len, heads, head_dim)
        keys = self.wk(k)  # (batch_size, key_len, heads, head_dim)
        queries = self.wq(q)  # (batch_size, query_len, heads, heads_dim)

        # Einsum does matrix mult. for query*keys for each training example

        attention = tf.einsum("nqhd,nkhd->nhqk", queries, keys)
        # queries shape: (batch_size, seq_len_q, heads, heads_dim),
        # keys shape: (batch_size, seq_len_k, heads, heads_dim)
        # attention: (batch_size, heads, seq_len_q, seq_len_k)

         # scale matmul_qk
        dk = tf.cast(tf.shape(keys)[1], tf.float32)
        scaled_attention_logits = attention / tf.math.sqrt(dk)

        # Mask padded indices so their weights become 0

        if mask is not None:
            scaled_attention_logits += (mask * -1e9)

        # Normalize energy values similarly to seq2seq + attention
        # so that they sum to 1. Also divide by scaling factor for
        # better stability
        attention_weights = tf.nn.softmax(scaled_attention_logits, axis=-1)
        # attention shape: (batch_size, heads, seq_len_q, seq_len_k)

        out = tf.einsum("nhql,nlhd->nqhd", attention_weights, values)
        out = tf.reshape(out, (batch_size, seq_len_q, -1))
        # attention shape: (batch_size, heads, seq_len_q, key_len)
        # values shape: (batch_size, seq_len_v, heads, heads_dim)
        # out after matrix multiply: (batch_size, seq_len_q, heads, head_dim), then
        # we reshape and flatten the last two dimensions.

        out = self.dense(out)
        # Linear layer doesn't modify the shape, final shape will be
        # (N, query_len, embed_size)

        return out, attention_weights

class EncoderLayer(tf.keras.layers.Layer):
  def __init__(self, embed_size, heads, forward_expansion, rate=0.1):
    super(EncoderLayer, self).__init__()

    self.self_attens= SelfAttention(embed_size, heads)
    self.ffn = tf.keras.Sequential([
      tf.keras.layers.Dense(forward_expansion, activation='relu'),  # (batch_size, seq_len, forward_expansion)
      tf.keras.layers.Dense(embed_size)  # (batch_size, seq_len, d_model)
       ])

    self.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-6)
    self.layernorm2 = tf.keras.layers.LayerNormalization(epsilon=1e-6)

    self.dropout1 = tf.keras.layers.Dropout(rate)
    self.dropout2 = tf.keras.layers.Dropout(rate)

  def call(self, x, training, mask):

    attn_output, _ = self.self_attens(x, x, x, mask)  # (batch_size, input_seq_len, d_model)
    attn_output = self.dropout1(attn_output, training=training)
    out1 = self.layernorm1(x + attn_output)  # (batch_size, input_seq_len, d_model)

    ffn_output = self.ffn(out1)  # (batch_size, input_seq_len, d_model)
    ffn_output = self.dropout2(ffn_output, training=training)
    out2 = self.layernorm2(out1 + ffn_output)  # (batch_size, input_seq_len, d_model)

    return out2

class Encoder(tf.keras.layers.Layer):
    def __init__(self, num_layers, embed_size,  heads, forward_expansion, max_length, rate=0.1):
        super(Encoder, self).__init__()
        self.embed_size = embed_size
        self.num_layers = num_layers
        self.max_length = max_length
        self.Layerss =[EncoderLayer(embed_size, heads, forward_expansion, rate)
                       for _ in range(self.num_layers)]

        self.dropout = tf.keras.layers.Dropout(rate)

    def positional_encoding(self):

        pos = np.arange(self.max_length)[:, np.newaxis]
        i = np.arange(self.embed_size)[np.newaxis, :]
        angle_rates = 1 / np.power(10000, (2 * (i//2)) / np.float32(self.embed_size))

        angle_rads = pos * angle_rates

        # apply sin to even indices in the array; 2i
        angle_rads[:, 0::2] = np.sin(angle_rads[:, 0::2])

        # apply cos to odd indices in the array; 2i+1
        angle_rads[:, 1::2] = np.cos(angle_rads[:, 1::2])

        pos_encoding = angle_rads[np.newaxis, ...]

        return tf.cast(pos_encoding, dtype=tf.float32)

    def call(self, x, training, mask):

        seq_len = tf.shape(x)[1]

        x += self.positional_encoding()[:, :seq_len, :] # (batch_size, input_seq_len, d_model)
#        x *= tf.math.sqrt(tf.cast(self.d_model, tf.float32))

        x = self.dropout(x, training=training)
        for i in range(self.num_layers):
           x = self.Layerss[i](x, training, mask)

        return x  # (batch_size, input_seq_len, d_model)


try:
    import fraction
except ImportError as exc:
    print(exc)
def addFractions():
    '''
addFractions()=adds two fractions together
@param numerator, denmoinator, numerator2, denominator2=numerators and denominators
of the fractions
@param balor=object holding fractions
@param added=sum of the two fractions
prints sum of two fractions
    '''
    try:
        numerator=int(input("Enter the numerator for the first fraction: "))
        denominator=int(input("Enter the denominator of the first fraction: "))
        numerator2=int(input("Enter the numerator of the second fraction: "))
        denominator2=int(input("Enter the denominator for the second fraction: "))
        balor=fraction.Fraction(numerator, denominator, 0, numerator2, denominator2)
        balor.addFractions()
        added=balor.simplify()
        print(numerator,"/",denominator," + ",numerator2,"/",denominator2,
              "=", added, sep="")
    except:
        print("Unhandled exception.")
if __name__=="__main__":
    def test_addFractions():
        '''
tests the addFractions method
@param cont=determines if loop repeats
        '''
        try:
            cont=True
            while cont==True:
                addFractions()
                end=input("Continue? y or n ")
                if end.lower()=="n":
                    cont=False
        except:
            print("Unhandled exception.")
    test_addFractions()


import numpy as np
import matplotlib.pyplot as plt

class differential:
    """Solver of differential equations
    using RK4. diffEq should be a function with the
    differential equation that returns acceleration.
    All variables inside diffEq must be global"""
    def __init__(self, diffEq, plot_str, dt=0.01, T=20, x0=0, v0=0):
        if callable(diffEq):
            self.diffEq = diffEq
        else:
            raise TypeError('diffEq must be a callable function')
        self.dt = float(dt)
        self.T = T
        self.n = int(self.T/self.dt) + 1
        self.x = np.zeros(self.n)
        self.v = np.zeros(self.n)
        self.t = np.linspace(0,self.T,self.n)
        self.x[0] = x0
        self.v[0] = v0
        self.plot_str = plot_str

    def solve(self):
        """ method that uses RK4 and diffEq
        to solve the entire motion"""
        for i in range(self.n - 1):
            self.x[i + 1],self.v[i + 1] = self.RK4(self.x[i],self.v[i],self.t[i])
        return self.x, self.v, self.t

    def RK4(self,xStart,vStart,tStart):
        """ Runge-Kutta method of 4th order"""
        a1 = self.diffEq(xStart,vStart,tStart)
        v1 = vStart
        xHalf1 = xStart + v1 * self.dt/2.0
        vHalf1 = vStart + a1 * self.dt/2.0
        a2 = self.diffEq(xHalf1,vHalf1,tStart+self.dt/2.0)
        v2 = vHalf1
        xHalf2 = xStart + v2 * self.dt/2.0
        vHalf2 = vStart + a2 * self.dt/2.0
        a3 = self.diffEq(xHalf2,vHalf2,tStart+self.dt/2.0)
        v3 = vHalf2
        xEnd = xStart + v3 * self.dt
        vEnd = vStart + a3 * self.dt
        a4 = self.diffEq(xEnd,vEnd,tStart + self.dt)
        v4 = vEnd
        aMiddle = 1.0/6.0 * (a1 + 2*a2 + 2*a3 + a4)
        vMiddle = 1.0/6.0 * (v1 + 2*v2 + 2*v3 + v4)
        xEnd = xStart + vMiddle * self.dt
        vEnd = vStart + aMiddle * self.dt
        return xEnd, vEnd

    def plot(self):
        """ plots phase space of motion,
        after solve() method is used"""
        plt.title(self.plot_str)
        plt.plot(self.x,self.v)
        plt.xlabel('position [m]')
        plt.ylabel('velocity [m/s]')
        plt.grid()
        plt.show()

if __name__ == '__main__':
    def diffEq(xNow,vNow,tNow):
        return - k*xNow/m
    oppgave1 = differential(diffEq,r'$m\ddot{x}(t) + kx(t) = 0$',x0=1.0)
    m = 0.500
    k = 1.0
    oppgave1.solve()
    oppgave1.plot()

"""
[Command: python -u /home/simen/github/university/4semester/fys2130/project.py]
[Finished in 2.405s]
"""


import sqlite3 as sql
import numpy as np
import pandas as pd
import pickle
import os
import joblib
import onnx
import onnxruntime as rt
import torch

filename = "./svm_iris.onnx"

PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__))
rf_model_loaded = onnx.load(os.path.join(PROJECT_ROOT, "static/rf_model_init.onnx"))
sess = rt.InferenceSession(os.path.join(PROJECT_ROOT, "static/rf_model_init.onnx"))
input_name = sess.get_inputs()[0].name
label_name = sess.get_outputs()[0].name

# scaler_loaded = onnx.load(os.path.join(PROJECT_ROOT, "static/scaler_init.onnx"))
# onnx.checker.check_model(scaler_loaded)

fixed_acidity = 7.5
volatile_acidity = 0.75
citric_acid = 3.00
residual_sugar = 3.9
chlorides = 0.176
free_sulfur_dioxide = 12.0
total_sulfur_dioxide = 35.0
density = 0.91
ph = 3.9
sulphates = 0.56
alcohol = 9.4

X = np.array(
    [
        fixed_acidity,
        volatile_acidity,
        citric_acid,
        residual_sugar,
        chlorides,
        free_sulfur_dioxide,
        total_sulfur_dioxide,
        density,
        ph,
        sulphates,
        alcohol,
    ]
)
pred_onx = sess.run(None, {input_name: X.astype(np.float32)})[0]
print(pred_onx)

X_scaled = scaler_loaded.transform(X)
quality = rf_model_loaded.predict(X_scaled)[0]

res = "хорошее" if quality == 1 else "плохое"
msg = f"Вино {res}"


# Objetivo: mostrar en pantalla los 20 primeros numeros enteros

# #Algoritmo:
# 1. Mostrar el num 1
# 2. Mostrar el num 2
#  . ...
# 3. Finalizar cuando los 20 numeros han sido mostrados

# #Traduccion
# print(1)
# print(2)
# ...
# print(20)

# Primera Variante: range(limSuperior) -> LimInferior: 0, Avance: 1 (por defecto)
# Segunda Variante: range (limInferior, limSuperior)-> Avance: 1
# Tercera Variante: range(limiteInferior, limSuperior, Avance)

# Tener en cuenta las variantes:
# Primera variante:
num = 1
for num in range(20):
    print(num+1, end='-')

# Segunda variante:
num = 1
for num in range(1, 21):
    print(num, end='/')

# Tercera variante:
num = 1
for num in range(1, 21, 2):
    print(num, end='-')

# Usando while
x = 1
while x <= 20:
    print(x)
    x += 1


from pprint import pprint

class Solution:
    def minDistance(self, word1: str, word2: str) -> int:
        x = len(word1) + 1
        y = len(word2) + 1
        memo = [[0]*y for i in range(x)]
        for i in range(x):
            for j in range(y):
                if i == 0:
                    memo[i][j] = j
                elif j == 0:
                    memo[i][j] = i
                elif word1[i-1] == word2[j-1]:
                    memo[i][j] = memo[i-1][j-1]
                else:
                    memo[i][j] = 1 + min(
                        memo[i - 1][j],  # deleting
                        memo[i - 1][j - 1],  # replacing
                        memo[i][j - 1]  # adding
                    )
        # pprint(memo)
        return memo[x-1][y-1]

    # def mD(self, word1: str, word2: str, i, j) -> int:
    #     # x = len(word1)
    #     # y = len(word2)
    #     # memo = [[] for i in range(y)]
    #     if i == 0:
    #         return j
    #     if j == 0:
    #         return i
    #     if word1[i] == word2[j]:
    #         return self.mD(word1, word2, i-1, j-1)
    #     else:
    #         return 1 + min(
    #                 self.mD(word1, word2, i-1, j), # deleting
    #                 self.mD(word1, word2, i-1, j-1),# replacing
    #                 self.mD(word1, word2, i, j-1) # adding
    #             )
    #
    # def minDistance(self, word1: str, word2: str) -> int:
    #     # x = len(word1)
    #     # y = len(word2)
    #     # memo = [[] for i in range(y)]
    #     word1 = '1' + word1
    #     word2 = '1' + word2
    #     return self.mD(word1, word2, len(word1)-1, len(word2)-1)

# obj = Solution()
# print(obj.minDistance("horse", "ros"))
# print(obj.minDistance("horse", "ros"))
# print(obj.minDistance("", "ros"))
# print(obj.minDistance("ros", ""))
# str1 = ''.join([chr(ord('a') + elem) for elem in [i for i in range(500)]])
# str2 = ''.join([chr(ord('a') + elem) for elem in [i for i in range(501, 1001)]])
# print(obj.minDistance(str1, str2))
# print(obj.minDistance("intention", "execution"))


import pandas as pd
from pathlib import Path
from configs import Config, configs
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.utils import to_categorical
from typing import Union, List
import pickle
import logging

class Dataset:
    def __init__(self, path_to_dataset: Union[Path, str],
                 output_dir: Union[Path, str],
                 val_size: float = 0.2,
                 config_name: str = 'default',
                 path_to_label_encoder: Union[Path, str] = None):
        self.path_to_dataset = Path(path_to_dataset)
        self.output_dir = Path(output_dir)
        self.val_size = val_size

        if not self.output_dir.exists():
            self.output_dir.mkdir(parents=True)

        self.dataframe = pd.read_csv(self.path_to_dataset)
        self.X_train = None
        self.y_train = None
        self.X_val = None
        self.y_val = None
        self.X = None
        self.X_seq_id = None
        self.y = None
        self.config = Config(**configs[config_name])

        self.label_encoder = (self._load_label_encoder(path_to_label_encoder=path_to_label_encoder)
                              if path_to_label_encoder is not None
                              else None)

    def apply_training_pipeline(self):
        self.clean()
        self.process()
        self.train_val_split(val_size=self.val_size)
        self.export_training()

    def apply_test_pipeline(self):
        self.process()
        self.export_test()

    def clean(self) -> pd.DataFrame():
        df_clean = self.dataframe.copy()
        cols_to_keep = ['protein_sequence', 'tm', 'seq_id']
        df_clean = df_clean[cols_to_keep]

        nb_elements_before = len(df_clean)
        logging.info(f'> Raw dataset length: {nb_elements_before}')
        df_clean.dropna(inplace=True)
        nb_elements_after = len(df_clean)
        logging.info(f'> {nb_elements_before - nb_elements_after} rows dropped due to null values')

        logging.info(f'> Upper bound for sequence length: {self.config.seq_len_upper_bound_drop}')
        nb_elements_before = len(df_clean)

        if self.config.seq_len_upper_bound_drop is not None:
            df_clean.loc[:, 'sequence_length'] = pd.Series([len(seq) for seq in df_clean.protein_sequence])
            df_clean.drop(df_clean[df_clean.sequence_length < self.config.seq_len_upper_bound_drop].index, inplace=True)
            df_clean.drop(columns='sequence_length', inplace=True)
            nb_elements_after = len(df_clean)
            logging.info(f'> {nb_elements_before - nb_elements_after} rows dropped due to seq_len_upper_bound')

        self.dataframe = df_clean
        logging.info('> Dataset cleaned')

    def process(self) -> None:
        df = self.dataframe.copy()
        max_seq_length_in_df = df.protein_sequence.str.len().max()

        if 'tm' in df.columns:
            self.y = df.tm.to_numpy()

        if self.label_encoder is None:
            # Label encode
            unique_amino_acids = []
            df.protein_sequence.apply(lambda sequence: Dataset.compute_unique_amino_acids(sequence, unique_amino_acids))

            self.label_encoder = LabelEncoder()
            self.label_encoder.fit(unique_amino_acids)

        encoded_sequences = df.protein_sequence.transform(lambda sequence: self.label_encode_sequences(sequence))

        # Padding
        sequence_length = self.config.max_seq_len if self.config.max_seq_len is not None else max_seq_length_in_df

        encoded_sequences = pad_sequences(encoded_sequences, maxlen=sequence_length,
                                          padding='post', truncating='post', value=-1)

        # One-hot encoding
        self.X = to_categorical(encoded_sequences)
        self.X_seq_id = df.seq_id.to_numpy()

        logging.info('> Dataset preprocessed')

    @staticmethod
    def compute_unique_amino_acids(seq: str, accumulator: List[str]) -> None:
        accumulator += [amino_acid for amino_acid in seq if amino_acid not in accumulator]

    def label_encode_sequences(self, seq: str) -> List[int]:
        return self.label_encoder.transform([amino_acid for amino_acid in seq])

    def train_val_split(self, val_size: float, random_state=42):
        self.X_train, self.X_val, self.y_train, self.y_val = train_test_split(
            self.X,
            self.y,
            test_size=val_size,
            random_state=random_state
        )

    def export_training(self):
        with open(self.output_dir / 'label_encoder.pkl', 'wb') as f:
            pickle.dump(self.label_encoder, f)

        with open(self.output_dir / 'X_train.pkl', 'wb') as f:
            pickle.dump(self.X_train, f)

        with open(self.output_dir / 'y_train.pkl', 'wb') as f:
            pickle.dump(self.y_train, f)

        with open(self.output_dir / 'X_val.pkl', 'wb') as f:
            pickle.dump(self.X_val, f)

        with open(self.output_dir / 'y_val.pkl', 'wb') as f:
            pickle.dump(self.y_val, f)

        logging.info(f'> Dataset exported to {self.output_dir}')

    def export_test(self):
        with open(self.output_dir / 'label_encoder.pkl', 'wb') as f:
            pickle.dump(self.label_encoder, f)

        with open(self.output_dir / 'X_test.pkl', 'wb') as f:
            pickle.dump(self.X, f)

        with open(self.output_dir / 'X_seq_id.pkl', 'wb') as f:
            pickle.dump(self.X_seq_id, f)

        logging.info(f'> Dataset exported to {self.output_dir}')

    def _load_label_encoder(self, path_to_label_encoder: Union[Path, str]):
        with open(path_to_label_encoder, 'rb') as f:
            return pickle.load(f)


"""SimPhoNy-wrapper for celery-workflows"""

import logging
from typing import TYPE_CHECKING

from osp.core.namespaces import emmo
from osp.core.session import SimWrapperSession

from .celery_workflow_engine import CeleryWorkflowEngine

if TYPE_CHECKING:
    from typing import UUID, Any, Dict, List, Optional

    from pydantic import BaseSettings

    from osp.core.cuds import Cuds

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

class CeleryWorkflowSession(SimWrapperSession):
    """SimPhoNy-wrapper session for Celery-Chains and Worklows"""

    def __init__(
        self,
        input_uuid: "UUID",
        engine: CeleryWorkflowEngine = None,
        logging_id: str = None,
    ) -> None:
        """Initalite the session."""
        if not engine:
            engine = CeleryWorkflowEngine(input_uuid, logging_id=logging_id)
        super().__init__(engine=engine)

    # OVERRIDE
    def __str__(self):
        return "CeleryWorkflowSession"

    # OVERRIDE
    def _run(self, root_cuds_object) -> str:
        """Run the wrapper session."""
        return self._engine.run()

    # OVERRIDE
    def _apply_added(self, root_obj, buffer) -> None:
        """Apply scans of added cuds in buffer."""
        for obj in buffer.values():
            if obj.is_a(emmo.Workflow):
                message = """Found %s. Will search for workflow steps
                    and related workers on the platform."""
                logger.info(message, obj)
                self._scan_for_neighbours(obj)
        if not self._engine.tasks:
            message = """Did not find any workflow steps with
            complementary workers. Will scan for single
            object of type %s."""
            logger.info(message, emmo.Calculation)
            self._scan_for_single_calc(buffer)
        else:
            message = """Scan for workflow steps complete.
            Identified the following chain of workers: %s"""
            logger.info(message, self._engine.tasks)

    def _scan_for_neighbours(self, obj: "Cuds", step: str = "first") -> None:
        """Scan the input cuds for neighbour-tasks"""
        neighbour = obj.get(rel=emmo[f"hasSpatial{step.title()}"])
        if not neighbour:
            message = f"""Did not find {step} task in the chain of calculations in {obj}.
            Workflow chain has ended here."""
            logger.info(message)
        else:
            neighbour = neighbour.pop()
            self._get_worker_mapping(neighbour)
            self._scan_for_neighbours(neighbour, step="next")

    def _scan_for_single_calc(self, buffer: "Dict[Any, Cuds]") -> None:
        """Find single calculations to be run in the buffer."""
        for obj in buffer.values():
            if obj.is_a(emmo.Calculation):
                self._get_worker_mapping(obj)
        if not self._engine.tasks:
            message = """Did not find any calculations with
            complementary workers."""
            raise TypeError(message)
        message = """Found additional workers %s in the buffer,
        but will ignored because not part of a workflow chain."""
        logger.info(message, self._engine.tasks)

    def _get_worker_mapping(self, calculation: "Cuds") -> None:
        mapping = self._scan_worker_mapping(calculation)
        if not mapping:
            message = f"""Task in the chain of calculations is not properly
            mapped to an existing worker {calculation}."""
            logger.info(message)
        else:
            self._engine.add_task((calculation, mapping))

    def _scan_worker_mapping(self, calculation: "Cuds") -> "Optional[str]":
        response = []
        for superclass, mapping in self.worker_mapping.items():
            if calculation.is_a(superclass):
                response.append(mapping)
        if len(response) > 1:
            raise ValueError(
                f"More than 1 {calculation.oclass} found in worker mapping!"
            )
        if response:
            response = response.pop()
        return response

    # OVERRIDE
    def _apply_deleted(self, root_obj, buffer) -> None:
        """Apply functions for updated-buffer."""

    def _apply_updated(self, root_obj, buffer) -> None:
        """Apply functions for deleted-buffer."""

    # OVERRIDE
    def _load_from_backend(self, uids, expired=None) -> "Cuds":
        """Load a cuds from backend."""
        for uid in uids:
            if uid in self._registry:
                yield self._registry.get(uid)
            else:
                yield None

    @property
    def settings(cls) -> "BaseSettings":
        """Return the settings from the engine."""
        return cls._engine.settings

    @property
    def result(cls) -> "Dict[str, Any]":
        """Return the final result of the workflow"""
        return cls._engine.result

    @property
    def worker_mapping(cls) -> "Dict[str, Any]":
        """Return the mappings of the ontology class and worker name"""
        return cls._engine.worker_mapping

    @property
    def workers(cls) -> "List[str]":
        """Return the list of workers to pass the knowledge graph in a chain."""
        return cls._engine.workers


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

from rdflib.serializer import Serializer
import configparser
import corpus
import csv
import glob
import json
import rdflib
import sys

CONFIG = configparser.ConfigParser()
CONFIG.read("rc.cfg")

PREAMBLE = """
@base <https://github.com/Coleridge-Initiative/adrf-onto/wiki/Vocabulary> .

@prefix cito:	<http://purl.org/spar/cito/> .
@prefix dct:	<http://purl.org/dc/terms/> .
@prefix foaf:	<http://xmlns.com/foaf/0.1/> .
@prefix rdf:	<http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix xsd:	<http://www.w3.org/2001/XMLSchema#> .
"""

TEMPLATE_DATASET = """
:{}
  rdf:type :Dataset ;
  foaf:page "{}"^^xsd:anyURI ;
  dct:publisher "{}" ;
  dct:title "{}" ;
"""

TEMPLATE_PUBLICATION = """
:{}
  rdf:type :ResearchPublication ;
  foaf:page "{}"^^xsd:anyURI ;
  dct:publisher "{}" ;
  dct:title "{}" ;
  dct:identifier "{}" ;
  :openAccess "{}"^^xsd:anyURI ;
"""

if __name__ == "__main__":
    out_buf = [ PREAMBLE.lstrip() ]

    ## load the datasets
    dataset_path = CONFIG["DEFAULT"]["dataset_path"]

    known_datasets = {}

    with open(dataset_path, "r") as f:
        for elem in json.load(f):
            dat_id = elem["id"]
            id_list = [elem["provider"], elem["title"]]
            known_datasets[dat_id] = corpus.get_hash(id_list, prefix="dataset-")

            if "url" in elem:
                url = elem["url"]
            else:
                url = "http://example.com"

            out_buf.append(
                TEMPLATE_DATASET.format(
                    known_datasets[dat_id],
                    url,
                    elem["provider"],
                    elem["title"]
                    ).strip()
                )

            if "alt_title" in elem:
                for alt_title in elem["alt_title"]:
                    out_buf.append("  dct:alternative \"{}\" ;".format(alt_title))

            out_buf.append(".\n")

    ## load the publications
    for filename in glob.glob("corpus/pub/*.json"):
        with open(filename) as f:
            for elem in json.load(f):
                link_map = elem["datasets"]

                if len(link_map) > 0:
                    id_list = [elem["publisher"], elem["title"]]
                    pub_id = corpus.get_hash(id_list, prefix="publication-")

                    out_buf.append(
                        TEMPLATE_PUBLICATION.format(
                            pub_id,
                            elem["url"],
                            elem["publisher"],
                            elem["title"],
                            elem["doi"],
                            elem["pdf"]
                            ).strip()
                        )

                    dat_list = [ ":{}".format(known_datasets[dat_id]) for dat_id in link_map ]
                    out_buf.append("  cito:citesAsDataSource {} ;".format(", ".join(dat_list)))
                    out_buf.append(".\n")

    ## write the TTL output
    filename = "tmp.ttl"

    with open(filename, "w") as f:
        for text in out_buf:
            f.write(text)
            f.write("\n")

    ## load the TTL output as a graph
    graph = rdflib.Graph()
    graph.parse(filename, format="n3")

    ## transform graph into JSON-LD
    with open("corpus/vocab.json", "r") as f:
        context = json.load(f)

    with open("tmp.jsonld", "wb") as f:
        f.write(graph.serialize(format="json-ld", context=context, indent=2))

    ## read back
    graph = rdflib.Graph()
    graph.parse("tmp.jsonld", format="json-ld")


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

class Solution:
    def hasPathSum(self, root, targetSum):
        # exception
        if not root:
            return False
        # dfs (stack)
        stack = collections.deque([(root, root.val)])
        while stack:
            root, count = stack.pop()
            if root.left == None and root.right == None and count == targetSum:
                return True
            if root.left != None:
                stack.appendleft((root.left, count + root.left.val))
            if root.right != None:
                stack.appendleft((root.right, count + root.right.val))
        else:
            return False