from typing import List

from dask.distributed import Client, SSHCluster
from dask import delayed
import distributed

scheduler_host_pinac22 = 'pinac22'
worker_hosts = [
    # 'pinac22',
    # 'pinac32',
    'pinac33',
    'pinac34',
    'pinac35',
    'pinac36',
    'pinac37',
    'pinac38'
    'pinac39'

]

# scheduler_host = 'pinac40'
# worker_hosts = [
#     'pinac22',
#     'pinac23',
#     'pinac25',
#     'pinac26',
#     'pinac28',
#     'pinac30',
#     'pinac-a',
#     'pinac-b',
# ]

scheduler_host_pinac27 = 'pinac27'
worker_hosts_himecs = [
#     #
#     #     # 'pinac22',
#     #     # 'pinac23',
#     #     # 'pinac24',
#     #     # 'pinac25',
#     #     # 'pinac26',
#     #     # 'pinac27',
#     #     # 'pinac28',
#     #     # 'pinac29',
#     #     # 'pinac30',
#     #     # 'pinac32',
#     #     # 'pinac33',
#     #     # 'pinac34',
#     #     # 'pinac35',
#     #     # 'pinac36',
#     #     # 'pinac37',
#     #     # 'pinac38',
#     #     # 'pinac39',
#     #     # 'pinac40',
    'himec01',
    'himec02',
    # 'himec03',
    # 'himec04',
#     #     # 'pinac-a',
#     #     # 'pinac-b',
#     #     # 'pinac-c',
#     #     # 'pinac-d',
]

# scheduler_host = 'pinac27'
worker_hosts_all = [

    'pinac22',
    'pinac23',
    'pinac24',
    'pinac25',
    'pinac26',
    'pinac27',
    'pinac28',
    'pinac29',
    'pinac30',
    'pinac32',
    'pinac33',
    'pinac34',
    'pinac35',
    'pinac36',
    'pinac37',
    'pinac38',
    'pinac39',
    'pinac40',
    'himec01',
    'himec02',
    'himec03',
    'himec04',
    'pinac-a',
    'pinac-b',
    'pinac-c',
    'pinac-d',
]

def initialize_client_for_ssh_cluster(
        scheduler_host: str,
        worker_hosts: List[str]
) -> Client:
    ssh_hosts = [scheduler_host, *worker_hosts]
    try:
        cluster = SSHCluster(
            hosts=ssh_hosts,
            connect_options={"known_hosts": None},
            worker_options={"nthreads": 1},
            # scheduler_options={"port": 0, "dashboard_address": ":8787"}
        )
        client = Client(cluster)
    except (KeyError, OSError):
        scheduler_address = f'{scheduler_host}:8786'
        client = Client(address=scheduler_address)

    return client

def reconnect_client_to_ssh_cluster(scheduler_host: str) -> Client:
    scheduler_address = f'{scheduler_host}:8786'
    client = Client(address=scheduler_address)

    return client


# leetcode-303-区域和检索-数组不可变.py
# 给定一个整数数组  nums，求出数组从索引 i 到 j  (i ≤ j) 范围内元素的总和，包含 i,  j 两点。

# 示例：

# 给定 nums = [-2, 0, 3, -5, 2, -1]，求和函数为 sumRange()

# sumRange(0, 2) -> 1
# sumRange(2, 5) -> -1
# sumRange(0, 5) -> -3
# 说明:

# 你可以假设数组不可变。
# 会多次调用 sumRange 方法。

"""
思路:
和数组

list index!!!!!!!!!!!!!!!!!! relations!!!!!!!!!!!!!!!!!!!!!!!!!!

"""

class NumArray(object):

    def __init__(self, nums):
        """
        :type nums: List[int]
        """
        self.sums = [0]
        l = len(nums)

        i = 0
        while i<l:
            self.sums.append(self.sums[i]+nums[i])
            i += 1

    def sumRange(self, i, j):
        """
        :type i: int
        :type j: int
        :rtype: int
        """

        return self.sums[j+1] - self.sums[i]

# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# param_1 = obj.sumRange(i,j)


#!/usr/bin/env python

import rospy
import numpy as np
from ackermann_msgs.msg import AckermannDriveStamped, AckermannDrive
from std_msgs.msg import Bool, Float32

class Safety(object):

	def __init__(self):

		self.TTCSub = rospy.Subscriber("TTC", Float32, self.TTC_callback)
		self.brakePub = rospy.Publisher("brake", AckermannDriveStamped, queue_size = 10)
		self.brakeBoolPub = rospy.Publisher("brake_bool", Bool, queue_size = 10)

	def TTC_callback(self, TTC_msg):

		TTCThreshold = 4
		TTC = TTC_msg.data

		if TTC < TTCThreshold:
			brake_bool = True
			self.brakeBoolPub.publish(brake_bool)
			ackMsg = AckermannDriveStamped()
			ackMsg.drive.speed = 0
			self.brakePub.publish(ackMsg)
		else:
			brake_bool = False
			self.brakeBoolPub.publish(brake_bool)

def main():
	rospy.init_node('safety_node')
	rospy.Rate(1000)
	sn = Safety()
	rospy.spin()
if __name__ == '__main__':
	main()


UNDER_TWENTY = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven",
    "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen",
    "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"]
TENS = ["Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]
MULTIPLIERS = ["Thousand", "Million", "Billion", "Trillion"]
MULTIPLIER_PARTITION_SIZE = 3

class Solution:
    def numberToWords(self, num):
        """
        :type num: int
        :rtype: str
        """
        if num == 0:
            return "Zero"

        words = []
        digits = count_digits(num)
        pivot = digits % MULTIPLIER_PARTITION_SIZE
        position = digits - pivot
        partitioned_num = num // 10 ** position
        while position >= 0:
            if partitioned_num:
                modulate_number(partitioned_num, words)
                if position >= 3:
                    words.append(MULTIPLIERS[(position // 3) - 1])
            num -= partitioned_num * 10 ** position
            position -= MULTIPLIER_PARTITION_SIZE
            partitioned_num = num // 10 ** position

        print(words)

def modulate_number(num, words):
    if num < 20:
        words.append(UNDER_TWENTY[num])
    elif num < 100:
        words.append(TENS[(num // 10) - 2])
        words.append(UNDER_TWENTY[num % 10])
    elif num < 1000:
        words.append(UNDER_TWENTY[num // 100])
        words.append("Hundred")
        modulate_number(num % 100, words)

def count_digits(num):
    count = 0
    while num:
        num //= 10
        count += 1
    return count

def test():
    s = Solution()
    s.numberToWords(1210543)
    s.numberToWords(12345)
    s.numberToWords(1234567891)
    s.numberToWords(123)

test()


def main():
	userGrade = Grading.getGrade()
	Grading.checkGrade(userGrade)

class Grading:
	def getGrade():

		print ("Please type in your score from 0-100.")
		''' Store user input as an integer '''
		userGrade = int(input())
		''' Would like to get rid of this if possible. Currently necessary to get input to checkGrade function. '''
		return userGrade

	def checkGrade(userGrade):

		if userGrade == int(100):
			print("Congrats, you got a perfect score! A+!!")
		elif 90 <= userGrade <= 99:
			print("Woohoo! You got an A!")
		elif 80 <= userGrade <= 89:
			print("Nice, you got a B!")
		elif 70 <= userGrade <= 79:
			print("You passed with a C!")
		elif 60 <= userGrade <= 69:
			print("You got a D... you may want to study more!")
		else:
			print("You got quite a low score, tutoring is a fantastic option!")
main()


Correct = 0
InCorrect = 0

def Question(Q = "",A1 = "", A2 = "", A3 = "", CA = 0):
    print(f"{Q}\n")
    print(f"А) {A1}")
    print(f"Б) {A2}")
    print(f"В) {A3}\n")
    CAStr = ""
    AL = ""
    Answer = input("Ответ: ")
    if(CA == 1):
        CAStr = A1
        AL = "а"
    elif(CA == 2):
        CAStr = A2
        AL = "б"
    elif (CA == 3):
        CAStr = A3
        AL = "в"
    if Answer.lower() == (CAStr.lower()) or Answer.lower() == (AL):
        print("\nПравильно\n")
        global Correct
        Correct += 1
    else:
        print("\nНе Правильно\n")
        global InCorrect
        InCorrect += 1

Question("QQQ","Q","QQ","QQQ",2)
'''
print("Кто Ты")
print("А) Собака")
print("Б) Человек ")
print("В) Еда")
Answer = input("Ответ: ")
if Answer.lower() == ("человек") or Answer.lower() == ("б"):
    print("Правильно")
    Correct += 1
else:
    print("Не Правильно")
    InCorrect += 1
print("Какая Столица Сингапура")
print("А) Сингапур")
print("Б) Киев")
print("В) Вена")
Answer = input("Ответ: ")
if Answer.lower() == ("сингапур") or Answer.lower() == ("а"):
    print("Правильно")
    Correct += 1
else:
    print("Не Правильно")
    InCorrect += 1
print("Где Находится Река Днепр")
print("А) Австрия")
print("Б) Турция")
print("В) Украина")
Answer = input("Ответ: ")
if Answer.lower() == ("украина") or Answer.lower() == ("в"):
    print("Правильно")
    Correct += 1
else:
    print("Не Правильно")
    InCorrect += 1
print("Где Купить Слона")
print("А) OLX")
print("Б) AlieExpress")
print("В) Amazon")
Answer = input("Ответ: ")
if Answer.lower() == ("olx") or Answer.lower() == ("а"):
    print("Правильно")
    Correct += 1
else:
    print("Не Правильно")
    InCorrect += 1

print(f"\nПравильно: {Correct}\n")
print(f"Не Правильно: {InCorrect}")
'''


import pandas as pd
from gensim.models.keyedvectors import KeyedVectors
from gensim.models import Word2Vec
import numpy as np
import matplotlib.pyplot as plt
import spacy
import unidecode
from word2number import w2n
import contractions
from bs4 import BeautifulSoup
from tqdm import tqdm
import gensim
from gensim import corpora
from pprint import pprint
from gensim.utils import simple_preprocess
from gensim.models import Word2Vec
from gensim.models.keyedvectors import KeyedVectors
from nltk.stem import PorterStemmer
from sklearn.feature_extraction.text import TfidfVectorizer
from statistics import mean
from vectorizer import getWeight

def strip_html_tags(text):
    """remove html tags from text"""
    soup = BeautifulSoup(text, "html.parser")
    stripped_text = soup.get_text(separator=" ")
    return stripped_text

def remove_whitespace(text):
    """remove extra whitespaces from text"""
    text = text.strip()
    return " ".join(text.split())

def remove_accented_chars(text):
    """remove accented characters from text, e.g. café"""
    text = unidecode.unidecode(text)
    return text

def expand_contractions(text):
    """expand shortened words, e.g. don't to do not"""
    text = contractions.fix(text)
    return text

def text_preprocessing(text, accented_chars=True, contractions=True,
                       convert_num=True, extra_whitespace=True,
                       lemmatization=True, lowercase=True, punctuations=True,
                       remove_html=True, remove_num=True, special_chars=True,
                       stop_words=True):
    """preprocess text with default option set to true for all steps"""
    if remove_html == True: #remove html tags
        text = strip_html_tags(text)
    if extra_whitespace == True: #remove extra whitespaces
        text = remove_whitespace(text)
    if accented_chars == True: #remove accented characters
        text = remove_accented_chars(text)
    if contractions == True: #expand contractions
        text = expand_contractions(text)
    if lowercase == True: #convert all characters to lowercase
        text = text.lower()

    doc = nlp(text) #tokenise text

    clean_text = []

    for token in doc:
        flag = True
        edit = token.text
        # remove stop words
        if stop_words == True and token.is_stop and token.pos_ != 'NUM':
            flag = False
        # remove punctuations
        if punctuations == True and token.pos_ == 'PUNCT' and flag == True:
            flag = False
        # remove special characters
        if special_chars == True and token.pos_ == 'SYM' and flag == True:
            flag = False
        # remove numbers
        if remove_num == True and (token.pos_ == 'NUM' or token.text.isnumeric()) \
        and flag == True:
            flag = False
        # convert number words to numeric numbers
        if convert_num == True and token.pos_ == 'NUM' and flag == True:
            edit = w2n.word_to_num(token.text)
        # convert tokens to base form
        elif lemmatization == True and token.lemma_ != "-PRON-" and flag == True:
            edit = token.lemma_
        # append tokens edited and not removed to list
        if edit != "" and flag == True:
            clean_text.append(edit)

    return clean_text

def toNum(value):
  value = value.replace(",", "")
  value = value.replace("$", "")
  return int(value)

def binning(value):
  if value < 1000:
    return np.round(value , -2)

  elif value < 10000:
    return np.round(value, -3)

  else:
    return np.round(value, -4)

def main():
  model = KeyedVectors.load_word2vec_format('data/GoogleNews-vectors-negative300.bin.gz', binary=True)

  df = pd.read_csv("data/JEOPARDY_CSV.csv")
  df = df[df[' Value'] != 'None']

  #making a new column of value without "$" and ","

  df['ValueNum'] = df[' Value'].apply(
  toNum
  )

#too many classes lets bin it

  df['ValueBins'] = df['ValueNum'].apply(binning)

  df.drop([" Value", "ValueNum"], axis=1, inplace = True)

  features = list(df.columns.values)

  classLabels = df['ValueBins'].unique()
  ans = df['ValueBins']
  features = list(df.columns.values)

  y = []

  Questions = []
  X = []

  with open('data/listfile.txt', 'r') as filehandle:
    for line in filehandle:
        # remove linebreak which is the last character of the string
        currentQuestion = line[:-1]

        # add item to the list
        Questions.append(currentQuestion)

  weights = np.array(getWeight())

  for sen in tqdm(Questions):
    vector = []
    for word in sen:
        try:
            vector.append((model[word]))
        except Exception:
            vector.append(0)

    X.append(mean(vector))

  y = np.array(ans)
  X = np.array(X)
  X = np.nan_to_num(X)

  X = X*weights

  print(X.shape)
  print(y.shape)
  np.save("data/y.npy", y)
  np.save("data/X.npy", X)

if __name__ == "__main__":
        main()


# test that a change in unit cell boundary conditions is
# handled correctly by lammpslib
from __future__ import print_function
import os
from ase.calculators.lammpslib import LAMMPSlib
from ase.lattice.cubic import FaceCenteredCubic

potential_path = os.environ.get('LAMMPS_POTENTIALS_PATH', '.')
cmds = ["pair_style eam/alloy",
        "pair_coeff * * {path}/NiAlH_jea.eam.alloy Ni H"
        "".format(path=potential_path)]
lammps = LAMMPSlib(lmpcmds=cmds,
                   atom_types={'Ni': 1, 'H': 2},
                   log_file='test.log', keep_alive=True)
atoms = FaceCenteredCubic(size=(2,2,2), latticeconstant=3.52, symbol="Ni", pbc=True)
atoms.set_calculator(lammps)

energy_ppp_ref = -142.400000403
energy_ppp = atoms.get_potential_energy()
print("Computed energy with boundary ppp = {}".format(energy_ppp))
diff_ppp = abs((energy_ppp - energy_ppp_ref) / energy_ppp_ref)
assert diff_ppp < 1e-10, "Expected "+str(energy_ppp_ref)

atoms.set_pbc((False,False,True))
energy_ssp_ref = -114.524625705
energy_ssp = atoms.get_potential_energy()
print("Computed energy with boundary ssp = {}".format(energy_ssp))
diff_ssp = abs((energy_ssp - energy_ssp_ref) / energy_ssp_ref)
assert diff_ssp < 1e-10, "Expected "+str(energy_ssp_ref)


""" This file defines utilities for trajectory optimization. """
import abc
import logging

import numpy as np
import scipy as sp

LOGGER = logging.getLogger(__name__)

# Constants used in TrajOptLQR.
DGD_MAX_ITER = 50
DGD_MAX_LS_ITER = 20
DGD_MAX_GD_ITER = 200

ALPHA, BETA1, BETA2, EPS = 0.005, 0.9, 0.999, 1e-8  # Adam parameters

def traj_distr_kl(new_mu, new_sigma, new_traj_distr, prev_traj_distr, tot=True):
    """
    Compute KL divergence between new and previous trajectory
    distributions.
    Args:
        new_mu: T x dX, mean of new trajectory distribution.
        new_sigma: T x dX x dX, variance of new trajectory distribution.
        new_traj_distr: A linear Gaussian policy object, new
            distribution.
        prev_traj_distr: A linear Gaussian policy object, previous
            distribution.
        tot: Whether or not to sum KL across all time steps.
    Returns:
        kl_div: The KL divergence between the new and previous
            trajectories.
    """
    # Constants.
    T = new_mu.shape[0]
    dU = new_traj_distr.dU

    # Initialize vector of divergences for each time step.
    kl_div = np.zeros(T)

    # Step through trajectory.
    for t in range(T):
        # Fetch matrices and vectors from trajectory distributions.
        mu_t = new_mu[t, :]
        sigma_t = new_sigma[t, :, :]
        K_prev = prev_traj_distr.K[t, :, :]
        K_new = new_traj_distr.K[t, :, :]
        k_prev = prev_traj_distr.k[t, :]
        k_new = new_traj_distr.k[t, :]
        chol_prev = prev_traj_distr.chol_pol_covar[t, :, :]
        chol_new = new_traj_distr.chol_pol_covar[t, :, :]

        # Compute log determinants and precision matrices.
        logdet_prev = 2 * sum(np.log(np.diag(chol_prev)))
        logdet_new = 2 * sum(np.log(np.diag(chol_new)))
        prc_prev = sp.linalg.solve_triangular(
            chol_prev, sp.linalg.solve_triangular(chol_prev.T, np.eye(dU),
                                                  lower=True)
        )
        prc_new = sp.linalg.solve_triangular(
            chol_new, sp.linalg.solve_triangular(chol_new.T, np.eye(dU),
                                                 lower=True)
        )

        # Construct matrix, vector, and constants.
        M_prev = np.r_[
            np.c_[K_prev.T.dot(prc_prev).dot(K_prev), -K_prev.T.dot(prc_prev)],
            np.c_[-prc_prev.dot(K_prev), prc_prev]
        ]
        M_new = np.r_[
            np.c_[K_new.T.dot(prc_new).dot(K_new), -K_new.T.dot(prc_new)],
            np.c_[-prc_new.dot(K_new), prc_new]
        ]
        v_prev = np.r_[K_prev.T.dot(prc_prev).dot(k_prev),
                       -prc_prev.dot(k_prev)]
        v_new = np.r_[K_new.T.dot(prc_new).dot(k_new), -prc_new.dot(k_new)]
        c_prev = 0.5 * k_prev.T.dot(prc_prev).dot(k_prev)
        c_new = 0.5 * k_new.T.dot(prc_new).dot(k_new)

        # Compute KL divergence at timestep t.
        kl_div[t] = max(
            0,
            -0.5 * mu_t.T.dot(M_new - M_prev).dot(mu_t) -
            mu_t.T.dot(v_new - v_prev) - c_new + c_prev -
            0.5 * np.sum(sigma_t * (M_new-M_prev)) - 0.5 * logdet_new +
            0.5 * logdet_prev
        )

    # Add up divergences across time to get total divergence.
    return np.sum(kl_div) if tot else kl_div

def traj_distr_kl_alt(new_mu, new_sigma, new_traj_distr, prev_traj_distr, tot=True):
    """
    This function computes the same quantity as the function above.
    However, it is easier to modify and understand this function, i.e.,
    passing in a different mu and sigma to this function will behave properly.
    """
    T, dX, dU = new_mu.shape[0], new_traj_distr.dX, new_traj_distr.dU
    kl_div = np.zeros(T)

    for t in range(T):
        K_prev = prev_traj_distr.K[t, :, :]
        K_new = new_traj_distr.K[t, :, :]

        k_prev = prev_traj_distr.k[t, :]
        k_new = new_traj_distr.k[t, :]

        sig_prev = prev_traj_distr.pol_covar[t, :, :]
        sig_new = new_traj_distr.pol_covar[t, :, :]

        chol_prev = prev_traj_distr.chol_pol_covar[t, :, :]
        chol_new = new_traj_distr.chol_pol_covar[t, :, :]

        inv_prev = prev_traj_distr.inv_pol_covar[t, :, :]
        inv_new = new_traj_distr.inv_pol_covar[t, :, :]

        logdet_prev = 2 * sum(np.log(np.diag(chol_prev)))
        logdet_new = 2 * sum(np.log(np.diag(chol_new)))

        K_diff, k_diff = K_prev - K_new, k_prev - k_new
        mu, sigma = new_mu[t, :dX], new_sigma[t, :dX, :dX]

        kl_div[t] = max(
                0,
                0.5 * (logdet_prev - logdet_new - new_traj_distr.dU +
                       np.sum(np.diag(inv_prev.dot(sig_new))) +
                       k_diff.T.dot(inv_prev).dot(k_diff) +
                       mu.T.dot(K_diff.T).dot(inv_prev).dot(K_diff).dot(mu) +
                       np.sum(np.diag(K_diff.T.dot(inv_prev).dot(K_diff).dot(sigma))) +
                       2 * k_diff.T.dot(inv_prev).dot(K_diff).dot(mu))
        )

    return np.sum(kl_div) if tot else kl_div

def approximated_cost(sample_list, traj_distr, traj_info):
    """
    This function gives the LQR estimate of the cost function given the noise
    experienced along each sample in sample_list.
    Args:
        sample_list: List of samples to extract noise from.
        traj_distr: LQR controller to roll forward.
        traj_info: Used to obtain dynamics estimate to simulate trajectories.
    Returns:
        mu_all: Trajectory means corresponding to each sample in sample_list.
        predicted_cost: LQR estimates of cost of each sample in sample_list.
    """
    T = traj_distr.T
    N = len(sample_list)
    dU = traj_distr.dU
    dX = traj_distr.dX
    noise = sample_list.get_noise()

    # Constants.
    idx_x = slice(dX)
    mu_all = np.zeros((N, T, dX+dU))

    # Pull out dynamics.
    Fm = traj_info.dynamics.Fm
    fv = traj_info.dynamics.fv
    dyn_covar = traj_info.dynamics.dyn_covar

    for i in range(N):
        mu = np.zeros((T, dX+dU))
        mu[0, idx_x] = traj_info.x0mu
        for t in range(T):
            mu[t, :] = np.hstack([
                mu[t, idx_x],
                (traj_distr.K[t, :, :].dot(mu[t, idx_x]) + traj_distr.k[t, :]
                 + traj_distr.chol_pol_covar[t].T.dot(noise[i, t]))
            ])
            if t < T - 1:
                mu[t+1, idx_x] = Fm[t, :, :].dot(mu[t, :]) + fv[t, :]
        mu_all[i, :, :] = mu

    # Compute cost.
    predicted_cost = np.zeros((N, T))

    for i in range(N):
        for t in range(T):
            predicted_cost[i, t] = traj_info.cc[t] + \
                    0.5 * mu_all[i,t,:].T.dot(traj_info.Cm[t, :, :]).dot(mu_all[i,t,:]) + \
                    mu_all[i,t,:].T.dot(traj_info.cv[t, :])

    return mu_all, predicted_cost


#Função de simulação de um automâto finito determinístico
########################################################################
def simular_dfa(dfa, entrada):
    estado = dfa['initial_state']
    aux = ''.join(entrada)
    aceitar = False
    while len(entrada) > 0:
        c = entrada.pop(0)

        if c not in dfa['sigma']:
            print("O símbolo",c,"não pertence ao alfabeto do autômato!")
            break
        elif(estado not in dfa['states']):
            print("O estado", estado,"não pertence ao conjunto de estados do autômato!")
            break

        try:
            estado = dfa['delta'][(estado,c)]
            print((estado,c), "->", dfa['delta'][(estado,c)])
        except KeyError:
            print("Não foi possível realizar a transição do estado", estado, "com entrada", c)
            break

    if(estado in dfa['final_states'] and len(entrada) == 0):
       aceitar = True

    if(aceitar == True):
       print("A cadeia", aux, "foi aceita pelo autômato!")
    else:
       print("A cadeia", aux, "foi rejeitada pelo autômato!")
########################################################################

while(True):
    #Programa Principal
    entrada = input("Digite a cadeia: ")
    entrada = list(entrada)
    with open('m.dfa.txt') as dfa_file:
            dfa_data = dfa_file.read()
    dfa = eval(dfa_data)
    #Para conferir o conteúdo
    #print(dfa)
    simular_dfa(dfa, entrada)


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

import cv2
import mediapipe as mp
import numpy as np
import sys

mp_drawing = mp.solutions.drawing_utils
mp_drawing_styles = mp.solutions.drawing_styles
mp_hands = mp.solutions.hands
mp_face_mesh = mp.solutions.face_mesh
face_mesh = mp_face_mesh.FaceMesh(min_detection_confidence=0.5, min_tracking_confidence=0.5)
cap = cv2.VideoCapture(0)

count = 0

while cap.isOpened():
    success, image = cap.read()
    count += 1

    # Flip the image horizontally for a later selfie-view display
    # Also convert the color space from BGR to RGB

    image = cv2.cvtColor(cv2.flip(image, 1), cv2.COLOR_BGR2RGB)
    scale_percent = 150 # percent of original size
    width = int(image.shape[1] * scale_percent / 100)
    height = int(image.shape[0] * scale_percent / 100)
    dim = (width, height)
    # resize image
    image = cv2.resize(image, dim, interpolation = cv2.INTER_AREA)
    with mp_hands.Hands(
        static_image_mode=True,
        max_num_hands=2,
        min_detection_confidence=0.5) as hands:
        results = hands.process(image)
    if results.multi_hand_landmarks:
        cv2.putText(image, "Recalibrating" , (30, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
        sys.stdout.flush()
        print("Recalibrating")
        #cv2.imshow('Head Pose Estimation', image)
    else:

        sys.stdout.flush()
        # To improve performance
        image.flags.writeable = False

        # Get the result
        results = face_mesh.process(image)

        # To improve performance
        image.flags.writeable = True

        img_h, img_w, img_c = image.shape
        face_3d = []
        face_2d = []

        if results.multi_face_landmarks:
            for face_landmarks in results.multi_face_landmarks:
                for idx, lm in enumerate(face_landmarks.landmark):
                    if idx == 33 or idx == 263 or idx == 1 or idx == 61 or idx == 291 or idx == 199:
                        if idx == 1:
                            nose_2d = (lm.x * img_w, lm.y * img_h)
                            nose_3d = (lm.x * img_w, lm.y * img_h, lm.z * 8000)

                        x, y = int(lm.x * img_w), int(lm.y * img_h)

                        # Get the 2D Coordinates
                        face_2d.append([x, y])

                        # Get the 3D Coordinates
                        face_3d.append([x, y, lm.z])

                # Convert it to the NumPy array
                face_2d = np.array(face_2d, dtype=np.float64)

                # Convert it to the NumPy array
                face_3d = np.array(face_3d, dtype=np.float64)

                # The camera matrix
                focal_length = 1 * img_w

                cam_matrix = np.array([ [focal_length, 0, img_h / 2],
                                        [0, focal_length, img_w / 2],
                                        [0, 0, 1]])

                # The Distance Matrix
                dist_matrix = np.zeros((4, 1), dtype=np.float64)

                # Solve PnP
                success, rot_vec, trans_vec = cv2.solvePnP(face_3d, face_2d, cam_matrix, dist_matrix)

                # Get rotational matrix
                rmat, jac = cv2.Rodrigues(rot_vec)
                noseEndPoints3D = np.array([[0, 0, 1000.0]], dtype=np.float64)
                noseEndPoint2D, jacobian = cv2.projectPoints(
                   noseEndPoints3D, rot_vec, trans_vec, cam_matrix, dist_matrix)

                #  draw nose line
                p1 = (int(nose_2d[0]), int(nose_2d[1]))
                p2 = (int(noseEndPoint2D[0, 0, 0]), int(noseEndPoint2D[0, 0, 1]))
                cv2.line(image, p1, p2, (110, 220, 0),
                        thickness=2, lineType=cv2.LINE_AA)

                # Get angles
                angles, mtxR, mtxQ, Qx, Qy, Qz = cv2.RQDecomp3x3(rmat)

                # Get the y rotation degree

                pitch = str(round(angles[0] * 360,0)-5)
                yaw = str(round(angles[1] * 360,0))

                #Add the text on the image
                cv2.putText(image, pitch +","+ yaw , (30, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
                print("entry," + yaw +","+ pitch)

    scale_percent = 30 # percent of original size
    width = int(image.shape[1] * scale_percent / 100)
    height = int(image.shape[0] * scale_percent / 100)
    dim = (width, height)
    # resize image

    image = cv2.resize(cv2.cvtColor(image, cv2.COLOR_RGB2BGR), dim, interpolation = cv2.INTER_AREA)
    cv2.imshow('Head Pose Estimation', image)

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


from setuptools import setup

__version__ = '3.2.1a'

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

extra_setuptools_args = dict(
    tests_require=['pytest'])

setup(
    name='meqc',
    version=__version__,
    description='Multi-echo independent components analysis of fMRI data.',
    maintainer='Prantik Kundu',
    maintainer_email='',
    install_requires=requirements,
    packages=['meqc'],
    license='MIT',
    **extra_setuptools_args)


#Exercício Python 035: Desenvolva um programa que leia o comprimento de três retas
# e diga ao usuário se elas podem ou não formar um triângulo.

a = float(input('Digite o primeiro segmento: '))
b = float(input('Digite o segundo segmento: '))
c = float(input('Digite o terceiro segmento: '))

if a < b + c and b < a + c and c < a + b:
    print('Os seguimentos acima pode formar triangulo')
else:
    print('Os seguimentos acima não formar triangulo:')


from flask import Flask, render_template, jsonify
import pandas as pd

app = Flask(__name__)
app.debug = True

@app.route('/')
def home():
    return render_template('index.html')

@app.route('/read-servers', methods=['GET'])
def readServer():
    # Lendo o arquivo CSV com pandas
    df = pd.read_csv("files/ServersLast24H.csv")

    # Convertendo o DataFrame para um dicionário
    data = df.to_dict(orient='records')

    # Enviando os dados como JSON
    return jsonify(data)

@app.route('/read-users', methods=['GET'])
def readUsers():
    # Lendo o arquivo CSV com pandas
    df = pd.read_csv("files/usuariosdash.csv")

    df = df.fillna(" ")
    # Convertendo o DataFrame para um dicionário
    data = df.to_dict(orient='records')

    # Enviando os dados como JSON
    return jsonify(data)

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


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

import configparser
import json
from collections import OrderedDict
import os

thisConfFileName = 'spydcmtk.conf'
rootDir = os.path.abspath(os.path.dirname(__file__))

# def group_items_to_list(config, default_items, groupName):
#     path_items = config.items( groupName )
#     myList = []
#     for __, tagName in path_items:
#         if tagName in default_items:
#             continue
#         if tagName not in myList: # Avoid doubles
#             myList.append(tagName)
#     return myList

config = configparser.ConfigParser(dict_type=OrderedDict)

all_config_files = [os.path.join(rootDir,thisConfFileName),
                    os.path.join(os.path.expanduser("~"),thisConfFileName),
                    os.path.join(os.path.expanduser("~"),'.'+thisConfFileName),
                    os.path.join(os.path.expanduser("~"), '.config',thisConfFileName),
                    os.environ.get("SPYDCMTK_CONF", '')]

config.read(all_config_files)

environment = config.get("app", "environment")
DEBUG = config.get("app", "debug")

# default_items = [vv for _,vv in config.items('DEFAULT')]

SERIES_OVERVIEW_TAG_LIST  = json.loads(config.get("series_overview_tags", "tagList"))
STUDY_OVERVIEW_TAG_LIST   = json.loads(config.get("study_overview_tags", "tagList"))
SUBJECT_OVERVIEW_TAG_LIST = json.loads(config.get("patient_overview_tags", "tagList"))
VTI_NAMING_TAG_LIST       = json.loads(config.get("vti_naming_tags", "tagList"))
# MANUSCRIPT_TABLE_TAG_LIST = json.loads(config.get("manuscript_table_tags","tagList"))


import time

import torch
import numpy as np
import transforms
from models import SSD300, Backbone
from PIL import Image
from torch2trt import torch2trt

def load_model(device, num_classes=20 + 1, checkpoint="../SSD/save_weights/ssd300-14.pth"):
    """
    加载SSD目标检测模型
    :return:
        SSD model
    """
    # create model
    # 目标检测数 + 背景
    model = create_model(num_classes=num_classes)

    # load train weights
    train_weights_dict = torch.load(checkpoint, map_location=device)['model']

    model.load_state_dict(train_weights_dict)
    model.to(device)
    model.eval()
    x = torch.ones((1, 3, 300, 300)).cuda()
    model_trt = torch2trt(model, [x])
    # with torch.no_grad():
    #     # initial model
    #     init_img = torch.zeros((1, 3, 300, 300), device=device)
    #     model(init_img)
    #
    return model_trt

def inference(model, tf, images_batches, category_index, threshold=0.5, device='cpu'):
    height, width = images_batches[0].shape[:2]
    imgs = []
    for img in images_batches:
        imgPIL = Image.fromarray(img)
        _img, _ = tf(imgPIL)
        imgs.append(_img)
    images = torch.stack(imgs, dim=0)

    with torch.no_grad():
        predictions = model(images.to(device))[0]  # bboxes_out, labels_out, scores_out
        predict_boxes = predictions[0].to("cpu").numpy()
        predict_boxes[:, [0, 2]] = predict_boxes[:, [0, 2]] * width
        predict_boxes[:, [1, 3]] = predict_boxes[:, [1, 3]] * height
        predict_classes = predictions[1].to("cpu").numpy()
        predict_scores = predictions[2].to("cpu").numpy()
        if len(predict_boxes) == 0:
            print("没有检测到任何目标!")
        filter_boxes = predict_boxes[predict_scores > threshold].astype(int)
        classes_str = [category_index[i] for i in predict_classes[predict_scores > threshold]]
    return filter_boxes, classes_str

def create_model(num_classes):
    backbone = Backbone()
    model = SSD300(backbone=backbone, num_classes=num_classes)

    return model

def time_synchronized():
    torch.cuda.synchronize() if torch.cuda.is_available() else None
    return time.time()

def get_data_transform():
    return transforms.Compose([transforms.Resize(),
                               transforms.ToTensor(),
                               transforms.Normalization()])


import tensorflow as tf
# 实现一个累加器，并且每一步均输出累加器的结果值
# 1、定一个变量
x = tf.Variable(1,dtype=tf.int32,name='v_x')
# 2、变量的更新assign， ref指定更新的变量名称
assign_op = tf.assign(ref=x,value= x+1)
# 变量初始化
x_init_op = tf.global_variables_initializer()

# 3、运行
with tf.Session(config=tf.ConfigProto(log_device_placement=True)) as sess:
    sess.run(x_init_op)
    for i in range(5):
        r_x = sess.run(x)
        print(r_x)
#         执行跟新操作
        sess.run(assign_op)

# 编写一段代码，实现动态的更新变量的维度数
# 1、定义一个不定形状的变量
x = tf.Variable(
    initial_value=[],#给定一个不固定的值
    dtype=tf.float32,
    trainable=False,#不把它加载缓存区（只有不定形状才是false）
    validate_shape= False#设置为True，表示在变量更新的时候，进行shape检查，默认为true
)

# 2、变量更改
contact = tf.constant([x,[0,0]],axis=0)
#实现一个求解阶乘的代码


from quantization import *
from pixels import get_pixel

class DifferentialEncoder:
    def __init__(self, original_sequence):
        self.original_sequence = original_sequence
        self.data_size = self.original_sequence.size
        self.data_type = type(self.original_sequence[0])

    def encode(self, quantizer_size):
        initial_differential_sequence = self.get_differential_sequence()
        quantization = Quantization(initial_differential_sequence)
        quantizer = quantization.create_nonuniform_quantizer(quantizer_size)
        differential_sequence = np.empty(self.data_size, dtype=self.data_type)
        differential_sequence[0] = self.original_sequence[0]
        quantized_idx_sequence = np.empty(self.data_size, dtype=np.uint8)
        quantized_idx_sequence[0] = best_fit_idx(quantizer, differential_sequence[0])
        encoded_sequence = np.empty(self.data_size, dtype=self.data_type)
        encoded_sequence[0] = quantizer[quantized_idx_sequence[0]]

        for i in range(1, self.data_size):
            differential_sequence[i] = self.original_sequence[i] - encoded_sequence[i - 1]
            quantized_idx_sequence[i] = best_fit_idx(quantizer, differential_sequence[i])
            encoded_sequence[i] = encoded_sequence[i - 1] + quantizer[quantized_idx_sequence[i]]

        return quantizer, quantized_idx_sequence

    def get_differential_sequence(self):
        return np.array([self.original_sequence[0]]
                        + [
                            self.original_sequence[i] - self.original_sequence[i-1]
                            for i in range(1, len(self.original_sequence))
                        ])

class DifferentialDecoder:
    def __init__(self, quantizer):
        self.quantizer = quantizer

    def decode(self, idx_sequence):
        decoded_sequence = np.empty(idx_sequence.shape, dtype=self.quantizer.dtype)
        decoded_sequence[0] = get_pixel(self.quantizer[idx_sequence[0]])

        for i in range(1, idx_sequence.size):
            decoded_sequence[i] = get_pixel(decoded_sequence[i - 1] + self.quantizer[idx_sequence[i]])

        return decoded_sequence


import unittest
from ds2.sorting.mergesort_iter import BufferedIterator

class TestBufferedIterator(unittest.TestCase):
    def testinit(self):
        BufferedIterator([1,2,3])
        BufferedIterator(iter({1,5}))
        BufferedIterator({})

    def testnext(self):
        B = BufferedIterator([1,2,3])
        self.assertEqual(next(B), 1)
        self.assertEqual(next(B), 2)
        self.assertEqual(next(B), 3)
        with self.assertRaises(StopIteration):
            next(B)

    def testiter(self):
        B = BufferedIterator([3,4,5])
        myiter = iter(B)
        self.assertEqual(list(myiter), [3,4,5])

    def testpeek(self):
        B = BufferedIterator([1,2,3])
        self.assertEqual(B.peek(), 1)
        next(B)
        self.assertEqual(B.peek(), 2)
        next(B)
        self.assertEqual(B.peek(), 3)

    def testhasnext(self):
        B = BufferedIterator([5,6])
        self.assertTrue(B.hasnext())
        next(B)
        self.assertTrue(B.hasnext())
        next(B)
        self.assertFalse(B.hasnext())

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


import requests,sys,bs4,webbrowser

#Making request to the server
print('Search in Progress.....')
res = requests.get('https://www.google.co.in/search?dcr=0&ei=vpCSWoLyK8bTvwTxgIiYDg&q=' + ' '.join(sys.argv[1:]))
res.raise_for_status()

#Get search results
soup = bs4.BeautifulSoup(res.text,"lxml")
print(soup.prettify())

#opens a tab for each result
elems = soup.select('.r a')
nOpen = min(2,len(elems))
for i in range(nOpen):
    webbrowser.open('https://google.com' + elems[i].get('href'))


#!/usr/bin/python
"""
Handles Arduino messages and publishes them to ROS topics
"""
import serial
import rospy
from std_msgs.msg import Float32
from anahita_msgs.msg import Thrust
from roslib.message import get_message_class

pwm_str = ""

def callback(msg):
    global pwm_str
    #rospy.loginfo("Here")
    pwm_str = str(msg.sideward_front) + ',' + str(msg.sideward_back) + ',' + \
                str(msg.forward_left) + ',' + str(msg.forward_right) + ',' + \
                str(msg.upward_north_east) + ',' + str(msg.upward_north_west) + ',' + \
                str(msg.upward_south_east) + ',' + str(msg.upward_south_west) + '\n'

if __name__ == '__main__':

    rospy.init_node('handle_arduino')

    rospy.Subscriber("/pwm", Thrust, callback)
    depth_publisher = rospy.Publisher("/anahita/depth", Float32, queue_size=10)
    bat_voltage_pub = rospy.Publisher("/anahita/battery_voltage", Float32, queue_size=10)

    serial_port_id = rospy.get_param("~serial_port_id", "/dev/ttyACM0")
    baud_rate = rospy.get_param("~baud_rate", 115200)

    depth_msg = Float32()
    bat_voltage_msg = Float32()

    # Initialize the serial connection
    try:
        serial_connection = serial.Serial("/dev/ttyACM0", 115200, timeout=5)
        rospy.sleep(2)

    except:
        rospy.logerr("Could not start serial_connection")
        exit()

    while not rospy.is_shutdown():

            rospy.loginfo('Inside the spin loop')
            serial_connection.flush()
            pwm_msg = pwm_str.encode('utf-8')
            serial_connection.write(pwm_msg)
            rospy.loginfo(pwm_str)
            rospy.sleep(0.067)

            # Serial read section
            msg = serial_connection.read(serial_connection.inWaiting()) # read all characters in buffer
            print(msg)
            rospy.logerr('Some error has occured')
            rospy.loginfo("Recieved: " + str(msg))
            try:
                data = list(map(float,[x.strip() for x in msg.split(',')]))
                print("Data:" + str(data))
                bat_voltage_msg.data = data[0]
                rospy.loginfo("Battery Voltage: " + str(bat_voltage_msg))
                depth_msg.data = data[1]
                rospy.loginfo("Depth: " + str(depth_msg))
                depth_publisher.publish(depth_msg)
                bat_voltage_pub.publish(bat_voltage_msg)
            except:
                rospy.loginfo("Error in incoming values")

    rospy.spin()
    serial_connection.close()


#Tendo como dado de entrada a altura (h) de uma pessoa, construa um algoritmo que calcule seu peso ideal,
# utilizando as seguintes fórmulas:
#Para homens: (72.7*h) - 58
#Para mulheres: (62.1*h) - 44.7
#-------------------------------------------------------------------------------------------------------------
sexo = input("digite M para masculino ou F para feminino: ")

#calculo masculino
if sexo == 'M' or sexo == 'm' :
   altura =  float(input("digite sua altura: "))
   mmc = float(( altura * 72.7) - 58.0)
   print("seu peso ideal é: %.3f" % mmc, "kg")

#calculo feminino
elif sexo == 'F' or sexo == 'f' :
   altura =  float( input("digite sua altura: "))
   mmc = float(( altura * 62.1) - 44.7)
   print("seu peso ideal é: %.3f" % mmc, "kg")

else :
    print("erro!!")


#!/usr/bin/env python3
# flake8: noqa
import argparse
from json import JSONDecodeError
from botocore.exceptions import ClientError

import boto3
import json
import logging
import os
import subprocess
import requests

import sys

logger = logging.getLogger()
ecs_client = boto3.client('ecs')
ecr_client = boto3.client('ecr')
webhook_url = os.environ.get('ECS_DEPLOYER_WEBHOOK_URL')

class DockerImage:
    def __init__(self, name, dockerfile, tagCommand, repository, build) -> None:
        self.name = name
        self.dockerfile = dockerfile
        self.tag_command = tagCommand
        self.repository = repository
        self.build = build

    @property
    def tag(self) -> str:
        try:
            return self._tag
        except AttributeError:
            self._tag = run_command(self.tag_command, shell=True).strip()
            return self._tag

    @property
    def tagged_name(self) -> str:
        return '{}:{}'.format(self.name, self.tag)

    @property
    def tagged_repo_name(self) -> str:
        return '{}:{}'.format(self.repository, self.tag)

    def build_image(self) -> None:
        run_command(['docker', 'build', '-t', self.tagged_name, '-f', self.dockerfile, '.'])
        run_command(['docker', 'tag', self.tagged_name, self.tagged_repo_name])

    def tag_image(self) -> None:
        run_command(['docker', 'tag', self.name, self.tagged_repo_name])

    def push(self) -> None:
        run_command(['docker', 'push', self.tagged_repo_name])

    def delete_local(self) -> None:
        run_command(['docker', 'rmi', self.tagged_name])

    def handle(self, keep_image, force_push_image) -> str:
        try:
            response = ecr_client.describe_images(repositoryName=self.repository.split('/')[1], imageIds=[{'imageTag': self.tag}])
            image_exists = len(response['imageDetails'])
        except ClientError:
            image_exists = False

        if not image_exists or force_push_image:
            if self.build:
                self.build_image()
            else:
                self.tag_image()
            self.push()

            if self.build and not keep_image:
                self.delete_local()
        else:
            print("Image {} exists, skipping.".format(self.tagged_repo_name))
        return self.tagged_repo_name

    def __str__(self) -> str:
        return "<Docker Image> - {}".format(self.name)

class TaskDefinition:
    def __init__(self, name, config) -> None:
        self.name = name
        self.config = config
        self.revision = None

    @property
    def deregister_previous_definitions(self) -> bool:
        return self.config.get('deregisterPreviousDefinitions', True)

    @property
    def family(self) -> str:
        return self.config['family']

    @property
    def task_role_arn(self) -> str:
        return self.config.get('taskRoleArn')

    @property
    def network_mode(self) -> str:
        return self.config.get('networkMode', 'bridge')

    @property
    def container_definitions(self) -> list:
        return self.config['containerDefinitions']

    @property
    def volumes(self) -> list:
        return self.config.get('volumes', [])

    @property
    def placement_constraints(self) -> list:
        return self.config.get('placementConstraints', [])

    def update_environment(self, envs) -> None:
        json_envs = [{"name": key, "value": value} for key, value in envs.items()]
        for container_def in self.container_definitions:
            if 'environment' in container_def:
                container_def['environment'] += json_envs
            else:
                container_def['environment'] = json_envs

    def set_images(self, images) -> None:
        for container_def in self.container_definitions:
            container_def['image'] = images[container_def['image']]

    def deregister_existing_definitions(self) -> None:
        if not self.revision:
            return
        definitions = ecs_client.list_task_definitions(familyPrefix=self.family)['taskDefinitionArns']

        for definition in definitions:
            if definition.split(':')[-1] != str(self.revision):
                ecs_client.deregister_task_definition(taskDefinition=definition)

    def register(self) -> str:
        print("Registering task definition: '{}'".format(self.family))
        result = ecs_client.register_task_definition(
            family=self.family,
            taskRoleArn=self.task_role_arn,
            networkMode=self.network_mode,
            containerDefinitions=self.container_definitions,
            volumes=self.volumes,
            placementConstraints=self.placement_constraints,
        )
        self.revision = result['taskDefinition']['revision']

        return '{}:{}'.format(self.family, self.revision)

    def deregister(self) -> None:
        if self.revision is not None:
            ecs_client.deregister_task_definition(taskDefinition='{}:{}'.format(self.family, self.revision))

    def __str__(self) -> str:
        return "<TaskDefinition> - {}".format(self.name)

class Task:
    def __init__(self, name, config) -> None:
        self.name = name
        self.config = config

    def run(self):
        print("Running task: '{}'".format(self.name))
        ecs_client.run_task(**self.config)

    def handle(self):
        self.run()

    def __str__(self) -> str:
        return "<Task> - {}".format(self.name)

class Service:
    def __init__(self, name, config) -> None:
        self.name = name
        self.config = config

    @property
    def cluster(self):
        return self.config['cluster']

    def update(self) -> None:
        print("Updating service: '{}'".format(self.name))
        ecs_client.update_service(service=self.name, **self.config)

    def handle(self):
        self.update()

    def __str__(self) -> str:
        return "<Service> - {}".format(self.name)

def run_command(command, ignore_error=False, silent=False, **kwargs) -> str:
    """f
    :param command: Command as string or tuple of args.
    :param ignore_error: Fail silently.
    :param silent: Do not log command execution.
    :return:
    """
    if not isinstance(command, (list, tuple)):
        command = (command,)

    if not silent:
        print('Running command: %s' % ' '.join(command))

    try:
        stdout = subprocess.check_output(command, **kwargs)
        return stdout.decode()
    except subprocess.CalledProcessError as e:
        if not ignore_error:
            print('Command failed: %s', str(e), file=sys.stderr)
            raise

def docker_login() -> None:
    cmd = run_command(['aws', 'ecr', 'get-login', '--no-include-email']).rstrip('\n').split(' ')
    run_command(cmd)

def get_json(file_path, fail_silently=False):
    try:
        with open(file_path, 'rt') as f:
            return json.loads(f.read())
    except:
        if fail_silently:
            return {}
        else:
            raise

def verify_config_files(config_dir):
    config_data = {}
    skipped_files = []
    invalid_files = []

    for conf_type in ('images', 'task_definitions', 'tasks', 'services', 'envs'):
        try:
            config_data[conf_type] = get_json(os.path.join(config_dir, '{}.json'.format(conf_type)))
        except FileNotFoundError:
            config_data[conf_type] = {}
            skipped_files.append(conf_type)
        except JSONDecodeError:
            invalid_files.append(conf_type)

    if skipped_files:
        logger.warning("Config files skipped (not found): {}".format(skipped_files))
    if invalid_files:
        raise ValueError("Invalid configuration files: {}".format(invalid_files))

    return config_data

def send_webhook_message(config_dir, success):
    if webhook_url is not None:
        if success:
            text = "Successfully deployed configuration `{}`.".format(config_dir)
            color = 'good'
        else:
            text = "Failed to deploy configuration `{}`.".format(config_dir)
            color = 'danger'

        try:
            tag, message = run_command(['git', 'log', '--oneline', '-1'], silent=True).strip().split(" ", 1)
            text += '\n`{}` {}'.format(tag, message)
        except:
            pass

        data = {'attachments': [
            {
                'fallback': text,
                'color': color,
                'text': text,
                'mrkdwn_in': ['text']
            }
        ]}
        requests.post(webhook_url, data=json.dumps(data), headers={'Content-Type': 'application/json'})

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description="Build and/or deploy Docker image to specified repo and update services/task definitions.")
    parser.add_argument('env', help='Path to config directory')
    parser.add_argument('-f', '--force-push-image', action='store_true', help='Push image even if tag exists in ecr.')
    parser.add_argument('-k', '--keep-image', action='store_true', help='Keep dockers image after pushing.')
    parser.add_argument('--skip-stash', action='store_true', help='Keep dockers image after pushing.')
    args = parser.parse_args()

    stashed = False
    if not args.skip_stash:
        # Stash changes so the deploy actually sends out correct code.
        try:
            stashed = run_command(['git', 'stash']).strip() != 'No local changes to save'
        except subprocess.CalledProcessError:
            pass

    config_dir = os.path.abspath(args.env)
    try:
        config_data = verify_config_files(config_dir)
    except:
        send_webhook_message(args.env, False)
        sys.exit(1)

    success = False

    try:
        docker_images = {}
        updated_task_definitions = []

        docker_login()

        # Handling docker containers based on config file.
        print("\nPreparing docker images...")
        for name, image_config in config_data['images'].items():
            image = DockerImage(name, **image_config)
            docker_images[name] = image.handle(args.keep_image, args.force_push_image)

        try:
            # Handling task definitions based on config file.
            print("\nUpdating task definitions...")
            for name, task_def_config in config_data['task_definitions'].items():
                task_def = TaskDefinition(name, task_def_config)
                task_def.update_environment(config_data['envs'])
                task_def.set_images(docker_images)
                task_def.register()
                updated_task_definitions.append(task_def)
        except:
            print("\nError updating task definitions, deregistering!")
            for task_def in updated_task_definitions:
                task_def.deregister()
        else:
            for task_def in updated_task_definitions:
                task_def.deregister_existing_definitions()

            # Handling one-time tasks
            print("\nRunning one-time tasks...")
            for name, task_config in config_data['tasks'].items():
                task_def = Task(name, task_config)
                try:
                    task_def.handle()
                except Exception as e:
                    logger.warning("Unable to run task {name}: {error}".format(name=name, error=str(e)))

            # Handling services based on config file
            print("\nUpdating services...")
            for name, service_config in config_data['services'].items():
                service = Service(name, service_config)
                service.handle()

            success = True
    finally:
        if stashed:
            run_command(['git', 'stash', 'pop'])
        send_webhook_message(args.env, success)


import os
from enum import Enum

import pyxel
import Box2D
from Box2D import b2

import main
import scenes

PPM = 16.0  # pixels per meter
TARGET_FPS = 30
TIME_STEP = 1.0 / TARGET_FPS
SCREEN_WIDTH, SCREEN_HEIGHT = 224, 126
SCREEN_Y_ZERO_OFFSET = 120
STAGE_WIDTH_M = 70  # m
STAGE_ITEMEND_X_M = 67  # ここまでしかものが置かない

SCREEN_WIDTH_M = int(SCREEN_WIDTH/PPM)
SCREEN_HIGHT_M = int(SCREEN_HEIGHT/PPM)

DEBUG_DRAW=False

STAGE_NUM = 12
GAME_TIMEOUT_S = 60 # 秒

# プレイヤーの移動の起点
PLAYER_SCROLL_X_M = 3

# プレイヤーの移動に合わせた全体の描画の移動量
DRAW_OFFSET_X = 0
DRAW_OFFSET_X_M = 0

SPRITE_SETS = [
    [0,0,16,16], # プレイヤー
    [0,16,16,16],
    [0, 48, 16, 16], # コイン
    [0, 64, 16, 16], # わな
    [0, 32, 16, 16], # 旗
]
class SpriteSet(Enum):
    PLAYER = 0
    COIN = 2
    TRAP = 3
    FLAG = 4

    @staticmethod
    def map_rect(n):
        if isinstance(n, SpriteSet):
            n = n.value
        if n<0 or n >= len(SPRITE_SETS):
            return None
        return SPRITE_SETS[n]

def draw_sprite_world(pos, sprite_n):
    pos = world_to_draw_pos(pos)

    r = SpriteSet.map_rect(sprite_n)
    if r is None:
        return
    w = r[2]
    h = r[3]

    pyxel.blt(pos[0]-w/2 + DRAW_OFFSET_X,
        pos[1]-h/2,
        0,
        r[0],r[1],r[2],r[3],
        11)

def draw_body_sprite(body, sprite_n):
    pos = body_pos(body)
    draw_sprite_world(pos, sprite_n)

def draw_sprite(pos, sprite_n):
    r = SpriteSet.map_rect(sprite_n)
    if r is None:
        return
    pyxel.blt(pos[0] + DRAW_OFFSET_X,
        pos[1],
        0,
        r[0],r[1],r[2],r[3],
        11)

# 描画の全体のオフセット値を設定
def set_draw_offset_x_m(offset_m):
    global DRAW_OFFSET_X_M
    global DRAW_OFFSET_X

    DRAW_OFFSET_X_M = offset_m
    DRAW_OFFSET_X = int(offset_m * PPM)

# ボディの位置を取得　ワールド座標
def body_pos(body):
    return body.transform * (0,0)

def set_body_pos(body, pos):
    body.transform = (pos, 0)

# ボディの位置を取得　描画座標
def body_draw_pos(body):
    return world_to_draw_pos(body.transform * (0,0))

# 位置をワールド座標から描画座標に変換
def world_to_draw_pos(pos):
    return int(pos[0]* PPM), int(SCREEN_Y_ZERO_OFFSET - pos[1] * PPM)

# ポリゴンを描画
# 引数は描画座標の位置
def draw_polygon(vertices, color):
    n = len(vertices)
    for i in range(n-1):
        pyxel.line(vertices[i][0] + DRAW_OFFSET_X, vertices[i][1],
            vertices[i+1][0] + DRAW_OFFSET_X, vertices[i+1][1],
            color)

    pyxel.line(vertices[n-1][0] + DRAW_OFFSET_X, vertices[n-1][1],
        vertices[0][0] + DRAW_OFFSET_X, vertices[0][1],
        color)

# ボディを描画
def draw_body(body, color):
    for fixture in body.fixtures:
        shape = fixture.shape

        if type(shape) is Box2D.b2PolygonShape:
            # print(shape.vertices)
            vertices = [(body.transform * v) * PPM for v in shape.vertices]
            vertices = [(int(v[0]), int(SCREEN_Y_ZERO_OFFSET - v[1])) for v in vertices]
            # print(vertices)
            draw_polygon(vertices, color)
        elif type(shape) is Box2D.b2CircleShape:
            pos = (body.transform * shape.pos) * PPM
            pos = int(pos[0]), int(SCREEN_Y_ZERO_OFFSET - pos[1])
#            print(pos)
            pyxel.circb(pos[0] + DRAW_OFFSET_X, pos[1], int(fixture.shape.radius*PPM), color)

def draw_center_x(text, y, color):
    w = len(text)*5
    pyxel.text(int((SCREEN_WIDTH-w)/2),
        y,
        text,
        color)

class GameMode(Enum):
    TITLE = 0
    MAIN = 1
    STAGE = 2
    END = 3

class InputKey(Enum):
    UP = 0
    DOWN = 1
    LEFT = 2
    RIGHT = 3
    A = 4
    B = 5
    COUNT = 6

class Input:
    def __init__(self):
        self.current_keys = [False] * InputKey.COUNT.value
        self.pref_keys = [False] * InputKey.COUNT.value

        self.record = []
        self.recoding = False

        self.replaying = False
        self.replay_counter = 0
        self.replay_record = None

    def update(self):
        self.pref_keys = self.current_keys[:]

        key_check = {
            InputKey.UP: pyxel.KEY_UP,
            InputKey.DOWN: pyxel.KEY_DOWN,
            InputKey.LEFT: pyxel.KEY_LEFT,
            InputKey.RIGHT: pyxel.KEY_RIGHT,
            InputKey.A: pyxel.KEY_X,
            InputKey.B: pyxel.KEY_R,
        }
        for key, value in key_check.items():
            self.current_keys[key.value] = pyxel.btn(value)

        if self.recoding:
            code = 0
            for n in range(InputKey.COUNT.value):
                if self.current_keys[n]:
                    code += pow(2, n)
            self.record.append(code)

        if self.replaying:
            if len(self.replay_record) > self.replay_counter:
                code = self.replay_record[self.replay_counter]
                for n in range(InputKey.COUNT.value):
                    self.current_keys[n] = True if (code & pow(2, n)) else False

            self.replay_counter += 1

    def draw(self):
        X = SCREEN_WIDTH - 15
        Y = 2

        LINES = [
            [2,0,2,1],
            [2,3,2,4],
            [0,2,1,2],
            [3,2,4,2],
            [8,3,8,4],
            [6,3,6,4],
        ]

        for n in range(InputKey.COUNT.value):
            c = 8 if self.current_keys[n] else 6
            p = LINES[n]

            pyxel.line(X+p[0], Y+p[1],
                X+p[2], Y+p[3],
                c
            )

        if self.replaying:
            t = "REPLAY"
            draw_center_x(t, SCREEN_HEIGHT/2, 8)

    def game_start(self, replay):
        if replay:
            self.recoding = False
            self.replaying = True
        else:
            self.recoding = True
            self.record = []
            self.replaying = False

    def game_end(self):
        if self.recoding:
            self.recoding = False
            self.replay_record = self.record[:]
        if self.replaying:
            self.replaying = False

    def btn(self, key):
        return self.current_keys[key.value]

    def btnp(self, key):
        return self.current_keys[key.value] and not self.pref_keys[key.value]

class Game:
    def __init__(self):
        pyxel.init(SCREEN_WIDTH, SCREEN_HEIGHT)
        pyxel.load(os.path.join(os.path.dirname(__file__), "main.pyxel"))

        self.mode = GameMode.TITLE
        self.coins = 0
        self.score = 0
        self.stage = 0
        self.stages = [False] * STAGE_NUM
        self.timecount = 1000*GAME_TIMEOUT_S

        self.next_mode = GameMode.TITLE
        self.next_param = {}

        self.input = Input()

    def run(self):
        pyxel.run(self.update, self.draw)

    def update(self):
        self.input.update()

        if pyxel.btnp(pyxel.KEY_Q):
            pyxel.quit()

        if self.next_mode:
            self.goto_next_mode()

        self.scene.update()

        if self.is_gaming():
            self.timecount -= (1000/TARGET_FPS)
            if self.timecount <= 0:
                self.game_end()

    def goto_next_mode(self):
        next_scenes = {
            GameMode.TITLE: scenes.SceneTitle,
            GameMode.STAGE: scenes.SceneStageSelect,
            GameMode.MAIN: main.SceneMain,
            GameMode.END: scenes.SceneEnd,
        }
        self.mode = self.next_mode
        self.scene = (next_scenes[self.next_mode])(self.next_param)
        self.next_mode = None
        self.next_param = None

    def is_gaming(self):
        return self.mode == GameMode.STAGE or self.mode == GameMode.MAIN

    def draw(self):
        pyxel.cls(0)
        self.scene.draw()

        if self.is_gaming():
            t = "TIME: %02d:%02d.%03d  SCORE:%03d" % (int(self.timecount/60/1000),
                int(self.timecount/1000)%60,
                self.timecount%1000,
                self.score)
            pyxel.text(10,3, t, 7)

        self.input.draw()

    def move_scene(self, next_mode, next_param):
        self.next_mode = next_mode
        self.next_param = next_param

    # ゲーム開始
    def game_start(self, replay):
        self.coins = 0
        self.score = 0
        self.stages = [False] * STAGE_NUM
        self.timecount = 1000*GAME_TIMEOUT_S

        self.move_scene(GameMode.STAGE, {})

        self.input.game_start(replay)

    def game_end(self):
        self.move_scene(GameMode.END, {})
        self.input.game_end()

    def stage_start(self, stage):
        self.coins = 0
        self.stage = stage
        self.move_scene(GameMode.MAIN, {"stage": stage})

    def stage_end(self):
        self.score += (self.coins+5)
        self.coins = 0
        self.stages[self.stage] = True
        self.move_scene(GameMode.STAGE, {})

    def get_coin(self):
        self.coins += 1

game = None
def game_main():
    global game
    game = Game()
    game.run()


import abc
from typing import Callable, Dict, Optional

class Query:
    """Base Query class.

    Examples
    --------
    >>> from clinica.pydra.query import Query
    >>> q = Query()
    >>> len(q)
    0
    """

    _default_queries = {}
    repr_indent = 4

    def __init__(self, query: Optional[Dict] = None):
        self._query = self.format_query(query)

    @property
    def query(self):
        return self._query

    def format_query(self, input_query: Optional[Dict] = None) -> Dict:
        """Format the input query in a form suitable for DataGrabbers.

        If the query is None, return an empty dictionary.

        Otherwise, `format_query` does two things:

            - parse the input query
            - potentially combine the parsed input query with default values

        The input query is a dictionary but has a heterogeneous structure
        depending on whether we wish to query BIDS or CAPS folders.

        More precisely, it can have the following form :

            {"label" : {query dict, possibly incomplete}}

            example : {"T1w": {"suffix": "T1w"}}

        which is the usual format for BIDS queries. In this case, we simply need
        to filter out queries for labels not supported for BIDS (for example we'd
        keep "T1w" but drop "dartel" or "mask_tissues" if these were present since
        these are labels for CAPS queries).

        The input query can also have the following form:

            {"label" : {kwargs for a query maker}}

            example: {"mask_tissues": {'tissue_number': (1, 2), 'modulation': False}}

        which is the usual format for CAPS queries. In this case, we need to
        filter out queries for labels not supported (for example we'd keep "mask_tissues"
        but drop "T1w" or "pet" if these were present since these are labels for BIDS queries).
        And we need to call the appropriate query maker to obtain a proper query dict.
        In this example, the query maker corresponding to the label "mask_tissues" is the
        function `clinica.utils.input_files.t1_volume_native_tpm_in_mni`. We call this
        function with arguments `tissue_number=(1, 2), modulation=False`.

        After parsing, the query structure is the same for both BIDS and CAPS:

            {"label" : {query dict, possibly incomplete} or list of query dicts}

        The query is then completed with potential default values:

            {"label" : {query dict} or list of query dicts}

            example: {"T1w": {"suffix": "T1w", "extension": [".nii.gz"]}}

        Parameters
        ----------
        input_query : Dict, optional
            Raw input query to format.

        Returns
        -------
        formatted_query : Dict
            Resulting formatted query.
        """
        formatted_query = {}
        if not input_query:
            return formatted_query
        for k, q in self.parse_query(input_query).items():
            if isinstance(q, dict):
                formatted_query[k] = {**self.default_query(k), **q}
            elif isinstance(q, list):
                formatted_query[k] = [{**self.default_query(k), **qq} for qq in q]
            else:
                raise TypeError(
                    f"Unexpected type {type(q)} for query {q}."
                    "Only dictionaries and lists are supported."
                )
        return formatted_query

    @abc.abstractmethod
    def parse_query(self, query: Dict) -> Dict:
        pass

    def default_query(self, label: str) -> Dict:
        """Returns the default query corresponding to the given label.
        If there is no such query, returns an empty dict.

        Parameters
        ----------
        label : str
            Label of the default query to look for.

        Returns
        -------
        Dict :
            The default query corresponding to the provided label.
        """
        return self._default_queries.get(label, {})

    def __getitem__(self, name):
        return self._query[name]

    def __iter__(self):
        return iter(self._query)

    def keys(self):
        return self._query.keys()

    def items(self):
        return self._query.items()

    def values(self):
        return self._query.values()

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

    def __str__(self):
        import json

        return json.dumps(self._query, indent=self.repr_indent)

class BIDSQuery(Query):
    """BIDSQuery class.

    Examples
    --------
    >>> from clinica.pydra.query import BIDSQuery
    >>> q = BIDSQuery({"T1w": {"suffix": "T1w"}})
    >>> len(q)
    1
    >>> q.query
    {'T1w': {'suffix': 'T1w', 'extension': ['.nii.gz']}}
    """

    _default_queries = {
        "T1w": {"suffix": "T1w", "extension": [".nii.gz"]},
        "pet": {"suffix": "pet", "extension": [".nii.gz"]},
    }

    def parse_query(self, query: Dict) -> Dict:
        """Parse the provided query.

        BIDS query are already specified in a proper dictionary format.
        Parsing is therefore equivalent to filtering out queries corresponding
        to invalid labels (for example labels for CAPS).
        """
        return {k: v for k, v in query.items() if k in self._default_queries}

class CAPSQuery(Query):
    """CAPSQuery class."""

    # Query makers are specified in subclasses
    _query_makers = {}

    def parse_query(self, query: Dict) -> Dict:
        """Parse the provided query.

        For CAPS, the user is providing a dictionary of kwargs for some function
        responsible for building the query dictionary (for example
        `clinica.utils.input_files.t1_volume_deformation_to_template`).
        These functions are stored in a mapping and accessed through the `query_maker`
        method which uses the labels to look for these functions.
        Parsing the query is equivalent to calling these functions for each label with
        the associated user-provided kwargs.

        Parameters
        ----------
        query : Dict
            The user provided query to be parsed.

        Returns
        -------
        parsed_query : Dict
            The parsed query.
        """
        parsed_query = {}
        for label, params in query.items():
            query_maker = self._query_maker(label)
            formatted_query = query_maker(**params)
            if len(formatted_query) > 0:
                parsed_query[label] = formatted_query
        return parsed_query

    def _query_maker(self, label: str) -> Callable:
        """Retrieve the query-making-function associated with the
        provided label.

        Parameters
        ----------
        label : str
            The label to use to get the function.

        Returns
        -------
        Callable :
            The function to use to generate the query dictionary for this label.
            If the label does not match any entry, a default maker which return
             an empty dict for any passed parameters is returned.
        """
        return self._query_makers.get(label, lambda **kwargs: {})

class CAPSFileQuery(CAPSQuery):
    """CAPSFileQuery class.

    This class only holds the mapping between labels and query makers
    to be used with the `CAPSFileDataGrabber`.

    Examples
    --------
    >>> from clinica.pydra.query import CAPSFileQuery
    >>> q = CAPSFileQuery({'mask_tissues': {'tissue_number': (1, 2), 'modulation': False}})
    >>> len(q)
    1
    >>> import json
    >>> print(json.dumps(q.query, indent=2))
    {
        "mask_tissues": [
            {
                "pattern": "t1/spm/segmentation/normalized_space/*_*_T1w_segm-graymatter_space-Ixi549Space_modulated-off_probability.nii*",
                "description": "Tissue probability map graymatter based on native MRI in MNI space (Ixi549) without modulation.",
                "needed_pipeline": "t1-volume-tissue-segmentation"
            },
            {
                "pattern": "t1/spm/segmentation/normalized_space/*_*_T1w_segm-whitematter_space-Ixi549Space_modulated-off_probability.nii*",
                "description": "Tissue probability map whitematter based on native MRI in MNI space (Ixi549) without modulation.",
                "needed_pipeline": "t1-volume-tissue-segmentation"
            }
        ]
    }
    """

    from clinica.utils.input_files import (
        custom_pipeline,
        pet_volume_normalized_suvr_pet,
        t1_volume_dartel_input_tissue,
        t1_volume_deformation_to_template,
        t1_volume_native_tpm,
        t1_volume_native_tpm_in_mni,
        t1_volume_template_tpm_in_mni,
    )

    def t1w_to_mni_transform():
        from clinica.utils.input_files import T1W_TO_MNI_TRANSFORM

        return T1W_TO_MNI_TRANSFORM

    _query_makers = {
        "tissues": t1_volume_native_tpm,
        "mask_tissues": t1_volume_native_tpm_in_mni,
        "flow_fields": t1_volume_deformation_to_template,
        "pvc_mask_tissues": t1_volume_native_tpm,
        "dartel_input_tissue": t1_volume_dartel_input_tissue,
        "t1w_to_mni": t1w_to_mni_transform,
        "pet_volume": pet_volume_normalized_suvr_pet,
        "t1_volume": t1_volume_template_tpm_in_mni,
        "custom_pipeline": custom_pipeline,
    }

class CAPSGroupQuery(CAPSQuery):
    """CAPSGroupQuery class.

    This class only holds the mapping between the labels and query makers
    to be used with the `CAPSGroupDataGrabber`.

    Examples
    --------
    >>> from clinica.pydra.query import CAPSGroupQuery
    >>> import json
    >>> q = CAPSGroupQuery({'dartel_template': {'group_label': "UnitTest"}})
    >>> len(q)
    1
    >>> print(json.dumps(q.query, indent=2))
    {
        "dartel_template": {
        "pattern": "group-UnitTest/t1/group-UnitTest_template.nii*",
        "description": "T1w template file of group UnitTest",
        "needed_pipeline": "t1-volume or t1-volume-create-dartel"
        }
    }
    """

    from clinica.utils.input_files import (
        custom_group,
        t1_volume_final_group_template,
        t1_volume_i_th_iteration_group_template,
    )

    _query_makers = {
        "dartel_template": t1_volume_final_group_template,
        "dartel_iteration_templates": t1_volume_i_th_iteration_group_template,
        "t_map": custom_group,
    }

def query_factory(query: Dict, query_type: str) -> Query:
    """Return the Query instance initialized from passed `query`,
    based on provided `query_type`.

    Parameters
    ----------
    query : dict
        The query in dictionary format.

    query_type : {"bids", "caps_file", "caps_group"}
        The type of query to build.

    Returns
    -------
    Query :
        The resulting Query instance.

    Raises
    ------
    ValueError
        If `query_type` is not a valid value.
    """
    if query_type == "bids":
        return BIDSQuery(query)
    elif query_type == "caps_file":
        return CAPSFileQuery(query)
    elif query_type == "caps_group":
        return CAPSGroupQuery(query)
    else:
        raise ValueError(
            f"query_factory() received an invalid argument for 'query_type' : {query_type}"
            f"Supported values are 'bids', 'caps_file', and 'caps_group'."
        )


#!/usr/bin/env python3
import tensorflow as tf
import eagerpy as ep
from foolbox import TensorFlowModel, accuracy, samples, Model
from foolbox.attacks import LinfPGD

def main() -> None:
    # instantiate a model (could also be a TensorFlow or JAX model)
    model = tf.keras.applications.ResNet50(weights="imagenet")
    pre = dict(flip_axis=-1, mean=[104.0, 116.0, 123.0])  # RGB to BGR
    fmodel: Model = TensorFlowModel(model, bounds=(0, 255), preprocessing=pre)
    fmodel = fmodel.transform_bounds((0, 1))

    # get data and test the model
    # wrapping the tensors with ep.astensors is optional, but it allows
    # us to work with EagerPy tensors in the following
    images, labels = ep.astensors(*samples(fmodel, dataset="imagenet", batchsize=16))
    clean_acc = accuracy(fmodel, images, labels)
    print(f"clean accuracy:  {clean_acc * 100:.1f} %")

    # apply the attack
    attack = LinfPGD()
    epsilons = [
        0.0,
        0.0002,
        0.0005,
        0.0008,
        0.001,
        0.0015,
        0.002,
        0.003,
        0.01,
        0.1,
        0.3,
        0.5,
        1.0,
    ]
    raw_advs, clipped_advs, success = attack(fmodel, images, labels, epsilons=epsilons)

    # calculate and report the robust accuracy (the accuracy of the model when
    # it is attacked)
    robust_accuracy = 1 - success.float32().mean(axis=-1)
    print("robust accuracy for perturbations with")
    for eps, acc in zip(epsilons, robust_accuracy):
        print(f"  Linf norm ≤ {eps:<6}: {acc.item() * 100:4.1f} %")

    # we can also manually check this
    # we will use the clipped advs instead of the raw advs, otherwise
    # we would need to check if the perturbation sizes are actually
    # within the specified epsilon bound
    print()
    print("we can also manually check this:")
    print()
    print("robust accuracy for perturbations with")
    for eps, advs_ in zip(epsilons, clipped_advs):
        acc2 = accuracy(fmodel, advs_, labels)
        print(f"  Linf norm ≤ {eps:<6}: {acc2 * 100:4.1f} %")
        print("    perturbation sizes:")
        perturbation_sizes = (advs_ - images).norms.linf(axis=(1, 2, 3)).numpy()
        print("    ", str(perturbation_sizes).replace("\n", "\n" + "    "))
        if acc2 == 0:
            break

if __name__ == "__main__":
    main()


import random

list = []
for num in range(100):
    nums = random.randrange(1, 1000)
    list.append(nums)
print(list)

def avg(thing):
    counter = 0
    adder = 0
    for item in thing[:]:
        counter += 1
        adder += int(item)
    avg = adder / counter
    print("The average of this list is ", avg)
avg(list)


import argparse

try:
    import importlib.metadata as metadata
except ImportError:
    import importlib_metadata as metadata

import numpy as np

from attractors.attractor import ATTRACTOR_PARAMS, Attractor

def case_convert(snakecase_string):
    return snakecase_string.replace("_", " ").title().replace("Cnn", "CNN")

def cli():
    parser = argparse.ArgumentParser(add_help=False, argument_default=argparse.SUPPRESS)
    required = parser.add_argument_group("required arguments")
    optional = parser.add_argument_group("other arguments")

    parser.add_argument(
        "-v",
        "--version",
        action="version",
        version=metadata.version("attractors"),
    )

    parser.add_argument(
        "-h",
        "--help",
        action="help",
        help="show this help message and exit",
    )

    required.add_argument(
        "-t",
        "--type",
        help="choose simulation type",
        type=str,
        choices=["multipoint", "gradient"],
        required=True,
    )

    optional.add_argument(
        "--des",
        help="choose the Differential Equation Solver. Default: rk4",
        type=str,
        choices=Attractor.list_des(),
        default="rk4",
    )

    optional.add_argument(
        "--width",
        help="set width of the figure Default: 16",
        type=int,
    )
    optional.add_argument(
        "--height",
        help="set height of the figure Default: 9",
        type=int,
    )
    optional.add_argument(
        "--dpi",
        help="set DPI of the figure Default: 120",
        type=int,
    )
    optional.add_argument(
        "--theme", help="choose theme (color palette) to be used", type=str
    )
    required.add_argument(
        "-s",
        "--simtime",
        help="set the simulation time",
        type=int,
        required=True,
    )
    required.add_argument(
        "-p",
        "--simpoints",
        help="set the number of points to be used for the simulation",
        type=int,
        required=True,
    )
    optional.add_argument(
        "--bgcolor",
        help=(
            "background color for figure in hex. Overrides theme settings if"
            " specified Default: #000000"
        ),
        type=str,
    )
    optional.add_argument(
        "--cmap",
        help=(
            "matplotlib cmap for palette. Overrides theme settings if"
            " specified Default: jet"
        ),
        type=str,
    )
    optional.add_argument(
        "--fps",
        help="set FPS for animated video (or interactive plot) Default: 60",
        type=int,
    )
    optional.add_argument(
        "--n",
        help="number of initial points for Multipoint animation Default: 3",
        type=int,
        default=3,
    )
    optional.add_argument(
        "--rk2",
        help="method for 2nd order Runge-Kutta if specified to be used. Default: heun",
        type=str,
        choices=["heun", "imp_poly", "ralston"],
        default="heun",
    )

    optional.add_argument(
        "--outf",
        help="output video filename Default: output.mp4",
        type=str,
    )
    optional.add_argument(
        "--live",
        help="live plotting instead of generating video.",
        action="store_true",
    )
    subparsers = parser.add_subparsers(
        title="Attractor settings",
        description="Choose one of the attractors and specify its parameters",
        dest="attractor",
        metavar="ATTRACTOR",
    )

    for attr, attrparams in ATTRACTOR_PARAMS.items():
        attrparser = subparsers.add_parser(
            f"{attr}",
            help=f"{case_convert(attr)} attractor",
            argument_default=argparse.SUPPRESS,
        )
        attrgroup = attrparser.add_argument_group(
            title=f"{case_convert(attr)} attractor parameters"
        )

        for i in range(len(attrparams["params"])):
            attrgroup.add_argument(
                f"--{attrparams['params'][i]}",
                help=(
                    f"Parameter for {case_convert(attr)} attractor "
                    f"Default: {attrparams['default_params'][i]}"
                ),
                type=float,
            )
        attrgroup.add_argument(
            "--initcoord",
            help=(
                f"Initial coordinate for {case_convert(attr)} attractor. Input"
                f" format: \"x y z\" Default: {attrparams['init_coord']}"
            ),
            type=float,
            nargs=3,
        )
        for k in ["x", "y", "z"]:
            attrgroup.add_argument(
                f"--{k}lim",
                help=(
                    f"{k} axis limits for figure. Input format:"
                    f" \"{k}min {k}max\" Default: {attrparams[f'{k}lim']}"
                ),
                type=float,
                nargs=2,
            )

    args = parser.parse_args()
    kwargs = vars(args)

    attractor = args.attractor
    if args.type == "multipoint":
        objs = [Attractor(attractor, kwargs=kwargs) for _ in range(args.n)]
        for obj in objs[1:]:
            obj.coord += np.random.normal(0, 0.01, size=3)
        itrs = []
        for obj in objs:
            func = getattr(obj, args.des)
            if args.des == "rk2":
                itr = func(0, args.simtime, args.simpoints, args.rk2)
            else:
                itr = func(0, args.simtime, args.simpoints)
            itrs.append(itr)
        Attractor.set_animate_multipoint(*itrs, **kwargs).animate(**kwargs)
    else:
        obj = Attractor(attractor, kwargs=kwargs)
        func = getattr(obj, args.des)
        if args.des == "rk2":
            itr = func(0, args.simtime, args.simpoints, args.rk2)
        else:
            itr = func(0, args.simtime, args.simpoints)
        Attractor.set_animate_gradient(itr, **kwargs).animate(**kwargs)

if __name__ == " __main__":
    cli()


import itertools
import random

class CellularAutomata():
    def __init__(self, rule_number=120, already_in_base=False, neighborhood=3, states=('0', '1'),
                    random_first_row=False, width=100, colors=None):
        # Set up basic info about automata.
        self.neighborhood = neighborhood
        self.states = states
        self.rule_number = rule_number
        self.maximum_rule_number = len(self.states) ** (len(self.states) ** self.neighborhood)
        self.width = width

        if not colors:
            self.colors = {
                # Colors assigned to each possible state
                "0": (255, 255, 255),
                "1": (255, 144, 251),
                "2": (160, 220, 252),
            }
        else:
            self.colors = colors

        # `rule_input_keys` is the list of all combinations of the state that are `neighborhood`
        # ... characters in length in reverse order that they're provided, like so:
        # `['222', '221', '220' '212' '211' '210' '202', '201', '200' ...]`
        self.rule_input_keys = list(map(''.join, itertools.product(self.states, repeat=self.neighborhood)))[::-1]

        if rule_number:
            if not already_in_base:
                self.rule_number = self._convert_rule_to_base(rule_number)
            self.rule_dictionary = self._create_rule_dictionary()
        else:
            self.rule_dictionary = None

        # If we have a randomly assigned first row, randomly decide values for each cell
        if random_first_row:
            self.curr_row = [random.choice(self.states) for _ in range(self.width)]
        else:
            # Center the problem string on the first row
            self.curr_row = ['0' for _ in range(self.width)]
            self.curr_row[self.width//2] = '1'

    # Converts `rule_number` to target base `len(states)`, with a maximum value of...
    # ... `maximum_rule_number = len(states) ** (len(states) ** neighborohood)`
    # Anything above that just uses unnecessary computer cycles, as they're...
    # ... equivalent to `rule_number % maximum_rule_number`
    def _convert_rule_to_base(self, rule_number):
        # Treat 0 as special otherwise we're dividing by 0
        if rule_number == 0:
            # Return a number that's just the length of
            return ''.join(['0'] * (len(self.states) ** self.neighborhood))
        if rule_number > self.maximum_rule_number:
            rule_number = rule_number % self.maximum_rule_number
        # We will generate the new rule one digit at a time, so we'll add the digits to a list
        new_rule_number_digits = []
        # Generate each digit of the new rule number in the target base
        while rule_number:
            rule_number, remainder = divmod(rule_number, len(self.states))
            new_rule_number_digits.append(str(remainder))

        # Complicated. Rule numbers in Cellular Automata are defined by the following
        new_rule_number = ''.join(new_rule_number_digits)[::-1].zfill(len(self.states) ** self.neighborhood)
        return new_rule_number

    # Returns a dictionary of possible inputs to the digits of
    def _create_rule_dictionary(self):
        # Maps the keys produced to the digits of `rule_number`
        return dict(zip(self.rule_input_keys, self.rule_number))

    def _decide_value_for_cell(self, cell_index, rules):
        # First cell used
        p_cell = (cell_index - self.neighborhood//2)
        # Joins the current values for the cells and uses it as
        input = "".join([self.curr_row[j % self.width] for j in range(p_cell, p_cell + self.neighborhood)])
        value = rules[input]
        return value

    # Expects a string similar to `011010001` to be passed in to determine the values of the rule outputs
    # `rule_values` is assumed to be in-base. We only check if it's the correct length to be used
    def advance_generation(self, rule_values=None):
        if rule_values:
            if len(rule_values) == len(self.rule_input_keys):
                # Use a custom transition function
                rule_dict = dict(zip(self.rule_input_keys, rule_values))
            else: # If the lengths don't match up...
                print("`rule_values` passed in is incorrect length to be used. Break time.")
                print("Length of rule_input_keys: " + len(self.rule_input_keys)
                    + "\nLength of rule_values: " + len(rule_values))
                rule_dict = dict()
        else:
            rule_dict = self.rule_dictionary

        new_row = [self._decide_value_for_cell(cell_index, rule_dict) for cell_index in range(len(self.curr_row))]
        self.curr_row = new_row


# Sum Root to Leaf Numbers
# Tree

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

# DFS
# runtime: faster than 86.74%
# https://blog.csdn.net/fuxuemingzhu/article/details/79369956
class Solution1:
    def sumNumbers(self, root: TreeNode) -> int:
        if root == None:
            return 0

        res = [0]
        self.dfs(root, res, root.val)
        return res[0]

    def dfs(self, root, res, path):
        if root.left == None and root.right == None:
            res[0] += path
        if root.left != None:
            self.dfs(root.left, res, path * 10 + root.left.val)
        if root.right != None:
            self.dfs(root.right, res, path * 10 + root.right.val)

# Recursion
# faster than 7.26%
# https://www.cnblogs.com/zuoyuan/p/3721420.html
class Solution2:
    def sumNumbers(self, root: TreeNode) -> int:
        return self.sum(root, 0)

    def sum(self, root, preSum):
        if not root:
            return 0
        preSum = preSum * 10 + root.val
        if not root.left and not root.right:
            return preSum
        return self.sum(root.left, preSum) + self.sum(root.right, preSum)


import random

parosszam:int = None
parosszamMasolat:str = None
paratlanszam:int=None
paratlanszamMasolat:str=None
atlag:float=0
dbatlag:int=0
darab:int=0
randszam:float=0

while (parosszam == None or  parosszam % 2 != 0):
    print("Kérek egy páros számot:", end='')
    parosszam = input()
    parosszamMasolat = parosszam.replace(".", "").replace("-", "")
    if(parosszamMasolat.isnumeric()):
        parosszam = int(parosszam)
    else:
        parosszam = None

while (paratlanszam == None or paratlanszam % 2 ==0 or parosszam> paratlanszam):
    print("Kérek egy páratlan számot:", end='')
    paratlanszam = input()
    paratlanszamMasolat = paratlanszam.replace(".", "").replace("-", "")
    if(paratlanszamMasolat.isnumeric()):
        paratlanszam = int(paratlanszam)
    else:
        paratlanszam= None

randszam = random.randrange(parosszam, paratlanszam)

if(abs(parosszam-randszam) < (paratlanszam-randszam)):
    print(f"A {randszam} random szám a páratlan számtól van messzebb ")
else:
    print(f"A {randszam} random szám a páros számtól van messzebb")

for i in range (parosszam, paratlanszam+1, 1):
    atlag = atlag+ i
    dbatlag +=1
    if(i % 4 == 0):
        darab += 1

atlag = atlag/dbatlag
print(f"A két szám közti számok átlaga: {atlag}\nA 4-el osztható számok darabszáma: {darab} db")


from janome.tokenizer import Tokenizer
from gensim.models import Word2Vec
import itertools
from sklearn.decomposition import PCA
import matplotlib.patches as patches
import matplotlib.pyplot as plt
from matplotlib import rcParams
import random

rcParams['font.family'] = 'sans-serif'
rcParams['font.sans-serif'] = ['Hiragino Maru Gothic Pro', 'Yu Gothic', 'Meirio', 'Takao', 'IPAexGothic', 'IPAPGothic', 'Noto Sans CJK JP']

path = "./data/"
lfiles = [
    "01.txt","02.txt","03.txt","04.txt","05.txt","06.txt","07.txt","08.txt","09.txt","10.txt",
    "11.txt","12.txt","13.txt","14.txt","15.txt","16.txt","17.txt","18.txt","19.txt","20.txt",
    "21.txt","22.txt","23.txt","24.txt","25.txt","26.txt","27.txt","28.txt","29.txt","30.txt",
    "41.txt","42.txt","43.txt","44.txt","45.txt","46.txt","47.txt","48.txt","49.txt","40.txt",
    "51.txt","52.txt","53.txt","54.txt","55.txt"
]

t = Tokenizer() # Tokenneizerインスタンスの生成
word_all = []   # 全ての単語をリスト形式で格納

### 関数 ###
# テキストを引数として、形態素解析の結果、名詞・動詞・形容詞の原形のみを配列で抽出する関数を定義
def extract_words(text):
    tokens = t.tokenize(text)
    return [token.base_form for token in tokens
        if token.part_of_speech.split(',')[0] in['名詞', '動詞','形容詞']]
# 類似単語の表示
def model_simulate( target_word ):
    try:
        print("■ {0}".format(target_word) )
        ret = model.wv.most_similar(positive=[target_word])
        for item in ret:
            print("\t{0} ({1})".format(item[0], item[1]) )
    except:
        print("[ERROR] {0}".format(target_word) )

def replaceStr(data):
    data = data.lower()
    # 文字列を置換する一覧 『 変換前：変換後 』
    dlist = {
        "protoout":"プロトアウト",
        "studio":"スタジオ",
        "protoout studio":"プロトアウトスタジオ",
        "protoout.studio":"プロトアウトスタジオ",
        "プロトアウト スタジオ":"プロトアウトスタジオ",
        "\"":"",
        "/":"",
        "画像":"",
        "0":"",
        "1":"",
        "2":"",
        "3":"",
        "4":"",
        "5":"",
        "6":"",
        "7":"",
        "8":"",
        "9":"",
        "月":"",
        "期生":"",
        "期":"",
        "土井":"",
        "com":"",
        ".":"",
        "-":"",
        "さん":"",
        "のびすけ":"",
        "コロナ":"",
        "(":"",
        ")":"",
        ":":"",
        "１":"",
        "飲む":"",
        "変化":"",
        "事":"",
    }

    for d in dlist:
        data = data.replace(d,dlist[d])
    return(data)

for file in lfiles:
    f = open( path + file, 'r', encoding='UTF-8')
    data = f.read()
    data = replaceStr(data)
    sentences = data.split('。')    # 全体のテキストを句点('。')で区切った配列にする。
    word_list = [extract_words(sentence) for sentence in sentences] # それぞれの文章を単語リストに変換(処理に数分かかります)
    word_all += word_list
    f.close()

model = Word2Vec(
        word_all,
        size=200,       # size: 圧縮次元数
        min_count=35,   # min_count: 出現頻度の低いものをカットする
        window=5,       # window: 前後の単語を拾う際の窓の広さを決める
        iter=100        # iter: 機械学習の繰り返し回数(デフォルト:5)十分学習できていないときにこの値を調整する
    )

target_word_list = [
    "プロトアウトスタジオ",
    "プロダクト",
    "アウトプット",
    "クラウドファンディング",
    "qiita",
]

for target_word in target_word_list:
    model_simulate( target_word )

########################################
# 参考：https://programming-info.dream-target.jp/python_word2vec
# プロットしたい単語を設定する
# 以下の例は、fire,earthquakeなどを設定しています。
words = []

for word in model.wv.index2word:
    words.append([word,"r"])

length = len(words)
data = []

j = 0
while j < length:
    data.append(model[words[j][0]])
    j += 1

#主成分分析により２次元に圧縮する
pca = PCA(n_components=2)
pca.fit(data)
data_pca= pca.transform(data)

length_data = len(data_pca)

### グラフ化 ######################

fig=plt.figure(figsize=(20,12),facecolor='w')
ax = plt.axes()

plt.rcParams["font.size"] = 10
i = 0
while i < length_data:
    plt.plot(data_pca[i][0], data_pca[i][1], ms=5.0, zorder=2, marker="x", color=words[i][1])   #点プロット
    plt.annotate(words[i][0], (data_pca[i][0], data_pca[i][1]), size=12)    #文字プロット
    for wd in target_word_list:
        if( words[i][0] == wd ):
            # 円を描く。色はランダム
            r=random.uniform(1,0)
            g=random.uniform(1,0)
            b=random.uniform(1,0)
            c = patches.Circle(xy=(data_pca[i][0], data_pca[i][1]), label=wd, radius=1.0, color=(r,g,b,0.5) )
            ax.add_patch(c)
    i += 1
ax.legend()
plt.show()


from math import floor
from typing import List

class Solution:
    def subMatrix(self, matrix: List[List[int]], left_top: List[int], right_bottom: List[int]) -> List[List[int]]:
        new_matrix = []
        if left_top[0] == right_bottom[0]:
            right_bottom[0] += 1
        if left_top[1] == right_bottom[1]:
            right_bottom[1] += 1
        for i in range(left_top[0], min(right_bottom[0] + 1, len(matrix))):
            row = []
            for j in range(left_top[1] + 1, right_bottom[1]):
                row.append(matrix[i][j])
            if row:
                new_matrix.append(row)
        return new_matrix

    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        if not matrix:
            return False
        height = len(matrix)
        width = len(matrix[0])
        if height <= 2 and width <= 2:
            for row in matrix:
                for i in row:
                    if i == target:
                        return True
            return False
        m_y = floor(height / 2)
        m_x = floor(width / 2)
        if matrix[m_y][m_x] == target:
            return True
        elif matrix[m_y][m_x] > target:
            return self.searchMatrix(self.subMatrix(matrix, [0, 0], [m_y, m_x]), target)
        else:
            return self.searchMatrix(self.subMatrix(matrix, [0, m_x], [m_y, width]), target) or self.searchMatrix(self.subMatrix(matrix, [m_y, m_x], [height, width]), target) or self.searchMatrix(self.subMatrix(matrix, [m_y, 0], [height, m_x]), target)

if __name__ == "__main__":
    matrix = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13,
                                                  14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25]]
    print(Solution().subMatrix(matrix, [0, 2], [5]))
    target = 15
    print(Solution().searchMatrix(matrix, target))


import logging
import os
from logging.handlers import RotatingFileHandler

formatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s', datefmt='%H:%M:%S')

def setup_logger(name, level=logging.DEBUG):
    """Function setup as many loggers as you want"""
    if not os.path.exists('logs'):
        os.mkdir('logs')

    file_handler = logging.handlers.RotatingFileHandler('logs/%s.log' % name.split('.')[-1],
                                                        maxBytes=10000000,
                                                        backupCount=2)  # 10 Mb
    file_handler.setFormatter(formatter)

    stream_handler = logging.StreamHandler()
    stream_handler.setFormatter(formatter)

    logger = logging.getLogger(name)
    logger.setLevel(level)
    logger.addHandler(file_handler)
    logger.addHandler(stream_handler)

    return logger


"""
    Module for tests in Request
"""
import unittest
from app.process.process import Process
from app.request.request import Request

class TestRequest(unittest.TestCase):
    """
    Tests in Request
    """

    def test_send_request_with_success(self):
        """
        Test request with success
        """

        sender = Process()
        receiver = Process()

        request = Request.send(sender, receiver)

        self.assertTrue(request)

    def test_send_request_sender_offline(self):
        """
        Test request failed because sender is offline
        """

        sender = Process()
        sender.change_status()
        receiver = Process()

        request = Request.send(sender, receiver)

        self.assertFalse(request)

    def test_send_request_receiver_not_exists(self):
        """
        Test request failed because receiver not exists
        """

        sender = Process()
        receiver = None

        request = Request.send(sender, receiver)

        self.assertFalse(request)