class Solution:
    def wordPatternMatch(self, pattern, str):
        mp = {}

        def dfs(pi: int, sstart: int):
            nonlocal mp
            if len(pattern) == pi:
                return len(str) == sstart

            for send in range(sstart + 1, len(str) - (len(pattern) - pi) + 2):
                if pattern[pi] not in mp and str[sstart:send] not in mp.values():
                    mp[pattern[pi]] = str[sstart:send]
                    if dfs(pi + 1, send):
                        return True
                    del mp[pattern[pi]]
                elif pattern[pi] in mp:
                    if mp[pattern[pi]] == str[sstart:send]:
                        if dfs(pi + 1, send):
                            return True
                    elif len(mp[pattern[pi]]) <= send - sstart:
                        return False

            return False

        return dfs(0, 0)


"""
This is the program that creates the different images for the card suites.
"""
import turtle

def main():
    """
    This contains all of the function calls. Use the functions below as needed.
    """
    _t = turtle.Turtle()

    #draw_spade(_t)
    #draw_heart(_t)
    #draw_red_star(_t)
    #draw_diamond(_t)
    #draw_part_circle(_t, (x=none), (y=none), 5, 5, "black")
def draw_clubs(_t):
    """
    Draws a clubs in the ceter of the screen. No parameters necessary.
    """
    draw_rectangle(_t, -100, -100, 300, 200, 0, "white", "black")
    draw_rectangle(_t, 0, 0, 50, 10, 0, "black", "black")
    draw_circle(_t, -45, 30, 25, "black", "black")
    draw_circle(_t, -20, 75, 25, "black", "black")
    draw_circle(_t, 5, 30, 25, "black", "black")

def draw_diamond(_t):
    """
    Draws a diamond in the center of the screen. No parameters necessary.
    """
    draw_rectangle(_t, -100, -100, 300, 200, 0, "white", "black")
    draw_right_triangle(_t, -41, 64, 40, 50, "red", "red", 0)
    draw_right_triangle(_t, -1, 24, 40, 60, "red", "red", 90)
    draw_right_triangle(_t, 39, 64, 40, 60, "red", "red", 180)
    draw_right_triangle(_t, -1, 104, 40, 60, "red", "red", 270)

#def draw_curve_right_triangle(_t, _x, _y, side, hype, fillcolor, pencolor, tilt):
#    """
#    Atomic shape used to create the triforce used on the shield.
#    _x, and _y are for coordinates
#    side is used for the triangle size
#    fillcolor is for the color inside of the circles
#    pencolor is for the circle borders
#    """
#    _t.up()
#    _t.goto(_x, _y)
#    _t.setheading(tilt)
#    _t.fillcolor(fillcolor)
#    _t.down()
#    _t.begin_fill()
#    _t.forward(side)
#    _t.left(90)
#    _t.forward(side)
#    _t.left(135)
#    hype = part_circle(_t, _x, _y, 50, 50, 3, "red")
#    _t.forward(part_circle(_t, 5, 5, 50, 50, 3, "red"))
#    _t.end_fill()
#    _t.up()
#def part_circle(_t, _x, _y, radius, ext, step, pencolor):
#    """
#    This is the atomic shape circle used for the ball on the sword and the shield in various places throughout.
#    _x, and _y are for coordinates
#    radius is used for the circle size
#    fillcolor is for the color inside of the circles
#    pencolor is for the circle borders
#    """
#    _t.pencolor(pencolor)
#    _t.up()
#    _t.goto(_x,_y)
#    _t.down()
#    _t.circle(radius, ext, step)
#    _t.speed(0)

def draw_circle(_t, _x, _y, radius, fillcolor, pencolor):
    """
    This is the atomic shape circle used for the ball on the sword and the shield in various places throughout.
    _x, and _y are for coordinates
    radius is used for the circle size
    fillcolor is for the color inside of the circles
    pencolor is for the circle borders
    """
    _t.color(pencolor, fillcolor)
    _t.begin_fill()
    _t.up()
    _t.goto(_x,_y)
    _t.down()
    _t.circle(radius)
    _t.end_fill()
    _t.speed(0)

def draw_red_star(_t):
    """
    Draws a red star in the center, could be used instead of the diamond. No parameters necessary.
    """
    draw_rectangle(_t, -100, -100, 300, 200, 0, "white", "black")
    draw_triangle(_t, -1, 64, 40, "red", "red", 120)
    draw_triangle(_t, -1, 24, 40, "red", "red", 180)
    draw_triangle(_t, 34, 44, 40, "red", "red", 150)
    draw_triangle(_t, -40, 64, 40, "red", "red", 210)
    draw_rectangle(_t, -40, 23, 41, 40, 0, "red", "red")

def draw_heart(_t):
    """
    Draws a red heart in the center of the screen. No parameters necessary.
    """
    draw_rectangle(_t, -100, -100, 300, 200, 0, "white", "black")
    draw_circle(_t, -20, 50, 25, "red", "red")
    draw_circle(_t, -45, 75, 25, "red", "red")
    draw_circle(_t, 5, 75, 25, "red", "red")
    draw_triangle(_t, -1, 64, 40, "red", "red", 180)
    draw_triangle(_t, -25, 92, 40, "red", "red", 197)
    draw_triangle(_t, 23, 80, 40, "red", "red", 163)

def draw_spade(_t):
    """
    Draws a spade in the center of the screen. No parameters necessary.
    """
    draw_rectangle(_t, -100, -100, 300, 200, 0, "white", "black")
    draw_rectangle(_t, 0, -10, 70, 10, 0, "black", "black")
    draw_circle(_t, -20, 50, 25, "black", "black")
    draw_circle(_t, -45, 25, 25, "black", "black")
    draw_circle(_t, 5, 25, 25, "black", "black")
    draw_triangle(_t, -15, 69, 40, "black", "black", 0)
    draw_triangle(_t, -40, 40, 40, "black", "black", -10)
    draw_triangle(_t, 5, 40, 40, "black", "black", 10)

def draw_right_triangle(_t, _x, _y, side, hype, fillcolor, pencolor, tilt):
    """
    Atomic shape used to create the triforce used on the shield.
    _x, and _y are for coordinates
    side is used for the triangle size
    fillcolor is for the color inside of the circles
    pencolor is for the circle borders
    """
    _t.up()
    _t.goto(_x, _y)
    _t.setheading(tilt)
    _t.fillcolor(fillcolor)
    _t.down()
    _t.begin_fill()
    _t.forward(side)
    _t.left(90)
    _t.forward(side)
    _t.left(135)
    _t.forward(hype)
    _t.end_fill()
    _t.up()

def draw_triangle(_t, _x, _y, side, fillcolor, pencolor, tilt):
    """
    Atomic shape used to create the triforce used on the shield.
    _x, and _y are for coordinates
    side is used for the triangle size
    fillcolor is for the color inside of the circles
    pencolor is for the circle borders
    """
    _t.up()
    _t.goto(_x, _y)
    _t.setheading(tilt)
    _t.fillcolor(fillcolor)
    _t.down()
    _t.begin_fill()
    for _i in range(3):
        _t.forward(side)
        _t.left(120)
    _t.end_fill()
    _t.up()

def draw_rectangle(_t, _x, _y, height, width, tilt, fillcolor, pencolor):
    """
    _x, and _y are for coordinates
    height and width are used for the rectangle size
    tilt is for the direction that the rectangle is tilted or not.
    fillcolor is for the color inside of the circles
    pencolor is for the circle borders
    """
    _t.setheading(tilt)
    _t.up()
    _t.goto(_x, _y)
    _t.down()
    _t.color(pencolor, fillcolor)
    _t.begin_fill()
    for _i in range(2):
        _t.forward(width)
        _t.left(90)
        _t.forward(height)
        _t.left(90)

    _t.right(90)
    _t.end_fill()
    _t.up()

if __name__== "__main__":
    main()


import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import sklearn.metrics as metric
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression, Ridge, Lasso
from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import StandardScaler, MinMaxScaler

################################################################################################ Load data

student = pd.read_csv('student-mat.csv')

################################################################################################ Drop data

# G3 Grade에 영향이 적은 feature 제거
preprocessed_student = student.copy()
preprocessed_student = preprocessed_student.drop(['address'], axis = 1)
preprocessed_student = preprocessed_student[preprocessed_student.age < 20]
preprocessed_student = preprocessed_student[preprocessed_student.G3 != 0]
preprocessed_student = preprocessed_student.drop(['school', 'G1', 'G2'], axis = 1)

# One-hot Encoding
preprocessed_student = pd.get_dummies(preprocessed_student)

# Correlation이 높은 것들 골라서 dataframe 재구성하기
most_correlated = preprocessed_student.corr().abs()['G3'].sort_values(ascending=False)
most_correlated = most_correlated[:9]
student_corr = preprocessed_student.loc[:, most_correlated.index]

################################################################################################ Scaling
# Before Scaling
#preprocessed_student.plot.kde()
#student_corr.plot.kde()

# StandardScaler
ss = StandardScaler()
ss2 = StandardScaler()
data = ss.fit_transform(preprocessed_student)
data2 = ss2.fit_transform(student_corr)
preprocessed_student = pd.DataFrame(data, columns=list(preprocessed_student.columns))
student_corr = pd.DataFrame(data2, columns=list(student_corr.columns))

# Minmax Scaler
mm = MinMaxScaler()
mm2 = MinMaxScaler()
data = mm.fit_transform(preprocessed_student)
data2 = mm2.fit_transform(student_corr)
preprocessed_student2 = pd.DataFrame(data, columns=list(preprocessed_student.columns))
student_corr2 = pd.DataFrame(data2, columns=list(student_corr.columns))

# After Scaling
#preprocessed_student.plot.kde()
#preprocessed_student2.plot.kde()
#student_corr2.plot.kde()
#student_corr.plot.kde()
#plt.show()

# Target Value G3 Restore
print(student_corr['G3'].shape)
print(student['G3'].shape)

preprocessed_student['G3'] = student['G3']
preprocessed_student2['G3'] = student['G3']
student_corr['G3'] = student['G3']
student_corr2['G3'] = student['G3']

################################################################################################ Modeling

X = student_corr.drop(['G3'], axis = 1)
y = student_corr['G3']
X2 = preprocessed_student.drop(['G3'], axis = 1)
y2 = preprocessed_student['G3']
X3 = student_corr2.drop(['G3'], axis = 1)
y3 = student_corr2['G3']
X4 = preprocessed_student2.drop(['G3'], axis = 1)
y4 = preprocessed_student2['G3']

# split Dataset
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2)
X_train2, X_test2, y_train2, y_test2 = train_test_split(X2, y2, test_size = 0.2)
X_train3, X_test3, y_train3, y_test3 = train_test_split(X3, y3, test_size = 0.2)
X_train4, X_test4, y_train4, y_test4 = train_test_split(X4, y4, test_size = 0.2)

# Basic Linear Regression
lr = LinearRegression()
lr.fit(X_train, y_train)
lr2 = LinearRegression()
lr2.fit(X_train2, y_train2)
lr3 = LinearRegression()
lr3.fit(X_train3, y_train3)
lr4 = LinearRegression()
lr4.fit(X_train4, y_train4)

# Linear Regression with Regularization (Ridge)
lr_ = Ridge(alpha = 0.001)
lr_.fit(X_train, y_train)
lr2_ = Ridge(alpha = 0.001)
lr2_.fit(X_train2, y_train2)
lr3_ = Ridge(alpha = 0.001)
lr3_.fit(X_train3, y_train3)
lr4_ = Ridge(alpha = 0.001)
lr4_.fit(X_train4, y_train4)

# Linear Regression with Regularization (Lasso)
lr__ = Lasso(alpha = 0.001)
lr__.fit(X_train, y_train)
lr2__ = Lasso(alpha = 0.001)
lr2__.fit(X_train2, y_train2)
lr3__ = Lasso(alpha = 0.001)
lr3__.fit(X_train3, y_train3)
lr4__ = Lasso(alpha = 0.001)
lr4__.fit(X_train4, y_train4)

################################################################################################ Evaluation

y_pred = lr.predict(X_test)
y_pred2 = lr2.predict(X_test2)
y_pred3 = lr3.predict(X_test3)
y_pred4 = lr4.predict(X_test4)

# With Regularization - Ridge
y_pred5 = lr_.predict(X_test)
y_pred6 = lr2_.predict(X_test2)
y_pred7 = lr3_.predict(X_test3)
y_pred8 = lr4_.predict(X_test4)

# With Regularization - Lasso
y_pred9 = lr__.predict(X_test)
y_pred10 = lr2__.predict(X_test2)
y_pred11 = lr3__.predict(X_test3)
y_pred12 = lr4__.predict(X_test4)

# Normal
MSE = metric.mean_absolute_error(y_test, y_pred)
MSE2 = metric.mean_absolute_error(y_test2, y_pred2)
MSE3 = metric.mean_absolute_error(y_test3, y_pred3)
MSE4 = metric.mean_absolute_error(y_test4, y_pred4)

# Ridge
MSE5 = metric.mean_absolute_error(y_test, y_pred5)
MSE6 = metric.mean_absolute_error(y_test2, y_pred6)
MSE7 = metric.mean_absolute_error(y_test3, y_pred7)
MSE8 = metric.mean_absolute_error(y_test4, y_pred8)

# Lasso
MSE9 = metric.mean_absolute_error(y_test, y_pred9)
MSE10 = metric.mean_absolute_error(y_test2, y_pred10)
MSE11 = metric.mean_absolute_error(y_test3, y_pred11)
MSE12 = metric.mean_absolute_error(y_test4, y_pred12)

# normal
RMSE = np.sqrt(metric.mean_absolute_error(y_test, y_pred))
RMSE2 = np.sqrt(metric.mean_absolute_error(y_test2, y_pred2))
RMSE3 = np.sqrt(metric.mean_absolute_error(y_test3, y_pred3))
RMSE4 = np.sqrt(metric.mean_absolute_error(y_test4, y_pred4))

# Ridge
RMSE5 = np.sqrt(metric.mean_absolute_error(y_test, y_pred5))
RMSE6 = np.sqrt(metric.mean_absolute_error(y_test2, y_pred6))
RMSE7 = np.sqrt(metric.mean_absolute_error(y_test3, y_pred7))
RMSE8 = np.sqrt(metric.mean_absolute_error(y_test4, y_pred8))

# Lasso
RMSE9 = np.sqrt(metric.mean_absolute_error(y_test, y_pred9))
RMSE10 = np.sqrt(metric.mean_absolute_error(y_test2, y_pred10))
RMSE11 = np.sqrt(metric.mean_absolute_error(y_test3, y_pred11))
RMSE12 = np.sqrt(metric.mean_absolute_error(y_test4, y_pred12))

# normal
r2 = metric.r2_score(y_test, y_pred)
r2_2 = metric.r2_score(y_test2, y_pred2)
r2_3 = metric.r2_score(y_test3, y_pred3)
r2_4 = metric.r2_score(y_test4, y_pred4)

# Ridge
r2_5 = metric.r2_score(y_test, y_pred5)
r2_6 = metric.r2_score(y_test2, y_pred6)
r2_7 = metric.r2_score(y_test3, y_pred7)
r2_8 = metric.r2_score(y_test4, y_pred8)

#Lasso
r2_9 = metric.r2_score(y_test, y_pred9)
r2_10 = metric.r2_score(y_test2, y_pred10)
r2_11 = metric.r2_score(y_test3, y_pred11)
r2_12 = metric.r2_score(y_test4, y_pred12)

print("MSE Normal")
print(f"STD MSE_Important : {MSE} | MSE_FULL : {MSE2}")
print(f"MINMAX MSE_Important : {MSE3} |  MSE_FULL : {MSE4}")

print("MSE Ridge")
print(f"STD MSE_Important : {MSE5} | MSE_FULL : {MSE6}")
print(f"MINMAX MSE_Important : {MSE7} |  MSE_FULL : {MSE8}")

print("MSE Lasso")
print(f"STD MSE_Important : {MSE9} | MSE_FULL : {MSE10}")
print(f"MINMAX MSE_Important : {MSE11} |  MSE_FULL : {MSE12}")
print()

print("RMSE Normal")
print(f"STD RMSE_Important : {RMSE} | RMSE_FULL : {RMSE2}")
print(f"MINMAX RMSE_Important : {RMSE3} |  RMSE_FULL : {RMSE4}")

print("RMSE Ridge")
print(f"STD RMSE_Important : {RMSE5} | RMSE_FULL : {RMSE6}")
print(f"MINMAX RMSE_Important : {RMSE7} |  RMSE_FULL : {RMSE8}")

print("RMSE Lasso")
print(f"STD RMSE_Important : {RMSE9} | RMSE_FULL : {RMSE10}")
print(f"MINMAX RMSE_Important : {RMSE11} |  RMSE_FULL : {RMSE12}")
print()

print("R2 Normal")
print(f"STD R2_Important : {r2} | R2_FULL : {r2_2}")
print(f"MINMAX R2_Important : {r2_3} |  R2_FULL : {r2_4}")

print("R2 Ridge")
print(f"STD R2_Important : {r2_5} | R2_FULL : {r2_6}")
print(f"MINMAX R2_Important : {r2_7} |  R2_FULL : {r2_8}")

print("R2 Lasso")
print(f"STD R2_Important : {r2_9} | R2_FULL : {r2_10}")
print(f"MINMAX R2_Important : {r2_11} |  R2_FULL : {r2_12}")

plt.figure(figsize = (32, 8))
plt.subplot(1,12,1)
plt.scatter(range(len(y_test)), y_test, color = 'blue')
plt.scatter(range(len(y_pred)), y_pred, color = 'red')
plt.title("Std with important Data")
plt.subplot(1,12,2)
plt.scatter(range(len(y_test2)), y_test2, color = 'blue')
plt.scatter(range(len(y_pred2)), y_pred2, color = 'red')
plt.title("Std with Full Data")
plt.subplot(1,12,3)
plt.scatter(range(len(y_test3)), y_test3, color = 'blue')
plt.scatter(range(len(y_pred3)), y_pred3, color = 'red')
plt.title("MinMax with important Data")
plt.subplot(1,12,4)
plt.scatter(range(len(y_test4)), y_test4, color = 'blue')
plt.scatter(range(len(y_pred4)), y_pred4, color = 'red')
plt.title("MinMax with Full Data")

plt.subplot(1,12,5)
plt.scatter(range(len(y_test)), y_test, color = 'blue')
plt.scatter(range(len(y_pred5)), y_pred5, color = 'red')
plt.title("Std with important Data")
plt.subplot(1,12,6)
plt.scatter(range(len(y_test2)), y_test2, color = 'blue')
plt.scatter(range(len(y_pred6)), y_pred6, color = 'red')
plt.title("Std with Full Data")
plt.subplot(1,12,7)
plt.scatter(range(len(y_test3)), y_test3, color = 'blue')
plt.scatter(range(len(y_pred7)), y_pred7, color = 'red')
plt.title("MinMax with important Data")
plt.subplot(1,12,8)
plt.scatter(range(len(y_test4)), y_test4, color = 'blue')
plt.scatter(range(len(y_pred8)), y_pred8, color = 'red')
plt.title("MinMax with Full Data")

plt.subplot(1,12,9)
plt.scatter(range(len(y_test)), y_test, color = 'blue')
plt.scatter(range(len(y_pred9)), y_pred9, color = 'red')
plt.title("Ridge with important Data")
plt.subplot(1,12,10)
plt.scatter(range(len(y_test2)), y_test2, color = 'blue')
plt.scatter(range(len(y_pred10)), y_pred10, color = 'red')
plt.title("Ridge with Full Data")
plt.subplot(1,12,11)
plt.scatter(range(len(y_test3)), y_test3, color = 'blue')
plt.scatter(range(len(y_pred11)), y_pred11, color = 'red')
plt.title("Lasso with important Data")
plt.subplot(1,12,12)
plt.scatter(range(len(y_test4)), y_test4, color = 'blue')
plt.scatter(range(len(y_pred12)), y_pred12, color = 'red')
plt.title("Lasso with Full Data")

plt.show()

# 모든 feature 다 사용할 것
# Random forest에서 feature importance를 사용해볼 것
# Scaling 해볼 것
# G1, G2 추가해볼 것
# hypermarameter tuning 할 것

# 과제
'''
1. Scaling 해서 G3 다시 예측해볼 것
2. Hypermarameter tuning 해보고 영향에 대해 논할 것
3. G1, G2를 포함시켜보고 이것의 영향에 대해 논할 것
4. 이걸 해야하나 말아야하나 논할 것
'''

## DS - Student Grade Prediction/Prediction_Regularization.py


# -*- coding: utf-8 -*-
"""
Created on Thu Jul  9 12:21:35 2020

@author: VARUN SAKUNIA
"""

import cv2
import numpy as np

# size of images must be same
#img1 = np.zeros((250,500,3), np.uint8)
img1 = cv2.imread(r'D:\My_Face_DataSet\varun.jpg')
img1 = cv2.resize(img1,(800,600))
img1 = cv2.rectangle(img1,(200,0),(300,100),(255,255,255),-1)
img2 = cv2.imread(r'D:\My_Face_DataSet\varun1.jpg')
img2 = cv2.resize(img2,(800,600))

# performing logical AND,OR,XOR,NOT
bitAnd = cv2.bitwise_and(img2, img1)
bitOr = cv2.bitwise_or(img2, img1)
bitXor = cv2.bitwise_xor(img1, img2)
bitNot1 = cv2.bitwise_not(img1)
bitNot2 = cv2.bitwise_not(img2)

cv2.imshow("img1", img1)
cv2.imshow("img2", img2)
cv2.imshow('bitAnd', bitAnd)
cv2.imshow('bitOr', bitOr)
cv2.imshow('bitXor', bitXor)
cv2.imshow('bitNot1', bitNot1)
cv2.imshow('bitNot2', bitNot2)

cv2.waitKey(0)
cv2.destroyAllWindows()


# -*- coding: utf-8 -*-
"""
Created on Fri Dec 18 23:06:57 2020

@author: PRANIKP

Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.

For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -1
Example 3:

Input: haystack = "", needle = ""
Output: 0

Constraints:

0 <= haystack.length, needle.length <= 5 * 104
haystack and needle consist of only lower-case English characters.

Time Complexity: O(m+n)
Space Complexity:O(n)
"""

class Solution(object):

    def calLPS(self,arr):

        res = [0] * len(arr)

        p1 = 0
        p2 = 1

        while p2 < len(arr):
            if arr[p2] == arr[p1]:
                res[p2] = p1 + 1
                p2 += 1
                p1 += 1
            else:
                if p1 !=0:
                    p1 = res[p1 - 1]
                else:
                    res[p2] = 0
                    p2 += 1

        return res

    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        if not needle:
            return 0

        first = 0
        second = 0

        lps = [0] * len(needle)

        lps = self.calLPS(needle)

        while first < len(haystack):

            if haystack[first] == needle[second]:
                first += 1
                second += 1
            else:
                if second != 0:
                    second = lps[second - 1]
                else:
                    first += 1

            if second == len(needle):
                return first - second

        return -1


"""

Given a string, find the minimum number of characters that we can remove to make it a palindrome.

Example 1:

Input: "abdbca"
Output: 1
Explanation: By removing "c", we get a palindrome "abdba".
Example 2:

Input: = "cddpd"
Output: 2
Explanation: Deleting "cp", we get a palindrome "ddd".
Example 3:

Input: = "pqr"
Output: 2
Explanation: We have to remove any two characters to get a palindrome, e.g. if we
remove "pq", we get palindrome "r".

The time and space complexity of the above algorithm is O(n^2)
, where ‘n’ is the length of the input string.

"""
def find_minimum_deletions(str):
    # subtracting the length of Longest Palindromic Subsequence from the length of
    # the input string to get minimum number of deletions
    return len(str) - find_LPS_length(str)

def find_LPS_length(str):
    n = len(str)
    dp = [[0 for x in range(n)]for y in range(n)]
    for i in range(n):
        dp[i][i] = 1
    for start in range(n - 1, -1, -1):
        for end in range(start + 1, n):
            if str[start] == str[end]:
                dp[start][end] = 2 + dp[start+1][end-1]
            else:
                dp[start][end] = max(dp[start + 1][end], dp[start][end-1])
    return dp[0][n-1]

def main():
  print(find_minimum_deletions("abdbca"))
  print(find_minimum_deletions("cddpd"))
  print(find_minimum_deletions("pqr"))

main()


def fib(n):    # write Fibonacci series up to n
    """Print a Fibonacci series up to n."""
    results = list()
    a, b = 0, 1
    while a < n:
        # print(a,end = ' ')
        results.append(a)
        a, b = b, a+b # a =b
        # b = a+b
    return results

# print(fib(4))
"""
String function string_cat(String* string1,String* string2){
    return "sss";
}
"""
def string_cat(string1,string2):
    string3 = string1+" "+string2
    return string3

# s1 = "Hello"
# s2 = "World"
# s3 = string_cat #Function pointer
# print(s3("H","W"))

# Day 3
def ask_ok(prompt, retries=4, reminder='Please try again!'):
    while True:
        ok = input(prompt)
        if ok in ('y', 'ye', 'yes'):
            return True
        if ok in ('n', 'no', 'nop', 'nope'):
            return False
        retries = retries - 1
        if retries < 0:
            raise ValueError('invalid user response')
        print(reminder)

# print(ask_ok("Type something: ",7,"You are typing a wrong value"))
i = 5

def ff(arg=i):
    print(arg)
    return arg
i =6
print(ff())
def f(a, L=None):
    if L is None:
        l = []
    l.append(a)
    return l

# if __name__ == "__main__":
i = 6
print(f(i))
print(f(i))

def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
    print("-- This parrot wouldn't", action, end=' ')
    print("if you put", voltage, "volts through it.")
    print("-- Lovely plumage, the", type)
    print("-- It's", state, "!")

parrot(1000,type="UI")

def cheeseshop(*value, **keywords):
    kind = ""
    print("-- Do you have any", kind, "?")
    print("-- I'm sorry, we're all out of", kind)
    for arg in value:
        print(arg)
    print("-" * 40)
    for kw in keywords:
        print(kw, ":", keywords[kw])

cheeseshop("huuhiu",pos ="uhkuhi")
d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
""" ** - unpacking
voltage = "four million"
state =  "bleedin' demised"
action = "VOOM"
"""
parrot(**d)

def sort_string(pair):
    # print(pair)
    return pair[0] + pair[1]

# Lambda functions
pairs = [[1, 5], [2, 9], [3, 7], [4, 14]]
# pairs.sort(key = sort_string, reverse=True)
pairs.sort(key=lambda a: a[0]+a[1])
print(pairs)


"""Tool to crop each of icons for costume"""
from PIL import Image
from tqdm import tqdm
HOME = "./"
im = Image.open(HOME+'image0.png')
# bar = tqdm(total=12*8)  # COSTUMES
# count = 1
# for tate in range(8):
#     for yoko in range(12):
#         bar.update(1)
#
#         # head:
#         # im_crop = im.crop((yoko * 80, tate * 80 + 5, yoko * 80 + 80, tate * 80 + 75))
#         # body, back:
#         im_crop = im.crop((yoko*80, tate*110+10, yoko*80+80, tate*110+100))
#
#         im_crop.save(HOME + f'res\\{count}.png')
#         count += 1

bar = tqdm(total=4*5)  # CHARACTER ICONS
count = 1
for tate in range(4):
    for yoko in range(5):
        bar.update(1)
        x = 90
        y = 90
        im_crop = im.crop((yoko * y, tate * x, yoko * x+x, tate * y+y))
        im_crop.save(HOME + f'res/{count}.png')
        count += 1


# -*- coding: utf-8 -*-
"""
Created on Mon Jun  3 18:42:28 2019

@author: Tang
"""

'''
题目描述

对于一个元素各不相同且按升序排列的有序序列，请编写一个算法，创建一棵高度最小的二叉查找树。

给定一个有序序列int[] vals,请返回创建的二叉查找树的高度。
'''
def solution(data):
     l=len(data)
     if l<=2:
          return l
     left=0
     right=l
     mid=(left+right)//2
     p=solution(data[:mid])
     q=solution(data[mid+1:])
     if p>q:
          return p+1
     else:
          return q+1

a=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
print(solution(a))
s=input()
print(s)

程序员面试宝典/20.高度最小BST.py


from typing import List
import numpy as np

import numpy as np

class Solution:

    def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
        resultArr = list(np.zeros([len(matrix[0]), len(matrix)],
                                  dtype="int32"))
        for i in range(len(matrix)):
            for j in range(len(matrix[i])):

                resultArr[j][i] = matrix[i][j]
        return list(map(lambda a: list(a), resultArr))

s = Solution()
mat = [[1, 2, 3], [4, 5, 6]]

print(s.transpose(mat))


# %% import modules
from mnist.loader import MNIST

import neural_network_package as nnp
import mnist_downloader
import numpy as np
import matplotlib.pyplot as plt

# %% Download MNIST Dataset
download_folder = "./mnist/"
mnist_downloader.download_and_unzip(download_folder)

# %% load training data
mndata = MNIST('mnist', return_type="numpy")
images_train, labels_train = mndata.load_training()
images_validation, labels_validation = mndata.load_testing()

# %% Scale Data
scaler = nnp.StandardScaler()
scaler.fit(images_train)
X_train_scaled = scaler.transform(images_train)
X_validation_scaled = scaler.transform(images_validation)

# Add Bias to X_pizza
X = nnp.add_bias_column(X_train_scaled)
X_validation = nnp.add_bias_column(X_validation_scaled)

# Defining Y_pizza Values as One-Hot-Vectors
Y = np.identity(10, dtype=int)[labels_train]
Y_validation = np.identity(10, dtype=int)[labels_validation]

# %% Running the NeuralNet

# define hyperparameter
alpha = 10
epoch = 25
batch_size = 300
lamda_value = 0.1
beta_val = 0.3

# initialize a new neural net
neural_net = nnp.NeuralNetwork([784, 20, 10])
neural_net.set_activation_function("tanh")

# train
error_history, accuracy_history, gradients, softmax = neural_net.train(x=X, y=Y,
                                                                       alpha=alpha, epochs=epoch, batch_size=batch_size,
                                                                       lamda_value=lamda_value, beta_value=beta_val)
# console output
print("Accuracy Training ", accuracy_history[-1])
print("Error Training ", error_history[-1])
generated_trainig_result = neural_net.predict(X)
print("F1 Training ", nnp.f1_score(generated_trainig_result, Y))

# %% Plot Training Progress
fig, ax = plt.subplots()
ax.plot(error_history, label="Error")
ax.set_xlabel("Iterations")
ax.set_ylabel("Error")
ax.set_title("Error History")
fig.legend()
fig.tight_layout()
plt.show()

# %% Validate Training

prediction_result = neural_net.predict(X_validation)
print("F1 Validation ", nnp.f1_score(prediction_result, Y_validation))


import pandas as pd
from mil_data_generator import *
from mil_models_pytorch import*
from mil_trainer_torch import *
from sklearn.utils.class_weight import compute_class_weight
import torch
from torchvision import transforms
import argparse

np.random.seed(42)
random.seed(42)
torch.manual_seed(42)

def main(args):

    # INPUTS #
    dir_images = '../data/SICAP_MIL/patches/'
    dir_data_frame = '../data/SICAP_MIL/dataframes/gt_global_slides.xlsx'
    dir_data_frame_test = '../data/SICAP_MIL/dataframes/gt_test_patches.xlsx'
    dir_experiment = '../data/results/' + args.experiment_name + '/'

    classes = ['G3', 'G4', 'G5']
    proportions = ['pG3', 'pG4', 'pG5']
    input_shape = (3, 224, 224)
    images_on_ram = True
    data_augmentation = True
    pMIL = False
    aggregation = 'max'  # 'max', 'mean', 'attentionMIL', 'mcAttentionMIL'
    mode = 'instance'  # 'embedding', 'instance', 'mixed'
    include_background = True
    iterations = 3

    df = pd.read_excel(dir_data_frame)

    metrics = []
    for ii_iteration in np.arange(0, iterations):

        # Set data generators
        dataset_train = MILDataset(dir_images, df[df['Partition'] == 'train'], classes, bag_id='slide_name',
                                   input_shape=input_shape, data_augmentation=False, images_on_ram=images_on_ram,
                                   pMIL=pMIL, proportions=proportions)
        data_generator_train = MILDataGenerator(dataset_train, batch_size=1, shuffle=True, max_instances=512)

        dataset_test = MILDataset(dir_images, df[df['Partition'] == 'test'], classes, bag_id='slide_name',
                                  input_shape=input_shape, data_augmentation=False, images_on_ram=images_on_ram,
                                  pMIL=pMIL, proportions=proportions, dataframe_instances=pd.read_excel(dir_data_frame_test))
        data_generator_test = MILDataGenerator(dataset_test, batch_size=1, shuffle=False, max_instances=512)

        # Test at instance level
        X_test = data_generator_test.dataset.X[data_generator_test.dataset.y_instances[:, 0] != -1, :, :, :]
        Y_test = data_generator_test.dataset.y_instances[data_generator_test.dataset.y_instances[:, 0] != -1, :]

        # Load network
        network = torch.load(dir_experiment + str(ii_iteration) + '_network_weights_best.pth')

        # Pseudolabels on training set
        labels = []
        yhat_one_hot = []
        Yglobal = data_generator_train.dataset.Yglobal
        X = data_generator_train.dataset.X

        for i in np.arange(0, X.shape[0]):
            print(str(i + 1) + '/' + str(X.shape[0]), end='\r')

            # Tensorize input
            x = torch.tensor(X[i, :, :, :]).cuda().float()
            x = x.unsqueeze(0)

            features = network.bb(x)
            yhat = torch.softmax(network.classifier(torch.squeeze(features)), 0)
            yhat = yhat.detach().cpu().numpy()
            yhat_one_hot.append(yhat)

            if np.max(Yglobal[i, 1:]) == 0:
                labels.append(0)
            else:
                if np.argmax(yhat) > 0:
                    if Yglobal[i, np.argmax(yhat)] == 1 and yhat[np.argmax(yhat)] > 0.5:
                        labels.append(np.argmax(yhat))
                    else:
                        labels.append(10)
                else:
                    labels.append(10)
        labels = np.array(labels)
        yhat_one_hot = np.array(yhat_one_hot)

        X = X[labels != 10, :, :, :]
        Y = labels[labels != 10]
        images_id = np.array(dataset_train.images)[labels != 10]
        class_weights = compute_class_weight('balanced', [0, 1, 2, 3], Y)

        # Set student network architecture
        lr = 1e-2
        network = MILArchitecture(classes, mode=mode, aggregation=aggregation, backbone='vgg19',
                                  include_background=include_background).cuda()
        opt = torch.optim.SGD(network.parameters(), lr=lr)

        tranf = torch.nn.Sequential(transforms.RandomHorizontalFlip(),
                                    transforms.RandomRotation(degrees=(-45, 45)),
                                    transforms.GaussianBlur(3, sigma=(0.1, 2.0)),
                                    transforms.ColorJitter(brightness=.5, hue=.3)).cuda()

        training_data = CustomImageDataset(X, Y, transform=False)
        train_dataloader = CustomGenerator(training_data, bs=32, shuffle=True)

        def test_instances(X, Y, network, dir_out, i_iteration):
            network.eval()
            Yhat = []
            for i in np.arange(0, X.shape[0]):
                print(str(i + 1) + '/' + str(X.shape[0]), end='\r')

                # Tensorize input
                x = torch.tensor(X[i, :, :, :]).cuda().float()
                x = x.unsqueeze(0)

                features = network.bb(x)
                yhat = torch.softmax(network.classifier(torch.squeeze(features)), 0)
                yhat = torch.argmax(yhat).detach().cpu().numpy()

                Yhat.append(yhat)

            Yhat = np.array(Yhat)
            Y = np.argmax(Y, 1)

            cr = classification_report(Y, Yhat, target_names=['NC'] + classes, digits=4)
            cm = confusion_matrix(Y, Yhat)
            k2 = cohen_kappa_score(Y, Yhat, weights='quadratic')

            f = open(dir_out + str(i_iteration) + '_report_student.txt', 'w')
            f.write('Title\n\nClassification Report\n\n{}\n\nConfusion Matrix\n\n{}\n\nKappa\n\n{}\n'.format(cr, cm, k2))
            f.close()

            return k2

        # STUDENT TRAINING

        epochs = 60
        dropout_rate = 0.2
        for i_epoch in np.arange(0, epochs):
            l_epoch = 0

            if (i_epoch + 1) % 25 == 0:
                for g in opt.param_groups:
                    g['lr'] = g['lr'] / 2

            for i_iteration, (X, Y) in enumerate(train_dataloader):
                # Set model to training mode and clear gradients
                network.train()
                opt.zero_grad()

                X = X.cuda().float()
                X = tranf(X)

                logits = network.classifier(torch.nn.Dropout(dropout_rate)(torch.squeeze(network.bb(X))))

                L = torch.nn.CrossEntropyLoss(weight=torch.tensor(class_weights).cuda().float())(logits, Y.type(torch.LongTensor).cuda())

                L.backward()
                opt.step()

                L_iteration = L.detach().cpu().numpy()
                l_epoch += L_iteration

                info = "[INFO] Epoch {}/{}  -- Step {}/{}: Lce={:.6f}".format(
                    i_epoch + 1, epochs, i_iteration + 1, len(train_dataloader), L_iteration)
                print(info, end='\r')

            l_epoch = l_epoch/len(train_dataloader)

            k2 = test_instances(X_test, Y_test, network, dir_experiment, ii_iteration)

            info = "[INFO] Epoch {}/{}  -- Step {}/{}: Lce={:.6f}; k2={:.6f}".format(
                i_epoch+1, epochs, i_iteration, len(train_dataloader), l_epoch, k2)
            print(info, end='\n')

        torch.save(network, dir_experiment + str(ii_iteration) + '_student_network_weights.pth')

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("--experiment_name", default="test_test_test", type=str)

    args = parser.parse_args()
    main(args)


import sys
sys.stdin = open('input.txt')

def dfs(s):
    visit[s] = False
    for x in list1[s]:
        if visit[x] == True:
            dfs(x)

for w in range(10):
    num, V = map(int, input().split())

    arr = list(map(int, input().split()))
    list1 = [[] for _ in range(101)]
    visit = [True for _ in range(101)]

    list_arr = list(range(0,2*V,2))

    for i in list_arr:
        list1[arr[i]].append(arr[i+1])

    dfs(0)
    result = 1
    if visit[99] == True:
        result = 0

    print(f'#{num} {result}')


import pygame as py

py.init()

win = py.display.set_mode((500, 500))

py.display.set_caption("First Game")

x = 50
y = 50
width = 40
height = 60
vel = 5  # how fast it moves

# main loop - check if you hit sth

run = True

while run:
    py.time.delay(100)  # clock for the game. 100ms
    # check for events

    for event in py.event.get():
        if event.type == py.QUIT:
            run = False

    keys = py.key.get_pressed()

    if keys[py.K_LEFT]:
        x -= vel
    if keys[py.K_RIGHT]:
        x += vel
    if keys[py.K_UP]:
        y -= vel
    if keys[py.K_DOWN]:
        y += vel

    win.fill((0, 0, 0))
    py.draw.rect(win, (255, 0, 0), (x, y, width, height))  # everything is on the surface
    py.display.update()

py.quit()


# -*- coding: utf-8 -*-
"""
Created on Thu Feb 24 05:07:00 2022

@author: dream
"""

import urllib.request, urllib.parse, urllib.error
import xml.etree.ElementTree as ET
import ssl

# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

url = input('Input URL: ')
addr = urllib.request.urlopen(url, context=ctx)
data = addr.read()
cnt = 0;

# print(data.decode())

tree = ET.fromstring(data)
comments = tree.findall('comments/comment')
for item  in comments:
    cnt += int(item.find('count').text)
print(cnt)


import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.distributions import Normal
from models.model_based import actor_model, critic_model, trans_model, reward_model
from MPC_agent import Memory
import copy
import numpy as np
import random

class OU_Noise(object):
    """Ornstein-Uhlenbeck process."""
    def __init__(self, size, seed=1, mu=0., theta=0.15, sigma=0.2):
        self.mu = mu * np.ones(size)
        self.theta = theta
        self.sigma = sigma
        self.seed = random.seed(seed)
        self.reset()

    def reset(self):
        """Reset the internal state (= noise) to mean (mu)."""
        self.state = copy.copy(self.mu)

    def sample(self):
        """Update internal state and return it as a noise sample."""
        dx = self.theta * (self.mu - self.state) + self.sigma * np.array(
            [np.random.normal() for _ in range(len(self.state))])
        self.state += dx
        return self.state

class OU_Noise_Exploration(object):
    """Ornstein-Uhlenbeck noise process exploration strategy"""
    def __init__(self, action_dim):
        self.noise = OU_Noise(action_dim)

    def perturb_action_for_exploration_purposes(self, action):
        """Perturbs the action of the agent to encourage exploration"""
        action += self.noise.sample()
        return action

    def reset(self):
        """Resets the noise process"""
        self.noise.reset()

class MVE_agent():
    """ A MVE Agent """
    def __init__(self, conf):
        self.conf = conf
        #self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
        self.device = 'cpu'
        """ model parameters"""
        self.num_random = self.conf.train.num_random  # number of first random trails
        self.tau = self.conf.MVE.target_model_update_rate
        self.gamma = self.conf.train.gamma  # reward discount
        self.T = self.conf.MVE.horizon  # forward predict steps
        self.trail_len = self.conf.train.trail_len  # steps in each trail
        self.batch_size = self.conf.data.mem_batchsize
        self.iter_num = self.conf.MVE.iteration_num  # iteration num after selecting an action
        self.dim_state = self.conf.data.state.dim
        self.dim_action = self.conf.data.action.dim
        self.dim_state_action = self.dim_state + self.dim_action
        self.up_X = torch.tensor(self.conf.data.state.high).expand(self.batch_size, -1)
        self.low_X = torch.tensor(self.conf.data.state.low).expand(self.batch_size, -1)

        """ models"""
        self.trans_model = trans_model(self.dim_state,
                                       self.dim_action).to(self.device)
        self.reward_model = reward_model(self.dim_state,
                                         self.dim_action).to(self.device)
        self.critic_local = critic_model(self.dim_state,
                                         self.dim_action).to(self.device)
        self.critic_target = critic_model(self.dim_state,
                                          self.dim_action).to(self.device)
        self.copy_model_over(self.critic_local, self.critic_target)
        self.actor_local = actor_model(self.dim_state,
                                       self.dim_action).to(self.device)
        self.actor_target = actor_model(self.dim_state,
                                        self.dim_action).to(self.device)
        self.copy_model_over(self.actor_local, self.actor_target)
        self.memory = Memory(self.conf.data.mem_capacity)
        self.optimizer_t = optim.Adam(self.trans_model.parameters(), lr=self.conf.train.mb_t_lr)
        self.optimizer_r = optim.Adam(self.reward_model.parameters(), lr=self.conf.train.mb_r_lr)
        self.optimizer_c = optim.Adam(self.critic_local.parameters(), lr=self.conf.train.mf_c_lr,
                                    weight_decay = 0.01)
        self.optimizer_a = optim.Adam(self.actor_local.parameters(), lr=self.conf.train.mf_a_lr)
        self.exploration_strategy = OU_Noise_Exploration(self.dim_action)
        self.training_step = 0
        if self.conf.GTMBMF.reduction_type == "direct_fixed":
            self.backward = 0
        else:
            self.backward = 1
        self.max_grad_norm = 0.01
        if self.conf.GTMBMF.reduction_type == "direct_fixed":
            self.backward = 0
        else:
            self.backward = 1

    def select_action(self, state, exploration=True):
        """Picks an action using the actor network and then adds some noise to it to ensure exploration"""
        state = state.unsqueeze(0).to(self.device)
        self.actor_local.eval()
        with torch.no_grad():
            action = self.actor_local(state).cpu().data.numpy()
        self.actor_local.train()
        if exploration:
            action = self.exploration_strategy.perturb_action_for_exploration_purposes(
                action)
        return action.squeeze(0)

    def store_transition(self, transition):
        self.memory.update(transition)

    def sample_transitions(self, num_trans=None):
        """random sample certain number (default: batchsize) of transitions from Memory"""
        if num_trans is not None:
            batch_size = num_trans
        else:
            batch_size = self.batch_size

        transitions = self.memory.sample(batch_size)
        s = torch.from_numpy(
            np.vstack((t.s for t in transitions
                       if t is not None))).float().to(self.device)
        a = torch.tensor([t.a for t in transitions], dtype=torch.float).view(
            -1, self.dim_action).to(self.device)
        s_a = torch.tensor([t.s_a for t in transitions],
                           dtype=torch.float).view(
                               -1, self.dim_state_action).to(self.device)
        s_ = torch.tensor([t.s_ for t in transitions], dtype=torch.float).view(
            -1, self.dim_state).to(self.device)
        r = torch.tensor([t.r for t in transitions],
                         dtype=torch.float).view(-1, 1).to(self.device)
        return s, a, s_a, r, s_,

    def update(self):
        """ update transition, reward, actor, critic model"""
        self.training_step += 1
        for _ in range(self.iter_num):
            s, a, s_a, r, s_ = self.sample_transitions()
            trans_loss = self.trans_learn(s_a, s_)
            reward_loss = self.reward_learn(s_a, r)
            actor_loss = self.actor_learn(s)
            critic_loss = self.critic_learn(s_a, r, s_)

        return trans_loss, reward_loss, actor_loss, critic_loss

    def trans_learn(self, states_actions, next_states):
        """Runs a learning iteration for the transition model"""
        states_pred = self.trans_model(states_actions).to(self.device)
        trans_loss = F.mse_loss(states_pred, next_states)
        self.optimizer_t.zero_grad()
        trans_loss.backward()
        self.optimizer_t.step()

        return trans_loss.item()

    def reward_learn(self, states_actions, rewards):
        """ update reward model"""
        reward_pred = self.reward_model(states_actions).to(self.device)
        reward_loss = F.mse_loss(reward_pred, rewards)
        self.optimizer_r.zero_grad()
        reward_loss.backward()
        self.optimizer_r.step()

        return reward_loss.item()

    def actor_learn(self, states):
        """Runs a learning iteration for the actor"""
        actions_pred = self.actor_local(states).to(self.device)
        actor_loss = -self.critic_local(torch.cat(
            (states, actions_pred), 1)).to(self.device).mean()
        self.optimizer_a.zero_grad()
        actor_loss.backward()
        nn.utils.clip_grad_norm_(self.actor_local.parameters(),
                                 self.max_grad_norm)
        self.optimizer_a.step()
        self.soft_update_of_target_network(self.actor_local, self.actor_target,
                                           self.tau)

        return actor_loss.item()

    def critic_learn(self, states_actions, rewards, next_states):
        """Runs a learning iteration for the critic"""
        imag_rewards_list = [rewards]
        # compute Q(s^t, a^t) for t~[-1,T]
        critic_pred = torch.empty(self.batch_size,
                                  self.T + 1,
                                  dtype=torch.float)
        critic_pred[:, 0:1] = self.critic_local(states_actions)

        for t in range(1, self.T + 1):  # model-based: predict T steps forward
            states = next_states
            with torch.no_grad():
                actions = self.actor_target(states)
                actions = torch.clamp(actions, -1, 1)
            states_actions = torch.cat((states, actions), 1)
            critic_pred[:, t:t + 1] = self.critic_local(states_actions)
            next_states = self.trans_model(states_actions)
            next_states = torch.max(torch.min(next_states, self.up_X),
                                    self.low_X)
            rewards = self.reward_model(states_actions)
            imag_rewards_list.append(rewards)

        critic_pred = critic_pred[:, :-1]  # Q(s^t,a^t), t~[-1,T-1]
        final_states = states  # s_T
        with torch.no_grad():
            final_actions = self.actor_target(final_states)  # a_T
            final_critic = self.critic_target(
                torch.cat((final_states, final_actions), 1))  # Q'(s_T,a_T)
            # compute sum of discounted reward and ternimal cost for each timestep t~[-1,T-1]
            critic_target = torch.empty(self.batch_size,
                                        self.T,
                                        dtype=torch.float)
            critic_target[:, self.T - 1:self.T] = imag_rewards_list[
                self.T - 1] + self.gamma * final_critic
            for t in range(self.T - 1, -1, -1):
                critic_target[:, t - 1:t] = imag_rewards_list[
                    t - 1] + self.gamma * critic_target[:, t:t + 1]
        critic_loss = F.mse_loss(critic_pred, critic_target) / (self.T)
        self.optimizer_c.zero_grad()
        critic_loss.backward()
        nn.utils.clip_grad_norm_(self.critic_local.parameters(),
                                 self.max_grad_norm)
        self.optimizer_c.step()
        self.soft_update_of_target_network(self.critic_local,
                                           self.critic_target, self.tau)

        return critic_loss.item()

    def soft_update_of_target_network(self, local_model, target_model, tau):
        """Updates the target network in the direction of the local network but by taking a step size
        less than one so the target network's parameter values trail the local networks. This helps stabilise training"""
        for target_param, local_param in zip(target_model.parameters(),
                                             local_model.parameters()):
            target_param.data.copy_(tau * local_param.data +
                                    (1.0 - tau) * target_param.data)

    @staticmethod
    def copy_model_over(from_model, to_model):
        """Copies model parameters from from_model to to_model"""
        for to_model, from_model in zip(to_model.parameters(),
                                        from_model.parameters()):
            to_model.data.copy_(from_model.data.clone())


from machine import PWM, ADC, Pin
from time import sleep

adc = ADC(Pin(26))
pwmin = Pin(26)
#p2 = Pin(26, Pin.IN, Pin.PULL_UP)

def ardu_map(val, in_min, in_max, out_min, out_max):
    return max(min(out_max,(val - in_min) * (out_max - out_min) // (in_max - in_min) + out_min), out_min)

while True:
    read_val = adc.read_u16()
    print(read_val)
    #print(red)
    sleep(0.1)


import re
import json

pa=re.compile(r'^0\d{6}$')

ids=[]
with open('grades.csv', encoding='utf-8') as inp:
	with open('ids.json', 'w', encoding='utf-8') as out:
		for l in inp:
			if(len(l)<7):
				continue
			l=l.replace('\n', '').split(',')
			if not pa.match(l[2]):
				continue
			ids+=[l[2]]
		json.dump(ids, out, indent='\t')

print('totally '+str(len(ids))+' ids')


from django.conf.urls.defaults import patterns, url
import views

urlpatterns = patterns('',
    url(r'^$', views.index, name='report_index'),
    url(r'^search/$', views.search, name='report_search'),
    url(r'^create/$', views.create, name='report_create'),
    url(r'^create/(?P<tag>[a-zA-Z_]+)/$', views.create, name='tagged_report_create'),
   # url(r'^create/thanks/$', views.thanks, name='report_thanks'),
    url(r'^(?P<report_id>\d+)/$', views.view, name='report_view'),
    url(r'^(?P<report_id>\d+)/edit/$', views.edit, name='report_edit'),
    url(r'^(?P<report_id>\d+)/delete/$', views.delete, name='report_delete'),
    url(r'^(?P<report_id>\d+)/comment/$', views.comment, name='comment_report'),
    url(r'^(?P<report_id>\d+)/comment/(?P<comment_id>\d+)/edit/$', views.comment_edit, name='comment_report_edit'),
    url(r'^(?P<tag>[a-zA-Z_]+)/(?P<report_id>\d+)/$', views.view, name='tagged_report_view'),
    url(r'^(?P<tag>[a-zA-Z_]+)/(?P<report_id>\d+)/edit/$', views.edit, name='tagged_report_edit'),
    url(r'^(?P<tag>[a-zA-Z_]+)/(?P<report_id>\d+)/delete/$', views.delete, name='tagged_report_delete'),
    url(r'^(?P<tag>[a-zA-Z_]+)/(?P<report_id>\d+)/comment/$', views.comment, name='tagged_comment_report'),
    url(r'^(?P<tag>[a-zA-Z_]+)/(?P<report_id>\d+)/comment/(?P<comment_id>\d+)/edit/$', views.comment_edit, name='tagged_comment_report_edit'),
    url(r'^(?P<tag>[a-zA-Z_]+)/(?P<report_id>\d+)/$', views.view, name='tagged_report_view'),
)


import socket
import numpy as np

class ActiveTwo():
    """
    Main class which implements major functions needed for communication with BioSemi ActiveTwo device
    """

    #: Host where ActiView acquisition software is running
    host = None

    #: This is the port ActiView listens on
    port = None

    #: Number of channles
    nchannels = None

    #: Data packet size (default: 32 channels @ 512Hz)
    buffer_size = None

    def __init__(self, host='127.0.0.1', sfreq=512, port=778, nchannels=32, tcpsamples=4):
        """
        Initialize connection and parameters of the signal
        :param host: IP address where ActiView is running
        :param port: Port ActiView is listening on
        :param nchannels: Number of EEG channels
        """

        # store parameters
        self.host = host
        self.port = port
        self.nchannels = nchannels
        self.sfreq = sfreq
        self.tcpsamples = tcpsamples
        self.buffer_size = self.nchannels * self.tcpsamples * 3

        # open connection
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.s.connect((self.host, self.port))

    def read(self, duration):
        """
        Read signal from the EEG device
        :param duration: How long to read in seconds
        :return: Signal in the matrix form: samples x channels
        """

        # initialize final data array
        rawdata = np.empty((0,32))

        # The reader process will run until requested amount of data is collected
        samples = 0
        while samples < duration * self.sfreq:

            # Create a 16-sample signal_buffer
            signal_buffer = np.zeros((self.nchannels, self.tcpsamples))

            # Read the next packet from the network
            # sometimes there is an error and packet is smaller than needed, read until get a good one
            data = []
            while len(data) != self.buffer_size:
                data = self.s.recv(self.buffer_size)

            # Extract 16 samples from the packet (ActiView sends them in 16-sample chunks)
            for m in range(self.tcpsamples):

                # extract samples for each channel
                for ch in range(self.nchannels):
                    offset = m * 3 * self.nchannels + (ch * 3)

                    # The 3 bytes of each sample arrive in reverse order
                    sample = (ord(data[offset+2]) << 16)
                    sample += (ord(data[offset+1]) << 8)
                    sample += ord(data[offset])

                    # Store sample to signal buffer
                    signal_buffer[ch, m] = sample

            # update sample counter
            samples += self.tcpsamples

            # transpose matrix so that rows are samples
            signal_buffer = np.transpose(signal_buffer)

            # add to the final dataset
            rawdata = np.concatenate((rawdata, signal_buffer), axis=0)

        return rawdata


nums_str = input().split(", ")
beggers_count = int(input())
numbers = []
beggers = []
for num_str in nums_str:
    number = int(num_str)
    numbers.append(number)

for i in range(beggers_count):
    beggers.append(0)
index = 0
for number in numbers:
    beggers[index] += number
    index += 1
    if index == beggers_count:
        index = 0
print(beggers)


# Lab 14: Secretary problem helper functions
# Your name
# Your email

import numpy as np

def simulate(r):
    """
    Simulate the outcome of a Secretary problem.

    INPUT ARGUMENTS
        r:  Rejection ratio (proportion of applicants to reject initially)

    RETURN VALUE
        True if the best applicant was hired, False otherwise.
    """

    # generate list of random scores
    n = 100                               # number of applicants
    score = np.random.rand(n)             # list of n random scores

    # reject initial applicants
    n_rejected = int(n * r)               # number of initial applicants rejected
    best_score = max(score[:n_rejected])  # best score among rejected

    # keep interviewing while next applicant doesn't score better and there are applicants remaining
    i = n_rejected    # next applicant to interview
    while score[i] <= best_score and i < n-1:
        i += 1
    # at the end of the loop, i will be the index of the hired applicant

    # return whether or not the hired applicant was the true best applicant
    return i == np.argmax(score)

def monte_carlo(m, r):
    """
    Use Monte Carlo simulate to estimate the success rate for a Secretary problem.

    INPUT ARGUMENTS
        m:  Number of samples to simulate.
        r:  Rejection ratio (proportion of applicants to reject initially)

    RETURN VALUE
        The success rate (proportion of optimal hires) across all simulated samples.
    """
    return np.mean([ simulate(r) for i in range(m) ])


"""
  Invoice JSON Token Generator
"""
import json

def create(input_fn, output_fn):
    """ ... """
    with open(input_fn, encoding="utf-8") as ifn:
        data = json.load(ifn)

    for key, value in data.items():
        data[key] = '#' + str(key) + ' ' + str(value) + ' #' + str(key)

    with open(output_fn, 'w', encoding="utf-8") as ofn:
        json.dump(data, ofn, ensure_ascii=False)


import numpy as np
from . import Misc
from . import Wavefunctions

class VSCF(object):
    """
    The parent class for VSCF.
    G{classtree}
    The class must be initialized with grids and potentials

    Parameters
    ----------
    potentials : Vibrations.Potential Object
       The potentials.
    nmodes : int
       number of modes.
    ngrid : int
       number of grid points.
    nstates : int
       number of states.
    wavefunction : object
       Vibrations.Wavefunctions.Wavefunction object.
    eigv : ndarray
       matrix of eigenvectors
    grids : object
       Vibrations.Grid object
    dx : array
       integration measure.
    solve : bool
       check of VSCF was already solved.
    maxpot : int
       array size of potential array.
    """

    def __init__(self, *potentials):  # always initialized with (some) potentials, grids are stored in the potentials
        """
        The class must be initialized with grids and potentials
        """
        if len(potentials) > 0:
            self.nmodes = potentials[0].grids.nmodes
            self.ngrid = potentials[0].ngrid
            self.nstates = self.ngrid
            self.wavefunction = Wavefunctions.Wavefunction(potentials[0].grids)
            self.eigv = np.zeros((self.nmodes, self.nstates))
            self.grids = potentials[0].grids
            self.dx = [x[1]-x[0] for x in self.grids.grids]  # integration step
            self.solved = False  # simple switch to check, whether VSCF was already solved
            self.maxpot = len(potentials)
        else:
            raise Exception("No potential given.")

    def _collocation(self, grid, potential):
        """
        The collocation method, see Chem. Phys. Lett., 153(1988), 98. for details.

        Parameters
        ----------
        grid : Vibrations.Grid Object
            Grid.
        potential : ndarray
           Array from the Attribute data of the Vibrations.Potential object.
           Example:
           >>> vscf._collaction(grid,v1.data[0])

        Returns
        -------
        eigval : array
        Eigenvalue of the hamiltonian.
        phi : ndarray
        phi = (eigenvector of hamiltonian) times wavefunctions - normalized.
        """
        # some basis set parameters
        c = 0.7
        a = c**2/((grid[1]-grid[0])**2)
        # end of parameters

        wfn = np.zeros((self.ngrid, self.ngrid))

        matg = np.zeros((self.ngrid, self.ngrid))

        fac = (2.0*a/np.pi)**0.25

        for i in range(self.ngrid):
            for j in range(self.ngrid):
                wfn[i, j] = fac * np.exp(-a*(grid[j]-grid[i])**2)
                dr2 = (4.0*(a**2)*((grid[j]-grid[i])**2))-2.0*a
                matg[i, j] = -0.5*dr2*wfn[i, j]

        # create potential matrix from a vector
        matv = np.diagflat(potential)
        # inverse matrix of wfn (R in paper)
        invwfn = np.linalg.inv(wfn)

        # multiply G and inverted wfn
        matgr = np.dot(matg, invwfn)

        # generate hamiltonian
        hamiltonian = matgr + matv

        # solve the Hamiltonian

        #(eigval, eigvec) = np.linalg.eigh(hamiltonian,UPLO='U')
        (eigval, eigvec) = np.linalg.eig(hamiltonian)
        eigval = np.real(eigval)
        eigvec = np.real(eigvec)

        # sort eigenvalues and eigenvectors with respect to the eigenvalues

        idx = eigval.argsort()
        eigval = eigval[idx]
        eigvec = eigvec[:, idx]

        # find wave functions
        phi = np.zeros((self.ngrid, self.ngrid))

        for i in range(self.ngrid):
            for j in range(self.ngrid):
                phi[i, j] = eigvec[j, i]*wfn[j, j]

        # correct the sings and norm the wave function

        for i in range(self.ngrid):
            psum = phi[i, :].sum()

            if i % 2 == 0 and psum < 0:
                phi[i, :] = -phi[i, :]

            elif i % 2 != 0 and psum > 0:
                phi[i, :] = -phi[i, :]

            phi[i, :] = self._norm(phi[i, :], grid[1]-grid[0])

        return eigval, phi

    def _norm(self, phi, dx):
        """
        Norms the wavefunction.

        Parameters
        ----------
        phi : ndarray
        phi = (eigenvector of hamiltonian) times wavefunctions. - Normalized
        dx : array
           Integration measure dx.

        Returns
        -------
        phi : ndarray
        normalized phi = (eigenvector of hamiltonian) times wavefunctions.
        """

        wnorm = 0.0

        for i in range(self.ngrid):
            wnorm += dx*phi[i]**2

        normphi = np.array([x * 1.0/np.sqrt(wnorm) for x in phi])

        # check norm

        #p = 0.0
        #p = (normphi**2 * dx).sum()
        #if p <> 1.0:
        #    raise Exception('Something went wrong with wave function normalization')

        return normphi

    def get_wave_functions(self):
        """
        Returns the wave functions as numpy.array

        Returns
        -------
        wavefunction.wfns : ndarray
            wavefunctions of the Vibrations.Wavefunction object.
        """

        return self.wavefunction.wfns

    def get_wave_function_object(self):
        """
        Returns the wave functions as Vibrations/Wavefunction object

        Returns
        -------
        wavefunction : Vibrations.Wavefunction object
            Wavefunction object.
        """
        return self.wavefunction

    def save_wave_functions(self, fname='wavefunctions'):
        """
        Saves the wave functions to a NumPy formatted binary file `*.npy`.

        Parameters
        ----------
        fname : str
            File name without extension and a time stamp is added.
        """
        from time import strftime
        fname = fname + '_' + strftime('%Y%m%d%H%M') + '.npy'
        np.save(fname, self.wavefunction.wfns)

class VSCFDiag(VSCF):
    """
    The class for the diagonal VSCF -- using only 1-mode potentials.

    VSCF - Attributes.
    """

    def __init__(self,*potentials):
        """
        VSCFDiag constructor.
        Further details in class description.
        """

        if len(potentials) == 0:
            raise Exception('No potential given')

        elif len(potentials) > 1:
            print('More than one potentials given, only the first will be used')

        VSCF.__init__(self, potentials[0])  # fist call the constructor of mother class
        self.v1 = potentials[0]

        self.solved = False

    def solve(self):
        """
        Solves the diagonal VSCF.
        """
        if self.solved:
            print('Already solved, nothing to do. See results with print_results() method')

        else:

            for i in range(self.nmodes):  # go over each mode
                #print self.grids[i]
                #print self.v1.data[i]
                v1ind = self.v1.indices.index(i)  #  find the index of the mode i in the  potential
                # TODO take into account that the mode can be not present in the potential, use try etc.
                (tmpeigv, tmpwfn) = self._collocation(self.grids.grids[i], self.v1.data[v1ind])
                self.eigv[i] = tmpeigv
                self.wavefunction.wfns[i] = tmpwfn

            self.solved = True

    def print_results(self):
        """
        Prints the results.
        """
        if self.solved:

            print('Fundamental transitions:')
            for i in range(self.nmodes):
                print('Mode %i, eigv: %f' % (i, (self.eigv[i, 1]-self.eigv[i, 0])/Misc.cm_in_au))

            print('Eigenvalues: ')
            for i in range(self.nmodes):
                print('Mode %i, eigv: %f' % (i, self.eigv[i, 0]/Misc.cm_in_au))
        else:
            print('VSCF not solved yet. Use solve() method first')

    def print_eigenvalues(self):
        """
        Prints the eigenvalues.
        """
        for i in range(self.nmodes):
            print('Mode %i' % i)

            for j in range(self.nstates):
                print(self.eigv[i, j], self.eigv[i, j]/Misc.cm_in_au)

    def save_wave_functions(self, fname='1D_wavefunctions'):
        """
        Saves the wave function to a NumPy formatted binary file `*.npy`.

        Parameters
        ----------
        fname : str
           File name, without extension, time stamp added.
        """
        from time import strftime
        fname = fname + '_' + strftime('%Y%m%d%H%M') + '.npy'
        np.save(fname, self.wavefunction.wfns)

class VSCF2D(VSCF):
    """
    The class for the 2-dimensional VSCF
    -- containing the mean-field potential for modes coupling.

    VSCF - Attributes.
    """
    def __init__(self, *potentials):
        """
        VSCF2D constructor.
        Further details in class description.
        """

        if len(potentials) == 0:
            raise Exception('No potentials given')

        elif len(potentials) == 1:
            raise Exception('Only one set of  potentials given, go to VSCF_diag() class')
        elif len(potentials) > 2:
            print('More than two sets potentials given. Only the two first will be used')

        VSCF.__init__(self, potentials[0])
        import copy
        self.v1 = copy.copy(potentials[0])
        self.v2 = copy.copy(potentials[1])
        self.grids = self.v1.grids
        self.dm1 = np.array([])
        self.dm2 = np.array([])

        #if len(self.v2.shape) < 4:
        #    raise Exception('The second set should consist of two-dimensional potentials')
        #if (self.nmodes != self.v1.shape[0]) or (self.ngrid != self.v1.shape[1]) \
        #   or (self.nmodes != self.v2.shape[0]) or (self.ngrid != self.v2.shape[2]):
        #    raise Exception('Potential and grid size mismatch')

        self.states = [[0]*self.nmodes]   # list of states for which the VSCF is solved, at first only gs considered
        self.energies = []
        self.eigenvalues = []
        self.vscf_wavefunctions = []   # list of Wavefunction objects (for each state)

    def calculate_intensities(self, *dipolemoments):
        """
        Calculates VSCF intensities with dipole moment surfaces

        Parameters
        ----------
        dipolemoments : ndarray
           dipole moment surfaces(object).
        """

        if not self.solved:
            raise Exception('Solve the VSCF first')

        self.dm1 = None
        self.dm2 = None
        if len(dipolemoments) == 0:
            raise Exception('No dipole moments given.')
        elif len(dipolemoments) == 1:
            print('Only one dipole moment surface given, the 2D counterpart will be set to 0.')
            self.dm1 = dipolemoments[0]
        elif len(dipolemoments) == 2:
            self.dm1 = dipolemoments[0]
            self.dm2 = dipolemoments[1]
        elif len(dipolemoments) > 2:
            print('More than two sets of dipole moments given, only the two first will be used.')
            self.dm1 = dipolemoments[0]
            self.dm2 = dipolemoments[1]

#       if dipolemoments[0].order == 1:
#           self.dm1 = dipolemoments[0].dm
#       else:
#           raise Exception('The 1-D DMS should be given as the first one.')
#       if len(dipolemoments) > 1 and dipolemoments[1].order == 2:
#           self.dm2 = dipolemoments[1].dm
#       elif len(dipolemoments) == 1:
#           self.dm2 = np.zeros((self.nmodes, self.nmodes, self.ngrid, self.ngrid, 3))
#       else:
#           raise Exception('The order of the second dipole moment surface does not match.')

        # assuming that the first state is a ground state
        gs = self.states[0]
        print(Misc.fancy_box('VSCF Intensities'))
        print('State        Energy /cm^-1    Intensity /km*mol^-1')
        self.intensities = []
        for s in self.states[1:]:
            tmptm = np.array([0.0, 0.0, 0.0])
            stateindex = self.states.index(s)
            for i in range(self.nmodes):
                tmpd1 = np.array([0.0, 0.0, 0.0])
                tmpovrlp = 1.0
                for j in range(self.nmodes):
                    if j == i:
                        ind = self.dm1.indices.index(j)
                        #calculate <psi|i|psi>
                        tmpd1[0] += (self.dx[i]*self.vscf_wavefunctions[0].wfns[i, gs[i]]*self.vscf_wavefunctions[stateindex].wfns[i, s[i]] *
                                     self.dm1.data[ind][:, 0]).sum()
                        tmpd1[1] += (self.dx[i]*self.vscf_wavefunctions[0].wfns[i, gs[i]]*self.vscf_wavefunctions[stateindex].wfns[i, s[i]] *
                                     self.dm1.data[ind][:, 1]).sum()
                        tmpd1[2] += (self.dx[i]*self.vscf_wavefunctions[0].wfns[i, gs[i]]*self.vscf_wavefunctions[stateindex].wfns[i, s[i]] *
                                     self.dm1.data[ind][:, 2]).sum()

                    else:
                        if s[j] == gs[j]:
                            tmpovrlp *= (self.dx[j]*self.vscf_wavefunctions[0].wfns[j, gs[j]] *
                                         self.vscf_wavefunctions[stateindex].wfns[j, s[j]]).sum()
                            #tmpovrlp *= 1.0
                        else:
                            tmpovrlp = 0.0

                tmptm += tmpd1 * tmpovrlp
                #tmptm = tmptm + tmpd1
            if self.dm2:
                for i in range(self.nmodes):
                    for j in range(i+1, self.nmodes):
                        tmpd2 = np.array([0.0, 0.0, 0.0])

                        for k in range(self.ngrid):
                            ind = self.dm2.indices.index((i,j))
                            for l in range(self.ngrid):
                                tmpd2[0] += self.dx[i] * self.dx[j] * self.dm2.data[ind][k, l, 0] \
                                    * self.vscf_wavefunctions[0].wfns[i, gs[i], k] \
                                    * self.vscf_wavefunctions[0].wfns[j, gs[j], l] \
                                    * self.vscf_wavefunctions[stateindex].wfns[i, s[i], k] \
                                    * self.vscf_wavefunctions[stateindex].wfns[j, s[j], l]
                                tmpd2[1] += self.dx[i] * self.dx[j] * self.dm2.data[ind][k, l, 1] \
                                    * self.vscf_wavefunctions[0].wfns[i, gs[i], k] \
                                    * self.vscf_wavefunctions[0].wfns[j, gs[j], l] \
                                    * self.vscf_wavefunctions[stateindex].wfns[i, s[i], k] \
                                    * self.vscf_wavefunctions[stateindex].wfns[j, s[j], l]
                                tmpd2[2] += self.dx[i] * self.dx[j] * self.dm2.data[ind][k, l, 2] \
                                    * self.vscf_wavefunctions[0].wfns[i, gs[i], k] \
                                    * self.vscf_wavefunctions[0].wfns[j, gs[j], l] \
                                    * self.vscf_wavefunctions[stateindex].wfns[i, s[i], k] \
                                    * self.vscf_wavefunctions[stateindex].wfns[j, s[j], l]
                        tmpovrlp = 1.0
                        for m in range(self.nmodes):
                            if m != i and m != j:
                                if s[m] == gs[m]:
                                    tmpovrlp *= (self.dx[m]*self.vscf_wavefunctions[0].wfns[m, gs[m]]
                                                 * self.vscf_wavefunctions[stateindex].wfns[ m, s[m]]).sum()

                                else:
                                    tmpovrlp = 0.0

                        tmptm += tmpd2 * tmpovrlp
                        #tmptm = tmptm + tmpd2
            factor = 2.5048
            intens = (tmptm[0]**2 + tmptm[1]**2 + tmptm[2]**2)*factor*(self.energies[stateindex]-self.energies[0])
            self.intensities.append(intens)
            print('%s %7.1f %7.1f' % (s, self.energies[stateindex]-self.energies[0], intens))
        self.intensities = np.array(self.intensities)

    def get_groundstate_wfn(self):
        """
        Returns the ground state wave function, which can be used for VCI calculations.
        """
        if self.states[0] == [0]*self.nmodes and self.solved:
            return self.vscf_wavefunctions[0]
        else:
            raise Exception('Ground state not solved')

#TODO: vscf_wfns???
    def save_wave_functions(self, fname='2D_wavefunctions'):
        """
        Saves the wave functions to a NumPy formatted binary file `*.npy`.

        Parameters
        ----------
        fname : Str
           File name
        """
        from time import strftime
        fname = fname + '_' + strftime('%Y%m%d%H%M') + '.npy'
        fname2 = 'States_' + fname
        np.save(fname, self.vscf_wfns)
        np.save(fname2, np.array(self.states))  # list of states in wave_function file

    def solve_singles(self):
        """
        Solves the VSCF for the ground state and all singly-excited states.
        """
        gs = [0]*self.nmodes
        states = [gs]

        for i in range(self.nmodes):
            vec = [0]*self.nmodes
            vec[i] = 1
            states.append(vec)

        self.solve(*states)

    def solve(self, *states):
        """
        Solves the VSCF for given states.

        Parameters
        ----------
        states : List of Lists of Ints
           considered states, the first given is assumed to be the ground state.
        """
        if len(states) == 0:
            states = [[0]*self.nmodes]  # if no states defined, only gs considered

        if self.solved and self.states == list(states):
            print('Already solved, nothing to do. See results with print_results() method')

        else:
            print('')
            print(Misc.fancy_box('Solving VSCF'))
            self.states = list(states)  # use new states and do the VSCF
            self.energies = []
            self.vscf_wavefunctions = []
            for i, s in enumerate(self.states):
                print(Misc.fancy_box('Solving State: '+str(s)))
                (energy, wfn, eigenvalues) = self._solve_state(s)
                self.energies.append(energy)
                wfn_obj = Wavefunctions.Wavefunction(self.v1.grids)
                wfn_obj.wfns = wfn
                self.vscf_wavefunctions.append(wfn_obj)
                self.eigenvalues.append(eigenvalues)

            self.solved = True
            print('')
            print(Misc.fancy_box('VSCF Done'))
            print('')
            self.print_results()

    def print_results(self):
        """
        Prints the results.
        """
        if self.solved:
            print('')
            print(Misc.fancy_box('VSCF Results'))
            print('VSCF states energies in cm^-1')
            print('---------------------------')
            for i, s in enumerate(self.states):
                print(s, '%.1f' % self.energies[i])
            print('')
            print('Initial state: ', self.states[0])
            print('Transition energies in cm^-1')
            for i, s in enumerate(self.states):
                if i != 0:
                    print('-> ', s, '%.1f' % (self.energies[i]-self.energies[0]))
        else:
            print('VSCF not solved yet. Use solve() method first')

    def _solve_state(self, state):
        """internal function - solving 2D VSCF for a given state"""
        maxiter = 100
        eps = 1e-8
        etot = 0.0
        actualwfns = np.zeros((self.nmodes,self.ngrid,self.ngrid))
        tmpwfns = np.zeros((self.nmodes,self.ngrid,self.ngrid))

        # first generate a diagonal wave function as a reference
        for i in range(self.nmodes):
            (modeen, modewfn) = self._collocation(self.grids.grids[i], self.v1.data[self.v1.indices.index(i)])
            actualwfns[i] = modewfn

        eprev = 0.0
        for niter in range(maxiter):
            etot = 0.0
            eigenvalues = []
            print('Iteration: %i ' % (niter+1))
            print('Mode State   Eigv')
            for i in range(self.nmodes):
                diagpot = self.v1.data[self.v1.indices.index(i)]
                # now get effective potential
                effpot = self._veffective(i, state, actualwfns)
                totalpot = diagpot+effpot
                # solve 1-mode problem
                (energies, wavefunction) = self._collocation(self.grids.grids[i], totalpot)
                eigenvalues.append(energies)
                tmpwfns[i] = wavefunction
                # add energy
                etot += energies[state[i]]   # add optimized state-energy
                print('%4i %5i %8.1f' % (i+1, state[i], energies[state[i]]/Misc.cm_in_au))

            #calculate correction
            actualwfns = tmpwfns
            emp1 = self._scfcorr(state, actualwfns)
            print('Sum of eigenvalues %.1f, SCF correction %.1f, total energy %.1f / cm^-1' \
                % (etot/Misc.cm_in_au,
                  emp1/Misc.cm_in_au,
                  (etot - emp1)/Misc.cm_in_au))
            etot -= emp1
            print('')
            if abs(etot-eprev) < eps:
                break
            else:
                eprev = etot

            # get delta E

        return etot / Misc.cm_in_au, actualwfns.copy(), eigenvalues

    def _scfcorr(self,state,wfns):
        """internal function - calculate scfcorr."""
        scfcorr = 0.0
        for i in range(self.nmodes):
            s1 = (self.dx[i]*wfns[i,state[i]]**2)
            for j in range(i+1, self.nmodes):
                s2 = (self.dx[j]*wfns[j,state[j]]**2)
                try:
                    v2 = self.v2[i,j]
                except:
                    pass
                else:
                    s = np.einsum('i,j,ij',s1,s2,v2)
                    scfcorr += s
        return scfcorr

    def _veffective(self, mode, state, wfns):
        """internal function - calculates veff"""
        veff = np.zeros(self.ngrid)

        for j in range(self.nmodes):
            sj = (self.dx[j]*wfns[j,state[j]]**2)
            try:
                v2 = self.v2[mode,j]
            except:
                pass
            else:
                for i in range(self.ngrid):
                    veff[i] += np.einsum('l,l',sj,v2[i,:])

#       for i in range(self.ngrid):
#           for j in range(self.nmodes):

#               sj = (self.dx[j]*wfns[j,state[j]]**2)
#               try:
#                   v2 = self.v2[mode,j][i,:]
#               except:
#                   pass
#               else:
#                   veff[i] += np.einsum('l,l',sj,v2)

        return veff

class VSCF3D(VSCF2D):

    def __init__(self, *potentials):
        """
        VSCF3D constructor.
        Further details in class description.
        """
        VSCF2D.__init__(self,*potentials)
        import copy
        self.v3 = copy.copy(potentials[2])

    def _scfcorr(self,state,wfns):
        """internal function - calculates scfcorr."""
        scfcorr = 0.0
        for i in range(self.nmodes):
            s1 = (self.dx[i]*wfns[i,state[i]]**2)
            for j in range(i+1, self.nmodes):
                s2 = (self.dx[j]*wfns[j,state[j]]**2)
                try:
                    v2 = self.v2[i,j]
                except:
                    pass
                else:
                    s = np.einsum('i,j,ij',s1,s2,v2)
                    scfcorr += s
                for k in range(j+1, self.nmodes):
                    s3 = (self.dx[k]*wfns[k,state[k]]**2)
                    try:
                        v3 = self.v3[i,j,k]
                    except:
                        pass
                    else:
                        s = np.einsum('i,j,k,ijk',s1,s2,s3,v3)
                        scfcorr += 2.0 * s

        return scfcorr

    def _veffective(self, mode, state, wfns):
        """internal function - calculates veff."""
        veff = np.zeros(self.ngrid)
        for j in range(self.nmodes):
            sj = (self.dx[j]*wfns[j,state[j]]**2)
            try:
                v2 = self.v2[mode,j]
            except:
                pass
            else:
                for i in range(self.ngrid):
                    veff[i] += np.einsum('l,l',sj,v2[i,:])
            for k in range(j+1, self.nmodes):
                sk = (self.dx[k]*wfns[k,state[k]]**2)
                try:
                    v3 = self.v3[mode,j,k]
                except:
                    pass
                else:
                    for i in range(self.ngrid):
                        s = np.einsum('l,m,lm',sj,sk,v3[i,:,:])
                        veff[i] += s

        return veff

class VSCF4D(VSCF3D):

    def __init__(self, *potentials):
        """
        VSCF4D constructor.
        Further details in class description.
        """
        VSCF3D.__init__(self, *potentials)
        import copy
        self.v4 = copy.copy(potentials[3])

    def _scfcorr(self,state,wfns):
        """internal function - calcualtes scfcorr"""
        scfcorr = 0.0
        for i in range(self.nmodes):
            s1 = (self.dx[i]*wfns[i,state[i]]**2)
            for j in range(i+1, self.nmodes):
                s2 = (self.dx[j]*wfns[j,state[j]]**2)
                try:
                    v2 = self.v2[i,j]
                except:
                    pass
                else:
                    s = np.einsum('i,j,ij',s1,s2,v2)
                    scfcorr += s

                for k in range(j+1, self.nmodes):
                    s3 = (self.dx[k]*wfns[k,state[k]]**2)
                    try:
                        v3 = self.v3[i,j,k]
                    except:
                        pass
                    else:
                        s = np.einsum('i,j,k,ijk',s1,s2,s3,v3)
                        scfcorr += 2.0 * s

                    for l in range(k+1, self.nmodes):
                        s4 = (self.dx[l]*wfns[l,state[l]]**2)
                        try:
                            v4 = self.v4[i,j,k,l]
                        except:
                            pass
                        else:
                            s = np.einsum('i,j,k,l,ijkl',s1,s2,s3,s4,v4)
                            scfcorr += 3.0 * s

        return scfcorr

    def _veffective(self, mode, state, wfns):
        """internal function - calculates veff."""
        veff = np.zeros(self.ngrid)

        for j in range(self.nmodes):
            sj = (self.dx[j]*wfns[j,state[j]]**2)
            try:
                v2 = self.v2[mode,j]
            except:
                pass
            else:
                for i in range(self.ngrid):
                    veff[i] += np.einsum('l,l',sj,v2[i,:])

            for k in range(j+1, self.nmodes):
                sk = (self.dx[k]*wfns[k,state[k]]**2)
                try:
                    v3 = self.v3[mode,j,k]
                except:
                    pass
                else:
                    for i in range(self.ngrid):
                        s = np.einsum('l,m,lm',sj,sk,v3[i,:,:])
                        veff[i] += s

                for l in range(k+1, self.nmodes):
                    sl = (self.dx[l]*wfns[l,state[l]]**2)
                    try:
                        v4 = self.v4[mode,j,k,l]
                    except:
                        pass
                    else:
                        for i in range(self.ngrid):
                            s = np.einsum('l,m,n,lmn',sj,sk,sl,v4[i,:,:,:])
                            veff[i] += s

        return veff


"""Autor:  Orlando Urbano Trejo (Lando)
   Fecha:  28-07-2023
   Correo: urbanoorlando79@gmail.com

Ejercicio: Convierte a mayuscula cualquier cadena de texto """

Texto = input("Ingresa una cadena de texto: ")
Mayuscula = Texto.upper()
print("Texto en mayúsculas:", Mayuscula)


import os
import logging
import importlib
import torch
import torch.distributed as dist
import hydra
from omegaconf import DictConfig
from hydra.core.hydra_config import HydraConfig

from guided_diffusion import dist_util
from ood_tester.classifier_model import load_classifier
from ood_tester.dataloader import get_dataloader, get_ood_dataloader
from ood_tester.test_runner import TestRunner
from external.pytorch_grad_cam import grad_cam
from testOOD.test_openood import fix_seed

def setup(rank, world_size, init_method, port="12345"):
    if init_method.startswith("env://"):
        os.environ["MASTER_ADDR"] = "localhost"
        os.environ["MASTER_PORT"] = port
    # this is important to use dist_util
    os.environ["CUDA_VISIBLE_DEVICES"] = f"{rank}"
    dist.init_process_group(
        "nccl", rank=rank, world_size=world_size, init_method=init_method)

@hydra.main(version_base=None, config_path="conf", config_name="config")
def main(cfg: DictConfig):
    # only log debug info to log file
    logging.getLogger().setLevel(logging.DEBUG)
    for handler in logging.getLogger().handlers:
        if isinstance(handler, logging.FileHandler):
            handler.setLevel(logging.DEBUG)
        else:
            handler.setLevel(logging.INFO)
    logging.debug("start!")
    logging.getLogger('PIL').setLevel(logging.WARNING)
    setattr(cfg, "log_root", HydraConfig.get().runtime.output_dir)
    setattr(cfg, "rank", 0)
    setup(0, 1, "env://")

    local_rand_gen = fix_seed(cfg.seed)

    classifier = load_classifier(**cfg.classifier.params)
    classifier = classifier.to(dist_util.dev())
    classifier.eval()
    logging.info("classifier loaded")

    # if we do not need cam, do not call it.
    if cfg.diffusion.use_cam:
        target_layers = [eval(f"classifier.model.{cfg.classifier.cam_layer}")]
        cam = grad_cam.GradCAM(
            model=classifier, target_layers=target_layers, use_cuda=True,
            norm_each=False)
    else:
        cam = None

    module, cls = cfg.diffusion.target.rsplit(".", 1)
    diffusion_model = getattr(
        importlib.import_module(module, package=None), cls)(
            config=cfg.diffusion, cam=cam, local_rand_gen=local_rand_gen)
    diffusion_model.to(dist_util.dev())
    if hasattr(diffusion_model, "log_inter_every"):
        diffusion_model.log_inter_every = 5
    logging.info("diffusion loaded")

    dataloader = get_dataloader(cfg)
    # ood_dataloader = get_ood_dataloader(cfg)
    logging.info("dataset loaded")

    runner = TestRunner(cfg)
    logging.info("start testing")
    runner.run(diffusion_model, classifier, dataloader, {})

if __name__ == "__main__":
    torch.hub.set_dir("../pretrained/torch_cache")
    main()


from horovod.spark.lightning import TorchModel
import numpy as np
import torch
from horovod.spark.lightning import TorchModel
from synapse.ml.dl.PredictionParams import TextPredictionParams
from pyspark.ml.param import Param, Params, TypeConverters
from pyspark.sql.functions import col, udf
from pyspark.sql.types import DoubleType
from synapse.ml.dl.utils import keywords_catch
from transformers import AutoTokenizer

class DeepTextModel(TorchModel, TextPredictionParams):

    tokenizer = Param(Params._dummy(), "tokenizer", "tokenizer")

    checkpoint = Param(
        Params._dummy(), "checkpoint", "checkpoint of the deep text classifier"
    )

    max_token_len = Param(Params._dummy(), "max_token_len", "max_token_len")

    @keywords_catch
    def __init__(
        self,
        history=None,
        model=None,
        input_shapes=None,
        optimizer=None,
        run_id=None,
        _metadata=None,
        loss=None,
        loss_constructors=None,
        # diff from horovod
        checkpoint=None,
        tokenizer=None,
        max_token_len=128,
        label_col="label",
        text_col="text",
        prediction_col="prediction",
    ):
        super(DeepTextModel, self).__init__()

        self._setDefault(
            optimizer=None,
            loss=None,
            loss_constructors=None,
            input_shapes=None,
            checkpoint=None,
            max_token_len=128,
            text_col="text",
            label_col="label",
            prediction_col="prediction",
            feature_columns=["text"],
            label_columns=["label"],
            outputCols=["output"],
        )

        kwargs = self._kwargs
        self._set(**kwargs)

    def setTokenizer(self, value):
        return self._set(tokenizer=value)

    def getTokenizer(self):
        return self.getOrDefault(self.tokenizer)

    def setCheckpoint(self, value):
        return self._set(checkpoint=value)

    def getCheckpoint(self):
        return self.getOrDefault(self.checkpoint)

    def setMaxTokenLen(self, value):
        return self._set(max_token_len=value)

    def getMaxTokenLen(self):
        return self.getOrDefault(self.max_token_len)

    def _update_cols(self):
        self.setFeatureColumns([self.getTextCol()])
        self.setLabelColoumns([self.getLabelCol()])

    # override this to encoding text
    def get_prediction_fn(self):
        text_col = self.getTextCol()
        max_token_len = self.getMaxTokenLen()
        tokenizer = self.getTokenizer()

        def predict_fn(model, row):
            text = row[text_col]
            data = tokenizer(
                text,
                max_length=max_token_len,
                padding="max_length",
                truncation=True,
                return_attention_mask=True,
                return_tensors="pt",
            )
            with torch.no_grad():
                outputs = model(**data)
                pred = torch.nn.functional.softmax(outputs.logits, dim=-1)

            return pred

        return predict_fn

    # pytorch_lightning module has its own optimizer configuration
    def getOptimizer(self):
        return None

    def _transform(self, df):
        self._update_cols()
        output_df = super()._transform(df)
        argmax = udf(lambda v: float(np.argmax(v)), returnType=DoubleType())
        pred_df = output_df.withColumn(
            self.getPredictionCol(), argmax(col(self.getOutputCols()[0]))
        )
        return pred_df


import os
import sys

import torch
import torchaudio
from einops import rearrange
import argparse

sys.path.append(os.path.join(os.path.dirname(__file__), '..'))

from open_musiclm.config import load_model_config, create_musiclm_from_config

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='run inference on trained musiclm model')

    parser.add_argument('prompt', help='prompts to generate audio for', type=str, nargs='+')
    parser.add_argument('--num_samples', default=4, type=int)
    parser.add_argument('--num_top_matches', default=1, type=int)
    parser.add_argument('--model_config', default='./configs/model/musiclm_small.json', help='path to model config')
    parser.add_argument('--semantic_path', required=True, help='path to semantic stage checkpoint')
    parser.add_argument('--coarse_path', required=True, help='path to coarse stage checkpoint')
    parser.add_argument('--fine_path', required=True, help='path to fine stage checkpoint')
    parser.add_argument('--rvq_path', default='./checkpoints/clap.rvq.350.pt')
    parser.add_argument('--kmeans_path', default='./results/hubert_kmeans/kmeans.joblib')
    parser.add_argument('--return_coarse_wave', default=False, action=argparse.BooleanOptionalAction)
    parser.add_argument('--duration', default=4, type=float, help='duration of audio to generate in seconds')
    parser.add_argument('--seed', default=0)

    args = parser.parse_args()

    model_config = load_model_config(args.model_config)

    semantic_path = args.semantic_path
    coarse_path = args.coarse_path
    fine_path = args.fine_path
    return_coarse_wave = args.return_coarse_wave
    duration = args.duration
    kmeans_path = args.kmeans_path
    rvq_path = args.rvq_path
    seed = args.seed

    device = 'cuda' if torch.cuda.is_available() else 'cpu'

    musiclm = create_musiclm_from_config(
        model_config=model_config,
        semantic_path=semantic_path,
        coarse_path=coarse_path,
        fine_path=fine_path,
        rvq_path=rvq_path,
        kmeans_path=kmeans_path,
        device=device)

    torch.manual_seed(seed)

    print(f'prompt: {args.prompt}')

    generated_wave, similarities = musiclm.generate_top_match(
        text=args.prompt,
        num_samples=args.num_samples,
        num_top_matches=args.num_top_matches,
        output_seconds=duration,
        semantic_window_seconds=model_config.global_cfg.semantic_audio_length_seconds,
        coarse_window_seconds=model_config.global_cfg.coarse_audio_length_seconds,
        fine_window_seconds=model_config.global_cfg.fine_audio_length_seconds,
        return_coarse_generated_wave=return_coarse_wave,
    )

    for i, (wave, sim) in enumerate(zip(generated_wave, similarities)):
        wave = rearrange(wave, 'b n -> b 1 n').detach().cpu()
        print(f'prompt: {args.prompt[i]}')
        print(f'topk similarities: {sim}')
        for j, w in enumerate(wave):
            torchaudio.save(f'results/{args.prompt[i][:35]}_top_match_{j}.wav', w, musiclm.neural_codec.sample_rate)