from numpy import NaN
import torch
import visualizing as Vis
import matplotlib.pyplot as plt

def fit_AutoEncoder(data_loader, model, loss_func, optimizer, epochs, val_loader, graph_loss = False):

    #Setup showcase batch
    batch, target_batch = next(iter(val_loader))
    batch, target_batch = batch[0:5], target_batch[0:5]
    history = torch.cat((target_batch.cpu(), batch.cpu()),0)

    #Loss Variables
    train_losses = []
    val_losses = [NaN]

    for epoch in range(epochs):

        #Training Parameters
        model.train()
        train_loss = 0
        for img, target_img in data_loader:
            loss = loss_func(model(img), target_img)
            train_loss += loss
            loss.backward()
            optimizer.step()
            optimizer.zero_grad()

        #Evaluating
        model.eval()
        with torch.no_grad():
            val_loss = 0
            for img, target_img in val_loader:
                val_loss += loss_func(model(img), target_img)

        #Print Progress
        avgTrainLoss = (train_loss.item()/(len(data_loader.dataset)))*100
        avgValLoss = (val_loss.item()/(len(val_loader.dataset)))*100
        train_losses.append(avgTrainLoss)
        val_losses.append(avgValLoss)
        print("Completed epoch " + str(epoch + 1) + " out of " + str(epochs))
        print("The new model has training loss: " + "{:.6f}".format(avgTrainLoss))
        print("The new model has validation loss: " + "{:.6f}".format(avgValLoss) + "\n")
        history = torch.cat(((history,) + (model(batch).cpu(),)), 0)

    #Show loss graph
    if(graph_loss):
        graphLossHistory(train_losses, val_losses)

    return history

def fit_Classifier(data_loader, model, loss_func, optimizer, epochs, val_loader, graph_loss = False):

    #Loss Variables
    train_losses = []
    val_losses = [NaN]

    for epoch in range(epochs):

        #Training Parameters
        model.train()
        train_loss = 0
        for img, label in data_loader:
            loss = loss_func(model(img), label)
            train_loss += loss
            loss.backward()
            optimizer.step()
            optimizer.zero_grad()

        #Evaluating
        model.eval()
        with torch.no_grad():
            val_loss = 0
            for img, label in val_loader:
                val_loss += loss_func(model(img), label)

        #Print Progress
        avgTrainLoss = (train_loss.item()/(len(data_loader.dataset)))*100
        avgValLoss = (val_loss.item()/(len(val_loader.dataset)))*100
        train_losses.append(avgTrainLoss)
        val_losses.append(avgValLoss)
        print("Completed epoch " + str(epoch + 1) + " out of " + str(epochs))
        print("The new model has training loss: " + "{:.6f}".format(avgTrainLoss))
        print("The new model has validation loss: " + "{:.6f}".format(avgValLoss) + "\n")

    #Show loss graph
    if(graph_loss):
        graphLossHistory(train_losses, val_losses)

def fit_DeepDream(model, loss_func, optimizer, epochs, history_size = 5):

    ending_encoding = model.getEndingEncoding()
    loss_history = []
    weight_history = []

    for epoch in range(epochs):

        #Training Parameters
        model.train()
        loss = loss_func(model(), ending_encoding)
        loss_history.append(loss.item())
        weight_history.append(model.getWeights())
        loss.backward(retain_graph=True)
        optimizer.step()
        optimizer.zero_grad()

        #Evaluating
        if(epoch%10 == 0):
            print("Completed epoch " + str(epoch + 1) + " out of " + str(epochs) + " with loss " + str(loss) + "\n")

    history = createHistory(loss_history, weight_history, history_size)
    return history

def createHistory(loss_history, weight_history, history_size):
    #Needs to be done
    loss_diff = loss_history[0]-loss_history[len(loss_history)-1]
    loss_interval = loss_diff/(history_size-1)
    history = weight_history[0]
    for i in range(history_size-1):
        target_loss = loss_history[0]-((i+1)*loss_interval)
        smallest_diff = float('inf')
        best_epoch = 0
        for j in range(len(loss_history)):
            targetloss_diff = abs(loss_history[j]-target_loss)
            if targetloss_diff < smallest_diff:
                smallest_diff = targetloss_diff
                best_epoch = j
        history = torch.cat(((history, )+(weight_history[best_epoch],)),0)
    return history

def graphLossHistory(train_hist, val_hist):
    plt.figure(figsize=(20,6))
    plt.plot(train_hist)
    plt.plot(val_hist)
    plt.title('model loss')
    plt.ylabel('loss')
    plt.xlabel('epoch')
    plt.legend(['train', 'validation'], loc='upper right')
    plt.show()

def getInterpolations(img1, img2, size = 5):

    hybrids = []
    interpolationFactor = 1/(size - 1)

    for i in range(size - 2):
        hybrids.append(torch.lerp(img1, img2, (i + 1) * interpolationFactor))

    interpolationTuple = (img1,) + tuple(hybrids) + (img2,)
    return torch.cat(interpolationTuple,0)

def interpolationMerge(img1, img2, model, size = 5):
    encoding1 = model.encode(img1)
    encoding2 = model.encode(img2)
    interpolatedEncodings = getInterpolations(encoding1, encoding2, size)
    interpolatedDecodings = model.decode(interpolatedEncodings)
    #Vis.displayImages(interpolatedDecodings)
    return interpolatedDecodings

def save_model_state(model, opt, path):
    torch.save({
            'model_state_dict': model.state_dict(),
            'optimizer_state_dict': opt.state_dict(),
            }, path)

def load_model_state(model, opt, path):
    data = torch.load(path, map_location=torch.device('cpu'))
    model.load_state_dict(data['model_state_dict'])
    opt.load_state_dict(data['optimizer_state_dict'])

def labelMapping(animal):
    return {
        'cat': 0,
        'dog': 1,
        'fox': 2,
        'lion': 3,
        'wolf': 4,
        'tiger': 5,
        'leopard': 6,
        'cheetah': 7,
    }[animal]


import sys

sys.path.append("./")

from src.modalsound.model import SoundObj
from src.visualize import plot_point_cloud, plot_mesh
import numpy as np

obj = SoundObj("dataset/00002/00002.tet.obj")
obj.modal_analysis()

print(obj.get_frequency(0))

data = (obj.modes**2).sum(1)[:, :4]
plot_mesh(obj.surf_vertices, obj.surf_triangles, data).show()
plot_mesh(
    obj.surf_vertices, obj.surf_triangles, obj.get_triangle_neumanns([0, 1, 2, 3])
).show()

bm = obj.solve_by_BEM(0)

plot_mesh(
    obj.surf_vertices, obj.surf_triangles, np.abs(bm.get_dirichlet_coeff())
).show()


#!/usr/bin/env python
#------------------------------
"""
    python ~/LCLS/con-detector/Detector/examples/test_load_npz.py
"""

import numpy as np
from Detector.GlobalUtils import print_ndarr #, info_ndarr, divide_protected

if True:

        fname = 'mfxlx4219_0048_epix10k2M_mean.npy'
        npy=np.load(fname)
        print('Constants loaded from file: %s' % fname)
        print_ndarr(npy, 'npy')

        np.save('test.npy', npy)


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

import re

from platformcode import config, logger, platformtools
from core.item import Item
from core import httptools, scrapertools, servertools, tmdb

host = 'https://ievenn.com/'

def do_downloadpage(url, post=None, headers=None):
    data = httptools.downloadpage(url, post=post, headers=headers).data

    return data

def mainlist(item):
    return mainlist_pelis(item)

def mainlist_pelis(item):
    logger.info()
    itemlist = []

    itemlist.append(item.clone( title = 'Buscar película ...', action = 'search', search_type = 'movie', text_color = 'deepskyblue' ))

    itemlist.append(item.clone( title = 'Catálogo', action = 'list_all', url = host + 'seccion/cine/', search_type = 'movie' ))

    itemlist.append(item.clone( title = 'Por género', action = 'generos', search_type = 'movie' ))

    itemlist.append(item.clone( title = 'Por categoría', action = 'categorias', search_type = 'movie' ))

    itemlist.append(item.clone( title = 'Por idioma', action = 'idiomas', search_type = 'movie' ))

    return itemlist

def categorias(item):
    logger.info()
    itemlist = []

    itemlist.append(item.clone( action = 'list_all', title = 'Abejas', url = host + 'tema/abejas/', text_color = 'deepskyblue' ))
    itemlist.append(item.clone( action = 'list_all', title = 'Cine alemán', url = host + 'tema/cine-alemania/', text_color = 'deepskyblue' ))
    itemlist.append(item.clone( action = 'list_all', title = 'Cine Usa', url = host + 'tema/cine-usa/', text_color = 'deepskyblue' ))
    itemlist.append(item.clone( action = 'list_all', title = 'Contaminación', url = host + 'tema/contaminacion/', text_color = 'deepskyblue' ))
    itemlist.append(item.clone( action = 'list_all', title = 'Coronavirus', url = host + 'tema/coronavirus/', text_color = 'deepskyblue' ))
    itemlist.append(item.clone( action = 'list_all', title = 'Documental', url = host + 'tema/documental/', text_color = 'deepskyblue' ))
    itemlist.append(item.clone( action = 'list_all', title = 'Kids en castellano', url = host + 'seccion/kids/kids-espanol/', text_color = 'deepskyblue' ))
    itemlist.append(item.clone( action = 'list_all', title = 'Kids en VO', url = host + 'seccion/kids/kids-english/', text_color = 'deepskyblue' ))
    itemlist.append(item.clone( action = 'list_all', title = 'Rugby', url = host + 'tema/rugby/', text_color = 'deepskyblue' ))
    itemlist.append(item.clone( action = 'list_all', title = 'Segunda guerra mundial', url = host + 'tema/segunda-guerra-mundial/', text_color = 'deepskyblue' ))
    itemlist.append(item.clone( action = 'list_all', title = 'Toc', url = host + 'tema/toc/', text_color = 'deepskyblue' ))

    return itemlist

def idiomas(item):
    logger.info()
    itemlist = []

    itemlist.append(item.clone( title = 'Árabe', action = 'list_all', url = host + 'seccion/cine/arabic/', text_color='moccasin' ))
    itemlist.append(item.clone( title = 'Alemán', action = 'list_all', url = host + 'seccion/cine/deutsche/', text_color='moccasin' ))
    itemlist.append(item.clone( title = 'Castellano', action = 'list_all', url = host + 'seccion/cine/cine-espanol/', text_color='moccasin' ))
    itemlist.append(item.clone( title = 'Chino', action = 'list_all', url = host + 'seccion/cine/chinese/', text_color='moccasin' ))
    itemlist.append(item.clone( title = 'Francés', action = 'list_all', url = host + 'seccion/cine/cine-francais/', text_color='moccasin' ))
    itemlist.append(item.clone( title = 'Hindú', action = 'list_all', url = host + 'seccion/cine/hindi/', text_color='moccasin' ))
    itemlist.append(item.clone( title = 'Inglés', action = 'list_all', url = host + 'seccion/cine/cine-english/', text_color='moccasin' ))
    itemlist.append(item.clone( title = 'Italiano', action = 'list_all', url = host + 'seccion/cine/cine-italiano/', text_color='moccasin' ))
    itemlist.append(item.clone( title = 'Japonés', action = 'list_all', url = host + 'seccion/cine/japanese/', text_color='moccasin' ))
    itemlist.append(item.clone( title = 'Portugués', action = 'list_all', url = host + 'seccion/cine/portugues/', text_color='moccasin' ))

    itemlist.append(item.clone( title = 'Subtitulado Vose', action = 'list_all', url = host + 'tema/subtitulos/', text_color='moccasin' ))
    itemlist.append(item.clone( title = 'Subtitulado VO', action = 'list_all', url = host + 'tema/subtitles/', text_color='moccasin'))

    return itemlist

def generos(item):
    logger.info()
    itemlist = []

    data = do_downloadpage(host)

    bloque = scrapertools.find_single_match(data,'>English<(.*?)>Inter<')

    matches = scrapertools.find_multiple_matches(bloque,'(.*?)')

    for url, tit in matches:
        if '/tv-series/' in url or '/seccion/' in url: continue

        elif tit == 'Subtitles': continue
        elif tit == 'Subtítulos': continue

        if 'eng' in url: tit = tit + ' (Eng)'

        itemlist.append(item.clone( title = tit, url = url, action = 'list_all', text_color = 'deepskyblue' ))

    return sorted(itemlist, key=lambda it: it.title)

def list_all(item):
    logger.info()
    itemlist = []

    data = do_downloadpage(item.url)
    data = re.sub(r'\n|\r|\t|\s{2}| ', '', data)

    matches = re.compile('(.*?)')
        if not url or not title: continue

        title = title.replace('–', '-')

        lang = scrapertools.find_single_match(match, '.*?>(.*?)')
        if lang == 'Español': lang = 'Esp'
        elif lang == 'English': lang = 'Ing'
        elif lang == 'Deutsche': lang = 'Ale'
        elif lang == 'Chinese': lang = 'Chi'
        elif lang == 'Français': lang = 'Fra'
        elif lang == 'Hindi': lang = 'Hin'
        elif lang == 'Italiano': lang = 'Ita'
        elif lang == 'Arabic': lang = 'Arb'
        elif lang == 'Japanese': lang = 'Jap'

        elif 'Portug' in lang: lang = 'Por'

        year = scrapertools.find_single_match(title, '-(.*?)-').strip()
        if not year: year = '-'

        if '-' in title: title = scrapertools.find_single_match(title, '(.*?)-').strip()

        thumb = scrapertools.find_single_match(match, 'style="background-image: url(.*?);')
        thumb = thumb.replace('(', '').replace(')', '')
        if thumb.startswith('//'): thumb = 'https:' + thumb

        itemlist.append(item.clone( action='findvideos', url = url, title = title, thumbnail = thumb, languages = lang,
                                    contentType = 'movie', contentTitle = title, infoLabels = {'year': year} ))

    tmdb.set_infoLabels(itemlist)

    if itemlist:
        if '<nav class="navigation pagination"' in data:
            next_url = scrapertools.find_single_match(data, '.*?href="(.*?)"')

            if next_url:
                if '/page/' in next_url:
                    itemlist.append(item.clone( title='Siguientes ...', url=next_url, action='list_all', text_color='coral' ))

    return itemlist

def findvideos(item):
    logger.info()
    itemlist = []

    data = do_downloadpage(item.url)

    url = scrapertools.find_single_match(data,'div class="post-format-meta.*?<iframe.*?src="(.*?)"')

    if url:
        if '/hqq.' in url or '/waaw.' in url or '/netu.' in url:
            platformtools.dialog_notification(config.__addon_name, 'Requiere verificación [COLOR red]reCAPTCHA[/COLOR]')
            return

        elif '/ronemo.com/' in url:
            platformtools.dialog_notification(config.__addon_name, 'Servidor [COLOR tan]No Soportado[/COLOR]')
            return

        if not url.startswith("http"): url = "https:" + url

        lng = item.languages

        servidor = servertools.get_server_from_url(url)
        servidor = servertools.corregir_servidor(servidor)

        itemlist.append(Item( channel = item.channel, action = 'play', title = '', server = servidor, url = url, language = lng ))

    return itemlist

def search(item, texto):
    logger.info()
    try:
        item.url = host + '?s=' + texto.replace(" ", "+")
        return list_all(item)
    except:
        import sys
        for line in sys.exc_info():
            logger.error("%s" % line)
        return []


#12.Sort list with Quicksort Algorithm
def qsort(l):
    if l==[]:
        return []
    return qsort([x for x in l[1:] if x<l[0]])+l[0:1]+ \
           qsort([x for x in l[1:] if x>=l[0]])

l = [12,34,2,6,9,11,9]
print(qsort(l)) #[2, 6, 9, 9, 11, 12, 34]


import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(101)
tf.set_random_seed(101)

x = np.linspace(0, 50, 50)
y = np.linspace(0, 50 ,50)

x += np.random.uniform(-4, 4, 50)
y += np.random.uniform(-4, 4, 50)

plt.scatter(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()

n = len(x)

X = tf.placeholder('float')
Y = tf.placeholder('float')

W = tf.Variable(np.random.randn(), name = 'W')
b = tf.Variable(np.random.randn(), name = 'b')

learning_rate = 0.01
training_epoch = 5000

y_prediction = tf.add(tf.multiply(X,W), b)

cost = tf.reduce_sum(tf.pow(y_prediction-Y, 2))/(2*n)
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

init = tf.global_variables_initializer()

with tf.Session() as sess:

  sess.run(init)

  for epoch in range(training_epoch):

    for (x1,y1) in zip(x,y):
        sess.run(optimizer, feed_dict = {X : x1, Y : y1})

    if (epoch+1)%75 == 0:

        c = sess.run(cost, feed_dict = {X : x, Y : y})
        print('Epoch: ',(epoch+1), 'Cost: ',c, 'W: ',sess.run(W), 'b: ', sess.run(b))

  training_cost = sess.run(cost, feed_dict = {X : x, Y : y})
  weight = sess.run(W)
  bias = sess.run(b)

prediction = weight*x + bias

print('Training Cost:',training_cost, 'Weight: ', weight, 'Bias: ', bias)

plt.plot(x,y,'go',label = 'Original_data')
plt.plot(x,prediction,label = 'Training_data')
plt.title("Learning Linear Regression")

plt.legend()
plt.show()


# if e else ela utiliza de operadores racionales para exibir o ejecutar el codigo
# Switch Case definida qque entra en una estructura de caso

# for e uma estructura de repeticion que cmposta por indice
# while ele uma estructura de repeticion que e baseada en operadores relaciones

nome = input('Digite su nome >>')
idade = int(input('Digite su idade >>'))

nota1 = float(input('Digite su nota >>'))
nota2 = float(input('Digite su nota >>'))

media = (nota1 + nota2) / 2

alumno = {

    "Nome" : nome,
    "Idade" : idade,
    "Nota 1" : nota1,
    "Nota 2" : nota2,
    "Media" : media,

}

cond = int(input('''
    Digite una opcion
    1) Nome
    2) Idade
    3) Nota 1
    4) Nota 2
    5) Media
    >>>>>
                 '''))

if cond == 1:
    print("El nombre del alumno es",alumno["Nombre"])

elif cond == 2:
    print ("La edad de ",alumno['Nome'],"es:",alumno['Idade'])
elif cond ==3:
    print ('Su primera nota fue:',alumno ['Nota 1'] )
elif cond == 4:
    print ('Su segunda nota fue',alumno ["Nota 2"] )
elif cond == 5:
    print ('Su media fue ',alumno ["Media"], ' ')


#!/usr/bin/python3

# http://www.e-disclosure.ru/Event/Page?companyId=5727&year=2019

#disclosure_himprom = "http://www.e-disclosure.ru/portal/company.aspx?id=5727"
#disclosure_himprom = "input\himprom_2019.html"
disclosure_himprom = "http://www.e-disclosure.ru/Event/Page?companyId=5727&year=2019" # ссылку взял из console-network-XHR

import requests
from bs4 import BeautifulSoup
import csv
# pip install beautifulsoup4
# pip install lxml
import re

# with open(disclosure_himprom, "r", encoding="utf-8") as f:

  # contents = f.read()

  # soup = BeautifulSoup(contents, 'lxml')

  # for link in soup.find_all('a'):
    # if ("Выплаченные доходы по эмиссионным ценным бумагам эмитента" in link.contents):
      # print(link) # .get('href'))
      # #print(link.contents)

elements_found = []

def get_html( url ):
    r = requests.get(url)    # Получим метод Response
    r.encoding = 'utf8'
    return r.text   # Вернем данные объекта text

def get_bsoup_data( html ):
  soup = BeautifulSoup( html, 'lxml' )

  for link in soup.find_all('a'):
    if ("Выплаченные доходы по эмиссионным ценным бумагам эмитента" in link.contents):
      #print(link.get('href'))
      elements_found.append(link.get('href'))

  return elements_found

def get_bsoup_in_report( html ):
  elements_found = []  # обнуляем
  soup = BeautifulSoup( html, 'lxml' )

  return soup.find('div', id='cont_wrap').text

if __name__ == '__main__':

  # сначала находим все ссылки на события выплат
  data_links = get_bsoup_data(get_html(disclosure_himprom))

  print(data_links)

  # скачиваем по полученным ссылкам
  if data_links is not None:
    for link in data_links:
      print("---------------------------------------------------------------")
      data = get_bsoup_in_report(get_html(link))
      #print(data)
	  # находим дату и дивиденд
      # пример
	  # Размер дивиденда, начисленного на одну привилегированную именную акции типа А – 0,142 рубля.
	  # Размер дивиденда, начисленного на одну привилегированную акцию типа А -0,0882 рубля.
      date = re.findall(r'\d{2}\.\d{2}\.\d{4}', data)[-1]
      print(date)
      res = re.findall(r'Размер дивиденда, начисленного на одну привилегированную акцию.*?\.', str(data))
      print(res)
      print(len(res))
        #print(i)


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import math
import sys

from ml_serving.drivers import driver
import numpy as np
import time

import facenet
import serving_hook

class Context(object):
    pass

def main(args):
    dataset = facenet.get_dataset(args.data_dir)
    # Check that there are at least one training image per class
    for cls in dataset:
        assert len(cls.image_paths) > 0, 'There must be at least one image for each class in the dataset'

    paths, labels = facenet.get_image_paths_and_labels(dataset)

    print('Number of classes: %d' % len(dataset))
    print('Number of images: %d' % len(paths))

    # Load the model
    print('Loading feature extraction model')

    # Load driver
    drv = driver.load_driver(args.driver)
    # Instantinate driver
    serving = drv(
        preprocess=serving_hook.preprocess,
        postprocess=serving_hook.postprocess,
        init_hook=serving_hook.init_hook,
        classifier=args.classifier,
        use_tf='False',
        use_face_detection='True',
        face_detection_path=args.face_detection_path
    )
    serving.load_model(
        args.model,
        inputs='input:0,phase_train:0',
        outputs='embeddings:0',
        device=args.device,
        flexible_batch_size=True,
    )

    # Run forward pass to calculate embeddings
    print('Calculating features for images')
    time_requests = 0.0
    epochs = 2
    start_time = time.time()
    for j in range(epochs):
        for path in paths:
            print('Processing %s...' % path)
            with open(path, 'rb') as f:
                data = f.read()

            t = time.time()

            feed_dict = {'input': np.array(data)}
            outputs = serving.predict_hooks(feed_dict, context=Context())

            delta = (time.time() - t) * 1000
            time_requests += delta

    duration = float(time.time() - start_time)
    print()
    print('Total time: %.3fs' % duration)
    per_request_ms = float(time_requests) / epochs / len(paths)
    print('Time per request: %.3fms' % per_request_ms)

    speed = 1 / (per_request_ms / 1000)
    print('Speed: {} sample/sec'.format(speed))

def parse_arguments(argv):
    parser = argparse.ArgumentParser()

    parser.add_argument(
        'data_dir',
        type=str,
        help='Path to the data directory containing images.'
    )
    parser.add_argument(
        '--model',
        type=str,
        help='Path to .xml openVINO IR file',
        required=True,
    )
    parser.add_argument(
        '--classifier',
        type=str,
        help='Path to classifier .pkl file',
        required=True,
    )
    parser.add_argument(
        '--face-detection-path',
        type=str,
        help='Path to face-detection .xml openVINO IR file',
        required=True,
    )

    parser.add_argument(
        '--device',
        help='Device for openVINO.',
        default="CPU",
        choices=["CPU", "MYRIAD"]
    )
    parser.add_argument(
        '--driver',
        help='Driver for inference.',
        default="tensorflow",
    )
    parser.add_argument(
        '--batch_size',
        type=int,
        help='Number of images to process in a batch.',
        default=1
    )

    parser.add_argument(
        '--image_size',
        type=int,
        help='Image size (height, width) in pixels.',
        default=160
    )
    return parser.parse_args(argv)

if __name__ == '__main__':
    main(parse_arguments(sys.argv[1:]))


from django.test import TestCase
from django.contrib.auth import get_user_model
from django.urls import reverse

from core.apps.products.models import (
    Product,
    Category,
    Tag,
)
from tests.models_setup import ModelsSetUp

User = get_user_model()

class ProductsViewsTest(ModelsSetUp):
    def setUp(self) -> None:
        super().setUp()
        self.client.force_login(self.user)

    def test_product_all_page(self):
        response = self.client.get(reverse('products:home'))
        assert response.status_code == 200
        assert str(response.context[0]['page_obj'][0]) == str(self.product)

    def test_product_detail_page(self):
        response = self.client.get(reverse('products:detail', args=[self.product.id]))
        assert response.status_code == 200
        assert 'Test_product' in str(response.context[0]['product'])

    def test_product_detail_page_blacklist1(self):
        self.client.force_login(self.user2)
        self.user2.blacklist.blocked_users.add(self.user)
        response = self.client.get(reverse('products:detail', args=[self.product.id]))
        assert response.status_code == 302
        assert response.url == reverse('products:home')

    def test_product_detail_page_blacklist2(self):
        self.client.force_login(self.user2)
        self.user.blacklist.blocked_users.add(self.user2)
        response = self.client.get(reverse('products:detail', args=[self.product.id]))
        assert response.status_code == 302
        assert response.url == reverse('products:home')

    def test_product_add_page(self):
        response = self.client.get(reverse('products:add'))
        assert response.status_code == 200

    def test_product_add_view_success(self):
        self.product.delete()
        response = self.client.post(reverse('products:add'), data={
            'title': 'test_product',
            'category': str(self.category.id),
            'price': '50',
            'discount_price': '40',
            'description': 'test_description',
        })
        assert response.status_code == 302
        assert response.url == reverse('products:detail', args=[Product.objects.first().pk])

    def test_product_edit_page(self):
        response = self.client.get(reverse('products:edit', args=[self.product.id]))
        assert response.status_code == 200
        response_html = response.content.decode('utf-8')
        assert f'Edit product - {self.product.title.title()}' in response_html

        self.client.logout()
        self.client.force_login(self.user2)
        response = self.client.get(reverse('products:edit', args=[self.product.id]), follow=True)
        assert response.status_code == 403

    def test_product_edit_post_success(self):
        response = self.client.post(reverse('products:edit', args=[self.product.id]), data={
            'title': 'test_product_edited',
            'category': str(self.category.id),
            'price': '1',
            'discount_price': '0',
            'description': 'test_description_edited',
        }, follow=True)
        assert response.status_code == 200
        assert Product.objects.get(id=self.product.id).title == 'Test_product_edited'
        response_html = response.content.decode('utf-8')
        assert 'Product succesfully updated.' in response_html

    def test_product_remove_page(self):
        response = self.client.get(reverse('products:remove', args=[self.product.id]))
        assert response.status_code == 200
        response_html = response.content.decode('utf-8')
        assert f'Are You sure you want to delete {self.product.title}?' in response_html
        self.assertTemplateUsed(response, 'products/product_remove_confirm.html')

    def test_product_remove_post_success(self):
        response = self.client.post(reverse('products:remove', args=[self.product.id]))
        assert response.status_code == 302
        assert Product.objects.count() == 1
        assert not Product.objects.filter(id=self.product.id)

    def test_product_remove_forbidden(self):
        self.client.force_login(self.user2)
        response = self.client.get(reverse('products:remove', args=[self.product.id]))
        assert response.status_code == 403

class CategoryViewTest(ModelsSetUp):
    def test_category_page(self):
        response = self.client.get(reverse('products:category', args=[self.category.name]))
        assert response.status_code == 200
        assert 'test_category' == str(response.context[0]['category_name'])

    def test_category_page_blacklist1(self):
        self.client.force_login(self.user2)
        self.user2.blacklist.blocked_users.add(self.user)
        response = self.client.get(reverse('products:category', args=[self.category.name]))
        assert response.status_code == 200
        assert len(response.context[0]['page_obj']) == 0

    def test_category_page_blacklist2(self):
        self.client.force_login(self.user2)
        self.user.blacklist.blocked_users.add(self.user2)
        response = self.client.get(reverse('products:category', args=[self.category.name]))
        assert response.status_code == 200
        assert len(response.context[0]['page_obj']) == 0


__author__ = 'roeiherz'

def URLify(x, n):
    """"
    input: "Mr John Smith   ", 13
    output: "Mr%20John%20Smith"
    """
    # not inplace
    new_x = []
    for c in x:
        if c == ' ':
            new_x.append('%20')
        else:
            new_x.append(c)

    new_x = new_x[:n]
    print(''.join(new_x))

    # not inplace 2
    arr = [chunk for chunk in x.split(' ') if chunk != '']
    print('%20'.join(arr))

if __name__ == '__main__':
    "Write a method to replace all spaces in a string '%20'. You are given the 'true' length of the string"
    URLify("Mr John Smith   ", 13)


import requests
from helpers import GenericImages as GI
from helpers import cache
import concurrent.futures

#------------------------------------------------------------------------------------------------------

def getMatchIDs(api, shard, puuid):
    url = f"https://{shard}.api.riotgames.com/lol/match/v5/matches/by-puuid/{puuid}/ids"
    response = requests.get(url, params={'api_key':api, 'count':20})
    resp = response.json()
    return resp

#------------------------------------------------------------------------------------------------------

def getAllMatchDetails(api, shard, matchID):
    with concurrent.futures.ThreadPoolExecutor() as executor:
        result = executor.map(getMatchDetails, [api]*len(matchID), [shard]*len(matchID), matchID)
    return list(result)

def getMatchDetails(api, shard, id):
    url = f"https://{shard}.api.riotgames.com/lol/match/v5/matches/{id}"
    response = requests.get(url, params={'api_key':api})
    resp = response.json()
    return(resp)

#------------------------------------------------------------------------------------------------------

def getMatchInfo(data):
    match_info_list = []

    for key in data:
        match_info = {}
        match_info['QueueID'] = key['info']['queueId']
        match_info['QueueType'] = 'Other'

        if match_info['QueueID'] == 420:
            match_info['QueueType'] = 'Ranked Solo'
        elif match_info['QueueID'] == 440:
            match_info['QueueType'] = 'Ranked Flex'
        elif match_info['QueueID'] == 430:
            match_info['QueueType'] = 'Normal Blind'
        elif match_info['QueueID'] == 400:
            match_info['QueueType'] = 'Normal Draft'
        elif match_info['QueueID'] == 450:
            match_info['QueueType'] = 'ARAM'
        elif match_info['QueueID'] == 830:
            match_info['QueueType'] = 'Co-op [Intro]'
        elif match_info['QueueID'] == 840:
            match_info['QueueType'] = 'Co-op [Beginner]'
        elif match_info['QueueID'] == 850:
            match_info['QueueType'] = 'Co-op [Intermediate]'

        match_info['GameDuration'] = key['info']['gameDuration']
        match_info['GameTime'] = f"{int(key['info']['gameDuration']/60)}m {key['info']['gameDuration']%60}s"
        match_info_list.append(match_info)
        match_info = {}

    return match_info_list

def getMatchPlayersDetails(version, data):
    match_info = getMatchInfo(data)
    match_players_info = []

    for i in range(len(data)):
        players_info = []
        player_data = {}

        for player in data[i]['info']['participants']:
            # General
            player_data['PlayerName'] = player['summonerName']
            player_data['PlayerLevel'] = player['champLevel']
            player_data['Champion'] = player['championName']
            player_data['PlayerTeam'] = 'Blue' if player['teamId'] == 100 else 'Red'
            player_data['Win'] = player['win'] if match_info[i]['GameDuration'] > 240 else 'Remake'
            # KDA
            player_data['Kills'] = player['kills']
            player_data['Deaths'] = player['deaths']
            player_data['Assists'] = player['assists']
            player_data['KDA'] = "Perfect" if player_data['Deaths'] == 0 else round(((player['kills'] + player['assists']) / player_data['Deaths']), 2)
            # CS
            player_data['LaneMinionsKilled'] = player['totalMinionsKilled']
            player_data['NeutralMinionsKilled'] = player['neutralMinionsKilled']
            player_data['TotalMinionsKilled'] = player_data['NeutralMinionsKilled'] + player_data['LaneMinionsKilled']
            player_data['CSPerMinute'] = round(player_data['TotalMinionsKilled'] / ((match_info[i]['GameDuration'])/60), 2)
            # Vision
            player_data['VisionScore'] = player['visionScore']
            player_data['ControlWards'] = player['visionWardsBoughtInGame']
            player_data['WardsPlaced'] = player['wardsPlaced']
            player_data['WardsDestroyed'] = player['wardsKilled']
            # Damage
            player_data['DamageToChampions'] = player['totalDamageDealtToChampions']
            player_data['DamageTaken'] = player['totalDamageTaken']
            # Images
            player_data['ChampionImage'] = GI.getChampImage(version, player['championName'])
            player_data['Keystone'] = GI.getRuneImage(version, player["perks"]["styles"][0]["selections"][0]["perk"])
            player_data['SecondaryRune'] = GI.getRuneImage(version, player["perks"]["styles"][1]['style'])
            player_data['Item0'] = GI.getItemImage(version, player['item0'])
            player_data['Item1'] = GI.getItemImage(version, player['item1'])
            player_data['Item2'] = GI.getItemImage(version, player['item2'])
            player_data['Item3'] = GI.getItemImage(version, player['item3'])
            player_data['Item4'] = GI.getItemImage(version, player['item4'])
            player_data['Item5'] = GI.getItemImage(version, player['item5'])
            player_data['Item6'] = GI.getItemImage(version, player['item6'])
            player_data['Summoner1'] = GI.getSummonerSpellImage(version, player['summoner1Id'])
            player_data['Summoner2'] = GI.getSummonerSpellImage(version, player['summoner2Id'])

            players_info.append(player_data)
            player_data = {}

        match_players_info.append(players_info)

    return match_players_info

#------------------------------------------------------------------------------------------------------


import requests
from bs4 import BeautifulSoup

class RentScraper:

    def __init__(self):

        self.apartment_url = "https://www.zillow.com/seattle-wa/rentals/?searchQueryState=%7B%22mapBounds%22%3A%7B" \
                             "%22north%22%3A47.80583778225086%2C%22east%22%3A-122.14910203027345%2C%22south%22%3A47" \
                             ".41978724907133%2C%22west%22%3A-122.54048996972658%7D%2C%22mapZoom%22%3A11%2C" \
                             "%22isMapVisible%22%3Atrue%2C%22filterState%22%3A%7B%22price%22%3A%7B%22max%22%3A414517" \
                             "%7D%2C%22beds%22%3A%7B%22min%22%3A1%7D%2C%22fore%22%3A%7B%22value%22%3Afalse%7D%2C%22mp" \
                             "%22%3A%7B%22max%22%3A2200%7D%2C%22auc%22%3A%7B%22value%22%3Afalse%7D%2C%22nc%22%3A%7B" \
                             "%22value%22%3Afalse%7D%2C%22fr%22%3A%7B%22value%22%3Atrue%7D%2C%22fsbo%22%3A%7B%22value" \
                             "%22%3Afalse%7D%2C%22cmsn%22%3A%7B%22value%22%3Afalse%7D%2C%22fsba%22%3A%7B%22value%22" \
                             "%3Afalse%7D%7D%2C%22isListVisible%22%3Atrue%2C%22usersSearchTerm%22%3A%22Seattle%20WA" \
                             "%22%2C%22regionSelection%22%3A%5B%7B%22regionId%22%3A16037%2C%22regionType%22%3A6%7D%5D" \
                             "%2C%22pagination%22%3A%7B%7D%7D"
        self.user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) " \
                          "Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.79"
        self.accent_language = "en-US,en;q=0.9"
        self.header = {
            "User-Agent": self.user_agent,
            "Accept-Language": self.accent_language
        }

        response = requests.get(self.apartment_url, headers=self.header)
        self.soup = BeautifulSoup(response.content, "html.parser")

        self.prices = []
        self.addresses = []
        self.urls = []
        self.rental_data = []

    def get_price(self):
        listings = self.soup.find_all(name="span", class_="PropertyCardWrapper__StyledPriceLine-srp__sc-16e8gqd-1 "
                                                          "iMKTKr")
        for apartment in listings:
            price = apartment.text.split("+")[0].split("/")[0]
            self.prices.append(price)
        return self.prices

    def get_address(self):
        listings = self.soup.find_all(name="address")
        for apartment in listings:
            address = apartment.text
            self.addresses.append(address)
        return self.addresses

    def get_url(self):
        listings = self.soup.find_all(name="a", class_="StyledPropertyCardDataArea-c11n-8-84-3__sc-yipmu-0 jnnxAW "
                                                       "property-card-link")
        for apartment in listings:
            url_text = apartment['href']
            if "https://www.zillow.com/" not in url_text:
                url = f"https://www.zillow.com{url_text}"
            else:
                url = url_text
            self.urls.append(url)
        return self.urls

    def get_data(self):
        prices = self.get_price()
        addresses = self.get_address()
        urls = self.get_url()

        for num in range(0, len(prices) - 1):
            apartment = {
                "Price": prices[num],
                "Address": addresses[num],
                "URL": urls[num]
            }
            self.rental_data.append(apartment)
        return self.rental_data


from bisect import bisect_left

# 3명의 합이 3이 되도록
# start, mid, end
n = int(input())
students = list(map(int, input().split()))
students.sort()

answer = 0
# 3포인터
# 각 start의 경우에서 mid, end 구해보기
for start in range(n-2):
    mid = start+1
    end = n-1
    while mid < end:
        score = students[start]+students[mid]+students[end]

        if score == 0:
            #
            if students[mid] == students[end]:
                # 같은 수 개수만큼 더해주기
                answer += end-mid
            else:
                # 개수기 때문에 +1
                answer += end-bisect_left(students, students[end]) + 1
            # mid와 같은값의 경우는 mid가 이동하면서 찾을 것
            mid += 1
        elif score < 0:
            mid += 1
        else:
            end -= 1

print(answer)


# coding: utf8
# config manager

import datetime

from classes.db_object import db_object
from classes.config.config import config

class config_manager(db_object):

	def __init__(self):
		super(config_manager, self).__init__('config', ['id', 'name', 'value', 'created_date', 'updated_date'])
		self.storable_items = [
			'download_dir',
		]

	def get_all(self, where = {}):

		rows = super(config_manager, self).get_all(where, 0, '')

		items = []

		for row in rows:

			self.get_class('classes.' + self.table)

			new_config = config()
			new_config.load(row)
			items.append(new_config)

		return items

	def get_all_items(self):
		items = self.get_all()

		config = {}
		for item in items:
			config[item.name] = item.value

		return config

	def get_item(self, item):
		item = self.get_all({'config_name', item})

	def save(self, conf):

		conf_list = self.get_all()

		if any(conf_list):
			for conf_item in conf_list:
				self.update_conf_item(conf, conf_item)
		else:
			for item in self.storable_items:
				conf_item = config()
				conf_item.id = None
				conf_item.name = item
				conf_item.created_date ='{:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now())
				self.update_conf_item(conf, conf_item)

	def update_conf_item(self, conf, conf_item):

		conf_item.updated_date ='{:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now())

		for item in self.storable_items:
			if conf_item.name == item and conf[item] != None:
				conf_item.value = conf[item]
				super(config_manager, self).save([conf_item.__dict__])


import logging
import logging.config

log_config = {
    "version": 1,
    "root": {
        "handlers": ["console", "file"],
        "level": "DEBUG"
    },
    "handlers": {
        "console": {
            "formatter": "std_out",
            "class": "logging.StreamHandler",
            "level": "DEBUG"
        },
        "file": {
            "formatter": "std_out",
            "class": "logging.FileHandler",
            "level": "INFO",
            "filename": "bidding.log"
        }
    },
    "formatters": {
        "std_out": {
            "format": "%(levelname)s - %(module)s - %(funcName)s - %(message)s",
        }
    },
}

def get_bidding_logger(logger_name, file_name=None):
    """
    Logger for bidding
    :return:
    """
    config_dict = log_config
    if file_name:
        config_dict['handlers']['file']['filename'] = file_name
    logging.config.dictConfig(config_dict)
    bidding_logger = logging.getLogger(logger_name)
    return bidding_logger

if __name__ == '__main__':
    logger = get_bidding_logger('drl_bidding')
    logger.info('test')


from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QMessageBox

def show_message_box():
    msg_box = QMessageBox()
    msg_box.setText("알림")
    msg_box.setInformativeText("이것은 메시지 박스입니다.")
    msg_box.setIcon(QMessageBox.Information)
    msg_box.setStandardButtons(QMessageBox.Ok)
    msg_box.setDefaultButton(QMessageBox.Ok)
    msg_box.exec_()

app = QApplication([])
window = QMainWindow()

button = QPushButton("메시지 박스 열기")
button.clicked.connect(show_message_box)
window.setCentralWidget(button)

window.show()
app.exec_()


#  Q2. Perform the following preprocessing tasks on the dirty_iris dataset.
# i) Calculate the number and percentage of observations that are complete.
# ii) Replace all the special values in data with NA.
# iii) Define these rules in a separate text file and read them.
# (Use editfile function in R (package editrules). Use similar function in Python).
# Print the resulting constraint object.
# – Species should be one of the following values: setosa, versicolor or virginica.
# – All measured numerical properties of an iris should be positive.
# – The petal length of an iris is at least 2 times its petal width.
# – The sepal length of an iris cannot exceed 30 cm.
# – The sepals of an iris are longer than its petals.
# iv)Determine how often each rule is broken (violatedEdits). Also summarize and plot the
# result.
# v) Find outliers in sepal length using boxplot and boxplot.stats

# Solution
import matplotlib.pyplot as plt
import copy

class iris:
    def __init__(self, sepalLength, sepalWidth, petalLength, petalWidth, species):
        self.sepalLength = sepalLength
        self.sepalWidth = sepalWidth
        self.petalWidth = petalWidth
        self.petalLength = petalLength
        self.species = species

    def value(self):
        temp = self.sepalLength + ',' + self.sepalWidth + ',' + \
            self.petalLength + ',' + self.petalWidth + ',' + self.species
        return temp

    def checkConstraiont(self):
        temp = [0, 0, 0, 0, 0]
        speciesValue = ['"setosa"\n', '"versicolor"\n', '"virginica"\n']

        if (self.sepalLength == 'NA' or self.sepalWidth == 'NA' or self.petalLength == 'NA' or self.petalWidth == 'NA'):
            return temp
        if (self.species in speciesValue):
            temp[0] = 0
        else:
            temp[0] = 1

        if (float(self.sepalLength) < 0 or float(self.sepalWidth) < 0 or float(self.petalLength) < 0 or float(self.petalWidth) < 0):
            temp[1] = 1
        if (float(self.petalLength) < 2*float(self.petalWidth)):
            temp[2] = 1
        if (float(self.sepalLength) > 30.0):
            temp[3] = 1
        if (float(self.sepalLength) < float(self.petalLength) or float(self.sepalWidth) < float(self.petalWidth)):
            temp[4] = 1

        return temp

irisList = []
fileLine = []
originalIrisList = []

file = open("dirty_iris.csv", "r")
for x in file:
    fileLine.append(x)

file.close()

for x in range(0, len(fileLine)):
    temp = fileLine[x].split(',')
    irisList.append(iris(temp[0], temp[1], temp[2], temp[3], temp[4]))

originalIrisList = copy.deepcopy(irisList)
irisLength = len(irisList)-1

incompleteData = 0

for x in irisList:
    if (x.sepalLength == "NA" or x.sepalWidth == "NA" or x.petalLength == "NA" or x.petalWidth == "NA" or x.species == "NA"):
        incompleteData = incompleteData + 1

print("Total no. of Data : ", irisLength)
print("No. of Incomplete Data : ", incompleteData)

try:
    print("Percentage of Incomplete Data : ", (incompleteData/irisLength)*100)
except:
    print("File is Empty")

# (ii) part starts Here.

for l in range(0, len(irisList)):
    try:
        if (float(irisList[l].sepalLength) <= 0.000 or irisList[l].sepalLength == 'Inf'):
            irisList[l].sepalLength = "NA"
        if (float(irisList[l].sepalWidth) <= 0.0000 or irisList[l].sepalWidth == 'Inf'):
            irisList[l].sepalWidth = "NA"
        if (float(irisList[l].petalLength) <= 0.0000 or irisList[l].petalLength == 'Inf'):
            irisList[l].petalLength = "NA"
        if (float(irisList[l].petalWidth) <= 0.0000 or irisList[l].petalWidth == 'Inf'):
            irisList[l].petalWidth = "NA"
    except:
        continue

fileWrite = open("dirty_iris.csv", "w")

for l in range(0, len(irisList)):
    fileWrite.write(irisList[l].value())

fileWrite.close()

ruleVoilation = [0, 0, 0, 0, 0]

for l in range(1, len(irisList)):
    result = originalIrisList[l].checkConstraiont()
    for k in range(0, 5):
        ruleVoilation[k] = ruleVoilation[k] + result[k]

print("Species Rule Voilation : " , ruleVoilation[0])
print("Positive Value Rule Voilation : " , ruleVoilation[1])
print("Petal Length Rule Voilation : " , ruleVoilation[2])
print("Sepal Length Rule Voilation : " , ruleVoilation[3])
print("Sepal and Petal Length Rule Voilation : " , ruleVoilation[4])

Options = ["Species Rule Voilation" ,"Positive Value Rule Voilation","Petal Length Rule Voilation","Sepal Length Rule Voilation","Sepal and Petal Length Rule Voilation"]

plt.bar(Options, ruleVoilation, color ='maroon',
        width = 0.4)
plt.ylabel('No. of Rule Voilation')
plt.title("No. of Record : " + str(len(irisList)-1))

plt.show()

sepalLengthList = []

for l in range(1 , len(irisList)):
    try:
     sepalLengthList.append(float(irisList[l].sepalLength))
    except:
        continue

graph = plt.boxplot(sepalLengthList)
plt.title("Sepal Length")
plt.show()
print(graph)


import os
import sys
import sqlite3
import numpy as np
import pandas as pd
import textwrap
from util.datamanage import fwrite

pd.set_option('display.min_rows', 30)
pd.set_option('display.max_rows', 30)
pd.set_option('display.max_columns', 20)
pd.set_option('display.width', 400)

# User-Scheme のテーブルを作成する
def create_US_table(filename, work_id):
    # index: user (一度も工夫を採用したことのないユーザは除く)
    # Column: scheme (一度も採用されたことのない工夫は除く)
    dbname = filename
    conn = sqlite3.connect(dbname)
    cur = conn.cursor()

    # 各ユーザごとに処理をループ
    # Users df (without duplicates)
    Users = pd.read_sql(
        f"""
            SELECT id , name
            FROM Users
            GROUP BY id, name
            ORDER BY id
        """ ,conn)

    # UsersWorks df without duplicates
    UsersWorks = pd.read_sql(
        f"""
            SELECT id, UserId, WorkId
            FROM UsersWorks
            WHERE WorkId = {work_id}
            GROUP BY UserId, WorkId
        """, conn)

    # UsersSchemes df without duplicates
    UsersSchemes = pd.read_sql(
        f"""
            SELECT UsersWorkId , SchemeId
            FROM UsersSchemes
            GROUP BY UsersWorkId, SchemeId
            ORDER BY SchemeId
        """, conn)

    # Schemes_during_use df without duplicates
    Schemes_during_use = pd.read_sql(
        f"""
            SELECT SchemeId
            FROM UsersSchemes
            GROUP BY SchemeId
            ORDER BY SchemeId
        """, conn)

    # Schemes df without duplicates
    Schemes = pd.read_sql(
        f"""
            SELECT id, label
            FROM Schemes
            GROUP BY id, label
            ORDER BY id
        """, conn)

    # UsersWorks - UsersSchemes でINNER JOIN
    # UsersWork-UsersSchemes df without duplicates
    uw_us = pd.merge(UsersWorks, UsersSchemes, left_on="id", right_on="UsersWorkId").drop(columns=['id', 'UsersWorkId'])

    # User - Scheme の行列を作成
    schemes_labels = Schemes[Schemes['id'].isin(Schemes_during_use['SchemeId'])]['label']
    users_ids = Users[Users['id'].isin(uw_us['UserId'])]['id']
    User_Scheme_matrix = pd.DataFrame(index=users_ids.to_numpy(), columns=schemes_labels.to_numpy())

    # 行列の値を計算
    for id in User_Scheme_matrix.index:
        users_schemes = uw_us.loc[uw_us['UserId'] == id, 'SchemeId']
        User_Scheme_matrix.loc[id] = Schemes_during_use['SchemeId'].isin(users_schemes).values * 1
    cur.close()
    conn.close()
    return User_Scheme_matrix

"""
    ユーザに工夫を推薦する
    引数：
        matrix:
            pandas Dataframe型の(User x Scheme)行列
            index: schemes name, column: user id
            工夫の採用有無を表現する（採用していれば1, していなければ0)
        user_id:
            推薦を受け取る対象ユーザのuser id
    戻り値：
        推薦を受け取る対象ユーザの未採用工夫に対する予測評価付き配列
"""
def recommend(matrix, user_id):
    # 推薦を受け取る対象ユーザの列を取得
    u_i = matrix[user_id]
    others = matrix.drop(columns=user_id)
    s_i_others = pd.Series(name="similarity")
    # 対象ユーザとその他ユーザとの類似度を計算

    #(おまけ)自身との類似度も出してみる
    # myself = pd.concat([u_i,u_i], axis=1)
    # s_myself = myself.corr(method='pearson')
    # s_myself = s_myself.iat[0,1]
    # print(f"me: {s_myself}")
    for _id, u_k in others.items():
        u_ik = pd.concat([u_i, u_k], axis=1)
        s_ik = u_ik.corr(method='pearson')
        s_ik = s_ik.iat[0,1]
        s_i_others[_id] = s_ik

    # 類似したユーザ集合を用意
    threshold = 0.05
    sim_set = s_i_others[s_i_others >= threshold].sort_values(ascending=False)
    # _show = textwrap.indent(sim_set.to_string(), '        ')
    # fwrite(f"similar user set(user id, similarity):\n{_show}\n", end="")

    # 未採用の工夫に対して採用スコアを予測
    # 予測方法は平均による閾値処理（オリジナル）
    predict_values = pd.Series(name="Predicted effect of schemes")
    if sim_set.shape[0] == 0:
        return predict_values
    for index in u_i[u_i == 0].index:
        # print(f"index:{index}")
        others_index_score = others[sim_set.index].loc[index]
        # 単純平均
        mean = others_index_score.mean()
        # print(f"単純平均: {round(mean,3)}")
        # 加重平均
        weight = np.arange(others_index_score.shape[0],0,-1)
        wma = sum(others_index_score * weight) / sum(weight)
        # print(f"加重平均: {round(wma,3)}")
        predict_values[index] = round(wma,3)
    return predict_values.sort_values(ascending=False)

def main(sqlite_path, user_id, work_id):
    try:
        # ユーザ×工夫の行列を取得
        us_table = create_US_table(sqlite_path, work_id)
        # 行列をcsvとして保存
        table_output = "/app/log/user_scheme_matrix.csv"
        us_table.to_csv(table_output)
        fwrite(f"ユーザ×工夫行列を'{table_output}'に保存しました")
        # 推薦を実施
        res_ps = recommend(us_table.T, user_id)
        if res_ps.shape[0] == 0:
            fwrite(f"user id {user_id} におすすめできる工夫が存在しません．")
            return None
        fwrite(f"user id {user_id} におすすめの工夫: {list(res_ps.to_dict().keys())[:10]}")
        return res_ps.to_dict()

    except Exception as e:
        fwrite(e)

if __name__ == "__main__":
    print("Don't exec this program from command line")


import numpy as np
import streamlit as st
from PIL import Image, ImageOps
import tensorflow
from sklearn.cluster import MiniBatchKMeans
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import cv2
from lime import lime_image
from skimage.segmentation import mark_boundaries

def color_compress_KNN(image, KNN=4):
    import warnings; warnings.simplefilter('ignore')
    Kmeans_images = []
    rescaled_image = np.array(image) / 255.0 # use 0...1 scale
    preprocessed_image = rescaled_image.reshape(150 * 150, 3)
    kmeans = MiniBatchKMeans(KNN)
    kmeans.fit(preprocessed_image)
    new_colors = kmeans.cluster_centers_[kmeans.predict(preprocessed_image)]
    color_compressed_image = new_colors.reshape(np.array(image).shape)
    #Changed to predict in Warren's Model
    reshaped_cci = cv2.resize(color_compressed_image, (75,75)).reshape(1,75,75,3)
    return reshaped_cci

def import_and_predict(image_data, model):

        img_output = color_compress_KNN(image_data)
        prediction = model.predict(img_output)[0]

        return prediction, img_output

def image_expl(model,image_array):
    '''
    Takes a model, single image array, name string of the model, and the true label of the image.
    Uses LIME to get an image explainer and plots the image and explaination.
    '''

    explained_image, ax = plt.subplots()
    #instantiate explainer
    explainer = lime_image.LimeImageExplainer(random_state=1)
    #explain an image caste to double bc updated keras version, pass predictor
    explanation = explainer.explain_instance(image_array[0].astype('double'), model.predict)
    #show the image
    ax = plt.imshow(image_array[0])
    #get the mask for the prediction
    temp, mask = explanation.get_image_and_mask(model.predict(image_array.reshape((1,75,75,3))).argmax(axis=1)[0], positive_only=False, hide_rest=False)
    #show image and mask together
    ax = plt.title("Best Explaination of What Our Model is Seeing.")
    ax = plt.imshow(mark_boundaries(temp, mask))
    plt.axis("off")
    return explained_image

class_names=['mountain', 'street', 'glacier', 'buildings', 'sea', 'forest']
def pick_a_graph(model, image, color_coder, graph_type="bar"):
    if graph_type == "bar":
        fig_bar, ax = plt.subplots()
        ax = plt.bar([0,1,2,3,4,5], model.predict(image)[0])
        for i in color_coder:
            if color_coder[i] == model.predict(image)[0].max():
                ax[i].set_color("r")
                Best_guess = mpatches.Patch(color='red', label=round(color_coder[i],2))
            else:
                ax[i].set_color("b")
        plt.legend(handles=[Best_guess])
        plt.title("Model's Confidence as a Bar Plot")
        plt.ylabel("Model Confidence")
        plt.xlabel("Classes")
        ax = plt.xticks(ticks=[0,1,2,3,4,5],labels=[x.title() for x in class_names], size=10)
        return fig_bar
    elif graph_type == "donut":
        fig_pie, ax = plt.subplots(subplot_kw=dict(aspect="equal"))
        recipe = color_coder
        data = color_coder.values()
        wedges, texts = plt.pie(color_coder.values(), wedgeprops=dict(width=0.5), startangle=-40)
        bbox_props = dict(boxstyle="square,pad=0.3", fc="w", ec="k", lw=0.72)
        kw = dict(arrowprops=dict(arrowstyle="-"), bbox=bbox_props, zorder=0, va="center")

        ax.legend(wedges, [x.title() for x in class_names], title="Classes")
        for i, p in enumerate(wedges):
            ang = (p.theta2 - p.theta1)/2. + p.theta1
            y = np.sin(np.deg2rad(ang))
            x = np.cos(np.deg2rad(ang))
            horizontalalignment = {-1: "right", 1: "left"}[int(np.sign(x))]
            connectionstyle = "angle,angleA=0,angleB={}".format(ang)
            kw["arrowprops"].update({"connectionstyle": connectionstyle})
            ax.annotate(round(color_coder[i],2), xy=(x, y), xytext=(1.35*np.sign(x), 1.4*y),
                        horizontalalignment=horizontalalignment, **kw)
        ax.set_title("Model's Confidence as a Pie Chart")
        return fig_pie
    elif graph_type == "lollipop":
        # creating an empty chart
        fig_lollipop, ax = plt.subplots()
        # plotting using plt.stem
        ax = plt.stem([0,1,2,3,4,5], model.predict(image)[0]
                  ,use_line_collection=True, basefmt=' ')
        plt.title("Model's Confidence as a Lollipop Graph")
        plt.ylabel("Model Confidence")
        plt.xlabel("Classes")
        ax = plt.xticks(ticks=[0,1,2,3,4,5],labels=[x.title() for x in class_names])
        return fig_lollipop
    elif graph_type == "scatter":
        fig_scatter= plt.figure()
        ax1=fig_scatter.add_subplot(111)
        X=[0,1,2,3,4,5]
        y=model.predict(image)[0]
        for i in color_coder:
            if color_coder[i] == y.max():
                ax1.scatter([i], y[i], c ='r', marker="*", s=750)
                ax1.scatter(np.delete(X,i), np.delete(y,i))
                Best_guess = mpatches.Patch(color='red', label=round(color_coder[i],2))
        plt.legend(handles=[Best_guess])
        plt.title("Model's Confidence as a Scatter Plot")
        plt.ylabel("Model Confidence")
        plt.xlabel("Classes")
        ax1= plt.xticks(ticks=X,labels=[x.title() for x in class_names])
        return fig_scatter

# Start of the website
# Loading in the Model
model = tensorflow.keras.models.load_model("Models/3rd-color_comp_model.h5")
page_image=("Sample_Pictures/Icon.jpg")
st.set_page_config(page_title="Image Classification",page_icon=page_image,layout="wide")
# Creating a centered layout
_, center_,_ = st.columns([1,2,1])
with center_:
    st.markdown("""
             # Intel Nature Image Predictor
             """
             )
    st.markdown(" ## **Data found on Kaggle**:")
    st.caption("https://www.kaggle.com/puneet6060/intel-image-classification")

col1, col2, col3, col4, col5, col6 = st.columns(6)
with col1:
    st.image("Sample_Pictures/Buildings_Image.jpg", caption="Building Example", width= 250)
with col2:
    st.image("Sample_Pictures/Forest_Image.jpg", caption="Forest Example", width= 250)
with col3:
    st.image("Sample_Pictures/Glacier_Image.jpg", caption="Glacier Example", width= 250)
with col4:
    st.image("Sample_Pictures/Mountain_Image.jpg", caption="Mountain Example", width= 250)
with col5:
    st.image("Sample_Pictures/Sea_Image.jpg", caption="Sea Example", width= 250)
with col6:
    st.image("Sample_Pictures/Street_Image.jpg", caption="Street Example", width= 250)

st.markdown("## This image classifier web app will predict which of 6 classes your uploaded Image should be.")
st.markdown("## Today we will be showing you how this Image performs in our model.")

file = st.file_uploader("Please upload an image file", type=["jpg","png"])
#
if file is None:
    st.text("Please select an Image from the Kaggle Dataset to be classified")
else:
    image = Image.open(file)
    prediction, new_image = import_and_predict(image, model)
    explained_image=image_expl(model, new_image)
    color_coder=dict(enumerate(prediction,0))

    fig_bar, ax = plt.subplots()
    plt.title("Model's Probablity for Class of Given Image")
    ax=plt.bar([0,1,2,3,4,5], prediction, edgecolor='black')
    for i in color_coder:
        if color_coder[i] == prediction.max():
            ax[i].set_color("r")
            Best_guess = mpatches.Patch(color='red', label=round(color_coder[i],2))
        else:
            ax[i].set_color("b")
    plt.legend(handles=[Best_guess])
    ax=plt.xticks(ticks=[0,1,2,3,4,5],labels=['mountain', 'street', 'glacier', 'buildings', 'sea', 'forest'])
    cola , colb, colc = st.columns([1,1,1])
    with cola:
        st.image(image,caption="Original Image", width=500)
    with colb:
        st.image(new_image,caption="Color Compressed Image", width=500)
    with colc:
        choice = st.selectbox("Graph Selector", ["Bar", "Donut", "Lollipop", "Scatter"])
        result_fig=pick_a_graph(model, new_image, color_coder, choice.lower())
        st.pyplot(result_fig)

# Lime required Section
    _,final,_ =st.columns([1,2,1])
    with final:
        if st.button('How did the Model do that!?!',  help="Click Me to Find out!"):
            st.pyplot(explained_image)


#Un vendedor recibe un sueldo base mas un 10% extra por comisión de sus ventas,
#el vendedor desea saber cuanto dinero obtendrá por concepto de comisiones por
#las tres ventas que realiza en el mes y el total que recibirá en el mes tomando
#en cuenta su sueldo base y comisiones.

sueldobase = float(input("¿Cuás es su sueldo base?: "))
comision = ((sueldobase * 10)/100) * 3
sueldototal = sueldobase + comision
print("Pos las comisiones obtendrá %.2f euros "% (comision))
print("Su sueldo total con las comisiones sería %.2f euros"%(sueldototal))


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

from contextlib import contextmanager
from django.http import HttpResponse
import locale
import threading
import unicodedata

LOCALE_LOCK = threading.Lock()

TRANSPARENT_1_PIXEL_GIF = "\x47\x49\x46\x38\x39\x61\x01\x00\x01\x00\x80\x00\x00\xff\xff\xff\x00\x00\x00\x21\xf9\x04\x01\x00\x00\x00\x00\x2c\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02\x44\x01\x00\x3b"  # noqa

def tracking_pixel():
    return HttpResponse(TRANSPARENT_1_PIXEL_GIF, content_type='image/gif')

def normalize_ascii(value):
    return unicodedata.normalize('NFKD', unicode(value))\
        .encode('ascii', 'ignore')

@contextmanager
def setlocale(name):
    with LOCALE_LOCK:
        saved = locale.setlocale(locale.LC_ALL)

        try:
            yield locale.setlocale(locale.LC_ALL, name)
        finally:
            locale.setlocale(locale.LC_ALL, saved)

{{ cookiecutter.repo_name }}/{{ cookiecutter.repo_name }}/apps/core/utils.py


from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, String, Float

engine = create_engine('sqlite:///space-exploration.db', echo=True)

Session = sessionmaker(bind=engine)
session = Session()

Base = declarative_base()

class Planet(Base):
    __tablename__ = 'planets'

    name = Column(String, primary_key=True)
    star_system = Column(String)
    distance = Column(Float)

def create_tables():
    Base.metadata.create_all(engine)

def insert_planets():
    planets = [
        {'name': 'Proxima Centauri b', 'star_system': 'Alpha Centauri', 'distance': 4.24},
        {'name': 'TRAPPIST-1 e', 'star_system': 'TRAPPIST-1', 'distance': 39.6},
        {'name': 'Kepler-442b', 'star_system': 'Kepler-442', 'distance': 1200},
        {'name': 'LHS 1140b', 'star_system': 'LHS 1140', 'distance': 40},
        {'name': 'Teegarden b', 'star_system': 'Teegarden', 'distance': 12.5},
        {'name': 'Ross 128 b', 'star_system': 'Ross 128', 'distance': 11},
        {'name': 'Gliese 667 Cc', 'star_system': 'Gliese 667 C', 'distance': 23.6},
        {'name': 'K2-18 b', 'star_system': 'K2-18', 'distance': 124},
        {'name': 'Wolf 1061c', 'star_system': 'Wolf 1061', 'distance': 14.1},
        {'name': 'TOI 700 d', 'star_system': 'TOI 700', 'distance': 101},
    ]

    for planet in planets:
        planet_obj = Planet(name=planet['name'], star_system=planet['star_system'], distance=planet['distance'])
        session.add(planet_obj)

    session.commit()


from dtos.IntervalDto import IntervalDto

class ScheduleDto:

    def __init__(self, id, name, project, branch, interval, start_date):
        self.id = id
        self.name = name
        self.project = project
        self.branch = branch
        self.interval = interval
        self.start_date = start_date

    @staticmethod
    def deserialize(data):
        interval = IntervalDto.deserialize(data['interval'])
        id = str(data['_id'])
        name = data['name']
        project = str(data['project'])
        branch = data['branch']
        start_date = data['startDate']
        return ScheduleDto(id, name, project, branch, interval, start_date)

    def __eq__(self, other):
        return self.id == other.id and self.name == other.name and \
               self.project == other.project and self.branch == other.branch and \
               self.interval == other.interval and self.start_date == other.start_date


from node import Node
from activation import Activation

class Layer:
    def __init__(self, node_count, _type):
        """Layer in nn"""
        self.nodes = []
        self.bias = None
        self.input = 0
        self.output = 0
        self.type = _type
        #self.activation = activation

        # init nodes
        for i in range(node_count):
            self.nodes.append(Node())

        # init bias node
        if self.type != 'output':
            self.bias = Node()

    #------------
    #
    #
    #
    #------------
    def connect(self, count):
        """connect layers to layers"""
        for i in range(len(self.nodes)):
            self.nodes[i].init_weights(count)

        if self.bias != None:
            self.bias.init_weights(count)

    #------------
    #
    #
    #
    #------------
    def feed_forward(self, layer):
        """Feeds forward the layers values"""
        for i in range(len(self.bias.weights)):
            layer.nodes[i].value = 0

        for i in range(len(self.nodes)):
            for weight in range(len(self.nodes[i].weights)):
                layer.nodes[weight].value += self.nodes[i].value * self.nodes[i].weights[weight]

        for weight in range(len(self.bias.weights)):
            layer.nodes[weight].value += self.bias.weights[weight]

        for w in range(len(layer.nodes)):
            # use tanh as our activation function
            layer.nodes[w].value = Activation.tanh(layer.nodes[w].value)

    #------------
    #
    #
    #
    #------------
    def set_value(self, ins):
        """set value of node"""
        for i in range(len(self.nodes)):
            self.nodes[i].value = ins[i]

    def get_values(self):
        """return value of nodes in array"""
        res = []
        for i in range(len(self.nodes)):
            res.append(self.nodes[i].value)
        return res


import os
import shutil
import subprocess
import sys

python_folder = "../../../PythonClient"
directories_to_remove = [
    os.path.join(python_folder, "build"),
    os.path.join(python_folder, "dist"),
    os.path.join(python_folder, "src", "quixstreams.egg-info"),
]

for directory in directories_to_remove:
    if os.path.exists(directory):
        shutil.rmtree(directory)

archname = os.uname().machine
if archname == "aarch64":
    platname = "manylinux_2_28_aarch64"
elif archname == "x86_64":
    platname = "manylinux2014_x86_64"
else:
    print(f"Not yet supported architecture {archname}")
    sys.exit(1)

os.chdir(python_folder)
subprocess.run(
    ["python3", "setup.py", "sdist", "bdist_wheel", "--plat-name", platname], check=True
)


import lupa
import fileinput
import os
from lupa import LuaRuntime
import time
from user import User
from channel import Channel
import util

fd_time_boot = 0

def dict_from_lua_tbl(luatbl):
    d = {}
    for k, v in luatbl.items():
        if str(type(v)) == "<class 'lupa._lupa._LuaTable'>":
            d[k] = dict_from_lua_tbl(v)
        else:
            d[k] = v
    return d

def lua_handle(lua_inst, str):
    a = lua_inst(str, time)
    d = dict_from_lua_tbl(a)
    print(d)

def should_reload_lua() -> bool:
    statinfo = os.stat('handle.lua')
    return statinfo.st_mtime != fd_time_boot

def load_lua():
    global fd_time_boot
    lua = LuaRuntime(unpack_returned_tuples=True)
    statinfo = os.stat('handle.lua')
    fd_time_boot = statinfo.st_mtime
    _ = lua.require('handle')
    yep = lua.eval(
        '''
        function(i, time)
            return handle_cmd(i, time)
        end
        '''
    )
    return yep, lua

def create_fake_globals(lua_instance):
    fake_user = User()
    fake_user.nickname = "TestUser"
    fake_user.username = "Testing"
    other_fake_user = User()
    other_fake_user.nickname = "teest2"
    other_fake_user.username = "mmmmm"
    fake_channel = Channel()
    fake_channel.name = "#fakechan"
    globalz = lua_instance.globals()
    globalz.users = [fake_user, other_fake_user]
    globalz.channels = [fake_channel]
    globalz.message_sender = fake_user
    globalz.hostname = util.HOSTNAME

def create_real_globals(lua_instance, server, sender_user):
    globz = lua_instance.globals()
    globz.users = server.users
    globz.channels = server.channels
    globz.message_sender = sender_user
    globz.server = server
    globz.hostname = util.HOSTNAME
    globz.motd = server.get_motd()

if __name__ == "__main__":
    # noinspection PyArgumentList
    lua_func, lua_inst = load_lua()
    create_fake_globals(lua_inst)
    lua_handle(lua_func, ":Server BRUH Yes No Maybe :So yeah")
    while True:
        time.sleep(1)
        if should_reload_lua():
            lua_func, lua_inst = load_lua()
            create_fake_globals(lua_inst)
            lua_handle(lua_func, ":Server BRUH Yes No Maybe :So yeah")


#Q4 to double the string given by the user
def double_string(a):
    c=""
    for i in range(0,len(a)):
        c+=2*a[i]
    return c
x=input("enter the string:")
y=double_string(x)
print("the result of the operation is ",y)


from math import floor

def calcuate_fuel(mass):
    # divided = mass / 3
    # floored = floor(divided)
    # subtracted = floored - 2
    # return subtracted
    print("Calculating fuel to carry {}".format(mass))

    return floor(mass / 3) - 2
    return mass // 3 - 2

def total_fuel(masses):
    totals = []
    for mass in masses:
        total = 0
        total += calcuate_fuel(mass)
        print("Now has a total of {}".format(total))

        print("Calculating fuel to carry {}".format(total))
        fuel_to_carry_fuel = calcuate_fuel(total)
        while fuel_to_carry_fuel > 0:
            print("Adding {} to the total.".format(fuel_to_carry_fuel))
            total += fuel_to_carry_fuel
            fuel_to_carry_fuel = calcuate_fuel(fuel_to_carry_fuel)

        totals.append(total)
    return sum(totals)

if __name__ == "__main__":

    import requests

    result = requests.get("https://adventofcode.com/2019/day/1/input", headers={"Cookie": "session=53616c7465645f5fa83960b1e99f2bfb3666e735109ba7aaa30e6e76b8f4fe458e74e9745c89fb3d8bc76b152ed1d446"})

    if result.status_code == 200:
        text = result.text
        split_lines = text.splitlines()

        # converted = []
        # for num in split_lines:
        #     converted.append(int(num))

        converted = list(map(int, split_lines))

        print(total_fuel(converted))

    else:
        print("Error.", result.status_code)


# -*- coding: utf-8 -*-
"""
Created on Wed Feb 17 16:30:44 2016

207. Course Schedule

Total Accepted: 31793 Total Submissions: 122872 Difficulty: Medium

There are a total of n courses you have to take, labeled from 0 to n - 1.

Some courses may have prerequisites, for example to take course 0 you have to
first take course 1, which is expressed as a pair: [0,1]

Given the total number of courses and a list of prerequisite pairs, is it
possible for you to finish all courses?

For example:

2, [[1,0]]
There are a total of 2 courses to take. To take course 1 you should have
finished course 0. So it is possible.

2, [[1,0],[0,1]]
There are a total of 2 courses to take. To take course 1 you should have
finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.

Note:
The input prerequisites is a graph represented by a list of edges, not
adjacency matrices. Read more about how a graph is represented.

click to show more hints.

Hints:

This problem is equivalent to finding if a cycle exists in a directed graph.
If a cycle exists, no topological ordering exists and therefore it will be
impossible to take all courses.
Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera
explaining the basic concepts of Topological Sort.
Topological sort could also be done via BFS.

http://www.cnblogs.com/grandyang/p/4484571.html

第二条提示是在讲如何来表示一个有向图，可以用边来表示，边是由两个端点组成的，用两个点来表示边。
第三第四条提示揭示了此题有两种解法，DFS和BFS都可以解此题。我们先来看BFS的解法，
我们定义二维数组graph来表示这个有向图，一位数组in来表示每个顶点的入度。
我们开始先根据输入来建立这个有向图，并将入度数组也初始化好。然后我们定义一个queue变量，
将所有入度为0的点放入队列中，然后开始遍历队列，从graph里遍历其连接的点，每到达一个新节点，
将其入度减一，如果此时该点入度为0，则放入队列末尾。直到遍历完队列中所有的值，
若此时还有节点的入度不为0，则说明环存在，返回false，反之则返回true。代码为AC代码。

DFS的代码在这里

下面我们来看DFS的解法，也需要建立有向图，还是用二维数组来建立，和BFS不同的是，
我们像现在需要一个一维数组visit来记录访问状态，大体思路是，先建立好有向图，
然后从第一个门课开始，找其可构成哪门课，暂时将当前课程标记为已访问，
然后对新得到的课程调用DFS递归，直到出现新的课程已经访问过了，则返回false，
没有冲突的话返回true，然后把标记为已访问的课程改为未访问。代码如下：

class Solution(object):
    def canFinish(self, numCourses, prerequisites):
        graph = {}; visit= {}
        for pair in prerequisites:
            graph[pair[1]] = graph.get(pair[1],[]) + [pair[0]]
            graph[pair[0]] = graph.get(pair[0],[])
            visit[pair[0]] = visit.get(pair[0],0)
            visit[pair[1]] = visit.get(pair[1],0)
        vertices = visit.keys()

        # -1 means visited; 1 means not visited
        def canFinishDFS(vertice):
            if visit[vertice] == -1: return False
            if visit[vertice] == 1 : return True
            visit[vertice] = -1

            for v in graph[vertice]:
                if not canFinishDFS(v): return False
            visit[vertice] = 1
            return True

        for v in vertices:
            if not canFinishDFS(v): return False
        return True

@author: zzhang04
"""

class Solution(object):
    def canFinish(self, numCourses, prerequisites):
        """
        :type numCourses: int
        :type prerequisites: List[List[int]]
        :rtype: bool
        """
        InDegree = {}
        for pair in prerequisites:
            InDegree[pair[0]] = InDegree.get(pair[0],0)
            InDegree[pair[1]] = InDegree.get(pair[1],0)
        for pair in prerequisites:
            InDegree[pair[0]] += 1

        queue = []
        for vertice in InDegree:
            if InDegree[vertice] == 0: queue.append(vertice)

        while queue:
            vertice = queue.pop()
            for pair in prerequisites:
                if vertice == pair[1]:
                    InDegree[pair[0]] -= 1
                    if InDegree[pair[0]] == 0: queue.insert(0,pair[0])

        for i in InDegree:
            if InDegree[i] != 0: return False
        return True


import unittest
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from worldoftanks.orm.data_model import Base, DataModel
from worldoftanks.orm.data_model import PlayerPersonalDataDetailsModel, PlayerPersonalDataStatisticsModel, \
    PlayerPersonalVehiclesModel, TankopediaInfoModel, TankopediaAchievementsModel, \
    TankopediaVehiclesModel, TankopediaMapsModel, VehiclesStatisticsModel, VehiclesFragsModel, \
    VehiclesAchievementsModel, TankopediaBadgesModel

test_data = {"id": 10, "account_id": "1234"}

class TestModels(unittest.TestCase):
    engine = create_engine('sqlite:///:memory:')
    Session = sessionmaker(bind=engine)
    session = Session()

    def test_db_setUp(self):
        DataModel.create_tables(self.engine)
        # Add all the data into the models here to be evaluated in the methods below.
        self.session.add(PlayerPersonalDataDetailsModel(id=test_data['id'], account_id=test_data['account_id']))
        self.session.add(PlayerPersonalDataStatisticsModel(id=test_data['id']))
        self.session.add(PlayerPersonalVehiclesModel(id=test_data['id']))
        self.session.add(TankopediaInfoModel(id=test_data['id']))
        self.session.add(TankopediaAchievementsModel(id=test_data['id']))
        self.session.add(TankopediaVehiclesModel(id=test_data['id']))
        self.session.add(TankopediaMapsModel(id=test_data['id']))
        self.session.add(VehiclesStatisticsModel(id=test_data['id']))
        self.session.add(VehiclesFragsModel(id=test_data['id']))
        self.session.add(VehiclesAchievementsModel(id=test_data['id']))
        self.session.add(TankopediaBadgesModel(id=test_data['id']))
        self.session.commit()

    def test_player_personal_details_model(self):
        expected = PlayerPersonalDataDetailsModel(id=test_data['id'], account_id=test_data['account_id'])
        query = self.session.query(PlayerPersonalDataDetailsModel).first()
        self.assertEqual(query.account_id, expected.account_id)

    def test_player_personal_statistics_model(self):
        expected = PlayerPersonalDataStatisticsModel(id=test_data['id'])
        query = self.session.query(PlayerPersonalDataStatisticsModel).first()
        self.assertEqual(query.id,  expected.id)

    def test_player_personal_vehicles_model(self):
        expected = PlayerPersonalVehiclesModel(id=test_data['id'])
        query = self.session.query(PlayerPersonalVehiclesModel).first()
        self.assertEqual(query.id,  expected.id)

    def test_tankopedia_information_model(self):
        expected = TankopediaInfoModel(id=test_data['id'])
        query = self.session.query(TankopediaInfoModel).first()
        self.assertEqual(query.id,  expected.id)

    def test_tankopedia_achievements_model(self):
        expected = TankopediaAchievementsModel(id=test_data['id'])
        query = self.session.query(TankopediaAchievementsModel).first()
        self.assertEqual(query.id,  expected.id)

    def test_tankopedia_vehicles_model(self):
        expected = TankopediaVehiclesModel(id=test_data['id'])
        query = self.session.query(TankopediaVehiclesModel).first()
        self.assertEqual(query.id,  expected.id)

    def test_tankopedia_maps_model(self):
        expected = TankopediaMapsModel(id=test_data['id'])
        query = self.session.query(TankopediaMapsModel).first()
        self.assertEqual(query.id,  expected.id)

    def test_vehicle_statistics_model(self):
        expected = VehiclesStatisticsModel(id=test_data['id'])
        query = self.session.query(VehiclesStatisticsModel).first()
        self.assertEqual(query.id,  expected.id)

    def test_vehicle_frags_model(self):
        expected = VehiclesFragsModel(id=test_data['id'])
        query = self.session.query(VehiclesFragsModel).first()
        self.assertEqual(query.id,  expected.id)

    def test_vehicle_achievement_model(self):
        expected = VehiclesAchievementsModel(id=test_data['id'])
        query = self.session.query(VehiclesAchievementsModel).first()
        self.assertEqual(query.id,  expected.id)

    def test_tankopedia_badges_model(self):
        expected = TankopediaBadgesModel(id=test_data['id'])
        query = self.session.query(TankopediaBadgesModel).first()
        self.assertEqual(query.id,  expected.id)

    def test_xdb_tearDown(self):
        # The 'zdb' is not a typo. The database still needs to be available for the rest of the tests to run.
        # The unittest module is taking the methods in an alphabetical order so it had to be prefixed with a "z".
        Base.metadata.drop_all(self.engine)


import serial
import os
import time
#import context  # Ensures paho is in PYTHONPATH
import paho.mqtt.client as MQTT # For MQTT publish/subscribe
import RPi.GPIO as GPIO # For input/output
#from tkinter import *

import pygame.mixer
from sys import exit

import pygame, sys
from pygame.locals import *

slideWinAFlag = False

ser= serial.Serial('/dev/ttyUSB-trellis',9600,timeout=1)
ser.flushInput()

#ser1 = serial.Serial('/dev/ttyUSB-trellis',9600,timeout=1)
# ser1.flushInput()

def printString( str ):
   #"This prints a passed string into this function"
    length = len(str)
    for x in range (length):
        print(x , " is " , (str[x]))
    return;

def convertString(str ):
   #"This take in a string of ASCII chars, converts to Chars and strips last 2 elements"
    stringLen = len(str)
    realLen = stringLen - 2

    tempStr = ""

    for x in range (realLen):
        temp = chr(str[x])
        tempStr = tempStr + temp
    str = tempStr
    return str;
#read from Arduino
# Callback after connecting to MQTT server
def on_connect(self, client, userdata, rc):
  print("Connected!")
  print("Subscribing to ToDevice/All")
  self.subscribe("ToDevice/All")
  print("Subscribing to ToDevice/1")
  self.subscribe("phone/#")
  print("Subscribing to phone")

def redWin_arduino():
    client.publish("phone/trellis/red", 1)
    print(" red <- Recieved Solved")
def redReset_arduino():
    client.publish("phone/trellis/red", 0)
    print(" red <- Recieved Reset")

def redWin_phone():
    ser.write('redSOLVED'.encode())
    print("red -> Sent Solved")
def redReset_phone():
    ser.write('redRESET'.encode())
    print("red -> Sent Reset")

def blueWin_arduino():
    #relay_1_Set_arduino()
    client.publish("phone/trellis/blue", 1)
    print(" blue <- Recieved Solved")
    #client.publish("phone/pots/status", "SOLVED")
def blueWin_phone():
   # ser.write('blueSOLVED'.encode())
    #lient.publish("phone/pots/status", "SOLVED")
    print("blue -> Sent Solved")
def blueReset_arduino():
    client.publish("phone/trellis/blue", 0)
    print(" blue <- Recieved Reset")
    #client.publish("phone/pots/status", "RESET")
def blueReset_phone():
    ser.write('blueRESET'.encode())
    #client.publish("phone/pots/status", "RESET")
    print("blue -> Sent Reset")

# Callback when message is published to MQTT subscribed topic
def on_message(client, userdata, msg):
  # Print the message and topic in which it was published
  print(msg.topic + " " + str(msg.payload))
  # Change the global puzzle state based on message received
  global state
  #temp = int(msg.payload)
  temp = int(msg.payload)

#========================= TRELLIS PUZZLES ========================

  if(msg.topic == "phone/trellis/blue"):
      if(   temp == 1 ):
          blueWin_phone()
      elif( temp == 0 ):
          blueReset_phone()

# ----------------- LOGIC #2 - SEQUENCE -----------------
  if(msg.topic == "phone/trellis/red"):
      if(   temp == 1 ):
          redWin_phone()
      elif( temp == 0 ):
          redReset_phone()

# Callback when client is disconnected from MQTT broker
def on_disconnect(client, userdata, rc):
  client.loop_stop()

# Setup MQTT
client = MQTT.Client()
# Assign callbacks
client.on_connect = on_connect
client.on_message = on_message
client.on_disconnect = on_disconnect
# Connect to MQTT server
client.connect("10.1.10.177", 1883, 60)
# Start the MQTT update loop
client.loop_start()

print("Main Loop Start")

# Main program loop ==============================================================================================================================

while True:

    #print("reading serial ....")

    str_read = ser.readline()
    #print("read String 1")
    newString = convertString(str_read)
    print(newString)

# SERIAL PORT # 1 - Circle Logic and Sequence Logic
    if(newString == "BLUE_WIN"):
        blueWin_arduino()
    elif(newString == "BLUE_RESET"):
        blueReset_arduino()

    elif(newString == "RED_WIN"):
        redWin_arduino()
    elif(newString == "RED_RESET"):
        redReset_arduino()

# SERIAL PORT # 2 - final Puzzle -Phases

    ser.flushInput()
    time.sleep(.5)
# READ FROM SECOND SERIAL PORT
#     str_read2 = ser1.readline()
#     newString1 = convertString(str_read2)
#     print(newString1)
#
#
#     if(newString1 == "PHASE_1"):
#         client.publish("phone/final/phase_1", 1)
#         #plays sound
#     if(newString1 == "PHASE_2"):
#         client.publish("phone/final/phase_2", 1)
#     if(newString1 == "PHASE_3"):
#         client.publish("phone/final/phase_3", 1)
#     if(newString1 == "PHASE_4"):
#         client.publish("phone/final/puzzle", 1)
#     if(newString1 == "FINAL_RESET"):
#         #client.publish("phone/final/puzzle", 0)
#         client.publish("phone/final/phase_1", 0)
#         client.publish("phone/final/phase_2", 0)
#         client.publish("phone/final/phase_3", 0)
#         client.publish("phone/final/start", 0)
#
#
# #    ser.flushInput()
#     ser1.flushInput()
#

 #   time.sleep(.5)


from pyexpat import model
from django.shortcuts import get_object_or_404, render, redirect
from django.http import HttpResponse
from django.views.generic import ListView, CreateView, UpdateView, DetailView
from django.db.models import Func, F
from django.core.paginator import Paginator

from books.models import BookItem, Publisher
from clothes.models import ClothesItem
from electronics.models import ElectronicItem, Laptop, MobilePhone, Tivi
from shoes.models import ShoesItem

# Create your views here.

class HomeView(ListView):
    context_object_name = 'bookItems'
    queryset = BookItem.objects.filter(status=True)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['electronicsItems'] = ElectronicItem.objects.filter(
            status=True)
        context['shoesItems'] = ShoesItem.objects.filter(status=True)
        context['ShoesItems'] = ShoesItem.objects.filter(status=True)
        return context

    template_name = 'home.html'
class CategoryElectronicView(ListView):
    context_object_name = 'electronicItems'

    def get_queryset(self):
        electronicItems = ElectronicItem.objects.filter(status=True)
        _manufacturer = self.request.GET.get('manufacturer')
        _price = self.request.GET.get('price')
        _sort = self.request.GET.get('sort')
        _page = self.request.GET.get('page')
        if _manufacturer:
            electronicItems = electronicItems.filter(
                electronic__manufacturer=_manufacturer)
        if _price:
            if _price == 'duoi5tr':
                electronicItems = electronicItems.annotate(priceBought=F(
                    'price')*((100-F('discount'))/100)).filter(priceBought__lt=5000000)
            elif _price == '5trden10tr':
                electronicItems = electronicItems.annotate(priceBought=F(
                    'price')*((100-F('discount'))/100)).filter(priceBought__gte=5000000, priceBought__lt=10000000)
            elif _price == '10trden15tr':
                electronicItems = electronicItems.annotate(priceBought=F(
                    'price')*((100-F('discount'))/100)).filter(priceBought__gte=10000000, priceBought__lt=15000000)
            elif _price == '15trden25tr':
                electronicItems = electronicItems.annotate(priceBought=F(
                    'price')*((100-F('discount'))/100)).filter(priceBought__gte=15000000, priceBought__lt=25000000)
            elif _price == 'tren25tr':
                electronicItems = electronicItems.annotate(priceBought=F(
                    'price')*((100-F('discount'))/100)).filter(priceBought__gte=25000000)
        if _sort:
            if _sort == 'low-to-high':
                electronicItems = electronicItems.annotate(priceBought=F(
                    'price')*((100-F('discount'))/100)).order_by('priceBought')
            elif _sort == 'high-to-low':
                electronicItems = electronicItems.annotate(priceBought=F(
                    'price')*((100-F('discount'))/100)).order_by('-priceBought')

        paginator = Paginator(electronicItems, 8)
        electronicItems = paginator.get_page(_page)

        return electronicItems

    template_name = 'category_electronic.html'

class CategoryElectronicDetailView(DetailView):
    model = ElectronicItem

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['sameItems'] = ElectronicItem.objects.filter(
            status=True).exclude(barCode=self.kwargs['pk']).order_by('?')
        print(ElectronicItem.objects.filter(
            status=True).exclude(barCode=self.kwargs['pk']).order_by('?'))
        return context

    template_name = 'electronic_detail.html'

class CategoryBookView(ListView):
    context_object_name = 'bookItems'

    def get_queryset(self):
        bookItems = BookItem.objects.filter(status=True)
        _publisher = self.request.GET.get('publisher')
        _price = self.request.GET.get('price')
        _sort = self.request.GET.get('sort')
        _page = self.request.GET.get('page')
        if _publisher:
            bookItems = bookItems.filter(
                book__publisher__name=_publisher)
        if _price:
            if _price == 'duoi100':
                bookItems = bookItems.annotate(priceBought=F(
                    'price')*((100-F('discount'))/100)).filter(priceBought__lt=100000)
            elif _price == '100den200':
                bookItems = bookItems.annotate(priceBought=F(
                    'price')*((100-F('discount'))/100)).filter(priceBought__gte=100000, priceBought__lte=200000)
            elif _price == 'tren200':
                bookItems = bookItems.annotate(priceBought=F(
                    'price')*((100-F('discount'))/100)).filter(priceBought__gt=200000)
        if _sort:
            if _sort == 'low-to-high':
                bookItems = bookItems.annotate(priceBought=F(
                    'price')*((100-F('discount'))/100)).order_by('priceBought')
            elif _sort == 'high-to-low':
                bookItems = bookItems.annotate(priceBought=F(
                    'price')*((100-F('discount'))/100)).order_by('-priceBought')

        paginator = Paginator(bookItems, 8)
        bookItems = paginator.get_page(_page)
        return bookItems

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['publishers'] = Publisher.objects.filter(status=True)
        return context
    template_name = 'category_book.html'

class CategoryBookDetailView(DetailView):
    model = BookItem

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['sameBookItems'] = BookItem.objects.filter(
            status=True).exclude(barCode=self.kwargs['pk']).order_by('?')
        return context
    template_name = 'book_detail.html'

class CategoryShoesView(ListView):
    context_object_name = 'ShoesItems'

    def get_queryset(self):
        ShoesItems = ShoesItem.objects.filter(status=True)

        _style = self.request.GET.get('style')
        _price = self.request.GET.get('price')
        _sort = self.request.GET.get('sort')
        _page = self.request.GET.get('page')

        if _style:
            ShoesItems = ShoesItems.filter(shoes__style=_style)

        if _price:
            if _price == 'duoi100000':
                ShoesItems = ShoesItems.annotate(priceBought=F(
                    'price')*((100-F('discount'))/100)).filter(priceBought__lt=100000)
            elif _price == '100000den200000':
                ShoesItems = ShoesItems.annotate(priceBought=F(
                    'price')*((100-F('discount'))/100)).filter(priceBought__gte=100000, priceBought__lt=200000)
            elif _price == 'tren200000':
                ShoesItems = ShoesItems.annotate(priceBought=F(
                    'price')*((100-F('discount'))/100)).order_by('priceBought')
        if _sort:
            if _sort == 'low-to-high':
                ShoesItems = ShoesItems.annotate(priceBought=F(
                    'price')*((100-F('discount'))/100)).order_by('priceBought')
            elif _sort == 'high-to-low':
                ShoesItems = ShoesItems.annotate(priceBought=F(
                    'price')*((100-F('discount'))/100)).order_by('-priceBought')

        paginator = Paginator(ShoesItems, 8)
        ShoesItems = paginator.get_page(_page)

        return ShoesItems

    template_name = 'category_Shoes.html'

class CategoryShoesDetailView(DetailView):
    model = ShoesItem

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['sameItems'] = ShoesItem.objects.filter(
            status=True).exclude(barCode=self.kwargs['pk']).order_by('?')
        print(ShoesItem.objects.filter(
            status=True).exclude(barCode=self.kwargs['pk']).order_by('?'))
        return context

    template_name = 'Shoes_detail.html'

class CategoryClothesView(ListView):
    context_object_name = 'clothesItems'

    def get_queryset(self):
        clothesItems = ClothesItem.objects.filter(status=True)
        _price = self.request.GET.get('price')
        _sort = self.request.GET.get('sort')
        _page = self.request.GET.get('page')

        if _price:
            if _price == 'duoi100000':
                clothesItems = clothesItems.annotate(priceBought=F(
                    'price')*((100-F('discount'))/100)).filter(priceBought__lt=100000)
            elif _price == '100000den200000':
                clothesItems = clothesItems.annotate(priceBought=F(
                    'price')*((100-F('discount'))/100)).filter(priceBought__gte=100000, priceBought__lt=200000)
            elif _price == 'tren200000':
                clothesItems = clothesItems.annotate(priceBought=F(
                    'price')*((100-F('discount'))/100)).filter(priceBought__gte=200000)

        if _sort:
            if _sort == 'low-to-high':
                clothesItems = clothesItems.annotate(priceBought=F(
                    'price')*((100-F('discount'))/100)).order_by('priceBought')
            elif _sort == 'high-to-low':
                clothesItems = clothesItems.annotate(priceBought=F(
                    'price')*((100-F('discount'))/100)).order_by('-priceBought')

        paginator = Paginator(clothesItems, 8)
        clothesItems = paginator.get_page(_page)

        return clothesItems

    template_name = 'category_clothes.html'

class CategoryClothesDetailView(DetailView):
    model = ClothesItem

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['sameItems'] = ClothesItem.objects.filter(
            status=True).exclude(barCode=self.kwargs['pk']).order_by('?')
        print(ClothesItem.objects.filter(
            status=True).exclude(barCode=self.kwargs['pk']).order_by('?'))
        return context

    template_name = 'clothes_detail.html'


import jsonpickle
from MQTT.encryption import Encryption
from model.message import Message
from MQTT.mqttClient import MQTTClient

class Sender:
    def __init__(self):
        self.acquisitions = None
        self.client = None
        self.encryption = None

    def JSONConverter(self, msg):
        aJSON = jsonpickle.encode(msg, unpicklable=False)
        #return json.dumps(aJSON)
        return(aJSON)

    def send(self, acquisitions):
        self.acquisitions = acquisitions
        if self.client is None:
            self.client = MQTTClient()
            self.client.connect_mqtt()
        if self.encryption is None:
            self.encryption = Encryption()

        for acquisition in acquisitions:
            message = Message(acquisition)
            jsonMessage = self.JSONConverter(message)
            self.client.publish(self.encryption.encrypt(jsonMessage))


############################################
# Name: Bryan John Baker
# Student ID: bake1358
# Email: bake1358@umn.edu
# Collaborators:
# File Name: hw4_adaboost.py
############################################

import numpy as np
import pandas as pd
from sklearn.tree import DecisionTreeClassifier
import matplotlib.pyplot as plt

def plot_margin(data, learner_lst, alpha_lst):
    """
    Create a margin plot.
    :param data: The dataset used to create the model.
    :param learner_lst: A list of weak learners.
    :param alpha_lst: A list of alphas to use in the Adaboost model.
    :return: A margin plot.
    """
    margin = []
    for i in range(data.shape[0]):
        f_x = 0
        for j in range(len(learner_lst)):
            f_x += (alpha_lst[j] * learner_lst[j].predict(np.array(data.iloc[i]).reshape(1, -1)))
        margin.append(f_x[0])
    margin = margin / sum(alpha_lst)
    margin = train_y.reshape(-1) * margin
    margin.sort()
    cumulative = np.cumsum(margin)
    cumulative = cumulative / sum(margin)
    plt.plot(margin, cumulative)
    plt.title("Adaboost Margin Plot for " + str(len(learner_lst)) + " learners")
    plt.xlabel("Margin")
    plt.ylabel("Cumulative Distribution")
    plt.xlim(-1, 1)
    plt.ylim(0, 1)
    plt.grid()
    plt.show()

# Read and prepare training dataset
training_data = pd.read_csv("cancer_train.csv")
train_y = np.array(training_data["y"])
train_y = train_y.reshape(-1, 1)
train_y[train_y == 0] = -1
train_x = training_data
train_x = train_x.drop("y", axis=1)

# Read and prepare testing dataset
testing_data = pd.read_csv("cancer_test.csv")
test_y = np.array(testing_data["y"])
test_y = test_y.reshape(-1, 1)
test_y[test_y == 0] = -1
test_x = testing_data
test_x = test_x.drop("y", axis=1)

# Initialize weights and lists to store alpha_lst and learner_lst
D_train = np.full(train_y.shape, 1/train_y.shape[0]).reshape(-1)
D_train = D_train / np.sum(D_train)
D_test = np.full(test_y.shape, 1/test_y.shape[0]).reshape(-1)
D_test = D_test / np.sum(D_test)
trees = []
alphas = []
iter = []
train_error_lst = []
test_error_lst = []

# Run Adaboost algorithm using 100 weak learners
for i in range(100):
    iter.append(i)
    # Train the weak learner using the sample weights we calculated
    decision_tree = DecisionTreeClassifier(max_depth=1, criterion="gini")
    decision_tree = decision_tree.fit(train_x, train_y, sample_weight=D_train)
    # Store the learner
    trees.append(decision_tree)
    # Calculate epsilon
    epsilon = np.sum(D_train * (decision_tree.predict(train_x) != train_y.reshape(-1)))
    # Calculate alpha
    alpha = 0.5 * np.log((1 - epsilon) / (epsilon))
    print("Model " + str(i) + "; epsilon: " + str(epsilon) + "; alpha: " + str(alpha))
    # Store alpha
    alphas.append(alpha)
    # Calculate the new training weights and normalize them
    D_train = D_train * np.exp(-alpha * train_y.reshape(-1) * decision_tree.predict(train_x))
    D_train = D_train / np.sum(D_train)
    # Find the training set predictions and misclassification error
    f_x = 0
    for j in iter:
        f_x += (alphas[j] * trees[j].predict(train_x))
    y_train_preds = np.sign(f_x)
    train_error = np.mean(np.not_equal(y_train_preds, train_y.reshape(-1)))
    train_error_lst.append(train_error)
    # Find the testing set predictions and misclassification error
    f_x = 0
    for j in iter:
        f_x += (alphas[j] * trees[j].predict(test_x))
    y_test_preds = np.sign(f_x)
    test_error = np.mean(np.not_equal(y_test_preds, test_y.reshape(-1)))
    test_error_lst.append(test_error)
    print("Training error: " + str(train_error) + "; Testing error: " + str(test_error))
    if i in [24, 49, 74, 99]:
        plot_margin(train_x, trees, alphas)

# Create the misclassification plot
plt.xlabel('Number of Weak Learners')
plt.ylabel('Misclassification Error')
plt.title('Adaboost Misclassification Error on Cancer Dataset')
plt.grid()
plt.plot(train_error_lst)
plt.plot(test_error_lst)
plt.gca().legend(('Training Data', 'Testing Data'))
plt.show()


class Solution:
    def sortArray(self, nums: List[int]) -> List[int]:
        if(len(nums) <= 1):
            return nums

        mid = len(nums) // 2
        l,r = nums[:mid], nums[mid:]
        return self.mergeSort(self.sortArray(l),self.sortArray(r))
    def mergeSort(self,left,right):
        sorted = [None]*(len(left) + len(right))
        i = j = k = 0
        while(i < len(left) and j < len(right)):
            if(left[i] <= right[j]):
                sorted[k] = left[i]
                i += 1
            else:
                sorted[k] = right[j]
                j += 1
            k += 1

        while(i < len(left)):
            sorted[k] = left[i]
            i += 1
            k += 1
        while(j < len(right)):
            sorted[k] = right[j]
            j += 1
            k += 1
        return sorted

Arrays, Matrix, Stack, Queue, Heaps/P912 - sortAnArray.py