from django.shortcuts import render

# Create your views here.
from django.contrib.auth.decorators import login_required
from datetime import datetime
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from app.models import PurchaseOrder, PurchaseOrderProduct, Staff
from django.http import HttpRequest

@login_required
def arviewPo(request):
    po_list = PurchaseOrder.objects.filter(selected=True).only('purchaseOrderID', 'staffID', 'poStatus')

    context = {
        'title':'View Purchase Order',
        'year':datetime.now().year,
        'po_list': po_list,
    }
    return render(request, 'arPurchaseOrder/viewPo.html', context)

def arselectPo(request):
    data = PurchaseOrder.objects.filter()
    po = None

    for i in data:
        if i.purchaseOrderID in request.POST:
            po = PurchaseOrder.objects.filter(purchaseOrderID=i.purchaseOrderID)
            products = PurchaseOrderProduct.objects.filter(purchaseOrderID=i.purchaseOrderID, productPurchased=True)
            qtyProvided = po.get().qtyProvided
            staffID = po.get().staffID
            vendorID = po.get().vendorID
            poStatus = po.get().poStatus
            totalPrice = po.get().totalPrice
            print(poStatus)

    quo = po.get().quotationID

    context = {
        'po': po.get(), 'quo': quo,
        'products': products,
        'qtyProvided': qtyProvided,
        'staffID': staffID, 'vendorID':vendorID,
        'poStatus':poStatus, 'totalPrice': totalPrice,
    }

    return render(request,'arPurchaseOrder/selectPo.html', context)

def arapprovePo(request):
    #DATA BEFORE
    # dataP = PurchaseOrder.objects.filter(poStatus__in=['Pending']).values()
    # dataAp = PurchaseOrder.objects.filter(poStatus__in=['Approved']).values()
    # print(dataP)
    # print(dataAp)

    #GET SELECTED PO
    currentPo = PurchaseOrder.objects.filter(purchaseOrderID=request.POST.get("purchaseOrder"))
    print(currentPo)
    currentPo.update(poStatus='Approved')

    #DATA AFTER
    # print(dataP)
    # print(dataAp)

    context = {
        'currentPo':currentPo
    }
    return render(request, 'arPurchaseOrder/messagePo.html', context)

def arrejectPo(request):
    #DATA BEFORE
    # dataP = PurchaseOrder.objects.filter(poStatus__in=['Pending']).values()
    # dataAp = PurchaseOrder.objects.filter(poStatus__in=['Approved']).values()
    # print(dataP)
    # print(dataAp)

    #GET SELECTED PO
    currentPo = PurchaseOrder.objects.filter(purchaseOrderID=request.POST.get("purchaseOrder"))
    print(currentPo)
    currentPo.update(poStatus='Rejected')

    #DATA AFTER
    # print(dataP)
    # print(dataAp)

    context = {
        'currentPo':currentPo
    }
    return render(request, 'arPurchaseOrder/messagePo.html', context)

##############################################################################################
def arsearchPo(request):
    if request.method == "POST":
        searched = request.POST['searched']
        purchaseOrderID = PurchaseOrder.objects.filter(purchaseOrderID__contains=searched)

        context = {
                'searched': searched,
                'purchaseOrderID' : purchaseOrderID,
            }

        return render(request,'arPurchaseOrder/searchPo.html',context)
    else:
        return render(request,'arPurchaseOrder/searchPo.html',context)

def arbacktohome(request):
    """Renders the home page."""
    assert isinstance(request, HttpRequest)
    if request.user.is_authenticated:
        return(redirect('/menu'))
    else:
        return render(
            request,
            'app/menu.html',
            {
                'title':'View Item',
                'year': datetime.now().year,
            }
        )
def arbacktolist(request):
    """Renders the home page."""
    assert isinstance(request, HttpRequest)
    if request.user.is_authenticated:
        return(redirect('/arviewPo/'))
    return render(
            request,
            'arPurchaseOrder/viewPo.html',
            {
                'title':'Purchase Order List',
                'year': datetime.now().year,
            }
        )


"""Implementations of loss functions for 3D semantic segmentation."""

import tensorflow as tf
from tensorflow.python.keras.losses import LossFunctionWrapper
from tensorflow.python.keras.utils.losses_utils import ReductionV2

from nobrainer import metrics

def dice(y_true, y_pred, axis=(1, 2, 3, 4)):
    return 1.0 - metrics.dice(y_true=y_true, y_pred=y_pred, axis=axis)

class Dice(LossFunctionWrapper):
    """Computes one minus the Dice similarity between labels and predictions.
    For example, if `y_true` is [0., 0., 1., 1.] and `y_pred` is [1., 1., 1., 0.]
    then the Dice loss is 0.6. The Dice similarity between these tensors is 0.4.

    Use this loss only for binary semantic segmentation tasks. The default value
    for the axis parameter is meant for models which output a shape of
    `(batch, x, y, z, 1)`. Values in `y_true` and `y_pred` should be in the
    range [0, 1].

    Usage:

    ```python
    dice = nobrainer.losses.Dice(axis=None)
    loss = dice([0., 0., 1., 1.], [1., 1., 1., 0.])
    print('Loss: ', loss.numpy())  # Loss: 0.6
    ```

    Usage with tf.keras API:
    ```python
    model = tf.keras.Model(inputs, outputs)
    model.compile('sgd', loss=nobrainer.losses.Dice())
    ```
    """

    def __init__(self, axis=(1, 2, 3, 4), reduction=ReductionV2.AUTO, name="dice"):
        super().__init__(dice, axis=axis, reduction=reduction, name=name)

def focal_tversky(y_true, y_pred):
    """
    https://arxiv.org/pdf/1810.07842.pdf
    """
    raise NotImplementedError()

def generalized_dice(y_true, y_pred, axis=(1, 2, 3)):
    return 1.0 - metrics.generalized_dice(y_true=y_true, y_pred=y_pred, axis=axis)

class GeneralizedDice(LossFunctionWrapper):
    """Computes one minus the generalized Dice similarity between labels and
    predictions. For example, if `y_true` is [[0., 0., 1., 1.]] and `y_pred` is
    [[1., 1., 1., 0.]] then the generalized Dice loss is 0.60. The generalized
    Dice similarity between these tensors is 0.40.

    Use this loss for binary or multi-class semantic segmentation tasks. The
    default value for the axis parameter is meant for models which output a
    shape of `(batch, x, y, z, n_classes)`. Values in `y_true` and `y_pred`
    should be in the range [0, 1].

    Usage:

    ```python
    generalized_dice = nobrainer.losses.GeneralizedDice(axis=1)
    generalized_dice([[0., 0., 1., 1.]], [[1., 1., 1., 0.]])
    print('Loss: ', loss.numpy())  # Loss: 0.60
    ```

    Usage with tf.keras API:
    ```python
    model = tf.keras.Model(inputs, outputs)
    model.compile('sgd', loss=nobrainer.losses.GeneralizedDice())
    ```
    """

    def __init__(
        self, axis=(1, 2, 3), reduction=ReductionV2.AUTO, name="generalized_dice"
    ):
        super().__init__(generalized_dice, axis=axis, reduction=reduction, name=name)

def jaccard(y_true, y_pred, axis=(1, 2, 3, 4)):
    return 1.0 - metrics.jaccard(y_true=y_true, y_pred=y_pred, axis=axis)

class Jaccard(LossFunctionWrapper):
    """Computes one minus the Jaccard similarity between labels and predictions.
    For example, if `y_true` is [0., 0., 1., 1.] and `y_pred` is [1., 1., 1., 0.]
    then the Jaccard loss is 0.75. The Jaccard similarity between these tensors
    is 0.25.

    Use this loss only for binary semantic segmentation tasks. The default value
    for the axis parameter is meant for models which output a shape of
    `(batch, x, y, z, 1)`. Values in `y_true` and `y_pred` should be in the
    range [0, 1].

    Usage:

    ```python
    jaccard = nobrainer.losses.Jaccard(axis=None)
    loss = jaccard([0., 0., 1., 1.], [1., 1., 1., 0.])
    print('Loss: ', loss.numpy())  # Loss: 0.75
    ```

    Usage with tf.keras API:
    ```python
    model = tf.keras.Model(inputs, outputs)
    model.compile('sgd', loss=nobrainer.losses.Jaccard())
    ```
    """

    def __init__(self, axis=(1, 2, 3, 4), reduction=ReductionV2.AUTO, name="jaccard"):
        super().__init__(jaccard, axis=axis, reduction=reduction, name=name)

def tversky(y_true, y_pred, axis=(1, 2, 3), alpha=0.3, beta=0.7):
    n_classes = tf.cast(tf.shape(y_pred)[-1], tf.float32)
    # Scores are in dynamic range of [0, n_classes].
    scores = metrics.tversky(
        y_true=y_true, y_pred=y_pred, axis=axis, alpha=alpha, beta=beta
    )
    return 1.0 - (scores / n_classes)

class Tversky(LossFunctionWrapper):
    """Computes Tversky loss between labels and predictions.

    Use this loss for binary or multi-class semantic segmentation tasks. The
    default value for the axis parameter is meant for binary or multi-class
    predictions. Values in `y_true` and `y_pred` should be in the range [0, 1].
    The default values for alpha and beta are set according to recommendations
    in the Tverky loss manuscript.

    Usage with tf.keras API:
    ```python
    model = tf.keras.Model(inputs, outputs)
    model.compile('sgd', loss=nobrainer.losses.Tversky())
    ```
    """

    def __init__(
        self,
        axis=(1, 2, 3),
        alpha=0.3,
        beta=0.7,
        reduction=ReductionV2.AUTO,
        name="tversky",
    ):
        super().__init__(
            tversky, axis=axis, alpha=alpha, beta=beta, reduction=reduction, name=name
        )

def elbo(y_true, y_pred, model, num_examples, from_logits=False):
    """Labels should be integers in `[0, n)`."""
    scc_fn = tf.losses.SparseCategoricalCrossentropy(from_logits=from_logits)
    neg_log_likelihood = scc_fn(y_true, y_pred)
    kl = sum(model.losses) / num_examples
    elbo_loss = neg_log_likelihood + kl
    return elbo_loss

class ELBO(LossFunctionWrapper):
    """Loss to minimize Evidence Lower Bound (ELBO).

    Use this loss for multiclass variational segmentation.
    Labels should not be one-hot encoded.
    """

    def __init__(
        self,
        model,
        num_examples,
        from_logits=False,
        reduction=ReductionV2.AUTO,
        name="ELBO",
    ):
        super().__init__(
            elbo,
            model=model,
            num_examples=num_examples,
            from_logits=from_logits,
            name=name,
            reduction=reduction,
        )

def get(loss):
    """Wrapper for `tf.keras.losses.get` that includes Nobrainer's losses."""
    objects = {
        "dice": dice,
        "Dice": Dice,
        "focal_tversky": focal_tversky,
        "jaccard": jaccard,
        "Jaccard": Jaccard,
        "tversky": tversky,
        "Tversky": Tversky,
        "elbo": elbo,
        "ELBO": ELBO,
    }
    with tf.keras.utils.CustomObjectScope(objects):
        return tf.keras.losses.get(loss)


# Definition for an interval.
# class Interval(object):
#     def __init__(self, s=0, e=0):
#         self.start = s
#         self.end = e

class Solution(object):
    def merge(self, intervals):
        """
        :type intervals: List[Interval]
        :rtype: List[Interval]
        """
        if len(intervals) == 1 or len(intervals) == 0:
            return intervals
        intervals.sort(key = lambda x: x.start)
        result = [intervals[0]]
        i = 1
        while i < len(intervals):
            if intervals[i].start <= result[-1].end:
                result[-1].end = max(result[-1].end, intervals[i].end)
            else:
                result.append(intervals[i])
            i += 1
        return result


## for testing, select a few labels
import pickle, gzip, os, sys, re
import random
from random import shuffle
import numpy as np
import pandas as pd

def submitJobs ( top_k, add_full_tree, do_manual, do_small ) : ## @add_full_tree add all ancestors

  os.chdir ('/u/flashscratch/d/datduong/MIMIC3database/format10Jan2019')

  all_ancestors = pickle.load ( open("all_ancestors_icd.pickle","rb") )

  list_data = ['disch_dev_split_correct_icd',
              #  'disch_full_correct_icd',
              'disch_test_split_correct_icd',
              'disch_train_split_correct_icd']

  print ('\n\ntesting on subset ??\n')
  if do_manual == 0:
    to_use = pickle.load ( open("/u/flashscratch/d/datduong/MIMIC3database/format10Jan2019/label_top"+str(top_k)+".pickle","rb"))

  if do_manual == 1:
    # to_use = ['401.9','38.93','428.0','427.31','414.01']
    # to_use = ['38.93','584.9'] ## add these KNOWN anti-correlated ones '584.5','584.6','584.7','584.8'
    to_use = ['38.93','584.5','584.6','584.7','584.8','584.9']
    top_k = len(to_use)
    if do_small == 'do_small':
      top_k = "small_"+str(top_k)

    pickle.dump (to_use, open("/u/flashscratch/d/datduong/MIMIC3database/format10Jan2019/label_manual_"+str(top_k)+".pickle","wb"))

  to_use = list (set (to_use))
  to_use.sort()
  print ( 'label wanted ')
  print ( to_use )

  if add_full_tree == 1:
    ancestor = []
    for j in to_use:
      ancestor = ancestor + all_ancestors[j]

    ancestor = list (set (ancestor))
    ancestor.sort()
    to_use_with_anc = to_use + ancestor ## add ancestors ??
    to_use_with_anc = list (set (to_use_with_anc))
    ## these ICD+ancestors of the ICD will be later used to extract from the whole 25k list.

    to_use_with_anc.sort()

    pickle.dump (to_use_with_anc, open("/u/flashscratch/d/datduong/MIMIC3database/format10Jan2019/label_top_full_tree_"+str(top_k)+".pickle","wb"))
    print ( '\nlabel wanted + their ancestors')
    print ( to_use_with_anc )

  for text_file in list_data:

    df = pd.read_csv (text_file+".csv",dtype=str) # 'disch_test_split.csv'
    df['LABELS'] = df['LABELS'].fillna('null')

    row_iterator = df.iterrows() ## is it faster ??
    keep_row = []
    for i, row in row_iterator:
      label = set(row['LABELS'].split(";")) ## get unique, because there are duplicated ... why ??
      inter = label.intersection ( to_use ) ## select only the LEAF NODES THAT WE WANT. ... LATER WE WILL APPEND THE PARENTS TO THEM

      if len(inter) > 0 :

        if do_small == 'do_small':
          if np.random.uniform() < .7 :
            continue ## skip so we get smaller dataset

        full_icd = list(inter)
        full_icd.sort()

        if add_full_tree == 1:
          for j in inter: ## for each label, we get their whole ancestors
            full_icd = full_icd + all_ancestors[j]

          ## add ancestors (may have duplicated so take "set")
          full_icd = list (set ( full_icd ) )
          full_icd.sort()

        df.loc[i,'LABELS'] = ";".join(j for j in full_icd) ## replace
        keep_row.append(i)

    # keep these row only
    df = df.loc[keep_row]

    if add_full_tree == 1:
      df.to_csv( text_file+"_full_tree_"+str(top_k)+"icd.csv", index=False )
    else:
      if do_manual == 1:
        df.to_csv( text_file+"_manual_"+str(top_k)+"icd.csv", index=False )
      else:
       df.to_csv( text_file+"_"+str(top_k)+"icd.csv", index=False )

if len(sys.argv)<1: ## run script
	print("Usage: \n")
	sys.exit(1)
else:
	submitJobs ( int(sys.argv[1]) , int(sys.argv[2]) , int(sys.argv[3]), sys.argv[4] )


import requests
from bs4 import BeautifulSoup
import openpyxl

wb = openpyxl.Workbook()
ws = wb.create_sheet('주식정보')

codes = [
    '005930',
    '000660',
    '035720'
]
i = 1
for code in codes:
    i += 1
    url = f'https://finance.naver.com/item/sise.naver?code={code}'
    response = requests.get(url)
    html = response.text

    soup = BeautifulSoup(html, 'html.parser')
    price = soup.select_one('#_nowVal').text
    price = price.replace(',', '')
    ws[f'B{i}'] = int(price)
wb.save(r'C:\python_crawling\C3\stock_data.xlsx')


'''
data = """
park 800905-1049118
kim  700905-1059119
"""

result = []
for line in data.split("\n"):
    word_result = []
    for word in line.split(" "):
        if len(word) == 14 and word [:6].isdigit() and word[7:].isdigit():
            word = word[:6] + "-" +"*******"
        word_result.append(word)
    result.append(" ".join(word_result))
print("\n". join(result))
'''

#match

import re
'''
p = re.compile('[a-z]+') # +는 최소 하나만 있어도 된다. a-z 소문자 하나만
#있으면 된다
m = p.match("Python") #왜냐면 문자열의 가장 처음부터 가기때문에, 여기는
#p가 대문자라서 none
print(m)

p = re.compile('[a-z]+') # +는 최소 하나만 있어도 된다. a-z 소문자 하나만
#있으면 된다
m = p.match("pyth0n 3") #p에서 h까지만 메치된다고 말해줌
print(m)
'''

#search
'''
p = re.compile('[a-z]+')
m = p.search("python")
print(m)

p = re.compile('[a-z]+')
m = p.search("Python") #p이후 부터만 됨/ 꼭앞에서 부터 보지 않음(unlike match)
print(m)

p = re.compile('[a-z]+')
m = p.search("3 pyth0n") #p이후 부터만 됨
print(m)
p.search()
'''
#fine all
'''
p = re.compile('[a-z]+')
m = p.findall("3 Pyth0n") #이 패턴인것을 다 찾고 싶다
print(m)
'''
#finditer
'''
p = re.compile('[a-z]+')
m = p.finditer("as3 pyth0n") #이것이 iterator인가?
print(m)
for r in m: #iterator이면은 어디가 iterator인가?
    print(r)
    '''

import re
p= re.compile("[a-z]+")
m=p.search("pYthOn")

print(m.group())
print(m.start())
print(m.end())
print(m.span())

a=[{'a':1, 'b':2}, {'a':1,'b':2}]
print(0['a'])

while True:
    newa = int(input('type'))
    for i in a:
        if newa == a[i]['a']:
            print("already exist")
        else: break


# -*- coding: utf-8 -*-
"""
Created on Wed Jun  3 12:11:37 2020

@author: Mack Pro
"""

import math
import random

import matplotlib.pyplot as plt
import numpy as npy

import volmdlr as volmdlr
import volmdlr.primitives2D as primitives2D
import volmdlr.primitives3D as primitives3D

rmin, rmax = 10, 100
posmin, posmax = -100, 100
x1, y1, z1 = random.randrange(posmin, posmax, 1)/100, random.randrange(posmin, posmax, 1)/100, random.randrange(posmin, posmax, 1)/100

r1 = random.randrange(rmin, rmax, 1)/1000
c1 = volmdlr.Point3D([x1,y1,z1])

x3, y3, z3 = random.randrange(posmin, posmax, 1)/100, random.randrange(posmin, posmax, 1)/100, random.randrange(posmin, posmax, 1)/100

n1 = volmdlr.Vector3D([x3,y3,z3])
n1 = n1.unit_vector() #Normalize the normal if it is not the case
plane1 = volmdlr.Plane3D.from_normal(c1, n1)

frame1 = volmdlr.Frame3D(c1, plane1.vectors[0], plane1.vectors[1], n1) #Frame in the center of the cylinder
cylsurface1 = volmdlr.CylindricalSurface3D(frame1, r1)

hmin, hmax = -50, 50

h1 = random.randrange(hmin, hmax, 5)/100

center2d = c1.To2D(c1, plane1.vectors[0], plane1.vectors[1])
#Classic Contour
segbh = volmdlr.LineSegment2D(center2d, center2d + volmdlr.Point2D((0,h1))) #### Minus Pt2D because of Step adaptation
circlestart = volmdlr.LineSegment2D(segbh.points[1], segbh.points[1]+volmdlr.Point2D((2*math.pi*3/4,0))) #You can change 2*pi by an other angle
seghb = volmdlr.LineSegment2D(circlestart.points[1],circlestart.points[1]-segbh.points[1])
circlend = volmdlr.LineSegment2D(seghb.points[1],segbh.points[0])
edges = [segbh, circlestart, seghb, circlend]
points = edges[0].points
contours =  [volmdlr.Contour2D(edges)]

cyl1 = volmdlr.CylindricalFace3D(contours, cylsurface1, points)

pts1, tangle1 = cyl1.triangulation(resolution=12)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
[pt.MPLPlot(ax=ax) for pt in pts1]

# number_holes = 5

# outer_circle = volmdlr.Circle2D(volmdlr.O2D, 0.06)

# circles = []
# delta_angle = 2*math.pi/number_holes
# inner_circle = volmdlr.Circle2D(volmdlr.O2D, 0.04)
# first_circle = volmdlr.Circle2D(volmdlr.Point2D((0, 0.05)), 0.005)
# circles = [inner_circle, first_circle]
# for i in range(1, number_holes):
#     circles.append(first_circle.Rotation(volmdlr.O2D, i*delta_angle))

# xn, yn, zn = random.randrange(posmin, posmax, 1)/100, random.randrange(posmin, posmax, 1)/100, random.randrange(posmin, posmax, 1)/100
# xc, yc, zc = random.randrange(posmin, posmax, 1)/100, random.randrange(posmin, posmax, 1)/100, random.randrange(posmin, posmax, 1)/100

# n = volmdlr.Vector3D([xn,yn,zn])
# n.Normalize()
# c = volmdlr.Point3D((xc,yc,zc))
# plane = volmdlr.Plane3D.from_normal(c, n)
# contours = [volmdlr.Contour2D([outer_circle])]#, inner_circle])]#, volmdlr.Contour2D(circles)]
# planeface = volmdlr.PlaneFace3D(contours,  plane)

# p1, p2 = cyl1.minimum_distance_points_plane(planeface)
# # print(p1.point_distance(p2))
# # print(p1)
# # print(p2)
# pts2, t2 = planeface.triangulation()
# [pt.MPLPlot(ax=ax) for pt in pts2]
# p1.MPLPlot(ax=ax, color='r')
# p2.MPLPlot(ax=ax, color='b')

##### extrusion 1

p1=volmdlr.Point2D((0, 0))
p2=volmdlr.Point2D((0.1, 0.))
p3=volmdlr.Point2D((0.1, 0.2))
p4=volmdlr.Point2D((0.05, 0.1))
p5=volmdlr.Point2D((0.,0.21))
p6=volmdlr.Point2D((0.05, 0.05))

p7 = volmdlr.Point2D((0.06, 0.05))
p8 = volmdlr.Point2D((0.04, 0.07))

radius = {0: 0.01, 2: 0.01, 3: 0.015}

outer_profile = primitives2D.ClosedRoundedLineSegments2D([p1, p2, p3, p4, p5], radius)
#hole = volmdlr.Circle2D(p6, 0.01)
#inner_profile = primitives2D.RoundedLineSegments2D([p6, p7, p8], {0: 0.5}, closed = True)
l1 = volmdlr.LineSegment2D(p6, p7)
l2 = volmdlr.LineSegment2D(p7, p8)
l3 = volmdlr.LineSegment2D(p8, p6)
c2 = volmdlr.Contour2D([l1,l2,l3])

#c1 = volmdlr.Contour2D([outer_profile])
#c2 = volmdlr.Contour2D([inner_profile])

# f, a = outer_profile.MPLPlot()
# c2.MPLPlot(a)

profile=primitives3D.ExtrudedProfile(volmdlr.O3D, volmdlr.Y3D, volmdlr.Z3D, outer_profile, [c2], volmdlr.X3D*0.1, name = 'extrusion')
dmin, p1 ,p2 = cyl1.minimum_distance(profile.faces[0], return_points=True)
face_min = profile.faces[0]
# print('dmin', dmin)
for face in profile.faces[1:] :
    dtest, ptest1, ptest2 = cyl1.minimum_distance(face, return_points=True)
    # print('dtest', dtest)
    if dtest < dmin :
        p1, p2 = ptest1, ptest2
        dmin = dtest
        face_min = face

# print('>>>>>>>>> distance minimale', dmin)

shell = volmdlr.Shell3D([cyl1])
vol = volmdlr.VolumeModel([shell, profile, p1, p2])
vol.babylonjs_from_script()
# m = volmdlr.VolumeModel([shell, profile])
# m.babylonjs()


#!/usr/bin/env python3

import csv

import bs4
import dateutil.parser
import requests

from collections import namedtuple
from datetime import timedelta
from itertools import chain

days = [
'http://www.tomorrowland.com/en/friday-22-july',
'http://www.tomorrowland.com/en/saturday-23-july',
'http://www.tomorrowland.com/en/sunday-24-july',
]

TimeSlot = namedtuple('TimeSlot', ['stage', 'artist', 'time_start', 'time_end', 'duration'])

def fetch_day(url, parser="lxml"):
    day_html = requests.get(url).text
    soup = bs4.BeautifulSoup(day_html, parser)
    return soup

def parse_day(url):
    soup = fetch_day(url)
    day_str = soup.find('h1', class_='page-title').text
    day = dateutil.parser.parse(day_str)

    stage_titles = {}
    for title in soup.find_all('div', class_='stage-logo'):
        stage_titles[title['data-id']] = title.find('img', class_='stage-icon')['title']

    stages = soup.find_all('div', class_='stage')
    return (parse_stage(stage, stage_titles, day) for stage in stages)

def parse_stage(stage, titles, day):
    timeslots = stage.find('div', class_='artists').find_all('div', class_="time-slot performance")
    stage_id = stage['data-id']
    stage_title = titles[stage_id]

    return (parse_timeslot(timeslot, day, stage_title) for timeslot in timeslots)

def parse_timeslot(timeslot, day, stage):
    artist = timeslot.find('a').text
    time_start, time_end = timeslot.find('span', class_='time').text.split('-')
    set_start = parse_time(day, time_start)
    set_end = parse_time(day, time_end)

    return TimeSlot(stage, artist, set_start, set_end, set_end - set_start)

def parse_time(day, time):
    # push times before 6am to the following day
    if int(time.partition(':')[0]) < 6:
        day = day + timedelta(days=1)

    return dateutil.parser.parse(time, default=day)

def main():
    sets = (parse_day(day) for day in days)

    # completely flatten the day[stage[set]] nested list structure
    flat_sets = chain.from_iterable((chain.from_iterable(sets)))

    # write out file
    with open("tomorrowland2016.csv", 'w') as outfile:
        csvfile = csv.writer(outfile)
        csvfile.writerow(TimeSlot._fields)
        csvfile.writerows(flat_sets)

if __name__ == '__main__':
    main()


#takes in the input
count = int(input())
words = list(input().split(' '))

#goes through the iterations and if the number matches, it's fine
for i in range(1, count+1):
    if(words[i-1]!='mumble' and int(words[i-1])!=i):
        print("something is fishy")
        exit()

#if it completed the loop, his count is fine
print("makes sense")


from itertools import product
import sys
class Solution():

    def get_max_product_of_three_numbers(self,arr):
        min_1 = sys.maxsize
        min_2 = sys.maxsize
        max_1 = -sys.maxsize
        max_2 = -sys.maxsize
        max_3 = -sys.maxsize
        for num in arr:
            if num >= max_1:
                max_3 = max_2
                max_2 = max_1
                max_1 = num
            elif num >= max_2:
                max_3 = max_2
                max_2 = num
            elif num >= max_3:
                max_3 = num

            if num <= min_1:
                min_2 = min_1
                min_1 = num
            elif num <= min_2:
                min_2 = num

        product1 = min_1 * min_2 * max_1
        product_2 = max_1 * max_2 * max_3
        ans = max(product1, product_2)
        print(ans)

Solution().get_max_product_of_three_numbers([1,2,3,7,4,5,6,8])

Level Up/arrays and strings/max_product_of_3_nums.py


import pyttsx3
import pyaudio
import speech_recognition as sr
import sys
import webbrowser
import bs4, requests
import random
from bs4 import BeautifulSoup
from requests_html import HTMLSession

session = HTMLSession()
engine = pyttsx3.init()
#Manual Override
manual = False
print("Enable manual override? (Y/N)")
engine.say("Enable manual override?")
engine.runAndWait()
override = input()
if(override.lower() == "y"):
    print("Manual override enabled")
    engine.say("Manual override enabled")
    manual = True
else:
    print("Voice recognition enabled")
    engine.say("Voice recognition enabled")
print("What's on your mind?")
engine.say("What's on your mind?")
engine.runAndWait()
while(True):
    query = ""
    search = ""
    question = ""
    insert = ""
    output = []
    #Input
    r = sr.Recognizer()
    end = False
    skip = False
    if(manual == False):
        with sr.Microphone() as source:
            audio = r.listen(source)
            try:
                text = r.recognize_google(audio)
            except:
                skip = True
    else:
        text = input()
    #Categories
            #Terminate, Math, Google, Youtube, Trivia, Store, Joke, Translate
    store = ["make", "acquire", "build", "read", "clear", "delete", "destroy"]
    trivia = ["who", "what", "when", "where", "why", "how","How", "Who", "What", "Where", "When", "Why"]
    youtube = ["YouTube", "play", "Play"]
    google = ["Google", "search"]
    math = ["math", "calculate"]
    terminate = ["exit", "terminate", "end", "stop", "bye", "goodbye", "close"]
    joke = ["joke", "laugh", "smile"]
    translate = ["translate", "language"]

    #Output
        #Terminate
    if(skip == False):
        tokens = text.split(" ")
        for i in range(len(terminate)):
            if(text == terminate[i]):
                end = True
                break

        if(end == False):
            if(skip == False):
                #Sentiment Values
                disgust = 0
                anger = 0
                sadness = 0
                suprise = 0
                fear = 0
                joy = 0
                trust = 0
                anticipation = 0
                sentiment = 0
                #Sentiment Analysis
                    ##Optimize Using Keystones
                    #Enable/Disable
                data = open(r"sentimentdata.txt","r")
                info = data.readlines()
                for e in range(len(tokens)):
                    for w in range(len(info)):
                        term = info[w].split(",")
                        if(term[0] == tokens[e]):
                            if(term[1] == "anger"):
                                anger += 1
                            if(term[1] == "sadness"):
                                sadness += 1
                            if(term[1] == "fear"):
                                fear += 1
                            if(term[1] == "joy"):
                                joy += 1
                            if(term[1] == "trust"):
                                trust += 1
                            if(term[1] == "anticipation"):
                                anticipation += 1
                            if(term[4] == "negative"):
                                sentiment -= 1
                            if(term[4] == "positive"):
                                sentiment += 1
                            break
                print(sentiment)
                print("Joy: " + str(joy))
                print("Anticipation: " + str(anticipation))
                print("Trust: " + str(trust))
                print("Sadness: " + str(sadness))
                print("Fear: " + str(fear))
                print("Anger: " + str(anger))
                #Joke
                reserve = ["Today at the bank, an old lady asked me to help check her balance. So I pushed her over.",
                           "I bought some shoes from a drug dealer. I don't know what he laced them with, but I've been tripping all day.",
                           "My dog used to chase people on a bike a lot. It got so bad, finally I had to take his bike away.",
                           "I couldn't figure out why the baseball kept getting larger. Then it hit me.",
                           "Why did the old man fall in the well? Because he couldn't see that well.",
                           "Where do you find a cow with no legs? Right where you left it.",
                           "What did one hat say to the other? You stay here. I’ll go on ahead.",
                           "Why did it take so long for the pirates to learn the Alphabet? They got stuck at C.",
                           "I think i would like a job cleaning mirrors, it's just something I could really see myself doing.",
                           "When a deaf person sees someone yawn do they think it’s a scream?"]
                for jk in range(len(joke)):
                    if(joke[jk] in tokens):
                        jok = random.randrange(0,9)
                        text = (reserve[jok])
                #Translate
                        #Refine Dictionary
                if(tokens[0] == translate[0] or tokens[0] == translate[1]):
                    try:
                        text = ""
                        dictionary = ""
                        msg = 1
                        while(msg < len(tokens)):
                            for tra in range(len(dictionary)):
                                word = dictionary[tra].split(" ")
                                if(tokens[msg] == word[0]):
                                    text += word[1]+" "
                                    break;
                                elif(tokens[msg] == word[1]):
                                    text += word[0]+" "
                                    break;
                            msg += 1
                    except:
                        text = "Please use the proper format, translate command, message. (EN-FR)"

                #Math
                for k in range(len(math)):
                    if(tokens[0] == math[k]):
                        if(len(tokens) > 3):
                            if(tokens[2] == "+" or tokens[2] == "add"):
                                text = int(tokens[1]) + int(tokens[3])
                            if(tokens[2] == "-" or tokens[2] == "subtract" or tokens[2] == "minus"):
                                text = int(tokens[1]) - int(tokens[3])
                            if(tokens[2] == "*" or tokens[2] == "multiply"):
                                text = int(tokens[1]) * int(tokens[3])
                            if(tokens[2] == "divide" or tokens[2] == "divided"):
                                text = int(tokens[1]) / int(tokens[3])
                            if(tokens[2] == "exponent"):
                                text = int(tokens[1]) ** int(tokens[3])
                            if(tokens[2] == "remainder" or tokens[2] == "modulus"):
                                text = int(tokens[1]) % int(tokens[3])
                        break
                #Google
                for j in range(len(google)):
                    if(tokens[0] == google[j]):
                        for m in range(len(tokens)):
                            if(m != 0):
                                query += tokens[m] + " "
                        webbrowser.open("https://google.com/search?q=%s" % query)
                        text = "Searching for: " + query
                        break
                #Youtube
                for b in range(len(youtube)):
                    if(tokens[0] == youtube[b]):
                        for n in range(len(tokens)):
                            if(n != 0):
                                search += tokens[n]
                                if(n != len(tokens)-1):
                                    search += "+"
                        results = requests.get("https://www.youtube.com/results?search_query=%s" % search).content
                        soup = BeautifulSoup(results, "html.parser")
                        for a in soup.find_all("a", href=True):
                            case = a['href']
                            if(len(case) > 1):
                                if(case[1] == "w"):
                                    webbrowser.open("https://www.youtube.com%s" % case)
                                    break
                        text = "Searching for: " + search.replace("+", " ")
                        break
                #Trivia
                for p in range(len(trivia)):
                    if(tokens[0] == trivia[p]):
                        for y in range(len(tokens)):
                            question += tokens[y]
                            if(y != len(tokens)-1):
                                question += " "
                        results = session.get("https://google.com/search?q=%s" % question).content
                        soup = BeautifulSoup(results, "html.parser")
                        try:
                            case = soup.find('div',{'class':'Z0LcW'})
                            if(case == None):
                                case = soup.find('span',{'class':'e24Kjd'})
                            text = case.text
                        except:
                            text = "Sorry, Kiwi encountered an issue"
                #Store
                for q in range(len(store)):
                    if(tokens[0] == store[q]):
                        if(tokens[0] == "make" or tokens[0] == "build"):
                            for v in range(len(tokens)):
                                if(v != 0):
                                    insert += tokens[v] + " "
                            file = open(r"notes.txt", "a")
                            file.write(insert)
                            text = "Notes updated successfully"
                        if(tokens[0] == "acquire" or tokens[0] == "read"):
                            file = open(r"notes.txt", "r")
                            try:
                                output = file.readlines()
                                text = output[0]
                            except:
                                text = "No notes found"
                        if(tokens[0] == "destroy" or tokens[0] == "delete" or tokens[0] == "clear"):
                            file = open(r"notes.txt", "w+")
                            file.write("")
                            text = "Notes successfully cleared"
                engine.say(text)
                print(text)
                engine.runAndWait()
        else:
            engine.say("Kiwi successfully terminated")
            print("Kiwi successfully terminated...")
            engine.runAndWait()
            break


from django.shortcuts import render, redirect
from django.views import View
from django.contrib import messages
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.http import HttpResponseRedirect
from django.utils.html import strip_tags
from django.utils.decorators import method_decorator

from backend.forms import Seat
from backend.models import Agency, Vehicle
from backend.forms import SeatForm
from core.utils.decorators import MustLogin

class SeatListView(PermissionRequiredMixin, View):
    permission_required = [
        "backend.view_seat",
    ]
    template = "backend/lists/seats.html"

    @method_decorator(MustLogin)
    def get(self, request, *args, **kwargs):
        if request.user.is_staff or request.user.is_superuser:
            seats = Seat.objects.all().order_by('-id')
        elif request.user.is_agency_admin:
            seats = Seat.objects.filter(vehicle__agency=request.user.agency)
        context = {'seats': seats}
        return render(request, self.template, context)

class CreateUpdateSeat(PermissionRequiredMixin, View):
    permission_required = [
        "backend.add_seat",
        "backend.change_seat",
    ]

    template = "backend/create_update_seat.html"

    @method_decorator(MustLogin)
    def get(self, request, *args, **kwargs):
        seat_id = request.GET.get('seat_id')
        vehicle_id = request.GET.get('vehicle_id')
        if request.user.is_staff or request.user.is_superuser:
            seat = Seat.objects.filter(id=seat_id).first()
            vehicle = Vehicle.objects.filter(id=vehicle_id).first()  # noqa
            vehicles = Vehicle.objects.all()
        elif request.user.is_agency_admin:
            seat = Seat.objects.filter(id=seat_id, vehicle__agency=request.user.agency).first()  # noqa
            vehicle = Vehicle.objects.filter(id=vehicle_id, agency=request.user.agency).first()  # noqa
            vehicles = Vehicle.objects.filter(agency=request.user.agency)
        context = {
            "seat": seat,
            "vehicle": vehicle,
            "vehicles": vehicles,
        }  # noqa
        return render(request, self.template, context)

    @method_decorator(MustLogin)
    def post(self, request, *args, **kwargs):
        seat_id = request.POST.get('seat_id')
        vehicle_id = request.POST.get('vehicle_id')
        if request.user.is_staff or request.user.is_superuser:
            vehicle = Vehicle.objects.filter(id=vehicle_id).first()
        elif request.user.is_agency_admin:
            vehicle = Vehicle.objects.filter(id=vehicle_id, agency=request.user.agency).first()  # noqa

        if seat_id:
            # seat exists - update seat
            if request.user.is_staff or request.user.is_superuser:
                seat = Seat.objects.filter(id=seat_id).first()
            elif request.user.is_agency_admin:
                seat = Seat.objects.filter(id=seat_id, vehicle__agency=request.user.agency).first()  # noqa
            form = SeatForm(request.POST, request.FILES, instance=seat)  # noqa
            if form.is_valid():
                new_seat = form.save(commit=False)
                new_seat.vehicle = vehicle
                new_seat.save()
                messages.success(request, 'Seat Detail Updated Successfully.')  # noqa
                return redirect('backend:seats')
            else:
                for field, error in form.errors.items():
                    message = f"{field.title()}: {strip_tags(error)}"
                    break
                messages.warning(request, message)
                return HttpResponseRedirect(request.META.get("HTTP_REFERER"))
        else:
            # it's a new seat - create seat
            form = SeatForm(request.POST, request.FILES)
            if form.is_valid():
                seat = form.save(commit=False)
                seat.vehicle = vehicle
                seat.save()
                messages.success(request, 'New Seat Created Successfully.')  # noqa
                return redirect('backend:seats')
            else:
                for field, error in form.errors.items():
                    message = f"{field.title()}: {strip_tags(error)}"
                    break
                messages.warning(request, message)
                return HttpResponseRedirect(request.META.get("HTTP_REFERER"))

class DeleteSeat(PermissionRequiredMixin, View):
    permission_required = [
        "backend.delete_seat",
    ]

    @method_decorator(MustLogin)
    def get(self, request, *args, **kwargs):
        return redirect('backend:seats')

    @method_decorator(MustLogin)
    def post(self, request, *args, **kwargs):
        seat_id = request.POST.get('seat_id')
        if request.user.is_staff or request.user.is_superuser:
            seat = Seat.objects.filter(id=seat_id).first()
        elif request.user.is_agency_admin:
            seat = Seat.objects.filter(
                id=seat_id, vehicle__agency=request.user.agency).first()
        seat.delete()
        messages.success(request, 'Vehicle Seat Deleted Successfully.')
        return HttpResponseRedirect(request.META.get("HTTP_REFERER"))


from PyQt5.QtCore import QThread
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

from src.db.NNstorage import available_networks, save_new_network
from src.game.GameEngine import GameEngine
from src.gui.WindowUtils import WindowUtils

class MenuTab(WindowUtils):
    """ Defines UI elements for configuration menu """

    def __init__(self, centralWidget, baseStack, ownStack, wrap):
        """ Widgets declaration and connection to methods """

        super(MenuTab, self).__init__(wrap)
        self.baseStack = baseStack  # Allows menu navigation

        # Main title {{
        title = QLabel("Othello")
        title.setFont(QFont('Courier', 18))

        # laying out
        title_layout = QHBoxLayout()
        title_layout.addStretch()
        title_layout.addWidget(title)
        title_layout.addStretch()
        # }}

        # Train ML agent #

        # select file {{
        train_file_lb = QLabel("Filename", centralWidget)
        train_file_lb.setMinimumWidth(100)

        self.train_file_cb = self.init_combobox(list(), centralWidget)

        # layout
        train_file_lt = self.horizontal_menu_widget_layout(train_file_lb, self.train_file_cb)
        # }}

        # move selection {{
        move_selec_lb = QLabel("Move selection", centralWidget)
        move_selec_lb.setMinimumWidth(100)

        self.move_selec_cb = self.init_combobox(["eps-greedy", "softmax exponential"], centralWidget)

        self.move_selec_lt = self.horizontal_menu_widget_layout(move_selec_lb, self.move_selec_cb)
        # }}

        # learning rate {{
        learn_rate_lb = QLabel("Learning rate", centralWidget)
        learn_rate_lb.setMinimumWidth(100)

        self.learn_rate_sb = QDoubleSpinBox(centralWidget)
        self.learn_rate_sb.setMinimumWidth(125)
        self.learn_rate_sb.setRange(0, 1)
        self.learn_rate_sb.setSingleStep(0.05)

        learn_rate_lt = self.horizontal_menu_widget_layout(learn_rate_lb, self.learn_rate_sb)
        # }}

        # random factor (epsilon) {{
        train_eps_lb = QLabel("Random factor", centralWidget)
        train_eps_lb.setMinimumWidth(100)

        self.train_eps_sb = QDoubleSpinBox(centralWidget)
        self.train_eps_sb.setMinimumWidth(125)
        self.train_eps_sb.setRange(0, 1)
        self.train_eps_sb.setSingleStep(0.05)

        train_eps_lt = self.horizontal_menu_widget_layout(train_eps_lb, self.train_eps_sb)
        # }}

        # number of games {{
        nb_trains_lb = QLabel("Number of games", centralWidget)
        nb_trains_lb.setMinimumWidth(100)

        self.nb_trains_sb = QSpinBox(centralWidget)
        self.nb_trains_sb.setMinimumWidth(125)
        self.nb_trains_sb.setRange(1000, 1000000)
        self.nb_trains_sb.setSingleStep(1000)

        nb_trains_lt = self.horizontal_menu_widget_layout(nb_trains_lb, self.nb_trains_sb)
        # }}

        # progress bar {{
        train_prog_lb = QLabel("Training", centralWidget)
        train_prog_lb.setMinimumWidth(100)

        self.train_prog_pb = QProgressBar()
        self.train_prog_pb.setMinimumWidth(125)

        train_prog_lt = self.horizontal_menu_widget_layout(train_prog_lb, self.train_prog_pb)
        # }}

        # launch button {{
        self.launch_train_btn = QPushButton("Train", centralWidget)
        self.launch_train_btn.setMinimumWidth(250)

        # connect
        self.launch_train_btn.clicked.connect(lambda: self.launch_train_compare("train"))

        launch_train_lt = self.horizontal_menu_widget_layout(self.launch_train_btn)
        # }}
        # end Train ML agent #

        # Game against program #

        # player 1 type {{
        player_1_lb = QLabel("Player 1", centralWidget)
        player_1_lb.setMinimumWidth(100)

        self.player1_type_cb = self.init_combobox(["human", "random", "ML agent", "minimax"], centralWidget)

        # layout
        player1_lt = self.horizontal_menu_widget_layout(player_1_lb, self.player1_type_cb)
        # }}

        # player 2 type {{
        player_2_lb = QLabel("Player 2", centralWidget)
        player_2_lb.setMinimumWidth(100)

        self.player2_type_cb = self.init_combobox(["human", "random", "ML agent", "minimax"], centralWidget)

        # layout
        player2_lt = self.horizontal_menu_widget_layout(player_2_lb, self.player2_type_cb)
        # }}

        # pawns style {{
        pawns_style_lb = QLabel("Pawns style", centralWidget)
        pawns_style_lb.setMinimumWidth(100)

        self.pawns_style_cb = self.init_combobox(["classic", "undertale"], centralWidget)

        pawns_style_lt = self.horizontal_menu_widget_layout(pawns_style_lb, self.pawns_style_cb)
        # }}

        # random factor (epsilon) {{
        match_eps_lb = QLabel("Random factor", centralWidget)
        self.match_eps_sb = QDoubleSpinBox(centralWidget)
        self.match_eps_sb.setMinimumWidth(125)
        self.match_eps_sb.setRange(0, 1)
        self.match_eps_sb.setSingleStep(0.05)

        # layout
        match_eps_lt = self.horizontal_menu_widget_layout(match_eps_lb, self.match_eps_sb)
        # }}

        # ML agent subtitle {{
        ml_subtitle = QLabel("ML agent", centralWidget)
        ml_subtitle.setFont(QFont('Courier', 12))

        # laying out
        ml_subtitle_lt = self.horizontal_menu_widget_layout(ml_subtitle)
        # }}

        # ML match file (player 1) {{
        match_file1_lb = QLabel("Filename (agent 1)", centralWidget)
        match_file1_lb.setMinimumWidth(100)

        self.match_file1_cb = self.init_combobox(list(), centralWidget)

        # layout
        match_file1_lt = self.horizontal_menu_widget_layout(match_file1_lb, self.match_file1_cb)
        # }}

        # ML match file (player 2) {{
        match_file2_lb = QLabel("Filename (agent 2)", centralWidget)
        match_file2_lb.setMinimumWidth(100)

        self.match_file2_cb = self.init_combobox(list(), centralWidget)

        # layout
        match_file2_lt = self.horizontal_menu_widget_layout(match_file2_lb, self.match_file2_cb)
        # }}

        # minimax subtitle {{
        mnx_subtitle = QLabel("Minimax agent", centralWidget)
        mnx_subtitle.setFont(QFont('Courier', 12))

        # laying out
        mnx_subtitle_lt = self.horizontal_menu_widget_layout(mnx_subtitle)
        # }}

        # minimax early hits (player 1) {{
        play_ehits1_lb = QLabel("Depth (agent 1)")
        play_ehits1_lb.setMinimumWidth(100)

        self.play_ehits1_sb = QSpinBox(centralWidget)
        self.play_ehits1_sb.setMinimumWidth(125)
        self.play_ehits1_sb.setRange(0, 60)
        self.play_ehits1_sb.setSingleStep(1)

        # layout
        play_ehits1_lt = self.horizontal_menu_widget_layout(play_ehits1_lb, self.play_ehits1_sb)
        # }}

        # minimax early hits (player 2) {{
        play_ehits2_lb = QLabel("Depth (agent 2)")
        play_ehits2_lb.setMinimumWidth(100)

        self.play_ehits2_sb = QSpinBox(centralWidget)
        self.play_ehits2_sb.setMinimumWidth(125)
        self.play_ehits2_sb.setRange(0, 60)
        self.play_ehits2_sb.setSingleStep(1)

        # layout
        play_ehits2_lt = self.horizontal_menu_widget_layout(play_ehits2_lb, self.play_ehits2_sb)
        # }}

        # launch button {{
        self.launch_match_btn = QPushButton("Play", centralWidget)
        self.launch_match_btn.setMinimumWidth(250)

        # connect
        self.launch_match_btn.clicked.connect(lambda: self.launch_match(baseStack, 1))

        launch_match_lt = self.horizontal_menu_widget_layout(self.launch_match_btn)
        # }}

        # End of game against program #

        # New ML agent #

        # filename {{
        new_agent_fname_lb, self.new_agent_fname = self.label_and_input("Filename", centralWidget)

        new_agent_fname_lt = self.horizontal_menu_widget_layout(new_agent_fname_lb, self.new_agent_fname)
        # }}

        # NN size {{
        nn_size_lb = QLabel("NN size")
        nn_size_lb.setMinimumWidth(100)

        self.nn_size_sb = QSpinBox(centralWidget)
        self.nn_size_sb.setMinimumWidth(125)
        self.nn_size_sb.setRange(1, 100)
        self.nn_size_sb.setSingleStep(1)

        # layout
        nn_size_lt = self.horizontal_menu_widget_layout(nn_size_lb, self.nn_size_sb)
        # }}

        # learning strategy {{
        learn_strat_lb = QLabel("Learning strategy", centralWidget)
        learn_strat_lb.setMinimumWidth(100)

        self.learn_strat_cb = self.init_combobox(["Q-learning", "SARSA"], centralWidget)

        learn_strat_lt = self.horizontal_menu_widget_layout(learn_strat_lb, self.learn_strat_cb)
        # }}

        # activation function {{
        act_fun_lb = QLabel("Activation function", centralWidget)
        act_fun_lb.setMinimumWidth(100)

        self.act_fun_cb = self.init_combobox(["sigmoïd", "ReLU", "hyperbolic tangent"], centralWidget)

        act_fun_lt = self.horizontal_menu_widget_layout(act_fun_lb, self.act_fun_cb)
        # }}

        # create button {{
        self.create_agent_btn = QPushButton("Create", centralWidget)
        self.create_agent_btn.setMinimumWidth(250)

        # connect
        self.create_agent_btn.clicked.connect(lambda: self.create_new_agent())

        create_agent_lt = self.horizontal_menu_widget_layout(self.create_agent_btn)
        # }}
        # End new ML agent #

        # Comparison #

        # agent 1 type {{
        agent1_type_lb = QLabel("Agent 1", centralWidget)
        agent1_type_lb.setMinimumWidth(100)

        self.agent1_type_cb = self.init_combobox(["random", "ML agent", "minimax"], centralWidget)

        agent1_type_lt = self.horizontal_menu_widget_layout(agent1_type_lb, self.agent1_type_cb)
        # }}

        # agent 2 type {{
        agent2_type_lb = QLabel("Agent 2", centralWidget)
        agent2_type_lb.setMinimumWidth(100)

        self.agent2_type_cb = self.init_combobox(["random", "ML agent", "minimax"], centralWidget)

        agent2_type_lt = self.horizontal_menu_widget_layout(agent2_type_lb, self.agent2_type_cb)
        # }}

        # number of games {{
        nb_comps_lb = QLabel("Number of games", centralWidget)
        nb_comps_lb.setMinimumWidth(100)

        self.nb_comps_sb = QSpinBox(centralWidget)
        self.nb_comps_sb.setMinimumWidth(125)
        self.nb_comps_sb.setRange(1, 1000000)
        self.nb_comps_sb.setSingleStep(1000)

        nb_comps_lt = self.horizontal_menu_widget_layout(nb_comps_lb, self.nb_comps_sb)
        # }}

        # random factor (epsilon) {{
        cmp_eps_lb = QLabel("Random factor", centralWidget)
        cmp_eps_lb.setMinimumWidth(100)
        self.cmp_eps_sb = QDoubleSpinBox(centralWidget)
        self.cmp_eps_sb.setMinimumWidth(125)
        self.cmp_eps_sb.setRange(0, 1)
        self.cmp_eps_sb.setSingleStep(0.05)

        cmp_eps_lt = self.horizontal_menu_widget_layout(cmp_eps_lb, self.cmp_eps_sb)
        # }}

        # ML agent subtitle {{
        cmp_ml_agent_subtitle = QLabel("ML agent")
        cmp_ml_agent_subtitle.setFont(QFont('Courier', 12))

        # laying out
        cmp_ml_agent_subtitle_lt = self.horizontal_menu_widget_layout(cmp_ml_agent_subtitle)
        # }}

        # agent 1 file (ML) {{
        agent1_file_lb = QLabel("Filename (ML)", centralWidget)
        agent1_file_lb.setMinimumWidth(100)

        self.agent1_file_cb = self.init_combobox(list(), centralWidget)

        # layout
        agent1_file_lt = self.horizontal_menu_widget_layout(agent1_file_lb, self.agent1_file_cb)
        # }}

        # agent 2 file (ML) {{
        agent2_file_lb = QLabel("Filename (ML)", centralWidget)
        agent2_file_lb.setMinimumWidth(100)

        self.agent2_file_cb = self.init_combobox(list(), centralWidget)

        # layout
        agent2_file_lt = self.horizontal_menu_widget_layout(agent2_file_lb, self.agent2_file_cb)
        # }}

        # minimax agent subtitle {{
        cmp_minimax_agent_subtitle = QLabel("Minimax agent")
        cmp_minimax_agent_subtitle.setFont(QFont('Courier', 12))

        # laying out
        cmp_minimax_agent_subtitle_lt = self.horizontal_menu_widget_layout(cmp_minimax_agent_subtitle)
        # }}

        # minimax early hits (agent 1) {{
        cmp_ehits1_lb = QLabel("Depth (agent 1)")
        cmp_ehits1_lb.setMinimumWidth(100)

        self.cmp_ehits1_sb = QSpinBox(centralWidget)
        self.cmp_ehits1_sb.setMinimumWidth(125)
        self.cmp_ehits1_sb.setRange(0, 60)
        self.cmp_ehits1_sb.setSingleStep(1)

        # layout
        cmp_ehits1_lt = self.horizontal_menu_widget_layout(cmp_ehits1_lb, self.cmp_ehits1_sb)
        # }}

        # minimax early hits (agent 2) {{
        cmp_ehits2_lb = QLabel("Depth (agent 2)")
        cmp_ehits2_lb.setMinimumWidth(100)

        self.cmp_ehits2_sb = QSpinBox(centralWidget)
        self.cmp_ehits2_sb.setMinimumWidth(125)
        self.cmp_ehits2_sb.setRange(0, 60)
        self.cmp_ehits2_sb.setSingleStep(1)

        # layout
        cmp_ehits2_lt = self.horizontal_menu_widget_layout(cmp_ehits2_lb, self.cmp_ehits2_sb)
        # }}

        # progress bar {{
        cmp_prog_lb = QLabel("Training", centralWidget)
        cmp_prog_lb.setMinimumWidth(100)

        self.cmp_prog_pb = QProgressBar()
        self.cmp_prog_pb.setMinimumWidth(125)

        cmp_prog_lt = self.horizontal_menu_widget_layout(cmp_prog_lb, self.cmp_prog_pb)
        # }}

        # results {{
        results_w_lb = QLabel("Results:", centralWidget)
        results_w_lb.setMinimumWidth(100)

        self.results_w_dsp = QLabel(str(), centralWidget)
        self.results_w_dsp.setMinimumWidth(100)

        results_b_lb = QLabel(str(), centralWidget)
        results_b_lb.setMinimumWidth(100)

        self.results_b_dsp = QLabel(str(), centralWidget)
        self.results_b_dsp.setMinimumWidth(100)

        results_t_lb = QLabel(str(), centralWidget)
        results_t_lb.setMinimumWidth(100)

        self.results_t_dsp = QLabel(str(), centralWidget)
        self.results_t_dsp.setMinimumWidth(100)

        cmp_results_lt = QVBoxLayout()
        cmp_results_lt.addLayout(self.horizontal_menu_widget_layout(results_b_lb, self.results_b_dsp))
        cmp_results_lt.addLayout(self.horizontal_menu_widget_layout(results_w_lb, self.results_w_dsp))
        cmp_results_lt.addLayout(self.horizontal_menu_widget_layout(results_t_lb, self.results_t_dsp))
        # }}

        # launch comparison button {{
        self.launch_comp_btn = QPushButton("Compare", centralWidget)
        self.launch_comp_btn.setMinimumWidth(250)

        # connect
        self.launch_comp_btn.clicked.connect(lambda: self.launch_train_compare("compare"))

        launch_comp_lt = self.horizontal_menu_widget_layout(self.launch_comp_btn)
        # }}

        # End comparison #

        self.update_comboboxes()

        # Groupboxes
        train_ml_gb = self.groupboxer("Train ML agent", train_file_lt, self.move_selec_lt, learn_rate_lt, train_eps_lt,
                                      nb_trains_lt, train_prog_lt, launch_train_lt)

        match_gb = self.groupboxer("Match", player1_lt, player2_lt, pawns_style_lt, match_eps_lt, ml_subtitle_lt,
                                   match_file1_lt, match_file2_lt, mnx_subtitle_lt, play_ehits1_lt, play_ehits2_lt,
                                   launch_match_lt)

        new_ml_gb = self.groupboxer("New ML agent", new_agent_fname_lt, nn_size_lt, learn_strat_lt, act_fun_lt,
                                    create_agent_lt)

        cmp_gb = self.groupboxer("Compare AIs", agent1_type_lt, agent2_type_lt, nb_comps_lt, cmp_eps_lt,
                                 cmp_ml_agent_subtitle_lt, agent1_file_lt, agent2_file_lt,
                                 cmp_minimax_agent_subtitle_lt, cmp_ehits1_lt, cmp_ehits2_lt, cmp_prog_lt,
                                 cmp_results_lt, launch_comp_lt)

        # finalize (layout the boxes)
        left_col = QVBoxLayout()
        left_col.addWidget(match_gb)

        middle_col = QVBoxLayout()
        middle_col.addStretch()
        middle_col.addLayout(title_layout)
        middle_col.addStretch()
        middle_col.addWidget(train_ml_gb)
        middle_col.addWidget(new_ml_gb)

        right_col = QVBoxLayout()
        right_col.addWidget(cmp_gb)

        mainmenu_layout = QHBoxLayout()
        mainmenu_layout.addLayout(left_col)
        mainmenu_layout.addLayout(middle_col)
        mainmenu_layout.addLayout(right_col)

        ownStack.setLayout(mainmenu_layout)

        # {{ end of __init__ }}

    # Utility functions #
    def fetch_parameters(self, game_mode):
        """ Read parameters from the widgets. All cases (match, train, comapre) are handled independently since
        parameters are provided by different widgets for those cases. """

        game_parameters = dict()

        if game_mode == "match":
            self.wrap.pawns_style = self.pawns_style_cb.currentText()
            game_parameters = {"mode": "match",
                               "player1": {"type": self.player1_type_cb.currentText().lower()},
                               "player2": {"type": self.player2_type_cb.currentText().lower()},
                               "nb_games": None}
            pars = None
            if game_parameters["player1"]["type"] == "ml agent":
                pars = {"network_name": self.match_file1_cb.currentText(), "eps": self.match_eps_sb.value()}
            elif game_parameters["player1"]["type"] == "minimax":
                pars = {"ehits": self.play_ehits1_sb.value(), "eps": self.match_eps_sb.value()}
            game_parameters["player1"]["pars"] = pars

            pars = None
            if game_parameters["player2"]["type"] == "ml agent":
                pars = {"network_name": self.match_file2_cb.currentText(), "eps": self.cmp_eps_sb.value()}
            elif game_parameters["player2"]["type"] == "minimax":
                pars = {"ehits": self.play_ehits2_sb.value(), "eps": self.cmp_eps_sb.value()}
            game_parameters["player2"]["pars"] = pars

        elif game_mode == "train":
            game_parameters = {"mode": "train",
                               "player1": {"type": "ml agent",
                                           "pars": {"network_name": self.train_file_cb.currentText(),
                                                    "eps": self.train_eps_sb.value(), "ls": None,
                                                    "mv_selec": self.move_selec_cb.currentText().split(" ")[0],
                                                    "lr": self.learn_rate_sb.value(), "act_f": None}},
                               "player2": None,
                               "nb_games": self.nb_trains_sb.value()}

        elif game_mode == "compare":
            game_parameters = {"mode": "compare",
                               "player1": {"type": self.agent1_type_cb.currentText().lower()},
                               "player2": {"type": self.agent2_type_cb.currentText().lower()},
                               "nb_games": self.nb_comps_sb.value()}
            pars = None
            if game_parameters["player1"]["type"] == "ml agent":
                pars = {"network_name": self.agent1_file_cb.currentText(), "eps": self.cmp_eps_sb.value()}
            elif game_parameters["player1"]["type"] == "minimax":
                pars = {"ehits": self.cmp_ehits1_sb.value(), "eps": self.cmp_eps_sb.value()}
            game_parameters["player1"]["pars"] = pars

            pars = None
            if game_parameters["player2"]["type"] == "ml agent":
                pars = {"network_name": self.agent2_file_cb.currentText(), "eps": self.cmp_eps_sb.value()}
            elif game_parameters["player2"]["type"] == "minimax":
                pars = {"ehits": self.cmp_ehits2_sb.value(), "eps": self.cmp_eps_sb.value()}
            game_parameters["player2"]["pars"] = pars

        return game_parameters

    def toggle_buttons_activation(self):
        disabling = self.launch_match_btn.isEnabled()
        self.launch_match_btn.setDisabled(disabling)
        self.create_agent_btn.setDisabled(disabling)
        self.launch_comp_btn.setDisabled(disabling)
        self.launch_train_btn.setDisabled(disabling)

    def update_comboboxes(self):
        """ Update contents of comboboxes that may be influenced by UI """
        for cb in [self.match_file1_cb, self.match_file2_cb, self.agent1_file_cb, self.agent2_file_cb, self.train_file_cb]:
            cb.clear()
            for f in available_networks():
                cb.addItem(f)
            if cb.count():
                cb.setCurrentIndex(0)

    # Button triggered operations #

    def create_new_agent(self):
        network_name = self.new_agent_fname.text()
        if network_name in available_networks():
            self.informative_popup("Warning", "Archived ai with this filename already exists.", "dismiss")

        elif network_name == str():
            self.informative_popup("Warning", "Filename must not be empty.", "dismiss")

        else:
            save_new_network(network_name, self.learn_strat_cb.currentText(), self.act_fun_cb.currentText().lower(), 128, self.nn_size_sb.value())
            self.update_comboboxes()
        self.new_agent_fname.setText(str())

    def launch_match(self, stack, menu_index):
        self.wrap.game_parameters = self.fetch_parameters("match")
        stack.setCurrentIndex(menu_index)

    def display_results(self, results):
        """ Display results after comparison session """

        self.results_w_dsp.setText(results[0])
        self.results_b_dsp.setText(results[1])
        self.results_t_dsp.setText(results[2])

    def launch_train_compare(self, mode):
        """ Launch train or compare loop in QThread. Same function is used for both purposes since GameEngine is passed
        parameter indicating if it's dealing with training or comparison. """

        self.toggle_buttons_activation()

        # Initialization of the QThread object
        self.thread = QThread()
        self.worker = GameEngine(self, self.fetch_parameters(mode))
        self.worker.moveToThread(self.thread)

        # Connect signals and slots
        self.thread.started.connect(self.worker.run)
        self.worker.finished.connect(self.thread.quit)
        self.worker.finished.connect(self.worker.deleteLater)
        self.thread.finished.connect(self.thread.deleteLater)
        self.thread.finished.connect(self.toggle_buttons_activation)

        # Other signals & slots
        self.worker.train_progress.connect(self.train_prog_pb.setValue)
        self.worker.compare_progress.connect(self.cmp_prog_pb.setValue)
        self.worker.compare_result.connect(self.display_results)

        # Start the thread
        self.thread.start()


from django.urls import path

from . import views

urlpatterns = [
  path('', views.home, name='home'),
  path('admission/', views.admission, name='admission'),
  path('academics/cs_bsc/', views.csBSc, name='cs-bsc'),
  path('academics/se_bsc/', views.seBSc, name='se-bsc'),
  path('academics/cs_msc/', views.csMSc, name='cs-msc'),
  path('academics/se_msc/', views.seMSc, name='se-msc'),
  path('academics/courses/', views.courses, name='courses-list'),
  path('about/', views.about, name='about'),
  path('contact/', views.contact, name='contact-us'),
]


from api.models import Incident, AffectedStation, Notification, Station
from django.utils import timezone

def create_incident(affected_stations, tweet_id):
    incidents = Incident.objects.filter(status=1)
    if incidents:
        # If there is active incidents
        # Check which stations are related to active incidents
        # Update incidents
        inc_updated = []
        for station in affected_stations:
            for incident in incidents:
                if AffectedStation.objects.filter(incident=incident, affected_station=station):
                    if incident.id not in inc_updated:

                        obj = Notification(tweet_id=tweet_id,
                                           incident=incident, date=timezone.now())
                        obj.save()
                        inc_updated.append(incident.id)
                    affected_stations = affected_stations.exclude(pk=station.pk)
        # If there are stations not related to active incidents
        # Create new incident
        if len(affected_stations) > 0:
            incident = Incident(status=1)
            incident.save()
            for station in affected_stations:
                obj = AffectedStation(
                    incident=incidents[0], affected_station=station)
                obj.save()

            noti = Notification(tweet_id=tweet_id,
                                incident=incident, date=timezone.now())
            noti.save()
    else:
        # If there is no active incidents
        # Create incident
        incident = Incident(status=1)
        incident.save()

        # Create notification

        noti = Notification(tweet_id=tweet_id,
                            incident=incident, date=timezone.now())
        noti.save()

        # Add affected stations to incident
        for station in affected_stations:
            af_st = AffectedStation(
                incident=incident, affected_station=station)
            af_st.save()

def full_incident(line, tweet, type="O"):
    """
    Change the status of all stations of a line to the given type.
    """
    stations_of_line = Station.objects.filter(line=line)
    if type == "O":
        incidents = Incident.objects.filter(status=1)
        if incidents:
            for incident in incidents:
                affected_stations = AffectedStation.objects.filter(
                    incident=incident)
                affected_stations_len = len(affected_stations)
                station_count = 0
                for station in affected_stations:
                    if station in stations_of_line:
                        station_count += 1
                        station.status = "O"
                        station.save()
                if station_count == affected_stations_len:
                    # If the incident stations are all related to the line
                    incident.status = 0
                if station_count > 0:

                    notif = Notification(tweet_id=tweet,
                                         incident=incident, date=timezone.now())
                    notif.save()
                incident.updated_at = timezone.now()
                incident.save()
    else:
        for station in stations_of_line:
            station.status = "M"
            station.save()
        incident = Incident(status=1)
        incident.save()
        for station in stations_of_line:
            affected_station = AffectedStation(
                incident=incident, affected_station=station)
            affected_station.save()

        notif = Notification(tweet_id=tweet,
                             incident=incident, date=timezone.now())
        notif.save()


import copy
import sys
from typing import List, Tuple

import numpy as np

from RBM import RBM

class DNN:
    def __init__(self, network_shape: np.ndarray):
        """
        Initialize the DNN

        :param network_shape: the shape of the network starting from layer 0 to layer P.
        :type network_shape: np.ndarray
        """
        self._DNN: List[RBM] = [None] * (network_shape.size - 1)
        for i in range(network_shape.size - 1):
            self._DNN[i] = RBM(network_shape[i], network_shape[i + 1])

    def pretrain(self, X: np.ndarray, nb_iter: int, learning_rate: float, minibatch_size: int, verbose: bool = False):
        """
        Pretrain the DNN.

        :param X: Data to pretrain the DNN.
        :type X: np.ndarray
        :param nb_iter: Number of iterations of gradient descent.
        :type nb_iter: int
        :param learning_rate: Learning rate of the gradient descent.
        :type learning_rate: float
        :param minibatch_size: Size of the minibatch.
        :type minibatch_size: int
        """

        x = X.copy()
        for i, rbm in enumerate(self._DNN):
            if verbose:
                print(f"Pretraining layer {i}")
            rbm.train(x, nb_iter, minibatch_size, learning_rate, verbose=verbose)
            x = rbm.entree_sortie(x)

    def generer_image(self, nb_iter: int, nb_img: int) -> np.ndarray:
        """
        Generate image with Gibbs procedure.

        :param nb_iter: Number of iteration of Gibbs.
        :type nb_iter: int
        :param nb_img: Number of images to be generated
        :type nb_img: int
        :return: The images generated
        :rtype: np.ndarray
        """

        h = 0.5
        for rbm in self._DNN[::-1]:
            v = (np.random.rand(nb_img, rbm.q) < h) * 1
            for j in range(nb_iter):
                h = (np.random.rand(nb_img, rbm.p) < rbm.sortie_entree(v)) * 1
                v = (np.random.rand(nb_img, rbm.q) < rbm.entree_sortie(h)) * 1

        return h

    def entree_sortie_reseau(self, X: np.ndarray) -> Tuple[List, np.ndarray]:
        sorties = []
        h = X
        for rbm in self._DNN[:-1]:
            h = rbm.entree_sortie(h)
            sorties.append(h)
        probs = self._DNN[-1].calcul_softmax(h)
        return sorties, probs

    def retropropagation(self, X: np.ndarray, labels: np.ndarray, nb_iter: int, learning_rate: float,
                         minibatch_size: int, verbose: bool = False):

        def cost(true_labels, predicted_labels):
            return -np.sum(true_labels * np.log(predicted_labels)) / X.shape[0]

        N = X.shape[0]

        for epoch in range(nb_iter):
            seed = np.random.randint(0, 10000)
            X_copy = X.copy()
            labels_copy = labels.copy()
            np.random.seed(seed)
            np.random.shuffle(X_copy)
            np.random.seed(seed)
            np.random.shuffle(labels_copy)

            DNN_copy = copy.deepcopy(self._DNN)

            # Mini-batch (Should I copy the RBMs?)
            for j in range(0, N, minibatch_size):
                # Taking only the minibatch
                X_minibatch = X_copy[j: min(j + minibatch_size, N)]
                labels_minibatch = labels_copy[j: min(j + minibatch_size, N)]

                # Getting batch size
                batch_size = X_minibatch.shape[0]

                # Forward pass
                sorties, probs = self.entree_sortie_reseau(X_minibatch)
                estimated_labels = probs

                # Computing the gradient
                C = estimated_labels - labels_minibatch
                for k in range(len(DNN_copy) - 1, -1, -1):
                    # Updating the weights
                    if k == 0:
                        dw = X_minibatch.T @ C / batch_size
                    else:
                        dw = sorties[k - 1].T @ C / batch_size

                    # Updating the biaises
                    db = np.sum(C, axis=0) / batch_size

                    # Updating the weights and the biases of the DNN
                    self._DNN[k].w -= learning_rate * dw
                    self._DNN[k].b -= learning_rate * db

                    # Updating the constant derivation
                    if k == 0:
                        C = (C @ DNN_copy[k].w.T) * X_minibatch * (1 - X_minibatch)
                    else:
                        C = (C @ DNN_copy[k].w.T) * sorties[k - 1] * (1 - sorties[k - 1])

            if verbose:
                temp, probs = self.entree_sortie_reseau(X)
                sys.stdout.write(f"\rEpoch {epoch} : {cost(labels, probs)}")
                sys.stdout.flush()

    def test(self, X: np.ndarray, labels: np.ndarray) -> float:
        sorties, probs = self.entree_sortie_reseau(X)
        estimated_labels = np.argmax(probs, axis=1)
        error_rate = np.sum(estimated_labels != labels) / X.shape[0]
        return error_rate


i = [input(),input(),input()]
car = [int(i[0].split(' ')[0]),int(i[0].split(' ')[1])]
dest = [int(i[1].split(' ')[0]),int(i[1].split(' ')[1])]
batt = int(i[2])
for i in range(batt):
    if car[0] > dest[0]:
        car[0] -= 1
    elif car[0] < dest[0]:
        car[0] += 1
    elif car[1] > dest[1]:
        car[1] -= 1
    elif car[1] < dest[1]:
        car[1] += 1
    else:
        car[0] += 1
if car == dest:
    print('Y')
else:
    print('N')


# -*- coding: utf-8 -*-
import re
import sys
import time
from datetime import date, datetime

from trac.attachment import Attachment
from trac.core import TracError
from trac.ticket.api import TicketSystem
from trac.util import sorted, embedded_numbers
from trac.util.datefmt import utc, utcmax, to_timestamp

__all__ = ['Client']

def simplify_whitespace(name):
    """Strip spaces and remove duplicate spaces within names"""
    return ' '.join(name.split())

class Client(object):

    def __init__(self, env, name=None, db=None):
        self.env = env
        if name:
            name = simplify_whitespace(name)
        if name:
            if not db:
                db = self.env.get_read_db()
            cursor = db.cursor()
            cursor.execute("SELECT description,"
                           "default_rate, currency "
                           "FROM client "
                           "WHERE name=%s", (name,))
            row = cursor.fetchone()
            if not row:
                raise TracError('Client %s does not exist.' % name)
            self.name = self._old_name = name
            self.description = row[0] or ''
            self.default_rate = row[1] or ''
            self.currency = row[2] or ''
        else:
            self.name = self._old_name = None
            self.description = None
            self.default_rate = ''
            self.currency = ''

    exists = property(fget=lambda self: self._old_name is not None)

    def delete(self, db=None):
        assert self.exists, 'Cannot deleting non-existent client'

        @self.env.with_transaction()
        def do_delete(db):
            cursor = db.cursor()
            self.env.log.info('Deleting client %s' % self.name)
            cursor.execute("DELETE FROM client WHERE name=%s", (self.name,))

            self.name = self._old_name = None

    def insert(self, db=None):
        assert not self.exists, 'Cannot insert existing client'
        self.name = simplify_whitespace(self.name)
        assert self.name, 'Cannot create client with no name'

        @self.env.with_transaction()
        def do_insert(db):
            cursor = db.cursor()
            self.env.log.debug("Creating new client '%s'" % self.name)
            cursor.execute("INSERT INTO client (name, description,"
                          " default_rate, currency) "
                          "VALUES (%s,%s, %s,%s)",
                          (self.name, self.description,
                           (self.default_rate or None), self.currency))

    def update(self, db=None):
        assert self.exists, 'Cannot update non-existent client'
        self.name = simplify_whitespace(self.name)
        assert self.name, 'Cannot update client with no name'

        @self.env.with_transaction()
        def do_update(db):
            cursor = db.cursor()
            self.env.log.info('Updating client "%s"' % self.name)
            cursor.execute("UPDATE client SET name=%s,description=%s,"
                          " default_rate=%s, currency=%s "
                          "WHERE name=%s",
                          (self.name, self.description,
                            (self.default_rate or None), self.currency,
                            self._old_name))
            if self.name != self._old_name:
                # Update tickets
                cursor.execute("UPDATE ticket_custom SET value=%s "
                              "WHERE name=%s AND value=%s",
                              (self.name, 'client', self._old_name))
                # Update event options
                cursor.execute("UPDATE client_event_summary_options SET client=%s "
                              "WHERE client=%s",
                              (self.name, self._old_name))
                cursor.execute("UPDATE client_event_action_options SET client=%s "
                              "WHERE client=%s",
                              (self.name, self._old_name))
                self._old_name = self.name

    def select(cls, env, db=None):
        if not db:
            db = env.get_read_db()
        cursor = db.cursor()
        cursor.execute("SELECT name,description,"
                       " default_rate, currency "
                       "FROM client "
                       "ORDER BY name")
        for name, description, default_rate, currency in cursor:
            client = cls(env)
            client.name = client._old_name = name
            client.description = description or ''
            client.default_rate = default_rate or ''
            client.currency = currency or ''
            yield client
    select = classmethod(select)


"""configuration file for transMap batch run"""

import os
from transMap.transMapConf import TransMapConf
from transMap.genomeData import ChainType

def getConfig(configPyFile, dataRootDir=None, srcHgDb=None, destHgDb=None,
              annotationType=None, chainType=None):
    version = "V1"

    # increment to prevent reusing batch directories on restart
    batchGen = 2
    dataRootDir = "/hive/users/markd/nanopore/projs/t2t-centromere/T2T_cenSat/cenSat1/transMap/work"
    hubRootDir = "/hive/users/markd/nanopore/projs/t2t-centromere/T2T_cenSat/hub/cenSat1"
    conf = TransMapConf(configPyFile,
                        dataRootDir=dataRootDir,
                        srcHgDb=srcHgDb,
                        destHgDb=destHgDb,
                        annotationType=annotationType,
                        chainType=chainType,
                        version=version,
                        batchGen=batchGen,
                        destTwoBitPathPat=os.path.join(hubRootDir, "cenSat1.2bit"),
                        destChromSizesPat=os.path.join(hubRootDir, "cenSat1.sizes"))
    return conf


import multiprocessing
from config import server_conf

bind = f'{server_conf.HOST}:{str(server_conf.WSGI_PORT)}'

timeout = 30

worker_class = 'gevent'

workers = multiprocessing.cpu_count() * 2 + 1

threads = 3

worker_connections = 1000


import numpy as np
import matplotlib.pyplot as plt
from testCases import *
import sklearn
import sklearn.datasets
from sklearn.linear_model import LogisticRegressionCV
from planar_utils import plot_decision_boundary, sigmoid, load_planar_dataset, load_extra_datasets
from sklearn.metrics import accuracy_score

np.random.seed(1)
X, Y = load_planar_dataset()

# plt.scatter(X[0, :], X[1, :], c=Y.ravel(), s=40, cmap=plt.cm.Spectral)
# plt.show()

### START CODE HERE ### (≈ 3 lines of code)
shape_X = X.shape
shape_Y = Y.shape
m = shape_X[1]  # training set size
### END CODE HERE ###

print('The shape of X is: ' + str(shape_X))
print('The shape of Y is: ' + str(shape_Y))
print('I have m = %d training examples!' % (m))

clf = LogisticRegressionCV()
clf.fit(X.T, Y.T)
# Plot the decision boundary for logistic regression
# plt.title("Logistic Regression")
# plot_decision_boundary(lambda x: clf.predict(x), X, Y)

# Print accuracy
LR_predictions = clf.predict(X.T)
print()
print('Accuracy of logistic regression: %d ' % float(
    (np.dot(Y, LR_predictions) + np.dot(1 - Y, 1 - LR_predictions)) / float(Y.size) * 100) +
      '% ' + "(percentage of correctly labelled datapoints)")

# GRADED FUNCTION: layer_sizes

def layer_sizes(X, Y):
    """
    Arguments:
    X -- input dataset of shape (input size, number of examples)
    Y -- labels of shape (output size, number of examples)

    Returns:
    n_x -- the size of the input layer
    n_h -- the size of the hidden layer
    n_y -- the size of the output layer
    """
    ### START CODE HERE ### (≈ 3 lines of code)
    n_x = X.shape[0]  # size of input layer
    n_h = 4
    n_y = Y.shape[0]  # size of output layer
    ### END CODE HERE ###
    return (n_x, n_h, n_y)

X_assess, Y_assess = layer_sizes_test_case()
(n_x, n_h, n_y) = layer_sizes(X_assess, Y_assess)
print()
print("The size of the input layer is: n_x = " + str(n_x))
print("The size of the hidden layer is: n_h = " + str(n_h))
print("The size of the output layer is: n_y = " + str(n_y))

# GRADED FUNCTION: initialize_parameters

def initialize_parameters(n_x, n_h, n_y):
    """
    Argument:
    n_x -- size of the input layer
    n_h -- size of the hidden layer
    n_y -- size of the output layer

    Returns:
    params -- python dictionary containing your parameters:
                    W1 -- weight matrix of shape (n_h, n_x)
                    b1 -- bias vector of shape (n_h, 1)
                    W2 -- weight matrix of shape (n_y, n_h)
                    b2 -- bias vector of shape (n_y, 1)
    """

    np.random.seed(2)  # we set up a seed so that your output matches ours although the initialization is random.

    ### START CODE HERE ### (≈ 4 lines of code)
    W1 = np.random.randn(n_h, n_x) * 0.01
    b1 = np.zeros((n_h, 1))
    W2 = np.random.randn(n_y, n_h) * 0.01
    b2 = np.zeros((n_y, 1))
    ### END CODE HERE ###

    assert (W1.shape == (n_h, n_x))
    assert (b1.shape == (n_h, 1))
    assert (W2.shape == (n_y, n_h))
    assert (b2.shape == (n_y, 1))

    parameters = {"W1": W1,
                  "b1": b1,
                  "W2": W2,
                  "b2": b2}

    return parameters

n_x, n_h, n_y = initialize_parameters_test_case()

parameters = initialize_parameters(n_x, n_h, n_y)
print()
print("W1 = " + str(parameters["W1"]))
print("b1 = " + str(parameters["b1"]))
print("W2 = " + str(parameters["W2"]))
print("b2 = " + str(parameters["b2"]))

# GRADED FUNCTION: forward_propagation

def forward_propagation(X, parameters):
    """
    Argument:
    X -- input data of size (n_x, m)
    parameters -- python dictionary containing your parameters (output of initialization function)

    Returns:
    A2 -- The sigmoid output of the second activation
    cache -- a dictionary containing "Z1", "A1", "Z2" and "A2"
    """
    # Retrieve each parameter from the dictionary "parameters"
    ### START CODE HERE ### (≈ 4 lines of code)
    W1 = parameters["W1"]
    b1 = parameters["b1"]
    W2 = parameters["W2"]
    b2 = parameters["b2"]
    ### END CODE HERE ###

    # Implement Forward Propagation to calculate A2 (probabilities)
    ### START CODE HERE ### (≈ 4 lines of code)
    Z1 = np.dot(W1, X) + b1
    A1 = np.tanh(Z1)
    Z2 = np.dot(W2, A1) + b2
    A2 = sigmoid(Z2)
    ### END CODE HERE ###

    assert (A2.shape == (1, X.shape[1]))

    cache = {"Z1": Z1,
             "A1": A1,
             "Z2": Z2,
             "A2": A2}

    return A2, cache

X_assess, parameters = forward_propagation_test_case()

A2, cache = forward_propagation(X_assess, parameters)

# Note: we use the mean here just to make sure that your output matches ours.
print()
print(np.mean(cache['Z1']), np.mean(cache['A1']), np.mean(cache['Z2']), np.mean(cache['A2']))

# GRADED FUNCTION: compute_cost

def compute_cost(A2, Y, parameters):
    """
    Computes the cross-entropy cost given in equation (13)

    Arguments:
    A2 -- The sigmoid output of the second activation, of shape (1, number of examples)
    Y -- "true" labels vector of shape (1, number of examples)
    parameters -- python dictionary containing your parameters W1, b1, W2 and b2

    Returns:
    cost -- cross-entropy cost given equation (13)
    """

    m = Y.shape[1]  # number of example

    # Compute the cross-entropy cost
    ### START CODE HERE ### (≈ 2 lines of code)
    logprobs = -1 / m * np.nan_to_num(np.multiply(Y, np.log(A2)) + np.multiply(1 - Y, np.log(1 - A2)))
    cost = np.sum(logprobs)
    ### END CODE HERE ###

    cost = np.squeeze(cost)  # makes sure cost is the dimension we expect.
    # E.g., turns [[17]] into 17
    assert (isinstance(cost, float))

    return cost

A2, Y_assess, parameters = compute_cost_test_case()

print()
print("cost = " + str(compute_cost(A2, Y_assess, parameters)))

# GRADED FUNCTION: backward_propagation

def backward_propagation(parameters, cache, X, Y):
    """
    Implement the backward propagation using the instructions above.

    Arguments:
    parameters -- python dictionary containing our parameters
    cache -- a dictionary containing "Z1", "A1", "Z2" and "A2".
    X -- input data of shape (2, number of examples)
    Y -- "true" labels vector of shape (1, number of examples)

    Returns:
    grads -- python dictionary containing your gradients with respect to different parameters
    """
    m = X.shape[1]

    # First, retrieve W1 and W2 from the dictionary "parameters".
    ### START CODE HERE ### (≈ 2 lines of code)
    W1 = parameters["W1"]
    W2 = parameters["W2"]
    ### END CODE HERE ###

    # Retrieve also A1 and A2 from dictionary "cache".
    ### START CODE HERE ### (≈ 2 lines of code)
    A1 = cache["A1"]
    A2 = cache["A2"]
    ### END CODE HERE ###

    # Backward propagation: calculate dW1, db1, dW2, db2.
    ### START CODE HERE ### (≈ 6 lines of code, corresponding to 6 equations on slide above)
    dZ2 = A2 - Y
    dW2 = np.dot(dZ2, A1.T) / m
    db2 = 1 / m * np.sum(dZ2, axis=1, keepdims=True)
    dZ1 = np.multiply(np.dot(W2.T, dZ2), 1 - np.power(A1, 2))
    dW1 = 1 / m * np.dot(dZ1, X.T)
    db1 = 1 / m * np.sum(dZ1, axis=1, keepdims=True)
    ### END CODE HERE ###

    grads = {"dW1": dW1,
             "db1": db1,
             "dW2": dW2,
             "db2": db2}

    return grads

parameters, cache, X_assess, Y_assess = backward_propagation_test_case()

grads = backward_propagation(parameters, cache, X_assess, Y_assess)
print()
print("dW1 = " + str(grads["dW1"]))
print("db1 = " + str(grads["db1"]))
print("dW2 = " + str(grads["dW2"]))
print("db2 = " + str(grads["db2"]))

# GRADED FUNCTION: update_parameters

def update_parameters(parameters, grads, learning_rate=1.2):
    """
    Updates parameters using the gradient descent update rule given above

    Arguments:
    parameters -- python dictionary containing your parameters
    grads -- python dictionary containing your gradients

    Returns:
    parameters -- python dictionary containing your updated parameters
    """
    # Retrieve each parameter from the dictionary "parameters"
    ### START CODE HERE ### (≈ 4 lines of code)
    W1 = parameters["W1"]
    b1 = parameters["b1"]
    W2 = parameters["W2"]
    b2 = parameters["b2"]
    ### END CODE HERE ###

    # Retrieve each gradient from the dictionary "grads"
    ### START CODE HERE ### (≈ 4 lines of code)
    dW1 = grads["dW1"]
    db1 = grads["db1"]
    dW2 = grads["dW2"]
    db2 = grads["db2"]
    ## END CODE HERE ###

    # Update rule for each parameter
    ### START CODE HERE ### (≈ 4 lines of code)
    W1 -= learning_rate * dW1
    b1 -= learning_rate * db1
    W2 -= learning_rate * dW2
    b2 -= learning_rate * db2
    ### END CODE HERE ###

    parameters = {"W1": W1,
                  "b1": b1,
                  "W2": W2,
                  "b2": b2}

    return parameters

parameters, grads = update_parameters_test_case()
parameters = update_parameters(parameters, grads)

print()
print("W1 = " + str(parameters["W1"]))
print("b1 = " + str(parameters["b1"]))
print("W2 = " + str(parameters["W2"]))
print("b2 = " + str(parameters["b2"]))

# GRADED FUNCTION: nn_model

def nn_model(X, Y, n_h, num_iterations=10000, print_cost=False):
    """
    Arguments:
    X -- dataset of shape (2, number of examples)
    Y -- labels of shape (1, number of examples)
    n_h -- size of the hidden layer
    num_iterations -- Number of iterations in gradient descent loop
    print_cost -- if True, print the cost every 1000 iterations

    Returns:
    parameters -- parameters learnt by the model. They can then be used to predict.
    """

    np.random.seed(3)
    n_x = layer_sizes(X, Y)[0]
    n_y = layer_sizes(X, Y)[2]

    # Initialize parameters, then retrieve W1, b1, W2, b2. Inputs: "n_x, n_h, n_y". Outputs = "W1, b1, W2, b2, parameters".
    ### START CODE HERE ### (≈ 5 lines of code)
    parameters = initialize_parameters(n_x, n_h, n_y)
    W1 = parameters["W1"]
    b1 = parameters["b1"]
    W2 = parameters["W2"]
    b2 = parameters["b2"]
    ### END CODE HERE ###

    # Loop (gradient descent)

    for i in range(0, num_iterations):

        ### START CODE HERE ### (≈ 4 lines of code)
        # Forward propagation. Inputs: "X, parameters". Outputs: "A2, cache".
        A2, cache = forward_propagation(X, parameters)

        # Cost function. Inputs: "A2, Y, parameters". Outputs: "cost".
        cost = compute_cost(A2, Y, parameters)

        # Backpropagation. Inputs: "parameters, cache, X, Y". Outputs: "grads".
        grads = backward_propagation(parameters, cache, X, Y)

        # Gradient descent parameter update. Inputs: "parameters, grads". Outputs: "parameters".
        parameters = update_parameters(parameters, grads)

        ### END CODE HERE ###

        # Print the cost every 1000 iterations
        if print_cost and i % 1000 == 0:
            print("Cost after iteration %i: %f" % (i, cost))

    return parameters

X_assess, Y_assess = nn_model_test_case()

parameters = nn_model(X_assess, Y_assess, 4, num_iterations=10000, print_cost=False)

print()
print("W1 = " + str(parameters["W1"]))
print("b1 = " + str(parameters["b1"]))
print("W2 = " + str(parameters["W2"]))
print("b2 = " + str(parameters["b2"]))

# GRADED FUNCTION: predict

def predict(parameters, X):
    """
    Using the learned parameters, predicts a class for each example in X

    Arguments:
    parameters -- python dictionary containing your parameters
    X -- input data of size (n_x, m)

    Returns
    predictions -- vector of predictions of our model (red: 0 / blue: 1)
    """

    # Computes probabilities using forward propagation, and classifies to 0/1 using 0.5 as the threshold.
    ### START CODE HERE ### (≈ 2 lines of code)
    A2, cache = forward_propagation(X, parameters)
    predictions = np.where(A2 > 0.5, 1, 0)
    ### END CODE HERE ###

    return predictions

parameters, X_assess = predict_test_case()

predictions = predict(parameters, X_assess)
print()
print("predictions mean = " + str(np.mean(predictions)))

# Build a model with a n_h-dimensional hidden layer
parameters = nn_model(X, Y, n_h=4, num_iterations=10000, print_cost=True)

# Plot the decision boundary
# plt.title("Decision Boundary for hidden layer size " + str(4))
# plot_decision_boundary(lambda x: predict(parameters, x.T), X, Y)

# Print accuracy
predictions = predict(parameters, X)
print('Accuracy: %d' % float((np.dot(Y, predictions.T) + np.dot(1 - Y, 1 - predictions.T)) / float(Y.size) * 100) + "%")
print('Accuracy: %d' % float(accuracy_score(Y.ravel(), predictions.ravel())) + "%")

# This may take about 2 minutes to run

# plt.figure(figsize=(16, 32))
# hidden_layer_sizes = [1, 2, 3, 4, 5, 10, 20]
# for i, n_h in enumerate(hidden_layer_sizes):
#     plt.subplot(5, 2, i + 1)
#     plt.title('Hidden Layer of size %d' % n_h)
#     parameters = nn_model(X, Y, n_h, num_iterations=5000)
#     plot_decision_boundary(lambda x: predict(parameters, x.T), X, Y, False)
#     predictions = predict(parameters, X)
#     accuracy = float((np.dot(Y, predictions.T) + np.dot(1 - Y, 1 - predictions.T)) / float(Y.size) * 100)
#     print("Accuracy for {} hidden units: {} %".format(n_h, accuracy))
# plt.show()

# Datasets
noisy_circles, noisy_moons, blobs, gaussian_quantiles, no_structure = load_extra_datasets()

datasets = {"noisy_circles": noisy_circles,
            "noisy_moons": noisy_moons,
            "blobs": blobs,
            "gaussian_quantiles": gaussian_quantiles}

### START CODE HERE ### (choose your dataset)
dataset = "noisy_moons"
### END CODE HERE ###

X, Y = datasets[dataset]
X, Y = X.T, Y.reshape(1, Y.shape[0])

# make blobs binary
if dataset == "blobs":
    Y = Y % 2

# Visualize the data
# plt.scatter(X[0, :], X[1, :], c=Y.ravel(), s=40, cmap=plt.cm.Spectral)

plt.figure(figsize=(16, 16))
hidden_layer_sizes = [1, 2, 3, 4]
for i, n_h in enumerate(hidden_layer_sizes):
    plt.subplot(5, 2, i + 1)
    parameters = nn_model(X, Y, n_h, num_iterations=5000)
    plot_decision_boundary(lambda x: predict(parameters, x.T), X, Y, False)
    predictions = predict(parameters, X)
    accuracy = float((np.dot(Y, predictions.T) + np.dot(1 - Y, 1 - predictions.T)) / float(Y.size) * 100)
    print("Accuracy for {} hidden units: {} %".format(n_h, accuracy))
    plt.xlabel("Accuracy: {} Hidden Layer of size {}".format(accuracy, n_h))

plt.show()