from hvps.utils import get_serial_ports
from hvps import Iseg

import pytest
import sys
import logging

serial_port = "COM4"  # change this to the serial port you are using
serial_baud = 9600
timeout = 5.0

def serial_port_available():
    ports = get_serial_ports()
    return ports != []

def is_macos():
    return sys.platform == "Darwin"

serial_skip_decorator = pytest.mark.skipif(
    serial_port_available() or not is_macos(), reason="No serial ports available"
)

@serial_skip_decorator
def test_iseg_init(caplog):
    caplog.set_level("DEBUG")

    with Iseg(logging_level="DEBUG") as iseg:
        assert iseg.baudrate == 115200
        assert "Using baud rate 115200" in caplog.text
        assert "Using port " in caplog.text
        assert "Using timeout " in caplog.text

@serial_skip_decorator
def test_iseg_module_monitor():
    iseg = Iseg(
        port=serial_port,
        baudrate=serial_baud,
        connect=True,
        timeout=timeout,
        logging_level=logging.DEBUG,
    )
    iseg.connect()

    print(
        f"Serial port status: connected: {iseg.connected}, port: {iseg.port}, baudrate: {iseg.baudrate}, timeout: {iseg.timeout}"
    )
    module = iseg.module(0)

    number_of_channels = module.number_of_channels
    print(f"number_of_channels: {number_of_channels}")

    firmware_release = module.firmware_release
    print(f"firmware_release: {firmware_release}")

    module_status = module.module_status
    print(f"module_status: {module_status}")

    filter_averaging_steps = module.filter_averaging_steps
    print(f"filter_averaging_steps: {filter_averaging_steps}")

    kill_enable = module.kill_enable
    print(f"kill_enable: {kill_enable}")

    adjustment = module.adjustment
    print(f"adjustment: {adjustment}")

    module_can_address = module.module_can_address
    print(f"module_can_address: {module_can_address}")

    module_can_bitrate = module.module_can_bitrate
    print(f"module_can_bitrate: {module_can_bitrate}")

    serial_echo_enabled = module.serial_echo_enabled
    print(f"serial_echo_enabled: {serial_echo_enabled}")

    serial_echo_disabled = module.serial_echo_disabled
    print(f"serial_echo_disabled: {serial_echo_disabled}")

    module_voltage_limit = module.module_voltage_limit
    print(f"module_voltage_limit: {module_voltage_limit}")

    module_current_limit = module.module_current_limit
    print(f"module_current_limit: {module_current_limit}")

    module_voltage_ramp_speed = module.module_voltage_ramp_speed
    print(f"module_voltage_ramp_speed: {module_voltage_ramp_speed}")

    module_current_ramp_speed = module.module_current_ramp_speed
    print(f"module_current_ramp_speed: {module_current_ramp_speed}")

    module_control_register = module.module_control_register
    print(f"module_control_register: {module_control_register}")

    module_status_register = module.module_status_register
    print(f"module_status_register: {module_status_register}")

    module_event_status_register = module.module_event_status_register
    print(f"module_event_status_register: {module_event_status_register}")

    module_event_mask_register = module.module_event_mask_register
    print(f"module_event_mask_register: {module_event_mask_register}")

    module_event_channel_status_register = module.module_event_channel_status_register
    print(
        f"module_event_channel_status_register: {module_event_channel_status_register}"
    )

    module_event_channel_mask_register = module.module_event_channel_mask_register
    print(f"module_event_channel_mask_register: {module_event_channel_mask_register}")

    module_supply_voltage = module.module_supply_voltage
    print(f"module_supply_voltage: {module_supply_voltage}")

    module_supply_voltage_p24v = module.module_supply_voltage_p24v
    print(f"module_supply_voltage_p24v: {module_supply_voltage_p24v}")

    module_supply_voltage_n24v = module.module_supply_voltage_n24v
    print(f"module_supply_voltage_n24v: {module_supply_voltage_n24v}")

    module_supply_voltage_p5v = module.module_supply_voltage_p5v
    print(f"module_supply_voltage_p5v: {module_supply_voltage_p5v}")

    module_supply_voltage_p3v = module.module_supply_voltage_p3v
    print(f"module_supply_voltage_p3v: {module_supply_voltage_p3v}")

    module_supply_voltage_p12v = module.module_supply_voltage_p12v
    print(f"module_supply_voltage_p12v: {module_supply_voltage_p12v}")

    module_supply_voltage_n12v = module.module_supply_voltage_n12v
    print(f"module_supply_voltage_n12v: {module_supply_voltage_n12v}")

    module_temperature = module.module_temperature
    print(f"module_temperature: {module_temperature}")

    setvalue_changes_counter = module.setvalue_changes_counter
    print(f"setvalue_changes_counter: {setvalue_changes_counter}")

    firmware_name = module.firmware_name
    print(f"firmware_name: {firmware_name}")

    # Setter methods
    module.serial_baud_rate = 9600
    module.serial_echo_enable = 1
    with pytest.raises(ValueError):
        module.serial_echo_enable = 2

    module.filter_averaging_steps = 256
    with pytest.raises(ValueError):
        module.filter_averaging_steps = 257

    module.kill_enable = 1
    with pytest.raises(ValueError):
        module.kill_enable = 2

    module.adjustment = 0
    with pytest.raises(ValueError):
        module.adjustment = 2

    module.module_event_mask_register = 5

    module.module_can_address = 12
    with pytest.raises(ValueError):
        module.module_can_address = 250

    module.module_can_bitrate = 250000
    with pytest.raises(ValueError):
        module.module_can_bitrate = 250

    # Other methods
    module.enter_configuration_mode(12345)
    module.exit_configuration_mode()
    module.set_serial_echo_enabled()
    module.set_serial_echo_disabled()
    module.reset_module_event_status()
    module.clear_module_event_status_bits(8)

    iseg.disconnect()

@serial_skip_decorator
def test_iseg_channel_monitor():
    # TODO: make this work
    # TODO: validate the values (atleast check if they are not None)
    # TODO: Do the same for CAEN

    trip_action = channel.trip_action
    print(f"trip_action: {trip_action}")

    output_mode = channel.output_mode
    print(f"output_mode: {output_mode}")

    output_polarity = channel.output_polarity
    print(f"output_polarity: {output_polarity}")

    available_output_polarities = channel.available_output_polarities
    print(f"available_output_polarities: {available_output_polarities}")

    voltage_set = channel.voltage_set
    print(f"voltage_set: {voltage_set}")

    voltage_limit = channel.voltage_limit
    print(f"voltage_limit: {voltage_limit}")

    voltage_nominal = channel.voltage_nominal
    print(f"voltage_nominal: {voltage_nominal}")

    available_output_modes = channel.available_output_modes
    print(f"available_output_modes: {available_output_modes}")

    voltage_mode = channel.voltage_mode
    print(f"voltage_mode: {voltage_mode}")

    voltage_mode_list = channel.voltage_mode_list
    print(f"voltage_mode_list: {voltage_mode_list}")

    voltage_bounds = channel.voltage_bounds
    print(f"voltage_bounds: {voltage_bounds}")

    set_on = channel.set_on
    print(f"set_on: {set_on}")

    emergency_off = channel.emergency_off
    print(f"emergency_off: {emergency_off}")

    current_set = channel.current_set
    print(f"current_set: {current_set}")

    current_limit = channel.current_limit
    print(f"current_limit: {current_limit}")

    current_nominal = channel.current_nominal
    print(f"current_nominal: {current_nominal}")

    current_mode = channel.current_mode
    print(f"current_mode: {current_mode}")

    modes = channel.current_mode_list
    print(f"modes: {modes}")

    bounds = channel.current_bounds
    print(f"bounds: {bounds}")

    speed = channel.current_ramp_speed
    print(f"speed: {speed}")

    speed = channel.voltage_ramp_speed
    print(f"speed: {speed}")

    speed_min = channel.voltage_ramp_speed_minimum
    print(f"speed_min: {speed_min}")

    speed_max = channel.voltage_ramp_speed_maximum
    print(f"speed_max: {speed_max}")

    speed_min = channel.current_ramp_speed_minimum
    print(f"speed_min: {speed_min}")

    speed_max = channel.current_ramp_speed_maximum
    print(f"speed_max: {speed_max}")

    control = channel.channel_control
    print(f"control: {control}")

    status = channel.channel_status
    print(f"status: {status}")

    mask = channel.channel_event_mask
    print(f"mask: {mask}")

    voltage = channel.measured_voltage
    print(f"voltage: {voltage}")

    current = channel.measured_current
    print(f"current: {current}")

    speed = channel.channel_voltage_ramp_up_speed
    print(f"speed: {speed}")

    speed = channel.channel_voltage_ramp_down_speed
    print(f"speed: {speed}")

    speed = channel.channel_current_ramp_up_speed
    print(f"speed: {speed}")

    speed = channel.channel_current_ramp_down_speed
    print(f"speed: {speed}")

    # Set the action to be taken when a current trip occurs for the channel
    channel.trip_action = 1
    with pytest.raises(ValueError):
        channel.trip_action = 5

    # Set the trip timeout in milliseconds
    channel.trip_timeout = 2000
    with pytest.raises(ValueError):
        channel.trip_timeout = 0

    # Set the action to be taken when an External Inhibit event occurs for the channel
    channel.external_inhibit_action = 2
    with pytest.raises(ValueError):
        channel.external_inhibit_action = 5

    # Set the channel output mode
    channel.output_mode = 3
    with pytest.raises(ValueError):
        channel.output_mode = 5

    # Set the output polarity of the channel
    channel.output_polarity = "n"
    with pytest.raises(ValueError):
        channel.output_polarity = "x"

    # Set the channel voltage set
    channel.voltage_set = 12.5

    # Set the channel voltage bounds
    channel.voltage_bounds = 10.0

    # Clear the channel from state emergency off
    channel.clear_emergency_off()

    # Set the channel current set
    channel.current_set = 2.5

    # Set the channel current bounds
    channel.current_bounds = 2.0

    # Set the channel voltage ramp speed for up and down direction
    channel.set_channel_voltage_ramp_up_down_speed(250)

    # Set the channel voltage ramp up speed
    channel.channel_voltage_ramp_up_speed = 200

    # Set the channel voltage ramp down speed
    channel.channel_voltage_ramp_down_speed = 150.0

    # Switch on the high voltage with the configured ramp speed
    channel.switch_on_high_voltage()

    # Switch off the high voltage with the configured ramp speed
    channel.switch_off_high_voltage()

    # Shut down the channel high voltage (without ramp)
    channel.shutdown_channel_high_voltage()

    # Clear the channel from state emergency off
    channel.clear_channel_emergency_off()

    # Clear the Channel Event Status register
    channel.clear_event_status()

    # Clears single bits or bit combinations in the Channel Event Status register
    channel.clear_event_bits(3)

    # Set the Channel Event Mask register
    channel.set_event_mask(7)


import argparse
import os
import warnings

import scipy
from PIL import Image

from extract_edges import extract_edges

warnings.filterwarnings("ignore", category=DeprecationWarning)

parser = argparse.ArgumentParser(description='Receiving directory for test')
parser.add_argument("--dir", type=str, default=None)
args = parser.parse_args()

dir = args.dir
list_of_files = os.listdir(dir)
number_of_images = len(list_of_files)

for file in list_of_files:
    img_path = dir + file
    img = Image.open(img_path).resize((224, 224))
    edges = extract_edges(img)
    scipy.misc.imsave("./tmp/" + file, edges)

os.system(
    "python test.py --dataroot ./tmp --name best_model --model test --netG unet_256 --direction BtoA --dataset_mode single --norm batch --num_test " + str(
        number_of_images))

for file in list_of_files:
    os.system("rm ./tmp/" + file)


"""
Code that goes along with the Airflow located at:
http://airflow.readthedocs.org/en/latest/tutorial.html
"""
from datetime import datetime, timedelta

from airflow import DAG
from airflow.operators import BashOperator, PythonOperator

from src.example_module import example_function

default_args = {
    "owner": "airflow",
    "depends_on_past": False,
    "start_date": datetime.now(),
    "email_on_failure": False,
    "email_on_retry": False,
    "retries": 1,
    "retry_delay": timedelta(minutes=5),
    "catchup": False,
    "max_active_runs": 1
}

dag = DAG("example", default_args=default_args, schedule_interval=timedelta(1))

# t1, t2 and t3 are examples of tasks created by instantiating operators
t1 = BashOperator(task_id="print_date", bash_command="date", dag=dag)

t2 = BashOperator(task_id="sleep", bash_command="sleep 5", retries=3, dag=dag)

templated_command = """
    {% for i in range(5) %}
        echo "{{ ds }}"
        echo "{{ macros.ds_add(ds, 7)}}"
        echo "{{ params.my_param }}"
    {% endfor %}
"""

t3 = BashOperator(
    task_id="templated",
    bash_command=templated_command,
    params={"my_param": "Parameter I passed in"},
    dag=dag,
)

t4 = PythonOperator(
    task_id="python_code",
    python_callable=example_function,
    dag=dag
)

t2.set_upstream(t1)
t3.set_upstream(t1)
t4.set_upstream(t1)


import sys
from typing import Tuple

import pygame

import ai
import chess

AI_DEPTH = 4

# Window settings
WIDTH = 1000
HEIGHT = 1000
FPS = 60

# Pygame setup
win = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Chess")
pygame.font.init()

# Chessboard visual settings
TILE_SIZE = 90
WHITE_COLOR = (238, 238, 210)
BLACK_COLOR = (118, 150, 86)
WHITE_SELECTED_COLOR = (246, 246, 105)
BLACK_SELECTED_COLOR = (186, 202, 43)
WHITE_HINT_COLOR = (255, 204, 203)
BLACK_HINT_COLOR = (220, 148, 146)

# Background visual settings
BACKGROUND_COLOR = (49, 46, 43)
background = pygame.Surface((WIDTH, HEIGHT))
background.fill(BACKGROUND_COLOR)
chessboard = pygame.Surface((8 * TILE_SIZE, 8 * TILE_SIZE))

# Promotion box settings and AI button settings
PROMOTION_BORDER_SIZE = 3
PROMOTION_BORDER_COLOR = "#272522"
PROMOTION_BUTTON_BACKGROUND_COLOR = "#1F1E1B"
PROMOTION_PROMOTE_TO_PIECES = (chess.Queen, chess.Knight, chess.Rook, chess.Bishop)
# AI button
AI_BUTTON_WIDTH = int(TILE_SIZE / 1.25)
AI_BUTTON_HEIGHT = int(TILE_SIZE / 2.5)

# Results box settings
RESULTS_BORDER_SIZE = 5
RESULTS_BORDER_COLOR = "#565352"
RESULTS_BACKGROUND_COLOR = "#FFFFFF"
RESULTS_FONT = pygame.font.SysFont("Source Sans Pro", int(TILE_SIZE / 2.75), True)
RESULTS_WIDTH = TILE_SIZE * 3.5
RESULTS_HEIGHT = TILE_SIZE * 4.5
# Result buttons settings
RESULTS_BUTTON_BORDER_SIZE = 3
RESULTS_BUTTON_BORDER_COLOR = "#565352"
RESULTS_BUTTON_BACKGROUND_COLOR = "#7FA650"
RESULTS_BUTTON_FONT = pygame.font.SysFont("Arial", int(TILE_SIZE / 3.25), True)
RESULTS_BUTTON_WIDTH = TILE_SIZE * 2.4
RESULTS_BUTTON_HEIGHT = RESULTS_BUTTON_FONT.get_height() * 1.5

def generate_board():
    """Generates a board with pieces in the correct positions"""
    pieces = [
        chess.Rook((0, 0), False),
        chess.Knight((1, 0), False),
        chess.Bishop((2, 0), False),
        chess.Queen((3, 0), False),
        chess.King((4, 0), False),
        chess.Bishop((5, 0), False),
        chess.Knight((6, 0), False),
        chess.Rook((7, 0), False),
        chess.Rook((0, 7), True),
        chess.Knight((1, 7), True),
        chess.Bishop((2, 7), True),
        chess.Queen((3, 7), True),
        chess.King((4, 7), True),
        chess.Bishop((5, 7), True),
        chess.Knight((6, 7), True),
        chess.Rook((7, 7), True),
    ]

    # Pawns
    for column in range(8):
        pieces.append(chess.Pawn((column, 1), False))
        pieces.append(chess.Pawn((column, 6), True))

    return chess.Board(pieces)

def draw_board(board: chess.Board, selectedPiece: chess.Piece = None):
    """Draws the board with all the pieces"""
    # Gets the valid moves if there is a selected piece
    if selectedPiece:
        possibleMoves = selectedPiece.get_valid_moves(board)

    # Looping through all the tiles
    for column in range(8):
        for rank in range(8):
            # Background color for the square
            # Default colors unless rewriten below
            white = WHITE_COLOR
            black = BLACK_COLOR
            # While having a selected piece
            if selectedPiece:
                # The selected square
                if selectedPiece.position == (column, rank):
                    white = WHITE_SELECTED_COLOR
                    black = BLACK_SELECTED_COLOR
                # Available moves
                elif chess.Position(column, rank) in possibleMoves:
                    white = WHITE_HINT_COLOR
                    black = BLACK_HINT_COLOR

            # Switches black and white color
            if (rank + column) % 2 == 0:
                color = white
            else:
                color = black

            # Gets the tile and draws it
            tile = pygame.Rect((column * TILE_SIZE, rank * TILE_SIZE), (TILE_SIZE, TILE_SIZE))
            pygame.draw.rect(chessboard, color, tile)

            # Adds the piece image to the square
            piece = board.get_piece((column, rank))
            if piece:
                if piece.color == False:
                    chessboard.blit(piece.blackImg, tile.topleft)
                else:
                    chessboard.blit(piece.whiteImg, tile.topleft)

def get_mouse_position() -> chess.Position:
    """Gets the square position under the mouse"""
    mouse = pygame.mouse.get_pos()

    # If the mouse is outside the board, return None
    if (
        mouse[0] > WIDTH / 2 - 8 / 2 * TILE_SIZE
        and mouse[0] < WIDTH / 2 + 8 / 2 * TILE_SIZE
        and mouse[1] > HEIGHT / 2 - 8 / 2 * TILE_SIZE
        and mouse[1] < HEIGHT / 2 + 8 / 2 * TILE_SIZE
    ):
        # Gets the position in tiles from the mouse position
        return chess.Position(
            int((mouse[0] - (WIDTH / 2 - 8 / 2 * TILE_SIZE)) // TILE_SIZE),
            int((mouse[1] - (HEIGHT / 2 - 8 / 2 * TILE_SIZE)) // TILE_SIZE),
        )
    else:
        return None

def draw_result_box(board: chess.Board):
    """Draws the results of the game"""
    resultBox = pygame.Surface((RESULTS_WIDTH, RESULTS_HEIGHT))
    # Background
    resultBox.fill(RESULTS_BACKGROUND_COLOR)
    # Border
    pygame.draw.rect(resultBox, RESULTS_BORDER_COLOR, resultBox.get_rect(), RESULTS_BORDER_SIZE)
    # Write a text of who has won
    if board.result == 0:
        text = "White has won!"
    elif board.result == 1:
        text = "Black has won!"
    else:
        text = "It's a draw!"
    resultText = RESULTS_FONT.render(text, True, (0, 0, 0))
    resultBox.blit(resultText, ((RESULTS_WIDTH - resultText.get_width()) / 2, resultText.get_height() * 2))

    def draw_button(text: str, position: Tuple[int, int]):
        """Draws a button with the given text"""
        # Button size
        button = pygame.Surface((BUTTON_WIDTH, BUTTON_HEIGHT))
        # Background
        button.fill(RESULTS_BUTTON_BACKGROUND_COLOR)
        # Border
        pygame.draw.rect(button, RESULTS_BUTTON_BORDER_COLOR, button.get_rect(), RESULTS_BUTTON_BORDER_SIZE)
        # Button text
        buttonText = RESULTS_BUTTON_FONT.render(text, True, (255, 255, 255))
        # Drawing the text
        button.blit(
            buttonText, ((BUTTON_WIDTH - buttonText.get_width()) / 2, (BUTTON_HEIGHT - buttonText.get_height()) / 2)
        )
        # Drawing the button
        resultBox.blit(button, position)

    BUTTON_WIDTH = RESULTS_BUTTON_WIDTH
    BUTTON_HEIGHT = RESULTS_BUTTON_HEIGHT
    # New game button
    draw_button("New game", ((RESULTS_WIDTH - BUTTON_WIDTH) / 2, RESULTS_HEIGHT / 2 + BUTTON_HEIGHT))
    # Quit button
    draw_button("Quit", ((RESULTS_WIDTH - BUTTON_WIDTH) / 2, RESULTS_HEIGHT / 2 + BUTTON_HEIGHT * 2.5))

    win.blit(resultBox, (WIDTH / 2 - RESULTS_WIDTH / 2, WIDTH / 2 - RESULTS_HEIGHT / 2))

def get_clicked_result():
    """Gets the clicked button in result box"""
    mouse = pygame.mouse.get_pos()

    BUTTON_WIDTH = RESULTS_BUTTON_WIDTH
    BUTTON_HEIGHT = RESULTS_BUTTON_HEIGHT

    newGameButton = pygame.Rect(WIDTH / 2 - BUTTON_WIDTH / 2, HEIGHT / 2 + BUTTON_HEIGHT, BUTTON_WIDTH, BUTTON_HEIGHT)
    if newGameButton.collidepoint(mouse):
        return 0

    quitButton = pygame.Rect(
        WIDTH / 2 - BUTTON_WIDTH / 2, HEIGHT / 2 + BUTTON_HEIGHT * 2.5, BUTTON_WIDTH, BUTTON_HEIGHT
    )
    if quitButton.collidepoint(mouse):
        return 1

def draw_promotion_box(pieceColor: bool = None):
    """Draws the promotion box"""
    BORDER_COLOR = PROMOTION_BORDER_COLOR
    BORDER_SIZE = PROMOTION_BORDER_SIZE
    BUTTON_BACKGROUND_COLOR = PROMOTION_BUTTON_BACKGROUND_COLOR

    promotionBox = pygame.Surface((4 * (TILE_SIZE + BORDER_SIZE) + BORDER_SIZE, TILE_SIZE + BORDER_SIZE * 2))
    # If the piece color is not specified, draw the box as background
    if pieceColor is not None:
        # The actual box
        promotionBox.fill(BORDER_COLOR)

        # Loops through all the promotion pieces and draws them into the box
        for i, piece in enumerate(PROMOTION_PROMOTE_TO_PIECES):
            square = pygame.Rect((i * (TILE_SIZE + BORDER_SIZE) + BORDER_SIZE, BORDER_SIZE, TILE_SIZE, TILE_SIZE))
            pygame.draw.rect(promotionBox, BUTTON_BACKGROUND_COLOR, square)
            if pieceColor:
                promotionBox.blit(piece.whiteImg, square)
            else:
                promotionBox.blit(piece.blackImg, square)
    else:
        # As background
        promotionBox.fill(BACKGROUND_COLOR)

    # Draws the promotion box onto the screen
    win.blit(
        promotionBox,
        (
            WIDTH / 2 - promotionBox.get_width() / 2,
            (HEIGHT - chessboard.get_height()) / 2 - promotionBox.get_height() * 1.1,
        ),
    )

def get_clicked_promotion():
    """Gets the clicked promotion piece under the mouse"""
    BORDER_SIZE = PROMOTION_BORDER_SIZE

    mouse = pygame.mouse.get_pos()

    # Box position, width and height
    width, height = 4 * (TILE_SIZE + BORDER_SIZE) + BORDER_SIZE, TILE_SIZE + BORDER_SIZE * 2
    left = WIDTH / 2 - width / 2
    top = (HEIGHT - chessboard.get_height()) / 2 - height * 1.1

    # Gets the clicked piece and returns it
    buttons = [
        pygame.Rect(left + BORDER_SIZE + (TILE_SIZE + BORDER_SIZE) * i, top + BORDER_SIZE, TILE_SIZE, TILE_SIZE)
        for i in range(4)
    ]
    for button, piece in zip(buttons, PROMOTION_PROMOTE_TO_PIECES):
        if button.collidepoint(mouse):
            return piece

def draw_ai_button(AI):
    """Draws the AI switch button"""
    BORDER_SIZE = PROMOTION_BORDER_SIZE
    BORDER_COLOR = PROMOTION_BORDER_COLOR
    BACKGROUND_COLOR = PROMOTION_BUTTON_BACKGROUND_COLOR

    button = pygame.Surface((AI_BUTTON_WIDTH, AI_BUTTON_HEIGHT))
    button.fill(BACKGROUND_COLOR)
    pygame.draw.rect(button, BORDER_COLOR, button.get_rect(), BORDER_SIZE)

    # AI off
    if AI == None:
        color = (128, 0, 0)
        left = BORDER_SIZE
    else:
        color = (128, 128, 128) if AI else (0, 0, 0)
        left = TILE_SIZE / 1.25 / 2
    pygame.draw.rect(
        button,
        color,
        (left, BORDER_SIZE, TILE_SIZE / 1.25 / 2 - BORDER_SIZE, TILE_SIZE / 2.5 - BORDER_SIZE * 2),
    )

    win.blit(
        button,
        (WIDTH * 0.75 + chessboard.get_width() / 4 - AI_BUTTON_WIDTH / 2, HEIGHT / 2 - AI_BUTTON_HEIGHT / 2),
    )

def clicked_ai_button() -> bool:
    """Returns if the mouse has clicked on the button"""
    return pygame.Rect(
        WIDTH * 0.75 + chessboard.get_width() / 4 - AI_BUTTON_WIDTH / 2,
        HEIGHT / 2 - AI_BUTTON_HEIGHT / 2,
        AI_BUTTON_WIDTH,
        AI_BUTTON_HEIGHT,
    ).collidepoint(pygame.mouse.get_pos())

def update(updateBoard: bool, board: chess.Board, selectedPiece: chess.Piece, AI):
    """Updates the board"""
    # Draws stuff only when needed
    if updateBoard:
        # Promotion box
        if board.promotion:
            draw_promotion_box(board.promotion.color)
        else:
            draw_promotion_box()

        # Chessboard
        draw_board(board, selectedPiece)
        win.blit(chessboard, (WIDTH / 2 - 8 / 2 * TILE_SIZE, HEIGHT / 2 - 8 / 2 * TILE_SIZE))

        # Result box
        if board.result != None:
            draw_result_box(board)

        # AI switch button
        draw_ai_button(AI)

    pygame.display.update()

def main():
    board = generate_board()
    selectedPiece = None
    AI = None

    # Draws the screen for the first time
    chess.assign_images(TILE_SIZE)
    win.blit(background, (0, 0))
    update(True, board, selectedPiece, AI)

    clock = pygame.time.Clock()
    run = True
    while run:
        updateBoard = False

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
            elif event.type == pygame.MOUSEBUTTONDOWN:
                # Clicking on AI switch button
                if clicked_ai_button():
                    # Switches the AI on and off
                    if AI == None:
                        # Turn on
                        if not board.lastMove:
                            # First move
                            AI = True
                        else:
                            # Locks the AI to play as the current color to move
                            AI = not board.lastMove.piece.color
                        ai.make_move(board, AI_DEPTH)
                    else:
                        # Turn off
                        AI = None
                    updateBoard = True
                # Getting the clicked button in the result box (End of game)
                if board.result != None:
                    clickedOn = get_clicked_result()
                    # New game
                    if clickedOn == 0:
                        board = generate_board()
                        updateBoard = True
                    # Quit
                    elif clickedOn == 1:
                        pygame.display.quit()
                        pygame.quit()
                        sys.exit()
                # Getting the clicked button in the promotion box (When a pawn is promoting)
                elif board.promotion:
                    # Promoting a pawn
                    promoteTo = get_clicked_promotion()
                    if promoteTo:
                        board.promote(promoteTo)
                        updateBoard = True
                # Regular piece movement and selection
                else:
                    # Moving and selecting pieces
                    # If there is a selected piece, move it
                    clickedTile = get_mouse_position()
                    if selectedPiece:
                        # Only move the selected piece when clicked on the board
                        if clickedTile:
                            # Only move to a valid position
                            if clickedTile in selectedPiece.get_valid_moves(board):
                                board.move(selectedPiece, clickedTile)
                                if AI != None:
                                    ai.make_move(board, AI_DEPTH)
                                updateBoard = True
                            selectedPiece = None
                        updateBoard = True
                    else:
                        # Only selects a piece when clicked on the board
                        if clickedTile:
                            # Selects a piece
                            selectedPiece = board.get_piece(get_mouse_position())
                            updateBoard = True

        # Updates the board
        update(updateBoard, board, selectedPiece, AI)

        # Locking the framerate
        clock.tick(FPS)

if __name__ == "__main__":
    main()


import codecs
import sys
import json
import tqdm
import os
# 处理SemanticScholar 数据的脚本
# from elasticsearch import Elasticsearch
# from elasticsearch.helpers import bulk

data_dir = "H:\\Scholar"
paper_path = os.path.join(data_dir)

bad_data_num =0

file_list = []
author_list = []
author_dict = {}

venue_list = []
venues ={}
journal_list = []
journals = {}
journal_out_list = []

in_citation_dict = {}
in_citation_list = []

for paper_file in os.listdir(paper_path):
    domain = os.path.abspath(paper_path)
    if paper_file.startswith("s2-corpus") and  not paper_file.endswith(".gz"):
        paper_file = os.path.join(domain,paper_file)
        file_list.append(paper_file)
file_list.sort()

# file_list = ["H:\\Scholar\\s2-corpus-000"]
def proc_file_list(file_list,label):
    global  bad_data_num
    file_num = 0
    for file in file_list:
        with codecs.open(file,'r','utf-8') as f:

            i = 0
            for line in f.readlines():
                if len(line.strip()) == 0:
                    break

                try:
                    dict_item = json.loads(line)
                except:
                    bad_data_num += 1
                    continue
                list_itme = list(dict_item["fieldsOfStudy"])
                if "Computer Science" not in list_itme :
                    continue
                if label == "authors":
                    for author in dict_item['authors']:
                        # print(author)
                        if (str(author['ids']) in author_dict.keys()) == True:
                            author_dict[str(author['ids'])]["citation_num"] += len(dict_item['inCitations'])
                            author_dict[str(author['ids'])]["publish_num"] += 1

                        else:
                            item = {"author_id" : list(author['ids']),"publish_num" : 1,"name":author['name'],'org':"","citation_num":len(dict_item['inCitations'])}
                            author_dict[str(author['ids'])] = item
                elif label == "journal":
                    venue,journalName,journalVolume,journalPages = dict_item['venue'],dict_item['journalName'],dict_item['journalVolume'],dict_item['journalPages']
                    journalName = str(journalName).strip()
                    if journalName != "":
                        if journalName not in journal_list:
                            item = {"name":journalName,"volume":journalVolume,"pages":journalPages,'id':len(journal_list),'venue':venue}
                            item['publish_num'],item['citation_num'] = 1,len(dict_item['inCitations'])

                            item['authors'] = []
                            for author in dict_item['authors']:
                                item['authors'].append(str(author['ids']))
                            item['authors_num'] = len(item['authors'])  #
                            journal_list.append(journalName)
                            journals[journalName] = item
                        else:
                            journals[journalName]['publish_num'], journals[journalName]['citation_num'] = journals[journalName]['publish_num']+1, journals[journalName]['citation_num']+len(dict_item['inCitations'])
                            for author in dict_item['authors']:
                                if (str(author['ids']) not in journals[journalName]["authors"] ) :
                                    journals[journalName]['authors'].append(str(author['ids']))
                            journals[journalName]['authors_num'] = len(journals[journalName]['authors'])  # 投稿人数

                elif label == "inCitations":
                    item = {"id":dict_item["id"],"inCitations":dict_item["inCitations"],"inCitationsNum":len(dict_item["inCitations"])}
                    # in_citation_dict[dict_item["id"]] = item
                    in_citation_list.append(item)
                i += 1
            file_num += 1

        if label == "inCitations":
            print(file_num,len(in_citation_dict.keys()))
            write_inCitations_list()
        elif label == "authors":
            print(file_num,len(author_dict))
        elif label == "journal":
            print(file_num, len(journal_list))

def make_author_list():
    print(len(list(author_dict.keys())))
    for key in list(author_dict.keys()):
        author_list.append(author_dict.pop(key))
def write_author_list():
    with codecs.open(data_dir+"authors.txt","w") as f:
        for author in author_list:
            f.write(json.dumps(author)+"\n")
    author_list.clear()
def make_journal_out_list():
    print(len(list(journals.keys())))
    for key in list(journals.keys()):
        journal_out_list.append(journals.pop(key))

def write_journal_out_list():
    with codecs.open(data_dir+"journal.txt","w") as f:
        for journal in journal_out_list:
            del journal['authors']
            f.write(json.dumps(journal)+"\n")
    journal_out_list.clear()
def write_inCitations_list():
    with codecs.open(data_dir+"inCitations.txt","a") as f:
        for item in in_citation_list:
            f.write(json.dumps(item)+"\n")
    in_citation_list.clear()
proc_file_list(file_list,"authors")
make_author_list()
write_author_list()

proc_file_list(file_list,"journal")
make_journal_out_list()
write_journal_out_list()

proc_file_list(file_list,"inCitations")


import unittest
from unittest.mock import patch

import tweepy

from whotweeted import get_country_code, who_is_output
from whotweeted import load_cache

DATA = dict(AU='875639674244444160',
            ES='875669971954806784',
            nopb='846302762736504833',
            noloc='844092059988508673',
            badid='8756396742444441da'
            )
get_tweet = lambda x: load_cache(DATA.get(x))  # noqa E731

class WhoTweetedTestCase(unittest.TestCase):

    @patch.object(tweepy.API, 'get_status', return_value=get_tweet('AU'))
    def test_julian(self, mock_method):
        tweetid = DATA.get('AU')
        country = get_country_code(tweetid)
        who_is_out = who_is_output(country)
        self.assertEqual(country, 'AU')
        self.assertIn('Julian', who_is_out)

    @patch.object(tweepy.API, 'get_status', return_value=get_tweet('ES'))
    def test_bob(self, mock_method):
        tweetid = DATA.get('ES')
        country = get_country_code(tweetid)
        who_is_out = who_is_output(country)
        self.assertEqual(country, 'ES')
        self.assertIn('Bob', who_is_out)

    @patch.object(tweepy.API, 'get_status', return_value=get_tweet('nopb'))
    def test_no_pybites_account(self, mock_method):
        tweetid = DATA.get('nopb')
        with self.assertRaises(ValueError):
            get_country_code(tweetid)

    @patch.object(tweepy.API, 'get_status', return_value=get_tweet('noloc'))
    def test_no_location_in_tweet(self, mock_method):
        tweetid = DATA.get('noloc')
        with self.assertRaises(AttributeError):
            get_country_code(tweetid)

    # not really a return value, it crashes before decorator can cash tweet
    @patch.object(tweepy.API, 'get_status', return_value=get_tweet('nopb'))
    def test_bad_tweet_id(self, mock_method):
        tweetid = DATA.get('badid')
        print(tweetid)
        with self.assertRaises(ValueError):
            get_country_code(tweetid)

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


from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
import smtplib
COMMASPACE = ', '

class AlarmEmail(object):
    def __init__(self, toAddrList=["alee@picarro.com"], fromAddr="alee@picarro.com"):
        self.smtpHostname = "woodstock.blueleaf.com"
        self.toAddrList = toAddrList
        self.fromAddr = fromAddr

    def sendMsg(self, subject="Message from CRDS", msg="This is a testing alarm message"):
        msg = MIMEText(msg)
        outer = MIMEMultipart()
        outer['Subject'] = subject
        outer['To'] = COMMASPACE.join(self.toAddrList)
        outer['From'] = self.fromAddr
        outer.attach(msg)
        mailServer = smtplib.SMTP(self.smtpHostname)
        mailServer.sendmail(self.fromAddr, self.toAddrList, outer.as_string())


from testapp.models import Book, Author
from django.db.models import Count
from django.db import connection

def list_books():
    books = Book.objects.select_related().all()
    for book in books:
        print(f'"{book.title}".{book.author.name}')

def author_books():
    authors  = Author.objects.select_related().all()
    for author in authors:
        author_books = author.books.all()
        print(f'{author.name}: ',", ".join([f'"{book.title}"' for book in author_books]) )

def authors_rank():
    authors  = Author.objects.select_related() \
        .annotate(num_books=Count('books')) \
        .order_by('-num_books')
    for author in authors:
        author_books = author.books.all()
        print(f'{author.name}: ', f'{author.num_books}'  )


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 23 08:07:20 2020

@author: agiovann
"""
from .caiman_functions import signal_filter
import cv2
from functools import partial
import matplotlib.pyplot as plt
import numpy as np
#import scipy
#from scipy.interpolate import interp1d
from scipy import stats
from scipy.signal import argrelextrema, butter, sosfilt, sosfilt_zi

class OnlineFilter(object):
    def __init__(self, freq, fr, order=3, mode='high'):
        '''
        Object encapsulating Online filtering for spike extraction traces
        Args:
            freq: float
            cutoff frequency

        order: int
            order of the filter

        mode: str
            'high' for high-pass filtering, 'low' for low-pass filtering

        '''
        self.freq = freq
        self.fr = fr
        self.mode = mode
        self.order=order
        self.normFreq = freq / (fr / 2)
        self.filt = butter(self.order, self.normFreq, self.mode, output='sos')
        self.z_init = sosfilt_zi(self.filt)

    def fit(self, sig):
        """
        Online filter initialization and running offline

        Parameters
        ----------
        sig : ndarray
            input signal to initialize
        num_frames_buf : int
            frames to use for buffering

        Returns
        -------
        sig_filt: ndarray
            filtered signal

        """
        sig_filt = signal_filter(sig, freq=self.freq, fr=self.fr, order=self.order, mode=self.mode)
        # result_init, z_init = signal.sosfilt(b, data[:,:20000], zi=z)
        self.z_init = np.repeat(self.z_init[:,None,:], sig.shape[0], axis=1)

        #sos_all = np.zeros(sig_filt.shape)

        for i in range(0,sig.shape[-1]-1):
            _ , self.z_init = sosfilt(self.filt, np.expand_dims(sig[:,i], axis=1), zi=self.z_init)

        return sig_filt

    def fit_next(self, sig):

        sig_filt, self.z_init = sosfilt(self.filt, np.expand_dims(sig,axis=1), zi=self.z_init)
        return sig_filt.squeeze()

def rolling_window(ndarr, window_size, stride):
        """
        generates efficient rolling window for running statistics
        Args:
            ndarr: ndarray
                input pixels in format pixels x time
            window_size: int
                size of the sliding window
            stride: int
                stride of the sliding window
        Returns:
                iterator with views of the input array

        """
        for i in range(0,ndarr.shape[-1]-window_size-stride+1,stride):
            yield ndarr[:,i:np.minimum(i+window_size, ndarr.shape[-1])]

        if i+stride != ndarr.shape[-1]:
           yield ndarr[:,i+stride:]

def estimate_running_std(signal_in, win_size=20000, stride=5000,
                         idx_exclude=None, q_min=25, q_max=75):
    """
    Function to estimate ROBUST runnning std

    Args:
        win_size: int
            window used to compute running std to normalize signals when
            compensating for photobleaching

        stride: int
            corresponding stride to win_size

        idx_exclude: iterator
            indexes to exclude when computing std

        q_min: float
            lower percentile for estimation of signal variability (do not change)

        q_max: float
            higher percentile for estimation of signal variability (do not change)

    Returns:
        std_run: ndarray
            running standard deviation

    """
    if idx_exclude is not None:
        signal = signal_in[np.setdiff1d(range(len(signal_in)), idx_exclude)]
    else:
        signal = signal_in
    iter_win = rolling_window(signal[None,:],win_size,stride)
    myperc = partial(np.percentile, q=[q_min,q_max], axis=-1)
    res = np.array(list(map(myperc,iter_win))).T.squeeze()
    iqr = (res[1]-res[0])/1.35
    std_run = cv2.resize(iqr,signal_in[None,:].shape).squeeze()
    return std_run

def compute_std(peak_height):
    data = peak_height - np.median(peak_height)
    ff1 = -data * (data < 0)
    Ns = np.sum(ff1 > 0)
    std = np.sqrt(np.divide(np.sum(ff1**2), Ns))
    return std

def compute_thresh(peak_height, prev_thresh=None, delta_max=0.03, number_maxima_before=1):
    kernel = stats.gaussian_kde(peak_height)
    x_val = np.linspace(0,np.max(peak_height),1000)
    pdf = kernel(x_val)
    second_der = np.diff(pdf,2)
    mean = np.mean(peak_height)
    min_idx = argrelextrema(kernel(x_val), np.less)

    minima = x_val[min_idx]
    minima = minima[minima>mean]
    minima_2nd = argrelextrema(second_der, np.greater)
    minima_2nd = x_val[minima_2nd]

    if prev_thresh is None:
        delta_max = np.inf
        prev_thresh = mean

    thresh = prev_thresh

    if (len(minima)>0) and (np.abs(minima[0]-prev_thresh)< delta_max):
        thresh = minima[0]
        mnt = (minima_2nd-thresh)
        mnt = mnt[mnt<0]
        thresh += mnt[np.maximum(-len(mnt)+1,-number_maxima_before)]
    #else:
    #    thresh = 100

    thresh_7 = compute_std(peak_height) * 7.5

    """
    print(f'previous thresh: {prev_thresh}')
    print(f'current thresh: {thresh}')
    """
    plt.figure()
    plt.plot(x_val, pdf,'c')
    plt.plot(x_val[2:],second_der*500,'r')
    plt.plot(thresh,0, '*')
    plt.vlines(thresh_7, 0, 2, color='r')
    plt.pause(0.1)

    return thresh

def non_symm_median_filter(t, filt_window):
    m = t.copy()
    for i in range(len(t)):
        if (i > filt_window[0]) and (i < len(t) - filt_window[1]):
            m[i] = np.median(t[i - filt_window[0] : i + filt_window[1] + 1])
    return m


#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""Load data from MongoDB.
   Note that, the ReadModelData class is not picklable,
     since MongoClient returns thread.lock objects.
    @author   : Liangjun Zhu
    @changelog: 18-01-02  - lj - separated from plot_timeseries.\n
                18-02-09  - lj - compatible with Python3.\n
"""
from __future__ import absolute_import

import os
import sys
from collections import OrderedDict

from pygeoc.utils import StringClass, text_type

if os.path.abspath(os.path.join(sys.path[0], '..')) not in sys.path:
    sys.path.insert(0, os.path.abspath(os.path.join(sys.path[0], '..')))

from preprocess.db_mongodb import ConnectMongoDB, MongoQuery
from preprocess.text import DBTableNames, ModelCfgFields, FieldNames, SubbsnStatsName, \
    DataValueFields, DataType, StationFields

class ReadModelData(object):
    def __init__(self, host, port, dbname):
        """Initialization."""
        client = ConnectMongoDB(host, port)
        conn = client.get_conn()
        self.maindb = conn[dbname]
        self.filein_tab = self.maindb[DBTableNames.main_filein]
        self._climdb_name = self.HydroClimateDBName
        self.climatedb = conn[self._climdb_name]
        self._mode = ''
        self._interval = -1
        # UTCTIME
        self._stime = None
        self._etime = None
        self._outletid = -1

    @property
    def HydroClimateDBName(self):
        climtbl = self.maindb[DBTableNames.main_sitelist]
        allitems = climtbl.find()
        if not allitems.count():
            raise RuntimeError('%s Collection is not existed or empty!' %
                               DBTableNames.main_sitelist)
        for item in allitems:
            if FieldNames.db in item:
                self._climdb_name = item.get(FieldNames.db)
                break
        return self._climdb_name

    @property
    def Mode(self):
        """Get simulation mode."""
        if self._mode != '':
            return self._mode.upper()
        mode_dict = self.filein_tab.find_one({ModelCfgFields.tag: FieldNames.mode})
        self._mode = mode_dict[ModelCfgFields.value]
        if isinstance(self._mode, text_type):
            self._mode = str(self._mode)
        return self._mode.upper()

    @property
    def Interval(self):
        if self._interval > 0:
            return self._interval
        findinterval = self.filein_tab.find_one({ModelCfgFields.tag: ModelCfgFields.interval})
        self._interval = int(findinterval[ModelCfgFields.value])
        return self._interval

    @property
    def OutletID(self):
        if self._outletid > 0:
            return self._outletid
        self._outletid = int(MongoQuery.get_init_parameter_value(self.maindb,
                                                                 SubbsnStatsName.outlet))
        return self._outletid

    @property
    def SimulationPeriod(self):
        if self._stime is not None and self._etime is not None:
            return self._stime, self._etime
        st = self.filein_tab.find_one({ModelCfgFields.tag: ModelCfgFields.stime})[
            ModelCfgFields.value]
        et = self.filein_tab.find_one({ModelCfgFields.tag: ModelCfgFields.etime})[
            ModelCfgFields.value]
        st = StringClass.get_datetime(st)
        et = StringClass.get_datetime(et)
        if self._stime is None or st > self._stime:
            self._stime = st
        if self._etime is None or et < self._etime:
            self._etime = et
        if st > self._etime > self._stime:
            self._stime = st
            self._etime = et
        return self._stime, self._etime

    def Precipitation(self, subbsn_id, start_time, end_time):
        """
        The precipitation is read according to the subbasin ID.
            Especially when plot a specific subbasin (such as ID 3).
            For the whole basin, the subbasin ID is 0.
        Returns:
            Precipitation data list with the first element as datetime.
            [[Datetime1, value1], [Datetime2, value2], ..., [Datetimen, valuen]]
        """
        pcp_date_value = list()
        sitelist_tab = self.maindb[DBTableNames.main_sitelist]
        findsites = sitelist_tab.find_one({FieldNames.subbasin_id: subbsn_id,
                                           FieldNames.mode: self.Mode})
        if findsites is not None:
            site_liststr = findsites[FieldNames.site_p]
        else:
            raise RuntimeError('Cannot find precipitation site for subbasin %d.' % subbsn_id)
        site_list = StringClass.extract_numeric_values_from_string(site_liststr)
        site_list = [int(v) for v in site_list]
        if len(site_list) == 0:
            raise RuntimeError('Cannot find precipitation site for subbasin %d.' % subbsn_id)

        pcp_dict = OrderedDict()

        for pdata in self.climatedb[DBTableNames.data_values].find(
                {DataValueFields.utc: {"$gte": start_time, '$lte': end_time},
                 DataValueFields.type: DataType.p,
                 DataValueFields.id: {"$in": site_list}}).sort([(DataValueFields.utc, 1)]):
            curt = pdata[DataValueFields.utc]
            curv = pdata[DataValueFields.value]
            if curt not in pcp_dict:
                pcp_dict[curt] = 0.
            pcp_dict[curt] += curv
        # average
        if len(site_list) > 1:
            for t in pcp_dict:
                pcp_dict[t] /= len(site_list)
        for t, v in pcp_dict.items():
            # print(str(t), v)
            pcp_date_value.append([t, v])
        print('Read precipitation from %s to %s done.' % (start_time.strftime('%c'),
                                                          end_time.strftime('%c')))
        return pcp_date_value

    def Observation(self, subbsn_id, vars, start_time, end_time):
        """Read observation data of given variables.

        Changelog:
          - 1. 2018-8-29 Use None when the observation of one variables is absent.

        Returns:
            1. Observed variable names, [var1, var2, ...]
            2. Observed data dict of selected plotted variables, with UTCDATETIME.
               {Datetime: [value_of_var1, value_of_var2, ...], ...}
        """
        vars_existed = list()
        data_dict = OrderedDict()

        coll_list = self.climatedb.collection_names()
        if DBTableNames.observes not in coll_list:
            return None, None
        isoutlet = 0
        if subbsn_id == self.OutletID:
            isoutlet = 1

        def get_observed_name(name):
            """To avoid the prefix of subbasin number."""
            if '_' in name:
                name = name.split('_')[1]
            return name

        def get_basename(name):
            """Get base variable name, e.g., SED for SED and SEDConc."""
            name = get_observed_name(name)
            if 'Conc' in name:
                name = name.split('Conc')[0]
            return name

        siteTbl = self.climatedb[DBTableNames.sites]
        obsTbl = self.climatedb[DBTableNames.observes]
        for i, param_name in enumerate(vars):
            site_items = siteTbl.find_one({StationFields.type: get_basename(param_name),
                                           StationFields.outlet: isoutlet,
                                           StationFields.subbsn: subbsn_id})

            if site_items is None:
                continue
            site_id = site_items.get(StationFields.id)
            for obs in obsTbl.find({DataValueFields.utc: {"$gte": start_time, '$lte': end_time},
                                    DataValueFields.type: get_observed_name(param_name),
                                    DataValueFields.id: site_id}).sort([(DataValueFields.utc, 1)]):

                if param_name not in vars_existed:
                    vars_existed.append(param_name)
                curt = obs[DataValueFields.utc]
                curv = obs[DataValueFields.value]
                if curt not in data_dict:
                    data_dict[curt] = [None] * len(vars)
                data_dict[curt][i] = curv
        if not vars_existed:
            return None, None
        # remove the redundant None in data_dict, in case of len(vars_existed) != len(vars)
        for i, vname in enumerate(vars):
            if vname in vars_existed:
                continue
            for dt, adata in list(data_dict.items()):
                del adata[i]

        print('Read observation data of %s from %s to %s done.' % (','.join(vars_existed),
                                                                   start_time.strftime('%c'),
                                                                   end_time.strftime('%c')))
        return vars_existed, data_dict

def main():
    """Functional tests."""
    import datetime

    host = '192.168.253.203'
    port = 27018
    dbname = 'youwuzhen10m_longterm_model'
    stime = datetime.datetime(2013, 1, 1, 0, 0)
    etime = datetime.datetime(2013, 12, 31, 0, 0)
    rd = ReadModelData(host, port, dbname)
    print(rd.HydroClimateDBName)
    print(rd.Precipitation(4, stime, etime))
    print(rd.Observation(4, ['Q'], stime, etime))

if __name__ == "__main__":
    main()


import json
import logging
import os
import re
import sys
from math import floor
from zipfile import ZipFile
import glob
from optparse import OptionParser

LOGGER = logging.getLogger(__name__)

def unzip_osz(filepath, dst):
    filename, ext = os.path.splitext(filepath)
    dstpath = os.path.join(dst, os.path.basename(filename))
    LOGGER.info(dstpath)
    with ZipFile(filepath, "r") as z:
        if not os.path.exists(dstpath):
            os.mkdir(dstpath)
        z.extractall(path=dstpath)

    return dstpath

def get_beatmap_data(filepath):
    """Reads osu file and returns metadata. Cannot use ini parser reliably as it is not a proper INI file

    Sometimes the osu file leaves comments, so it is more reliable to parse this section manually and
    get the information that we need

    Top sections contain metadata with key:val split
    Bottom sections are a list of objects with ,: separated parameters
    """
    f = open(filepath, "rb")
    f.seek(0)

    metadata = {}
    objs = {}

    # first line is osu file format
    metadata["format"] = re.match("osu file format (.+)", f.readline().decode()).group(
        1
    )
    LOGGER.info(f"Got file format {metadata['format']}")

    obj_headers = ["Events", "TimingPoints", "HitObjects"]

    # 0 = skip, 1 = keyval, 2 = parameterlist
    linefmt = 1
    section = None
    for line in f:
        line = line.decode()
        line = line.strip("\r\n")
        if re.match("\/\/", line) or not line or line == "":
            continue

        # anything with obj lists
        obj_headers = ["Events", "TimingPoints", "HitObjects"]

        # [Section] header
        matches = re.match("\[(.+)\]", line)
        if matches and matches.group(1):
            section = matches.group(1)

            if section == "Editor":
                linefmt = 0

            # everything events and below is object list
            elif section in obj_headers:
                linefmt = 2
                objs[section] = []

            else:
                linefmt = 1

        elif linefmt == 0:
            continue
        elif linefmt == 1:
            key, val = list(map(lambda x: x.strip(" "), line.split(":")))
            metadata[key] = val
        elif linefmt == 2:
            vals = list(map(lambda x: x.strip(" "), line.split(",")))
            objs[section].append(vals)
    return metadata, objs

def sanitise_metadata(m):
    for k, v in m.items():
        for fn in (int, float):
            try:
                m[k] = fn(v)
            except:
                continue

    return m

def sanitise_event(e):
    ret = {}

    if len(e) < 2:
        LOGGER.error(f"Unparseable event {e}")

    ret["startTime"] = float(e[1])

    if e[0] == "0":
        ret["eventType"] = "bg"
        ret["file"] = e[2].strip('"')
        ret["x"] = int(e[3])
        ret["y"] = int(e[4])
    else:
        LOGGER.error(f"Unsupported event {e[0]}")
        ret["eventType"] = "unsupported"

    # not supporting anything else right now
    return ret

def sanitise_timing(e):
    ret = {}

    ret["uninherited"] = True if e[6] == "1" else False

    # this can either be measure value, or SV change
    if ret["uninherited"]:
        ret["beatLength"] = float(e[1])
    else:
        ret["sv_mult"] = -1.0 / (float(e[1]) / 100.0)

    ret["time"] = int(e[0])
    ret["meter"] = int(e[2])
    ret["sampleSet"] = int(e[3])
    ret["sampleIndex"] = int(e[4])
    ret["volume"] = int(e[5])
    ret["effects"] = int(e[7])

    return ret

def sanitise_mania_hitobj(e, n):
    ret = {}

    ret["lane"] = floor(int(e[0]) * n / 512)
    ret["time"] = int(e[2])
    type_int = int(e[3])

    # note last variable is empty as .osu has trailing :
    tail = e[5].split(":")

    if (type_int >> 0) & 1:
        ret["ln"] = False
    elif (type_int >> 7) & 1:
        ret["ln"] = True
        ret["time_end"] = int(tail[0])
    ret["hitSound"] = int(e[4])
    ret["sample"] = tail[-2]

    return ret

def _measure_time_from_bpm(bpm):
    return 1 / (bpm / 60 / 1000)

def _bpm_from_measure_time(ms):
    return 1 / ms * 1000 * 60

def mania_calc_offset(timings):
    """Calculate the required offset from start for timings

    BMS gets measures from the BPM value, we can offset the measure by changing BPM
    Calculate how much offset by checking the first timing point for the BPM
    (this would be 1/beatLength * 1000 * 60)
    """

    first_timing = [x for x in timings if x["uninherited"]][0]
    initial_bpm = _bpm_from_measure_time(first_timing["beatLength"])
    LOGGER.info(f"Got first timing BPM {initial_bpm}")

    offset_ms = (first_timing["time"] / first_timing["beatLength"] % 1) * first_timing[
        "beatLength"
    ]

    # how much the audio needs to shift in order to create a full measure at start of track
    shift_ms = first_timing["beatLength"] - offset_ms
    LOGGER.info(f"Got offset of {shift_ms}")

    return initial_bpm, shift_ms

def mania_add_offset(obj, offset):
    obj["time"] += offset
    if "time_end" in obj:
        obj["time_end"] += offset
    return obj

def extract_osz(filepath):
    with ZipFile(filepath, "r") as osz:
        osz.extractall()

def _mania_ms_to_pulse(ms, measure_ms, resolution):
    """Given an osumania hitobj, convert the ms into pulse (ignoring previous timing points)"""
    measure_pulse = (ms / measure_ms) * resolution
    return measure_pulse

def bmson_gen_note(maniaobj, beat_ms, time_offset):
    """Generate bmson note from osumania objects and timings"""
    note = {}
    note["x"] = maniaobj["lane"] + 1

    note["y"] = _mania_ms_to_pulse(maniaobj["time"] - time_offset, beat_ms, 240)
    note["y"] = int(round(note["y"], 1))

    if not maniaobj["ln"]:
        note["l"] = 0
    else:
        diff = maniaobj["time_end"] - maniaobj["time"]
        note["l"] = _mania_ms_to_pulse(diff, beat_ms, 240)
        note["l"] = int(round(note["l"], 1))

    return note

def bmson_group_mania_soundchannels(hitobjs, timings, hitsounds):
    """bmson format groups notes with the same hitsounds together"""

    timings_i = iter(timings)

    # current timing reference = at x time, y beats per measure
    c_timing_ref = next(timings_i, None)
    c_next_ref = next(timings_i, None)
    if not c_timing_ref:
        LOGGER.error("No timings in list")
        return

    if not c_timing_ref["uninherited"]:
        LOGGER.error("Expected first timing point to be uninherited")
        return

    ref_measure_ms = c_timing_ref["beatLength"]
    measure_ms = ref_measure_ms

    # the total amount of pulses elapsed since beginning of timing point
    total_pulses = _mania_ms_to_pulse(c_timing_ref["time"], measure_ms, 240)

    sound_channels = []
    default_channel = {"name": "0", "notes": []}
    bpm_events = []

    for o in hitobjs:
        if c_next_ref and c_next_ref["time"] <= o["time"]:
            time_diff = c_next_ref["time"] - c_timing_ref["time"]
            total_pulses += _mania_ms_to_pulse(time_diff, measure_ms, 240)

            c_timing_ref = c_next_ref
            c_next_ref = next(timings_i, None)

            if not c_timing_ref["uninherited"]:
                target_ref_ms = ref_measure_ms
                target_ms = ref_measure_ms / c_timing_ref["sv_mult"]
            else:
                target_ref_ms = c_timing_ref["beatLength"]
                target_ms = target_ref_ms
                LOGGER.warning("Multiple bpm settings may not work")

            # check if values are sensible
            if 10 < target_ms < 9999:
                measure_ms = target_ms
                ref_measure_ms = target_ref_ms

            bpm_event = {"y": total_pulses, "bpm": _bpm_from_measure_time(measure_ms)}
            bpm_events.append(bpm_event)

        sample = o["sample"]
        if sample != "0" and hitsounds:
            channel_obj = next(
                filter(lambda x: x["name"] == sample, sound_channels), None
            )
        else:
            channel_obj = default_channel
        if not channel_obj:
            channel_obj = {"name": sample, "notes": []}
            sound_channels.append(channel_obj)

        note_obj = bmson_gen_note(o, measure_ms, c_timing_ref["time"])
        note_obj["y"] += total_pulses
        channel_obj["notes"].append(note_obj)

    sound_channels.append(default_channel)
    return sound_channels, bpm_events

def bmson_gen_main_audio_info(pulse, audiofile):
    """Generates the main audio file name in osumania at the correct offset"""
    channel_obj = {"name": audiofile, "notes": []}

    start_obj = {"x": 0, "y": pulse, "c": True}
    channel_obj["notes"].append(start_obj)

    return channel_obj

def bmson_gen_info(metadata):
    info = {}
    info["title"] = metadata["TitleUnicode"]
    info["subtitle"] = metadata["Version"]
    info["artist"] = metadata["ArtistUnicode"]
    info["subartists"] = [f'obj:{metadata["Creator"]}']
    info["genre"] = "O!M Converted"
    info["mode_hint"] = "beat-7k"
    info["level"] = 0
    info["preview_music"] = metadata["AudioFilename"]
    info["resolution"] = 240

    return info

def bmson_gen_bga(bg):
    # only images for now
    bga = {
        "bga_header": [{"id": 0, "name": bg}],
        "bga_events": [{"id": 0, "y": 0}],
        "layer_events": [],
        "poor_events": [],
    }
    return bga

def convert_mania_chart(filepath, dstpath, extra_offset, hitsounds):
    LOGGER.info(f"Converting {filepath}")
    chart_data, chart_objs = get_beatmap_data(filepath)

    # sanitise collected data
    chart_data = sanitise_metadata(chart_data)

    if chart_data["CircleSize"] != 7:
        return

    chart_events_all = list(map(sanitise_event, chart_objs["Events"]))
    chart_events = list(filter(lambda x: x["eventType"] != "unused", chart_events_all))
    chart_timings = list(map(sanitise_timing, chart_objs["TimingPoints"]))
    chart_hitobjs = list(
        map(
            lambda x: sanitise_mania_hitobj(x, chart_data["CircleSize"]),
            chart_objs["HitObjects"],
        )
    )

    # calculate offset for measures
    bpm, offset = mania_calc_offset(chart_timings)
    bpm = round(bpm, 3)
    offset = round(offset, 3)

    chart_hitobjs = list(
        map(lambda x: mania_add_offset(x, offset + extra_offset), chart_hitobjs)
    )
    chart_timings = list(
        map(lambda x: mania_add_offset(x, offset + extra_offset), chart_timings)
    )

    for i in chart_hitobjs[0:5]:
        print(i)

    """BMS Chart processing"""
    # make info dictionary
    info = bmson_gen_info(chart_data)

    # add timing data
    info["init_bpm"] = bpm
    bg = next(filter(lambda x: x["eventType"] == "bg", chart_events), "")["file"]
    info["eyecatch_image"] = bg
    info["back_image"] = bg

    print(info)

    # make sound channels
    channels, bpm_events = bmson_group_mania_soundchannels(chart_hitobjs, chart_timings, hitsounds)

    # calc pulse for first audio
    first_length = chart_timings[0]["beatLength"]
    pulse = _mania_ms_to_pulse(offset + chart_data["AudioLeadIn"], first_length, 240)
    pulse = int(pulse)

    channels.append(bmson_gen_main_audio_info(pulse, chart_data["AudioFilename"]))

    bmson = {
        "version": "1.0.0",
        "info": info,
        "bga": bmson_gen_bga(bg),
        "bpm_events": bpm_events,
        "lines": None,
        "stop_events": None,
        "sound_channels": channels,
    }

    filebase = os.path.basename(filepath)
    dstfile = os.path.join(dstpath, f"{filebase}.bmson")
    with open(dstfile, "w") as f:
        json.dump(bmson, f, indent=2)

if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)

    parser = OptionParser()
    parser.add_option("-z", "--osz", dest="osz", help="mania beatmap to convert")
    parser.add_option("-d", "--dst", dest="dst", help="destination bms directory")
    parser.add_option("-o", "--offset", dest="offset", help="offset override")
    parser.add_option(
        "-s",
        "--hitsounds",
        dest="hitsounds",
        default=False,
        help="make dedicated hitsound channels, default off",
    )
    parser.add_option(
        "-p",
        "--present",
        dest="preset",
        default="beatoraja",
        help="offset preset for mp3 [beatoraja/bemuse] (defaults to beatoraja)",
    )

    opt, args = parser.parse_args()
    if not opt.osz:
        parser.error("osz not given")
    if not opt.dst:
        parser.error("dst not given")

    if opt.offset:
        try:
            offset = int(opt.offset)
        except ValueError:
            offset = 0

    elif opt.preset and opt.preset == "bemuse":
        offset = 5

    """Mania chart processing"""
    # get raw data of beatmap
    dstfolder = unzip_osz(opt.osz, opt.dst)
    LOGGER.info(dstfolder)
    for file in glob.glob(f"{dstfolder}/*.osu"):
        convert_mania_chart(file, dstfolder, offset, opt.hitsounds)


from itertools import product

import numpy as np
import pytest

from pandas import DataFrame, Series
import pandas._testing as tm
from pandas.core.base import DataError

# gh-12373 : rolling functions error on float32 data
# make sure rolling functions works for different dtypes
#
# NOTE that these are yielded tests and so _create_data
# is explicitly called.
#
# further note that we are only checking rolling for fully dtype
# compliance (though both expanding and ewm inherit)

class Dtype:
    window = 2

    funcs = {
        "count": lambda v: v.count(),
        "max": lambda v: v.max(),
        "min": lambda v: v.min(),
        "sum": lambda v: v.sum(),
        "mean": lambda v: v.mean(),
        "std": lambda v: v.std(),
        "var": lambda v: v.var(),
        "median": lambda v: v.median(),
    }

    def get_expects(self):
        expects = {
            "sr1": {
                "count": Series([1, 2, 2, 2, 2], dtype="float64"),
                "max": Series([np.nan, 1, 2, 3, 4], dtype="float64"),
                "min": Series([np.nan, 0, 1, 2, 3], dtype="float64"),
                "sum": Series([np.nan, 1, 3, 5, 7], dtype="float64"),
                "mean": Series([np.nan, 0.5, 1.5, 2.5, 3.5], dtype="float64"),
                "std": Series([np.nan] + [np.sqrt(0.5)] * 4, dtype="float64"),
                "var": Series([np.nan, 0.5, 0.5, 0.5, 0.5], dtype="float64"),
                "median": Series([np.nan, 0.5, 1.5, 2.5, 3.5], dtype="float64"),
            },
            "sr2": {
                "count": Series([1, 2, 2, 2, 2], dtype="float64"),
                "max": Series([np.nan, 10, 8, 6, 4], dtype="float64"),
                "min": Series([np.nan, 8, 6, 4, 2], dtype="float64"),
                "sum": Series([np.nan, 18, 14, 10, 6], dtype="float64"),
                "mean": Series([np.nan, 9, 7, 5, 3], dtype="float64"),
                "std": Series([np.nan] + [np.sqrt(2)] * 4, dtype="float64"),
                "var": Series([np.nan, 2, 2, 2, 2], dtype="float64"),
                "median": Series([np.nan, 9, 7, 5, 3], dtype="float64"),
            },
            "sr3": {
                "count": Series([1, 2, 2, 1, 1], dtype="float64"),
                "max": Series([np.nan, 1, 2, np.nan, np.nan], dtype="float64"),
                "min": Series([np.nan, 0, 1, np.nan, np.nan], dtype="float64"),
                "sum": Series([np.nan, 1, 3, np.nan, np.nan], dtype="float64"),
                "mean": Series([np.nan, 0.5, 1.5, np.nan, np.nan], dtype="float64"),
                "std": Series(
                    [np.nan] + [np.sqrt(0.5)] * 2 + [np.nan] * 2, dtype="float64"
                ),
                "var": Series([np.nan, 0.5, 0.5, np.nan, np.nan], dtype="float64"),
                "median": Series([np.nan, 0.5, 1.5, np.nan, np.nan], dtype="float64"),
            },
            "df": {
                "count": DataFrame(
                    {0: Series([1, 2, 2, 2, 2]), 1: Series([1, 2, 2, 2, 2])},
                    dtype="float64",
                ),
                "max": DataFrame(
                    {0: Series([np.nan, 2, 4, 6, 8]), 1: Series([np.nan, 3, 5, 7, 9])},
                    dtype="float64",
                ),
                "min": DataFrame(
                    {0: Series([np.nan, 0, 2, 4, 6]), 1: Series([np.nan, 1, 3, 5, 7])},
                    dtype="float64",
                ),
                "sum": DataFrame(
                    {
                        0: Series([np.nan, 2, 6, 10, 14]),
                        1: Series([np.nan, 4, 8, 12, 16]),
                    },
                    dtype="float64",
                ),
                "mean": DataFrame(
                    {0: Series([np.nan, 1, 3, 5, 7]), 1: Series([np.nan, 2, 4, 6, 8])},
                    dtype="float64",
                ),
                "std": DataFrame(
                    {
                        0: Series([np.nan] + [np.sqrt(2)] * 4),
                        1: Series([np.nan] + [np.sqrt(2)] * 4),
                    },
                    dtype="float64",
                ),
                "var": DataFrame(
                    {0: Series([np.nan, 2, 2, 2, 2]), 1: Series([np.nan, 2, 2, 2, 2])},
                    dtype="float64",
                ),
                "median": DataFrame(
                    {0: Series([np.nan, 1, 3, 5, 7]), 1: Series([np.nan, 2, 4, 6, 8])},
                    dtype="float64",
                ),
            },
        }
        return expects

    def _create_dtype_data(self, dtype):
        sr1 = Series(np.arange(5), dtype=dtype)
        sr2 = Series(np.arange(10, 0, -2), dtype=dtype)
        sr3 = sr1.copy()
        sr3[3] = np.NaN
        df = DataFrame(np.arange(10).reshape((5, 2)), dtype=dtype)

        data = {"sr1": sr1, "sr2": sr2, "sr3": sr3, "df": df}

        return data

    def _create_data(self):
        self.data = self._create_dtype_data(self.dtype)
        self.expects = self.get_expects()

    def test_dtypes(self):
        self._create_data()
        for f_name, d_name in product(self.funcs.keys(), self.data.keys()):

            f = self.funcs[f_name]
            d = self.data[d_name]
            exp = self.expects[d_name][f_name]
            self.check_dtypes(f, f_name, d, d_name, exp)

    def check_dtypes(self, f, f_name, d, d_name, exp):
        roll = d.rolling(window=self.window)
        result = f(roll)
        tm.assert_almost_equal(result, exp)

class TestDtype_object(Dtype):
    dtype = object

class Dtype_integer(Dtype):
    pass

class TestDtype_int8(Dtype_integer):
    dtype = np.int8

class TestDtype_int16(Dtype_integer):
    dtype = np.int16

class TestDtype_int32(Dtype_integer):
    dtype = np.int32

class TestDtype_int64(Dtype_integer):
    dtype = np.int64

class Dtype_uinteger(Dtype):
    pass

class TestDtype_uint8(Dtype_uinteger):
    dtype = np.uint8

class TestDtype_uint16(Dtype_uinteger):
    dtype = np.uint16

class TestDtype_uint32(Dtype_uinteger):
    dtype = np.uint32

class TestDtype_uint64(Dtype_uinteger):
    dtype = np.uint64

class Dtype_float(Dtype):
    pass

class TestDtype_float16(Dtype_float):
    dtype = np.float16

class TestDtype_float32(Dtype_float):
    dtype = np.float32

class TestDtype_float64(Dtype_float):
    dtype = np.float64

class TestDtype_category(Dtype):
    dtype = "category"
    include_df = False

    def _create_dtype_data(self, dtype):
        sr1 = Series(range(5), dtype=dtype)
        sr2 = Series(range(10, 0, -2), dtype=dtype)

        data = {"sr1": sr1, "sr2": sr2}

        return data

class DatetimeLike(Dtype):
    def check_dtypes(self, f, f_name, d, d_name, exp):

        roll = d.rolling(window=self.window)
        if f_name == "count":
            result = f(roll)
            tm.assert_almost_equal(result, exp)

        else:
            with pytest.raises(DataError):
                f(roll)

class TestDtype_timedelta(DatetimeLike):
    dtype = np.dtype("m8[ns]")

class TestDtype_datetime(DatetimeLike):
    dtype = np.dtype("M8[ns]")

class TestDtype_datetime64UTC(DatetimeLike):
    dtype = "datetime64[ns, UTC]"

    def _create_data(self):
        pytest.skip(
            "direct creation of extension dtype "
            "datetime64[ns, UTC] is not supported ATM"
        )


import easygui
import random

num = 0

times = 6
answer = random.randint(1,100)

while num != answer and times > 0 :
    num = easygui.integerbox("1~100 사이 숫자를 입력하세요 . 도전기회 = " + str(times))
    if num < answer :
        easygui.msgbox(str(num)  + " 은 정답보다 큽습니다.")
    else :
        easygui.msgbox(str(num) + " 은 정답보다 작습니다.")

    times -= 1

if num == answer :
    easygui.msgbox(" 정답입니다. 정답은 {} 입니다. ".format(answer))
else :
    easygui.msgbox(" 실격입니다. 정답은 {} 입니다.".format(answer))


from django.urls import path
from . import views

urlpatterns = [
    # path(<urlpath_in_address_bar>, <views.py_file.FunctionName>, <name = name_mentioned_in_html_page>)

    path('register', views.register, name='register'),
    path('login', views.login, name='login'),
    path('logout', views.logout, name='logout'),
    path('dashboard', views.dashboard, name='dashboard'),
]


#coding:utf-8

"""
ID:          issue-2755
ISSUE:       2755
TITLE:       ALTER DOMAIN invalid RDB$FIELD_SUB_TYPE
DESCRIPTION:
JIRA:        CORE-2331
FBTEST:      bugs.core_2331
"""

import pytest
from firebird.qa import *

db = db_factory()

test_script = """CREATE DOMAIN TESTDOM VARCHAR(50);
COMMIT;
ALTER DOMAIN TESTDOM TYPE VARCHAR(80);
COMMIT;

SELECT RDB$FIELD_SUB_TYPE FROM RDB$FIELDS WHERE RDB$FIELD_NAME = 'TESTDOM';
"""

act = isql_act('db', test_script)

expected_stdout = """
RDB$FIELD_SUB_TYPE
==================
                 0

"""

@pytest.mark.version('>=3')
def test_1(act: Action):
    act.expected_stdout = expected_stdout
    act.execute()
    assert act.clean_stdout == act.clean_expected_stdout


import logging as _logging

from os.path import sep as _sep

# * for printing defaults
if __name__ == "__main__":
    from util import base_off_cwd as _base_off_cwd
else:
    from .util import base_off_cwd as _base_off_cwd

#! boolean flags should NOT be overriden, unless argument names are changed (--save_args flag disables saving etc.)

# default logger level
# LOG_LEVEL = _logging.DEBUG
LOG_LEVEL = _logging.INFO

# * export.py
# check unused parameters in annotation files
CHECK_UNUSED_PARAMS = True

#! paths are based off cwd (not this file)
# argument defaults
SAVE_ARGS = False
EXEC_PATH = _base_off_cwd(f"..{_sep}..{_sep}..", __file__)
OUTPUT_PATH = _base_off_cwd(f"..{_sep}..{_sep}config", __file__)
INPUT_PATH = _base_off_cwd(f"..{_sep}..{_sep}data", __file__)
EVALUATION_PERCENT = 10
DATA_PREFIX = "!"
DATA_EXTENSION = "json"
ABSOLUTE_PATH = False
FORCE_OVERRIDE = False

# yolo
YOLO_BACKUP_PATH = _base_off_cwd(f"..{_sep}..{_sep}backup", __file__)
YOLO_BATCH_SIZE = 64
YOLO_SUBDIVISIONS = 16
YOLO_HEIGHT = YOLO_WIDTH = 416

# attributes
ATTR_MULTIPLE = True

# * organize.py
DATA_ROOT = INPUT_PATH
IMAGE_EXTENSION = "jpg"
USE_PREFIX = False
NO_PREFIX = False
LEAVE_FOLDERS = False
TRANSFER_METHOD = "copy"

def _print_defaults() -> None:
    # print(f"cwd: {_path.abspath('.')}")
    print(
        f"LOG_LEVEL: {LOG_LEVEL}",
        f"CHECK_UNUSED_PARAMS: {CHECK_UNUSED_PARAMS}",
        f"SAVE_ARGS: {SAVE_ARGS}",
        f"EXEC_PATH: {EXEC_PATH}",
        f"OUTPUT_PATH: {OUTPUT_PATH}",
        f"INPUT_PATH: {INPUT_PATH}",
        f"EVALUATION_PERCENT: {EVALUATION_PERCENT}",
        f"DATA_PREFIX: {DATA_PREFIX}",
        f"DATA_EXTENSION: {DATA_EXTENSION}",
        f"ABSOLUTE_PATH: {ABSOLUTE_PATH}",
        f"FORCE_OVERRIDE: {FORCE_OVERRIDE}",
        f"YOLO_BACKUP_PATH: {YOLO_BACKUP_PATH}",
        f"YOLO_BATCH_SIZE: {YOLO_BATCH_SIZE}",
        f"YOLO_SUBDIVISIONS: {YOLO_SUBDIVISIONS}",
        f"YOLO_HEIGHT: {YOLO_HEIGHT}",
        f"YOLO_WIDTH: {YOLO_WIDTH}",
        f"ATTR_MULTIPLE: {ATTR_MULTIPLE}",
        f"DATA_ROOT: {DATA_ROOT}",
        f"USE_PREFIX: {USE_PREFIX}",
        f"NO_PREFIX: {NO_PREFIX}",
        f"LEAVE_FOLDERS: {LEAVE_FOLDERS}",
        f"TRANSFER_METHOD: {TRANSFER_METHOD}",
        sep="\n"
    )

if __name__ == "__main__":
    _print_defaults()


"""
VGG16 Convolutional Network for masked face people classification

:author:
    Ricardo Espantaleón
"""

from base.base_model import BaseModel
import tensorflow as tf
from tensorflow.keras.optimizers import Adam
from utils import get_learning_rate
from keras.models import Sequential
from keras.layers import Dense, Conv2D, MaxPool2D, Flatten

class Model(BaseModel):
    def __init__(self, config):
        """
        Parametrized constructor for initialize config file variable

        :param config: Configuration file where read all models params required for the creation
        """
        super(Model, self).__init__(config)
        self.build_model(compilation=True)

    def build_model(self, compilation=False):
        """
        Implemented function of the abstract class base_model, to create the specific instance of the model

        This specific implementation is based in typical VGG16 architecture

        A convolutional block consist: in 2/3 convolutional layers and a max Pooling layer

        :param compilation: Boolean to compile the resulting model
        """
        self.model = Sequential()

        # Adding input_layers to te sequential model
        for input_layer in self.config.model.input_layers:
            self.model.add(tf.keras.Input(shape=tuple(map(int, input_layer.shape.split(', ')))))

        # Adding convolutional blocks to the sequential model
        for conv_block in self.config.model.conv_blocks:

            # Each block can contain between 2 and 3 layers of conv
            for num in range(conv_block.num_conv_layers):
                self.model.add(
                    Conv2D(filters=conv_block.filters,
                           kernel_size=tuple(map(int, conv_block.kernel_size.split(', '))),
                           padding=conv_block.padding,
                           activation=conv_block.activation))

            # Final maxPool layer in each convolution block
            self.model.add(MaxPool2D(pool_size=tuple(map(int, conv_block.pool_size.split(', '))),
                                     strides=tuple(map(int, conv_block.strides.split(', ')))))

        self.model.add(Flatten())

        # Adding final dense layers
        for dense_layer in self.config.model.dense_layers:
            self.model.add(Dense(units=dense_layer.units, activation=dense_layer.activation))

        # If user indicated that wants the model compiled
        if compilation:

            # If learning rate param was specified by the user
            if self.config.model.learning_rate is not None:

                # We need to create a specified model.optimizer for call the __init__ function
                if self.config.model.optimizer == "Adam":
                    optimizer = Adam(learning_rate=self.config.model.learning_rate)

                self.model.compile(optimizer=optimizer,
                                   loss=self.config.model.loss,
                                   metrics=['accuracy', get_learning_rate.get_lr_metric(optimizer)])

            # If learning rate wasn't specified, we can use default constructor
            else:

                # We need to create a specified model.optimizer for call the __init__ function
                if self.config.model.optimizer == "Adam":
                    optimizer = Adam()

                self.model.compile(optimizer=optimizer,
                                   loss=self.config.model.loss,
                                   metrics=['accuracy', get_learning_rate.get_lr_metric(optimizer)])

        # Printing final model summary
        print(self.model.summary())


import sys
import os

import oelite
import oelite.parse

import ply.lex
import ply.yacc

doclexer = None

__initialized__ = False
if not __initialized__:
    import doclex
    doclexer = ply.lex.lex(module=doclex)
    __initialized__ = True

class DocParser(oelite.parse.oeparse.OEParser):

    def __init__(self, meta=None, parent=None, **kwargs):
        self.body = ""
        self.vars = {}
        self.useflags = {}
        self.inherits = []
        super(DocParser, self).__init__(meta, parent, lexer=doclexer, **kwargs)
        return

    def p_statement_doc_section(self, p):
        '''statement : doc_paragraph NEWLINE'''
        self.body += p[1] + '\n\n'
        return

    def p_doc_asciidoc_par1(self, p):
        '''doc_paragraph : doc_string'''
        p[0] = p[1]
        return

    def p_doc_asciidoc_par3(self, p):
        '''doc_paragraph : doc_paragraph NEWLINE doc_string'''
        p[0] = p[1] + '\n' + p[3]
        return

    def p_doc_string1(self, p):
        '''doc_string : DOCSTRING'''
        p[0] = p[1]
        return

    def p_doc_string2(self, p):
        '''doc_string : doc_string DOCSTRING'''
        p[0] = p[1] + ' ' + p[2]
        return

    # the @var syntax is similar to the doxygen \tparam special command
    # http://www.stack.nl/~dimitri/doxygen/manual/commands.html#cmdtparam
    def p_doc_cmd_var(self, p):
        '''statement : DOCCMDVAR VARNAME doc_paragraph NEWLINE'''
        if self.vars.has_key(p[2]):
            raise oelite.parse.ParseError(
                self, "Variable documentation already defined", p)
        self.vars[p[2]] = p[3]
        return

    # the @useflag syntax is similar to the doxygen \tparam special command
    # http://www.stack.nl/~dimitri/doxygen/manual/commands.html#cmdtparam
    def p_doc_cmd_useflag(self, p):
        '''statement : DOCCMDUSEFLAG VARNAME doc_paragraph NEWLINE'''
        if self.useflags.has_key(p[2]):
            raise oelite.parse.ParseError(
                self, "USE flag documentation already defined", p)
        self.useflags[p[2]] = p[3]
        return

    #Do not continue into (other) oeclass files
    def p_inherit(self, p):
        '''inherit : INHERIT inherit_classes'''
        self.inherits.extend(p[2])
        return

    def docparse(self, filename, title):
        super(DocParser,self).parse(filename)
        return OEliteDocumentation(
            title,
            self.body, self.vars, self.useflags, self.inherits)

class OEliteDocumentation(object):

    def __init__(self, title, body, variables={}, useflags={}, inherits=[]):
        self.title = title
        self.body = body
        self.vars = variables
        self.useflags = useflags
        self.inherits = inherits

    @staticmethod
    def asciidoc_header(title, level='-'):
        return title + '\n' + level*len(title) + '\n\n'

    def get_asciidoc(self):
        text = ''
        if self.body:
            text += self.body + '\n'
        if self.vars:
            text += self.asciidoc_header('Variables')
            for var in sorted(self.vars.keys()):
                text += "%s::\n%s\n"%(var, self.vars[var])
            text += '\n\n'
        if self.useflags:
            text += self.asciidoc_header('USE Flags')
            for useflag in sorted(self.useflags.keys()):
                text += "%s::\n%s\n"%(useflag, self.useflags[useflag])
            text += '\n\n'
        if not text:
            text = 'Seeking documentation writer...\n'
        text = self.asciidoc_header(self.title, level='=') + text
        return text


import collections
import operator

def count_unique_words(filename):
    # your code here
    result = collections.defaultdict(lambda: 1)
    with open(filename, "r") as f:
        t = f.read()
        for w in t.split():
            result[w] = result[w] + 1
    return sorted(result.items(), key = operator.itemgetter(1), reverse = True)

if __name__ == '__main__':
    print(*count_unique_words('file/hamlet.txt')[:10], sep="\n")


import pandas as pd
import numpy as np
from skimage import io, color, exposure, transform
from sklearn.model_selection import train_test_split
import os
import glob
import h5py
import tensorflow as tf
from keras.models import load_model

NUM_CLASSES = 43
IMG_SIZE = 48

def preprocess_img(img):
    # Histogram normalization in v channel
    hsv = color.rgb2hsv(img)
    hsv[:, :, 2] = exposure.equalize_hist(hsv[:, :, 2])
    img = color.hsv2rgb(hsv)

    # central square crop
    min_side = min(img.shape[:-1])
    centre = img.shape[0] // 2, img.shape[1] // 2
    img = img[centre[0] - min_side // 2:centre[0] + min_side // 2,
              centre[1] - min_side // 2:centre[1] + min_side // 2,
              :]

    # rescale to standard size
    img = transform.resize(img, (IMG_SIZE, IMG_SIZE))

    # roll color axis to axis 0
    img = np.rollaxis(img, -1)

    return img

test = pd.read_csv('GT-final_test.csv', sep=';')
# load model
model = load_model('model.h5')
# summarize model.
model.summary()
# Load test dataset
X_test = []
y_test = []
i = 0
for file_name, class_id in zip(list(test['Filename']), list(test['ClassId'])):
    img_path = os.path.join('GTSRB/Final_Test/Images/', file_name)
    X_test.append(preprocess_img(io.imread(img_path)))
    y_test.append(class_id)

X_test = np.array(X_test)
y_test = np.array(y_test)

# predict and evaluate
y_pred = model.predict_classes(X_test)
acc = np.sum(y_pred == y_test) / np.size(y_pred)
print("Test accuracy = {}".format(acc))


# -*- coding: utf-8 -*-
from datetime import datetime

from PyQt5.QtCore import Qt
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QMainWindow, QApplication

from Core.Models.Worker import Usuarios
from Login_System.Verifications_and_Responses.Responses import Responses

from ui.windows.ui_SetNewDatePayment import Ui_SetNewDatePayment

class SetNewDatePaymentWindow(QMainWindow):

    def __init__(self, id_contract=None, date_old_payment=None, parent=None):
        super(SetNewDatePaymentWindow, self).__init__(parent)
        self.ui = Ui_SetNewDatePayment()
        self.ui.setupUi(self)
        self.statusBar().setStyleSheet('color: #ffffff;')
        self.setWindowIcon(QIcon(":/Images/logo-mini.png"))
        self.setWindowTitle(f'Новая дата платежа')

        # Выравнивание окна по центру монитора
        desktop = QApplication.desktop()
        x = (desktop.width() - self.frameSize().width()) // 2
        y = (desktop.height() - self.frameSize().height()) // 2
        self.move(x, y)

        self.parent = parent
        self.id_contract = id_contract
        self.date_old_payment = date_old_payment

        self.responses = Responses()

        self.users_db = Usuarios()

        self.ui.de_new_date_payment.calendarWidget().setCursor(Qt.PointingHandCursor)

        # print(f'ID contract: {self.id_contract} дата платежа: {self.date_old_payment}')

        self.ui.de_new_date_payment.setDate(datetime.today().date())

        self.ui.btn_cancel.clicked.connect(self.close_form_set_new_date_payment)
        self.ui.btn_save.clicked.connect(self.set_new_date_payment)

    def set_new_date_payment(self):
        responce = self.users_db.set_new_date_payment(id_conract = self.id_contract, new_date_payment = self.ui.de_new_date_payment.date().toPyDate(), old_date_payment = self.date_old_payment)
        self.responses.message_from_db(responce, self.statusBar(), f'Дата платежа успешно изменена')
        if responce == 'update':
            self.ui.btn_cancel.setText(f'Закрыть')
            self.parent.update()

    def close_form_set_new_date_payment(self):
        self.parent.effect.setEnabled(False)
        self.close()

    def closeEvent(self, event):
        self.parent.effect.setEnabled(False)
        super(SetNewDatePaymentWindow, self).closeEvent(event)


#!/usr/bin/python3
# Author: Rustam Gubaydullin (@second_fry)
# License: MIT (https://opensource.org/licenses/MIT)

from datetime import datetime
import logging

from config.statsconfig import StatsConfig

logging.basicConfig(filename='wingspanstats.log', level=logging.DEBUG)

def log(level, message):
  logging.info('[' + str(datetime.now()) + '] ' + '-' * level + '> ' + message)
  if level < StatsConfig.LOG_LEVEL_CONSOLE:
    print('[{}] {}> {}'.format(
      datetime.now().strftime('%H:%M:%S'),
      '-' * level,
      message,
    ))


import json
import os
import random
from collections import namedtuple
import torch.utils.data as data
from PIL import Image
import numpy as np
import torch.nn.functional as F

class Cityscapes(data.Dataset):
    """Cityscapes <http://www.cityscapes-dataset.com/> Dataset.

    **Parameters:**
        - **root** (string): Root directory of dataset where directory 'leftImg8bit' and 'gtFine' or 'gtCoarse' are located.
        - **split** (string, optional): The image split to use, 'train', 'test' or 'val' if mode="gtFine" otherwise 'train', 'train_extra' or 'val'
        - **mode** (string, optional): The quality mode to use, 'gtFine' or 'gtCoarse' or 'color'. Can also be a list to output a tuple with all specified target types.
        - **transform** (callable, optional): A function/transform that takes in a PIL image and returns a transformed version. E.g, ``transforms.RandomCrop``
        - **target_transform** (callable, optional): A function/transform that takes in the target and transforms it.
    """

    # Based on https://github.com/mcordts/cityscapesScripts
    CityscapesClass = namedtuple('CityscapesClass', ['name', 'id', 'train_id', 'category', 'category_id',
                                                     'has_instances', 'ignore_in_eval', 'color'])
    classes = [
        CityscapesClass('unlabeled', 0, 255, 'void', 0, False, True, (0, 0, 0)),
        CityscapesClass('ego vehicle', 1, 255, 'void', 0, False, True, (0, 0, 0)),
        CityscapesClass('rectification border', 2, 255, 'void', 0, False, True, (0, 0, 0)),
        CityscapesClass('out of roi', 3, 255, 'void', 0, False, True, (0, 0, 0)),
        CityscapesClass('static', 4, 255, 'void', 0, False, True, (0, 0, 0)),
        CityscapesClass('dynamic', 5, 25, 'void', 0, False, True, (111, 74, 0)),
        CityscapesClass('ground', 6, 24, 'void', 0, False, True, (81, 0, 81)),
        CityscapesClass('road', 7, 0, 'flat', 1, False, False, (128, 64, 128)),
        CityscapesClass('sidewalk', 8, 1, 'flat', 1, False, False, (244, 35, 232)),
        CityscapesClass('parking', 9, 23, 'flat', 1, False, True, (250, 170, 160)),
        CityscapesClass('rail track', 10, 22, 'flat', 1, False, True, (230, 150, 140)),
        CityscapesClass('building', 11, 2, 'construction', 2, False, False, (70, 70, 70)),
        CityscapesClass('wall', 12, 3, 'construction', 2, False, False, (102, 102, 156)),
        CityscapesClass('fence', 13, 4, 'construction', 2, False, False, (190, 153, 153)),
        CityscapesClass('guard rail', 14, 21, 'construction', 2, False, True, (180, 165, 180)),
        CityscapesClass('bridge', 15, 20, 'construction', 2, False, True, (150, 100, 100)),
        CityscapesClass('tunnel', 16, 19, 'construction', 2, False, True, (150, 120, 90)),
        CityscapesClass('pole', 17, 5, 'object', 3, False, False, (153, 153, 153)),
        CityscapesClass('polegroup', 18, 18, 'object', 3, False, True, (153, 153, 153)),
        CityscapesClass('traffic light', 19, 6, 'object', 3, False, False, (250, 170, 30)),
        CityscapesClass('traffic sign', 20, 7, 'object', 3, False, False, (220, 220, 0)),
        CityscapesClass('vegetation', 21, 8, 'nature', 4, False, False, (107, 142, 35)),
        CityscapesClass('terrain', 22, 9, 'nature', 4, False, False, (152, 251, 152)),
        CityscapesClass('sky', 23, 10, 'sky', 5, False, False, (70, 130, 180)),
        CityscapesClass('person', 24, 11, 'human', 6, True, False, (220, 20, 60)),
        CityscapesClass('rider', 25, 12, 'human', 6, True, False, (255, 0, 0)),
        CityscapesClass('car', 26, 13, 'vehicle', 7, True, False, (0, 0, 142)),
        CityscapesClass('truck', 27, 14, 'vehicle', 7, True, False, (0, 0, 70)),
        CityscapesClass('bus', 28, 15, 'vehicle', 7, True, False, (0, 60, 100)),
        CityscapesClass('caravan', 29, 13, 'vehicle', 7, True, True, (0, 0, 90)),
        CityscapesClass('trailer', 30, 13, 'vehicle', 7, True, True, (0, 0, 110)),
        CityscapesClass('train', 31, 16, 'vehicle', 7, True, False, (0, 80, 100)),
        CityscapesClass('motorcycle', 32, 17, 'vehicle', 7, True, False, (0, 0, 230)),
        CityscapesClass('bicycle', 33, 18, 'vehicle', 7, True, False, (119, 11, 32)),
        CityscapesClass('license plate', -1, 13, 'vehicle', 7, False, True, (0, 0, 142)),
    ]

    train_id_to_color = [c.color for c in classes if (c.train_id != -1 and c.train_id != 255)]
    train_id_to_color.append([0, 0, 0])
    train_id_to_color = np.array(train_id_to_color)
    id_to_train_id = np.array([c.train_id for c in classes])

    def __init__(self, root, cell_list, interested_classes, split='train', target_type='semantic', transform=None):
        self.root = os.path.expanduser(root)
        self.mode = 'gtFine'
        self.target_type = target_type
        self.images_dir = os.path.join(self.root, 'leftImg8bit', split)
        self.targets_dir = os.path.join(self.root, self.mode, split)
        self.transform = transform

        self.split = split
        self.images = []
        self.targets = []
        self.cell_list = cell_list
        self.interested_classes = interested_classes

        if split not in ['train', 'test', 'val']:
            raise ValueError('Invalid split for mode! Please use split="train", split="test"'
                             ' or split="val"')

        if not os.path.isdir(self.images_dir) or not os.path.isdir(self.targets_dir):
            raise RuntimeError('Dataset not found or incomplete. Please make sure all required folders for the'
                               ' specified "split" and "mode" are inside the "root" directory')

        for city in os.listdir(self.images_dir):
            img_dir = os.path.join(self.images_dir, city)
            target_dir = os.path.join(self.targets_dir, city)

            for file_name in os.listdir(img_dir):
                self.images.append(os.path.join(img_dir, file_name))
                target_name = '{}_{}'.format(file_name.split('_leftImg8bit')[0],
                                             self._get_target_suffix(self.mode, self.target_type))
                self.targets.append(os.path.join(target_dir, target_name))

    @classmethod
    def encode_target(cls, target):
        return cls.id_to_train_id[np.array(target)]

    @classmethod
    def decode_target(cls, target):
        target[target == 255] = 19
        # target = target.astype('uint8') + 1
        return cls.train_id_to_color[target]

    @classmethod
    def encode_cell(cls, target, cell_list, interested_classes):
        label_len = len(cell_list) * len(interested_classes)
        label_list = np.zeros(label_len, dtype=np.uint8)

        for num, region in enumerate(cell_list):
            cell = target[region[0][1]:region[1][1], region[0][0]:region[1][0]]
            value, count = np.unique(cell, return_counts=True)
            # print(value, count)

            last_class_idx = len(interested_classes) - 1
            for j, subclasses in enumerate(interested_classes):
                if isinstance(subclasses, int):
                    subclasses = (subclasses,)
                if j == last_class_idx:
                    if any(label_list[num * len(interested_classes):num * len(interested_classes) + last_class_idx]):
                        if np.size(value) == 2 and value[0] == 0 and value[1] == 255 and num >= 216:
                            label_list[num * len(interested_classes) + j] = 1
                        else:
                            label_list[num * len(interested_classes) + j] = 0
                    else:
                        if np.size(value) == 1 and value[0] == 255 and num <= 216:
                            label_list[num * len(interested_classes) + j] = 0
                        else:

                            label_list[num * len(interested_classes) + j] = 1
                else:
                    if any(subclass in value for subclass in subclasses):
                        label_list[num * len(interested_classes) + j] = 1
        return label_list

    def __getitem__(self, index):
        """
        Args:
            index (int): Index
        Returns:
            tuple: (image, target) where target is a tuple of all target types if target_type is a list with more
            than one item. Otherwise target is a json object if target_type="polygon", else the image segmentation.
        """
        image = Image.open(self.images[index]).convert('RGB')
        filename, _ = os.path.splitext(os.path.basename(self.images[index]))
        target = Image.open(self.targets[index])
        cell_list = self.cell_list
        interested_classes = self.interested_classes
        # flip image and target image horizontally with 0.5 probability
        if self.split == 'train':
            if random.random() > 0.5:
                image = image.transpose(Image.FLIP_LEFT_RIGHT)
                target = target.transpose(Image.FLIP_LEFT_RIGHT)
            if random.random() > 0.5:
                new_width = 2198
                new_height = 1099
                image = image.resize((new_width, new_height), Image.ANTIALIAS)
                target = target.resize((new_width, new_height), Image.NEAREST)
                crop_width, crop_height = 2048, 1024
                left = random.randint(0, new_width - crop_width)
                upper = random.randint(0, new_height - crop_height)
                right = left + crop_width
                lower = upper + crop_height
                # Crop the image
                image = image.crop((left, upper, right, lower))
                target = target.crop((left, upper, right, lower))
        if self.transform:
            image = self.transform(image)
        target = self.encode_target(target)
        cell_label = self.encode_cell(target, cell_list, interested_classes)
        image = np.array(image)
        return image, cell_label

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

    def _load_json(self, path):
        with open(path, 'r') as file:
            data = json.load(file)
        return data

    def _get_target_suffix(self, mode, target_type):
        if target_type == 'instance':
            return '{}_instanceIds.png'.format(mode)
        elif target_type == 'semantic':
            return '{}_labelIds.png'.format(mode)
        elif target_type == 'color':
            return '{}_color.png'.format(mode)
        elif target_type == 'polygon':
            return '{}_polygons.json'.format(mode)
        elif target_type == 'depth':
            return '{}_disparity.png'.format(mode)


import sys
from bitstring import BitArray, BitStream

def boothMul(i,j,x=4,y=4):

    print ("Numbers entered are :",i, j)
    print ("Operand width : x =", x, "\t", "y =",y)
    print()

    try:
        A=BitArray(int=i,length=x) + BitArray(int=0,length=y+1)
        S=BitArray(int=-i,length=x) + BitArray(int=0,length=y+1)
        P=BitArray(int=0,length=x) + BitArray(int=j,length=y) + BitArray('0b0')
    except Exception as err:
        sys.stderr.write('ERROR: %s\n' % str(err))
        return -1

    print("A =", A.bin, "\tS =", S.bin, "\tP =", P.bin)

    count=y

    while(count > 0):
        count -= 1

        if P[-2:] == '0b00':
            P.int >>= 1
            print("count = ", count, "00 : ")
            print("A =", A.bin, "\tS =", S.bin, "\tP =", P.bin)

        elif P[-2:] == '0b01':
            Sum = P.int + A.int
            P = BitArray(int=Sum,length=x+y+2)[-(x+y+1):]
            P.int >>= 1
            print("count = ", count, "01 : ")
            print("A =", A.bin, "\tS =", S.bin, "\tP =", P.bin)

        elif P[-2:] == '0b10':
            Sum = P.int + S.int
            P = BitArray(int=Sum,length=x+y+2)[-(x+y+1):]
            P.int >>= 1
            print("count = ", count, "10 : ")
            print("A =", A.bin, "\tS =", S.bin, "\tP =", P.bin)

        else:
            P.int >>= 1
            print("count = ", count, "11 : \n")
            print("A =", A.bin, "\tS =", S.bin, "\tP =", P.bin)

    P.int >>= 1
    print(P.int)