import unittest
from setuptools import setup
try: # for pip >= 10
    from pip._internal.req import parse_requirements
    from pip._internal.download import PipSession
except ImportError: # for pip <= 9.0.3
    from pip.req import parse_requirements
    from pip.download import PipSession

################################################################################
def my_test_suite():
    test_loader = unittest.TestLoader()
    test_suite = test_loader.discover('argoslabs.mygroup.mycalc',
                                      pattern='test*.py')
    return test_suite

################################################################################
# parse_requirements() returns generator of pip.req.InstallRequirement objects
install_reqs = parse_requirements("argoslabs\\mygroup\\mycalc\\requirements.txt", session=PipSession())
reqs = [str(ir.req) for ir in install_reqs]
reqs.extend([])

setup(
    name='argoslabs.mygroup.mycalc',
    test_suite='setup.my_test_suite',
    packages=[
        'argoslabs','argoslabs.mygroup','argoslabs.mygroup.mycalc','argoslabs.mygroup.mycalc.tests'
    ],
    version='2.602.2002',
    description='ARGOS-LABS RPA plugin module sample',
    author='Jerry Chae',
    author_email='mcchae@argos-labs.com',
    url='https://www.argos-labs.com',
    license='ARGOS-LABS Proprietary License',
    keywords=['rpa', 'robot', 'module', 'mygroup', 'mycalc', 'argoslabs'],
    platforms=['Mac', 'Windows', 'Linux'],
    install_requires=reqs,
    python_requires='>=3.6',
    package_data={'argoslabs.mygroup.mycalc': ['icon.*', 'dumpspec.json']},
    zip_safe=False,
    classifiers=[
        'Build :: Date :: 2020-07-23 10:19',
        'Build :: Method :: alabs.ppm',
        'License :: Other/Proprietary License',
        'Natural Language :: English',
        'Operating System :: MacOS :: MacOS X',
        'Operating System :: Microsoft :: Windows :: Windows 10',
        'Operating System :: POSIX :: Linux',
        'Programming Language :: Python :: 3 :: Only',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
        'Topic :: Change :: Log :: Unittest for Linux',
        'Topic :: Change :: Log :: Unittest for Mac',
        'Topic :: Change :: Log :: Unittest for Windows',
        'Topic :: Demo :: HelloWorld',
        'Topic :: RPA',
    ],
    entry_points={
        'console_scripts': [
            'argoslabs.mygroup.mycalc=argoslabs.mygroup.mycalc:main',
        ],
    },
    include_package_data=True,
)


# -*- coding: utf-8 -*-
"""
Created on Wed May 20 09:53:47 2020

@author: Hui Zhou
"""

import torch
import torchvision
import numpy as np
import cv2

#test image
img_path = "../img/test.jpg"
img = cv2.imread(img_path)
img = cv2.resize(img, (224, 224))
img = np.transpose(img, (2, 0, 1)).astype(np.float32)
img = torch.from_numpy(img)
img = img.unsqueeze(0)

#pytorch test
model = torchvision.models.mobilenet_v2(pretrained=True)
model.eval()
output = model.forward(img)
val, cls = torch.max(output.data, 1)
print("[pytorch]--->predicted class: %d, predicted value: %.6f" % (cls.item(), val.item()))


from urllib import request,response,parse
from requests import Request
import json
import time
import random
import hashlib
import operator

while True:
    content = input('请输入需要翻译的内容(退出q/Q):')
    if(content != 'Q' and content != 'q') :
        url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'
        head = {}
        head['User-Agent']='Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36]'

        data = {}
        S = 'fanyideskweb'
        n = content
        r = str(int(time.time() * 1000) + random.randint(1, 10))
        D = 'ebSeFb%=XZ%T[KZ)c(sy!'

        sign = hashlib.md5((S + n + r + D).encode('utf-8')).hexdigest()

        data['i'] = content
        data['from'] = 'AUTO'
        data['to'] = 'AUTO'
        data['smartresult'] = 'dict'
        data['client'] = 'fanyideskweb'
        data['salt'] = r
        data['sign'] = sign
        data['doctype'] = 'json'
        data['version'] = '2.1'
        data['keyfrom'] = 'fanyi.web'
        data['action'] = 'FY_BY_CLICKBUTTION'
        data['typoResult'] = 'false'

        data = parse.urlencode(data).encode('utf-8')
        request1 = request.Request(url=url, data=data, method='POST')
        response1 = request.urlopen(request1)
        html=response1.read().decode('utf-8')
        target = json.loads(html)
        result = target['translateResult'][0][0]['tgt']
        print ('翻译的结果是:',result)
    else:
        print('退出翻译器')
        break


## advent of code 2018
## https://adventofcode.com/2018
## day 03
import re
import sys

from Map2D import *
claim_re = re.compile(r"#(\d+) @ (\d+),(\d+): (\d+)x(\d+)")
class Claim:
    def __init__(self, line):
        match = claim_re.search(line)
        self.id =  int(match.group(1))
        self.x = int(match.group(2))
        self.y = int(match.group(3))
        self.w = int(match.group(4))
        self.h = int(match.group(5))
    def coords(self):
        return rectangle_coords(self.x, self.y, self.w, self.h)

class Puzzle:
    def __init__(self, lines):
        self.claims = []
        for line in lines:
            self.claims.append(Claim(line))

        self.grid = InfiniteGrid()

    def part1(self):
        for claim in self.claims:
            for coord in claim.coords():
                self.grid[coord] = self.grid[coord] + 1

        result = len(list(filter(lambda x: x > 1, self.grid.map.values())))
        return result

    def part2(self):
        for claim in self.claims:
            found = True
            for coord in claim.coords():

                if self.grid[coord] > 1:
                    found = False
                    break
            if found:
                return claim.id

def parse_input(lines):
    return Puzzle(lines)

def part1(puzzle):

    return puzzle.part1()

def part2(puzzle):
    return puzzle.part2()


#!/usr/bin/env python3

from baseline import learner

import argparse
import time
import cProfile

def run():
    argparser = argparse.ArgumentParser(description='')
    argparser.add_argument("data_directory",
        help="""Location of User.csv, Items.csv, Interactions.csv,
                TargetItems.csv and TargetUsers.csv""")
    argparser.add_argument("-f", "--xfold",
        type=int,
        help="Value from 1-9 for cross validation of data.")
    argparser.add_argument("-n", "--name",
        default="submit" + str(time.time())[:10] + ".csv",
        help="Name for recommender file.")
    args = argparser.parse_args()

    start_time = time.time()
    if args.name == None or args.name == "":
        args.name = "submit" + str(start_time) + ".csv"

    (users, items,
     interactions,
     target_users,
     target_items) = learner.baseline_parse(args.data_directory)
    if args.xfold is None:
        bst = learner.baseline_learn(users, items, interactions, target_users, target_items)
        learner.baseline_predict(users, items, target_users, target_items, bst, args.name)
#    else:
#        cross_validate.fold10(interactions, args.xfold)

    print("--- TOTAL RECSYS TIME: %s SECONDS ---" % (time.time() - start_time))

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


import random

user_wins = 0
computer_wins = 0

# options variable to reduce redundancies
options =  ["rock", "paper", "scissors"]

while True:
    user_input = input("Type Rock/Paper/Scissors or Q to quit: ").lower()

    if user_input == "q":
        break

    # ensure valid user entry
    if user_input not in options:
        continue

    # generate random number to decide computers pick of rock/paper/scissors
    random_number = random.randint(0,2)

    # rock: 0, paper: 1, scissors: 2
    computer_pick = options[random_number]
    print("Computer picked", computer_pick + ".")

    # determine win conditions
    if user_input == "rock" and computer_pick == "scissors":
        print ("You won!")
        user_wins += 1

    elif user_input == "paper" and computer_pick == "rock":
        print ("You won!")
        user_wins += 1

    elif user_input == "scissors" and computer_pick == "paper":
        print ("You won!")
        user_wins += 1

    else:
        print("You lost!")
        computer_wins += 1

# fix this
print ("You won", user_wins, "times.")
print ("Computer won", computer_wins, "times.")
print ("Goodbye!")


print('Bem vindo ao 53')

print('Crie um programa que leia uma frase qualquer e diga se ela é um palindromo')

# Palavra que é lida tanto na frente quanto atrás e dá igual

frase = str(input('Informe uma frase')).strip().upper()
palavras = frase.split() # Aqui ela divide todas as palavras
juntas = ''.join(palavras)
inverso = ''
for letra in range(len(juntas)-1,-1,-1):
    inverso = inverso + juntas[letra]
print(juntas, inverso)
if inverso == juntas:
    print('Temos um palindromo')
else:
    print('Não é palindromo')


import pandas as pd
from pandas import DataFrame

data = pd.read_csv("all_games.csv")

games = pd.DataFrame(data, columns = ["game_id", "away", "home", "score_away", "score_home"])

games = games.drop_duplicates(['game_id'], keep='last')

games["away_wins"] = ""
games["away_lost"] = ""

for index, row in games.iterrows():
    if row["score_away"] > row["score_home"]:
        games.loc[index,'away_wins'] = 1
        games.loc[index,'away_lost'] = 0

    else:
        games.loc[index,'away_wins'] = 0
        games.loc[index,'away_lost'] = 1

games = games.drop(games.columns[[0, 2, 3, 4]], axis=1)

away_count = games.groupby("away").sum().reset_index()

for index, row in away_count.iterrows():
    print(row["away"])
    print(DataFrame(row).T)
    count_row = DataFrame(row).T
    file = row["away"] + ".csv"
    print(file)
    count_row.to_csv("form_away/"+file, index = False)


from typing import Any

class ErrorSetValue:
    def __init__(self, error, value=None, message=None, stackdelta=0):
        self.error: Exception = error
        self.value: Any = value
        self.message: str = message
        self.stackdelta = stackdelta

    def __repr__(self) -> str:
        return "<ErrorSetValue {}\n    {}\n    {}>".format(
            self.error, self.message, self.value
        )

    def displays(self):
        from machaon.types.stacktrace import ErrorObject
        err = ErrorObject(self.error)
        for l in err.short_display(self.stackdelta).splitlines():
            yield "    " + l

        if self.value is None and self.message is None:
            return

        parts = []
        if self.value is not None:
            if isinstance(self.value, (list, tuple)):
                parts.append("{}".format(self.value))
            else:
                parts.append("({})".format(self.value))
        if self.message is not None:
            parts.append(self.message)
        yield " ".join(parts)

class ErrorSet(Exception):
    def __init__(self, message):
        self._errors = []
        self._message = message

    def try_(self, fn, *args, value=None, message=None):
        try:
            return fn(*args)
        except Exception as e:
            self.add(e, value, message, 1)

    def add(self, e: Exception, value= None, message:str = None, stackdelta = 0):
        self._errors.append(ErrorSetValue(e, value, message, stackdelta))

    def failed(self):
        return len(self._errors) > 0

    def throw_if_failed(self):
        if self._errors:
            raise self.Error(self._errors, self._message)

    def __enter__(self):
        return self

    def __exit__(self, et, ev, tb):
        self.throw_if_failed()

    class Error(Exception):
        def __str__(self):
            errors = self.args[0]
            message = self.args[1]

            # 最初の1件だけ表示
            if not errors:
                return "<no error is contained>"

            count = len(errors)

            header = "{}件のエラーが発生:".format(min(count, 3))
            if message is not None:
                header += " ［{}］".format(message)
            lines = [header]
            for x in errors[:3]:
                x: ErrorSetValue
                lines.extend(x.displays())
                lines.append("")
            if count > 3:
                lines.append("  ...（さらに{}件のエラーが発生)".format(count-3))

            return "\n".join(lines)


def catAndMouse(x, y, z):
    xDist = abs(z-x)
    yDist = abs(z-y)
    if xDist == yDist:
        return('Mouse C')
    elif xDist < yDist:
        return('Cat A')
    else:
        return('Cat B')

if __name__ == '__main__':
    q = int(input())
    for q_itr in range(q):
        xyz = input().split()
        x = int(xyz[0])
        y = int(xyz[1])
        z = int(xyz[2])
        result = catAndMouse(x, y, z)
        print(result + '\n')


def listParameter():
    parameterName = []
    while True:
        print('Enter a list value or enter nothing to stop')
        name = input()
        if name == '':
            break
        parameterName = parameterName + [name]  # list concatenation
    parameterName.insert(-1, ' and')

    joinedString = ', '.join(parameterName[:-2])
    joinedSecond = ' '.join(parameterName[-2:])
    print(joinedString + joinedSecond)

listParameter()


from absl import app
from absl import flags
from absl import logging
from pathlib import Path
from PIL import Image
from PIL import ImageFile
from tensorflow.keras.applications.vgg19 import VGG19
from tensorflow.keras.callbacks import Callback
from tensorflow.keras.callbacks import LearningRateScheduler
from tensorflow.keras.callbacks import TensorBoard
from tensorflow.keras.layers import Input
from tensorflow.keras.layers import Lambda
from tensorflow.keras.models import Model
import numpy as np
import tensorflow.keras.backend as K
import tensorflow.keras.optimizers as optimizers

from dataloader import ContentStyleLoader
from network import AdaIN
from network import Encoder
from network import Decoder
from utils import mse_loss
from utils import rm_path

# dataset options
flags.DEFINE_string('content_dir', default=None, help='Directory with content images', short_name='cd')
flags.mark_flag_as_required('content_dir')
flags.DEFINE_string('style_dir', default=None, help='Directory with style images', short_name='sd')
flags.mark_flag_as_required('style_dir')
flags.DEFINE_integer('image_size', default=512, help='Size of images to load')
flags.DEFINE_integer('crop_size', default=256, help='Size of images after random crop')
flags.DEFINE_integer('batch_size', default=8, help='Size of the batch')
flags.DEFINE_integer('dataset_size', default=1000, help='Size of the dataset per epoch')
flags.DEFINE_integer('workers', default=1, help='Number of threads for input preprocessing')

# hyper-parameters
flags.DEFINE_float('content_weight', default=1.0, help='Weight of content loss')
flags.DEFINE_float('style_weight', default=10.0, help='Weight of style loss')
flags.DEFINE_integer('epochs', default=160, help='Total epochs')
flags.DEFINE_float('learning_rate', default=1e-4, help='Learning rate')
flags.DEFINE_float('learning_rate_decay', default=5e-5, help='Learning rate decay')

# logging
flags.DEFINE_string('save_dir', default='./experiments', help='Directory to save trained models')
flags.DEFINE_string('tensorboard', default='./logs', help='Directory to save tensorboard logs')
flags.DEFINE_bool('save_best_only', default=False, help='Option to save one best model')
flags.DEFINE_integer('save_every', default=None, help='Number of batches between checkpoints, default=per_epoch')

FLAGS = flags.FLAGS

def calculate_style_loss(x, epsilon=1e-5):
  y_trues, y_preds = x
  loss = [
    mse_loss(K.mean(y_true, axis=(1, 2)), K.mean(y_pred, axis=(1, 2)))
    + mse_loss(K.sqrt(K.var(y_true, axis=(1, 2)) + epsilon), K.sqrt(K.var(y_pred, axis=(1, 2)) + epsilon))
    for y_true, y_pred in zip(y_trues, y_preds)
  ]
  return K.sum(loss)

def calculate_content_loss(x):
  y_true, y_pred = x
  return mse_loss(y_true, y_pred)

class SubmodelCheckpoint(Callback):
  def __init__(self, filepath, submodel_name, monitor='val_loss', verbose=0, save_best_only=False, save_weights_only=False, mode='auto', save_freq='epoch', **kwargs):
    super(SubmodelCheckpoint, self).__init__()
    self.filepath = filepath
    self.submodel_name = submodel_name
    self.monitor = monitor
    self.verbose = verbose
    self.save_best_only = save_best_only
    self.save_weights_only = save_weights_only
    if mode == 'min':
      self.monitor_op = np.less
      self.best = np.Inf
    elif mode == 'max':
      self.monitor_op = np.greater
      self.best = -np.Inf
    else: # mode == 'auto'
      if 'acc' in self.monitor or self.monitor.startswith('fmeasure'):
        self.monitor_op = np.greater
        self.best = -np.Inf
      else: # monitor loss
        self.monitor_op = np.less
        self.best = np.Inf
    self.save_freq = save_freq
    if 'period' in kwargs:
      self.period = kwargs['period']
    else:
      self.period = 1
    self.epochs_since_last_save = 0
    self.samples_since_last_save = 0
    self.current_epoch = None

  def on_batch_end(self, batch, logs=None):
    logs = logs or {}
    if isinstance(self.save_freq, int):
      self.samples_since_last_save += 1
      if self.samples_since_last_save >= self.save_freq:
        self.save_model(name_dict={'batch': batch}, logs=logs)
        self.samples_since_last_save = 0

  def on_epoch_start(self, epoch, logs=None):
    self.current_epoch = epoch

  def on_epoch_end(self, epoch, logs=None):
    logs = logs or {}
    if self.save_freq == 'epoch':
      self.epochs_since_last_save += 1
      if self.epochs_since_last_save >= self.period:
        self.save_model(name_dict={'epoch': epoch}, logs=logs)
        self.epochs_since_last_save = 0

  def save_model(self, name_dict=None, logs=None):
    name_dict = name_dict or {}
    if 'epoch' not in name_dict:
      name_dict['epoch'] = self.current_epoch
    name_dict['epoch'] += 1
    logs = logs or {}
    filepath = self.filepath.format(**name_dict, **logs)
    submodel = self.model.get_layer(self.submodel_name)
    if self.save_best_only:
      current = logs.get(self.monitor)
      if current is None:
        logging.warning('Can save best model only with {} available, skipping.'.format(self.monitor))
      else:
        if self.monitor_op(current, self.best):
          if self.verbose > 0:
            print('\nEpoch {:5d}: {} improved from {:.5f} to {:.5f}, save model to {}'.format(self.current_epoch + 1, self.monitor, self.best, current, filepath))
          if self.save_weights_only:
            submodel.save_weights(filepath, overwrite=True)
          else:
            submodel.save(filepath, overwrite=True)
    else:
      if self.verbose > 0:
        print('\nEpoch {:5d}: save mode to {}'.format(self.current_epoch + 1, filepath))
      if self.save_weights_only:
        submodel.save_weights(filepath, overwrite=True)
      else:
        submodel.save(filepath, overwrite=True)

def run():

  # create directories
  save_dir = Path(FLAGS.save_dir)
  if save_dir.exists():
    logging.warning('The directory can be overwritten: {}'.format(FLAGS.save_dir))
  save_dir.mkdir(exist_ok=True, parents=True)
  log_dir = Path(FLAGS.tensorboard)
  if log_dir.exists():
    logging.warning('The directory will be removed: {}'.format(FLAGS.tensorboard))
    rm_path(log_dir)
  log_dir.mkdir(exist_ok=True, parents=True)

  # to handle errors while loading images
  Image.MAX_IMAGE_PIXELS = None
  ImageFile.LOAD_TRUNCATED_IMAGES = True

  # image generator
  dataset = ContentStyleLoader(
    content_root=FLAGS.content_dir,
    content_image_shape=(FLAGS.image_size, FLAGS.image_size),
    content_crop='random',
    content_crop_size=FLAGS.crop_size,
    style_root=FLAGS.style_dir,
    style_image_shape=(FLAGS.image_size, FLAGS.image_size),
    style_crop='random',
    style_crop_size=FLAGS.crop_size,
    n_per_epoch=FLAGS.dataset_size,
    batch_size=FLAGS.batch_size
  )

  # create model
  encoder = Encoder(input_shape=(FLAGS.crop_size, FLAGS.crop_size, 3), pretrained=True, name='encoder')
  # freeze the model
  for l in encoder.layers:
    l.trainable = False
  adain = AdaIN(alpha=1.0, name='adain')
  decoder = Decoder(input_shape=encoder.output_shape[-1][1:], name='decoder')

  # place holders for inputs
  content_input = Input(shape=(FLAGS.crop_size, FLAGS.crop_size, 3), name='content_input')
  style_input = Input(shape=(FLAGS.crop_size, FLAGS.crop_size, 3), name='style_input')

  # forwarding
  content_features = encoder(content_input)
  style_features = encoder(style_input)
  normalized_feature = adain([content_features[-1], style_features[-1]])
  generated = decoder(normalized_feature)

  # loss calculation
  generated_features = encoder(generated)
  content_loss = Lambda(calculate_content_loss, name='content_loss')([normalized_feature, generated_features[-1]])
  style_loss = Lambda(calculate_style_loss, name='style_loss')([style_features, generated_features])
  loss = Lambda(lambda x: FLAGS.content_weight * x[0] + FLAGS.style_weight * x[1], name='loss')([content_loss, style_loss])

  # trainer
  trainer = Model(inputs=[content_input, style_input], outputs=[loss])
  optim = optimizers.Adam(learning_rate=FLAGS.learning_rate)
  trainer.compile(optimizer=optim, loss=lambda _, y_pred: y_pred)
  trainer.summary()

  # callbacks
  callbacks = [
    # learning rate scheduler
    LearningRateScheduler(lambda epoch, _: FLAGS.learning_rate / (1.0 + FLAGS.learning_rate_decay * FLAGS.dataset_size * epoch)),
    # Tensor Board
    TensorBoard(str(log_dir), write_graph=False, update_freq='batch'),
    # save model
    SubmodelCheckpoint(str(save_dir / 'decoder.epoch-{epoch:d}.h5'), submodel_name='decoder', save_weights_only=True, save_best_only=FLAGS.save_best_only, save_freq=FLAGS.save_every if FLAGS.save_every else 'epoch')
  ]

  # train
  trainer.fit_generator(dataset, epochs=FLAGS.epochs, workers=FLAGS.workers, callbacks=callbacks)

def main(argv):
  del argv
  run()

if __name__ == '__main__':
  app.run(main)


from PyQt5.QtWidgets import QWidget, QLabel, QLineEdit, \
    QMessageBox, QSpinBox, QHBoxLayout, QGroupBox, QRadioButton, \
    QVBoxLayout, QComboBox, QStackedWidget, QDoubleSpinBox, QCheckBox, \
    QGridLayout
from PyQt5.QtCore import Qt

import app.data.ai as ai
from app.data.database import DB

from app.extensions.custom_gui import PropertyBox, ComboBox
from app.editor.custom_widgets import ClassBox, UnitBox, FactionBox, PartyBox
from app.utilities import str_utils

# Target Specifications
class NullSpecification(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.window = parent

        self.layout = QHBoxLayout()

        self.setLayout(self.layout)

    def set_current(self, target_spec):
        pass

class UnitSpecification(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.window = parent

        self.layout = QGridLayout()
        self.box1 = ComboBox(self)
        for spec in ai.unit_spec:
            self.box1.addItem(spec)
        self.box1.currentIndexChanged.connect(self.unit_spec_changed)

        self.box2 = QStackedWidget(self)
        all_box = ComboBox(self)
        all_box.setEnabled(False)
        self.box2.addWidget(all_box)
        class_box = ClassBox(self)
        class_box.edit.currentIndexChanged.connect(self.sub_spec_changed)
        self.box2.addWidget(class_box)
        tag_box = ComboBox(self)
        tag_box.addItems([tag.nid for tag in DB.tags])
        tag_box.currentIndexChanged.connect(self.sub_spec_changed)
        self.box2.addWidget(tag_box)
        name_box = ComboBox(self)
        name_box.addItems([unit.name for unit in DB.units])
        name_box.currentIndexChanged.connect(self.sub_spec_changed)
        self.box2.addWidget(name_box)
        faction_box = FactionBox(self)
        faction_box.edit.currentIndexChanged.connect(self.sub_spec_changed)
        self.box2.addWidget(faction_box)
        party_box = PartyBox(self)
        party_box.edit.currentIndexChanged.connect(self.sub_spec_changed)
        self.box2.addWidget(party_box)
        unit_box = UnitBox(self)
        unit_box.edit.currentIndexChanged.connect(self.sub_spec_changed)
        self.box2.addWidget(unit_box)

        self.except_check_box = QCheckBox(self)
        self.except_check_box.setText("Except")
        self.except_check_box.toggled.connect(self.check_box_toggled)
        self.except_check_box.setEnabled(False)

        self.layout.addWidget(self.except_check_box, 0, 0)
        self.layout.addWidget(self.box1, 1, 0)
        self.layout.addWidget(self.box2, 0, 1, 2, 1)

        self.setLayout(self.layout)

    def unit_spec_changed(self, index):
        unit_spec = self.box1.currentText()
        self.box2.setEnabled(True)
        self.except_check_box.setEnabled(True)
        if unit_spec == "Class":
            self.box2.setCurrentIndex(1)
        elif unit_spec == "Tag":
            self.box2.setCurrentIndex(2)
        elif unit_spec == "Name":
            self.box2.setCurrentIndex(3)
        elif unit_spec == "Faction":
            self.box2.setCurrentIndex(4)
        elif unit_spec == "Party":
            self.box2.setCurrentIndex(5)
        elif unit_spec == "ID":
            self.box2.setCurrentIndex(6)
        else:
            self.box2.setCurrentIndex(0)
            self.box2.setEnabled(False)
            self.except_check_box.setEnabled(False)

    def sub_spec_changed(self, index):
        unit_spec = self.box1.currentText()
        if self.box2.currentIndex() in (0, 2, 3):
            sub_spec = self.box2.currentWidget().currentText()
        else:
            sub_spec = self.box2.currentWidget().edit.currentText()
        self.window.current.target_spec = (unit_spec, sub_spec)

    def check_box_toggled(self, checked):
        self.window.current.invert_targeting = bool(checked)

    def set_current(self, target_spec):
        self.except_check_box.setChecked(bool(self.window.current.invert_targeting))
        if target_spec:
            self.box1.setValue(target_spec[0])
            self.box2.currentWidget().setValue(target_spec[1])
        else:
            self.box1.setValue("All")
            self.box2.setEnabled(False)
            self.except_check_box.setEnabled(False)

class EventSpecification(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.window = parent

        self.layout = QHBoxLayout()
        self.box = QLineEdit(self)
        self.box.setPlaceholderText("Event Region Type")
        self.box.textChanged.connect(self.spec_changed)

        self.layout.addWidget(self.box)
        self.setLayout(self.layout)

    def spec_changed(self, text):
        event = self.box.text()
        self.window.current.target_spec = event

    def set_current(self, target_spec):
        self.box.setText(target_spec)

class PositionSpecification(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.window = parent

        self.layout = QVBoxLayout()
        self.starting = QRadioButton("Starting", self)
        self.starting.toggled.connect(self.starting_toggled)
        self.custom = QRadioButton("Custom", self)

        bottom = QHBoxLayout()
        bottom.addWidget(self.custom)
        self.x_spinbox = QSpinBox()
        self.y_spinbox = QSpinBox()
        self.x_spinbox.setMinimumWidth(40)
        self.y_spinbox.setMinimumWidth(40)
        self.x_spinbox.setRange(0, 255)
        self.y_spinbox.setRange(0, 255)
        self.x_spinbox.setEnabled(False)
        self.y_spinbox.setEnabled(False)
        self.x_spinbox.valueChanged.connect(self.change_spinbox)
        self.y_spinbox.valueChanged.connect(self.change_spinbox)
        bottom.addWidget(self.x_spinbox)
        bottom.addWidget(self.y_spinbox)

        self.layout.addWidget(self.starting)
        self.layout.addLayout(bottom)

        self.setLayout(self.layout)

    def starting_toggled(self, checked):
        if checked:
            self.x_spinbox.setEnabled(False)
            self.y_spinbox.setEnabled(False)
            self.window.current.target_spec = "Starting"
        else:
            self.x_spinbox.setEnabled(True)
            self.y_spinbox.setEnabled(True)
            x, y = int(self.x_spinbox.value()), int(self.y_spinbox.value())
            self.window.current.target_spec = (x, y)

    def change_spinbox(self, value):
        x, y = int(self.x_spinbox.value()), int(self.y_spinbox.value())
        self.window.current.target_spec = (x, y)

    def set_current(self, target_spec):
        if target_spec == "Starting":
            self.window.current.target_spec = "Starting"
            self.starting.setChecked(True)
        elif target_spec:
            self.starting.setChecked(False)
            self.x_spinbox.setValue(int(target_spec[0]))
            self.y_spinbox.setValue(int(target_spec[1]))
        else:
            self.starting.setChecked(False)
            self.x_spinbox.setValue(0)
            self.y_spinbox.setValue(0)

class BehaviourBox(QGroupBox):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.window = parent

        self.current = None

        self.layout = QHBoxLayout()

        self.action = ComboBox(self)
        for action in ai.AI_ActionTypes:
            self.action.addItem(action.replace('_', ' '))
        self.action.currentIndexChanged.connect(self.action_changed)

        self.target = ComboBox(self)
        for target in ai.AI_TargetTypes:
            self.target.addItem(target)
        self.target.currentIndexChanged.connect(self.target_changed)
        self.target.setEnabled(False)

        self.target_spec = QStackedWidget(self)
        for target in ai.AI_TargetTypes:
            if target == "None":
                target_spec = NullSpecification(self)
            elif target in ("Unit", "Ally", "Enemy"):
                target_spec = UnitSpecification(self)
            elif target == "Position":
                target_spec = PositionSpecification(self)
            elif target == "Event":
                target_spec = EventSpecification(self)
            self.target_spec.addWidget(target_spec)

        self.view_range = ComboBox(self)
        self.view_range.setInsertPolicy(QComboBox.NoInsert)
        self.view_range.addItem("Max Item Range")
        self.view_range.addItem("Movement + Max Item Range")
        self.view_range.addItem("Movement*2 + Max Item Range")
        self.view_range.addItem("Entire Map")
        self.view_range.addItem("Custom Integer")
        self.view_range.currentIndexChanged.connect(self.check_view_range)

        self.custom_view_range = QSpinBox(self)
        self.custom_view_range.setMaximum(255)
        self.custom_view_range.editingFinished.connect(self.check_view_range)

        self.layout.addWidget(self.action)
        self.layout.addWidget(self.target)
        self.layout.addWidget(self.target_spec)
        self.layout.addWidget(QLabel(" within "))
        self.layout.addWidget(self.view_range)
        self.layout.addWidget(self.custom_view_range)
        self.custom_view_range.hide()
        self.setLayout(self.layout)

    def action_changed(self, index):
        action = self.action.currentText().replace(' ', '_')
        self.current.action = action

        if self.current.action in ('Move_to', 'Move_away_from'):
            self.target.setEnabled(True)
            self.target.setValue(self.current.target)
            target_spec = self.target_spec.currentWidget()
            target_spec.set_current(self.current.target_spec)
        elif self.current.action == 'None':
            self.target.setEnabled(False)
            self.target.setValue('None')
        elif self.current.action in ('Attack', 'Steal'):
            self.target.setEnabled(False)
            self.target.setValue('Enemy')
            target_spec = self.target_spec.currentWidget()
            target_spec.set_current(self.current.target_spec)
        elif self.current.action == 'Support':
            self.target.setEnabled(False)
            self.target.setValue('Ally')
            target_spec = self.target_spec.currentWidget()
            target_spec.set_current(self.current.target_spec)
        elif self.current.action == 'Interact':
            self.target.setEnabled(False)
            self.target.setValue('Event')
            target_spec = self.target_spec.currentWidget()
            target_spec.set_current(self.current.target_spec)

    def target_changed(self, index):
        target = self.target.currentText()
        self.current.target = target
        # Swap the specification
        idx = ai.AI_TargetTypes.index(target)
        self.target_spec.setCurrentIndex(idx)

    def check_view_range(self):
        cur_val = self.view_range.currentText()
        if cur_val == 'Custom Integer':
            self.custom_view_range.show()
            self.current.view_range = int(self.custom_view_range.value())
        else:
            self.custom_view_range.hide()
            self.current.view_range = -1 * (self.view_range.currentIndex() + 1)

    def set_current(self, behaviour):
        self.current = behaviour
        action = behaviour.action.replace('_', ' ')
        self.action.setValue(action)
        self.action_changed(None)

        if behaviour.view_range < 0:
            correct_index = -behaviour.view_range - 1
            self.view_range.setCurrentIndex(correct_index)
        else:
            self.custom_view_range.setValue(int(behaviour.view_range))
            self.view_range.setCurrentIndex(4)

class AIProperties(QWidget):
    def __init__(self, parent, current=None):
        super().__init__(parent)
        self.window = parent
        self.model = self.window.left_frame.model
        self._data = self.window._data
        self.database_editor = self.window.window

        self.current = current

        top_section = QHBoxLayout()

        self.nid_box = PropertyBox("Unique ID", QLineEdit, self)
        self.nid_box.edit.textChanged.connect(self.nid_changed)
        self.nid_box.edit.editingFinished.connect(self.nid_done_editing)
        top_section.addWidget(self.nid_box)

        self.priority_box = PropertyBox("Priority", QSpinBox, self)
        self.priority_box.setToolTip("Higher priority AIs move first")
        self.priority_box.edit.setRange(0, 255)
        self.priority_box.edit.setAlignment(Qt.AlignRight)
        self.priority_box.edit.valueChanged.connect(self.priority_changed)
        top_section.addWidget(self.priority_box)

        self.offense_bias_box = PropertyBox("Offense Bias", QDoubleSpinBox, self)
        self.offense_bias_box.setToolTip("Higher offense AIs weigh damage dealt over their own survival")
        self.offense_bias_box.edit.setRange(0.01, 100)
        self.offense_bias_box.edit.setSingleStep(0.2)
        self.offense_bias_box.edit.setAlignment(Qt.AlignRight)
        self.offense_bias_box.edit.valueChanged.connect(self.offense_bias_changed)
        top_section.addWidget(self.offense_bias_box)

        main_section = QVBoxLayout()

        self.behaviour1 = BehaviourBox(self)
        self.behaviour1.setTitle("Behaviour 1")
        self.behaviour2 = BehaviourBox(self)
        self.behaviour2.setTitle("Behaviour 2")
        self.behaviour3 = BehaviourBox(self)
        self.behaviour3.setTitle("Behaviour 3")
        self.behaviour_boxes = [self.behaviour1, self.behaviour2, self.behaviour3]

        main_section.addWidget(self.behaviour1)
        main_section.addWidget(self.behaviour2)
        main_section.addWidget(self.behaviour3)

        total_section = QVBoxLayout()
        total_section.addLayout(top_section)
        total_section.addLayout(main_section)
        self.setLayout(total_section)

    def nid_changed(self, text):
        self.current.nid = text
        self.window.update_list()

    def nid_done_editing(self):
        # Check validity of nid!
        other_nids = [d.nid for d in self._data.values() if d is not self.current]
        if self.current.nid in other_nids:
            QMessageBox.warning(self.window, 'Warning', 'AI ID %s already in use' % self.current.nid)
            self.current.nid = str_utils.get_next_name(self.current.nid, other_nids)
        self.model.on_nid_changed(self._data.find_key(self.current), self.current.nid)
        self._data.update_nid(self.current, self.current.nid)
        self.window.update_list()

    def priority_changed(self, val):
        self.current.priority = int(val)

    def offense_bias_changed(self, val):
        self.current.offense_bias = float(val)

    def set_current(self, current):
        self.current = current
        self.nid_box.edit.setText(current.nid)
        self.priority_box.edit.setValue(current.priority)
        self.offense_bias_box.edit.setValue(current.offense_bias)
        for idx, behaviour in enumerate(current.behaviours):
            self.behaviour_boxes[idx].set_current(behaviour)


import cv2
import numpy as np
import pyclipper
from shapely.geometry import Polygon
from pyclipper import PyclipperOffset
import math
import operator
from functools import reduce

def clockwise_sort_points(_point_coordinates):
    """
        以左上角为起点的顺时针排序
        原理就是将笛卡尔坐标转换为极坐标，然后对极坐标的φ进行排序
    Args:
        _point_coordinates:  待排序的点[(x,y),]
    Returns:    排序完成的点
    """
    center_point = tuple(
        map(operator.truediv, reduce(lambda x, y: map(operator.add, x, y), _point_coordinates),
            [len(_point_coordinates)] * 2))
    return sorted(_point_coordinates, key=lambda coord: (180 + math.degrees(
        math.atan2(*tuple(map(operator.sub, coord, center_point))[::-1]))) % 360)

class DistillationDBPostProcess(object):
    def __init__(self, model_name=None,
                 key=None,
                 thresh=0.3,
                 box_thresh=0.6,
                 max_candidates=1000,
                 unclip_ratio=1.5,
                 use_dilation=False,
                 score_mode="fast",
                 **kwargs):
        if model_name is None:
            model_name = ["student"]
        self.model_name = model_name
        self.key = key
        self.post_process = DBPostProcess(thresh=thresh,
                                          box_thresh=box_thresh,
                                          max_candidates=max_candidates,
                                          unclip_ratio=unclip_ratio,
                                          use_dilation=use_dilation,
                                          score_mode=score_mode)

    def __call__(self, predicts, shape_list):
        results = {}
        for k in self.model_name:
            results[k] = self.post_process(predicts[k].detach().cpu().numpy(), shape_list=shape_list)
        return results

class DBPostProcess(object):
    """
    The post process for Differentiable Binarization (DB).
    """

    def __init__(self,
                 thresh=0.6,
                 box_thresh=0.6,
                 max_candidates=1000,
                 unclip_ratio=1.5,
                 use_dilation=False,
                 **kwargs):
        self.thresh = thresh
        self.box_thresh = box_thresh
        self.max_candidates = max_candidates
        self.unclip_ratio = unclip_ratio
        self.min_size = 3
        self.dilation_kernel = None if not use_dilation else np.array(
            [[1, 1], [1, 1]])

    def boxes_from_bitmap(self, pred, _bitmap, dest_width, dest_height):
        '''
        _bitmap: single map with shape (1, H, W),
                whose values are binarized as {0, 1}
        '''

        bitmap = _bitmap
        height, width = bitmap.shape

        bitmap = (bitmap * 255).astype(np.uint8)
        # structure_element = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
        # bitmap = cv2.morphologyEx(bitmap, cv2.MORPH_CLOSE, structure_element)

        if cv2.__version__.startswith('3'):
            _, contours, _ = cv2.findContours(bitmap, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
        elif cv2.__version__.startswith('4'):
            contours, _ = cv2.findContours(bitmap, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
        else:
            raise NotImplementedError(f'opencv {cv2.__version__} not support')

        num_contours = min(len(contours), self.max_candidates)

        boxes = []
        scores = []
        for index in range(num_contours):
            contour = contours[index]
            points, sside = self.get_mini_boxes(contour)
            if sside < self.min_size:
                continue
            points = np.array(points)
            # score = self.box_score_fast(pred, points.reshape(-1, 2))
            score = self.box_score_slow(pred, contour)
            if score < self.box_thresh:
                continue
            box = self.unclip(points).reshape(-1, 1, 2)
            box, sside = self.get_mini_boxes(box)
            if sside < self.min_size + 2:
                continue
            box = np.array(box)

            box[:, 0] = np.clip(np.round(box[:, 0] / width * dest_width), 0, dest_width)
            box[:, 1] = np.clip(np.round(box[:, 1] / height * dest_height), 0, dest_height)
            boxes.append(box.astype(np.int16))
            scores.append(score)
        return np.array(boxes, dtype=np.int16), scores

    def unclip(self, box):
        unclip_ratio = self.unclip_ratio
        poly = Polygon(box)
        distance = poly.area * unclip_ratio / poly.length
        offset = pyclipper.PyclipperOffset()
        offset.AddPath(box, pyclipper.JT_ROUND, pyclipper.ET_CLOSEDPOLYGON)
        expanded = np.array(offset.Execute(distance))
        return expanded

    def get_mini_boxes(self, contour):
        try:
            rotated_box = cv2.minAreaRect(contour)
        except:
            print(len(contour))
            return None, 0
        box_points = cv2.boxPoints(rotated_box)
        rotated_points = clockwise_sort_points(box_points)
        rotated_points = list(rotated_points)
        return rotated_points, min(rotated_box[1])

    def box_score_fast(self, bitmap, _box):
        h, w = bitmap.shape[:2]
        box = _box.copy()
        xmin = np.clip(np.floor(box[:, 0].min()).astype(np.int), 0, w - 1)
        xmax = np.clip(np.ceil(box[:, 0].max()).astype(np.int), 0, w - 1)
        ymin = np.clip(np.floor(box[:, 1].min()).astype(np.int), 0, h - 1)
        ymax = np.clip(np.ceil(box[:, 1].max()).astype(np.int), 0, h - 1)

        mask = np.zeros((ymax - ymin + 1, xmax - xmin + 1), dtype=np.uint8)
        box[:, 0] = box[:, 0] - xmin
        box[:, 1] = box[:, 1] - ymin
        cv2.fillPoly(mask, box.reshape(1, -1, 2).astype(np.int32), 1)
        return cv2.mean(bitmap[ymin:ymax + 1, xmin:xmax + 1], mask)[0]

    def box_score_slow(self, bitmap, contour):
        '''
        box_score_slow: use polyon mean score as the mean score
        '''
        h, w = bitmap.shape[:2]
        contour = contour.copy()
        contour = np.reshape(contour, (-1, 2))

        xmin = np.clip(np.min(contour[:, 0]), 0, w - 1)
        xmax = np.clip(np.max(contour[:, 0]), 0, w - 1)
        ymin = np.clip(np.min(contour[:, 1]), 0, h - 1)
        ymax = np.clip(np.max(contour[:, 1]), 0, h - 1)

        mask = np.zeros((ymax - ymin + 1, xmax - xmin + 1), dtype=np.uint8)

        contour[:, 0] = contour[:, 0] - xmin
        contour[:, 1] = contour[:, 1] - ymin

        cv2.fillPoly(mask, contour.reshape(1, -1, 2).astype(np.int32), 1)
        return cv2.mean(bitmap[ymin:ymax + 1, xmin:xmax + 1], mask)[0]

    def __call__(self, outs_dict, shape_list):
        pred = outs_dict
        pred = pred[:, 0, :, :]
        segmentation = np.zeros_like(pred, dtype=np.float32)
        np.putmask(segmentation, pred > self.thresh, pred)

        boxes_batch = []
        scores_batch = []
        for batch_index in range(pred.shape[0]):
            src_h, src_w = shape_list[batch_index]
            if self.dilation_kernel is not None:
                mask = cv2.dilate(np.array(segmentation[batch_index]).astype(np.uint8), self.dilation_kernel)
            else:
                mask = segmentation[batch_index]
            boxes, scores = self.boxes_from_bitmap(pred[batch_index], mask, src_w, src_h, )
            boxes_batch.append(boxes)
            scores_batch.append(scores)
        return boxes_batch, scores_batch


def solution(i, j, k):
    answer = ''
    for v in range(i, j+1):
        answer += str(v)

    cnt = 0
    for s in list(answer):
        if s == str(k):
            cnt += 1

    return cnt

print(solution(1,13,1))


from collections.abc import Sequence

import torch
import torch.nn as nn
import torch.nn.functional as F
from hirl.utils import dist

class CSyncBatchNorm(nn.SyncBatchNorm):
    def __init__(self,
                 *args,
                 with_var=False,
                 **kwargs):
        super(CSyncBatchNorm, self).__init__(*args, **kwargs)
        self.with_var = with_var

    def forward(self, x):
        # center norm
        self.training = False
        if not self.with_var:
            self.running_var = torch.ones_like(self.running_var)
        normed_x = super(CSyncBatchNorm, self).forward(x)
        # udpate center
        self.training = True
        _ = super(CSyncBatchNorm, self).forward(x)
        return normed_x

class PSyncBatchNorm(nn.SyncBatchNorm):
    def __init__(self,
                 *args,
                 bunch_size,
                 **kwargs):
        procs_per_bunch = min(bunch_size, dist.get_world_size())
        assert dist.get_world_size() % procs_per_bunch == 0
        n_bunch = dist.get_world_size() // procs_per_bunch
        #
        ranks = list(range(dist.get_world_size()))
        print('---ALL RANKS----\n{}'.format(ranks))
        rank_groups = [ranks[i*procs_per_bunch: (i+1)*procs_per_bunch] for i in range(n_bunch)]
        print('---RANK GROUPS----\n{}'.format(rank_groups))
        process_groups = [torch.distributed.new_group(pids) for pids in rank_groups]
        bunch_id = dist.get_rank() // procs_per_bunch
        process_group = process_groups[bunch_id]
        print('---CURRENT GROUP----\n{}'.format(process_group))
        super(PSyncBatchNorm, self).__init__(*args, process_group=process_group, **kwargs)

class CustomSequential(nn.Sequential):
    bn_types = (nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d, nn.SyncBatchNorm)

    def forward(self, input):
        for module in self:
            dim = len(input.shape)
            if isinstance(module, self.bn_types) and dim > 2:
                perm = list(range(dim - 1)); perm.insert(1, dim - 1)
                inv_perm = list(range(dim)) + [1]; inv_perm.pop(1)
                input = module(input.permute(*perm)).permute(*inv_perm)
            else:
                input = module(input)
        return input

class MLP(nn.Module):
    """
    An  Multi-layer Perceptron.

    Args:
        input_dim (int): input dimension
        hidden_dim (list of int): hidden dimensions
        short_cut (bool, optional): use short cut or not
        batch_norm (bool, optional): apply batch normalization or not
        activation (str or function, optional): activation function
        dropout (float, optional): dropout rate
    """

    def __init__(self, input_dim, hidden_dims, short_cut=False, batch_norm=False,
                activation="relu", dropout=0):
        super(MLP, self).__init__()

        if not isinstance(hidden_dims, Sequence):
            hidden_dims = [hidden_dims]
        self.dims = [input_dim] + hidden_dims
        self.short_cut = short_cut

        if isinstance(activation, str):
            self.activation = getattr(F, activation)
        else:
            self.activation = activation
        if dropout:
            self.dropout = nn.Dropout(dropout)
        else:
            self.dropout = None

        self.layers = nn.ModuleList()
        for i in range(len(self.dims) - 1):
            if batch_norm and i < len(self.dims) - 2:
                # Not use bias when the linear layer is followed by BN
                self.layers.append(nn.Linear(self.dims[i], self.dims[i + 1], bias=False))
            else:
                self.layers.append(nn.Linear(self.dims[i], self.dims[i + 1]))
        if batch_norm:
            self.batch_norms = nn.ModuleList()
            for i in range(len(self.dims) - 2):
                self.batch_norms.append(nn.BatchNorm1d(self.dims[i + 1]))
        else:
            self.batch_norms = None

    def forward(self, input):
        """"""
        layer_input = input

        for i, layer in enumerate(self.layers):
            hidden = layer(layer_input)
            if i < len(self.layers) - 1:
                if self.batch_norms:
                    x = hidden.flatten(0, -2)
                    hidden = self.batch_norms[i](x).view_as(hidden)
                hidden = self.activation(hidden)
                if self.dropout:
                    hidden = self.dropout(hidden)
            if self.short_cut and hidden.shape == layer_input.shape:
                hidden = hidden + layer_input
            layer_input = hidden

        return hidden

class MultiCropWrapper(nn.Module):
    """
    Perform forward pass separately on each resolution input.
    The inputs corresponding to a single resolution are clubbed and single
    forward is run on the same resolution inputs. Hence we do several
    forward passes = number of different resolutions used. We then
    concatenate all the output features and run the head forward on these
    concatenated features.

    Args:
        backbone (nn.Module): backbone network.
        head (nn.Module, optional): head network.
    """
    def __init__(self, backbone, head=None):
        super(MultiCropWrapper, self).__init__()
        # disable layers dedicated to ImageNet labels classification
        backbone.fc, backbone.head = nn.Identity(), nn.Identity()
        self.backbone = backbone
        if head is None:
            self.head = nn.Identity()
        else:
            self.head = head

    def forward(self, x, mask=None, return_backbone_feat=False,
                **kwargs):
        # convert to list
        if not isinstance(x, list):
            x = [x]
            mask = [mask] if mask is not None else None
        idx_crops = torch.cumsum(torch.unique_consecutive(
            torch.tensor([inp.shape[-1] for inp in x]),
            return_counts=True,
        )[1], 0)
        start_idx = 0
        for end_idx in idx_crops:
            inp_x = torch.cat(x[start_idx: end_idx])

            if mask is not None:
                inp_m = torch.cat(mask[start_idx: end_idx])
                kwargs.update(dict(mask=inp_m))

            _out = self.backbone(inp_x, **kwargs)
            if start_idx == 0:
                output = _out
            else:
                output = torch.cat((output, _out))
            start_idx = end_idx
        # Run the head forward on the concatenated features.
        output_ = self.head(output)
        if return_backbone_feat:
            return output, output_
        return output_


import unittest

import cla
from cla.controllers.github import webhook_secret_validation, webhook_secret_failed_email_content
from cla.utils import get_comment_badge

SUCCESS = ":white_check_mark:"
FAILED = ":x:"
SIGN_URL = "http://test.contributor.lfcla/sign"
SUPPORT_URL = "https://jira.linuxfoundation.org/servicedesk/customer/portal/4"
GITHUB_HELP_URL = (
    "https://help.github.com/en/github/committing-changes-to-your-project/why-are-my-commits-linked-to-the-wrong-user"
)
GITHUB_FAKE_SHA = "fake_sha"
GITHUB_FAKE_SHA_2 = "fake_sha_2"

# def test_get_comment_body_no_user_id():
#     """
#     Test CLA comment body for case CLA test failure when commit has no user ids
#     """
#     # case with missing list with no authors
#     response = get_comment_body(
#         "github",
#         SIGN_URL,
#         [],
#         [(GITHUB_FAKE_SHA, [None, "foo", "foo@bar.com"]), (GITHUB_FAKE_SHA_2, [None, "fake", "fake@gmail.com"])],
#     )
#     expected = (
#             f"<url>
 {FAILED} The commit ({' ,'.join([GITHUB_FAKE_SHA, GITHUB_FAKE_SHA_2])}) "
#             + f"is missing the User's ID, preventing the EasyCLA check. "
#             + f"Consult GitHub Help to resolve."
#             + f"For further assistance with EasyCLA, "
#             + f"please submit a support request ticket."
#             + "
</url>"
#     )
#     assert response == expected

# def test_get_comment_body_cla_fail_no_user_id_and_user_id():
#     """
#     Test CLA comment body for case CLA fail check with no user id and existing user id
#     """
#     # case with missing list with user id existing
#     author_name = "wanyaland"
#     response = get_comment_body(
#         "github",
#         SIGN_URL,
#         [],
#         [
#             (GITHUB_FAKE_SHA, ["12", author_name, "foo@gmail.com"]),
#             (GITHUB_FAKE_SHA_2, [None, author_name, " foo@gmail.com"]),
#         ],
#     )
#     expected = (
#             f"

[{FAILED}]({SIGN_URL}) {author_name} "
#             + "The commit ("
#             + " ,".join([GITHUB_FAKE_SHA])
#             + ") is not authorized under a signed CLA. "
#             + f"[Please click here to be authorized]({SIGN_URL}). For further assistance with "
#             + f"EasyCLA, [please submit a support request ticket]({SUPPORT_URL})."
#             + "
"
#             + "
 " + FAILED + " The commit ("
#             + " ,".join([GITHUB_FAKE_SHA_2])
#             + ") is missing the User's ID, preventing the EasyCLA check. [Consult GitHub Help]("
#             + GITHUB_HELP_URL
#             + ") to resolve. For further assistance with EasyCLA, "
#             + f"[please submit a support request ticket]({SUPPORT_URL})."
#             + "

"
#     )
#
#     assert response == expected

# def test_get_comment_body_whitelisted_missing_user():
#     """
#     Test CLA comment body for case of a whitelisted user that has not confirmed affiliation
#     """
#     is_whitelisted = True
#     author = "foo"
#     signed = []
#     missing = [(GITHUB_FAKE_SHA, ["12", author, "foo@gmail.com", is_whitelisted])]
#     response = get_comment_body("github", SIGN_URL, signed, missing)
#     expected = (
#             f"

{author} ({' ,'.join([GITHUB_FAKE_SHA])}) "
#             + "is authorized, but they must confirm "
#             + "their affiliation with their company. "
#             + f'[Start the authorization process by clicking here]({SIGN_URL}), click "Corporate",'
#             + "select the appropriate company from the list, then confirm "
#             + "your affiliation on the page that appears. For further assistance with EasyCLA, "
#             + f"[please submit a support request ticket]({SUPPORT_URL})."
#             + "
"
#             + "
"
#     )
#     assert response == expected

def test_get_comment_badge_with_no_user_id():
    """
    Test CLA badge for CLA fail check with no user id
    """
    missing_id_badge = "cla-missing-id.svg"
    missing_user_id = True
    all_signed = False
    response = get_comment_badge("github", all_signed, SIGN_URL, "v1", missing_user_id=missing_user_id)
    assert missing_id_badge in response

def test_comment_badge_with_missing_whitelisted_user():
    """
    Test CLA badge for CLA fail check and whitelisted user
    """
    confirmation_needed_badge = "cla-confirmation-needed.svg"
    response = get_comment_badge("github", False, SIGN_URL, "v1", missing_user_id=False, is_approved_by_manager=True)
    assert confirmation_needed_badge in response

class TestWebhookSecretValidation(unittest.TestCase):
    def setUp(self) -> None:
        self.old_email = cla.config.EMAIL_SERVICE
        self.oldval = cla.config.GITHUB_APP_WEBHOOK_SECRET

    def tearDown(self) -> None:
        cla.config.GITHUB_APP_WEBHOOK_SECRET = self.oldval
        cla.config.EMAIL_SERVICE = self.oldval

    def test_webhook_secret_validation_empty(self):
        """
        Tests the webhook_secret_validation method
        """
        cla.config.GITHUB_APP_WEBHOOK_SECRET = ""
        with self.assertRaises(RuntimeError) as ex:
            _ = webhook_secret_validation("secret", b'')

    def test_webhook_secret_validation_failed(self):
        """
        Tests the webhook_secret_validation method
        """
        cla.config.GITHUB_APP_WEBHOOK_SECRET = "secret"
        assert not webhook_secret_validation("sha1=secret", ''.encode())

    def test_webhook_secret_validation_success(self):
        """
        Tests the webhook_secret_validation method
        """
        cla.config.GITHUB_APP_WEBHOOK_SECRET = "secret"
        input_data = 'data'.encode('utf-8')
        assert webhook_secret_validation("sha1=9818e3306ba5ac267b5f2679fe4abd37e6cd7b54", input_data)

    # def test_webhook_secret_failed_email(self):
    #     """
    #     Tests the email sending of the failed webhook
    #     :return:
    #     """
    #     with self.assertRaises(RuntimeError) as ex:
    #         webhook_secret_failed_email_content("repositories", {}, [])
    #
    #     s, b, m = webhook_secret_failed_email_content("repositories", {}, ["john@gmail.com"])
    #     assert s
    #     assert "Hello EasyCLA Maintainer" in b
    #     assert m == ["john@gmail.com"]
    #
    #     s, b, m = webhook_secret_failed_email_content("repositories", {
    #         "sender": {"login": "john"},
    #         "repository": {"id": "123", "full_name": "github.com/penguin/activity",
    #                        "html_url": "https://github.com/foo",
    #                        "owner": {"login": "test"},
    #                        "organization": {"login": "test"}
    #                        },
    #         "installation": {"id": 345}
    #     }, ["john@gmail.com"])
    #     assert s
    #     assert "event type: repositories" in b
    #     assert "user login: john" in b
    #     assert "repository_id: 123" in b
    #     assert "installation_id: 345" in b
    #     assert m == ["john@gmail.com"]


"""Functions for handling exceptions when attempting to write to SQL."""
import logging

import pandas as pd

from mssql_dataframe.core import (
    custom_errors,
    modify,
)

logger = logging.getLogger(__name__)

def add_metadata_timestamps(
    failure: custom_errors,
    table_name: str,
    dataframe: pd.DataFrame,
    modifier: modify,
) -> pd.DataFrame:
    """Handle a failed write attempt.

    Parameters
    ----------
    failure (mssql_dataframe.core.errors) : exception to potentially handle
    table_name (str) : name of the table for which the failed write attempt occured
    dataframe (pandas.DataFrame) : data to insert
    modifier (mssql_dataframe.core.modify) : class to modify SQL columns

    Returns
    -------
    dataframe (pandas.DataFrame) : data to insert that may have been adjust to conform to SQL data types

    """
    columns = pd.Series(failure.args[1], dtype="string")
    include_metadata_timestamps = ["_time_insert", "_time_update"]
    if isinstance(failure, custom_errors.SQLColumnDoesNotExist) and all(
        columns.isin(include_metadata_timestamps)
    ):
        for col in columns:
            msg = f"Creating column '{col}' in table '{table_name}' with data type 'datetime2'."
            logger.warning(msg)
            modifier.column(
                table_name, modify="add", column_name=col, data_type="datetime2"
            )

    else:
        raise failure

    return dataframe


import shutil
import json

with open("pc.py", "r", encoding="utf-8") as pc_file:
    pc_py = pc_file.read()

with open("pclibs\\arguments.py", "r", encoding="utf-8") as pc_file:
    arguments_py = pc_file.read()

with open("pclibs\\boilerplates.py", "r", encoding="utf-8") as pc_file:
    boilerplates_py = pc_file.read()

with open("pclibs\\emaillib.py", "r", encoding="utf-8") as pc_file:
    emaillib_py = pc_file.read()

with open("pclibs\\project.py", "r", encoding="utf-8") as pc_file:
    project_py = pc_file.read()

pc_py = pc_py.replace("from pclibs.arguments import Arguments", "").replace("from pclibs.project import Project", "")
project_py = project_py.replace("from .arguments import Arguments", "").replace("from .boilerplates import *", "")
project_py = project_py.replace("from .emaillib import Email", "")
project_py = project_py.replace("self.current_path = self.__get_current_path().parent", "self.current_path = self.__get_current_path()")

bundle_py = emaillib_py + "\n\n" + boilerplates_py + "\n\n" + arguments_py + "\n\n" + project_py + "\n\n" + pc_py

with open("dist\\pc.py", "w", encoding="utf-8") as bundle_file:
    bundle_file.write(bundle_py)

shutil.copy("config.json", "dist\\config.json")


class Solution:
    def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
        intervals.append(newInterval)
        intervals.sort(key=lambda x:x[0])

        res = []
        start = intervals[0][0]
        stop = intervals[0][1]

        for i in range(len(intervals)):
            if intervals[i][0] <= stop:
                stop = max(intervals[i][1], stop)
            else:
                res.append([start, stop])
                start = intervals[i][0]
                stop = intervals[i][1]

        res.append([start, stop])
        return res


import os
import numpy as np
import matplotlib.pyplot as plt
import h5py
from sklearn.metrics import r2_score
from pyplm.utilities import tools
from pyplm import utilities
import seaborn as sns

from scipy.ndimage import gaussian_filter1d

import jackknife_helpers as helpers

def plot_histograms(ax, models, bins=None, colors='default', labels=None):
    if colors == 'default':
        colors = ['k']
        [
            colors.append(c)
            for c in plt.rcParams['axes.prop_cycle'].by_key()['color']
        ]
    if labels == None:
        labels = ['true', 'inferred', 'cor-SC', 'cor-JK']
    if np.all(bins)==None:
        bins = np.linspace(models.min(), models.max(), 50)

    for i, mod in enumerate(models):
        params = tools.triu_flat(mod, k=1)
        n, x = np.histogram(params, bins, density=True)
        x = x[:-1]
        n = gaussian_filter1d(n, sigma=2)
        ax.plot(
            x, n,
            marker=',', ls='-', lw=2,
            c=colors[i],
            label=labels[i], zorder=10)
        # sns.kdeplot(params, marker=',', label=labels[i], ax=ax, c=colors[i], lw=2, ls='--')

def plot_correlations(ax, models, k=1, a = 0.25):

    ax.plot(tools.triu_flat(models[0], k=k), tools.triu_flat(models[0], k=k), marker=',', c='k')
    ax.plot(tools.triu_flat(models[0], k=k), tools.triu_flat(models[1], k=k), ls='none', alpha=a)
    ax.plot(tools.triu_flat(models[0], k=k), tools.triu_flat(models[2], k=k), ls='none', alpha=a)
    ax.plot(tools.triu_flat(models[0], k=k), tools.triu_flat(models[3], k=k), ls='none', alpha=a)
    # ax.set(ylim=[-2.75, 2.75])

    print(r2_score(tools.triu_flat(models[0], k=k), tools.triu_flat(models[1], k=k)))
    print(r2_score(tools.triu_flat(models[0], k=k), tools.triu_flat(models[2], k=k)))
    print(r2_score(tools.triu_flat(models[0], k=k), tools.triu_flat(models[3], k=k)))

plt.style.use('/Users/mk14423/Dropbox/mpl-styles/thesisbody.mplstyle')
FIGDIR = '/Users/mk14423/Documents/tempfigs'
save = False
grps = ['SK_N24_T1.5', 'SK_N48_T1.5']
new_file_grps=[
    # 'SK_N50', 'SK_N100', 'SK_N50_B1500_T1.2',
    'SK_N50_B750_T2.0', 'SK_N50_B1500_T2.0', 'SK_N50_B3000_T2.0']

'''
# multiple models!
fig, ax = plt.subplots(nrows=2, ncols=2)
colors = ['k']
[colors.append(c) for c in plt.rcParams['axes.prop_cycle'].by_key()['color']]
labels = ['true', 'inferred', 'cor-SC', 'cor-JK']

models, B = helpers.get_models(group=new_file_grps[3])
plot_histograms(ax[0, 0], models, colors=colors, labels=labels)
plot_correlations(ax[0, 1], models)

models, B = helpers.get_models(group=new_file_grps[4])
plot_histograms(ax[1, 0], models, colors=colors, labels=labels)
plot_correlations(ax[1, 1], models)
ax.legend()
ax[0, 0].legend()
if save is True:
    plt.savefig(os.path.join(FIGDIR, 'sigma_vs_B.png'))
plt.show()
'''

# example: (low B=750)
models, B = helpers.get_models(group=new_file_grps[0])
labels = ['true', 'PLM', 'cor-SC', 'cor-JK']
print(B)
on = True
if on == True:
    # distributions
    fig, ax = plt.subplots()
    plot_histograms(ax, models)
    ax.legend()
    ax.set(xlabel=r'$J_{ij}$', ylabel=r'$PDF$')
    plt.show()

on = False
if on == True:
    # imshows
    fig, ax = plt.subplots(nrows=2, ncols=2)
    ax = ax.ravel()
    for iA in range(0, ax.size):
        im = ax[iA].matshow(models[iA])
        # fig.colorbar(im, ax=ax)
        ax[iA].set(title=labels[iA])
    plt.show()

on = False
if on == True:
    # difference models and distributions
    fig, ax = plt.subplots(nrows=2, ncols=2)
    ax = ax.ravel()
    # vmin = models[0].min()
    # vmax = models[0].max()
    vmin = -0.05
    vmax = +0.05
    # let's do an difference distribution?
    diffs = []
    print('-----')
    for iA in range(0, 3):
        diff = models[iA + 1] - models[0]
        im = ax[iA].matshow(diff, vmin=vmin, vmax=vmax)
        ax[iA].set(title=labels[iA + 1])
        diffs.append(diff)
        print(np.mean(diff), np.std(diff))
    print('-----')
    fig.colorbar(im, ax=ax)
    diffs = np.array(diffs)
    cs = plt.rcParams['axes.prop_cycle'].by_key()['color']
    plot_histograms(ax=ax[-1], models=diffs, colors=cs)
    plt.show()

on = False
if on == True:
    # let's compare how the sc and jk corrections change the model..
    fig, ax = plt.subplots(1, 2)
    ax = ax.ravel()
    vmin = 1.07353515625 - (1.07353515625 * 0.5)
    vmax = 1.07353515625 + (1.07353515625 * 0.5)
    # let's set some vmax and vmin stuff to see if they're really similar
    # or whatever... so far I'm a little concerned that something isn't right..
    # matrix comparision.
    print(np.mean(models[1]/models[2]))
    print(np.mean(models[1]/models[3]))
    ax[0].matshow(models[1]/models[3], vmin=vmin, vmax=vmax)
    im = ax[1].matshow(models[1]/models[2], vmin=vmin, vmax=vmax)
    fig.colorbar(im, ax=ax[1])
    plt.show()

on = True
if on == True:
    fig, ax = plt.subplots()
    iMods = [2]
    cols = plt.rcParams['axes.prop_cycle'].by_key()['color']
    # cols
    for i in iMods:
        # plt.matshow(models[3])
        # plt.show()
        models, B = helpers.get_models(group=new_file_grps[i])
        models = np.abs(models)
        input_params = tools.triu_flat(models[0], k=1)
        plm_params = tools.triu_flat(models[1], k=1)
        sc_params = tools.triu_flat(models[2], k=1)
        jk_params = tools.triu_flat(models[3], k=1)

        jk_percentage_cor = (jk_params - plm_params) / plm_params
        sc_percentage_cor = (sc_params - plm_params) / plm_params
        # print(np.mean(selfcon_percentage_cor))
        print(1 / (np.mean(sc_percentage_cor) + 1))
        line, = ax.plot(
            (input_params), jk_percentage_cor,
            ls='none', zorder=2, marker='o', c=cols[2],
            # label=f'JK, B={B}'
            label='Jackknife'
            )
        # B={B}:
        line, = ax.plot(
            (input_params), sc_percentage_cor,
            ls='-', marker=',', c=line.get_color(), zorder=10, lw=2,
            # label=f'SC, B={B}',
            label='Self-consistency'
            )

        # ax.axhline(selfcon_percentage_cor, ls='-', marker=',', c=line.get_color(), lw=2, zorder=10)

        # let's do the absolute correction!
    ax.set(
        xlabel=r'$| J_{ij} ^{0} |$',
        ylabel=r'$\Delta | J_{ij}|$',
        # ylim=[-0.15, +0.05]
        # ylim=[-0.075, 0.025]
        ylim=[-0.15, 0.15]
    )
    ax.yaxis.set_major_locator(plt.MaxNLocator(6))
    ax.legend()
    plt.show()

    fig, ax = plt.subplots()
    iMods = [0, 1, 2]
    cols = plt.rcParams['axes.prop_cycle'].by_key()['color']
    ci = 0
    bins_both = [
        np.linspace(-0.15, 0, 200),
        np.linspace(-0.15, 0, 200),
        np.linspace(-0.075, 0.025, 200),
    ]
    for i in iMods:
        models, B = helpers.get_models(group=new_file_grps[i])
        models = np.abs(models)

        sc_percentage_cor = (models[2] - models[1]) / models[1]
        jk_percentage_cor = (models[3] - models[1]) / models[1]

        plot_histograms(
            ax, models=np.array([jk_percentage_cor]),
            bins=bins_both[ci],
            labels=[f'B={B}'], colors=[None],
            )
        ax.axvline(np.mean(sc_percentage_cor), ls='-', marker=',', c=cols[ci], lw=2)
        ci+=1
    ax.legend()
    ax.set(xlabel=r'$\Delta |J_{ij}|$', ylabel=r'$PDF$')
    plt.show()


#coding:utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import os
ROOT_DIR = os.path.abspath(os.path.dirname(__file__))
sys.path.append(ROOT_DIR+"/../Model")
from decision_tree_model import DecisionTreeModel
import numpy as np
import json

if __name__ == "__main__":
  # data = np.loadtxt(ROOT_DIR+"/../watermelon/watermelon_2.0.csv", dtype=str, delimiter=",", skiprows=0)
  # data = np.loadtxt(ROOT_DIR+"/../watermelon/watermelon_3.0.csv", dtype=str, delimiter=",", skiprows=0)
  data = np.loadtxt(ROOT_DIR+"/../watermelon/watermelon_3.0_x.csv", dtype=str, delimiter=",", skiprows=0)
  data = data[:,1:]
  ###测试data weights support，样本权重设置为1/m，则结果应该和不设置一样
  m, n = data.shape
  m -= 1
  data_weights = np.array([1.0/m]*m)
  ###测试data weights support，没有样本权重，则结果应该和设置为1/m一样
  data_weights = None
  # print(data)
  model = DecisionTreeModel()
  model.fit(data=data, algo_model="id3", data_weights=data_weights)
  # print(model.root["feature"])
  print(json.dumps(model.root, indent=4, ensure_ascii=False))

  ## predict train
  x = data[1:,:-1]
  y = data[1:,-1]
  predictions = model.predict(x)
  print(",".join(predictions))
  print(",".join(y))
  print("train accuracy:{}".format(model.accuracy(y, predictions)))

  dot = model.export_graphviz()
  print(dot.render(view=True, cleanup=True))


import requests, json, io, pandas, os
import html_parser

# reading query.csv file onto a pandas csv object
query_colnames = ["tags","is_answered","view_count","answer_count","score","last_activity_date","creation_date","last_edit_date","question_id","content_license","link","title","body","code"]
extracted_questions = "python_queries.csv"
run_data = pandas.read_csv(extracted_questions,header=0,names=query_colnames)

# extracting the question_ids column onto a list
question_ids=run_data.question_id.tolist()
json_dir = os.getcwd() + "/json_answers"
if not os.path.exists(json_dir):
    os.mkdir(json_dir)

for id in question_ids:
	print("Extracting the answers for query "+ str(id))
	query_answers = json_dir+"/query_answers" + str(id) +".json"
	request_statement = "https://api.stackexchange.com/2.3/questions/" +str(id) +"/answers?order=desc&sort=activity&site=stackoverflow&filter=withbody"
	r = requests.get(request_statement)
	scraped_data = json.loads(r.text)

	data_json = open(query_answers, "w")
	json.dump(scraped_data,data_json)
	data_json.close()

# reading from JSON file and writinc onto a CSV file
goal_file = "python_answers.csv"
fp = io.open(goal_file,"a", encoding = "utf-8")
fp.write('"is_accepted","score","last_activity_date","creation_date","answer_id","question_id","body","code"\n') #

for id in question_ids:

	answer_file = json_dir+"/query_answers" + str(id) +".json"
	f_out = io.open(answer_file, encoding = "utf-8")
	answers = json.loads(f_out.read())

	item = answers["items"]
	for i in range(len(item)):
		if "is_accepted" in item[i]:
			is_accepted = str(item[i]["is_accepted"])
		else:
			is_accepted = ""
		if "score" in item[i]:
			score = str(item[i]["score"])
		else:
			score = ""
		if "last_activity_date" in item[i]:
			last_activity_date = str(item[i]["last_activity_date"])
		else:
			last_activity_date = ""
		if "creation_date" in item[i]:
			creation_date = str(item[i]["creation_date"])
		else:
			creation_date = ""
		if "answer_id" in item[i]:
			answer_id = str(item[i]["answer_id"])
		else:
			answer_id = ""
		if "question_id" in item[i]:
			question_id = str(item[i]["question_id"])
		else:
			question_id = ""
		if "body" in item[i]:
			text = str(item[i]["body"])
			body = html_parser.parse_body(text)
			code = html_parser.parse_code(text)
		else:
			body = ""
			code = ""
		fp.write( '"' + is_accepted + '","' + score + '","' + last_activity_date  + '","' + creation_date + '","' + answer_id + '","' + question_id  + '","' + body  + '","' + code + '"\n') #

fp.close()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 15 12:33:14 2021

@author: igal
"""

import streamlit as st

import pandas as pd
from datetime import datetime, timedelta
import numpy as np
from pandas import DataFrame
import matplotlib.pyplot as plt
from dateutil.relativedelta import relativedelta
import seaborn as sns
from prophet import Prophet
import statsmodels.api as sm
import itertools
import datetime
from statsmodels.tsa.stattools import acf
from statsmodels.tsa.stattools import pacf
from statsmodels.tsa.seasonal import seasonal_decompose
from statsmodels.graphics.tsaplots import plot_pacf, plot_acf
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import RidgeCV
from sklearn.linear_model import Ridge
from sklearn.linear_model import Lasso
from sklearn import preprocessing
from sklearn.metrics import r2_score, median_absolute_error, mean_absolute_error
from sklearn.metrics import median_absolute_error, mean_squared_error, mean_squared_log_error

import scipy.stats as stats

from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.ensemble import RandomForestRegressor
from sklearn.neighbors import KNeighborsRegressor

#Création de differents partie
st.sidebar.title('Projet elecPymeteo')
st.sidebar.subheader('Menu')
dif_parti=["Dataviz régionale","Prévision de la consommation (série temporelle)", \
           "Prévision de la consommation (données météorologiques)",'Prévision de la production éolienne']
Partie=st.sidebar.radio(' ',options=dif_parti)

#Partie=st.selectbox('choix paragraphe', options=dif_parti)

#st.write('Partie: ', Partie)
df=pd.read_csv('donnee_regional.csv', sep=';', parse_dates=[3], squeeze=True, usecols=[0,1,2,3,4,5,6,7,8,9])
#st.write(df.head())
df=df.rename(columns={'Consommation (MW)':'Consommation'})

df=df.drop(['Code INSEE région','Nature','Date','Heure','Date - Heure'],axis=1)

df_Bour_FC=df[(df.Région=='Bourgogne-Franche-Comté')]
df_ile_d_fr=df[(df.Région=='Île-de-France')]
date= pd.date_range("2013-01-01", periods=148944, freq="0.5H")
df_ile_d_fr['date']=date
df_Bour_FC['date']=date

df_ile_defrance=df_ile_d_fr[['date','Consommation']]
df_ile_defrance=df_ile_defrance.set_index('date')
df_ile_defrance=df_ile_defrance.fillna(method='bfill')
df_ile_defrance_heure=df_ile_defrance.resample('H').sum()
df_ile_defrance_mois=df_ile_defrance.resample('M').sum()

#prepartion de données de la region Pays de la loir pour la previon de la production
df=df.rename(columns={'Eolien (MW)':'Eolien'})

df_P_d_loire=df[(df.Région=='Pays de la Loire')]

df_P_d_loire['date']=date

df_pays_d_loire=df_P_d_loire[['date','Eolien']]
df_pays_d_loire=df_pays_d_loire.set_index('date')
df_pays_d_loire=df_pays_d_loire.fillna(method='bfill')

df_pays_d_loire_3h=df_pays_d_loire.resample('3H').sum()
df_pays_de_loire_2020=df_pays_d_loire_3h['Eolien'].loc['2020-01-01 00:00:00':'2021-06-30 21:00:00']

df_geoloc=pd.read_csv('Géolocalisation_éoliennes.csv')

df_geoloc=df_geoloc.rename(columns={'Distance à la station (m)':'distance'})

df_vent_pdl=pd.read_csv('Vent_PDL.csv',sep=',',parse_dates=[0], squeeze=True)

df_vent_pdl=df_vent_pdl.replace('mq','0')

df_vent_pdl=df_vent_pdl.rename(columns={'Date - Heure':'date'})

coef_puissance=[]
for k in range(len(df_geoloc['distance'])):
    if df_geoloc['distance'][k]>50000:
        coef_puissance.append(0.001)
    else:
        coef=(-0.89*df_geoloc['distance'][k]+44950)/45000
        coef_puissance.append(coef)
df_geoloc['coef_puissance']=coef_puissance

vent_vitesse_pondere=[]

for k in range(len(df_vent_pdl)):
        som_vent=0.158*float(df_vent_pdl.iloc[k,1])+0.223*float(df_vent_pdl.iloc[k,2])+0.088*float(df_vent_pdl.iloc[k,3])+0.184*float(df_vent_pdl.iloc[k,4])
        vent_vitesse_pondere.append( som_vent/4)
df_vent_pdl['vent_vitesse_pondere']=vent_vitesse_pondere

df_vent_pdl=df_vent_pdl.set_index('date')

data_pays_loire_reg=df_vent_pdl.merge(right = df_pays_de_loire_2020, on = 'date', how = 'inner')

y=data_pays_loire_reg['Eolien']
X=data_pays_loire_reg['vent_vitesse_pondere']

y=pd.DataFrame(y)
X=pd.DataFrame(X)

train_size_eo=int(len(X) *0.8)
test_size_eo=int(len(X))-train_size_eo
X_train_eo=X[:train_size_eo]
X_test_eo=X[train_size_eo:]
y_train_eo=y[:train_size_eo]
y_test_eo=y[train_size_eo:]

y_nor=pd.DataFrame(preprocessing.StandardScaler().fit_transform(y))
def mean_absolute_percentage_error(y_true, y_pred):
    return np.mean(np.abs((y_true - y_pred) / y_true)) * 100

train_size=int(len(df_ile_defrance_mois) *0.7)
test_size=int(len(df_ile_defrance_mois))-train_size
X_train=df_ile_defrance_mois[:train_size]
X_test=df_ile_defrance_mois[train_size:]

df_ile_defrance_pro_M=df_ile_defrance_mois.rename(columns={'Consommation':'y'})
df_ile_defrance_pro_M=df_ile_defrance_pro_M.reset_index('date')
df_ile_defrance_pro_M=df_ile_defrance_pro_M.rename(columns={'date':'ds'})

train_size_p=int(len(df_ile_defrance_pro_M) *0.7)
test_size_p=int(len(df_ile_defrance_pro_M))-train_size_p
X_train_pro=df_ile_defrance_pro_M[:train_size_p]
X_test_pro=df_ile_defrance_pro_M[train_size_p:]

df_Bour_FC_conso=df_Bour_FC[['date','Consommation']]
df_Bour_FC_conso=df_Bour_FC_conso.set_index('date')

df_Bour_FC_conso=df_Bour_FC_conso.fillna(method='bfill')
df_Bour_FC_conso_heure=df_Bour_FC_conso.resample('H').sum()

df_Bour_FC_conso_jour=df_Bour_FC_conso.resample('D').sum()

df_Bour_FC_conso['year']=df_Bour_FC_conso.index.year
df_Bour_FC_conso['Month']=df_Bour_FC_conso.index.month
df_Bour_FC_conso['day']=df_Bour_FC_conso.index.day
df_Bour_FC_conso['hour']=df_Bour_FC_conso.index.hour
df_Bour_FC_conso['month_name']=df_Bour_FC_conso.index.month_name()
df_Bour_FC_conso['day_name']=df_Bour_FC_conso.index.day_name()

som_de_conso_par_jour=df_Bour_FC_conso.groupby('day_name').sum().Consommation.reset_index()

som_de_conso_par_mois=df_Bour_FC_conso.groupby('month_name').sum().Consommation.reset_index()

som_de_conso_par_heure=df_Bour_FC_conso.groupby('hour').sum().Consommation.reset_index()

if Partie==dif_parti[0]:
    st.title("Consommation électrique en Bourgogne-Franche-Comté")
    st.info("Dans cette section, nous proposons quelques datavisualisations permettant, à l'échelle d'une région, \
             de confirmer le caractère multipériodique de la consommation électrique.")
    options=['Consommation/jour','Consommation/mois','Consommation/heure', 'Profil de consommation selon la saison']
    choix=st.selectbox('Type de graphique', options=options)
    st.write('Graphique choisi : ', choix)

    if choix==options[0]:
        st.set_option('deprecation.showPyplotGlobalUse', False)
        plt.figure(figsize=(8, 4))
        order=['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']
        sns.barplot(x=som_de_conso_par_jour['day_name'], y=som_de_conso_par_jour['Consommation'], order=order)
        plt.xlabel('jour')
        plt.title('consommation par rapport aux jours')
        st.pyplot();
    elif choix==options[1]:
        plt.figure(figsize=(11, 6))
        order_m=['January','February','March','April','May','June','July','September','October','November','December']
        sns.barplot(x=som_de_conso_par_mois['month_name'], y=som_de_conso_par_mois['Consommation'], order=order_m)
        plt.xlabel('mois')
        plt.title('consommation par rapport aux mois')
        st.pyplot();
    elif choix==options[2]:
        plt.figure(figsize=(10, 6))
        sns.barplot(x=som_de_conso_par_heure['hour'], y=som_de_conso_par_heure['Consommation'])
        plt.xlabel('heure')
        plt.title('consommation par rapport aux heures')
        st.pyplot();
    else:
        plt.figure(figsize=(15, 6))
        plt.subplot(1,2,1)
        plt.plot(range(len(df_Bour_FC_conso_heure['Consommation'].loc['2013-01-01 00:00:00':'2013-01-07 23:00:00']))
         ,df_Bour_FC_conso_heure['Consommation'].loc['2013-01-01 00:00:00':'2013-01-07 23:00:00'],
         label='hiver')
        plt.plot(range(len(df_Bour_FC_conso_heure['Consommation'].loc['2013-04-01 00:00:00':'2013-04-07 23:00:00']))
         ,df_Bour_FC_conso_heure['Consommation'].loc['2013-04-01 00:00:00':'2013-04-07 23:00:00'],
         label='Printemps')
        plt.plot(range(len(df_Bour_FC_conso_heure['Consommation'].loc['2013-07-01 00:00:00':'2013-07-07 23:00:00']))
         ,df_Bour_FC_conso_heure['Consommation'].loc['2013-07-01 00:00:00':'2013-07-07 23:00:00'],
         label='été')

        plt.plot(range(len(df_Bour_FC_conso_heure['Consommation'].loc['2013-10-01 00:00:00':'2013-10-07 23:00:00']))
         ,df_Bour_FC_conso_heure['Consommation'].loc['2013-10-01 00:00:00':'2013-10-07 23:00:00'],
         label='automne')

        plt.xlabel('Heure')
        plt.title('Consommation de 2013')
        plt.legend();
        plt.subplot(1,2,2)

        plt.plot(range(len(df_Bour_FC_conso_heure['Consommation'].loc['2019-01-01 00:00:00':'2019-01-07 23:00:00']))
         ,df_Bour_FC_conso_heure['Consommation'].loc['2019-01-01 00:00:00':'2019-01-07 23:00:00'],
         label='hiver')
        plt.plot(range(len(df_Bour_FC_conso_heure['Consommation'].loc['2019-04-01 00:00:00':'2019-04-07 23:00:00']))
         ,df_Bour_FC_conso_heure['Consommation'].loc['2013-04-01 00:00:00':'2013-04-07 23:00:00'],
         label='Printemps')
        plt.plot(range(len(df_Bour_FC_conso_heure['Consommation'].loc['2019-07-01 00:00:00':'2019-07-07 23:00:00']))
         ,df_Bour_FC_conso_heure['Consommation'].loc['2019-07-01 00:00:00':'2019-07-07 23:00:00'],
         label='été')

        plt.plot(range(len(df_Bour_FC_conso_heure['Consommation'].loc['2019-10-01 00:00:00':'2019-10-07 23:00:00']))
         ,df_Bour_FC_conso_heure['Consommation'].loc['2019-10-01 00:00:00':'2019-10-07 23:00:00'],
         label='automne')

        plt.xlabel('Heure')
        plt.title('Consommation de 2019')
        plt.legend()
        plt.suptitle("Consommation d'une semaine type de chaque saison en 2013 et 2019",fontsize=20);
        st.pyplot();

elif Partie==dif_parti[1]:
    st.title("Prévision à l'aide des modèles traitant les séries temporelle")
    st.info("La consommation électrique présente un caractère multipériodique (annuel, hebdomadaire et quotidien). Nous pouvons \
            donc utiliser les modèles de prévision communément utilisés pour modéliser les séries temporelles.")
    Actuelle=pd.DataFrame(df_ile_defrance_mois.iloc[train_size:, 0])
    options=['SARIMA','Prophet']
    choix=st.selectbox('Choix du modèle', options=options)
    st.write('Modèle choisi : ', choix)
    if choix==options[0]:
#SARIMA(0,1,1)(1,1,0,12)
        model_manuelle_6= sm.tsa.statespace.SARIMAX(X_train,
                                    order=(0,1,1),
                                    seasonal_order=(1,1,1,12),
                                    enforce_stationarity=False,
                                    enforce_invertibility=False,
                                    freq='M')

# Fit the model
        resultat_manuelle_6=model_manuelle_6.fit()

# Resumé de Resultats
   # print(resultat_manuelle_6.summary())
        y_pred_m6=resultat_manuelle_6.predict(start =train_size, end=train_size+test_size-1)

        pred_int_conf_m6=resultat_manuelle_6.get_prediction(start=train_size, end=train_size+test_size-1)

        int_conf_m6=pred_int_conf_m6.conf_int()
        y_pred_m6=pd.DataFrame(y_pred_m6)
        y_pred_m6.reset_index(drop=True, inplace=True)
        y_pred_m6.index=X_test.index
        y_pred_m6['valeur_réelle'] = Actuelle['Consommation']
        y_pred_m6.columns = ['valeur_predite','valeur_réelle']
        #y_pred_m6.rename(columns=0:'valeur_predite'}, inplace=True)
        mape_m6=mean_absolute_percentage_error(y_pred_m6['valeur_réelle'],y_pred_m6['valeur_predite'])

        #st.write("l'erreur moyenne absolue du modèle est :", mape_m6)
        st.write("L'erreur moyenne absolue sur les données de test est de :", round(mape_m6,2), "%")
        st.text('Les graphiques suivants representent les valeurs observées et les valeurs prédites\n par le modèle SARMA')
        pred_m6=resultat_manuelle_6.predict(102, 124)#Prédiction
        df_pred_m6 = pd.concat([df_ile_defrance_mois, pred_m6])#Concaténation des prédictions
        pred_m6=resultat_manuelle_6.predict(102, 124)#Prédiction
        df_pred_m6 = pd.concat([df_ile_defrance_mois, pred_m6])
        fig = plt.figure(figsize=(20,8))
        plt.subplot(221)

        plt.plot(y_pred_m6['valeur_réelle'], color='blue', label='valeurs réelles')
        plt.plot(y_pred_m6['valeur_predite'], color='red', label='valeurs predite')
        plt.fill_between(int_conf_m6.index[1:],
                int_conf_m6.iloc[1:, 0],
                int_conf_m6.iloc[1:, 1], color='k', alpha=.2)
        plt.ylabel('consommation')
        plt.legend()
        plt.title('Valeurs actuelles et prédites avec intervalle de confiance de 95%');
        plt.subplot(222)

        plt.plot(y_pred_m6['valeur_réelle'], color='blue', label='valeurs réelles')
        plt.plot(y_pred_m6['valeur_predite'], color='red', label='valeurs predite')
        plt.ylabel('consommation')
        plt.legend()
        plt.title('Valeurs actuelles et prédites')
        plt.subplot(223)

        plt.plot(df_pred_m6) #Visualisation

        plt.title('previsions à horizon 24');
        plt.axvline(x= df_pred_m6.index[len(X_train)+len(X_test)], color='red'); # Ajout de la ligne verticale
        st.pyplot();
        plt.subplot(223)
    else:
        model_prophet = Prophet()
        model_prophet.fit(X_train_pro)
        future = model_prophet.make_future_dataframe(periods=31, freq='M')
        futur_forecast = model_prophet.predict(df=future)
        y_pred_prophet=futur_forecast['yhat']
        y_pred_prophet=pd.DataFrame(y_pred_prophet)
        y_pred_prophet.reset_index(drop=True, inplace=True)
        y_pred_prophet=y_pred_prophet.rename(columns={'yhat':'valeur_predite'})
        y_pred_prophet['ds']=df_ile_defrance_pro_M.ds
        y_pred_prophet['valeur_réelle'] =df_ile_defrance_pro_M['y']
        y_pred_prophet['yhat_upper']=futur_forecast['yhat_upper'].values
        y_pred_prophet['yhat_lower']=futur_forecast['yhat_lower'].values
        y_pred_prophet=y_pred_prophet.rename(columns={'ds':'date'})
        y_pred_prophet=y_pred_prophet.set_index('date')
        mape_pro1=mean_absolute_percentage_error(y_pred_prophet['valeur_réelle'],y_pred_prophet['valeur_predite'])

        #st.write("l'erreur moyenne absolue du modèle est :", mape_pro1)
        st.write("L'erreur moyenne absolue sur les données de test est de :", round(mape_pro1,2), "%")

        st.text('Les graphiques suivants representent les valeurs observées et les valeurs prédites\n par le modèle Prophet')
        fig = plt.figure(figsize=(15,6))
        plt.subplot(121)
        y_pred_prophet['valeur_réelle'].plot(figsize=(15,8), legend=True, color='blue', label='valeurs réelles')
        y_pred_prophet['valeur_predite'].plot(legend=True, color='red', figsize=(15,8), label='valeurs predite')
        plt.ylabel('consommation')
        plt.legend()
        plt.title('Valeurs actuelles et prédites');
        plt.subplot(122)
        plt.plot(y_pred_prophet['valeur_predite'], label='valeurs prédites')
        plt.plot(y_pred_prophet['valeur_réelle'], label='valeurs actuelles')

        plt.fill_between(y_pred_prophet['yhat_lower'].index,
                y_pred_prophet['yhat_upper'],
                y_pred_prophet['yhat_lower'], color='b', alpha=.2)
#plt.plot(y_pred_prophet['yhat_upper'],'--', label='valeurs prédites maximum')
#plt.plot(y_pred_prophet['yhat_lower'],'--',label='valeurs prédites minimum');
        plt.xlabel('date')
        plt.ylabel('consommation')
        plt.title(' Valeurs prédites et actuelles avec intervalle de confiance')
        plt.legend()
        st.pyplot();

elif Partie==dif_parti[2]:
    st.title("Prévision de la consommation grâce à des variables externes")
    st.info("La consommation électrique a un caractère périodique correspondant à l'organisation de notre société industrielle \
            mais dépend également fortement de la température extérieure. Nous allons ici prédire la consommation à l'aide de \
            modèles de régression s'appuyant sur ces 2 composantes.")

    st.subheader("Consommation en fonction de la température")

    ###   PREPARATION DES DONNEES METEO   ###

    #On prépare un dataframe unique à partir des dataframes mensuels récoltés
    df_meteo = pd.read_csv("Données_météo_complètes.csv", parse_dates = [2])

    df_meteo_idf = df_meteo[df_meteo["numer_sta"]==7149].loc[:,["date","t"]]
    df_meteo_idf.columns = ["Date - Heure", "Température (K)"]

    ### PREPARATION DES DONNEES ENERGETIQUES   ###

    données = pd.read_csv("donnee_regional.csv", sep =";")

    #A partir du dataframe des données, on nettoie les cellules vides de la colonne "Consommation (MW)" on met la colonne
    #temporelle au même format que le dataframe météo et on isole les données de la région IDF
    def preprocessing_ener_idf(df):
        df = df[df["Consommation (MW)"].notna()]
        df['Date - Heure'] = df['Date - Heure'].apply(lambda x: x[:-6])
        df['Date - Heure'] = pd.to_datetime(df['Date - Heure'], format = "%Y-%m-%dT%H:%M:%S")
        df = df.sort_values(by = ["Date - Heure"])
        df = df[df["Région"]=="Île-de-France"].loc[:,["Date - Heure","Consommation (MW)"]]
        return df

    df_energ_idf = données.copy()
    df_energ_idf = preprocessing_ener_idf(df_energ_idf)

    df_complet = df_energ_idf.merge(right = df_meteo_idf, on = "Date - Heure", how = "inner")
    df_complet["Jour de la semaine"] = df_complet["Date - Heure"].dt.weekday
    df_complet["Heure"] = df_complet["Date - Heure"].dt.hour
    df_complet["Mois"] = df_complet["Date - Heure"].dt.month
    df_complet = df_complet.set_index('Date - Heure')
    df_complet = df_complet.drop(df_complet[df_complet["Température (K)"]=='mq'].index,axis=0)
    df_complet["Température (K)"] = df_complet["Température (K)"].astype(float)
    df = df_complet["2013":"2019"] #on va établir notre modèle sur le période précédant la crise COVID

    #VISUALISATION DE LA CONSOMMATION PAR RAPPORT A LA TEMPERATURE
    fig1 = plt.figure(figsize=(10, 8))
    ax1 = fig1.add_subplot(111)
    ax1.scatter(df['Température (K)'], df['Consommation (MW)'], color='darkblue')
    ax1.set_xlabel('Température (K)')
    ax1.set_ylabel('Consommation (MW)')
    st.pyplot(fig1)

    ###########################################################################################
    st.subheader("Modélisation")
    data = df.loc[:,['Jour de la semaine','Mois','Heure', 'Température (K)']]
    target = df['Consommation (MW)']
    X_train, X_test, y_train, y_test = train_test_split(data, target, test_size=0.2, random_state=789)

    modèles = ("RandomForestRegressor","KNeighborsRegressor","Ridge","Lasso")
    choix = st.selectbox("Choix du modèle :", options = modèles)

    st.write("Modèle sélectionné :", choix)

    def train_model(choix):
        if choix == modèles[0]:
            model = RandomForestRegressor(bootstrap= True,
             max_depth= 50,
             max_features= 'sqrt',
             min_samples_leaf= 2,
             min_samples_split= 15,
             n_estimators= 700)
        elif choix == modèles[1]:
            nb_voisins = st.slider("n_neighbors :", 2, 14, step = 2)
            model = KNeighborsRegressor(n_neighbors = nb_voisins)
        elif choix == modèles[2]:
            model = RidgeCV()
        else :
            model = Lasso()
        model.fit(X_train, y_train)
        df_complet["Prédiction de consommation (MW)"] = model.predict(df_complet[['Jour de la semaine','Mois','Heure', 'Température (K)']])
        fig2 = plt.figure(figsize=(15,10))
        ax2 = fig2.add_subplot(111)
        ax2.plot(df_complet.loc[:,'Consommation (MW)'].resample("W").mean(), label = 'Consommation (MW)')
        ax2.plot(df_complet.loc[:,'Prédiction de consommation (MW)'].resample("W").mean(), label = 'Prédiction de consommation (MW)')
        ax2.legend()
        ax2.set_xlabel("Temps")
        ax2.set_ylabel("Consommation (MW)")
        ax2.set_title("Consommation lissée par semaine (2012 à 2021)")
        y_pred = model.predict(X_test)
        mape = np.mean(np.abs((y_test - y_pred)/ y_test))*100
        return mape, fig2

    mape, fig2 = train_model(choix)

    st.write("L'erreur moyenne absolue sur les données de test est de :", round(mape,2), "%")
    st.pyplot(fig2)

else:
    st.title("Prévision de la production éolienne")
    st.info("Tout comme nous pouvons prédire la consommation électrique d'une région à l'aide de la température, nous pouvons \
            prévoir la production électrique éolienne d'une région à l'aide de la vitesse du vent")

    st.subheader("Implantation géographique des éoliennes et des stations météorologiques utilisées")

    df = pd.read_csv("Géolocalisation_éoliennes.csv")

    nantes = [47.15, -1.61, "Nantes"]
    alencon = [48.45, 0.11, "Alençon"]
    tours = [47.44, 0.73, "Tours"]
    la_rochelle = [46.04, -1.405, "La Rochelle"]

    #CREATION DE LA CARTE
    import folium
    import json
    from folium.plugins import BeautifyIcon
    from streamlit_folium import folium_static

    lat_centre = 47.4
    long_centre = -0.9
    zoom = 7
    carte= folium.Map(location=[lat_centre,long_centre],zoom_start=zoom)

    for i in range(df.shape[0]):
        latitude = df.iloc[i,1]
        longitude = df.iloc[i,2]
        puissance = df.iloc[i,3]
        m = "<strong>" + "Puissance : " + "</strong>" + str(puissance) + " MW"\
        + "<br>Station la plus proche : " + df.iloc[i,5]
        folium.CircleMarker([latitude, longitude], radius = 5,color=None,fill_color ="red",
                        fill_opacity=0.5,popup = folium.Popup(m, max_width = 400)).add_to(carte)

    folium.Marker([nantes[0],nantes[1]], icon=folium.Icon(color='blue', icon='cloud'),popup = nantes[2]).add_to(carte)
    folium.Marker([alencon[0], alencon[1]], icon=folium.Icon(color='blue', icon='cloud'),popup = alencon[2]).add_to(carte)
    folium.Marker([tours[0], tours[1]], icon=folium.Icon(color='blue', icon='cloud'),popup = tours[2]).add_to(carte)
    folium.Marker([la_rochelle[0], la_rochelle[1]], icon=folium.Icon(color='blue', icon='cloud'),popup = la_rochelle[2]).add_to(carte)

    folium_static(carte)

    st.subheader("Production éolienne en fonction de la vitesse du vent")

    plt.figure(figsize=(8, 6))
    plt.scatter(data_pays_loire_reg['vent_vitesse_pondere'],data_pays_loire_reg['Eolien'],color='darkblue');
    plt.xlabel('Vitesse de vent')
    plt.ylabel("Production de l'éolien (kW)")
    #plt.title('Nuage de points entre production Eolienne et vitesse de vent');
    st.pyplot();

    st.subheader("Modélisation")

    options=['LinearRegression','Ridge','Lasso']
    choix=st.selectbox('Choix du modèle', options=options)
    st.write('Modèle choisi : ', choix)

    if choix==options[0]:
        model=LinearRegression()
    elif choix==options[1]:
        alphas_value=st.slider('alpha',min_value=0.01, max_value=8.0, step=.01)
        model=Ridge(alpha=alphas_value)
    else :
        alphas_value=st.slider('alpha',min_value=0.01, max_value=1.0, step=.01)
        model=Lasso(alpha=alphas_value)

    model.fit(X_train_eo, y_train_eo)
    st.write("Le score du modèle d'entraiment est :",   round(model.score(X_train_eo, y_train_eo),2))
    st.write('Le score du modèle de test  est :',   round(model.score(X_test_eo, y_test_eo),2))
    pred_test = model.predict(X_test_eo)
    pred_test=pd.DataFrame(pred_test)
    pred_test=pred_test.rename(columns={0:'valeur_predite'})
    y_prevision=pred_test
    new_index=y_test_eo.index
    y_prevision=y_prevision.set_index(new_index)
    y_prevision['valeur_observé']=y_test_eo['Eolien']
    y_pred_semaine=y_prevision.resample('D').sum()
    fig = plt.figure(figsize=(12,6))
    plt.plot(y_pred_semaine['valeur_predite'], label='valeurs prédites')
    plt.plot(y_pred_semaine['valeur_observé'], label='valeurs observées')
    plt.xlabel('date')
    plt.ylabel('Production (kW)')
    plt.legend()
    plt.title('Production Éolienne')
    st.pyplot();