import numpy as np
import matplotlib.pyplot as plt
from part4 import kf_smooth

def time_and_meas_update(Sigma, A, Sigma_w, C, R):
    '''Your code here'''
    # all the definitions are similar to KF implementation, performing time update and measurement update
    # here Sigma_w is Q in the slides. You need to output the Sigma for the measurement update.
    n = A.shape[0]
    Sigma_new = Sigma # this line is given
    Sigma_new = A @ Sigma_new @ A.T + Sigma_w
    S = C @ Sigma_new @ C.T + R
    K = Sigma_new @ C.T @ np.linalg.inv(S)
    Sigma_new = (np.identity(n) - K @ C) @ Sigma_new
    '''your code end'''
    return Sigma_new

# initialize the three sensors
n=3
A  = np.array([[-0.6, 0.8, 0.5], [-0.1, 1.5, -1.1], [1.1, 0.4, -0.2]])
Sigma_w = np.eye(n)
S1 = np.array([[0.74, -0.21, -0.64]])
S2 = np.array([[0.37, 0.86, 0.37]])
S3 = np.array([[0, 0, 1]])
Sigma_S1 = np.array([[0.1**2]])
Sigma_S2 = np.array([[0.1**2]])
Sigma_S3 = np.array([[0.1**2]])

Sigma_0 = np.eye(n)

T = 50
s1_trace = []
s2_trace = []
s3_trace = []

# same sensor version code provided as an example
Sigma = Sigma_0
for t in range(T):
    Sigma = time_and_meas_update(Sigma, A, Sigma_w, S1, Sigma_S1)
    s1_trace.append(np.trace(Sigma))

Sigma = Sigma_0
for t in range(T):
    Sigma = time_and_meas_update(Sigma, A, Sigma_w, S2, Sigma_S2)
    s2_trace.append(np.trace(Sigma))

Sigma = Sigma_0
for t in range(T):
    Sigma = time_and_meas_update(Sigma, A, Sigma_w, S3, Sigma_S3)
    s3_trace.append(np.trace(Sigma))

plt.figure()
plt.plot(s1_trace, 'b', label='Sigma_S1')
plt.plot(s2_trace,'g', label='Sigma_S2')
plt.plot(s3_trace,'r', label='Sigma_S3')
plt.legend()
plt.show()

Sigma = Sigma_0
s123_trace = []
for t in range(T):
    '''Your code here'''
    # you need to write the round robin algo to choose which Sigma to use
    # note C is selected from Sigma_S*
    if t % n == 0:
        C = S1
        R = Sigma_S1
    elif t % n == 1:
        C = S2
        R = Sigma_S2
    else:
        C = S3
        R = Sigma_S3
    '''Your code end'''

    Sigma = time_and_meas_update(Sigma, A, Sigma_w, C, R)
    s123_trace.append(np.trace(Sigma))

plt.figure()
plt.plot(s123_trace, '--')
plt.show()

# greedy:

Sigma = Sigma_0
s1_greedy_trace = []
s2_greedy_trace = []
s3_greedy_trace = []
sgreedy_choice = []
sgreedy_trace = []
for t in range(T):
    C = S1
    R = Sigma_S1
    Sigma_try1 = time_and_meas_update(Sigma, A, Sigma_w, C, R)
    s1_greedy_trace.append(np.trace(Sigma_try1))

    C = S2
    R = Sigma_S2
    Sigma_try2 = time_and_meas_update(Sigma, A, Sigma_w, C, R)
    s2_greedy_trace.append(np.trace(Sigma_try2))

    C = S3
    R = Sigma_S3
    Sigma_try3 = time_and_meas_update(Sigma, A, Sigma_w, C, R)
    s3_greedy_trace.append(np.trace(Sigma_try3))
    '''Your code here'''
    # your greedy algorithm
    # select your Sigma based on tries!
    greedy_choice = np.argmin([s1_greedy_trace[t], s2_greedy_trace[t], s3_greedy_trace[t]])
    if greedy_choice == 0:
        Sigma = Sigma_try1
    elif greedy_choice == 1:
        Sigma = Sigma_try2
    else:
        Sigma = Sigma_try3
    sgreedy_trace.append(np.trace(Sigma))
    '''Your code end'''

plt.figure()
plt.plot(sgreedy_trace, 'g--')
plt.show()


import numpy

from typing import Optional, cast

from UM.Qt.Bindings.Theme import Theme
from UM.Qt.QtApplication import QtApplication
from UM.Logger import Logger

class LayerPolygon:
    NoneType = 0
    Inset0Type = 1
    InsetXType = 2
    SkinType = 3
    SupportType = 4
    SkirtType = 5
    InfillType = 6
    SupportInfillType = 7
    MoveCombingType = 8
    MoveRetractionType = 9
    SupportInterfaceType = 10
    PrimeTowerType = 11
    __number_of_types = 12

    __jump_map = numpy.logical_or(numpy.logical_or(numpy.arange(__number_of_types) == NoneType,
                                                   numpy.arange(__number_of_types) == MoveCombingType),
                                                   numpy.arange(__number_of_types) == MoveRetractionType)

    def __init__(self, extruder: int, line_types: numpy.ndarray, data: numpy.ndarray,
                 line_widths: numpy.ndarray, line_thicknesses: numpy.ndarray, line_feedrates: numpy.ndarray) -> None:
        """LayerPolygon, used in ProcessSlicedLayersJob

        :param extruder: The position of the extruder
        :param line_types: array with line_types
        :param data: new_points
        :param line_widths: array with line widths
        :param line_thicknesses: array with type as index and thickness as value
        :param line_feedrates: array with line feedrates
        """

        self._extruder = extruder
        self._types = line_types
        unknown_types = numpy.where(self._types >= self.__number_of_types, self._types, None)
        if unknown_types.any():
            # Got faulty line data from the engine.
            for idx in unknown_types:
                Logger.warning(f"Found an unknown line type at: {idx}")
                self._types[idx] = self.NoneType
        self._data = data
        self._line_widths = line_widths
        self._line_thicknesses = line_thicknesses
        self._line_feedrates = line_feedrates

        self._vertex_begin = 0
        self._vertex_end = 0
        self._index_begin = 0
        self._index_end = 0

        self._jump_mask = self.__jump_map[self._types]
        self._jump_count = numpy.sum(self._jump_mask)
        self._mesh_line_count = len(self._types) - self._jump_count
        self._vertex_count = self._mesh_line_count + numpy.sum(self._types[1:] == self._types[:-1])

        # Buffering the colors shouldn't be necessary as it is not
        # re-used and can save a lot of memory usage.
        self._color_map = LayerPolygon.getColorMap()
        self._colors = self._color_map[self._types]  # type: numpy.ndarray

        # When type is used as index returns true if type == LayerPolygon.InfillType
        # or type == LayerPolygon.SkinType
        # or type == LayerPolygon.SupportInfillType
        # Should be generated in better way, not hardcoded.
        self._is_infill_or_skin_type_map = numpy.array([0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0], dtype=bool)

        self._build_cache_line_mesh_mask = None  # type: Optional[numpy.ndarray]
        self._build_cache_needed_points = None  # type: Optional[numpy.ndarray]

    def buildCache(self) -> None:
        # For the line mesh we do not draw Infill or Jumps. Therefore those lines are filtered out.
        self._build_cache_line_mesh_mask = numpy.ones(self._jump_mask.shape, dtype = bool)
        self._index_begin = 0
        self._index_end = cast(int, numpy.sum(self._build_cache_line_mesh_mask))

        self._build_cache_needed_points = numpy.ones((len(self._types), 2), dtype = bool)
        # Only if the type of line segment changes do we need to add an extra vertex to change colors
        self._build_cache_needed_points[1:, 0][:, numpy.newaxis] = self._types[1:] != self._types[:-1]
        # Mark points as unneeded if they are of types we don't want in the line mesh according to the calculated mask
        numpy.logical_and(self._build_cache_needed_points, self._build_cache_line_mesh_mask, self._build_cache_needed_points)

        self._vertex_begin = 0
        self._vertex_end = cast(int, numpy.sum(self._build_cache_needed_points))

    def build(self, vertex_offset: int, index_offset: int, vertices: numpy.ndarray,
              colors: numpy.ndarray, line_dimensions: numpy.ndarray, feedrates: numpy.ndarray,
              extruders: numpy.ndarray, line_types: numpy.ndarray, indices: numpy.ndarray) -> None:
        """Set all the arrays provided by the function caller, representing the LayerPolygon

        The arrays are either by vertex or by indices.

        :param vertex_offset: determines where to start and end filling the arrays
        :param index_offset: determines where to start and end filling the arrays
        :param vertices: vertex numpy array to be filled
        :param colors: vertex numpy array to be filled
        :param line_dimensions: vertex numpy array to be filled
        :param feedrates: vertex numpy array to be filled
        :param extruders: vertex numpy array to be filled
        :param line_types: vertex numpy array to be filled
        :param indices: index numpy array to be filled
        """

        if self._build_cache_line_mesh_mask is None or self._build_cache_needed_points is None:
            self.buildCache()

        if self._build_cache_line_mesh_mask is None or self._build_cache_needed_points is None:
            Logger.log("w", "Failed to build cache for layer polygon")
            return

        line_mesh_mask = self._build_cache_line_mesh_mask
        needed_points_list = self._build_cache_needed_points

        # Index to the points we need to represent the line mesh.
        # This is constructed by generating simple start and end points for each line.
        # For line segment n, these are points n and n+1. Row n reads [n n+1]
        # Then the indices for the points we don't need are thrown away based on the pre-calculated list.
        index_list = (numpy.arange(len(self._types)).reshape((-1, 1)) + numpy.array([[0, 1]])).reshape((-1, 1))[needed_points_list.reshape((-1, 1))]

        # The relative values of begin and end indices have already been set in buildCache, so we only need to offset them to the parents offset.
        self._vertex_begin += vertex_offset
        self._vertex_end += vertex_offset

        # Points are picked based on the index list to get the vertices needed.
        vertices[self._vertex_begin:self._vertex_end, :] = self._data[index_list, :]

        # Create an array with colors for each vertex and remove the color data for the points that has been thrown away.
        colors[self._vertex_begin:self._vertex_end, :] = numpy.tile(self._colors, (1, 2)).reshape((-1, 4))[needed_points_list.ravel()]

        # Create an array with line widths and thicknesses for each vertex.
        line_dimensions[self._vertex_begin:self._vertex_end, 0] = numpy.tile(self._line_widths, (1, 2)).reshape((-1, 1))[needed_points_list.ravel()][:, 0]
        line_dimensions[self._vertex_begin:self._vertex_end, 1] = numpy.tile(self._line_thicknesses, (1, 2)).reshape((-1, 1))[needed_points_list.ravel()][:, 0]

        # Create an array with feedrates for each line
        feedrates[self._vertex_begin:self._vertex_end] = numpy.tile(self._line_feedrates, (1, 2)).reshape((-1, 1))[needed_points_list.ravel()][:, 0]

        extruders[self._vertex_begin:self._vertex_end] = self._extruder

        # Convert type per vertex to type per line
        line_types[self._vertex_begin:self._vertex_end] = numpy.tile(self._types, (1, 2)).reshape((-1, 1))[needed_points_list.ravel()][:, 0]

        # The relative values of begin and end indices have already been set in buildCache,
        # so we only need to offset them to the parents offset.
        self._index_begin += index_offset
        self._index_end += index_offset

        indices[self._index_begin:self._index_end, :] = numpy.arange(self._index_end-self._index_begin, dtype=numpy.int32).reshape((-1, 1))
        # When the line type changes the index needs to be increased by 2.
        indices[self._index_begin:self._index_end, :] += numpy.cumsum(needed_points_list[line_mesh_mask.ravel(), 0], dtype = numpy.int32).reshape((-1, 1))
        # Each line segment goes from it's starting point p to p+1, offset by the vertex index.
        # The -1 is to compensate for the necessarily True value of needed_points_list[0,0] which causes an unwanted +1 in cumsum above.
        indices[self._index_begin:self._index_end, :] += numpy.array([self._vertex_begin - 1, self._vertex_begin])

        self._build_cache_line_mesh_mask = None
        self._build_cache_needed_points = None

    def getColors(self):
        return self._colors

    def mapLineTypeToColor(self, line_types: numpy.ndarray) -> numpy.ndarray:
        return self._color_map[line_types]

    def isInfillOrSkinType(self, line_types: numpy.ndarray) -> numpy.ndarray:
        return self._is_infill_or_skin_type_map[line_types]

    def lineMeshVertexCount(self) -> int:
        return self._vertex_end - self._vertex_begin

    def lineMeshElementCount(self) -> int:
        return self._index_end - self._index_begin

    @property
    def extruder(self):
        return self._extruder

    @property
    def types(self):
        return self._types

    @property
    def data(self):
        return self._data

    @property
    def elementCount(self):
        return (self._index_end - self._index_begin) * 2  # The range of vertices multiplied by 2 since each vertex is used twice

    @property
    def lineWidths(self):
        return self._line_widths

    @property
    def lineThicknesses(self):
        return self._line_thicknesses

    @property
    def lineFeedrates(self):
        return self._line_feedrates

    @property
    def jumpMask(self):
        return self._jump_mask

    @property
    def meshLineCount(self):
        return self._mesh_line_count

    @property
    def jumpCount(self):
        return self._jump_count

    def getNormals(self) -> numpy.ndarray:
        """Calculate normals for the entire polygon using numpy.

        :return: normals for the entire polygon
        """

        normals = numpy.copy(self._data)
        normals[:, 1] = 0.0  # We are only interested in 2D normals

        # Calculate the edges between points.
        # The call to numpy.roll shifts the entire array by one
        # so that we end up subtracting each next point from the current, wrapping around.
        # This gives us the edges from the next point to the current point.
        normals = numpy.diff(normals, 1, 0)

        # Calculate the length of each edge using standard Pythagoras
        lengths = numpy.sqrt(normals[:, 0] ** 2 + normals[:, 2] ** 2)
        # The normal of a 2D vector is equal to its x and y coordinates swapped
        # and then x inverted. This code does that.
        normals[:, [0, 2]] = normals[:, [2, 0]]
        normals[:, 0] *= -1

        # Normalize the normals.
        normals[:, 0] /= lengths
        normals[:, 2] /= lengths

        return normals

    __color_map = None  # type: numpy.ndarray

    @classmethod
    def getColorMap(cls) -> numpy.ndarray:
        """Gets the instance of the VersionUpgradeManager, or creates one."""

        if cls.__color_map is None:
            theme = cast(Theme, QtApplication.getInstance().getTheme())
            cls.__color_map = numpy.array([
                theme.getColor("layerview_none").getRgbF(),  # NoneType
                theme.getColor("layerview_inset_0").getRgbF(),  # Inset0Type
                theme.getColor("layerview_inset_x").getRgbF(),  # InsetXType
                theme.getColor("layerview_skin").getRgbF(),  # SkinType
                theme.getColor("layerview_support").getRgbF(),  # SupportType
                theme.getColor("layerview_skirt").getRgbF(),  # SkirtType
                theme.getColor("layerview_infill").getRgbF(),  # InfillType
                theme.getColor("layerview_support_infill").getRgbF(),  # SupportInfillType
                theme.getColor("layerview_move_combing").getRgbF(),  # MoveCombingType
                theme.getColor("layerview_move_retraction").getRgbF(),  # MoveRetractionType
                theme.getColor("layerview_support_interface").getRgbF(),   # SupportInterfaceType
                theme.getColor("layerview_prime_tower").getRgbF()   # PrimeTowerType
            ])

        return cls.__color_map


from pydicom import dcmread
import numpy as np
from scipy.sparse import csc_matrix
import matplotlib.pyplot as plt
import math
from mpl_toolkits.mplot3d import Axes3D  # noqa: F401 unused import
import pandas as pd
import scipy.stats as stats

def fun(contour_dataset, image, zcoord):
    img_ID = image.SOPInstanceUID
    img = image
    img_arr = img.pixel_array
    x_spacing, y_spacing = float(img.PixelSpacing[0]), float(img.PixelSpacing[1])
    origin_x, origin_y, _ = img.ImagePositionPatient
    rows = []
    cols = []
    #массивы для хранения номеров контуров
    CTNumbers = []
    T1Numbers = []
    T2Numbers = []
    #массивы контуров
    CTX = []
    CTY = []
    T1X = []
    T1Y = []
    T2X = []
    T2Y = []
    #буфер
    CTXT = []
    CTYT = []
    T1XT = []
    T1YT = []
    T2XT = []
    T2YT = []
    #массивы для центров контуров
    CTXPoints = []
    T1XPoints = []
    T2XPoints = []
    CTYPoints = []
    T1YPoints = []
    T2YPoints = []
    #инициализация графиков
    fig, ax = plt.subplots(1, figsize=(60, 50))
    #заполнение массивов номерами контуров, чтобы произвести дальнейшее распределение контуров по своим массивам, согласно их номераам
    for ObservationT in contour_dataset.RTROIObservationsSequence:
        if 'CT' in ObservationT.ROIObservationLabel:
            CTNumbers.append(int(ObservationT.ReferencedROINumber))
        if 'T1' in ObservationT.ROIObservationLabel:
            T1Numbers.append(int(ObservationT.ReferencedROINumber))
        if 'T2' in ObservationT.ROIObservationLabel:
            T2Numbers.append(int(ObservationT.ReferencedROINumber))
#обработка данных
    for ROIContourSequenceNumber in contour_dataset.ROIContourSequence:
        for t in range(0, len(ROIContourSequenceNumber.ContourSequence)):
            contour_coordinates = ROIContourSequenceNumber.ContourSequence[t].ContourData
            # x, y, z координаты контура в миллиметрах
            x0 = contour_coordinates[len(contour_coordinates) - 3]
            y0 = contour_coordinates[len(contour_coordinates) - 2]
            z0 = contour_coordinates[len(contour_coordinates) - 1]
            coordinates = []
            if (contour_coordinates[2] == zcoord):
                tempry = -1
                #преобразование
                for i in range(0, len(contour_coordinates), 3):
                    x = contour_coordinates[i]
                    y = contour_coordinates[i + 1]
                    z = contour_coordinates[i + 2]
                    l = math.sqrt((x - x0) * (x - x0) + (y - y0) * (y - y0) + (z - z0) * (z - z0))
                    l = math.ceil(l * 2) + 1
                    for k in range(1, l + 1):
                        coordinates.append([(x - x0) * k / l + x0, (y - y0) * k / l + y0, (z - z0) * k / l + z0])
                    x0 = x
                    y0 = y
                    z0 = z
                    #заполнение массивов контуров CT T1 T2
                    if ROIContourSequenceNumber.ReferencedROINumber in CTNumbers:
                        CTX.append((x - origin_x) / x_spacing)
                        CTY.append((y - origin_y) / y_spacing)
                        CTXT.append((x - origin_x) / x_spacing)
                        CTYT.append((y - origin_y) / y_spacing)
                        #этот блок ниже отвечает за прорисовку контура
                        if tempry != ROIContourSequenceNumber.ReferencedROINumber:
                            xt = CTXT[-1]
                            yt = CTYT[-1]
                            CTXT.pop() #ПОСЛЕДНИЙ ЭЛЕМЕНТ НАДО ПЕРЕНЕСТИ В НАЧАЛО СЛЕДУЮЩЕГО КОНТУРА
                            CTYT.pop()
                            # на ноль делить нельзя, поэтому откидываем эти варианты (это не выкинет точки, все на месте)
                            if len(CTXT) != 0:
                                CTXPoints.append(sum(CTXT) / len(CTXT))
                                CTYPoints.append(sum(CTYT) / len(CTYT))
                            # if len(CTXT) == 0:
                            #     CTXPoints.append(sum(CTX) / len(CTX))
                            # if len(CTYT) == 0:
                            #     CTYPoints.append(sum(CTY) / len(CTY))
                            ax.plot(CTXT, CTYT, color='g', linestyle='-')
                            CTXT.clear()
                            CTYT.clear()
                            CTXT.append(xt)
                            CTYT.append(yt)
                    if ROIContourSequenceNumber.ReferencedROINumber in T1Numbers:
                        T1X.append((x - origin_x) / x_spacing)
                        T1Y.append((y - origin_y) / y_spacing)
                        T1XT.append((x - origin_x) / x_spacing)
                        T1YT.append((y - origin_y) / y_spacing)
                        # этот блок ниже отвечает за прорисовку контура
                        if tempry != ROIContourSequenceNumber.ReferencedROINumber:
                            xt = T1XT[-1]
                            yt = T1YT[-1]
                            T1XT.pop()
                            T1YT.pop()
                            #на ноль делить нельзя, поэтому откидываем эти варианты (это не выкинет точки, все на месте)
                            if len(T1XT) != 0 :
                                T1XPoints.append(sum(T1XT) / len(T1XT))
                                T1YPoints.append(sum(T1YT) / len(T1YT))
                            # if len(T1XT) == 0:
                            #     T1XPoints.append(sum(T1X) / len(T1X))
                            # if len(CTYT) == 0:
                            #     T1YPoints.append(sum(T1Y) / len(T1Y))
                            ax.plot(T1XT, T1YT, color='r', linestyle='-')
                            T1XT.clear()
                            T1YT.clear()
                            T1XT.append(xt)
                            T1YT.append(yt)
                    if ROIContourSequenceNumber.ReferencedROINumber in T2Numbers:
                        T2X.append((x - origin_x) / x_spacing)
                        T2Y.append((y - origin_y) / y_spacing)
                        T2XT.append((x - origin_x) / x_spacing)
                        T2YT.append((y - origin_y) / y_spacing)
                        # этот блок ниже отвечает за прорисовку контура
                        if tempry != ROIContourSequenceNumber.ReferencedROINumber:
                            xt = T2XT[-1]
                            yt = T2YT[-1]
                            T2XT.pop()
                            T2YT.pop()
                            # на ноль делить нельзя, поэтому откидываем эти варианты (это не выкинет точки, все на месте)
                            if len(T2XT) != 0:
                                T2XPoints.append(sum(T2XT) / len(T2XT))
                                T2YPoints.append(sum(T2YT) / len(T2YT))
                            # if len(T2XT) == 0:
                            #     T2XPoints.append(sum(T2X) / len(T2X))
                            # if len(CTYT) == 0:
                            #     T2YPoints.append(sum(T2Y) / len(T2Y))
                            ax.plot(T2XT, T2YT, color='b', linestyle='-')
                            T2XT.clear()
                            T2YT.clear()
                            T2XT.append(xt)
                            T2YT.append(yt)
                    tempry = ROIContourSequenceNumber.ReferencedROINumber
            pixel_coordinates = [(np.round((y - origin_y) / y_spacing), np.round((x - origin_x) / x_spacing)) for x, y, _ in coordinates]
            for i, j in list(set(pixel_coordinates)):
                rows.append(i)
                cols.append(j)
            contour_arr = csc_matrix((np.ones_like(rows), (rows, cols)), dtype=np.int8, shape=(img_arr.shape[0], img_arr.shape[1])).toarray()

    #графики для центров контуров
    plt.scatter(CTXPoints, CTYPoints, color='g', marker='.')
    plt.scatter(T1XPoints, T1YPoints, color='r', marker='.')
    plt.scatter(T2XPoints, T2YPoints, color='b', marker='.')
    # fig = plt.gcf()
    plt.show()
    # plt.draw()
    # fig.savefig('contours.png', dpi=300)
    plt.figure(1)
    # обсчет точек по тройкам CT-T1 CT-T2 T1-T2
    distancesCTT1 = []
    distancesCTT2 = []
    # ручная обработка первых трех выбивающихся точек (не очень сработало :с )
    # xa = CTXPoints[0]
    # ya = CTYPoints[0]
    # xb = CTXPoints[1]
    # yb = CTYPoints[1]
    #
    # CTXPoints[0] = CTXPoints[2]
    # CTYPoints[0] = CTYPoints[2]
    # CTXPoints[2] = xa
    # CTYPoints[2] = ya
    # CTXPoints[1] = CTXPoints[0]
    # CTYPoints[1] = CTYPoints[0]
    # CTXPoints[0] = xb
    # CTYPoints[0] = yb
    # начинается не от 0, а от 3, потому что отброшены первые три значения
    for i in range(3, len(T1XPoints)):
        distancesCTT1.append(math.sqrt((CTXPoints[i] - T1XPoints[i]) ** 2 + (CTYPoints[i] - T1YPoints[i]) ** 2))
    for i in range(3, len(T2XPoints)):
        distancesCTT2.append(math.sqrt((CTXPoints[i] - T2XPoints[i]) ** 2 + (CTYPoints[i] - T2YPoints[i]) ** 2))
    print(distancesCTT1)
    print(len(distancesCTT1), "/ 88")
    print(distancesCTT2)
    print(len(distancesCTT2), "/ 88")
    meandistanceCTT1 = np.mean(distancesCTT1)
    meandistanceCTT2 = np.mean(distancesCTT2)
    print("mean distance CT T1 = ", round(meandistanceCTT1, 5), " mm")
    print("max distance CT T1 = ", round(max(distancesCTT1), 5), " mm")
    print("min distance CT T1 = ", round(min(distancesCTT1), 5), " mm")

    print("mean distance CT T2 = ", round(meandistanceCTT2, 5), " mm")
    print("max distance CT T2 = ", round(max(distancesCTT2), 5), " mm")
    print("min distance CT T2 = ", round(min(distancesCTT2), 5), " mm")

    # графики для отклонений T1 и T2 от СТ
    d = dict(T1 = np.array(distancesCTT1), T2 = np.array(distancesCTT2))
    df = pd.DataFrame(dict([(k, pd.Series(v)) for k, v in d.items()]))

    # df = pd.DataFrame({
    #     'T1': distancesCTT1,
    #     'T2': distancesCTT2,
    # })
    df = df.plot.kde()
    plt.show()

    return img_arr, contour_arr, img_ID, CTX, CTY, T1X, T1Y, T2X, T2Y

#найти все доступные координаты z контуров
def zcoords(contour_dataset):
    print("Possible z coordinates")
    possibleZ = []
    for q in range(0, len(contour_dataset.ROIContourSequence)):
        for p in range(0, len(contour_dataset.ROIContourSequence[q].ContourSequence)):
            contour_coordinates = contour_dataset.ROIContourSequence[q].ContourSequence[p].ContourData
            for i in range(0, len(contour_coordinates), 3):
                z = contour_coordinates[i + 2]
                possibleZ.append(z)
    possibleZ = list(set(possibleZ))
    possibleZ.sort()
    for x in possibleZ: print(x)

if __name__ == "__main__":
    #путь до папки
    path = 'C:\\Users\\bzavo\\PycharmProjects\\MainProject\\DICOM\\'
    filename = 'RTSS.dcm'
    image = 'IMG0000000100.dcm'
    ds = dcmread(path + filename)
    image = dcmread(path + image)
    #все данные есть при z=-14
    zcoords(ds)
    print("z = -14 или -24 отлично подходит")
    zcoord = float(input("Enter Z coordinate from the list above \n"))
    t = fun(ds, image, zcoord)


"""Tests for ``highcharts.no_data``."""
from copy import deepcopy
import pytest

from json.decoder import JSONDecodeError
from validator_collection import checkers

from highcharts_core.headless_export import ExportServer as cls
from highcharts_core.options import HighchartsOptions
from highcharts_core import errors
from tests.fixtures import input_files, check_input_file, to_camelCase, to_js_dict, \
    Class__init__, Class__to_untrimmed_dict, Class_from_dict, Class_to_dict, \
    Class_from_js_literal, run_download_tests, create_output_directory

STANDARD_PARAMS = [
    ({}, None),
]

@pytest.mark.parametrize('kwargs, error', STANDARD_PARAMS)
def test__init__(kwargs, error):
    Class__init__(cls, kwargs, error)

@pytest.mark.parametrize('kwargs, error', STANDARD_PARAMS)
def test__to_untrimmed_dict(kwargs, error):
    Class__to_untrimmed_dict(cls, kwargs, error)

@pytest.mark.parametrize('kwargs, error',  STANDARD_PARAMS)
def test_from_dict(kwargs, error):
    Class_from_dict(cls, kwargs, error)

@pytest.mark.parametrize('kwargs, error',  STANDARD_PARAMS)
def test_to_dict(kwargs, error):
    from tests.fixtures import trim_expected_dict, does_kwarg_value_match_result
    from validator_collection import checkers

    kwargs_copy = deepcopy(kwargs)
    if not kwargs:
        kwargs_copy['url'] = 'https://export.highcharts.com'
        kwargs_copy['format'] = 'png'
        kwargs_copy['scale'] = 1
        kwargs_copy['use_base64'] = False
        kwargs_copy['no_download'] = False
        kwargs_copy['async_rendering'] = False
        kwargs_copy['constructor'] = 'Chart'

        untrimmed_expected = {
            'url': kwargs_copy['url'],
            'type': kwargs_copy['format'],
            'scale': kwargs_copy['scale'],
            'constr': kwargs_copy['constructor'],
            'b64': kwargs_copy['use_base64'],
            'noDownload': kwargs_copy['no_download'],
            'asyncRendering': kwargs_copy['async_rendering']
        }

    else:
        untrimmed_expected = to_js_dict(deepcopy(kwargs))

    expected = trim_expected_dict(untrimmed_expected)
    check_dicts = True
    for key in expected:
        if not checkers.is_type(expected[key], (str, int, float, bool, list, dict)):
            check_dicts = False
        elif isinstance(expected[key], str) and expected[key].startswith('function'):
            check_dicts = False
        elif isinstance(expected[key], str) and expected[key].startswith('class'):
            check_dicts = False

    if not error:
        instance = cls(**kwargs)
        result = instance.to_dict()
        assert result is not None
        assert isinstance(result, dict) is True
        print('EXPECTED:')
        print(expected)
        print('RESULT:')
        print(result)
        if check_dicts:
            assert len(expected) == len(result)
            for key in expected:
                print(f'CHECKING: {key}')
                assert does_kwarg_value_match_result(expected[key],
                                                     result.get(key)) is True
    else:
        with pytest.raises(error):
            instance = cls(**kwargs)
            result = instance.to_dict()

@pytest.mark.parametrize('value, error', [
    ({
        'url': 'https://export.highcharts.com',
        'protocol': 'https',
        'domain': 'export.highcharts.com',
        'port': None,
        'path': None
    }, None),
    ({
        'url': 'https://export.highcharts.com:1234/some_path_goes_here/andcontinueshere',
        'protocol': 'https',
        'domain': 'export.highcharts.com',
        'port': 1234,
        'path': 'some_path_goes_here/andcontinueshere'
    }, None),
    ({
        'url': 'http://www.highcharts.com/some_path_goes_here/andcontinueshere',
        'protocol': 'http',
        'domain': 'www.highcharts.com',
        'port': None,
        'path': 'some_path_goes_here/andcontinueshere'
    }, None),
    ({
        'url': 'http://www.highcharts.com:8080',
        'protocol': 'http',
        'domain': 'www.highcharts.com',
        'port': 8080,
        'path': None
    }, None),
])
def test_url(value, error):
    instance = cls()
    if not error:
        if 'expected_url' not in value and 'url' in value:
            value['expected_url'] = value.get('url')

        url = value.get('url', None)

        instance.url = url
        assert instance.url is not None
        assert instance.url == value.get('expected_url')
        assert instance.protocol == value.get('protocol')
        assert instance.domain == value.get('domain')
        assert instance.port == value.get('port')
        assert instance.path == value.get('path')
    else:
        with pytest.raises(error):
            instance.url = value.get('url')

@pytest.mark.parametrize('input_filename, target_filename, kwargs, error', [
    ('headless_export/basic.json',
     'headless_export/output/test-basic.png',
     {
      'timeout': 5,
      'format_': 'png',
      'constructor': 'Chart'
     },
     None),
    ('headless_export/with-series-types.js',
     'headless_export/output/test-with-series-types.png',
     {
      'timeout': 5,
      'format_': 'png',
      'constructor': 'Chart'
     },
     None),
    ('headless_export/with-chart-type.js',
     'headless_export/output/test-with-chart-type.png',
     {
      'timeout': 5,
      'format_': 'png',
      'constructor': 'Chart'
     },
     None),
    ('headless_export/with-chart-type.js',
     'headless_export/output/test-with-chart-type.svg',
     {
      'timeout': 5,
      'format_': 'svg',
      'constructor': 'Chart'
     },
     None),
])
def test_get_chart(input_files,
                   run_download_tests,
                   create_output_directory,
                   input_filename,
                   target_filename,
                   kwargs,
                   error):
    if run_download_tests:
        input_file = check_input_file(input_files, input_filename)
        target_file = check_input_file(input_files,
                                       target_filename,
                                       create_directory = create_output_directory)

        with open(input_file, 'r') as file_:
            as_str = file_.read()

        options = HighchartsOptions.from_js_literal(as_str)

        kwargs['options'] = options

        if target_filename:
            kwargs['filename'] = target_file

        if not error:
            result = cls.get_chart(**kwargs)

            format = kwargs.get('format_', None)
            print(f'TESTING FORMAT: {format}')

            assert result is not None
            if target_filename:
                assert checkers.is_on_filesystem(target_file) is True
                if format == 'svg':
                    with open(target_file, 'r', encoding = 'utf-8') as file_:
                        file_contents = file_.read()
                    contents = str(file_contents)
                    assert contents.startswith(
                        '<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"'
                    ) is True


import copy
import random
from typing import Optional, List

from ..services.spu_feature_service import SpuFeatureService
from ...entity.rec_item import RecItem

class HotsRecall(object):
    def get_candidates(self, k: Optional[int] = None) -> List[RecItem]:
        """
        获取前k个热映商品
        :param k: 待获取的数量，如果为None，表示获取所有
        :return: 结果
        """
        return self._get_hot_items(k)

    @staticmethod
    def _get_hot_items(k: Optional[int] = None) -> List[RecItem]:
        spu_ids = SpuFeatureService.get_hot_ids()  # 获取所有的热映商品id列表
        if spu_ids is None or len(spu_ids) == 0:
            return []
        if k is not None and k > 0:
            spu_ids = copy.deepcopy(spu_ids)
            random.shuffle(spu_ids)
            spu_ids = spu_ids[:k]
        items: List[RecItem] = []
        for spu_id in spu_ids:
            items.append(RecItem.get_recall_rec_item(spu_id, 1.0, 'hots', 'hots'))
        return items


import math
import sys
import time
from typing import Tuple
from codebase.real_world.base.getters import Getters
from codebase.real_world.base.senders import Senders
from socket import socket
from codebase.real_world.base.base_client import BaseClient

class PTP(BaseClient):
    def __init__(self, host: str, port: int, trans: Tuple, sock: socket) -> None:
        super().__init__(host, port, trans)

        self.set_socket(sock)
        self.sender = Senders(host, port, trans, sock)
        self.getter = Getters(host, port, trans, sock)

    def _send(self, data: str):
        data = data + "\n"
        self.send(data)
        message = self.receive()
        # print(message)
        # sys.stdout.flush()
        time.sleep(0.05)

    def awaitConfirmation(self):
        message = self.sock.recv(1024).decode("utf-8")
        # print(message)
        sys.stdout.flush()

    ## Arc motions
    def movePTPArc_AC(self, theta, c, k, vel):
        # print(theta)
        # print(c)
        # print(k)
        # print(vel)
        assert len(c) == 3, "Center of circle should be an array of 3 elements"
        assert len(k) == 3, "Orientation vector should be an array of 3 elements"
        assert len(theta) == 1, "Angle of an arc should be a scalar"
        assert len(vel) == 1, "Relative velocity should be a scalar"

        theta_ = theta[0]
        pos = self.getter.get_EEF_pos()
        r_2 = (
            math.pow(c[0] - pos[0], 2)
            + math.pow(c[1] - pos[1], 2)
            + math.pow(c[2] - pos[2], 2)
        )
        r = math.pow(r_2, 0.5)

        assert r != 0, "Radius can not be zero"
        assert theta_ != 0, "Angle can not be zero"

        # calculate unit vector
        r_2 = math.pow(k[0], 2) + math.pow(k[1], 2) + math.pow(k[2], 2)
        normK = math.pow(r_2, 0.5)
        assert normK != 0, "Norm of direction vector k shall not be zero"

        k[0] = k[0] / normK
        k[1] = k[1] / normK
        k[2] = k[2] / normK
        # print('k normalized successfully')
        s = [c[0] - pos[0], c[1] - pos[1], c[2] - pos[2]]
        s[0] = -s[0] / r
        s[1] = -s[1] / r
        s[2] = -s[2] / r
        n = [
            (k[1] * s[2] - k[2] * s[1]),
            (k[2] * s[0] - k[0] * s[2]),
            (k[0] * s[1] - k[1] * s[0]),
        ]
        # print('Performing arc motion based on c1 and c2')
        angle = theta_ / 2
        c1 = self.rotTheThing(angle, r, s, n, c)
        angle = theta_
        c2 = self.rotTheThing(angle, r, s, n, c)
        for i in range(3, 6):
            c1.append(pos[i])
            c2.append(pos[i])
        self.movePTPCirc1OrintationInter(c1, c2, vel)

    def rotTheThing(self, theta, r, s, n, c):
        c1 = [0, 0, 0]
        cos_ = math.cos(theta)
        sin_ = math.sin(theta)
        c1[0] = r * cos_ * s[0] + r * sin_ * n[0] + c[0]
        c1[1] = r * cos_ * s[1] + r * sin_ * n[1] + c[1]
        c1[2] = r * cos_ * s[2] + r * sin_ * n[2] + c[2]
        print(c1)
        return c1

    def checkErrorInRelVel(self, relVel):
        if not isinstance(relVel, (int, float)):
            print("Relative velocity should be a scalar")
            return True
        if not 0 < relVel < 1:
            print("Relative velocity should be in the range (0, 1)")
            return True
        return False

    def movePTPArcXY_AC(self, theta, c, vel):
        assert (
            len(theta) == 1
        ), "Error in function [movePTPArcXY_AC]: Rotation angle should be a scalar"
        assert (
            len(c) == 2
        ), "Error in function [movePTPArcXY_AC]: Center of rotation should be an array of two elements [x, y]"
        assert (
            len(vel) == 1
        ), "Error in function [movePTPArcXY_AC]: Velocity should be a scalar"
        k = [0, 0, 1]
        pos = self.getter.get_EEF_pos()
        c1 = [c[0], c[1], pos[2]]
        self.movePTPArc_AC(theta, c1, k, vel)

    def movePTPArcXZ_AC(self, theta, c, vel):
        assert (
            len(theta) == 1
        ), "Error in function [movePTPArcXZ_AC]: Rotation angle should be a scalar"
        assert (
            len(c) == 2
        ), "Error in function [movePTPArcXZ_AC]: Center of rotation should be an array of two elements [x, z]"
        assert (
            len(vel) == 1
        ), "Error in function [movePTPArcXZ_AC]: Velocity should be a scalar"

        k = [0, 1, 0]
        pos = self.getter.get_EEF_pos()
        c1 = [c[0], pos[1], c[1]]
        self.movePTPArc_AC(theta, c1, k, vel)

    def movePTPArcYZ_AC(self, theta, c, vel):
        assert (
            len(theta) == 1
        ), "Error in function [movePTPArcYZ_AC]: Rotation angle should be a scalar"
        assert (
            len(c) == 2
        ), "Error in function [movePTPArcYZ_AC]: Center of rotation should be an array of two elements [x, z]"
        assert (
            len(vel) == 1
        ), "Error in function [movePTPArcYZ_AC]: Velocity should be a scalar"

        k = [1, 0, 0]
        pos = self.getter.get_EEF_pos()
        c1 = [pos[0], c[1], c[2]]
        self.movePTPArc_AC(theta, c1, k, vel)

    def movePTPCirc1OrintationInter(self, f1, f2, relVel):
        assert (
            len(f1) == 6
        ), "Error in function [movePTPCirc1OrintationInter]: The first frame should be an array of 6 elements [x, y, z, alpha, beta, gamma]"
        assert (
            len(f2) == 6
        ), "Error in function [movePTPCirc1OrintationInter]: The second frame should be an array of 6 elements [x, y, z, alpha, beta, gamma]"
        assert (
            len(relVel) == 1
        ), "Error in function [movePTPCirc1OrintationInter]: Relative velocity should be a scalar"

        buff = "jRelVel_"
        buff = buff + str(relVel[0])
        buff = buff + "_"
        self._send(buff)
        self.sender.sendCirc1FramePos(f1)
        self.sender.sendCirc2FramePos(f2)
        theCommand = "doPTPinCSCircle1_"
        self._send(theCommand)
        self.awaitConfirmation()  # bug fixed on 1st October 2019, awaiting end of blocking motion

    def movePTPLineEEF(self, pos, vel):
        assert (
            len(vel) == 1
        ), "Error in function [movePTPLineEEF]: Velocity shall be a scalar"
        assert (
            len(pos) == 6
        ), "Error in function [movePTPLineEEF]: Position should be an array of 6 elements"

        buff = "jRelVel_" + str(vel[0]) + "_"
        command = buff
        self._send(command)
        self.sender.sendEEfPositions(pos)
        theCommand = "doPTPinCS"
        self._send(theCommand)
        self.awaitConfirmation()  # bug fixed on 1st October 2019, awaiting end of blocking motion

    def movePTPLineEefRelEef(self, pos, vel):
        assert (
            len(vel) == 1
        ), "Error in function [movePTPLineEefRelEef]: Velocity should be a scalar"
        assert (
            len(pos) == 3
        ), "Error in function [movePTPLineEefRelEef]: Position should be an array of 3 elements [x, y, z]"

        buff = "jRelVel_" + str(vel[0]) + "_"
        command = buff
        self._send(command)

        newPos = [0, 0, 0, 0, 0, 0]
        newPos[0] = pos[0]
        newPos[1] = pos[1]
        newPos[2] = pos[2]

        self.sender.sendEEfPositions(newPos)

        theCommand = "doPTPinCSRelEEF"
        self._send(theCommand)
        self.awaitConfirmation()  # bug fixed on 1st October 2019, awaiting end of blocking motion

    def movePTPLineEefRelBase(self, pos, vel):
        assert len(pos) == 3, "Position should be an array of three elements [x, y, z]"
        assert len(vel) == 1, "Velocity should be a scalar"

        buff = "jRelVel_" + str(vel[0]) + "_"
        command = buff
        self._send(command)

        newPos = [0, 0, 0, 0, 0, 0]
        newPos[0] = pos[0]
        newPos[1] = pos[1]
        newPos[2] = pos[2]

        self.sender.sendEEfPositions(newPos)

        theCommand = "doPTPinCSRelBase"
        self._send(theCommand)
        self.awaitConfirmation()  # bug fixed on 1st October 2019, awaiting end of blocking motion

    # joint space
    def movePTPJointSpace(self, jpos, relVel):
        assert (
            len(jpos) == 7
        ), "Error in function [movePTPJointSpace]: Joints positions shall be an array of 7 elements"
        assert (
            len(relVel) == 1
        ), "Error in function [movePTPJointSpace]: Relative velocity should be a scalar"

        buff = "jRelVel_" + str(relVel[0]) + "_"
        command = buff
        self._send(command)
        self.sender.sendJointsPositions(jpos)
        theCommand = "doPTPinJS"
        self._send(theCommand)
        self.awaitConfirmation()

    def movePTPHomeJointSpace(self, relVel):
        assert (
            len(relVel) == 1
        ), "Error in function [movePTPHomeJointSpace]: Relative velocity should be a scalar"

        buff = "jRelVel_" + str(relVel[0]) + "_"
        command = buff
        self._send(command)
        jpos = [0, 0, 0, 0, 0, 0, 0]
        self.sender.sendJointsPositions(jpos)
        theCommand = "doPTPinJS"
        self._send(theCommand)
        self.awaitConfirmation()

    def movePTPTransportPositionJointSpace(self, relVel):
        assert (
            len(relVel) == 1
        ), "Error in function [movePTPTransportPositionJointSpace]: Relative velocity should be a scalar"
        jpos = [0, 0, 0, 0, 0, 0, 0]
        jpos[3] = 25 * math.pi / 180
        jpos[5] = 90 * math.pi / 180
        self.movePTPJointSpace(jpos, relVel)


#!/usr/bin/env python3

import os
import sys
from dataclasses import dataclass, field

"""
author: dmaynor@gmail.com
The script will scan through my ~/code and ~/home directory to look for virtual enviroments for python by looking for a venv directory structure.
It can be called from my ~/tools/bin directory so first it has to change working directory to my home directory, It will then scan ~/code and ~/work
looking for venv directories. If it finds one the full path to venv is sotred in a list. When the scan is complete the list of all discovered venv directories
is displayed to the user. The user can then select a venv directory and the script will then change the working directory to that directory and execute the venv/bin/activate script.
"""
#Build a dataclass to store the path to the venv directory and metadata about the venv and project.
@dataclass
class ProjectList:
    project_lists: list = field(default_factory=dict)

    def __repr__(self) -> str:

        pass

#Initialize the ProjectList dataclass
pl = ProjectList()

#Check wthe current directory is my home directory, if not change to my homme directory
if os.getcwd() != os.path.expanduser('~'):
    os.chdir(os.path.expanduser('~'))

#build a list with code and work directories
directories = [os.path.expanduser('~/code'), os.path.expanduser('~/work')]

#recursively scan through the directories and look for venv directories
venv_list = []
found_count=1
for directory in directories:
    for root, dirs, files in os.walk(directory):
        for dir in dirs:
            if dir == 'venv':
                venv_dir = os.path.join(root, dir)
                venv_list.append(venv_dir)
                pl.project_lists[found_count] = venv_dir
                found_count += 1

#print the list of venv directories
print('\n')
if len(venv_list) == 0:
    print('No venv directories found')
else:
    print('The following venv directories were found:')
    for venv in venv_list:
        print(venv)
    print("Dataclass:", pl.project_lists)


import warnings
from PIL import Image,ImageFilter

def down_sample_fit(pil_img, num):
    ds = [2 ** (i + 1) for i in range(num)]
    for d in ds:
        a, b = pil_img.size
        add = (a % d)
        na = a + add
        add = (b % d)
        nb = b + add
        pil_img = pil_img.resize((na, nb),Image.BICUBIC)
    return pil_img

def max_size_fit(pil_img, max_size):
    max_ = max(pil_img.size)
    if max_ <= max_size:
        return pil_img
    else:
        warnings.warn("The image is over the max size:{}".format(max_size))
        a, b = pil_img.size
        if a >= b:
            na = max_size
            nb = int(na * (b / a))
        else:
            nb = max_size
            na = int(nb * (a / b))

        return pil_img.resize((na, nb),Image.BICUBIC)

def blur_image(pil_img,mode,r):
    if mode == "g":
        kernel = ImageFilter.GaussianBlur(radius=r)
    elif mode == "m":
        kernel = ImageFilter.MedianFilter(size=r)
    else:
        raise ValueError("{} not support".format(mode))
    return pil_img.filter(kernel)


from typing import Sequence
import math
import torch
from torch.utils.data.sampler import Sampler, RandomSampler

class StratifiedEventBatchSampler(Sampler):
    """Samples elements with from a set with binary labelling to ensure
    the event label (1) is evenly distributed across batches.

    This sampler is useful when the loss function requires at least one event,
    such as in the case of a Cox Proportional Hazard based loss.
    """

    events: torch.Tensor
    batch_size: int

    def __init__(self, events: Sequence[int], batch_size: int) -> None:
        """Generate an StratifiedBinaryBatchSampler instance

        Args:
            events: int sequence of binary event labels (0, 1)
            batch_size: int that defines size of mini-batch.
        """
        if not isinstance(batch_size, int) or batch_size <= 0:
            raise ValueError("batch_size should be a positive integer value, "
                             "but got batch_size={}".format(batch_size))
        self.events = torch.as_tensor(events, dtype=torch.int64)
        self.batch_size = batch_size

        self.events0_idx = torch.where(self.events == 0)[0]
        self.events1_idx = torch.where(self.events == 1)[0]

        self._len = math.ceil(len(self.events) / self.batch_size)

        if self.events1_idx.shape[0] < self._len:
            raise ValueError("the number of events ({}) must be equal or "
                             "larger than the number of batches ({})"
                             .format(self.events1_idx.shape[0], self._len))

        # Get batch sizes for each
        self.batch0_size = math.ceil(
            self.events0_idx.shape[0] / self.events.shape[0] * batch_size)
        self.batch1_size = math.floor(
            self.events1_idx.shape[0] / self.events.shape[0] * batch_size)

        self.sampler0 = RandomSampler(self.events0_idx, replacement=False)
        self.sampler1 = RandomSampler(self.events1_idx, replacement=False)

    def __iter0__(self):
        """Iterate the non-event (0) label sampler"""
        batch = torch.tensor([], dtype=torch.int64)
        for idx in self.sampler0:
            idx0 = self.events0_idx[idx, None]
            batch = torch.cat((batch, idx0), 0)
            if batch.shape[0] == self.batch0_size:
                yield batch
                batch = torch.tensor([], dtype=torch.int64)
        if batch.shape[0] > 0:
            yield batch

    def __iter1__(self):
        """Iterate the event (0) label sampler"""
        batch = torch.tensor([], dtype=torch.int64)
        for idx in self.sampler1:
            idx1 = self.events1_idx[idx, None]
            batch = torch.cat((batch, idx1), 0)
            if batch.shape[0] == self.batch1_size:
                yield batch
                batch = torch.tensor([], dtype=torch.int64)
        if batch.shape[0] > 0:
            yield batch

    def __iter__(self):
        """Generate the indices for the next batch of elements"""
        for batch0, batch1 in zip(self.__iter0__(), self.__iter1__()):
            batch = torch.cat((batch0, batch1), 0).sort()[0]
            yield batch

    # Removed - https://github.com/Lightning-AI/lightning/issues/2429
    # def __len__(self):
    #     """Return the number of batches"""
    #     return self._len


from cx_Freeze import setup, Executable

# On appelle la fonction setup

buildOptions = dict(
    includes=["pygame.py"],
    include_files=["fichier1.txt", "mon_icone.ico"]
)

setup(
    name="BoumeurMan",
    version="1",
    description="Projet Terminale 2021",
    executables=[Executable("main.py")],
)


import pickle
from pathlib import Path

import matplotlib
import matplotlib.pyplot as plt
import matplotlib.patches as ptc

from nicpy import nic_misc, nic_pic
import a_star
from geometry import Square, SquareGrid

def algo_animation(history_directory, fps=2, frame_skip=1):

    matplotlib.use('Agg')   # Gets rid of plot popups, faster to produce frames
    max_iteration = 0       # Find the number of iterations saved
    for file in history_directory.iterdir():
        if file.is_file():
            string_iter_num = str(file.stem).split('_')[0]
            if string_iter_num != 'graph':
                if int(string_iter_num)>max_iteration: max_iteration = int(string_iter_num)

    # Save a frame for each algo iteration
    counter = 0
    frames_directory = history_directory/'frames'
    nic_misc.mkdir_if_DNE(frames_directory)
    its = list(range(0, max_iteration+1, frame_skip))
    if its[-1] != max_iteration: its.append(max_iteration)
    for iteration in its:
        print('Producing image {} of {}'.format(iteration+1, max_iteration+1))
        frame = plot_algo_state(history_directory, iteration)
        frame.savefig(frames_directory/'frame_{}.png'.format(str(counter).zfill(5)), bbox_inches='tight')
        counter += 1
        plt.close(frame)

    nic_pic.frames_to_video(frames_directory, video_name_with_format='video.avi', image_format='png', fps=fps)

def plot_algo_state(history_directory, iteration):
    maze = pickle.load(open(str(history_directory/'graph.dat'.format(iteration)), 'rb'))
    closed_list = pickle.load(open(str(history_directory/'{}_closed_list.dat'.format(iteration)), 'rb'))
    open_list = pickle.load(open(str(history_directory/'{}_open_list.dat'.format(iteration)), 'rb'))
    current_node = pickle.load(open(str(history_directory/'{}_current_node.dat'.format(iteration)), 'rb'))
    current_path = a_star.reconstruct_path(current_node)
    fig = plot_maze(maze, current_path, closed_list, open_list)
    return fig

def plot_maze(maze, current_path=None, closed_list=None, open_list=None):
    maze.check_graph()
    fig, ax = plt.subplots(1, dpi=100)
    plt.gca().invert_yaxis()
    ax.axis('equal')
    ax.set_facecolor([0.5, 0.5, 0.5])
    patch_width = 1

    # Add lines on top layers
    for row in range(maze.dimensions[0]+1):
        ax.plot([0, maze.dimensions[1]], [row, row], 'k', zorder=102, linewidth=3)
    for col in range(maze.dimensions[1]+1):
        ax.plot([col, col], [0, maze.dimensions[0]], 'k', zorder=103, linewidth=3)

    # Add colour patches
    for row in range(maze.dimensions[0]):
        for col in range(maze.dimensions[1]):
            if maze.maze_array[row, col] > 0: ax.add_patch(ptc.Rectangle([col, row], patch_width, patch_width, color = [1, 1, 1]))
            if maze.maze_array[row, col] == 0: ax.add_patch(ptc.Rectangle([col, row], patch_width, patch_width, color=[0.3, 0.2, 0.1], zorder=100))
            elif (row, col) == maze.start: ax.add_patch(ptc.Rectangle([col, row], patch_width, patch_width, color='r', zorder=101))
            elif (row, col) == maze.end: ax.add_patch(ptc.Rectangle([col, row], patch_width, patch_width, color='g'))

    # These elements change each time
    if closed_list:
        for node in closed_list:
            ax.add_patch(ptc.Rectangle((node.label[1], node.label[0]), patch_width, patch_width, color='y'))
    if open_list:
        for pair in open_list.elements:
            node = pair[1]
            ax.add_patch(ptc.Rectangle((node.label[1], node.label[0]), patch_width, patch_width, color='m'))
    if current_path:
        for i, step in enumerate(current_path[1:-1]):
            # ax.add_patch(ptc.Rectangle((step[1], step[0]), 1, 1, color='b'))
            ax.text(step[1]+0.5, step[0]+0.5, 'x', color='b', horizontalalignment='center', verticalalignment='center')

    return fig

if __name__ == '__main__':
    # Plot an algo state
    plot_algo_state(Path(r'E:\dev\python_projects\pathfinding\saved_histories\2020-08-16_15_13_19'), 40)

    # Create an animation
    algo_animation(Path(r'E:\dev\python_projects\pathfinding\saved_histories\2020-08-16_15_13_19'), fps=5, frame_skip = 1)


import datetime

from aiogram import types
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters.builtin import CommandStart
from aiogram.types import InputFile

from handlers.helps.met_support import create_array_account_proxy, replaceter_text_in_aiogram
from handlers.users.som_inviter.a_invite import get_user_invaiter_tg_asyncio
from handlers.users.som_spam.a_spam import Spammer_in_tg_asyncio
from keyboards.default import menu_start
from keyboards.default.start_menu import menu_beck, menu_beck_inv, menu_beck_spam
from loader import dp, bot

@dp.message_handler(text='🧛🏿♂Рассылка', state='*')
async def start(message: types.Message, state: FSMContext):
    proxy_file, sessions_len = create_array_account_proxy()
    __userid = message.from_user.id
    await message.answer(f"👑{message.from_user.first_name}👑 Вы перешели в - 🧙🏿Инвайт\n\n"
                         f"Аккаунтов для рассылки - {len(sessions_len)}\n"
                         f"Прокси для рассылки - {len(proxy_file)}\n\n"
                         f"Что бы начать спамить пришлите базу\n"
                         f"Пример",reply_markup=menu_beck)

    file = InputFile(
        fr"data/spam_bd.csv"
    )
    await bot.send_document(chat_id=message.chat.id, document=file,
                            reply_markup=menu_beck)
    await state.set_state('spamdoc')

@dp.message_handler(state='spamdoc',content_types=['document'])
async def add_channel_get_photo(message, state: FSMContext):
    await message.document.download(rf'data\spam_bd.csv')
    await message.answer("Пришлите сообщение для рассылки\n"
                         "В данный момент поддерживается:\n"
                         "Упитанный шрифт\n"
                         "Италик\n"
                         "Гиперссылки\n"
                         "Фото")
    await state.set_state('spamtext')

@dp.message_handler(state='spamtext',content_types=['photo'])
async def add_channel_get_photo(message, state: FSMContext):
    new_text = await replaceter_text_in_aiogram(new_text=message.caption, array_caption=message.caption_entities)
    new_text = f"{new_text}~photo"
    with open(rf'data/text_spam.txt','w+',encoding='utf-8') as file:
        file.write(new_text)
    await state.finish()
    await message.answer("Начинаем рассылать?", reply_markup=menu_beck_spam)

@dp.message_handler(state='spamtext')
async def add_channel_get_photo(message: types.Message, state: FSMContext):
    new_text = await replaceter_text_in_aiogram(new_text=message.text, array_caption=message.entities)
    new_text = f"{new_text}~text"
    with open(rf'data/text_spam.txt','w+',encoding='utf-8') as file:
        file.write(new_text)
    await state.finish()
    await message.answer("Начинаем рассылать?", reply_markup=menu_beck_spam)

@dp.message_handler(text='🚀 Рассылаем', state='*')
async def start(message: types.Message, state: FSMContext):
    await message.answer('Рассылка началась', reply_markup=menu_beck)
    msg = await message.answer('Статус запущенно')
    pc = Spammer_in_tg_asyncio(msg=msg)
    await pc.__start__()
    await state.finish()


'''
Author: 千仞无锋
Date: 2022-04-20 21:31:30
LastEditors: 千仞无锋
LastEditTime: 2022-04-20 22:36:20
FilePath: \20220411HTML_CSS\一个小插曲关于excel和py的\youtube_openpyxl_03.py
'''
import openpyxl
from openpyxl import Workbook, load_workbook
from openpyxl.utils import get_column_letter, column_index_from_string
from openpyxl.styles import Font ,PatternFill, Border, Side, Alignment, Protection
# data 是一个列表，每个元素是一个字典
data = [{
    'name': '赵日天',
    'tall': 180,
    'age': 18,
    'weight': 80,
}, {
    'name': '钱多多',
    'tall': 190,
    'age': 19,
    'weight': 100
}, {
    'name': '孙小小',
    'tall': 210,
    'age': 22,
    'weight': 120
}]
# 写入excel
wb = Workbook()
ws = wb.active

title = ['姓名', '身高', '年龄', '体重']
ws.append(title)

for person in data:
    # 字典变列表
    ws.append(list(person.values()))
wb.save(r'H:\study-notes\20220411HTML_CSS\一个小插曲关于excel和py的\text.xlsx')

# 基础计算
# 调用公式
for col in range(2, 5):
    char = get_column_letter(col)
    ws[char + '7'] = f'=AVERAGE({char+"2"}:{char+"6"})'
wb.save(r'H:\study-notes\20220411HTML_CSS\一个小插曲关于excel和py的\text.xlsx')

# 字体
for col in range(1, 5):
    char = get_column_letter(col)
    ws[char + '1'].font = Font(bold=True,color='FF0000') # 字体加粗,变红
wb.save(r'H:\study-notes\20220411HTML_CSS\一个小插曲关于excel和py的\text.xlsx')


#!/usr/bin/env python
"""
Example application views.

Note that `render_template` is wrapped with `make_response` in all application
routes. While not necessary for most Flask apps, it is required in the
App Template for static publishing.
"""

import app_config
import json
import oauth
import static

from flask import Flask, make_response, render_template
from render_utils import make_context, smarty_filter, urlencode_filter
from werkzeug.debug import DebuggedApplication

# This is needed by the response_minify() function below
from htmlmin.main import minify

# This is needed by the less() function below
from fabric.api import local

app = Flask(__name__)
app.debug = app_config.DEBUG

app.add_template_filter(smarty_filter, name='smarty')
app.add_template_filter(urlencode_filter, name='urlencode')

@app.route('/')
@oauth.oauth_required
def index():
    """
    Example view demonstrating rendering a simple HTML page.
    """
    context = make_context()
    context['directory_depth'] = 0

    with open('data/featured.json') as f:
        context['featured'] = json.load(f)

    return make_response(render_template('index.html', **context))

@app.route('/404.html')
def four_oh_four():
    context = make_context()
    context['directory_depth'] = 0

    return make_response(render_template('404.html', **context))

@app.errorhandler(404)
def page_not_found(e):
    context = make_context()

    return make_response(render_template('404.html', **context))

@app.route('/css/<path:path>')
def less(path):
    """
    Render LESS files to CSS.
    """
    file_prefix = path.split('.')[0]
    srcfile = 'less/%s.less' % file_prefix
    outfile = 'www/css/%s.min.css' % file_prefix
    name = '%s.min.css' % file_prefix
    try:
        # run the LESS compiler, with --clean-css option set to minify, to generate static .css file
        local('node_modules/less/bin/lessc --clean-css %s %s' % (srcfile, outfile))
        # use Flask's send_from_directory to serve the static .css file
        return send_from_directory('www/css', name)
    except Exception as e:
        print('It looks like "lessc" isn\'t installed. Try running: "npm install"')
        print(e)

@app.after_request
def response_minify(response):
    """
    Minify html response to decrease site traffic
    """
    if response.content_type == 'text/html; charset=utf-8':
        response.set_data(
            minify(response.get_data(as_text=True))
        )

        return response
    return response

app.register_blueprint(static.static)
app.register_blueprint(oauth.oauth)

# Enable Werkzeug debug pages
if app_config.DEBUG:
    wsgi_app = DebuggedApplication(app, evalex=False)
else:
    wsgi_app = app

# Catch attempts to run the app directly
if __name__ == '__main__':
    print('This command has been removed! Please run "fab app" instead!')


import logging
import os
import time

import asyncpraw
import discord
from discord.ext import tasks, commands

from cogs.commands import settings

log = logging.getLogger(__name__)

class RedditTask(commands.Cog):
    """ Reddit Background Task """

    def __init__(self, bot):
        self.bot = bot

        # Attempt to get the environment variables, defaults to None if non-existent.
        self.client_id = os.getenv("REDDIT_CLIENT_ID")
        self.client_secret = os.getenv("REDDIT_CLIENT_SECRET")
        self.user_agent = os.getenv("REDDIT_USER_AGENT")

        # Only define the object if all the env variable prerequisites exist.
        if not all([self.client_id, self.client_secret, self.user_agent]):
            log.warning("Reddit functionality is disabled due to missing prerequisites")
            return

        # Only start the task if the needed prerequisites exist in the settings database.
        if not all([settings.get_value("subreddit"), settings.get_value("channel_reddit"), settings.get_value("poll_rate")]):
            log.warning("Reddit functionality is disabled due to missing prerequisites")
            return

        self.reddit = asyncpraw.Reddit(
            client_id=self.client_id,
            client_secret=self.client_secret,
            user_agent=self.user_agent
        )

        log.info("Starting reddit functionality background task")
        self.cache = []
        self.bot_started_at = time.time()
        self.check_for_posts.start()

    def cog_unload(self):
        self.check_for_posts.cancel()

    @tasks.loop(seconds=settings.get_value("poll_rate"))
    async def check_for_posts(self):
        """ Checking for new reddit posts """
        # Wait before starting or else new posts may not post to discord.
        await self.bot.wait_until_ready()

        try:
            subreddit = await self.reddit.subreddit(settings.get_value("subreddit"))
            # Grabs 10 latest posts, we should never get more than 10 new submissions in < 10 seconds.
            async for submission in subreddit.new(limit=10):
                # Skips over any posts already stored in cache.
                if submission.id in self.cache:
                    continue

                # Skips over any posts from before the bot started to avoid infinite loops.
                if submission.created_utc <= self.bot_started_at:
                    continue

                # Loads the subreddit and author so we can access extra data.
                await submission.author.load()
                await submission.subreddit.load()

                log.info(f"{submission.title} was posted by /u/{submission.author.name}")

                # Builds and populates the embed.
                embed = discord.Embed(
                    title=submission.title[0:252],
                    url=f"https://reddit.com{submission.permalink}",
                    description=submission.selftext[0:350],  # Cuts off the description.
                )

                embed.set_author(
                    name=submission.author.name,
                    url=f"https://reddit.com/u/{submission.author.name}",
                    icon_url=submission.author.icon_img
                )

                embed.set_footer(
                    text=f"{submission.link_flair_text} posted on /r/{submission.subreddit}",
                    icon_url=submission.subreddit.community_icon)

                # Adds ellipsis if the data is too long to signify cutoff.
                if len(submission.selftext) >= 350:
                    embed.description = embed.description + "..."

                if len(submission.title) >= 252:
                    embed.title = embed.title + "..."

                # Attempts to find the channel to send to and skips if unable to locate.
                channel = self.bot.get_channel(settings.get_value("channel_reddit"))
                if not channel:
                    log.warning(f"Unable to find channel to post: {submission.title} by /u/{submission.author.name}")
                    continue

                # Sends embed into the Discord channel and adds to cache to avoid dupes in the future.
                await channel.send(embed=embed)
                self.cache.append(submission.id)

        # Catch all exceptions to avoid crashing and log the error.
        except Exception as e:
            log.error(e)

def setup(bot) -> None:
    """ Load the reddit cog. """
    bot.add_cog(RedditTask(bot))
    log.info("Task loaded: reddit")


import pygame, sys, random
import pygame.camera
from pygame.locals import *
from PIL import Image
import pytesseract as pt

"""S_L = 'eng'
D_L = 'en'"""
WINDOWWIDTH = 640
WINDOWHEIGHT = 480
FPS = 30

BLACK =         (  0,   0,   0)
WHITE =         (255, 255, 255)
BRIGHTBLUE =    (  0,  50, 255)

BUTTONCOLOR = WHITE
BUTTONTEXTCOLOR = BLACK
MESSAGECOLOR = WHITE

BGCOLOR = BLACK
BASICFONTSIZE = 20

pygame.init()
pygame.camera.init()

camlist = pygame.camera.list_cameras()
if camlist:
    cam = pygame.camera.Camera(camlist[0],(640,480))

def terminate():
    pygame.quit()
    sys.exit()

def startScreen():
    pygame.display.set_caption('Linguista')
    DISPLAYSURF.fill(BLACK)
    TITLEFONT = pygame.font.Font('Fonts/calibri.ttf', 40)
    titleText = TITLEFONT.render('Linguista', True, WHITE)
    titleRect = titleText.get_rect()
    titleRect.center = (WINDOWWIDTH / 2, WINDOWHEIGHT / 2)
    DISPLAYSURF.blit(titleText, titleRect)
    pygame.display.flip()
    chooseScreen()
    going = True
    while going:
        events = pygame.event.get()
        for e in events:
            if (e.type == KEYDOWN and e.key == K_ESCAPE):
                # close the camera safely
                terminate()
                going = False
            elif (e.type == MOUSEBUTTONDOWN):
                obj = Capture()
                obj.main()
            elif (e.type == KEYDOWN and e.key == K_BACKSPACE):
                startScreen()

def chooseScreen():

    #DISPLAYSURF.fill(BGCOLOR)
    global S_L
    global D_L

    srcLang = BASICFONT.render('Source Language', True, WHITE)
    srcLangRect = srcLang.get_rect()
    srcLangRect.center = (WINDOWWIDTH / 4, WINDOWHEIGHT / 30)

    s_eng = BASICFONT.render('English', True, WHITE)
    s_engRect = s_eng.get_rect()
    s_engRect.center = (WINDOWWIDTH / 4, WINDOWHEIGHT / 12)

    s_ger = BASICFONT.render('German', True, WHITE)
    s_gerRect = s_ger.get_rect()
    s_gerRect.center = (WINDOWWIDTH / 4, 2 * WINDOWHEIGHT / 12)

    s_spa = BASICFONT.render('Spanish', True, WHITE)
    s_spaRect = s_spa.get_rect()
    s_spaRect.center = (WINDOWWIDTH / 4, 3 * WINDOWHEIGHT / 12)

    s_hin = BASICFONT.render('Hindi', True, WHITE)
    s_hinRect = s_hin.get_rect()
    s_hinRect.center = (WINDOWWIDTH / 4, 4 * WINDOWHEIGHT / 12)

    s_ben = BASICFONT.render('Bengali', True, WHITE)
    s_benRect = s_ben.get_rect()
    s_benRect.center = (WINDOWWIDTH / 4, 5 * WINDOWHEIGHT / 12)

    s_pun = BASICFONT.render('Punjabi', True, WHITE)
    s_punRect = s_pun.get_rect()
    s_punRect.center = (WINDOWWIDTH / 4, 6 * WINDOWHEIGHT / 12)

    s_fre = BASICFONT.render('French', True, WHITE)
    s_freRect = s_fre.get_rect()
    s_freRect.center = (WINDOWWIDTH / 4, 7 * WINDOWHEIGHT / 12)

    s_ita = BASICFONT.render('Italian', True, WHITE)
    s_itaRect = s_ita.get_rect()
    s_itaRect.center = (WINDOWWIDTH / 4, 8 * WINDOWHEIGHT / 12)

    dstLang = BASICFONT.render('Destination Language', True, WHITE)
    dstLangRect = dstLang.get_rect()
    dstLangRect.center = ((3*WINDOWWIDTH) / 4, WINDOWHEIGHT / 30)

    d_eng = BASICFONT.render('English', True, WHITE)
    d_engRect = d_eng.get_rect()
    d_engRect.center = ((3*WINDOWWIDTH) / 4, WINDOWHEIGHT / 12)

    d_ger = BASICFONT.render('German', True, WHITE)
    d_gerRect = d_ger.get_rect()
    d_gerRect.center = ((3*WINDOWWIDTH) / 4, 2 * WINDOWHEIGHT / 12)

    d_spa = BASICFONT.render('Spanish', True, WHITE)
    d_spaRect = d_spa.get_rect()
    d_spaRect.center = ((3*WINDOWWIDTH) / 4, 3 * WINDOWHEIGHT / 12)

    d_hin = BASICFONT.render('Hindi', True, WHITE)
    d_hinRect = d_hin.get_rect()
    d_hinRect.center = ((3*WINDOWWIDTH) / 4, 4 * WINDOWHEIGHT / 12)

    d_ben = BASICFONT.render('Bengali', True, WHITE)
    d_benRect = d_ben.get_rect()
    d_benRect.center = ((3*WINDOWWIDTH) / 4, 5 * WINDOWHEIGHT / 12)

    d_pun = BASICFONT.render('Punjabi', True, WHITE)
    d_punRect = d_pun.get_rect()
    d_punRect.center = ((3*WINDOWWIDTH) / 4, 6 * WINDOWHEIGHT / 12)

    d_fre = BASICFONT.render('French', True, WHITE)
    d_freRect = d_fre.get_rect()
    d_freRect.center = ((3*WINDOWWIDTH) / 4, 7 * WINDOWHEIGHT / 12)

    d_ita = BASICFONT.render('Italian', True, WHITE)
    d_itaRect = d_ita.get_rect()
    d_itaRect.center = ((3*WINDOWWIDTH) / 4, 8 * WINDOWHEIGHT / 12)

    DISPLAYSURF.blit(srcLang, srcLangRect)
    DISPLAYSURF.blit(s_hin, s_hinRect)
    DISPLAYSURF.blit(s_spa, s_spaRect)
    DISPLAYSURF.blit(s_ger, s_gerRect)
    DISPLAYSURF.blit(s_eng, s_engRect)
    DISPLAYSURF.blit(s_pun, s_punRect)
    DISPLAYSURF.blit(s_fre, s_freRect)
    DISPLAYSURF.blit(s_ita, s_itaRect)

    DISPLAYSURF.blit(dstLang, dstLangRect)
    DISPLAYSURF.blit(d_hin, d_hinRect)
    DISPLAYSURF.blit(d_spa, d_spaRect)
    DISPLAYSURF.blit(d_ger, d_gerRect)
    DISPLAYSURF.blit(d_eng, d_engRect)
    DISPLAYSURF.blit(d_pun, d_punRect)
    DISPLAYSURF.blit(d_fre, d_freRect)
    DISPLAYSURF.blit(d_ita, d_itaRect)

    pygame.display.update()

    going = True
    count_s = 0
    count_d = 0

    while going:
        for event in pygame.event.get():
            if event.type == QUIT:
                terminate()
            elif event.type == MOUSEBUTTONUP:
                mouseX, mouseY = event.pos
                if s_hinRect.collidepoint(mouseX, mouseY):
                    S_L = 'hin'
                    count_s = count_s + 1
                elif s_gerRect.collidepoint(mouseX, mouseY):
                    S_L = 'deu'
                    count_s = count_s + 1
                elif s_engRect.collidepoint(mouseX, mouseY):
                    S_L = 'eng'
                    count_s = count_s + 1
                elif s_spaRect.collidepoint(mouseX, mouseY):
                    S_L = 'spa'
                    count_s = count_s + 1
                elif s_punRect.collidepoint(mouseX, mouseY):
                    S_L = 'pan'
                    count_s = count_s + 1
                elif s_freRect.collidepoint(mouseX, mouseY):
                    S_L = 'fra'
                    count_s = count_s + 1
                elif s_itaRect.collidepoint(mouseX, mouseY):
                    S_L = 'ita'
                    count_s = count_s + 1
                elif d_hinRect.collidepoint(mouseX, mouseY):
                    D_L = 'hi'
                    count_d = count_d + 1
                elif d_engRect.collidepoint(mouseX, mouseY):
                    D_L = 'en'
                    count_d = count_d + 1
                elif d_gerRect.collidepoint(mouseX, mouseY):
                    D_L = 'de'
                    count_d = count_d + 1
                elif d_spaRect.collidepoint(mouseX, mouseY):
                    D_L = 'es'
                    count_d = count_d + 1
                elif d_punRect.collidepoint(mouseX, mouseY):
                    D_L = 'pa'
                    count_d = count_d + 1
                elif d_freRect.collidepoint(mouseX, mouseY):
                    D_L = 'fr'
                    count_d = count_d + 1
                elif d_itaRect.collidepoint(mouseX, mouseY):
                    D_L = 'it'
                    count_d = count_d + 1
                if (count_s == 1 and count_d == 1):
                    going = False
                    break

class Capture(object):
    def __init__(self):
        self.size = (640,480)
        #self.size2 = (640, 380)
        # create a display surface. standard pygame stuff
        self.display = pygame.display.set_mode(self.size, 0)

        # this is the same as what we saw before
        self.clist = pygame.camera.list_cameras()
        if not self.clist:
            raise ValueError("Sorry, no cameras detected.")
        self.cam = pygame.camera.Camera(self.clist[0], self.size)
        self.cam.start()

        # create a surface to capture to.  for performance purposes
        # bit depth is the same as that of the display surface.
        self.snapshot = pygame.surface.Surface(self.size, 0, self.display)
        self.img = pygame.image.load('Images/black.jpg')
        self.display.blit(self.img,(0,360))
        pygame.display.update()

    def black_region(self, blck):
        self.display.blit(blck,(0,360))
        pygame.display.update()

    def get_and_flip(self, blck):
        # if you don't want to tie the framerate to the camera, you can check
        # if the camera has an image ready.  note that while this works
        # on most cameras, some will never return true.
        if self.cam.query_image():
            self.snapshot = self.cam.get_image(self.snapshot)

        # blit it to the display surface.  simple!
        self.display.blit(self.snapshot, (0,0))
        self.black_region(blck)

    def main(self):
        going = True
        while going:
            events = pygame.event.get()
            for e in events:
                if e.type == QUIT:
                    # close the camera safely
                    self.cam.stop()
                    going = False
                elif (e.type == KEYDOWN and e.key == K_SPACE):
                    ini_image = self.cam.get_image()
                    self.filename = '2.jpg'
                    pygame.image.save(ini_image, self.filename)
                    self.display.blit(ini_image, (0,0))
                    self.get_text()
                elif (e.type == KEYDOWN and e.key == K_ESCAPE):
                    self.cam.stop()
                    startScreen()

            self.get_and_flip(self.img)

    def get_text(self):
        fin_file = pt.func(self.filename, S_L, D_L)
        fin_img = pygame.image.load(fin_file)
        going = True
        while going:
            self.black_region(fin_img)
            events = pygame.event.get()
            for e in events:
                if (e.type == KEYDOWN and e.key == K_BACKSPACE):
                    going = False
                    self.main()
                elif (e.type == KEYDOWN and e.key == K_ESCAPE):
                    self.cam.stop()
                    startScreen()
                elif e.type == QUIT:
                    # close the camera safely
                    self.cam.stop()
                    going = False
"""self.display.blit(fin_img,(0,360))
        pygame.display.update()"""

def main():
    global DISPLAYSURF, BASICFONT, FPSCLOCK, S_L, D_L
    pygame.init()
    DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
    BASICFONT = pygame.font.Font('Fonts/calibri.ttf', BASICFONTSIZE)
    S_L = 'eng'
    D_L = 'en'
    startScreen()

if __name__ == '__main__':
	main()


import datetime
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated

from drf_yasg.utils import swagger_auto_schema

from apps.commons.views import Pagination, MyPagination

from apps.posts.serializers import PostMySerializer
from apps.posts.models import Post

pagination = Pagination(0, 10)

my_pagination = MyPagination(0, 10)

class PostMy(APIView):
    permission_classes = [IsAuthenticated]

    @swagger_auto_schema(
        operation_description="""
        # 내가 작성한 post를 가져옵니다.
        ### - 반환은 다음과 같습니다.
        ### - posts: 날짜별로 정렬된 post들을 반환합니다.
        ```
        {
            "start": 0,
            "offset": 10,
            "next": 10,
            "posts": {
                    "2023-05-06": [
                        {
                            "id": 53,
                            "content": "~~~",
                            "created_at": "2023-05-06T16:47:57.651504+09:00",
                            "updated_at": "2023-05-06T16:48:01.421320+09:00"
                        },
                        ....
                },

        }
        ```
        ### - 다음 요청시에는 next값을 start로 요청해주세요!
        ### - next가 null이면 더이상 요청할 데이터가 없습니다.
        ### - 날짜별로 쓴 글이 정렬되어 내려갑니다.
        """,
        manual_parameters=pagination.get_params,
    )
    def get(self, request, format=None):
        queryset = Post.objects.filter(is_deleted=False, user=request.user).order_by(
            "-created_at"
        )
        result = my_pagination.get(request, queryset)
        serializer = PostMySerializer(
            result.pop("result"),
            many=True,
        )

        # serializer.data의 인자를 날짜별로 묶어서 반환
        posts_by_date = {}
        for post in serializer.data:
            if post["created_at"][:10] == str(datetime.date.today()):
                post["created_at"] = "Today"
            elif post["created_at"][:10] == str(
                datetime.date.today() - datetime.timedelta(days=1)
            ):
                post["created_at"] = "Yesterday"
            else:
                post["created_at"] = post["created_at"][:10]

            if post["created_at"] not in posts_by_date:
                posts_by_date[post["created_at"]] = [post]
            else:
                posts_by_date[post["created_at"]].append(post)

        result["posts"] = posts_by_date

        return Response(result)


import json
import os
import time
import uuid
from pathlib import Path
from typing import (
    Any,
    AsyncGenerator,
    Coroutine,
    Dict,
    Generator,
    Optional,
    Tuple,
    Union,
)

import tiktoken
from anthropic import Anthropic
from fastapi import HTTPException
from fastapi.responses import JSONResponse, StreamingResponse
from pydantic import BaseModel, ValidationError
from tokenizers import Tokenizer

from llmstudio.tracking.tracker import tracker

provider_registry = {}

def provider(cls):
    """Decorator to register a new provider."""
    provider_registry[cls.__name__] = cls
    return cls

class ChatRequest(BaseModel):
    api_key: Optional[str] = None
    model: str
    chat_input: str
    parameters: Optional[BaseModel] = None
    is_stream: Optional[bool] = False
    has_end_token: Optional[bool] = False

class Provider:
    END_TOKEN = "<END_TOKEN>"

    def __init__(self, config):
        self.config = config
        self.tokenizer: Tokenizer = self._get_tokenizer()

    async def chat(
        self, request: ChatRequest
    ) -> Union[StreamingResponse, JSONResponse]:
        """Makes a chat connection with the provider's API"""
        try:
            request = self.validate_request(request)
        except ValidationError as e:
            raise HTTPException(status_code=422, detail=e.errors())

        self.validate_model(request)

        start_time = time.time()
        response = await self.generate_client(request)

        response_handler = self.handle_response(request, response, start_time)
        if request.is_stream:
            return StreamingResponse(response_handler)
        else:
            return JSONResponse(content=await response_handler.__anext__())

    def validate_request(self, request: ChatRequest):
        pass

    def validate_model(self, request: ChatRequest):
        if request.model not in self.config.models:
            raise HTTPException(
                status_code=400,
                detail=f"Model {request.model} is not supported by {self.config.name}",
            )

    async def generate_client(
        self, request: ChatRequest
    ) -> Coroutine[Any, Any, Generator]:
        """Generate the provider's client"""

    async def handle_response(
        self, request: ChatRequest, response: AsyncGenerator, start_time: float
    ) -> AsyncGenerator[str, None]:
        """Handles the response from an API"""
        chat_output = ""
        first_token_time = None
        previous_token_time = None
        token_times = []
        token_count = 0

        async for chunk in self.parse_response(response):
            token_count += 1
            current_time = time.time()
            first_token_time = first_token_time or current_time
            if previous_token_time is not None:
                token_times.append(current_time - previous_token_time)
            previous_token_time = current_time

            chat_output += chunk
            if request.is_stream:
                yield chunk

        metrics = self.calculate_metrics(
            request.chat_input,
            chat_output,
            request.model,
            start_time,
            time.time(),
            first_token_time,
            token_times,
            token_count,
        )

        if request.is_stream and request.has_end_token:
            yield self.get_end_token_string(metrics)

        response = self.generate_response(request, chat_output, metrics)

        self.save_log(response)

        if not request.is_stream:
            yield response

    async def parse_response(
        self, response: AsyncGenerator
    ) -> AsyncGenerator[str, None]:
        pass

    def generate_response(
        self,
        request: ChatRequest,
        chat_output: str,
        metrics: Dict[str, Any],
    ) -> Dict[str, Any]:
        """Generates a complete response with metrics"""
        return {
            "id": str(uuid.uuid4()),
            "chat_input": request.chat_input,
            "chat_output": chat_output,
            "timestamp": time.time(),
            "provider": self.config.id,
            "model": request.model,
            "metrics": metrics,
            "parameters": request.parameters.dict(),
        }

    def calculate_metrics(
        self,
        input: str,
        output: str,
        model: str,
        start_time: float,
        end_time: float,
        first_token_time: float,
        token_times: Tuple[float, ...],
        token_count: int,
    ) -> Dict[str, Any]:
        """Calculates metrics based on token times and output"""
        model_config = self.config.models[model]
        input_tokens = len(self.tokenizer.encode(input))
        output_tokens = len(self.tokenizer.encode(output))

        input_cost = model_config.input_token_cost * input_tokens
        output_cost = model_config.output_token_cost * output_tokens

        total_time = end_time - start_time
        return {
            "input_tokens": input_tokens,
            "output_tokens": output_tokens,
            "total_tokens": input_tokens + output_tokens,
            "cost": input_cost + output_cost,
            "latency": total_time,
            "time_to_first_token": first_token_time - start_time,
            "inter_token_latency": sum(token_times) / len(token_times),
            "tokens_per_second": token_count / total_time,
        }

    def get_end_token_string(self, metrics: Dict[str, Any]) -> str:
        return f"{self.END_TOKEN},input_tokens={metrics['input_tokens']},output_tokens={metrics['output_tokens']},cost={metrics['cost']},latency={metrics['latency']:.5f},time_to_first_token={metrics['time_to_first_token']:.5f},inter_token_latency={metrics['inter_token_latency']:.5f},tokens_per_second={metrics['tokens_per_second']:.2f}"

    def _get_tokenizer(self) -> Tokenizer:
        return {
            "anthropic": Anthropic().get_tokenizer(),
            "cohere": Tokenizer.from_pretrained("Cohere/command-nightly"),
        }.get(self.config.id, tiktoken.get_encoding("cl100k_base"))

    def save_log(self, response: Dict[str, Any]):
        local = False  # NB: Make this dynamic
        if local:
            file_name = Path(
                os.path.join(os.path.dirname(__file__), "..", "logs.jsonl")
            )
            if not os.path.exists(file_name):
                with open(file_name, "w") as f:
                    pass

            with open(file_name, "a") as f:
                f.write(json.dumps(response) + "\n")
        else:
            tracker.log(response)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This server watches for changes in log files and sends out updates to
subscribers via web sockets.
"""
import time
import subprocess
import select
import threading
from websocket_server import WebsocketServer
from baibaitrader.utils import build_logger

class TickerServer:

    def __init__(self, filepath):
        self._log = build_logger('server_log', 'server_log.log')
        self.watched_file = filepath
        self._server = WebsocketServer(3000, host='127.0.0.1')
        self._server.set_fn_new_client(self.client_connected)
        self._server.set_fn_client_left(self.client_disconnected)
        self.watch_file(filepath)
        self._log.info('Ticker server running!')
        self._server.serve_forever()

    def client_connected(self, client, _):
        self._log.info('Client connected!')
        self.send_all_lines(client, self.watched_file)

    def client_disconnected(self, client, server):
        self._log.info('Client disconnected!')

    def send_all_lines(self, client, file):
        with open(file, 'r') as f:
            for line in f:
                #self._server.send_message(client, line)
                pass

    def received_messsage(self, client, server, message):
        self._log.info('Server received message: ' + str(message))

    def watch_file(self, filepath):
        self._log.info('Watching file: ' + filepath)
        tail = subprocess.Popen(['tail', '-F', filepath],
                                stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        poll = select.poll()
        poll.register(tail.stdout)
        threading.Timer(1.0, self._check_for_new_lines(poll, tail)).start()

    def _check_for_new_lines(self, poll, tail):
        self._log.info('polling')
        if poll.poll(1):
            line = tail.stdout.readline()
            self._log.info('new line!: ' + str(line))
            self._server.send_message_to_all(line)
        time.sleep(1)
        threading.Timer(1.0, self._check_for_new_lines(poll, tail)).start()


from sPENminer import sPENminer
from oPENminer import oPENminer
from stream import Stream
import argparse
import sys

def parse_args():
    def str2bool(v):
        if v.lower() in ('yes', 'true', 't', 'y', '1'):
            return True
        elif v.lower() in ('no', 'false', 'f', 'n', '0'):
            return False
        else:
            raise argparse.ArgumentTypeError('Boolean value expected.')

    parser = argparse.ArgumentParser()
    parser.add_argument('--verbose', type=str2bool, default=True, required=False, help="If True, then print on the fly.")
    parser.add_argument('--stream', '-s', type=str, required=True, help="Stream name.")
    parser.add_argument('--window_size', '-ws', type=int, default=1, required=False, help="Window size; equivalent to max duration (\delta_max).")
    parser.add_argument('--max_size', '-ms', type=int, default=1, required=False, help="Max snippet size (k_max).")
    parser.add_argument('--view', '-v', type=str, default='id', required=False, help="What view of nodes to use.")
    parser.add_argument('--alpha', '-alpha', type=float, default=1, required=False, help="What exponent to use for W().")
    parser.add_argument('--beta', '-beta', type=float, default=1, required=False, help="What exponent to use for F().")
    parser.add_argument('--gamma', '-gamma', type=float, default=1, required=False, help="What exponent to use for S().")
    parser.add_argument('--delimiter', '-d', type=str, default=',', required=False, help="Delimiter.")
    parser.add_argument('--offline', '-o', type=str2bool, default=False, required=False, help="If True, then run offline version.")
    parser.add_argument('--seed', '-seed', type=int, default=0, required=False, help="Seed for random cut forests.")
    parser.add_argument('--save_output', '-save', type=str2bool, default=True, required=False, help="If True, then save persistence scores.")
    parser.add_argument('--save_occs', '-so', type=str2bool, default=False, required=False, help="If True, then save occurrences (offline version only).")
    return parser.parse_args()

def main(args):
    stream = Stream(args.stream, delimiter=args.delimiter)
    print('Using view \"{}\"'.format(args.view))
    if not args.offline:
        if args.save_occs:
            print('\'save_occs = True\' is only an option for offline verions. Occurrences will not be saved')
        method = sPENminer(stream,
                           window_size=args.window_size,
                           max_size=args.max_size,
                           view=args.view,
                           alpha=args.alpha,
                           beta=args.beta,
                           gamma=args.gamma,
                           save_output=args.save_output)
    else:
        method = oPENminer(stream,
                           window_size=args.window_size,
                           max_size=args.max_size,
                           view=args.view,
                           alpha=args.alpha,
                           beta=args.beta,
                           gamma=args.gamma,
                           save_output=args.save_output,
                           save_occs=args.save_occs)
    method.mine(verbose=args.verbose)

if __name__ == "__main__":
    args = parse_args()
    main(args)


import copy
import torch.nn as nn
import torch.optim as optim

from Net import Net

class Agent(object):
    def __init__(self, LR, global_net_dict, label_length, output_length):
        self.LR = LR
        self.output_length = output_length
        self.net = Net(label_length, self.output_length+1) # 由于取头取尾,所以加1
        self.net.load_state_dict(global_net_dict)
        self.criterion = nn.CrossEntropyLoss()

    def train(self, inputs, labels, global_net_dict):
        labels = labels.view(len(labels)).long()
        # inputs, labels = inputs.to(device), labels.to(device)
        self.net.load_state_dict(global_net_dict)
        outputs = self.net(inputs)
        loss = self.criterion(outputs, labels)
        optimizer = optim.SGD(self.net.parameters(), lr=self.LR)
        optimizer.zero_grad()  # 梯度置零
        loss.backward()  # 求取梯度
        # 提取梯度
        grad_dict = dict()
        params_modules = list(self.net.named_parameters())
        for params_module in params_modules:
            (name, params) = params_module
            params_grad = copy.deepcopy(params.grad)
            grad_dict[name] = params_grad
        optimizer.zero_grad()  # 梯度置零
        return grad_dict


import torch
import torch.nn as nn

from typing import Dict, Any

from argparse import _ArgumentGroup

import argparse
import numpy as np

from .cnn import CNN, IMAGE_SIZE

class IvanoConv(nn.Module):
    def __init__(self, in_dim: int, out_dim: int, kernel_size:int=3, stride:int=1, padding:int=1):
        super().__init__()
        self.conv = nn.Conv2d(in_dim, out_dim, kernel_size=kernel_size, stride=stride, padding=padding)
        self.relu = nn.ReLU()

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        x = self.conv(x)
        x = self.relu(x)
        return x

class LineCNNIvan(nn.Module):
    """Process the line through a CNN and process the resulting sequence through LSTM layers."""

    def __init__(
        self,
        data_config: Dict[str, Any],
        args: argparse.Namespace = None,
    ) -> None:
        super().__init__()
        conv_dim = args.fc_dim
        n_classes = len(data_config['mapping'])
        n_colors, HEIGHT, _W = data_config["input_dims"]
        seq_len, _ = data_config['output_dims']
        fc_dim = args.fc_dim
        self.window_width = args.window_width
        self.window_height = args.window_width
        self.window_stride = args.window_stride
        self.data_config = data_config
        # striding early (vs in the last layer) allows us to reduce the amount of compute while still passing info down the line
        self.convs = nn.Sequential(
            IvanoConv(n_colors    , conv_dim              ),
            IvanoConv(conv_dim    , conv_dim    , stride=2),
            IvanoConv(conv_dim    , conv_dim),
            IvanoConv(conv_dim    , conv_dim * 2, stride=2),
            IvanoConv(conv_dim * 2, conv_dim * 2),
            IvanoConv(conv_dim * 2, conv_dim * 4, stride=2),
            IvanoConv(conv_dim * 4, conv_dim * 4),
            IvanoConv(conv_dim * 4, fc_dim,
                                    kernel_size=(HEIGHT//8, self.window_width//8),
                                    stride=(self.window_height//8, self.window_stride//8),
                                    padding=0
            )
        )

        # TODO: this sort of gets to 27x27 receptive field on a single output of the feature map
        self.fc1 = nn.Linear(fc_dim, fc_dim)
        self.dropout = nn.Dropout(0.2)
        self.fc2 = nn.Linear(fc_dim, n_classes)
        self.limit_output_length = args.limit_output_length
        self.output_length = seq_len
        if args.init_weights:
            self._init_weights()

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """
        [Batch, Color, Height, Width] -> [Batch, Classes, SeqLen]
        1) receptive field size for each of the output columns ~window_width
        2) there-s gonna be (line_width-window_width)/window_stride columns in the output
        last? convolutional layer will be basically doing the job the code was doing of sliding the CNN
        """
        x = self.convs(x)
        # we're at (B, fc_dim, 1, SeqLen) here
        # -> (B, SeqLen, n_classes)

        x = x.squeeze(2).transpose(1, 2)
        x = self.fc1(x)
        x = self.dropout(x)
        x = self.fc2(x)

        # -> (B, n_classes, SeqLen)
        x = x.transpose(1, 2)

        # -> torch.Size([128, 83, 32])
        if self.limit_output_length:
            x = x[..., :self.output_length]

        return x

    def _init_weights(self):
        import math
        """
        Initialize weights in a better way than default.
        See https://github.com/pytorch/pytorch/issues/18182
        """
        for m in self.modules():
            if type(m) in {
                nn.Conv2d,
                nn.Conv3d,
                nn.ConvTranspose2d,
                nn.ConvTranspose3d,
                nn.Linear,
            }:
                nn.init.kaiming_normal_(m.weight.data, a=0, mode="fan_out", nonlinearity="relu")
                if m.bias is not None:
                    _fan_in, fan_out = nn.init._calculate_fan_in_and_fan_out(  # pylint: disable=protected-access
                        m.weight.data
                    )
                    bound = 1 / math.sqrt(fan_out)
                    nn.init.normal_(m.bias, -bound, bound)

    def add_to_argparse(parser: _ArgumentGroup):
        parser.add_argument('--window_width', type=int)
        parser.add_argument('--window_stride', type=int)
        parser.add_argument('--fc_dim', type=int, default=128)
        parser.add_argument('--conv_dim', type=int, default=128)
        parser.add_argument("--limit_output_length", action="store_true", default=False)
        parser.add_argument("--init_weights", action="store_true", default=False)