import random
import numpy as np

from graphs.base_graph import BaseGraph
from simulation.sampling.sampling_strategy import random_sampling

def dwug_sampling(sample_graph: BaseGraph, annotated_graph: BaseGraph, percentage_nodes: float or int, percentage_edges: float or int, min_size_mc: int, num_flag: bool = False, random_sample_empty_round: int = 0) -> list:
    """
    Uses the DWUG sampling strategy, as described in the paper.

    Args:
        :param sample_graph: graph on which to sample edge weight
        :param annotated_graph: annotation graph
        :param percentage_nodes: percentage of nodes to add this round
        :param percentage_edges: percentage of edges to add this round
        :param min_size_mc: minimum size of cluster to be considered as multi-cluster
        :param num_flag: if :percentage_nodes: & :percentage_edges: are the actual number of nodes/edges to be used  (optional)
        :param random_sample_empty_round: if set, on empty rounds the amount of edges will be random sampled
    """
    if annotated_graph.get_number_edges() == 0:
        # initial exploration
        return _z_sampling_round(sample_graph, percentage_nodes, percentage_edges, num_flag)
    edges = _n_sampling_round(sample_graph, annotated_graph, min_size_mc, percentage_nodes, percentage_edges, num_flag)

    if len(edges) == 0 and random_sample_empty_round > 0:
        edges = random_sampling(sample_graph, {'sample_size': random_sample_empty_round})

    return edges

def _z_sampling_round(sample_graph: BaseGraph, percentage_nodes: float, percentage_edges: float, num_flag: bool) -> list:
    number_nodes = percentage_nodes if num_flag else round(sample_graph.get_number_nodes() * percentage_nodes)

    try:
        nodes = np.random.choice(sample_graph.G.nodes(), number_nodes, replace=False)
    except ValueError:
        nodes = sample_graph.G.nodes()

    max_edges = percentage_edges if num_flag else len(nodes) * (len(nodes) - 1) * 0.5 * percentage_edges

    return _exploration_phase(sample_graph, nodes, max_edges)

def _n_sampling_round(sample_graph: BaseGraph, annotated_graph: BaseGraph, min_size_mc: int, percentage_nodes: float, percentage_edges: float, num_flag: bool) -> list:
    # Nodes not in cluster size >= min_size_mc
    nodes = [node for k, v in annotated_graph.get_community_nodes().items() if len(v) < min_size_mc for node in v]
    multi_clusters = [v for k, v in annotated_graph.get_community_nodes().items() if len(v) >= min_size_mc]

    # Find nodes to be used in the sample round
    combination_nodes = []
    exploration_nodes = []

    for node in nodes:
        cn_flag = False
        for cluster in multi_clusters:
            cn_flag |= not _check_node_cluster_con(annotated_graph, node, cluster)

        if cn_flag:
            combination_nodes.append(node)
        else:
            exploration_nodes.append(node)

    # add new nodes to combination phase
    not_added_nodes = list(set(sample_graph.G.nodes()) - set(annotated_graph.G.nodes()))
    num_new_nodes_add = percentage_nodes if num_flag else round(sample_graph.get_number_nodes() * percentage_nodes)

    try:
        new_nodes = np.random.choice(not_added_nodes, num_new_nodes_add, replace=False)
    except ValueError:
        new_nodes = not_added_nodes

    combination_nodes.extend(new_nodes)
    max_edges = percentage_edges if num_flag else len(exploration_nodes) * (len(exploration_nodes) - 1) * 0.5 * percentage_edges

    # execute both phases
    sampled_edge_list = []
    sampled_edge_list.extend(_combination_phase(sample_graph, annotated_graph, combination_nodes, multi_clusters))
    sampled_edge_list.extend(_exploration_phase(sample_graph, exploration_nodes, max_edges))

    return sampled_edge_list

def _combination_phase(sample_graph: BaseGraph, annotated_graph: BaseGraph, nodes: list, multi_clusters: list) -> list:
    if len(nodes) == 0:
        return []

    sampled_edge_list = []

    for node in nodes:
        for cluster in multi_clusters:
            if not _check_node_cluster_con(annotated_graph, node, cluster):
                connection = random.choice(cluster)
                sampled_edge_list.append((node, connection, sample_graph.get_edge(node, connection)))

    return sampled_edge_list

def _check_node_cluster_con(graph: BaseGraph, node: int, cluster: list) -> bool:
    for c_node in cluster:
        u, v = sorted([node, c_node])
        if graph.get_edge(u, v) is not None:
            return True

    return False

def _exploration_phase(sample_graph: BaseGraph, nodes: list, max_edges: float) -> list:
    # RandomWalk till percentage edges found
    if len(nodes) == 0 or len(nodes) == 1:
        return []

    sampled_edge_list = []
    last_node = random.choice(nodes)

    while len(sampled_edge_list) < max_edges:
        next_node = random.choice(np.delete(np.array(nodes), np.where(np.array(nodes) == last_node)))
        sampled_edge_list.append((last_node, next_node, sample_graph.get_edge(last_node, next_node)))
        last_node = next_node

    return sampled_edge_list


import math
import numpy as np

def randomDataGenerator(alpha, beta, n):
    return np.random.gumbel(alpha, beta, n)

def firstDerivative(alpha, beta, all_points, n, flag):
    if (flag == 'alpha'):
        first_term = 0
        for datapoint in all_points:
            first_term += math.exp(-((datapoint - alpha) / beta))
        final_result = n / beta - first_term / beta
    if (flag == 'beta'):
        first_term = 0
        second_term = 0
        for datapoint in all_points:
            first_term += ((datapoint - alpha) / (beta * beta))
            second_term += ((datapoint - alpha) / (beta * beta)) * (math.exp(-((datapoint - alpha) / beta)))
        final_result = -n / beta + first_term - second_term
    return final_result

def secondDerivative(alpha, beta, all_points, n, flag):
    if (flag == 'alpha'):
        first_term = 0
        for datapoint in all_points:
            first_term += math.exp(-((datapoint - alpha) / beta))
        final_result = (-1 / (beta * beta)) * first_term
    if (flag == 'beta'):
        first_term = 0
        second_term = 0
        third_term = 0
        for datapoint in all_points:
            first_term += (datapoint - alpha)
            second_term += ((datapoint - alpha) * math.exp(-((datapoint - alpha) / beta)))
            third_term += ((datapoint - alpha) * (datapoint - alpha) * math.exp(-((datapoint - alpha) / beta)))
        first_term = (-2 / (beta * beta * beta)) * first_term
        second_term = (2 / beta * beta * beta) * second_term
        third_term = -third_term / (beta * beta * beta * beta)
        final_result = (n / beta * beta) + first_term + second_term + third_term
    return final_result

def secondDerivativeAlphaBeta(alpha, beta, all_points, n):
    first_term = 0
    second_term = 0
    for datapoint in all_points:
        first_term += math.exp(-((datapoint - alpha) / beta))
        second_term += ((datapoint - alpha) * (math.exp(-(datapoint - alpha) / beta)))
    first_term = first_term / (beta * beta)
    second_term = -second_term / (beta * beta * beta)

    final_result = (-n / (beta * beta)) + first_term + second_term
    return final_result

def estimateGumbelParameters(n):
    alpha_list = []
    beta_list = []
    for i in range(0, 10):
        dataset = randomDataGenerator(0, 0.1, n)
        mean_dataset = np.mean(dataset)
        std_dataset = np.std(dataset)
        beta = 0.7797 * std_dataset
        alpha = mean_dataset - 0.5772 * beta
        itr=0
        while True:
            itr+=1
            first_alpha_derivative = firstDerivative(alpha, beta, dataset, n, 'alpha')
            first_beta_derivative = firstDerivative(alpha, beta, dataset, n, 'beta')
            second_alpha_derivative = secondDerivative(alpha, beta, dataset, n, 'alpha')
            second_beta_derivative = secondDerivative(alpha, beta, dataset, n, 'beta')
            second_alpha_beta_derivative = secondDerivativeAlphaBeta(alpha, beta, dataset, n)
            gumbel_function = np.array([[first_alpha_derivative], [first_beta_derivative]])
            hessian = np.array([[second_alpha_derivative, second_alpha_beta_derivative],
                                [second_alpha_beta_derivative, second_beta_derivative]])
            hessian_inv = np.linalg.pinv(hessian)
            out_old = np.array([[alpha], [beta]])
            out_new = np.subtract(out_old, (hessian_inv * gumbel_function))
            new_alpha = out_new[0][0]
            new_beta = out_new[1][0]
            threshold = ((new_alpha - alpha) ** 2) + ((new_beta - beta) ** 2)
            alpha = new_alpha
            beta = new_beta
            if threshold < 10 ** -6:
                print(itr)
                break
            if itr > 10:
                break
        alpha_list.append(alpha)
        beta_list.append(beta)
    return alpha_list, beta_list

def reportValues(n):
    alpha_list, beta_list = estimateGumbelParameters(n)
    print("--------------ALPHA VALUES FOR N = ",n," -------------------------------------------------------------------")
    print("List of Alphas", alpha_list)
    print("Mean value of alpha ", np.mean(alpha_list))
    print("Standard Deviation alpha ", np.std(alpha_list))
    print("--------------BETA VALUES FOR N = ",n," --------------------------------------------------------------------")
    print("List of Betas", beta_list)
    print("Mean value of beta ", np.mean(beta_list))
    print("Standard Deviation beta ", np.std(beta_list))

temp = [100, 1000, 10000]
for entry in temp:
    reportValues(entry)


import math

a=int(input("enter your number: "))
print("For performing factorial use:'!',sine use:'sin',cosine use:'cos',tangent use:'tan',secant:'sec',cosecant:'cosec,"
      "cotangent:'cot',sininverse:'asine',cosinverse:'acos',taninverse:'atan',cotinverse:'acot',cosecinverse:'acosec,secinverse:'asec'")
b=" "
ans=0
while b!="":
    print("To get answer press enter")
    b=str(input("operation: "))
    if b == "*":
        c = int(input("enter second number: "))
        ans= a*c
    elif b =="/":
        c = int(input("enter second number: "))
        ans= a/c
    elif b == "+":
        c = int(input("enter second number: "))
        ans=a+c
    elif b == "-":
        c = int(input("enter second number: "))
        ans=a-c
    elif b == "%":
        c = int(input("enter second number: "))
        ans=a%c
    elif b == "//":
        c = int(input("enter second number: "))
        ans=a//c
    elif b == "pow":
        c = int(input("enter second number: "))
        ans=math.pow(a,c)
    elif b == "sin":
        ans=round(math.sin(a),2)
    elif b == "cos":
        ans = round(math.cos(a),2)
    elif b == "tan":
        ans = round(math.tan(a),2)
    elif b == "cosec":
        try:
            ans = round(1/math.sin(a),2)
        except ZeroDivisionError:
            print("cosec of",ans,"is not defined")
    elif b == "sec":
        try:
            ans = round(1/math.cos(a),2)
        except ZeroDivisionError:
            print("sec of",ans,"is not defined")

    elif b == "cot":
        try:
            ans = round(1/math.tan(a),2)
        except ZeroDivisionError:
            print("cot of",ans,"is not defined")
    elif b == "square":
        ans = math.pow(a,2)
    elif b == "sqrt":
        ans = math.sqrt(a)
    elif b == "cube":
        ans = math.pow(a,3)
    elif b == "cbrt":
        ans = math.pow(a,1/3)
    elif b == "log":
        c = int(input("enter second number: "))
        ans = math.log(a,c)
    elif b == "expo":
        ans = math.exp(a)
    elif b == "asin":
        ans = round(math.asin(a),2)
    elif b == "acos":
        ans = round(math.acos(a),2)
    elif b == "atan":
        ans = round(math.atan(a),2)
    elif b == "acosec":
        ans = 1/math.asin(a)
    elif b == "asec":
        ans = 1/math.acos(a)
    elif b == "acot":
        ans = 1/math.atan(a)
    elif b == "per":
        ans= a/100
    elif b == "abs":
        ans = abs(a)
    elif b == "!":
        ans = math.factorial(a)
    a=ans
print(ans)


#! /usr/bin/env python3
"""apply tf transform to marvelmind position

    from marvelmind frame to map"""

import rospy
import tf2_ros
import tf2_geometry_msgs
from geometry_msgs.msg import PoseWithCovarianceStamped, PoseStamped

# function to strip covariance because do_transform_pose can only do PoseStamped
def remove_covariance(with_cov):
    """strip covariance and return the message and covariance seperately"""

    no_cov = PoseStamped()
    no_cov.header = with_cov.header
    no_cov.pose = with_cov.pose.pose
    cov = with_cov.pose.covariance
    return(no_cov,cov)

# ..and re-add the covariance
def add_covariance(no_cov,cov):
    """take covariance and message and re-combine them"""

    with_cov = PoseWithCovarianceStamped()
    with_cov.header = no_cov.header
    with_cov.pose.pose = no_cov.pose
    with_cov.pose.covariance = cov
    return(with_cov)

def callback_pose(msg_in):
    """on receiving marvelmind pose strip covariance, do transform, re-add it and publish

    do_transform_pose cannot handle PoseWithCovariance"""

    pose_removed_covariance,cov = remove_covariance(msg_in)

    transform = tfBuffer.lookup_transform("map",
                                    "marv_frame",
                                    rospy.Time(0), #get the tf at first available time
                                    rospy.Duration(1.0))

    pose_transformed = tf2_geometry_msgs.do_transform_pose(pose_removed_covariance, transform)
    pose_added_covariance = add_covariance(pose_transformed, cov)

    pub.publish(pose_added_covariance)

if __name__=='__main__':
    rospy.init_node("pose_transform")

    tfBuffer = tf2_ros.Buffer(rospy.Duration(100.0))
    tf_listener = tf2_ros.TransformListener(tfBuffer)

    sub_pose = rospy.Subscriber("/marvelmind_pos", PoseWithCovarianceStamped, callback_pose)
    pub = rospy.Publisher("/transformed_pos", PoseWithCovarianceStamped, queue_size=10)
    rospy.spin()


# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

# 637. 二叉树的层平均值

class Solution(object):
    def averageOfLevels(self, root):
        """
        :type root: TreeNode
        :rtype: List[float]
        """
        level_order_averages = []

        level_order_vals = self.levelOrderTraverse(root)

        for level_order_val in level_order_vals:
            tmp = float(sum(level_order_val)) / len(level_order_val)
            level_order_averages.append(tmp)

        return level_order_averages

    def levelOrderTraverse(self, root):
        result = []

        if root is None:
            return result

        current_level = []
        next_level = []

        current_level.append(root)

        while len(current_level) != 0:
            current_level_vals = []

            for node in current_level:
                current_level_vals.append(node.val)

                if node.left is not None:
                    next_level.append(node.left)

                if node.right is not None:
                    next_level.append(node.right)

            result.append(current_level_vals)
            current_level = next_level
            next_level = []

        return result


import numpy as np
import sys, os
sys.path.append(os.pardir)  # 为了导入父目录的文件而进行的设定
import numpy as np
#from mnist import load_mnist
from collections import OrderedDict
import matplotlib.pyplot as plt

class Relu:
    def __init__(self):
        self.mask = None

    def forward(self, x):
        self.mask = (x <= 0)
        out = x.copy()
        out[self.mask] = 0

        return out

    def backward(self, dout):
        dout[self.mask] = 0
        dx = dout

        return dx

class Sigmoid:

    def __init__(self):
        self.out = None
        self.loss = None
        self.y = None # 网络的输出
        self.t = None # 监督数据

    def forward(self, x, t):
        self.t = t
        self.y = sigmoid(x)
        out = sigmoid(x)
        self.out = out
        self.loss = cross_entropy_error(self.y, self.t)

        return self.loss
        '''
        out = sigmoid(x)
        self.out = out
        return out
        '''

    def backward(self, dout=1):
        batch_size = self.t.shape[0]
        if self.t.size == self.y.size: # 监督数据是one-hot-vector的情况
            #print(self.out.shape)
            #print((dout * (1.0 - self.out) * self.out).shape)
            #print((self.y - self.t).shape)
            dx = dout * (1.0 - self.out) * self.out * (self.y - self.t) / batch_size
            #dx = (self.y - self.t) / batch_size
        else:
            dx = self.y.copy()
            dx[np.arange(batch_size), self.t] -= 1
            dx = dx / batch_size

        return dx
        '''
        dx = dout * (1.0 - self.out) * self.out

        return dx
        '''

#未完善
class Tanh:

    def __init__(self):
        self.out = None

    def forward(self, x):
        out = tanh(x)
        self.out = out
        return out

    def backward(self, dout):
        dx = dout * (2.0 - self.out) * self.out
        #dx = dout * (1.0 - self.out) * self.out

        return dx

class Affine:
    def __init__(self, W, b):
        self.W =W
        self.b = b

        self.x = None
        self.original_x_shape = None
        # 权重和偏置参数的导数
        self.dW = None
        self.db = None

    def forward(self, x):
        # 对应张量
        self.original_x_shape = x.shape
        x = x.reshape(x.shape[0], -1)
        self.x = x

        out = np.dot(self.x, self.W) + self.b

        return out

    def backward(self, dout):
        dx = np.dot(dout, self.W.T)
        self.dW = np.dot(self.x.T, dout)
        self.db = np.sum(dout, axis=0)

        dx = dx.reshape(*self.original_x_shape)  # 还原输入数据的形状（对应张量）
        return dx

class SoftmaxWithLoss:
    def __init__(self):
        self.loss = None
        self.y = None # softmax的输出
        self.t = None # 监督数据

    def forward(self, x, t):
        self.t = t
        self.y = softmax(x)
        self.loss = cross_entropy_error(self.y, self.t)

        return self.loss

    def backward(self, dout=1):
        batch_size = self.t.shape[0]
        if self.t.size == self.y.size: # 监督数据是one-hot-vector的情况
            dx = (self.y - self.t) / batch_size
        else:
            dx = self.y.copy()
            dx[np.arange(batch_size), self.t] -= 1
            dx = dx / batch_size

        return dx

def sigmoid(x):
    return 1 / (1 + np.exp(-x))
def tanh(x):
    return 2 / (1 + np.exp(-2*x))
    #return 2*sigmoid(2*x)-1

def cross_entropy_error(y, t):
    if y.ndim == 1:
        t = t.reshape(1, t.size)
        y = y.reshape(1, y.size)

    # 监督数据是one-hot-vector的情况下，转换为正确解标签的索引
    if t.size == y.size:
        batch_size = y.shape[0]
        return 0.5 * np.sum((y-t)**2)/batch_size
        #t = t.argmax(axis=1)

    batch_size = y.shape[0]
    return -np.sum(np.log(y[np.arange(batch_size), t] + 1e-7)) / batch_size

def softmax(x):
    if x.ndim == 2:
        x = x.T
        x = x - np.max(x, axis=0)
        y = np.exp(x) / np.sum(np.exp(x), axis=0)
        return y.T

    x = x - np.max(x) # 溢出对策
    return np.exp(x) / np.sum(np.exp(x))

class TwoLayerNet:

    def __init__(self, input_size, hidden_size, output_size, weight_init_std = 0.01):
        # 初始化权重
        #hidden_size = [1,2,3,4,5]
        self.params = {}
        l = len(hidden_size)
        for i in range(l-1):
            no = i + 1
            w = 'W' + str(no)
            b = 'b' + str(no)
            self.params[w] = weight_init_std * np.random.randn(hidden_size[i],hidden_size[i+1])   #123
            self.params[b] = np.zeros(hidden_size[i+1])

        '''
        self.params['W1'] = weight_init_std * np.random.randn(input_size, hidden_size)
        self.params['b1'] = np.zeros(hidden_size)
        self.params['W2'] = weight_init_std * np.random.randn(hidden_size, output_size)
        self.params['b2'] = np.zeros(output_size)
        '''
        # 生成层
        self.layers = OrderedDict()
        for i in range(l-1):
            affine = 'Affine' + str(i + 1)
            #sgm = 'Sigmoid' + str(i + 1)
            th = 'Tanh' + str(i + 1)
            w = 'W' + str(i + 1)
            b = 'b' + str(i + 1)
            self.layers[affine] = Affine(self.params[w], self.params[b])

            if i != l-2:
                #self.layers[sgm] = Sigmoid()
                self.layers[th] = Tanh()

        '''
        self.layers = OrderedDict()
        self.layers['Affine1'] = Affine(self.params['W1'], self.params['b1'])
        self.layers['Relu1'] = Relu()
        self.layers['Affine2'] = Affine(self.params['W2'], self.params['b2'])
        '''
        self.lastLayer = Sigmoid()
        #self.lastLayer = SoftmaxWithLoss()

    def predict(self, x):
        for layer in self.layers.values():
            x = layer.forward(x)

        return x

    # x:输入数据, t:监督数据
    def loss(self, x, t):
        y = self.predict(x)
        return self.lastLayer.forward(y, t)

    def accuracy(self, x, t):
        y = self.predict(x)
        y = np.argmax(y, axis=1)
        if t.ndim != 1 : t = np.argmax(t, axis=1)

        accuracy = np.sum(y == t) / float(x.shape[0])
        return accuracy

    def gradient(self, x, t):
        # forward
        self.loss(x, t)

        # backward
        dout = 1
        dout = self.lastLayer.backward(dout)

        layers = list(self.layers.values())
        layers.reverse()
        for layer in layers:
            dout = layer.backward(dout)

        # 设定
        grads = {}
        grads['W1'], grads['b1'] = self.layers['Affine1'].dW, self.layers['Affine1'].db
        grads['W2'], grads['b2'] = self.layers['Affine2'].dW, self.layers['Affine2'].db

        return grads

# 读入数据
#(x_train, t_train), (x_test, t_test) = load_mnist(normalize=True, one_hot_label=True)
x_train = np.array([[1.58, 2.32, -5.8], [0.67, 1.58, -4.78], [1.04, 1.01, -3.63],
                   [-1.49, 2.18, -3.39], [-0.41, 1.21, -4.73], [1.39, 3.16, 2.87],
                   [1.20, 1.40, -1.89], [-0.92, 1.44, -3.22], [0.45, 1.33, -4.38],
                   [-0.76, 0.84, -1.96],
                   [0.21, 0.03, -2.21], [0.37, 0.28, -1.8], [0.18, 1.22, 0.16],
                   [-0.24, 0.93, -1.01], [-1.18, 0.39, -0.39], [0.74, 0.96, -1.16],
                   [-0.38, 1.94, -0.48], [0.02, 0.72, -0.17], [0.44, 1.31, -0.14],
                   [0.46, 1.49, 0.68],
                   [-1.54, 1.17, 0.64], [5.41, 3.45, -1.33], [1.55, 0.99, 2.69],
                   [1.86, 3.19, 1.51], [1.68, 1.79, -0.87], [3.51, -0.22, -1.39],
                   [1.40, -0.44, -0.92], [0.44, 0.83, 1.97], [0.25, 0.68, -0.99],
                   [0.66, -0.45, 0.08]])
t_train = np.array([[1,0,0],[1,0,0],[1,0,0],[1,0,0],[1,0,0],[1,0,0],[1,0,0],[1,0,0],[1,0,0],[1,0,0],
                    [0,1,0],[0,1,0],[0,1,0],[0,1,0],[0,1,0],[0,1,0],[0,1,0],[0,1,0],[0,1,0],[0,1,0],
                    [0,0,1],[0,0,1],[0,0,1],[0,0,1],[0,0,1],[0,0,1],[0,0,1],[0,0,1],[0,0,1],[0,0,1]])
print(x_train.shape,t_train.shape)

network = TwoLayerNet(input_size=3, hidden_size=[3,72,3], output_size=3)
#network = TwoLayerNet(input_size=3, hidden_size=3, output_size=3)

iters_num = 1000000
train_size = x_train.shape[0]
batch_size = 10
learning_rate = 0.01

train_loss_list = []
train_acc_list = []
test_acc_list = []

#iter_per_epoch = max(train_size / batch_size, 1)
iter_per_epoch = 1000

for i in range(iters_num):
    batch_mask = np.random.choice(train_size, batch_size)
    x_batch = x_train[batch_mask]
    t_batch = t_train[batch_mask]

    # 梯度
    #grad = network.numerical_gradient(x_batch, t_batch)
    grad = network.gradient(x_batch, t_batch)

    # 更新
    for key in ('W1', 'b1', 'W2', 'b2'):
        network.params[key] -= learning_rate * grad[key]

    loss = network.loss(x_batch, t_batch)
    train_loss_list.append(loss)

    if i % iter_per_epoch == 0:
        train_acc = network.accuracy(x_train, t_train)
        #test_acc = network.accuracy(x_test, t_test)
        train_acc_list.append(train_acc)
        #test_acc_list.append(test_acc)
        print(i, train_acc, loss)
print(network.params)
plt.plot(train_loss_list)
plt.show()

f = open('C:/Users/14775/Desktop/模式识别导论/作业/三/'+'[3723]'+str(iters_num)+'_'+str(learning_rate)+'_'+str(batch_size)+'.txt', 'w')
f.write('train_loss_list\n')
for i in train_loss_list:
    f.write(str(i)+'\n')
f.write('train_acc_list\n')
for i in train_acc_list:
    f.write(str(i)+'\n')
f.close()


from django.http import HttpResponse
from F3FChrono.data.dao.EventDAO import EventDAO
from F3FChrono.data.dao.RoundDAO import RoundDAO
from F3FChrono.data.web.HTMLText import HTMLText
from F3FChrono.data.web.ResultPage import ResultPage
from F3FChrono.data.web.ResultTable import ResultTable
from F3FChrono.data.web.Header import Header
from F3FChrono.data.web.Line import Line
from F3FChrono.data.web.Cell import Cell
from F3FChrono.data.web.Link import Link
from F3FChrono.data.web.Utils import Utils
from django.views.decorators.cache import never_cache
import datetime

@never_cache
def is_alive(request):
    return HttpResponse('
Hello world !
')

@never_cache
def index(request):

    Utils.set_port_number(request.META['SERVER_PORT'])

    dao = EventDAO()

    events = dao.get_list()

    page = ResultPage(title='Events list')

    table = ResultTable(title='', css_id='ranking')

    header = Header(name=Cell('Name'))
    header.add_cell(Cell('Location'))
    header.add_cell(Cell('Begin date'))
    header.add_cell((Cell('End date')))
    table.set_header(header)

    for event in events:
        fetched_event = dao.get(event.id)
        row = Line(name=Link(fetched_event.name, 'event_view?event_id=' + str(fetched_event.id)))
        row.add_cell(Cell(fetched_event.location))
        row.add_cell(Cell(str(fetched_event.begin_date)))
        row.add_cell(Cell(str(fetched_event.end_date)))
        table.add_line(row)

    page.add_table(table)

    return HttpResponse(page.to_html())

@never_cache
def event_view(request):

    Utils.set_port_number(request.META['SERVER_PORT'])

    event_id = request.GET.get('event_id')

    return HttpResponse(event_view_html(event_id))

def get_cell_css_id(competitor_rank):
    if competitor_rank==1:
        return 'first'
    elif competitor_rank==2:
        return 'second'
    elif competitor_rank==3:
        return 'third'
    else:
        return None

def event_view_html(event_id):

    event = EventDAO().get(event_id=event_id, fetch_competitors=True, fetch_rounds=True, fetch_runs=True)

    page = ResultPage(title=event.name)

    if event.current_round is not None:
        table = ResultTable('Ongoing round :', css_id='ranking')
        header = Header(name=Link('Round ' + str(len(event.valid_rounds)+1),
                                  'round_view?event_id=' + str(event_id) +
                                  '&round_number=' + str(event.get_current_round().round_number)))
        table.set_header(header)
        page.add_table(table)

    if len(event.valid_rounds) > 0:
        event.compute_ranking()

        warning = HTMLText('WARNING : These results are not official. '
                           'They are based on raw data and does not have been validated')

        page.add_text(warning)

        #Evolutive ranking table
        table = ResultTable(title='Evolutive ranking', css_id="ranking")
        header = Header(name=Cell('Rank'))
        header.add_cell(Cell('Bib'))
        header.add_cell(Cell('Points'))
        header.add_cell(Cell('Points / 1000'))
        header.add_cell(Cell('Name'))
        for f3f_round in event.valid_rounds:
            header.add_cell(Link(f3f_round.display_name(),
                                 'round_view?event_id=' + str(event_id) +
                                 '&round_number=' + str(f3f_round.round_number)))
        table.set_header(header)

        best_score = None
        for competitor in sorted([competitor for bib, competitor in event.competitors.items()], key=lambda c: c.rank):
            row = Line(name=Cell('{:2d}'.format(int(competitor.rank))))
            row.add_cell(Cell(str(competitor.bib_number)))
            competitor_score = competitor.score_with_jokers(len(event.valid_rounds))
            row.add_cell(Cell('{:6.2f}'.format(competitor_score)))
            if best_score is None:
                best_score = competitor_score
            if best_score>0:
                row.add_cell(Cell('{:2d}'.format(int(competitor_score / best_score * 1000))))
            else:
                row.add_cell(Cell('NaN'))
            row.add_cell(Cell(competitor.pilot.to_string()))
            for f3f_round in event.valid_rounds:
                competitor_rank = int(competitor.evolutive_rank[f3f_round.valid_round_number-1])
                row.add_cell(Cell('{:2d}'.format(competitor_rank), css_id=get_cell_css_id(competitor_rank)))
            table.add_line(row)

        page.add_table(table)

        # Round scores table
        table = ResultTable(title='Round scores', css_id="ranking")
        header = Header(name=Cell('Bib'))
        header.add_cell(Cell('Name'))
        for f3f_round in event.rounds:
            if f3f_round.valid:
                header.add_cell(Link(f3f_round.display_name(),
                                     'round_view?event_id=' + str(event_id) +
                                     '&round_number=' + str(f3f_round.round_number)))
        table.set_header(header)

        for competitor in sorted([competitor for bib, competitor in event.competitors.items()], key=lambda c: c.bib_number):
            row = Line(name=Cell(str(competitor.bib_number)))
            row.add_cell(Cell(competitor.pilot.to_string()))
            for f3f_round in event.valid_rounds:
                round_group = f3f_round.find_group(competitor)
                if round_group is not None:
                    run = round_group.get_valid_run(competitor)
                    if run is None:
                        score = 0
                    else:
                        score = run.score
                else:
                    score = 0
                winner = score >= 1000
                joker = (event.number_of_valid_rounds >= event.first_joker_round_number and
                         f3f_round.valid_round_number == competitor.first_joker_round_number) \
                        or \
                        (event.number_of_valid_rounds >= event.second_joker_round_number and
                         f3f_round.valid_round_number == competitor.second_joker_round_number)

                row.add_cell(Cell('{:2d}'.format(int(score)), joker=joker, winner=winner))
            table.add_line(row)

        page.add_table(table)

    result = page.to_html()

    return result

@never_cache
def round_view(request):

    Utils.set_port_number(request.META['SERVER_PORT'])

    event_id = request.GET.get('event_id')
    round_number = request.GET.get('round_number')

    return HttpResponse(round_view_html(event_id, round_number))

def round_view_html(event_id, round_number):

    f3f_round = RoundDAO().get_from_ids(event_id, round_number, fetch_runs=True)

    page = ResultPage(title=f3f_round.event.name + '\t' + f3f_round.display_name() +
                            '(id:' + str(f3f_round.round_number) + ')', event=f3f_round.event)

    best_runs = f3f_round.get_best_runs()
    best_runs_string = 'Best time :
'

    for run in best_runs:
        if run is not None:
            best_runs_string += run.to_string()

    table = ResultTable(title=best_runs_string, css_id='ranking')
    header = Header(name=Cell('Bib'))
    header.add_cell(Cell('Group'))
    header.add_cell(Cell('Name'))
    header.add_cell(Cell('Flight time'))
    header.add_cell(Cell('Score'))
    table.set_header(header)

    #Later loop on rounds and round groups
    round_group = f3f_round.groups[0]
    for round_group in f3f_round.groups:
        round_group.compute_scores()
        for competitor in sorted(round_group.runs):
            row = Line(name=Cell(str(competitor.bib_number)))
            row.add_cell(Cell(str(round_group.group_number)))
            row.add_cell(Cell(competitor.pilot.to_string()))
            row.add_cell(Cell(round_group.run_value_as_string(competitor)))
            row.add_cell(Cell(str(round_group.run_score_as_string(competitor))))
            table.add_line(row)

    page.add_table(table)

    table = ResultTable(title='Remaining pilots to fly', css_id='ranking')
    header = Header(name=Cell('Bib'))
    header.add_cell(Cell('Group'))
    header.add_cell(Cell('Name'))
    table.set_header(header)

    for bib_number in f3f_round.get_remaining_bibs_to_fly():
        row = Line(name=Cell(str(bib_number)))
        row.add_cell(Cell(str(f3f_round.find_group(f3f_round.event.competitors[bib_number]).group_number)))
        row.add_cell(Cell(f3f_round.event.competitors[bib_number].display_name()))
        table.add_line(row)

    page.add_table(table)

    result = page.to_html()
    return result

if __name__ == "__main__":
    # execute only if run as a script
    event_view_html(1)
    #round_view_html(1, 21)


#!/usr/bin/env python3

#import
import argparse

#define functions/classes

def argparser():
    parser = argparse.ArgumentParser()
    parser.add_argument('-v', '--verbose', type = bool, help = "Set to True to print status updates. Default True", default = True)
    parser.add_argument('-g', '--gff', help = 'Path to input gff.')
    parser.add_argument('-p', '--plus', help = 'name of output for plus strand CDSs')
    parser.add_argument('-m', '--minus', help = 'name of output for minus strand CDSs')

    args = parser.parse_args()
    return args

def main():
    args = argparser()
    #insert code
    with open(args.gff) as inf:
        with open(args.plus,'w+') as plusout:
            with open(args.minus,'w+') as minusout:
                for entry in inf:
                    if entry[0] != "#":
                        spent = entry.strip().split()
                        if spent[2] == "CDS":
                            #get the parent information.
                            pinfo = spent[8].split(';')[1].strip("Parent=gene-")
                            data = '\t'.join(spent[0:8] + ['gene_id', '"' + pinfo + '";',])
                            if spent[6] == '+':
                                print(data, file = plusout)
                            else:
                                print(data, file = minusout)

if __name__ == "__main__":
    main()


from ..utils import ApiUtil
from ..utils.ApiUtil import Url

class Systems:
    def __init__(self, code, auth_token, project_id):
        self.code = code
        self.auth_token = auth_token
        self.project_id = project_id
        data = {
                'auth_token': self.auth_token,
                'project_id': self.project_id
               }
        self.systems = ApiUtil.requestGet(Url.systemList, self.code, data)

    def get_system(self, id):
        for system in self.systems:
            if system['id'] == id:
                return system

    def __iter__(self):
        for system in self.systems:
            yield(system)


from math import sqrt as sqrt
def sieve(size):
    numbers = list(range(2,size+1))
    for ptr in range(0,int(sqrt(size))+1):
        if numbers[ptr] != 0:
            for k in range(ptr + numbers[ptr], len(numbers), numbers[ptr]):
                numbers[k] = 0
    primes = [x for x in numbers if x!=0]
    return primes
def floorlog(num, n):
    i = 1
    stor = num
    while stor < n:
        stor*=num
        i+=1
    return i-1
def mindivby1ton(n):
    primes = sieve(n)
    rv = 1
    for i in primes:
        rv*=(i**floorlog(i,n))
    return rv
print(mindivby1ton(1000000) % (10**9 + 7))


from toolkit.logger import Logger

logger = Logger("classes").get_logger()

import pandas as pd

import matplotlib.pyplot as plt
from PIL import Image

from sklearn.model_selection import train_test_split

from pathlib import Path
import gc

from tqdm.notebook import tqdm

from typing import List, Dict

class ImageDataFrame(pd.DataFrame):
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)

    @property
    def _constructor(self):
        return ImageDataFrame

    def show_images(self, idxs: List[int]) -> None:
        for idx in idxs:
            _, ax = plt.subplots(1, 1, figsize=(15, 10), tight_layout=True, dpi=400)
            ax.imshow(Image.open(self.iloc[idx].img))
            ax.set_xticks([])
            ax.set_yticks([])
            ax.set_ylabel(f"{idx}")
            plt.show()

class DataFrameCreator(dict):
    logger.debug(f"INIT: {__qualname__}")
    columns: List[str] = [
        "img_dir",
        "img_file",
        "img",
        "label",
        "label_enc",
    ]

    def __init__(self) -> None:
        self.update(
            {
                "dataset": ImageDataFrame(columns=self.columns),
                "train": ImageDataFrame(columns=self.columns),
                "validation": ImageDataFrame(columns=self.columns),
                "test": ImageDataFrame(columns=self.columns),
            }
        )

    def __del__(self) -> None:
        logger.debug(f"DESTRUCT: {__name__}")
        gc.collect()

    def load_dataset(self, sample_dir: str, labels: Dict) -> None:
        for label, encode in labels.items():
            src = Path(sample_dir) / label
            for e, entity in tqdm(
                enumerate(src.iterdir()), total=len(list(src.rglob("*")))
            ):
                if entity.is_file():
                    df = pd.DataFrame(
                        {
                            "img_dir": str(entity.parent),
                            "img_file": str(entity.name),
                            "img": str(entity),
                            "label": str(label),
                            "label_enc": int(encode),
                        },
                        index=[e],
                    )
                    self["dataset"] = pd.concat([self["dataset"], df], axis=0)
                elif entity.is_dir():
                    logger.warning(f"Directory found: {entity}")
                else:
                    logger.critical(f"Unknown entity type: {entity}")
                    raise TypeError(f"Unknown entity type: {entity}")
            logger.info(f"Images loaded from {sample_dir} with label {label}")
        self["dataset"].sort_values(by=["img_file"], inplace=True)
        self["dataset"].reset_index(drop=True, inplace=True)

    def split_dataset(self, val_rate: float = 0.2, test_rate: float = 0.1) -> None:
        self["train"], _X = train_test_split(
            self["dataset"],
            test_size=val_rate + test_rate,
            shuffle=True,
            stratify=self["dataset"].label,
        )
        self["validation"], self["test"] = train_test_split(
            _X,
            test_size=test_rate / (val_rate + test_rate),
            shuffle=True,
            stratify=_X.label,
        )
        self["train"].reset_index(drop=True, inplace=True)
        self["validation"].reset_index(drop=True, inplace=True)
        self["test"].reset_index(drop=True, inplace=True)

    def info(self) -> None:
        for k, v in self.items():
            logger.info(f"Name :          {k}")
            logger.info(f"Labels:         {v.label.value_counts().to_dict()}")
            logger.info(f"Columns:        {*v.columns,}")
            logger.info(f"Shape:          {v.shape}")
            logger.info(
                f"File types:     {*v.img_file.apply(lambda x: str(x).split('.')[-1]).unique(),}"
            )


from keras.preprocessing.image import ImageDataGenerator

# x_train and y_train assume the image data and labels have been preprocessed and
# split into training and test data.

# instantiate an Image Data generator object
datagen = ImageDataGenerator()

# the number of batches in an epoch
nbatches = len(x_train) // 32
# the number of epochs (training passes over the entire training data)
epochs = 10

for epoch in range(epochs):
    batches = 0
    # Use generator to create batches
    for x_batch, y_batch in datagen.flow(x_train, y_train, batch_size=32,
                                         shuffle=True):
        model.fit(x_batch, y_batch)
        batches += 1
        if batches > nbatches:
            break


from torch_geometric.datasets import Reddit, NELL, Flickr, Planetoid, Yelp, PPI
import torch_geometric.transforms as T

def get_dataset(args, dataset_dir):

    if args.dataset_name == 'Cora' or args.dataset_name == 'Pubmed' or args.dataset_name == 'CiteSeer':
        dataset = Planetoid(dataset_dir, args.dataset_name, transform=T.NormalizeFeatures())
        data = dataset[0]

        num_features = dataset.num_features
        num_classes = dataset.num_classes

    if args.dataset_name == 'Flickr':
        dataset = Flickr(dataset_dir, transform=T.NormalizeFeatures())
        data = dataset[0]

        num_features = dataset.num_features
        num_classes = dataset.num_classes

    if args.dataset_name == 'Yelp':
        dataset = Yelp(dataset_dir,  transform=None)
        data = dataset[0]

        num_features = dataset.num_features
        num_classes = dataset.num_classes

    if args.dataset_name == 'NELL':
        dataset = NELL(dataset_dir, pre_transform=None)
        data = dataset[0]
        data.x = data.x.to_dense()[:, :5414]
        num_features = 5414
        num_classes = dataset.num_classes

    return dataset, data, num_features, num_classes


import torch
import torch.nn as nn

Loss_func = nn.MSELoss()

def build_net():
    net = nn.Sequential(nn.Linear(9, 7),
                        nn.ReLU(),
                        nn.Linear(7, 5),
                        nn.ReLU(),
                        nn.Linear(5, 4),
                        nn.ReLU(),
                        nn.Linear(4, 3),
                        nn.ReLU(),
                        nn.Linear(3, 1),
                        nn.Sigmoid()
                        )

    optimizer = torch.optim.Adam(net.parameters(), 0.002)

    return net, optimizer

def generate(neighbors, net):
    neighbors = torch.tensor(neighbors, dtype=torch.float32)
    new_state = net(neighbors)

    return new_state.item()

def train(neighbors, target, net, optimizer):  # div per 2
    neighbors = torch.tensor(neighbors, dtype=torch.float32)
    target = torch.tensor([target], dtype=torch.float32)

    new_state = net(neighbors)

    loss = Loss_func(new_state, target)
    loss.backward()
    # print(loss.item())

    optimizer.step()
    optimizer.zero_grad()

    return new_state.item()


import train
from train_config import mlp_config, cnn_config
import copy

epoch_run = [1, 10, 50, 100, 200]

mlp_mnist = copy.deepcopy(mlp_config)
mlp_cifar10 = copy.deepcopy(mlp_config)
cnn_mnist = copy.deepcopy(cnn_config)
cnn_cifar10 = copy.deepcopy(cnn_config)

for run in epoch_run:
    mlp_mnist['hyperparameters']['n_epochs'] = run
    mlp_cifar10['hyperparameters']['n_epochs'] = run
    mlp_cifar10['dataset_name'] = 'cifar10'

    cnn_mnist['hyperparameters']['n_epochs'] = run
    cnn_cifar10['hyperparameters']['n_epochs'] = run
    cnn_cifar10['dataset_name'] = 'cifar10'

    train.train(mlp_mnist)
    print(f'\n\n\n*********Done training mlp on mnist for {run} epochs*********\n\n\n')

    train.train(mlp_cifar10)
    print(f'\n\n\n*********Done training mlp on cifar10 for {run} epochs*********\n\n\n')

    train.train(cnn_mnist)
    print(f'\n\n\n*********Done training cnn on mnist for {run} epochs*********\n\n\n')

    train.train(cnn_cifar10)
    print(f'\n\n\n*********Done training cnn on cifar10 for {run} epochs*********\n\n\n')

print("\n\n\n***----***All training is done")


# main.py
import discord
from discord.ext import commands
import os

def main():
    prefix = '!'
    intents = discord.Intents.all()

    client = commands.Bot(command_prefix=prefix, intents = intents)

    # 주어진 함수를 명령어로 변환하고, 봇에 등록 해 주는 함수를 호출하는 데코레이터
    # 단순히 명령어를 등록한다. 라고 이해할것.
    @client.command(name = 'pings')

    # 비동기 함수로, 명령어를 받아 메세지를 전송하는 작업은 디스코드의 API와 연동을 해야하기 때문에
    # 비동기 함수로 구현한다. ctx라는 인자는 context의 줄임말로, 메시지의 문맥에 대한 정보를 가지고 있다.
    # 자주 사용되는 속성과 메소드는
    # ctx.send(message) : 명령어가 전송된 위치에 메세지를 전송한다.
    # ctx.author : 명령어를 전송한 사람에 대한 정보
    # ctx.channel : 명령어가 전송된 채널에 대한 정보
    # 더 자세한 내용은 주소 참고 :
    # https://discordpy.readthedocs.io/en/stable/ext/commands/api.html?highlight=context#discord.ext.commands.Context
    async def _ping(ctx):
       await ctx.send("pongs!")

    with open('token.txt', 'r') as f:
        token = f.read()
    client.run(token)

if __name__ == '__main__':
    main()

2. 봇에게 명령할당.py


#!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import with_statement

__license__   = 'GPL v3'
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'

import __builtin__

from calibre import config_dir

#_resolver = PathResolver()

def get_path(path, data=False, allow_user_override=True):
    #fpath = _resolver(path, allow_user_override=allow_user_override)
    fpath = path
    if data:
        with open(fpath, 'rb') as f:
            return f.read()
    return fpath

def get_image_path(path, data=False, allow_user_override=True):
    if not path:
        return get_path('images')
    return get_path('images/'+path, data=data)

__builtin__.__dict__['P'] = get_path
__builtin__.__dict__['I'] = get_image_path


import pandas as pd
import torch
from metrics import EER, minDCF

def speaker_verification(path_dev_file, path_mean_file):
    df_dev = pd.read_csv(path_dev_file)
    df_mean = pd.read_csv(path_mean_file)

    embeddings_dev_list = df_dev.values.tolist()
    embeddings_mean_list = df_mean.values.tolist()

    similarity = torch.nn.CosineSimilarity(dim=-1, eps=1e-6)
    trials = []
    target_scores = []
    non_target_scores = []
    for row_dev in embeddings_dev_list:
        for row_mean in embeddings_mean_list:
            file_dev = row_dev[0]
            id_dev = row_dev[1]
            id_mean = row_mean[0]
            emb1 = torch.FloatTensor(row_dev[4:])
            emb2 = torch.FloatTensor(row_mean[1:])
            score = similarity(emb1, emb2)
            # make trials (check if both have same id)
            if id_mean in file_dev:
                trials.append('\n' + id_mean + ' ' + file_dev + ' ' + 'TARGET')
                target_scores.append(score)
            else:
                trials.append('\n' + id_mean + ' ' + file_dev + ' ' + 'NONTARGET')
                non_target_scores.append(score)

    # write trials.txt file
    with open('trials.txt', 'w') as trials_file:
        trials_file.writelines(trials)

    # calculate metrics
    eer, eer_th = EER(torch.tensor(target_scores), torch.tensor(non_target_scores))
    min_dcf, min_dcf_th = minDCF(torch.tensor(target_scores), torch.tensor(non_target_scores))
    print('eer: ' + str(eer) + ', eer_th: ' + str(eer_th))
    print('min_dcf: ' + str(min_dcf) + ', min_dcf_th: ' + str(min_dcf_th))

if __name__ == '__main__':
    # select model: 'ecapa' or 'xvector'
    model = 'xvector'
    path_dev = 'voxceleb_pt/embeddings/devel_' + model + '.csv'
    path_mean = 'voxceleb_pt/embeddings/train_' + model + '_mean.csv'
    # speaker verification
    speaker_verification(path_dev, path_mean)


import matplotlib.pyplot as plt
import numpy as np

_direction = [[0, 1], [1, 0], [0, 1]]
_eps = 0.01

def foo(x, xd, y, yd, nd, lam=0, dx=0, operation=1):
    n = 8
    px = x + (lam - operation * dx) * xd / nd
    py = y + (lam - operation * dx) * yd / nd
    return 5 * (px - n) ** 2 + px * py + 3 * py ** 2

def setup(start, direction, sb=True):
    x, y = start[0], start[1]
    xd, yd = direction[0], direction[1]
    nd = (xd ** 2 + yd ** 2) ** 0.5
    ns = (x ** 2 + y ** 2) ** 0.5
    dx = 0.1 * (ns / nd)
    if sb:
        return x, y, xd, yd, nd, ns, dx
    else:
        return x, y, xd, yd, nd

def sven(start, direction, lam=0, dsk_=False):
    x0, y0, xd, yd, normalized_direction, normalized_start, dx = setup(start, direction)

    values = [foo(x0, xd, y0, yd, normalized_direction, lam)]
    lambdas = [lam]
    if foo(x0, xd, y0, yd, normalized_direction, lam, dx) < \
            foo(x0, xd, y0, yd, normalized_direction, lam) < \
            foo(x0, xd, y0, yd, normalized_direction, lam, dx, -1):
        values.append(foo(x0, xd, y0, yd, normalized_direction, lam, dx))
        lambdas.append(lam - dx)
    elif foo(x0, xd, y0, yd, normalized_direction, lam, dx) > \
            foo(x0, xd, y0, yd, normalized_direction, lam) > \
            foo(x0, xd, y0, yd, normalized_direction, lam, dx, -1):
        values.append(foo(x0, xd, y0, yd, normalized_direction, lam, dx, -1))
        lambdas.append(lam + dx)
    elif foo(x0, xd, y0, yd, normalized_direction, lam, dx) > \
            foo(x0, xd, y0, yd, normalized_direction, lam, ) < \
            foo(x0, xd, y0, yd, normalized_direction, lam, dx, -1):
        if not dsk_:
            return lam - dx, lam + dx
        else:
            return lam-dx, lam, lam+dx
    operation = 1 if lambdas[1] > lambdas[0] else -1
    i = 1
    while values[i] < values[i - 1]:
        step = lambdas[i] + operation * dx * (2 ** i)
        lambdas.append(step)

        values.append(foo(x0, xd, y0, yd, normalized_direction, step, -operation))
        i += 1

    last = (lambdas[i], (lambdas[i] + lambdas[i - 1])/2, lambdas[i - 1], lambdas[i - 2])
    eval_lambdas = []
    for i in last:
        eval_lambdas.append(foo(x0, xd, y0, yd, normalized_direction, i))

    minimal = eval_lambdas.index(min(eval_lambdas))

    if not dsk_:
        return sorted([last[minimal - 1], last[minimal + 1]])
    else:
        return sorted((last[minimal - 1], last[minimal], last[minimal + 1]))

def dichotomy(sven_, start, direction):
    x0, y0, xd, yd, nd = setup(start, direction, sb=False)
    long = sven_[1] - sven_[0]
    middle = (sven_[1] + sven_[0]) / 2
    left = (sven_[0] + middle) / 2
    right = (middle + sven_[1]) / 2
    while long > _eps:
        if foo(x0, xd, y0, yd, nd, left) < \
                foo(x0, xd, y0, yd, nd, middle) < \
                foo(x0, xd, y0, yd, nd, right):
            right = (left + middle) / 2
            middle = left
            left = (sven_[0] + middle) / 2
        elif foo(x0, xd, y0, yd, nd, left) > \
                foo(x0, xd, y0, yd, nd, middle) > \
                foo(x0, xd, y0, yd, nd, right):
            left = (middle + right) / 2
            middle = right
            right = (middle + sven_[1]) / 2
        elif foo(x0, xd, y0, yd, nd, left) > \
                foo(x0, xd, y0, yd, nd, middle) < \
                foo(x0, xd, y0, yd, nd, right):
            left = (left + middle) / 2
            middle = middle
            right = (right + middle) / 2
        long = long / 2
    return (left + middle) / 2

def golden_ratio(sven_, start, direction):
    x0, y0, xd, yd, nd = setup(start, direction, sb=False)
    long = sven_[1] - sven_[0]
    left = sven_[0] + 0.382 * long
    right = sven_[0] + 0.618 * long
    while long > _eps:
        if foo(x0, xd, y0, yd, nd, left) < \
                foo(x0, xd, y0, yd, nd, right):
            sven_[1] = right
            long = sven_[1] - sven_[0]
            left = sven_[0] + 0.382 * long
            right = sven_[0] + 0.618 * long
        elif foo(x0, xd, y0, yd, nd, left) > \
                foo(x0, xd, y0, yd, nd, right):
            sven_[0] = left
            long = sven_[1] - sven_[0]
            left = sven_[0] + 0.382 * long
            right = sven_[0] + 0.618 * long
    return (sven_[0] + sven_[1]) / 2

def dsk(sven_, start, direction):
    x0, y0, xd, yd, nd = setup(start, direction, sb=False)
    dx = abs(sven_[0] - sven_[1])
    f1 = foo(x0, xd, y0, yd, nd, sven_[0])
    f2 = foo(x0, xd, y0, yd, nd, sven_[1])
    f3 = foo(x0, xd, y0, yd, nd, sven_[2])

    x_dsk = sven_[1] + (dx*(f1-f3))/(2*(f1-2*f2+f3))
    f_dsk = foo(x0, xd, y0, yd, nd, x_dsk)
    if (sven_[1]-x_dsk) < _eps and (f2-f_dsk) < _eps:
        return x_dsk
    end = False
    while not end:
        dotes = sorted([sven_[0], sven_[1], sven_[2], x_dsk])
        dsk_index = dotes.index(x_dsk)
        if dsk_index == 0 or dsk_index == 1:
            dotes.remove(dotes[-1])
        elif dsk_index == 2 or dsk_index == 3:
            dotes.remove(dotes[0])
        f1 = foo(x0, xd, y0, yd, nd, dotes[0])
        f2 = foo(x0, xd, y0, yd, nd, dotes[1])
        f3 = foo(x0, xd, y0, yd, nd, dotes[2])
        a1 = (f2-f1)/(dotes[1]-dotes[0])
        a2 = (1/(dotes[2]-dotes[1]))*((f3-f1)/(dotes[2]-dotes[0])-a1)
        x_dsk = (dotes[0]+dotes[1])/2-a1/(2*a2)
        f_dsk = foo(x0, xd, y0, yd, nd, x_dsk)
        tmp_f = [f1, f2, f3, f_dsk]
        tmp_dotes = [dotes[0], dotes[1], dotes[2], x_dsk]
        index_f_min = tmp_f.index(min(tmp_f))
        x_min = tmp_dotes[index_f_min]

        if abs(min(tmp_f)-f_dsk) < _eps and abs(x_min - x_dsk) < _eps:
            end = True
    return x_dsk

def powell(start):
    with open("rgr Zinchuk.txt", "w+") as file:
        file.write(f"Find minimum of function f(x) = 5(x1-8)**2 + x1x2 + 3x2**2\n")
        file.write(f"Minimum reached at X = [8.136, -1.355] and value equal 0\n\n\n")
        i = 0
        position = [start]
        end_ = 0
        while end_ < 4:
            end_ += 1
            file.write(f"--Iteration {i+1}--\n")
            sven_ = sven(position[i], _direction[i])
            file.write(f" Direction = {_direction[i]}, point = {position[i]}\n")
            file.write(f"Lambda interval = {sven_}\n")
            if i == 0:
                lambda_optimal = dichotomy(sven_, position[i], _direction[i])
                file.write(f"Dichotomy method for optimal lambda. Lambda Value = {lambda_optimal}\n")
            elif i == 1:
                lambda_optimal = golden_ratio(sven_, position[i], _direction[i])
                file.write(f"Golden ratio method for optimal lambda. Lambda Value = {lambda_optimal}\n")
            else:
                lambda_optimal = dsk(sven(position[i], _direction[i], dsk_=True), position[i], _direction[i])
                file.write(f"DSK method for optimal lambda. Lambda Value = {lambda_optimal}\n")
            new_x = [0, 0]
            new_x[0] = position[i][0] + lambda_optimal * _direction[i][0]
            new_x[1] = position[i][1] + lambda_optimal * _direction[i][1]
            position.append(new_x)
            file.write(f"New dote {new_x}\n\n\n")

            if (i+1) % 3 == 0:
                old = _direction[i]
                x = position[i+1][0] - position[i-1][0]
                y = position[i+1][1] - position[i-1][1]
                new_dir = [x, y]
                normalized_new = (x**2+y**2) ** 0.5
                new_dir[0] = new_dir[0]/normalized_new
                new_dir[1] = new_dir[1]/normalized_new
                _direction.append(new_dir)
                _direction.append(old)
                _direction.append(new_dir)

            i += 1
            norm_new_x = (position[i][0]**2 + position[i][1]**2) ** 0.5
            prev_norm_x = (position[i-1][0]**2 + position[i-1][1]**2) ** 0.5
            if abs(norm_new_x - prev_norm_x)/norm_new_x <= _eps:
                end_ = 5
        file.write(f"\nEnd of calculation via reaching criteria of ending")
        file.close()
        position[-1][0] = round(position[-1][0], 4)
        position[-1][1] = round(position[-1][1], 4)
        return position

def plot_():
    start, stop, n_values = -5, 15, 2000

    x_values = np.linspace(start, stop, n_values)
    y_values = np.linspace(start, stop, n_values)
    _x, _y = np.meshgrid(x_values, y_values)

    _z = (5 * (_x - 5) ** 2 + _x * _y + 3 * _y ** 2)

    plt.contour(_x, _y, _z)

    path = powell([14.4, 14.4])

    x_coords = []
    for i in range(len(path)):
        x_coords.append(path[i][0])

    y_coords = []
    for i in range(len(path)):
        y_coords.append(path[i][1])

    plt.scatter(x_coords, y_coords)
    plt.plot(x_coords, y_coords)

    plt.show()

if __name__ == '__main__':
    plot_()


#!/usr/bin/env python

import glob
import os
import sys

try:
    sys.path.append(glob.glob('../carla/dist/carla-*%d.%d-%s.egg' % (
        sys.version_info.major,
        sys.version_info.minor,
        'win-amd64' if os.name == 'nt' else 'linux-x86_64'))[0])
except IndexError:
    pass

import carla

# Connect to CARLA simulator
client = carla.Client('localhost', 2000)
client.set_timeout(20.0)

try:
    # Load Tesla blueprint
    blueprints = client.get_world().get_blueprint_library().filter('model3')

    if not blueprints:
        raise RuntimeError("Tesla blueprint not found in CARLA")

    # Choose a spawn location
    spawn_point = carla.Transform(carla.Location(x=100, y=200, z=50), carla.Rotation(pitch=0, yaw=0, roll=0))

    # Spawn Tesla vehicle
    tesla_vehicle = client.get_world().spawn_actor(blueprints[0], spawn_point)

    # Calculate desired speed for 20 meters ahead
    distance_to_cover = 20.0  # meters
    desired_speed = distance_to_cover / 5.0  # Adjust the divisor for desired time of travel

    # Control the Tesla vehicle
    control = carla.VehicleControl()
    control.throttle = 0.5
    tesla_vehicle.apply_control(control)

    # Monitor the vehicle's position to determine when it has covered the desired distance
    initial_location = tesla_vehicle.get_location()
    current_location = initial_location
    while current_location.distance(initial_location) < distance_to_cover:
        current_location = tesla_vehicle.get_location()

    # Stop the vehicle
    control.throttle = 0.0
    tesla_vehicle.apply_control(control)

finally:
    # Cleanup
    if 'tesla_vehicle' in locals():
        tesla_vehicle.destroy()

# Disconnect from CARLA
client.disconnect()


import pandas as pds
import numpy as np

data = pds.read_csv('Base_pictures_blurry.csv', index_col = 0)
queryl= []
column = (list(data.columns))
Chevu = True

for i in [-1,1] :
    queryi = "Male == " + str(i) + " and "
    for j in [-1,1] :
        queryj = queryi + "Bald == " + str(j) + " and "
        if j == 1 :
            Chevu = False
        for k in [-1,1] :
            queryk = queryj + "Young == " + str(k) + " and "
            for l in [-1,1] :
                queryil = queryk + "Eyeglasses == " + str(l) + " and "
                for m in [0,-1,1]:
                    if m == 0 :
                        querym = queryil + "Bushy_Eyebrows == -1" + " and " + "Arched_Eyebrows == -1" + " and "
                    else :
                        querym = queryil + "Bushy_Eyebrows == "+ str(m) + " and " + "Arched_Eyebrows == "+ str(m*-1) + " and "
                    for n in [0,-1,1]:
                        if n == 0 :
                            queryn = querym + "Big_Nose == -1" + " and " + "Pointy_Nose == -1" + " and "
                        else :
                            queryn = querym + "Big_Nose == "+ str(n) + " and " + "Pointy_Nose == "+ str(n*-1) + " and "
                        for o in [0,-1,1]:
                            if o == 0 :
                                queryo = queryn + "No_Beard == 1" + " and " + "Mustache == -1" + " and "
                            if o == 1 :
                                queryo = queryn + "No_Beard == -1" + " and "
                            if o == -1 :
                                queryo = queryn + "Mustache == 1" + " and "
                            if Chevu :
                                for v in [0,-1,1] :
                                    if v == 0 :
                                        queryv = queryo + "(Brown_Hair == -1" + " or " + "Black_Hair == -1" + ") and " + "(Blond_Hair == -1" + " or " + "Grey_Hair == -1" + ") and "
                                    if v == 1 :
                                        queryv = queryo + "(Brown_Hair == " + str(v) + " or " + "Black_Hair == " + str(v) + ") and " + "(Blond_Hair == " + str(v*-1) + " or " + "Grey_Hair == " + str(v*-1) + ") and "
                                    if v == -1 :
                                        queryv = queryo + "(Brown_Hair == " + str(v) + " or " + "Black_Hair == " + str(v) + ") and " + "(Blond_Hair == " + str(v*-1) + " or " + "Grey_Hair == " + str(v*-1) + ") and "

                                    queryv += " Blurry == - 1"
                                    queryl.append(queryv)
                            else :
                                queryo += " Blurry == - 1"
                                queryl.append(queryo)
total_pics = []
empty_queer = []
for queer in queryl :
    pics = data.query(queer)
    if len(pics) == 0:
        empty_queer.append(queer)
    if len(pics) <= 10 :
        for i in range(len(pics)) :
            total_pics.append(pics.iloc[i])
    else :
        choi = np.random.randint(0,len(pics),10)
        for nb in choi :
            total_pics.append(pics.iloc[nb])
pds.DataFrame(empty_queer).to_csv("empty_queer.csv")
tpic = pds.DataFrame(total_pics)
tpic.to_csv("Total_Base_Pics.csv")


#hackertools by Iyanuhacks
import mechanize
#Now, we will create an object named brwsr of the mechanize browser −

brwsr = mechanize.Browser()
#The next line of code shows that the user agent is not a robot.

brwsr.set_handle_robots( False )
#Now, we need to provide the url of our dummy website containing the web form on which we need to bypass validation.

url = input("Enter URL:>>> ")
#Now, following lines will set some parenters to true.

brwsr.set_handle_equiv(True)
brwsr.set_handle_gzip(True)
brwsr.set_handle_redirect(True)
brwsr.set_handle_referer(True)
#Next it will open the web page and print the web form on that page.

brwsr.open(url)
for form in brwsr.forms():
   print(form)
#Next line of codes will bypass the validations on the given fields.

brwsr.select_form(nr = 0)
brwsr.form['name'] = ''
brwsr.form['gender'] = ''
brwsr.submit()


#!/usr/bin/env python

from collections import defaultdict
import intcode

def print_arcade(panels):
    minx = min([k[0] for k in panels.keys()])
    maxx = max([k[0] for k in panels.keys()])
    miny = min([k[1] for k in panels.keys()])
    maxy = max([k[1] for k in panels.keys()])

    for y in range(miny, maxy+1):
        for x in range(minx, maxx+1):
            if panels[(x, y)] == 0:
                print(' ', end='')
            if panels[(x, y)] == 1:
                print('#', end='')
            if panels[(x, y)] == 2:
                print('=', end='')
            if panels[(x, y)] == 3:
                print('_', end='')
            if panels[(x, y)] == 4:
                print('o', end='')
        print('')

def solve(opcodes):
    run = intcode.runner(opcodes)
    grid = defaultdict(int)
    try:
        while True:
            x, y, id = next(run), next(run), next(run)
            grid[(x, y)] = id
    except StopIteration:
        pass

    print_arcade(grid)
    print(len([v for v in grid.values() if v == 2]))

with open('input.txt', 'r') as f:
    inp = f.read().strip().split(',')
    solve(inp)


"""
Tic Tac Toe Player
"""

import math
import copy

X = "X"
O = "O"
EMPTY = None

def initial_state():
    """
    Returns starting state of the board.
    """
    return [[EMPTY, EMPTY, EMPTY],
            [EMPTY, EMPTY, EMPTY],
            [EMPTY, EMPTY, EMPTY]]

def player(board):
    """
    Returns player who has the next turn on a board.
    """
    next_player = X
    played_moves = []
    for i in board:
        for j in i:
            if j is not None:
                played_moves.append(j)

    number_of_x = played_moves.count("X")
    number_of_o = played_moves.count("O")

    if number_of_x > number_of_o:
        next_player = O

    return next_player

def actions(board):
    """
    Returns set of all possible actions (i, j) available on the board.
    """
    possible_actions = set()

    for i in range(3):
        for j in range(3):
            if board[i][j] is None:
                possible_actions.add((i, j))

    return possible_actions

def result(board, action):
    """
    Returns the board that results from making move (i, j) on the board.
    """
    new_board = copy.deepcopy(board)

    next_player = player(board)

    row = action[0]
    cell = action[1]
    if new_board[row][cell] is None:
        new_board[row][cell] = next_player
    else:
        raise ValueError

    return new_board

def winner(board):
    """
    Returns the winner of the game, if there is one.
    """
    if all(i == board[0][0] for i in board[0]):
        return board[0][0]
    elif all(i == board[1][0] for i in board[1]):
        return board[1][0]
    elif all(i == board[2][0] for i in board[2]):
        return board[2][0]

    elif board[0][0] == board[1][0] and board[1][0] == board[2][0]:
        return board[0][0]
    elif board[0][1] == board[1][1] and board[1][1] == board[2][1]:
        return board[0][1]
    elif board[0][2] == board[1][2] and board[1][2] == board[2][2]:
        return board[0][2]

    elif board[0][0] == board[1][1] and board[1][1] == board[2][2]:
        return board[0][0]
    elif board[0][2] == board[1][1] and board[1][1] == board[2][0]:
        return board[0][2]
    else:
        return None

def terminal(board):
    """
    Returns True if game is over, False otherwise.
    """

    state_of_board = winner(board)
    game_over = True
    if state_of_board is not None:
        return game_over
    else:
        for i in board:
            for j in i:
                if j is None:
                    game_over = False

        return game_over

def utility(board):
    """
    Returns 1 if X has won the game, -1 if O has won, 0 otherwise.
    """
    game_over = terminal(board)
    if game_over:
        player = winner(board)
        if player == X:
            return 1
        elif player is O:
            return -1
        else:
            return 0

def minimax(board):
    """
    Returns the optimal action for the current player on the board.
    """
    if terminal(board):
        return None
    else:
        if player(board) == X:
            value, move = max_value(board)
            return move
        else:
            value, move = min_value(board)
            return move

def max_value(board):
    if terminal(board):
        return utility(board), None

    v = float('-inf')
    move = None
    for action in actions(board):
        aux, act = min_value(result(board, action))
        if aux > v:
            v = aux
            move = action
            if v == 1:
                return v, move

    return v, move

def min_value(board):
    if terminal(board):
        return utility(board), None

    v = float('inf')
    move = None
    for action in actions(board):
        aux, act = max_value(result(board, action))
        if aux < v:
            v = aux
            move = action
            if v == -1:
                return v, move

    return v, move


def draw(n):
    AREA = n // 3  # n이 9라면, AREA는 3으로 3*3의 구역이 있다.
    if n == 3:
        Map[1] = ['*', ' ', '*']
        Map[0][:3] = Map[2][:3] = ["*"] * 3
        return
    draw(AREA)
    for i in range(0, n, AREA):  # n=9, AREA=3이라면 i는 0, 3, 6 (0 : 1구역의 첫번째 인덱스, 3 : 2구역의 첫번째 인덱스, 6 : 3구역의 첫번째 인덱스)
        for j in range(0, n, AREA):
            if (i != AREA) or (j != AREA):
                for k in range(AREA): # k는 0 1 2
                    Map[i + k][j:j + AREA] = Map[k][:AREA]

N = int(input())
Map = [[' ' for _ in range(N)] for _ in range(N)]

draw(N)

for i in range(N):
    for j in range(N):
        print(Map[i][j], end='')
    print()


import ipaddress

valid_input = False

while not valid_input:
    cidr = input("Introduce una dirección IP y máscara en formato CIDR: ")
    try:
        direccion = ipaddress.ip_interface(cidr)
        valid_input = True
    except ValueError as e:
        print("Formato incorrecto: {}".format(e))
else:
    red = direccion.network
    broadcast = red.broadcast_address
    ip_disponible_inicial = int(ipaddress.IPv4Address(red.network_address) + 1)
    ip_disponible_final = int(ipaddress.IPv4Address(red.broadcast_address) - 1)
    tamaño = ip_disponible_final - ip_disponible_inicial + 1

    print("Tipo: {}{}".format("IPv6 " if direccion.version == 6 else "", "privada" if direccion.is_private else "pública"))
    print("ID de red: {}".format(red))
    print("Máscara: {}".format(direccion.netmask))
    print("Broadcast: {}".format(broadcast))
    print("1a IP disponible: {}".format(ipaddress.IPv4Address(ip_disponible_inicial)))
    print("Última IP disponible: {}".format(ipaddress.IPv4Address(ip_disponible_final)))
    print("Tamaño: {}".format(tamaño))


import json
from modules.Aimbot import aimbot

with open('data/pixels.json') as f:
    dataPixel = json.load(f)

# Screenshot de um local selecionado e retorna a coordenadas do getpixel
def findInScreenshot (coordinate, rgbTargets):
    # Declarando dados do pixel nas propriedades do aimbot
    # Tira print de uma area especificada nas propriedades do aimbot
    screenshot = aimbot.printTarget(coordinate)
    # Retorna a localização do pixel q coincide com as propriedades do aimbot, se não for encontrado retorna None
    data = aimbot.findRgb(screenshot, coordinate, rgbTargets)

    return data

# (Leitura de tela) Verifica se no camto superior esquerdo, há a indicação de um inimigo
def watcherTarget ():
    # Dados do pixel
    coordinate = tuple(dataPixel['target']['region']) # (1269, 39, 1, 1)
    # Rgb alvos
    rgbEnemyLife = tuple(dataPixel['target']['rgbEnemyLife']) # (208,   208,   208)
    rgbEnemyDead = tuple(dataPixel['target']['rgbEnemyDead']) # (255,   0,   0)

    rgbTargets = [rgbEnemyLife, rgbEnemyDead]

    # Retorna a localização do pixel se coiciderem com os dados enviados, se não retorna None
    data = findInScreenshot(coordinate, rgbTargets)

    if (data !=  None):
        if (data['rgb'] == (255, 0, 0)):
            return 'isEnemy'
        else:
            return 'isLoot'
    else:
        return None

# Verifica se o loot está aberto
def watchLootOpen ():
    # Dados do pixel
    coordinate = tuple(dataPixel['isLootOpen']['region'])  # (932, 220, 1, 1)
    # Rgb alvos
    rgbOpen = [tuple(dataPixel['isLootOpen']['rgb'])] # [( 90, 239,  74)]

    # Retorna a localização do pixel se coiciderem com os dados enviados, se não retorna None
    data = findInScreenshot(coordinate, rgbOpen)

    if (data !=  None):
        print('Loot está aberto')
        return True
    else:
        print('Loot não está aberto.')
        return False

# Verifica se há itens valiosos no loot
def watchValueItem ():
    # Dados do pixel
    coordinate = tuple(dataPixel['isValueItem']['region']) # (990, 220, 1, 1)
    # Rgb alvos
    rgbGold = tuple(dataPixel['isValueItem']['rgbGold']) # (255, 255,  57)
    rgbImundice = tuple(dataPixel['isValueItem']['rgbImundice']) # (198, 181,  82)

    rgbLoots = [rgbGold, rgbImundice]

    # Retorna a localização do pixel se coiciderem com os dados enviados, se não retorna None
    data = findInScreenshot(coordinate, rgbLoots)

    return data

# Verifica se o menu do game está aberto
def watchMenuOpen ():
    # Dados do pixel
    coordinate = tuple(dataPixel['isMenuOpen']['region']) # (726, 470, 1, 1)
    # Rgb alvos
    rgbMenu = [tuple(dataPixel['isMenuOpen']['rgb'])] # [(238, 238, 187)]

    # Retorna a localização do pixel se coiciderem com os dados enviados, se não retorna None
    data = findInScreenshot(coordinate, rgbMenu)

    if (data !=  None):
        print('Menu está aberto.')
        return True
    else:
        print('Menu não está aberto.')
        return False

# Retorna as coordenadas do user
def myLocation ():
    # Coordenadas da area onde o user pode estar
    coordinate = tuple(dataPixel['myLocation']['region']) # (880, 30, 465, 564)
    rgbTargets = [tuple(dataPixel['myLocation']['rgb'])] # [(255,  57, 255)]
    data = findInScreenshot(coordinate, rgbTargets)
    return data


""" Name:Rajeev Kumar
    Roll:B20124
    mo:9341062431
"""
import numpy as np
import pandas as pd
from sklearn import metrics
from sklearn.metrics import confusion_matrix
test_df=pd.read_csv("SteelPlateFaults-test.csv")
train_df=pd.read_csv("SteelPlateFaults-train.csv")
Y_true=test_df["Class"]
test_df.drop(columns=['Unnamed: 0',"X_Minimum", "Y_Minimum", "TypeOfSteel_A300", "TypeOfSteel_A300","Class" ],inplace=True)
train_df0=train_df[train_df.Class == 0]
train_df1=train_df[train_df.Class == 1]
train_df0.drop(columns=['Unnamed: 0',"X_Minimum", "Y_Minimum", "TypeOfSteel_A300", "TypeOfSteel_A300","Class" ],inplace=True)
train_df1.drop(columns=['Unnamed: 0',"X_Minimum", "Y_Minimum", "TypeOfSteel_A300", "TypeOfSteel_A300","Class" ],inplace=True)
train_mean0=train_df0.mean()
train_mean1=train_df1.mean()
print(train_mean0,train_mean1)
def calculateCovariance(X):
    meanX = np.mean(X, axis = 0)
    lenX = X.shape[0]
    X = X - meanX
    covariance = X.T.dot(X)/lenX
    return covariance
train_cov0=calculateCovariance(train_df0)
train_cov1=calculateCovariance(train_df1)
print(train_cov0.to_string())
print(train_cov1.to_string())
t1=train_df1.subtract(train_mean1, axis = 1)
Y_pred=[]
#print(test_df.iloc[0],train_mean1)
#print(test_df.iloc[0].subtract(train_mean1).T)
for i in range(336):
    t0=(np.exp(-0.5*np.dot(np.dot((test_df.iloc[i].subtract(train_mean0)).T, np.linalg.inv(train_cov0)),
                                  ((test_df.iloc[i].subtract(train_mean0))))))/((2*np.pi)*5 * (np.linalg.det(train_cov0))*0.5)
    t1=(np.exp(-0.5*np.dot(np.dot((test_df.iloc[i].subtract(train_mean1)).T, np.linalg.inv(train_cov1)),
                                  ((test_df.iloc[i].subtract(train_mean1))))))/((2*np.pi)*5 * (np.linalg.det(train_cov1))*0.5)
    if t1>t0:
        Y_pred.append(1)
    else:
        Y_pred.append(0)
cm = confusion_matrix(Y_true, Y_pred)
print(cm)
print("Accuracy:",metrics.accuracy_score(Y_true, Y_pred))


import argparse
import gzip
import os
import re

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--inputdir", help="分析対象のログを格納",default="logs")
    parser.add_argument("--filename", help="ログファイルの名前", default="mail.log")
    args = parser.parse_args()

    filename = os.path.join(args.inputdir,args.filename)

    content =[]

    with open(filename,mode="r") as f:
        c= f.read()
        content.append(c)

    with open(filename+".1",mode="r") as f:
        c= f.read()
        content.append(c)

    with gzip.open(filename+".2.gz",mode="rt") as f:
        c= f.read()
        content.append(c)

    with gzip.open(filename+".3.gz",mode="rt") as f:
        c= f.read()
        content.append(c)

    with gzip.open(filename+".4.gz",mode="rt") as f:
        c= f.read()
        #content.append(c)

    postfix_logs=[]
    dovecot_logs=[]
    for i in content:
        lines = i.splitlines()
        for j in lines:
            if re.search('postfix.*with cipher',j)!=None:
                ip=re.search(r'[\d]{1,3}\.[\d]{1,3}\.[\d]{1,3}.[\d]{1,3}',j)
                cipher=re.search('[^ \t]* with cipher [^ \t]*',j)
                log=ip.group(0)+","+cipher.group(0)
                postfix_logs.append(log)
            if re.search('dovecot.*with cipher',j)!=None:
                user=re.search('user=<[A-Za-z0-9\-]*>',j)
                ip=re.search('rip=[\d\.]*',j)
                cipher=re.search('[^ \t]* with cipher [^ \t]*',j)
                if user!=None and ip!=None:
                    log=user.group(0)[6:-1]+","+ip.group(0)[4:]+","+cipher.group(0)
                    dovecot_logs.append(log)

    postfix_logs=list(set(postfix_logs))
    dovecot_logs=list(set(dovecot_logs))
    with open("postfix.csv",mode="w") as f:
        print("ip,cipher",file=f)
        for log in postfix_logs:
            print(log,file=f)
    with open("dovecot.csv",mode="w") as f:
        print("username,ip,cipher",file=f)
        for log in dovecot_logs:
            print(log,file=f)

if __name__ == "__main__":
    main()


from todoscanner import *
import tkinter as tk
import os
import subprocess
a, b, c = None, None, None

def submit():
    global a, b, c
    a = entry_a.get()
    b = entry_b.get()
    c = entry_c.get()
    fileEndings = formatFileEnding(a)
    file = open("found.txt", "w")
    file.write(str(main(fileEndings, b, c)))
    file.close()

def formatFileEnding(a):
    x = a.split(", ")
    return x

def getDefault():
    global da, db, dc
    file = open("defaultsave.txt", "r")
    x = file.read().split("\n")
    da, db, dc = x[0], x[1], x[2]

def saveDefault():
    global a, b, c
    da, db, dc = a, b, c
    file = open("defaultsave.txt", "w")
    file.write(f"{da}\n{db}\n{dc}")
    file.close()

# Create the Tkinter window
root = tk.Tk()
try:
    getDefault()
except:
    ""

root.title("TODO-Finder by Kadir | Copyright Kadir Aras Yanar FROG")
root.iconbitmap("logo.ico")

# Create the input fields and labels
label_a = tk.Label(root, text="File ending: (format: '.java')")
label_a.pack()
entry_a = tk.Entry(root)
entry_a.pack()
try:
    entry_a.insert(0, da)
except:
    ""

label_b = tk.Label(root, text="Directory: (use '/' instead of *backslash*)")
label_b.pack()
entry_b = tk.Entry(root)
entry_b.pack()
try:
    entry_b.insert(0, db)
except:
    ""

label_c = tk.Label(root, text="TODO Keyword:")
label_c.pack()
entry_c = tk.Entry(root)
entry_c.pack()
try:
    entry_c.insert(0, dc)
except:
    ""

# Create the submit button
submit_button = tk.Button(root, text="Search for TODO", command=submit)
submit_button.pack()

default_button = tk.Button(root, text="Set current as default", command=lambda: saveDefault())
default_button.pack()

file = open("found.txt", "r")
variable_label = tk.Label(root, text=f"Found TODOs:\n{file.read()}")
variable_label.pack()

# Start the Tkinter event loop
root.mainloop()


import json
import logging
import os
import time

from api_gateway import ApiGateway

logging.getLogger()
current_dir = os.path.dirname(__file__)

class Location(object):
    def __init__(self):
        self.lh = LocationHistory()

    def continuously_get_current_location(self):
        while True:
            time.sleep(0.1)
            self.get_current_location()

    def update_current_location(self, location):
        _lat = location.get('latitude')
        _long = location.get('longitude')
        if LastSeenLocation.latitude and LastSeenLocation.longitude is not None:
            if _lat != LastSeenLocation.latitude or _long != LastSeenLocation.longitude:
                LastSeenLocation.set_last_seen_location(_lat, _long)
                self.lh.location_history.append([LastSeenLocation.latitude, LastSeenLocation.longitude])
                logging.info('update location : lat {0}, long {1}'.format(_lat, _long))
        else:
            LastSeenLocation.set_last_seen_location(_lat, _long)
            self.lh.location_history.append([LastSeenLocation.latitude, LastSeenLocation.longitude])
            logging.info('update location : lat {0}, long {1}'.format(_lat, _long))

    def get_current_location(self):
        current_location = ApiGateway.get_current_location()
        self.update_current_location(current_location)

class LastSeenLocation(object):
    latitude = None
    longitude = None

    @staticmethod
    def set_last_seen_location(latitude, longitude):
        LastSeenLocation.latitude = latitude
        LastSeenLocation.longitude = longitude

class LocationHistory(object):
    LOCATION_HISTORY = os.path.join(current_dir,'location_history.json')
    location_history = None

    def __init__(self):
        LocationHistory.location_history = LocationHistory.read_history()

    @staticmethod
    def read_history(file_path=LOCATION_HISTORY):
        with open(file_path, 'r') as f:
            return json.load(f)

    @staticmethod
    def write_history(file_path=LOCATION_HISTORY):
        timestr = time.strftime("%Y%m%d-%H%M%S")
        _file_path, ext = os.path.splitext(file_path)
        file_path_time_based = _file_path + '-'+timestr + ext
        with open(file_path_time_based, 'w') as f:
            json.dump(LocationHistory.location_history, f)
        with open(file_path, 'r+') as f:
            json.dump(LocationHistory.location_history, f)


"""
Build Ward pages
"""

import hashlib
import numpy as np
import pandas as pd
from tqdm import tqdm
import geopandas as gpd

import config

from scripts.common import (
    build_smd_html_table
    , add_footer
    , add_google_analytics
    , add_geojson
    , ward_geojson
    , mapbox_slugs
    )

from scripts.urls import (
    generate_url
    , generate_link
    , relative_link_prefix
    )

from scripts.data_transformations import districts_candidates_commissioners

class BuildWards():

    def __init__(self):
        self.geojson_shape = ward_geojson()
        self.mapbox_style_slugs = mapbox_slugs()

        self.districts = pd.read_csv('data/districts.csv')
        self.mapbox_styles = pd.read_csv('data/mapbox_styles.csv')
        self.wards = pd.read_csv('data/wards.csv')
        self.candidate_statuses = pd.read_csv('data/candidate_statuses.csv')
        self.dcc = districts_candidates_commissioners(link_source='ward')

    def ward_list_page(self, redistricting_year):
        """Build a page showing a list of all the wards"""

        with open('templates/list.html', 'r') as f:
            output = f.read()

        output = add_google_analytics(output)

        output = output.replace('REPLACE_WITH_MAPBOX_GL_JS_VERSION', config.mapbox_gl_js_version)
        output = output.replace('REPLACE_WITH_LIST_NAME', f'List of Wards (Redistricting Year {redistricting_year})')
        output = output.replace('REPLACE_WITH_LINK_PATH___', relative_link_prefix(source='ward', destination='root'))

        output = output.replace('REPLACE_WITH_LIST_VALUES', self.list_of_wards(redistricting_year))

        with open(f'docs/map_{redistricting_year}/wards/index.html', 'w') as f:
            f.write(output)

    def list_of_wards(self, redistricting_year):

        ward_districts = pd.merge(
            self.wards[self.wards.redistricting_year == redistricting_year]
            , self.districts, how='inner', on='ward_id'
            )

        display_df = ward_districts.groupby(['ward_id', 'ward_name', 'councilmember']).agg(count_of_smds=('smd_id', 'size')).reset_index()
        display_df['Ward'] = display_df.apply(lambda x: generate_link(x.ward_id, x.ward_name, link_source='ward'), axis=1)
        display_df['Council Member'] = display_df['councilmember']
        display_df['Count of SMDs'] = display_df['count_of_smds']

        columns_to_html = ['Ward', 'Council Member', 'Count of SMDs']

        html = (
            display_df[columns_to_html]
            .fillna('')
            .style
            .set_uuid('list_of_wards_')
            .hide(axis='index')
            .to_html()
            )

        return html

    def build_all_ward_pages(self):
        """Build pages for each ward"""

        for _, ward in tqdm(self.wards.iterrows(), total=len(self.wards), desc='Wards  '):
            self.build_ward_page(ward)

    def build_ward_page(self, ward):
        """Build one ward page"""

        with open('templates/ward.html', 'r') as f:
            output = f.read()

        output = add_google_analytics(output)
        output = add_geojson(self.geojson_shape, 'ward_id', ward.ward_id, output)

        output = output.replace('REPLACE_WITH_WARD_NAME', f'{ward.ward_name} [{ward.redistricting_cycle} Cycle]')
        output = output.replace('REPLACE_WITH_CM', ward.councilmember)

        ward_smd_ids = self.districts[self.districts['ward_id'] == ward.ward_id]['smd_id'].to_list()
        output = output.replace(
            ''
            , build_smd_html_table(ward_smd_ids, link_source='ward', district_comm_commelect=self.dcc, candidate_statuses=self.candidate_statuses)
            )

        if ward.ward_name in (3,4):
            output = output.replace(
                ''
                , '
Note that the Single Member Districts 3G01, 3G02, 3G03, and 3G04 are a part of ANC 3G but located in Ward 4.
'
                )

        if ward.redistricting_year == 2012:
            mapbox_slug_id = 'smd'
        else:
            mapbox_slug_id = 'smd-2022'

        output = output.replace('REPLACE_WITH_MAPBOX_SLUG', self.mapbox_style_slugs[mapbox_slug_id])
        output = output.replace('REPLACE_WITH_LONGITUDE', '-77.03412954884507')
        output = output.replace('REPLACE_WITH_LATITUDE', '38.9361129455516')
        output = output.replace('REPLACE_WITH_ZOOM_LEVEL', '11')

        output = add_footer(output, link_source='ward')

        with open('docs/' + generate_url(ward.ward_id, link_source='root'), 'w') as f:
            f.write(output)

    def run(self):

        for ry in [2012, 2022]:
            self.ward_list_page(redistricting_year=ry)

        self.build_all_ward_pages()


#!/usr/bin/env python
# -*- coding: utf-8 -*-

import collections
import numpy as np
import sympy as sp
import time

import dh
import jacobian
import inverse_kinematics
import utils

pwm = utils.import_pwm()

class Planner(object):
    '''
    This class selects actions for the manipulator
    This is extremely limited right now, for example
        - this doesn't account for constraints
        - it only outputs a single angle to achieve
    '''

    def __init__(self, params):
        '''
        Args:
            - params: DH params defining robot links
                dictionary of dictionaries
                first set of keys is 1 up to 6 indicating the link number
                each link dictionary contains a map from string to sympy symbol
                valid strings are a,l,t,d
                a = alpha, l = length, t = theta, d = distance
        '''
        self.params = params
        # forward kinematics
        self.T, self.transforms = dh.build_transforms(params)
        # extract joint configuration
        self.qs = utils.extract_joints_from_params(params)
        self.nq = len(self.qs)
        # compute jacobian
        self.J = jacobian.jacobian(self.transforms, self.qs)
        # compute inverse of jacobian (this takes a while)
        self.J_inv = sp.zeros(6,6)
        self.J_inv[:self.nq,:] = utils.left_pseudoinv(self.J[:,:self.nq])
        self.J_inv_fn = sp.lambdify(self.qs, self.J_inv)

    def find_joint_config(self, p_des, q_cur):
        '''
        Description:
            - given an end-effector position and orientation vector 'pos', first
            finds the joint configuration yielding that position, then sets
            servos to achieve that configuration.

        Args:
            - p_des: 6-vector of floats. First 3 indicate x,y,z position, second 3
            indicate α, β, γ orientation. The desired state.
            - q_cur: current joint configuration. 6-vector of floats.
        '''
        # increase desired position to include any missing coordinates as zeros
        if len(p_des) < 6:
            zeros = np.zeros(6 - len(p_des))
            p_des = np.concatenate((p_des, zeros))

        # compute the joint angles that achieve the desired position
        p_des = sp.Matrix(p_des)
        q_cur = sp.Matrix(q_cur)
        q_des, valid = inverse_kinematics.find_joint_config(
            self.J,
            self.J_inv_fn,
            self.qs,
            p_des,
            q_cur,
            self.T
        )
        # assume joints are all revolute and that their angles should be
        # in the range [0,2pi], so clip them here
        q_des = utils.normalize_angles_0to2pi(q_des)
        return q_des

    def forward_kinematics(self, q):
        p = self.T.evalf(subs=dict(zip(self.qs, q)))[:-1,-1]
        return np.array(p).astype(float).reshape(-1)

class Servo(object):
    '''
    A servo on the manipulator
    '''
    def __init__(
            self,
            channel,
            min_angle=10,
            max_angle=170,
            min_pulse=150,
            max_pulse=600):
        self.channel = channel
        self.min_angle = min_angle
        self.max_angle = max_angle
        self.min_pulse = min_pulse
        self.max_pulse = max_pulse

    def set_state(self, pwm, rad):
        utils.set_servo_angle(
            pwm,
            self.channel,
            np.rad2deg(rad),
            self.min_angle,
            self.max_angle,
            self.min_pulse,
            self.max_pulse
        )

    def random_state(self):
        return np.deg2rad(
            self.min_angle + np.random.rand() * (self.max_angle - self.min_angle)
        )

class Controller(object):
    '''
    This class enacts the actions of the planner through communication with
    the servos on the manipulator
    '''
    def __init__(self, servos, address=0x40, debug=False):
        # Initialise the PWM device
        self.pwm = pwm.PWM(address)
        self.servos = servos
        self.debug = debug
        # initial end-effector position
        self.state = sp.zeros(6,1)

    def set_end_effector_pos(self, new_state):
        for i, servo in enumerate(self.servos):
            servo.set_state(self.pwm, new_state[i])
            self.state[i] = new_state[i]
        if self.debug:
            print('controller state: {}'.format(self.state))

    def random_state(self):
        qs = []
        for servo in self.servos:
            q = servo.random_state()
            qs.append(q)
        return qs

class Manipulator(object):
    '''
    Represents the manipulator and coordinates the planner and controller
    '''
    def __init__(self, planner, controller):
        self.planner = planner
        self.controller = controller

    def set_end_effector_position(self, pos):
        new_state = self.planner.find_joint_config(pos, self.controller.state)
        self.controller.set_end_effector_pos(new_state)

    def random_position(self):
        '''
        Returns a random end-effector position
        '''
        # sample valid joint configuration
        q = self.controller.random_state()
        # determine the position associated with this joint configuration
        pos = self.planner.forward_kinematics(q)
        return pos

def build_RR_manipulator(l1=1, l2=1):
    # symbols used throughout equations
    t1, t2 = sp.symbols('t1 t2')

    # compute transformation matrix
    params = dict()
    params[1] = collections.defaultdict(int, dict(t=t1))
    params[2] = collections.defaultdict(int, dict(l=l1, t=t2))
    params[3] = collections.defaultdict(int, dict(l=l2))

    # build manipulator
    planner = Planner(params)

    # build controller
    servos = [Servo(i) for i in range(2)]
    controller = Controller(servos)

    # build manipulator
    manipulator = Manipulator(planner, controller)
    return manipulator


class Solution:
    def nextLargerElement(self,arr,n):

        stack =[]
        ans = []
        for i in range (n-1,-1,-1):
            if len(stack)==0:
                ans.append(-1)
            elif len(stack)>0 and stack[-1] > arr[i]:
                ans.append(stack[-1])
            elif len(stack)>0 and stack[-1] < arr[i]:

                while (len(stack) !=0 and stack[-1]<=arr[i]):
                    stack.pop()

                if len(stack)==0:
                    ans.append(-1)
                else:
                    ans.append(stack[-1])
            stack.append(arr[i])
        return ans[::-1]


import json
from os import path

import requests

from app.models import Paste, File
from past3r.settings import CACHE_DIR, WEB3_STORAGE_TOKEN, WEB3_STORAGE_URL

def write_files(directory, files, metadata):
    filenames = []
    filepath_metadata = path.join(directory, 'metadata.json')

    for file in files:
        filepath = path.join(directory, file['name'])
        with open(path.join(CACHE_DIR, filepath), 'w') as file_manager:
            file_manager.write(file['content'])
        filenames.append({'path': filepath, 'syntax': file.get('syntax', 'plaintext')})

    with open(path.join(CACHE_DIR, filepath_metadata), 'w') as file_manager:
        file_manager.write(json.dumps(metadata))

    return filenames, filepath_metadata

def upload_file(*args, **kwargs):
    _id = kwargs.get('_id')
    paste = Paste.objects.get(id=_id)
    file_id = kwargs.get('file_id')
    filename = kwargs.get('filename')

    headers = {
        'Content-Type': 'application/json',
        'Authorization': f'Bearer {WEB3_STORAGE_TOKEN}'
    }

    file = File.objects.get(id=file_id, paste=paste)
    with open(path.join(CACHE_DIR, file.path), 'rb') as f:
        response = requests.request("POST", f"{WEB3_STORAGE_URL}/upload", headers=headers, data=f)
        file.cid = response.json().get("cid")
        file.save()

        push = File.objects.filter(id=file_id, cid='').count() == 0
        metadata = update_metadata(paste, paste.manifest_path, file.file_name, file.cid, 'files', push=push)

        print(f'## DONE: {metadata}')
        print(f'== DONE: {file.path} - {file.cid}')

def update_metadata(paste, filepath, field, value, type_field, push=False):
    abs_path = path.join(CACHE_DIR, filepath)
    with open(abs_path, 'r+') as f:
        metadata = json.loads(f.read())
        if type_field == 'files':
            metadata['files'][field]['cid'] = value
        f.seek(0)
        f.write(json.dumps(metadata))
        f.truncate()

    headers = {
        'Content-Type': 'application/json',
        'Authorization': f'Bearer {WEB3_STORAGE_TOKEN}'
    }

    if push:
        with open(abs_path, 'rb') as f:
            response = requests.request("POST", f"{WEB3_STORAGE_URL}/upload", headers=headers, data=f)
            paste.manifest_cid = response.json().get("cid")

            paste.save()
            return paste.manifest_cid
    return 'No update metadata'


from django.urls import path
from . import views
# http://127.0.0.1:8000/        => Index
# http://127.0.0.1:8000/index   => Index
# http://127.0.0.1:8000/blogs   => blogs
# http://127.0.0.1:8000/blogs/3 => blog-detalis

urlpatterns = [
    path("",views.index),
    path("index",views.index),
    path("mahmut",views.blogs),
    path("blogs/<int:id>",views.blog_details),
]


# Game codes-------------------------------------------------------------------------------------
import random
import time
user_num = int(input('Guess a number between 0-30:   '))
rand_num = random.randint(0,30)
num_variance = user_num - rand_num
user_guesses = 1
price_per_guess = 3

while num_variance != 0:
    user_guesses += 1
    if num_variance < 0:
        print (f'Oh no! Your guess is smaller than the magic number! Try again.')
    elif num_variance > 0:
        print(f'Oh no! Your guess is bigger than the magic number! Try again.')
    else:
        print(f'Not sure what you have entered. Try again with another input in a number format!')
    user_num = int(input('Try another number between 0-30:   '))
    num_variance = user_num - rand_num
print (f'Aha! You have guess the correct magic number {rand_num}!')
time.sleep(1)
print(f'Well... you took {user_guesses} guesses, '
      f'you now owe me £{price_per_guess*user_guesses} at £{price_per_guess} for each guesses.')


from selenium.webdriver.common.by import By
from .base_page_object import BasePage

class GoogleMainPage(BasePage):

    def __init__(self, context, base_url='https://www.google.ru/'):
        BasePage.__init__(
            self,
            context,
            base_url=base_url)

    locator_dictionary = {
        "search_input": (By.XPATH, '//input[@title="Поиск"]'),
        "search_button": (By.XPATH, '//*[@class="VlcLAe"]//input[@value="Поиск в Google"]')
    }


# Merge Sort Algorithm

# Time Complexity Best Case,Average Case and Worst Case ==> O(NlogN)
# Space Complexity ==> O(N)

def merge(array,left_array,right_array):

    left_index,right_index,array_index=0,0,0

    while left_index<len(left_array) and right_index<len(right_array):

        if left_array[left_index] < right_array[right_index]:

            array[array_index] = left_array[left_index]
            left_index +=1
            array_index+=1

        else:

            array[array_index] = right_array[right_index]
            right_index +=1
            array_index +=1

    while left_index<len(left_array):

        array[array_index] = left_array[left_index]
        left_index +=1
        array_index +=1

    while right_index<len(right_array):

        array[array_index] = right_array[right_index]
        right_index +=1
        array_index +=1

def mergeSort(array):

    if len(array)>1:

        mid = len(array)//2
        left = array[:mid]
        right = array[mid:]
        mergeSort(left)
        mergeSort(right)
        merge(array,left,right)

if __name__ == "__main__":

    array = [6,4,3,2,1,100,90,82,72,89,56]

    mergeSort(array)

    print(array)


# -*- coding: utf-8 -*-
import numpy as np
import torch
from torch.utils.data import Dataset
from ..utils.misc import pbar

class NumpySequenceDataset(Dataset):
    """Read a sequence of numpy arrays.

    Arguments:
        fname (str or Path): Path to a list of paths to Numpy `.npy` files
            where each file contains an array with shape `(n_features, feat_dim)`.
            If the lines are in `<path>:<len>` format, additional length
            information will be used for bucketing. If the file itself is
            a `.npy` file, it will be treated as an array of numpy objects.
            For cases where all features are the same length, you should use
            `NumpyDataset`.
    """

    def __init__(self, fname):
        self.fname = fname
        self.data = []
        self.lengths = []
        self.has_lengths = False

        if not self.fname:
            raise RuntimeError('{} does not exist.'.format(self.fname))

        if str(self.fname).endswith('.npy'):
            self.data = np.load(self.fname)
            self.lengths = [x.shape[0] for x in self.data]
            self._read = lambda idx: self.data[idx]
            self.has_lengths = True
        else:
            self._read = lambda idx: np.load(self.data[idx])
            with open(self.fname) as f_list:
                # Detect file format and seek back
                self.has_lengths = ':' in f_list.readline()
                f_list.seek(0)
                for line in pbar(f_list, unit='sents'):
                    if self.has_lengths:
                        path, length = line.strip().split(':')
                        self.lengths.append(int(length))
                    else:
                        path = line.strip()
                    self.data.append(path)

        # Set dataset size
        self.size = len(self.data)

    @staticmethod
    def to_torch(batch):
        # List of (t, feat_dim)
        max_len = max(x.shape[0] for x in batch)
        width = batch[0].shape[1]
        padded = [np.zeros((max_len, width)) for _ in batch]
        for pad, x in zip(padded, batch):
            pad[:x.shape[0]] = x
        # padded is (n_samples, t, feat_dim)
        # return (n, f, t) for compatibility with the other input sources
        return torch.from_numpy(
            np.array(padded, dtype='float32')).transpose(1, 2)

    def __getitem__(self, idx):
        # Each item is (t, feat_dim)
        return self._read(idx)

    def __len__(self):
        return self.size

    def __repr__(self):
        s = "{} (has_lengths={}) ({} samples)\n".format(
            self.__class__.__name__, self.has_lengths, self.__len__())
        s += " {}".format(self.fname)
        return s