from db_client import cursor, db
from datetime import date, datetime
from random import randint, randrange
from queries.insert_queries import *
from insert_tables import insert_sample_rows
from create_tables import create_tables

from utils import delete_all_rows_from_database, list_of_tables

def select_sample_rows():  # Do I need to make a def similar to the one in select.test.py?
    cursor.execute("SELECT restaurant_name FROM RestaurantParent WHERE cuisine = 'Fast Food'")
    record = cursor.fetchall()  # cuisine was changed from Sushi to Fast Food, to match sample insertion

    for row in record:
        print("Name = ", row[0])  # Query selects restaurant names for which the cuisine is "Fast Food"

    cursor.execute("SELECT consumer_id FROM _Order")  # Projection query to find consumer_id for orders
    record = cursor.fetchall()

    for row in record:
        print("ID = ", row[0])

    cursor.execute("SELECT restaurant_name, Item.restaurant_id, item_name, price FROM Restaurant, Item WHERE "
                   "Restaurant.restaurant_id = Item.restaurant_id")  # Join query, gives restaurant and item info
    # removed restaurant_id from the SELECT, as it gave an error stating it as "ambiguous"
    record = cursor.fetchall()

    for row in record:
        print("Restaurant Name = ", row[0])
        print("Restaurant ID = ", row[1])
        print("Item Name = ", row[2])
        print("Price = ", row[3])  # Nice

    cursor.execute("SELECT COUNT(*) FROM RestaurantParent")  # Aggregate query, counts the number of restaurant brands
    record = cursor.fetchall()

    for row in record:
        print("Number of restaurant choices = ", row[0])

    cursor.execute("SELECT restaurant_id, MIN(price) FROM Item WHERE restaurant_id IN (SELECT restaurant_id FROM "
                   "Restaurant GROUP BY restaurant_name)")  # Nested aggregation with group-by, could someone check if this is appropriate?
    record = cursor.fetchall()

    for row in record:
        print("Restaurant ID = ", row[0])
        print("Minimum item price = ", row[1])

    # unable to code the "Division query part": An example of what could be done is all customers that have placed
    # an order at every restaurant, or something similar

    # cursor.execute("SELECT * FROM Order o WHERE NOT EXISTS ((SELECT r.restaurant_id FROM Restaurant r) EXCEPT (SELECT or.restaurant_id FROM Order ord WHERE ord.consumer_id = o.consumer_id))")
    # record = cursor.fetchall()
    #
    # for row in record:
    #     print("Print statements...")

if __name__ == "__main__":
    create_tables()
    insert_sample_rows()
    select_sample_rows()


#Q4. 3번 문제까지 해결하셨다면, 이제 학습을 위한 준비는 거의 끝났다고 볼 수 있습니다. 위 구현 함수들을 이용해 학습 Loop를 구현해보세요.
#위에서 구현한 모델, optimzer, loss fn 등을 이용해 학습을 구현해주세요.

for epoch in range(training_epochs):
    for i, (imgs, labels) in enumerate(train_loader):
        #input 데이터 얻음
        imgs, labels = imgs.to(device), labels.to(device)
        # MNIST 이미지 : 흑백이미지 / 채널 1개를 가짐
        #imgs는 처음에 (batch_size, 1, 28, 28)의 형태 - view함수를 통해 (28*28) 형태로 변형
        #-1은 데이터를 수정하고 복사본을 만들지 않음을 의미
        imgs = imgs.view(-1, 28 * 28)

        #input 데이터에 대한 y=wx+b 형태의 선형 변환 수행, prediction한 값 출력
        outputs = linear(imgs)
        #loss 계산
        loss = criterion(outputs, labels)

        # loss 이용해 모델 개선
        #gradient를 0으로 초기화
        optimizer.zero_grad()
        #loss function을 미분해 gradient 계산, backward 연산
        loss.backward()
        # 가중치, 편향 업데이트
        optimizer.step()

        #각 배치별로 가장 높은 가능성의 숫자 클래스를 뽑아줌
        _, argmax = torch.max(outputs, 1)
        #labels == argmax 둘이 일치하는 개수 평균의 정확도
        accuracy = (labels == argmax).float().mean()

        #100번마다 출력
        if (i+1) % 100 == 0:
            print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}, Accuracy: {:.2f}%'.format(
                epoch+1, training_epochs, i+1, len(train_loader), loss.item(), accuracy.item() * 100))


from keras.models import Sequential
from keras.layers import Dense, LSTM, Dropout
import os
import tensorflow as tf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import time
from datetime import date
from pandas_datareader import data as pdr
import yfinance as yf
yf.pdr_override()
import bs4 as bs
import requests
import random
def normalize(data):
    max_val = data.max()
    min_val = data.min()
    data=(data-min_val)/(max_val-min_val)
    return data

def create_dataset(dataset):
    dataX, dataY = [], []
    # for i in range(200, len(dataset)):
    for i in range(60, len(dataset) - 30):
        # print(i)
        # print(dataset[i-60:i,:])
        # print(dataset[i:i+30,1])
        a = dataset[i-60:i,:]
        dataX.append(a)
        a = dataset[i:i+30,1]
        dataY.append(a)
    return np.array(dataX), np.array(dataY)

# def create_dataset_with_test(dataset):
#     dataX, dataY = [], []
#     # for i in range(200, len(dataset)):
#     for i in range(60, len(dataset) - 28):
#         a = dataset[i-60:i,:]
#         dataX.append(a)
#         dataY.append([dataset[i + 7,0],dataset[i + 14,0],dataset[i + 21,0],dataset[i + 28,0]])
#     return np.array(dataX[0:int(len(dataX) * .75)]), np.array(dataY[0:int(len(dataY) * .75)]),np.array(dataX[int(len(dataX) * .75):1]),np.array(dataY[int(len(dataY) * .75):1])

os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
while (1):
    # ticker = input("Enter a ticker to predict or type 'quit' to quit: ")
    ticker = "AMD"
    if ticker == "quit":
        break
    ticker = ticker.upper()
    today = date.today()
    df = pdr.get_data_yahoo(ticker, start="1970-01-01" , end=today)

    df.columns = df.columns.str.replace(' ', '')
    data = df.iloc[:,0:5].astype('float32').values

    max_val = data.max()
    min_val = data.min()
    data=(data-min_val)/(max_val-min_val)

    # datatest = data[2000:]
    # data = data[:2000]
    # print(data)
    # print("======")
    # print(datatest)
    # index = int(data.shape[0] * 0.75)
    # print(index)
    # print(int(len*0.75))
    # datatrain = data[:index,:]
    # datatest = data[index:,:]
    # print(datatest)
    # print("========")
    # print(datatrain)
    trainX, trainY = create_dataset(data)
    # testX, testY = create_dataset(datatest)
    # print("train")
    # print(trainX)
    # print("test")
    # print(testX)
    model = Sequential()
    # model.add(LSTM(1000, return_sequences=True, input_shape=(60,5)))
    # model.add(Dense(500))
    # model.add(Dropout(0.2))
    # model.add(LSTM(1000, return_sequences=False))
    # model.add(Dropout(0.5))
    # model.add(Dense(30))
    model.add(LSTM(100, return_sequences=True, input_shape=(60,5)))
    model.add(Dropout(0.2))
    model.add(LSTM(100, return_sequences=False))
    model.add(Dropout(0.2))
    model.add(Dense(units=30))
    model.compile(loss='mse', optimizer='adam')
    t0 = time.time()
    # callback = tf.keras.callbacks.EarlyStopping(monitor='loss', patience=3, mode='min', verbose=1)
    hist = model.fit(trainX, trainY, epochs=20, batch_size=64, validation_data=[testX,testY], verbose=2)
    model.save(f'models_new/{ticker}.h5')
    print("Training time:", time.time()-t0)

    plt.plot(hist.history['loss'], label='loss')
    # plt.plot(hist.history['val_loss'], label='val_loss')
    plt.legend()
    plt.show()
    today = date.today()
    data = pdr.get_data_yahoo(ticker, start="1970-01-01" , end=today)
    data = data.iloc[:,0:5].astype('float32').values
    rand = random.randint(1000,(data.shape[0]-1000)) * -1
    print(rand)
    temp = data[rand:rand+30:,1]
    max_val = data.max()
    min_val = data.min()
    data=(data-min_val)/(max_val-min_val)

    data = data[rand-60:rand,:]
    x = []
    x.append(data)
    dataPredict = np.array(x)

    print("Predicting...")

    prediction = model.predict(dataPredict)
    prediction = prediction * (max_val - min_val) + min_val
    data = data * (max_val - min_val) + min_val

    prediction = prediction[0]

    totaldiff = 0
    for i in range(30):
        diff = prediction[i] - temp[i]
        print(f'{diff:.2f}% difference')
        totaldiff += diff
    totaldiff /= 30
    print(f'{totaldiff:.2f}% average difference')

    x = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29]
    plt.plot(x,temp, color = 'black', label = 'Stock Price')
    plt.plot(x,prediction, color = 'blue', label = 'Prediction Price')

    plt.xlabel('Time')
    plt.ylabel('Stock Price')
    plt.legend()
    plt.show()
    break


import numpy as np
import matplotlib.pyplot as plt

print('Enter n')
n = int(input())
print('Enter 0 if Left Riemann Sum')
print('Enter 1 if Midpoint Riemann Sum')
print('Enter 2 if Right Riemann Sum')
i = int(input())
f = lambda x: x ** 2
a, b = 1, 2
dx = 1 / n
x_left = np.linspace(a, b - dx, n)
x_midpoint = np.linspace(dx / 2, b - dx / 2, n)
x_right = np.linspace(dx, b, n)
left_riemann_sum = np.sum(f(x_left) * dx)
midpoint_riemann_sum = np.sum(f(x_midpoint) * dx)
right_riemann_sum = np.sum(f(x_right) * dx)

if i == 0:
    print('Left Riemann Sum:', left_riemann_sum)
if i == 1:
    print('Midpoint Riemann Sum:', midpoint_riemann_sum)
if i == 2:
    print('Right Riemann Sum:', right_riemann_sum)
# Create matplotlib
x = np.arange(1, 2, 0.05)
y = x**2
fig, ax = plt.subplots()
ax.plot(x, y, 'r')
ax.set_ylim(bottom=0)
for j in range(n):
    x = np.linspace(a, b, n + 1)
    y = f(x)
    X = np.linspace(a, b, n**2 + 1)
    Y = f(X)
    if i == 0:
        plt.plot(X, Y, 'b')
        x_left = x[:-1]  # Left endpoints
        y_left = y[:-1]
        plt.plot(x_left, y_left, 'b.', markersize=10)
        plt.bar(x_left, y_left, width=(1 / n), alpha=0.2, align='edge', edgecolor='r')
        plt.title('Left Riemann Sum, n = {}'.format(n))
    if i == 1:
        plt.plot(X, Y, 'b')
        x_mid = (x[:-1] + x[1:]) / 2  # Midpoints
        y_mid = f(x_mid)
        plt.plot(x_mid, y_mid, 'b.', markersize=10)
        plt.bar(x_mid, y_mid, width=(1 / n), alpha=0.2, edgecolor='r')
        plt.title('Midpoint Riemann Sum, n = {}'.format(n))
    if i == 2:
        plt.plot(X, Y, 'b')
        x_right = x[1:]  # Left endpoints
        y_right = y[1:]
        plt.plot(x_right, y_right, 'b.', markersize=10)
        plt.bar(x_right, y_right, width=(-1 / n), alpha=0.2, align='edge', edgecolor='r')
        plt.title('Right Riemann Sum, n = {}'.format(n))

plt.show()


import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import datetime
df = pd.read_csv("D-GROWTH.csv")
df['Date'] = pd.to_datetime(df["Date"])
all_years = df['Date'].dt.year.unique()
temp = {'Date': [], 'Growth': []}
for i in all_years:
    for j in range(12, 0, -1):
        data = df[(df['Date'].dt.year == i) & (df['Date'].dt.month == j)]
        try:
            last_date = max(data['Date'].dt.date)
            temp['Date'].append(last_date)
            temp['Growth'].append(data[data['Date'] == last_date].iloc[0, 2])
        except:
            continue
temp = pd.DataFrame(temp)
month_data = {'Date': [], 'Month Growth': []}
for i in range(len(temp)):
    month_data['Date'].append(temp['Date'][i])
    try:
        x = ((temp['Growth'][i+1] - temp['Growth'][i]) / temp['Growth'][i+1]) * 100
        month_data['Month Growth'].append(x)
    except:
        month_data['Month Growth'].append(temp['Growth'][i])
month_data = pd.DataFrame(month_data)
month_data.to_csv("M-Growth.csv")
sns.lineplot(x='Date', y='Month Growth', data=month_data, markers=True, dashes=False)
plt.show()


# ExperimentDetails is for collecting all the experiment-related details
class ExperimentDetails(object):
	def __init__(self, ExperimentName=None, EngineName=None, ChaosDuration=None, ChaosInterval=None, RampTime=None, Force=None, ChaosLib=None,
		ChaosServiceAccount=None, AppNS=None, AppLabel=None, AppKind=None, InstanceID=None, ChaosNamespace=None, ChaosPodName=None, Timeout=None,
		Delay=None, TargetPods=None, PodsAffectedPerc=None, Sequence=None, LIBImagePullPolicy=None, TargetContainer=None, UID=None):
		self.ExperimentName      = ExperimentName
		self.EngineName          = EngineName
		self.ChaosDuration       = ChaosDuration
		self.ChaosInterval       = ChaosInterval
		self.RampTime            = RampTime
		self.Force               = Force
		self.ChaosLib            = ChaosLib
		self.ChaosServiceAccount = ChaosServiceAccount
		self.AppNS               = AppNS
		self.AppLabel            = AppLabel
		self.AppKind             = AppKind
		self.InstanceID          = InstanceID
		self.ChaosUID            = UID
		self.ChaosNamespace      = ChaosNamespace
		self.ChaosPodName        = ChaosPodName
		self.Timeout             = Timeout
		self.Delay               = Delay
		self.TargetPods          = TargetPods
		self.PodsAffectedPerc    = PodsAffectedPerc
		self.Sequence            = Sequence
		self.LIBImagePullPolicy  = LIBImagePullPolicy
		self.TargetContainer     = TargetContainer


from math import floor
import os
import sys

os.system("cls")

with open('day15.txt',"r") as f:
    inp1 = f.read().split("\n")
inp1 = [[int(xx) for xx in x] for x in inp1]

orows = len(inp1)
ocols = len(inp1[0])
rows = orows*5
cols = ocols*5

inp =  [[0 for column in range(cols)]
                  for row in range(rows)]

for i in range(rows):
  for j in range(cols):
    num = (inp1[i%orows][j%ocols]  + (floor(i/orows) + floor(j/ocols)))
    inp[i][j] = num if num < 10 else (num%10)+1

# for i in range(rows):
#   line = ""
#   for j in range(cols):
#     line += str(inp[i][j]) + " "
#   print(line)

class Graph():

  def __init__(self, vertices):
    self.V = vertices
    self.graph = [[] for row in range(vertices)]

    # A utility function to find the vertex with
    # minimum distance value, from the set of vertices
    # not yet included in shortest path tree
  def minDistance(self, dist, sptSet):

    # Initialize minimum distance for next node
    min = sys.maxsize

    # Search the nearest vertex not in the
    # shortest path tree
    for u in dist.keys():
      if dist[u] < min:
        min = dist[u]
        min_index = u

    return min_index

    # Function that implements Dijkstra's single source
    # shortest path algorithm for a graph represented
    # using adjacency matrix representation
  def dijkstra(self, src):

    # dist = [sys.maxsize] * self.V
    dist = {}
    dist1 = {}
    dist[src] = 0
    dist1[src] = 0
    sptSet = [False] * self.V

    for cout in range(self.V):

      # Pick the minimum distance vertex from
      # the set of vertices not yet processed.
      # x is always equal to src in first iteration
      x = self.minDistance(dist1, sptSet)

      # Put the minimum distance vertex in the
      # shortest path tree
      sptSet[x] = True
      del dist1[x]
      if  x == rows*cols-1:
        print(dist[x])
        break

      # Update dist value of the adjacent vertices
      # of the picked vertex only if the current
      # distance is greater than new distance and
      # the vertex in not in the shortest path tree
      neighbors = graph[x]

      for n in neighbors:
        y = n[0]
        val = n[1]
        if sptSet[y] == False and (dist.get(y) == None or dist[y] > dist[x] + val):
          dist1[y] = dist[y] = dist[x] + val

    # self.printSolution(dist)

def get_flat_index(row, col):
  return row*cols + col

graph = [[] for row in range(rows*cols)]

def populate_graph(src, x, y):
  up = inp[x][y]
  dest = get_flat_index(x,y)
  graph[src].append([dest, up])

def run():
  for i in range(rows):
    for j in range(cols):
      src = get_flat_index(i,j)
      if i>0:
        populate_graph(src, i-1, j)
      if j>0:
        populate_graph(src, i, j-1)
      if i<rows-1:
        populate_graph(src, i+1, j)
      if j<cols-1:
        populate_graph(src, i, j+1)

  print("generated graph", rows*cols)
  g = Graph(rows*cols)
  g.graph = graph
  g.dijkstra(0)

run()


#Saumit Madireddy

#I pledge my honor that I have abided by the Stevens Honor System.

def main():
    is_correct = True
    months_with_31_days = [1, 3, 5, 7, 8, 10, 12]
    date = input("Enter a date in the month/day/year format (xx/xx/xxxx): ")

    date_list = date.split("/")
    if len(date_list) !=3:
        is_correct = False
    else:
        month, day, year = date_list

        try:
            month = int(month)
            day = int(day)
            year = int(year)

            if month > 12 or month < 1 or day > 31 or day < 1 or year < 1:
                is_correct = False
            elif month not in months_with_31_days and day == 31:
                is_correct = False
        except:
            is_correct = False

    if is_correct:
        print("The date", date, "is valid")
    else:
        print("The date", date, "is not valid.")

main()


from django.shortcuts import render, get_object_or_404, get_list_or_404
from django.http import HttpResponseRedirect, Http404
from django.urls import reverse
from django.contrib import messages

# import model from another module

# import Users model from authentication module
from authentication.models import Users, AccountType

# import model
from .models import Schools

# Create your views here.
def index(request, id):

    # fetch all the schools
    instance = get_object_or_404(Schools, id=id)

    context = {'instance':instance}
    return render(request, 'index.html', context)

# School registration page
def register(request):
    if request.method == 'POST':
        name = request.POST.get('name' or None)
        address = request.POST.get('address' or None)
        state = request.POST.get('state' or None)
        lga = request.POST.get('lga' or None)
        logo = request.FILES.get('logo' or None)
        school_type = request.POST.get('school_type' or None)

        school = Schools()
        school.name = name
        school.address = address
        school.state = state
        school.lga = lga
        school.logo = logo
        school.school_type = school_type
        school.save()

        if school is not None:
            return HttpResponseRedirect(reverse('administrator:register'))
    else:
        return render(request, 'register.html')

# Show all School
def all_school(request):
    schools = Schools.objects.all()
    context = {'schools': schools, 'instance':instance}
    return render(request, 'all_school.html', context)

# view a specific school
def view_school(request, id):

    # fetch all the schools
    instance = get_object_or_404(Schools, id=id)

    # fetch all the school admin
    # school_admin = get_object_or_404(Users(), id=id)

    # Register School admin
    if request.method == 'POST':
        first_name = request.POST.get('first_name')
        last_name = request.POST.get('last_name')
        middlename = request.POST.get('middlename')
        email = request.POST.get('email')
        account_type = AccountType.objects.get(id=2)
        gender = request.POST.get('gender')
        school_id = id

        s_admin = Users()
        s_admin.first_name = first_name
        s_admin.last_name = last_name
        s_admin.middlename = middlename
        s_admin.email = email
        s_admin.account_type = account_type
        s_admin.gender = gender
        s_admin.school_id = school_id
        s_admin.save()

        if s_admin is not None:
            return HttpResponseRedirect(reverse('administrator:view_school', args=[id]))
    else:
        return render(request, 'view_school.html')

    context = {'instance':instance}
    return render(request, 'view_school.html', context)


import cv2 as cv
import numpy as np

'''
Tranformação geometrica:
Rotação:
>getRotationMatrix2D(center, angle, scale) -> Obtem uma matriz de rotação.
==>center -> Indica o centro da imagem (X, Y)
==>angle -> Define o ângulo desejado para rotacionar [0, 360]
==>scale -> Escala para imagem
>warpAffine(src, matriz, dsize) -> Gera a imagem rotacionada.
==>src -> Mesma coisa que o .this
==>matriz -> matriz de rotação.
==>dsize -> Tamanho da imagem rotacionada.
'''

img = cv.imread('1.jpg')
linhas, colunas = img.shape[:2]

matriz = cv.getRotationMatrix2D((colunas / 2, linhas / 2), 90, 1)
imgRot = cv.warpAffine(img, matriz, (colunas, linhas))
print(img.shape)

cv.imshow('Rot', imgRot)
cv.waitKey(0)
cv.destroyAllWindows()

matriz = np.float32([[1, 0, 32], [0, 1, 30]])
imgDesloc = cv.warpAffine(img, matriz, (colunas, linhas))

cv.imshow('Desloc', imgDesloc)
cv.waitKey(0)
cv.destroyAllWindows()

'''
*Ajuste Escala
resize(src, dst, fx, fy, interpolation)
'''

# img = cv.imread('5.jpg')
img = cv.resize(cv.imread('5.jpg'), None, None, .5, .5, cv.INTER_NEAREST)

cv.imshow('Resultado', img)
cv.waitKey(0)
cv.destroyAllWindows()

'''
*Ajuste perpectiva
warpPerspective()
getPerpectiveTransform()
'''


from app.settings import PLAYER_1, PLAYER_2

def verify_start(data):
    player_1_moves = "".join(data['player1']["moviminetos"])
    player_2_moves = "".join(data['player2']["moviminetos"])
    player_1_golpe = "".join(data['player1']["golpes"])
    player_2_golpe = "".join(data['player2']["golpes"])

    player_1_total = player_1_moves + player_1_golpe
    player_2_total = player_2_moves + player_2_golpe

    if len(player_1_total) > len(player_2_total):
        return PLAYER_2

    elif len(player_1_total) == len(player_2_total):

        if len(player_1_moves) > len(player_2_moves):
            return PLAYER_2

        if len(player_1_moves) == len(player_2_moves):

            if len(player_1_golpe)> len(player_2_golpe):
                return PLAYER_2

            else:
                return PLAYER_1
        else:
            return PLAYER_1
    else :
        return PLAYER_1


import logging
import zmq

from cifsdk.actor.manager import Manager as _Manager
from cifsdk.actor import Actor as Enricher
from .constants import TRACE, ENRICHER_ADDR, ENRICHER_SINK_ADDR, \
    LOGLEVEL

logger = logging.getLogger(__name__)
logger.setLevel(LOGLEVEL)

if TRACE:
    logger.setLevel(logging.DEBUG)

class Manager(_Manager):

    def __init__(self, context, threads=0):

        if threads > 0:
            _Manager.__init__(self, Enricher, threads)

        self.socket = context.socket(zmq.PUSH)
        self.socket.bind(ENRICHER_ADDR)
        self.socket.SNDTIMEO = 5000
        self.socket.RCVTIMEO = 5000
        self.socket.setsockopt(zmq.LINGER, 3)

        self.sink_s = context.socket(zmq.PULL)
        self.sink_s.bind(ENRICHER_SINK_ADDR)


import logging
import os

from wafl.connectors.bridges.llm_task_extractor_bridge import LLMTaskExtractorBridge
from wafl.extractors.dataclasses import Answer

_path = os.path.dirname(__file__)
_logger = logging.getLogger(__file__)

class TaskExtractor:
    def __init__(self, config, interface, logger=None):
        self._interface = interface
        self._connector = LLMTaskExtractorBridge(config)
        self._max_num_past_utterances = 3
        self._to_ignore = ["yes", "no", "ok", "okay", "sure", "nope", "yep", "you"]

    async def extract(self, query: str) -> Answer:
        print(__name__)
        dialogue = "\n".join(
            self._interface.get_utterances_list()[-self._max_num_past_utterances :]
        )
        if not dialogue:
            dialogue = query

        if self._ignore_utterances(dialogue):
            return Answer.create_neutral()

        prediction = await self._connector.get_answer(
            "",
            dialogue,
            query,
        )
        return Answer(text=prediction.strip())

    def _ignore_utterances(self, dialogue: str) -> bool:
        utterance = dialogue.split("\n")[-1].split("user:")[-1].strip()
        if utterance.lower() in self._to_ignore:
            return True

        return False


"""
This is meant to be executed using mpirun.  It is called as a subprocess
to run an MPI test.

"""

if __name__ == '__main__':
    import sys
    import os
    import traceback

    from mpi4py import MPI
    from testflo.test import Test
    from testflo.cover import setup_coverage, save_coverage
    from testflo.qman import get_client_queue
    from testflo.options import get_options

    exitcode = 0  # use 0 for exit code of all ranks != 0 because otherwise,
                  # MPI will terminate other processes

    queue = get_client_queue()
    os.environ['TESTFLO_QUEUE'] = ''

    setup_coverage(get_options())

    try:
        try:
            comm = MPI.COMM_WORLD
            test = Test(sys.argv[1])
            test.nocapture = True # so we don't lose stdout
            test.run()
        except:
            print(traceback.format_exc())
            test.status = 'FAIL'
            test.err_msg = traceback.format_exc()

        # collect results
        results = comm.gather(test, root=0)
        if comm.rank == 0:
            total_mem_usage = sum(r.memory_usage for r in results)
            test.memory_usage = total_mem_usage

            # check for errors and record error message
            for r in results:
                if test.status != 'FAIL' and r.status in ('SKIP', 'FAIL'):
                    test.err_msg = r.err_msg
                    test.status = r.status
                    if r.status == 'FAIL':
                        break

        save_coverage()

    except Exception:
        test.err_msg = traceback.format_exc()
        test.status = 'FAIL'

    finally:
        sys.stdout.flush()
        sys.stderr.flush()

        if comm.rank == 0:
            queue.put(test)


from random import choice
# Suit      Element Attribute           Description
# ====      ======  ========            ==========
# WANDS     Fire    Physical            incarnation of physical strength and resilience
# SWORDS    Air     Mental              mental aspects of life
# CUPS      Water   Emotional/Creative  ability to create and captivate in story
# PENTACLES Earth   Social              mastery of language and discourse
# # # # #
# PENTACLES also known as COINS
basic_arcana = {
        "w": ['1','2','3','4','5','6','7','8','9','10','p','n','q','k'],
        "c": ['1','2','3','4','5','6','7','8','9','10','p','n','q','k'],
        "s": ['1','2','3','4','5','6','7','8','9','10','p','n','q','k'],
        "p": ['1','2','3','4','5','6','7','8','9','10','p','n','q','k']
        }

major_arcana = [
        'fool', 'emperor', 'strength', 'hanged man', 'tower', 'judgement',
        'magican', 'hierophant', 'hermit', 'death', 'star', 'world',
        'high priestess', 'lover', "wheel of fortune", 'temperance', 'moon',
        'empress', 'chariot', 'justice', 'devil', 'sun'
        ]

suits = list(basic_arcana.keys())

full_basic = basic_arcana.copy()
full_major = major_arcana[:]

#########################################
# This draw a card from the minor arcana
# it first checks to see if you specified a suit, if not, it is randomized
# it then check to see if you specified a card, if not, same deal
# I then check to see if the suit you called for has any cards,
# then checks if the card is in the list
# is all those pass, we pop out the card you called and give it to you
#########################################
def draw_minor_card(suit="r", card="r"):
    if suit=='r':
        suit=choice(suits)
        if basic_arcana == []:
            suits.remove(suit)
            suit=choice(suits)
    if suit not in suits:
        return "na"
    if card=='r':
        card=choice(basic_arcana[suit])
    if basic_arcana[suit] == []:
        return "na"
    if card not in basic_arcana[suit]:
        return "na"
    s = basic_arcana[suit]
    card = basic_arcana[suit].pop(s.index(card))
    return suit+card

#########################################
# This draws out a major arcana for you
# first checking if you asked for a specific card, if not, then get a random one
# it checks to see if the card you asked for is in the list
# if it is, it gives it to you
#########################################
def draw_major_card(card="random"):
    if card=="random":
        card=choice(major_arcana)
    if card not in major_arcana:
        return "na"
    s = major_arcana
    major_arcana.remove(card)
    return card

#########################################
# it just puts a card into the deck
# we are sorting by suit, so that is why
# we ask if the suit is in the list
#########################################
def insert_minor_card(suit, card):
    if suit not in list(basic_arcana.keys()):
        return "na"
    basic_arcana[suit].append(card)
    return 0

#########################################
# I might regret this
# this allows us to add a card to the major arcana deck
# yes, no checks at all
#########################################
def insert_major_card(card):
    major_arcana.append(card)
    return 0

#########################################
# this recycles the desk, meaning resets it
# we have a variable that holds the original deck that it references
# it also refreshes the suits
#########################################
def recycle():
    major_arcana.clear()
    basic_arcana.clear()
    major_arcana = full_major.copy()
    basic_arcana = full_basic.copy()
    suits = list(basic_arcana.keys())
    return 0


import turtle
import math

r = int(input("Enter the radius:"))

turtle.hideturtle()
turtle.circle(r)
turtle.done()

c = 2 * math.pi * r
s = math.pi * r * r

print("Chu vi của hình tròn có bán kính = {r} là {c}".format(r=r, c=c))
print("Diện tích của hình tròn có bán kính = {r} là {s}".format(r=r, s=s))


if __name__ == "__main__":
    import __fixDir__

import tkinter

class MenuBar(tkinter.Frame):
    def __init__(self, clide, activebackground="#4B6EAF", textColor="white", *args, **kwargs):
        tkinter.Frame.__init__(self, clide, *args, **kwargs)

        fileButton = tkinter.Menubutton(self, text="File", bg=self["background"],
                                        activebackground=activebackground, foreground=textColor,
                                        underline=0)
        fileButton.pack(side=tkinter.LEFT)
        fileMenu = tkinter.Menu(fileButton, tearoff=0)
        fileMenu.add_command(label="New", command=clide.new)
        fileMenu.add_command(label="Save", command=clide.save)
        fileMenu.add_command(label="Open", command=clide.open)
        fileButton["menu"] = fileMenu

        editButton = tkinter.Menubutton(self, text="Edit", bg=self["background"],
                                        activebackground=activebackground, foreground=textColor)
        editButton.pack(side=tkinter.LEFT)
        editMenu = tkinter.Menu(editButton, tearoff=0)
        editMenu.add_command(label="Find", command=clide.find)
        editButton["menu"] = editMenu

        self._stopImage = tkinter.PhotoImage(file="stop.png")
        stopButton = tkinter.Button(self, image=self._stopImage, borderwidth=0, bg=self["background"],
                                    command=clide.terminal.close)
        stopButton.pack(side=tkinter.RIGHT, padx=5)

        self._debugImage = tkinter.PhotoImage(file="debug.png")
        debugButton = tkinter.Button(self, image=self._debugImage, borderwidth=0, bg=self["background"],
                                     command=clide.debugLisp)
        debugButton.pack(side=tkinter.RIGHT, padx=5)

        self._runImage = tkinter.PhotoImage(file="run.png")
        runButton = tkinter.Button(self, image=self._runImage, borderwidth=0, bg=self["background"],
                                   command=clide.runLisp)
        runButton.pack(side=tkinter.RIGHT, padx=5)

        try:
            self.master.config(menu=self)
        except AttributeError:
            self.master.tk.call(clide, "config", "-menu", self)


import gym
from random import sample

from keras import optimizers, Sequential
from keras.layers import Dense
from numpy import random, argmax
import numpy as np
from gym.spaces import Box, Discrete
import logging
from keras.utils import to_categorical

import sys
import pickle
import logging
from actor_evaluator import evaluate_actor, optimal_actions
import math

from actor_evaluator import evaluate_actor

class DQNLearnerFrozenLake:
    def __init__(self, env, epsilon=.3, N=100, sample_size=32, lr=.2, discount=.96, obs_preprocess=lambda obs: obs):
        self.preprocess = obs_preprocess
        self.env = env
        self._state = None
        self.reset()
        self.epsilon = epsilon
        self.Qnn = make_dnn_frozen(env)
        self.bad_memory = []
        self.good_memory = []
        self.temp_memory = []
        self.memory_size = N
        self.sample_size = sample_size
        self.lr = lr
        self.discount = discount
        self.silent = True

    def reset(self, good=False):
        self.state = self.preprocess(self.env.reset())
        if good:
            for trans in self.temp_memory:
                self._remember(trans, bad=False, dumping=True)
        self.temp_memory = []

    def step(self, learning):
        exploring = random.uniform() < self.epsilon
        if learning and exploring:
            action = self.env.action_space.sample()
        else:  # exploiting
            action = self.optimal_action()
        obs, reward, done, info = self.env.step(action)
        obs = self.preprocess(obs)
        prev_state = self.state
        self.state = obs
        if learning:
            transition = (prev_state, action, reward, self.state, done)
            self._remember(transition)
            self._update_q()
        if done:
            self.reset(reward > 0)
        return reward, done

    def _update_q(self):
        X, y = self._get_x_y(self.sample_size * 2, self.sample_size)
        # ®self.Qnn.optimizer.lr.assign(self.lr)
        error = self.Qnn.train_on_batch(X, y)
        outprint = ''
        for i in range(len(self.Qnn.metrics_names)):
            outprint += f'{self.Qnn.metrics_names[i]}: {error[i]} '
        logging.debug(outprint)

    def _get_x_y(self, good, bad):
        good_replay = sample(self.good_memory, min(good, len(self.good_memory)))
        bad_replay = sample(self.bad_memory, min(bad, len(self.bad_memory)))
        replay = np.stack(good_replay + bad_replay, axis=0)
        states = np.array([a[0] for a in replay])
        new_states = np.array([a[3] for a in replay])
        Q = self.Qnn.predict(states)
        Q_new = self.Qnn.predict(new_states)

        replay_size = len(replay)
        X = np.empty((replay_size, len(states[0])))
        y = np.empty((replay_size, len(Q[0])))
        for i in range(replay_size):
            state_r, action_r, reward_r, new_state_r, done_r = replay[i]

            target = Q[i]
            target[action_r] = reward_r
            # If we're done the utility is simply the reward of executing action a in
            # state s, otherwise we add the expected maximum future reward as well
            if not done_r:
                target[action_r] += self.discount * np.amax(Q_new[i])

            X[i] = state_r
            y[i] = target
        return X, y

    def silent_level(self):
        if self.silent:
            return 0
        else:
            return 2

    def optimal_action(self, state=None):
        if state is None:
            state = self.state
        actions = self.Qnn.predict(np.expand_dims(state, axis=0))[0]
        assert max(actions) != float('nan') and max(actions) != float('inf')
        return argmax(actions)

    def _remember(self, transition, bad=True, dumping=False):
        if not dumping:
            self.temp_memory.append(transition)
        if not bad:
            self.good_memory.append(transition)
        else:
            self.bad_memory.append(transition)
        while len(self.good_memory) > self.memory_size * 2:
            self.bad_memory.append(self.good_memory.pop(0))
        while len(self.bad_memory) > self.memory_size:
            self.bad_memory.pop(0)

    @property
    def state(self):
        return self._state

    @state.setter
    def state(self, value):
        if type(value) is np.ndarray:
            self._state = value
        elif type(value) is int or type(value) is np.int64:
            arr = np.ndarray((1,))
            assert len(arr) == 1
            arr[0] = value
            self._state = arr

        else:
            raise ValueError(f'got value {value} of type {type(value)}')

    def learn(self, steps, static_epsilon=None):
        i = 0
        self.reset()
        while i < steps:
            epsilon = (steps - i) / steps
            self.epsilon = epsilon
            if static_epsilon is not None:
                self.epsilon = static_epsilon
            i += 1
            self.step(True)

def preproc(obs):
    return to_categorical(obs, num_classes=16)

if __name__ == '__main__':
    import pickle

    env_name = 'FrozenLake-v0'
    env = gym.make(env_name)

    actor = DQNLearnerFrozenLake(env, obs_preprocess=preproc)
    file = open("pickles/dqn_f.pkl", 'wb+')
    pickle.dump(actor, file)

def make_dnn_frozen(env):
    adam = optimizers.Adam(learning_rate=0.0003)

    input_dim = get_dimension(env.observation_space, False)
    output_dim = get_dimension(env.action_space, True)
    input_dim = 16
    model = Sequential()
    # model.add(Embedding(1000, 64, input_length=10))
    model.add(Dense(units=10, activation='relu', input_dim=input_dim))
    model.add(Dense(units=10, activation='relu'))
    model.add(Dense(units=10, activation='relu'))
    model.add(Dense(units=output_dim, activation='linear'))

    model.compile(loss='mean_squared_error',
                  optimizer=adam,
                  metrics=['mse', 'accuracy'])
    return model

def get_dimension(space, action):
    if type(space) is Box:
        return space.shape[0]
    elif type(space) is Discrete:
        if len(space.shape) > 0:
            raise ValueError(f'unexpected val {len(space.shape)}')
        elif action:
            return space.n
        else:
            return 1
    else:
        raise ValueError(f'Unexpected type {type(space)}')


def birthday(s, d, m):
    """_summary_

    Args:
        s (_type_): Chocolate array
        d (_type_): Number to sum to
        m (_type_): Number of squares of chocolate

    Returns:
        _type_: _description_
    """
    num_days = 0

    if len(s) == 0:
        return 0

    print(s, d, m)
    for cnt, val in enumerate(s):
        squares_to_sum = s[cnt:cnt+m]
        if len(squares_to_sum) == m:
            total = sum(squares_to_sum)
            if total == d:
                print(cnt, val, num_days, squares_to_sum, total)
                num_days += 1

    return num_days

# print(birthday([1, 2, 1, 3, 2,], 3, 2))
# print(birthday([4], 4, 1))
print(birthday([1, 1, 1, 1, 1, 1,], 3, 2))


__author__ = 'Jonny'
__date__ = '2018-03-07'
__location__ = '西安'
# -*- coding: utf-8 -*-

import time
import login
import check
import requests
import station
import booking

#---------------------------- 登录账户--------------------------------------------------
def logIn(request):
    state = 1
    while(state != 0):
        print('请登录：')
        state = login.login(request)

#----------------------------检测余票-------------------------------------------------
def checkStandbyTicket(request,city_from,city_to,train_date):
    result= check.ticket_infor(request,1,city_from,city_to,train_date)
    train_no = input('请输入需订车次：')
    print('#######################################################################################')
    count = 0
    #循环检测余票
    while True:
        count += 1
        print('小J玩命查询中(%s)........'%count)
        if count % 100 == 0:
            autoCheck = input('是否继续自动查询,或切换车次：（Y/N/Z105）')
            if (autoCheck == 'N' or autoCheck == 'n' ):
                print('已终止自动查询！')
                return None
            if (autoCheck != 'N' or autoCheck != 'n' or autoCheck != 'Y' or autoCheck != 'y'):
                train_no = autoCheck
        time.sleep(2) #延时2秒，避免重复查询过快
        for tempData in result:
            if tempData[3] == train_no and tempData[11] =='Y':
                print('（注意：若无坐席类型后无余座或为‘无’均表示无剩余席位！）\n', '车次：', tempData[3], '\t始发站：', station.sel_station(tempData[6]),
                      '\t终点站：',station.sel_station(tempData[7]), '\n乘车日期：',tempData[13], '\t是否当日到达：', tempData[18],
                      '\t发车时间：', tempData[8], '\t到站时间：', tempData[9], '\t耗时：', tempData[10], '\n特等商务座：', tempData[32], '\t一等座：',
                      tempData[31], '\t二等座：',tempData[30], '\n高级软卧：', tempData[21], '\t动卧：', tempData[33], '\t硬卧：', tempData[28], '\t硬座：',
                      tempData[29], '\t无座：', tempData[36])
                break
            if tempData[3] == train_no and tempData[11] =='IS_TIME_NOT_BUY':
                print('无该车次信息或停运!')
                break
            if tempData[3] == train_no and tempData[11] =='N':
                result = check.ticket_infor(request,0,city_from,city_to,train_date)
                break

        if tempData[11] == 'Y':
            return train_no

if __name__ =='__main__':
    # 确保是同一个浏览器的操作
    request = requests.session()
    # ---------------------------输入趁车信息-------------------------------------------------
    city_from = input('请输入始发城市：')
    city_to = input('请输入终点站：')
    train_date = input('请输入乘车时间（格式：2018-01-01）：')

    # ----------------------------检测余票-------------------------------------------------
    while True:
        train_no = checkStandbyTicket(request, city_from, city_to, train_date)
        if train_no !=None:
            print('是否登录购票：')
            if input('是否登录购票：(Y/N)') == 'Y' or 'y':
                # ---------------------------- 登录账户--------------------------------------------------
                logIn(request)

                # ---------------------------- 车票下单（由于某些参数问题，暂时无法实现所有车站自动预定）--------------------------------------------------
                booking(request, city_from, city_to, train_no)
        else:
            if input('是否退出：(Y/N)') == 'Y' or 'y':
                print('谢谢使用12306爬虫订票系统！')
                break


from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.models import Group
from django.contrib.auth.models import PermissionsMixin
from django.core.exceptions import ValidationError
from django.core.validators import FileExtensionValidator
from django.core.validators import RegexValidator
from django.db import models
from django.utils.translation import gettext_lazy as _

from app_settings.models import SiteSettings
from .managers import UserManager

class User(AbstractBaseUser, PermissionsMixin):
    image_validator = FileExtensionValidator(
        allowed_extensions=['png', 'jpg', 'gif', 'jpeg'],
        message=_('Расширение не поддерживается. Разрешенные расширения .jpg .gif .png .jpeg')
    )

    def validate_image_size(fieldfile_obj):
        settings: SiteSettings = SiteSettings.objects.all().first()
        megabyte_limit = settings.avatar_image_max_size_mb
        filesize = fieldfile_obj.file.size
        if filesize > megabyte_limit * 1024 * 1024:
            raise ValidationError(
                _("Вы не можете загрузить аватар размером > {} MB").format(settings.avatar_image_max_size_mb)
            )

    email = models.EmailField(
        unique=True,
        verbose_name='E-mail'
    )
    full_name = models.CharField(
        max_length=254,
        verbose_name=_('Полное имя')
    )
    date_joined = models.DateTimeField(
        auto_now_add=True,
        verbose_name=_('Дата регистрации')
    )
    is_active = models.BooleanField(
        default=True,
        verbose_name=_('Активен')
    )
    avatar_file = models.ImageField(
        verbose_name=_('Аватар'),
        upload_to='images/user_avatars/',
        null=True,
        blank=True,
        validators=[validate_image_size, image_validator]
    )
    phoneNumberRegex = RegexValidator(
        regex=r"^\d{10}$"
    )
    phoneNumber = models.CharField(
        validators=[phoneNumberRegex],
        max_length=10,
        unique=True,
        verbose_name=_('Телефон')
    )
    is_staff = models.BooleanField(
        default=False,
        verbose_name=_('Сотрудник')
    )

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    def __str__(self):
        return f'{self.email} ({self.full_name})'

    class Meta:
        ordering = ['id']
        verbose_name = _('пользователь')
        verbose_name_plural = _('пользователи')
        db_table = 'users'

class ProxyGroups(Group):
    class Meta:
        proxy = True
        verbose_name = _('группа')
        verbose_name_plural = _('группы')


import numpy as np
import pandas as pd
import argparse

def get_tail(hmm, ncRNA, strict=False):
    expression = [int(x) for x in hmm.loc[ncRNA].score.split(',')]
    if (np.mean(expression) > 1.5) and (len(expression) > 1000):
        trim_length = trim_expression(expression, strict)
        return trim_length
    else:
        return False

def trim_expression(expression_list, strict):
    trim_length = 0
    while True:
        if strict:
            if np.mean(np.array(expression_list[-100:])) < 1.1:
                expression_list = expression_list[:-100]
                trim_length += 5000
            else:
                break
        else:

            if all(np.array(expression_list[-100:]) == 1):
                expression_list = expression_list[:-100]
                trim_length += 5000
            else:
                break
    return trim_length

def get_largest_string_non_zero(x):
    cum_sum = []
    suma= 0
    for i in x:
        if (i > 1.1):
            suma+= 1
        else:
            suma = 0
        cum_sum.append(suma)

    max_cum_sum = np.max(cum_sum)
    largest_string_non_zero = max_cum_sum/len(x)
    return largest_string_non_zero

def is_fractured(transcripto):
    x = [int(x) for x in transcripto.split(',')]
    if np.max(x) >= 3.9:
        return False
    largest_string_non_zero = get_largest_string_non_zero(x)
    mean_non_zero = np.mean(np.array(x)>1)

    if (mean_non_zero > 0.4) and (largest_string_non_zero < 0.2):
        return True
    else:
        return False

def trim_and_split(hmm, ncRNA, split_len = 50, min_len=200, min_portion = 0.2, strict=True,
                  strand = 'plus'):

    current_pos = 0
    start_list = []
    end_list = []

    transcript_length = hmm.loc[ncRNA].end - hmm.loc[ncRNA].start

    transcripto = hmm.loc[ncRNA].score

#     if strand == 'minus':
#         transcripto = transcripto[::-1]

    if strict:
        transcripto_split = transcripto.split(',')
        counts = [int(x) for x in transcripto_split]

        largest_non_zero = get_largest_string_non_zero(counts)
        percent_zero = np.mean(np.array(counts) == 1)

#         if is_fractured(counts):#np.mean(counts) > 1.5:
#             split_len = 1e100

        #if (np.max(counts)==4):
        if (np.max(counts)==4) or (np.quantile(counts, 0.5)>=2.9):
            if np.quantile(counts, 0.75) <= 3.1:
                transcripto = transcripto.replace('2,'*100, '3,'*100)
                transcripto_split = transcripto.split(',')
            transcripto_split = ['1' if x == '2' else x for x in transcripto_split]
            if np.quantile(counts, 0.75) >= 3.9:
                print('enormous!')
                transcripto_split = ['1' if x == '3' else x for x in transcripto_split]
        elif (largest_non_zero > 0.25) and (percent_zero > 0.5):
            split_len = 5

        transcripto = ','.join(transcripto_split)

    if is_fractured(transcripto):#np.mean(counts) > 1.5:
        print('fractured!')
        end = len(transcripto.split(','))*50
        return [0], [end]
    split_transcripts = transcripto.split(','.join(['1']*split_len))

    longest = max([len(x) for x in split_transcripts])

    high_scores = []
    for transcript in split_transcripts:
        try:
            sc = np.mean([int(x) for x in transcript.strip(',').split(',')])
            high_scores.append(sc)
        except:
            continue
    highest = np.max(high_scores)
    inherited = False
    print(counts)
    print(split_transcripts)
    len_to_add = 0
    for transcript in split_transcripts:
        current_longest = ((len(transcript) == longest) and (len(transcript) > 3))

        if transcript == ',':
            current_pos += (50*split_len)
        elif transcript == '':
            current_pos += (50*split_len)
        else:

            transcript_counts = transcript.strip(',').split(',')
            if (transcript[0] == ',') and (strand == 'plus'):
                current_pos += 50
#             if (strand == 'minus') and inherited:
#                 current_pos += (50*split_len)

            transcript_counts = [int(x) for x in transcript_counts]

            print(transcript_counts)

            current_highest = np.abs(np.mean(transcript_counts) - highest) <= 1e-100

            is_max_peak = transcript_counts.count(4) >= 5

            transcript_portion = (len(transcript_counts)*50)/transcript_length
            if ((len(transcript_counts) > min_len) and (transcript_portion >= min_portion)) or is_max_peak or current_highest or current_longest:

                start_pos = current_pos

                for i in range(len(transcript_counts)):

                    if transcript_counts[i] == 1:
                        print('trimmin')
                        start_pos += 50

                    else:
                        break

                if np.mean(transcript_counts) > 1.1:
                    start_list.append(start_pos)

                trim = trim_expression(transcript_counts, True)

                if trim:
                    if np.mean(transcript_counts) > 1.1:
                        end_list.append(current_pos + ((len(transcript_counts)*50)-trim))

                else:
                    if np.mean(transcript_counts) > 1.1:
                        trimmer = 50
#                         if strand == 'plus':
#                             trimmer = 50
#                         elif strand == 'minus':
#                             trimmer = 0
#                         else:
#                             raise Exception('strand error')
                        end_list.append(current_pos + (len(transcript_counts)*50) - trimmer)

            print('adding')
            if transcript[-1] == ',':
                current_pos += (50*split_len)
            current_pos += (len(transcript_counts)*50)

            if transcript[-1] == ',':
                inherited = True

#     if strand == 'minus':
#         return end_list, start_list

    return start_list, end_list

# def trim_and_split(hmm, ncRNA, split_len = 50, min_len=200, min_portion = 0.2, strict=True,
#                   strand = 'plus'):

#     current_pos = 0
#     start_list = []
#     end_list = []

#     transcript_length = hmm.loc[ncRNA].end - hmm.loc[ncRNA].start

#     transcripto = hmm.loc[ncRNA].score

#     if strand == 'minus':
#         transcripto = transcripto[::-1]

#     if strict:
#         transcripto_split = transcripto.split(',')
#         counts = [int(x) for x in transcripto_split]
#         #if (np.max(counts)==4):
#         if (np.max(counts)==4) or (np.quantile(counts, 0.75)>=3):
#             transcripto_split = ['1' if x == '2' else x for x in transcripto_split]
#         transcripto = ','.join(transcripto_split)

#     split_transcripts = transcripto.split(','.join(['1']*split_len))

#     longest = max([len(x) for x in split_transcripts])

#     high_scores = []
#     for transcript in split_transcripts:
#         try:
#             sc = np.mean([int(x) for x in transcript.strip(',').split(',')])
#             high_scores.append(sc)
#         except:
#             continue
#     highest = np.max(high_scores)
#     inherited = False
#     print(counts)
#     print(split_transcripts)
#     len_to_add = 0
#     for transcript in split_transcripts:
#         current_longest = ((len(transcript) == longest) and (len(transcript) > 3))

#         if transcript == ',':
#             current_pos += (50*split_len)
#         elif transcript == '':
#             current_pos += (50*split_len)
#         else:

#             transcript_counts = transcript.strip(',').split(',')
#             if (transcript[0] == ',') and (strand == 'plus'):
#                 current_pos += 50
#             if (strand == 'minus') and inherited:
#                 current_pos += (50*split_len)
# #             if (transcript[-1] == ',') and (strand == '-'):
# #                 current_pos += (50*split_len)

#             transcript_counts = [int(x) for x in transcript_counts]

#             print(transcript_counts)

#             current_highest = np.abs(np.mean(transcript_counts) - highest) <= 1e-100

#             transcript_portion = (len(transcript_counts)*50)/transcript_length
#             if ((len(transcript_counts) > min_len) and (transcript_portion >= min_portion)) or current_highest or current_longest:

#                 start_pos = current_pos

#                 for i in range(len(transcript_counts)):

#                     if transcript_counts[i] == 1:
#                         print('trimmin')
#                         start_pos += 50

#                     else:
#                         break

#                 if np.mean(transcript_counts) > 1.1:
#                     start_list.append(start_pos)

#                 trim = trim_expression(transcript_counts, True)

#                 if trim:
#                     if np.mean(transcript_counts) > 1.1:
#                         end_list.append(current_pos + ((len(transcript_counts)*50)-trim))

#                 else:
#                     if np.mean(transcript_counts) > 1.1:
#                         if strand == 'plus':
#                             trimmer = 50
#                         elif strand == 'minus':
#                             trimmer = 0
#                         else:
#                             raise Exception('strand error')
#                         end_list.append(current_pos + (len(transcript_counts)*50) - trimmer)

#             print('adding')
#             if transcript[-1] == ',':
#                 current_pos += (50*split_len)
#             current_pos += (len(transcript_counts)*50)

#             if transcript[-1] == ',':
#                 inherited = True

#     return start_list, end_list

parser = argparse.ArgumentParser()
parser.add_argument('--chrom', type=str, required=True)
parser.add_argument('--strand', type=str, required=True)

if __name__ == '__main__':

    args = parser.parse_args()
    chrom = args.chrom
    strand = args.strand

    hmm = pd.read_csv('NonCodingRNA/tables/{chrom}.{strand}.hmm.sorted.bed.gz'.format(
        chrom = chrom, strand = strand), sep='\t',
                 names = ['chrom', 'start', 'end', 'names', 'score', 'strand'] + [
                     'chRNA_'+str(i+1) for i in range(86)
                 ]
                     ).sort_values('start')

    hmm.index = hmm.names

    hmm['length'] = hmm.end - hmm.start
    samples = ['chRNA_'+str(i+1) for i in range(86)]
    RPKM = ((hmm[samples]/np.array(hmm[samples].sum(axis=0))).T/np.array(hmm.length)).T*1e9
    RPKM.index = hmm.names

    chrom_list = []
    start_list = []
    end_list = []
    names_list = []
    score_list = []
    strand_list = []

    ncRNAs = pd.Index([x for x in hmm.index if x[:5] == 'ncRNA'])
    ncRNAs = ncRNAs.intersection(RPKM.loc[RPKM.median(axis=1)>0.1].index)

    for n in ncRNAs:
        start = hmm.loc[n].start
        transcript_end = hmm.loc[n].end
        scores = [int(x) for x in hmm.loc[n].score.split(',')]
        transcript_ln = transcript_end - start
        ln = len(scores)
        if (RPKM.loc[n].median() >= 1) or (ln > 100):
#             if (ln < 750):
            if (ln < 650):
                srt, end = trim_and_split(hmm, n, min_len=50, strict=True, split_len=10, strand=strand)
#             elif (ln >= 750):
            else:
                srt, end = trim_and_split(hmm, n, min_len=50, strict=True, split_len=100, strand=strand)
        else:
            srt, end = [], []

        print('trimming: ' + n)
        print(srt, end)
        print('')
        if len(srt) > 0:

            for i in range(len(srt)):

#                 if strand == 'plus':

                start_ = start + srt[i]
                end_ = start + end[i]
                if strand == 'plus':
                    strand_list.append('+')
                else:
#                     start_ = start + (transcript_ln - end[i])
#                     print(end[i])
#                     end_ = start + (transcript_ln - srt[i])
#                     print(srt[i])
                    strand_list.append('-')

                chrom_list.append(chrom)
                start_list.append(start_)
                end_list.append(end_)
                names_list.append(n + '_' + str(i+1))
                score_list.append('.')
        else:
            chrom_list.append(chrom)
            start_list.append(start)
            end_list.append(transcript_end)
            names_list.append(n)
            score_list.append('.')
            if strand == 'plus':
                strand_list.append('+')
            else:
                strand_list.append('-')

#     pc_names = pd.Index([x for x in hmm.index if x[:5] != 'ncRNA'])
#     chrom_list += list(hmm.loc[pc_names].chrom)
#     start_list += list(hmm.loc[pc_names].start)
#     end_list += list(hmm.loc[pc_names].end)
#     names_list += list(hmm.loc[pc_names].names)
#     score_list += list(hmm.loc[pc_names].score)
#     strand_list += list(hmm.loc[pc_names].strand)

    df = pd.DataFrame()
    df['chrom'] = chrom_list
    df['start'] = start_list
    df['end'] = end_list
    df['names'] = names_list
    df['score'] = score_list
    df['strand'] = strand_list

    df.to_csv('NonCodingRNA/tables/{chrom}.{strand}.hmm_trimmed.bed.gz'.format(
        chrom = chrom, strand = strand), sep='\t', index=False, header=False)


class Solution:
    def transpose(self, A: List[List[int]]) -> List[List[int]]:
        row = len(A)
        col = len(A[0])
        if row == col:
            for i in range(1, len(A)):
                for j in range(i):
                    A[i][j], A[j][i] = A[j][i], A[i][j]
            return A
        else:
            B = []
            for i in range(col):
                temp = []
                for j in range(row):
                    temp.append(A[j][i])

                B.append(temp)

        return B


from collections import deque

class Solution:
    def averageOfLevels(self, root):
        queue = deque([(root, 0)])
        prev_lev = -1
        sum_lev = 0
        cnt_lev = 0
        avg_lev = []
        while queue:
            node, lev = queue.popleft()
            if lev != prev_lev:
                if cnt_lev > 0:
                    avg_lev.append(sum_lev / cnt_lev)
                sum_lev = 0
                cnt_lev = 0
                prev_lev = lev
            sum_lev += node.val
            cnt_lev += 1
            for child in ((node.left, node.right)):
                if child:
                    queue.append((child, lev+1))
        avg_lev.append(sum_lev / cnt_lev)
        return avg_lev


import sys
import math
import numpy as np

# UNCERTAINTY FUNCTIONS written by Adrian Alcolea ("https://github.com/AdrianAlcolea") for the work presented in:
"https://github.com/universidad-zaragoza/BNN_for_hyperspectral_datasets_analysis"
# =============================================================================

# H --> PREDICTIVE (ALEATORIC + EPISTEMIC)
def _predictive_entropy(prediction):

    _, num_pixels, num_classes = prediction.shape

    entropy = np.zeros(num_pixels)
    for p in range(num_pixels):
        for c in range(num_classes):
            avg = np.mean(prediction[..., p, c])
            if avg == 0.0:
                avg = sys.float_info.min
            entropy[p] += avg * math.log(avg)

    return -1 * entropy

# Ep --> ALEATORIC
def _expected_entropy(prediction):

    num_tests, num_pixels, num_classes = prediction.shape

    entropy = np.zeros(num_pixels)
    for p in range(num_pixels):
        for t in range(num_tests):
            class_sum = 0
            for c in range(num_classes):
                val = prediction[t][p][c]
                if val == 0.0:
                    val = sys.float_info.min
                class_sum += val * math.log(val)
            entropy[p] -= class_sum

    return entropy / num_tests

# ANALYSIS FUNCTIONS
# =============================================================================

def reliability_diagram(predictions, y_test, num_groups=10):

    num_classes = predictions.shape[2]

    prediction = np.mean(predictions, axis=0) # Bayesian samples average
    labels = np.zeros((len(y_test), num_classes))
    labels[np.arange(len(y_test)), y_test] = 1 # Labels to one-hot

    p_groups = np.linspace(0.0, 1.0, num_groups + 1)
    p_groups[-1] += 0.1 # For including the last value

    result = []
    for i in range(num_groups):
        group_avg = labels[(prediction >= p_groups[i]) & (prediction < p_groups[i + 1])]
        result.append(group_avg.sum() / len(group_avg))

    return result

def accuracy_vs_uncertainty(predictions, y_test, num_groups=15):

    test_H = _predictive_entropy(predictions)
    test_ok = np.mean(predictions, axis=0).argmax(axis=1) == y_test

    H_groups = np.linspace(0.0, 1.5, num_groups + 1)

    H_acc = []
    p_pixels = []
    for i in range(num_groups):
        group = test_ok[(test_H >= H_groups[i]) & (test_H < H_groups[i + 1])]
        p_pixels.append(len(group)/len(y_test))
        H_acc.append(group.sum() / len(group))

    return H_acc, p_pixels

def analyse_entropy(prediction, y_test):

    model_H = _predictive_entropy(prediction)
    model_Ep = _expected_entropy(prediction)
    model_H_Ep = model_H - model_Ep

    num_classes = prediction.shape[2]
    class_H = np.zeros(num_classes + 1)
    class_Ep = np.zeros(num_classes + 1)
    class_H_Ep = np.zeros(num_classes + 1)
    class_px = np.zeros(num_classes + 1, dtype='int')

    for px, (H, Ep, H_Ep, label) in enumerate(zip(model_H, model_Ep,
                                                  model_H_Ep, y_test)):

        label = int(label)

        class_H[label] += H
        class_Ep[label] += Ep
        class_H_Ep[label] += H_Ep
        class_px[label] += 1

        class_H[-1] += H
        class_Ep[-1] += Ep
        class_H_Ep[-1] += H_Ep
        class_px[-1] += 1

    return class_H/class_px, class_Ep/class_px, class_H_Ep/class_px

# PREDICTIONS FUNCTION
# =============================================================================

def bayesian_predictions(model, X_test, samples=100):

    # Bayesian stochastic passes
    predictions = []
    for i in range(samples):
        prediction = model.predict(X_test)
        predictions.append(prediction)

    return np.array(predictions)


from decimal import Decimal, InvalidOperation
from typing import TYPE_CHECKING, Any, List, Optional, TypedDict

from django.db import models, transaction

if TYPE_CHECKING:
    from senda.core.models.clients import ClientModel
    from senda.core.models.localities import LocalityModel, StateChoices
    from senda.core.models.offices import OfficeModel
    from senda.core.models.order_internal import InternalOrderModel
    from senda.core.models.order_supplier import SupplierOrderModel
    from senda.core.models.products import (
        ProductModel,
        ProductTypeChoices,
        ProductStockInOfficeModel,
    )
    from senda.core.models.purchases import PurchaseModel
    from senda.core.models.rental_contracts import RentalContractModel
    from senda.core.models.suppliers import SupplierModel
    from senda.core.models.employees import EmployeeModel, EmployeeOfficeModel
    from users.models import UserModel

class ClientModelManager(models.Manager["ClientModel"]):
    """
    Custom manager for the ClientModel, providing methods to create and update client instances.
    """

    def create_client(
        self,
        email: str,
        first_name: str,
        last_name: str,
        locality: "LocalityModel",
        house_number: str,
        street_name: str,
        house_unit: str,
        dni: str,
        phone_code: str,
        phone_number: str,
    ) -> "ClientModel":
        """
        Creates a new client instance with the given details. Validates to ensure the email and DNI are unique.
        """

        if self.filter(email=email).exists():
            raise ValueError("Ya existe un cliente con ese email")

        if self.filter(dni=dni).exists():
            raise ValueError("Ya existe un cliente con ese DNI")

        return self.create(
            email=email,
            first_name=first_name,
            last_name=last_name,
            locality=locality,
            house_number=house_number,
            street_name=street_name,
            house_unit=house_unit,
            dni=dni,
            phone_code=phone_code,
            phone_number=phone_number,
        )

    def update_client(
        self, client: "ClientModel", locality: "LocalityModel", **kwargs: Any
    ) -> "ClientModel":
        """
        Updates an existing client instance with the provided details.
        """

        client.locality = locality
        for field, value in kwargs.items():
            setattr(client, field, value)
        client.save()
        return client

class LocalityModelManager(models.Manager["LocalityModel"]):
    """
    Custom manager for the LocalityModel, providing methods to create and retrieve locality instances.
    """

    def create_locality(
        self, name: str, postal_code: str, state: "StateChoices"
    ) -> "LocalityModel":
        """
        Creates a new locality instance with the given details. Ensures the locality's uniqueness.
        """
        name = name.strip().lower().title()

        if self.filter(name=name, postal_code=postal_code, state=state).exists():
            raise ValueError("La localidad ya existe")

        return self.create(name=name, postal_code=postal_code, state=state)

    def get_or_create_locality(
        self, name: str, postal_code: int, state: "StateChoices"
    ) -> "LocalityModel":
        """
        Retrieves or creates a locality instance based on the provided details.
        """
        locality, _created = self.get_or_create(
            name=name, postal_code=postal_code, state=state
        )
        return locality

InternalOrderProductsDict = TypedDict(
    "InternalOrderProductsDict", {"id": str, "quantity": int}
)

class InternalOrderManager(models.Manager["InternalOrderModel"]):
    """
    Custom manager for the InternalOrderModel, handling the creation of internal orders.
    """

    @transaction.atomic
    def create_internal_order(
        self,
        office_branch: "OfficeModel",
        office_destination: "OfficeModel",
        user: "UserModel",
        products: List[InternalOrderProductsDict],
    ) -> "InternalOrderModel":
        """
        Creates a new internal order with associated products and history. This process is atomic.
        """
        from senda.core.models.order_internal import InternalOrderHistoryStatusChoices

        internal_order = self.create(
            office_branch=office_branch, office_destination=office_destination
        )
        internal_order.save()
        internal_order.history.create(
            status=InternalOrderHistoryStatusChoices.PENDING,
            internal_order=internal_order,
            user=user,
        )

        for product in products:
            internal_order.orders.create(
                product_id=product["id"],
                quantity=product["quantity"],
            )

        return internal_order

class SupplierModelManager(models.Manager["SupplierModel"]):
    @transaction.atomic
    def create_supplier(
        self,
        cuit: str,
        name: str,
        email: str,
        locality: "LocalityModel",
        house_number: str,
        street_name: str,
        house_unit: str,
        phone_code: str,
        phone_number: str,
        note: str,
    ) -> "SupplierModel":
        if self.filter(email=email).exists():
            raise ValueError("Ya existe un proveedor con ese email")

        if self.filter(cuit=cuit).exists():
            raise ValueError("Ya existe un proveedor con ese CUIT")

        return self.create(
            cuit=cuit,
            name=name,
            email=email,
            locality=locality,
            house_number=house_number,
            street_name=street_name,
            house_unit=house_unit,
            phone_code=phone_code,
            phone_number=phone_number,
            note=note,
        )

SupplierOrderProductsDict = TypedDict(
    "SupplierOrderProductsDict", {"id": str, "quantity": int}
)

class SupplierOrderManager(models.Manager["SupplierOrderModel"]):
    """
    Custom manager for the SupplierOrderModel, handling the creation of supplier orders.
    """

    @transaction.atomic
    def create_supplier_order(
        self,
        supplier: "SupplierModel",
        office_destination: "OfficeModel",
        user: "UserModel",
        products: List[SupplierOrderProductsDict],
    ) -> "SupplierOrderModel":
        """
        Creates a new supplier order with associated products, history, and total cost calculation. This process is atomic.
        """
        from senda.core.models.order_supplier import SupplierOrderHistoryStatusChoices

        supplier_order = self.create(
            supplier=supplier, office_destination=office_destination
        )
        supplier_order.save()

        supplier_order.history.create(
            status=SupplierOrderHistoryStatusChoices.PENDING,
            supplier_order=supplier_order,
        )

        for product in products:
            supplier_order.orders.create(
                product_id=product["id"],
                quantity=product["quantity"],
            )

        supplier_order.total = supplier_order.calculate_total()

        return supplier_order

ProductStockInOfficeModelDict = TypedDict(
    "ProductStockInOfficeModelDict", {"office_id": str, "stock": int}
)

ProductSupplierDict = TypedDict(
    "ProductSupplierDict", {"supplier_id": str, "price": str}
)

ProductServiceDict = TypedDict("ProductServiceDict", {"name": str, "price": str})

def parse_price(price_str: str) -> Decimal:
    """
    Parses a price string into a Decimal object, handling different formatting conventions.
    """

    standard_format_str = price_str.replace(".", "").replace(",", ".")
    try:
        return Decimal(standard_format_str)
    except InvalidOperation:
        raise ValueError(f"The price {price_str} is not a valid number format")

class ProductModelManager(models.Manager["ProductModel"]):
    """
    Custom manager for the ProductModel, providing methods to create product instances with associated details.
    """

    def create_product(
        self,
        sku: str,
        name: str,
        brand_id: str,
        description: str,
        type: "ProductTypeChoices",
        price: str,
        stock: List[ProductStockInOfficeModelDict],
        services: List[ProductServiceDict],
        suppliers: List[ProductSupplierDict],
    ) -> "ProductModel":
        """
        Creates a new product instance with various associated data like stock, services, and suppliers.
        """
        if self.filter(sku=sku).exists():
            raise ValueError("Ya existe un producto con ese sku")

        product = self.create(
            sku=sku,
            name=name,
            brand_id=brand_id,
            description=description,
            type=type,
            price=parse_price(price),
        )

        for stock_data in stock:
            product.stock.create(
                office_id=stock_data["office_id"],
                stock=stock_data["stock"],
            )

        for service_data in services:
            product.services.create(
                name=service_data["name"],
                price=parse_price(service_data["price"]),
            )

        for supplier_data in suppliers:
            product.suppliers.create(
                supplier_id=supplier_data["supplier_id"],
                price=parse_price(supplier_data["price"]),
            )

        return product

    def get_products_with_stock_in_office(self, office: "OfficeModel", **kwargs: Any):
        """
        Returns all products with associated stock in the given office.
        """
        return self.filter(stock__office=office, **kwargs)

class ProductStockInOfficeManager(models.Manager["ProductStockInOfficeModel"]):
    """
    Custom manager for the ProductStockInOfficeModel, providing methods to create and update stock instances.
    """

    def create_stock(
        self, product: "ProductModel", office: "OfficeModel", stock: int
    ) -> "ProductStockInOfficeModel":
        """
        Creates a new stock instance for the given product and office.
        """
        if self.filter(product=product, office=office).exists():
            raise ValueError("Ya existe un stock para ese producto en esa sucursal")

        return self.create(product=product, office=office, stock=stock)

PurchaseProductsItemDict = TypedDict(
    "PurchaseProductsItemDict", {"product": str, "quantity": int}
)

class PurchaseModelManager(models.Manager["PurchaseModel"]):
    """
    Custom manager for the PurchaseModel, handling the creation of purchase instances.
    """

    @transaction.atomic
    def create_purchase(
        self,
        client: "ClientModel",
        office: str,
        products: List[PurchaseProductsItemDict],
    ) -> "PurchaseModel":
        """
        Creates a new purchase instance with associated purchase items. This process is atomic.
        """
        purchase = self.create(client=client, office_id=office)
        purchase.save()

        for product in products:
            purchase.purchase_items.create(
                quantity=product["quantity"],
                product_id=product["product"],
            )

        purchase.recalculate_total()

        return purchase

RentalContractProductsItemDict = TypedDict(
    "RentalContractProductsItemDict",
    {"id": str, "quantity": int, "service": Optional[str]},
)

class RentalContractManager(models.Manager["RentalContractModel"]):
    """
    Custom manager for the RentalContractModel, handling the creation of rental contract instances.
    """

    @transaction.atomic
    def create_rental_contract(
        self,
        client: "ClientModel",
        products: List[RentalContractProductsItemDict],
        office: str,
        locality: "LocalityModel",
        house_number: str,
        street_name: str,
        house_unit: str,
        contract_start_datetime: str,
        contract_end_datetime: str,
    ) -> "RentalContractModel":
        """
        Creates a new rental contract with associated items and history. This process is atomic.
        """
        from senda.core.models.rental_contracts import RentalContractStatusChoices

        rental_contract = self.create(
            client=client,
            office_id=office,
            locality=locality,
            house_number=house_number,
            street_name=street_name,
            house_unit=house_unit,
            contract_start_datetime=contract_start_datetime,
            contract_end_datetime=contract_end_datetime,
        )

        for product in products:
            rental_contract.rental_contract_items.create(
                product_id=product["id"],
                service_id=product["service"],
                quantity=product["quantity"],
            )

        rental_contract.rental_contract_history.create(
            status=RentalContractStatusChoices.PRESUPUESTADO,
            rental_contract=rental_contract,
        )

        return rental_contract

class EmployeeModelManager(models.Manager["EmployeeModel"]):
    """
    Custom manager for the EmployeeModel, providing methods to create and update employee instances.
    """

    @transaction.atomic
    def create_employee(self, user: "UserModel", offices: List[str]):
        from senda.core.models.offices import OfficeModel
        from senda.core.models.employees import EmployeeOfficeModel

        """
        Creates a new employee instance, ensuring the user does not already have an associated employee.
        """
        if self.filter(user=user).exists():
            raise ValueError("Ya existe ese empleado")

        employee = self.create(user=user)

        for office_id in offices:
            office = OfficeModel.objects.get(id=office_id)
            EmployeeOfficeModel.objects.create(employee=employee, office=office)

        return employee

    def update_employee(self, employee: "EmployeeModel", **kwargs: Any):
        """
        Updates an existing employee instance with the provided details.
        """
        for field, value in kwargs.items():
            setattr(employee, field, value)
        employee.save()
        return employee


# Implement user-defined window size for the play. For example, an user
# could use a keyboard to input different values of widths and heights.
# Accordingly, the screen will display in different sizes regarding the user's input.

import cv2
print(cv2.__version__)

cam = cv2.VideoCapture(0)
width = int(input('Desired width: '))
height = int(input('Desired height: '))

cam.set(cv2.CAP_PROP_FRAME_WIDTH, width)
cam.set(cv2.CAP_PROP_FRAME_HEIGHT, height)

while True:
    ret,frame = cam.read()
    cv2.imshow('frame', frame)
    cv2.moveWindow('frame', 0,0)

    if cv2.waitKey(1) == ord('q'):
        break

cam.release()


import os
import subprocess

class CPPInterop:
    __cpp_file = None
    _command_str = None

    def __init__(self, file):
        assert os.path.exists(file)
        self.__cpp_file = file
        self._command_str = self.__cpp_file

    def build_command(self, use_equals=False, **kwargs):
        """
        Builds Command string
        @param use_equals: instead of --ab txt it will generate --ab=txt
        @param kwargs: specifies arguments for the command.
        For example with the command test.exe --ab txt --abc "text space" -h 1.1.1.1 -l
        command(ab="txt", abc="text space", h="1.1.1.1", l="").
        If non-str types are provided they will be cast to str
        """
        # loop through arguments
        for k in kwargs:
            v = str(kwargs[k])
            # depending on length of key we will do -- or -
            if len(k) == 1:
                self._command_str += f" -{k}"
            else:
                self._command_str += f" --{k}"

            # add value if needed
            if len(v) > 0:
                if " " in v:
                    v = f'"{v}"'

                # Combine key and value
                if use_equals:
                    self._command_str += f"={v}"
                else:
                    self._command_str += f" {v}"

    @property
    def command(self):
        return self._command_str

    def execute(self):
        """ Execute command str """
        print(f"Executing : {self._command_str}")
        subprocess.call(self._command_str)


from PIL import Image
import numpy as np

def calculate_apl(filename):
    """Calculate the average picture level (APL) from an image.

    Keyword arguments:
    filename -- path of image
    """
    # load the image
    image = Image.open(filename)

    # convert image to numpy array
    data = np.asarray(image)

    # calculate APL slicing is to remove the 255 at the end of each pixel array so entire array can be averaged
    APL = np.average(data[:, :, :3]) / 255

    return APL

if __name__ == "__main__":
    # prompt user for image
    filepath = input("Enter the file name (including extension) of the image: ")

    result = calculate_apl(filepath)
    print("The APL is ", result)


# Вводятся данные в формате ключ=значение в одну строчку через
# пробел. Значениями здесь являются целые числа (см. пример ниже).
# Необходимо на их основе создать словарь d с помощью функции dict()

lst = list(map(str, input().split()))
for i in range(len(lst)):
    lst[i] = lst[i].split('=')
    for j in range(len(lst[i])):
        lst[i][-1] = int(lst[i][-1])
print(dict(lst))

# На вход программы поступают данные в виде набора строк в формате:
# # ключ1=значение1
# ключ2=значение2
# ...
# ключN=значениеN
# # Ключами здесь выступают целые числа (см. пример ниже).
# Необходимо их преобразовать в словарь d (без использования
# функции dict())

lst_in = ['5=отлично', '4=хорошо', '3=удовлетворительно']
lst = [i.split('=') for i in lst_in][::-1]
dic = {int(i): j for i, j in lst}
print(dic)

#  Вводятся данные в формате ключ=значение в одну строчку
#  через пробел. Необходимо на их основе создать словарь
#  d, затем удалить из этого словаря ключи 'False' и '3',
#  если они существуют. Ключами и значениями словаря являются строки.

dic = dict(i.split('=') for i in input().split())
if 'False' in dic:
    del dic['False']
if '3' in dic:
    del dic['3']
print(*sorted(dic.items()))

# Вводятся данные в формате ключ=значение в одну
# строчку через пробел. Необходимо на их основе
# создать словарь, затем проверить, существуют
# ли в нем ключи со значениями: 'house', 'True'
# и '5' (все ключи - строки). Если все они существуют,
# то вывести на экран ДА, иначе - НЕТ.

lst = input().split()
dic = dict(i.split('=') for i in lst)
if ('house' in dic) and ('True' in dic) and ('5' in dic):
    print('ДА')
else:
    print('НЕТ')

# Вводятся номера телефонов в одну строчку через
# пробел с разными кодами стран: +7, +6, +2, +4 и т.д.
# Необходимо составить словарь d, где ключи - это
# коды +7, +6, +2 и т.п., а значения - список номеров
# (следующих в том же порядке, что и во входной строке)
# с соответствующими кодами.

# Sample Input:
# +71234567890 +71234567854 +61234576890 +52134567890 +21235777890 +21234567110 +71232267890

lst = input().split()
dic = {}
for i in range(len(lst)):
    if lst[i][:2] not in dic:
        dic[lst[i][:2]] = [lst[i]]
    else:
        dic[lst[i][:2]] += [lst[i]]
print(*sorted(dic.items()))

# Вводятся номера телефонов в формате:
# номер_1 имя_1
# номер_2 имя_2
# ...
# номер_N имя_N
# Необходимо создать словарь d, где ключами будут имена,
# а значениями - список номеров телефонов для этого имени.
# Обратите внимание, что одному имени может принадлежать
# несколько разных номеров.

# Sample Input:
# +71234567890 Сергей
# +71234567810 Сергей
# +51234567890 Михаил
# +72134567890 Николай

import sys

# считывание списка из входного потока
lst_in = list(map(str.strip, sys.stdin.readlines()))

# здесь продолжайте программу (используйте список lst_in)
dic = {}
for i in lst_in:
    for j in [i.split()]:
        if j[1] not in dic:
            dic[j[1]] = [j[0]]
        else:
            dic[j[1]] += [j[0]]
print(*sorted(dic.items()))

# 2
import sys
lst = list(map(str.strip, sys.stdin.readlines()))
a=list([i.split()[1],i.split()[0]]for i in lst)
d=dict([[i[0],[k[1] for k in a if k[0]==i[0]]]for i in a])
print(*sorted(d.items()))

# 3
import sys
lst_in, d = list(map(str.strip, sys.stdin.readlines())), {}
for x in lst_in:
    value, key = x.split()
    d[key] = (d[key] if key in d else []) + [value]
print(*sorted(d.items()))

# Пользователь вводит в цикле целые положительные числа,
# пока не введет число 0. Для каждого числа вычисляется
# квадратный корень (с точностью до сотых) и значение
# выводится на экран (в столбик). С помощью словаря
# выполните кэширование данных так, чтобы при повторном
# вводе того же самого числа результат не вычислялся,
# а бралось ранее вычисленное значение из словаря.
# При этом на экране должно выводиться:
# значение из кэша: <число>

d ={}
while True:
    n = int(input())
    if n == 0:
        break
    else:
        if n in d:
            print(f'значение из кэша: {d[n]}')
        else:
            d[n] = round(n ** .5, 2)
            print(d[n])

# 2
d = {}
while True:
    n = int(input())
    if n == 0:
        break
    else:
        print(round(n ** 0.5, 2) if n not in d else f'значение из кэша: {d[n]}')
        d[n] = round(n ** 0.5, 2)

# Тестовый веб-сервер возвращает HTML-страницы по URL-адресам (строкам).
# На вход программы поступают различные URL-адреса.
# Если адрес пришел впервые, то на экране отобразить строку (без кавычек):
# "HTML-страница для адреса <URL-адрес>"
# Если адрес приходит повторно, то следует взять строку
# "HTML-страница для адреса <URL-адрес>" из словаря и вывести на экран сообщение (без кавычек):
# "Взято из кэша: HTML-страница для адреса <URL-адрес>"
# Сообщения выводить каждое с новой строки.

l = ['ustanovka-i-zapusk-yazyka', 'ustanovka-i-poryadok-raboty-pycharm',
     'peremennyye-operator-prisvaivaniya-tipy-dannykh',
     'arifmeticheskiye-operatsii', 'ustanovka-i-poryadok-raboty-pycharm']
d = {}
for i in l:
     if i in d:
          print(f'Взято из кэша: {d[i]}')
     else:
          print(f'HTML-страница для адреса {i}')
          d[i] = 'HTML-страница для адреса ' + i


import csv
import json
from collections import defaultdict
import itertools
import os
import sys
import argparse

## NB update relevant config file name here
#from config2019 import *
# Mr Gorbachev, tear down etc etc

# Generate booth data structure (combinations hardcoded):
NPP_FIELDS = ["ID", "Division", "Booth", "Latitude", "Longitude"]

# So we'll have 7 columns of stuff before the prefs start:
SA1s_FIELDS = ["year","state_ab", "div_nm", "SA1_id", "pp_id", "pp_nm", "votes"]

# we'll use this one later
ttyjump = '\033[F\033[2K' if (hasattr(sys.stderr, "isatty") and sys.stderr.isatty()) else ""

def main(SCENARIO, NPP_BOOTHS_PATH, STATE, YEAR, PARTIES, SA1S_BREAKDOWN_PATH, SA1S_PREFS_PATH):

    combinations = ["None"] # special-casing the empty

    for r in range(len(PARTIES)):
        chooseN = list(itertools.combinations(sorted(PARTIES), r+1))
        for i in chooseN:
            combinations += ["".join(j) for j in list(itertools.permutations(i))]

    total_combos = len(combinations)

    ### Load in booth data

    booths = {}

    boothsfields = NPP_FIELDS+combinations+["Total"]

    with open(NPP_BOOTHS_PATH) as consolcsv:
        consolreader = csv.DictReader(consolcsv) # fieldnames implicit from the first line

        for row in consolreader:
            booths[row["Division"]+row["Booth"]] = row # key by 'divbooth'

    ###

    lines = []

    with open(SA1S_BREAKDOWN_PATH) as sa1scsv:

        sa1sreader = csv.DictReader(sa1scsv) # fieldnames implicit from the first line

        progress = 0
        print()
        for srow in sa1sreader:

            if not srow["state_ab"]==STATE:
                continue # All SA1s nationwide are in the one file - so any row with the wrong state can be safely skipped.
            elif not (srow["year"] == YEAR):
                sys.exit("Problem in `{SA1s_BREAKDOWN_PATH}`: Unsupported election year: "+srow["year"]+". Exiting.")
                # However, the wrong year is definitely cause for concern

            # if progress == 0:
            #     print(f"Projecting Senate results for scenario {SCENARIO} from "+srow["year"]+" onto state/territory-level electoral boundaries.\n", file=sys.stderr)

            # basically a big vector multiply

            bob = [srow["SA1_id"]]
            db = [ booths[srow["div_nm"]+srow["pp_nm"]][i] for i in boothsfields[5:] ]
            ##  print("db:\t", db)
            for i in range(len(db)):
                try:
                    bob.append(float(srow["votes"]) * float(db[i]) / float(db[-1]))
                except ZeroDivisionError:
                    bob.append(0.0)

            lines.append(bob)

            ##  print("bob:\t", bob)

            progress+= 1
            if (progress % 1000 == 0):
                print(ttyjump+f"... Projection progress: {progress:n} SA1s...", file=sys.stderr)

    print(ttyjump+f"... Projection complete: {progress:n} SA1s", file=sys.stderr)

    # Accumulation phase.

    sa1s = {}
    print(f"... Progress: summing SA1s...", file=sys.stderr)
    for line in lines:
        sa1_id = line[0]

        if sa1_id not in sa1s:
            sa1s[sa1_id] = line[1:]
        else:
            for i in range(1, len(line)):
                sa1s[sa1_id][i-1] += line[i]

    outlines = []

    for ids in sa1s.keys():
        outlines.append([ids] + sa1s[ids])

    outlines.sort()

    print(ttyjump+"... Writing File...", file=sys.stderr, end='')

    with open(SA1S_PREFS_PATH, 'w') as fp:
        print(*(["SA1_id"] + boothsfields[5:]), sep=',', file=fp, flush=True)

        for line in outlines:
            print(*line, sep=',', file=fp)

    print("... Done!\n", file=sys.stderr)

# end main()

def run(argp, confp):
    try:
        if argp.scenarios and not (set(argp.scenarios).intersection(set(confp.sections()))):
            print(f"Error: no specified scenario is defined.", file=sys.stderr)
        else:
            scenlist = confp.sections() if argp.all else argp.scenarios
            for SCENARIO in scenlist:
                YEAR = confp[SCENARIO]['YEAR']
                PARTIES = json.loads(confp[SCENARIO]['GROUPS'])
                STATE = confp[SCENARIO]['STATE']
                SA1S_DISTRICTS_PATH = confp[SCENARIO]['SA1S_DISTS_PATH']
                SA1S_BREAKDOWN_PATH = confp[SCENARIO]['SA1S_BREAKDOWN_PATH']
                OUTPUT_DIR = confp[SCENARIO]['OUTPUT_DIR']
                NPP_BOOTHS_PATH = os.path.join(OUTPUT_DIR, SCENARIO, confp[SCENARIO]['NPP_BOOTHS_FN'])
                SA1S_PREFS_PATH = os.path.join(OUTPUT_DIR, SCENARIO, confp[SCENARIO]['SA1S_PREFS_FN'])

                print("*** Projecting Scenario {}: {}, in {} [{}] ***\n".format(SCENARIO, " vs ".join(PARTIES.keys()), STATE, YEAR), file=sys.stderr)
                main(SCENARIO, NPP_BOOTHS_PATH, STATE, YEAR, PARTIES, SA1S_BREAKDOWN_PATH, SA1S_PREFS_PATH)
    except KeyError as k:
        sys.exit(f"There was an issue with the arguments or configuration file: {k}")

def parse_argv():
    parser = argparse.ArgumentParser(help="Project booth results down onto SA1s")
    # pretty much everything comes from the configfile, yeah?
    parser.add_argument('configfile', type=argparse.FileType('r'))
    mxg = parser.add_mutually_exclusive_group(required=True)
    mxg.add_argument("-a", "--all", action="store_true", help="run every scenario defined in `configfile`")
    mxg.add_argument("-s", "--scenario", dest='scenarios', metavar='scenario', action="append", help="run a scenario code defined in `configfile` (can be specified multiple times to run several scenarios)")
    # not going to support listing scenarios here

    return parser.parse_args()

if __name__ == "__main__":
    argp = parser.parse_args()
    confp = configparser.ConfigParser()
    confp.read_file(argp.configfile)
    run(argp, confp)


import requests
from requests.structures import CaseInsensitiveDict
import base64
import json
from django.conf import settings

requests.packages.urllib3.disable_warnings(
    requests.packages.urllib3.exceptions.InsecureRequestWarning
)

GITHUB_TOKEN = getattr(settings, "GITHUB_TOKEN", None)

def deploy_done(
    git_repository,
    target_branch,
    repository_path,
    deployment,
    bef_bluegreen,
    bef_canary,
    chg_bluegreen,
    chg_canary,
    container,
    tag,
):
    basic_url = "https://raw.githubusercontent.com/"
    basic_api_url = "https://api.github.com/repos/"
    github_token = GITHUB_TOKEN

    git_repo = git_repository.split("/")[-2:]
    if len(git_repo[1]) > 4 and git_repo[1][-4:] == ".git":
        git_repo[1] = git_repo[1][:-4]

    chg_container_url = (
        basic_url
        + "/".join(git_repo)
        + "/"
        + target_branch
        + "/"
        + repository_path
        + "/kustomization.yaml"
    )
    chg_container_upload_url = (
        basic_api_url
        + "/".join(git_repo)
        + "/contents/"
        + repository_path
        + "/kustomization.yaml"
    )

    bef_url = (
        basic_url
        + "/".join(git_repo)
        + "/"
        + target_branch
        + "/"
        + repository_path
        + "/deploy/"
        + bef_bluegreen
        + "/"
        + bef_canary
        + "/kustomization.yaml"
    )
    bef_upload_url = (
        basic_api_url
        + "/".join(git_repo)
        + "/contents/"
        + repository_path
        + "/deploy/"
        + bef_bluegreen
        + "/"
        + bef_canary
        + "/kustomization.yaml"
    )
    tar_url = (
        basic_url
        + "/".join(git_repo)
        + "/"
        + target_branch
        + "/"
        + repository_path
        + "/deploy/"
        + chg_bluegreen
        + "/"
        + chg_canary
        + "/kustomization.yaml"
    )
    chg_upload_url = (
        basic_api_url
        + "/".join(git_repo)
        + "/contents/"
        + repository_path
        + "/deploy/"
        + chg_bluegreen
        + "/"
        + chg_canary
        + "/kustomization.yaml"
    )
    headers = CaseInsensitiveDict()
    headers["Accept"] = "application/json"
    headers["Authorization"] = f"Bearer {github_token}"
    resp = requests.get(chg_container_url, headers=headers, verify=False)

    target_text = []
    next_change = False
    for text in resp.text.split("\n"):
        if ("- name:") in text and (container) in text:
            target_text.append(text)
            next_change = True
        elif next_change:
            target_text.append(f'''  newTag: "{tag}"''')
            next_change = False
        else:
            target_text.append(text)

    chg_container_text = "\n".join(target_text)

    headers = CaseInsensitiveDict()
    headers["Accept"] = "application/json"
    headers["Authorization"] = f"Bearer {github_token}"
    resp = requests.get(bef_url, headers=headers, verify=False)
    target = "-".join(deployment.split("-")[1:-2])

    target_text = []
    target_path = ""
    for text in resp.text.split("\n"):
        if text.split("/")[-1] == target:
            target_path = text
        else:
            target_text.append(text)

    print("target_path :", target_path)
    before_text = "\n".join(target_text)
    headers = CaseInsensitiveDict()
    headers["Accept"] = "application/json"
    headers["Authorization"] = f"Bearer {github_token}"
    resp = requests.get(tar_url, headers=headers, verify=False)
    target_text = []

    count = 0
    for text in resp.text.split("\n"):
        if count == 2:
            target_text.append(target_path)
        target_text.append(text)
        count += 1

    chg_text = "\n".join(target_text)
    # # test code
    # bef_upload_url = basic_api_url + "/".join(git_repo) + "/contents/" + "test.txt"
    # print(before_text)
    # print(chg_text)

    result_code, msg = github_edit_file(
        github_url=chg_container_upload_url,
        github_token=github_token,
        text_content=chg_container_text,
    )

    if result_code == -1:
        return -1, "컨테이너 이미지 변경 실패"

    result_code, msg = github_edit_file(
        github_url=bef_upload_url, github_token=github_token, text_content=before_text
    )
    if result_code == -1:
        return -1, "GIT 저장소 변경 실패"

    result_code, msg = github_edit_file(
        github_url=chg_upload_url, github_token=github_token, text_content=chg_text
    )
    if result_code == -1:
        return -1, "GIT 저장소 변경 실패"

    return 1, "GIT 변경 성공"

def github_edit_file(github_url, github_token, text_content):
    headers = CaseInsensitiveDict()
    headers["Accept"] = "application/json"
    headers["Authorization"] = f"Bearer {github_token}"
    resp = requests.get(github_url, headers=headers, verify=False)

    if resp.status_code != 200 and resp.status_code != 201:
        return -1, "깃허브 연동 실패"
    bef_upload_sha = resp.json()["sha"]

    headers = CaseInsensitiveDict()
    headers["Accept"] = "application/json"
    headers["Authorization"] = f"Bearer {github_token}"
    data = {
        "message": "Multi Deploy-Go auto-commit",
        "content": base64.b64encode(text_content.encode("UTF-8")).decode("ascii"),
        "sha": bef_upload_sha,
    }
    resp = requests.put(
        github_url, headers=headers, data=json.dumps(data), verify=False
    )

    if resp.status_code != 200 and resp.status_code != 201:
        return -1, "깃허브 연동 실패"
    return 1, "깃허브 변경 완료"

if __name__ == "__main__":
    git_repository = "https://github.com/kakaocloudschool/kustomize-test.git"
    target_branch = "main"
    repository_path = "overlays/prod"
    deployment = "deploy-httpd-stable-s"
    bef_bluegreen = "blue"
    bef_canary = "stable"
    chg_bluegreen = "blue"
    chg_canary = "canary"
    deploy_done(
        git_repository=git_repository,
        target_branch=target_branch,
        repository_path=repository_path,
        deployment=deployment,
        bef_bluegreen=bef_bluegreen,
        bef_canary=bef_canary,
        chg_bluegreen=chg_bluegreen,
        chg_canary=chg_canary,
    )