"""Handles download and preprocessing of competition data."""

import logging
import sqlite3
from zipfile import ZipFile
from tqdm import tqdm

import pandas as pd
from kaggle import api

class Preprocessor:
    """Handles download and preprocessing of competition data."""

    def __init__(self, data_path: str):
        """Initialize Preprocessor instance.

        Arguments:
            data_path {str} -- Target path data storage.
        """
        LOG_FORMAT = "%(levelname)s %(asctime)s - %(message)s"
        logging.basicConfig(
            filename='preprocessing_log.log',
            level=20,
            format=LOG_FORMAT,
            filemode='w'
        )

        logging.info('Initializing...')

        self.data_path = data_path
        self.zipfile = None
        self.file_generator = None

        self.connection = sqlite3.connect(data_path + '/m5.db')

        self.api_download = api.competition_download_cli

    def execute(self):
        """Execute Preprocessing pipeline."""
        self._download_zip()
        self._open_zip()
        self._stream_to_db()

        self.connection.close()

    def _download_zip(self):
        logging.info('Starting download...')
        self.api_download(
            competition='m5-forecasting-accuracy', path=self.data_path
        )
        logging.info('Data obtained!')

    def _open_zip(self):
        logging.info('Accessing...')
        self.zipfile = ZipFile(self.data_path + '/m5-forecasting-accuracy.zip')
        logging.info('Successfully accessed!')

    def _stream_to_db(self):
        filenames = (
            'calendar.csv',
            'sell_prices.csv',
            'sales_train_validation.csv'
        )

        file_generator = (
            (name, pd.read_csv(self.zipfile.open(name), chunksize=10000))
            for name in filenames
        )

        logging.info('Starting chunkwise upload...')
        upload = map(
            lambda pair:
            self._upload_file(pair[0], pair[1]), file_generator
        )

        _ = tuple(upload)

    def _upload_file(self, name, chunk_generator):
        sql_config = {
            'if_exists': 'append',
            'index': False,
            'con': self.connection
        }

        name = name.split('.')[0]
        uploader = map(
            lambda chunk:
            chunk.to_sql(name, **sql_config)
            if name != 'sales_train_validation.csv'
            else self._sales_to_long(chunk).to_sql(name, **sql_config),
                tqdm(chunk_generator)
        )
        logging.info(f'Starting upload for {name}...')
        _ = tuple(uploader)
        logging.info(f'Succesfully uploaded {name}!')

    @staticmethod
    def _sales_to_long(self, sub_table):
        result = sub_table.melt(
            id_vars=['id', 'item_id', 'dept_id', 'cat_id_store', 'state_id'],
            var_name='d',
            value_name='sales'
        )

        return result


from tkinter import *
from Slutprojekt.Game_of_40.config import *
import random
import time

def start_game_of_40():
    # Slår tärningen
    def roll():
        nummber = random.randint(1, 6)
        active_dice.append(nummber)
        update_screen()

        # Om tärnningen bliv 6 så byt aktiv spelare
        if nummber == 6:
            switch_players()

    # Byter spelare
    def switch_players():
        global active_player

        if active_player == "P1":
            active_player = "P2"
        else:
            active_player = "P1"

        # Tömmer aktiva törnings listan
        active_dice.clear()

    def late_dice():
        # Kollar den senaste tärnig slaget
        try:
            return active_dice[-1]
        except:
            return ""

    # skapar en text
    def lbl(txt, r, c, win, big_txt=True, size=20, c_span=1):
        """
        :param txt: Texten som ska visas
        :param r: Vilken row texten ska vara
        :param c: Vilken kolumn den ska vara
        :param win: vilket fönster texten ska vara i
        :param big_txt: Om texten ska vara stor
        :param size: Vilken storlek den ska vara
        :param c_span: Hur många kolumner texten ska ta up
        :return:
        """
        lbl = Label(win, text=txt)
        if big_txt:
            lbl.config(font=("Courier", size))
        lbl.grid(row=r, column=c, columnspan=c_span)

    # Skapar Knappar
    def btn(txt, r, c, win, x=0, y=0, com=0):
        """
        :param txt: Vilken text som ska vara på knappen
        :param r: Vilken row som knappen ska vara
        :param c: Vilken kolumn som knappen ska vara
        :param win: vilket fönster texten ska vara i
        :param x: Hur bred knappen ska vara
        :param y: Hur hög knappen ska vara
        :param com: Vilken funktion som ska användas när knppen klickas på
        """
        btn = Button(win, text=txt, command=com)
        btn.grid(row=r, column=c, ipadx=x, ipady=y)

    # sparar sina poäng och byter ativ spelare
    def save():
        global active_dice, p1_score, p2_score
        if len(active_dice) != 0:
            if active_player == "P1":
                p1_score += sum(active_dice)

            else:
                p2_score += sum(active_dice)
            active_dice = []

            switch_players()

    # Byter bilden till den senaste tärngslags värde som du fick
    def change_img():
        photos.config(file=f"D:\Python\Slutprojekt\Game_of_40\Assets\Dice_{str(late_dice())}.png")

    # updaterar fönstret
    def update_screen():
        global img
        img = f"D:\Python\Slutprojekt\Game_of_40\Assets\Dice_{str(late_dice())}.png"
        photos.config(file=img)
        score_round.config(text=f"Score this round: {str(active_dice)[1:-1]}")
        total_round.config(text=f"Total score on this round: {sum(active_dice):02d}")
        p1_text.config(text=f"{p1_score:02d}")
        total_for_player.config(text=f"Total for player 1: {p1_score:02d}")
        player_turn.config(text=f"player {active_player}s turn!")
        p2_text.config(text=f"{p2_score:02d}")

        # Om någon spelare har över 40 poäng sä visas winnar skärmen
        if int(p2_score) >= 40 or int(p1_score) >= 40:
            winning_screen()

    # Gör funtionen och sedan updaterar fönstret
    def function(funk):
        funk()
        update_screen()

    # Startar om spelet
    def re_open():
        global p1_score, p2_score, active_dice, active_player
        screen.destroy()
        p1_score = 0
        p2_score = 0
        active_dice = []
        active_player = "P1"
        game_of_40()

    # Stänger av spelet
    def close_game():
        screen.destroy()

    # Winnar fönstert
    def winning_screen():
        global screen
        game.destroy()

        # Skapar fönstet
        screen = Tk()
        screen.title("Game of 40")
        screen.geometry("440x100")
        screen.iconbitmap("D:\Python\Slutprojekt\Game_of_40\Assets\Game_of_40.ico")

        # Skriver text
        if int(p1_score) >= 40:
            lbl(f"Player 1 Won with {p1_score} points", 0, 0, screen, True, 20, 2)
        else:
            lbl(f"Player 2 won with {p2_score} points", 0, 0, screen, True, 20, 2)

        # Knappar
        btn("Exit", 1, 0, screen, 20, 10, close_game)
        btn("Play Again", 1, 1, screen, 20, 10, re_open)

        screen.mainloop()

    def game_of_40():
        global score_round, total_round, photos, p1_text, total_for_player, player_turn, p2_text, game
        # Skapar fönster
        game = Tk()
        game.title("Game of 40")
        game.geometry("580x550")
        game.iconbitmap("D:\Python\Slutprojekt\Game_of_40\Assets\Game_of_40.ico")

        # Text
        lbl("Game of 40", 0, 1, game)
        lbl("P1 Score:", 0, 0, game)
        lbl("P2 Score:", 0, 2, game)

        # Tärnings bilden
        img = f"D:\Python\Slutprojekt\Game_of_40\Assets\Dice_{str(late_dice())}.png"
        photos = PhotoImage(master=game, file=f"D:\Python\Slutprojekt\Game_of_40\Assets\Dice_{str(late_dice())}.png")
        dice_photos = Label(game, image=photos)
        dice_photos.grid(row=1, column=1)

        # Text
        player_turn = Label(game, text=f"player {active_player}s turn!")
        player_turn.config(font=("Courier", 15))
        player_turn.grid(row=2, column=0, columnspan=3)

        # slå tärning knapp
        btn("Roll", 3, 1, game, 30, 5, lambda: function(roll))

        # Poäng text
        score_round = Label(game, text="Score this round:")
        score_round.config(font=("Courier", 15))
        score_round.grid(row=4, column=0, columnspan=3)

        # Totala poäng text
        total_round = Label(game, text="Total score on this round: 00")
        total_round.config(font=("Courier", 15))
        total_round.grid(row=5, column=0, columnspan=3)

        # Text
        total_for_player = Label(game, text=f"Total for player 1: {p1_score:02d}")
        total_for_player.config(font=("Courier", 15))
        total_for_player.grid(row=6, column=0, columnspan=3)

        # Spara knapp
        btn("Save", 7, 1, game, 30, 5, lambda: function(save))

        # Spelar 1 poäng text
        p1_text = Label(game, text="00")
        p1_text.config(font=("Courier", 40))
        p1_text.grid(row=1, column=0)

        # Spelar 2 poäng text
        p2_text = Label(game, text="00")
        p2_text.config(font=("Courier", 40))
        p2_text.grid(row=1, column=2)

        game.mainloop()

    game_of_40()

if __name__ == "__main__":
    start_game_of_40()


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

class Solution:
    """
    @param root: the root of binary tree
    @return: the length of the longest consecutive sequence path
    """

    def longestConsecutive(self, root):
        # write your code here
        if not root:
            return 0
        self.longest = 0
        self.dfs(root, 1)

        return self.longest

    def dfs(self, root, curtLen):
        if not root:
            return

        self.longest = max(self.longest, curtLen)

        if root.left:
            if root.left.val == root.val + 1:
                self.dfs(root.left, curtLen + 1)
            else:
                self.dfs(root.left, 1)

        if root.right:
            if root.right.val == root.val + 1:
                self.dfs(root.right, curtLen + 1)
            else:
                self.dfs(root.right, 1)


## Write a function named crazy_list that accepts a list as parameter and
## returns a boolean (either True or False) based on whether or not the
## list is the same forward and backwards. You may NOT use list.reverse()
## method.

def crazy_list(lista):
    i = 0
    for i in range (len(lista)//2):
        if lista[i] != lista[-1-i]:
            return False
    return True

print (crazy_list([5, 6, 8, 9, 'PYTHON', 9, 8, 6, 5]))
print (crazy_list([4, 5, 6, 7, 8, 4, 5, 2]))


from Output import *

"""
This is a useful tool for people playing Pokémon Mystery Dungeon: Explorers of Sky (EoS) on an emulator.
Wonder Code S is a mechanic that allows players to make themselves missions to complete.
However, these "Wonder Codes" used to create the missions are time-consuming and tedious to input.
This tool does the inputs for the user extremely quickly.
"""

def main():
    file = open("code.txt", "r")
    codes = getCodesList(file)

    for code in codes:
        outputCode(code)

def getCodesList(file):
    """
    A function to read the text file containing the codes, and return those codes as a list.
    :return: A list containing every code to be inputted.
    :param file: File containing the codes to input.
    """

    codes = []
    currentCode = ""

    for line in file:
        # If the line is empty, then it's a new code.  In that case, add the old code to the list, and start again.
        if line == "":
            # Empty spaces and newline characters need to be removed.
            currentCode = currentCode.replace(" ", "")
            currentCode = currentCode.replace("\n", "")
            codes.append(currentCode)
            currentCode = ""
        # If the line is not empty, then it should be added to the current code.
        else:
            currentCode += line

    # Adds the last code in the file to the list.
    # Empty spaces and newline characters need to be removed.
    currentCode = currentCode.replace(" ", "")
    currentCode = currentCode.replace("\n", "")
    codes.append(currentCode)

    return codes

main()


from django.shortcuts import render, redirect
from django.views import View
from .models import Person, Address, Telephone, Email, Group
from .forms import PersonCreateForm, AddressCreateForm, TelephoneCreateForm, EmailCreateForm

# Create your views here.
class MainPageView(View):
    def get(self, request):
        persons = Person.objects.order_by('name')
        ctx = {
            'persons': persons
        }
        return render(request, 'main.html', ctx)

class NewPersonView(View):
    def get(self, request):
        form = PersonCreateForm()
        return render(request, 'new.html', {'form': form})

    def post(self, request):
        form = PersonCreateForm(request.POST)
        if form.is_valid():
            p = Person()
            p.name = form.cleaned_data['name']
            p.surname = form.cleaned_data['surname']
            p.description = form.cleaned_data['description']
            p.save()
            return redirect('/')

class ModifyPersonView(View):
    def get(self, request, person_id):
        person = Person.objects.get(pk=person_id)
        form = PersonCreateForm()
        ctx = {
            'form': form,
            'person': person
        }
        return render(request, 'modify.html', ctx)

    def post(self, request, person_id):
        person = Person.objects.get(pk=person_id)
        form = PersonCreateForm(request.POST)
        if form.is_valid():
            p = Person()
            p.name = form.cleaned_data['name']
            p.surname = form.cleaned_data['surname']
            p.description = form.cleaned_data['description']
            p.pk = person.id
            p.save()
            return redirect('/')

class DeletePersonView(View):
    def get(self, request, person_id):
        p = Person.objects.get(pk=person_id)
        p.delete()
        return redirect('/')

class ShowPersonView(View):
    def get(self, request, person_id):
        person = Person.objects.get(pk=person_id)
        ctx = {
            'person': person,
        }
        return render(request, 'show.html', ctx)

class AddAddressView(View):
    def get(self, request, person_id):
        person = Person.objects.get(pk=person_id)
        form = AddressCreateForm()
        ctx = {
            'person': person,
            'form': form
        }
        return render(request, 'new.html', ctx)

    def post(self, request, person_id):
        person = Person.objects.get(pk=person_id)
        form = AddressCreateForm(request.POST)
        if form.is_valid():
            a = Address()
            a.city = form.cleaned_data['city']
            a.street = form.cleaned_data['street']
            a.house = form.cleaned_data['house']
            a.flat = form.cleaned_data['flat']
            a.person_id = person.id
            a.save()
            return redirect('/')

class AddTelephoneView(View):
    def get(self, request, person_id):
        person = Person.objects.get(pk=person_id)
        form = TelephoneCreateForm()
        ctx = {
            'person': person,
            'form': form
        }
        return render(request, 'new.html', ctx)

    def post(self, request, person_id):
        person = Person.objects.get(pk=person_id)
        form = TelephoneCreateForm(request.POST)
        if form.is_valid():
            t = Telephone()
            t.number = form.cleaned_data['number']
            t.type = form.cleaned_data['type']
            t.person_id = person.id
            t.save()
            return redirect('/')

class AddEmailView(View):
    def get(self, request, person_id):
        person = Person.objects.get(pk=person_id)
        form = EmailCreateForm()
        ctx = {
            'person': person,
            'form': form
        }
        return render(request, 'new.html', ctx)

    def post(self, request, person_id):
        person = Person.objects.get(pk=person_id)
        form = EmailCreateForm(request.POST)
        if form.is_valid():
            e = Email()
            e.email = form.cleaned_data['email']
            e.type = form.cleaned_data['type']
            e.person_id = person.id
            e.save()
            return redirect('/')


import torch
import torch.nn as nn
from model.backbone.myvgg import vgg16
from model.init_weights import kaiming_init,constant_init,normal_init,xavier_init
from model.load_pretrained import load_checkpoint

class ssd(vgg16):
    def __init__(self,
                 input_size=300,
                 with_last_pool=False,
                 ceil_mode=True,
                 out_indices=(3,4),
                 out_feat_indices=(22,34),
                 l2_norm_scale=20.):
        super(ssd,self).__init__(
            with_last_pool=with_last_pool,
            out_indices=out_indices,
            ceil_mode=ceil_mode
        )
        assert input_size in (300,512)
        self.input_size = input_size
        self.out_feature_indices = out_feat_indices

        self.features.add_module(
            str(len(self.features)),
            nn.MaxPool2d(kernel_size=3, stride=1, padding=1))
        self.features.add_module(
            str(len(self.features)),
            nn.Conv2d(512, 1024, kernel_size=3, padding=6, dilation=6))
        self.features.add_module(
            str(len(self.features)), nn.ReLU(inplace=True))
        self.features.add_module(
            str(len(self.features)), nn.Conv2d(1024, 1024, kernel_size=1))
        self.features.add_module(
            str(len(self.features)), nn.ReLU(inplace=True))

        extra_layers = [nn.Conv2d(1024,256,kernel_size=1),
                        nn.Conv2d(256,512,kernel_size=3,stride=2,padding=1),
                        nn.Conv2d(512,128,kernel_size=1),
                        nn.Conv2d(128,256,kernel_size=3,stride=2,padding=1),
                        nn.Conv2d(256,128,kernel_size=1),
                        nn.Conv2d(128,256,kernel_size=3),
                        nn.Conv2d(256, 128, kernel_size=1),
                        nn.Conv2d(128, 256, kernel_size=3),
                        ]
        self.add_module('extra',nn.Sequential(*extra_layers))
        self.l2_norm = L2Norm(self.features[out_feat_indices[0]-1].out_channels, l2_norm_scale)

    def init_weights(self, pretrained=None):
        """Initialize the weights in backbone.

        Args:
            pretrained (str, optional): Path to pre-trained weights.
                Defaults to None.
        """
        if isinstance(pretrained, str):
            load_checkpoint(self, pretrained, strict=False, logger=None)
            print('load pretrained checkpoint from {}'.format(pretrained))
        elif pretrained is None:
            for m in self.features.modules():
                if isinstance(m, nn.Conv2d):
                    kaiming_init(m)
                elif isinstance(m, nn.BatchNorm2d):
                    constant_init(m, 1)
                elif isinstance(m, nn.Linear):
                    normal_init(m, std=0.01)
        else:
            raise TypeError('pretrained must be a str or None')

        for m in self.extra.modules():
            if isinstance(m, nn.Conv2d):
                xavier_init(m, distribution='uniform')

        constant_init(self.l2_norm, self.l2_norm.scale)

    def forward(self, x):
        outs = []
        for i, layer in enumerate(self.features):
            #print(layer)
            x = layer(x)
            if i in self.out_feature_indices:
                outs.append(x)
        for i, layer in enumerate(self.extra):

            x = nn.functional.relu(layer(x),inplace=True)
            if i % 2 == 1:
                outs.append(x)
        outs[0] = self.l2_norm(outs[0])
        return tuple(outs)

# copy from mmdet
class L2Norm(nn.Module):

    def __init__(self, n_dims, scale=20., eps=1e-10):
        """L2 normalization layer.

        Args:
            n_dims (int): Number of dimensions to be normalized
            scale (float, optional): Defaults to 20..
            eps (float, optional): Used to avoid division by zero.
                Defaults to 1e-10.
        """
        super(L2Norm, self).__init__()
        self.n_dims = n_dims
        self.weight = nn.Parameter(torch.Tensor(self.n_dims))
        self.eps = eps
        self.scale = scale

    def forward(self, x):
        """Forward function."""
        # normalization layer convert to FP32 in FP16 training
        x_float = x.float()
        norm = x_float.pow(2).sum(1, keepdim=True).sqrt() + self.eps
        return (self.weight[None, :, None, None].float().expand_as(x_float) *
                x_float / norm).type_as(x)


#
# @lc app=leetcode.cn id=1247 lang=python3
#
# [1247] 交换字符使得字符串相同
#

# @lc code=start
import numpy as np
class Solution:
    def minimumSwap(self, s1: str, s2: str) -> int:
        xy, yx = np.sum([(int(a == 'x' and b == 'y'), int(a == 'y' and b == 'x')) for a, b in zip(s1, s2)], axis = 0)
        if (xy + yx) % 2 == 1: return -1
        return int(xy // 2 + yx // 2 + xy % 2 + yx % 2)
# @lc code=end

print(Solution().minimumSwap(s1 = "xx", s2 = "yy"))
print(Solution().minimumSwap(s1 = "xxyyxyxyxx", s2 = "xyyxyxxxyx"))

1247.交换字符使得字符串相同.py

1247.交换字符使得字符串相同.py


# Course: CS261 - Data Structures
# Student Name: Casey Levy
# Assignment: Assignment 1 - Problem 4
# Description: Function that recevies two parameters, a StaticArray and int value called "steps".
#              Will create and return a new StaticArray with all elements from original, but their
#              positions will be shifted left or right "steps" number of times, depending on if they're positive or negative.

from a1_include import *

def move_right(arr, new_arr, num):

    """
    Function takes parameters of a current array, new array, and "num" of steps.
    Number of steps determines how many places a value in the array moves right.
    Will return a new array with the new value rotations in place.
    """

    i = 0
    arr_length = arr.size()

# Copying items from specific points and then copying from the rest of the array
    for x in range(arr_length - num, arr_length):
        new_arr.set(i, arr.get(x))
        i += 1

    for x in range(0, arr_length - num):
        new_arr.set(i, arr.get(x))
        i += 1

    return new_arr

def move_left(arr, new_arr, num):

    """
    Function takes parameters of a current array, new array, and "num" of steps.
    Number of steps determines how many places a value in the array moves left.
    Will return a new array with the new value rotations in place.
    """

    i = 0
    arr_length = arr.size()

# Copying items from specific point
    for x in range(num, arr_length):
        new_arr.set(i, arr.get(x))
        i += 1

    for x in range(0, num):
        new_arr.set(i, arr.get(x))
        i += 1

    return new_arr

def rotate(arr: StaticArray, steps: int) -> StaticArray:

    """
    Creating a function that receives two parameters, a StaticArray, and an int value called "steps".
    The function will create and return a new StaticArray with same elements from original array but
    shifted left or right depending on the value of "steps". If "steps" is positive, elements will move right.
    If not, elements move left.
    """

    new_arr = StaticArray(arr.size())
    arr_length = arr.size()

#moving left
    if steps < 0:
        steps = abs(steps)

        if steps > arr_length:
            remain = steps - arr_length
            while remain >= arr_length:
                remain -= arr_length
            new_arr = move_left(arr, new_arr, remain)
        else:
            new_arr = move_left(arr, new_arr, steps)

        return new_arr

#moving right
    if steps >= 0:
        if steps > arr_length:
            remain = steps - arr_length

            while remain >= arr_length:
                remain -= arr_length
            new_arr = move_right(arr, new_arr, remain)
        else:
            new_arr = move_right(arr, new_arr, steps)

    return new_arr

# BASIC TESTING
if __name__ == "__main__":

    # example 1
    source = [_ for _ in range(-20, 20, 7)]
    arr = StaticArray(len(source))
    for i, value in enumerate(source):
        arr.set(i, value)

    print(arr)
    for steps in [1, 2, 0, -1, -2, 28, -100]:
        print(rotate(arr, steps), steps)
    print(arr)

Assignment 1 - Python Programming Practice/a1_problem4.py


# -*- coding: utf-8 -*-

# sxvao.py

import serial

class SXVAO():
    def __init__(self, parent, comport, timeout=10):
        self.parent = parent
        self.comport = comport
        self.timeout = timeout
        # configuration attributes
        self.steps_per_pixel = 6.0
        self.switch_xy = False
        self.reverse_x = False
        self.reverse_y = False
        self.mount_steps_per_pixel = 6.0
        self.mount_switch_xy = False
        self.mount_reverse_x = False
        self.mount_reverse_y = False
        self.max_steps = 10
        self.steps_limit = 1000
        # internal variables
        self.ao = None
        self.count_steps_N = 0
        self.count_steps_W = 0

    def Connect(self):
        if self.ao is None:
            try:
                self.ao = serial.Serial(self.comport, timeout=10)
            except OSError:
                return False
            self.ao.write('X')
            response = self.ao.read(1)
            return response == 'Y'
        else:
            return False

    def Disconnect(self):
        if self.ao is not None:
            self.ao.close()
            self.ao = None

    def MakeCorrection(self, dx, dy):
        if self.reverse_x:
            dx = -dx
        if self.reverse_y:
            dy = -dy
        if self.switch_xy:
            dx, dy = dy, dx
        nx = self.DeltaToSteps(dx)
        dir = 'T' if dx > 0 else 'W'
        while nx > 0:
            n = nx%self.max_steps
            self.MakeSteps(dir, n)
            nx -= n
        ny = self.DeltaToSteps(dy)
        dir = 'N' if dy > 0 else 'S'
        while ny > 0:
            n = ny%self.max_steps
            self.MakeSteps(dir, n)
            ny -= n
        return True

    def MakeMountCorrection(self, dx, dy):
        if self.mount_reverse_x:
            dx = -dx
        if self.mount_reverse_y:
            dy = -dy
        if self.mount_switch_xy:
            dx, dy = dy, dx
        nx = self.DeltaToMountSteps(dx)
        dir = 'T' if dx > 0 else 'W'
        self.MakeMountSteps(dir, nx)
        ny = self.DeltaToMountSteps(dy)
        dir = 'N' if dy > 0 else 'S'
        self.MakeMountSteps(dir, ny)
        return True

    def DeltaToSteps(self, d):
        return int(round(abs(d)/self.steps_per_pixel))

    def DeltaToMountSteps(self, d):
        return int(round(abs(d)/self.mount_steps_per_pixel))

    def MakeSteps(self, dir, n=1):
        # dir must be one of [N, S, T, W]
        if dir == 'N':
            self.count_steps_N += n
        elif dir == 'S':
            self.count_steps_N -= n
        if dir == 'W':
            self.count_steps_W += n
        elif dir == 'T':
            self.count_steps_W -= n
        command = 'G{:1s}{:05d}'.format(dir, n)
        self.ao.write(command)
        response = self.ao.read(1)
        if response == 'G':
            self.parent.Log('AO unit took {:d} steps {:s}'.format(n, dir))
        elif response == 'L':
            self.parent.Log('AO unit hit limit')
        else:
            self.parent.Log('AO unit stepping failed')
        self.RecentreMountIfNeeded(force=(response=='L'))

    def MakeMountSteps(self, dir, n=1):
        # dir must be one of [N, S, T, W]
        command = 'M{:1s}{:05d}'.format(dir, n)
        self.ao.write(command)
        response = self.ao.read(1)
        if response == 'M':
            self.parent.Log('Mount took {:d} steps {:s}'.format(n, dir))
        else:
            self.parent.Log('Mount stepping failed')

    def RecentreMountIfNeeded(self, force=False):
        # Move to approximately recentre AO with
        # opposing move for scope to keep image stationary
        # North-South
        mount_steps_N = (self.count_steps_N * self.mount_steps_per_pixel
                         / self.steps_per_pixel)
        if self.count_steps_N > self.steps_limit or force:
            self.MakeSteps('S', abs(self.count_steps_N))
            self.MakeMountSteps('N', abs(mount_steps_N))
            self.count_steps_N = 0
        elif self.count_steps_N < -self.steps_limit:
            self.MakeSteps('N', abs(self.count_steps_N))
            self.MakeMountSteps('S', abs(mount_steps_N))
            self.count_steps_N = 0
        # West-East
        mount_steps_W = (self.count_steps_W * self.mount_steps_per_pixel
                         / self.steps_per_pixel)
        if self.count_steps_W > self.steps_limit or force:
            self.MakeSteps('T', abs(self.count_steps_W))
            self.MakeMountSteps('W', abs(mount_steps_W))
            self.count_steps_W = 0
        elif self.count_steps_W < -self.steps_limit:
            self.MakeSteps('W', abs(self.count_steps_W))
            self.MakeMountSteps('T', abs(mount_steps_W))
            self.count_steps_W = 0

    def Centre(self):
        self.ao.write('K')
        response = self.ao.read(1)
        return response == 'K'


import auth.auth as auth
from flask import Response
import json
from datastore.datastore import initClient, datastore
import datetime, uuid
from utils import response

client = initClient()

@auth.auth_required()
def whoami(request):
    return Response(status=200,
                    mimetype='application/json',
                    response=json.dumps(request.user_info))

@auth.auth_required()
def login(request):

    email = request.user_info['user']

    #get user from datastore
    user_data = client.get(client.key('user', email))
    if(user_data == None):
        new_user = datastore.Entity(key=client.key('user', email))
        new_user['createdAt'] = datetime.datetime.utcnow()
        new_user['email'] = email
        new_user['children'] = {}
        client.put(new_user)

        return Response(status=200,
                        mimetype='application/json',
                        response=json.dumps(new_user, default=str))
    else:
        return Response(status=200,
                        mimetype='application/json',
                        response=json.dumps(user_data, default=str))

@auth.auth_required()
def addChildren(request):
    # check content type
    if request.content_type.split(";")[0] != 'application/json':
        return Response(status=415,
                        mimetype='application/json',
                        response=json.dumps({"error": "Content-Type must be application/json"}))

    # get data from request
    data = request.get_json()
    childName = data.get('childName')
    childAge = data.get('childAge')

    email = request.user_info['user']

    if childName == None:
        return response.missing_field('childName')
    if childAge == None:
        return response.missing_field('childAge')

    user_data = client.get(client.key('user', email))
    if(user_data == None):
        return Response(status=404,
                        mimetype='application/json',
                        response=json.dumps({"error": "User not found, are you sure you are logged in?"}))
    else:
        # create children entity
        child = {}
        child['childName'] = childName
        child['yearOfBirth'] = datetime.datetime.now().year - int(childAge)
        child['photoUrl'] = "https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.istockphoto.com%2Fphotos%2Fbaby&psig=AOvVaw0QZ2Z2Q4Z3Q4Z3Q4Z3Q4Z3&ust=1614784750000000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCJjQ4Z3Q4-8CFQAAAAAdAAAAABAD"
        child['createdAt'] = datetime.datetime.utcnow()

        childId = str(uuid.uuid4())
        # check if childId already exists
        while client.get(client.key('user_learning', childId)) != None:
            childId = str(uuid.uuid4())

        user_data['children'][childId] = child
        client.put(user_data)

        # create user learning entity
        user_learning = datastore.Entity(key=client.key('user_learning', childId))
        user_learning['childId'] = childId
        user_learning['email'] = email
        user_learning['completedLessonsObject'] = {}
        user_learning['tagScoring'] = {}
        user_learning['weeklyLearningIndex'] = {
            "integer": 0,
            "lastUpdated": datetime.datetime.utcnow()
        }

        client.put(user_learning)

        return Response(status=200,
                        mimetype='application/json',
                        response=json.dumps({
                            childId: child
                        }, default=str))

@auth.auth_required()
def updateChild(request):
    userid = request.user_info['user']
    data = request.get_json()

    childId = data.get('childId')
    childName = data.get('childName')
    childAge = data.get('childAge')

    if childId == None:
        return response.missing_field('childId')
    if childName == None:
        return response.missing_field('childName')
    if childAge == None:
        return response.missing_field('childAge')

    userData = client.get(client.key('user',userid))
    if userData == None:
        return Response (status=401,
                        mimetype='application/json',
                        response=json.dumps({'error': 'Strange, you are not registered. Maybe /login first and thn make some child if you know what I mean {ಠʖಠ}'}))

    if userData.get('children').get(childId) == None:
        return Response (status=403,
                        mimetype='application/json',
                        response=json.dumps({'error': 'child Id not found or this child does not belong to you'}))

    childData = userData.get('children').get(childId)
    childData['childName'] = childName
    childData['yearOfBirth'] = datetime.datetime.now().year - int(childAge)
    userData['children'][childId] = childData
    client.put(userData)

    return Response (status=200,
                    mimetype='application/json',
                    response=json.dumps({"message":f"{childId} updated"}))

# TODO: use this function in pubsub
# instead of deleting the child, we should just set the status to inactive
# and schedule delete after n days
@auth.auth_required()
def deleteChild(request):
    userId = request.user_info['user']
    data = request.get_json()
    childId = data.get('childId')
    if childId == None:
        return response.missing_field('childId')

    # delete user learning
    client.delete(client.key('user_learning', childId))

    # delete child from user
    userData = client.get(client.key('user',userId))
    if userData == None:
        return Response (status=401,
                        mimetype='application/json',
                        response=json.dumps({'error': 'Strange, you are not registered. Maybe /login first and thn make some child if you know what I mean {ಠʖಠ}'}))

    if userData.get('children').get(childId) == None:
        return Response (status=403,
                        mimetype='application/json',
                        response=json.dumps({'error': 'child Id not found or this child does not belong to you'}))

    del userData['children'][childId]
    client.put(userData)

    return Response (status=200,
                    mimetype='application/json',
                    response=json.dumps({"message":f"{childId} deleted"}))

@auth.auth_required()
def getChildById(request):
    userId = request.user_info['user']
    childId = request.args.get('childId')

    if childId == None:
        return response.missing_field('childId')

    userData = client.get(client.key('user',userId))
    if userData == None:
        return Response (status=401,
                        mimetype='application/json',
                        response=json.dumps({'error': 'Strange, you are not registered. Maybe /login first and thn make some child if you know what I mean {ಠʖಠ}'}))

    if userData.get('children').get(childId) == None:
        return Response (status=403,
                        mimetype='application/json',
                        response=json.dumps({'error': 'child Id not found or this child does not belong to you'}))

    return Response(
            status=200,
            mimetype='application/json',
            response = json.dumps(userData.get('children').get(childId), default=str)
            )


import time

import pygame
import random

class Laser:
    def __init__(self, screen, pos: list[float, float], color, dt):
        self._screen = screen
        self.pos = pos
        self._color = color
        self._dt = dt

        self.rect = pygame.Rect(self.pos[0] + 46, self.pos[1] - 20, 8, 20),
        pygame.draw.rect(
            self._screen,
            self._color,
            rect=self.rect
        )

    def fire(self, lasers: list):
        self.pos[1] -= 600 * self._dt

        if self.pos[1] < 0:
            lasers.remove(self)
        else:
            self.rect = pygame.Rect(self.pos[0] + 46, self.pos[1] - 20, 8, 20),

            pygame.draw.rect(
                self._screen,
                self._color,
                rect=self.rect
            )

class Enemy:
    def __init__(self, pos: list[int, int], screen, dt):
        self._dt = dt
        self._screen = screen
        self.pos = pos
        self._color = (255, 0, 255)
        self.rect = pygame.Rect(self.pos[0], self.pos[1], 100, 100)
        self._image = pygame.image.load("images/alien.gif")

    def move(self):
        if self.pos[0] < 100:
            self.pos[0] += 20 * self._dt
        elif self.pos[0] > 1000:
            self.pos[0] -= 20 * self._dt

        self.pos[1] += 2 * self._dt

        self.rect = pygame.Rect(self.pos[0], self.pos[1], 100, 100)

        self._screen.blit(self._image, self.rect)

class Player:
    def __init__(self):
        self._screen = pygame.display.set_mode((1280, 720))

        vector = pygame.Vector2(
            (self._screen.get_width() / 2) - 50, (self._screen.get_height() / 2) - 50
        )
        self.pos = [vector.x, vector.y]

        self._image = pygame.image.load("images/space_ship.gif")

    def draw(self):
        rect = pygame.Rect(self.pos[0], self.pos[1], 100, 100)
        self._screen.blit(self._image, rect)

class Game:
    def __init__(self):
        pygame.init()
        self._player = Player()
        self._screen = pygame.display.set_mode((1280, 720))
        self._clock = pygame.time.Clock()
        self._running = True
        self._time = 0
        self._lasers = []
        self._enemies = []

        # self._enemies = [Enemy(self._screen, self._dt)]
        self._clock = pygame.time.Clock()
        self._dt = self._clock.tick(60) / 1000

    def run(self):
        _ = list(
            map(
                lambda _: self._enemies.append(
                    Enemy([random.randint(0, 1180), 200], self._screen, self._dt)
                ),
                range(10),
            )
        )

        while self._running:
            self._screen.fill((0, 0, 0))

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self._running = False

            self._player.draw()

            keys = pygame.key.get_pressed()

            if keys[pygame.K_w] or keys[pygame.K_UP]:
                self._player.pos[1] -= 50 * self._dt
            if keys[pygame.K_s] or keys[pygame.K_DOWN]:
                self._player.pos[1] += 50 * self._dt
            if keys[pygame.K_a] or keys[pygame.K_LEFT]:
                self._player.pos[0] -= 50 * self._dt
            if keys[pygame.K_d] or keys[pygame.K_RIGHT]:
                self._player.pos[0] += 50 * self._dt

            if keys[pygame.K_SPACE] and self._time < time.time():
                self._lasers.append(
                    Laser(
                        self._screen,
                        [self._player.pos[0], self._player.pos[1]],
                        "green",
                        self._dt,
                    )
                )
                self._time = time.time() + 0.4

            _ = list(map(lambda laser: laser.fire(self._lasers), self._lasers))

            _ = list(map(lambda enemy: enemy.move(), self._enemies))

            for enemy in self._enemies:
                for laser in self._lasers:
                    if enemy.rect.colliderect(laser.rect):
                        self._enemies.remove(enemy)
                        self._lasers.remove(laser)

            pygame.display.flip()

        pygame.quit()


import sys
import ast
import os
import time

from dronekit import connect, VehicleMode, LocationGlobal, LocationGlobalRelative
from pymavlink import mavutil

#####################   connecting to the the drone   ###########################

vehicle = connect('/dev/ttyS0', baud=57600, wait_ready=True)
print( str(vehicle.system_status.state) )

############## converting the argument to a usable python list###################
os.system("clear")
# the argument
body = sys.argv
# removes 'python front_end.py'
body.pop(0)
# body is a string, this converts it to a python list
after_ast = ast.literal_eval(body[0])

###### All functions that can be selected from the front end drop down menu #####

def arm_drone(*param):
    print("vehicle mode: ", vehicle.mode, "vehicle system status-state: ", vehicle.system_status.state)

    vehicle.mode = VehicleMode("LOITER")

    print("Is vehicle armable? ", vehicle.is_armable)
    while vehicle.armed==False:
        print("Waiting for vehicle to be armed.")
        vehicle.armed = True
        if vehicle.armed == True:
            break
        time.sleep(1)
    print("vehicle is now armed")

    time.sleep(1)
    return None

def takeoff_drone(height):
    print("takeoff_drone function")
    vehicle.simple_takeoff(height)
    # verify the drone has reached the desired alt before calling the next function
    while True:
        print("Altitude: ", vehicle.location.global_relative_frame.alt)
        #Break and return from function just below target altitude.
        if vehicle.location.global_relative_frame.alt >= height * 0.95:
            print("Desired Altitude Reached!")
            break
    vehicle.mode = VehicleMode("LOITER")
    print("Vehicle mode is currently set to: ", vehicle.mode)
    time.sleep(1)

def loiter_time(time):
    print("loiter_time function")
    vehicle.mode = VehicleMode("LOITER")
    print("Vehicle mode is currently set to: ", vehicle.mode)
    time.sleep(time)

def land_drone(*param):
    print("land_drone function")
    vehicle.mode = VehicleMode("LAND")
    time.sleep(1)

def take_picture(*param):
    print("take_picture function")
    # TODO mavlink message to ake a picture

def set_yaw(heading):
    print("set_yaw function")
    # based on the user input, this decides if the drone should yaw cw or ccw
    if heading == 0:
        direction = 1
    elif heading > 0:
        direction = 1
    elif heading < 0:
        direction = -1
    # create the CONDITION_YAW command using command_long_encode()
    msg = vehicle.message_factory.command_long_encode(
        0, 0,       # target system, target component
        mavutil.mavlink.MAV_CMD_CONDITION_YAW, #command
        0,          #confirmation
        heading,    # param 1, yaw in degrees
        0,          # param 2, yaw speed deg/s
        direction,  # param 3, direction -1 ccw, 1 cw
        1,          # param 4, relative offset 1, absolute angle 0
        0, 0, 0)    # param 5 ~ 7 not used
    # send command to vehicle
    vehicle.send_mavlink(msg)

def move_front(Vx):
    print("move_front function")
    move_front_msg = vehicle.message_factory.set_position_target_local_ned_encode(
    0,
    0, 0,
    mavutil.mavlink.MAV_FRAME_LOCAL_NED,
    0b0000111111111000,
    Vx, 0, 0,
    0, 0, 0,
    0, 0, 0,
    0, 0
    )
    vehicle.send_mavlink(move_front_msg)

def move_back(Vx):
    print("move_back function")
    move_back_msg = vehicle.message_factory.set_position_target_local_ned_encode(
    0,
    0, 0,
    mavutil.mavlink.MAV_FRAME_LOCAL_NED,
    0b0000111111111000,
    -Vx, 0, 0,
    0, 0, 0,
    0, 0, 0,
    0, 0
    )
    vehicle.send_mavlink(move_back_msg)

def move_right(Vy):
    print("move_right function")
    move_right_msg = vehicle.message_factory.set_position_target_local_ned_encode(
    0,
    0, 0,
    mavutil.mavlink.MAV_FRAME_LOCAL_NED,
    0b0000111111111000,
    0, Vy, 0,
    0, 0, 0,
    0, 0, 0,
    0, 0
    )
    vehicle.send_mavlink(move_right_msg)

def move_left(Vy):
    print("move_left function")
    move_left_msg = vehicle.message_factory.set_position_target_local_ned_encode(
    0,
    0, 0,
    mavutil.mavlink.MAV_FRAME_LOCAL_NED,
    0b0000111111111000,
    0, -Vy, 0,
    0, 0, 0,
    0, 0, 0,
    0, 0
    )
    vehicle.send_mavlink(move_left_msg)

def move_up(Vz):
    print("move_up function")
    move_up_msg = vehicle.message_factory.set_position_target_local_ned_encode(
    0,
    0, 0,
    mavutil.mavlink.MAV_FRAME_LOCAL_NED,
    0b0000111111111000,
    0, 0, -Vz,
    0, 0, 0,
    0, 0, 0,
    0, 0
    )
    vehicle.send_mavlink(move_up_msg)

def move_down(Vz):
    print("move_down function")
    move_down_msg = vehicle.message_factory.set_position_target_local_ned_encode(
    0,
    0, 0,
    mavutil.mavlink.MAV_FRAME_LOCAL_NED,
    0b0000111111111000,
    0, 0, Vz,
    0, 0, 0,
    0, 0, 0,
    0, 0
    )
    vehicle.send_mavlink(move_down_msg)

# Yes, this actually does work
def second_execute_commands(body):
    # 'body' is the list, 'dictionary' is the each {'command' : 'arbitrary_function(argument)'}
    for dictionary in body:
         exec(dictionary['command'])

second_execute_commands(after_ast)

# safety measure in case no final land command is passed in
vehicle.mode = VehicleMode("LAND")

print("the script is over")

################################### for testing #################################

vehicle.cond


#1
class Person:
    def __init__(self, name='', age=0, dni=''):
        self.__name = name
        self.__age = age
        self.__dni = dni

    def set_name(self, name):
        if len(name) > 0:
            self.__name = name
        else:
            print("Nombre no válido. Debe tener al menos un carácter.")

    def get_name(self):
        return self.__name

    def set_age(self, age):
        if age >= 0:
            self.__age = age
        else:
            print("Edad no válida. Debe ser un valor no negativo.")

    def get_age(self):
        return self.__age

    def set_dni(self, dni):
        if len(dni) == 9:  # Suponemos que el DNI tiene 9 caracteres
            self.__dni = dni
        else:
            print("DNI no válido. Debe tener exactamente 9 caracteres.")

    def get_dni(self):
        return self.__dni

    def mostrar(self):
        print(f"Nombre: {self.__name}")
        print(f"Edad: {self.__age}")
        print(f"DNI: {self.__dni}")

    def esMayorDeEdad(self):
        return self.__age >= 18

persona1 = Person("Juan", 25, "123456789")
persona1.mostrar()
print("¿Es mayor de edad?", persona1.esMayorDeEdad())

persona2 = Person()
persona2.set_name("Ana")
persona2.set_age(16)
persona2.set_dni("987654321")
persona2.mostrar()
print("¿Es mayor de edad?", persona2.esMayorDeEdad())

#2
class Account:
    def __init__(self, holder, balance=0.0):
        self.holder = holder
        self.balance = balance
    def set_balance(self, balance):
        if balance >= 0:
            self.balance = balance
        else:
            print("No se puede establecer un saldo negativo.")
    def get_balance(self):
        return self.balance
    def show(self):
        print("Titular: ", self.holder)
        print("Saldo: $", self.balance)
    def deposit(self, amount):
        if amount > 0:
            self.balance += amount
        else:
            print("No se puede depositar una cantidad negativa o cero.")
    def withdraw(self, amount):
        if amount > 0:
            self.balance -= amount
        else:
            print("No se puede retirar una cantidad negativa o cero.")

account_holder = "John Doe"
account = Account(account_holder, 1000.0)
account.show()
account.deposit(500)
account.withdraw(300)
account.show()

#3
class Triangle:
    def __init__(self, side1, side2, side3):
        self.side1 = side1
        self.side2 = side2
        self.side3 = side3
    def get_longest_side(self):
        return max(self.side1, self.side2, self.side3)
    def determine_type(self):
        if self.side1 == self.side2 == self.side3:
            return "equilátero"
        elif self.side1 == self.side2 or self.side2 == self.side3 or self.side1 == self.side3:
            return "isósceles"
        else:
            return "escaleno"

side1 = float(input("Ingrese la longitud del primer lado del triángulo: "))
side2 = float(input("Ingrese la longitud del segundo lado del triángulo: "))
side3 = float(input("Ingrese la longitud del tercer lado del triángulo: "))
triangle = Triangle(side1, side2, side3)
longest_side = triangle.get_longest_side()
print(f"El lado más largo del triángulo tiene una longitud de {longest_side} unidades.")
triangle_type = triangle.determine_type()
print(f"El triángulo es de tipo {triangle_type}.")

#4

class Contact:
    def __init__(self, name, phone, email):
        self.name = name
        self.phone = phone
        self.email = email
class Agenda:
    def __init__(self):
        self.contacts = []
    def add_contact(self, name, phone, email):
        new_contact = Contact(name, phone, email)
        self.contacts.append(new_contact)
        print("Contacto agregado con éxito.")
    def list_contacts(self):
        if not self.contacts:
            print("La agenda está vacía.")
        else:
            print("Lista de contactos:")
            for contact in self.contacts:
                print(f"Nombre: {contact.name}")
                print(f"Teléfono: {contact.phone}")
                print(f"Email: {contact.email}")
                print("")
    def find_contact(self, name):
        found = False
        for contact in self.contacts:
            if contact.name == name:
                print(f"Contacto encontrado:")
                print(f"Nombre: {contact.name}")
                print(f"Teléfono: {contact.phone}")
                print(f"Email: {contact.email}")
                found = True
                break
        if not found:
            print(f"El contacto '{name}' no se encuentra en la agenda.")
    def edit_contact(self, name, new_phone, new_email):
        found = False
        for contact in self.contacts:
            if contact.name == name:
                contact.phone = new_phone
                contact.email = new_email
                print(f"Contacto '{name}' editado con éxito.")
                found = True
                break
        if not found:
            print(f"El contacto '{name}' no se encuentra en la agenda.")
    def close_agenda(self):
        print("Agenda cerrada.")
def menu():
    print("Menú de la Agenda:")
    print("1. Añadir contacto")
    print("2. Lista de contactos")
    print("3. Buscar contacto")
    print("4. Editar contacto")
    print("5. Cerrar agenda")
    option = input("Seleccione una opción (1/2/3/4/5): ")
    return option

agenda = Agenda()

while True:
    option = menu()
    if option == "1":
        name = input("Ingrese el nombre del contacto: ")
        phone = input("Ingrese el teléfono del contacto: ")
        email = input("Ingrese el correo electrónico del contacto: ")
        agenda.add_contact(name, phone, email)
    elif option == "2":
        agenda.list_contacts()
    elif option == "3":
        name = input("Ingrese el nombre del contacto a buscar: ")
        agenda.find_contact(name)
    elif option == "4":
        name = input("Ingrese el nombre del contacto a editar: ")
        new_phone = input("Ingrese el nuevo teléfono del contacto: ")
        new_email = input("Ingrese el nuevo correo electrónico del contacto: ")
        agenda.edit_contact(name, new_phone, new_email)
    elif option == "5":
        agenda.close_agenda()
        break
    else:
        print("Opción no válida. Por favor, seleccione una opción válida (1/2/3/4/5).")


"""
Counting Sundays
Problem 19
You are given the following information, but you may prefer to do some research for yourself.

- 1 Jan 1900 was a Monday.
- Thirty days has September,
  April, June and November.
  All the rest have thirty-one,
  Saving February alone,
  Which has twenty-eight, rain or shine.
  And on leap years, twenty-nine.
  A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.

How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
"""

def count_sundays(start_year,end_year):
    year = start_year
    period = 1
    sundays = list()
    for year in range(start_year,end_year+1):
        for month in range(1,12+1):
            if period % 7 == 0:
                sundays.append((year,month))
            period += days_of_month(year, month)
    return sundays

def days_of_month(year,month):
    """

    """
    if month == 1:
        return 31
    elif month == 2:
        if year % 4 == 0 and not (year % 100 == 0 and year % 400 != 0):
            return 29
        else:
            return 28
    elif month == 3:
        return 31
    elif month == 4:
        return 30
    elif month == 5:
        return 31
    elif month == 6:
        return 30
    elif month == 7:
        return 31
    elif month == 8:
        return 31
    elif month == 9:
        return 30
    elif month == 10:
        return 31
    elif month == 11:
        return 30
    elif month == 12:
        return 31

def test_f(year,month):
    """
    Num year -> Num month -> num (28 or 29)
    This function simply checks for a given year with the assumption that the month is 2
    if the
    """
    if month == 2:
        if year % 4 == 0 and not (year % 100 == 0 and year % 400 != 0):
            return 29
        else:
            return 28

if __name__ == "__main__":
    sundays = count_sundays(1900,2000)
    years_of_interest = {year for year in range(1901,2000+1)}
    sundays_no_1900 = filter(lambda item: item[0] in years_of_interest, sundays)
    num_sundays = len(sundays_no_1900)
    print("The number of 1st month Sundays in the years 1901 and including 2000 is " + str(num_sundays))


import glob
from PIL import Image
# img = Image.open('data/src/sample.png')

img_list = glob.glob('C:/Users/ASIAE-12/Desktop/before_val_img/*.jpg')
print(img_list[0], len(img_list))
for image in img_list:
    print(image[-44:])
    img = Image.open(image)
    print(img)
    img_resize = img.resize((640,360))
    img_resize.save('C:/Users/ASIAE-12/Desktop/img/val_img/{}'.format(image[-44:]))


import requests
from bs4 import BeautifulSoup

URL = requests.get('http://www.io-net.com/violet/violet1/sumiresaisin.htm')
URL.encoding = URL.apparent_encoding  # 呪文
soup = BeautifulSoup(URL.text, 'html.parser')

viola = {}

table = soup.find('table')
tbody = table.find('tbody')
trs = tbody.find_all('tr')  # trタグを探す

for tr in trs:
    for th in tr.find_all('th'):  # trタグからthタグを探す
        if not th.get('rowspan'):
            viola[th.text] = 'x'
    for td in tr.find_all('td'):  # trタグからtdタグを探す
        viola[th.text] = td.text

print(viola)

# viola[r] = s
# print(viola)


# lesson_7_functions. Task 3
# A simple calculator.
# Create a function called make_operation, which takes
# in a simple arithmetic operator as a first parameter
# (to keep things simple let it only be ‘+’, ‘-’ or ‘*’)
# and an arbitrary number of arguments (only numbers) as
# the second parameter. Then return the sum or product of
# all the numbers in the arbitrary parameter. For example:
#
#     the call make_operation(‘+’, 7, 7, 2) should return 16
#     the call make_operation(‘-’, 5, 5, -10, -20) should return 30
#     the call make_operation(‘*’, 7, 6) should return 42

def make_operation(action, *args):
    def my_add(a, b):
        return a + b

    def my_sub(a, b):
        return a - b

    def my_mul(a, b):
        return a * b

    def my_div(a, b):
        return a / b

    actions_list = ['+', '-', '*', '/']

    if action in actions_list:
        print(f'ARGS имеет следующие значения: {args}, с длиной {len(args)} и типом {type(args)}')
        i = 0
        res = args[0]
        print(f'Первичный res равен: {res}')
        if action == '+':
            for i in args[1:]:
                res = my_add(res, i)
                print(f'при добавлении {i} к {res}, получен результат: {res}')
            return res
        elif action == '-':
            for i in args[1:]:
                res = my_sub(res, i)
                print(f'при вычитании {i} от {res}, получен результат: {res}')
            return res
        elif action == '*':
            for i in args[1:]:
                res = my_mul(res, i)
                print(f'при умножении {i} на {res}, получен результат: {res}')
            return res
        elif action == '/':
            try:
                for i in args[1:]:
                    res = my_div(res, i)
                    print(f'при делении {i} на {res}, получен результат: {res}')
            except ZeroDivisionError:
                print(f'На 0 делить нельзя')
            return res
        else:
            print('Был использован неправильный оператор')

if __name__ == "__main__":
    try:
        a = make_operation('*', 5, 5, 10, -20)
        print(a)
    except:
        print('Что то не получилось')


import recursiveDescentParser as rdp
import inputUtils as utils

if __name__ == "__main__":

    runProgram = True

    while runProgram:
        fileName, runProgram = utils.getUserInput()

        if runProgram:

            fileHandle = open(fileName, 'r')

            for line in fileHandle:
                rdp.rdparser(line)


from PIL import Image, ImageOps
from src.models.class_patcher import patcher

class patcher(patcher):
    def __init__(self, body='./body/body_quiche_nbody.png', **options):
        super().__init__('キッシュ(素体)', body=body, pantie_position=[403, 836], **options)
        try:
            self.with_bra = self.options['with_bra']
        except:
            self.with_bra = self.ask(question='With bra?', default=True)
        if self.with_bra:
            import src.models.quiche_bra as bra
            self.bra_patcher = bra.patcher(options=options)

    def convert(self, image):
        cut = 7
        right_pantie = image.crop((cut, 0, image.size[0], image.size[1]))
        left_pantie = ImageOps.mirror(right_pantie)
        npantie = Image.new("RGBA", (right_pantie.size[0] * 2, right_pantie.size[1]))
        npantie.paste(right_pantie, (right_pantie.size[0], 0))
        npantie.paste(left_pantie, (0, 0))
        return npantie

    def patch(self, image, transparent=False):
        pantie = self.convert(image)
        if transparent:
            patched = Image.new("RGBA", self.body_size)
        else:
            patched = self.body.copy()
        if self.with_bra:
            bra = self.bra_patcher.convert(image)
            self.paste(patched, bra, self.bra_patcher.pantie_position)
        patched = self.paste(patched, pantie, self.pantie_position)
        return patched


#!/usr/bin/env python
# encoding: utf-8
"""
@author: ssuf1998
@file: model.py
@time: 2021/2/21 18:26
@desc: Null
"""

import tensorflow as tf

def xception(classes):
    base = tf.keras.applications.Xception(
        input_shape=(299, 299, 3),
        weights='xception_weights_tf_dim_ordering_tf_kernels_notop.h5',
        include_top=False,
        pooling='avg'
    )
    base.trainable = False
    m = tf.keras.Sequential()
    m.add(base)

    # lr_fn = tf.keras.optimizers.schedules.ExponentialDecay(
    #     initial_learning_rate=0.01,
    #     decay_steps=256,
    #     decay_rate=0.96
    # )
    # opt = tf.keras.optimizers.Adam(learning_rate=0.001 if conf.RETRAIN else lr_fn)

    m.add(tf.keras.layers.Dense(classes, activation='softmax'))
    opt = tf.keras.optimizers.Adam()
    m.compile(optimizer=opt,
              loss='sparse_categorical_crossentropy',
              metrics=['acc'])

    return m


# Testing Acyclicity

from .helpers import parse_graphs

# Recursively remove leaf nodes (with no onward connections)
# If we remove all nodes, graph must be acyclic.

def graph_nodes(graph):
    nodes = set()
    for node, val in graph.items():
        nodes.add(node)
        nodes = nodes.union(val)
    return nodes

def remove_leaves(graph):
    nodes = graph_nodes(graph)
    leaves = nodes - graph.keys()
    return {n: set(v) - leaves for n, v in graph.items() if len(set(v) - leaves)}

def dag(graph):
    while graph:
        ngraph = remove_leaves(graph)
        if len(graph) == len(ngraph):
            return -1
        graph = ngraph
    return 1

def main(file):
    gen = parse_graphs(open(file), directed=True)
    print(*[dag(graph) for graph in gen])


import os
import sys
import faampy
import file_info

class File_List(list):
    """
    A list of File_Info objects. The list can be sorted and filtered which can
    be useful for batch processing.

    For example it is possible to (i) get all DECADES rawdlu and flight
    constant files from a path, (ii) filter those for the latest revisions and
    reprocess them.
    """

    def __init__(self, *args):
        """
        Get all FAAM data files in the path. The path argument can either be
        *one* existing path or a list of paths.

        If no path is supplied the directories that are defined in the
        .faampy_config file are searched.

        :param str path: path which will be walked and checked for
          FAAM data files

        :Example:

          In [16]: l = File_List('/home/axel/gdrive/ncas/core_processing/')

          In [17]: print(l)
          0: flight-sum_faam_20150806_r0_b919.txt
          1: core_faam_20150806_r0_b919_rawdlu.zip
          2: flight-cst_faam_20150806_r0_b919.txt
          3: flight-cst_faam_20150806_r1_b919.txt
        """
        if args:
            path_list = args[0]
            if not hasattr(path_list, "__iter__"):
                path_list = [path_list, ]
        else:
            path_list = faampy.DATA_SEARCH_PATH_LIST

        self.Path_List = path_list[:]
        for path in self.Path_List:
            if os.path.isdir(path):
                for root, subFolders, files in os.walk(path):
                    for f in files:
                        if file_info.get_data_type_from_filename(f):
                            finfo = file_info.File_Info(os.path.join(root, f))
                            if int(finfo.rev) < 90:
                                self.append(finfo)
            else:
                sys.stdout.write('%s: does not exist.\n' % path)
        self.sort()

    def filter_by_data_type(self, dtype):
        """
        Filtering by data type.
        """
        if dtype not in file_info.DATA_TYPES:
            sys.stdout.write('Submitted dtype unknown.\nValid data types are: %s\n' % ', '.join(sorted(file_info.DATA_TYPES.keys())))

        bad_index = []
        for i in self:
            if not i.data_type == dtype:
                bad_index.append(i)
        for b in bad_index:
            self.remove(b)

    def filter_latest_revision(self):
        """
        Compresses the list and keeps only the latest revision for a FID.
        """
        bad_index = []
        self.sort(key=lambda i: '%4s_%s_%s_%0.3i' % (i.fid, i.date,
                                                     i.data_type, i.rev))
        self.reverse()
        for i in range(len(self)-1):
            if ((self[i].fid, self[i].date, self[i].data_type)) == ((self[i+1].fid, self[i+1].date, self[i+1].data_type)):
                bad_index.append(self[i+1])
        for b in bad_index:
            self.remove(b)
        self.sort()

    def __str__(self):
        output = ''
        for _i, i in enumerate(self):
            output += '%i: %s\n' % (_i+1, i.filename)
        return output

    def get_filenames(self):
        """
        Returns the file names for each entry.
        """
        result = [os.path.join(i.path, i.filename) for i in self]
        return result

    def extract_fid(self, fid):
        ix = [i for i, x in enumerate(self) if x.fid == fid]
        return _File_List([self[i] for i in ix])

    def extract_date(self, date_string):
        ix = [i for i, x in enumerate(self) if x.date.startswith(date_string)]
        return _File_List([self[i] for i in ix])

class _File_List(File_List):
    """
    Copy of the File_List class that takes a list of file_info objects as an
    input instead of paths.
    """
    def __init__(self, file_info_items):
        for i in file_info_items:
            self.append(i)


from math import sqrt, atan2, cos, sin, pi

D = {'R': (1, 0), 'L': (-1, 0), 'U': (0, 1), 'D': (0, -1)}

def step(H, T):
    dist = sqrt((H[0]-T[0])**2 + (H[1]-T[1])**2)
    if dist <= sqrt(2): return H, T

    dir = atan2(H[1]-T[1], H[0]-T[0])

    if abs(dir/pi) in [0., 0.5, 1., 1.5, 2.0]:
        T[0] += int((dist-1)*cos(dir))
        T[1] += int((dist-1)*sin(dir))
        return H, T
    T[0] += -1 if H[0]-T[0] < 0 else 1
    T[1] += -1 if H[1]-T[1] < 0 else 1
    return H, T

with open('input') as f:
    moves = [(d, int(n)) for d, n in (line.split(' ') for line in f.read().splitlines())]

R = [[0, 0] for _ in range(10)]
history = [{str(R[1])},{str(R[-1])}]

for d, n in moves:
    for _ in range(n):
        R[0][0] += D[d][0]
        R[0][1] += D[d][1]
        for t in range(1, 10):
            R[t-1], R[t] = step(R[t-1], R[t])
        history[0].add(f'{R[1]}')
        history[1].add(f'{R[-1]}')
print(len(history[0]))
print(len(history[1]))


# -*- coding:utf-8 -*-
# email:bingchengzhou@foxmail.com
# create: 2021/1/13
import torch
from torch import nn
from networks.components.double_conv import DoubleConv, Down, Up, OutConv

class Generator(nn.Module):
    # Network Architecture is exactly same as in infoGAN (https://arxiv.org/abs/1606.03657)
    # Architecture : FC1024_BR-FC7x7x128_BR-(64)4dc2s_BR-(1)4dc2s_S
    def __init__(self, n_channels, n_classes, bilinear=True):
        super(Generator, self).__init__()
        self.n_channels = n_channels
        self.n_classes = n_classes
        self.bilinear = bilinear

        self.inc = DoubleConv(n_channels, 64)
        self.down1 = Down(64, 128)
        self.down2 = Down(128, 256)
        self.down3 = Down(256, 512)
        self.down4 = Down(512, 512)
        self.up1 = Up(1024, 256, bilinear)
        self.up2 = Up(512, 128, bilinear)
        self.up3 = Up(256, 64, bilinear)
        self.up4 = Up(128, 64, bilinear)
        self.dilation = nn.Sequential(
            nn.Conv2d(512, 512, 3, 1, 2, dilation=2),
            nn.BatchNorm2d(512),
            nn.LeakyReLU(0.2),
            nn.Conv2d(512, 512, 3, 1, 4, dilation=4),
            nn.BatchNorm2d(512),
            nn.LeakyReLU(0.2),
            nn.Conv2d(512, 512, 3, 1, 6, dilation=6),
            nn.BatchNorm2d(512),
            nn.LeakyReLU(0.2),
        )
        self.outw = OutConv(64, 3)
        self.outa = OutConv(64, 1)
        self.out_mask = OutConv(64, 1)
        self.sg = nn.Sigmoid()
        self.other = OutConv(64, 64)
        self.post_process_1 = nn.Sequential(
            nn.Conv2d(64 + 6, 64, 3, 1, 1),
            nn.BatchNorm2d(64),
            nn.LeakyReLU(0.2),
            nn.Conv2d(64, 128, 3, 1, 1),
        )
        self.post_process_2 = nn.Sequential(
            nn.BatchNorm2d(128),
            nn.LeakyReLU(0.2),
            nn.Conv2d(128, 128, 3, 1, 1),
        )
        self.post_process_3 = nn.Sequential(
            nn.BatchNorm2d(128),
            nn.LeakyReLU(0.2),
            nn.Conv2d(128, 128, 3, 1, 1),
        )
        self.post_process_4 = nn.Sequential(
            nn.BatchNorm2d(128),
            nn.LeakyReLU(0.2),
            nn.Conv2d(128, 128, 3, 1, 1),
        )
        self.post_process_5 = nn.Sequential(
            nn.BatchNorm2d(128),
            nn.LeakyReLU(0.2),
            nn.Conv2d(128, 3, 3, 1, 1),
            nn.Sigmoid(),
        )
        self.device = torch.device("cuda:0")

    def reset_post_process_device(self, device):
        self.device = device
        self.post_process_1 = self.post_process_1.to(self.device)
        self.post_process_2 = self.post_process_2.to(self.device)
        self.post_process_3 = self.post_process_3.to(self.device)
        self.post_process_4 = self.post_process_4.to(self.device)
        self.post_process_5 = self.post_process_5.to(self.device)

    def forward(self, x0):
        x1 = self.inc(x0)
        x2 = self.down1(x1)
        x3 = self.down2(x2)
        x4 = self.down3(x3)
        x5 = self.down4(x4)
        x5 = self.dilation(x5)
        x = self.up1(x5, x4)
        x = self.up2(x, x3)
        x = self.up3(x, x2)
        x = self.up4(x, x1)
        w = self.outw(x)
        a = self.outa(x)
        other = self.other(x)
        other = self.sg(other)
        mask = self.out_mask(x)
        mask = self.sg(mask)
        a = self.sg(a)
        w = self.sg(w)
        a = mask * a
        I_watermark = (x0 - a * w) / (1.0 - a + 1e-6)
        I_watermark = torch.clamp(I_watermark, 0, 1)
        xx1 = self.post_process_1(torch.cat([other, I_watermark, x0], 1).to(self.device))
        xx2 = self.post_process_2(xx1)
        xx3 = self.post_process_3(xx1 + xx2)
        xx4 = self.post_process_4(xx2 + xx3)
        I_watermark2 = self.post_process_5(xx4 + xx3)
        I = I_watermark2.to(x0.device) * mask + (1.0 - mask) * x0
        return I, mask, a, w, I_watermark

class Discriminator(nn.Module):
    # Network Architecture is exactly same as in infoGAN (https://arxiv.org/abs/1606.03657)
    # Architecture : (64)4c2s-(128)4c2s_BL-FC1024_BL-FC1_S
    def __init__(self, input_dim=3, output_dim=1):
        super(Discriminator, self).__init__()
        self.input_dim = input_dim
        self.output_dim = output_dim
        #self.input_size = input_size
        #self.class_num = class_num

        self.conv = nn.Sequential(
            nn.Conv2d(self.input_dim, 64, 16, 8, 4),
            nn.BatchNorm2d(64),
            nn.LeakyReLU(0.2),
            nn.Conv2d(64, 128, 3, 2, 1),
            nn.BatchNorm2d(128),
            nn.LeakyReLU(0.2),
            nn.Conv2d(128, 256, 3, 1, 1),
            nn.BatchNorm2d(256),
            nn.LeakyReLU(0.2),
            nn.Conv2d(256, 1, 3, 1, 1),
            nn.Sigmoid()
        )
        #utils.initialize_weights(self)

    def forward(self, x):
        x = self.conv(x)
        return x


from django.urls import path, include
from rest_framework.routers import DefaultRouter
from rest_framework.authtoken.views import obtain_auth_token

from .views import (
    # user
    UserList, UserListDisplay, AddUser, UpdateUser, GetCurrentUser, DeleteUser, LoginView,

    # enterprise
    EntepriseList, EntepriseListDisplay,

    # profile
    ProfileList, ProfileListDisplay, AddProfile,

    # privilege
    PrivilegeList,

    # project
    ProjectList, ProjectListDisplay,

    # offre
    OfferList, OfferListDisplay

)

router = DefaultRouter()
router.register(r'users', UserList, basename='users')
router.register(r'users-display', UserListDisplay, basename='users-display')

router.register(r'enterprises', EntepriseList, basename='enterprises')
router.register(r'enterprises-display', EntepriseListDisplay,
                basename='enterprises-display')
router.register(r'profiles', ProfileList, basename='profiles')
router.register(r'profiles-display', ProfileListDisplay,
                basename='profiles-display')
router.register(r'privileges', PrivilegeList, basename='privileges')
router.register(r'projects', ProjectList, basename='projects')
router.register(r'projects-display', ProjectListDisplay,
                basename='projects-display')
router.register(r'offers', OfferList, basename='offers')
router.register(r'offers-display', OfferListDisplay, basename='offers-display')

urlpatterns = [
    path('', include(router.urls)),

    # users
    path(r'add/', AddUser.as_view(), name='add'),
    path(r'update/<str:pk>/', UpdateUser.as_view(), name='update'),
    path(r'delete/<str:pk>/', DeleteUser.as_view(), name='delete'),
    path(r'get-user/', GetCurrentUser.as_view(), name='get-user'),
    path(r'login/', LoginView.as_view(), name="login"),
    # path(r'login/', obtain_auth_token),

    # profiles
    path(r'add-profile/', AddProfile.as_view())
]


pt = int(input('Digite o primeiro termo: '))
r = int(input('Digite a razão: '))
q = int(input('Quantos termos você quer: '))
a = 1
total = 0
while q != 0:
    total += q
    while a <= total:
        print(pt, end=' ')
        pt += r
        a += 1
    q = int(input('\nQuantos termos a mais vc quer ver: '))
print(f'FIM. \nForam mostrados {total} termos.')


# -*- coding: utf-8 -*-

import os.path
from itertools import product

from .constants import CHAR_MAP

def get_complete_path_of_file(filename):
    """Join the path of the current directory with the input filename."""
    root = os.path.abspath(os.path.dirname(__file__))
    return os.path.join(root, filename)

def read_wordlist(filename: str):
    """Return words from a wordlist file."""
    with open(filename, encoding="utf-8") as wordlist_file:
        for row in wordlist_file:
            row = row.strip()
            if row != "":
                yield row

def get_leet_combinations(word):
    """Get all combinations of leet character substitutions for a word

    https://stackoverflow.com/q/44181772"""
    combos = [(char,) if char not in CHAR_MAP else CHAR_MAP[char] for char in word]
    return ("".join(o) for o in product(*combos))


import scrapy
import json
from demo.items import DemoItem
from datetime import datetime
from datetime import date
from  demo.spiders import url_list
import uuid
from decouple import config
import pymongo
import gc

def load_datetime():

 today = date.today()
 now = datetime.now()
 date_now = today.strftime("%d/%m/%Y")
 time_now = now.strftime("%H:%M:%S")

 return date_now, time_now, today

class SagaSpider(scrapy.Spider):
    name = "saga"
    allowed_domains = ["falabella.com.pe"]

    def __init__(self, *args, **kwargs):
        super(SagaSpider, self).__init__(*args, **kwargs)
        self.client = pymongo.MongoClient(config("MONGODB"))
        self.db = self.client["brand_allowed"]
        self.lista = self.brand_allowed()[int(self.b)]  # Initialize self.lista based on self.b

    def brand_allowed(self):
        collection1 = self.db["shoes"]
        collection2 = self.db["electro"]
        collection3 = self.db["tv"]
        collection4 = self.db["cellphone"]
        collection5 = self.db["laptop"]
        collection6 = self.db["consola"]
        collection7 = self.db["audio"]
        collection8 = self.db["colchon"]
        collection9 = self.db["nada"]
        collection10 = self.db["sport"]
        collection11 = self.db["curacao"]
        collection12 = self.db["todo"]

        shoes = collection1.find({})
        electro = collection2.find({})
        tv = collection3.find({})
        cellphone = collection4.find({})
        laptop = collection5.find({})
        consola = collection6.find({})
        audio = collection7.find({})
        colchon = collection8.find({})
        nada = collection9.find({})
        sport = collection10.find({})
        curacao = collection11.find({})
        todo = collection12.find({})

        shoes_list = [doc["brand"] for doc in shoes]
        electro_list = [doc["brand"] for doc in electro]
        tv_list = [doc["brand"] for doc in tv]
        cellphone_list = [doc["brand"] for doc in cellphone]
        laptop_list = [doc["brand"] for doc in laptop]
        consola_list = [doc["brand"] for doc in consola]
        audio_list = [doc["brand"] for doc in audio]
        colchon_list = [doc["brand"] for doc in colchon]
        nada_list = [doc["brand"] for doc in nada]
        sport_list = [doc["brand"] for doc in sport]
        curacao_list = [doc["brand"] for doc in curacao]
        todo_list = [doc["brand"] for doc in todo]
        return (shoes_list ,electro_list,tv_list,cellphone_list,laptop_list, consola_list,
                audio_list, colchon_list,nada_list,sport_list,curacao_list, todo_list)

    def start_requests(self):
        u = int(getattr(self, 'u', '0'))
        b = int(getattr(self, 'b', '0'))

        # Define a dictionary to map 'u' values to the corresponding url_list
        url_mapping = {
            1: url_list.list1, 2: url_list.list1, 3: url_list.list3, 4: url_list.list4, 5: url_list.list5, 6: url_list.list6,
            7: url_list.list7, 8: url_list.list8, 9: url_list.list9, 10: url_list.list10, 11: url_list.list11, 12: url_list.list12, 13: url_list.list13,
            14: url_list.list14, 15: url_list.list15, 16: url_list.list16,  17: url_list.list17,  18: url_list.list18,
            19: url_list.list19, 20: url_list.list20,21: url_list.list21, 22: url_list.list22,23: url_list.list23

            }

        # Retrieve the appropriate list based on the value of 'u'
        urls = url_mapping.get(u, [])

        for i, v in enumerate(urls):
            if "linio" in v[0]:
                for e in range (v[1]+10):
                    url = v[0]+ "?subdomain=linio&page="+str(e+1)
                    yield scrapy.Request(url, self.parse)
            else:

                for e in range (v[1]+10):
                    url = v[0]+ "?page="+str(e+1)
                    yield scrapy.Request(url, self.parse)

        # Now you can use the 'urls

    def parse(self, response):

        if response.status != 200:
        # If the response status is not 200, skip processing this link and move to the next one
                self.logger.warning(f"Skipping URL {response.url} due to non-200 status code: {response.status}")
                return

        if "/noResult" in response.url:
                # Move to the next URL in the array (since it is a "noResult" page)
                self.logger.info("Skipping this URL and moving to the next one.")
                return

        item = DemoItem()

        # Find the script tag with the JSON data
        script_tag = response.xpath('//script[@id="__NEXT_DATA__"]/text()').get()

        if script_tag:
            json_content = json.loads(script_tag)

            # Assuming the relevant JSON data is under "props" -> "pageProps" in the JSON response
            page_props = json_content.get('props', {}).get('pageProps', {}).get("results",{})
        #     with open ("source", "w+") as f:
        #         f.write(str(page_props))

        productos = page_props
        for i in productos:

                # try:
                try:
                    item["brand"]= i["brand"]
                except:   item["brand"] = None
                product = item["brand"]
                if self.lista == []:
                    pass
                else:
                    if product.lower() not in self.lista:
                        continue

                # except: item["brand"]= None

                item["product"]=  i["displayName"]

                item["sku"] = i["skuId"]
                #item["_id"] = i["skuId"]#+str(load_datetime()[0])
                item["_id"] :str(uuid.uuid4())

                try:
                 item["best_price"] = float(i["prices"][1]["price"][0].replace(",",""))

                except:
                 item["best_price"] = 0
                print("#######")
                # print(item["best_price"])

                try:
                 item["list_price"] = float(i["prices"][2]["price"][0].replace(",",""))
                except:
                        item["list_price"] = 0

                try:

                 item["card_price"] = float(i["prices"][0]["price"][0].replace(",",""))
                except:item["card_price"] =0

                item["link"]=i["url"]

                try:
                 item["image"]=i["mediaUrls"][0]
                except:
                 item["image"]=str(i["mediaUrls"])

                try:
                 item["web_dsct"]=float(i["discountBadge"]["label"].replace("-","").replace("%",""))
                except:
                        item["web_dsct"]=0

                item["market"]= "saga"

                item["date"]= load_datetime()[0]
                item["time"]= load_datetime()[1]
                item["home_list"] = response.url
                item["card_dsct"] = 0

                yield item

        gc.collect()


from django.contrib import admin
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.auth import views as auth_views

from core.views import index, contact, biography, discography, album_detail, signup, user_profile, like_album, unlike_album, add_comment, delete_comment
from core.forms import LoginForm

app_name = 'core'

urlpatterns = [
    path('discography/<int:pk>/delete-comment', delete_comment, name='delete_comment'),
    path('discography/<int:pk>/add-comment', add_comment, name='add_comment'),
    path('logout/', auth_views.LogoutView.as_view(), name='logout'),
    path('album/<int:album_id>/like/', like_album, name='like_album'),
    path('album/<int:album_id>/unlike/', unlike_album, name='unlike_album'),
    path('profile/', user_profile, name='user_profile'),
    path('login/', auth_views.LoginView.as_view(template_name='core/login.html', authentication_form=LoginForm), name='login'),
    path('signup/', signup, name='signup'),
    path('discography/', discography, name='discography'),
    path('discography/<int:pk>', album_detail, name='album_detail'),
    path('biography/', biography, name='biography'),
    path('', index, name='index'),
    path('contact/', contact, name='contact'),
    path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


numbers_of_searching = 0
def find_fake_bag(bags, nums, coin):
    left, right = 0, len(bags) - 1

    while left < right:
        nums += 1
        mid = (left + right) // 2
        print("mid: ", mid, " right: ", right, " left: ", left)
        sum_of_left = sum(bags[left:mid+1])
        print("bags[left:mid+1]  ", bags[left:mid+1])
        sum_of_right = sum(bags[mid+1:right+1])
        print("bags[mid+1:right+1]   ", bags[mid+1:right+1])

        if sum_of_left < sum_of_right:
            left = mid + 1
        else:
            right = mid

    return left, nums

not_real_coin = 1.1
bags = [1.0, 1.0, 1.0, 1.0, 1.0, 1.1, 1.0, 1.0, 1.0, 1.0]
fake_bag = find_fake_bag(bags, numbers_of_searching, not_real_coin)
print(f"The fake bag is at position {fake_bag[0] + 1}\nNumber of searching: {fake_bag[1]}")


from ev3dev2.sound import Sound
from ev3dev2.motor import LargeMotor, MoveTank, MoveSteering
from ev3dev2.motor import OUTPUT_A, OUTPUT_B, OUTPUT_C, OUTPUT_D

tank = MoveTank(OUTPUT_D, OUTPUT_B)
mySnd = Sound()

print("turn in place")
mySnd.speak("Turning left in place")

tank.on_for_seconds(-90, 90, 2)

print("curve left")
mySnd.speak("Curving left")
tank.on_for_seconds(45, 80, 2)

print("curve right")
mySnd.speak("Curving right")
tank.on_for_seconds(80, 45, 2)

tank.off()


from inspect import isclass

import requests
import requests_cache

from libtimed import models

class TimedAPIClient:
    def __init__(self, token, url, api_namespace):
        self.token = token
        self.url = f"{url}/{api_namespace}/"
        self.session = requests.Session()
        self.session.headers["Authorization"] = f"Bearer {token}"
        self.session.headers["Content-Type"] = "application/vnd.api+json"
        self.cached_session = requests_cache.CachedSession(
            "libtimed", expire_after=60 * 60 * 24, use_cache_dir=True
        )
        self.cached_session.headers["Authorization"] = f"Bearer {token}"
        self.cached_session.headers["Content-Type"] = "application/vnd.api+json"
        # Models
        self.users = models.Users(self)
        self.reports = models.Reports(self)
        self.overtime = models.WorktimeBalances(self)
        self.activities = models.Activities(self)
        self.customers = models.Customers(self)
        self.tasks = models.Tasks(self)
        self.projects = models.Projects(self)
        # self.employments = models.Employments(self)

        self._type_map = {
            getattr(models, model).resource_name: getattr(models, model)
            for model in dir(models)
            if isclass(getattr(models, model))
            and issubclass(getattr(models, model), models.BaseModel)
        }


from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.screenmanager import ScreenManager, Screen, NoTransition
from kivy.uix.floatlayout import FloatLayout
from kivy.lang import Builder
from kivy.uix.textinput import TextInput
from kivy.core.window import Window
from kivy.clock import Clock
from functools import partial
import Spiral_weld_0 as sw
import serial
from urx import Robot
import math
import time

Window.fullscreen = 'auto'

class Home(Screen):
    pass

class Control(Screen):

    d = ''
    log_string = ''
    state = 0
    robot = sw.robot
    arduino = sw.arduino
    start = [1.334, -0.168, -0.030, 3.13, 0.00, 0.00]

    def __init__(self, **kwargs):
        super(Control, self).__init__(**kwargs)
        self.Build()
        print('done init')

    def Build(self):
        self.log = GridLayout(cols = 1, size_hint = (0.5, 1), pos_hint = {'x':0.5, 'y':0})

        self.rightside = TextInput(text = "CONSOLE\n\n" + self.log_string, font_size = 20)
        self.log.add_widget(self.rightside)

        self.add_widget(self.log)
        print("done building")

    def ConfirmDiameter(self):
        if self.state == 0:
            self.d = self.ids.diameter.text

            if self.d:
                try:
                    int(self.d)
                except:
                    self.Refresh("Not a valid input (no integer)", False)
                else:
                    if int(self.d) == 0:
                        self.Refresh("Not a valid input (zero input)", False)
                    else:
                        self.Refresh("The diameter is set at " + self.d + " mm\nPress 'Start grinding'\n", False)
                        self.r = int(self.d)/2
            else:
                self.Refresh("Not a valid input (no input)", False)

    def Start(self):
        print(self.log_string)
        if ("The diameter is set" in self.log_string):

            #Startup & homing
            if self.state == 0:
                sw.robot.set_analog_out(0, 0.0)
                sw.robot.set_analog_out(1, 0.0)
                sw.robot.set_tool_voltage(0)
                sw.robot.set_digital_out(1, False)
                self.Refresh("Homing\n", True)
                sw.robot.movel(self.start, vel = 1.0, acc = 1.0)
                self.state = 1
                self.Start()

            #Go to pipe
            elif self.state == 1:
#                sw.arduinocheck()
                sw.robot.movel([0, 0, -0.500, 0, 0, 0], relative = True, wait = False, vel = 0.007, acc = 1)
                Clock.schedule_interval(self.CheckForPipe,1/1000)

            #Looking for weld
            elif self.state == 2:
                sw.robot.set_analog_out(0, 0.5)
                Clock.schedule_interval(self.CheckForWeld,1/1000)

            #Looking for direction
            elif self.state == 3:
                sw.robot.movel([0, 0, 0.03, 0, 0, 0], relative = True)
                sw.robot.movel([-0.090, 0, 0, 0, 0, 0], relative = True, wait = True)
                sw.robot.movel([0, 0, -0.03, 0, 0, 0], relative = True)
                self.start_circle = sw.robot.getl()
                sw.arduinocheck()
                sw.robot.movels(sw.quartercircle(self.r, self.start_circle), wait = False)
                Clock.schedule_interval(self.WeldDirection,1/1000)

            #Set grinder on pipe
            elif self.state == 4:
                sw.robot.movel([0, 0, self.y_w/1000 + 0.090, 0, 0, 0], relative = True)
                sw.robot.movel(self.startgrinder_offset, vel = 2.0, acc = 1.0)
                sw.robot.movels(sw.grindsetup(self.r + 78, self.startgrinder_offset), wait = False)
                time.sleep(10)
                sw.robot.stop()
                sw.robot.translate_tool([0, 0, 1], vel = 0.002, acc = 1, wait = False)
                Clock.schedule_interval(self.Set,1/1000)

            #Grinding
            elif self.state == 5:
                self.Grinding()

            #Finishing and resetting process
            elif self.state == 6:
                self.Reset()

        elif ("The diameter is set" not in self.log_string and self.state == 0):
            self.Refresh("No diameter set", False)

    def Stop(self):
        if self.state != 0:
            Clock.unschedule(self.CheckForPipe)
            Clock.unschedule(self.CheckForWeld)
            Clock.unschedule(self.WeldDirection)
            Clock.unschedule(self.Set)
            sw.robot.stop()
            sw.robot.set_analog_out(0, 0.0)
            sw.robot.set_analog_out(1, 0.0)
            sw.robot.set_tool_voltage(0)
            self.Refresh("STOPPING PROCESS!\nHoming\n", True)
            sw.robot.movel([0, 0, 0.10, 0, 0, 0], relative = True, vel = 0.003, acc = 1)
            sw.robot.set_digital_out(1, False)
            self.state = 0
            self.Refresh("PROCESS STOPPED AND RESET!\nPress 'Start grinding' to restart the process \nor enter different diameter than " + self.d + "\n", True)

    def CheckForPipe(self,dt):
        print('joe')
        if "Approach pipe\n" not in self.log_string:
            self.Refresh("Approach pipe\n", True)
        if sw.switch() <= 3:
            sw.robot.stop()
            Clock.unschedule(self.CheckForPipe)
            sw.robot.movel([0, 0, -0.006, 0, 0, 0], relative = True, vel = 0.003, acc = 1)
            self.start = sw.robot.getl()
            self.startgrinder = sw.sensor_grind_coords(self.start)
            self.startgrinder_offset = sw.offset(self.startgrinder, 0, 0, 0.030)
            self.state = 2
            self.Refresh("Tool on pipe\n", True)
            self.Start()

    def CheckForWeld(self,dt):
        if "Looking for weld\n" not in self.log_string:
            self.Refresh("Looking for weld\n", True)
        if sw.induxion() <= 3:
            sw.robot.set_analog_out(0, 0)
            Clock.unschedule(self.CheckForWeld)
            self.state = 3
            self.Refresh("Weld detected\n", True)
            self.Start()

    def WeldDirection(self,dt):
        if "Finding weld direction\n" not in self.log_string:
            self.Refresh("Finding weld direction\n", True)
        if sw.induxion() <= 3:
            sw.robot.stop()
            Clock.unschedule(self.WeldDirection)
            self.welpos = sw.robot.getl()
            self.welposgrinder = sw.sensor_grind_coords(self.welpos)
            self.welposgrinder_offset = sw.offset(self.welposgrinder, 0, 0, 0.030)
            self.x_w, self.y_w, self.z_w = sw.spiralcoords(self.start, self.welpos)
            if (self.x_w >= -0.05 and self.x_w <= 0.05):
                self.state = 4
                self.Refresh("Weld is straight\n", True)
            elif self.x_w > 0.05:
                self.state = 4
                self.Refresh("Weld is spiraling\n", True)
            self.Start()

    def Set(self,dt):
        if "Tuning on pipe\n" not in self.log_string:
            self.Refresh("Tuning on pipe\n", True)
        if sw.endstop_grinder() <= 50:
            sw.robot.stop()
            Clock.unschedule(self.Set)
            sw.robot.set_digital_out(1,True)
            self.state = 5
            self.Refresh("Tool tuned\n", True)
            self.Start()

    def Grinding(self):
        if "Grinding in progress\n" not in self.log_string:
            self.Refresh("Grinding in progress\n(PRESS DEAD MAN'S SWITCH TO TURN ON TOOL AND KEEP PRESSED)\n", True)
        sw.robot.movel([0, 0, 0.04, 0, 0, 0], relative = True)#, vel = 2.0, acc = 1.0)
        sw.robot.movel(self.startgrinder_offset, vel = 2.0, acc = 1.0)
        sw.robot.movel([0, 0 + (self.x_w / 1000), 0, 0, 0, 0], relative = True, vel = 2.0, acc = 1.0)

        self.welposgrinder_offset = sw.offset(self.welposgrinder_offset, 0.03, 0, 0)
        self.startgrinder_offset = sw.offset(self.startgrinder_offset, 0.03, 0, 0)
        self.welposgrinder = sw.offset(self.welposgrinder, 0.03, 0, 0)
        self.startgrinder = sw.offset(self.startgrinder, 0.03, 0, 0)

        sw.robot.movel(self.welposgrinder_offset, vel = 2.0, acc = 1.0)

        self.welposgrinder_1 = sw.offset(self.welposgrinder, 0, 0, 0.005)
        self.startgrinder_1 = sw.offset(self.startgrinder, 0, 0, 0.005)

        self.welposgrinder_2 = sw.offset(self.welposgrinder, 0, 0, 0.002)
        self.startgrinder_2 = sw.offset(self.startgrinder, 0, 0, 0.002)

        sw.robot.set_analog_out(1, 0.5)

        sw.robot.movels(self.spiralback(self.startgrinder_1, self.welposgrinder_1, self.r + 78), vel = 0.010, acc = 0.2)#, vel = 0.005, acc = 1)
        sw.robot.movel([0.04, -((40*self.x_w)/self.z_w)/1000, ((40*self.y_w)/self.z_w)/1000, 0, 0, 0], relative = True)

        sw.robot.movel([0, 0, 0.04, 0, 0, 0], relative = True, vel = 2.0, acc = 1.0)
        sw.robot.movel([0, 0 + (self.x_w / 1000), 0, 0, 0, 0], relative = True, vel = 2.0, acc = 1.0)
        sw.robot.movel(self.welposgrinder_offset, vel = 2.0, acc = 1.0)

        sw.robot.movels(sw.spiralback(self.startgrinder_2, self.welposgrinder_2, self.r + 78), vel = 0.005, acc = 0.2)#, vel = 0.005, acc = 1)
        sw.robot.movel([0.04, -((40*self.x_w)/self.z_w)/1000, ((40*self.y_w)/self.z_w)/1000, 0, 0, 0], relative = True)

        sw.robot.movel([0, 0, 0.010, 0, 0, 0], relative = True, vel = 2.0, acc = 1.0)
        sw.robot.movel([0, 0 + (self.x_w / 1000), 0, 0, 0, 0], relative = True, vel = 2.0, acc = 1.0)
        sw.robot.movel(self.welposgrinder_offset, vel = 2.0, acc = 1.0)

        sw.robot.movels(sw.spiralback(self.startgrinder, self.welposgrinder, self.r + 78), vel = 0.010, acc = 0.2)#, vel = 0.005, acc = 1)
        sw.robot.movel([0.04, -((40*self.x_w)/self.z_w)/1000, ((40*self.y_w)/self.z_w)/1000, 0, 0, 0], relative = True)

        sw.robot.movel([0, 0, 0.04, 0, 0, 0], relative = True, vel = 2.0, acc = 1.0)

        self.state = 6
        self.Refresh("Grinding finished\n(DEAD MAN'S SWITCH CAN BE RELEASED)\n", True)
        self.Start()

    def Reset(self):
        sw.robot.set_analog_out(0, 0.0)
        sw.robot.set_analog_out(1, 0.0)
        sw.robot.set_tool_voltage(0)
        sw.robot.set_digital_out(1, False)
        self.state = 0
        self.Refresh("Everything is reset\n----------END----------", True)
        self.Refresh()

    def Refresh(self, txt, add):
        if add:
            self.log_string += txt
        else:
            self.log_string = txt
        self.clear_widgets()
        self.__init__()

class WindowManager(ScreenManager):
    pass

kv = Builder.load_file("HMI.kv")

class HMI(App):
    def build(self):
        return kv

if __name__ == "__main__":
    HMI().run()


from PIL import Image
import numpy as np
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
import os

actual_path = os.getcwd()
data_path = os.path.join(actual_path, 'data', 'estadio_guillermon_moncada.jpg')

image = Image.open(data_path)

# Convert the image to a matrix of RGB values
image = np.array(image.convert('RGB'))

height, width, _ = image.shape

features = np.zeros((height * width, 5))

# Fill the features with the RGB values and XY coordinates of the pixels of the image
for i in range(height):
    for j in range(width):
        index = i * width + j
        features[index, 0] = image[i, j, 0]
        features[index, 1] = image[i, j, 1]
        features[index, 2] = image[i, j, 2]
        features[index, 3] = i
        features[index, 4] = j

n_clusters = 10

kmeans = KMeans(n_clusters=n_clusters, random_state=42, n_init='auto').fit(features)

# Get the cluster labels assigned to each pixel
labels = kmeans.labels_

# Create a new image with the colors of the centroids of each cluster
new_image = np.zeros_like(image)
for i in range(height):
    for j in range(width):
        index = i * width + j
        label = labels[index]
        new_image[i, j, 0] = kmeans.cluster_centers_[label, 0]
        new_image[i, j, 1] = kmeans.cluster_centers_[label, 1]
        new_image[i, j, 2] = kmeans.cluster_centers_[label, 2]

plt.imshow(new_image)
plt.show()