# print out board each move and sleep for 300 so that people can watch
# CAL is chutes and ladders
# for sake of simplicity board will wrap to the right instead of switch back and forth

"""
example board for chutes and ladders
@ 0 0 0 0 3 0
0 1 0 0 0 0 0
0 0 0 0 -9 0 0
0 0 4 0 5 0 0
0 0 0 0 0 0 start

+---+---+---+
| 0 | 9 | 0 |
+---+---+---+
"""

import os
from time import sleep
import random
import copy

HOWTO = """
This game seeks to follow the rules of chutes and ladders.
Players roll a die and move spaces accordingly, spaces with a number
require players to adjust their position by that number of spaces.
The main catch is that players can roll multiple times based on how
many tokens they have. Each token gives one more roll for the turn
and each player starts with 7 tokens. At the start of their turn, each player
can grab one token from the discard pile and add it to their own. First to reach space 100 wins.
"""

SPARSEBOARD = [
    ['@', 0, 0, 0, 0, 0, 0, 10, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 10, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 10, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 10, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 10, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 10, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 10, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 10, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 10, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 10, 0, 0]
]

DENSEBOARD = []

NEGATIVEBOARD = []

class Board:
    # the matrix variable should not change after init
    cols = 0
    rows = 0
    matrix = []
    positions = []

    def __init__(self, i, j, m, p):
        """
        example input looks like
        g = Board([ [0,0,0,0,0], [1,2,1,-1,0], [3,0,0,2,0], [0,0,0,0,1], [0,0,0,0,0] ],
        0,
        [ ['A', 5, 5], ['B', 5, 5], ['C', 5, 5] ])
        """
        self.rows = j
        self.cols = i
        self.matrix = m
        self.positions = p

    # positions will will determine whether to print
    # tile number or piece on tile
    def print_board(self):
        # add in the player pieces without overriding any of them
        actual = copy.deepcopy(self.matrix)
        for guy in self.positions:
            if str(actual[guy[1]] [guy[2]]).isdigit():
                actual[guy[1]] [guy[2]] = guy[0]
            else:
                actual[guy[1]] [guy[2]] += str(guy[0])
        # print out the board with borders
        for i in actual:
            border = "+"
            middle = "|"
            for j in i:
                border += "---+"
                middle += str(j).center(3) + "|"
            print(border)
            print(middle)
        print(border)

    # move piece according to position stored in positions
    def update_piece(self, player, value):
        for p in range(len(self.positions)):
            if self.positions[p] == player:
                # can get new position using mod division
                newi = player[1] - (value // self.cols)
                newj = player[2] - (value % self.cols)
                if newj < 0:
                    if newi < 1:
                        newj = 0
                    else:
                        newj = self.cols + newj
                        newi -= 1
                if newi < 0:
                    newi = 0
                self.positions[p] = [player[0], newi, newj]

    # checks value of tile and moves piece on it accordingly
    def update_bonus_tile(self, player):
        if player[1] == 0 and player[2] == 0:
            pass
        else:
            val = self.matrix[player[1]][player[2]]
            if val < 0:
                print("player has fallen x spaces!")
            if val > 0:
                print("player is launched forward x spaces!")
            self.update_piece(player, val)

class Player:
    position = []
    name = ""
    role = ""
    token_count = 0
    # player doenst need to know turn order

    # name has to shortened for formatting
    def __init__(self, pos, na, ro):
        self.position = pos
        if len(na) > 10:
            self.name = na[:9]
        else:
            self.name = na
        self.role = ro
        self.token_count = 7

    # for keeping track with the board
    def update_position(self, x, y):
        self.position = [self.position[0], x, y]

    #
    def use_tokens(self, amount):
        self.token_count = self.token_count - amount

    # three methods for deciding how to spend players tokens on their turn
    def decide_turn(self):
        # human -> input
        if self.role == "human":
            val = "."
            while not val.isdigit():
                val = input(f"how many coins will {self.name} spend: ")
                if val.isdigit():
                    if int(val) < self.token_count:
                        return int(val)
                    else:
                        return self.token_count

        # greedy -> all tokens if > 1
        if self.role == "greedy":
            return self.token_count

        # binge -> all if covered over 50% of board spend all else spend 1
        if self.role == "binge":
            if self.position[1] < 5:
                return self.token_count
            else:
                return 0

class Game:
    turn = 0
    board = 0
    players = []

    def __init__(self):
        # for now we will go with 2 humans and 2 ai
        self.players = []
        print(HOWTO)
        self.players.append(Player(['A', 9, 9], input("enter player 1 name: "), "human"))
        self.players.append(Player(['B', 9, 9], input("enter player 2 name: "), "human"))
        self.players.append(Player(['C', 9, 9], "Bot1", "greedy"))
        self.players.append(Player(['D', 9, 9], "Fred", "binge"))
        self.turn = 0
        initials = [['A', 9, 9], ['B', 9, 9], ['C', 9, 9], ['D', 9, 9]]
        self.board = Board(10, 10, SPARSEBOARD, initials)

    def win_condition(self):
        for guy in self.players:
            if guy.position[1] == 0 and guy.position[2] == 0:
                return True
        return False

    def player_turn(self, turn):
        amount = self.players[turn].decide_turn()
        self.players[turn].use_tokens(amount)

        # automatically performs die roll in for loop
        for i in range(amount + 1):
            roll = random.randint(1, 6)
            print(f"{self.players[turn].name} jumped {roll} spaces!")
            # update board info
            self.board.update_piece(self.players[turn].position, roll)
            self.board.update_bonus_tile(self.board.positions[turn])
            # update player info
            self.players[turn].position = self.board.positions[turn]

        self.players[turn].token_count += 1

    def print_game(self):
        row1 = "TURN".ljust(7)
        row2 = str(self.turn).ljust(7)
        for i in range(len(self.players)):
            row1 += str(self.players[i].name).ljust(10)
            row2 += str(self.players[i].token_count).ljust(10)
        print(row1)
        print(row2)
        self.board.print_board()

    def play(self):
        # cls -> print_score -> print_board -> get_coin_input -> roll_turn -> switch_to_next_player
        while not self.win_condition():
            os.system('clear')
            self.print_game()
            for i in range(len(self.players)):
                self.player_turn(i)
            self.turn += 1
            input("press enter to continue: ")
        print("Congrats to <player2> you win the game!!!!!!")
        self.board.print_board()

# need extensive planning
p = Game()
p.play()


def digitalSumSort(a):
    return sorted(a, key=lambda n: 1000000 * sum(map(int, list(str(n)))) + n)

def polishNotation(tokens):
    def isNumber(stringRepresentation):
        return (len(stringRepresentation) > 1 or
              '0' <= stringRepresentation[0] and
              stringRepresentation[0] <= '9')

    stack = []

    for i in range(len(tokens)):
        stack.append(tokens[i])
        while (len(stack) > 2 and isNumber(stack[-1])
          and isNumber(stack[-2])):
            leftOperand = int(stack[-2])
            rightOperand = int(stack[-1])
            result = 0
            if stack[-3] == '-':
                result = leftOperand - rightOperand
            if stack[-3] == '+':
                result = leftOperand + rightOperand
            if stack[-3] == '*':
                result = leftOperand * rightOperand
            stack = stack[:-3]
            stack.append(str(result))

    return int(stack[0])

def test():
    testeql(polishNotation(["+",
 "3",
 "7"]), 10)

    testeql(polishNotation(["*",
 "-",
 "5",
 "6",
 "7"]), -7)


import unittest
from typing import List

class Solution:
    def sumPrefixScores(self, words: List[str]) -> List[int]:
        # get prefix map
        prefix_map = {}
        for word in words:
            prefix = ""
            for c in word:
                prefix += c
                if prefix in prefix_map:
                    prefix_map[prefix] += 1
                else:
                    prefix_map[prefix] = 1

        ans = []
        for word in words:
            score = 0
            prefix = ""
            for c in word:
                prefix += c
                score += prefix_map[prefix]
            ans.append(score)
        return ans

class Test(unittest.TestCase):
    def test(self):
        cases = [
            [["abc", "ab", "bc", "b"], [5, 4, 3, 2]],
            [["abcd"], [4]],
        ]
        for ci, co in cases:
            result = Solution().sumPrefixScores(ci)
            assert result == co, (ci, co, result)

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

6183. Sum of Prefix Scores of Strings.py


#!/usr/bin/env python

# Machine Learning 445
# HW 1: Perceptrons
# Katie Abrahams, abrahake@pdx.edu
# 1/19/16

# maximum value for letter attributes
# in data set is 15
max_letter_attribute_val = 15

class letter:
    """Letter entity class
    contains alphabet letter value and dataset attributes"""
    # value = None # alphabet letter
    # attributes = []  # 16 numerical attributes for a letter from the data set
    # target = 0

    def __init__(self, input):
        """
        :param input: list containing letter and attributes
        normalize attributes
        """
        self.value = input[:1]
        self.attributes = map(float, input[1:])
        # scale each data value to be between 0 and 1 by dividing by 15 (max val = 15)
        self.attributes = [i/max_letter_attribute_val for i in self.attributes]
        self.target = 0


import unittest

def urlfy(my_string, true_lenght):
    put_space = False
    new_string = ''
    index_char = 0
    spaces_no = 0
    while True:
        if put_space:
            new_string += '%20'
        if (my_string[index_char] == ' ' and
                index_char > 0 and my_string[index_char - 1] != ' '):
                put_space = True
                spaces_no += 2
        else:
            new_string += my_string[index_char]
            put_space = False
            if len(new_string) - spaces_no == true_lenght:
                break
        index_char += 1
    return new_string

class TestUrlfy(unittest.TestCase):

    input_string = "Mr John Smith           "
    n = 13
    expected_string = "Mr%20John%20Smith"

    def test(self):
        self.assertEqual(
            urlfy(self.input_string, self.n), self.expected_string)

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


from gui import Renderer
import game_checkers as gm
import pygame as pg
from game import predictNextStep

class Controller:
    def __init__(self, screen):
        self.game = gm.Checkers()
        self.handeled_checker_pos = None
        self.screen = screen

    def run_player2player_game(self):
        running = True
        while running:
            for event in pg.event.get():
                if event.type == pg.QUIT:
                    running = False

            self.take_checker()
            self.place_checker()

            Renderer.update(self.screen, self.game, self.handeled_checker_pos, pg.mouse.get_pos())

    def run_player2bot_game(self, model):
        running = True
        while running:
            for event in pg.event.get():
                if event.type == pg.QUIT:
                    running = False

            if self.game.get_order() == gm.Order.WHITE:
                self.take_checker()
                self.place_checker()
            else:
                step = predictNextStep(model, self.game)
                self.game.make_step(step[0], step[1])

            Renderer.update(self.screen, self.game, self.handeled_checker_pos, pg.mouse.get_pos())

    def run_bot2bot_game(self):
        pass

    def is_mouse_button_pressed(self):
        if pg.mouse.get_pressed()[0]:
            return True
        return False

    def is_mouse_button_released(self):
        if not pg.mouse.get_pressed()[0]:
            return True
        return False

    def take_checker(self):
        if not self.is_mouse_button_pressed():
            return

        pos = self.get_cell_by_pixel(pg.mouse.get_pos())
        if pos == None:
            return

        steps = self.game.get_loc_possible_steps()

        for p in steps:
            if (int(pos[0]), int(pos[1])) == p[0]:
                self.handeled_checker_pos = pos
                break

    def place_checker(self):
        if not self.is_mouse_button_released():
            return

        if self.handeled_checker_pos == None:
            return

        h_pos = (int(self.handeled_checker_pos[0]), int(self.handeled_checker_pos[1]))

        pos = self.get_cell_by_pixel(pg.mouse.get_pos())
        pos = (int(pos[0]), int(pos[1]))
        if pos == None:
            return

        steps = self.game.get_loc_possible_steps()

        if (h_pos, pos) in steps:
            self.game.make_step(h_pos, pos)

        self.handeled_checker_pos = None

    def get_cell_by_pixel(self, pos):
        h_cell = Renderer.get_cell_by_pixel(self.screen, self.game, pos)

        if (h_cell[0] < 0 or h_cell[1] < 0 or
            h_cell[0] >= self.game.get_board_size()[0] or
            h_cell[1] >= self.game.get_board_size()[1]):
            return None
        else:
            return h_cell[0], self.game.get_board_size()[1] - h_cell[1]


import logging
import boto3
from botocore.exceptions import ClientError

def create_bucket(bucket_name):
    try:
        s3_client = boto3.client('s3')
        s3_client.create_bucket(Bucket=bucket_name)
        print("Bucket successfully created!")
    except ClientError as e:
        logging.error(e)
        print('Bucket already exists or could not be created.')

if __name__ == '__main__':
    bucket_name = 'bucket-for-audio-12345'
    create_bucket(bucket_name)


# teste = list()
# teste.append('Brenda')
# teste.append(10)
# print(teste)
#
# galera = list()
# galera.append(teste) #teste[:] faria uma cópia
# print(galera)
#
# teste[0] = 'Maria'
# teste[1] = 20
# galera.append(teste) #para fazer cópia teste[:]
#
# print(galera) #mudou os dois

galera = list()
dado = list()
for c in range(0, 3):
    dado.append(str(input('Nome: ')))
    dado.append(int(input('Idade:')))
    galera.append(dado[:])
    dado.clear()

print(galera)
print(dado)


import base64
import gzip
import io
from pathlib import Path

import pandas as pd

from mpu.excel_formats import (STOCK_COLUMNS_FORMAT,
                               STOCK_WITH_NEW_PRICE_COLUMNS_FORMAT)
from mpu.utils.pyopenxl_utils import EXCEL_ENGINE, format_excel_df

def get_stock_file_path(folder_path: Path, csv: bool = False) -> Path:
    """Constructs the stock file path from a folder path"""
    if csv:
        return folder_path / "stock.csv"
    else:
        return folder_path / "stock.xlsx"

def convert_base64_gzipped_string_to_dataframe(b64_zipped_string: str) -> pd.DataFrame:
    """Converts a base64 gzipped strings (or bytes) into a pandas dataframe"""
    decoded_string = base64.b64decode(b64_zipped_string)
    csv_string = gzip.decompress(decoded_string)

    return pd.read_csv(io.BytesIO(csv_string), sep=";")

def save_stock_df_as_excel_formatted_file(
    df: pd.DataFrame, file_path: Path, new_price: bool = False
) -> None:
    cols_format = (
        STOCK_WITH_NEW_PRICE_COLUMNS_FORMAT if new_price else STOCK_COLUMNS_FORMAT
    )

    with pd.ExcelWriter(path=str(file_path), engine=EXCEL_ENGINE) as writer:
        df.to_excel(excel_writer=writer, index=False, engine=EXCEL_ENGINE)

        format_excel_df(df=df, writer=writer, format_config=cols_format)


import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

#%load_ext google.colab.data_table

import pandas as pd
import random
from datetime import datetime, timedelta
from functools import wraps

first_names = [
    "Maria Carmen",
    "Maria",
    "Carmen",
    "Josefa",
    "Isabel",
    "Ana Maria",
    "Maria Dolores",
    "Maria Pilar",
    "Maria Teresa",
    "Ana",
    "Laura",
    "Francisca",
    "Antonia",
    "Dolores",
    "Maria Angeles",
    "Cristina",
    "Marta",
    "Maria Jose",
    "Maria Isabel",
    "Pilar",
    "Maria Luisa",
    "Lucia",
    "Concepcion",
    "Elena",
    "Mercedes",
    "Manuela",
    "Rosa Maria",
    "Raquel",
    "Sara",
    "Maria Jesus",
    "Paula",
    "Juana",
    "Teresa",
    "Rosario",
    "Encarnacion",
    "Beatriz",
    "Rosa",
    "Nuria",
    "Silvia",
    "Montserrat",
    "Julia",
    "Patricia",
    "Irene",
    "Monica",
    "Andrea",
    "Rocio",
    "Angela",
    "Maria Mar",
    "Margarita",
    "Sonia",
    "Sandra",
    "Susana",
    "Alicia",
    "Yolanda",
    "Alba",
    "Maria Josefa",
    "Marina",
    "Natalia",
    "Maria Rosario",
    "Inmaculada",
    "Angeles",
    "Esther",
    "Maria Mercedes",
    "Ana Isabel",
    "Eva",
    "Veronica",
    "Amparo",
    "Noelia",
    "Maria Rosa",
    "Maria Victoria",
    "Maria Concepcion",
    "Carolina",
    "Claudia",
    "Eva Maria",
    "Catalina",
    "Consuelo",
    "Victoria",
    "Lorena",
    "Ana Belen",
    "Maria Antonia",
    "Maria Elena",
    "Miriam",
    "Emilia",
    "Nerea",
    "Luisa",
    "Ines",
    "Maria Nieves",
    "Gloria",
    "Lidia",
    "Carla",
    "Aurora",
    "Esperanza",
    "Josefina",
    "Sofia",
    "Milagros",
    "Olga",
    "Celia",
    "Maria Soledad",
    "Purificacion",
]

store_names = [
    "Situwala",
    "Yakkha",
    "Gnawale",
    "Buhyo",
    "Kutal",
    "Bindukar",
    "Upeti",
    "Mana",
    "Badhyo",
    "Barme",
    "Dhnaju",
    "Kami",
    "Baidhaya",
    "Ma",
    "Ghimere",
    "Sangami",
    "Ghotane",
    "Kewat",
    "Singtan",
    "Chitrakr",
    "Khwaonjoo",
    "Manjhi",
]

city_names = [
    "Távora",
    "Cataguases",
    "Médici",
    "Bressane",
    "Onça",
    "Brígida",
    "Parati",
    "Mônica",
    "Pantano",
    "Anastácio",
    "Ostras",
    "Jequitibá",
]

# Decorate (@) data generating functions to randomly return certain values (decorating = adding to an existing function)
def randomly_return(frequency, value):
    # frequency = 0..1, 0 is return never, 1 is return always
    # value: what to return
    def inner_function(fn):
        @wraps(fn)
        def wrapper():
            return fn() if random.random() > frequency else value
        return wrapper
    return inner_function

@randomly_return(frequency = 0.002, value=np.datetime64('nat'))
def get_datetime_string(min_year=1980, max_year=datetime.now().year):
    # generate a datetime in format yyyy-mm-dd hh:mm:ss.000000
    start = datetime(min_year, 1, 1, 0, 0, 0)
    years = max_year - min_year + 1
    end = start + timedelta(days=365 * years)
    return start + (end - start) * random.random()

@randomly_return(frequency = 0.003, value=".")
def get_total_amount():
    return round(random.random() * 500, 2)

# Distributed evenly, not realistic.
@randomly_return(frequency = 0.01, value=np.nan)
def get_number_of_products():
    return random.randint(0, 200)

@randomly_return(frequency = 0.07, value="")
def get_cashier():
    return random.choice(first_names)

@randomly_return(frequency = 0.02, value=None)
def get_store_name():
    return random.choice(store_names)

@randomly_return(frequency = 0.07, value="Missing")
def get_city():
    return random.choice(city_names)

@randomly_return(frequency = 0.5, value="NA")
def get_discount_card():
    return random.random() > 0.5

@randomly_return(frequency = 0.006, value=-1)
def get_time_spent():
    return random.randint(30, 600)

def get_random_data(fn, n):
    return [fn() for _ in range(n)]

num_rows = 20_000

data = {
    "datetime": get_random_data(get_datetime_string, num_rows),
    "total_amount": get_random_data(get_total_amount, num_rows),
    "number_of_products": get_random_data(get_number_of_products, num_rows),
    "cashier": get_random_data(get_cashier, num_rows),
    "store": get_random_data(get_store_name, num_rows),
    "city": get_random_data(get_city, num_rows),
    "discount_card_used": get_random_data(get_discount_card, num_rows),
    "time_spent": get_random_data(get_time_spent, num_rows)
}

df = pd.DataFrame(data=data)

## Changing different kind of null values to a default null value
## defaults are: None, NAN (np.nan), NAT (np.nat)

# Three ways of doing this

# 1. Using .loc
# df.loc[df["total_amount"] == ".", "total_amount"] = np.nan  # replacing "." with "NaN"
# print(df.head(20))

# 2. Simple replace .replace(old,new)
# df["total_amount"].replace(".", np.nan, inplace=True)
# print(df.head(20))

# 3. Complex replace
# Simple replace doesn't work when there are None values (empty cells), instead use a dictionary replace:
# .replace({old:new})
np.sort(df["cashier"].unique()) # inplace argument doesn't work in this case
print(df["cashier"].tail(20))

df["cashier"] = df["cashier"].replace({"": None , np.nan: None})  # inplace argument doesn't work in this case
print(df["cashier"].tail(20))

print(df["cashier"].value_counts(dropna=False))
print(df.loc[df["cashier"].isna()]) # Selects all None values

# Coverting values from different columns to standard null values (in this case: None )
print(df["city"].unique())
df["city"].replace("Missing", None, inplace=True)
print(df["city"].unique())

df["discount_card_used"].unique()
df["discount_card_used"].replace("NA", False, inplace=True)  # Think about what value you replace 'NA' with (False, True)
print(df["discount_card_used"].value_counts())


import os

from flask import Flask, render_template, request, redirect
from flask_sqlalchemy import SQLAlchemy

# set the db folder and name relative to the application root folder
project_dir = os.path.dirname(os.path.abspath(__file__))
database_file = f"sqlite:///{os.path.join(project_dir,'bookdatabase.db')}"
print(f"database located at:{database_file}")

app = Flask(__name__)

# bind the app and the db location
app.config["SQLALCHEMY_DATABASE_URI"] = database_file

# initialize the connction to the database and keep this in db variable
db=SQLAlchemy(app)

# class Book, will create a table in db

class Book(db.Model):
    title = db.Column(db.String(80), unique=True, nullable=False, primary_key=True)

    # default representer for the Book class. This will allow to use 'print(book)' and
    # receive a meaningful output.
    def __repr__(self):
        return "<Title: {}".format(self.title)

# to initiate the database use the foolowing
# >python
# >>>from app import db
# >>>db.create_all()
# >>>exit()

# main route of the applicaiton
# by default, flask accepts GET request for all routes
# adding 'methods=["GET", "POST"]' to the route decorator will solve 'Method not allowed'
# error after submitting the form
@app.route("/", methods=["GET", "POST"])
def home():
    if request.form:
        try:
            book = Book(title=request.form.get("title"))
            db.session.add(book)
            db.session.commit()
        except Exception as e:
            print("Failed to add book")
            print(e)

    books = Book.query.all()
    return render_template("index.html", books=books)

@app.route("/update", methods=["POST"])
def update():
    try:
        newtitle = request.form.get("newtitle")
        oldtitle = request.form.get("oldtitle")
        book = Book.query.filter_by(title=oldtitle).first()
        book.title = newtitle
        db.session.commit()
    except Exception as e:
        print("Failed to update book title")
        print(e)
    return redirect("/")

@app.route("/delete", methods=["POST"])
def delete():
    try:
        title = request.form.get("title")
        book = Book.query.filter_by(title=title).first()
        db.session.delete(book)
        db.session.commit()
    except Exception as e:
        print("Failed to delete book")
        print(e)

    return redirect("/")

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


S = list(input())
N = len(S)
if(len(S)!=8):
    print("No")
    exit()

if(S[0].isupper()== True and S[N-1].isupper()==True):
    S.pop(N-1)
    S.pop(0)
else:
    print("No")
    exit()
number = "".join(S)

if(number.isdigit() == True):
    number = int(number)
    if(100000 <= number < 999999):
        print("Yes")
    else:
        print("No")
else:
    print("No")


from django.contrib import admin

from .models import Category, Product, ProductReview

class ProductAdmin(admin.ModelAdmin):
    list_display=('title', 'slug', 'category', 'parent', 'is_featured', 'price', 'num_available', 'num_visits')
    list_filter=('category', 'is_featured', 'num_visits')
    prepopulated_fields={'slug': ('title', 'quantity', 'unit')}

admin.site.register(Category)
admin.site.register(Product, ProductAdmin)
admin.site.register(ProductReview)


"""
Author: OpenAI
Modified by: Julio Cesar RAMIREZ
Institution: ESTIA

Modified in November 2023 by J.Edgar Hernandez Cancino EStrada
B.S. in Robotics and Digital Systems Engineering (June, 2024)
Tecnologico de Monterrey

"""
import numpy as np
from gym_xarm6.envs import rotations, robot_env, utils
import time
from gym_xarm6.data import dhm
import math
def goal_distance(goal_a, goal_b):
    assert goal_a.shape == goal_b.shape
    return np.linalg.norm(goal_a - goal_b, axis=-1)

var = -math.sqrt(2)/2
eef_qpos = [var, 0, var, 0]
# eef_qpos = [0.5, 0.5, -0.5, 0.5]

class xArm6Env(robot_env.RobotEnv):
    """Superclass for all xArm6 environments.
    """

    def __init__(
            self, model_path, n_substeps, gripper_extra_height, block_gripper,
            target_in_the_air, target_offset, obj_range, target_range,
            distance_threshold, initial_qpos, reward_type,
            ):
        """Initializes a new xArm6 environment.

        Args:
            model_path (string): path to the environments XML file
            n_substeps (int): number of substeps the simulation runs on every call to step
            gripper_extra_height (float): additional height above the table when positioning the gripper
            block_gripper (boolean): whether or not the gripper is blocked (i.e. not movable) or not
            target_in_the_air (boolean): whether or not the target should be in the air above the table or on the table surface
            target_offset (float or array with 3 elements): offset of the target
            obj_range (float): range of a uniform distribution for sampling initial object positions
            target_range (float): range of a uniform distribution for sampling a target
            distance_threshold (float): the threshold after which a goal is considered achieved
            initial_qpos (dict): a dictionary of joint names and values that define the initial configuration
            reward_type ('sparse' or 'dense'): the reward type, i.e. sparse or dense
        """
        self.gripper_extra_height = gripper_extra_height
        self.block_gripper = block_gripper
        self.target_in_the_air = target_in_the_air
        self.target_offset = target_offset
        self.obj_range = obj_range
        self.target_range = target_range
        self.distance_threshold = distance_threshold
        self.reward_type = reward_type

        super(xArm6Env, self).__init__(
                model_path=model_path, n_substeps=n_substeps, n_actions=4,
                initial_qpos=initial_qpos)

        # GoalEnv methods
    # --------------------------

    def compute_reward(self, achieved_goal, goal, info):
        # Compute distance between goal and the achieved goal.
        d = goal_distance(achieved_goal, goal)
        if self.reward_type == 'sparse':
            return -(d > self.distance_threshold).astype(np.float32)
        else:
            return -d

    # RobotEnv methods
    # --------------------------

    def _step_callback(self):
        if self.block_gripper:
            self.sim.data.set_joint_qpos('robot0:wrist_roll_joint', 0.)
            self.sim.forward()

    def _set_action(self, action):
        assert action.shape == (4,)
        action = action.copy()  # ensure that we don't change the action outside of this scope
        pos_ctrl, gripper_ctrl = action[:3], action[3]

        pos_ctrl *= 0.02  # limit maximum change in position
        rot_ctrl = eef_qpos  # fixed rotation of the end effector, expressed as a quaternion

        gripper_ctrl = np.array([gripper_ctrl, gripper_ctrl])
        assert gripper_ctrl.shape == (2,)
        if self.block_gripper:
            gripper_ctrl = np.zeros_like(gripper_ctrl)
        action = np.concatenate([pos_ctrl, rot_ctrl, gripper_ctrl])

        # Apply action to simulation.
        utils.ctrl_set_action(self.sim, action)
        utils.mocap_set_action(self.sim, action)

    def _get_obs(self):
        # positions
        grip_pos = self.sim.data.get_site_xpos('robot0:grip')
        dt = self.sim.nsubsteps * self.sim.model.opt.timestep
        grip_velp = self.sim.data.get_site_xvelp('robot0:grip') * dt
        robot_qpos, robot_qvel = utils.robot_get_obs(self.sim)

        # object_pos = np.zeros(0)
        # gripper_state = robot_qpos[-2:]
        # gripper_vel = robot_qvel[-2:] * dt  # change to a scalar if the gripper is made symmetric

        achieved_goal = grip_pos.copy()

        obs = np.concatenate([
            grip_pos, grip_velp
            ])

        return {
                'observation': obs.copy(),
                'achieved_goal': achieved_goal.copy(),
                'desired_goal': self.goal.copy(),
            }

    def _viewer_setup(self):
        body_id = self.sim.model.body_name2id('robot0:tool_link')
        lookat = self.sim.data.body_xpos[body_id]
        for idx, value in enumerate(lookat):
            self.viewer.cam.lookat[idx] = value
        self.viewer.cam.distance = 2.5
        self.viewer.cam.azimuth = 132.
        self.viewer.cam.elevation = -14.

    def _render_callback(self):
        # Visualize target.
        sites_offset = (self.sim.data.site_xpos - self.sim.model.site_pos).copy()
        site_id = self.sim.model.site_name2id('target0')
        self.sim.model.site_pos[site_id] = self.goal - sites_offset[0]
        self.sim.forward()

    def _reset_sim(self):
        self.sim.set_state(self.initial_state)

        self.sim.forward()
        return True

    def _working_space(self):
        pass

    def _sample_goal(self):

        goal = np.array([
            np.random.uniform(0.5, .62, size=1)[0],
            np.random.uniform(-.3, .3, size=1)[0],
            np.random.uniform(.15, .45, size=1)[0]])

        # goal = np.array([
        #     np.random.uniform(-.3, .3, size=1)[0],
        #     np.random.uniform(-0.42, -.62, size=1)[0],
        #     np.random.uniform(.15, .45, size=1)[0]])

        return goal.copy()

    def _is_success(self, achieved_goal, desired_goal):
        d = goal_distance(achieved_goal, desired_goal)
        return (d < self.distance_threshold).astype(np.float32)

    def _env_setup(self, initial_qpos):
        for name, value in initial_qpos.items():
            self.sim.data.set_joint_qpos(name, value)
        utils.reset_mocap_welds(self.sim)
        self.sim.forward()

        # Move end effector into position.
        gripper_target = self.sim.data.get_site_xpos('robot0:grip')
        gripper_rotation = np.array(eef_qpos)

        self.sim.data.set_mocap_pos('robot0:mocap', gripper_target)
        self.sim.data.set_mocap_quat('robot0:mocap', gripper_rotation)
        for _ in range(50):
            self.sim.step()

        # Extract information for sampling goals.
        self.initial_gripper_xpos = self.sim.data.get_site_xpos('robot0:grip').copy()

    def render(self, mode='human', width=500, height=500):
        return super(xArm6Env, self).render(mode, width, height)


import re
import os
import socket
import time
import struct
import dpkt
import dpkt.dns
from threading import Thread, Event

from tiny_test_fw import DUT
import ttfw_idf

# g_run_server = True
# g_done = False
stop_mdns_server = Event()
esp_answered = Event()

def get_dns_query_for_esp(esp_host):
    dns = dpkt.dns.DNS(b'\x00\x00\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x01')
    dns.qd[0].name = esp_host + u'.local'
    print("Created query for esp host: {} ".format(dns.__repr__()))
    return dns.pack()

def get_dns_answer_to_mdns(tester_host):
    dns = dpkt.dns.DNS(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
    dns.op = dpkt.dns.DNS_QR | dpkt.dns.DNS_AA
    dns.rcode = dpkt.dns.DNS_RCODE_NOERR
    arr = dpkt.dns.DNS.RR()
    arr.cls = dpkt.dns.DNS_IN
    arr.type = dpkt.dns.DNS_A
    arr.name = tester_host
    arr.ip = socket.inet_aton('127.0.0.1')
    dns. an.append(arr)
    print("Created answer to mdns query: {} ".format(dns.__repr__()))
    return dns.pack()

def get_dns_answer_to_mdns_lwip(tester_host, id):
    dns = dpkt.dns.DNS(b"\x5e\x39\x84\x00\x00\x01\x00\x01\x00\x00\x00\x00\x0a\x64\x61\x76\x69\x64"
                       b"\x2d\x63\x6f\x6d\x70\x05\x6c\x6f\x63\x61\x6c\x00\x00\x01\x00\x01\xc0\x0c"
                       b"\x00\x01\x00\x01\x00\x00\x00\x0a\x00\x04\xc0\xa8\x0a\x6c")
    dns.qd[0].name = tester_host
    dns.an[0].name = tester_host
    dns.an[0].ip = socket.inet_aton('127.0.0.1')
    dns.an[0].rdata = socket.inet_aton('127.0.0.1')
    dns.id = id
    print("Created answer to mdns (lwip) query: {} ".format(dns.__repr__()))
    return dns.pack()

def mdns_server(esp_host):
    global esp_answered
    UDP_IP = "0.0.0.0"
    UDP_PORT = 5353
    MCAST_GRP = '224.0.0.251'
    TESTER_NAME = u'tinytester.local'
    TESTER_NAME_LWIP = u'tinytester-lwip.local'
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
    sock.bind((UDP_IP,UDP_PORT))
    mreq = struct.pack("4sl", socket.inet_aton(MCAST_GRP), socket.INADDR_ANY)
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
    sock.settimeout(30)
    while not stop_mdns_server.is_set():
        try:
            if not esp_answered.is_set():
                sock.sendto(get_dns_query_for_esp(esp_host), (MCAST_GRP,UDP_PORT))
                time.sleep(0.2)
            data, addr = sock.recvfrom(1024)
            dns = dpkt.dns.DNS(data)
            if len(dns.qd) > 0 and dns.qd[0].type == dpkt.dns.DNS_A:
                if dns.qd[0].name == TESTER_NAME:
                    print("Received query: {} ".format(dns.__repr__()))
                    sock.sendto(get_dns_answer_to_mdns(TESTER_NAME), (MCAST_GRP,UDP_PORT))
                elif dns.qd[0].name == TESTER_NAME_LWIP:
                    print("Received query: {} ".format(dns.__repr__()))
                    sock.sendto(get_dns_answer_to_mdns_lwip(TESTER_NAME_LWIP, dns.id), addr)
            if len(dns.an) > 0 and dns.an[0].type == dpkt.dns.DNS_A:
                if dns.an[0].name == esp_host + u'.local':
                    print("Received answer to esp32-mdns query: {}".format(dns.__repr__()))
                    esp_answered.set()
        except socket.timeout:
            break
        except dpkt.UnpackError:
            continue

@ttfw_idf.idf_example_test(env_tag="Example_WIFI")
def test_examples_protocol_mdns(env, extra_data):
    global stop_mdns_server
    """
    steps: |
      1. join AP + init mdns example
      2. get the dut host name (and IP address)
      3. check the mdns name is accessible
      4. check DUT output if mdns advertized host is resolved
    """
    dut1 = env.get_dut("mdns-test", "examples/protocols/mdns", dut_class=ttfw_idf.ESP32DUT)
    # check and log bin size
    binary_file = os.path.join(dut1.app.binary_path, "mdns-test.bin")
    bin_size = os.path.getsize(binary_file)
    ttfw_idf.log_performance("mdns-test_bin_size", "{}KB".format(bin_size // 1024))
    ttfw_idf.check_performance("mdns-test_bin_size", bin_size // 1024, dut1.TARGET)
    # 1. start mdns application
    dut1.start_app()
    # 2. get the dut host name (and IP address)
    specific_host = dut1.expect(re.compile(r"mdns hostname set to: \[([^\]]+)\]"), timeout=30)
    specific_host = str(specific_host[0])
    thread1 = Thread(target=mdns_server, args=(specific_host,))
    thread1.start()
    try:
        dut1.expect(re.compile(r" sta ip: ([^,]+),"), timeout=30)
    except DUT.ExpectTimeout:
        stop_mdns_server.set()
        thread1.join()
        raise ValueError('ENV_TEST_FAILURE: Cannot connect to AP')
    try:
        # 3. check the mdns name is accessible
        if not esp_answered.wait(timeout=30):
            raise ValueError('Test has failed: did not receive mdns answer within timeout')
        # 4. check DUT output if mdns advertized host is resolved
        dut1.expect(re.compile(r"mdns-test: Query A: tinytester.local resolved to: 127.0.0.1"), timeout=30)
        dut1.expect(re.compile(r"mdns-test: gethostbyname: tinytester-lwip.local resolved to: 127.0.0.1"), timeout=30)
        dut1.expect(re.compile(r"mdns-test: getaddrinfo: tinytester-lwip.local resolved to: 127.0.0.1"), timeout=30)
    finally:
        stop_mdns_server.set()
        thread1.join()

if __name__ == '__main__':
    test_examples_protocol_mdns()


import numpy as np
from scipy import signal
from skimage.util import pad
from skimage.measure import compare_ssim
from timeit import default_timer as timer

def compute_nrmse(im1, im2):
    """
    Compute the Normalized Mean Square Error.

    A min-max normalized mean square error value and array are computed from
    two input images (i.e. patterns). This implementation ignores the order of
    im1 and im2 in the normalization. We normalize to scale values between 0
    and 1, and then subtract both the global value and the array from 1 so
    that higher values indicate a greater degree of similarity (i.e. less
    error) between the two images.

    Args:
        im1 (ndarray): 2d array
        im2 (ndarray): 2d array, same size/shape/type as im1
    Returns:
        nrmse (tuple): nrmse value and array of nrsme values
    Raises:
        Exception: description
    """
    print("Computing NRMSE...")
    start = timer()

    im1_max = np.nanmax(im1)
    im2_max = np.nanmax(im2)
    im1_min = np.nanmin(im1)
    im2_min = np.nanmin(im2)
    both_max = max(im1_max, im2_max)
    both_min = min(im1_min, im2_min)

    # Compute global index NRMSE value
    mse = np.mean(np.square(im1 - im2))
    min_max_nrmse = np.sqrt(mse) / (both_max - both_min)
    # Compute NRSE array
    square_error = np.square(im1 - im2)
    min_max_nrmse_arr = np.sqrt(square_error) / (both_max - both_min)
    # Reverse scale so 1 is 'good', 0 is 'bad'
    nrmse_flip = round(1 - min_max_nrmse, 3)
    nrmse_arr_flip = 1 - min_max_nrmse_arr

    nrmse_results = (nrmse_flip, nrmse_arr_flip)

    print("Complete. " + str((timer() - start))[0:4] + " s")

    return nrmse_results

def compute_ssim(im1, im2):
    """
    Compute Structural Similarity Index of two single band images.

    The human visual system is well adapted to extracting structural
    information from a scene. Structural information refers to how
    objects are arranged in a scene independent of background
    intensity and contrast (Wang et al., 2004). "We define
    structural information in an image as those attributes that
    represent the structure of objects in the scene, independent of
    the average luminance and contrast. Since luminance and contrast
    can vary across a scene, we use the local luminance and contrast
    for our definition. Luminance, contrast, and structure
    comparisons make up SSIM. Brightness in the SSIM map indicates
    the magnitude of the local SSIM index (squared for visibility).

     Wang, Z., Bovik, A. C., Sheikh, H. R., & Simoncelli, E. P.
     (2004). Image quality assessment: From error visibility to
     structural similarity. IEEE Transactions on Image Processing,
     13, 600-612.
     https://ece.uwaterloo.ca/~z70wang/publications/ssim.pdf,
     DOI:10.1109/TIP.2003.819861

    Args:
        im1 (ndarray): 2d array for similarity
        im2 (ndarray): 2d array, same size/shape as im1
    Returns:
        ssim (tuple): mean value and array of SSIM values
    Raises:
        Exception: description
    """

    start = timer()
    print("Computing SSIM...")
    mean_ssim_val, ssim_arr = compare_ssim(im1, im2,
                                           sigma=1.5,
                                           gaussian_weights=True,
                                           use_sample_covariance=False,
                                           full=True)

    mean_ssim_val_scaled = (mean_ssim_val + 1) / 2
    ssim_arr_scaled = (ssim_arr + 1) / 2
    ssim = (mean_ssim_val_scaled, ssim_arr_scaled)

    print("Complete. " + str((timer() - start))[0:4] + " s")

    return ssim

def cw_ssim(im1, im2, width):
    """
    Compute a complex wavelet implementation of SSIM (CW-SSIM).

    CW-SSIM insensitive to translation, scaling and rotation of
    images. A value of +1 indicates perfect similarity and a value of
    -1 indicates lack of similarity.

    Args:
        im1 (ndarray): 2d array for similarity
        im2 (ndarray): 2d array, same size/shape as im1
        width (int): wavelet width for convolution (default: 30)
    Returns:
        ssim (tuple): mean value and array of CW-SSIM values
    Raises:
        Exception: description
    """
    start = timer()
    print("Computing Complex Wavelet SSIM...")

    # Define a width for the wavelet convolution
    widths = np.arange(1, width+1)

    # Unwrap image arrays to 1 dimensional arrays
    sig1 = np.ravel(im1)
    sig2 = np.ravel(im2)

    # Perform a continuous wavelet transform (cwt) on each array
    # Use Ricker (a.k.a. Mexican Hat a.k.a. Marr) wavelet
    # Ricker is neg. normalized 2nd derivative of a Gaussian
    cwtmatr1 = signal.cwt(sig1, signal.ricker, widths)
    cwtmatr2 = signal.cwt(sig2, signal.ricker, widths)

    # Compute the first term:
    # Compute product of the absolute values of the cwts
    c1c2 = np.multiply(abs(cwtmatr1), abs(cwtmatr2))
    # Compute squares of absolute values of the cwt for each image
    c1_2 = np.square(abs(cwtmatr1))
    c2_2 = np.square(abs(cwtmatr2))
    num_ssim_1 = 2 * np.sum(c1c2, axis=0) + 0.01
    den_ssim_1 = np.sum(c1_2, axis=0) + np.sum(c2_2, axis=0) + 0.01
    # Compute the second term:
    """
    Compute consistency of phase changes between the arrays.
    Structural info of local features is concentrated in the relative
    phase patterns of the wavelet coefficients (i.e. a consistent
    phase shift of all coefficients does not change the structure of
    the local image feature. First compute the product of the cwt of
    the first image and the complex conjugate of the cwt of the second image:
    """
    c1c2_conj = np.multiply(cwtmatr1, np.conjugate(cwtmatr2))
    num_ssim_2 = 2 * np.abs(np.sum(c1c2_conj, axis=0)) + 0.01
    den_ssim_2 = 2 * np.sum(np.abs(c1c2_conj), axis=0) + 0.01

    # Compute Index and Mean
    cw_ssim_map = (num_ssim_1 / den_ssim_1) * (num_ssim_2 / den_ssim_2)
    cw_ssim_map = cw_ssim_map.reshape(im1.shape[0],
                                      im1.shape[1])
    cw_ssim_index = round(np.average(cw_ssim_map), 3)

    print("Complete. " + str((timer() - start))[0:4] + " s")

    return (cw_ssim_index + 1) / 2, (cw_ssim_map + 1) / 2

def convolve(image, kernel):
    """ Perform Convolution on Image with a given kernel.

    Parameters
    ----------
    image : ndarray
        Image.  Any dimensionality.
    kernel : ndarray
        Kernel to convolve over image.

    Returns
    -------
    output : ndarray
        Convolved Image.
    """

    # grab the spatial dimensions of the image, along with
    # the spatial dimensions of the kernel
    (iH, iW) = image.shape[:2]
    (kH, kW) = kernel.shape[:2]

    # allocate memory for the output image, taking care to
    # "pad_size" the borders of the input image so the spatial
    # size (i.e., width and height) are not reduced

    pad_size = int((kW - 1) / 2)
    image = pad(image, pad_size, mode='edge')
    output = np.zeros((iH, iW), dtype="float32")

    # loop over the input image, "sliding" the kernel across
    # each (x, y)-coordinate from left-to-right and top to
    # bottom

    for y in np.arange(pad_size, iH + pad_size):
        for x in np.arange(pad_size, iW + pad_size):
            # extract the ROI of the image by extracting the
            # *center* region of the current (x, y)-coordinates
            # dimensions

            roi = image[y - pad_size:y + pad_size + 1, x - pad_size:x
                        + pad_size + 1]

            # perform the actual convolution by taking the
            # element-wise product between the ROI and
            # the kernel, then summing the matrix

            k = (roi * kernel).sum()

            # store the convolved value in the output (x,y)
            # coordinate of the output image
            output[y - pad_size, x - pad_size] = k
    return output

def compute_gms(im1, im2):
    """ Compute the Gradient Magnitude Similarity (GMS) and
    Deviation Index (GMSD) of two images.

    A GMSD of 1 indicates perfect similarity. A GMSD of 0 is the
    lower bound for poor similarity.
    Xue, W., Zhang, L., Mou, X., & Bovik, A. C. (2014).
    Gradient magnitude similarity deviation: A highly efficient perceptual
    image quality index.
    IEEE Transactions on Image Processing, 23(2), 668–695.
    http://doi.org/10.1109/TIP.2013.2293423

    Args:
        im1 (ndarray): 2d array for similarity
        im2 (ndarray): 2d array, same size/shape as im1
    Returns:
        gms_index (float): The GMSD metric.
    gms_map (ndarray) GMS Array.
    """

    print("Computing Gradient Magnitude Similarity...")
    start = timer()
    # Construct Prewitt kernels with values from literature
    h_x = [0.33, 0, -0.33, 0.33, 0, -0.33, 0.33, 0, -0.33]
    h_x = np.array(h_x).reshape(3, 3)
    h_y = np.flipud(np.rot90(h_x))

    # Create gradient magnitude images for each image with Prewitt kernels
    # Reference (im1)
    ref_conv_hx = convolve(im1, h_x)
    ref_conv_hy = convolve(im1, h_y)
    ref_grad_mag = np.sqrt((ref_conv_hx ** 2) + (ref_conv_hy ** 2))

    # 'Distorted' (im2)
    dst_conv_hx = convolve(im2, h_x)
    dst_conv_hy = convolve(im2, h_y)
    dst_grad_mag = np.sqrt((dst_conv_hx ** 2) + (dst_conv_hy ** 2))

    c = 0.0026  # Constant provided by literature

    gms_map = (2 * ref_grad_mag * dst_grad_mag + c) / (ref_grad_mag ** 2 + dst_grad_mag ** 2 + c)
    gms_index = np.sqrt(np.sum((gms_map - gms_map.mean()) ** 2) / gms_map.size)

    end = timer()
    print("...Complete. Elapsed Seconds: " + str((end - start))[0:4])

    return 1 - round(gms_index, 3), gms_map

def compute_all_iqa(im1, im2):
    """
    Compute all similarity metrics and maps and return a dictionary.

    Calls all simliarity metrics (IQA) on an image pair. Current metrics: MSE,
    SSIM, CW-SSIM, and GMS).
    Args:
        im1 (ndarray): 2d array for similarity
        im2 (ndarray): 2d array, same size/shape as im1
    Returns:
        sim (dict): dictionary that stores results with the following
        structure: results{
                    [*metric*: float,
                    *metric*_arr: array]}
    Raises:
        None.
    """
    sim = dict()
    sim['nrmse'], sim['nrmse_arr'] = compute_nrmse(im1, im2)
    sim['ssim'], sim['ssim_arr'] = compute_ssim(im1, im2)
    sim['cwssim'], sim['cwssim_arr'] = cw_ssim(im1, im2, 10)
    sim['gms'], sim['gms_arr'] = compute_gms(im1, im2)
    # sim['fsim_value'], sim['pc_max_map'] = compute_fsim(im1, im2)
    return sim


import  random
from model.contact import Contact

#@pytest.mark.skip(reason="no way of currently testing this") # это нужно для отключение теста
def test_modify_contact_name(app, db, check_ui):
    if len(db.get_contact_list()) == 0:
        app.contact.create(Contact(firstname="test7777"))
    old_contacts = db.get_contact_list()
    random_contact = random.choice(old_contacts)
    contact = Contact(firstname="new firstname1")
    contact.id = random_contact.id
    app.contact.modify_contact_by_id(random_contact.id, contact)
#    assert len(old_contacts) == app.contact.count()
    new_contacts = db.get_contact_list()
    old_contacts.remove(random_contact)
    old_contacts.append(contact)
    assert sorted(old_contacts, key=Contact.id_or_max) == sorted(new_contacts, key=Contact.id_or_max)
    if check_ui:
        assert sorted(new_contacts, key=Contact.id_or_max) == sorted(app.contact.get_contact_list(), key=Contact.id_or_max)

# def test_modify_contact_header(app):
#     if app.contact.count() == 0:
#         app.contact.create(Contact(middlename="test7777"))
#     old_contacts = app.contact.get_contact_list()
#     app.contact.modify_first_contact(Contact(middlename="new middlename1"))
#     new_contacts = app.contact.get_contact_list()
#     assert len(old_contacts) == len(new_contacts)


# 2. Write a program that checks two given integers and returns true if at least one of
# them is 30 or if their sum is 30. In other words, if either of the two integers is 30 or
# if their sum equals 30, the program will return true.

def check_numbers(nr1, nr2):
	print(f"nr1: {nr1}")
	print(f"nr2: {nr2}")
	print(f"sum: {nr2 + nr1}")
	if ((nr1 == 30) or (nr2 == 30)) or (nr1 + nr2 == 30):
		return True
	else: return False

nr1 = 15
nr2 = 15

print(check_numbers(nr1, nr2))


import requests as r
import config as cfg
from collections import deque
import sys
import time
import os

tree = dict()  #
d = dict()  #
q = deque()  #
used = dict()  #
pred = dict()  #
fout = open("order.txt", "w")

def nameFromID(id):
    response = r.get(
        "https://api.vk.com/method/users.get?access_token={0}&user_ids={1}&v=5.75".format(cfg.token, id))
    name = response.json()["response"][0]["first_name"]
    surname = response.json()["response"][0]["last_name"]
    return name + " " + surname

maxD, ids, idf = sys.argv[1:]
maxD = int(maxD)

start = time.clock()

response = r.get(
    "https://api.vk.com/method/users.get?access_token={0}&user_ids={1}&v=5.75".format(cfg.token, ids))
ids = response.json()["response"][0]["id"]
response = r.get(
    "https://api.vk.com/method/users.get?access_token={0}&user_ids={1}&v=5.75".format(cfg.token, idf))
idf = response.json()["response"][0]["id"]

q.append(ids)
d[ids] = 0
pred[ids] = ids
used[ids] = True
curD = 0
found = False
count = 0

while len(q) > 0 and curD <= maxD and not found:
    start = time.clock()
    v = q.popleft()
    curD = d[v]
    if v == idf:
        found = True
    response = None
    while response is None:
        try:
            response = r.get(
                "https://api.vk.com/method/friends.get?access_token={0}&user_id={1}&v=5.75".format(cfg.token, v), timeout=5)
        except r.exceptions.BaseHTTPError as e:
            print("Connection error, trying again in 2s")
            print()
            time.sleep(2)
            continue
    items = response.json().get("response", {"items": []})["items"]
    for item in items:
        if used.get(item, False):
            continue
        used[item] = True
        d[item] = d[v] + 1
        pred[item] = v
        if item == idf:
            found = True
            break
        q.append(item)
        count += 1

    sys.stdout.write("\rTotal people checked: " + str(count))
    sys.stdout.flush()
    time.sleep(0.1)

print()
if found:
    if not os.path.exists("img"):
        os.makedirs("img")
    id = idf
    order = []
    while d[id] > 0:
        order.append(nameFromID(id))
        order.append(str(id))
        response = r.get(
            "https://api.vk.com/method/users.get?access_token={0}&fields=photo_max&user_ids={1}&v=5.75".format(cfg.token, id))
        imgR = r.get(response.json()["response"][0]["photo_max"])
        with open("img/" + str(id) + ".jpg", "wb") as img:
            img.write(imgR.content)
            img.close()
        id = pred[id]
    response = r.get(
        "https://api.vk.com/method/users.get?access_token={0}&fields=photo_max&user_ids={1}&v=5.75".format(cfg.token, id))
    imgR = r.get(response.json()["response"][0]["photo_max"])
    with open("img/" + str(id) + ".jpg", "wb") as img:
        img.write(imgR.content)
        img.close()
    order.append(nameFromID(id))
    order.append(str(id))
    order.reverse()
    print(len(order) // 2, file=fout)
    for id in order:
        print(id, file=fout)
    fout.close()
else:
    print("Sorry, finish id is out of max range")


import os
import wx

import gimelstudio.constants as const

class NodeGraphDropTarget(wx.DropTarget):
    def __init__(self, window, *args, **kwargs):
        super(NodeGraphDropTarget, self).__init__(*args, **kwargs)
        self._window = window
        self._composite = wx.DataObjectComposite()
        self._textDropData = wx.TextDataObject()
        self._fileDropData = wx.FileDataObject()
        self._composite.Add(self._textDropData)
        self._composite.Add(self._fileDropData)
        self.SetDataObject(self._composite)

    def OnDrop(self, x, y):
        return True

    def OnData(self, x, y, result):
        self.GetData()
        formatType, formatId = self.GetReceivedFormatAndId()
        if formatType in (wx.DF_TEXT, wx.DF_UNICODETEXT):
            return self.OnTextDrop()
        elif formatType == wx.DF_FILENAME:
            return self.OnFileDrop()

    def GetReceivedFormatAndId(self):
        _format = self._composite.GetReceivedFormat()
        formatType = _format.GetType()
        try:
            formatId = _format.GetId()  # May throw exception on unknown formats
        except Exception:
            formatId = None
        return formatType, formatId

    def OnTextDrop(self):
        try:
            self._window.AddNode(self._textDropData.GetText(), nodeid=None,
                                 pos=(0, 0), location="CURSOR")
            self._window.UpdateNodegraph()
        except Exception as error:
            self.ShowError(error)
        return wx.DragCopy

    def OnFileDrop(self):
        for filename in self._fileDropData.GetFilenames():
            try:
                filetype = os.path.splitext(filename)[1]

                if filetype.lower() in const.SUPPORTED_FT_SAVE_LIST:
                    if os.path.exists(filename) is True:
                        # Create Image node with path
                        node = self._window.AddNode("corenode_image", pos=(0, 0),
                                                    nodeid=None, location="CURSOR")
                        node.NodeEditProp(idname="file_path",
                                          value=filename, render=False)
                        node.ToggleExpand()
                        node.NodeDndEventHook()
                        self._window.UpdateNodegraph()

                    else:
                        self.ShowError()

                else:
                    dlg = wx.MessageDialog(None,
                                           _("That file type isn't currently supported!"),
                                           _("Cannot Open File!"), style=wx.ICON_EXCLAMATION)
                    dlg.ShowModal()
                    return False

            except Exception as error:
                self.ShowError(error)

        return wx.DragCopy

    def ShowError(self, error=""):
        dlg = wx.MessageDialog(None, "\n {}!".format(str(error)),
                               _("Error!"), style=wx.ICON_ERROR)
        dlg.ShowModal()
        return False


# -*- coding: utf-8 -*-
"""
Created on Thu Mar  4 15:21:08 2021

@author: Ana Clara St. Aubyn

Data Treatment Domestic Violence National Portugal

"""

import pandas as pd
import numpy as np
import os, inspect
os.chdir(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))))

#Importing National Data
data = pd.read_csv(r'Data\National.csv', delimiter=';')

#Eliminate Irrelevant Rows
data = data.iloc[5:]
data.reset_index(drop=True, inplace=True)

#Creating Titles for Columns
data.columns = data.iloc[0]
data = data.iloc[1:]

#Removing Null and Unnecessary Columns
data.dropna(axis=1, how='all', inplace=True)
data.drop([data.columns[0], data.columns[1]], axis=1, inplace=True)
data.rename(columns={data.columns[0]: "Crime"}, inplace=True)

#Eliminate Rows Referring to Other Type 2 Crimes
data = data[data[data.columns[0]].notna()]

#Removing Unknown Characters from Crime
data['Crime'] = data['Crime'].str.replace("[^A-Za-z1234567890'-. ]", "")

#Keeping Only Domestic Violence
data = data[data['Crime'].str.contains('violncia domstica') | data['Crime'].str.contains('Violncia domstica')]

#Remove Years With No Data
data = data.replace('..', np.nan)
data.dropna(axis=1, how='all', inplace=True)

#Sort Years in Ascending Order
data = data[data.columns[::-1]]
cols = data.columns.tolist()
cols = cols[-1:] + cols[:-1]
data = data[cols]
del cols

#Create a Total Row
data[data.columns[1:].tolist()] = data[data.columns[1:].tolist()].apply(lambda x: x.str.replace(' ',''))
data[data.columns[1:].tolist()] = data[data.columns[1:].tolist()].apply(pd.to_numeric)
data.loc['Total']= data.sum(numeric_only=True, axis=0)
data.reset_index(drop=True, inplace=True)

#Correct Crime Column
data['Crime'] = ['Violencia Domestica Conjuge ou Analogo', 'Violencia Domestica Menores', 'Outros Violencia Domestica', 'Total']

#Export as CSV
data.to_csv(r'Data\national_treated.csv', index=False)


#!/usr/bin/env python3

from wearebeautiful.scale import scale_mesh
import click

@click.command()
@click.option('--cleanup', default=False, help='Clean the mesh before scaling')
@click.option('--invert/--no-invert', default=False, help='Flip the normals on the STL file')
@click.argument("len", nargs=1, type=float)
@click.argument("in_file", nargs=1)
@click.argument("out_file", nargs=1)
def scale(invert, len, in_file, out_file):
    scale_mesh(invert, len, in_file, out_file)

def usage(command):
    with click.Context(command) as ctx:
        click.echo(command.get_help(ctx))

if __name__ == "__main__":
    print("scale_mesh.py running, making STL files. <3\n")
    scale()
    sys.exit(0)


import pandas as pd
import numpy as np

def main(file, output):
    '''
    file: 输入文件
    output: 输出文件
    '''
    data_all = pd.read_csv(file)
    # print(data_all['0.3um'])
    df = pd.DataFrame([data_all['0.3um'], data_all['0.5um'], data_all['1.0um'],
                       data_all['2.0um'], data_all['5.0um'], data_all['10.0um'], data_all['Sample Number']]).T

    print('df.length = ' + str(df.shape[0]))

    # 获取 次数 分界线 应为 19 个数字
    length = df.shape[0]
    number = []
    for i in range(length):
        row = df.loc[i]
        if row['Sample Number'] == 1:
            number.append(i)
    number.append(length)
    print(str(number))
    assert(len(number) == 19)

    # 获取每一个次数的 DataFrame 并拼接需要保存的数据
    mean_df = pd.DataFrame()
    median_df = pd.DataFrame()
    for n in range(len(number) - 1):
        # 行切分
        _df = df[number[n]: number[n + 1]]
        # 剔除异常值
        excluding_outliers_df = excluding_outliers(_df)
        # 平均值 df
        mean_df = mean_df.append(
            excluding_outliers_df.mean(), ignore_index=True)
        # 中位数 df
        median_df = median_df.append(
            excluding_outliers_df.median(), ignore_index=True)
        # 保存
        save_excluding_outliers(n + 1, excluding_outliers_df, output)

    save_df(mean_df, output + '_mean')
    save_df(median_df, output + '_median')

def save_df(df, output):
    ten_um = df['10.0um']
    df.drop(labels=['10.0um'], axis=1, inplace=True)
    df.insert(5, '10.0um', ten_um)

    # 保存 mean, median 等 df
    with open(output + '.csv', 'a') as f:
        f.write(df.to_csv())

def excluding_outliers(df):
    mean = df.mean()
    std = df.std()

    return df[(df - mean).abs() <= 3 * std]

def save_excluding_outliers(n, df, output):
    # 保存剔除异常值后的 df
    data = str(n) + '\n'
    _mean = df.mean().values  # 每一列的 平均数 list
    _max = df.max().values  # 最大值 list
    _min = df.min().values  # 最小值 list
    _std = df.std().values  # 标准差 list
    _median = df.median().values  # 中位数 list

    data += df.to_csv()
    data += 'mean, ' + ', '.join(str(x) for x in _mean) + '\n'
    data += 'max, ' + ','.join(str(x) for x in _max) + '\n'
    data += 'min, ' + ','.join(str(x) for x in _min) + '\n'
    data += 'std, ' + ','.join(str(x) for x in _std) + '\n'
    data += 'median, ' + ','.join(str(x) for x in _median) + '\n'
    with open(output + '.csv', 'a') as f:
        f.write(data)

files = [
    ('handle-data/0703.csv', 'handle-data/output_0703'),
    ('handle-data/0710.csv', 'handle-data/output_0710'),
    ('handle-data/0712.csv', 'handle-data/output_0712'),
    ('handle-data/0713.csv', 'handle-data/output_0713'),
    ('handle-data/0714.csv', 'handle-data/output_0714'),
    ('handle-data/0715.csv', 'handle-data/output_0715'),
    ('handle-data/0716.csv', 'handle-data/output_0716'),
    ('handle-data/0717.csv', 'handle-data/output_0717'),
    ('handle-data/0718.csv', 'handle-data/output_0718'),
    ('handle-data/0719.csv', 'handle-data/output_0719'),
    ('handle-data/0720.csv', 'handle-data/output_0720')
]

# 执行
for file in files:
    main(file[0], file[1])


"""Altair charts definitions"""
import altair as alt
import pandas as pd

def create_balance_chart(balance_df: pd.DataFrame) -> alt.Chart:
    """
    Creates an interactive chart of absolute balance in time.

    Args:
        balance_df: Balance DataFrame including `date` and `balance` columns.

    Returns:
        Altair chart.
    """
    line = (
        alt.Chart(balance_df)
        .mark_line()
        .encode(
            alt.X("date:T", title=None, axis=alt.Axis(format="%b %y", labelAngle=-70)),
            alt.Y("balance:Q", title="balance [SEK]"),
        )
    )

    selection_nearest = alt.selection_single(
        fields=["date"],
        nearest=True,
        on="mouseover",
        empty="none",
    )

    tooltips = (
        alt.Chart(balance_df)
        .mark_rule(color="white")
        .encode(
            x="date:T",
            opacity=alt.condition(selection_nearest, alt.value(0.5), alt.value(0)),
            tooltip=[
                alt.Tooltip("date:T", format="%d %b %Y"),
                alt.Tooltip("balance:Q", format=",.2f"),
            ],
        )
        .add_selection(selection_nearest)
    )

    points = line.mark_point().encode(
        opacity=alt.condition(selection_nearest, alt.value(1), alt.value(0))
    )

    return (line + tooltips + points).interactive()

def create_expenses_incomes_chart(expenses_incomes_df: pd.DataFrame) -> alt.Chart:
    """
    Creates a bar chart of monthly aggregated incomes and expenses.

    Args:
        expenses_incomes_df: DataFrame including `date`, `type` and `amount` columns.

    Returns:
        Altair chart.
    """
    bars = (
        alt.Chart(expenses_incomes_df)
        .mark_bar()
        .encode(
            x=alt.X("type:N", title="", sort="descending"),
            y=alt.Y("amount:Q", title="amount [SEK]"),
            color=alt.Color(
                "type:N",
                sort="descending",
                scale=alt.Scale(range=["mediumseagreen", "indianred"]),
            ),
            column="yearmonth(date):T",
        )
        .configure_legend(
            orient="top",
            title=None,
        )
        .configure_header(title=None)
        .configure_facet(spacing=5)
    )

    return bars


import os
from datetime import timedelta, timezone

import discord
from discord.ext import commands
from dotenv import load_dotenv

load_dotenv()

utc = timezone.utc
jst = timezone(timedelta(hours=9), "Asia/Tokyo")

guild_id = int(os.environ["GUILD_ID"])

vc_log_channel = int(os.environ["VC_LOG_CHANNEL"])

class Logger(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener(name="on_voice_state_update")
    async def vc_log(
        self,
        member: discord.Member,
        before: discord.VoiceState,
        after: discord.VoiceState,
    ):
        if member.guild.id == guild_id and (before.channel != after.channel):
            channel = self.bot.get_channel(vc_log_channel)
            now = discord.utils.utcnow().astimezone(jst)
            if before.channel is None:
                message = f"{now:%m/%d %H:%M:%S} : {member.name}(ID: {member.id}) が {after.channel.mention} に参加しました。"
                await channel.send(message)
                return
            elif after.channel is None:
                message = f"{now:%m/%d %H:%M:%S} : {member.name}(ID: {member.id}) が {before.channel.mention} から退出しました。"
                await channel.send(message)
                return
            else:
                message = f"{now:%m/%d %H:%M:%S} : {member.name}(ID: {member.id}) が {before.channel.mention} から {after.channel.mention} に移動しました。"
                await channel.send(message)
                return

def setup(bot):
    return bot.add_cog(Logger(bot))


'''
2023.06.13
김수종
#문제정의
    3개의 매개변수를 전달 받아서 가장 큰 값을 리턴하는
    findmax(a,b,c)함수 구현
#알고리즘
    1. findmax(a,b,c)함수 선언
        a, b, c중  가장 큰 값 찾기
    2. num1, num2, num3 정수 입력 받기
    3. findmax(num1, num2, num3) 호출
    4. 리턴받은 가장 큰 값 출력
'''

def findmax(a,b,c):
    if a>b :
        biggest=a
    else:
        biggest=b

    if biggest<c:
        biggest=c

    return biggest #가장 큰값 반환

num1=int(input("num1 : "))
num2=int(input("num2 : "))
num3=int(input("num3 : "))

biggest_number=findmax(num1, num2, num3) #함수 호츨
print("가장 큰 숫자 :",biggest_number)


"""A setuptools based setup module."""
from os import path
from setuptools import setup, find_packages
from io import open

here = path.abspath(path.dirname(__file__))

# Get the long description from the README file
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
    long_description = f.read()

setup(
    name='Immunitor',
    version='0.0.1',
    description='Immunitor',
    long_description=long_description,
    long_description_content_type='text/markdown',
    url='https://github.com/cunyap/immunitor',
    author='Andreas P. Cuny',
    author_email='andreas.cuny@bsse.ethz.ch',
    classifiers=[
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.7',
        'Programming Language :: Python :: 3.8',
    ],
    keywords='Immunitor',
    packages=find_packages(),
    install_requires=['Flask',
                      'Flask-WTF',
                      "click",
                      "itsdangerous",
                      "Jinja2",
                      "MarkupSafe",
                      "python-dotenv",
                      "Werkzeug",
                      "WTForms",
                      "Flask-QRcode",
                      "pgeocode",
                      "plotly",
                      "pandas",
                      "pybis",
                      "flask_recaptcha",
                      "waitress"],
    extras_require={
        'dev': ['check-manifest'],
        'test': ['coverage'],
        'env': ['python-dotenv']
    },
    entry_points={
        'console_scripts': [
            'run=wsgi:__main__',
        ],
    },
    project_urls={
        'Bug Reports': 'https://github.com/cunyap/codevscovid19_app/issues',
        'Source': 'https://github.com/cunyap/codevscovid19_app',
    },
)


import torch

class Args():
    def __init__(self):
        self.max_length = 128
        self.lr = 1e-5
        self.num_epochs = 5
        self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
        self.batch_size = 8
        self.model_name = "ai-forever/ruRoberta-large"
        self.random_state = 101
        self.num_classes = 29


import socket, cv2, pickle, struct

fuente1 = "rtsp://192.168.226.202:554"

host_ip = '192.168.226.100'
print('HOST IP:',host_ip)
port = 9999
socket_address = (host_ip,port)

# Socket Create
server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server_socket.bind(socket_address)	# Socket Bind
server_socket.listen(5) 			# Socket Listen
print("LISTENING AT:",socket_address)

client_socket,addr = server_socket.accept()
if client_socket:
	print('GOT CONNECTION FROM:',addr)
	rov_cam1 = cv2.VideoCapture(fuente1)

	while(rov_cam1.isOpened()):
		ret,frame = rov_cam1.read()

		if ret == True:
			# Pack size of frame + frame
			#frame = cv2.resize(frame,(176,144))
			a = pickle.dumps(frame)
			message = struct.pack("Q",len(a))+a
			client_socket.sendall(message)


from ANNarchy import *
import pylab as plt
from scipy import signal, stats
from model_neuronmodels import params, rng, Izhikevich2007RS, Izhikevich2007FS
from extras import lognormalPDF, get_log_normal_fit, set_size

### create 1000 neurons of each neurontype
corE = Population(1000, neuron=Izhikevich2007RS, name='CorE')
corI = Population(1000, neuron=Izhikevich2007FS, name='CorI')

### create spiketimearray input with one spike
spike_times = [
  [10] for i in range(1)
]
inputPop = SpikeSourceArray(spike_times=spike_times)

### direct this spike to both populations
inputPopcorE = Projection(
    pre    = inputPop,
    post   = corE,
    target = 'ampa',
    name = 'inputPopcorE'
).connect_all_to_all(weights = params['weightDist'](rng))#weights have specific log normal dist to obtain PSP dist

inputPopcorI = Projection(
    pre    = inputPop,
    post   = corI,
    target = 'ampa',
    name = 'inputPopcorI'
).connect_all_to_all(weights = params['weightDist'](rng))#weights have specific log normal dist to obtain PSP dist

"""
### Define weights so that the PSP distribution looks like the target PSP population (see extras.lognormalPDF)

#how new mu, sigma were obtained:
#inputPopcorE --> weights * 0.5
test=0.3*rng.lognormal(-0.7,0.93,10000)
shape,loc,scale = stats.lognorm.fit(test)
sigma=shape
mu=np.log(scale)
print(mu,sigma)
quit()
#inputPopcorE --> weights * 0.3-0.4
... both about mu=1.5"""

### compile
compile()

### compare weight distribution with target EPSP distribution
plt.figure()
x=np.arange(0.01,7.5,0.01)
plt.hist(np.array(inputPopcorE.w).flatten(), 100, density=True, align='mid', label='weights')
plt.plot(x, lognormalPDF(x), label='EPSPs Song et al. (2005)')
plt.xlim(0,10)
plt.legend()
plt.savefig('../results/get_weightDist/get_weightDist_weightsE_dist.svg')

### record membranepotential of both neurons
mon_v_corE = Monitor(corE, 'v')
mon_v_corI = Monitor(corI, 'v')

### simulate 100 ms
simulate(100)

### plot membrane potentials
v_corE = mon_v_corE.get('v')
v_corI = mon_v_corI.get('v')

### get peak values from membrane potentials
maxPosE=np.zeros(1000)*np.nan
maxPosI=np.zeros(1000)*np.nan
maxValE=np.zeros(1000)*np.nan
maxValI=np.zeros(1000)*np.nan
for idx in range(1000):
    if len(signal.argrelmax(v_corE[:,idx])[0])>0:
        maxPosE[idx]=signal.argrelmax(v_corE[:,idx])[0][0]
        maxValE[idx]=v_corE[int(maxPosE[idx]),idx]
    if len(signal.argrelmax(v_corI[:,idx])[0])>0:
        maxPosI[idx]=signal.argrelmax(v_corI[:,idx])[0][0]
        maxValI[idx]=v_corI[int(maxPosI[idx]),idx]

plt.figure()
plt.subplot(211)
plt.plot(v_corE[:,0],color='C0')
plt.plot(v_corE[:,1],color='C1')
plt.plot(v_corE[:,999],color='C2')
plt.axvline(maxPosE[0],color='C0')
plt.axvline(maxPosE[1],color='C1')
plt.axvline(maxPosE[999],color='C2')
plt.axhline(maxValE[0],color='C0')
plt.axhline(maxValE[1],color='C1')
plt.axhline(maxValE[999],color='C2')
plt.subplot(212)
plt.plot(v_corI[:,0],color='C0')
plt.plot(v_corI[:,1],color='C1')
plt.plot(v_corI[:,999],color='C2')
plt.axvline(maxPosI[0],color='C0')
plt.axvline(maxPosI[1],color='C1')
plt.axvline(maxPosI[999],color='C2')
plt.axhline(maxValI[0],color='C0')
plt.axhline(maxValI[1],color='C1')
plt.axhline(maxValI[999],color='C2')
plt.savefig('../results/get_weightDist/get_weightDist_PSPexamples.svg')

### calculate PSP distribution from membrane potentials

## difference between resting potential and peaks below 0
PSPsE=maxValE[maxValE<0]-params['RS_v_r']
PSPsI=maxValI[maxValE<0]-params['FS_v_r']

plt.figure()
plt.subplot(211)
plt.hist(PSPsE[PSPsE<=10], 100, density=True, align='mid', label='EPSPs in CorE')
plt.plot(x,lognormalPDF(x), label='EPSPs Song et al. (2005)')
plt.xlim(0,10)
plt.legend()
plt.subplot(212)
plt.hist(PSPsI[PSPsI<=10], 100, density=True, align='mid', label='EPSPs in CorI')
plt.plot(x,lognormalPDF(x), label='EPSPs Song et al. (2005)')
plt.xlim(0,10)
plt.legend()
plt.savefig('../results/get_weightDist/get_weightDist_PSP_dist.svg')

### COMPARISON COMBINED PSP DISTRIBUTION SIMULATION (E+I) VS EXPERIMENTAL

## COMBINE PSP DISTRIBUTIONS OF E AND I
PSP_dist = np.concatenate([PSPsE, PSPsI])

### OBTAIN FITTED LOG NORMAL DISTRIBUTION
fit = get_log_normal_fit(PSP_dist)

## PLOT
plt.figure()
plt.hist(PSP_dist[PSP_dist<=10], 100, density=True, align='mid', color='grey', alpha=0.5)
plt.plot(x,lognormalPDF(x), label='Song et al. (2005)', color='k')
plt.plot(x, lognormalPDF(x, mu=fit[0], sigma=fit[1], shift=fit[2]), label='Model', color='red', ls='dashed')
plt.legend(fontsize=8)
set_size(5.93/2.54,2.44/2.54)
plt.savefig('../results/get_weightDist/get_weightDist_combined_PSP_dist.svg')


taka="Takahashi"
aoki="Aoki"
sosu=[True]*201

a,b,c,d=map(int,input().split())

for i in range(201):
    j=2
    while j**2<=i:
        if i%j==0:
            sosu[i]=False
            break
        j+=1

ans=aoki
for i in range(a,b+1):
    not_sosu=True
    for j in range(c,d+1):
        if sosu[i+j]==True:
            not_sosu=False
            break
    if not_sosu:
        ans=taka

print(ans)


import cv2
import numpy as np

# Comment: CV2 is based on static image analysis.
#   But videos are just a collection of several static images. So it works pretty similar with video or image

# Using grayscale takes away different colors (3, being RGB) and +1 being Alpha (opacity)
#   it requires less processing using just grayscale

# img = cv2.imread('wristwatch.jpeg', cv2.IMREAD_GRAYSCALE)
img = cv2.imread('wristwatch.jpeg', cv2.IMREAD_COLOR)

cv2.line(img, (0,0), (150,150), (255,255,255), 15) #xy0 , xy1 , color BGR, linewidth
cv2.rectangle(img, (15,25), (200,150), (0,0,0), 10)
cv2.circle(img, (100,63), 55, (0,0,255), 10) # center, radius, color, linewidth = -1 => fill

font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img, 'OpenCV Tutorial', (0,130), font, 1, (200,200,130), 2, cv2.LINE_AA)
# IMREAD_COLOR = 1
# IMREAD_UNCHANGED = -1
# IMREAD_GRAYSCALE = 0

### Plotting with OpenCV
cv2.imshow('image', img)
cv2.waitKey(0) # any key closes the window
cv2.destroyAllWindows()

# cv2.imwrite('filename.png', img) # Saves the image


## Preamble
"""
# Program: ChimeraX_AtomFinder.py
# Version: 0.0.1
# Author: Jonathan Myers
# Date Created: Fri Aug  5 13:45:53 2022
# Date Modified: Aug 8 2022
# Purpose:
# Imports:
# Inputs/Arguments:
# Outputs/Returns:
"""

## Articles

from chimerax.atomic import all_atomic_structures
import numpy as np

# Import Structures And Get Atoms And Coordinates
structures = all_atomic_structures(session)
atoms = structures[0].atoms
coords = atoms.scene_coords

# Find Alpha Carbons
RTracker = []
for i in range (len(atoms)):
    residue = str(atoms[i]).split()
    if residue[3] == "CA":
        # (Residue Number,Index Number)
        tracker = (int(residue[2]),i)
        RTracker.append(tracker)
RArray = np.array(RTracker)

# Save Data Files
np.savetxt('/home/jmyers/Documents/FHV_Crown/Structure/PISA/AtomCoordinates.csv',coords,delimiter=',')
np.savetxt('/home/jmyers/Documents/FHV_Crown/Structure/PISA/AlphaCarbonMeta.csv',RArray,fmt='%i',delimiter=',')

# Code Executed
print("Code Executed")

# M02 End Program


import re
import pandas as pd
import draughts
from draughts import *
from draughts.PDN import PDNReader, _PDNGame
import numpy as np
import torch
from torch import Tensor
import torch.nn as nn
import torch.nn.functional as F
import torchvision
import torch.utils.data
from torch.utils.data import *
import pickle

filepath = "/Users/benakkermans/Downloads/CheckersDB.txt"
#reader = PDNReader(filepath)
#print(reader.games[0].moves)

def PDN_parse(filepath):
    """
    Parse text at given filepath
    Pasres a PDN FIle as .txt into games

    Parameters
    ----------
    filepath : str
        Filepath for file to be parsed

    Returns
    -------
    data : pd.DataFrame
        Parsed data

    """
    re_startmove = "^1."
    re_movesplit = " "
    terminate_list = ['1-0','0-1','1/2-1/2']

    data = []
    with open(filepath, 'r') as file:
        # Flags to indicate where in the file structure we are
        movesflag = False
        validflag = True
        ## MOVE LIST FOR EACH GAME
        movelist = []
        game_result = ''

        lines = file.readlines()

        for line in lines:
            if re.search(re_startmove,line):
                # Change flag to indicate it is a move line
                movesflag = True

            # Parse line of moves
            if movesflag:
                moves = re.split(re_movesplit, line)

                for move in moves:
                    move = move.strip("\n")
                    ## COmment in game, just scrap as there is very few
                    if '{' in move:
                        validflag = False

                    # Check if ending condition
                    if move in terminate_list:
                        if move == '1-0':
                            game_result = 1
                        elif move == '0-1':
                            game_result = -1
                        else:
                            game_result = 0

                        movesflag = False
                        if validflag:
                            data.append((movelist,game_result))
                        movelist = []
                        validflag = True

                    elif re.search("\.",move) == None:
                        movelist.append(move)

    return data

def get_BoardState(moveslist, game_result=0):
    ## Pieces denoted in the board as follows
    ## -3: White K, -1: White Piece, 0: No Piece, 1: Black Piece, 3: Black King
    ## Function currently starts with Black at Square 1 (Index 0)
    ## Game result denoted as follows:
        # 0 = Draw
        # 1 = Player-to-move Wins
        #-1 = Opposing Player Wins
    ## The game result attached to the output will flip considering who is at move(flip flag integration)
    ###############################################################################
    # Index to Move Dict:
    index_dict = {1:[0,0],2:[0,1],3:[0,2],4:[0,3],
                  5:[1,0],6:[1,1],7:[1,2],8:[1,3],
                  9:[2,0],10:[2,1],11:[2,2],12:[2,3],
                  13:[3,0],14:[3,1],15:[3,2],16:[3,3],
                  17:[4,0],18:[4,1],19:[4,2],20:[4,3],
                  21:[5,0],22:[5,1],23:[5,2],24:[5,3],
                  25:[6,0],26:[6,1],27:[6,2],28:[6,3],
                  29:[7,0],30:[7,1],31:[7,2],32:[7,3]}

    # Board Initialzied to starting position of the board
    board = np.array([[1,1,1,1],
                      [1,1,1,1],
                      [1,1,1,1],
                      [0,0,0,0],
                      [0,0,0,0],
                      [-1,-1,-1,-1],
                      [-1,-1,-1,-1],
                      [-1,-1,-1,-1]])

    cols = ['num_moves','board_state','next_move']
    #master_list = pd.DataFrame(columns=cols)
    master_list = []
    num_moves = 0
    ## Flip the board if it is Black's move (Board currently set so player-to-move is at the bottom)
    flip_flag = False

    ## Next define the changes made to the board by each type of move
    for strmove in moveslist:
        # Breakdown the move first
        ## Basic Move
        if re.search("-",strmove) != None:
            ## Simple as we know there are only two moves, no capture so straight update
            move = strmove.split("-")
            start_id = index_dict[int(move[0])]
            end_id = index_dict[int(move[1])]
            piece = board[start_id[0],start_id[1]]

            ## Execute the Update using above info on the move
            board[start_id[0],start_id[1]] = 0
            ## KING CHECK
            if piece == 1 and end_id[0] == 7:
                board[end_id[0],end_id[1]] = 3
            elif piece == -1 and end_id[0] == 0:
                board[end_id[0],end_id[1]] = -3
            else:
                board[end_id[0],end_id[1]] = piece

        ## Capture Move / Jump --> x-number of jumps in the move
        else:
            move = strmove.split("x")
            x = len(move)
            start_id = index_dict[int(move[0])]

            visited_squares = []
            for i in range(x-1):
                idx = index_dict[int(move[i+1])]
                visited_squares.append(idx)

            #end_id = visited_squares[-1]
            piece = board[start_id[0],start_id[1]]

            ## Execute the Update using above info on the move
            board[start_id[0],start_id[1]] = 0

            current = start_id
            for target in visited_squares:
                ## First Check if current/target rows are EVEN or ODD
                ## A KING off of a jump can only occur in two scenarios ->
                ## [Odd-row moving down the board (5->7) BLACK King and Even-row moving up (2->0) WHITE King

                # EVEN ROW RULES
                if current[0] % 2 == 0:
                    if (current[0]<target[0] and current[1]>target[1]) or (current[0]>target[0] and current[1]>target[1]):
                        middle_row = (max([current[0],target[0]])) - 1
                        # Remove piece in middle row, starting column
                        board[middle_row,current[1]] = 0
                        ## KING CHECK (3 conditions: Last Jump, White Piece, Row=0), even row can only be a WHITE KING
                        if (visited_squares.index(target) == (len(visited_squares) - 1)) and (piece == -1) and (target[0] == 0):
                             board[target[0],target[1]] = -3
                        else:
                            board[target[0],target[1]] = piece

                        current = target

                    elif (current[0]<target[0] and current[1]<target[1]) or (current[0]>target[0] and current[1]<target[1]):
                        middle_row = (max([current[0],target[0]])) - 1
                        # Remove piece in middle row, target column
                        board[middle_row,target[1]] = 0
                        ## KING CHECK (3 conditions: Last Jump, White Piece, Row=0), even row can only be a WHITE KING
                        if (visited_squares.index(target) == (len(visited_squares) - 1)) and (piece == -1) and (target[0] == 0):
                             board[target[0],target[1]] = -3
                        else:
                            board[target[0],target[1]] = piece

                        current = target

                # ODD ROW RULES
                else:
                    if (current[0]<target[0] and current[1]>target[1]) or (current[0]>target[0] and current[1]>target[1]):
                        middle_row = (max([current[0],target[0]])) - 1
                        # Remove piece in middle row, starting column
                        board[middle_row,target[1]] = 0
                        ## KING CHECK (3 conditions: Last Jump, Black Piece, Row=7), odd row can only be a BLACK KING
                        if (visited_squares.index(target) == (len(visited_squares) - 1)) and (piece == 1) and (target[0] == 7):
                             board[target[0],target[1]] = 3
                        else:
                            board[target[0],target[1]] = piece

                        current = target

                    elif (current[0]<target[0] and current[1]<target[1]) or (current[0]>target[0] and current[1]<target[1]):
                        middle_row = (max([current[0],target[0]])) - 1
                        # Remove piece in middle row, target column
                        board[middle_row,current[1]] = 0
                        ## KING CHECK (3 conditions: Last Jump, Black Piece, Row=7), odd row can only be a BLACK KING
                        if (visited_squares.index(target) == (len(visited_squares) - 1)) and (piece == 1) and (target[0] == 7):
                             board[target[0],target[1]] = 3
                        else:
                            board[target[0],target[1]] = piece

                        current = target
        num_moves += 1
        ## Calculate whos move is next for the flip_flag
        if num_moves % 2 == 0:
            # Black's Turn
            flip_flag = True
        else:
            flip_flag = False

        ## Output with next move
        # Set board, flip if flip_flag
        c_board = board.copy()
        gc = game_result
        ## Black to move, game result fine
        if flip_flag:
            c_board = np.flip(c_board, axis=0)
            c_board = np.flip(c_board, axis=1)
            gc = game_result

        ## White to move, flip game result and pieces (white is standard negative, we want white positive)
        else:
            c_board *= -1
            gc = game_result*-1

        master_list.append((c_board,gc))

        #print("Move was: ",strmove)
        #print(board)

    return master_list, moveslist

def add_game_data(df,moves,games_master,labels_master):
    #game = np.array([])
    labels = []
    for z in df:
        board = z[0]
        label = z[1]
        #print(board)
        #b_tensor = torch.from_numpy(board.copy())
        #b_tensor = torch.flatten(b_tensor)
        board = board.flatten()
        #games_master = torch.cat((games_master,b_tensor),1)
        games_master = np.vstack([games_master,board])
        labels.append(label)
        #print(games_master)
        #print('\n')
    labels_master.append(labels)

    return games_master,labels_master

#games_master = torch.Tensor()
games_master = np.empty((0,32))
labels_master = []
data = PDN_parse(filepath)

i = 0
for game in data:
    i += 1
    print(i)
    df, moves = get_BoardState(game[0],game[1])
    games_master,labels_master = add_game_data(df,moves,games_master,labels_master)

games_master = torch.Tensor(games_master)

gamefile = open('boardDB','wb')
pickle.dump(games_master,gamefile)
gamefile.close()

labelfile = open('labelDB','wb')
pickle.dump(labels_master,labelfile)
labelfile.close()


from project.animal import Animal
from project.worker import Worker

class Zoo:
    def __init__(self, name: str, budget: int, animal_capacity: int, workers_capacity: int) -> None:
        self.name = name
        self.__budget = budget
        self.__animal_capacity = animal_capacity
        self.__workers_capacity = workers_capacity
        self.animals = []
        self.workers = []

    def add_animal(self, animal: Animal, price: int) -> str:
        if self.__budget > price and self.__animal_capacity > len(self.animals):
            self.__budget -= price
            self.animals.append(animal)
            return f"{animal.name} the {animal.__class__.__name__} added to the zoo"

        elif self.__animal_capacity > len(self.animals):
            return "Not enough budget"

        else:
            return "Not enough space for animal"

    def hire_worker(self, worker: Worker) -> str:
        if self.__workers_capacity > len(self.workers):
            self.workers.append(worker)
            return f"{worker.name} the {worker.__class__.__name__} hired successfully"

        else:
            return "Not enough space for worker"

    def fire_worker(self, worker_name: str) -> str:
        for worker in self.workers:
            if worker.name == worker_name:
                self.workers.remove(worker)
                return f"{worker_name} fired successfully"

        else:
            return f"There is no {worker_name} in the zoo"

    def pay_workers(self) -> str:
        required = sum([w.salary for w in self.workers])
        if self.__budget >= required:
            self.__budget -= required
            return f"You payed your workers. They are happy. Budget left: {self.__budget}"

        else:
            return "You have no budget to pay your workers. They are unhappy"

    def tend_animals(self) -> str:
        required = sum([a.money_for_care for a in self.animals])
        if self.__budget >= required:
            self.__budget -= required
            return f"You tended all the animals. They are happy. Budget left: {self.__budget}"

        else:
            return "You have no budget to tend the animals. They are unhappy."

    def profit(self, amount: int) -> None:
        self.__budget += amount

    def animals_status(self) -> str:
        lions = []
        tigers = []
        cheetahs = []

        for a in self.animals:
            if a.__class__.__name__ == "Lion":
                lions.append(f"{a}")
            elif a.__class__.__name__ == "Tiger":
                tigers.append(f"{a}")
            else:
                cheetahs.append(f"{a}")

        lions_c = len(lions)
        tigers_c = len(tigers)
        cheetahs_c = len(cheetahs)
        lions = "\n".join(lions)
        tigers = "\n".join(tigers)
        cheetahs = "\n".join(cheetahs)

        return f"You have {len(self.animals)} animals\n" \
               f"----- {lions_c} Lions:\n{lions}\n" \
               f"----- {tigers_c} Tigers:\n{tigers}\n" \
               f"----- {cheetahs_c} Cheetahs:\n{cheetahs}"

    def workers_status(self) -> str:
        keepers = []
        caretakers = []
        vets = []

        for w in self.workers:
            if w.__class__.__name__ == "Keeper":
                keepers.append(f"{w}")
            elif w.__class__.__name__ == "Caretaker":
                caretakers.append(f"{w}")
            else:
                vets.append(f"{w}")

        keepers_c = len(keepers)
        caretakers_c = len(caretakers)
        vets_c = len(vets)
        keepers = "\n".join(keepers)
        caretakers = "\n".join(caretakers)
        vets = "\n".join(vets)

        return f"You have {len(self.workers)} workers\n" \
               f"----- {keepers_c} Keepers:\n{keepers}\n" \
               f"----- {caretakers_c} Caretakers:\n{caretakers}\n" \
               f"----- {vets_c} Vets:\n{vets}"


from django.test import TestCase
from django.urls import reverse
from django.http import JsonResponse
import json

class GetSuggestedFriendsViewTest(TestCase):
    def test_get_suggested_friends(self):
        # test user_id
        user_id = 5

        # Loading JSON file with user data
        with open('friends/users.json', 'r') as json_file:
            data = json.load(json_file)

        # get request with user_id
        response = self.client.get(reverse('suggest-friends', args=[user_id]))

        # ok response?
        self.assertEqual(response.status_code, 200)

        # contains json?
        self.assertIsInstance(response, JsonResponse)

        # response contains the user_data, user_id, and suggested_friends keys ?
        content = json.loads(response.content)
        self.assertIn('user_data', content)
        self.assertIn('user_id', content)
        self.assertIn('suggested_friends', content)

        # maximum 5 friends?
        suggested_friends = content['suggested_friends']
        self.assertTrue(len(suggested_friends) <= 5)


# Cow Beauty Pageant
# Gold 5, BFS, DFS

from collections import deque
import sys
input = sys.stdin.readline
M = 5931
sys.setrecursionlimit(M)

def dfs(x,y):
    grid[x][y] = k
    for nx,ny in ((x+1,y),(x-1,y),(x,y+1),(x,y-1)):
        if 0 <= nx < n and 0 <= ny < m and grid[nx][ny] == 'X':
            dfs(nx,ny)

def bfs(i,j):
    q = deque([(i,j)])
    visit = [[-2]*m for _ in range(n)]
    visit[i][j] += 1
    while q:
        x,y = q.popleft()
        if grid[i][j]*grid[x][y] < 0:
            return visit[x][y]
        for nx,ny in ((x+1,y),(x-1,y),(x,y+1),(x,y-1)):
            if 0 <= nx < n and 0 <= ny < m and grid[nx][ny] != grid[i][j] and visit[nx][ny] == -2:
                q.append((nx,ny))
                visit[nx][ny] = visit[x][y]+1
    return M

n,m = map(int,input().split())
grid = [list(input()) for _ in range(n)]

k = -1
for i in range(n):
    for j in range(m):
        if grid[i][j] == 'X':
            dfs(i,j)
            k = 1
        elif grid[i][j] == '.':
            grid[i][j] = 0

result = M
for i in range(n):
    for j in range(m):
        if grid[i][j] != 0:
            result = min(result,bfs(i,j))
print(result)


from numpy import *

import operator

def create_data_set():
    group = array([[1.0,1.1],
    [1.0,1.0],[0,0],[0,0.1]])
    labels = ['A', 'A', 'B', 'B']
    return group, labels

def classify0(inX, data_set, labels, k):
    data_set_size = data_set.shape[0]
    diff_max = tile(inX, (data_set_size, 1)) - data_set
    sq_diff_max = diff_max**2
    sq_distances = sq_diff_max.sum(axis=1)
    distances = sq_distances**0.5
    sorted_dist_indicies = distances.argsort()
    class_count = {}
    for i in range(k):
        vote_I_label = labels[sorted_dist_indicies[i]]
        class_count[vote_I_label] = class_count.get(vote_I_label, 0) + 1
        sorted_class_count = sorted(class_count.items(), key=operator.itemgetter(1), reverse=True)
        return sorted_class_count[0][0]


from typing import *

def peakIndexInMountainArray(arr: List[int]) -> int:
    n = len(arr)
    lo = 0
    hi = n - 1

    while lo <= hi:
        m = lo + ((hi - lo) // 2)

        if m > 0 and m < n - 1 and arr[m - 1] < arr[m] and arr[m] > arr[m + 1]:
            return m

        if arr[m] < arr[m+1]:
            lo = m + 1

        elif arr[m] > arr[m+1]:
            hi = m - 1

arr = [24,69,100,99,79,78,67,36,26,19]
ans = peakIndexInMountainArray(arr)
print(ans)