# -*- coding: utf-8 -*-
"""
Created on Wed Apr  6 14:38:54 2016

@author: Coline, Régis, Arnaud
"""
#import os
#os.chdir('C:\\Users\\Ariane\\Projet_info')
import random as rd
import matplotlib
matplotlib.use('Qt4Agg')
import matplotlib.pyplot as plt
import time
from humain import Sylviculteur, Bucheron
from terrain import Terrain
from eau import Eau
from foret import Foret
from foret_morte import Foret_morte
from foret_malade import Foret_malade
from plaine import Plaine
import numpy as np
import math

def generation_hum(nb_humains,type_classe,taille_x,taille_y,field):
    """
    method which create a list containing the human objects. They are randomly distributed on the map, except on the water.
    :param taille_x/y: integer which referts to the size of the map
    """
    humains=[]
    for i in range(nb_humains):
        x=rd.randint(0,taille_x-1)
        y=rd.randint(0,taille_y-1)
        while field[x][y].nature==0:
            x=rd.randint(0,taille_x-1)
            y=rd.randint(0,taille_y-1)
        humains=humains+[type_classe(x,y)]
    return(humains)

def tour(field,sylviculteurs,bucherons):
    """
    Method which runs a round, like a simulation with probabilities calculated in each method "maj" belonging to every class.
    It updates the matrice which contains the objects (plaine ,eau , foret etc...)

    """
    #on met à jour tous les sylviculteurs
    for sylviculteur in sylviculteurs:
        sylviculteur.maj(field,4)
      #on met à jour tous les bucherons
    for bucheron in bucherons:
        bucheron.maj(field, 3)

    #on met à jour tous les objets du terrains
    for x in range(field.shape[0]):
        for y in range(field.shape[1]):
            field[x,y].maj(field)

    #La valeur des attributs nature_suivant détermine quelle classe s'applique à la case.
    for x in range(field.shape[0]):
        for y in range(field.shape[1]):
            if field[x,y].nature!=field[x,y].nature_suivant:
                if field[x,y].nature_suivant==1:
                    field[x,y]=Plaine(x,y,field[x,y].presence)
                if field[x,y].nature_suivant==2 and field[x,y].nature==1:
                    field[x,y]=Foret(x,y,0,False)
                if field[x,y].nature_suivant==2 and field[x,y].nature==4:
                    field[x,y]=Foret(x,y,field[x,y].taille,field[x,y].presence)
                if field[x,y].nature_suivant==4:
                    field[x,y]=Foret_malade(x,y,field[x,y].taille,field[x,y].presence)
                if field[x,y].nature_suivant==3:
                    field[x,y]=Foret_morte(x,y,field[x,y].taille,field[x,y].presence)
    #Nature_suivant reprend la valeur 9, qui sert de valeur tampon
    for x in range(field.shape[0]):
        for y in range(field.shape[1]):
            if field[x,y].nature_suivant!=9:
                field[x,y].nature=field[x,y].nature_suivant
                field[x,y].nature_suivant=9

def ihm(field,sylviculteurs,bucherons,tours):
    """
    return a graphic showing the shape of the simulation
    """
    ihm=np.zeros(field.shape)
    for x in range(field.shape[0]):
        for y in range(field.shape[1]):
            ihm[x,y]=field[x,y].couleur
    fig=plt.figure()
    plt.pcolormesh(ihm,cmap='brg')
    for sylviculteur in sylviculteurs:
        plt.plot(sylviculteur.y,sylviculteur.x,'o')
    for bucheron in bucherons:
        plt.plot(bucheron.y,bucheron.x,'*')
    return(fig)

def generation_terrain(taille_x,taille_y,nb_sylviculteurs,nb_bucherons):
    """
    Method which create a matrice with field objects (eau, plaine, etc...)
    and uses two lists created by the method generation_hum (sylviculteur and bucheron).
    To create a coherent field, it uses noise.
    The shapes created are smoothed by bilinear interpolation,
    then each case is discretised to make them correspond at each object
    """
    print('starting Map creation')
    start_gen=time.time()
    imgx = taille_x
    imgy = taille_y
    octaves = int(math.log(max(imgx, imgy), 2.0))
    persistence =0.8
    imgAr = [[0.0 for i in range(imgx)] for j in range(imgy)] # matrice intermédiaire
    totAmp = 0.0
    for k in range(octaves):
        freq = 2**k
        amp = persistence ** k
        totAmp += amp
        # création d'une matrice de taille n*m (*amplitude)
        n = freq + 1; m = freq + 1 # taille de la matrice
        ar = [[rd.random() * amp for i in range(n)] for j in range(m)]
        nx = imgx / (n - 1.0); ny = imgy / (m - 1.0)
        for ky in range(imgy):
            for kx in range(imgx):
                #création du bruit de valeur
                #avec une interpolation bilinéaire
                i = int(kx / nx); j = int(ky / ny)
                dx0 = kx - i * nx; dx1 = nx - dx0
                dy0 = ky - j * ny; dy1 = ny - dy0
                z = ar[j][i] * dx1 * dy1
                z += ar[j][i + 1] * dx0 * dy1
                z += ar[j + 1][i] * dx1 * dy0
                z += ar[j + 1][i + 1] * dx0 * dy0
                z /= nx * ny
                imgAr[ky][kx] += z # Rassemblement dans la matrice intermédiaire

    # on cherche les propriétés statistiques de la matrice
    somme=0
    ecart_carre=0
    for y in range(imgy):
        for x in range(imgx):
            somme=somme+imgAr[y][x]

    moyenne=somme/(imgx*imgy)

    for y in range(imgy):
        for x in range(imgx):
            ecart_carre=ecart_carre+(imgAr[y][x]-moyenne)**2

    ecart_type=np.sqrt(ecart_carre/(imgx*imgy))

    # on regroupe toutes les valeurs de la matrice pour n'avoir plus que 3 valeurs
    for y in range(imgy):
        for x in range(imgx):
            if imgAr[y][x]<moyenne-ecart_type:
                imgAr[y][x]=0
            if imgAr[y][x]>moyenne+ecart_type:
                imgAr[y][x]=1.6
            if imgAr[y][x]>=moyenne-ecart_type and imgAr[y][x]<=moyenne+ecart_type:
                imgAr[y][x]=2
    # Création matrice objet ( elle sera modifié par la suite)
    mat_obj=np.array([[Plaine(x,y,False) for x in range(imgx)]for y in range(imgy)])
    #Les 3 valeurs de la matrice intermédiaire sont associés aux 3 classes terrains de départ (Eau, Plaine, Forêt)
    for y in range(imgy):
        for x in range(imgx):
            if imgAr[y][x]==0:
                mat_obj[x][y]=Eau(x,y,False)
            if imgAr[y][x]==1.6:
                mat_obj[x][y]=Foret(x,y,0,False)
            if imgAr[y][x]==2:
                mat_obj[x][y]=Plaine(x,y,False)

    sylviculteurs=generation_hum(nb_sylviculteurs,Sylviculteur,taille_x,taille_y,mat_obj)
    bucherons=generation_hum(nb_bucherons,Bucheron,taille_x,taille_y,mat_obj)

    end_gen=time.time()
    print('Map created in ' +str(end_gen-start_gen)+'seconds')

    return(mat_obj,sylviculteurs,bucherons)

#
#def film(Map,nb_tours):
#    """
#    Méthode permettant de générer un film
#    """
#    fig=plt.figure()
#    plt.xlim(0,10)
#    plt.ylim(0,10)
#    FFMpegWriter = manimation.writers['ffmpeg']
#    metadata = dict(title='Movie Test', artist='Matplotlib',
#                    comment='Movie support!')
#    writer = FFMpegWriter(fps=15, metadata=metadata)
#    with writer.saving(fig, "wild.mp4", 100):
#        for i in range(nb_tours):
#            tour(Map, sylviculteurs, bucherons, nature_case)
#            ihm=np.zeros(Map.shape)
#            for x in range(Map.shape[0]):
#                for y in range(Map.shape[1]):
#                    ihm[x,y]=Map[x,y].nature
#            plt.pcolor(ihm, cmap='brg')
#            writer.grab_frame()
#
#def dessin(field,nb_tours):
#    """
#    Renvoie l'état de la simulation après nb_tours
#    """
#    tic=time.time()
#    ihm(field,sylviculteurs,bucherons,tour)
#    for i in range(nb_tours):
#        print('start Round '+str(i))
#        start_tour=time.time()
#        tour(field, sylviculteurs, bucherons)
#        end_tour=time.time()
#        print('End Round ' +str(i))
#        print('Round done in '+str(end_tour-start_tour)+' seconds')
#        if i>nb_tours-10:
#            ihm(field,sylviculteurs, bucherons, i)
#    ihm(field,sylviculteurs, bucherons, nb_tours)
#    toc=time.time()
#    print('la simulation a mis ' +str(toc-tic)+ ' secondes')

#Generation=generation_terrain(100,100,10,10)
#field=Generation[0]
#sylviculteurs=Generation[1]
#bucherons=Generation[2]
#dessin(field,10)


from django.conf.urls import *
from rest_framework import routers
from controle import views

routerLuminosidade = routers.DefaultRouter()
routerLuminosidade.register(r'luminosidade', views.LuminosidadeViewSet)

routerIrrigacao = routers.DefaultRouter()
routerIrrigacao.register(r'irrigacao', views.IrrigacaoViewSet)

routerTemperatura = routers.DefaultRouter()
routerTemperatura.register(r'temperatura', views.TemperaturaViewSet)

urlpatterns = [
    url(r'^luminosidade_api/', include(routerLuminosidade.urls)),
    url(r'^irrigacao_api/', include(routerIrrigacao.urls)),
    url(r'^temperatura_api/', include(routerTemperatura.urls)),
]


import numpy as np
import glob
from PIL import Image
from sklearn.model_selection import train_test_split

#  ФУНКЦИЯ ДЛЯ ПРЕОБРАЗОВАНИЯ ФОТОГРАФИЙ ПОД НУЖНЫЙ ФОРМАТ
def get_images(path):
    image_paths = glob.glob(path)

    for image_file in image_paths:
        image = Image.open(image_file).resize((220, 220))
        image = np.asarray(image.convert('RGB')) / 255.0

        yield image

def get_image_data(path):
    images_data = []

    images = get_images(path)
    for img in images:
        images_data.append(img)

    return images_data

#  ФУНКЦИЯ ДЛЯ ПРЕОБРАЗОВАНИЯ ФАЙЛОВ К ФОТО ПОД НУЖНЫЙ ФОРМАТ
def get_txt(path):
    txt_data = []
    txt_path = glob.glob(path)

    for txt_file in txt_path:
        with open(txt_file, 'r', encoding='utf-8') as f:
            tmp = f.readline().split(' ')

            bndbox = [None] * 5
            bndbox[0] = int(tmp[0])
            bndbox[1] = int(tmp[1])
            bndbox[2] = int(tmp[2])
            bndbox[3] = int(tmp[3])
            bndbox[4] = int(tmp[4])

            txt_data.append(bndbox)

    return txt_data

def get_txt_index(path, index):
    txt_data = []
    txt_path = glob.glob(path)

    for txt_file in txt_path:
        with open(txt_file, 'r', encoding='utf-8') as f:
            tmp = f.readline().split(' ')
            tmp = int(tmp[index])

            if tmp == 2 and index == 0:
                tmp = 0
            elif index == 1 and index == 3:
                img = Image.open(os.path.splitext(txt_file)[0] + '.jpg')
                w, _ = img.size
                tmp = tmp / w
            elif index == 2 and index == 4:
                img = Image.open(os.path.splitext(txt_file)[0] + '.jpg')
                _, h = img.size
                tmp = tmp / h

            txt_data.append(tmp)

    return txt_data

# Получение всех данных
def get_data(path_train_jpg, path_train_txt, path_valid_jpg, path_valid_txt):
    images = get_image_data(path_train_jpg)
    txt = get_txt(path_train_txt)

    txt_class = get_txt_index(path_train_txt, 0)
    txt_xmin = get_txt_index(path_train_txt, 1)
    txt_ymin = get_txt_index(path_train_txt, 2)
    txt_xmax = get_txt_index(path_train_txt, 3)
    txt_ymax = get_txt_index(path_train_txt, 4)

    x_train, x_test, _, _ = train_test_split(images, txt, test_size=0.1)

    _, _, y_train_class, y_test_class = train_test_split(images, txt_class, test_size=0.1)
    _, _, y_train_xmin, y_test_xmin = train_test_split(images, txt_xmin, test_size=0.1)
    _, _, y_train_ymin, y_test_ymin = train_test_split(images, txt_ymin, test_size=0.1)
    _, _, y_train_xmax, y_test_xmax = train_test_split(images, txt_xmax, test_size=0.1)
    _, _, y_train_ymax, y_test_ymax = train_test_split(images, txt_ymax, test_size=0.1)

    images_valid = get_image_data('cats_dogs_dataset/valid/*.jpg')
    txt_class_valid = get_txt_index('cats_dogs_dataset/valid/*.txt', 0)
    txt_xmin_valid = get_txt_index('cats_dogs_dataset/valid/*.txt', 1)
    txt_ymin_valid = get_txt_index('cats_dogs_dataset/valid/*.txt', 2)
    txt_xmax_valid = get_txt_index('cats_dogs_dataset/valid/*.txt', 3)
    txt_ymax_valid = get_txt_index('cats_dogs_dataset/valid/*.txt', 4)

    x_train = np.array(x_train)
    x_test = np.array(x_test)

    y_train_class = np.array(y_train_class)
    y_train_xmin = np.array(y_train_xmin)
    y_train_ymin = np.array(y_train_ymin)
    y_train_xmax = np.array(y_train_xmax)
    y_train_ymax = np.array(y_train_ymax)

    y_test_class = np.array(y_test_class)
    y_test_xmin = np.array(y_test_xmin)
    y_test_ymin = np.array(y_test_ymin)
    y_test_xmax = np.array(y_test_xmax)
    y_test_ymax = np.array(y_test_ymax)

    x_valid = np.array(images_valid)
    txt_class_valid = np.array(txt_class_valid)
    txt_xmin_valid = np.array(txt_xmin_valid)
    txt_ymin_valid = np.array(txt_ymin_valid)
    txt_xmax_valid = np.array(txt_xmax_valid)
    txt_ymax_valid = np.array(txt_ymax_valid)

    y_train_cat = {'class': y_train_class,
                   'out': [y_train_xmin, y_train_ymin, y_train_xmax, y_train_ymax]}

    y_test_cat = {'class': y_test_class,
                  'out': [y_test_xmin, y_test_ymin, y_test_xmax, y_test_ymax]}

    y_valid_cat = {'class': txt_class_valid,
                   'out': [txt_xmin_valid, txt_ymin_valid, txt_xmax_valid, txt_ymax_valid]}

    return x_train, y_train_cat, x_test, y_test_cat, x_valid, y_valid_cat

if __name__ == '__main__':
    images_data = []

    images = get_images('cats_dogs_dataset/train/*.jpg')
    for img in images:
        images_data.append(img)

    print(len(images_data))


from nornir import InitNornir
from nornir_utils.plugins.functions import print_result
from nornir_junos.tasks.junos_get import junos_get
from nornir.core.plugins.connections import ConnectionPluginRegister
from nornir_junos.connections import nornir_junos
ConnectionPluginRegister.register("nornir_junos", nornir_junos)
nr = InitNornir(
    runner={
        "plugin": "threaded",
        "options": {
            "num_workers": 100,
        },
    },
    inventory={
        "plugin": "SimpleInventory",
        "options": {
            "host_file": "inventory/hosts.yaml"
        },
    },
)

results = nr.run(
    task=junos_get, commands=["show system uptime"]
)
print_result(results)


import customtkinter as Ctk
from tkinter import *

Ctk.set_appearance_mode('white')
Ctk.set_default_color_theme('white')

janela=Ctk.Ctk()

janela.geometry('1000x700')

janela.title('Jogo da Forca')

def jogar_forca():
    palavra_secreta = input("Digite a palavra secreta: ").upper()
    letras_certas = []
    letras_erradas = []
    tentativas = 6

    while True:
        for letra in palavra_secreta:
            if letra in letras_certas:
                print(letra, end=" ")
            else:
                print("_", end=" ")
        print("\n")

        if len(letras_erradas) > 0:
            print("Letras erradas:", " ".join(letras_erradas))

        letra_palpite = input("Digite uma letra: ").upper()

        if letra_palpite in palavra_secreta:
            letras_certas.append(letra_palpite)
        else:
            letras_erradas.append(letra_palpite)
            tentativas -= 1

        if tentativas == 0:
            print("Você perdeu! A palavra secreta era:", palavra_secreta)
            break

        if all(letra in letras_certas for letra in palavra_secreta):
            print("Parabéns! Você venceu!")
            break

jogar_forca()

FORCA - HANGMAN/Jogo da forca - Hangman game.py


import asyncio
from tmdb_api import TmdbApi
import os

async def main():
    api = TmdbApi(os.environ["API_KEY"])

    movie_ids = [500, 234, 600]

    movies = await asyncio.gather(*map(api.movie, movie_ids))

    for i, movie in enumerate(movies):
        print(f"{i+1:2} | {movie['title']:30} ({movie['tagline']})")

if __name__ == "__main__":
    # avoids windows specific issue, see https://stackoverflow.com/a/66772242
    asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())

    asyncio.run(main())


import argparse
import os
import multiprocessing
import glob
from functools import partial

def parse_args():
    parser = argparse.ArgumentParser(description='')

    requiredArgs = parser.add_argument_group("Required Arguments")

    requiredArgs.add_argument('-f', '--fas_tafile',
                               dest='faa_file',
                               required=True,
                               help='directory with the .faa proteins files'
                               )
    requiredArgs.add_argument('-hmms', '--hmms_folder',
                               dest='hmms_folder',
                               required=True,
                               help='hmm db built with hmmpress'
                               )

    requiredArgs.add_argument('-o', '--output_dir',
                               dest='out_dir',
                               required=True,
                               help=''
                               )

    return parser.parse_args()

def run_hmmsearch(faa_file, outdir, hmm_db):
    hmm_id   = os.path.basename(hmm_db).split(".hmm")[0]
    faa_id   = os.path.basename(faa_file).split(".faa")[0]
    #outfile   = f"{os.path.abspath(outdir)}/{file_id}.out"
    tblout    = f"{os.path.abspath(outdir)}/{faa_id}-{hmm_id}.tblout"
    domtblout = f"{os.path.abspath(outdir)}/{faa_id}-{hmm_id}.domtblout"

    os.system(f"time hmmsearch --noali --tblout {tblout} --domtblout {domtblout} --cpu 1 {hmm_db} {faa_file} > /dev/null")
    print(f"{hmm_id} completed")

def main():

    args = parse_args()

    # get all hmms to scan
    hmms = glob.glob(f"{args.hmms_folder}/*.hmm")

    # def partial function
    partial_func = partial(run_hmmsearch, args.faa_file, args.out_dir)

    # parallel
    pool = multiprocessing.Pool(processes=40)
    pool.map(partial_func, hmms)
    pool.close()
    pool.join()

if __name__ == "__main__":
    main()