import sys
import pymorphy2
from datetime import datetime
from PyQt5.QtCore import QUrl
from PyQt5 import QtWidgets, QtCore
from PyQt5.QtGui import QFont, QPalette, QBrush, QPixmap, QIntValidator
from PyQt5.QtWidgets import QMainWindow, QLabel, QGridLayout,  QLineEdit, QMessageBox
from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEnginePage
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtCore import QSize
from pyqt5_plugins.examplebuttonplugin import QtGui
import pyqtgraph as pg
import fon_rc
from map import Map
from database import DbAdvanced

class Example(QMainWindow):
    def __init__(self, *args, **kwargs):
        super(Example, self).__init__(*args, **kwargs)

        self.setMinimumSize(QSize(1900, 1000))
        self.setWindowTitle("MarkingHack")
        self.setGeometry(0, 0, 1900, 1000)

        self.layout = QGridLayout()

        self.browser = QWebEngineView()
        self.browser.setGeometry(0, 0, 1300, 810)
        self.browser.setUrl(QUrl("https://hack.markirovka.ru/task2"))
        self.setCentralWidget(self.browser)

        self.layout.addWidget(self.browser)

        self.graphWidget = pg.PlotWidget()
        hour = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        temperature = [30, 32, 34, 32, 33, 31, 29, 32, 35, 45]
        self.graphWidget.plot(hour, temperature)
        self.graphWidget.setGeometry(1310, 0, 610, 400)
        self.graphWidget.setBackground('y')
        self.setCentralWidget(self.graphWidget)

        self.layout.addWidget(self.graphWidget)

        self.graphWidget2 = pg.PlotWidget()
        hour = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        temperature = [30, 32, 34, 32, 33, 31, 29, 32, 35, 45]
        self.graphWidget2.plot(hour, temperature)
        self.graphWidget2.setGeometry(1310, 410, 610, 400)
        self.graphWidget2.setBackground('y')
        self.setCentralWidget(self.graphWidget2)

        self.layout.addWidget(self.graphWidget2)

        self.setLayout(self.layout)

        self.textbox1 = QLineEdit(self)
        self.textbox1.move(220, 820)
        self.textbox1.resize(340, 50)
        self.textbox1.setFont(QFont('San Francisco', 10))
        self.textbox1.setStyleSheet("""QLineEdit {
                                                color: rgb(80,85,88);
                                                background-color: yellow;
                                                border-radius: 10px;} """)

        self.label1 = QLabel('Все города', self)
        self.label1.setGeometry(1500, 880, 300, 50)
        self.label1.setFont(QFont('San Francisco', 12))
        self.label1.setStyleSheet(styletext)

        self.label2 = QLabel('GTIN', self)
        self.label2.setGeometry(40, 820, 300, 50)
        self.label2.setFont(QFont('San Francisco', 12))
        self.label2.setStyleSheet(styletext)

        self.label3 = QLabel('Построить графики', self)
        self.label3.setGeometry(1500, 820, 300, 50)
        self.label3.setFont(QFont('San Francisco', 12))
        self.label3.setStyleSheet(styletext)

        self.label4 = QLabel('Карта ввода товара', self)
        self.label4.setGeometry(40, 880, 300, 50)
        self.label4.setFont(QFont('San Francisco', 12))
        self.label4.setStyleSheet(styletext)

        self.label5 = QLabel('Карта вывода товара', self)
        self.label5.setGeometry(40, 940, 300, 50)
        self.label5.setFont(QFont('San Francisco', 12))
        self.label5.setStyleSheet(styletext)

        self.label6 = QLabel('Создать БД из CSV', self)
        self.label6.setGeometry(1500, 940, 300, 50)
        self.label6.setFont(QFont('San Francisco', 12))
        self.label6.setStyleSheet(styletext)

        self.label7 = QLabel('Маршрутная карта', self)
        self.label7.setGeometry(800, 820, 300, 50)
        self.label7.setFont(QFont('San Francisco', 12))
        self.label7.setStyleSheet(styletext)

        self.label8 = QLabel('Предиктивная модель', self)
        self.label8.setGeometry(800, 880, 300, 50)
        self.label8.setFont(QFont('San Francisco', 12))
        self.label8.setStyleSheet(styletext)

        self.bt1 = QPushButton("Выполнить", self)
        self.bt1.move(1740, 820)
        self.bt1.setFont(QFont('Arial', 12))
        self.bt1.setFixedSize(140, 50)
        self.bt1.setObjectName("pushButton")

        self.bt1.setStyleSheet(stylesheet)
        self.bt1.clicked.connect(self.Button1)

        self.bt2 = QPushButton("Отобразить", self)
        self.bt2.move(1740, 880)
        self.bt2.setFont(QFont('Arial', 12))
        self.bt2.setFixedSize(140, 50)
        self.bt2.setObjectName("pushButton")
        self.bt2.setStyleSheet(stylesheet)
        self.bt2.clicked.connect(self.Button2)

        self.bt3 = QPushButton("Отобразить", self)
        self.bt3.move(270, 880)
        self.bt3.setFont(QFont('Arial', 12))
        self.bt3.setFixedSize(140, 50)
        self.bt3.setObjectName("pushButton")
        self.bt3.setStyleSheet(stylesheet)
        self.bt3.clicked.connect(self.Button3)

        self.bt4 = QPushButton("Отобразить", self)
        self.bt4.move(270, 940)
        self.bt4.setFont(QFont('Arial', 12))
        self.bt4.setFixedSize(140, 50)
        self.bt4.setObjectName("pushButton")
        self.bt4.setStyleSheet(stylesheet)
        self.bt4.clicked.connect(self.Button4)

        self.bt5 = QPushButton("Карта\nввода/вывода\nтовара", self)
        self.bt5.move(420, 880)
        self.bt5.setFont(QFont('Arial', 12))
        self.bt5.setFixedSize(140, 110)
        self.bt5.setObjectName("pushButton")
        self.bt5.setStyleSheet(stylesheet)
        self.bt5.clicked.connect(self.Button5)

        self.bt6 = QPushButton("Выполнить", self)
        self.bt6.move(1740, 940)
        self.bt6.setFont(QFont('Arial', 12))
        self.bt6.setFixedSize(140, 50)
        self.bt6.setObjectName("pushButton")
        self.bt6.setStyleSheet(stylesheet)
        self.bt6.clicked.connect(self.Button6)

        self.bt7 = QPushButton("Отобразить", self)
        self.bt7.move(1150, 820)
        self.bt7.setFont(QFont('Arial', 12))
        self.bt7.setFixedSize(140, 50)
        self.bt7.setObjectName("pushButton")
        self.bt7.setStyleSheet(stylesheet)
        self.bt7.clicked.connect(self.Button7)

        self.bt8 = QPushButton("Отобразить", self)
        self.bt8.move(1150, 880)
        self.bt8.setFont(QFont('Arial', 12))
        self.bt8.setFixedSize(140, 50)
        self.bt8.setObjectName("pushButton")
        self.bt8.setStyleSheet(stylesheet)
        self.bt8.clicked.connect(self.Button8)

        self.showMaximized()

        self.database = DbAdvanced()

    def Button1(self):
        self.graphWidget.clear()
        vvod_data = self.database.create_plot_vvod(self.textbox1.text())
        vivod_data = self.database.create_plot_vivod(self.textbox1.text())
        vvod_mas = []
        vivod_mas = []

        for key, value in vvod_data.items():
            if key in vivod_data:
                vvod_mas.append(value)
                vivod_mas.append(vivod_data[key])

        self.graphWidget.plot(range(len(vvod_mas)), vvod_mas, pen=pg.mkPen(color=(255, 0, 0)))
        self.graphWidget.plot(range(len(vivod_mas)), vivod_mas, pen=pg.mkPen(color=(0, 0, 255)))
        self.graphWidget.setTitle("Ввод/вывод товаров ")
        styles = {'color': 'r', 'font-size': '20px'}
        self.graphWidget.setLabel('left', 'Количество', **styles)
        self.graphWidget.setLabel('bottom', 'Дата', **styles)
        self.graphWidget.showGrid(x=True, y=True)
        self.graphWidget.addLegend()

    def Button2(self):
        self.new_map = Map()
        self.new_map.add_points()
        url = QtCore.QUrl.fromLocalFile(r"C:\Users\Chubu\PycharmProjects\MarkingHack\marking_hack.html")
        self.browser.load(url)

    def Button3(self):
        self.gtin_new_map = Map()
        self.gtin_new_map.add_gtin_points(self.textbox1.text())
        url = QtCore.QUrl.fromLocalFile(r"C:\Users\Chubu\PycharmProjects\MarkingHack\gtin_marking_hack.html")
        self.browser.load(url)

    def Button4(self):
        self.gtin_new_map_vivod = Map()
        self.gtin_new_map_vivod.add_gtin_points_vivod(self.textbox1.text())
        url = QtCore.QUrl.fromLocalFile(r"C:\Users\Chubu\PycharmProjects\MarkingHack\gtin_marking_hack_vivod.html")
        self.browser.load(url)

    def Button5(self):
        self.gtin_new_map_total = Map()
        self.gtin_new_map_total.add_gtin_points_total(self.textbox1.text())
        url = QtCore.QUrl.fromLocalFile(r"C:\Users\Chubu\PycharmProjects\MarkingHack\marking_hack_total.html")
        self.browser.load(url)

    def Button6(self):
        self.new_db = DbAdvanced()
        self.new_db.insert_into_db()

    def Button7(self):
        self.route_map = Map()
        self.route_map.routes(self.textbox1.text())
        url = QtCore.QUrl.fromLocalFile(r"C:\Users\Chubu\PycharmProjects\MarkingHack\marking_hack_route.html")
        self.browser.load(url)

    def Button8(self):
        self.graphWidget2.clear()
        self.prediction_db = DbAdvanced()
        self.prediction_db.prediction(self.textbox1.text())

        self.graphWidget2.plot(range(len(self.prediction_db.current1)), self.prediction_db.current2, pen=pg.mkPen(color=(255, 0, 0)))
        self.graphWidget2.plot(range(len(self.prediction_db.current1), (len(self.prediction_db.current1)+len(self.prediction_db.predicted1))), self.prediction_db.predicted2, pen=pg.mkPen(color=(0, 0, 255)))
        self.graphWidget2.setTitle(('Продажи продукта "{}"'.format(self.textbox1.text())))
        styles = {'color': 'r', 'font-size': '20px'}
        self.graphWidget2.setLabel('left', 'Количество', **styles)
        self.graphWidget2.setLabel('bottom', 'Дата', **styles)
        self.graphWidget2.showGrid(x=True, y=True)
        self.graphWidget2.addLegend()

styletext = ("""QLabel {color: rgb(80,85,88)}""")

stylesheet = ("""QPushButton#pushButton {
                                    color: rgb(80,85,88);
                                    border-style: outset;
                                    border-radius: 10px;
                                    font: bold 16px;
                                    padding: 6px;
                                    border-bottom-width: 4px;
                                    border-right-width: 4px;
                                    border-color: rgb(217, 217, 20) ;
                                    background-color: yellow;
                                    }
                                    QPushButton#pushButton:pressed {
                                    border-top-width: 4px;
                                    border-left-width: 4px;
                                    border-bottom-width: 0px;
                                    border-right-width: 0px;
                                    background-color: yellow;
                                    border-style: inset;}""")

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    mainWin = Example()
    mainWin.setStyleSheet("""Example {
                              background-image: url(:/main_window/Fon.png);
                              background-repeat: no-repeat;
                              background-position: center;

    }""")
    mainWin.show()
    sys.exit(app.exec_())


numero=int(input('ingresa un numero entero: '))
print('has ingresado el',numero)
numero+=1
print('y el numero siguiente es: ', numero)

# 1. Solicitamos el número al usuario.
# NOTA: Recuerda que hay que convertir la entrada
# por teclado a entero.
num = int(input('Introduce un número > '))
# 2. Calculamos el número siguiente y lo
# mostramos por pantalla
num = num + 1
print('Siguiente: ', num)
# ---- Una alternativa al código anterior
num = int(input('Introduce un número > '))
num += 1
print('Siguiente: ', num)


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

# In[12]:
import cv2
def grayscale(input,output):
    #gray the photos
    image = cv2.imread(input)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    cv2.imwrite(output, gray)
    return
'''
input="/Users/YiHung/Downloads/0002_com.png"
output="/Users/YiHung/Downloads/後來灰階.png"
grayscale(input,output)
'''


from bs4 import BeautifulSoup
import requests

class ReadRSS:
    '''Class for reading RSS Feeds only takes
    one argument. The URL of a feed'''
    def __init__(self, url) -> None:
        '''Initializes class returns None'''
        self.url = url
        self.page = requests.get(url)
        self.soup = BeautifulSoup(self.page.content, "html5lib",
                                  from_encoding="utf-8")

    def getTitles(self):
        '''Prints all the titles from the given rss url
        and returns that title'''
        temp = []
        titles = self.soup.find_all("title")
        for i in range(2, len(titles)):
            temp.append(titles[i].text)
        self.page.close()
        return temp

    def getContent(self, t):
        '''Takes the title (t) of an article and prints the aritcles
        content to the screen.'''
        title = self.soup.find(string=t)
        parent = title.findParent("title").findParent("item")
        self.page.close()
        return parent.prettify()


from Ch11_12.Py704 import BuildGraph
from basis.Queue import Queue

def bfs(g,start):
    # 广度优先算法，搜索所有从起始顶点start可到达的边，在搜索更远距离k+1的顶点之前，会搜索完全部距离为k的顶点
    # 算法复杂度为O（v+e）v为顶点数量，e为边的数量
    start.setDistance(0)
    start.setPred=None
    vertQueue=Queue()
    vertQueue.enqueue(start)
    while (vertQueue.size()>0):
        # 取队首为当前顶点
        currentVert=vertQueue.dequeue()
        # 边最多检查一次
        for nbr in currentVert.getConnections():
            # Color 白色：顶点尚未发现，灰色：已经发现，黑色：完成探索
            if (nbr.getColor()=="white"):
                nbr.setColor("gray")
                # 当前节点到起始顶点的距离
                nbr.setDistance(currentVert.getDistance()+1)
                nbr.setPred(currentVert)
                # 将发现的顶点加入到队列中
                vertQueue.enqueue(nbr)
        # 遍历完后，将当前顶点标记为黑色，标志完成探索
        currentVert.setColor("black")

def traverse(y):
    # 通过回溯函数，得到从开始顶点start到任何单词的最短词梯
    # getPred()获取前驱顶点
    x=y
    while (x.getPred()):
        print(x.getId())
        x=x.getPred()
    print(x.getId())

filePath="C:\\Users\\zwk\\PycharmProjects\\DataStructureAndAgrithom\\fourletterwords.txt"
wordGraph=BuildGraph(filePath)

bfs(wordGraph,wordGraph.getVertex("FOOL"))

traverse(wordGraph.getVertex("SAGE"))

print(wordGraph.getVertex("SAGE").getDistance())

# import sys
# print(sys.maxsize+3)


import os
import numpy as np
import matplotlib.pyplot as mp
from mpl_toolkits.mplot3d import axes3d

colors = ('r', 'g', 'b', 'k')

data_list = []
with open('celiang.txt','r') as f:
    data_list = [i.strip().split(' ') for i in f.readlines()]

x = [-250,0,250]

data_x = [float(i[0]) for i in data_list]
data_y = [float(i[1]) for i in data_list]
data_z = [float(i[2]) for i in data_list]

mp.figure("3D scatter", facecolor="lightgray")
ax3d = mp.gca(projection="3d")  # 创建三维坐标

ax3d.set_xlabel('x', fontsize=14)
ax3d.set_ylabel('y', fontsize=14)
ax3d.set_zlabel('z', fontsize=14)

ax3d.scatter(data_x, data_y, data_z, s=20, cmap="jet", marker="o")

mp.show()


#-*- coding:utf-8 -*-
#----------------------------------------------------------------
#
# red/black/white epd with image support, based on frameBuffer
#
# by dotnfc, 2023/09/26
#

import sys
from efont import *
import machine
import time
import ufont
if sys.platform == 'linux':
    from panel.epd_sdl_102rbw import *
else:
    from panel.epd_102a013c import *

# color definitions for Monochrome EPD, values correspond to RGB565 values for TFTs
EPD_BLACK     = const(0x0000)
EPD_WHITE     = const(0xFFFF)

# values for 3-color
EPD_RED       = const(0xF800) # 255,   0,   0
EPD_YELLOW    = const(0xFFE0) # 255, 255,   0 !!no longer same as GxEPD_RED!!
EPD_COLORED   = EPD_RED

class EpdImage(EPD):

    def __init__(self):
        EPD.__init__(self)
        self.image = Image(self.WIDTH, self.HEIGHT)
        self.fb = self      # default fb object is black and white buffer

        self.fonts = {}     # fonts loaded
        self.font = None    # font object currently selected

        self.foreColor = EPD_BLACK
        self.backColor = EPD_WHITE

    def clear(self, bw = EPD_WHITE, rw = EPD_WHITE):
        if bw == EPD_WHITE:
            self.fill(RBW_WHITE)
        else:
            self.fill(RBW_BLACK)

        if rw == EPD_WHITE:
            self.fb_rw.fill(RRW_WHITE)
        else:
            self.fb_rw.fill(RRW_RED)

    def drawImage(self, x, y, filename):
        '''Draw image file at (x, y).'''
        self.image.setColor(self.foreColor, self.backColor)
        self.image.load(filename, True)
        self.image.draw(self.fb, x, y)

    def deepSleep(self, microseconds):
        '''deep sleep for microseconds.'''
        if sys.platform == "linux":
            print("sys deepsleep")
            while(not self.eventProcess()):
                time.sleep(0.01)
        else:
            machine.deepsleep(microseconds)

    def setColor(self, foreColor, backColor):
        '''Set image/font drawing color, and select internal working Frame Buffer.

        Args:
            foreColor: foreground color
            backColor: background color
        '''

        if foreColor == EPD_RED or backColor == EPD_RED:
            self.fb = self.fb_rw    # red & white buffer

            # map to panel color
            if foreColor == EPD_RED:
                self.foreColor = RRW_RED
                self.backColor = RRW_WHITE
            else:
                self.foreColor = RRW_WHITE
                self.backColor = RRW_RED
        else:
            self.fb = self          # black & white buffer

            # map to panel color
            if foreColor == EPD_BLACK:
                self.foreColor = RBW_BLACK
                self.backColor = RBW_WHITE
            else:
                self.foreColor = RBW_WHITE
                self.backColor = RBW_BLACK

        if self.font != None:
            self.font.setRender(self.fb)    # update current font render
            self.font.setColor(self.foreColor, self.backColor)

    def loadFont(self, fonName, size=16):
        '''Load font file from storage.

        Args:
            fonName: Font name from font registry
        '''

        if fonName in self.fonts:
            fon = self.fonts[f'{fonName}']
            fon.setSize(size)
            return fon  # font loaded before

        fon = FT2(ufont.fonts[f'{fonName}'], render=self.fb, mono=True, size=size)
        self.fonts[f'{fonName}'] = fon
        return fon

    def selectFont(self, fonName):
        '''Select current font.

        Args:
            fonName: Font name to select, which should be in the 'font registry'

        Return:
            True if the font selected, False otherwise
        '''
        if fonName in self.fonts:
            self.font = self.fonts[f'{fonName}']
            self.font.setRender(self.fb)    # update current font render
            self.font.setColor(self.foreColor, self.backColor)
            return True

        return False

    def drawText(self, x, y, w, h, align, text, size=-1):
        if self.font == None:
            raise RuntimeError("Font not selected")

        if size != -1:
            return self.font.drawString(x, y, w, h, align, text, size)
        else:
            return self.font.drawString(x, y, w, h, align, text)

    def text_3c(self, s, x, y, c=1):
        '''
        Write text to the FrameBuffer using the the coordinates as the upper-left corner of the text.

        The color of the text can be defined by the optional argument but is otherwise a default value of 1.

        All characters have dimensions of 8x8 pixels and there is currently no way to change the font.
        '''
        self.fb.text(s, x, y, c)

    def line_3c(self, x1, y1, x2, y2, c):
        '''
        Draw a line from a set of coordinates using the given color and a thickness of 1 pixel.

        The line method draws the line up to a second set of coordinates whereas the hline and vline methods
        draw horizontal and vertical lines respectively up to a given length.
        '''
        self.fb.line(x1, y1, x2, y2, c)


"""
Cases and functions for testing the non- scraping and plotting functions in the
helpers.py file
"""
import pytest
import pandas as pd

from helpers import (
    average_data,
    clean_gdp_data,
    clean_population_data,
    merge_dataframes,
    pivot
)

clean_gdp_data_cases = [
    ("test_data/gdp_test_data1_raw.csv", "test_data/gdp_test_data1_clean.csv"),
    ("test_data/gdp_test_data2_raw.csv", "test_data/gdp_test_data2_clean.csv")
]

@pytest.mark.parametrize("raw,clean", clean_gdp_data_cases)
def test_clean_gdp_data(raw, clean):
    """
    Test the clean_gdp_data() function in helpers.py.

    Args:
        raw: the filepath for the CSV containing the test data to be cleaned.
        clean: the filepath for the CSV containing the test data correctly
            cleaned.
    """
    df_clean = pd.read_csv(clean)
    assert df_clean.equals(clean_gdp_data(raw))

clean_pop_data_cases = [
    ("test_data/pop_test_data1_raw.csv", "test_data/pop_test_data1_clean.csv"),
    ("test_data/pop_test_data2_raw.csv", "test_data/pop_test_data2_clean.csv")
]

@pytest.mark.parametrize("raw,clean", clean_pop_data_cases)
def test_clean_population_data(raw, clean):
    """
    Test the clean_population_data() function in helpers.py.

    Args:
        raw: the filepath for the CSV containing the test data to be cleaned.
        clean: the filepath for the CSV containing the test data correctly
            cleaned.
    """
    df_clean = pd.read_csv(clean)
    assert df_clean.equals(clean_population_data(raw))

def test_merge_dataframe():
    """
    Test the merge_dataframe() function in helpers.py.
    """
    # Load the correctly merged dataframe to check against
    df_merged = pd.read_csv("test_data/merge_test_data.csv")
    # Load the three test dataframes to be merged
    test_medals = pd.read_csv("test_data/medals_test_data_clean.csv")
    test_gdp = pd.read_csv("test_data/gdp_test_data1_clean.csv")
    test_pop = pd.read_csv("test_data/pop_test_data1_clean.csv")
    # Assert the merge done properly
    assert df_merged.equals(merge_dataframes(
        [test_medals, test_gdp, test_pop]))

def test_pivot():
    """
    Test the pivot() function in helpers.py.
    when we saved our CSVs the data type of year was automatically changed
    from object to int64. As a work around to this, we save our CSV and then
    read it back in for the test. In our actual files, we never save the pivot
    data as a csv so this doesn't affect the actual function.
    """
    df_clean = pd.read_csv("test_data/pivoting_test_data_clean.csv")
    df_pivot = pd.read_csv("test_data/pivoting_test_data.csv")
    df_pivot = pivot(df_pivot)
    df_pivot.to_csv("test_data/pivoting_test_data_intermediate.csv", index=False)
    df_pivot = pd.read_csv("test_data/pivoting_test_data_intermediate.csv")
    pd.testing.assert_frame_equal(df_clean, df_pivot)

def test_average_data():
    """
    Test the average_data() function in helpers.py.
    """
    # Load the correctly averaged dataframe to check against
    df_done = pd.read_csv("test_data/averaging_test_data_done.csv")
    # Load test dataframe to be averaged
    df_raw = pd.read_csv("test_data/averaging_test_data.csv")
    # Assert the averaging done properly
    assert df_done.equals(average_data(df_raw))


version = input()
version_numbers = version.split('.')

num_1 = int(version_numbers[0])
num_2 = int(version_numbers[1])
num_3 = int(version_numbers[2])

num_3 += 1
if num_3 > 9:
    num_3 = 0
    num_2 += 1
    if num_2 > 9:
        num_2 = 0
        num_1 += 1

new_version = f'{num_1}.{num_2}.{num_3}'
print(new_version)

# OR -------------------------------------------------------

def next_version(version):
    version_parts = version.split('.')

    n_1 = int(version_parts[0])
    n_2 = int(version_parts[1])
    n_3 = int(version_parts[2])

    n_3 += 1
    if n_3 > 9:
        n_3 = 0
        n_2 += 1
        if n_2 > 9:
            n_2 = 0
            n_1 += 1

    new_version = f'{n_1}.{n_2}.{n_3}'
    return new_version

version = input()
print(next_version(version))

# OR -----------------------------------------------------------

version = input().split('.')

first = int(version[0])
second = int(version[1])
third = int(version[2])
new_version = 0

for n_1 in range(1):
    for n_2 in range(1):
        for n_3 in range(1):

            third += 1
            if third > 9:
                third = 0
                second += 1
                if second > 9:
                    second = 0
                    first += 1

new_version = f'{first}.{second}.{third}'

print(new_version)

# OR -----------------------------------------------------------

version = [int(number) for number in input().split('.')]
version[-1] += 1

for index in range(len(version) - 1, -1, -1):
    if version[index] > 9 and index != 0: # index != 0 to make sure that we will print 10.0.0 if 9.9.9
        version[index] = 0
        if index - 1 >= 0: # because we need to make sure that we will not update the first index
            version[index - 1] += 1

print('.'.join(str(number) for number in version))


import json as _json
from arcgis.raster._layer import ImageryLayer as _ImageryLayer
#from arcgis.raster._layer import Raster as _Raster
from arcgis.features import FeatureLayer as _FeatureLayer
import arcgis as _arcgis
import string as _string
import random as _random
from arcgis._impl.common._utils import _date_handler
import datetime
from arcgis.geometry import Geometry  as _Geometry
import numbers
import time
import os

import logging as _logging
_LOGGER = _logging.getLogger(__name__)

try:
    import numpy as _np
    import matplotlib.pyplot as _plt
    from matplotlib.pyplot import cm as _cm
except:
    pass

def _set_context(params, function_context = None):
    out_sr = _arcgis.env.out_spatial_reference
    process_sr = _arcgis.env.process_spatial_reference
    out_extent = _arcgis.env.analysis_extent
    mask = _arcgis.env.mask
    snap_raster = _arcgis.env.snap_raster
    cell_size = _arcgis.env.cell_size
    parallel_processing_factor = _arcgis.env.parallel_processing_factor

    context = {}

    if out_sr is not None:
        context['outSR'] = {'wkid': int(out_sr)}

    if out_extent is not None:
        context['extent'] = out_extent

    if process_sr is not None:
        context['processSR'] = {'wkid': int(process_sr)}

    if mask is not None:
        if isinstance(mask, _ImageryLayer):
            context['mask'] = {"url":mask._url}
        elif isinstance(mask,str):
            context['mask'] = {"url":mask}

    if cell_size is not None:
        if isinstance(cell_size, _ImageryLayer):
            context['cellSize'] = {"url":cell_size._url}
        elif isinstance(cell_size,str):
            if 'http:' in cell_size or 'https:' in cell_size:
                context['cellSize'] = {"url":cell_size}
            else:
                context['cellSize'] = cell_size
        else:
            context['cellSize'] = cell_size

    if snap_raster is not None:
        if isinstance(snap_raster, _ImageryLayer):
            context['snapRaster'] = {"url":snap_raster._url}
        elif isinstance(mask,str):
            context['snapRaster'] = {"url":snap_raster}

    if parallel_processing_factor is not None:
        context['parallelProcessingFactor'] = parallel_processing_factor

    if function_context is not None:
        if context is not None:
            context.update({k: function_context[k] for k in function_context.keys()})

        else:
            context = function_context

    if context:
        params["context"] = _json.dumps(context)

def _id_generator(size=6, chars=_string.ascii_uppercase + _string.digits):
    return ''.join(_random.choice(chars) for _ in range(size))

def _set_time_param(time):
    time_val = time
    if time is not None:
        if type(time) is list:
            if isinstance(time[0], datetime.datetime) or isinstance(time[0], datetime.date):
                if time[0].tzname() is None or time[0].tzname() != "UTC":
                    time[0] = time[0].astimezone(datetime.timezone.utc)
            if isinstance(time[1], datetime.datetime) or isinstance(time[1], datetime.date):
                if time[1].tzname() is None or time[1].tzname() != "UTC":
                    time[1] = time[1].astimezone(datetime.timezone.utc)
            starttime = _date_handler(time[0])
            endtime = _date_handler(time[1])
            if starttime is None:
                starttime = 'null'
            if endtime is None:
                endtime = 'null'
            time_val = "%s,%s" % (starttime, endtime)
        else:
            time_val = _date_handler(time)

    return time_val

def _to_datetime(dt):
    import datetime
    try:
        if dt<0:
            return datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=(dt/1000))
        else:
            return  datetime.datetime.utcfromtimestamp(dt/1000)
    except:
        return dt

def _datetime2ole(date):
    #date = datetime.strptime(date, '%d-%b-%Y')
    import datetime
    OLE_TIME_ZERO = datetime.datetime(1899, 12, 30)
    delta = date - OLE_TIME_ZERO
    return float(delta.days) + (float(delta.seconds) / 86400)

def _ole2datetime(oledt):
    import datetime
    OLE_TIME_ZERO = datetime.datetime(1899, 12, 30, 0, 0, 0)
    try:
        return OLE_TIME_ZERO + datetime.timedelta(days=float(oledt))
    except:
        return datetime.datetime.utcfromtimestamp(oledt/1000)

def _iso_to_datetime(timestamp):
    format_string = '%Y-%m-%dT%H:%M:%S%z'
    try:
        colon = timestamp[-3]
        colonless_timestamp = timestamp
        if colon == ':':
            colonless_timestamp = timestamp[:-3] + timestamp[-2:]
        dt_ob = datetime.datetime.strptime(colonless_timestamp, format_string)
        return dt_ob.replace(tzinfo=None)
    except:
        try:
            format_string = '%Y-%m-%dT%H:%M:%S'
            dt_ob = datetime.datetime.strptime(timestamp, format_string)
            return dt_ob
        except:
            return timestamp

def _check_if_iso_format(timestamp):
    format_string = '%Y-%m-%dT%H:%M:%S%z'
    try:
        colon = timestamp[-3]
        colonless_timestamp = timestamp
        if colon == ':':
            colonless_timestamp = timestamp[:-3] + timestamp[-2:]
        dt_ob = datetime.datetime.strptime(colonless_timestamp, format_string)
        return True
    except:
        try:
            format_string = '%Y-%m-%dT%H:%M:%S'
            dt_ob = datetime.datetime.strptime(timestamp, format_string)
            return dt_ob
        except:
            return False

def _time_filter(time_extent,ele):
    if time_extent is not None:
        if isinstance(time_extent, datetime.datetime):
            if(ele<time_extent):
                return True
            else:
                return False
        elif isinstance(time_extent, list):
            if isinstance(time_extent[0], datetime.datetime) and isinstance(time_extent[1], datetime.datetime):
                if(time_extent[0] < ele and ele < time_extent[1]):
                    return True
                else:
                    return False

        else:
            return True
    else:
        return True

def _linear_regression(sample_size, date_list, x, y):
    ncoefficient = 2
    if sample_size < ncoefficient:
        _LOGGER.warning("Trend line cannot be drawn. Insufficient points to plot Linear Trend Line")
        return [],[]

    AA = _np.empty([sample_size,ncoefficient], dtype=float, order='C')
    BB = _np.empty([sample_size,1], dtype=float, order='C')
    XX = _np.empty([ncoefficient,1], dtype=float, order='C')
    for i in range(sample_size):
        n=0
        AA[i][n] = date_list[i]
        AA[i][n+1] = 1
        BB[i] = y[i]

    x1 = _np.linalg.lstsq(AA, BB, rcond=None)[0]

    YY=[]
    for i in range(sample_size):
        y_temp=x1[0][0]*date_list[i] + x1[1][0]
        YY.append(y_temp)
    return x,YY

def _harmonic_regression(sample_size, date_list, x, y, trend_order):
    PI2_Year = 3.14159265*2/365.25

    ncoefficient = 2 * (trend_order + 1)
    if sample_size < ncoefficient:
        _LOGGER.warning("Trend line cannot be drawn. Insufficient points to plot Harmonic Trend Line for trend order "+str(trend_order)+". Please try specifying a lower trend order.")
        return [],[]

    AA = _np.empty([sample_size,ncoefficient], dtype=float, order='C')
    BB = _np.empty([sample_size,1], dtype=float, order='C')
    XX = _np.empty([ncoefficient,1], dtype=float, order='C')

    for i in range(sample_size):
        n=0
        AA[i][n] = date_list[i]
        AA[i][n+1] = 1

        for j in range(1,trend_order+1):
            AA[i][n + 2 * j] = _np.sin(PI2_Year * j * date_list[i])
            AA[i][n + 2 * j + 1] = _np.cos(PI2_Year * j * date_list[i])

        BB[i] = y[i]

    x1 = _np.linalg.lstsq(AA, BB, rcond=None)[0]
    YY=[]
    for i in range(sample_size):
        y_temp=x1[0][0]*date_list[i] + x1[1][0]
        for q in range(2,len(x1),2):
            y_temp=y_temp + x1[q][0] * _np.sin(2 * 3.14159265358979323846 * (q / 2) * date_list[i] / 365.25)
            y_temp=y_temp + x1[q+1][0] * _np.cos(2 * 3.14159265358979323846 * (q / 2) * date_list[i] / 365.25)
        YY.append(y_temp)
    return x, YY

def _epoch_to_iso(dt):
    import datetime
    try:
        if dt<0:
            return (datetime.datetime(1970, 1, 1, tzinfo = datetime.timezone.utc) + datetime.timedelta(seconds=(dt/1000))).isoformat()
        else:
            return  datetime.datetime.fromtimestamp(dt/1000, tz=datetime.timezone.utc).isoformat()
    except:
        return dt

def _datetime2ole(date):
    #date = datetime.strptime(date, '%d-%b-%Y')
    import datetime
    OLE_TIME_ZERO = datetime.datetime(1899, 12, 30)
    delta = date - OLE_TIME_ZERO
    return float(delta.days) + (float(delta.seconds) / 86400)

def _ole2datetime(oledt):
    import datetime
    OLE_TIME_ZERO = datetime.datetime(1899, 12, 30, 0, 0, 0)
    try:
        return OLE_TIME_ZERO + datetime.timedelta(days=float(oledt))
    except:
        return datetime.datetime.utcfromtimestamp(oledt/1000)

def _iso_to_datetime(timestamp):
    format_string = '%Y-%m-%dT%H:%M:%S%z'
    try:
        colon = timestamp[-3]
        colonless_timestamp = timestamp
        if colon == ':':
            colonless_timestamp = timestamp[:-3] + timestamp[-2:]
        dt_ob = datetime.datetime.strptime(colonless_timestamp, format_string)
        return dt_ob.replace(tzinfo=None)
    except:
        try:
            format_string = '%Y-%m-%dT%H:%M:%S.%f%z'
            dt_ob = datetime.datetime.strptime(colonless_timestamp, format_string)
            return dt_ob.replace(tzinfo=None)
        except:
            try:
                format_string = '%Y-%m-%dT%H:%M:%S'
                dt_ob = datetime.datetime.strptime(timestamp, format_string)
                return dt_ob
            except:
                return timestamp

def _check_if_iso_format(timestamp):
    format_string = '%Y-%m-%dT%H:%M:%S%z'
    try:
        colon = timestamp[-3]
        colonless_timestamp = timestamp
        if colon == ':':
            colonless_timestamp = timestamp[:-3] + timestamp[-2:]
        dt_ob = datetime.datetime.strptime(colonless_timestamp, format_string)
        return True
    except:
        try:
            format_string = '%Y-%m-%dT%H:%M:%S'
            dt_ob = datetime.datetime.strptime(timestamp, format_string)
            return dt_ob
        except:
            return False

def _local_function_template(operation_number=None):
    template_dict = {
  "name" : "max_rft",
  "description" : "A raster function template.",
  "function" : {
    "pixelType" : "UNKNOWN",
    "name" : "Cell Statistics",
    "description" : "Calculates a per-cell statistic from multiple rasters.  The available statistics are Majority, Maximum, Mean, Median, Minimum, Minority, Range, Standard Deviation, Sum, and Variety.",
    "type" : "LocalFunction",
    "_object_id" : 1
  },
  "arguments" : {
    "Rasters" : {
      "name" : "Rasters",
      "value" : {
        "elements" : [
        ],
        "type" : "ArgumentArray",
        "_object_id" : 2
      },
      "aliases" : [
        "__IsRasterArray__"
      ],
      "isDataset" : False,
      "isPublic" : False,
      "type" : "RasterFunctionVariable",
      "_object_id" : 3
    },
    "Operation" : {
      "name" : "Operation",
      "value" : "",
      "isDataset" : False,
      "isPublic" : False,
      "type" : "RasterFunctionVariable",
      "_object_id" : 4
    },
    "CellsizeType" : {
      "name" : "CellsizeType",
      "value" : 2,
      "isDataset" : False,
      "isPublic" : False,
      "type" : "RasterFunctionVariable",
      "_object_id" : 5
    },
    "ExtentType" : {
      "name" : "ExtentType",
      "value" : 1,
      "isDataset" : False,
      "isPublic" : False,
      "type" : "RasterFunctionVariable",
      "_object_id" : 6
    },
    "ProcessAsMultiband" : {
      "name" : "ProcessAsMultiband",
      "value" : True,
      "isDataset" : False,
      "isPublic" : False,
      "type" : "RasterFunctionVariable",
      "_object_id" : 7
    },
    "MatchVariable" : {
      "name" : "MatchVariable",
      "value" : True,
      "isDataset" : False,
      "isPublic" : False,
      "type" : "RasterFunctionVariable",
      "_object_id" : 8
    },
    "UnionDimension" : {
      "name" : "UnionDimension",
      "value" : False,
      "isDataset" : False,
      "isPublic" : False,
      "type" : "RasterFunctionVariable",
      "_object_id" : 9
    },
    "type" : "LocalFunctionArguments",
    "_object_id" : 10
  },
  "functionType" : 0,
  "thumbnail" : ""
}
    if operation_number is not None:
        template_dict["arguments"]["Operation"]["value"]=operation_number
    return template_dict

def _get_geometry(data):
    if data is None:
        return None

    if isinstance(data, _Geometry):
        return data
    elif isinstance(data, _arcgis.raster.Raster):
        return _Geometry(data.extent)
    elif isinstance(data, _ImageryLayer):
        return _Geometry(data.extent)
    elif isinstance(data, _FeatureLayer):
        return _get_geometry_from_feature_layer(data)
    else:
        return data

def _get_geometry_from_feature_layer(data):
    geo=None
    layer_fset = layer.query()
    for ele in layer_fset.features:
        geo = geo.union(_Geometry(ele.geometry)) if geo else _Geometry(ele.geometry)
    return geometry

def build_query_string(field_name, operator, field_values):
    operator_map = {
    "equals": "=",
    "less_than": "<",
    "greater_than": ">",
    "not_equals": "<>",
    "not_less_than": ">=",
    "not_greater_than": "<=",
        }

    if operator in operator_map:
        if isinstance(field_values, numbers.Number):
            return field_name + ' ' + operator_map[operator] + ' ' + str(field_values)
        elif isinstance(field_values, str):
            return field_name + ' ' + operator_map[operator] + ' \'' + field_values + '\''
        else:
            raise TypeError('field_value must be numeric or string')

    elif operator in ['starts_with', 'ends_with', 'not_starts_with', 'not_ends_with', 'contains', 'not_contains']:
        if not isinstance(field_values, str):
            raise TypeError('field_value must be string')
        if operator == 'starts_with':
            return field_name + ' LIKE ' + '\'' + field_values + '%\''
        elif operator == 'ends_with':
            return field_name + ' LIKE' + '\'%' + field_values + '\''
        elif operator == 'not_starts_with':
            return field_name + ' NOT LIKE ' + '\'' + field_values + '%\''
        elif operator == 'not_ends_with':
            return field_name + ' NOT LIKE ' + '\'%' + field_values + '\''
        elif operator == 'contains':
            return field_name + ' LIKE ' + '\'%' + field_values + '%\''
        elif operator == 'not_contains':
            return field_name + ' NOT LIKE ' + '\'%' + field_values + '%\''
    elif operator == 'in':
        if not isinstance(field_values, list):
            raise TypeError('field_values must be type list for operator "in"')
        values = '('
        for item in field_values:
            if not (isinstance(item, numbers.Number) or isinstance(item, str)):
                raise TypeError('item in field_values must be numeric or string')
            if values == '(':
                values += '\'' + item + '\'' if isinstance(item, str) else str(item)
            else:
                values += ',\'' + item + '\'' if isinstance(item, str) else ',' + str(item)
        values += ')'
        return field_name + ' IN ' + values
    elif operator == 'not_in':
        values = '('
        for item in field_values:
            if not (isinstance(item, numbers.Number) or isinstance(item, str)):
                raise TypeError('item in field_values must be numeric or string')
            if values == '(':
                values += '\'' + item + '\'' if isinstance(item, str) else str(item)
            else:
                values += ',\'' + item + '\'' if isinstance(item, str) else ',' + str(item)
        values += ')'
        return field_name + ' NOT IN ' + values
    else:
        raise ValueError('invalid operator value')

def _generate_direct_access_url(gis=None):
    """helper fn to get the direct access url for azure storage"""
    gis = _arcgis.env.active_gis if gis is None else gis
    url = "%s/sharing/rest/content/users/%s/generateDirectAccessUrl" % (gis._portal.url,
                                                                 gis._username)
    params = {"f" : "json", "storeType":"rasterStore"}
    res = gis._portal.con.post(url, params)
    if isinstance(res, dict):
        if "url" in res.keys():
            return res["url"]
        else:
            raise RuntimeError("Couldn't generate direct access url")
    else:
        raise RuntimeError("Couldn't generate direct access url")

def _upload_imagery_agol(files, gis=None):
    """uploads a file to the image layer to AGOL and returns the list of urls"""

    try:
        from azure.storage.blob import ContainerClient
    except:
        print("Install Azure library packages for Python. (version - azure-storage-blob-12.5.0) \
        (https://docs.microsoft.com/en-us/azure/developer/python/azure-sdk-install)")
    sas_url = _generate_direct_access_url(gis)
    container = ContainerClient.from_container_url(sas_url)
    if not isinstance(files,list):
        files = [files]

    url_list = []
    for file in files:
        current_time = int(time.time())
        prefix =  "_images/"+str(current_time)+"/"

        if os.path.exists(file):
            if(os.path.isdir(file)):
                folder = os.path.basename(file)
                basename_len=len(os.path.dirname(file))
                for root,d_names,f_names in os.walk(file):
                    for f in f_names:
                        blobname = prefix + (root+"/"+f)[basename_len+1:].replace(os.sep, '/')
                        filepath = os.path.join(root, f)
                        blob=container.get_blob_client(blobname)
                        url = blob.url.split("?", 1)[0]
                        url_list.append(url)
                        with open(filepath, "rb") as data:
                            blob.upload_blob(data, blob_type="BlockBlob")

            else:
                blobname = prefix+os.path.basename(file).replace(os.sep, '/')
                blob=container.get_blob_client(blobname)
                with open(file, "rb") as data:
                    blob.upload_blob(data, blob_type="BlockBlob")
                url = blob.url.split("?", 1)[0]
                url_list.append(url)

    return url_list

def _upload_imagery_enterprise(files, raster_type_name=None, gis=None):
    """uploads a file to the image layer to enterprise and returns the item id"""

    ra_url = gis.properties.helperServices["rasterAnalytics"]["url"]
    url = "%s/uploads/upload" % ra_url
    params = {
        "f" : 'json'
    }

    if not isinstance(files,list):
        files = [files]

    item_ids_list = []
    res = {}

    append_path = False
    for file in files:
        item_id_dict={}
        if os.path.exists(file):
            if(os.path.isdir(file)):
                if file.endswith(".crf") or raster_type_name !="Raster Dataset":
                    append_path = True
                folder = os.path.basename(file)
                basename_len=len(os.path.dirname(file))
                for root,d_names,f_names in os.walk(file):
                    for f in f_names:
                        fp =os.path.join(root, f)
                        path = ("/"+root+"/"+f)[basename_len+1:].replace(os.sep, '/')
                        files_param = {'file' : fp }
                        try:
                            res = gis._con.post(path=url, postdata=params, files=files_param)
                        except Exception as e:
                            _LOGGER.warning('file: '+str(fp)+ " "+ str(e))

                        if 'success' in res and res['success']:
                            item_id = res['item']['itemID']
                            res = {}
                            if append_path:
                                item_id_dict = {"itemId":item_id, "path":fp}
                                item_ids_list.append(item_id_dict)
                                item_id_dict={}
                            else:
                                item_ids_list.append(item_id)

            else:
                files_param = {'file' : file}
                try:
                    res = gis._con.post(path=url, postdata=params, files=files_param)
                except Exception as e:
                    _LOGGER.warning('file: '+str(file)+ " "+ str(e))
                if 'success' in res and res['success']:
                    item_id = res['item']['itemID']
                    res = {}
                if item_id is not None:
                    item_ids_list.append(item_id)

    return item_ids_list


class Solution:
    # @param {integer} m
    # @param {integer} n
    # @return {integer}
    def uniquePaths(self, m, n):
        dict = {}
        for i in range(m):
            for j in range(n):
                if i is 0 or j is 0:
                    dict[(i, j)] = 1
                else:
                    dict[(i, j)] = dict[(i - 1, j)] + dict[(i, j - 1)]
        return dict[(m - 1, n - 1)]


from cmath import log

num = int(input("Enter : "))
x=1
sum = 0

while x <= int(num/2):
     print(num,x)
     if(num%x==0):
        sum = sum+x
     x=x+1

if(sum==num and num>0):
    print(num, "is a perfect number")
else:
    print(num, "is not perfect number")


import logging
import unittest

import pack.test_module

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

logger.critical('Display critical infomration')

''' Practice on invoking function '''
pack.test_module.test_invoke('Jaron','Anny')

''' Practice on invoking class '''
acct = pack.test_module.Account('Justin', '123-4567', 1000)
acct.name = 'Marco'

check_acct = pack.test_module.CheckingAccount('Anny', '123-4567', 100, 'Female')
logger.debug('acct = {}'.format(acct))
logger.debug('check_acct = {}'.format(check_acct))

acct.deposit(500)

check_acct.deposit(100)

logger.debug('acct = {}'.format(acct))
logger.debug('check_acct = {}'.format(check_acct))
logger.debug("{0}'s balance = {1}".format(acct.name, acct.balance))

check_acct.set_gendor('Male')
check_acct.set_gendor('Female')

logger.debug("check_acct = {}".format(check_acct))


# -*- coding: utf-8 -*-
import pytest

from django.conf import settings

from web.favorites_utils import decode_favorites, encode_favorites, toggle_favorite

TEST_OK_SIZES = [(3), (settings.MAX_FAVORITES)]

@pytest.mark.parametrize("size", TEST_OK_SIZES)
def test_ok_encode_decode(size):
    favorites = []
    for id in range(size):
        favorites.append(id)

    encoded = encode_favorites(favorites)
    decoded = decode_favorites(encoded)

    assert len(favorites) == len(decoded)

    for i in range(size):
        assert favorites.pop(0) == decoded.pop(0), "items at %d not same" % i

def test_nok_toggle_decode():
    buffer = "X" * (settings.MAX_FAVORITES * 8 + 1)
    with pytest.raises(ValueError) as e_info:
        decoded = decode_favorites(buffer)

def test_nok_toggle_favorite():
    favorites = []
    for id in range(settings.MAX_FAVORITES):
        favorites.append(id)
    result = toggle_favorite(favorites, settings.MAX_FAVORITES + 1)
    assert result == "error"


# Leetcode 1721 - https://leetcode.com/problems/swapping-nodes-in-a-linked-list/
# Problem - You are given the head of a linked list, and an integer k. Return the head of the LL after
# swapping the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed).
# Solution - Adapted from https://leetcode.com/problems/swapping-nodes-in-a-linked-list/discuss/1911996/Python-Simple-Solution-with-Explanation

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
# Naive: Convert LL to list, swap elements with slicing, convert back to LL
class Solution:
    def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        l, r = head, head # Define two pointers both at the node head (which is null and points to first element)
        # Traverse l to get to the k-1 element from the left due to 1 indexing of LL
        for i in range(k-1):
            l = l.next
        tail = l # Pointer l is now where we need it. Start tail node from here and traverse r along with it
        while tail.next:
            r, tail = r.next, tail.next # r will stay the same distance from tail...k-1 so it ends up k-1 from right
        l.val, r.val = r.val, l.val # Now swap r and l values in LL
        return head


"""Class for Job Badges resource generator."""

from PIL import Image, ImageDraw
from utils.TextBoxDrawer import TextBox, TextBoxDrawer
from django.utils.translation import ugettext_lazy as _
from resources.utils.BaseResourceGenerator import BaseResourceGenerator
from resources.utils.coords import calculate_box_vertices

FONT_PATH = "static/fonts/PatrickHand-Regular.ttf"
FONT_SIZE = 200
TEXTBOX_WIDTH = 1000
TEXTBOX_HEIGHT = 275
LABEL_DATA = {
    "programmer": _("Hello, I'm a Programmer"),
    "tester": _("Hello, I'm a Tester"),
    "bot": _("Hello, I'm a Bot"),
}

class JobBadgesResourceGenerator(BaseResourceGenerator):
    """Class for Job Badges resource generator."""

    def data(self):
        """Create data for a copy of the Job Badges resource.

        Returns:
            A dictionary of the one page for the resource.
        """
        image_path = "static/img/resources/job-badges/job-badges.png"
        image = Image.open(image_path)
        draw = ImageDraw.Draw(image)
        textbox_drawer = TextBoxDrawer(image, draw)

        # coordinates of top left point of text box
        top_left_x_coords = [50, 1200]
        top_left_y_coord = 100

        # Add text labels
        for label, label_text in LABEL_DATA.items():
            for top_left_x_coord in top_left_x_coords:
                vertices = calculate_box_vertices(
                    (top_left_x_coord, top_left_y_coord),
                    TEXTBOX_WIDTH,
                    TEXTBOX_HEIGHT
                )
                box = TextBox(
                    vertices=vertices,
                    width=TEXTBOX_WIDTH,
                    height=TEXTBOX_HEIGHT,
                    font_path=FONT_PATH,
                    font_size=FONT_SIZE,
                )
                textbox_drawer.write_text_box(
                    box,
                    label_text,
                    horiz_just="center",
                    vert_just="center",
                )

            # increase y coord for next name tag down
            top_left_y_coord += 675

        return {"type": "image", "data": image}


# simRemoteApi.start(19999)

try:
    import sim
except:
    print ('--------------------------------------------------------------')
    print ('"sim.py" could not be imported. This means very probably that')
    print ('--------------------------------------------------------------\n')

import time
import MonitorTimes
import Tarefas
import camera
import matplotlib.pyplot as mlp
import numpy as np
from threading import Thread

# -----------------------------------START----------------------------
print ('Program started')
sim.simxFinish(-1)  # just in case, close all opened connections
clientID = sim.simxStart('127.0.0.1', 19999, True, True, 5000, 5)  # Connect to CoppeliaSim
if clientID != -1:
    print ('Connected to remote API server')
    sim.simxAddStatusbarMessage(clientID, 'conectado a API...', sim.simx_opmode_oneshot)
    erro, S1 = sim.simxGetObjectHandle(clientID, 'S1', sim.simx_opmode_oneshot_wait)
    erro, S2 = sim.simxGetObjectHandle(clientID, 'S2', sim.simx_opmode_oneshot_wait)
    erro, S3 = sim.simxGetObjectHandle(clientID, 'S3', sim.simx_opmode_oneshot_wait)
    erro, Camera = sim.simxGetObjectHandle(clientID, 'Camera', sim.simx_opmode_oneshot_wait)

    estatusS1 = sim.simxReadProximitySensor(clientID, S1, sim.simx_opmode_streaming)
    estatusS2 = sim.simxReadProximitySensor(clientID, S2, sim.simx_opmode_streaming)
    estatusS3 = sim.simxReadProximitySensor(clientID, S3, sim.simx_opmode_streaming)
    button = sim.simxGetInt32Signal(clientID, "myButton", sim.simx_opmode_streaming)
    flag1 = 0
    flag2 = 0
    flag3 = 0
    flagCalculo = False
    flagCamera = False
    time.sleep(2)
    Tarefas.setInicio(clientID,Camera)  # Passa o clinetID e o Handle da camera para a classe tarefas
    thc = Tarefas.calculo()
    tempoinicio = time.time()
    semaforo = 0
    sim.simxAddStatusbarMessage(clientID, 'SEMAFORO ESTA VERDE', sim.simx_opmode_oneshot_wait)
    # -------------------------------Fim da inicializacao ------------------------------------------------
    while True:

        estatusS1 = sim.simxReadProximitySensor(clientID, S1, sim.simx_opmode_buffer)
        if (semaforo == 0) and estatusS1[1]:
            if flag1 == 0:
                print("S1 detect")
                Tarefas.sensor1Ativado().start()
                flag1 = 1
        elif semaforo == 1 and estatusS1[1]:
            if not flagCamera:
                sim.simxAddStatusbarMessage(clientID, "Multa por sinal vermelho", sim.simx_opmode_oneshot_wait)
                Tarefas.AtivaCamera().start()
                camera.tirafoto(Camera,clientID)
                flagCamera = True
        else:
            if flag1 == 1:
                flag1 = 0
                flagCamera = False

        estatusS2 = sim.simxReadProximitySensor(clientID, S2, sim.simx_opmode_buffer)
        if estatusS2[1]:
            if flag2 == 0:
                print("S2 detect")
                if semaforo == 0:
                    Tarefas.sensor2Ativado().start()
                    if not flagCalculo:
                        Tarefas.calculo().start()
                        flagCalculo = True
                else:
                    if not flagCamera:
                        sim.simxAddStatusbarMessage(clientID, "multa por sinal vermelho", sim.simx_opmode_oneshot_wait)
                        Tarefas.AtivaCamera().start()
                        camera.tirafoto(Camera,clientID)
                        flagCamera = True
                flag2 = 1

        estatusS3 = sim.simxReadProximitySensor(clientID, S3, sim.simx_opmode_buffer)
        if estatusS3[1]:
            if flag3 == 0:
                print("S3 detect")
                if semaforo == 0:
                    Tarefas.sensor3Ativado().start()
                    if not flagCalculo:
                        Tarefas.calculo().start()
                        flagCalculo = True
                else:
                    if not flagCamera:
                        sim.simxAddStatusbarMessage(clientID, "Multa por sinal vermelho", sim.simx_opmode_oneshot_wait)
                        Tarefas.AtivaCamera().start()
                        camera.tirafoto(Camera,clientID)
                        flagCamera = True
                flag3 = 1
        else:
            if flag3 == 1:
                flag3 = 0
                flag2 = 0
                flagCalculo = False
                flagCamera = False

        tempoVerifica = time.time()

        if ((tempoVerifica - tempoinicio) > 20):
            print('Verifica botao')
            Tarefas.verificaBt(semaforo)
            time.sleep(0.01)
            Tarefas.verificaBt(semaforo).start()
            time.sleep(0.1)
            tempoinicio = time.time()
            semaforo = MonitorTimes.lerSemaforo()

else:
    print ('Failed connecting to remote API server')
print ('Program ended')


import sys
sys.path.append("../../pygra")  # add pygra library

import geometry  # library to create crystal geometries
import hamiltonians  # library to work with hamiltonians
import sculpt  # to modify the geometry
import correlator
import numpy as np
import matplotlib.pyplot as plt
import kpm

g = geometry.chain()
g = g.supercell(100)
g.dimensionality = 0
h = g.get_hamiltonian()
h.shift_fermi(.4)

h.add_zeeman([.8,.8,.8])
h.add_rashba(.8)

i = 0
j = 7

(x,y,yi) = kpm.correlator0d(h.intra,npol=300,i=i,j=j)
(x2,y2,yi2) = correlator.correlator0d(h.intra,i=i,j=j,delta=0.1)
#print(np.trapz(y,x=x,dx=x[1]-x[0]))

plt.subplot(1,2,1)
plt.plot(x,y,marker="o",label="KPM")
plt.plot(x2,y2,marker="o",label="Green")

plt.legend()

plt.subplot(1,2,2)
plt.plot(x,yi,marker="o",label="KPM")
plt.plot(x2,yi2,marker="o",label="Green")

plt.legend()

plt.show()


from collections import namedtuple
import config
import dataset
import graph
import random
import tensorflow as tf

RunInfo = namedtuple("RunInfo", [
    "dataset",
    "graph",
    "session",
])

BatchInfo = namedtuple("BatchInfo", [
    "epoch_idx",
    "batch_idx",
])

def run_batch(run_info, batch_info):
    d, g = run_info.dataset, run_info.graph

    examples = random.sample(d.training_idx_examples, config.BATCH_SIZE)
    _, loss = run_info.session.run(
        [g.training_op, g.training_loss],
        feed_dict = {
            g.input_sequence: [e[0] for e in examples],
            g.output_sequence: [e[1] for e in examples],
            g.learning_rate: config.LEARNING_RATE
        }
    )

    print(f"Epoch {batch_info.epoch_idx:02d} | "
          f"Batch {batch_info.batch_idx:02d} | "
          f"Loss: {loss:.3f}")

def run_validation(run_info, epoch_idx):
    print("Beginning validation")
    d, g = run_info.dataset, run_info.graph

    examples = random.sample(
        d.validation_idx_examples, config.BATCH_SIZE
    )
    accuracy = run_info.session.run(
        g.accuracy,
        feed_dict = {
            g.input_sequence: [e[0] for e in examples],
            g.output_sequence: [e[1] for e in examples],
        }
    )

    print(f"Epoch {epoch_idx:02d} | "
          f"Accuracy: {accuracy:.3f}")

def run(session):
    d = dataset.dataset(
        max_length = config.EXAMPLE_MAX_LEN,
        num_examples = config.NUM_EXAMPLES
    )

    g = graph.graph(
        batch_size = config.BATCH_SIZE,
        sequence_length = config.EXAMPLE_MAX_LEN,
        vocab_size = len(d.word_to_idx),
        num_embedding_dimensions = config.NUM_EMBEDDING_DIMENSIONS,
        num_lstm_layers = config.NUM_LSTM_LAYERS,
        num_lstm_units = config.NUM_LSTM_UNITS,
        start_word_idx = d.word_to_idx[dataset.start_word],
        stop_word_idx = d.word_to_idx[dataset.stop_word],
    )

    session.run(tf.global_variables_initializer())

    file_writer = tf.summary.FileWriter('logs/', session.graph)

    run_info = RunInfo(
        dataset = d,
        graph = g,
        session = session
    )
    for epoch_idx in range(1, config.NUM_EPOCHS):
        num_batches = len(d.training_idx_examples) // config.BATCH_SIZE
        for batch_idx in range(1, num_batches):
            batch_info = BatchInfo(
                epoch_idx = epoch_idx,
                batch_idx = batch_idx,
            )
            run_batch(run_info, batch_info)
        run_validation(run_info, epoch_idx)

with tf.Session() as session:
    run(session)


with open('../inputs/day_10.txt', 'r') as f:
    adapters = [int(line) for line in f]  # list of joltages

adapters.append(0)
device = max(adapters) + 3
adapters.append(device)
adapters.sort()
diffs = {}

"""
What is the number of 1-jolt differences multiplied by the number of 3-jolt differences?
"""
for i in range(len(adapters)):  # find all joltage differences
    if i is not len(adapters) - 1:
        diff = adapters[i + 1] - adapters[i]
        if diff in diffs:
            diffs[diff] += 1
        else:
            diffs[diff] = 1
print(diffs[1] * (diffs[3]))

"""
What is the total number of distinct ways you can arrange the adapters to connect the charging outlet to your device?
"""
# consider unweighted digraph where nodes are adapters and edges are valid connections; find total paths to max
a_ways = {0: 1}  # joltage: ways to reach it
for i in range(1, len(adapters)):
    ways = 0
    for j in range(1, 4):  # possible valid differences
        if i - j >= 0 and adapters[i] - adapters[i - j] < 4:  # check for valid differences
            ways += a_ways[adapters[i - j]]
    a_ways[adapters[i]] = ways
print(a_ways[device])


from dataclasses import dataclass, field
import sys
# add support for python<3.11
if sys.version_info >= (3, 11):
    from typing import Callable, Self, TypedDict
else:
    from typing import Callable, TypedDict
    from typing_extensions import Self

class DirectiveDict(TypedDict):
    """
    TypedDict for type hinting a dictionary that represents
    a directive, retrieved from crossplane library
    """
    directive: str
    line: int
    args: list[str]
    block: list[dict]

@dataclass
class Directive:
    """
    Data class that represents a directive
    """
    directive: str = None
    line: int = None
    parent: Self = None
    args: list[str] = field(default_factory=list)
    block: list[Self] = field(default_factory=list)

    def get_full_directive(self) -> str:
        """
        Get a directive along with its arguments.

        Returns:
            A string containing the directive and its arguments
        """
        return ' '.join([self.directive, *self.args])

    def get_full_args(self) -> str:
        """
        Get a directive's arguments, joined into one string

        Returns:
            str -> A string containing the directive's arguments
        """
        return ' '.join(self.args)

class DirectiveUtil:
    """
    Utility class for handling Directive objects
    """
    @staticmethod
    def traverse(directives: list[Directive],
                 callback: Callable[[Directive], None]) -> None:
        """
        Given a list of directives, recursively traverse through the
        tree of directives and performs a callback on each directive.

        Args:
            directives (list[Directive]): list of Directive objects
            callback (Callable[[Directive], None]): Operation to perform
        """
        for directive in directives:
            callback(directive)
            DirectiveUtil.traverse(directive.block, callback)

    @staticmethod
    def get_directives_set(directives: list[Directive]) -> set[str]:
        """
        Get a full unique set of directive names

        Args:
            directives (list[Directive]): List of directives to retrieve from

        Returns:
            set[str]
        """
        directive_set = set()
        DirectiveUtil.traverse(directives, lambda directive: directive_set.add(directive.directive))
        return directive_set

    @staticmethod
    def get_directives(directive_name: str,
                       directives: list[Directive]) -> list[Directive]:
        """
        Given a list of Directives objects and a directive name, retrieve all
        Directive objects with the given name.

        Args:
            directive_name (str): Directive name to search for
            directives (list[Directive]): List of directives to search through

        Returns:
            List of directives
        """
        retrieved_directives: list[Directive] = []

        def traversal_callback(directive: Directive):
            if directive.directive == directive_name:
                retrieved_directives.append(directive)

        DirectiveUtil.traverse(directives, traversal_callback)

        return retrieved_directives

    @staticmethod
    def recursive_initialize_directives(directive: Directive,
                                        directive_dict: DirectiveDict) -> None:
        """
        Use this method on a top-level Directive object. Each directive object
        will have its properties filled in using the provided corresponding
        dictionary of values.

        Args:
            directive (Directive): Top-level Directive object to initialize with values
            directive_dict (DirectiveDict): Dictionary to copy values from
        """
        directive.directive = directive_dict["directive"]
        directive.line = directive_dict["line"]
        directive.args = directive_dict["args"]
        directive.block = []

        if directive_dict.get("block") is not None:
            for sub_directive_dict in directive_dict.get("block"):
                sub_directive = Directive()
                sub_directive.parent = directive
                DirectiveUtil.recursive_initialize_directives(
                    sub_directive,
                    sub_directive_dict
                )
                directive.block.append(sub_directive)


from django.test import TestCase

# Create your tests here.

print("hello"[0:150])

from bs4 import BeautifulSoup

s="
hello
123"

soup=BeautifulSoup(s,"html.parser")

# print(soup.text)

print(soup.find_all())

for tag in soup.find_all():

    print(tag.name)
    if tag.name=="script":
        tag.decompose()

print(str(soup))


from binance.client import Client
from binance.enums import *
import websocket, json, pprint, numpy
from config import BINANCE, COIN_REFER, COIN_TARGET, PERSISTENCE_CONNECTION, TESTING_PRODUCTION,PHEMEX_PRICE
from datetime import timedelta, datetime
import pandas as pd
import math
from indicators.sqlCache import  SqlCache
from production.automation_phemex import Automation
import sys, os

class BrokerProduction:
    def __init__(self, info, interval, phemex_automation, testing_production_date = None, stand_alone = False):
        self.comminfo = info
        self.testing_production_date = testing_production_date
        self.interval = {
            'KLINE_INTERVAL_1MINUTE': '1m',
            'KLINE_INTERVAL_3MINUTE': '3m',
            'KLINE_INTERVAL_5MINUTE': '5m',
            'KLINE_INTERVAL_15MINUTE': '15m',
            'KLINE_INTERVAL_30MINUTE': '30m',
            'KLINE_INTERVAL_1HOUR': '1h',
            'KLINE_INTERVAL_2HOUR': '2h',
            'KLINE_INTERVAL_4HOUR': '4h',
            'KLINE_INTERVAL_6HOUR': '6h',
            'KLINE_INTERVAL_8HOUR': '8h',
            'KLINE_INTERVAL_12HOUR': '12h',
            'KLINE_INTERVAL_1DAY': '1d',
            'KLINE_INTERVAL_3DAY': '3d',
            'KLINE_INTERVAL_1WEEK': '1w',
            'KLINE_INTERVAL_1MONTH': '1M'
        }
        self.STANDALONE = stand_alone
        self.klineInterval = interval
        self.cerebro = None
        # sin futuros wss://stream.binance.com:9443/ws/btcusdt@kline_
        # con fuures wss://fstream.binance.com/ws/btcusdt@kline_
        self.socket  = "wss://fstream.binance.com/ws/"+COIN_TARGET.lower() + COIN_REFER.lower() +"@kline_" + self.interval[self.klineInterval]
        print(self.socket)
        self.symbol = COIN_TARGET + COIN_REFER
        # en la version stand alone, en fuerza bruto por ejemplo, no es necesario instanciar el Client.
        # ya hay uno funcionando si es en Live Production o se trate todo lo necesario de la BD.
        if self.STANDALONE == False:
            self.client = Client(BINANCE.get("key"), BINANCE.get("secret"))
        try:
            self.sql_cache = SqlCache()
        except:
            self.sql_cache = SqlCache.getInstance()
        # automation phemex
        self.phemex_automation = phemex_automation

    def run(self):
        if TESTING_PRODUCTION == False:
            self.ws = websocket.WebSocketApp(self.socket,
                        on_message = lambda ws,msg: self.on_message(ws, msg),
                        on_error   = lambda ws,msg: self.on_error(ws, msg),
                        on_close   = lambda ws:     self.on_close(ws),
                        on_open    = lambda ws:     self.on_open(ws))
            self.ws.run_forever()
        else:
            self.simulate_binance_socket()

    def simulate_binance_socket(self, data_tick= None):
        if self.STANDALONE == False:
            data_tick = self.sql_cache.get_ticks_realtime(self.testing_production_date.get("from"), self.testing_production_date.get("to"))
        # obtiene con datos del config los ticks correspondientes
        for index, tick in data_tick.iterrows():
            message = {}
            candle = {}
            message["E"] = tick["timestamp"]
            candle["x"] = tick["is_close"]
            candle["c"] = tick["close"]
            candle["o"] = tick["open"]
            candle["h"] = tick["high"]
            candle["l"] = tick["low"]
            candle["v"] = tick["volume"]
            candle["T"] = tick["timestamp_close"]
            message["k"] = candle
            message["phemex"] = tick["phemex_close"]
            self.on_message(None, json.dumps(message))
        '''
        print("Finaliza con los siguientes resultados:")
        print(self.cerebro.get_wallet_balance())
        print("History Balance:")
        print(self.cerebro.get_history_balance())
        print("History Profit por hora")
        print(self.cerebro.get_history_profit())
        print("Binance profit")
        print(self.cerebro.get_binance_wallet_balance())
        print("Binance Leverage")
        print(self.cerebro.get_wallet_balance_leverage())
        # print(self.cerebro.get_wallet_balance_leverage())
        # genera el json_message simulando lo que envia Binance desde el API
        # llama on_message
        '''

    def set_cerebro(self,cerebro):
        self.cerebro = cerebro

    def on_open(self,ws):
        print("opened connection")

    def on_close(self,ws):
        print("closed connection")

    def on_message(self,ws, message):
        json_message = json.loads(message)
        # los ticks cuando se dispara el evento
        datetime = json_message['E']
        candle = json_message["k"]
        is_candle_closed = candle["x"]
        timestamp = pd.to_datetime(json_message['E'], unit='ms')

        close = candle["c"]
        open = candle["o"]
        low = candle["l"]
        high = candle["h"]
        volume = candle["v"]

        datetime_closed = datetime
        is_closed = 0
        if (is_candle_closed):
            is_closed = 1
            # close candle time
            datetime_closed = candle["T"]
            # no ejecuta next frame
            self.cerebro.addNextFrame(1, datetime, open,  low, high, close, volume, False)

        # si esta en config PHEMEX_PRICE
        if PHEMEX_PRICE == True:
            if TESTING_PRODUCTION == True:
                phemex_price = json_message['phemex']
            else:
                phemex_price = self.phemex_automation.get_current_price()
            # addNextFrame con indice 2  en close los demas 0, False
            self.cerebro.addNextFrame(2,datetime, 0, 0, 0, phemex_price, 0, False)
        try:
            self.cerebro.addNextFrame(0,datetime, open, low, high, close, volume, True)
        except Exception as e:
            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            print(exc_type, fname, exc_tb.tb_lineno)
        # agrega el precio realtime a la BD
        # esto solo se llama en ENV = PRODUCTION
        # si hay problema en la BD evita que se corte el flujo del bot.
        #try:
        if TESTING_PRODUCTION == False and self.STANDALONE == False:
            if PHEMEX_PRICE == True:
                # agrega el price pero con el precio phemex
                self.sql_cache.insert_realtime_price_with_phemex(datetime, open, low, high, close, volume, datetime_closed,  is_closed, phemex_price, coin=COIN_TARGET)
            else:
                self.sql_cache.insert_realtime_price(datetime, open, low, high, close, volume, datetime_closed,  is_closed, coin=COIN_TARGET)
        #except:
        #    print("Problema en guardar en la BD el tick en realtime.")

    def on_error(self, ws, message):
        print("Error socket")
        print(message)
        if PERSISTENCE_CONNECTION:
            self.run()

    def get_historical_klines(self, interval, lapse):
        print("Getting historical " + self.interval[interval])
        N = lapse
        date_N_days_ago = datetime.now() - timedelta(days=N)
        klines = self.client.get_historical_klines(self.symbol, self.interval[interval], date_N_days_ago.strftime("%d %b %Y %H:%M:%S"))
        data = pd.DataFrame(klines, columns = ['timestamp', 'open', 'high', 'low', 'close', 'volume', 'close_time', 'quote_av', 'trades', 'tb_base_av', 'tb_quote_av', 'ignore' ])
        # data['timestamp'] = pd.to_datetime(data['timestamp'], unit='ms')

        data.set_index('timestamp', inplace=True)
        data.sort_values(by=['timestamp'], inplace=True, ascending=True)

        row = len(data.index)
        for i in range(row):
            datatime = data.index[i]
            open = data.iat[i,0]
            high = data.iat[i,1]
            low = data.iat[i,2]
            close = data.iat[i,3]
            volume = data.iat[i,4]
            self.cerebro.addNextFrame(1,datatime, open, low, high, close, volume,  False)
        self.cerebro.setLenData1()

    def order(self, side, quantity, symbol,  order_type = ORDER_TYPE_MARKET):
        try:
            order = self.client.create_order(
                symbol=symbol,
                side=side,
                type=order_type,
                quantity=quantity
            )
        except Exception as e:
            print(e)
            return False
        return True


# -*- coding: utf-8 -*-
"""
ffmpeg probe
"""
import subprocess
from typing import NamedTuple

class FFProbeResult(NamedTuple):
    """ffmpeg probe result"""

    return_code: int
    json: str
    error: str

def ffprobe(file_path) -> FFProbeResult:
    """return ffprobe in json format"""
    command_array = [
        "ffprobe",
        "-v",
        "quiet",
        "-print_format",
        "json",
        "-show_format",
        "-show_streams",
        file_path,
    ]
    try:
        result = subprocess.run(
            command_array,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            universal_newlines=True,
            encoding="utf8",
            check=True,
        )
    except (UnicodeDecodeError, subprocess.CalledProcessError) as _e:
        return FFProbeResult(return_code=1212, json="", error=str(_e))
    return FFProbeResult(
        return_code=result.returncode, json=result.stdout, error=result.stderr
    )

def smart_probe(ffmpeg_json):
    """add smart infos to original ffmpeg probe"""
    streams = ffmpeg_json.get("streams", [])
    dstreams = {"video": [], "audio": [], "subtitle": []}
    screen_size = ""
    for stream in streams:
        language = (
            f'({stream.get("tags").get("language")})'
            if (stream.get("tags") and stream.get("tags").get("language"))
            else ""
        )
        codec_type = stream.get("codec_type", "unknown")
        if codec_type in ["video", "audio", "subtitle"]:
            dstreams[codec_type].append(f'{stream.get("codec_name")} {language}')
        if codec_type == "video":
            screen_size = f'{stream.get("width", "?")}x{stream.get("height", "?")}'
    codecs = []
    for codec_type in ["video", "audio", "subtitle"]:
        if dstreams[codec_type]:
            codecs.append(codec_type)
    streams = [
        f"{codec_type}: {', '.join(dstreams[codec_type])}" for codec_type in codecs
    ]
    streams = " | ".join(streams)
    ffmpeg_json["smart_streams"] = streams
    ffmpeg_json["format"]["screen_size"] = screen_size
    # fields can be missing (damaged video file ?): force it
    ffmpeg_json["format"]["bit_rate"] = ffmpeg_json["format"].get("bit_rate", 0)
    ffmpeg_json["format"]["duration"] = ffmpeg_json["format"].get("duration", 0)
    # duplicate title in format field
    ffmpeg_json["title"] = (
        ffmpeg_json["format"]["tags"]["title"]
        if ffmpeg_json["format"].get("tags")
        and ffmpeg_json["format"]["tags"].get("title")
        else ""
    )
    return ffmpeg_json


import os
import threading
from tkinter.messagebox import showwarning
from tkinter.filedialog import askdirectory
from datetime import datetime

class Modelo:

    # Funciones

    @staticmethod
    def seleccion_dir(rutain, rutaout, opc=None):

        if not opc:
            ruta_sel = askdirectory()
            ruta_normalizada = os.path.abspath(ruta_sel)
            rutain.set(ruta_normalizada)
        else:
            ruta_sel = askdirectory()
            ruta_normalizada = os.path.abspath(ruta_sel)
            rutaout.set(ruta_normalizada)

    @staticmethod
    def listar_dirs(cantdirs, cantarchs, rutain, rutaout, pbar):

        cantdirs = cantdirs
        cantdirs.set("0")
        cantarch = cantarchs
        cantarch.set("0")
        root_in = rutain.get()
        rootdir = root_in
        root_out = rutaout.get()
        progressbar = pbar

        def listar_dirs2():

            progressbar.start()
            ficheros_cont = 0
            carpetas_cont = 0
            with open(root_out + "/Directory_Lister.txt", "a", encoding="utf-8") as f:
                for carpeta in os.walk(rootdir):
                    a = f'\nEn Carpeta "{carpeta[0]}" Hay {len(carpeta[2])} Archivos:'
                    b = "-" * 50 + "\n"
                    carpetas_cont += 1
                    f.write(str(a) + "\n" + b)
                    cantdirs.set(str(carpetas_cont))

                    for fichero in carpeta[2]:
                        b = f' ---> {fichero}'
                        ficheros_cont += 1
                        f.write(str(b) + "\n")
                        cantarch.set(str(ficheros_cont))

                report = "*" * 80 + "\n" + f"{ficheros_cont} archivos encontrados en {carpetas_cont} carpetas."
                f.write(report + "\n")
                progressbar.stop()
                progressbar.set(100)

        if root_in and root_out != "":
            time_ahora = datetime.now()
            dir_in_var = "-"*80 + "\nCarpeta a analizar:\n".title() + root_in + "\n"
            dir_out_var = "carpeta destino reporte:\n".title() + root_out + "\n" + "-" * 80 + "\n" + str(time_ahora)\
                          + "\n" + "-" * 80
            with open(root_out + "/Directory_Lister.txt", "w", encoding="utf-8") as ff:
                ff.write(dir_in_var + "\n" + dir_out_var + "\n")
                threading.Thread(target=listar_dirs2).start()

        else:
            showwarning("Error en seleccion de directorios".title(),
                        message="deben seleccionarse tanto el directorio source como el target antes de la "
                                "ejecucion !".title())

source code/MVC Diretory lister/model.py


# Provides the handling function for the BB webpage

import threading
from selenium import webdriver
from bs4 import BeautifulSoup
from selenium.webdriver.chrome.options import Options
import requests
import json
from utility import error, headers, bb_dir, init_log, log, info, success, db_path, get_login_credentials, chromedriver_path
import os
import handler as hd

base_url = "https://shs.blackboardchina.cn/"
login_url = "https://shs.blackboardchina.cn/"
req_url = "https://shs.blackboardchina.cn/webapps/blackboard/execute/announcement?method=search&context=mybb&handle=my_announcements&returnUrl=/webapps/portal/execute/tabs/tabAction?tab_tab_group_id=_1_1&tabId=_1_1&forwardUrl=index.jsp"

class BBHandler:
    def __init__(self):
        info('Setting BB Handler...')
        self.driver = hd.init_driver()

    def run(self, username):
        info('Loading login page...')

        hd.login(
            username,
            'bb',
            self.driver,
            login_url,
            'user_id',
            'password',
        )

        info('Loading BB announcements...')
        ann_list = hd.get_targets(self.driver, req_url, "#announcementList > li")
        ann_filtered = []
        info('Filtering announcements...')
        for ann in ann_list:
            imgs = ann.select('img')
            for img in imgs:
                img_src = img["src"]
                if img_src.startswith('blob:'):
                    continue
                img_name = img_src[len("https://shs.blackboardchina.cn/") :].replace(
                    "/", "_"
                )
                self.buf_img(img_src, img_name)
                img["src"] = "/buffer/bb/{}.jpg".format(img_name)

            content = ""
            for ch in ann.children:
                content += str(ch)

            ann_filtered.append(content)

        info('Buffering BB announcements...')
        hd.write_buf(ann_filtered, os.path.join(bb_dir, username))
        success('Buffered BB announcements')

    def buf_img(self, img_src: str, img_name: str):
        cookies = {}
        for cookie in self.driver.get_cookies():
            cookies[cookie["name"]] = cookie["value"]

        img_url = img_src.replace("https", "http")

        img_path = os.path.join(bb_dir, img_name + ".jpg")
        if not os.path.exists(img_path):
            info('Buffering image: {}'.format(img_name))
            img = requests.get(img_url, headers=headers, cookies=cookies)
            with open(img_path, "wb") as img_buf:
                img_buf.write(img.content)

    def read_buf(self, username, page):
        buf_dir = os.path.join(bb_dir, username)
        buffer = hd.get_buf(buf_dir, page)

        return buffer

    def get_info(self):
        bb_info = {
            "base_url": base_url,
            "original_url": req_url
        }
        return bb_info

# init_log()
# bb_crawler = BBHandler()
# bb_crawler.run('zyd')


import numpy as np
import cv2

rows, cols = 480, 320
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, cols)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, rows)
_, frame = cap.read()

exp1 = 0.5
exp2 = 2.0
scale = 1

# concave
mapy, mapx = np.indices((rows, cols), dtype = np.float32)
mapx = 2 * mapx / (cols - 1) - 1
mapy = 2 * mapy / (rows - 1) - 1
r, theta = cv2.cartToPolar(mapx, mapy)

r[r<scale] = r[r<scale] ** exp1
mapx, mapy = cv2.polarToCart(r, theta)
mapx = ((mapx + 1) * cols - 1) / 2
mapy = ((mapy + 1) * rows - 1) / 2

# convex
mapy, mapx = np.indices((rows, cols), dtype = np.float32)
mapx = 2 * mapx / (cols - 1) - 1
mapy = 2 * mapy / (rows - 1) - 1
r, theta = cv2.cartToPolar(mapx, mapy)

r[r<scale] = r[r<scale] ** exp2
mapx, mapy = cv2.polarToCart(r, theta)
mapx = ((mapx + 1) * cols - 1) / 2
mapy = ((mapy + 1) * rows - 1) / 2

# sin, cos
mapy, mapx = np.indices((rows, cols), dtype = np.float32)
sinx = mapx + 15 * np.sin(mapy / 20)
cosy = mapy + 15 * np.cos(mapx / 20)

# mirror
maphy, maphx = np.indices((rows, cols), dtype = np.float32)
mapvy, mapvx = np.indices((rows, cols), dtype = np.float32)
maphx[ : , cols // 2 : ] = cols - maphx[ : , cols // 2 : ] - 1
mapvy[rows // 2 : , : ] = rows - mapvy[rows // 2 : , : ] - 1

while True:
    _, frame = cap.read()
    distorted_concave = cv2.remap(frame, mapx, mapy, cv2.INTER_LINEAR)
    distorted_convex = cv2.remap(frame, mapx, mapy, cv2.INTER_LINEAR)
    distorted_sin_cos = cv2.remap(frame, sinx, cosy, cv2.INTER_LINEAR)
    distorted_hmirror = cv2.remap(frame, maphx, maphy, cv2.INTER_LINEAR)
    distorted_vmirror = cv2.remap(frame, mapvx, mapvy, cv2.INTER_LINEAR)
    frame = cv2.resize(frame, (320, 480))
    r1 = np.hstack([frame, distorted_concave, distorted_convex])
    r2 = np.hstack([distorted_sin_cos, distorted_vmirror, distorted_hmirror])
    result = np.vstack([r1, r2])
    cv2.imshow("distorted", result)
    key = cv2.waitKey(1)
    if key & 0xFF == 27:
        break

cap.release()
cv2.destroyAllWindows()


"""
    爬取百度产品，并将url与产品用字典连接，并将各种产品分类
"""
import requests
import re

class BaiDu:
    def __init__(self):
        # 设置url
        self.url = 'http://www.baidu.com/more'

    def get_data(self):
        # 设置请求头
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
                          '(KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36'
        }
        # 发送请求并获取响应
        response = requests.get(self.url, headers=headers)
        return response.content

    def parse_data(self, response):
        # 从html中提取各项功能分类并存入字典中,get_text()获取文本信息
        features_dict = {}
        response1 = response.decode()
        a = 0
        pattern = r'\s*[\S|\s]*?

'
        temp = re.findall(pattern, response1)
        list2 = {}
        for item in temp:
            key = re.findall(r'', item)[0]
            values = re.findall(r'<a (.+)', item)
            list1 = []
            if a == 0:
                del values[4]
                del values[2]
                del values[0]
            list2[key] = list1
            a += 1
            for item1 in values:
                url = re.findall(r'"(http://.*?|https://.*?)"', item1)
                name = re.findall(r'>(.+?)\b', item1)
                list1.append((url[0], name[-1]))
        print(list2)
        # 返回信息字典
        return features_dict

    def run(self):
        # url
        # headers
        # 发送get请求获取响应
        response = self.get_data()
        # 从响应结果提取信息
        res = self.parse_data(response)

if __name__ == '__main__':
    a = BaiDu()
    a.run()

python/python学习小分队打卡/课程代码/爬虫/爬虫实例/1/1 爬取百度产品.py


import sys
import tempfile
import unittest

from io import StringIO
from os import path

import mock

from zelos import Zelos

DATA_DIR = path.join(
    path.dirname(path.abspath(__file__)), path.join("..", "data")
)

rule1 = """
rule testrule1
{
      meta:
        description="test rule 1"
      strings:
        $a = "Hello"
      condition:
        $a
}
"""

rule2 = """
rule testrule2
{
      meta:
        description="test rule 2"
      strings:
        $a = "World"
      condition:
        $a
}
"""

rule3 = """
rule testrule3
{
      meta:
        description="test rule 3"
      strings:
        $a = "C++"
      condition:
        $a
}
"""

expected_yaml = [
    """- cmdline_rule0:
        namespace: cmdline
        rule: rule0
        region_desc: "08176000-08177000 00001000 rwx private static_elf_helloworld, main"
        region_address: 0x8176000
        xrefs: 0
        strings:
                address: 0x8176449
                        offset: 0x449
                        value: "b'Hello World!'"
                        xrefs: 0
""",  # noqa
    """- rulefile3_testrule3:
        description: "test rule 3"
        namespace: rulefile3
        rule: testrule3
        region_desc: "08176000-08177000 00001000 rwx private static_elf_helloworld, main"
        region_address: 0x8176000
        xrefs: 0
        strings:
                address: 0x817645d
                        offset: 0x45d
                        value: "b'C++'"
                        xrefs: 0
""",  # noqa
    """- rulefile1_testrule1:
        description: "test rule 1"
        namespace: rulefile1
        rule: testrule1
        region_desc: "08176000-08177000 00001000 rwx private static_elf_helloworld, main"
        region_address: 0x8176000
        xrefs: 0
        strings:
                address: 0x8176449
                        offset: 0x449
                        value: "b'Hello'"
                        xrefs: 0
""",  # noqa
    """- rulefile2_testrule2:
        description: "test rule 2"
        namespace: rulefile2
        rule: testrule2
        region_desc: "08176000-08177000 00001000 rwx private static_elf_helloworld, main"
        region_address: 0x8176000
        xrefs: 0
        strings:
                address: 0x817644f
                        offset: 0x44f
                        value: "b'World'"
                        xrefs: 0
""",  # noqa
]

def remove_matching_lines(haystack, needles):
    result = StringIO()
    for line in haystack.split("\n"):
        if not any(needle in line for needle in needles):
            result.write(f"{line}\n")
    return result.getvalue()

class TestYaraScanPlugin(unittest.TestCase):
    def test_yarascan(self):
        # Create temp directory to store yarascan output files
        with tempfile.TemporaryDirectory() as tmpdir:
            filename1 = path.join(tmpdir, "rulefile1.yar")
            filename2 = path.join(tmpdir, "rulefile2.yar")
            filename3 = path.join(tmpdir, "rulefile3.yap")
            with open(filename1, "w") as f1, open(filename2, "w") as f2, open(
                filename3, "w"
            ) as f3:
                f1.write(rule1)
                f2.write(rule2)
                f3.write(rule3)
            testglob = path.join(tmpdir, "*.yar")
            yaml_filename = path.join(tmpdir, "yara.yaml")
            memdump_dir = path.join(tmpdir, "memdumps")

            # Init `zelos` and request yara scanning post-emulation.
            z = Zelos(
                path.join(DATA_DIR, "static_elf_helloworld"),
                trace_off=True,
                yara_file=filename3,
                yara_file_glob=testglob,
                yara_rule=r"/hello\sworld!/nocase",
                yara_memdump=memdump_dir,
                yara_outfile=yaml_filename,
                yara_xrefs=True,
                # yara_brief=True,
                # yara_pid=None,
            )
            z.start(timeout=10)

            # Invoke yarascan plugin via scripting, independent of the
            # post-emulation scanning.
            yara = z.plugins.yarascan
            yara.compile(rules=["Hello World"], files=[], glob_string=None)
            matches = list(
                yara.matches(
                    pid=z.process.pid, yamldump=yaml_filename, brief=True
                )
            )
            self.assertEqual(1, len(matches))
            self.assertEqual(
                matches[0].info(brief=True), "Matched rule: cmdline.rule0"
            )

            # Test missing `yara-python` dependency
            with mock.patch.dict(sys.modules, {"yara": None}):
                self.assertFalse(yara.import_yara())
            self.assertTrue(yara.import_yara())

            # `close` triggers the yara memory scan requested via
            # the `yara_` arguments during `zelos` initialization.
            z.close()

            # Load in the yaml file generated by yarascan for validation
            with open(yaml_filename, "r") as f:
                yaml = f.read()
            # PID may change, omit it from test
            yaml = remove_matching_lines(yaml, ["pid"])
            yaml = yaml.replace("\t", "        ")

            # Check each yaml entry individually, since `yara-python`
            # match order is not deterministic.
            for expected in expected_yaml:
                self.assertTrue(expected in yaml)

    def test_yarascan_no_xrefs_issue_129(self):
        # Create temp directory to store yarascan output files
        # Init `zelos` and request yara scanning post-emulation.
        z = Zelos(
            path.join(DATA_DIR, "static_elf_helloworld"),
            trace_off=True,
            yara_rule=r"/hello\sworld!/nocase",
        )
        z.start(timeout=10)

        yara = z.plugins.yarascan
        yara.compile(rules=["Hello World"], files=[], glob_string=None)
        matches = list(yara.matches(pid=z.process.pid, xrefs=False))
        # Check whether we are handling the strings method correctly,
        # specifically when xrefs is false.
        matches[0].strings

if __name__ == "__main__":
    unittest.main()


import threading as thr
import node as nd
import filechunk as fc
import numpy as np
import time

BASE_PORT = 30000
CMD_PREFIX = '>> '
MUSIC = ['SalmonLikeTheFish - Glacier.mp3', 'SalmonLikeTheFish - Shenandoah.mp3', 'SalmonLikeTheFish - Zion.mp3']

if __name__ == "__main__":
    nodes = []
    threads = []
    node_count = int(input('Node count: '))
    for i in range(node_count):
        nodes.append(nd.Node(('127.0.0.1', BASE_PORT+i)))
        threads.append(thr.Thread(target=nodes[i].listen))
    for i in range(node_count):
        threads[i].start()
        while nodes[i].id == None: # Sincronização
            time.sleep(5e-3)

    try:
        for i in range(1, node_count):
            nodes[i].enter_dht(nodes[0].addr)
    except TimeoutError:
        for node in nodes:
            print(f'{node.prev} (prev) - {node.addr} - {node.next} (next)')

    cmd = input(CMD_PREFIX)
    while cmd != 'exit':
        args = cmd.split(' ')
        cmd = args.pop(0)
        if cmd == 'echo':
            nodes[0].echo()
        elif cmd == 'print':
            for node in nodes:
                print(f'{node.prev} (prev) - {node.addr} - {node.next} (next)')
        elif cmd == 'find' and len(args) == 2:
            song = MUSIC[int(args[0])]
            nodes[0].find(song, int(args[1]))
        elif cmd == 'put' and len(args) == 1:
            song = MUSIC[int(args[0])]
            fc.add_file('music', song, [node.addr for node in nodes])
        elif cmd == 'get' and len(args) == 2:
            song = MUSIC[int(args[0])]
            fc.get_file(args[1], song, [node.addr for node in nodes])
        elif cmd == 'count':
            chunk_count = [len(node.dict) for node in nodes]
            if len(args) == 1 and args[0] == 'std':
                print(np.std(chunk_count))
            else:
                print(chunk_count)
        cmd = input(CMD_PREFIX)
    for node in nodes:
        node.alive = False
    for t in threads:
        t.join()


class Dog():
    def __init__(self,name,age,breed,owner):
        self.name = name
        self.age = age
        self.breed = breed
        self.owner = owner

class Person():
    def __init__(self,name,age):
        self.name = name
        self.age = age

Son = Person('Son',31)
Min = Dog('Min',12,'Huskie',Son)

print(Min.owner.name)