from yacs.config import CfgNode as CN

def set_cfg(cfg):

    # ------------------------------------------------------------------------ #
    # Basic options
    # ------------------------------------------------------------------------ #
    # Dataset name
    cfg.dataset = 'ZINC'
    # Additional num of worker for data loading
    cfg.num_workers = 8
    # Cuda device number, used for machine with multiple gpus
    cfg.device = 0
    # Additional string add to logging
    cfg.handtune = ''
    # Whether fix the running seed to remove randomness
    cfg.seed = None
    # Whether downsampling the dataset, used for large dataset for faster tuning
    cfg.downsample = False
    # version
    cfg.version = 'final'
    # task, for simulation datasets
    cfg.task = -1

    # ------------------------------------------------------------------------ #
    # Training options
    # ------------------------------------------------------------------------ #
    cfg.train = CN()
    # Total graph mini-batch size
    cfg.train.batch_size = 128
    # Maximal number of epochs
    cfg.train.epochs = 100
    # Number of runs with random init
    cfg.train.runs = 3
    # Base learning rate
    cfg.train.lr = 0.001
    # number of steps before reduce learning rate
    cfg.train.lr_patience = 50
    # learning rate decay factor
    cfg.train.lr_decay = 0.5
    # L2 regularization, weight decay
    cfg.train.wd = 0.
    # Dropout rate
    cfg.train.dropout = 0.

    # ------------------------------------------------------------------------ #
    # Model options
    # ------------------------------------------------------------------------ #
    cfg.model = CN()
    # GNN type used, see core.model_utils.pyg_gnn_wrapper for all options
    cfg.model.gnn_type = 'GINEConv' # change to list later
    # Hidden size of the model
    cfg.model.hidden_size = 128
    # Number of gnn layers (doesn't include #MLPs)
    cfg.model.num_layers = 4
    # Number of inner layers, 0 means use normal GNN
    cfg.model.mini_layers = 0
    # Pooling type for generaating graph/subgraph embedding from node embeddings
    cfg.model.pool = 'add'
    # Use residual connection
    cfg.model.residual = True
    # Whether use virtual node in message passing, keep it always false
    cfg.model.virtual_node = False
    # Distance to centroid embedding dim, 0 means do not use it
    cfg.model.hops_dim = 16
    # What embedding to include
    cfg.model.embs = (0, 1, 2) # 0-Centroid, 1-Subgraph,  2-Context
    # How to combine embs together when have more than 1 embs, choose from ['concat', 'add']
    cfg.model.embs_combine_mode = 'concat'
    # Number of MLP layers in generating subgraph embeddings
    cfg.model.mlp_layers = 1
    # Whether combine with normal gnn, only used for random walk based subgraph which doesn't cover whole 1st hop
    cfg.model.use_normal_gnn = False

    # ------------------------------------------------------------------------ #
    # Subgraph patterns options
    # ------------------------------------------------------------------------ #
    cfg.subgraph = CN()
    ##### Option 1: Egonet based subgraph
    cfg.subgraph.hops = 3
    ##### Option 2: Random walk based subgraph
    # Random walk based subgraph walk length, when 0 use egonet
    cfg.subgraph.walk_length = 0
    # We use node2vec based random walk, p is return parameter. Small p => local walk
    cfg.subgraph.walk_p = 1.0
    # q is in-out parameter. Large q => local walk
    cfg.subgraph.walk_q = 1.0
    # Number of times of repeating the random walk to reduce randomness
    cfg.subgraph.walk_repeat = 5

    # extract subgraph online or offline. Online cost more, but can help randomness
    cfg.subgraph.online = True # When use sampling subgraphs, keep it True.

    # ------------------------------------------------------------------------ #
    # Subgraph sampling options, to improve scalability
    # ------------------------------------------------------------------------ #
    cfg.sampling = CN()
    # mode to use, choose from [shortest_path, min_set, random, None]
    cfg.sampling.mode = None # None means don't use sampling
    # The minimum times each node is covered by all sampled subgraphs
    cfg.sampling.redundancy = 0
    # Options for shortest_path_distance based farthest sampling
    cfg.sampling.stride = 2
    # Options for random sampling
    cfg.sampling.random_rate = 0.5
    # Reduce evaluation batch size by a factor to avoid use more meory, as test is always in full-mode
    cfg.sampling.batch_factor = 1

    return cfg

import os
import argparse
# Principle means that if an option is defined in a YACS config object,
# then your program should set that configuration option using cfg.merge_from_list(opts) and not by defining,
# for example, --train-scales as a command line argument that is then used to set cfg.TRAIN.SCALES.

def update_cfg(cfg, args_str=None):
    parser = argparse.ArgumentParser()
    parser.add_argument('--config', default="", metavar="FILE", help="Path to config file")
    # opts arg needs to match set_cfg
    parser.add_argument("opts", default=[], nargs=argparse.REMAINDER,
                         help="Modify config options using the command-line")

    if isinstance(args_str, str):
        # parse from a string
        args = parser.parse_args(args_str.split())
    else:
        # parse from command line
        args = parser.parse_args()
    # Clone the original cfg
    cfg = cfg.clone()

    # Update from config file
    if os.path.isfile(args.config):
        cfg.merge_from_file(args.config)

    # Update from command line
    cfg.merge_from_list(args.opts)

    return cfg

"""
    Global variable
"""
cfg = set_cfg(CN())


# ler 7 números e separar em par e impar
# num = list()
# lista_pares = list()
# lista_impares = list()
#
# for c in range(0, 7):
#     num.append(int(input(f'Digite o {c+1}º número: ')))
#     if num[c] % 2 == 0:
#         lista_pares.append(num[c])
#     else:
#         lista_impares.append(num[c])
# lista_impares.sort()
# lista_pares.sort()
# num.sort()
# print(f'A lista total foi: {num}')
# print(f'Os valores pares são: {lista_pares}')
# print(f'Os valores ímpares são: {lista_impares}')

# meu código deu 17 linhas, o do guanabara deu 10 kkk a seguir como ele fez
valores = [[], []]
for i in range(1, 8):
    val = int(input(f'Digite o {i}o número: '))
    if val % 2 == 0:
        valores[0].append(val)
    else:
        valores[1].append(val)
valores[0].sort()
valores[1].sort()
print(f'Lista de pares: {valores[0]}')
print(f'Lista de ímpares: {valores[1]}')


sudoku = [list(map(int, input().split())) for _ in range(9)]

empty_cells = list()

for i in range(9) :
  for j in range(9) :
    if sudoku[i][j] == 0 :
      empty_cells.append((j, i))

def check(x, y, num) :
  for i in range(9) :
    if sudoku[i][x] == num:
      return False
    if sudoku[y][i] == num:
      return False
  for i in range(y // 3 * 3, y // 3 * 3 + 3) :
    for j in range(x // 3 * 3, x // 3 * 3 + 3) :
      if sudoku[i][j] == num:
        return False
  return True

def dfs(idx) :
  if idx == len(empty_cells) :
    return True

  x, y = empty_cells[idx]
  for i in range(1, 10) :
    if check(x, y, i) :
      sudoku[y][x] = i
      result = dfs(idx+1)
      if result :
        return True
      sudoku[y][x] = 0
  return False
dfs(0)
for _sudoku in sudoku :
  print(*_sudoku)


from flask import Flask, request
import sqlite3
import uuid
from werkzeug.exceptions import HTTPException
import json
import csv

app = Flask(__name__)

@app.route('/initdb')
def init_db():
    conn = sqlite3.connect('movies.db')
    print("Opened database successfully");

    # clear out db if table already exists...
    conn.execute(
        'DROP TABLE IF EXISTS movies'
    )

    conn.execute(
        'CREATE TABLE movies (' +
            'id TEXT NOT NULL PRIMARY KEY, ' +
            'release_year TEXT, ' +
            'title TEXT, ' +
            'origin TEXT, ' +
            'director TEXT,' +
            'cast TEXT,' +
            'genre TEXT,' +
            'wiki_page TEXT,' +
            'plot TEXT' +
        ')'
    )

    conn.close()
    return 'database initialized', 200

# TODO: Allow specification of file location
@app.route('/populatedb')
def populate_db():
    try:
        con = sqlite3.connect("movies.db")
        cur = con.cursor()

        filename="movie_plots.csv"

        movie_plots = open(filename)
        rows = csv.reader(movie_plots)

        movies_with_ids = [[str(uuid.uuid1())] + row for row in rows]

        print(movies_with_ids[0])

        cur.executemany("INSERT INTO movies VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", movies_with_ids[1:len(movies_with_ids)])

        con.commit()
        con.close()

        return "db has been populated from csv", 200

    except Exception as e:
        return f'an exception has occured in populating the database: {e}', 500

# TODO: DRY...
@app.route('/movies', defaults={'movie_id': None}, methods=['GET'])
@app.route('/movies/<movie_id>')
def get_movie_by_id(movie_id):
    if movie_id != None:

        con = sqlite3.connect('movies.db')
        cur = con.cursor()

        cur.execute(f'SELECT * FROM movies where ID=\'{movie_id}\'')
        data = cur.fetchall()

        con.close()

        formatted = []
        for item in data:
            formatted.append(
                {
                    "id": item[0],
                    "release_year": item[1],
                    "title": item[2],
                    "origin": item[3],
                    "director": item[4],
                    "cast": item[5],
                    "genre": item[6],
                    "wiki": item[7],
                    "plot": item[8],

               }
            )

        return {'content': formatted}

    else:
        con = sqlite3.connect('movies.db')
        cur = con.cursor()

        pagenumber = request.args.get('page')

        if pagenumber != None:
            cur.execute(f'SELECT id, release_year, title, origin, director, genre FROM movies ORDER BY id LIMIT 50 OFFSET {str((int(pagenumber)-1)*50)};')
        else:
            cur.execute(f'SELECT id, release_year, title, origin, director, genre FROM movies ORDER BY id;')

        data = cur.fetchall()

        con.close()

        formatted = []
        for item in data:
            formatted.append(
                {
                    "id": item[0],
                    "release_year": item[1],
                    "title": item[2],
                    "origin": item[3],
                    "director": item[4],
                    "genre": item[5]

               }
            )

        return {'content': formatted, "page": pagenumber}

@app.route('/movies', methods=['POST'])
def create_movie():

    body = request.get_json()

    try:
        con = sqlite3.connect("movies.db")
        cur = con.cursor()

        movie_id = str(uuid.uuid1())

        new_movie = [
            movie_id,
            body["releaseYear"],
            body["title"],
            body["origin"],
            body["director"],
            body["cast"],
            body["genre"],
            body["wiki"],
            body["plot"]
        ]
        cur.execute("INSERT INTO movies VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", new_movie)
        cur.execute(f'SELECT * FROM movies where ID=\'{movie_id}\'')
        data = cur.fetchall()

        con.commit()
        con.close()

        formatted = []
        for item in data:
            formatted.append(
                {
                    "id": item[0],
                    "release_year": item[1],
                    "title": item[2],
                    "origin": item[3],
                    "director": item[4],
                    "cast": item[5],
                    "genre": item[6],
                    "wiki": item[7],
                    "plot": item[8],

               }
            )

        print(formatted)

        return {'content': formatted}, 200
    except Exception as e:
        return f'error creating movie: {e}', 500

@app.route('/movies/<movie_id>', methods=['PUT'])
def update_movie(movie_id):
    body = request.get_json()

    try:
        con = sqlite3.connect("movies.db")
        cur = con.cursor()

        new_movie = [
            body["releaseYear"],
            body["title"],
            body["origin"],
            body["director"],
            body["cast"],
            body["genre"],
            body["wiki"],
            body["plot"],
            movie_id
        ]

        sql = """
        UPDATE movies
        SET release_year = ? ,
            title = ? ,
            origin = ? ,
            director = ? ,
            cast = ? ,
            genre = ? ,
            wiki_page = ? ,
            plot = ?
        WHERE id = ?"""

        cur.execute(sql, new_movie)
        cur.execute(f'SELECT * FROM movies where ID=\'{movie_id}\'')
        data = cur.fetchall()

        con.commit()
        con.close()

        formatted = []
        for item in data:
            formatted.append(
                {
                    "id": item[0],
                    "release_year": item[1],
                    "title": item[2],
                    "origin": item[3],
                    "director": item[4],
                    "cast": item[5],
                    "genre": item[6],
                    "wiki": item[7],
                    "plot": item[8],

               }
            )

        return {'content': formatted}, 200

    except Exception as e:
        return f'error creating movie: {e}'

@app.route('/movies/<movie_id>', methods=['DELETE'])
def delete_movie(movie_id):

    body = request.get_json()

    try:
        con = sqlite3.connect("movies.db")
        cur = con.cursor()

        cur.execute(f'DELETE FROM movies where ID=\'{movie_id}\'')

        con.commit()
        con.close()

        return f'deleted movie with id: {movie_id}', 200

    except Exception as e:
        return f'error creating movie: {e}'
    return f'Deleteing movie with id: {movie_id}'

@app.route('/search/<search_string>', methods=['GET'])
def search(search_string):
    try:
        con = sqlite3.connect("movies.db")
        cur = con.cursor()

        pagenumber = request.args.get('page')

        cur.execute(f'SELECT id, release_year, title, origin, director, genre FROM movies WHERE title LIKE \'{search_string}%\' ORDER BY title LIMIT 50 OFFSET {str((int(pagenumber)-1)*50)};')

        data = cur.fetchall()

        con.commit()
        con.close()
        formatted = []
        for item in data:
            formatted.append(
                {
                    "id": item[0],
                    "release_year": item[1],
                    "title": item[2],
                    "origin": item[3],
                    "director": item[4],
                    "genre": item[5]

               }
            )

        return {'content': formatted}

    except Exception as e:
        return f'error searching for movie: {e}'

@app.errorhandler(HTTPException)
def handle_bad_request(e):
    response = e.get_response()
    # replace the body with JSON
    response.data = json.dumps({
        "code": e.code,
        "name": e.name,
        "description": e.description,
    })
    response.content_type = "application/json"
    return response


# -*- coding: utf-8 -*-
"""
Created on Sun Oct 13 17:25:18 2019

@author: jacqueline.cortez
Chapter 1: Introduction to geospatial vector data
    In this chapter, you will be introduced to the concepts of geospatial data, and more specifically of vector data.
    You will then learn how to represent such data in Python using the GeoPandas library, and the basics to read,
    explore and visualize such data. And you will exercise all this with some datasets about the city of Paris.
"""

print("****************************************************")
print("** BEGIN                                          **")
print("****************************************************")
topic = "Importing libraries"; print("** %s\n" % topic)

import matplotlib.pyplot as plt                                               #For creating charts
import pandas            as pd                                                #For loading tabular data
import contextily                                                             #To add a background web map to our plot
import geopandas         as gpd                                               #For working with geospatial data

print("****************************************************")
topic = "Preparing the environment"; print("** %s\n" % topic)

print("****************************************************")
topic = "User Variables"; print("** %s\n" % topic)

print("****************************************************")
topic = "Defined functions"; print("** %s\n" % topic)

print("****************************************************")
topic = "Reading geospatialdata"; print("** %s\n" % topic)

df_countries_geo = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
print("Columns of df_countries_geo:\n{}\n".format(df_countries_geo.columns))

df_cities_geo = gpd.read_file(gpd.datasets.get_path('naturalearth_cities'))
print("Columns of df_cities_geo:\n{}\n".format(df_cities_geo.columns))

# Read the Paris districts dataset
filename = "paris_districts_utm.geojson"
df_paris_districts_geo = gpd.read_file(filename)
print("Columns of {}:\n{}\n".format(filename, df_paris_districts_geo.columns))

print("****************************************************")
topic = "Reading data"; print("** %s\n" % topic)

filename = "paris_restaurants.csv"
df_restaurants = pd.read_csv(filename)
print("Columns of {}:\n{}\n".format(filename, df_restaurants.columns))

print("****************************************************")
topic = "2. Restaurants in Paris"; print("** %s\n" % topic)

print("Head of paris_restaurants:\n{}\n".format(df_restaurants.head()))

# Make a plot of all points
fig, ax = plt.subplots()
ax.plot(df_restaurants.x, df_restaurants.y, marker='o', alpha=0.5, linestyle='None')
plt.xlabel('Longitude'); plt.ylabel('Latitude'); # Labeling the axis.
plt.title('Restaurants in Paris'); plt.suptitle(topic);  # Setting the titles.
plt.subplots_adjust(left=0.2, bottom=None, right=None, top=None, wspace=None, hspace=None);
plt.show()

print("****************************************************")
topic = "3. Adding a background map"; print("** %s\n" % topic)

# A figure of all restaurants with background
fig, ax = plt.subplots()
ax.plot(df_restaurants.x, df_restaurants.y, marker='o', alpha=0.5, linestyle='None', markersize=1)
contextily.add_basemap(ax)
plt.xticks(fontsize=7); plt.yticks(fontsize=7);
plt.xlabel('Longitude'); plt.ylabel('Latitude'); # Labeling the axis.
plt.title('Restaurants in Paris'); plt.suptitle(topic);  # Setting the titles.
plt.subplots_adjust(left=0.2, bottom=None, right=None, top=None, wspace=None, hspace=None);
plt.show()

print("****************************************************")
topic = "4. Introduction to GeoPandas"; print("** %s\n" % topic)

df_countries_geo.plot()
plt.xlabel('Longitude'); plt.ylabel('Latitude'); # Labeling the axis.
plt.title('World Map'); plt.suptitle(topic);  # Setting the titles.
#plt.subplots_adjust(left=0.2, bottom=None, right=None, top=None, wspace=None, hspace=None);
plt.show()

df_countries_geo['area'] = df_countries_geo.geometry.area
print("Head of df_countries:\n{}\n".format(df_countries_geo.head()))

print("****************************************************")
topic = "5. Explore the Paris districts (I)"; print("** %s\n" % topic)

# Inspect the first rows
print("Head of df_paris_districts:\n{}\n".format(df_paris_districts_geo.head()))

# Make a quick visualization of the districts
df_paris_districts_geo.plot()
plt.xlabel('Longitude'); plt.ylabel('Latitude'); # Labeling the axis.
plt.title('Paris Districts'); plt.suptitle(topic);  # Setting the titles.
plt.subplots_adjust(left=0.2, bottom=None, right=None, top=None, wspace=None, hspace=None);
plt.show()

print("****************************************************")
topic = "6. Explore the Paris districts (II)"; print("** %s\n" % topic)

df_paris_districts_geo['area'] = df_paris_districts_geo.geometry.area
print("Head of df_paris_districts:\n{}\n".format(df_paris_districts_geo.head()))

print("****************************************************")
topic = "7. The Paris restaurants as a GeoDataFrame"; print("** %s\n" % topic)

# Convert it to a GeoDataFrame
df_restaurants_geo = gpd.GeoDataFrame(df_restaurants, geometry=gpd.points_from_xy(df_restaurants.x, df_restaurants.y))
print("Head of df_restaurants_geo:\n{}\n".format(df_restaurants_geo.head()))

# Make a plot of the restaurants
ax = df_restaurants_geo.plot(markersize=1)
contextily.add_basemap(ax)
plt.xlabel('Longitude'); plt.ylabel('Latitude'); # Labeling the axis.
plt.title('Restaurants in Paris'); plt.suptitle(topic);  # Setting the titles.
plt.subplots_adjust(left=0.2, bottom=None, right=None, top=None, wspace=None, hspace=None);
plt.show()

print("****************************************************")
topic = "8. Exploring and visualizing spatial data"; print("** %s\n" % topic)

#Filtering data
df_africa_geo = df_countries_geo[df_countries_geo.continent == 'Africa']
df_africa_geo.plot(color='red', edgecolor='black')
plt.xlabel('Longitude'); plt.ylabel('Latitude'); # Labeling the axis.
plt.title('Africa Continent'); plt.suptitle(topic);  # Setting the titles.
#plt.subplots_adjust(left=0.2, bottom=None, right=None, top=None, wspace=None, hspace=None);
plt.show()

#Coloring the world map
df_countries_geo.plot(column='continent', edgecolor='black')
plt.xlabel('Longitude'); plt.ylabel('Latitude'); # Labeling the axis.
plt.title('World Map (Coloring by continent)'); plt.suptitle(topic);  # Setting the titles.
#plt.subplots_adjust(left=0.2, bottom=None, right=None, top=None, wspace=None, hspace=None);
plt.show()

#Coloring the world map
df_countries_geo.plot(column='gdp_md_est', edgecolor='black')
plt.xlabel('Longitude'); plt.ylabel('Latitude'); # Labeling the axis.
plt.title('World Map (Coloring by gdp_md_est)'); plt.suptitle(topic);  # Setting the titles.
#plt.subplots_adjust(left=0.2, bottom=None, right=None, top=None, wspace=None, hspace=None);
plt.show()

#Multilayered plot
fig, ax = plt.subplots(figsize=(10,4))
df_countries_geo.plot(ax = ax)
df_cities_geo.plot(ax=ax, color='red', markersize=10)
ax.set_axis_off()
plt.xlabel('Longitude'); plt.ylabel('Latitude'); # Labeling the axis.
plt.title('Main cities in the world'); plt.suptitle(topic);  # Setting the titles.
#plt.subplots_adjust(left=0.2, bottom=None, right=None, top=None, wspace=None, hspace=None);
plt.show()

print("****************************************************")
topic = "9. Visualizing the population density"; print("** %s\n" % topic)

df_paris_districts_geo['population_density'] = df_paris_districts_geo.population / df_paris_districts_geo.area * (10**6) # Add a population density column

# Make a plot of the districts colored by the population density
fig, ax = plt.subplots(figsize=(10,4))
base = df_paris_districts_geo.plot(ax = ax, column='population_density', legend=True)
#ax.set_anchor('N');
#Changing the fontsize of the color bar: (Source: https://gist.github.com/sebbacon/60ceec549f1d461af4543ccc5024c095?short_path=839cef5)
#     The Figure has two Axes: one for the map, and one for the Colorbar. The one we care about is the second one.
#     cb_ax = fig.axes[1] #Axes for the colorbar.
#     The legend is actually a Colorbar object. To change the legend's font size, we have to get hold of the Colorbar's
#     Axes object, and call .tick_params() on that.
fig.axes[1].tick_params(labelsize=7) #Changing the fontsize of the colorbar in second axes of the graph.
plt.xticks(fontsize=7); plt.yticks(fontsize=7);
plt.xlabel('Longitude', fontsize=7); plt.ylabel('Latitude', fontsize=7); # Labeling the axis.
plt.title('Density population in Paris'); plt.suptitle(topic);  # Setting the titles.
#plt.subplots_adjust(left=0.2, bottom=None, right=None, top=None, wspace=None, hspace=None);
plt.show()

print("****************************************************")
topic = "10. Using pandas functionality: groupby"; print("** %s\n" % topic)

restaurants_type_counts = df_restaurants_geo.groupby('type').size() # Calculate the number of restaurants of each type

print("Restaurants by type (Using groupb)y:\n{}\n".format(restaurants_type_counts)) # Print the result
print("Restaurants by type (Using value_counts method):\n{}\n".format(df_restaurants_geo['type'].value_counts())) # Print the result

print("****************************************************")
topic = "11. Plotting multiple layers"; print("** %s\n" % topic)

# Take a subset of the African restaurants
df_african_restaurants_geo = df_restaurants_geo[df_restaurants_geo['type']=='African restaurant']

# Make a multi-layered plot
fig, ax = plt.subplots(figsize=(10, 5))
df_restaurants_geo.plot(ax=ax, color='darkgreen', markersize=1)
df_african_restaurants_geo.plot(ax=ax, color='red', markersize=3)
ax.set_axis_off()
contextily.add_basemap(ax)
plt.title('African Restaurants in Paris'); plt.suptitle(topic);  # Setting the titles.
plt.show()

#Making one more example:
#Source: http://datos.mop.gob.sv/?q=search/field_topic/proyectos-de-inversi%C3%B3n-6
filename = "SV_proyectos_MOP.csv"
df_mop_sv = pd.read_csv(filename)
print("Columns of {}:\n{}\n".format(filename, df_mop_sv.columns))
df_mop_sv_geo = gpd.GeoDataFrame(df_mop_sv, geometry=gpd.points_from_xy(df_mop_sv.LONGITUD, df_mop_sv.LATITUD), crs={'init': 'epsg:4326'})
print("Columns of df_mop_sv_geo:\n{}\n".format(df_mop_sv_geo.columns))
gpd.GeoDataFrame.crs = {'init': 'epsg:4326'}
df_mop_sv_geo = df_mop_sv_geo.to_crs(epsg = 3857)

#print(dir(contextily.tile_providers)) # To use in url=contextily.tile_providers.OSM_A
#print(dir(contextily.providers))      # To use in url=contextily.providers.Stamen.TonerLite

# Make a multi-layered plot
ax = df_mop_sv_geo.plot(color='red', figsize=(10, 5))
contextily.add_basemap(ax) #, url=contextily.providers.Stamen.TonerLite)
plt.xticks(fontsize=7); plt.yticks(fontsize=7);
plt.xlabel('Longitude', fontsize=7); plt.ylabel('Latitude', fontsize=7); # Labeling the axis.
plt.title('Proyectos MOP en Ejecución (El Salvador 2018)'); plt.suptitle(topic);  # Setting the titles.
plt.show()

print("****************************************************")
print("** END                                            **")
print("****************************************************")

#import contextily                                                             #To add a background web map to our plot
#import inspect                                                                #Used to get the code inside a function
#import folium                                                                 #To create map street folium.__version__'0.10.0'
#import geopandas         as gpd                                               #For working with geospatial data
#import matplotlib        as mpl                                               #To format numbers with ax.yaxis.set_major_formatter(mpl.ticker.StrMethodFormatter('{x:,.0f}')) or ax.get_xaxis().set_major_formatter(matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ',')))
#import matplotlib.pyplot as plt                                               #For creating charts
#import numpy             as np                                                #For making operations in lists
#import pandas            as pd                                                #For loading tabular data
#import seaborn           as sns                                               #For visualizing data
#import pprint                                                                 #Import pprint to format disctionary output
#import missingno         as msno                                              #Missing data visualization module for Python

#import os                                                                     #To raise an html page in python command
#import tempfile                                                               #To raise an html page in python command
#import webbrowser                                                             #To raise an html page in python command

#import calendar                                                               #For accesing to a vary of calendar operations
#import math                                                                   #For accesing to a complex math operations
#import nltk                                                                   #For working with text data
#import random                                                                 #For generating random numbers
#import re                                                                     #For regular expressions
#import tabula                                                                 #For extracting tables from pdf
#import timeit                                                                 #For Measure execution time of small code snippets
#import time                                                                   #To measure the elapsed wall-clock time between two points
#import scykit-learn                                                           #For performing machine learning
#import warnings
#import wikipedia

#from collections                     import defaultdict                       #Returns a new dictionary-like object
#from datetime                        import date                              #For obteining today function
#from datetime                        import datetime                          #For obteining today function
#from functools                       import reduce                            #For accessing to a high order functions (functions or operators that return functions)
#from glob                            import glob                              #For using with pathnames matching
#from itertools                       import combinations                      #For iterations
#from itertools                       import cycle                             #Used in the function plot_labeled_decision_regions()
#from math                            import ceil                              #Used in the function plot_labeled_decision_regions()
#from math                            import floor                             #Used in the function plot_labeled_decision_regions()
#from math                            import radian                            #For accessing a specific math operations
#from mpl_toolkits.mplot3d            import Axes3D
#from pandas.api.types                import CategoricalDtype                  #For categorical data
#from pandas.plotting                 import parallel_coordinates              #For Parallel Coordinates
#from pandas.plotting                 import register_matplotlib_converters    #For conversion as datetime index in x-axis
#from shapely.geometry                import Point                             #(Geospatial) To create a point geometry column
#from string                          import Template                          #For working with string, regular expressions

#from bokeh.io                        import curdoc                            #For interacting visualizations
#from bokeh.io                        import output_file                       #For interacting visualizations
#from bokeh.io                        import show                              #For interacting visualizations
#from bokeh.plotting                  import ColumnDataSource                  #For interacting visualizations
#from bokeh.plotting                  import figure                            #For interacting visualizations
#from bokeh.layouts                   import column                            #For interacting visualizations
#from bokeh.layouts                   import gridplot                          #For interacting visualizations
#from bokeh.layouts                   import row                               #For interacting visualizations
#from bokeh.layouts                   import widgetbox                         #For interacting visualizations
#from bokeh.models                    import Button                            #For interacting visualizations
#from bokeh.models                    import CategoricalColorMapper            #For interacting visualizations
#from bokeh.models                    import CheckboxGroup                     #For interacting visualizations
#from bokeh.models                    import ColumnDataSource                  #For interacting visualizations
#from bokeh.models                    import HoverTool                         #For interacting visualizations
#from bokeh.models                    import RadioGroup                        #For interacting visualizations
#from bokeh.models                    import Select                            #For interacting visualizations
#from bokeh.models                    import Slider                            #For interacting visualizations
#from bokeh.models                    import Toggle                            #For interacting visualizations
#from bokeh.models.widgets            import Panel                             #For interacting visualizations
#from bokeh.models.widgets            import Tabs                              #For interacting visualizations
#from bokeh.palettes                  import Spectral6                         #For interacting visualizations

#import keras                                                                  #For DeapLearning
#import keras.backend as k                                                     #For DeapLearning
#from keras.applications.resnet50     import decode_predictions                #For DeapLearning
#from keras.applications.resnet50     import preprocess_input                  #For DeapLearning
#from keras.applications.resnet50     import ResNet50                          #For DeapLearning
#from keras.callbacks                 import EarlyStopping                     #For DeapLearning
#from keras.callbacks                 import ModelCheckpoint                   #For DeapLearning
#from keras.datasets                  import fashion_mnist                     #For DeapLearning
#from keras.datasets                  import mnist                             #For DeapLearning
#from keras.layers                    import BatchNormalization                #For DeapLearning
#from keras.layers                    import Concatenate                       #For DeapLearning
#from keras.layers                    import Conv2D                            #For DeapLearning
#from keras.layers                    import Dense                             #For DeapLearning
#from keras.layers                    import Dropout                           #For DeapLearning
#from keras.layers                    import Embedding                         #For DeapLearning
#from keras.layers                    import Flatten                           #For DeapLearning
#from keras.layers                    import GlobalMaxPooling1D                #For DeapLearning
#from keras.layers                    import Input                             #For DeapLearning
#from keras.layers                    import LSTM                              #For DeapLearning
#from keras.layers                    import MaxPool2D                         #For DeapLearning
#from keras.layers                    import SpatialDropout1D                  #For DeapLearning
#from keras.layers                    import Subtract                          #For DeapLearning
#from keras.models                    import load_model                        #For DeapLearning
#from keras.models                    import Model                             #For DeapLearning
#from keras.models                    import Sequential                        #For DeapLearning
#from keras.optimizers                import Adam                              #For DeapLearning
#from keras.optimizers                import SGD                               #For DeapLearning
#from keras.preprocessing             import image                             #For DeapLearning
#from keras.preprocessing.text        import Tokenizer                         #For DeapLearning
#from keras.preprocessing.sequence    import pad_sequences                     #For DeapLearning
#from keras.utils                     import plot_model                        #For DeapLearning
#from keras.utils                     import to_categorical                    #For DeapLearning
#from keras.wrappers.scikit_learn     import KerasClassifier                   #For DeapLearning

#import networkx          as nx                                                #For Network Analysis in Python
#import nxviz             as nv                                                #For Network Analysis in Python
#from nxviz                           import ArcPlot                           #For Network Analysis in Python
#from nxviz                           import CircosPlot                        #For Network Analysis in Python
#from nxviz                           import MatrixPlot                        #For Network Analysis in Python

#import scipy.stats as stats                                                   #For accesign to a vary of statistics functiosn
#from scipy.cluster.hierarchy         import dendrogram                        #For learning machine - unsurpervised
#from scipy.cluster.hierarchy         import fcluster                          #For learning machine - unsurpervised
#from scipy.cluster.hierarchy         import linkage                           #For learning machine - unsurpervised
#from scipy.ndimage                   import gaussian_filter                   #For working with images
#from scipy.ndimage                   import median_filter                     #For working with images
#from scipy.signal                    import convolve2d                        #For learning machine - deep learning
#from scipy.sparse                    import csr_matrix                        #For learning machine
#from scipy.special                   import expit as sigmoid                  #For learning machine
#from scipy.stats                     import pearsonr                          #For learning machine
#from scipy.stats                     import randint                           #For learning machine

#from skimage                         import exposure                          #For working with images
#from skimage                         import measure                           #For working with images
#from skimage.filters.thresholding    import threshold_otsu                    #For working with images
#from skimage.filters.thresholding    import threshold_local                   #For working with images

#from sklearn                         import datasets                          #For learning machine
#from sklearn.cluster                 import KMeans                            #For learning machine - unsurpervised
#from sklearn.decomposition           import NMF                               #For learning machine - unsurpervised
#from sklearn.decomposition           import PCA                               #For learning machine - unsurpervised
#from sklearn.decomposition           import TruncatedSVD                      #For learning machine - unsurpervised
#from sklearn.ensemble                import AdaBoostClassifier                #For learning machine - surpervised
#from sklearn.ensemble                import BaggingClassifier                 #For learning machine - surpervised
#from sklearn.ensemble                import GradientBoostingRegressor         #For learning machine - surpervised
#from sklearn.ensemble                import RandomForestClassifier            #For learning machine
#from sklearn.ensemble                import RandomForestRegressor             #For learning machine - unsurpervised
#from sklearn.ensemble                import VotingClassifier                  #For learning machine - unsurpervised
#from sklearn.feature_selection       import chi2                              #For learning machine
#from sklearn.feature_selection       import SelectKBest                       #For learning machine
#from sklearn.feature_extraction.text import CountVectorizer                   #For learning machine
#from sklearn.feature_extraction.text import HashingVectorizer                 #For learning machine
#from sklearn.feature_extraction.text import TfidfVectorizer                   #For learning machine - unsurpervised
#from sklearn.impute                  import SimpleImputer                     #For learning machine
#from sklearn.linear_model            import ElasticNet                        #For learning machine
#from sklearn.linear_model            import Lasso                             #For learning machine
#from sklearn.linear_model            import LinearRegression                  #For learning machine
#from sklearn.linear_model            import LogisticRegression                #For learning machine
#from sklearn.linear_model            import Ridge                             #For learning machine
#from sklearn.manifold                import TSNE                              #For learning machine - unsurpervised
#from sklearn.metrics                 import accuracy_score                    #For learning machine
#from sklearn.metrics                 import classification_report             #For learning machine
#from sklearn.metrics                 import confusion_matrix                  #For learning machine
#from sklearn.metrics                 import mean_squared_error as MSE         #For learning machine
#from sklearn.metrics                 import roc_auc_score                     #For learning machine
#from sklearn.metrics                 import roc_curve                         #For learning machine
#from sklearn.model_selection         import cross_val_score                   #For learning machine
#from sklearn.model_selection         import GridSearchCV                      #For learning machine
#from sklearn.model_selection         import KFold                             #For learning machine
#from sklearn.model_selection         import RandomizedSearchCV                #For learning machine
#from sklearn.model_selection         import train_test_split                  #For learning machine
#from sklearn.multiclass              import OneVsRestClassifier               #For learning machine
#from sklearn.neighbors               import KNeighborsClassifier as KNN       #For learning machine
#from sklearn.pipeline                import FeatureUnion                      #For learning machine
#from sklearn.pipeline                import make_pipeline                     #For learning machine - unsurpervised
#from sklearn.pipeline                import Pipeline                          #For learning machine
#from sklearn.preprocessing           import FunctionTransformer               #For learning machine
#from sklearn.preprocessing           import Imputer                           #For learning machine
#from sklearn.preprocessing           import MaxAbsScaler                      #For learning machine (transforms the data so that all users have the same influence on the model)
#from sklearn.preprocessing           import Normalizer                        #For learning machine - unsurpervised (for pipeline)
#from sklearn.preprocessing           import normalize                         #For learning machine - unsurpervised
#from sklearn.preprocessing           import scale                             #For learning machine
#from sklearn.preprocessing           import StandardScaler                    #For learning machine
#from sklearn.svm                     import SVC                               #For learning machine
#from sklearn.tree                    import DecisionTreeClassifier            #For learning machine - supervised
#from sklearn.tree                    import DecisionTreeRegressor             #For learning machine - supervised

#import statsmodels             as sm                                          #For stimations in differents statistical models
#import statsmodels.api         as sm                                          #Make a prediction model
#import statsmodels.formula.api as smf                                         #Make a prediction model

#import tensorflow              as tf                                          #For DeapLearning

# Setting the pandas options
#pd.set_option("display.max_columns",20)
#pd.options.display.float_format = '{:,.4f}'.format
#pd.reset_option("all")
#pd.set_option('display.max_rows', -1)                                         #Shows all rows

#register_matplotlib_converters()                                              #Require to explicitly register matplotlib converters.

#Setting images params
#plt.rcParams = plt.rcParamsDefault
#plt.rcParams['figure.constrained_layout.use'] = True
#plt.rcParams['figure.constrained_layout.h_pad'] = 0.09
#plt.rcParams.update({'figure.max_open_warning': 0})                           #To solve the max images open
#plt.rcParams["axes.labelsize"] = 8                                            #Font
#plt.rc('xtick',labelsize=8)
#plt.rc('ytick',labelsize=6)
#plt.rcParams['figure.max_open_warning'] = 60                                  #params = {'legend.fontsize': 'x-large', 'figure.figsize': (15, 5), 'axes.labelsize': 'x-large', 'axes.titlesize':'x-large', 'xtick.labelsize':'x-large', 'ytick.labelsize':'x-large'}
#plt.rcParams["legend.fontsize"] = 8
#plt.style.use('dark_background')
#plt.style.use('default')
#plt.xticks(fontsize=7); plt.yticks(fontsize=8);
#plt.xticks(rotation=45)

#from matplotlib.axes._axes import _log as matplotlib_axes_logger              #To avoid warnings
#matplotlib_axes_logger.setLevel('ERROR')
#matplotlib_axes_logger.setLevel(0)                                            #To restore default

#ax.tick_params(labelsize=6)                                                   #axis : {'x', 'y', 'both'}
#ax.tick_params(axis='x', rotation=45)                                         #Set rotation atributte

#Setting the numpy options
#np.set_printoptions(precision=3)                                              #precision set the precision of the output:
#np.set_printoptions(suppress=True)                                            #suppress suppresses the use of scientific notation for small numbers
#np.set_printoptions(threshold=np.inf)                                         #Show all the columns and rows from an array.
#np.set_printoptions(threshold=8)                                              #Return to default value.
#np.random.seed(SEED)

#tf.compat.v1.set_random_seed(SEED)                                            #Instead of tf.set_random_seed, because it is deprecated.

#sns.set(font_scale=0.8)                                                       #Font
#sns.set(rc={'figure.figsize':(11.7,8.27)})                                    #To set the size of the plot
#sns.set(color_codes=True)                                                     #Habilita el uso de los codigos de color
#sns.set()                                                                     #Seaborn defult style
#sns.set_style(this_style)                                                     #['white', 'dark', 'whitegrid', 'darkgrid', 'ticks']:
#sns.despine(left=True)                                                        #Remove the spines (all borders)
#sns.palettes.SEABORN_PALETTES                                                 #Despliega todas las paletas disponibles
#sns.palplot(sns.color_palette())                                              #Display a palette
#sns.color_palette()                                                           #The current palette
#sns.set(style=”whitegrid”, palette=”pastel”, color_codes=True)
#sns.mpl.rc(“figure”, figsize=(10,6))

#warnings.filterwarnings('ignore', 'Objective did not converge*')              #To avoid the warning, review https://github.com/scikit-learn/scikit-learn/issues/13394
#warnings.filterwarnings('default', 'Objective did not converge*')             #To avoid the warning, review https://github.com/scikit-learn/scikit-learn/issues/13394

#Create categorical type data to use
#cats = CategoricalDtype(categories=['good', 'bad', 'worse'],  ordered=True)
# Change the data type of 'rating' to category
#weather['rating'] = weather.rating.astype(cats)

#print("The area of your rectangle is {}cm\u00b2".format(area))                 #Print the superscript 2

### Show a basic html page
#tmp=tempfile.NamedTemporaryFile()
#path=tmp.name+'.html'
#f=open(path, 'w')
#f.write("<html><body><h1>Test</h1></body></html>")
#f.close()
#webbrowser.open('file://' + path)

Working with Geospatial Data in Python/01_Introduction_to_geospatial_vector_data.py


from random import randint

itens = ['Pedra', 'Papel', 'Tesoura']

jogador = int(input('''Escolha entre:
0 - Pedra
1 - Papel
2 - Tesoura\n\n'''))

maquina = randint(0, 2)

print('-='*11)
print(f'Você jogou {itens[jogador]}\nA máquina escolheu {itens[maquina]}')
print('-='*11)

if(jogador == 0 and maquina == 2):
    print('Você ganhou! Pedra ganha de tesoura')
elif (jogador == 1 and maquina == 0):
    print('Você ganhou! Papel ganha de pedra')
elif (jogador == 2 and maquina == 1):
    print('Você ganhou! Tesoura ganha de papel')
elif jogador == maquina:
    print('Empate')
else:
    print('Você perdeu')


# importation
import discord
from discord.ext import commands
from discord.ext import tasks
import time

from variable import *

# Définition des permission (intents)
intents = discord.Intents.default()
intents.message_content = True
intents.presences = True
bot = commands.Bot(command_prefix='!', intents=intents)

# Définition de la tache en arrière-plan
@tasks.loop(seconds=10)
async def my_background_task():
    Joueur_en_linge = statu_serveur()

    # Si joueur en linge passé en actif (vert) est afficher le nombre de joueur
    if Joueur_en_linge >= 1 :
        await bot.change_presence(status=discord.Status.online, activity=discord.Game(name=f"{Joueur_en_linge} joueurs en linge"))

    # si il y a pas de joueur en linge passer le Bot en inactif (jaune) est afficher le nombre de joueur
    elif Joueur_en_linge == 0 :
        await bot.change_presence(status=discord.Status.idle, activity=discord.Game(name=f"{Joueur_en_linge} joueurs en linge"))

    # Sinon passer en ne pas déranger (rouge) est afficher erreur
    else :
        await bot.change_presence(status=discord.Status.dnd, activity=discord.Game(name="erreur"))

@tasks.loop(seconds=10)
async def my_background_task_2(message):
    await message.edit(content=f"Il y a {statu_serveur()} joueur connecter sur le serveur  ")

@bot.event
async def on_ready():
    # Démarrage de la tache en arrière-plan
    my_background_task.start()

# Commande de test de fonctionnement
@bot.command()
async def ping(ctx):
    msg = await ctx.send('pong')

# Commande pour afficher le statu du serveur en version textuelle
@bot.command()
async def serveur(message_info) :
    # envoi tu message de base
    message = await message_info.send("go")

    # Démarrage de la tache en arrière-plan
    my_background_task_2.start(message)

bot.run('TOKEN')


import tensorflow as tf
from tensorflow.keras import layers
import tensorflow_addons as tfa

from utils import CustomLayer, compute_factors
from attention import SqueezeExcite, MHSA3D, AbsPosEmb

def down_stack(x, filters, nblocks, block, strides=1, frac_dv=0, **kwargs):
    x = block(filters, frac_dv=frac_dv, strides=strides, **kwargs)(x)
    for i in range(1, nblocks):
        x = block(filters, frac_dv=frac_dv, **kwargs)(x)
    return x

def up_stack(x, skip, filters, nblocks, block, strides=1, frac_dv=0, **kwargs):
    if strides > 1:
        x = layers.UpSampling3D(data_format="channels_first")(x)
    x = layers.Concatenate(axis=1)([x, skip])

    for i in range(nblocks):
        x = block(filters, frac_dv=frac_dv, **kwargs)(x)
    return x

def hard_sigmoid(x):
    return tf.keras.activations.relu((x + 3.), max_value=6.) * (1. / 6.)

def hard_swish(x):
    return hard_sigmoid(x) * x

class NormAct(CustomLayer):
    def __init__(self, activation=tf.nn.leaky_relu, norm='gn', gn_grps=8, **kwargs):
        super().__init__(**kwargs)
        self.save_inits(locals())
        if norm == 'gn':
            # gn_grps = compute_factors(gn_grps, filters, gn_grps)
            self.norm = tfa.layers.GroupNormalization(groups=gn_grps, axis=1)
        else:
            self.norm = layers.BatchNormalization(axis=1)
        if activation == 'leaky_relu':
            activation = tf.nn.leaky_relu
        elif activation == 'hard_swish':
            activation =  hard_swish
        self.act = layers.Activation(activation)

    def call(self, inp):
        x = self.norm(inp)
        x = self.act(x)
        return x

class ConvNorm(CustomLayer):
    def __init__(self, filters, kernel_size=3, strides=1, groups=1, deconv=False, padding='same', use_bias=True,
                 activation=tf.nn.leaky_relu, do_norm_act=True, norm='gn', gn_grps=8, **kwargs):
        super().__init__(**kwargs)
        self.save_inits(locals())
        self.filters = filters
        self.kernel_size = kernel_size
        self.strides = strides
        self.padding = padding
        self.use_bias = use_bias
        self.groups = groups
        self.do_norm_act = do_norm_act
        self.activation = activation
        self.norm = norm
        self.gn_grps = gn_grps
        if deconv:
            print("[!] DeConv not ported yet.")

    def build(self, input_shape):
        in_filters = input_shape[1]
        self.lyrs = list()
        self.groups = compute_factors(in_filters, self.filters, self.groups) # just to make sure filters divisible by groups
        bias_state = (not self.do_norm_act) and self.use_bias
        self.lyrs.append(layers.Conv3D(self.filters, kernel_size=self.kernel_size, strides=self.strides, padding=self.padding,
                                       use_bias=bias_state , data_format="channels_first", groups=self.groups))
        if self.do_norm_act:
            self.lyrs.append(NormAct(activation=self.activation, norm=self.norm, gn_grps=self.gn_grps))

    def call(self, inp):
        x = inp
        for lyr in self.lyrs:
            x = lyr(x)
        return x

class AttnBottleneckBlock(CustomLayer):
    def __init__(self, filters, strides=1, activation=tf.nn.relu, expansion=4, dp_rate=0, dropout_type='Spatial',
                 groups=1, norm='gn', squeeze_attn=True, frac_dv=0, nheads=8, downsample_method="pool" , **kwargs):
        super().__init__(**kwargs)
        self.save_inits(locals())
        self.filters = filters
        self.expansion = expansion
        self.strides = strides
        self.out_filters = filters*expansion
        self.activation = activation
        self.groups = groups
        self.norm = norm
        self.squeeze_attn = squeeze_attn
        self.dropout = None
        self.dv = int(filters*frac_dv)
        self.conv_filters = filters - self.dv
        self.nheads = nheads
        self.downsample_method = downsample_method
        self.norm_act = NormAct(activation=activation, norm=norm)
        if dp_rate:
            if dropout_type == 'Spatial':
                self.dropout = layers.SpatialDropout3D(dp_rate, data_format="channels_first")
            else:
                self.dropout = layers.Dropout(dp_rate)

    def build(self, input_shape):
        self.shortcut = self.get_shortcut(input_shape)
        self.net = self.get_net(input_shape)

    def get_shortcut(self, input_shape):
        in_filters = input_shape[1]
        # operations for shortcut
        self.short_inp = True              # to decide input for shortcut, based on preact, filters and stride.
        shortcut = tf.keras.Sequential()

        if self.strides>1:
            shortcut.add(layers.AveragePooling3D(self.strides, data_format="channels_first"))
        if in_filters != self.out_filters:
            self.short_inp = False
            shortcut.add(ConvNorm(self.out_filters, kernel_size=1, strides=1, do_norm_act=False))
        return shortcut

    def get_net(self, input_shape):
        inp = layers.Input(shape=input_shape[1:])
        # Main bottleneck network
        x = ConvNorm(self.filters, kernel_size=1, activation=self.activation, norm=self.norm)(inp)

        conv_strides = self.strides
        c_x = x
        if self.strides > 1:
            x = layers.AveragePooling3D(self.strides, data_format="channels_first")(x)
            if self.downsample_method == "pool":
                conv_strides = 1
                c_x = x

        if self.conv_filters > 0:
            x_s = ConvNorm(self.conv_filters, kernel_size=3, strides=conv_strides, do_norm_act=False,
                           use_bias=False, groups=self.groups)(c_x)
        if self.dv > 0:
            x = MHSA3D(dv=self.dv, nheads=self.nheads)(x)
            x_s = layers.Concatenate(axis=1)([x, x_s]) if self.conv_filters > 0 else x

        x = NormAct(activation=self.activation, norm=self.norm)(x_s)

        if self.squeeze_attn and self.dv==0:
            x = SqueezeExcite()(x)
        if self.dropout is not None:
            x = self.dropout(x)

        x = ConvNorm(self.out_filters, kernel_size=1, do_norm_act=False)(x)
        return tf.keras.Model(inputs=inp, outputs=x)

    def call(self, inp):
        x = inp
        x = self.norm_act(x)    # pre-act

        identity = self.shortcut(inp if self.short_inp else x)

        x = self.net(x)
        x = x + identity
        return x

class BasicBlock(AttnBottleneckBlock):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.out_filters = self.filters

    def get_net(self, input_shape):
        inp = layers.Input(shape=input_shape[1:])

        x = ConvNorm(self.filters, kernel_size=3, strides=self.strides, activation=self.activation, norm=self.norm,
                     groups=self.groups)(inp)
        if self.squeeze_attn:
            x = SqueezeExcite()(x)
        if self.dropout is not None:
            x = self.dropout(x)
        x = ConvNorm(self.out_filters, kernel_size=3, do_norm_act=False)(x)

        return tf.keras.Model(inputs=inp, outputs=x)

class InvertedResBlock(AttnBottleneckBlock):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.out_filters = self.filters
        self.exp_filters = self.filters * self.expansion

    def get_net(self, input_shape):
        inp = layers.Input(shape=input_shape[1:])

        x = ConvNorm(self.exp_filters, kernel_size=1, activation=self.activation, norm=self.norm)(inp)
        x = ConvNorm(self.exp_filters, kernel_size=3, strides=self.strides, activation=self.activation, norm=self.norm,
                     groups=self.exp_filters)(x)
        if self.squeeze_attn:
            x = SqueezeExcite()(x)
        if self.dropout is not None:
            x = self.dropout(x)
        x = ConvNorm(self.out_filters, kernel_size=1, activation=self.activation, norm=self.norm)(x)

        return tf.keras.Model(inputs=inp, outputs=x)

    def get_shortcut(self, input_shape):
        in_filters = input_shape[1]
        # operations for shortcut
        shortcut = tf.keras.Sequential()

        if self.strides>1:
            shortcut.add(layers.AveragePooling3D(self.strides, data_format="channels_first"))
        if in_filters != self.out_filters:
            shortcut.add(ConvNorm(self.out_filters, kernel_size=1, activation=self.activation, norm=self.norm))
        return shortcut

    def call(self, inp):
        x = inp

        identity = self.shortcut(x)

        x = self.net(x)
        x = x + identity
        return x


class Poly():

    text_on = False
    drag = -1
    drag_hole = -1
    drag_drag_pt = -1

    def __init__(self, outer_pts, holes=[[(0, 0)]]):
        self.outer_pts = outer_pts
        self.holes = holes

    def plot(self, x_offset, y_offset, cell_size):
        pushStyle()
        if len(self.outer_pts) >= 3:
            fill(255)
            beginShape()
            for x, y in self.outer_pts:
                stroke(0)
                sx = (x + x_offset) * cell_size
                sy = (y + y_offset) * cell_size
                vertex(sx, sy)
            for h in self.holes:
              beginContour()
              for x, y in h:
                sx = (x + x_offset) * cell_size
                sy = (y + y_offset) * cell_size
                vertex(sx, sy)
              endContour()
            endShape(CLOSE)
        Poly.annotate_pts(self.outer_pts, color(200, 0, 0), 5)
        Poly.annotate_pts(self.holes[0], color(0, 0, 200), 5)
        popStyle()

        def remove_pt(self, i, j):
            pass

    @classmethod
    def annotate_pts(cls, pts, c, scale_m=1):
        if Poly.text_on:
            strokeWeight(5)
            textSize(16)
            fill(c)
            stroke(c)
            for i, j in pts:
                x, y = (i + x_offset) * cell_size, (j + y_offset) * cell_size
                point(x, y)
                text(str((i * scale_m, j * scale_m)), x, y)


import uuid

from flask import Response, flash, redirect, render_template, request, url_for
from functools import wraps

from ..db import Playlist

from . import frontend

@frontend.route("/playlist")
def playlist_index():
    return render_template(
        "playlists.html",
        mine=Playlist.select().where(Playlist.user == request.user),
        others=Playlist.select().where(Playlist.user != request.user, Playlist.public),
    )

def resolve_and_inject_playlist(func):
    @wraps(func)
    def decorated(uid):
        try:
            uid = uuid.UUID(uid)
        except ValueError:
            flash("Invalid playlist id")
            return redirect(url_for("frontend.playlist_index"))

        try:
            playlist = Playlist[uid]
        except Playlist.DoesNotExist:
            flash("Unknown playlist")
            return redirect(url_for("frontend.playlist_index"))

        return func(uid, playlist)

    return decorated

@frontend.route("/playlist/<uid>")
@resolve_and_inject_playlist
def playlist_details(uid, playlist):
    return render_template("playlist.html", playlist=playlist)

@frontend.route("/playlist/<uid>/export")
@resolve_and_inject_playlist
def playlist_export(uid, playlist):
    return Response(
        render_template("playlist_export.m3u", playlist=playlist),
        mimetype="audio/mpegurl",
        headers={"Content-disposition": f"attachment; filename={playlist.name}.m3u"},
    )

@frontend.route("/playlist/<uid>", methods=["POST"])
@resolve_and_inject_playlist
def playlist_update(uid, playlist):
    if playlist.user_id != request.user.id:
        flash("You're not allowed to edit this playlist")
    elif not request.form.get("name"):
        flash("Missing playlist name")
    else:
        playlist.name = request.form.get("name")
        playlist.public = request.form.get("public") in (
            True,
            "True",
            1,
            "1",
            "on",
            "checked",
        )
        playlist.save()
        flash("Playlist updated.")

    return playlist_details(str(uid))

@frontend.route("/playlist/del/<uid>")
@resolve_and_inject_playlist
def playlist_delete(uid, playlist):
    if playlist.user_id != request.user.id:
        flash("You're not allowed to delete this playlist")
    else:
        playlist.delete_instance()
        flash("Playlist deleted")

    return redirect(url_for("frontend.playlist_index"))


# on windows:
# set VS90COMNTOOLS=%VS100COMNTOOLS%
# python setup.py build_ext --compiler=msvc

from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import glob
from distutils.ccompiler import new_compiler

sources = glob.glob('../source/*.cpp')
sources.append('terran.pyx')

if new_compiler().compiler_type == 'msvc':
    compile_args = ['/openmp']
    link_args = ['']
else:
    compile_args = ['-fopenmp']
    link_args = ['-lgomp']

ext_modules = [Extension('terran',
                        include_dirs = ['../include'],
                        language = 'c++',
                        sources = sources,
                        define_macros = [('TERRAN_BUILDING_SHARED_LIBRARY', '1')],
                        extra_compile_args = compile_args,
                        extra_link_args = link_args,
                        )]

setup(
    name = 'TERRAN',
    cmdclass = {'build_ext': build_ext},
    ext_modules = ext_modules
)


from flask import Flask
from os.path import isfile
from sys import argv
from config import config
from model.EMS import EMS
from flask_login import LoginManager

app = Flask(__name__, static_url_path='/static')
app.config.from_object(config)

# init login_manager
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = "login"

@login_manager.user_loader
def load_user(email):
    return ems.getUserByEmail(email)

# instantiate EMS
ems = None

binFile = argv[1] if len(argv) > 1 else 'emsData.bin'
if len(argv) <= 1 and not isfile(binFile):
    ems = EMS(userCSV='user.csv', debug=type(config).__name__ == 'Development')
else:
    ems = EMS(binFile=binFile, debug=type(config).__name__ == 'Development')


##!/usr/bin/python

# Afficher les coordonnées GPS, la taille et l’adresse de l’arbre le plus grand.

#!/usr/bin/env python3
#-*- coding: utf-8 -*-
import sys
from pyspark import SparkContext

if __name__ == "__main__":

	# Creation d un contexte Spark
    sc = SparkContext(appName="Spark Count")
    sc.setLogLevel("ERROR") # Valid log levels include: ALL, DEBUG, ERROR, FATAL, INFO, OFF, TRACE, WARN

    tableau_ratings = sc.textFile(sys.argv[1]).map(lambda line: line.split(',')) # userId  movieId	rating
    tableau_movies = sc.textFile(sys.argv[2]).map(lambda line: line.split(','))

    paires_ratings = tableau_ratings.map(lambda champs: (champs[1],champs[2])) # movieId rating
    paires_movies = tableau_movies.map(lambda champs: (champs[0],champs[1])) # movieId title

    paires_ratings = paires_ratings.filter(lambda duet: duet[1]!='' and duet[1]!='rating') # on retire les valeurs manquantes et le titre
    paires_movies = paires_movies.filter(lambda duet: duet[0]!='movieId') # on retire le titre

    paires_ratings = paires_ratings.map(lambda champs: (champs[0],float(champs[1]))) # movieId rating

    paires_ratings_sum= paires_ratings.reduceByKey(lambda v1,v2 : v1+v2) # on  somme les notes de tous les films

    paires_ratings_count = tableau_ratings.map(lambda champs: (champs[1],1)) # movieId  1
    paires_ratings_count= paires_ratings_count.reduceByKey(lambda v1,v2 : v1+v2) # on  compte le nombre de fois où chaque film est noté

    threshold = float(sys.argv[3])
    paires_ratings_count = paires_ratings_count.filter(lambda pair: pair[1]>threshold) # on donne un nombre minimale de notation de film

    classement = paires_ratings_sum.join(paires_ratings_count) # movie id, (sum des ratings, count des ratings)
    classement = classement.map(lambda champs: (champs[1][0]/champs[1][1],(champs[0],champs[1][0],champs[1][1]))) # rapport sum/count,(movie id, sum des ratings, count des ratings)
    classement = classement.sortByKey(ascending=False) # classement décroissant par rapport sum/count
    classement_join = classement.map(lambda champs: (champs[1][0],(champs[0],champs[1][1],champs[1][2]))) # movie id,  (rapport sum/count,sum des ratings, count des ratings)

    classement_final = classement_join.join(paires_movies) # on join les 2 dataframes pour obtenir le nom des movies

    classement_final.saveAsTextFile("classement")

	# Arret du contexte Spark
    sc.stop()