from domain.incident import Incident

class HelpFormatter:
    """"""

    def format(self):
        response = {
            # "response_type": "in_channel",
            "blocks": [
                {
                    "type": "section",
                    "text": {
                        "type": "mrkdwn",
                        "text": "Hey there ðŸ‘‹ I'm Sereno. I'm here to show you how we can interact with each other. First let's see the commands you can send me",
                    },
                },
                {
                    "type": "section",
                    "text": {
                        "type": "mrkdwn",
                        "text": "â€¢ `/sereno register` This command will show you a list of apps you can integrate with me. For example: zoom, jira, pagerduty. etc.",
                    },
                },
                {
                    "type": "section",
                    "text": {
                        "type": "mrkdwn",
                        "text": "â€¢ `/sereno responders list` This command will show you the list of responders. When a new incident is created, a user set as responder will be added to the incident channel. If a channel is set as responder, that channel will get a notification when an incident is created.",
                    },
                },
                {
                    "type": "section",
                    "text": {
                        "type": "mrkdwn",
                        "text": "â€¢ `/sereno responders add @username` This command will add a user to the list of responders. You can concatenate as many users as you want in one command.",
                    },
                },
                {
                    "type": "section",
                    "text": {
                        "type": "mrkdwn",
                        "text": "â€¢ `/sereno responders add #channel` This command will add achannel to the list of responders. You can concatenate as many channels or users as you want in one command.",
                    },
                },
                {
                    "type": "section",
                    "text": {
                        "type": "mrkdwn",
                        "text": "â€¢ `/sereno set oncall @username` This command will set the oncall person. To get who is set as oncall you can tag me asking me this question. For exampe: `@Sereno who's oncall?`. The oncall will also be added to an incident channel.",
                    },
                },
                {
                    "type": "section",
                    "text": {
                        "type": "mrkdwn",
                        "text": "â€¢ `/sereno close incident` I'll close the incident and log a closing line into the associated jira ticket. This will work inside an incident channel",
                    },
                },
                {"type": "divider"},
                {
                    "type": "section",
                    "text": {
                        "type": "mrkdwn",
                        "text": "You can also tag me asking me questions or telling me things to do",
                    },
                },
                {
                    "type": "section",
                    "text": {
                        "type": "mrkdwn",
                        "text": "â€¢ `@Sereno new incident` By telling me this, I'll create a new incident. I'll create an incident channel, inbolve the appropriate people, and work with the integrations you set up.",
                    },
                },
                {
                    "type": "section",
                    "text": {
                        "type": "mrkdwn",
                        "text": "â€¢ `LOG: <any text>` If you have a jira integration, I'll log anything you add after the LOG: command into the jira ticket associated to the incident. This will work inside an incident channel",
                    },
                },
                {
                    "type": "section",
                    "text": {
                        "type": "mrkdwn",
                        "text": "â€¢ `@Sereno who's oncall` I'll tell you who's the oncall",
                    },
                },
            ]
        }
        return response


from tkinter import *

def count(text):
    data = text.get('0.0', END)
    a, t, c, g = 0, 0, 0, 0
    for char in data:
        if char == 'A':
            a += 1
        if char == 'T':
            t += 1
        if char == 'G':
            g += 1
        if char == 'C':
            c += 1
    counter.set('A:%d T:%d C:%d G:%d' % (a, t, c, g))

window = Tk()
frame = Frame(window)
frame.pack()
text = Text(frame, height=3, width=10)
text.pack()
button = Button(frame, text='Count', command=lambda: count(text))
button.pack()
counter = StringVar()
label = Label(frame, textvariable=counter)
label.pack()

window.mainloop()


def three_sum_bucket_search(arr, M):
    n = len(arr)

    bucket = [0] * 100001

    for i in range(len(arr)):
        bucket[arr[i]] = i

    count = 0
    for i in range(n):
        for j in range(i + 1, n):
            k = bucket[M - arr[i] - arr[j]]
            if k is not None and k > j:
                print("%d + %d + %d == %d" % (arr[i], arr[j], M - arr[i] - arr[j], M))
                count += 1
    return count

# examples
if __name__ == "__main__":
    print("\nNumber of triples = %s" % three_sum_bucket_search([3, 1, 13, 9, 21, 11, 5, 10, 6, 34], 25))


import sys

s = str(sys.stdin.readline().rstrip())
s = list(s)
rst = []
"""후위표기식"""
stack = []
"""연산자"""
for i in s:
    if i.isalpha():
        """i가 알파벳인 경우 rst에 push"""
        rst.append(i)
    if i == '(':
        """(는 연산자 stack에 push"""
        stack.append(i)
    elif i == ')':
        while True:
            if stack and stack[-1] != '(':
                """연산자 스택이 비거나 (를 만날때까지, stack에는 (와 연산자들만 있음"""
                """ex)A*(B+C)면 stack에는 [*,(,+]"""
                rst += stack.pop()
                """stack을 pop해서 rst에 넣어줌"""
            else:
                stack.pop()
                """(를 지워주기 위함"""
                break
            """어려움"""
            """연산자가 들어오면 자기보다 우선순위가 높거나 같은 것들을 빼고 자신을 stack에 넣는다"""
    elif i == '+' or i == '-':
        """i가 +인지 -인지 확인"""
        while stack and stack[-1] != '(':
            """+와 -는 연산자 우선순위 상관이 없다"""
            rst += stack.pop()
            """stack을 pop한 후 rst에 더함"""
        stack.append(i)
        """stack에 i추가"""
    elif i == '*' or i == '/':
        """i가 *인지 /인지 확인"""
        while stack and (stack[-1] == '*' or stack[-1] == '/'):
            """같은 우선순위에 있는 *와 /"""
            rst += stack.pop()
            """rst뒤에 stack pop한것을 넣음"""
        stack.append(i)
        """stack에 i추가"""
while stack:
    rst += stack.pop()
print("".join(rst))


from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.generic import TemplateView
from django.views.generic.base import RedirectView

from dg.base_settings import TRAINING_PAGE, TRAINING_APP_PAGE

from tastypie.api import Api
from training.api import TrainerResource, LanguageResource, AssessmentResource, QuestionResource, MediatorResource, DistrictResource, VillageResource, PartnerResource, TrainingResource, StateResource, ScoreResource

from views import login, dashboard, graph_data, get_overall_data, get_filter_data

from training.log.training_log import send_updated_log
from training.admin import training_admin

from social_website.views import picoseekho_view, disseminationprep_view, disseminationform_view, adoptionverification_view

api = Api(api_name = "v1")
api.register(TrainerResource())
api.register(TrainingResource())
api.register(LanguageResource())
api.register(AssessmentResource())
api.register(QuestionResource())
api.register(MediatorResource())
api.register(DistrictResource())
api.register(VillageResource())
api.register(PartnerResource())
api.register(StateResource())
api.register(ScoreResource())

urlpatterns = patterns('',
	url(r'^$', RedirectView.as_view(url=TRAINING_PAGE)),
    url(r'^app/', RedirectView.as_view(url=TRAINING_APP_PAGE)),
    url(r'^login/', login),
    url(r'^api/', include(api.urls)),
    url(r'^analytics/', dashboard),
    url(r'^graph_data', graph_data),
    url(r'^get_log/', send_updated_log),
    url(r'^getCardGraphData', get_overall_data),
    url(r'^get_filter_data',get_filter_data),
    # admin/logout/ should be above admin/ URL
    url(r'^admin/logout/?$', 'django.contrib.auth.views.logout', {'next_page': '/training/admin/'}),
    url(r'^admin/', include(training_admin.urls)),
    url(r'^courseware/$', TemplateView.as_view(template_name='training_hi.html'), name='training'),
    url(r'^courseware/en/$', TemplateView.as_view(template_name='training_en.html'), name='training-el'),
    url(r'^courseware/hi/$', TemplateView.as_view(template_name='training_hi.html'), name='training-hi'),
    url(r'^courseware/fr/$', TemplateView.as_view(template_name='training_fr.html'), name='training-fr'),
    url(r'^courseware/picoseekho/(?P<uid>.+)/$', picoseekho_view, name='picoseekho'),
    url(r'^courseware/picoseekho/$', picoseekho_view, name='picoseekho'),
    url(r'^courseware/dissemination_prep/(?P<uid>.+)/$', disseminationprep_view, name='disseminationprep'),
    url(r'^courseware/dissemination_prep/$', disseminationprep_view, name='disseminationprep'),
    url(r'^courseware/dissemination_form/(?P<uid>.+)/$', disseminationform_view, name='disseminationform'),
    url(r'^courseware/dissemination_form/$', disseminationform_view, name='disseminationform'),
    url(r'^courseware/adoption_verification/(?P<uid>.+)/$', adoptionverification_view, name='adoptionverification'),
    url(r'^courseware/adoption_verification/$', adoptionverification_view, name='adoptionverification'),
    )


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

from imdb import IMDb
import json
# oppure jsonpickle???

# JSON snippets from https://github.com/hrishikeshsathe/IMDb-to-JSON
class JSONAttributes:
    title = ''
    duration = ''
    genre = []
    rating= 0.0
    description = ''
    actors = []
    seasons = []
    director = ''
    creators = []
    def __init__(self):
        self.title = ''
        self.duration = ''
        self.genre = []
        self.rating = 0.0
        self.description = ''
        self.actors = []
        self.director = ''
        self.creators = []

    def print_overview(self):
        print("Title: ",self.title)
        print("Duration: ",self.duration)
        print("Genre: ",self.genre)
        print("Rating: ",self.rating)
        print("Description: ",self.description)
        print("Creators: ",self.creators)
        print("Director: ",self.director)
        print("Actors: ",self.actors)

def write_json(json):

    """ write data into file as json object """

    file = open(json.title+'.json','w')
    file.write('{\n')
    file.write('"title":"'+json.title+'",\n')
    file.write('"duration":"'+json.duration+'",\n')
    file.write('"genre":[')
    file.write(','.join('"'+x+'"' for x in json.genre))
    file.write('],\n')
    file.write('"rating":"'+json.rating+'",\n')
    file.write('"description":"'+json.description+'",\n')
    file.write('"director":"'+json.director+'",\n')
    file.write('"creators":[')
    file.write(','.join('"'+x+'"' for x in json.creators))
    file.write('],\n')
    file.write('"actors":[')
    file.write(','.join('"'+x+'"' for x in json.actors))
    file.write('],\n')
    file.write('"seasons":[')
    file.write(','.join('['+episode_list_as_string(season)+']\n' for season in json.seasons))
    file.write(']\n}')
    file.close()
    print('Writing done')

#create json object. check class JSONAttributes(). it just contains variables to store values
json_temp = JSONAttributes()

# create an instance of the IMDb class
ia = IMDb()

# get a movie
movie = ia.get_movie('0060315')

# print the names of the directors of the movie
#print('Actors:')
for director in movie['director']:
    json_temp.director = director
    print(json.dump(json_temp))

# print the genres of the movie
print('Genres:')
for genre in movie['genres']:
    print(genre)


############################################ PREGUNTA 2
text="Lorem ipsum"
list=["Lorem","ipsum"]

def pregunta1():
    print(text.split(sep=" "))
    print(" ".join(list))
    print(text.count("ipsum"))
    print(text.find("ipsum"))
    print(text.upper())
    print(text.lower())

pregunta1()

############################################ PREGUNTA 3
def pregunta2():
    print(number*2)
    print(number/5)
number=int(input("Ingrese un número: "))

pregunta2()

############################################ PREGUNTA 4
class producto:
    def __init__(self,nombre,marca,expire,medida):
        self.nombre= nombre
        self.marca= marca
        self.expire= expire
        self.medida= medida
        print("Se ha agregado un producto:",self.nombre)
    def __str__(self):
        return '{}, {} - {}'.format(self.nombre,self.marca, self.medida)
class catalogo:
    product=[]
    def __init__(self, product=[]):
        self.product=product
    def agregar(self,p):
        self.product.append(p)
    def mostrar(self):
        for p in self.product:
            print(p)

p=producto("Filtro hidráulico","TECFIL","No expira","Estándar")
c=catalogo([p])

c.agregar(producto("Batería", "ACDELCO","2025","Estándar"))
c.mostrar()

############################################ PREGUNTA 5
def sumatoria(a):
    print("La suma refrectiva es", a + sumatoria(a-1))

def divide(c,d):
    print("La división es ", c/d)

############################################ PREGUNTA 6

############################################ PREGUNTA 7
class PRODUCTO:
    def __init__(self,PAIS,LOTE,AÑO):
        self.PAIS= PAIS
        self.LOTE= LOTE
        self.AÑO= AÑO
        print("El lote número ", self.LOTE, "se ubica en ", self.PAIS)

codigo=(input("Digite el número de serie: "))
c_1=codigo.split(sep="-")
a=PRODUCTO(c_1[0],c_1[1],c_1[-1])

############################################


"""Authentication-related models for nautobot-netbox-importer."""

from typing import List

from diffsync.enum import DiffSyncModelFlags
import django.contrib.auth.models as auth
import structlog

from .abstract import DjangoBaseModel
from .references import ContentTypeRef, PermissionRef

class Group(DjangoBaseModel):
    """Definition of a user group."""

    _modelname = "group"
    _identifiers = ("name",)
    _attributes = ("permissions",)
    _nautobot_model = auth.Group

    name: str
    permissions: List[PermissionRef] = []

class Permission(DjangoBaseModel):
    """Definition of a permissions rule."""

    _modelname = "permission"
    _identifiers = ("content_type", "codename")
    _attributes = ("name",)
    _nautobot_model = auth.Permission

    content_type: ContentTypeRef
    codename: str

    name: str

    def __init__(self, *args, **kwargs):
        """Set the IGNORE flag on permissions that refer to content-types that do not exist in Nautobot."""
        super().__init__(*args, **kwargs)
        if (
            self.content_type["app_label"]
            not in [
                "auth",
                "circuits",
                "contenttypes",
                "dcim",
                "extras",
                "ipam",
                "references",
                "taggit",
                "tenancy",
                "users",
                "virtualization",
            ]
            or self.content_type["model"] not in self.diffsync.top_level
        ):
            structlog.get_logger().debug(
                "Flagging permission for extraneous content-type as ignorable",
                diffsync=self.diffsync,
                app_label=self.content_type["app_label"],
                model=self.content_type["model"],
            )
            self.model_flags |= DiffSyncModelFlags.IGNORE


# -*- coding: utf-8 -*-
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
# Import
import numpy as np
import matplotlib.pyplot as plt

from .utils.activation import Activation
from .utils.cost_functions import CostFunctions

#------------------------------------------------------------------------------
#------------------------------------------------------------------------------

class Perceptron:
    """
    A simple implementation of a Perceptron.

    Parameters
    ----------
    n_iter : int, optional
        The number of iterations to train the Perceptron for, by default 100.
    learning_rate : float, optional
        The learning rate for the Perceptron, by default 0.1.
    activation : str, optional
        The activation function to use for the Perceptron, by default 'sigmoid'.
        Can take 'sigmoid', 'tanh' or 'relu' values

    Attributes
    ----------
    W : np.ndarray
        The weights for the Perceptron.
    b : np.ndarray
        The bias for the Perceptron.

    Methods
    -------
    fit(X: np.ndarray, y: np.ndarray) -> None:
        Trains the Perceptron on the given data.
    predict(X: np.ndarray) -> np.ndarray:
        Predicts the output for the given input using the trained Perceptron.
    """
    def __init__(self, n_iter: int = 100, learning_rate: float = 0.1, activation: str = 'sigmoid'):
        """
        Initializes a new instance of the Perceptron class.

        Parameters
        ----------
        n_iter : int, optional
            The number of iterations to train the Perceptron for, by default 100.
        learning_rate : float, optional
            The learning rate for the Perceptron, by default 0.1.
        activation : str, optional
            The activation function to use for the Perceptron, by default 'sigmoid'.
        """
        self.n_iter = n_iter
        self.learning_rate = learning_rate
        try :
            self.activation = getattr(Activation, activation)
        except :
            raise ValueError(f'Unknown activation function: {activation}')

    def __initialize_weights(self, input_size: int) -> None:
        """
        Initializes the weights for the Perceptron.

        Parameters
        ----------
        input_size : int
            The number of features in the input data.
        """
        self.W = np.random.randn(input_size, 1)
        self.b = np.random.randn(1)

    def __compute_gradients(self, X: np.ndarray, y: np.ndarray) -> tuple:
        """
        Computes the gradients for weights and bias.

        Parameters
        ----------
        X : np.ndarray
            The input data.
        y : np.ndarray
            The target values.

        Returns
        -------
        tuple
            Tuple containing gradients for weights and bias.
        """
        Z = X.dot(self.W) + self.b
        A = self.activation(Z)
        dW = 1 / len(y) * np.dot(X.T, A - y)
        db = 1 / len(y) * np.sum(A - y)
        return dW, db

    def __update_weights(self, dW: np.ndarray, db: np.ndarray) -> None:
        """
        Updates the weights and bias using the computed gradients.

        Parameters
        ----------
        dW : np.ndarray
            Gradients for weights.
        db : np.ndarray
            Gradient for bias.
        """
        self.W -= self.learning_rate * dW
        self.b -= self.learning_rate * db

    def fit(self, X: np.ndarray, y: np.ndarray, record_loss: bool = False) -> None:
        """
        Trains the Perceptron on the given data.

        Parameters
        ----------
        X : np.ndarray
            The input data to train the Perceptron on.
        y : np.ndarray
            The target values for the input data.
        """
        self.__initialize_weights(X.shape[1])
        if record_loss:
            self.losses = []

        for _ in range(self.n_iter):
            dW, db = self.__compute_gradients(X, y)
            self.__update_weights(dW, db)

            if record_loss:

                A = self.activation(X.dot(self.W) + self.b)
                loss = CostFunctions.log_loss(y, A)
                self.losses.append(loss)

    def predict(self, X: np.ndarray) -> np.ndarray:
        """
        Predicts the output for the given input using the trained Perceptron.

        Parameters
        ----------
        X : np.ndarray
            The input data to predict the output for.

        Returns
        -------
        np.ndarray
            The predicted output for the input data.
        """
        Z = X.dot(self.W) + self.b
        if self.activation == Activation.sigmoid:
            A = self.activation(Z)
            return A >= 0.5
        elif self.activation == Activation.tanh:
            A = self.activation(Z)
            return A >= 0
        elif self.activation == Activation.relu:
            A = self.activation(Z)
            return A >= 0
        else:
            raise ValueError(f'Unknown activation function: {self.activation}')

    def plot_decision_boundary(self, X, y, title="Decision Boundaries"):
        plt.scatter(X[:, 0], X[:, 1], c=y, cmap="viridis", label="Data Points")
        x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
        y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
        xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.1), np.arange(y_min, y_max, 0.1))
        Z = self.predict(np.c_[xx.ravel(), yy.ravel()])
        Z = Z.reshape(xx.shape)
        plt.contour(xx, yy, Z, alpha=0.3, levels=[0], linestyles='dashed', colors='blue', label="Decision Boundary")
        plt.xlabel('Feature 1')
        plt.ylabel('Feature 2')
        plt.title(title)
        plt.legend()
        plt.show()

    def get_loss_history(self) -> list:
        """
        Returns the recorded loss values during training.

        Returns
        -------
        list
            List of loss values recorded during training.
        """
        if hasattr(self, 'losses'):
            return self.losses
        else:
            print("Loss history not available. Train the model with record_loss=True to capture loss values.")
            return []

#------------------------------------------------------------------------------
#------------------------------------------------------------------------------


import cv2
import imutils
import numpy as np
import pytesseract

img = cv2.imread("/Users/rasleen/Downloads/opencv-text-recognition/car.jpg")
img = cv2.resize(img, (620,480) )
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #convert to grey scale
gray = cv2.bilateralFilter(gray, 11, 17, 17)
edged = cv2.Canny(gray, 30, 200) #Perform Edge detection
cnts = cv2.findContours(edged.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:10]
screenCnt = None
# loop over our contours
for c in cnts:
                # approximate the contour
	peri = cv2.arcLength(c, True)
	approx = cv2.approxPolyDP(c, 0.018 * peri, True)
                # if our approximated contour has four points, then
                # we can assume that we have found our screen
	if len(approx) == 4:
		screenCnt = approx
		break
# Masking the part other than the number plate
mask = np.zeros(gray.shape,np.uint8)
new_image = cv2.drawContours(mask,[screenCnt],0,255,-1,)
new_image = cv2.bitwise_and(img,img,mask=mask)
#cv2.imwrite('biketest.jpg',new_image)
# Now crop
(x, y) = np.where(mask == 255)
(topx, topy) = (np.min(x), np.min(y))
(bottomx, bottomy) = (np.max(x), np.max(y))
Cropped = gray[topx:bottomx+1, topy:bottomy+1]
#Read the number plate
cv2.imwrite('10croptest.jpg',Cropped)
text = pytesseract.image_to_string(Cropped, config='--psm 11')

print("Detected Number is:",text)


#!/usr/bin/env python

"""

You are given a positive integer array nums.

The element sum is the sum of all the elements in nums.
The digit sum is the sum of all the digits (not necessarily distinct) that appear in nums.
Return the absolute difference between the element sum and digit sum of nums.

Note that the absolute difference between two integers x and y is defined as |x - y|.

Example 1:

Input: nums = [1,15,6,3]
Output: 9
Explanation:
The element sum of nums is 1 + 15 + 6 + 3 = 25.
The digit sum of nums is 1 + 1 + 5 + 6 + 3 = 16.
The absolute difference between the element sum and digit sum is |25 - 16| = 9.

Example 2:

Input: nums = [1,2,3,4]
Output: 0
Explanation:
The element sum of nums is 1 + 2 + 3 + 4 = 10.
The digit sum of nums is 1 + 2 + 3 + 4 = 10.
The absolute difference between the element sum and digit sum is |10 - 10| = 0.

Constraints:

1 <= nums.length <= 2000
1 <= nums[i] <= 2000

Hint:
Use a simple for loop to iterate each number.
How you can get the digit for each number?

"""

def digitsum(n):
    r = 0
    while n > 0:
        r += n % 10
        n //= 10
    return r

def diffsum(a):
    x = sum(a)
    y = 0
    for v in a:
        y += digitsum(v)
    return abs(x - y)

def main():
    assert(diffsum([1, 15, 6, 3]) == 9)
    assert(diffsum([1, 2, 3, 4]) == 0)

main()


import asyncio
import os
import time
from asyncio.exceptions import TimeoutError, IncompleteReadError
from ssl import SSLError
from urllib.parse import urlparse

from aiohttp import ClientSession, ClientTimeout, ServerDisconnectedError
from aiohttp_socks import ProxyConnector
from python_socks._errors import ProxyConnectionError, ProxyError, ProxyTimeoutError

DATA_FILES_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data')
PROXIES_FILE_PATH = os.path.join(DATA_FILES_PATH, 'proxies.txt')
ALIVE_PROXIES_FILE_PATH = os.path.join(DATA_FILES_PATH, 'alive_proxies.txt')

CHECKING_URL = 'https://google.com/'
CONNECTION_TIMEOUT = 10

async def check_proxy(proxy: str) -> tuple[str, float]:
    connector = ProxyConnector.from_url(proxy)
    session_timeout = ClientTimeout(sock_connect=CONNECTION_TIMEOUT)

    async with ClientSession(connector=connector, timeout=session_timeout) as session:
        start = time.time()
        try:
            await session.get(CHECKING_URL, timeout=CONNECTION_TIMEOUT)
        except (
                ProxyConnectionError, ConnectionResetError, ProxyError, ProxyTimeoutError,
                IncompleteReadError, TimeoutError, ServerDisconnectedError, SSLError,
        ):
            print(f'Proxy {proxy} is DEAD.')
            return proxy, 0
        else:
            response_time = time.time() - start

        prts = urlparse(proxy)
        proxy = f'{prts.scheme}\t{prts.hostname}\t{prts.port}'

        print(f'Proxy {proxy} is ALIVE.')
        return proxy, response_time

async def main() -> None:
    with open(PROXIES_FILE_PATH) as proxies_file:
        proxies = set(proxies_file.read().split('\n'))

    tasks = []
    for proxy in proxies:
        tasks.append(asyncio.create_task(check_proxy(proxy)))

    result = await asyncio.gather(*tasks)

    alive_proxies = [(proxy, response_time) for proxy, response_time in result if response_time > 0]
    sorted_alive_proxies = [proxy for proxy, _ in sorted(alive_proxies, key=lambda x: x[1])]

    with open(PROXIES_FILE_PATH, 'w') as proxies_file, open(ALIVE_PROXIES_FILE_PATH, 'w') as alive_proxies_file:
        proxies_file.write('\n'.join(proxies))
        alive_proxies_file.write('\n'.join(sorted_alive_proxies))

if __name__ == '__main__':
    asyncio.run(main())


from dataclasses import dataclass
import logging
import pprint
import threading

from typing import Optional

from google.protobuf import empty_pb2

import tmux_pb2_grpc
import x11

@dataclass(frozen=True)
class TmuxClient:
    """Tmux clients are represented by hostname + client name.

    Client name happens to be a tty name.
    """
    hostname: str
    client_name: str

@dataclass(frozen=True)
class TmuxSession:
    """Tmux sessions are represented by tmux server PID + session name."""
    session_name: str
    hostname: str
    server_pid: int

class XWindowIdTmuxClientMap:
    """Maintains a mapping from a X Window ID to a tmux client.

    Thread-unsafe.
    """

    def __init__(self):
        self._map = {}

    def __getitem__(self, x_window_id: x11.XWindowId) -> TmuxClient:
        return self._map[x_window_id]

    def __setitem__(self, x_window_id: x11.XWindowId, client: TmuxClient) -> None:
        self._map[x_window_id] = client

    def __delitem__(self, x_window_id: x11.XWindowId) -> None:
        del self._map[x_window_id]

    def __contains__(self, x_window_id: x11.XWindowId) -> bool:
        return x_window_id in self._map

    def __repr__(self):
        rpr = pprint.pformat({
            k: f'{v.hostname}:{v.client_name}'
            for k, v in self._map.items()
        })
        return f'{self.__class__.__name__}({rpr})'

class TmuxClientSessionMap:
    """Maintains a mapping from a tmux client to a tmux session."""

    def __init__(self):
        self._map = {}
        self._lock = threading.Lock()

    def __getitem__(self, client: TmuxClient) -> TmuxSession:
        with self._lock:
            return self._map[client]

    def __setitem__(self, client: TmuxClient, session: TmuxSession) -> None:
        with self._lock:
            self._map[client] = session

    def __delitem__(self, client: TmuxClient) -> None:
        with self._lock:
            del self._map[client]

    def __contains__(self, client: TmuxClient) -> bool:
        with self._lock:
            return client in self._map

    def session_renamed(self, client: TmuxClient, new_session: TmuxSession) -> None:
        with self._lock:
            # * Find the name of the session the client is connected to
            #   according to our data.
            old_session = self._map[client]
            # * Find if there are any other clients on that hostname connected
            #   to the same session on the same tmux server.
            clients_to_update = [
                    client
                    for client, session in self._map.items()
                    if session == old_session
            ]
            # * For each client set it to the new session
            for client in clients_to_update:
                self._map[client] = new_session

    def session_closed(self, session: TmuxSession) -> None:
        with self._lock:
            clients_to_update = [
                    client
                    for client, session_ in self._map.items()
                    if session_ == session
            ]
            for client in clients_to_update:
                del self._map[client]

    def __repr__(self):
        with self._lock:
            rpr = pprint.pformat({
                k.client_name: f'{v.hostname}:{v.session_name}'
                for k, v in self._map.items()
            })
            return f'{self.__class__.__name__}({rpr})'

class TmuxAdapter:

    def __init__(self, span_tracker):
        self._x_window_id_tmux_client_map = XWindowIdTmuxClientMap()
        self._tmux_client_session_map = TmuxClientSessionMap()
        self._lock = threading.Lock()
        self._span_tracker = span_tracker
        self._focused_x_window_id: Optional[x11.XWindowId] = None

    def _check_span(self):
        if self._focused_x_window_id not in self._x_window_id_tmux_client_map:
            self._span_tracker.update_active_session(None)
            return
        client = self._x_window_id_tmux_client_map[self._focused_x_window_id]

        if client not in self._tmux_client_session_map:
            self._span_tracker.update_active_session(None)
            return
        session = self._tmux_client_session_map[client]

        self._span_tracker.update_active_session(session)

    def set_focused_x_window_id(self, x_window_id: x11.XWindowId, window_name: str) -> None:
        # logging.debug('set_focused_x_window_id(%r, %r)', x_window_id, window_name)
        with self._lock:
            self._focused_x_window_id = x_window_id
            self._check_span()

    ##
    # Methods for maintaining X Window ID ↔ tmux client mapping.

    def set_client_for_x_window_id(self, x_window_id: x11.XWindowId, client: TmuxClient) -> None:
        logging.debug('set_client_for_x_window_id(%r, %r)', x_window_id, client)
        with self._lock:
            self._x_window_id_tmux_client_map[x_window_id] = client
            # TODO: At this point the client shouldn't have a corresponding TmuxSession.
            # If it does we should raise a "surprise alert" here.
            self._check_span()

    def clear_client_for_x_window_id(self, x_window_id: x11.XWindowId) -> None:
        logging.debug('clear_client_for_x_window_id(%r)', x_window_id)
        with self._lock:
            try:
                client = self._x_window_id_tmux_client_map[x_window_id]
            except KeyError:
                pass
            else:
                del self._x_window_id_tmux_client_map[x_window_id]
                # The client will also be detached from any sessions.
                try:
                    del self._tmux_client_session_map[client]
                except KeyError:
                    pass
            self._check_span()

    ##
    # Methods for maintaining tmux client ↔ session mapping.

    def client_session_changed(self, client: TmuxClient, session: TmuxSession) -> None:
        logging.debug('client_session_changed(%r, %r)', client, session)
        with self._lock:
            self._tmux_client_session_map[client] = session
            self._check_span()

    def client_detached(self, client: TmuxClient) -> None:
        logging.debug('client_detached(%r)', client)
        with self._lock:
            try:
                del self._tmux_client_session_map[client]
            except KeyError:
                pass
            self._check_span()

    def session_renamed(self, client: TmuxClient, new_session: TmuxSession) -> None:
        logging.debug('session_renamed(%r, %r)', client, new_session)
        with self._lock:
            self._tmux_client_session_map.session_renamed(client, new_session)
            self._check_span()

    def session_closed(self, session: TmuxSession) -> None:
        logging.debug('session_closed(%r)', session)
        with self._lock:
            self._tmux_client_session_map.session_closed(session)
            self._check_span()

class Tmux(tmux_pb2_grpc.TmuxServicer):
    """A Tmux gRPC server.

    Passes updates from shell and tmux to TmuxController.
    """

    def __init__(self, tmux_adapter: TmuxAdapter):
        self._tmux_adapter = tmux_adapter

    def set_client_for_x_window_id(self, request, context):
        client = TmuxClient(hostname=request.hostname,
                            client_name=request.client_name)
        self._tmux_adapter.set_client_for_x_window_id(request.x_window_id, client)
        return empty_pb2.Empty()

    def clear_client_for_x_window_id(self, request, context):
        self._tmux_adapter.clear_client_for_x_window_id(request.x_window_id)
        return empty_pb2.Empty()

    def client_session_changed(self, request, context):
        client = TmuxClient(hostname=request.hostname,
                            client_name=request.client_name)
        session = TmuxSession(hostname=request.hostname,
                              server_pid=request.server_pid,
                              session_name=request.session_name)
        self._tmux_adapter.client_session_changed(client, session)

        return empty_pb2.Empty()

    def client_detached(self, request, context):
        client = TmuxClient(hostname=request.hostname,
                            client_name=request.client_name)
        self._tmux_adapter.client_detached(client)
        return empty_pb2.Empty()

    def session_renamed(self, request, context):
        client = TmuxClient(hostname=request.hostname,
                            client_name=request.client_name)
        new_session = TmuxSession(hostname=request.hostname,
                                  server_pid=request.server_pid,
                                  session_name=request.new_session_name)
        self._tmux_adapter.session_renamed(client, new_session)
        return empty_pb2.Empty()

    def session_closed(self, request, context):
        session = TmuxSession(hostname=request.hostname,
                              server_pid=request.server_pid,
                              session_name=request.session_name)
        self._tmux_adapter.session_closed(session)
        return empty_pb2.Empty()


# Migratory Birds

def migratoryBirds(arr):
    max = 0
    bird_type = None

    birds_type = {
        5: 0,
        4: 0,
        3: 0,
        2: 0,
        1: 0
    }

    for i in arr:
        birds_type[i] += 1

    for key, value in birds_type.items():
        if value >= max:
            max = value
            bird_type = key

    return bird_type

n = 6
arr = [1, 2, 3, 4, 5, 4, 3, 2, 1, 3, 4]

result = migratoryBirds(arr)

print(result)


import pandas as pd
from IPython.core.display import display

def stats_for_ens_first_stage():
    filename1 = 'resurse/out_ens_alsaedi.csv'
    # filename2 = 'resurse/out_ens_alsaedi_2.csv'
    # filename3 = 'resurse/out_ens_alsaedi_3.csv'
    # filename4 = 'resurse/out_ens_alsaedi_4.csv'
    # filename = 'resurse/out_ens_2_2.csv'
    # outfile = 'resurse/out_ens_d1_stats_2.csv'
    outfile = 'resurse/out_ens_d2_stats_faza1_primul_fisier.csv'
    df1 = pd.read_csv(filename1)
    # df2 = pd.read_csv(filename2)
    # df3 = pd.read_csv(filename3)
    # df4 = pd.read_csv(filename4)
    df = pd.concat([df1])
    display(df.to_string())
    df_grouped_by_strategy = df.groupby('strategy').mean()
    df_grouped_by_c1_strategy = df.groupby('c1_strategy').mean()
    df_grouped_by_c2_strategy = df.groupby('c2_strategy').mean()
    df_grouped_by_w_strategy = df.groupby('w_strategy').mean()
    df_grouped_by_estimators = df.groupby('estimators').mean()
    # df_grouped_by_weights = df.groupby('weights').mean().sort_values(
    #     ['test_accuracy', 'test_macro_avg_f1', 'test_weighted_avg_f1'], ascending=False).head(10)
    # df_grouped_by_c1 = df.groupby('c1').mean().sort_values(
    #     ['test_accuracy', 'test_macro_avg_f1', 'test_weighted_avg_f1'], ascending=False).head(10)
    # df_grouped_by_c2 = df.groupby('c2').mean().sort_values(
    #     ['test_accuracy', 'test_macro_avg_f1', 'test_weighted_avg_f1'], ascending=False).head(10)
    # df_grouped_by_w = df.groupby('w').mean().sort_values(
    #     ['test_accuracy', 'test_macro_avg_f1', 'test_weighted_avg_f1'], ascending=False).head(10)

    display(df_grouped_by_strategy.to_string())
    display(df_grouped_by_c1_strategy.to_string())
    display(df_grouped_by_c2_strategy.to_string())
    display(df_grouped_by_w_strategy.to_string())
    df_grouped_by_strategy.to_csv(outfile, mode='a')
    df_grouped_by_w_strategy.to_csv(outfile, mode='a')
    df_grouped_by_c1_strategy.to_csv(outfile, mode='a')
    df_grouped_by_c2_strategy.to_csv(outfile, mode='a')
    df_grouped_by_estimators.to_csv(outfile, mode='a')
    display(df_grouped_by_estimators.to_string())
    # display(df_grouped_by_weights.to_string())
    # display(df_grouped_by_c1.to_string())
    # display(df_grouped_by_c1.reset_index().mean())
    # display(df_grouped_by_c2.to_string())
    # display(df_grouped_by_c2.reset_index().mean())
    # display(df_grouped_by_w.to_string())
    # display(df_grouped_by_w.reset_index().mean())

def prepare_data_for_2_phase_stats():
    # file1 = 'resurse/out_ens_3_continuare.csv'
    # file2 = 'resurse/out_ens_3_test.csv'
    # file3 = 'resurse/out_ens_3.csv'
    file1 = 'resurse/out_ens_alsaedi_5_phase2.csv'
    df = pd.read_csv(file1)
    # df1= pd.read_csv(file2)
    # df2= pd.read_csv(file3)
    print(df.count())
    print(df.shape)
    # print(df1.count())
    # print(df1.shape)
    # print(df2.count())
    # print(df2.shape)
    # df_final = pd.concat([df, df1, df2], axis = 0).drop_duplicates()
    # df_final = pd.concat([df, df1, df2], axis = 0).groupby(['estimators', 'w_strategy', 'c1_strategy',
    #                                                         'c2_strategy', 'n_inter_pso', 'n_particles', 'best_cost',
    #                                                         'weights'] ).mean()
    df_final = pd.concat([df])
    # indexNoIterations = df_final[~df_final['n_inter_pso'].isin([10, 100, 300, 500])].index
    # df_final.drop(indexNoIterations, inplace=True)
    # indexNoParticles = df_final[~df_final['n_particles'].isin([10, 30, 50, 80, 100])].index
    # df_final.drop(indexNoParticles, inplace=True)
    print(df_final.count())
    print(df_final.shape)
    display(df_final.to_string())
    df_final.to_csv('resurse/out_ens_2_phase.csv', index = False)

def stats_for_ens_second_stage():
    # file = 'resurse/out_ens_2_phase.csv'
    # outfile = 'resurse/out_ens_2_phase_stats.csv'
    file = 'resurse/out_ens_alsaedi_5_phase2.csv'
    outfile = 'resurse/out_ens_D2_2phase_stats.csv'
    df = pd.read_csv(file)
    df_groupby_n_iter_pso = df.groupby('n_inter_pso').mean().reset_index()
    df_groupby_n_particles = df.groupby('n_particles').mean().reset_index()
    df_grouped_by_estimators = df.groupby('estimators').mean().reset_index()

    df_groupby_n_iter_pso.to_csv(outfile, mode='a')
    df_groupby_n_particles.to_csv(outfile, mode='a')
    df_grouped_by_estimators.to_csv(outfile, mode='a')

if __name__ == "__main__":
    stats_for_ens_second_stage()
    # stats_for_ens_first_stage()


from setuptools import setup

def get_long_description() -> str:
    with open('README.md') as f:
        return f.read()

package_name = 'pytest_network'

setup(
    name=package_name,
    version='0.0.2',
    author='Artem Lomonosov',
    author_email='mcproger7@gmail.com',
    maintainer='Artem Lomonosov',
    maintainer_email='mcproger7@gmail.com',
    license='MIT',
    url='https://github.com/best-doctor/pytest_network',
    description='A simple plugin to disable network on socket level.',
    long_description=get_long_description(),
    long_description_content_type='text/markdown',
    py_modules=[package_name],
    install_requires=['pytest>=5.3.1'],
    classifiers=[
        'Framework :: Pytest',
        'Topic :: Software Development :: Testing',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3.7',
        'Programming Language :: Python :: 3.8',
        'Programming Language :: Python :: 3.9',
    ],
    entry_points={
        'pytest11': [
            'network = pytest_network',
        ],
    },
)


# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def middleNode(self, head: ListNode) -> ListNode:
        middle = [head]
        while (middle[-1].next):
            middle.append(middle[-1].next)
        return middle[len(middle)//2]


# Making a long, but simple decision-based typing adventure game to practice my Python.
# Author: Brandon Helfrich

import sys
import time   # time.sleep() function pauses the program in between lines to simulate the feel of a "terminal game."

# Defining a typing text effect for the print() function
def typingPrint(text):
    for character in text:
        sys.stdout.write(character)
        sys.stdout.flush()
        time.sleep(0.025)

# Defining a typing text effect for the input() function
def typingInput(text):
    for character in text:
        sys.stdout.write(character)
        sys.stdout.flush()
        time.sleep(0.025)
    value = input()
    return value

# START OF INTRO

name = input("Name your character: ")
name = name.capitalize().strip()   # .capitalize().strip() function will auto capitalize the name & strip of spaces.
print()

time.sleep(1)

typingPrint("You awaken in a cold, damp cell. The feint squeaks of rats and water dripping on stone \n")
typingPrint("echoes in the dark.\n\n")

time.sleep(1)

typingPrint("Footsteps approach your cell and a raspy voice whispers out.\n\n")

time.sleep(1)

print("Voice :")
typingPrint("'Do you know who I am?'\n\n")

time.sleep(1)

# This typing game is decision-based and is heavily built on 'While True' loops.
while True:
    answer = input("([Y] for yes | [N] for no): ").lower().strip()   # .lower().strip() function will auto lowercase
    print()                                                          # input & strip of spaces. Useful in many cases
    if answer == "y":                                                # throughout this program.

        time.sleep(1)

        print(name, ": ")
        typingPrint("'Yes, Your Grace.'\n\n")

        time.sleep(1)

        print("The King :")
        typingPrint("'Then you must be very confused. I have seen a prophecy, and you at the center of it. I do \n ")
        typingPrint("not know what it means but I must get you out of here.'\n\n")
        break

    if answer == "n":

        time.sleep(1)

        print(name, ":")
        typingPrint("'I can't see a thing in here. Who are you?'\n\n")

        time.sleep(1)

        print("The King :")
        typingPrint("'I am the King, and I have seen a prophecy of great destruction to this land. I do not know \n")
        typingPrint(" why, but you are the only one who can stop it. I must get you out of here.'\n\n")
        break

    print("Invalid choice. Try again!")   # Will loop until you give a valid answer.

time.sleep(1)

typingPrint("The King unlocks your cell and walks in, closing the door behind him.\n\n")

time.sleep(1)

print("The King :")
typingPrint("'There is a much bigger picture. When you were falsely put in here, I could not interfere as the Lords \n")
typingPrint(" wouldn't get behind the foolery of a prophecy. I fear whoever arranged you to be put in here knows of \n")
typingPrint(" the prophecy and will be making sure you don't fulfill it.'\n\n")

time.sleep(1)

typingPrint("The King pushes in a block of stone and a secret tunnel behind the wall is revealed.\n\n")

time.sleep(1)

print("The King :")
typingPrint("'Follow this tunnel and it will lead you through the sewer system and outside of the city. \n")
typingPrint(" I was never here...'\n\n")

time.sleep(1)

typingPrint("How will you respond?\n")

time.sleep(1)

while True:
    answer = input("([Y] for correspondence | [N] for resistance): ").lower().strip()
    print()
    if answer == "y":

        time.sleep(1)

        print(name, ":")
        typingPrint("'Yes, Your Grace. I will not fail you.'\n\n")
        break

    if answer == "n":

        time.sleep(1)

        print(name, ":")
        typingPrint("'This is blasphemy. I will have no part in whatever charade this is. You look absolutely \n")
        typingPrint(" nothing like his Majesty. Leave at once!'\n\n")

        time.sleep(1)

        typingPrint("You spend the rest of your days rotting in your cell until an incredibly bright light \n")
        typingPrint("shreds across the sky, and everything around you bursts to flames.\n\n")

        time.sleep(1)

        typingPrint("You have died.")
        exit()
        break

    print("Invalid choice. Try again!")

time.sleep(3)

typingPrint("You are walking along the sewer path and you reach a crossroads.\n")

time.sleep(1)

while True:
    answer = input("([L] for left | [R] for right): ").lower().strip()
    print()
    if answer == "l":

        time.sleep(1)

        typingPrint("You encounter a monster. You have no weapon.\n")

        time.sleep(1)

        while True:
            answer = input("([A] for attack | [R] for run): ").lower().strip()
            print()
            if answer == "a":

                time.sleep(1)

                typingPrint("That wasn't a good idea.\n")

                time.sleep(1)

                typingPrint("You have died.")
                exit()
                break

            if answer == "r":

                time.sleep(1)

                typingPrint("You run past the monster, but now it is chasing you. It is gaining on you.\n")

                time.sleep(1)

                while True:
                    answer = input("([H] for hide | [P] for panic): ").lower().strip()
                    print()
                    if answer == "p":

                        time.sleep(1)

                        typingPrint("You panic and scream for help. The monster grabs you by the legs and pulls \n")
                        typingPrint("you back.\n")

                        time.sleep(1)

                        typingPrint("You have died.")
                        exit()
                        break

                    if answer == "h":

                        time.sleep(1)

                        typingPrint("You see a barrel ahead and decide to hide under it.\n")

                        time.sleep(1)

                        typingPrint("You successfully evaded the monster.\n\n")

                        time.sleep(1)

                        break

                    print("Invalid choice. Try again!")

                break

            print("Invalid choice. Try again!")

        typingPrint("You see a hole in the ground with a ladder going down, deeper into the network. \n\n")

        break

    if answer == "r":

        time.sleep(1)

        typingPrint("You are walking down the path and start to hear a clicking sound.\n")
        typingPrint("You turn around to see a massive arachnid.\n\n")

        time.sleep(1)

        typingPrint("What will you do?\n")

        while True:
            answer = input("([A] for attack | [R] for run): ").lower().strip()
            print()
            if answer == "a":

                time.sleep(1)

                typingPrint("You see a large broken piece of wood nearby on the ground and quickly impale the \n")
                typingPrint("creature in the center.\n")

                time.sleep(1)

                typingPrint("You have successfully killed the arachnid.\n\n")

                time.sleep(1)

                break

            if answer == "r":

                time.sleep(1)

                typingPrint("You attempt to flee from the arachnid but you feel a powerful web tangle you by \n")
                typingPrint("the legs and pull you back. You have become his meal.\n\n")

                time.sleep(1)

                typingPrint("You have died.")
                print()

                break

            print("Invalid choice. Try again!")

        typingPrint("You walk past the fallen beast and see a hole in the ground with a ladder going down, \n")
        typingPrint("deeper into the network.\n\n")

        break

    print("Invalid choice. Try again!")

time.sleep(3)

typingPrint("You continue down the path until you start to hear a faint groaning sound.\n")
typingPrint("A frail old man sits on a pipe. His hair and beard nearing his knees.\n\n")

time.sleep(1)

print("Man :")
typingPrint("'So, another seeks passage to his freedom, hmm?'\n\n")

time.sleep(1)

print(name, ":")
typingPrint("'Excuse me?'\n\n")

time.sleep(1)

print("Man :")
typingPrint("'Many before you have made mistakes to end up in the place you come from. \n")
typingPrint(" Many before you have grown tired of its conditions and found the passages \n")
typingPrint(" placed for their escape. All would end up lost in the network of tunnels if \n")
typingPrint(" it were not for me. I can guide you, but you must answer a riddle.'\n\n")

time.sleep(1)

typingPrint("Do you accept?\n")
while True:
    answer = input("([Y] for yes | [N] for no): ").lower().strip()
    print()
    if answer == "n":

        time.sleep(1)

        print(name, ":")
        typingPrint("'I am not a child and I do not have time for your games.'\n\n")

        time.sleep(1)

        typingPrint("You continue through the network but find the old fool was right.\n")
        typingPrint("No matter how much you retrace your steps, you can't find your way \n")
        typingPrint("back. You search for what seems like an eternity until the monster \n")
        typingPrint("you evaded before corners you for his revenge.\n\n")

        time.sleep(1)

        typingPrint("You have died.")
        exit()
        break

    if answer == "y":

        time.sleep(1)

        print(name, ":")
        typingPrint("'Alight, fine. I will play your silly game. What is the riddle?'\n\n")

        time.sleep(1)

        print("Man :")
        typingPrint("'Be careful! You get one chance or your corpse shall fill my belly. \n")
        typingPrint(" It has been so long since I've had a good meal! So here goes: \n\n")
        typingPrint(" What comes once in a minute, twice in a moment, but never in a \n")
        typingPrint(" thousand years?'\n\n")

        time.sleep(1)

        while True:
            answer = typingInput("What is your answer? ").lower()
            print()
            if answer == "m":
                break
            if answer == "letter m":
                break
            if answer == "the letter m":
                break
            typingPrint("'Wrong!'\n\n")

            time.sleep(1)

            typingPrint("The old man slashes your throat.\n")

            time.sleep(1)

            typingPrint("You have died.")
            sys.exit()

        time.sleep(1)

        print("Man :")
        typingPrint("'Correct! I will grant you safe passage to your freedom!'\n\n")
        break

    print("Invalid choice. Try again!")

    time.sleep(1)

typingPrint("The old man guides through what seems like a maze of tunnels until you reach \n")
typingPrint("the large mouth of a cave. You can see the light of day in the distance.\n\n")

time.sleep(1)

print("Man :")
typingPrint("'I'm afraid this is where I must leave you. Once you get out, you will be outside of the city. \n")
typingPrint(" Be warned, though. There is little to save you outside the walls.'\n\n")

time.sleep(1)

typingPrint("The man bows and walks back into the tunnels. You begin to walk towards the light until a \n")
typingPrint("deafening screeching sound bellows throughout the cave.\n\n")

time.sleep(3)

typingPrint("From the shadows, a dragon shows his head. His pure black scales contrasted his bright eyes, \n")
typingPrint("which looked as if they were made of fire.\n\n")

time.sleep(1)

print("Dragon :")
typingPrint("'I have seen your face, Protector. The only reason I don't burn you where you stand is because \n")
typingPrint(" I enjoy a good fight. We will meet again, I assure you.'\n\n")

time.sleep(1)

typingPrint("The dragon opens his mouth and shoots a massive blast of fire at the tunnel entrance behind you, \n")
typingPrint("sealing the passage. His magnificent wings stretch, and he takes off.\n\n")

typingPrint("By the time you reach the outside of the cave, he is but a speck in the sky.\n\n")

time.sleep(3)

typingPrint("The light beams down and nearly blinds you. It has been so long since you've seen the sun.\n")
typingPrint("A path lies before you, leading into the forest that outlines the city walls.\n")
typingPrint("Your journey starts now.\n\n")

# END OF INTRO


from ..commands import command_decorator
from ..hookspec import deltabot_hookimpl

@deltabot_hookimpl
def deltabot_init_parser(parser) -> None:
    parser.add_subcommand(DB)

def slash_scoped_key(key: str) -> tuple:
    i = key.find("/")
    if i == -1:
        raise ValueError("key {!r} does not contain a '/' scope delimiter")
    return (key[:i], key[i + 1 :])

class DB:
    """low level settings."""

    def add_arguments(self, parser) -> None:
        parser.add_argument(
            "-l", "--list", help="list all key,values.", metavar="SCOPE", nargs="?"
        )
        parser.add_argument(
            "-g",
            "--get",
            help="get a low level setting.",
            metavar="KEY",
            type=slash_scoped_key,
        )
        parser.add_argument(
            "-s",
            "--set",
            help="set a low level setting.",
            metavar=("KEY", "VALUE"),
            nargs=2,
        )
        parser.add_argument(
            "-d",
            "--del",
            help="delete a low level setting.",
            metavar="KEY",
            type=slash_scoped_key,
            dest="_del",
        )

    def run(self, bot, args, out) -> None:
        if args.get:
            self._get(bot, *args.get, out)
        elif args._del:
            self._del(bot, *args._del, out)
        elif args.set:
            self._set(bot, *args.set)
        else:
            self._list(bot, args.list, out)

    def _get(self, bot, scope, key, out) -> None:
        res = bot.get(key, scope=scope)
        if res is None:
            out.fail(f"key {scope}/{key} does not exist")
        else:
            out.line(res)

    def _set(self, bot, key, value) -> None:
        scope, key = slash_scoped_key(key)
        bot.set(key, value, scope=scope)

    def _list(self, bot, scope, out) -> None:
        for key, res in bot.list_settings(scope):
            if "\n" in res:
                out.line(f"{key}:")
                for line in res.split("\n"):
                    out.line("   " + line)
            else:
                out.line(f"{key}: {res}")

    def _del(self, bot, scope, key, out) -> None:
        res = bot.get(key, scope=scope)
        if res is None:
            out.fail(f"key {scope}/{key} does not exist")
        else:
            bot.delete(key, scope=scope)
            out.line(f"key {scope}/{key} deleted")

@command_decorator(name="/set")
def cmd_set(bot, payload, message, replies) -> None:
    """show all available settings or set a value for a setting.

    Examples:

    # show all settings
    /set

    # unset one setting named "mysetting"
    /set_mysetting

    # set one setting named "mysetting"
    /set_mysetting value
    """
    addr = message.get_sender_contact().addr
    if not payload:
        text = dump_settings(bot, scope=addr)
    else:
        args = payload.split(maxsplit=1)
        name = args[0]
        if bot.get_preference_description(name) is None:
            text = "Invalid setting. Available settings:"
            for name, desc in bot.get_preferences():
                text += f"\n\n/set_{name}: {desc}"
        else:
            value = None if len(args) == 1 else args[1]
            old = bot.set(name, value and value.strip(), scope=addr)
            text = f"old: {name}={old!r}\nnew: {name}={value!r}"
    replies.add(text=text)

def dump_settings(bot, scope) -> str:
    lines = []
    for name, desc in bot.get_preferences():
        value = bot.get(name, scope=scope)
        lines.append(f"/set_{name} = {value}\nDescription: {desc}\n")
    if not lines:
        return "no settings"
    return "\n".join(lines)

class TestCommandSettings:
    def test_mock_get_set_empty_settings(self, mocker):
        reply_msg = mocker.get_one_reply("/set")
        assert reply_msg.text.startswith("no settings")

    def test_mock_set_works(self, mocker):
        reply_msg = mocker.get_one_reply("/set hello world")
        assert "old" in reply_msg.text
        msg_reply = mocker.get_one_reply("/set")
        assert msg_reply.text == "hello=world"

    def test_get_set_functional(self, bot_tester):
        msg_reply = bot_tester.send_command("/set hello world")
        msg_reply = bot_tester.send_command("/set hello2 world2")
        msg_reply = bot_tester.send_command("/set")
        assert "hello=world" in msg_reply.text
        assert "hello2=world2" in msg_reply.text
        msg_reply = bot_tester.send_command("/set hello")
        assert "hello=None" in msg_reply.text


import os
import filecmp
import time

import pytest
import numpy as np

from damask import VTK
from damask import grid_filters

@pytest.fixture
def reference_dir(reference_dir_base):
    """Directory containing reference results."""
    return reference_dir_base/'VTK'

@pytest.fixture
def default():
    """Simple VTK."""
    grid = np.array([5,6,7],int)
    size = np.array([.6,1.,.5])
    return VTK.from_rectilinear_grid(grid,size)

class TestVTK:

    @pytest.fixture(autouse=True)
    def _execution_stamp(self, execution_stamp):
        print('patched damask.util.execution_stamp')

    def test_rectilinearGrid(self,tmp_path):
        grid   = np.random.randint(5,10,3)*2
        size   = np.random.random(3) + 1.0
        origin = np.random.random(3)
        v = VTK.from_rectilinear_grid(grid,size,origin)
        string = v.__repr__()
        v.save(tmp_path/'rectilinearGrid',False)
        vtr = VTK.load(tmp_path/'rectilinearGrid.vtr')
        with open(tmp_path/'rectilinearGrid.vtk','w') as f:
            f.write(string)
        vtk = VTK.load(tmp_path/'rectilinearGrid.vtk','VTK_rectilinearGrid')
        assert(string == vtr.__repr__() == vtk.__repr__())

    def test_polyData(self,tmp_path):
        points = np.random.rand(100,3)
        v = VTK.from_poly_data(points)
        string = v.__repr__()
        v.save(tmp_path/'polyData',False)
        vtp = VTK.load(tmp_path/'polyData.vtp')
        with open(tmp_path/'polyData.vtk','w') as f:
            f.write(string)
        vtk = VTK.load(tmp_path/'polyData.vtk','polyData')
        assert(string == vtp.__repr__() == vtk.__repr__())

    @pytest.mark.parametrize('cell_type,n',[
                                            ('VTK_hexahedron',8),
                                            ('TETRA',4),
                                            ('quad',4),
                                            ('VTK_TRIANGLE',3)
                                            ]
                            )
    def test_unstructuredGrid(self,tmp_path,cell_type,n):
        nodes = np.random.rand(n,3)
        connectivity = np.random.choice(np.arange(n),n,False).reshape(-1,n)
        v = VTK.from_unstructured_grid(nodes,connectivity,cell_type)
        string = v.__repr__()
        v.save(tmp_path/'unstructuredGrid',False)
        vtu = VTK.load(tmp_path/'unstructuredGrid.vtu')
        with open(tmp_path/'unstructuredGrid.vtk','w') as f:
            f.write(string)
        vtk = VTK.load(tmp_path/'unstructuredGrid.vtk','unstructuredgrid')
        assert(string == vtu.__repr__() == vtk.__repr__())

    def test_parallel_out(self,tmp_path):
        points = np.random.rand(102,3)
        v = VTK.from_poly_data(points)
        fname_s = tmp_path/'single.vtp'
        fname_p = tmp_path/'parallel.vtp'
        v.save(fname_s,False)
        v.save(fname_p,True)
        for i in range(10):
            if os.path.isfile(fname_p) and filecmp.cmp(fname_s,fname_p):
                assert(True)
                return
            time.sleep(.5)
        assert(False)

    @pytest.mark.parametrize('fname',['a','a.vtp','a.b','a.b.vtp'])
    def test_filename_variations(self,tmp_path,fname):
        points = np.random.rand(102,3)
        v = VTK.from_poly_data(points)
        v.save(tmp_path/fname)

    @pytest.mark.parametrize('name,dataset_type',[('this_file_does_not_exist.vtk', None),
                                                  ('this_file_does_not_exist.vtk','vtk'),
                                                  ('this_file_does_not_exist.vtx', None)])
    def test_invalid_dataset_type(self,name,dataset_type):
        with pytest.raises(TypeError):
            VTK.load(name,dataset_type)

    def test_add_extension(self,tmp_path,default):
        default.save(tmp_path/'default.txt',parallel=False)
        assert os.path.isfile(tmp_path/'default.txt.vtr')

    def test_invalid_get(self,default):
        with pytest.raises(ValueError):
            default.get('does_not_exist')

    def test_invalid_add_shape(self,default):
        with pytest.raises(ValueError):
            default.add(np.ones(3),'valid')

    def test_invalid_add_missing_label(self,default):
        data = np.random.randint(9,size=np.prod(np.array(default.vtk_data.GetDimensions())-1))
        with pytest.raises(ValueError):
            default.add(data)

    def test_invalid_add_type(self,default):
        with pytest.raises(TypeError):
            default.add('invalid_type','valid')

    def test_comments(self,tmp_path,default):
        default.add_comments(['this is a comment'])
        default.save(tmp_path/'with_comments',parallel=False)
        new = VTK.load(tmp_path/'with_comments.vtr')
        assert new.get_comments() == ['this is a comment']

    def test_compare_reference_polyData(self,update,reference_dir,tmp_path):
        points=np.dstack((np.linspace(0.,1.,10),np.linspace(0.,2.,10),np.linspace(-1.,1.,10))).squeeze()
        polyData = VTK.from_poly_data(points)
        polyData.add(points,'coordinates')
        if update:
             polyData.save(reference_dir/'polyData')
        else:
             reference = VTK.load(reference_dir/'polyData.vtp')
             assert polyData.__repr__() == reference.__repr__() and \
                    np.allclose(polyData.get('coordinates'),points)

    def test_compare_reference_rectilinearGrid(self,update,reference_dir,tmp_path):
        grid = np.array([5,6,7],int)
        size = np.array([.6,1.,.5])
        rectilinearGrid = VTK.from_rectilinear_grid(grid,size)
        c = grid_filters.cell_coord0(grid,size).reshape(-1,3,order='F')
        n = grid_filters.node_coord0(grid,size).reshape(-1,3,order='F')
        rectilinearGrid.add(c,'cell')
        rectilinearGrid.add(n,'node')
        if update:
             rectilinearGrid.save(reference_dir/'rectilinearGrid')
        else:
             reference = VTK.load(reference_dir/'rectilinearGrid.vtr')
             assert rectilinearGrid.__repr__() == reference.__repr__() and \
                    np.allclose(rectilinearGrid.get('cell'),c)


import argparse
import os
from logging import Logger
from pathlib import Path

from qcore import shared as qc_shared
from qcore import constants, qclogging, utils, simulation_structure, geo

from workflow.automation.lib import shared as wf_shared

def load_args():
    parser = argparse.ArgumentParser(allow_abbrev=False)
    parser.add_argument("cs_root", type=Path)
    parser.add_argument("fault")
    parser.add_argument("--log_dir", type=Path)
    args = parser.parse_args()
    return args

def main():
    args = load_args()

    fault_name = args.fault
    cybershake_root: Path = args.cs_root
    runs_dir = simulation_structure.get_runs_dir(cybershake_root)

    if args.log_dir is None:
        log_dir = Path(simulation_structure.get_sim_dir(cybershake_root, fault_name))
    else:
        log_dir: Path = args.log_dir

    logger = qclogging.get_logger(f"install_fault_{fault_name}")
    qclogging.add_general_file_handler(logger, log_dir / f"install_fault_{fault_name}")

    root_params_path = simulation_structure.get_root_yaml_path(runs_dir)
    root_params = utils.load_yaml(root_params_path)

    vm_params_path = simulation_structure.get_vm_params_yaml(
        simulation_structure.get_fault_VM_dir(cybershake_root, fault_name)
    )
    vm_params_dict = utils.load_yaml(vm_params_path)

    fd_statcords, fd_statlist = generate_fd_files(
        simulation_structure.get_fault_dir(cybershake_root, fault_name),
        vm_params_dict,
        stat_file=root_params[constants.RootParams.stat_file.value],
        logger=logger,
        keep_dup_station=root_params[constants.RootParams.keep_dup_station.value],
    )

    fault_params_dict = generate_fault_params(
        cybershake_root, fault_name, fd_statcords, fd_statlist
    )

    fault_params_path = simulation_structure.get_fault_yaml_path(runs_dir, fault_name)
    utils.dump_yaml(fault_params_dict, fault_params_path)

def generate_fault_params(cybershake_root, fault_name, fd_statcords, fd_statlist):
    runs_dir = simulation_structure.get_runs_dir(cybershake_root)
    root_params_yaml = simulation_structure.get_root_yaml_path(runs_dir)
    vel_mod_dir = simulation_structure.get_fault_VM_dir(cybershake_root, fault_name)
    fault_dir = Path(simulation_structure.get_fault_dir(cybershake_root, fault_name))
    fault_params_dict = {
        constants.FaultParams.root_yaml_path.value: root_params_yaml,
        constants.FaultParams.vel_mod_dir.value: vel_mod_dir,
        constants.FaultParams.stat_coords.value: str(fault_dir / fd_statcords),
        constants.FaultParams.FD_STATLIST.value: str(fault_dir / fd_statlist),
    }

    return fault_params_dict

def generate_fd_files(
    output_path,
    vm_params_dict,
    stat_file="default.ll",
    keep_dup_station=True,
    logger: Logger = qclogging.get_basic_logger(),
):
    MODEL_LAT = vm_params_dict["MODEL_LAT"]
    MODEL_LON = vm_params_dict["MODEL_LON"]
    MODEL_ROT = vm_params_dict["MODEL_ROT"]
    hh = vm_params_dict["hh"]
    nx = vm_params_dict["nx"]
    ny = vm_params_dict["ny"]
    sufx = vm_params_dict["sufx"]
    wf_shared.verify_strings([MODEL_LAT, MODEL_LON, MODEL_ROT, hh, nx, ny, sufx])

    filename = "fd{}".format(sufx)
    logger.info(stat_file)

    # arbitrary longlat station input
    ll_in = stat_file
    # where to save gridpoint and longlat station files
    gp_out = os.path.join(output_path, "{}.statcords".format(filename))
    ll_out = os.path.join(output_path, "{}.ll".format(filename))

    logger.info("From: {}. To: {}, {}".format(stat_file, gp_out, ll_out))

    # velocity model parameters
    nx = int(nx)
    ny = int(ny)
    mlat = float(MODEL_LAT)
    mlon = float(MODEL_LON)
    mrot = float(MODEL_ROT)
    hh = float(hh)

    # retrieve in station names, latitudes and longitudes
    sname, slat, slon = qc_shared.get_stations(ll_in, locations=True)
    slon = list(map(float, slon))
    slat = list(map(float, slat))

    # convert ll to grid points
    xy = geo.ll2gp_multi(
        list(map(list, zip(slon, slat))),
        mlon,
        mlat,
        mrot,
        nx,
        ny,
        hh,
        keep_outside=True,
    )

    # store gridpoints and names if unique position
    sxy = []
    suname = []
    for i in range(len(xy)):
        if xy[i] is None or xy[i][0] == nx - 1 or xy[i][1] == ny - 1:
            logger.log(
                qclogging.VERYVERBOSE, "Station outside domain: {}".format(sname[i])
            )
        elif xy[i] not in sxy:
            sxy.append(xy[i])
            suname.append(sname[i])
        elif keep_dup_station:
            # still adds in the station but raise a warning
            sxy.append(xy[i])
            suname.append(sname[i])
            logger.log(
                qclogging.NOPRINTWARNING,
                f"Duplicate Station added: {sname[i]} at {xy[i]}",
            )
        else:
            logger.log(
                qclogging.VERYVERBOSE, "Duplicate Station Ignored: {}".format(sname[i])
            )

    # create grid point file
    with open(gp_out, "w") as gpf:
        # file starts with number of entries
        gpf.write("%d\n" % (len(sxy)))
        # x, y, z, name
        for i, xy in enumerate(sxy):
            gpf.write("%5d %5d %5d %s\n" % (xy[0], xy[1], 1, suname[i]))

    # convert unique grid points back to ll
    # warning: modifies sxy
    ll = geo.gp2ll_multi(sxy, mlat, mlon, mrot, nx, ny, hh)

    # create ll file
    with open(ll_out, "w") as llf:
        # lon, lat, name
        for i, pos in enumerate(ll):
            llf.write("%11.5f %11.5f %s\n" % (pos[0], pos[1], suname[i]))

    return gp_out, ll_out

if __name__ == "__main__":
    main()


"""
Unit tests for fxpqeditor
"""

import unittest

from core.package_manager import PackageManager
from core.serializer import Serializer

class SerializerTests(unittest.TestCase):

    packages_dir = "./packages"

    @classmethod
    def setUpClass(cls):
        pm = PackageManager(cls.packages_dir)
        Serializer.package_manager = pm
        cls.Zone = pm.get_class("fxpq.roots", "Zone")
        cls.Dimension = pm.get_class("fxpq.roots", "Dimension")
        cls.Change = pm.get_class("fxpq.entities", "Change")
        cls.Author = pm.get_class("fxpq.entities", "Author")
        cls.Rectangle = pm.get_class("fxpq.entities", "Rectangle")

        cls.xmldimension = '<?xml version="1.0" encoding="UTF-8"?>\n'\
            '<!DOCTYPE fxpq>\n'\
            '<fxpq version="1.0">'\
            '<dimension cellsize="16" display_name="My Favorite Dimension">'\
            '<dimension.changelog><change version="0.1">We did some stuff, I think..</change>'\
            '<change breaking="True" version="0.2">We did some stuff, I think..</change>'\
            '<change version="0.3">We did some stuff, I think..</change>'\
            '</dimension.changelog><dimension.authors><author>Jean Rochefort</author>'\
            '<author>Jean Rochefort</author></dimension.authors><zone><zone.rectangles>'\
            '<rectangle h="1" w="1"/></zone.rectangles></zone></dimension></fxpq>'
        cls.maxDiff = None

    def test_serialize_dimension(self):
        obj = SerializerTests.Dimension()
        obj.display_name = "My Favorite Dimension"
        obj.cellsize = 16
        obj.changelog = list(SerializerTests._sample_changes(3))
        obj.authors = list(SerializerTests._sample_authors(2))
        obj.children = list(SerializerTests._sample_zones(1))

        self.assertEqual(Serializer.instance().serialize(obj), SerializerTests.xmldimension)

    def test_deserialize_dimension(self):
        dimension = Serializer.instance().deserialize(SerializerTests.xmldimension)

        self.assertEqual(dimension.display_name, "My Favorite Dimension")
        self.assertEqual(dimension.cellsize, 16)

        sample_changes = list(SerializerTests._sample_changes(3))
        sample_authors = list(SerializerTests._sample_authors(2))
        sample_zones = list(SerializerTests._sample_zones(1))

        self.assertListEqual(
            [c.children for c in dimension.changelog],
            [c.children for c in sample_changes])
        self.assertListEqual(
            [a.children for a in dimension.authors],
            [a.children for a in sample_authors])
        self.assertListEqual(
            [z.rectangles[0].w for z in dimension.children],
            [z.rectangles[0].w for z in sample_zones])

        for i, change in enumerate(dimension.changelog):
            self.assertListEqual(
                [p.value(change) for p in change.properties.values()],
                [p.value(sample_changes[i]) for p in sample_changes[i].properties.values()])

        for i, author in enumerate(dimension.authors):
            self.assertListEqual(
                [p.value(author) for p in author.properties.values()],
                [p.value(sample_authors[i]) for p in sample_authors[i].properties.values()])

    def test_raises_if_no_package_manager(self):
        pm = Serializer.package_manager
        Serializer.package_manager = None

        with self.assertRaises(AssertionError):
            Serializer.instance()

        Serializer.package_manager = pm

    @classmethod
    def _sample_changes(cls, amount):
        for i in range(1, amount + 1):
            change = cls.Change()
            change.version = "0.{}".format(i)
            change.children = "We did some stuff, I think.."
            change.breaking = (i % 2 == 0)
            yield change

    @classmethod
    def _sample_authors(cls, amount):
        for i in range(1, amount + 1):
            author = cls.Author()
            author.children = "Jean Rochefort"
            yield author

    @classmethod
    def _sample_zones(cls, amount):
        for i in range(1, amount + 1):
            zone = cls.Zone()
            rect = cls.Rectangle()
            rect.w, rect.h = 1, 1
            zone.rectangles = [rect]
            yield zone


#Importando la libreria de tkinter:

from tkinter import *

#Creando la ventana principal
ventana = Tk()

#Se crea el frame o panel para visualizar contenido:
frame= Frame(ventana,width=500,height=500)

#Es muy importante empaquetar el Frame:
frame.pack()

#Un label puede contener muchos atributos, tambien se puede mostrar imagenes en el
texto1= Label(frame,text="Hola este es un label",bg="blue", fg="white", font=("Comic Sans MS",18))
texto1.place(x=100,y=200)

#Si no vas a usar mas adelante el label tambien puedes ovbiar la escritura anterior de la siguiente manera:

Label(frame,text="Hola2",bg="Red", fg="white").place(x=50,y=50)

#Tambien si lo deceas puedes agregar imagenes en formato gif y png de la siguiente manera:

imagen= PhotoImage(file="iconos/python.png")

Label(frame, image=imagen).place(x=200,y=250)

#Ejecutando el bucle que permite mostrar la ventana
ventana.mainloop()


import os
import config.settings
def get_image_path(self,filename):
    prefix='media/profile_picture'
    name=str(uuid.uuid4()).replace('-','')
    extension=os.path.splitext(filename)[-1]
    return prefix+name+extension
def delete_previous_file(function):
    def wrapper(*args,**kwargs):
        self=args[0]
        result=Image.objects.filter(pk=self.pk)
        previous=result[0] if len(result) else None
        super(Image,self).save()
        result=function(*args,**kwargs)
        if previous:
            os.remove(MEDIA_ROOT+'/')
        return wrapper


from django.db.utils import IntegrityError

import pytest

from teams.models import TeamMember

def test_create(team_factory, user_factory):
    """
    Test creating a team member.
    """
    TeamMember.objects.create(
        is_admin=True,
        member_type=TeamMember.PLAYER,
        team=team_factory(),
        user=user_factory())

def test_unique_team_and_user(team_member_factory):
    """
    Team members should be unique with respect to user and team.

    Regression test for #14
    """
    member = team_member_factory()

    with pytest.raises(IntegrityError):
        team_member_factory(team=member.team, user=member.user)


import minimalmodbus

minimalmodbus.TIMEOUT = 0.5

class RD6006:
    def __init__(self, port, address=1, baudrate=115200):
        self.port = port
        self.address = address
        self.instrument = minimalmodbus.Instrument(port=port, slaveaddress=address)
        self.instrument.serial.baudrate = baudrate
        regs = self._read_registers(0, 4)
        self.sn = regs[1] << 16 | regs[2]
        self.fw = regs[3] / 100
        self.type = int(regs[0] / 10)

        if self.type == 6012 or self.type == 6018 or self.type == 6024:
            print("RD6012, RD6018 or RD6024 detected")
            self.voltres = 100
            self.ampres = 100
        else:
            print("RD6006 or other detected")
            self.voltres = 100
            self.ampres = 1000

    def __repr__(self):
        return f"RD6006 SN:{self.sn} FW:{self.fw}"

    def _read_register(self, register):
        try:
            return self.instrument.read_register(register)
        except minimalmodbus.NoResponseError:
            return self._read_register(register)

    def _read_registers(self, start, length):
        try:
            return self.instrument.read_registers(start, length)
        except minimalmodbus.NoResponseError:
            return self._read_registers(start, length)
        except minimalmodbus.InvalidResponseError:
            return self._read_registers(start, length)

    def _write_register(self, register, value):
        try:
            return self.instrument.write_register(register, value)
        except minimalmodbus.NoResponseError:
            return self._write_register(register, value)

    def _mem(self, M=0):
        """reads the 4 register of a Memory[0-9] and print on a single line"""
        regs = self._read_registers(M * 4 + 80, 4)
        print(
            f"M{M}: {regs[0] / self.voltres:4.1f}V, {regs[1] / self.ampres:3.3f}A, OVP:{regs[2] / self.voltres:4.1f}V, OCP:{regs[3] / self.ampres:3.3f}A"
        )

    def status(self):
        regs = self._read_registers(0, 84)
        print("== Device")
        print(f"Model   : {regs[0]/10}")
        print(f"SN      : {(regs[1]<<16 | regs[2]):08d}")
        print(f"Firmware: {regs[3]/100}")
        print(f"Input   : {regs[14] / self.voltres}V")
        if regs[4]:
            sign = -1
        else:
            sign = +1
        print(f"Temp    : {sign * regs[5]}°C")
        if regs[34]:
            sign = -1
        else:
            sign = +1
        print(f"TempProb: {sign * regs[35]}°C")
        print("== Output")
        print(f"Voltage : {regs[10] / self.voltres}V")
        print(f"Current : {regs[11] / self.ampres}A")
        print(f"Energy  : {regs[12]/1000}Ah")
        print(f"Power   : {regs[13]/100}W")
        print("== Settings")
        print(f"Voltage : {regs[8] / self.voltres}V")
        print(f"Current : {regs[9] / self.ampres}A")
        print("== Protection")
        print(f"Voltage : {regs[82] / self.voltres}V")
        print(f"Current : {regs[83] / self.ampres}A")
        print("== Battery")
        if regs[32]:
            print("Active")
            print(f"Voltage : {regs[33] / self.voltres}V")
        print(
            f"Capacity: {(regs[38] <<16 | regs[39])/1000}Ah"
        )  # TODO check 8 or 16 bits?
        print(
            f"Energy  : {(regs[40] <<16 | regs[41])/1000}Wh"
        )  # TODO check 8 or 16 bits?
        print("== Memories")
        for m in range(10):
            self._mem(M=m)

    @property
    def input_voltage(self):
        return self._read_register(14) / self.voltres

    @property
    def voltage(self):
        return self._read_register(8) / self.voltres

    @property
    def meastemp_internal(self):
        if self._read_register(4):
            return -1 * self._read_register(5)
        else:
            return 1 * self._read_register(5)

    @property
    def meastempf_internal(self):
        if self._read_register(6):
            return -1 * self._read_register(7)
        else:
            return 1 * self._read_register(7)

    @property
    def meastemp_external(self):
        if self._read_register(34):
            return -1 * self._read_register(35)
        else:
            return 1 * self._read_register(35)

    @property
    def meastempf_external(self):
        if self._read_register(36):
            return -1 * self._read_register(37)
        else:
            return 1 * self._read_register(37)

    @voltage.setter
    def voltage(self, value):
        self._write_register(8, int(value * self.voltres))

    @property
    def measvoltage(self):
        return self._read_register(10) / self.voltres

    @property
    def meascurrent(self):
        return self._read_register(11) / self.ampres

    @property
    def measpower(self):
        return (
            self._read_register(12) << 16 | self._read_register(13)
        ) / 100

    @property
    def measah(self):
        return (
            self._read_register(38) << 16 | self._read_register(39)
        ) / 1000  # TODO check 16 or 8 bit

    @property
    def measwh(self):
        return (
            self._read_register(40) << 16 | self._read_register(41)
        ) / 1000  # TODO check 16 or 8 bit

    @property
    def battmode(self):
        return self._read_register(32)

    @property
    def battvoltage(self):
        return self._read_register(33)

    @property
    def current(self):
        return self._read_register(9) / self.ampres

    @current.setter
    def current(self, value):
        self._write_register(9, int(value * self.ampres))

    @property
    def voltage_protection(self):
        return self._read_register(82) / self.voltres

    @voltage_protection.setter
    def voltage_protection(self, value):
        self._write_register(82, int(value * self.voltres))

    @property
    def current_protection(self):
        return self._read_register(83) / self.ampres

    @current_protection.setter
    def current_protection(self, value):
        self._write_register(83, int(value * self.ampres))

    @property
    def enable(self):
        return self._read_register(18)

    @enable.setter
    def enable(self, value):
        self._write_register(18, int(value))

    @property
    def ocpovp(self):
        return self._read_register(16)

    @property
    def CVCC(self):
        return self._read_register(17)

    @property
    def backlight(self):
        return self._read_register(72)

    @backlight.setter
    def backlight(self, value):
        self._write_register(72, value)

    @property
    def date(self):
        """returns the date as tuple: (year, month, day)"""
        regs = self._read_registers(48, 3)
        year = regs[0]
        month = regs[1]
        day = regs[2]
        return (year, month, day)

    @date.setter
    def date(self, value):
        """Sets the date, needs tuple with (year, month, day) as argument"""
        year, month, day = value
        self._write_register(48, year)
        self._write_register(49, month)
        self._write_register(50, day)

    @property
    def time(self):
        """returns the time as tuple: (h, m, s)"""
        regs = self._read_registers(51, 3)
        h = regs[0]
        m = regs[1]
        s = regs[2]
        return (h, m, s)

    @time.setter
    def time(self, value):
        """sets the time, needs time with (h, m, s) as argument"""
        h, m, s = value
        self._write_register(51, h)
        self._write_register(52, m)
        self._write_register(53, s)

    @property
    def read_timeout(self):
        return self.instrument.serial.timeout

    @read_timeout.setter
    def read_timeout(self, value):
        self.instrument.serial.timeout = value

    @property
    def write_timeout(self):
        return self.instrument.serial.write_timeout

    @write_timeout.setter
    def write_timeout(self, value):
        self.instrument.serial.write_timeout = value

if __name__ == "__main__":
    import serial.tools.list_ports

    ports = list(serial.tools.list_ports.comports())
    for p in ports:
        if "VID:PID=1A86:7523" in p[2]:
            print(p)
            r = RD6006(p[0])
            break
    else:
        raise Exception("Port not found")
    r.status()


"""
Entry script for SageMaker training
"""

import argparse
import os

import torch

from dataloader import creat_dataloader
from net import Generator, Discriminator
from train import train
from training_default_config import load_config

def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser()

    parser.add_argument(
        '--train_cfg_filename',
        type=str,
        required=True,
        help='Training config filename')

    parser.add_argument(
        '--config_dir',
        type=str,
        help='Directory for config files',
        default=os.environ.get('SM_CHANNEL_CONFIG'))

    parser.add_argument(
        '--train_data',
        type=str,
        help='Directory for training images',
        default=os.environ.get('SM_CHANNEL_TRAINDATA')
    )

    parser.add_argument(
        "--output_dir",
        type=str,
        required=True,
        help="Directory where model checkpoints, logs and other artefacts are saved."
             "This directory will be synced with s3://SAGEMAKER_RESULTS_BUCKET/EXPERIMENT_NAME/CHECKPOINT_DIR on S3.")
    return parser.parse_args()

def populate_data_dir(dataloader_cfg, data_dir):
    dataloader_cfg.defrost()
    dataloader_cfg.DATA_DIR = data_dir
    dataloader_cfg.freeze()
    return dataloader_cfg

def main():
    args = parse_args()
    cfg = load_config(os.path.join(args.config_dir, args.train_cfg_filename))

    dataloader_cfg = cfg.DATALOADER
    dataloader_cfg = populate_data_dir(dataloader_cfg, args.train_data)
    generator_cfg = cfg.GENERATOR
    discriminator_cfg = cfg.DISCRIMINATOR
    training_cfg = cfg.TRAINING

    dataloader = creat_dataloader(dataloader_cfg)
    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    generator_network = Generator(generator_cfg, device)
    discriminator_network = Discriminator(discriminator_cfg, device)

    train(training_cfg, generator_cfg, dataloader, generator_network, discriminator_network, device)

if __name__ == "__main__":
    main()