""" Unit test functions in quickSort module. """

#===============================================================================
import unittest
import numpy as np
import quickSort as qS

#===============================================================================
class TestSwapArrayElements(unittest.TestCase):
    """ Unit test swapArrayElements. """

    def test_swap_element_2_and_5(self):
        """ Are elements 2 and 5 swapped correctly? """
        B      = [0, 1, 2, 3, 4, 5, 6, 7]
        i      = 2
        j      = 5
        BOut   = [0, 1, 5, 3, 4, 2, 6, 7]
        BPrime = qS.swapArrayElements(B, i, j)
        self.assertEqual(BOut, BPrime)

    def test_error_if_first_element_is_not_in_array(self):
        """ Is an error raised if the first swap element is not in array? """
        B      = [0, 1, 2, 3, 4, 5, 6, 7]
        i      = 9
        j      = 2
        self.assertRaises(IndexError, qS.swapArrayElements, B, i, j)

    def test_error_if_second_element_is_not_in_array(self):
        """ Is an error raised if the second swap element is not in array? """
        B      = [0, 1, 2, 3, 4, 5, 6, 7]
        i      = 2
        j      = 8
        self.assertRaises(IndexError, qS.swapArrayElements, B, i, j)

#-------------------------------------------------------------------------------
class TestPartition(unittest.TestCase):
    """ Unit test partition subroutine. """

    def test_partitioned_ascending_array(self):
        """ Ensure that the array B, an ascending sequence, is partitioned. """
        B         = [100, 1, 2, 3, 4, 5, 1000]  # Pivot element 1
        BPrime, k = qS.partition(B, 1, 5)
        self.assertEqual(B, BPrime)
        self.assertEqual(1, k)

    def test_partitioned_descending_array(self):
        """ Ensure that the array C, a descending sequence, is partitioned. """
        C          = [100, 5, 4, 3, 2, 1, 1000]  # Pivot element 5
        CPartition = [100, 1, 4, 3, 2, 5, 1000]
        CPrime, k  = qS.partition(C, 1, 5)
        self.assertEqual(CPartition, CPrime)
        self.assertEqual(5, k)

    def test_partitioned_mixed_array(self):
        """ Ensure that the array D, a mixed sequence, is partitioned. """
        D          = [3, 5, 4, 1, 2]  # Pivot element 3
        DPartition = [2, 1, 3, 5, 4]
        DPrime, k  = qS.partition(D, 0, 4)
        self.assertEqual(DPartition, DPrime)
        self.assertEqual(2, k)

    def test_error_raised_l_out_of_range(self):
        """ Ensure error is raised if l is out of range of A. """
        B = []
        # NB check type of error; syntax for below? Might be (B, 0, 0)
        self.assertRaises(IndexError, qS.partition, B, 0, 0)

    def test_error_raised_r_out_of_range(self):
        """ Ensure error is raised if r is out of range of A. """
        B = [100, 1, 2, 3, 4, 5, 1000]
        # Check type of error and syntax
        self.assertRaises(IndexError, qS.partition, B, 0, 7)

#-------------------------------------------------------------------------------
class TestSelectPivot(unittest.TestCase):
    """ Unit test selectPivot subroutine. """

    def test_given_pivot_selected(self):
        """ Check correct pivot is chosen.

            This utilises setting the random seed twice.
        """
        B = [100, 1, 2, 3, 4, 5, 1000]
        np.random.seed(936231120)
        l = 1
        r = 5

        i    = int(round(np.random.rand() * (r - l) + l))
        # Swap elements
        temp = B[i]
        B[i] = B[l]
        B[l] = temp

        np.random.seed(936231120)
        BPrime = qS.selectPivot(B, l, r)

        self.assertEquals(B, BPrime)

    def test_error_raised_l_out_of_range(self):
        """ Ensure error is raised if l is out of range of A. """
        B = [100, 1, 2, 3, 4, 5, 1000]
        l = 9
        r = 10
        # Check error type, syntax for below
        self.assertRaises(IndexError, qS.selectPivot, B, l, r)

    def test_error_raised_r_out_of_range(self):
        """ Ensure error is raised if r is out of range of A. """
        np.random.seed(19552314)
        B = [100, 1, 2, 3, 4, 5, 1000]
        l = 1
        r = 8
        # Check error type, syntax for below
        self.assertRaises(IndexError, qS.selectPivot, B, l, r)

#-------------------------------------------------------------------------------
class TestQuickSort(unittest.TestCase):
    """ Unit test quickSort subroutine. """

    def test_base_case(self):
        """ Does providing an input array of length 1 return the same array? """
        B = [1]
        self.assertEqual(B, qS.quickSort(B, 0, 0))

    def test_array_of_length_5(self):
        """ Does an array of length 5 get correctly sorted? """
        D      = [3, 5, 4, 1, 2]
        DPrime = [1, 2, 3, 4, 5]
        self.assertEqual(DPrime, qS.quickSort(D, 0, 4))

    def test_if_l_out_of_array_array_returned(self):
        """ Is the original array returned if l is outside of array? """
        D = [3, 5, 4, 1, 2]
        self.assertEqual(D, qS.quickSort(D, 8, 4))

    def test_error_if_r_in_array(self):
        """ Is an error raised if r outside of array? """
        D      = [3, 5, 4, 1, 2]
        self.assertRaises(IndexError, qS.quickSort, D, 0, 6)

#===============================================================================
if __name__ == '__main__':
    unittest.main()


#!/usr/bin/python3

"""
This test checks that we can assemble and disassemble all the instructions
found in `arm_test.dis` and similar dumps obtained via `objdump`
"""

import re
import sys
from typing import List

from CpuA32 import symbolic
from CpuA32 import opcode_tab as a32

def FixupAliases(opcode: a32.Opcode, name: str, ops: List[str]) -> str:
    if name[:3] in ["lsl", "lsr", "asr", "ror"]:
        # lsrs	r3, r3, #7  -> movs  r3, r3, lsr #7
        ops.insert(-1, name[:3])
        return "mov" + name[3:]

    if a32.OPC_FLAG.MULTIPLE in opcode.classes:
        # unsplit '{r0', 'r1}'
        while not ops[-1].startswith("{"):
            end = ops.pop(-1)
            ops[-1] = ops[-1] + "," + end

        if "push" in name:
            ops.insert(0, "sp")
            return name.replace("push", "stmdb")
        elif "pop" in name:
            ops.append("sp")
            return name.replace("pop", "ldmia")

        # ia suffix if no suffix is specified
        start = 1 if name[0] == "v" else 0
        if name[start + 3: start + 5] not in {"ia", "ib", "da", "db"}:
            name = name[:start + 3] + "ia" + name[start + 3:]
        if name.startswith("ldm") or name.startswith("vldm"):
            # move loadee to end of ops
            loadee = ops.pop(0)
            ops.append(loadee)
        return name

    if name.startswith("strex"):
        storee = ops.pop(1)
        ops.append(storee)
    elif name.startswith("str") or name.startswith("vstr"):
        storee = ops.pop(0)
        ops.append(storee)
    return name

# range looks like: {d8-d10} or  {d1}
def _GetFirstRegFromRange(range):
    token = range[1:-1].split("-")
    assert len(token) <= 2, f"{token}"
    return token[0]

def _GetWidthFromRange(range) -> int:
    token = range[1:-1].split("-")
    if len(token) == 1:
        return 1
    assert len(token) == 2
    return 1 + int(token[1][1:]) - int(token[0][1:])

def _GetRegListFromMask(reg_mask_str: str) -> str:
    if reg_mask_str.startswith("reglist:"):
        reg_mask_str = reg_mask_str[8:]
    reg_mask = int(reg_mask_str, 0)
    regs = [a32.REG(x).name for x in range(16) if reg_mask & (1 << x)]
    expr = "{%s}" % (",".join(regs))
    return expr

def OperandsMatch(opcode: a32.Opcode, objdump_name: str,
                  objdump_ops: List[str], std_ops: List[str]) -> bool:
    j = 0
    for i, (ok, op) in enumerate(zip(opcode.fields, std_ops)):
        objdump_op = objdump_ops[j] if j < len(objdump_ops) else ""
        if objdump_op.startswith("#"):
            objdump_op = objdump_op[1:]

        # This is a bit hackish and incomplete
        if objdump_op.startswith("-") and a32.OPC_FLAG.ADDR_DEC in opcode.classes:
            # that is a bit weak
            assert ok in {a32.OK.REG_0_3, a32.OK.IMM_0_7_TIMES_4, a32.OK.IMM_0_11, a32.OK.IMM_0_3_8_11}
            objdump_op = objdump_op[1:]

        if op == objdump_op:
            j += 1
        elif (ok is a32.OK.PRED_28_31 and
              op == "al" or objdump_name.endswith(op)):
            continue
        elif ok in {a32.OK.IMM_0_7_TIMES_4, a32.OK.IMM_7_11,
                    a32.OK.IMM_0_11, a32.OK.IMM_0_3_8_11,
                    a32.OK.IMM_10_11_TIMES_8} and op == "0":
            continue
        elif ok is a32.OK.SHIFT_MODE_5_6 and op == "lsl":
            continue
        elif a32.OPC_FLAG.MULTIPLE in opcode.classes:
            if a32.OPC_FLAG.VFP in opcode.classes:
                if ok in {a32.OK.DREG_12_15_22, a32.OK.SREG_12_15_22}:
                    if _GetFirstRegFromRange(objdump_op) == op:
                        continue
                elif ok in {a32.OK.REG_RANGE_0_7, a32.OK.REG_RANGE_1_7}:
                    if f"regrange:{_GetWidthFromRange(objdump_op)}" == op:
                        j += 1
                        continue
            else:
                if _GetRegListFromMask(op) == objdump_op:
                    j += 1
                    continue

            return False

        else:
            return False
    return True

def HandleOneInstruction(count: int, line: str,
                         data: int,
                         actual_name: str, actual_ops: List):
    ins = a32.Disassemble(data)
    assert ins is not None, f"cannot disassemble [{count}]: {line}"
    assert ins.opcode is not None and ins.operands is not None, f"unknown opcode {line}"
    data2 = a32.Assemble(ins)
    assert data == data2, f"disass mismatch [{ins.opcode.name}] {data:x} vs {data2:x}"
    actual_name = FixupAliases(ins.opcode, actual_name, actual_ops)
    if not actual_name.startswith(ins.opcode.official_name):
        print("BAD NAME", ins.opcode.name, actual_name, line, end="")

    name, operands_str = symbolic.InsSymbolize(ins)
    if not OperandsMatch(ins.opcode, actual_name, actual_ops, operands_str):
        print(f"OPERANDS differ {operands_str} {actual_ops} in line  {line}", end="")

    ins2 = symbolic.InsFromSymbolized(name, operands_str)
    assert tuple(ins.operands) == tuple(ins2.operands), f"{ins.operands} vs {ins2.operands}"

def main(argv):
    for fn in argv:
        with open(fn) as fp:
            # actual_XXX: derived from the text assembler listing
            # expected_XXX: derived from decoding the `data`
            count = 0
            for line in fp:
                count += 1
                token = line.split(None, 2)
                data = int(token[0], 16)
                actual_name = token[1]
                actual_ops = []
                if len(token) == 3:
                    # Note this removes all the address mode syntax
                    # so we lose a bit of fidelity
                    actual_ops = [x for x in re.split("[, \t\n\[\]!]+", token[2]) if x]
                HandleOneInstruction(
                    count, line, data, actual_name, actual_ops)

if __name__ == "__main__":
    # import cProfile
    # cProfile.run("main(sys.argv[1:])")
    main(sys.argv[1:])


from odoo.exceptions import UserError

from . import base

class PartnerMailListWizardCase(base.BaseCase):
    def test_add_to_mail_list(self):
        wizard = self.env["partner.mail.list.wizard"].create(
            {"mail_list_id": self.mailing_list.id}
        )
        wizard.partner_ids = [self.partner.id]
        wizard.add_to_mail_list()
        contacts = self.env["mailing.contact"].search(
            [("partner_id", "=", self.partner.id)]
        )
        cont = contacts.filtered(lambda r: wizard.mail_list_id in r.list_ids)
        self.assertEqual(len(cont), 1)
        self.check_mailing_contact_partner(cont)
        # This line does not create a new contact
        wizard.add_to_mail_list()
        self.assertEqual(len(self.partner.mass_mailing_contact_ids), 1)
        self.assertEqual(
            self.partner.mass_mailing_contact_ids.list_ids, self.mailing_list
        )

        list_2 = self.create_mailing_list({"name": "Test Add to List"})
        wizard.mail_list_id = list_2
        wizard.add_to_mail_list()
        self.assertEqual(len(self.partner.mass_mailing_contact_ids), 1)
        self.assertEqual(
            self.partner.mass_mailing_contact_ids.list_ids, self.mailing_list | list_2
        )

        partner = self.env["res.partner"].create({"name": "No email partner"})
        wizard.partner_ids = [partner.id]
        with self.assertRaises(UserError):
            wizard.add_to_mail_list()


from handDetectorModule import *
import cv2

cap = cv2.VideoCapture(0)
hands=HandDetector(conf=0.6,tracking_conf=0.6,mode=True)

while True:
    ret,frame=cap.read()
    frame=cv2.flip(frame,1)
    if frame is None:
        continue
    frame,mask=hands.DetectHand(frame)
    index=hands.handPostion(frame,0)
    if len(index)>0:

        r=hands.isup(frame,[0])
        c=sum(r.values())-1
        cv2.putText(mask,str(c),org=(50,50),fontFace=cv2.FONT_HERSHEY_SIMPLEX,thickness=3,fontScale=2,color=(32,255,2))

    cv2.imshow('mask',mask)

    if cv2.waitKey(1) & 0xFF == ord('q'):
                break
cap.release()
cv2.destroyAllWindows()


import tensorflow as tf
from tensorflow.keras import layers, models
def create_context_module(input_tensor):
    # Define the dilation rates for each layer
    dilation_rates = [(1, 1), (1, 1), (1, 1), (2, 4), (4, 8), (8, 12), (12, 16),
                                  (16, 20), (20, 24), (24, 28), (28, 32), (32, 1), (1, 1)]

    # Input
    x = input_tensor

    for i, dilation in enumerate(dilation_rates):
        # Add dilated convolution layers
        x = layers.Conv2D(96, (3, 3), padding='same', dilation_rate=dilation)(x)
        x = layers.ELU()(x)

        # Add spatial dropout to all but the last layer
        if i < 12:
            x = layers.SpatialDropout2D(0.20)(x)

        # Reduce the number of feature maps in the final layer
        x = layers.Conv2D(16, (3, 3), padding='same', dilation_rate=dilation_rates[-1])(x)
        x = layers.ELU()(x)

    # Return the model
    return x

def create_model():
    inputs = layers.Input(shape=(600, 600, 8))

    # 1st and 2nd Convolutional layers
    x = layers.Conv2D(8, (3, 3), strides=(1, 1), padding='same')(inputs)
    x = layers.ELU()(x)
    x = layers.Conv2D(8, (3, 3), strides=(1, 1), padding='same')(x)
    x = layers.ELU()(x)

    # First Max Pooling
    x = layers.MaxPooling2D(pool_size=(2, 2), strides=(2, 2))(x)

    # 3rd, 4th, and 5th Convolutional layers
    for _ in range(3):
        x = layers.Conv2D(16, (3, 3), strides=(1, 1), padding='same')(x)
        x = layers.ELU()(x)

    # Second Max Pooling
    x = layers.MaxPooling2D(pool_size=(2, 2), strides=(2, 2))(x)

    # Context Module (implement as described in Table 1)
    x = create_context_module(x)

    # Max Unpooling
    x = tf.keras.layers.UpSampling2D(size=(2, 2))(x)

    # 10th, 11th, and 12th Convolutional layers
    for filters in [16, 16, 8]:
        x = layers.Conv2D(filters, (3, 3), strides=(1, 1), padding='same')(x)
        x = layers.ELU()(x)

    # Second Max Unpooling
    x = tf.keras.layers.UpSampling2D(size=(2, 2))(x)

    # Final Convolutional layers
    x = layers.Conv2D(8, (3, 3), strides=(1, 1), padding='same')(x)
    x = layers.ELU()(x)
    x = layers.Conv2D(8, (3, 3), strides=(1, 1), padding='same')(x)
    x = layers.ELU()(x)
    x = layers.Conv2D(2, (3, 3), strides=(1, 1), padding='same')(x)
    x = layers.ELU()(x)

    # Softmax
    outputs = layers.Softmax()(x)
    model = models.Model(inputs=inputs, outputs=outputs)

    # Print model summary
    model.summary()
    return model

if __name__ == "__main__":
    model = create_model()


import tkinter as tk
import threading
import time
from random_words import random_words

class TypingTest:

    def __init__(self):

        self.window = tk.Tk()
        self.window.title("Typing Speed App")
        self.window.geometry("800x600")
        self.window.config(bg="black")

        self.title = tk.Label(self.window, text="Typing Speed App")
        self.title.config(font=("Arial", 25))

        self.frame = tk.Frame(self.window, bg="black")

        self.text_to_type = tk.Label(self.frame, fg="white", bg="black", text=random_words(),
                                     wraplength=500, justify="center", font=("Consolas", 16))
        self.text_to_type.grid(row=0, column=0, columnspan=2, padx=5, pady=5)

        self.input_field = tk.Entry(self.frame, width=45, font=("Consolas", 20))
        self.input_field.grid(row=1, column=0, columnspan=2, padx=5, pady=15)
        self.input_field.bind("<KeyPress>", self.start)

        self.wpm_field = tk.Label(self.frame, bg="black", fg="white", text="Speed: 0 WPM", font=("Consolas", 16))
        self.wpm_field.grid(row=2, column=0, columnspan=2, padx=5, pady=15)

        self.high_score_field = tk.Label(self.frame, bg="black", fg="white", text="Highest score: 0 WPM", font=("Consolas", 16))
        self.high_score_field.grid(row=3, column=0, columnspan=2, padx=5, pady=15)

        self.reset_button = tk.Button(self.frame, bg="black", fg="white", text="Reset", command=self.reset)
        self.reset_button.grid(row=4, column=0, columnspan=2, padx=5, pady=15)

        self.frame.pack(expand=True)

        self.counter = 0
        self.running = False
        self.wpm_count = tk.StringVar()
        self.read_highscore()
        self.window.mainloop()

    def start(self, event):
        if not self.running:
            if not event.keycode in [16, 17, 18]:
                self.running = True
                timing = threading.Thread(target=self.timer)
                timing.start()
        if not self.text_to_type.cget('text').startswith(self.input_field.get()):
            self.input_field.config(fg="red")
        else:
            self.input_field.config(fg="black")
        if self.input_field.get() == self.text_to_type.cget('text')[:-1]:
            self.running = False
            self.input_field.config(fg="green")

    def timer(self):
        while self.running:
            time.sleep(0.1)
            self.counter += 0.1
            wpm = round(len(self.input_field.get()) / 5 / self.counter * 60)
            self.wpm_field.config(text=f"Speed: {wpm} WPM")

            try:
                with open("high_score.txt", "r") as file:
                    self.previous_highscore = file.read()
                    self.high_score_field.config(text=f"Highest score: {self.previous_highscore} WPM")
            except IOError:
                file = open("high_score.txt", "w+")
                file.write('%d' % 0)
                self.previous_highscore = file.read()

        if wpm > int(self.previous_highscore):
            print(wpm)
            print(self.previous_highscore)
            with open("high_score.txt", "w") as file:
                file.write('%d' % wpm)
                self.high_score_field.config(text=f"Highest Score: {wpm} WPM")

    def reset(self):
        self.running = False
        self.counter = 0
        self.wpm_field.config(text="Speed: 0 WPM")
        self.text_to_type.config(text=random_words())
        self.input_field.delete("0", tk.END)

    def read_highscore(self):
        try:
            with open("high_score.txt", "r") as file:
                self.previous_highscore = file.read()
                self.high_score_field.config(text=f"Highest score: {self.previous_highscore} WPM")
        except IOError:
            file = open("high_score.txt", "w+")
            file.write('%d' % 0)
            self.previous_highscore = file.read()

TypingTest()


import serial  # pyserial is required
from micropyGPS import MicropyGPS #https://github.com/inmcm/micropyGPS

gps = MicropyGPS()
uart = serial.Serial("/dev/ttyS0", baudrate=9600, timeout=30)

x1 = gps.longitude[1]
y1 = gps.latitude[1]

x2 = float(input("Enter Latitude"))
y2 = float(input("Enter Longitude"))

while 1:
    sent = uart.readline().decode('utf-8')
    print(sent)
    for x in sent:
        gps.update(x)
    if gps.latitude[1] <= 35:
    	print("test")

    #print("fix_type 1 means no fix: ",gps.fix_type)
    print("lat " ,gps.latitude)
    print("long " ,gps.longitude)
    print("speed ", gps.speed)
    #print("satellites_visible " ,gps.satellites_visible())
    #print("direction ", gps.compass_direction())


'''
https://leetcode.com/problems/linked-list-cycle-ii/

Time: O(N) since we travel all nodes
Space: O(1)

Hint:
    - Use Floyd's hare and tortoise algorithm,
      where there is one pointer will be faster (.next.next) and another with normal pace (.next)
'''

from typing import *

class ListNode:
    def __init__(self, val):
        self.val = val
        self.next = None

class Solution:
    '''
    implement hare and tortoise race in get_intersect function
    '''
    def get_intersect(self, head: Optional[ListNode]) -> Optional[ListNode]:
        tortoise = head
        hare = head

        while hare and hare.next:
            hare = hare.next.next
            tortoise = tortoise.next

            if hare == tortoise:
                return tortoise

        return None

    def detect_cycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if not head:
            return None

        #get the intersect node from hare and tortoise race
        intersect = self.get_intersect(head)
        if not intersect:
            return None

        #walktrough between intersect and head, if the pointers meet, it is a cycle
        pointer_1 = intersect
        pointer_2 = head
        while pointer_1 != pointer_2:
            pointer_1 = pointer_1.next
            pointer_2 = pointer_2.next

        return pointer_1

import unittest

class TestProgram(unittest.TestCase):
    def test_program1(self):
        head = ListNode(3)
        head.next = ListNode(4)
        head.next.next = head

        solution = Solution()

        result = head

        #print(result, solution.detect_cycle(head))

        self.assertEqual(solution.detect_cycle(head), result)

    def test_program2(self):
        head = ListNode(1)
        head.next = ListNode(2)
        head.next.next = ListNode(3)
        head.next.next.next = ListNode(4)
        head.next.next.next.next = head.next.next

        solution = Solution()

        result = head.next.next

        #print(result, solution.detect_cycle(head))

        self.assertEqual(solution.detect_cycle(head), result)

    def test_program3(self):
        head = ListNode(1)
        head.next = ListNode(2)
        head.next.next = ListNode(3)

        solution = Solution()

        result = None

        #print(result, solution.detect_cycle(head))

        self.assertEqual(solution.detect_cycle(head), result)

if __name__ == '__main__':
    unittest.main()


"""
Vault inventory reader plugin.
"""
import base64
import ansible_deployment.inventory_plugins.helpers.vault as vault_helpers
import os
from pathlib import Path
from ansible_deployment.inventory_plugins.inventory_plugin import InventoryPlugin
from hvac import exceptions as vault_exceptions

class VaultReader(InventoryPlugin):
    """
    VaultReader InventoryPlugin class.
    """

    name = "vault"

    def read_secret(self, secret, fallback_value=None, template=None):
        """
        Reads a secret from vault.

        Arguments:
            secret (str): Vault secret path.
            fallback_value (any): Fallback value if no secret is stored.
            template (str): Vault template path.

        Returns:
            any: Stored secret.
        """
        vault_client, error = vault_helpers.init_vault_client()

        if error is not None:
            raise Exception(error)

        vault_path = f"ansible-deployment/{self.deployment_name}/{secret}"
        vault_template_path = f"ansible-deployment/{template}/{secret}"
        deployment_secret = None
        template_secret = None

        if template is not None:
            try:
                if secret == 'deployment_key':
                    template_secret = vault_client.secrets.kv.read_secret_version(path=vault_template_path)[
                        "data"
                    ]["data"]["data"]["data"]
                else:
                    template_secret = vault_client.secrets.kv.read_secret_version(path=vault_template_path)[
                        "data"
                    ]["data"]["data"]
            except vault_exceptions.InvalidPath:
                template_secret = None

        try:
            if secret == 'deployment_key':
                deployment_secret = vault_client.secrets.kv.read_secret_version(path=vault_path)[
                    "data"
                ]["data"]["data"]["data"]
            else:
                deployment_secret = vault_client.secrets.kv.read_secret_version(path=vault_path)[
                    "data"
                ]["data"]["data"]
        except vault_exceptions.InvalidPath:
            deployment_secret = None

        if template_secret is not None and deployment_secret is None:
            deployment_secret = template_secret
        elif template_secret is None and deployment_secret is None:
            deployment_secret = fallback_value
        return deployment_secret

    def update_inventory(self):
        template = os.getenv('VAULT_TEMPLATE')
        self.hosts = self.read_secret("hosts", fallback_value=dict(), template=template)
        self.deployment_key = self.read_secret("deployment_key", template=template)
        if self.deployment_key is not None:
            self.deployment_key = base64.decodebytes(self.deployment_key.encode("ascii"))
        self.ssh_keypair.private_key = self.read_secret("ssh_private_key", template=template)
        self.ssh_keypair.public_key = self.read_secret("ssh_public_key", template=template)
        self.ssh_keypair.private_key_path = Path(".ssh/id_rsa", template=template)
        self.ssh_keypair.public_key_path = Path(".ssh/id_rsa.pub", template=template)

        for group in self.groups + ["all"]:
            secret_name = f"group_vars/{group}"
            self.group_vars[group] = self.read_secret(secret=secret_name,
                                                      fallback_value=dict(),
                                                      template=template)

        if "all" in self.hosts and "hosts" in self.hosts["all"]:
            for host in [*self.hosts["all"]["hosts"]]:
                secret_name = f"host_vars/{host}"
                host_vars = self.read_secret(secret=secret_name,
                                             fallback_value=dict(),
                                             template=template)
                self.host_vars[host] = host_vars
                self.all_hosts[host] = host_vars


#!/usr/bin/env python3

from tkinter import Tk, Label, Frame, Button, Menu, PhotoImage, StringVar, IntVar, Radiobutton
from time import sleep

# Create the root window with title and size
root = Tk()
root.title('Hello World')
root.geometry('700x400')
# Create window logo
win_icon = PhotoImage(file = "Rlogo.png")
root.iconphoto(False, win_icon)

# Define a menu
my_menu = Menu(root)
root.config(menu=my_menu)
# Create Menu Items
file_menu = Menu(my_menu, tearoff=0)
my_menu.add_cascade(label='File', menu=file_menu)
##file_menu.add_command
file_menu.add_separator()
file_menu.add_command(label='Exit', command=root.quit)

# Create the label to display the result
my_label = Label(root)

# Create Radio Button function
def radio():
    if v.get() not in [1,2]:
        return
    if my_label.winfo_exists():
        my_label.pack_forget()
    my_label['text'] = f'You clicked button {v.get()}'
    my_label.pack(pady=10)

def clear_selection():
    if my_label.winfo_exists():
        my_label.pack_forget()
    my_label['text'] = 'Selection Cleared'
    v.set(0)
    my_label.pack(pady=10)

# Radio Buttons
v = IntVar(0)

rbutton_1 = Radiobutton(root, text='One', variable=v, value=1, command=radio)
rbutton_2 = Radiobutton(root, text='Two', variable=v, value=2, command=radio)
rbutton_1.pack()
rbutton_2.pack()

my_button = Button(root, text='Clear Selection', command=clear_selection)
my_button.pack()

root.mainloop()


from flask_restful import Resource, reqparse, fields, marshal_with, abort
from flask_jwt_extended import (create_access_token, create_refresh_token, jwt_required, jwt_refresh_token_required, get_jwt_identity, get_raw_jwt)
from app import db
from app.models import User, RevokedToken, Client
from datetime import datetime,timedelta
import time

post_parser = reqparse.RequestParser()
post_parser.add_argument('username', location='json', required=True)
post_parser.add_argument('password', location='json',  required=True)
class Auth(Resource):
	def post(self):
		args = post_parser.parse_args()
		user = User.query.filter(User.username == args.username, User.activo == 1).first()
		if (user):
			if(user.check_password(args.password)):
				last = user.ultimo_acceso
				user.ultimo_acceso = datetime.utcnow()
				db.session.commit()
				expires = timedelta(days=1)
				access_token = create_access_token(identity = args.username, expires_delta=expires)
				refresh_token = create_refresh_token(identity = args.username)
				expiredToken = datetime.now() + expires
				return {
					'user':{
						'id': user.id,
						'nombre': user.nombre,
						'apellido': user.apellido,
						'email': user.email,
						'ultimo_acceso': last.strftime("%d/%m/%Y %H:%M:%S"),
						'puntaje': user.puntaje,
						'role':user.rols.descripcion
					},
					'access_token':access_token,
					'refresh_token':refresh_token,
					'expired_token': time.mktime(expiredToken.timetuple())
				}, 200
		abort(404, message="You username {} and/or password {} is incorrect, please try again".format(args.username, args.password))

class TokenRefresh(Resource):
		@jwt_refresh_token_required
		def post(self):
				current_user = get_jwt_identity()
				expires = timedelta(days=1)
				access_token = create_access_token(identity = current_user, expires_delta=expires)
				expiredToken = datetime.now() + expires
				return {
					'access_token': access_token,
					'expired_token': time.mktime(expiredToken.timetuple())
				},200

class LogoutAccess(Resource):
		@jwt_required
		def post(self):
				jti = get_raw_jwt()['jti']
				try:
						revoked_token = RevokedToken(jti = jti)
						revoked_token.add()
						return {'message': 'Access token has been revoked'},200
				except:
					return {'message': 'Something went wrong'}, 500

class LogoutRefresh(Resource):
		@jwt_refresh_token_required
		def post(self):
				jti = get_raw_jwt()['jti']
				try:
						revoked_token = RevokedToken(jti = jti)
						revoked_token.add()
						return {'message': 'Refresh token has been revoked'}
				except:
						return {'message': 'Something went wrong'}, 500


import gym
from gym_vision import envs
import matplotlib.pyplot as plt

env_names = [k for k in envs.custom_envs.keys() if 'NV' not in k]

for env_name in env_names:
    env = gym.make(env_name)
    env.reset()
    for _ in range(20):
        obs,_,_,_ = env.step(env.action_space.sample())

    plt.figure()
    plt.imshow(obs)
    plt.savefig('docs/%s.png'%env_name)

for env_name in env_names:
    print("""
**%s**
![Alt text](docs/%s.png?raw=true "%s")"""%(env_name,env_name,env_name))


import numpy as np
from qutip import *
import matplotlib.pyplot as plt
from matplotlib import interactive
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits import mplot3d
from pathlib import Path
import math
from scipy.optimize import curve_fit
from Funcs import *

global RECALC

RECALC = False
# RECALC = True

#variables

N=40

omega_r_tilde_vec   = np.array([1])*10**(-3) *2*np.pi
kappa_vec = np.array([20,40,80,160,240])*10**(-6)*2*np.pi #20,10##  80,10,20,40 ,10,20,80,160
g=5*10**(-6)*2*np.pi   ## 5, 2.5, 1,0.5

resolution=  300000
det_vec_0 =np.linspace(0.5,8,25)*100
det_vec_add1 =np.linspace(8,8.1,3)*100
det_vec_add2 =np.linspace(8.1,9.5,5)*100
det_vec=np.concatenate([det_vec_0,det_vec_add1,det_vec_add2[0:-2]])

plt.rcParams["mathtext.fontset"]="cm"

gamma=0*2*np.pi
n=0

i=0
markers_vec = ['*','^','o','s','D']
for kappa in kappa_vec:
    for omega_r_tilde in omega_r_tilde_vec:
        PhotonNumber_vec =[]
        Analytic =[]
        r_vec = np.linspace(0.8,1.2,25)
        for r in r_vec:
            l=omega_r_tilde*np.tanh(2*r)
            print('Probe r is ' ,r)
            PhotonNumber_vec.append(Photon_Number(N,kappa,g, omega_r_tilde,r,gamma,0))
            Analytic.append(2*l**2/(4*omega_r_tilde**2 + kappa**2-4*l**2 ))
        plt.plot(r_vec,PhotonNumber_vec,linewidth=1,marker=markers_vec[i],label= r'$\kappa=$ {:.0f}'.format(kappa*10**6/(2*np.pi)))
    i=i+1

plt.ylabel(r'$\left<a^\dagger a\right>$',fontsize='24')
plt.xlabel(r'$r$',fontsize='24')
plt.tick_params(axis='x', labelsize=18 )
plt.tick_params(axis='y', labelsize=18 )
# plt.grid(b=True,linestyle='dotted',linewidth=1)
# plt.legend()
fig = plt.gcf()
fig.set_size_inches(6,4)
fig.set_tight_layout(True)
plt.show()


from __future__ import print_function, division
import os
import torch
import pandas as pd
import numpy as np

from torch.utils.data import Dataset, DataLoader
import torchaudio
import ctypes
import multiprocessing as mp

# Ignore warnings
import warnings
warnings.filterwarnings("ignore")

class TimitDataset(Dataset):
    """Timit dataset."""

    def __init__(self, csv_file, root_dir, pre_epmh, num_ceps, n_fft, frame_size, frame_shift):
        """
        Args:
            csv_file (string): Path to the csv file with annotations.
            root_dir (string): Directory with all the audio.
            transform (callable, optional): Optional transform to be applied
                on a sample.
        """
        path = os.path.join(root_dir, csv_file)
        self.audio_frame = pd.read_csv(os.path.join(root_dir, csv_file))
        self.audio_frame = self.audio_frame[self.audio_frame['is_converted_audio'] == True]

        self.root_dir = root_dir
        #self.transform = transform

        self.use_cache = False
        self.cache = {}
        self.pre_emph = pre_epmh
        self.num_ceps = num_ceps
        self.n_fft = n_fft
        self.frame_size = frame_size
        self.frame_shift = frame_shift
        self.phones = ["b", "d", "g", "p", "t", "k", "dx", "q",
                  "jh", "ch", "s", "sh", "z", "zh", "f", "th",
                  "v", "dh", "m", "n", "ng", "em", "en", "eng",
                  "nx", "l", "r", "w", "y", "hh", "hv", "el",
                  "iy", "ih", "eh", "ey", "ae", "aa", "aw", "ay",
                  "ah", "ao", "oy", "ow", "uh", "uw", "ux", "er",
                  "ax", "ix", "axr", "ax-h", "pau", "epi",
                  # closure portion of stops
                  "bcl", "dcl", "gcl", "pcl", "tcl", "kcl",
                  # silence
                  "h#"]
        self.fullPhones2int = dict([(key,val) for val,key in enumerate(self.phones)])
        self.mergedPhones2int = {'iy': 0, 'ih': 1, 'eh': 2, 'ae': 3, 'ix': 4, 'ax': 5, 'ah': 6, 'uw': 7, 'ux': 7,
                                 'uh': 8, 'ao': 9, 'aa': 10, 'ey': 11, 'ay': 12, 'oy': 13, 'aw': 14, 'ow': 15,
                                 'l': 16, 'el': 17, 'r': 18, 'y': 19, 'w': 20, 'er': 21, 'axr': 21,
                                 'm': 22, 'em': 22, 'n': 23, 'nx': 23, 'en': 24, 'ng': 25, 'eng': 25,
                                 'ch': 26, 'jh': 27, 'dh': 28, 'b': 29, 'd': 30, 'dx': 31, 'g': 32,
                                 'p': 33, 't': 34, 'k': 35, 'z': 36, 'zh': 37, 'v': 38, 'f': 39,
                                 'th': 40, 's': 41, 'sh': 42, 'hh': 43, 'hv': 43,
                                 'pcl': 44, 'tcl': 44, 'kcl': 44, 'qcl': 44, 'bcl': 45,
                                 'dcl': 45, 'gcl': 45, 'epi': 46, 'sil': 47, 'h#': 47, '#h': 47, 'pau': 47, 'q': 48, 'ax-h': 49}
        self.num_labels = max(self.mergedPhones2int.values()) + 1
        self.max_length = 777

    def __len__(self):
        return len(self.audio_frame)

    def __getitem__(self, idx):
        '''args: idx of data sample
            operation: extracts wav audio and phn file (phone transcription) of sample, enframes
            audio and returns with 13 MFCC coefficients, computes correct phoneme for each frame
            and one-hot encodes a target num_frames x num_phones
            out: sample, target'''
        if torch.is_tensor(idx):
            idx = idx.tolist()

        path = os.path.join(self.root_dir, 'data',
                            self.audio_frame.iloc[idx]['path_from_data_dir'])
        #print(path)
        path = os.path.splitext(path)[0]
        path = os.path.splitext(path)[0]

        audio_name = path + '.WAV.wav'
        #print("audio", audio_name)

        audio, self.sample_rate = torchaudio.load(audio_name)
        phonemes_name = path + '.PHN'
        #print('phonemes: ', phonemes_name)
        with open(phonemes_name, 'r') as phonemes_file:
            start = []
            stop = []
            phonemes = []
            chunks = []
            number_of_frames = []
            frame_labels = []
            lines = phonemes_file.readlines()
            last = lines[-1]
            for l in lines:
                phoneme = l.strip().split()
                start.append(int(phoneme[0]))
                stop.append(int(phoneme[1]))
                if l == last:
                    phoneme[1] = audio.shape[1]
                chunk = int(phoneme[1]) - int(phoneme[0])
                chunks.append(int(phoneme[1]) - int(phoneme[0]))
                num_frames = (chunk/self.sample_rate) / 0.01
                number_of_frames.append(num_frames)
                if num_frames < 1:
                    frame_labels.append(phoneme[2])
                else:
                    frame_labels += [phoneme[2]]*round(num_frames)
                phonemes.append(phoneme[2])

        '''for i in range(len(phonemes)):
            print("start {} stop {} phoneme {} number of frames {}".format(start[i], stop[i], phonemes[i], number_of_frames[i]))
        '''

        sample = self.get_MFCC(audio)
        pad = self.max_length - sample.shape[0]
        #torch.nn.functional.pad(sample, (0, 0, 0, 10))

        frame_labels = frame_labels[:sample.shape[0]]
        if len(frame_labels) < sample.shape[0]:
            pad = sample.shape[0] - len(frame_labels)
            frame_labels += ['h#']*pad

        encoded_phones = []
        #for phone in frame_labels:
         #   encoded_phones.append(self.getPhoneCode(phone))
        #targets = torch.tensor([self.oneHot(self.num_labels, self.getPhoneCode(phone)) for phone in frame_labels] , dtype=torch.float64)
        '''try without one hot encoding'''
        targets = torch.tensor([self.getPhoneCode(phone) for phone in frame_labels])
        #targets = torch.nn.utils.rnn.pad_packed_sequence(targets, total_length=777)
        #print(targets.shape)
        #sample = {'audio': sample, 'targets': targets}
        return sample, targets

    def getPhoneCode(self, phone):
        return self.mergedPhones2int[phone]

    def oneHot(self, size, idx):
        return np.eye(size)[idx]

    def get_MFCC(self, sample):

        #frame_length = self.n_fft / self.sample_rate * 1000.0
        #frame_shift = frame_length / 2.0

        params = {
            "channel": 0,
            "dither": 0.0,
            "window_type": "hamming",
            "frame_length": self.frame_size,
            "frame_shift": int(self.frame_size/2),
            "remove_dc_offset": False,
            "round_to_power_of_two": False,
            "sample_frequency": self.sample_rate,
            "preemphasis_coefficient": self.pre_emph,
            "num_ceps": self.num_ceps
        }

        #audio = torch.tensor(audio, dtype=torch.float)
        frames_mfcc = torchaudio.compliance.kaldi.mfcc(sample, **params)
        return frames_mfcc

csv_filename = 'train_data.csv'
root_dir = '../timit'
'''
train_set = TimitDataset(csv_file=csv_filename, root_dir=root_dir, pre_epmh=0.97, num_ceps=13, n_fft=512, frame_size=20, frame_shift=10)
print('dataset size', len(train_set))
max_len = 0
for i in range(len(train_set)):
    sample, target = train_set.__getitem__(i)
    print(sample.shape, target.shape)
    if sample.shape[0] > max_len:
        max_len = sample.shape[0]
        print("new max: ", max_len)
print("max", max_len)
print("dataset size", len(train_set))
test_file = 'test_data.csv'

test_set = TimitDataset(csv_file=test_file, root_dir=root_dir, pre_epmh=0.97, num_ceps=13, n_fft=512, frame_size=20, frame_shift=10)

max_len = 0
for i in range(len(test_set)):
    sample, target = test_set.__getitem__(i)
    print(sample.shape, target.shape)
    if sample.shape[0] > max_len:
        max_len = sample.shape[0]
        print("new max: ", max_len)
print("max", max_len)
print("dataset size", len(test_set)) '''


import re

# pipes return whatever comes first in the search.
# don't put spaces between the pipes, it adds white space
heroes = re.compile(r'batman|tina fey')
mo1 = heroes.search('I like tina fey and batman')
print(mo1.group())  # returns tina fey, she was first

mo2 = heroes.search('batman destroys tina fey')
print(mo2.group()) #returns batman


import glob
import os
import random
import tempfile
import time
from unittest import mock

from absl import flags
from absl.testing import absltest
from absl.testing import parameterized
from learner import test_data
from learner.brains import continuous_imitation_brain
from learner.brains import demonstration_buffer
import numpy as np
import tensorflow as tf

class ContinuousImitationBrainTest(parameterized.TestCase):

  _STEPS_PER_EPISODE = 6
  _EPISODES_TO_RUN = 10
  _EPISODE_ID = 0

  def setUp(self):
    super().setUp()
    self.temp_dirs = []
    self.temp_path = self._temporary_directory('cil_test_')
    self.checkpoint_path = os.path.join(self.temp_path, 'checkpoint')
    self.summary_path = os.path.join(self.temp_path, 'summary')
    self.brain_spec = test_data.brain_spec()

  def tearDown(self):
    """Clean up all temporary directories."""
    super().tearDown()
    for temp_dir in self.temp_dirs:
      temp_dir.cleanup()

  def _temporary_directory(self, prefix):
    """Create a temporary directory under the test temporary dir.

    Args:
      prefix: Prefix for the temporary directory name.

    Returns:
      Name of the temporary directory.
    """
    temp_dir = tempfile.TemporaryDirectory(
        prefix=os.path.join(flags.FLAGS.test_tmpdir, prefix))
    self.temp_dirs.append(temp_dir)
    return temp_dir.name

  def _init_brain(self):
    hparams = continuous_imitation_brain.BCAgent.default_hparams()
    hparams['use_xla_jit'] = False
    hparams['num_batches_to_sample'] = 5
    hparams['batch_size'] = 500
    hparams['training_examples'] = 500
    self.brain = continuous_imitation_brain.ContinuousImitationBrain(
        brain_id=0,
        spec_pb=self.brain_spec,
        checkpoint_path=self.checkpoint_path,
        summary_path=self.summary_path,
        hparams=hparams)
    self.assertEqual(self.brain.hparams['training_steps'], 1)

  def test_trajectory_subdivision(self):
    self._init_brain()

    def test_generator():
      yield {'a': tf.constant([0, 1, 2, 3, 4])}, 5
      yield {'a': tf.constant([0, 1, 2, 3, 4, 5])}, 6
      yield {'a': tf.constant([0, 1, 2, 3, 4, 5])}, 6

    rng = mock.MagicMock()
    rng.randint.side_effect = [0, 2, 5]

    result = list(
        continuous_imitation_brain._select_sub_trajectories(
            test_generator(), 0.2, rng))

    result = tf.nest.map_structure(  # convert tensors to lists
        lambda x: x.numpy().tolist() if hasattr(x, 'numpy') else x, result)

    self.assertEqual(result[0], (None, {'a': [0]}, {'a': [1, 2, 3, 4]}))

    self.assertEqual(result[1], ({'a': [0, 1]}, {'a': [2]}, {'a': [3, 4, 5]}))

    self.assertEqual(result[2], ({'a': [0, 1, 2, 3, 4]}, {'a': [5]}, None))

  @staticmethod
  def _random_step_generator():
    """Generate random training data.

    Yields:
      (observation_data_proto, action_data_proto) populated with random data.
    """
    yield (test_data.observation_data(
        random.uniform(0, 100.0),
        (random.uniform(0, 50), random.uniform(0, 50), random.uniform(0, 50))),
           test_data.action_data(
               random.randrange(0, 1), random.uniform(-1.0, 1.0)))

  @staticmethod
  def _constant_step_generator():
    """Generate constant training data.

    Yields:
      (observation_data_proto, action_data_proto) populated with constan data.
    """
    yield (test_data.observation_data(50.0, (10, 15, 20)),
           test_data.action_data(1, 0.3))

  def _add_training_data_to_brain(self,
                                  number_of_episodes,
                                  steps_per_episode,
                                  first_episode_id=0,
                                  constant=False):
    """Add training data to the test's brain.

    Args:
      number_of_episodes: Episode to create.
      steps_per_episode: Number of steps in each episode.
      first_episode_id: Integer ID of the first episode.
      constant: Use constant data for all steps.
    """
    step_generator = (
        self._constant_step_generator
        if constant else self._random_step_generator)
    reward = 0
    for episode_index in range(number_of_episodes):
      for i, step_phase in (demonstration_buffer.generate_index_and_step_phase(
          steps_per_episode, demonstration_buffer.StepPhase.SUCCESS)):
        observation_data, action_data = next(step_generator())
        self.brain.record_step(observation_data, reward, step_phase,
                               first_episode_id + episode_index, action_data,
                               episode_index + i)

  def test_short_episodes(self):
    self._init_brain()
    steps_per_episode = 3
    episodes_to_run = 100
    self._add_training_data_to_brain(episodes_to_run, steps_per_episode)

    got_frames = self.brain.num_train_frames + self.brain.num_eval_frames

    # Eval frames received are sent as pairs (cur, next), so we get one less
    # than the length of the episode.
    want_frames = (steps_per_episode - 1) * episodes_to_run

    # Check that we recorded all the frames:
    self.assertEqual(got_frames, want_frames)
    # Check that we have some versions in the eval datastore.
    self.assertNotEmpty(self.brain._eval_datastore.versions)

  def test_train_brain(self):
    """Tests training a brain using continuous imitation learning."""
    self._init_brain()
    self._add_training_data_to_brain(
        self._EPISODES_TO_RUN,
        self._STEPS_PER_EPISODE,
        first_episode_id=self._EPISODE_ID,
        constant=True)

    got_frames = self.brain.num_train_frames + self.brain.num_eval_frames
    # Eval frames received are sent as pairs (cur, next), so we get one less
    # than the length of the episode.
    want_frames = (self._STEPS_PER_EPISODE - 1) * self._EPISODES_TO_RUN

    # Check that we recorded all the frames:
    self.assertEqual(got_frames, want_frames)
    # Check that we have some versions in the eval datastore.
    self.assertNotEmpty(self.brain._eval_datastore.versions)
    self.assertLen(self.brain._eval_datastore.versions, self._EPISODES_TO_RUN)
    # Check that we have some frames in the eval datastore.
    self.assertEqual(self.brain._eval_datastore.eval_frames,
                     self._EPISODES_TO_RUN * int(self._STEPS_PER_EPISODE * 0.2))

    # Check that the difference between versions is of the expected size.
    last_frames = 0
    for v in self.brain._eval_datastore.versions:
      data = self.brain._eval_datastore.get_version(v)

      def batch_size(tensor_nest):
        """Return outermost dim of tensors in tensor nest."""
        size = 0

        def _set_size(t):
          nonlocal size
          size = len(t)

        tf.nest.map_structure(_set_size, tensor_nest)
        return size

      frames = batch_size(data)
      diff = frames - last_frames

      self.assertEqual(diff, int(self._STEPS_PER_EPISODE * 0.2))
      last_frames = frames

    # Save policy before training.
    policy_0_path = self._temporary_directory('before_training')
    p0_saved_model_dir = os.path.join(policy_0_path, 'saved_model')
    p0_checkpoint_dir = os.path.join(policy_0_path, 'checkpoint')
    p0_tflite_dir = os.path.join(p0_saved_model_dir, 'tflite')
    os.makedirs(p0_checkpoint_dir)

    self.brain.save_checkpoint(p0_checkpoint_dir)
    self.brain.export_saved_model(p0_saved_model_dir)
    self.brain.convert_model_to_tflite(p0_saved_model_dir, p0_tflite_dir)

    self.brain.train()

    # Save policy after training.
    policy_1_path = self._temporary_directory('after_training')
    p1_saved_model_dir = os.path.join(policy_1_path, 'saved_model')
    p1_checkpoint_dir = os.path.join(policy_1_path, 'checkpoint')
    p1_tflite_dir = os.path.join(p1_saved_model_dir, 'tflite')
    os.makedirs(p1_checkpoint_dir)

    self.brain.save_checkpoint(p1_checkpoint_dir)
    self.brain.export_saved_model(p1_saved_model_dir)
    self.brain.convert_model_to_tflite(p1_saved_model_dir, p1_tflite_dir)

    # Test evaluation:
    full_eval = list(self.brain.compute_full_evaluation())
    # Test evaluation when frehly loading the recent checkpoint.
    from_checkpoint_full_eval = list(
        self.brain.compute_full_evaluation(policy_1_path))
    # Test evaluation on older checkpoint
    prev_full_eval = list(self.brain.compute_full_evaluation(policy_0_path))

    # Data is the same, so eval score should be the same for each version.
    _, score0 = full_eval[0]
    _, scores = zip(*full_eval)
    _, from_checkpoint_scores = zip(*from_checkpoint_full_eval)
    for score, ckpt_score in zip(scores, from_checkpoint_scores):

      def _assert_float_eq(f1, f2):
        self.assertLess(abs(float(f1) - float(f2)), 1e-5)

      # Should be equal to score[0]
      _assert_float_eq(score, score0)
      _assert_float_eq(ckpt_score, score)

    _, prev_scores = zip(*prev_full_eval)

    # Check that the eval score is different before and after training.
    self.assertTrue(any(old != new for old, new in zip(prev_scores, scores)))

  def test_save_policy(self):
    self._init_brain()
    temp_path = self._temporary_directory('save_policy')

    saved_checkpoint_dir = os.path.join(temp_path, 'checkpoint')
    os.makedirs(saved_checkpoint_dir)
    saved_model_dir = os.path.join(temp_path, 'saved_model')
    checkpoint_dir = os.path.join(temp_path, 'checkpoint')
    tflite_dir = os.path.join(saved_model_dir, 'tflite')

    self.brain.save_checkpoint(saved_checkpoint_dir)
    self.brain.export_saved_model(saved_model_dir)
    self.brain.convert_model_to_tflite(saved_model_dir, tflite_dir)

    dir_contents = {
        saved_model_dir: [
            'assets',
            'policy_specs.pbtxt',
            'saved_model.pb',
            'tflite',
            'variables',
        ],
        checkpoint_dir: [
            'ckpt-0.index', 'ckpt-0.data-00000-of-00001', 'checkpoint'
        ],
        tflite_dir: ['model.tflite']
    }
    if not self.brain._write_tflite:
      del dir_contents[tflite_dir]

    for path, contents in dir_contents.items():
      self.assertCountEqual(
          glob.glob(path + '/*'), [os.path.join(path, c) for c in contents])

  def test_checkpoint_restore(self):
    self._init_brain()
    tmp1 = self._temporary_directory('cil_ckpt_restore1')
    tmp2 = self._temporary_directory('cil_ckpt_restore2')
    tmp3 = self._temporary_directory('cil_ckpt_restore3')

    observation_data = test_data.observation_data(50.0, (10, 15, 20))
    action_data = test_data.action_data(1, 0.3)
    reward = 1

    def _record_steps():
      self.brain.record_step(observation_data, reward,
                             demonstration_buffer.StepPhase.START,
                             self._EPISODE_ID, action_data, 0)
      self.brain.record_step(observation_data, reward,
                             demonstration_buffer.StepPhase.IN_PROGRESS,
                             self._EPISODE_ID, action_data, 1)
      self.brain.record_step(observation_data, reward,
                             demonstration_buffer.StepPhase.SUCCESS,
                             self._EPISODE_ID, action_data, 2)

    self.brain.save_checkpoint(tmp1)
    for _ in range(100):
      _record_steps()
    self.brain.train()
    self.brain.save_checkpoint(tmp2)
    del self.brain  # Delete and reinitialize the brain from checkpoint.
    self._init_brain()
    for _ in range(100):
      _record_steps()
    self.brain.train()
    self.brain.save_checkpoint(tmp3)

    global_step = self.brain.tf_agent.train_step_counter
    self.assertEqual(global_step, self.brain.hparams['training_steps'] * 2)

  @parameterized.parameters((1,), (2,), (3,))
  def test_only_discrete_actions(self, num_actions):
    self._init_brain()
    self.brain_spec.action_spec.Clear()
    spec = self.brain_spec.action_spec
    spec.Clear()

    # Fix up spec to match requested number of actions.
    for i in range(num_actions):
      action = spec.actions.add()
      action.name = f'action_{i}'
      action.category.enum_values.append('False')
      action.category.enum_values.append('True')

    self._init_brain()  # Ensure brain can initialize on discrete action space.
    tmp = os.path.join(
        self._temporary_directory('only_discrete'), 'saved_model')
    self.brain.export_saved_model(tmp)  # Ensure we can save policies.

  def test_reinitialize_faster_than_initialize(self):
    """Verify that reinitializing a brain is faster than initialization."""
    start_time = time.perf_counter()
    self._init_brain()
    initialization_time = time.perf_counter() - start_time

    # Set the step counter variable which should be overwritten when
    # reinitializing the brain.
    train_step_counter = self.brain.tf_agent.train_step_counter
    train_step_counter.assign(123)

    start_time = time.perf_counter()
    self.brain.reinitialize_agent()
    reinitialization_time = time.perf_counter() - start_time

    # Training step counter should be restored from the initial checkpoint.
    self.assertEqual(int(train_step_counter), 0)

    # Reinitialization should be >100x faster than initialization.
    # Initialization / compilation should take tens of seconds and
    # reinitialization should typically take tens to hundres of milliseconds.
    print(f'Initialized in {initialization_time}s, '
          f'Reinitialized in {reinitialization_time}s')
    self.assertLess(reinitialization_time * 100, initialization_time)

    # Add trajectories and train, which should be faster than compilation.
    training_times = []
    for i in range(6):
      # Add training data every other iteration.
      if i % 2 == 0:
        self._add_training_data_to_brain(
            self._EPISODES_TO_RUN,
            self._STEPS_PER_EPISODE,
            first_episode_id=self._EPISODE_ID)
      start_time = time.perf_counter()
      self.brain.train()
      training_times.append(time.perf_counter() - start_time)

    print(f'Initialized in {initialization_time}s, '
          f'Training times in seconds {training_times}')
    # Training time should be significantly >10x less than initialization
    # time.
    self.assertLess(training_times[0] * 10, initialization_time)
    # Sequential training times should be nearly the same (within ~1s).
    self.assertLess(np.var(training_times), 1)

if __name__ == '__main__':
  absltest.main()


# def load_classes(path):
#     with open(path, "r") as fp:
#         names = fp.read().split("\n")[:-1]
#     return names

# if __name__ == '__main__':
#     class_path = 'data/coco/coco.names'
#     class_list = load_classes(class_path)
#     img_path = 'data/coco/images/000000581886.jpg'
#     img = np.array(Image.open(img_path))
#     H, W, C = img.shape
#     label_path = 'data/coco/labels/000000581886.txt'
#     boxes = np.loadtxt(label_path, dtype=np.float).reshape(-1, 5)
#     # xywh to xxyy
#     boxes[:, 1] = (boxes[:, 1] - boxes[:, 3] / 2) * W
#     boxes[:, 2] = (boxes[:, 2] - boxes[:, 4] / 2) * H
#     boxes[:, 3] *= W
#     boxes[:, 4] *= H
#     fig = plt.figure()
#     ax = fig.subplots(1)
#     for box in boxes:
#         bbox = patches.Rectangle((box[1], box[2]), box[3], box[4], linewidth=2,
#                                  edgecolor='r', facecolor="none")
#         label = class_list[int(box[0])]
#         # Add the bbox to the plot
#         ax.add_patch(bbox)
#         # Add label
#         plt.text(
#             box[1],
#             box[2],
#             s=label,
#             color="white",
#             verticalalignment="top",
#             bbox={"color": 'g', "pad": 0},
#         )
#         ax.imshow(img)
#     plt.show()

import os
path = '/home/yu/data/dataset/coco/images/val2017'
label_dir = os.listdir(path)
image_path = [os.path.join(path,i) for i in label_dir]
print(image_path[0])
with open('val.txt','w',encoding='utf-8')as f:
    for paths in image_path:
        assert os.path.exists(paths),'path erro!'
        f.writelines(paths+'\n')


from collections import defaultdict

t = int(input())

for i in range(t):
  c_count = defaultdict(list)
  w = str(input())
  k = int(input())

  for i in range(len(w)):
    if w.count(w[i]) >= k:
        c_count[w[i]].append(i)

  if not c_count:
    print(-1)
    continue

  a = len(w)
  b = 0

  for idx_list in c_count.values():
    for j in range(len(idx_list)-k+1):
        temp = idx_list[j+k-1] - idx_list[j] + 1

        if temp < a:
            a = temp

        if temp > b:
            b  = temp

  print(a, b)


'''Write a function named is_perfect that accepts a positive integer n as argument and returns True if it is a perfect number, and False otherwise.'''

def is_perfect(n):
    summ = 0
    for i in range(1,n):
        if n%i == 0:
            summ += i
    if summ == n:
        return True
    return False
print(is_perfect(int(input())))

Programming in Python/Week 5/perfect num.py


import os
import re

def _drop_file_name(file_path):
    # with this select we drop the filename and keep the folder strcuture
    m = re.search('\.\/.*\/', file_path)
    if m:
        return m.group(0)
    else:
        None

def _reduce_forward_slashes(file_path):
    updated_file_path = file_path.replace('//','/')
    if updated_file_path.endswith('/'):
        updated_file_path = updated_file_path[:-1]
    return updated_file_path

def ensure_subfolder_exists(file_path):
    reduced_path = _drop_file_name(file_path)
    if reduced_path != None and not os.path.exists(reduced_path):
        os.makedirs(reduced_path)

def delete(path):
    if os.path.exists(path):
        if os.path.isdir(path):
            files = os.listdir(path)
            for file in files:
                file_path = os.path.join(path, file)
                if os.path.isdir(file_path):
                    delete(file_path)
                else:
                    os.remove(file_path)
            os.rmdir(path)
        else:
            os.remove(path)

def extract_subject(file_path):
    reduced_path = _drop_file_name(file_path)
    reduced_path = _reduce_forward_slashes(reduced_path)
    split = reduced_path.split('/')
    return split[-1]

def extract_simple_file_name(file_path):
    return os.path.split(file_path)[1]

def process_folder(folder_path, file_function):
    results=[]
    for file in os.listdir(folder_path):
        file_path = os.path.join(folder_path, file)
        if os.path.isdir(file_path):
            local_results = process_folder(file_path,file_function)
            results = results + local_results
        else:
            if not file.startswith("."):
                local_results = file_function(file_path)
                if local_results != None:
                    results = results + local_results
                else:
                    print(f'Skipping \'{file_path}\' due to missing accelerations')
            else:
                print(f'Skipping \'{file_path}\' since it\'s a hidden file')
    return results


import logging
import os
import datetime

from webcore.wdcore_driver import WdCoreDriver
from spotify.config import TestSuiteConfig

class StaticLogger:
    started = False
    logger = None

    __console_handler = None

    def __init__(self):
        if not StaticLogger.started:
            StaticLogger.start()

    @staticmethod
    def start():

        config = TestSuiteConfig()
        desired_level = logging.getLevelName(config.log_level)   # Put config level here

        log_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'logs')
        dt_now = datetime.datetime.now().strftime('%Y%m%d%H%M%S')

        StaticLogger.started = True
        root_logger = logging.getLogger()
        root_logger.setLevel(desired_level)
        log_format = '%(asctime)s [%(levelname)s] %(name)s %(message)s'
        log_handler = logging.FileHandler('{0}/{1}.log'.format(log_dir, dt_now))
        log_formatter = logging.Formatter(log_format)
        log_handler.setFormatter(log_formatter)
        root_logger.addHandler(log_handler)

        StaticLogger.logger = logging.getLogger('hempbombs_tests')

        if config.console:  # Put console flag here
            console_format = '[%(levelname)s] %(name)s %(message)s'
            console_handler = logging.StreamHandler()
            console_formatter = logging.Formatter(console_format)
            console_handler.setFormatter(console_formatter)
            root_logger.addHandler(console_handler)

    @staticmethod
    def take_screenshot(filename=None):
        current_test_info = os.environ.get('PYTEST_CURRENT_TEST').split('::')
        # Getting this info in case we need to add it in the future
        test_class_name = current_test_info[1]
        test_name = current_test_info[2].split(' ')[0]

        if filename is None:
            filename = '{0}-{1}'.format(test_class_name, test_name)

        screen_shots_folder = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'screenshots')

        # Create the filename using the filename and the current timestamp
        current_time = datetime.datetime.now()
        filename = '{filename}_{timestamp}.png'.format(
            filename=filename, timestamp=current_time.strftime('%m-%d-%H%M%S')
        )
        full_file_path = os.path.join(screen_shots_folder, filename)
        WdCoreDriver.get_active_driver().save_screenshot(full_file_path)


from typing import List, Union

def first_recurring_char(chars: List[Union[str, int]]) -> Union[str, int, None]:
    """
    Returns the first recurring character from the list of characters, returns None if there is no such character

    Args:
        chars (List[Union[str, int]]): List of characters represented as strings or integers

    Returns:
        Union[str, int, None]: First recurring character or None if there is no such character
    """
    if not chars:
        raise ValueError("No characters")

    if not all(isinstance(char, (str, int)) for char in chars):
        raise TypeError("All characters must be either string or int")

    if len(chars) < 1:
        return None

    char_set = set()

    for char in chars:
        if char in char_set:
            return char
        char_set.add(char)

    return None

print(first_recurring_char([""]))
print(first_recurring_char(['a', 'b', 'a', 'c']))
print(first_recurring_char(['a', 'b', 'b', 'c']))


product = ["tomato", "carrot", "milk", "bread", "snack"]
price = [20, 15, 24, 35, 10]
purchased = []
exit = 1

def find_duplicates(array):
    count = {}
    for item in array:
        if item in count:
            count[item] += 1
        else:
            count[item] = 1
    duplicates = {k: v for k, v in count.items() if v > 1}
    return count

def generate_invoice(purchased):
    purchased.sort()
    purchases = find_duplicates(purchased)
    print(purchases)

while exit == 1:
    print("What you want to buy?")
    for i in range(5):
        print(i + 1, "-", product[i], "-", price[i])
    print(6, "- to exit")
    user_input = int(input("Enter the number"))
    if user_input >= 1 and user_input <= 5:
        purchased.append(user_input - 1)
    else:
        generate_invoice(purchased)
        exit = 0

# product = ["tomato", "carrot", "milk", "bread", "snack"]
# price = [20, 15, 24, 35, 10]
# purchased = []
# exit = 1
#
#
# def generate_invoice(purchased):
#     total_price = 0
#     print("Invoice:")
#     for item in purchased:
#         print("-", product[item], price[item])
#         total_price += price[item]
#     print("Total Price:", total_price)
#     return
#
#
# while exit == 1:
#     print("What you want to buy?")
#     for i in range(5):
#         print(i + 1, "-", product[i], "-", price[i])
#     print(6, "- to exit")
#     user_input = int(input("Enter the number"))
#     if user_input >= 1 and user_input <= 5:
#         purchased.append(user_input - 1)
#     else:
#         generate_invoice(purchased)
#         exit = 0


"""Kata: Parameters of squares in a rectangle - determine the parameters of all the squares in a rectangle

#1 Best Practices Solution by EarlGrey

def fib(n):
    a, b = 0, 1

    for i in range(n+1):
        if i == 0:
            yield b
        else:
            a, b = b, a+b
            yield b

def perimeter(n):
    return sum(fib(n)) * 4
"""

def perimeter(n):
    """."""
    p = 1
    a = 0
    b = 1
    for i in range(n):
        p += a + b
        c = a
        a = b
        b += c
    return p * 4


import cv2 as cv
import numpy as np
import pytest
import torch
import torchvision.transforms.functional as F
from PIL import Image

from src.scaling import *
from src.scaling.cv import ScalingBackendCV
from src.scaling.pil import ScalingBackendPIL

lib_list = list(ScalingLib)
alg_list = list(ScalingAlg)
src_list = [(666, 555), (333, 444)]
tgt_list = [(555, 444), (333, 222), (111, 66)]

def _setup(src_shape: Shape, tgt_shape: Shape, lib: ScalingLib, alg: ScalingAlg):
    # Generate random image
    shape = src_shape + (3,)
    img = np.random.randint(256, size=shape, dtype=np.uint8)

    # API result
    api = ScalingAPI(src_shape, tgt_shape, lib, alg)
    api_img = F.to_tensor(img).numpy()
    api_img = api(api_img)
    return img, api_img, api

class TestScalingAPI(object):

    @pytest.mark.parametrize('src_shape', src_list)
    @pytest.mark.parametrize('tgt_shape', tgt_list)
    @pytest.mark.parametrize('alg', alg_list)
    def test_pil_api(self, src_shape: Shape, tgt_shape: Shape, alg: ScalingAlg):
        # API
        img, api_img, _ = _setup(src_shape, tgt_shape, ScalingLib.PIL, alg)

        # PIL
        pil_alg = ScalingBackendPIL.algorithms[alg]
        pil_img = Image.fromarray(img).resize(tgt_shape[::-1], resample=pil_alg)
        pil_img = F.to_tensor(pil_img).numpy()

        assert pil_img.shape == api_img.shape
        assert pil_img.shape[1:] == tgt_shape
        assert np.allclose(pil_img, api_img)

    @pytest.mark.parametrize('src_shape', src_list)
    @pytest.mark.parametrize('tgt_shape', tgt_list)
    @pytest.mark.parametrize('alg', alg_list)
    def test_cv_api(self, src_shape: Shape, tgt_shape: Shape, alg: ScalingAlg):
        # API
        img, api_img, api = _setup(src_shape, tgt_shape, ScalingLib.CV, alg)
        api_img = np.clip(api_img, 0, 1)

        # CV
        cv_alg = ScalingBackendCV.algorithms[alg]
        cv_img = cv.resize(img.astype(np.float32), tgt_shape[::-1], interpolation=cv_alg)
        cv_img = np.clip(cv_img, 0, 255)
        cv_img = F.to_tensor(cv_img.astype(np.uint8)).numpy()

        assert cv_img.shape == api_img.shape
        assert cv_img.shape[1:] == tgt_shape
        assert np.allclose(cv_img, api_img, atol=1.e-2)

    @pytest.mark.parametrize('src_shape', src_list)
    @pytest.mark.parametrize('tgt_shape', tgt_list)
    @pytest.mark.parametrize('lib', lib_list)
    @pytest.mark.parametrize('alg', alg_list)
    def test_matrix(self, src_shape: Shape, tgt_shape: Shape, lib: ScalingLib, alg: ScalingAlg):
        # By API
        img, api_img, api = _setup(src_shape, tgt_shape, lib, alg)

        # By matrix
        mat_img = F.to_tensor(img).numpy()
        mat_img = api.cl @ mat_img @ api.cr
        mat_img = np.clip(mat_img, 0, 1)

        diff = np.percentile(np.abs(mat_img - api_img), 98)
        assert np.isclose(diff, 0, atol=0.1)

    @pytest.mark.parametrize('src_shape', src_list)
    @pytest.mark.parametrize('tgt_shape', tgt_list)
    @pytest.mark.parametrize('lib', lib_list)
    @pytest.mark.parametrize('alg', alg_list)
    def test_mask_shape(self, src_shape: Shape, tgt_shape: Shape, lib: ScalingLib, alg: ScalingAlg):
        api = ScalingAPI(src_shape, tgt_shape, lib, alg)
        assert api.mask.shape == src_shape

class TestScalingLayer(object):

    @pytest.mark.parametrize('src_shape', src_list)
    @pytest.mark.parametrize('tgt_shape', tgt_list)
    @pytest.mark.parametrize('lib', lib_list)
    @pytest.mark.parametrize('alg', alg_list)
    def test_scaling_layer(self, src_shape: Shape, tgt_shape: Shape, lib: ScalingLib, alg: ScalingAlg):
        # Generate random image
        img = np.random.rand(3, *src_shape).astype(np.float32)

        # Normal scale
        api = ScalingAPI(src_shape, tgt_shape, lib, alg)
        api_img = api(img)

        # Scaling layer
        from src.models import ScalingLayer
        scaling = ScalingLayer.from_api(api).cuda()
        img = torch.tensor(img)[None, ...].cuda()
        scaling_img = scaling(img)[0].cpu().numpy()

        diff = np.percentile(np.abs(api_img - scaling_img), 98)
        assert np.allclose(diff, 0, atol=0.1)


import httplib
import json
import logging
import socket
import urlparse
import uuid

LOG = logging.getLogger(__name__)

def log_curl_request(conn, base_url, url, method, kwargs):
    curl = ['curl -i -X %s' % method]

    for (key, value) in kwargs['headers'].items():
        header = '-H \'%s: %s\'' % (key, value)
        curl.append(header)

    if 'body' in kwargs:
        curl.append('-d \'%s\'' % kwargs['body'])

    curl.append('http://%s:%d%s%s' % (conn.host, conn.port, base_url, url))
    LOG.debug(' '.join(curl))

def log_http_response(resp, body=None):
    status = (resp.version / 10.0, resp.status, resp.reason)
    dump = ['\nHTTP/%.1f %s %s' % status]
    dump.extend(['%s: %s' % (k, v) for k, v in resp.getheaders()])
    dump.append('')
    if body:
        dump.extend([body, ''])
    LOG.debug('\n'.join(dump))

def make_connection_url(base_url, url):
    return '%s/%s' % (base_url.rstrip('/'), url.lstrip('/'))

def http_request(conn, base_url, url, method, **kwargs):
    log_curl_request(conn, base_url, url, method, kwargs)

    try:
        conn_url = make_connection_url(base_url, url)
        conn.request(method, conn_url, **kwargs)
        resp = conn.getresponse()
    except socket.gaierror as e:
        message = ('Error finding address for %(url)s: %(e)s' %
                   {'url': url, 'e': e})
        raise RuntimeError(message)
    except (socket.error, socket.timeout) as e:
        message = ('Error communicating with %(endpoint)s %(e)s' %
                   {'endpoint': 'http://%s:%d' % (conn.host, conn.port),
                    'e': e})
        raise RuntimeError(message)

    if 300 <= resp.status < 600:
        LOG.warn('Request returned failure/redirect status.')
        raise RuntimeError('Status code %d returned' % resp.status)

    body = resp.read()

    log_http_response(resp, body)

    return resp, body

def json_request(conn, base_url, url, method, **kwargs):
    kwargs.setdefault('headers', {})
    kwargs['headers'].setdefault('Content-Type', 'application/json')
    kwargs['headers'].setdefault('Accept', 'application/json')

    if 'body' in kwargs:
        kwargs['body'] = json.dumps(kwargs['body'])

    resp, body = http_request(conn, base_url, url, method, **kwargs)
    content_type = resp.getheader('content-type', None)

    if resp.status == 204 or resp.status == 205 or content_type is None:
        body = None
    elif 'application/json' in content_type:
        try:
            body = json.loads(body)
        except ValueError:
            LOG.error('Could not decode response body as JSON')
    else:
        body = None

    return resp, body

def create_resource_class(conn, base_url, name, service_type, racks, flavors):
    return json_request(conn, base_url, '/resource_classes', 'POST',
                        body=dict(name=name, service_type=service_type,
                                  racks=racks, flavors=flavors))

def create_rack(conn, base_url, name, slots, location,
                subnet, capacities, nodes):
    return json_request(conn, base_url, '/racks', 'POST',
                        body=dict(name=name, slots=slots,
                                  subnet=subnet, location=location,
                                  capacities=capacities,nodes=nodes))

def set_nodes_on_rack(conn, base_url, rack_url, nodes):
    return json_request(conn, base_url, rack_url, 'PUT',
                        body=dict(nodes=nodes))

def create_flavor(conn, base_url, resource_class_url, flavor):
    return json_request(conn, base_url + resource_class_url, '/flavors', 'PUT', body=flavor)

def get_location(base_url, resp):
    return urlparse.urlparse(resp.getheader('location')).path[len(base_url):]

def generate_uuid():
    return str(uuid.uuid4())

def generate_data():
    logging.basicConfig(format='%(message)s', level=logging.DEBUG)

    conn = httplib.HTTPConnection('localhost', 6385)

    base_url = '/v1'

    capacities = [
        dict(name='total_cpu', value='64', unit='count'),
        dict(name='total_memory', value='16384', unit='MB'),
    ]
    nodes = []
    while len(nodes) < 30:
        nodes.append(dict(id=generate_uuid()))

    rack_resp1, rack_body1 = create_rack(conn, base_url,
                                         name='compute_1', slots=3,
                                         subnet='192.168.1.0/24',
                                         location='room d2, row 1',
                                         capacities=capacities,
                                         nodes=nodes[0:3])

    rack_resp2, rack_body2 = create_rack(conn, base_url,
                                         name='compute_2', slots=3,
                                         subnet='192.168.2.0/24',
                                         location='room d2, row 2',
                                         capacities=capacities,
                                         nodes=nodes[3:6])

    compute_racks = [
            dict(id=rack_body1.get('id'),links=rack_body1.get('links')),
            dict(id=rack_body2.get('id'),links=rack_body2.get('links')),
    ]

    rack_resp3, rack_body3 = create_rack(conn, base_url,
                                         name='not_compute', slots=3,
                                         subnet='192.168.3.0/24',
                                         location='room d2, row 3',
                                         capacities=capacities,
                                         nodes=[nodes[7]])

    non_compute_racks = [
            dict(id=rack_body3.get('id'),links=rack_body3.get('links')),
    ]

    flavors = [
        dict(name='m1.small',
             capacities=[
                dict(name='cpu', value='1', unit='count'),
                dict(name='memory', value='1.7', unit='GB'),
                dict(name='storage', value='160', unit='GB'),
             ]),
        dict(name='m1.medium',
             capacities=[
                dict(name='cpu', value='1', unit='count'),
                dict(name='memory', value='3.75', unit='GB'),
                dict(name='storage', value='410', unit='GB'),
             ]),
        dict(name='m1.large',
             capacities=[
                dict(name='cpu', value='2', unit='count'),
                dict(name='memory', value='7.5', unit='GB'),
                dict(name='storage', value='840', unit='GB'),
             ]),
        dict(name='m1.xlarge',
             capacities=[
                dict(name='cpu', value='4', unit='count'),
                dict(name='memory', value='15', unit='GB'),
                dict(name='storage', value='1680', unit='GB'),
             ]),
    ]

    rc_resp1, rc_body1 = create_resource_class(conn, base_url,
                                               name='compute-rc',
                                               service_type='compute',
                                               racks=compute_racks,
                                               flavors=[flavors[3]])

    rc_resp1, rc_body1 = create_resource_class(conn, base_url,
                                               name='non-compute-rc',
                                               service_type='not_compute',
                                               racks=non_compute_racks,
                                               flavors=[])

if __name__ == '__main__':
    generate_data()


import os

def split_file(file_path):
    # Разделяем путь и имя файла
    file_dir, file_name = os.path.split(file_path)

    # Разделяем имя файла и его расширение
    file_name, file_extension = os.path.splitext(file_name)

    return file_dir, file_name, file_extension

file_path = "/home/pc/PycharmProjects/lesson5/task1.py"
result = split_file(file_path)
print(result)


import asyncio
import unittest as t
from unittest.mock import patch, MagicMock, Mock, ANY
from collections import namedtuple

from diy_framework import http_parser
from diy_framework.http_server import HTTPConnection
from diy_framework.exceptions import TimeoutException
from diy_framework import Router

HTTPServerMock = namedtuple('HTTPServerMock', 'router, http_parser, loop')

class AsyncMock(Mock):
    def __call__(self, *args, **kwargs):
        sup = super(AsyncMock, self)
        async def coro():
            return sup.__call__(*args, **kwargs)
        return coro()

    def __await__(self):
        return self().__await__()

class TestHTTPConnection(t.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.server = HTTPServerMock(router=None,
                                     http_parser=http_parser,
                                     loop=None)

    def setUp(self):
        self.loop = asyncio.new_event_loop()
        asyncio.set_event_loop(None)

        self.router = Router()
        self.server = self.server._replace(router=self.router, loop=self.loop)

        self.reader = asyncio.streams.StreamReader(loop=self.loop)
        self.writer = MagicMock(spec=asyncio.streams.StreamWriter)
        self.writer.write = MagicMock()
        self.writer.drain = AsyncMock()
        self.writer.close = MagicMock()

        self.conn = HTTPConnection(self.server, self.reader, self.writer)

    def tearDown(self):
        self.loop.stop()
        self.loop.close()

    def test_empty_get_request(self):
        mock_get_handler = AsyncMock(return_value='response')
        self.reader.feed_data(b'GET / http/1.1\r\n\r\n')

        self.router.add_route(r'/', mock_get_handler)

        self.loop.run_until_complete(self.conn.handle_request())
        self.assertTrue(self.writer.write.call_args[0][0].endswith(b'response'))

    def test_url_params_get_request(self):
        mock_get_handler = AsyncMock(return_value='response')
        self.reader.feed_data(b'GET /12/edit/bob http/1.1\r\n\r\n')

        self.router.add_route(r'/{id}/edit/{name}', mock_get_handler)

        self.loop.run_until_complete(self.conn.handle_request())
        mock_get_handler.assert_any_call(ANY, id='12', name='bob')

    def test_post_request(self):
        async def echo_coro(r):
            return bytes(r.body_raw).decode('utf-8')
        self.reader.feed_data(
            (b'POST / http/1.1\r\nContent-Length:8\r\n'
             b'Content-Type: application/x-www-form-urlencoded\r\n\r\n'
             b'abcd=123'))

        self.router.add_route(r'/', echo_coro)
        self.loop.run_until_complete(self.conn.handle_request())
        self.assertTrue(self.writer.write.call_args[0][0].endswith(b'abcd=123'))

    def test_post_large_request(self):
        async def echo_coro(r):
            return bytes(r.body_raw).decode('utf-8')
        self.reader.feed_data(
            (b'POST / http/1.1\r\nContent-Length: 2000\r\n'
             b'Content-Type: application/x-www-form-urlencoded\r\n\r\n') +
            b'abcd=12345' * 200)
        self.router.add_route(r'/', echo_coro)
        self.loop.run_until_complete(self.conn.handle_request())
        rsp_body = self.writer.write.call_args[0][0].split(b'\r\n\r\n')[1]
        self.assertEqual(len(rsp_body), 2000)

    @t.skip('')
    def test_request_timeout(self):
        self.reader.feed_data(b'GET / ')
        self.loop.run_until_complete(self.conn.handle_request())

if __name__ == '__main__':
    t.main()


"""
    Sequence of Execution - LEGB:
    -----------------------------
    1) Local       : Variables defined within function, accessible only to it's function
    2) Enclosing   : Variables defined in an enclosing function
    3) Global      : Specific to module
    4) Built-in    : Pre-assigned in Python

"""

x = 'global x'

def test():
    x = 'local x'
    print(x)

test()
print(x)

''' min is a Built-in Function '''

# To know the list of built-in variables/functions:
import builtins
print(dir(builtins))

# Sample use case of min function:
m = min([1,8,9,0,10])
print(m)

# Caution! - It will be overwritten, if you do so:
def min():
    pass

''' Let's discuss about Enclosing '''
x = 'global x'

def outer():
    x = 'outer x'

    def inner():
        # global x # affects globally
        # nonlocal x # affects enclosing function
        x = 'inner x'
        print(x)

    inner()
    print(x)

outer()


from PyQt5.QtWidgets import (QWidget, QGridLayout, QLineEdit, QPushButton)
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont

class MainForm(QWidget):
    def __init__(self):
        super().__init__()
        self.setupUi()

    def setupUi(self):
        self.resize(250, 250)
        self.move(250, 300)
        self.setWindowTitle("Kalulator")

        self.lineEdit = QLineEdit()  # Inisialisasi objek dengan tanda kurung
        self.lineEdit.setAlignment(Qt.AlignRight)
        self.lineEdit.setFont(QFont('SansSerif', 14))
        self.lineEdit.setDisabled(True)
        self.lineEdit.setStyleSheet("background-color: lightgray;")

        self.__7btn = QPushButton('7')
        self.__8btn = QPushButton('8')
        self.__9btn = QPushButton('9')
        self.mulbtn = QPushButton('X')
        self.clearbtn = QPushButton('CLR')
        self.__4btn = QPushButton('4')
        self.__5btn = QPushButton('5')
        self.__6btn = QPushButton('6')
        self.divbtn = QPushButton('/')
        self.__1btn = QPushButton('1')
        self.__2btn = QPushButton('2')
        self.__3btn = QPushButton('3')
        self.__0btn = QPushButton('0')
        self.dotbtn = QPushButton('.')
        self.minusbtn = QPushButton('-')
        self.plusbtn = QPushButton('+')
        self.percentagebtn = QPushButton('%')
        self.calculatebtn = QPushButton('=')

        layout = QGridLayout()
        layout.addWidget(self.lineEdit, 0, 0, 1, 4)

        # Baris Pertama
        layout.addWidget(self.__7btn, 1, 0)
        layout.addWidget(self.__8btn, 1, 1)
        layout.addWidget(self.__9btn, 1, 2)
        layout.addWidget(self.clearbtn, 1, 3)

        # Baris Kedua
        layout.addWidget(self.__4btn,2, 0)
        layout.addWidget(self.__5btn,2, 1)
        layout.addWidget(self.__6btn,2, 2)
        layout.addWidget(self.mulbtn,2, 3)

        # Baris Ketiga
        layout.addWidget(self.__1btn,3,0)
        layout.addWidget(self.__2btn,3,1)
        layout.addWidget(self.__3btn,3,2)
        layout.addWidget(self.divbtn,3,3)

        # Baris keempat
        layout.addWidget(self.__0btn,4,0)
        layout.addWidget(self.dotbtn,4,1)
        layout.addWidget(self.minusbtn,4,2)
        layout.addWidget(self.plusbtn,4 ,3)

        # Baris Keempat
        layout.addWidget(self.percentagebtn,5,0)
        layout.addWidget(self.calculatebtn, 5, 1, 1, 3)
        self.setLayout(layout)

        self.__0btn.clicked.connect(lambda: self.writeDigit(0))
        self.__1btn.clicked.connect(lambda: self.writeDigit(1))
        self.__2btn.clicked.connect(lambda: self.writeDigit(2))
        self.__3btn.clicked.connect(lambda: self.writeDigit(3))
        self.__4btn.clicked.connect(lambda: self.writeDigit(4))
        self.__5btn.clicked.connect(lambda: self.writeDigit(5))
        self.__6btn.clicked.connect(lambda: self.writeDigit(6))
        self.__7btn.clicked.connect(lambda: self.writeDigit(7))
        self.__8btn.clicked.connect(lambda: self.writeDigit(8))
        self.__9btn.clicked.connect(lambda: self.writeDigit(9))
        self.dotbtn.clicked.connect(self.writePoint)
        self.mulbtn.clicked.connect(lambda: self.writeOperator('*'))
        self.divbtn.clicked.connect(lambda: self.writeOperator('/'))
        self.plusbtn.clicked.connect(lambda: self.writeOperator('+'))
        self.minusbtn.clicked.connect(lambda: self.writeOperator('-'))
        self.calculatebtn.clicked.connect(self.writeCalculate)
        self.percentagebtn.clicked.connect(self.percentagebtnClick)
        self.clearbtn.clicked.connect(self.lineEdit.clear)

    def writeDigit(self, digit):
        if digit in range(0,10):
            self.lineEdit.setText(
                self.lineEdit.text() + str(digit))

    def writePoint(self):
        if len(self.lineEdit.text()) == 0 or \
        self.lineEdit.text()[-1] in ['*', '/', '+', '-']:
            return
        self.lineEdit.setText(
            self.lineEdit.text() + '.')

    def writeOperator(self, operator):
        if len(self.lineEdit.text()) == 0: return
        if operator in ['*', '/', '+', '-']:
            if self.lineEdit.text()[-1] in ['*', '/', '+', '-']:
                self.lineEdit.setText(self.lineEdit.text()[-1] + operator)
            else:
                self.lineEdit.setText(self.lineEdit.text() + operator)

    def writeCalculate(self):
        expression = self.lineEdit.text()
        if len(expression)  == 0: return
        try:
            result = eval(expression)
            self.lineEdit.setText(str(result))
        except:
            self.lineEdit.setText('ERROR')

    def percentagebtnClick(self):
        expression = self.lineEdit.text()
        if len(expression)  == 0: return
        try:
            result = eval(expression) / 100
            self.lineEdit.setText(str(result))
        except:
            self.lineEdit.setText('ERROR')


t = int(input())
while t>0:
    n,c0,c1,h = map(int,input().split())
    s = input()
    ans = 0

    for i in range(n):
        if s[i] == '0':
            ans = ans + min(c0,h+c1)
        else:
            ans = ans+min(c1,c0+h)

    print(ans)
    t=t-1


def solution(name):
    answer = 0

    num_list = [min(abs(ord('A')-ord(n)), 26-abs(ord('A')-ord(n))) for n in name]
    print(num_list)
    answer += sum(num_list)
    min_move = len(name) -1

    for i, c in enumerate(name):
        #print(i,c)
        next_i = i+1

        while True:
            if (next_i >= len(name) or name[next_i] != 'A'): break
            else: next_i += 1

        min_move = min(min_move, 2*i+ len(name)-next_i, 2*(len(name)-next_i)+i)
        print(min_move)

    return answer+min_move


import pandas as pd
import numpy as np
import requests
import psycopg2
import psycopg2.extras as extras
from datetime import date
import os

def add_date_inserted_column(dfs):
    for i in dfs:
        i['date_inserted'] = date.today()

def api_call():
    url = 'https://fantasy.premierleague.com/api/bootstrap-static/'
    r = requests.get(url)
    json = r.json()

    elements_df = pd.DataFrame(json['elements'])
    elements_types_df = pd.DataFrame(json['element_types'])
    teams_df = pd.DataFrame(json['teams'])
    events_df = pd.DataFrame(json['events'])

    events_df.drop("chip_plays", axis=1, inplace=True) #### REMOVE COLUMN WITH NESTED JSON, INFORMATION NOT REQUIRED FOR NOW
    events_df.drop('top_element_info', axis=1, inplace = True) #### REMOVE COLUMN WITH NESTED JSON, INFORMATION NOT REQUIRED FOR NOW

    teams_df = teams_df.rename(columns = {'name':'name_'}) ### CHANGED COLUMN NAME BECAUSE COMMAND IN SQL
    events_df = events_df.rename(columns = {'name':'name_'}) ### CHANGED COLUMN NAME BECAUSE COMMAND IN SQL

    elements_df = elements_df.rename(columns = {'id':'id_'}) ### CHANGED COLUMN NAME BECAUSE COMMAND IN SQL
    elements_types_df = elements_types_df.rename(columns = {'id':'id_'}) ### CHANGED COLUMN NAME BECAUSE COMMAND IN SQL

    dfs = [elements_df, elements_types_df, teams_df, events_df]
    add_date_inserted_column(dfs)
    return  dfs


import logging
from pathlib import Path
from socket import socket
from typing import Callable, Dict, Iterator, List, Optional

from uvicorn.config import Config
from uvicorn.supervisors.basereload import BaseReload

logger = logging.getLogger("uvicorn.error")

class StatReload(BaseReload):
    def __init__(
        self,
        config: Config,
        target: Callable[[Optional[List[socket]]], None],
        sockets: List[socket],
    ) -> None:
        super().__init__(config, target, sockets)
        self.reloader_name = "statreload"
        self.mtimes: Dict[Path, float] = {}

    def should_restart(self) -> bool:
        for file in self.iter_py_files():
            try:
                mtime = file.stat().st_mtime
            except OSError:  # pragma: nocover
                continue

            old_time = self.mtimes.get(file)
            if old_time is None:
                self.mtimes[file] = mtime
                continue
            elif mtime > old_time:
                display_path = str(file)
                try:
                    display_path = str(file.relative_to(Path.cwd()))
                except ValueError:
                    pass
                message = "StatReload detected file change in '%s'. Reloading..."
                logger.warning(message, display_path)
                return True
        return False

    def restart(self) -> None:
        self.mtimes = {}
        return super().restart()

    def iter_py_files(self) -> Iterator[Path]:
        for reload_dir in self.config.reload_dirs:
            for path in list(reload_dir.rglob("*.py")):
                yield path.resolve()


# https://atcoder.jp/contests/abc094/tasks/arc095_b

import bisect
n = int(input())
a = list(map(int, input().split()))
a.sort()

ai = a[-1]
j = bisect.bisect(a, ai/2)
if abs(ai/2 - a[j]) < abs(ai/2 - a[j-1]):
    aj = a[j]
else:
    aj = a[j-1]

print(ai, aj)


import random
def CompChoice():
    n=random.randint(0,2)
    c=["snake", "water", "gun"]
    return c[n]

p1=0
p2=0
win={"snake":"water", "water":"gun", "gun":"snake"}
while(p1<3 and p2<3):
    choice = input("Enter ur choice")
    Cchoice=CompChoice()
    print(f"{choice} Vs {Cchoice}")
    if choice.lower()==Cchoice:
        print("Tie")
    elif win.get(choice)==Cchoice:
        print("u win")
        p1+=1
    else:
        print("Computer wins")
        p2+=1

if p1>p2:
    print("U win the whole Match")
else:
    print("Computer wins the whole match")


from setuptools import setup, find_packages

with open("README.md", "r") as f:
    page_description = f.read()

with open("requirements.txt") as f:
    requirements = f.read().splitlines()

setup(
    name="numero_nome",
    version="0.0.1",
    author="Alan Vieira",
    author_email="alansilvavieira@gmail.com",
    description="Significa o nome completo pela soma se suas letras, pela numerologia.",
    long_description=page_description,
    long_description_content_type="text/markdown",
    url="https://github.com/alan-vieira/numero-nome-package",
    packages=find_packages(),
    install_requires=requirements,
    python_requires='>=3.8',
)