import video
import funkcijos
import plotly.graph_objects as go
import math

dataList = list()

eUploader = 0
eAge = 0
eCategory = 0
eLength = 0
eViews = 0
eRate = 0
eRatings = 0
eComments = 0

atributeNames = list()
missingValues = list()
avarages = list()
medians = list()
mins = list()
maxs = list()
cardinalities = list()
quartiles1st = list()
quartiles2nd = list()
standartDeviations = list()

atributeNames2 = list()
missingValues2 = list()
cardinalities2 = list()
modes2nd = list()
modeRates = list()
modePercents = list()
modes = list()
mode2ndRates = list()
mode2ndPercents = list()

def ReadData():
    dataFile = open("Good data with commas.csv", "r")

    dataRL = dataFile.readlines()

    for x in dataRL:

        wordList = x.split(",")

        #print(f"{wordList[0]}|{wordList[1]}|{wordList[2]}|{wordList[3]}|{wordList[4]}|{wordList[5]}|{wordList[6]}|{wordList[7]}")

        global eUploader
        if not wordList[0]: eUploader += 1
        global eAge
        if not wordList[1]: eAge += 1
        global eCategory
        if not wordList[2]: eCategory += 1
        global eLength
        if not wordList[3]: eLength += 1
        global eViews
        if not wordList[4]: eViews += 1
        global eRate
        if not wordList[5]: eRate += 1
        global eRatings
        if not wordList[6]: eRatings += 1
        global eComments
        if not wordList[7]: eComments += 1

        dataList.append(video.Video(wordList[0], wordList[1], wordList[2], wordList[3], wordList[4], wordList[5], wordList[6], wordList[7]))

    dataFile.close()

ReadData()

def ProcessAge():
    global atributeNames
    global missingValues
    global avarages
    global medians
    global mins
    global maxs
    global cardinalities
    global quartiles1st
    global quartiles2nd
    global standartDeviations

    valueList = list()
    valueSet = set()

    for x in dataList:
        if x.age is not None:
            valueList.append(x.age)
            valueSet.add(x.age)

    atributeNames.append('Age')
    missingValues.append(100 / (len(valueList) + eAge) * eAge)
    avarages.append(funkcijos.Funkcijos.Vidurkis(None, valueList))
    medians.append(funkcijos.Funkcijos.Mediana(None, valueList))
    mins.append(funkcijos.Funkcijos.Minimum(None, valueList))
    maxs.append(funkcijos.Funkcijos.Maximum(None, valueList))
    cardinalities.append(len(valueSet))
    quartiles = funkcijos.Funkcijos.Quartiles(None, valueList)
    quartiles1st.append(quartiles[0])
    quartiles2nd.append(quartiles[1])
    standartDeviations.append(funkcijos.Funkcijos.StandartDeviation(None,valueList))

def ProcessLength():
    global atributeNames
    global missingValues
    global avarages
    global medians
    global mins
    global maxs
    global cardinalities
    global quartiles1st
    global quartiles2nd
    global standartDeviations

    valueList = list()
    valueSet = set()

    for x in dataList:
        if x.length is not None:
            valueList.append(x.length)
            valueSet.add(x.length)

    atributeNames.append('Length')
    missingValues.append(100 / (len(valueList) + eLength) * eLength)
    avarages.append(funkcijos.Funkcijos.Vidurkis(None, valueList))
    medians.append(funkcijos.Funkcijos.Mediana(None, valueList))
    mins.append(funkcijos.Funkcijos.Minimum(None, valueList))
    maxs.append(funkcijos.Funkcijos.Maximum(None, valueList))
    cardinalities.append(len(valueSet))
    quartiles = funkcijos.Funkcijos.Quartiles(None, valueList)
    quartiles1st.append(quartiles[0])
    quartiles2nd.append(quartiles[1])
    standartDeviations.append(funkcijos.Funkcijos.StandartDeviation(None,valueList))

def ProcessViews():
    global atributeNames
    global missingValues
    global avarages
    global medians
    global mins
    global maxs
    global cardinalities
    global quartiles1st
    global quartiles2nd
    global standartDeviations

    valueList = list()
    valueSet = set()

    for x in dataList:
        if x.views is not None:
            valueList.append(x.views)
            valueSet.add(x.views)

    atributeNames.append('Views')
    missingValues.append(100 / (len(valueList) + eViews) * eViews)
    avarages.append(funkcijos.Funkcijos.Vidurkis(None, valueList))
    medians.append(funkcijos.Funkcijos.Mediana(None, valueList))
    mins.append(funkcijos.Funkcijos.Minimum(None, valueList))
    maxs.append(funkcijos.Funkcijos.Maximum(None, valueList))
    cardinalities.append(len(valueSet))
    quartiles = funkcijos.Funkcijos.Quartiles(None, valueList)
    quartiles1st.append(quartiles[0])
    quartiles2nd.append(quartiles[1])
    standartDeviations.append(funkcijos.Funkcijos.StandartDeviation(None,valueList))

def ProcessRate():
    global atributeNames
    global missingValues
    global avarages
    global medians
    global mins
    global maxs
    global cardinalities
    global quartiles1st
    global quartiles2nd
    global standartDeviations

    valueList = list()
    valueSet = set()

    for x in dataList:
        if x.rate is not None:
            valueList.append(x.rate)
            valueSet.add(x.rate)

    atributeNames.append('Rate')
    missingValues.append(100 / (len(valueList) + eRate) * eRate)
    avarages.append(funkcijos.Funkcijos.Vidurkis(None, valueList))
    medians.append(funkcijos.Funkcijos.Mediana(None, valueList))
    mins.append(funkcijos.Funkcijos.Minimum(None, valueList))
    maxs.append(funkcijos.Funkcijos.Maximum(None, valueList))
    cardinalities.append(len(valueSet))
    quartiles = funkcijos.Funkcijos.Quartiles(None, valueList)
    quartiles1st.append(quartiles[0])
    quartiles2nd.append(quartiles[1])
    standartDeviations.append(funkcijos.Funkcijos.StandartDeviation(None,valueList))

def ProcessRatings():
    global atributeNames
    global missingValues
    global avarages
    global medians
    global mins
    global maxs
    global cardinalities
    global quartiles1st
    global quartiles2nd
    global standartDeviations

    valueList = list()
    valueSet = set()

    for x in dataList:
        if x.ratings is not None:
            valueList.append(x.ratings)
            valueSet.add(x.ratings)

    atributeNames.append('Ratings')
    missingValues.append(100 / (len(valueList) + eRatings) * eRatings)
    avarages.append(funkcijos.Funkcijos.Vidurkis(None, valueList))
    medians.append(funkcijos.Funkcijos.Mediana(None, valueList))
    mins.append(funkcijos.Funkcijos.Minimum(None, valueList))
    maxs.append(funkcijos.Funkcijos.Maximum(None, valueList))
    cardinalities.append(len(valueSet))
    quartiles = funkcijos.Funkcijos.Quartiles(None, valueList)
    quartiles1st.append(quartiles[0])
    quartiles2nd.append(quartiles[1])
    standartDeviations.append(funkcijos.Funkcijos.StandartDeviation(None,valueList))

def ProcessComments():
    global atributeNames
    global missingValues
    global avarages
    global medians
    global mins
    global maxs
    global cardinalities
    global quartiles1st
    global quartiles2nd
    global standartDeviations

    valueList = list()
    valueSet = set()

    for x in dataList:
        if x.comments is not None:
            valueList.append(x.comments)
            valueSet.add(x.comments)

    atributeNames.append('Comments')
    missingValues.append(100 / (len(valueList) + eComments) * eComments)
    avarages.append(funkcijos.Funkcijos.Vidurkis(None, valueList))
    medians.append(funkcijos.Funkcijos.Mediana(None, valueList))
    mins.append(funkcijos.Funkcijos.Minimum(None, valueList))
    maxs.append(funkcijos.Funkcijos.Maximum(None, valueList))
    cardinalities.append(len(valueSet))
    quartiles = funkcijos.Funkcijos.Quartiles(None, valueList)
    quartiles1st.append(quartiles[0])
    quartiles2nd.append(quartiles[1])
    standartDeviations.append(funkcijos.Funkcijos.StandartDeviation(None,valueList))

def ProcessUploader():
    global atributeNames2
    global missingValues2
    global cardinalities2
    global modes
    global modeRates
    global modePercents
    global modes2nd
    global mode2ndRates
    global mode2ndPercents

    valueList = list()
    valueSet = set()

    for x in dataList:
        if x.uploader is not None:
            valueList.append(x.uploader)
            valueSet.add(x.uploader)

    atributeNames2.append("Uploader")
    missingValues2.append(100 / (len(valueList) + eUploader) * eUploader)
    cardinalities2.append(len(valueSet))
    modes.append(funkcijos.Funkcijos.Moda(None, valueList))
    modeRates.append(valueList.count(funkcijos.Funkcijos.Moda(None, valueList)))
    modePercents.append(100 / len(valueList) * valueList.count(funkcijos.Funkcijos.Moda(None, valueList)))
    modes2nd.append(funkcijos.Funkcijos.Moda2nd(None, valueList))
    mode2ndRates.append(valueList.count(funkcijos.Funkcijos.Moda2nd(None, valueList)))
    mode2ndPercents.append(100 / len(valueList) * valueList.count(funkcijos.Funkcijos.Moda2nd(None, valueList)))

def ProcessCategory():
    global atributeNames2
    global missingValues2
    global cardinalities2
    global modes
    global modeRates
    global modePercents
    global modes2nd
    global mode2ndRates
    global mode2ndPercents

    valueList = list()
    valueSet = set()

    for x in dataList:
        if x.category is not None:
            valueList.append(x.category)
            valueSet.add(x.category)

    atributeNames2.append("Category")
    missingValues2.append(100 / (len(valueList) + eCategory) * eCategory)
    cardinalities2.append(len(valueSet))
    modes.append(funkcijos.Funkcijos.Moda(None, valueList))
    modeRates.append(valueList.count(funkcijos.Funkcijos.Moda(None, valueList)))
    modePercents.append(100 / len(valueList) * valueList.count(funkcijos.Funkcijos.Moda(None, valueList)))
    modes2nd.append(funkcijos.Funkcijos.Moda2nd(None, valueList))
    mode2ndRates.append(valueList.count(funkcijos.Funkcijos.Moda2nd(None, valueList)))
    mode2ndPercents.append(100 / len(valueList) * valueList.count(funkcijos.Funkcijos.Moda2nd(None, valueList)))

ProcessAge()
ProcessLength()
ProcessViews()
ProcessRate()
ProcessRatings()
ProcessComments()

fig = go.Figure(
    data=[go.Table(header=dict(values=['Atributas', 'Trukstamos reiksmes %', 'Vidurkis','Mediana','Minimumas','Maximumas','Kardinalumas','Pirmas kvartilis','Trecias Kvartilis', 'Standartinis nuokrypis']),
cells=dict( values=[ atributeNames, [ round(e, 2) for e in missingValues ], [ round(e, 2) for e in avarages ], medians, mins, maxs, cardinalities, quartiles1st, quartiles2nd, [ round(e, 2) for e in standartDeviations ] ] ))
])

ProcessUploader()
ProcessCategory()

fig2 = go.Figure(
    data=[go.Table(header=dict(values=['Atributas', 'Trukstamos reiksmes %', 'Kardinalumas','Moda','Modos Daznis','Moda %','2-oji Moda','2-osios Modos Daznis','2-oji Moda %']),
cells=dict( values=[ atributeNames2, [ round(e, 2) for e in missingValues2 ], cardinalities2, modes, modeRates, [ round(e, 2) for e in modePercents ], modes2nd, mode2ndRates, [ round(e, 2) for e in mode2ndPercents ] ] ))
])

fig.write_html('Breziniai\Tolydieji_duomenys.html', auto_open=True)
fig2.write_html('Breziniai\Kategoriniai_duomenys.html', auto_open=True)

def drawHists():
    global dataList

    valueList = list()

    for x in dataList:
        if x.age is not None:
            valueList.append(x.age)

    HistAge = go.Figure(data=[go.Histogram(x=valueList)])
    HistAge.update_layout(xaxis_title_text='Amzius', yaxis_title_text='Kiekis')
    HistAge.write_html('Breziniai\Amziaus_Hist.html', auto_open=True)

    valueList = list()

    for x in dataList:
        if x.length is not None:
            valueList.append(x.length)

    HistLength = go.Figure(data=[go.Histogram(x=valueList)])
    HistLength.update_layout(xaxis_title_text='Ilgis', yaxis_title_text='Kiekis')
    HistLength.write_html('Breziniai\Ilgis_Hist.html', auto_open=True)

    valueList = list()

    for x in dataList:
        if x.views is not None:
            valueList.append(x.views)

    HistViews = go.Figure(data=[go.Histogram(x=valueList)])
    HistViews.update_layout(xaxis_title_text='Perziuros', yaxis_title_text='Kiekis')
    HistViews.write_html('Breziniai\Perziuros_Hist.html', auto_open=True)

    valueList = list()

    for x in dataList:
        if x.rate is not None:
            valueList.append(x.rate)

    HistRate = go.Figure(data=[go.Histogram(x=valueList)])
    HistRate.update_layout(xaxis_title_text='Rate', yaxis_title_text='Kiekis')
    HistRate.write_html('Breziniai\Rate_Hist.html', auto_open=True)

    valueList = list()

    for x in dataList:
        if x.ratings is not None:
            valueList.append(x.ratings)

    HistRatings = go.Figure(data=[go.Histogram(x=valueList)])
    HistRatings.update_layout(xaxis_title_text='Reitingai', yaxis_title_text='Kiekis')
    HistRatings.write_html('Breziniai\Reitingai_Hist.html', auto_open=True)

    valueList = list()

    for x in dataList:
        if x.comments is not None:
            valueList.append(x.comments)

    HistComments = go.Figure(data=[go.Histogram(x=valueList)])
    HistComments.update_layout(xaxis_title_text='Komentarai', yaxis_title_text='Kiekis')
    HistComments.write_html('Breziniai\Komentarai_Hist.html', auto_open=True)

def scatterAndSplom():
    global dataList

    ageList = list()
    lengthList = list()
    viewsList = list()
    rateList = list()
    ratingsList = list()
    commentsList = list()

    for x in dataList:
        if x.age is not None:
            ageList.append(x.age)
        if x.length is not None:
            lengthList.append(x.length)
        if x.views is not None:
            viewsList.append(x.views)
        if x.rate is not None:
            rateList.append(x.rate)
        if x.ratings is not None:
            ratingsList.append(x.ratings)
        if x.comments is not None:
            commentsList.append(x.comments)

    Splom=go.Splom(dimensions=[dict(label='Amzius', values=ageList),
                                dict(label='Ilgis', values=lengthList),
                                dict(label='Perziuros', values=viewsList),
                                dict(label='Rate', values=rateList),
                                dict(label='Reitingai', values=ratingsList),
                                dict(label='Komentarai', values=commentsList)])

    SplomFig = go.Figure(data=Splom)
    SplomFig.write_html('Breziniai\Splom.html', auto_open=True)

    ScatterFigKor1 = go.Figure(data=go.Scatter(x=lengthList, y=rateList, mode="markers"))
    ScatterFigKor1.update_layout(xaxis_title_text='Ilgis', yaxis_title_text='Ivertinimas')
    ScatterFigKor1.write_html('Breziniai\Scatter_Length_Rate_Kor.html', auto_open=True)

    ScatterFigKor2 = go.Figure(data=go.Scatter(x=ageList, y=rateList, mode="markers"))
    ScatterFigKor2.update_layout(xaxis_title_text='Amzius', yaxis_title_text='Ivertinimas')
    ScatterFigKor2.write_html('Breziniai\Scatter_Age_Rate_Kor.html', auto_open=True)

    ScatterFigNekor1 = go.Figure(data=go.Scatter(x=rateList, y=commentsList, mode="markers"))
    ScatterFigNekor1.update_layout(xaxis_title_text='Ivertinimas', yaxis_title_text='Komentarai')
    ScatterFigNekor1.write_html('Breziniai\Scatter_Rate_Comments_Nekor.html', auto_open=True)

    ScatterFigNekor2 = go.Figure(data=go.Scatter(x=rateList, y=ratingsList, mode="markers"))
    ScatterFigNekor2.update_layout(xaxis_title_text='Ivertinimas', yaxis_title_text='Ivertinimu kiekis')
    ScatterFigNekor2.write_html('Breziniai\Scatter_Rate_Ratings_Nekor.html', auto_open=True)

def barPlots():
    global dataList
    categoriesList = list()
    categoriesCount = list()
    for x in dataList:
        if categoriesList.__contains__(x.category):
            categoriesCount[categoriesList.index(x.category)] += x.views
        else:
            categoriesList.append(x.category)
            categoriesCount.append(x.views)

    barCategoriesViewsFig = go.Figure([go.Bar(x=categoriesList, y=categoriesCount)])
    barCategoriesViewsFig.update_layout(xaxis_title_text='Kategorija', yaxis_title_text='Perziuru kiekis')
    barCategoriesViewsFig.write_html('Breziniai\\bar_Cat_Views.html', auto_open=True)

    categoriesList = list()
    categoriesCount = list()
    for x in dataList:
        if categoriesList.__contains__(x.category):
            categoriesCount[categoriesList.index(x.category)] += x.views
        else:
            categoriesList.append(x.category)
            categoriesCount.append(x.rate)

    barCategoriesRatesFig = go.Figure([go.Bar(x=categoriesList, y=categoriesCount)])
    barCategoriesRatesFig.update_layout(xaxis_title_text='Kategorija', yaxis_title_text='Ivertinmu suma')
    barCategoriesRatesFig.write_html('Breziniai\\bar_Cat_Rates.html', auto_open=True)

def boxPlots():
    global dataList
    categoriesList = list()
    categoriesCount = list()
    for x in dataList:
        if categoriesList.__contains__(x.category):
            categoriesCount[categoriesList.index(x.category)].append(x.views)
        else:
            categoriesList.append(x.category)
            newList = list()
            newList.append(x.views)
            categoriesCount.append(newList)

    boxCategoriesViewsFig = go.Figure()
    for x in range(len(categoriesCount) - 1):
        boxCategoriesViewsFig.add_trace(go.Box(y=categoriesCount[x], name=categoriesList[x]))
    boxCategoriesViewsFig.write_html('Breziniai\\box_Cat_Views.html', auto_open=True)

    categoriesList = list()
    categoriesCount = list()
    for x in dataList:
        if categoriesList.__contains__(x.category):
            categoriesCount[categoriesList.index(x.category)].append(x.rate)
        else:
            categoriesList.append(x.category)
            newList = list()
            newList.append(x.rate)
            categoriesCount.append(newList)

    boxCategoriesViewsFig = go.Figure()
    for x in range(len(categoriesCount) - 1):
        boxCategoriesViewsFig.add_trace(go.Box(y=categoriesCount[x], name=categoriesList[x]))
    boxCategoriesViewsFig.write_html('Breziniai\\box_Cat_Rate.html', auto_open=True)

drawHists()
scatterAndSplom()
barPlots()
boxPlots()

forCov = []
covAverages = []
covAverages.append(avarages[0])
covAverages.append(avarages[1])
covAverages.append(avarages[2])
covAverages.append(avarages[3])
covAverages.append(avarages[4])
covAverages.append(avarages[5])
for x in dataList:
    forCov.append([x.age, x.length, x.views, x.rate, x.ratings, x.comments])

cov = []
for i in range(0, 6):
    for j in range(0, 6):
        sum = 0.0
        for x in forCov:
            if x[i] == None or x[j] == None:
                continue
            else:
                sum = sum + ((x[i] - covAverages[i]) * (x[j] - covAverages[j]))
        if j == 0:
            cov.append([sum / (len(forCov) - 1)])
        else:
            cov[i].append(sum / (len(forCov) - 1))

atributeNamesWithoutSpace = atributeNames.copy()
atributeNames.insert(0," ")

fig3 = go.Figure(
    data=[go.Table(header=dict(values=atributeNames),
cells=dict( values=[ atributeNamesWithoutSpace, cov[0], cov[1], cov[2], cov[3], cov[4], cov[5]] ))
])

fig3.write_html('Breziniai\\Kovariacijos lentele.html', auto_open=True)

cor = []
for i in range(0, 6):
    for j in range(0, 6):
        if j == 0:
            cor.append([cov[i][j] / (standartDeviations[i] * standartDeviations[j])])
        else:
            cor[i].append(cov[i][j] / (standartDeviations[i] * standartDeviations[j]))

fig4 = go.Figure(
    data=[go.Table(header=dict(values=atributeNames),
cells=dict( values=[ atributeNamesWithoutSpace, cor[0], cor[1], cor[2], cor[3], cor[4], cor[5]] ))
])

fig4.write_html('Breziniai\\Koreliacijos lentele.html', auto_open=True)

fig5 = go.Figure(data=go.Heatmap(z=cor, x = atributeNamesWithoutSpace, y = atributeNamesWithoutSpace))
fig5.write_html('Breziniai\\Koreliacijos matrica.html', auto_open=True)

NormalizedFile = open("Normalized data.csv", "w+")
NormalizedList = list()

for x in dataList:
    nAge = (x.age - avarages[0]) / standartDeviations[0]
    nLength = (x.length - avarages[1]) / standartDeviations[1]
    nViews = (x.views - avarages[2]) / standartDeviations[2]
    nRate = (x.rate - avarages[3]) / standartDeviations[3]
    nRatings = (x.ratings - avarages[4]) / standartDeviations[4]
    nComments = (x.comments - avarages[5]) / standartDeviations[5]
    NormalizedList.append(video.Video(x.uploader, nAge, x.category, nLength, nViews, nRate, nRatings, nComments))

for x in NormalizedList:
    NormalizedFile.write(x.ToStringWithCommas() + "\n")


# This script will create all you need for a hunt group and tie it all together
# This creates a Line Group, Hunt List, and Pilot
# There's also logic to specify if you want calls to rona to a VM box
# If you want calls to rona to another number other than a VM box you will need to tweak the code a bit

from lxml import etree
from requests import Session
from requests.auth import HTTPBasicAuth
from zeep import Client, Settings, Plugin, xsd
from zeep.transports import Transport
from zeep.exceptions import Fault
import sys
import urllib3
import random

# Edit .env file to specify your Webex site/user details
import os
from dotenv import load_dotenv
load_dotenv()

# Change to true to enable output of request/response headers and XML
DEBUG = False

# The WSDL is a local file in the working directory, see README
# WSDL_FILE = 'schema/AXLAPI.wsdl'
WSDL_FILE = '<your wsdl file path here>'

# This class lets you view the incoming and outgoing http headers and XML

class MyLoggingPlugin( Plugin ):

    def egress( self, envelope, http_headers, operation, binding_options ):

        # Format the request body as pretty printed XML
        xml = etree.tostring( envelope, pretty_print = True, encoding = 'unicode')

        print( f'\nRequest\n-------\nHeaders:\n{http_headers}\n\nBody:\n{xml}' )

    def ingress( self, envelope, http_headers, operation ):

        # Format the response body as pretty printed XML
        xml = etree.tostring( envelope, pretty_print = True, encoding = 'unicode')

        print( f'\nResponse\n-------\nHeaders:\n{http_headers}\n\nBody:\n{xml}' )

# The first step is to create a SOAP client session
session = Session()

# We avoid certificate verification by default
# And disable insecure request warnings to keep the output clear
session.verify = False
urllib3.disable_warnings( urllib3.exceptions.InsecureRequestWarning )

# To enabled SSL cert checking (recommended for production)
# place the CUCM Tomcat cert .pem file in the root of the project
# and uncomment the line below

# session.verify = 'changeme.pem'

# Add Basic Auth credentials
session.auth = HTTPBasicAuth( os.getenv( 'AXL_USERNAME' ), os.getenv( 'AXL_PASSWORD' ) )

# Create a Zeep transport and set a reasonable timeout value
transport = Transport( session = session, timeout = 10 )

# strict=False is not always necessary, but it allows zeep to parse imperfect XML
settings = Settings( strict = False, xml_huge_tree = True )

# If debug output is requested, add the MyLoggingPlugin callback
plugin = [ MyLoggingPlugin() ] if DEBUG else [ ]

# Create the Zeep client with the specified settings
client = Client( WSDL_FILE, settings = settings, transport = transport,
        plugins = plugin )

# Create the Zeep service binding to AXL at the specified CUCM
service = client.create_service( '{http://www.cisco.com/AXLAPIService/}AXLAPIBinding',
                                f'https://{os.getenv( "CUCM_ADDRESS" )}:8443/axl/' )

print('')
print('Add Hunt Group Script')
print('')
siteCode=input('Enter 4 Digit Site Code: ') # you can change siteCode to what you want, like huntGroupName maybe
locationType=input('Enter Location Type: ') # optional, you can remove this and just use site sideCode
globalName=(f'{siteCode}_{locationType}')
print('')
print('Department name would be like Front_Office or Cash_Room')
print('DO NOT include any spaces in name')
print('')
deptName=input('Enter Dept Name: ')
print('')
extension=input('Enter Pilot Extension: ')
print('')
# You need to have a RONA location.  We can't let calls ring forever
ronaToNumber=input('Enter where calls RONA to: ')
print('')

# Checks to see if RONA is a voicemail so it knows to set the *
isVM=input('Is RONA number a Unity VM box? (Y/N): ')
choice=False
while choice == False:
    isVM=input('Yes or No: ')
    if isVM.upper() == 'Y':
        ronaTo=( '*' + ronaToNumber )
        mask=( ronaToNumber )
        choice=True
    elif isVM.upper() == 'N':
        ronaTo=( ronaToNumber )
        mask=('')
        choice=True
    else:
        print('Invalid selection, please try again.')

# This will do its best to pick a CM Group to help maintain balance between active subscribers
# if you only have 1 active subscriber with 1 backup, you can remove this code and just specify your CM group in the
# hunt list creation part by putting cucmGroup=('<your cucm group'>) above with the user input variables
# Optional Begin
rando=random.randint(1,1000)
iRemainder = (rando % 2)
if iRemainder == 0:
    cucmGroup = '<enter your CM group here>'
else:
    cucmGroup = '<enter your CM group here>'
# Optional End

# Create Line Group
lineGroup = {
    'name': ( f'{globalName}_{deptName}_LG' ),
    'distributionAlgorithm': 'Broadcast',
    'rnaReversionTimeOut': '32',
    'huntAlgorithmNoAnswer': 'Try next member; then, try next group in Hunt List',
    'huntAlgorithmBusy': 'Try next member; then, try next group in Hunt List',
    'huntAlgorithmNotAvailable': 'Try next member; then, try next group in Hunt List'
}

# Execute the addLineGroup request
try:
    resp = service.addLineGroup( lineGroup )

except Fault as err:
    print( f'Zeep error: addLineGroup: { err }' )
    sys.exit( 1 )

print( '\naddLineGroup response:\n' )
print( resp,'\n' )

# Create Hunt List
huntList = {
    'name': ( f'{globalName}_{deptName}_HL' ),
    'description': ( f'{globalName}_{deptName}_HL'),
    'callManagerGroupName': (cucmGroup),
    'routeListEnabled': 'true',
    'voiceMailUsage': 'true',
    'members':
        {
        'member':
            {
            'lineGroupName': ( f'{globalName}_{deptName}_LG' ),
            'selectionOrder': "1"
            }
        }
}

# Execute the addHuntList request
try:
    resp = service.addHuntList( huntList )

except Fault as err:
    print( f'Zeep error: addHuntList: { err }' )
    sys.exit( 1 )

print( '\naddHuntList response:\n' )
print( resp,'\n' )

# Create Pilot Number
huntPilot = {
    'pattern': (extension),
    'description': ( f'{globalName}_{deptName}_Pilot' ),
    'routePartitionName': ('<your partition here>'),
    'patternUrgency': 'false',
    'patternPrecedence': '',
    'provideOutsideDialtone': 'false',
    'huntListName': ( f'{globalName}_{deptName}_HL' ),
    'alertingName': ( '""' + globalName + '_' + deptName + '""'), # need "" quotes because in CUCM 12.5x hunt group name doesn't pass to clients phones
    'asciiAlertingName': ( f'{globalName}_{deptName}' ),
    'maxHuntduration': '32',
    'blockEnable': 'false',
    'useCallingPartyPhoneMask': '',
# if site needs to route calls that are busy or no answer to another destination, need to include the following and set destination
    'forwardHuntNoAnswer':
        {
        'usePersonalPreferences': 'false',
        'destination': ( ronaTo ),
        'callingSearchSpaceName': ( '<your calling search space here>' )
        },
    'forwardHuntBusy':
        {
        'usePersonalPreferences': 'false',
        'destination': ( ronaTo ),
        'callingSearchSpaceName': ( '<your calling search space here>' )
        },
    'calledPartyTransformationMask': ( mask )

# if site is sending calls to VM that does NOT = pilot number then you need to include the following and enter the VM Extension
#    'calledPartyTransformationMask': (ronaTo)
}

# Execute the addHuntPilot request
try:
    resp = service.addHuntPilot( huntPilot )

except Fault as err:
    print( f'Zeep error: addHuntPilot: { err }' )
    sys.exit( 1 )

print( '\naddHuntPilot response:\n' )
print( resp,'\n' )


from setuptools import setup

install_requires = [
    # NOTE: Apache Beam tests depend on this library and cannot
    # currently upgrade their httplib2 version.
    # Please see https://github.com/googleapis/google-api-python-client/pull/84
    "httplib2>=0.9.2,<1dev",
    "google-auth>=1.16.0",
    "google-auth-httplib2>=0.0.3",
    "google-api-core>=1.18.0,<2dev",
    "google-api-python-client",
    "google",
    "timeout_decorator",
    "unittest2"
]

setup(
   name='vm_network_migration',
   version='1.0',
   description='',
   author='',
   author_email='',
   test_suite = 'tests',
   packages=['vm_network_migration'],  #same as name
   install_requires=install_requires, #external packages as dependencies
)


from django.shortcuts import render, redirect, reverse
from django.contrib.auth import logout
from django.contrib.auth.views import LoginView, LogoutView, login_required

@login_required(login_url='accounts:login')
def logoutview(request):
    logout(request)
    return redirect('accounts:login')

@login_required(login_url='accounts:login')
def profileview(request):
    context = {}
    return render(request, 'accounts/profile.html', context)

class Login(LoginView):
    template_name = 'accounts/login.html'
    next_page = 'accounts:profile'
    redirect_authenticated_user = True


import functools

print("******* Recursive and Memoization *******")

@functools.lru_cache(maxsize=None)
def grid_traveller(m,n):
    if (m == 1 and n == 1):
        return 1
    elif (m == 0 or n==0 ):
        return 0
    else:
        return (grid_traveller(m-1,n)+grid_traveller(m,n-1))

print(grid_traveller(1,1))   # 1
print(grid_traveller(2,3))   # 3
print(grid_traveller(3,2))   # 3
print(grid_traveller(3,3))   # 6
print(grid_traveller(18,18)) # 2333606220

# tabulation

print("******* Tabulation *******")

def grid_traveller2(m,n):
    table = []
    for i in range(m+1):
        table.append([0 for i in range(n+1)])
    table[1][1] = 1
    for i in range(m+1):
        for x in range(n+1):
            current = table[i][x]
            if x+1 <= n:
                table[i][x+1] += current
            if i+1 <=m:
                table[i+1][x] += current
    return table[m][n]

print(grid_traveller2(1,1))   # 1
print(grid_traveller2(2,3))   # 3
print(grid_traveller2(3,2))   # 3
print(grid_traveller2(3,3))   # 6
print(grid_traveller2(18,18)) # 2333606220


"""
Script to install Souma on OsX, Windows, and Unix

Usage:
    python package.py py2app
    python package.py py2exe
"""
import ez_setup
import numpy  # important for py2exe to work
ez_setup.use_setuptools()

import sys
import os
from esky.bdist_esky import Executable
from setuptools import setup

if sys.platform == 'win32':
    import py2exe

APP = ['run.py', ]

""" Read current version identifier as recorded in `souma/__init__.py` """
with open("__init__.py", 'rb') as f:
    VERSION = f.readline().split("=")[1].strip().replace('"', '')

""" Compile list of static files """
with open(".gitignore") as f:
    ignorefiles = [l.strip() for l in f.readlines()]

DATA_FILES = [('', ['__init__.py'])]
for datadir in ['templates', 'static']:
    for root, dirs, files in os.walk(datadir):
        DATA_FILES.append((root, [os.path.join(root, fn) for fn in files if fn not in ignorefiles]))

""" Modules imported using import() need to be manually specified here """
INCLUDES = [
    "web_ui",
    "argparse",
    "jinja2.ext",
    "sqlalchemy.dialects.sqlite",
    "sqlalchemy.ext.declarative",
    "wtforms.ext",
    "wtforms.ext.csrf",
    "flask",
    "flask_sqlalchemy",
    "flask.views",
    "flask.signals",
    "flask.helpers",
    "flask.ext",
    "flaskext",
    "flaskext.uploads",
    "flask_misaka",
    "flask_wtf",
    "sqlalchemy.orm",
    "sqlalchemy.event",
    "sqlalchemy.ext.declarative",
    "sqlalchemy.engine.url",
    "sqlalchemy.connectors.mxodbc",
    "sqlalchemy.connectors.mysqldb",
    "sqlalchemy.connectors.zxJDBC",
    "sqlalchemy.dialects.sqlite.base",
    "sqlalchemy.dialects.sybase.base",
    "sqlalchemy.dialects.sybase.mxodbc",
    "sqlalchemy.engine.base",
    "sqlalchemy.engine.default",
    "sqlalchemy.engine.interfaces",
    "sqlalchemy.engine.reflection",
    "sqlalchemy.engine.result",
    "sqlalchemy.engine.strategies",
    "sqlalchemy.engine.threadlocal",
    "sqlalchemy.engine.url",
    "sqlalchemy.engine.util",
    "sqlalchemy.event.api",
    "sqlalchemy.event.attr",
    "sqlalchemy.event.base",
    "sqlalchemy.event.legacy",
    "sqlalchemy.event.registry",
    "sqlalchemy.events",
    "sqlalchemy.exc",
    "sqlalchemy.ext.associationproxy",
    "sqlalchemy.ext.automap",
    "sqlalchemy.ext.compiler",
    "sqlalchemy.ext.declarative.api",
    "sqlalchemy.ext.declarative.base",
    "sqlalchemy.ext.declarative.clsregistry",
    "sqlalchemy.ext.horizontal_shard",
    "sqlalchemy.ext.hybrid",
    "sqlalchemy.ext.instrumentation",
    "sqlalchemy.ext.mutable",
    "sqlalchemy.ext.orderinglist",
    "sqlalchemy.ext.serializer",
    "sqlalchemy.inspection",
    "sqlalchemy.interfaces",
    "sqlalchemy.log",
    "sqlalchemy.orm.attributes",
    "sqlalchemy.orm.base",
    "sqlalchemy.orm.collections",
    "sqlalchemy.orm.dependency",
    "sqlalchemy.orm.deprecated_interfaces",
    "sqlalchemy.orm.descriptor_props",
    "sqlalchemy.orm.dynamic",
    "sqlalchemy.orm.evaluator",
    "sqlalchemy.orm.events",
    "sqlalchemy.orm.exc",
    "sqlalchemy.orm.identity",
    "sqlalchemy.orm.instrumentation",
    "sqlalchemy.orm.interfaces",
    "sqlalchemy.orm.loading",
    "sqlalchemy.orm.mapper",
    "sqlalchemy.orm.path_registry",
    "sqlalchemy.orm.persistence",
    "sqlalchemy.orm.properties",
    "sqlalchemy.orm.query",
    "sqlalchemy.orm.relationships",
    "sqlalchemy.orm.scoping",
    "sqlalchemy.orm.session",
    "sqlalchemy.orm.state",
    "sqlalchemy.orm.strategies",
    "sqlalchemy.orm.strategy_options",
    "sqlalchemy.orm.sync",
    "sqlalchemy.orm.unitofwork",
    "sqlalchemy.orm.util",
    "sqlalchemy.pool",
    "sqlalchemy.processors",
    "sqlalchemy.schema",
    "sqlalchemy.sql.annotation",
    "sqlalchemy.sql.base",
    "sqlalchemy.sql.compiler",
    "sqlalchemy.sql.ddl",
    "sqlalchemy.sql.default_comparator",
    "sqlalchemy.sql.dml",
    "sqlalchemy.sql.elements",
    "sqlalchemy.sql.expression",
    "sqlalchemy.sql.functions",
    "sqlalchemy.sql.naming",
    "sqlalchemy.sql.operators",
    "sqlalchemy.sql.schema",
    "sqlalchemy.sql.selectable",
    "sqlalchemy.sql.sqltypes",
    "sqlalchemy.sql.type_api",
    "sqlalchemy.sql.util",
    "sqlalchemy.sql.visitors",
    "sqlalchemy.types",
    "sqlalchemy.util._collections",
    "sqlalchemy.util.compat",
    "sqlalchemy.util.deprecations",
    "sqlalchemy.util.langhelpers",
    "sqlalchemy.util.queue",
    "sqlalchemy.util.topological",
    "flask_sqlalchemy._compat",
    "gzip",
    "gevent",
    "gevent.core",
    "logging",
    "Crypto",
    "Crypto.Hash"
]

# might need to explicitly include dll:
# data_files=[('.', 'libmmd.dll')
# also:
# http://stackoverflow.com/questions/10060765/create-python-exe-without-msvcp90-dll

WIN_OPTIONS = {
    "dist_dir": "../dist",
    "includes": INCLUDES,
    "iconfile": "static/images/icon_win.ico",
    "packages": ["nucleus", "web_ui", "synapse", "requests"],
    "dll_excludes": [],
    'bundle_files': 1
}

DARWIN_OPTIONS = {
    "argv_emulation": True,
    "bdist_base": "../build",
    "dist_dir": "../dist",
    "iconfile": "static/images/icon_osx.icns",
    "includes": INCLUDES,
    "packages": ["nucleus", "web_ui", "synapse", "requests"],
    "site_packages": True,
    "plist": {
        "CFBundleVersion": VERSION,
        "LSBackgroundOnly": True,
        "LSUIElement": True
    },
}

""" Platform specific options """
if sys.platform == 'darwin':
    # Compile .less files
    filenames = ["main", ]
    for fn in filenames:
        rv = os.system("touch ./static/css/{}.css".format(fn))
        rv += os.system("lesscpy ./static/css/{fn}.less > ./static/css/{fn}.css".format(fn=fn))

    """ Patch gevent implicit loader """
    patched = False
    with open("../lib/python2.7/site-packages/gevent/os.py", "r+") as f:
        patch = "\n# make os.path available here\nmy_os = __import__('os')\npath = my_os.path\n"
        for line in f.readlines():
            if line == "# make os.path available here":
                patched = True
        if not patched:
            f.write(patch)

    """ Setup Esky Executable """
    exe = Executable("run.py",
        description="Souma App",
        gui_only=True,
        icon=DARWIN_OPTIONS["iconfile"],
        name="run")

    extra_options = dict(
        setup_requires=['py2app'],
        app=['run.py'],
        options=dict(
            bdist_esky=dict(
                freezer_module="py2app",
                freezer_options=DARWIN_OPTIONS
            )
        ),
        scripts=[exe, ]
    )

    install_requires = open('requirements.txt').read()

elif sys.platform == 'win32':
    """ Setup Esky Executable """
    exe = Executable("run.py",
        description="Souma App",
        gui_only=True,
        icon=WIN_OPTIONS["iconfile"],
        name="run")

    extra_options = dict(
        setup_requires=['py2exe'],
        options=dict(
            bdist_esky=dict(
                freezer_module="py2exe",
                freezer_options=WIN_OPTIONS
            )
        ),
        scripts=[exe, ],
        zipfile=None
    )

    #Some little hacks for making py2exe work
    #Create empty __init__.py in flaskext directory
    #so py2exe recognizes it as module
    import flaskext
    try:
        flaskext.__file__
    except:
        flaskext_init = open(flaskext.__path__[0] + '\\__init__.py', 'w')
        flaskext_init.close()

    with open('requirements.txt') as f:
        install_requires = [req.strip() for req in f.readlines()]
else:
    extra_options = dict(
        scripts=APP)

    install_requires = open('requirements.txt').read()

setup(
    name="Souma",
    version=VERSION,
    author="Cognitive Networks Group",
    author_email="team@souma.io",
    url="https://github.com/ciex/souma/",
    packages=["nucleus", "web_ui", "synapse"],
    data_files=DATA_FILES,
    license="Apache License 2.0",
    description="A Cognitive Network for Groups",
    long_description=open("README.md").read(),
    install_requires=install_requires,
    **extra_options
)


import numpy as np

def weird_division(x, y):
    return 0 if y == 0 else x / y

def modeleval(save_test_model, var, f):
    results = np.load(f'data/results/{save_test_model}.npz')
    inputs, labels, outputs = results['inputs'], results['labels'], results['outputs']
    del results

    n_samples, n_classes, w, h = outputs.shape
    predictions = outputs.argmax(axis=1)

    r_count = 0
    PA, mPA = 0, 0
    m_IOU, background_iou, landslide_iou = 0, 0, 0
    pre, rec, f1 = 0, 0, 0
    for label, pred in zip(labels, predictions):
        PA += (pred == label).sum() / (w * h) #pixel accuracy
        mPA += weird_division(((pred == 0) & (label == 0)).sum(), ((label == 0).sum())) + weird_division(((pred == 1) & (label == 1)).sum(), ((label == 1).sum()))

        background_iou += weird_division(((pred == 0) & (label == 0)).sum(), ((pred == 0) | (label == 0)).sum())
        landslide_iou += weird_division(((pred == 1) & (label == 1)).sum(), ((pred == 1) | (label == 1)).sum())

        pre += weird_division(((pred == 1) & (label == 1)).sum(), (pred == 1).sum())
        rec += weird_division(((pred == 1) & (label == 1)).sum(), (label == 1).sum())

        if weird_division(((pred == 1) & (label == 1)).sum(), (label == 1).sum()) >= 0.3:
            r_count += 1

    PA /= n_samples
    mPA /= (n_samples * 2)
    background_iou /= n_samples
    landslide_iou /= n_samples
    mIOU = (background_iou + landslide_iou) / 2
    pre /= n_samples
    rec /= n_samples
    f1 = (2 * pre * rec) / (pre + rec)

    acc = r_count / n_samples

    f.write('**********' + var + '**********' + '\n')
    f.write(f'PA: {PA:.4f}, mPA: {mPA:.4f}'+'\n')
    f.write(f'mIOU: {mIOU:.4f}, background_iou: {background_iou:.4f}, landslide_iou: {landslide_iou:.4f}'+'\n')
    f.write(f'pre: {pre:.4f}, rec: {rec:.4f}, f1: {f1:.4f}'+'\n')
    f.write(f'acc: {acc:.4f}'+'\n')


# coding=utf-8
"""Resources API feature tests."""

__copyright__ = 'Copyright (c) 2020, Utrecht University'
__license__   = 'GPLv3, see LICENSE'

from pytest_bdd import (
    given,
    parsers,
    scenarios,
    then,
)

from conftest import api_request

scenarios('../../features/api/api_resources.feature')

@given('the Yoda resources API is queried for all research groups of current datamanager', target_fixture="api_response")
def api_get_groups_of_datamanger(user):
    return api_request(
        user,
        "resource_groups_dm",
        {}
    )

@then('"<group>" for datamanager are found')
def api_response_groups_for_datamanager(api_response, group):
    _, body = api_response

    assert len(body["data"]) > 0
    found_group = False
    for list in body["data"]:
        if group in list:
            found_group = True
            break

    assert found_group

@given('the Yoda resources API is queried by a datamanager for monthly storage data', target_fixture="api_response")
def api_get_monthly_stats_dm(user):
    return api_request(
        user,
        "resource_monthly_stats_dm",
        {}
    )

@then('monthly storage data for a datamanager is found')
def api_response_monthly_storage_for_dm(api_response):
    _, body = api_response

    # check presence all keys
    assert body["data"][0]["category"]
    assert body["data"][0]["tier"]
    assert body["data"][0]["storage"]

@given('the Yoda resources API is queried by a for statistics data to be used as a feed for an export file', target_fixture="api_response")
def api_get_monthly_category_stats_export_dm(user):
    return api_request(
        user,
        "resource_monthly_category_stats_export_dm",
        {}
    )

@then('storage data for export is found')
def api_response_storage_data_for_export(api_response):
    _, body = api_response

    assert body["data"][0]["category"]
    assert body["data"][0]["subcategory"]
    assert body["data"][0]["storage"]
    assert body["data"][0]["month"]
    assert body["data"][0]["groupname"]
    assert body["data"][0]["tier"]

@given('the Yoda resources API is queried for all monthly statistics', target_fixture="api_response")
def api_monthly_stats(user):
    return api_request(
        user,
        "resource_monthly_stats",
        {}
    )

@then('rodsadmin monthly statistics is found')
def api_response_monthly_statistics_rodsadmin(api_response):
    _, body = api_response

    assert body['data'][0]['category']
    assert body['data'][0]['tier']
    assert body['data'][0]['storage']

@given('the Yoda resources API is queried for all resources and tiers', target_fixture="api_response")
def api_resource_and_tier_data(user):
    return api_request(
        user,
        "resource_resource_and_tier_data",
        {}
    )

@then('list of resources and tiers is found')
def api_response_list_of_resources_and_tiers(api_response):
    _, body = api_response

    # {'tier': 'Standard', 'name': 'dev001_2', 'id': '10018'}
    assert body['data'][0]['tier']
    assert body['data'][0]['name']
    assert body['data'][0]['id']

@given('the Yoda resources API is queried for tier_name of "<resource_name>"', target_fixture="api_response")
def api_get_tier_on_resource(user, resource_name):
    return api_request(
        user,
        "resource_tier",
        {"res_name": resource_name}
    )

@then('"<tier_name>" is found')
def api_response_tier_name_for_resource(api_response, tier_name):
    _, body = api_response

    assert body['data'] == tier_name

@given('the Yoda resources API is queried for all available tiers', target_fixture="api_response")
def api_get_tiers(user):
    return api_request(
        user,
        "resource_get_tiers",
        {}
    )

@then('list with "<tier_name>" is found')
def api_response_all_tiers(api_response, tier_name):
    _, body = api_response

    assert tier_name in body['data']

@given('the Yoda resources API is requested to save tier "<tier_name>" for resource "<resource_name>"', target_fixture="api_response")
def api_save_tier_for_resource(user, resource_name, tier_name):
    return api_request(
        user,
        "resource_save_tier",
        {"resource_name": resource_name, "tier_name": tier_name}
    )

@then('tier is saved successfully for resource')
def api_response_save_tier_name_successful(api_response):
    _, body = api_response

    assert body['status'] == 'ok'

@given('the Yoda resources API is queried for usertype of current user', target_fixture="api_response")
def api_get_user_type(user):
    return api_request(
        user,
        "resource_user_get_type",
        {}
    )

@then('"<user_type>" is found')
def api_response_user_type(api_response, user_type):
    _, body = api_response

    assert body["data"] == user_type

@given('the Yoda resources API is queried for research groups of current user', target_fixture="api_response")
def api_get_user_research_groups(user):
    return api_request(
        user,
        "resource_user_research_groups",
        {}
    )

@then('"<research_group>" are found for current user')
def api_response_research_groups_for_user(api_response, research_group):
    _, body = api_response

    assert research_group in body["data"]

@given('the Yoda resources API is queried to know if current user is datamanager', target_fixture="api_response")
def api_is_user_datamanager(user):
    return api_request(
        user,
        "resource_user_is_datamanager",
        {}
    )

@then('current user is found')
def api_response_user_is_datamanager(api_response):
    _, body = api_response

    assert body["data"] == 'yes'

@given('the Yoda resources API is queried for full year of monthly data for group "<group_name>" starting from current month backward', target_fixture="api_response")
def api_get_monthly_user_research_groups(user, group_name):
    from datetime import datetime
    current_month = datetime.now().month

    return api_request(
        user,
        "resource_full_year_group_data",
        {"group_name": group_name, "current_month": current_month}
    )

@then('full year storage data is found')
def api_response_full_year_storage(api_response):
    _, body = api_response

    # A list of dicts like following
    # [{'month=10-tier=Standard': 6772}]

    # Look at first entry
    storage_month_data = body['data'][0]
    for key in storage_month_data:
        assert 'month=' in key
        break

@then(parsers.parse('the response status code is "{code:d}"'))
def api_response_code(api_response, code):
    http_status, _ = api_response

    assert http_status == code


def solution(routes):
    answer = 0
    lst = []
    SZ = len(routes)
    camera = [0]*SZ

    for index, route in enumerate(routes):
        lst.append((route[0] , 0 , index))
        lst.append((route[1] , 1 , index))

    lst.sort()
    i , j =0, 0
    while j<len(lst):
        if lst[j][1] == 1 and camera[lst[j][2]] == 0:
            camera_cnt = 0
            for index in range(i,j+1):
                if camera[lst[index][2]] == 1: continue
                camera[lst[index][2]] = 1
                camera_cnt += 1
            i = j+1
            if camera_cnt > 0 :
                answer += 1
        j+=1

    return answer

프로그래머스/단속카메라.py


# -*- coding: utf-8 -*-

import datetime

from django.core.paginator import Paginator
from django.shortcuts import render, get_object_or_404

from blogs.models import Post

def index(request):
    posts = Post.objects.filter(visible=True).order_by('-created')

    try:
        page = int(request.GET.get('page'))
    except (TypeError, ValueError):
        page = 1

    objects = Paginator(posts, 5)

    context = {
        'posts': objects,
    }

    return render(request, 'blogs/index.html', context)

def read(request, slug):
    post = get_object_or_404(Post, slug=slug)

    context = {
        'post': post,
    }

    return render(request, 'blogs/read.html', context)


#Libray
import csv
import math
import matplotlib.pyplot as plt
from sklearn import tree
from sklearn.model_selection import KFold

#Variables
X = []
y = []
Y_series = [] #used to save real values and respective predictions
dtr_MADscores = []
dtr_RMSEscores = []
features = ('X','Y','month','day','FFMC','DMC','DC','ISI','temp','RH','wind','rain')
month_dict = {'jan':1,'feb':2,'mar':3,'apr':4,'may':5,'jun':6,
              'jul':7,'aug':8,'sep':9,'oct':10,'nov':11,'dec':12,}
day_dict = {'mon':1,'tue':2,'wed':3,'thu':4,'fri':5,'sat':6,'sun':7}
#modifiable
keep_col = None
kf_rounds = None
depth = None

#Retrieve user input
n = int(input("Enter # of desired features: "))
keep_col = list(map(int,input("Enter the feature columns (format: 0 1 2 ...): ").strip().split()))[:n]
kf_rounds = int(input("Enter # of 10 fold cross validation rounds: "))
depth = int(input("Enter depth of decision tree (3 is reccomended): "))

#Load data
print("\nLoading data...", end=' ')
with open("../resource/forestfires.csv", 'r') as csvfile:
  reader = csv.reader(csvfile)
  for i, row in enumerate(reader):
      if i > 0: #skipping the header
          temp = [row[0],row[1],month_dict[row[2]],day_dict[row[3]],row[4],row[5],
                  row[6],row[8],row[9],row[10],row[11]]
          X.append([float(i) for i in temp])
          #natural log transform function
          y.append(math.log(float(row[-1])+1))
print("Done")

#Update X according to selected features
X_fs = []
for instance in X:#_std:
    temp = []
    for k,value in enumerate(instance):
        if k in keep_col:
            temp.append(value)
    X_fs.append(temp)

#Train and test model with rounds of 10 fold cross validtion
print("\nPerforming 10 fold cross validation...")
for kf_round in range(kf_rounds):
    print("Round " + str(kf_round+1))
    #split data into test and train
    kf = KFold(n_splits=10, shuffle=True)
    kf.split(X_fs,y)
    for train_index, test_index in kf.split(X_fs):
        X_train = []
        y_train = []
        for index in train_index:
            X_train.append(X_fs[index])
            y_train.append(y[index])
        X_test = []
        y_test = []
        for index in test_index:
            X_test.append(X_fs[index])
            y_test.append(y[index])

        #Build models
        dtr = tree.DecisionTreeRegressor(max_depth=depth)
        dtr = dtr.fit(X_train,y_train)

        #Test models
        dtr_totalError = 0
        dtr_totalSE = 0
        for instance,target in zip(X_test,y_test):
            #reversing natural log transformation
            dtr_prediction = math.exp(dtr.predict([instance])[0])-1
            target_transform = math.exp(target)-1
            #populating series for later plotting
            Y_series.append([target_transform,dtr_prediction])
            #totaling errors
            dtr_error = target_transform - dtr_prediction
            dtr_totalError += abs(dtr_error)
            dtr_totalSE += dtr_error*dtr_error
        #saving MAD and RMSE scores
        dtr_MADscores.append(dtr_totalError/len(X_test))
        dtr_RMSEscores.append(math.sqrt(dtr_totalSE/len(X_test)))
print("Done")

#Calculte average scores
dtr_avgMAD = sum(dtr_MADscores)/len(dtr_MADscores)
dtr_avgRMSE = sum(dtr_RMSEscores)/len(dtr_RMSEscores)

#Print average peformace of models
print("\nDT w/ depth " + str(depth) +":")
print("average MAD = " + str(dtr_avgMAD))
print("average RMSE = " + str(dtr_avgRMSE))

#Sort real values and predictions by increasing order of actual values
Y_series.sort(key=lambda x:x[0])
truth_series = [i for i,j in Y_series] #actual values
dtr_series = [j for i,j in Y_series] #dtr predictions

#Plot real values and dtr predictions
plt.figure(figsize=(12,12))
plt.title(label="DT")
plt.xlabel('Ordered test set')
plt.ylabel('Burned area (in hectares)')
plt.ylim([0,20])
plt.plot(truth_series, 'bo', label='real values')
plt.plot(dtr_series, 'r+', label='predictions')
plt.legend()
plt.show()


class Solution:
    def fizzBuzz(self, n: int):
        l = []
        for i in range(1, n):
            if (i % 3) and (i % 5) == 0:
                ['FizzBuzz'] == l[i]
                # l[i] == ['FizzBuzz']
            elif (i % 3) == 0:
                l[i] == ['Fizz']
            elif (i % 5) == 0:
                l[i] == ['Buzz']
            else:
                return l
        return l

s = Solution()
print(s.fizzBuzz(5))


import sys
sys.path.insert(0, 'src/vendor')
from imdb import IMDb
from imdb import helpers

ia = IMDb()
h = helpers()

def multipleMovies(title, allMoviesWithName, movie):
	if(len(allMoviesWithName) == 1):
		movie = ia.get_movie(allMoviesWithName[0].movieID)
	else:
		filterBy = input(f'Multiple items named "{title}" ({len(allMoviesWithName)} total).  Filter by: \nkind\nyear\n')
		if(filterBy == 'kind'):
			possibleKinds = [x.get('kind', '') for x in allMoviesWithName]
			chosenKind = input(f'Which kind?\n{possibleKinds}\n')
			allMoviesWithName = [m for m in allMoviesWithName if m.get('kind', '') == chosenKind]
		elif(filterBy == 'year'):
			possibleYears = [x.get('year', 'unknown') for x in allMoviesWithName]
			chosenYear = input(f'Multiple movies named "{title}".Which year?\n{possibleYears}\n')
			allMoviesWithName = [m for m in allMoviesWithName if m.get('year', '') == int(chosenYear)]

		if(len(allMoviesWithName) == 1):
			return (0, allMoviesWithName, ia.get_movie(allMoviesWithName[0].movieID))
		else:
			return (1, allMoviesWithName, '')

def getMovie(movieDetails):
	title = movieDetails[1]
	# director = movieDetails[2]
	year = int(movieDetails[3])
	allMoviesWithName = ia.search_movie(title)
	if(len(allMoviesWithName) > 1):
		print(f'Multiple items found ({len(allMoviesWithName)}).  Filtering by year = {year} and kind == movie')
		allMoviesWithName = [m for m in allMoviesWithName if m.get('year','')==year and m.get('kind','')=='movie']
	if(len(allMoviesWithName) == 1):
		movie = ia.get_movie(allMoviesWithName[0].movieID)
	else:
		print(f'Something went wrong.  Total moves found after filter: {len(allMoviesWithName)}.  Stopping. ')
		return

	directors = [x['name'] for x in movie['directors']]
	genres = movie['genres']
	description = movie['plot outline']
	rating = movie['rating']
	numberVotes = movie['votes']
	writers = [x.get('name', '') for x in movie['writers']]
	stars = [x['name'] for x in movie['cast'][:3]]
	runtime = movie['runtime'][0]
	imageUrl = '.'.join(movie['cover url'].split('.')[:-2])+'.jpg'
	budget =  movie['box office'].get('Budget','') if movie.get('box office','') != '' else ''
	openingWeekendUSA =  movie['box office'].get('Opening Weekend United States','') if movie.get('box office','') != '' else ''

	movieJ = {
	"title": title,
	"year": year,
	"description": description,
	"image": imageUrl,
	"ratings": [{
		"source": "IMDB",
		"rating": rating,
		"numberVotes": numberVotes
	}],
	"watched": "notWatched",
	"liked": "",
	"id": movie.movieID,
	"director": directors,
	"writer": writers,
	"stars": stars,
	"releaseDate": movie['original air date'],
	"runtime": runtime,
	"genres": genres,
	"budget": budget,
	"openingWeekendUSA": openingWeekendUSA,
	"worldwideGross": "",
	"tags": [],
	"AFI100LaughsRank": movieDetails[0]
	}
	return movieJ


import setuptools
from ast import literal_eval

name = 'asterion'

with open(f'{name}/version.py') as file:
    # Assuming version.py follows format __version__ = '<version_string>'
    line = file.readline().strip()
    version = literal_eval(line.split(' = ')[1])

description = 'Fits the asteroseismic helium-II ionisation zone glitch ' + \
              'present in the mode frequencies of solar-like oscillators.'

packages = setuptools.find_packages(include=[name, f'{name}.*'])

author = 'Alex Lyttle'

url = 'https://github.com/alexlyttle/asterion'

classifiers = [
    "Programming Language :: Python :: 3",
    "License :: OSI Approved :: MIT License",
    "Operating System :: OS Independent",
]

with open('requirements.txt') as file:
    install_requires = file.read().splitlines()

with open('docs/requirements.txt') as file:
    docs_require = file.read().splitlines()

with open('tests/requirements.txt') as file:
    tests_require = file.read().splitlines()

setuptools.setup(
    name=name,
    version=version,
    description=description,
    packages=packages,
    author=author,
    url=url,
    classifiers=classifiers,
    install_requires=install_requires,
    extras_require={
        'docs': docs_require,
        'tests': tests_require,
    },
    package_data={
        '': ['*.nc', '*.mplstyle'],
    },
    include_package_data=True,
    python_requires='>=3.8',
    licence='MIT',
)


#!/usr/bin/env python
import os
import sys
import re

try:
    from setuptools import setup
    setup
except ImportError:
    from distutils.core import setup
    setup

if sys.argv[-1] == "publish":
    os.system("python setup.py sdist upload")
    sys.exit()

# Handle encoding
major, minor1, minor2, release, serial = sys.version_info
if major >= 3:
    def rd(filename):
        f = open(filename, encoding="utf-8")
        r = f.read()
        f.close()
        return r
else:
    def rd(filename):
        f = open(filename)
        r = f.read()
        f.close()
        return r

setup(
    name='simfit',
    packages =['simfit'],
    version="0.1.1",
    author='John Livingston',
    author_email = 'jliv84@gmail.com',
    url = 'https://github.com/john-livingston/sxp',
    license = ['GNU GPLv3'],
    description ='Framework for simultaneous fitting of heterogeneous datasets and models',
    long_description=rd("README.md") + "\n\n"
                    + "---------\n\n",
    package_dir={"simfit": "simfit"},
    package_data={"simfit": []},
    scripts=['scripts/fitk2', 'scripts/fitk2spz'],
    include_package_data=True,
    keywords=[],
    classifiers = [
        'Development Status :: 3 - Alpha',
        'Intended Audience :: Science/Research',
        'Topic :: Scientific/Engineering',
        'Programming Language :: Python'
        ],
    install_requires = ['numpy', 'scipy', 'matplotlib', 'astropy', 'photutils', 'tqdm'],
)


################################################################
# Use nmrglue package
# latest version (09.06.2021) needs this package commit https://github.com/jjhelmus/nmrglue.git@6ca36de7af1a2cf109f40bf5afe9c1ce73c9dcdc
################################################################

import numpy as np
import nmrglue as ng
import os
import glob

#Function to read ShimDB from folder structure into numpy array
def get_dataset(DATASET_PATH, target_def = 'firstorder', normalize=True, downsamplefactor=1):

    norm_factor = 2**15
    #load data, sort and remove first point
    FNAMEs_shims = glob.glob(DATASET_PATH+"/*/shims.par")
    FNAMEs_shims = sorted(FNAMEs_shims, key = os.path.getmtime)[1:] #sort by creation time
    FNAMEs_1d = glob.glob(DATASET_PATH+"/*/data.1d")
    FNAMEs_1d = sorted(FNAMEs_1d, key = os.path.getmtime)[1:] #sort by creation time

    shims_dic = np.array([ { line.split()[0] : int(line.split()[2]) for line in open(f) }
                 for f in FNAMEs_shims])

    DIR_ref_shims = glob.glob(DATASET_PATH+"/RefShims.par")
    if DIR_ref_shims == []:
        print('No ref sim file found. Old version of dataset acquisition. Exiting.' )
        exit()
    else:
        ref_shim = np.array([ { line.split()[0] : int(line.split()[2]) for line in open(DIR_ref_shims[0]) }])[0]

    #dummy scan to get parameters
    dummy_dic,_  = ng.spinsolve.read(os.path.dirname(FNAMEs_1d[0]))

    data_bin = np.empty([len(FNAMEs_1d), int(dummy_dic['spectrum']['xDim']/downsamplefactor) ])
    for idx,f in enumerate(FNAMEs_1d):
        dic, fid = ng.spinsolve.read(os.path.dirname(f))
        # more uniform listing
        udic = ng.spinsolve.guess_udic(dic, fid)
        # fft and phase correction
        spectrum = ng.proc_base.fft(fid)
        spectrum = ng.proc_base.ps(spectrum, p0=float(dic['proc']['p0Phase']) ,p1=float(dic['proc']['p1Phase']))
        spectrum = ng.proc_base.di(spectrum)
        data_bin[idx] = np.array(spectrum)[::downsamplefactor]

    xaxis = np.arange(-udic[0]['sw']/2,udic[0]['sw']/2, udic[0]['sw']/udic[0]['size'])

    if target_def == 'firstorder': # return 3 first order shim values per sample
        #create array of labels similar to digital twin (as offset to reference)
        labels = np.empty([len(shims_dic),  3])
        for idx,d in enumerate(shims_dic):
            labels[idx,0] = d["xshim"] - ref_shim["xshim"]
            labels[idx,1] = d["yshim"] - ref_shim["yshim"]
            labels[idx,2] = d["zshim"] - ref_shim["zshim"]
        if normalize:
            labels = labels / norm_factor
            max_data = 1e5
            data_all = data_bin/max_data
            return data_bin, labels, norm_factor, max_data, xaxis
        else:
            return data_bin, labels, xaxis

# function to combine 4 spectra (channels) to a single input batch
def batch_dataset(data_all, labels_all, downsamplefactor, channels=4, offsets=[1000], sets = [21**3]):
    data_tmp = []
    labels_tmp = []

    for s in sets:
        data_tmp.append(np.zeros([s, channels, int(32768/downsamplefactor)]))
        labels_tmp.append(np.zeros([s, 3]))

    counters = [0,0,0]
    for idx_off, off in enumerate(offsets):
        start = sum(sets[:idx_off])
        stop = start + sets[idx_off]
        for idx_sub, l in enumerate(labels_all[start:stop]):
            idx = idx_sub+start
            bool_x = np.sum((labels_all == (l + [off,0,0])), axis=1)
            idx_x = np.where(bool_x == 3)[0]

            bool_y = np.sum((labels_all == (l + [0,off,0])), axis=1)
            idx_y = np.where(bool_y == 3)[0]

            bool_z = np.sum((labels_all == (l + [0,0,off])), axis=1)
            idx_z = np.where(bool_z == 3)[0]
            if idx_x.any() != False and idx_y.any() != False and idx_z.any() != False :
                if len(idx_x) > 1:
                    idx_x = min(idx_x, key=lambda x:abs(x-idx)) # get closest idx if more than 2 spectra found
                if len(idx_y) > 1:
                    idx_y = min(idx_y, key=lambda x:abs(x-idx)) # get closest idx if more than 2 spectra found
                if len(idx_z) > 1:
                    idx_z = min(idx_z, key=lambda x:abs(x-idx)) # get closest idx if more than 2 spectra found
                #if idx_sub % 1000 == 0: print('{}\n{}\n{}\n{}'.format(labels_all[idx],labels_all[idx_x.item()],labels_all[idx_y.item()],labels_all[idx_z.item()]))
                ######data_batched = np.concatenate( [data_batched, [np.array([data_all[idx_sub], data_all[idx_x.item()]])]  ] ) # concat (1,channels, 32768)
                data_tmp[idx_off][counters[idx_off]] = [data_all[idx], data_all[idx_x.item()], data_all[idx_y.item()], data_all[idx_z.item()]]
                labels_tmp[idx_off][counters[idx_off]] = l
                counters[idx_off] += 1

    # trim zeros values
    for idx, s in enumerate(sets):
        #last value
        #lastnonzero = np.nonzero(s[::-1])[0][0]
        lastnonzero = counters[idx]

        labels_tmp[idx] = labels_tmp[idx][:lastnonzero]
        data_tmp[idx] = data_tmp[idx][:lastnonzero]

    dic = {'offsets':offsets, 'channels': channels, 'sets': sets}

    return data_tmp, labels_tmp, dic


from requests import Session
from requests.structures import CaseInsensitiveDict

class BaseSession(Session):

    def __init__(self, driver_cookie: dict):
        super().__init__()
        self.verify = False
        self.headers = CaseInsensitiveDict(
            {'Content-Type': 'application/x-www-form-urlencoded',
             'cookie': f'{driver_cookie["name"]}={driver_cookie["value"]}'}
        )


# Your message is a string containing space separated words.
# You need to encrypt each word in the message using the following rules:
# The first letter needs to be converted to its ASCII code.
# The second letter needs to be switched with the last letter
# Keepin' it simple: There are no special characters in input.

# -----------------Examples----------------:
# encrypt_this("Hello") == "72olle"
# encrypt_this("good") == "103doo"
# encrypt_this("hello world") == "104olle 119drlo"

def encrypt_this(text):
    arr = text.split()
    new_str = []
    new_wrd = ""
    for word in arr:
        new_wrd = "".join([str(ord(word[i])) if i == 0 else word[-1] if i == 1 else word[1] if i == len(word) - 1 else word[i] for i in range(len(word))])
        new_str.append(new_wrd)
    return " ".join(new_str)

print(encrypt_this("The more he saw the less he spoke"))    #
print("expected: 84eh 109ero 104e 115wa 116eh 108sse 104e 115eokp")


import csv
with open("emp.csv",'r') as fp:
    data=csv.reader(fp)
    for line in data:
        for j in line[1]:
            if j[0]=='A':
                print(line)
                break

#OUTPUT
"""
python EmployeName.py
['101', 'Anna', '5500']
['104', 'Alice', '3500']

"""


from tokenizers import BertWordPieceTokenizer
import numpy as np
import argparse
import torch

parser = argparse.ArgumentParser(description="Numerize text into numpy format")
parser.add_argument('--vocab', default='path/to/vocab.txt',
                    help="path to vocabulary file")
parser.add_argument('--merge', default='',
                    help="path to merge file")
parser.add_argument('--input', default='en.train',
                    help="path to tokenized text file")
parser.add_argument('--bin_path', default='en.train.pth',
                    help="path to binary file output")
parser.add_argument("--model", choices=["bert", "roberta"], default="bert",
                    help="source pre-trained model")
params = parser.parse_args()

if params.model == 'bert':
    CLS_TOKEN, CLS_INDEX = "[CLS]", 101
    SEP_TOKEN, SEP_INDEX = "[SEP]", 102
    UNK_TOKEN, UNK_INDEX = "[UNK]", 100
    PAD_TOKEN, PAD_INDEX = "[PAD]", 0
    MASK_TOKEN, MASK_INDEX = "[MASK]", 103
elif params.model == 'roberta':
    CLS_TOKEN, CLS_INDEX = '<s>', 0
    SEP_TOKEN, SEP_INDEX = '</s>', 2
    UNK_TOKEN, UNK_INDEX = '<unk>', 3
    PAD_TOKEN, PAD_INDEX = '<pad>', 1
    MASK_TOKEN, MASK_INDEX = '<mask>', 50264

def numerize(vocab_path, input_path, bin_path):
    tokenizer = BertWordPieceTokenizer(
        vocab_path,
        unk_token=UNK_TOKEN,
        sep_token=SEP_TOKEN,
        cls_token=CLS_TOKEN,
        pad_token=PAD_TOKEN,
        mask_token=MASK_TOKEN,
        lowercase=False,
        strip_accents=False)
    sentences = []
    with open(input_path, 'r') as f:
        batch_stream = []
        for i, line in enumerate(f):
            batch_stream.append(line)
            if i % 1000 == 0:
                res = tokenizer.encode_batch(batch_stream)
                batch_stream = []
                # flatten the list
                for s in res:
                    sentences.extend(s.ids[1:])
            if i % 100000 == 0:
                print(f'processed {i} lines')

    print('convert the data to numpy')

    # convert data to numpy format in uint16
    if tokenizer.get_vocab_size() < 1 << 16:
        sentences = np.uint16(sentences)
    else:
        assert tokenizer.get_vocab_size() < 1 << 31
        sentences = np.int32(sentences)

    # save special tokens for later processing
    sep_index = tokenizer.token_to_id(SEP_TOKEN)
    cls_index = tokenizer.token_to_id(CLS_TOKEN)
    unk_index = tokenizer.token_to_id(UNK_TOKEN)
    mask_index = tokenizer.token_to_id(MASK_TOKEN)
    pad_index = tokenizer.token_to_id(PAD_TOKEN)

    # sanity check
    assert sep_index == SEP_INDEX
    assert cls_index == CLS_INDEX
    assert unk_index == UNK_INDEX
    assert pad_index == PAD_INDEX
    assert mask_index == MASK_INDEX

    print('collect statistics')
    # collect some statistics of the dataset
    n_unks = (sentences == unk_index).sum()
    n_toks = len(sentences)
    p_unks = n_unks * 100. / n_toks
    n_seqs = (sentences == sep_index).sum()
    print(f'| {n_seqs} sentences - {n_toks} tokens - {p_unks:.2f}% unknown words')

    # print some statistics
    data = {'sentences': sentences,
            'sep_index': sep_index,
            'cls_index': cls_index,
            'unk_index': unk_index,
            'pad_index': pad_index,
            'mask_index': mask_index}

    torch.save(data, bin_path, pickle_protocol=4)

numerize(params.vocab, params.input, params.bin_path)


from typing import List

class UnionFind:
    """
    유니온 파인드 : 두 노드가 같은 그룹 인지 체크
    """

    def __init__(self):
        super().__init__()
        self.parent: List[int] = []

    def union(self, node_count: int, edge_list: List[List[int]]):
        """
        유니온 연산 : 두 노드의 대표 노드끼리 연결
        Args:
            node_count: 노드의 개수
            edge_list: edge 정보 리스트

        Returns: None

        """
        # 대표 노드 리스트
        self.parent = [x for x in range(node_count + 1)]

        # edge 연결
        for edge in edge_list:
            # 각 노드의 대표 노드를 조회
            a = self.__find(edge[0])
            b = self.__find(edge[1])

            # 각 노드의 대표 노드가 다르면 대표 노드를 연결
            if a != b:
                self.parent[b] = a

    def __find(self, idx: int):
        """
        노드의 대표 노드를 조회
        Args:
            idx: 노드의 인덱스

        Returns: 노드의 대표 노드 인덱스

        """
        if self.parent[idx] == idx:
            # 현재 노드의 대표노드가 자신이라면 자신의 인덱스 리턴
            return idx
        else:
            # 대표 노드가 자신이 아닌 경우 현재 노드의 대표노드로 find 연산 다시 실행
            self.parent[idx] = self.__find(self.parent[idx])
            return self.parent[idx]

    def check_same(self, first: int, second: int):
        """
        두 노드의 대표 노드가 동일한지 체크
        Args:
            first: 첫 번째 노드
            second: 두 번째 노드

        Returns: 대표 노드의 동일 여부. True or False

        """
        a = self.__find(first)
        b = self.__find(second)

        if a == b:
            return True
        else:
            return False

if __name__ == "__main__":
    N = 7

    edge_list = [[1, 3], [7, 6], [3, 7], [4, 2], [1, 1]]
    q_list = [[1, 7], [1, 5], [2, 6]]

    obj = UnionFind()
    obj.union(N, edge_list)

    for q in q_list:
        result = obj.check_same(q[0], q[1])
        if result:
            print("YES")
        else:
            print("NO")


import turtle as tt
class Card():
    def __init__(self,name = None,suit = None):
        self.name = name
        self.suit = suit
        #diamonds (♦), clubs (♣), hearts (♥) and spades (♠)
        self.symbols = {'D':'♦','C':'♣','H':'♥','S':'♠'} #dictionary

    def print_card(self):
        if self.suit == 'S':
            symbol ='♠'
        print(f'{self.name}{self.symbols[self.suit]}')

    def render(self,x,y,pen : tt.Turtle):
        #draw border
        pen.penup()
        pen.goto(x,y)
        pen.color('blue')
        pen.goto(x-50, y+75)
        pen.begin_fill()
        pen.pendown()
        pen.goto(x+50,y+75)
        pen.goto(x+50,y-75)
        pen.goto(x-50,y-75)
        pen.goto(x-50,y+75)
        pen.end_fill()
        pen.penup()

        if self.name !='':
        #Draw suit in the middle
            pen.color('white')
            pen.goto(x-18,y-30)
            pen.write(self.symbols[self.suit], False,font=('Courier New', 48,'normal'))

            #Draw top left
            pen.goto(x-40, y+45)
            pen.write(self.name, False,font=('Courier New', 18,'normal'))
            pen.goto(x-40, y+25)
            pen.write(self.symbols[self.suit], False,font=('Courier New', 18,'normal'))

            #Draw bottom right
            pen.goto(x+30, y-60)
            pen.write(self.name, False,font=('Courier New', 18,'normal'))
            pen.goto(x+30, y-80)
            pen.write(self.symbols[self.suit], False,font=('Courier New', 18,'normal'))


T=int(input())
for tc in range(T):
    N=int(input())
    tmp=[]
    for _ in range(N):
        tmp.append(list(map(int,input().split())))
    alert=[] # 경보기 위치 뽑기
    for row in range(N):
        temp=[]
        for col in range(N):
            if tmp[row][col]==1:
                temp.append((row,col))

        if len(temp)!=0:
            alert.append(temp)
    # 첫 경보기의 0번 -1 번 마지막 경보기의 0번 -1 번 사용
    cnt=0
    #왼위

    for row in range(0,alert[0][0][0]+1):
        for col in range(0,alert[0][0][1]+1):
            if tmp[row][col]==2:
                cnt+=1
    #오위
    for row in range(0,alert[0][-1][0]+1):
        for col in range(alert[0][-1][1],N):
            if tmp[row][col]==2:
                cnt+=1
    #왼 아래
    for row in range(alert[-1][0][0],N):
        for col in range(alert[-1][0][1]+1):
            if tmp[row][col]==2:
                cnt+=1
    #오 아래
    for row in range(alert[-1][-1][0],N):
        for col in range(alert[-1][-1][1],N):
            if tmp[row][col]==2:
                cnt+=1
    print("#{} {}".format(tc+1,cnt))

혼자하는거/멧돼지밭경보기.py


from pathlib import Path
from itertools import zip_longest

f = open(Path(__file__).resolve().parent / 'input.txt')

# eval would have been easier ...
def read_packet(s):
  def read(s,p):
    if s[p] == '[':
      return read_list(s,p)
    return read_number(s,p)
  def read_number(s,p):
    e = p
    while s[e].isdigit():
      e += 1
    return int(s[p:e]),e
  def read_list(s,p):
    l = []
    p += 1
    while True:
      if s[p] == ',':
        p += 1
        continue
      if s[p] == ']':
        p += 1
        break
      i,p = read(s,p)
      l.append(i)
    return l,p
  return read_list(s,0)[0]

input = []
i = iter(f)
while True:
  n = next(i)
  a = read_packet(n.strip())
  n = next(i)
  b = read_packet(n.strip())
  input.append((a,b))
  try:
    next(i)
  except:
    break

def cmp(a,b):
  if isinstance(a,int) and isinstance(b,int):
    if a < b:
      return True
    if a > b:
      return False
    return None
  if isinstance(a,list) and isinstance(b,list):
    for aa,bb in zip_longest(a,b):
      if aa is None:
        return True
      if bb is None:
        return False
      c = cmp(aa,bb)
      if c is not None:
        return c
    return None
  if isinstance(a,int):
    return cmp([a],b)
  return cmp(a,[b])

sum = 0
for i,(a,b) in enumerate(input):
  if cmp(a,b):
    sum += i+1
print(sum)

from functools import cmp_to_key

div1,div2 = [[2]],[[6]]
input = [a for a,b in input] + [b for a,b in input] + [div1,div2]

def cmp2(a,b):
  c = cmp(a,b)
  if c is None:
    raise RuntimeError('dafuq')
  return -1 if c else 1

s = sorted(input, key=cmp_to_key(cmp2))
print((s.index(div1)+1) * (s.index(div2)+1))


# -*- coding: utf-8 -*-
"""
Created on Tue Jul 14 20:21:07 2020

@author: gabriel bustamante
"""

import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

def get_attributes_list(information_level, attributes_description):

    attributes_list = list(attributes_description[attributes_description['information'] == information_level]['attribute'].unique())

    if information_level == '125m x 125m Grid':
        attributes_list += ['D19_BUCH_CD', 'D19_LETZTER_KAUF_BRANCHE', 'D19_LOTTO', 'D19_SOZIALES']
    if information_level == 'Building':
        attributes_list += ['FIRMENDICHTE', 'HH_DELTA_FLAG', 'KOMBIALTER']
    if information_level == 'Household':
        attributes_list += ['ALTER_KIND1', 'ALTER_KIND2', 'ALTER_KIND3', 'ALTER_KIND4',
                            'ANZ_KINDER', 'ANZ_STATISTISCHE_HAUSHALTE',
                            'D19_BANKEN_ANZ_12', 'D19_BANKEN_ANZ_24', 'D19_KONSUMTYP_MAX',
                            'D19_TELKO_ANZ_12', 'D19_TELKO_ANZ_24', 'D19_TELKO_ONLINE_QUOTE_12', 'D19_VERSAND_ANZ_12',
                            'D19_VERSAND_ANZ_24', 'D19_VERSI_ANZ_12', 'D19_VERSI_ANZ_24', 'D19_VERSI_ONLINE_QUOTE_12',
                            'KK_KUNDENTYP', 'KONSUMZELLE', 'UMFELD_ALT', 'STRUKTURTYP',
                            'UMFELD_JUNG', 'UNGLEICHENN_FLAG', 'VERDICHTUNGSRAUM',
                            'VHA', 'VHN', 'VK_DHT4A', 'VK_DISTANZ', 'VK_ZG11']
    if information_level == 'PLZ8':
        attributes_list += ['KBA13_ANTG1', 'KBA13_ANTG2', 'KBA13_ANTG3', 'KBA13_ANTG4', 'KBA13_BAUMAX', 'KBA13_CCM_1401_2500',
                            'KBA13_CCM_3000', 'KBA13_CCM_3001', 'KBA13_GBZ', 'KBA13_HHZ', 'KBA13_KMH_210']
    if information_level == 'Person':
        attributes_list += ['ALTERSKATEGORIE_FEIN', 'AKT_DAT_KL',
                            'CJT_KATALOGNUTZER', 'CJT_TYP_1', 'CJT_TYP_2', 'CJT_TYP_3', 'CJT_TYP_4', 'CJT_TYP_5', 'CJT_TYP_6',
                            'DSL_FLAG', 'EINGEFUEGT_AM', 'EINGEZOGENAM_HH_JAHR',
                            'RT_KEIN_ANREIZ', 'RT_SCHNAEPPCHEN', 'RT_UEBERGROESSE', 'SOHO_KZ']
    if information_level == 'Microcell (RR4_ID)':
        attributes_list += ['CAMEO_INTL_2015']
    if information_level == 'Postcode':
        attributes_list += ['GEMEINDETYP', 'EXTSEL992']
    if information_level == 'RR1_ID':
        attributes_list += ['MOBI_RASTER']

    return attributes_list

def plot_heatmap_isna(information_columns, title, data):
    plt.figure(figsize=(10,5))
    sns.heatmap(data[information_columns].isna(), cbar=False)
    plt.title(title)

    plt.show()


#import constants
from constants import *

#import necessary classes
from space_invaders.game.casting.sound import Sound #import sound class for collision sound
from space_invaders.game.scripting.action import Action #import action class as parent class

class CollideShipAlienAction(Action):
    '''checks for and resolves collisions between ship and an alien.

        Arguments:
            physics service: an instance of physics_service
            audio service: an instance of audio_service
    '''
    def __init__(self, physics_service, audio_service):
        self._physics_service = physics_service #assigns _physics_service attribute from args
        self._audio_service = audio_service #assigns _audio_service attribute from args

    def execute(self, cast, script, callback):
        ship = cast.get_first_actor(SHIP_GROUP)
        aliens = cast.get_actors(ALIEN_GROUP)
        stats = cast.get_first_actor(STATS_GROUP)
        #over_sound = Sound(OVER_SOUND) #assigns variable to game over sound

        for alien in aliens:
            alien_body = alien.get_body()
            ship_body = ship.get_body()

            if self._physics_service.has_collided(ship_body, alien_body):
                #if the body of the ship has collided with the body of an alien the player loses a life
                stats = cast.get_first_actor (STATS_GROUP) #assign the stats object a variable
                stats.lose_life() #call the stats lose life method
                #self._audio_service.play_sound(sound) - not implemented in this version
                if stats.get_lives() > 0:
                    #if there is still a life available move to try_again scene
                    callback.on_next(TRY_AGAIN)
                else:
                    #if that was the las life move to game over screen and play game over sound
                    callback.on_next(GAME_OVER)
                    #self._audio_service.play_sound(over_sound)


from bs4 import BeautifulSoup
import sqlite3
import urllib.request
import urllib.error
import re
import xlwt
def main():
    baseurl = 'https://www.liepin.com/zhaopin/?sfrom=click-pc_homepage-centre_searchbox-search_new&dqs=010&key=JAVA'
    datalist = getdata(baseurl)
    savepath = ".\\职位信息"
    print(datalist)
    # 伪装请求
def askurl(url):
    # 请求头
    head = {
        'accept': '*/*',
        'accept - encoding': 'gzip, deflate, br',
        'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
        'x-requested-with': 'XMLHttpRequest',
        'referer':'https://www.liepin.com/zhaopin/?sfrom=click-pc_homepage-centre_searchbox-search_new&dqs=010&key=JAVA',
        'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36 Edg/88.0.705.50',

    }
    #构造request
    request = urllib.request.Request(url=url, headers=head)
    html = ""
    try:
    #构造response
        response = urllib.request.urlopen(request)
        html = response.read().decode("utf-8")
    except urllib.error.URLError as e:
        if hasattr(e, "code"):
            print(e.code)
        if hasattr(e, "reason"):
            print(e.reason)
def getdata(baseurl):
    data = [ ]
    for i in range(0,1):
        url = baseurl + "?page=2&ka=page-"+str(i)
        html = askurl(url)
        soup = BeautifulSoup(html, "html.parser")
        print(html)
        # 获取职位列表
        for item in soup.find_all('div', class_="job-content"):
            # 保存职位信息
            data = []
            item = str(item)
            # 添加公司名字，月薪，技能要求，工作地点，职位描述到列表
            companyname = re.findall(findcompanyname, item)[0]
            data.append(companyname)
            salary = re.findall(findsalary, item)[0]
            data.append(salary)
            workposition = re.findall(findworkposition, item)[0]
            data.append(workposition)
    return data
# 保存数据到excel
def savedata(datalist,savepath):
    print("...")
    book = xlwt.Workbook(encodeing="utf-8",style_copression=0)
    sheet = book.add_sheet('职位表单',cell_overwrite_ok=True)
    #定义列
    col = ("公司名字")
    for i in range(0,5):
        sheet.write(0,i,col[i])
    for i in range(0,):
        dta = datalist[i]
        for j in range(0,5):
            sheet.write(i+1,j,data[j])
    book.save(savepath)
if __name__ == "__main__":
    main()
    print("....")
    # init_db("movetest.db")
# 公司名字正则
findcompanyname = re.compile(r'
(.*?)')
# 月薪正则
findsalary = re.compile(r'(.*?)')
# 工作地点正则
findworkposition = re.compile(r'(.*?)')
# 描述正则
# finddescription = re.compile()
# # def init_db(dbpath):
#     sql = '''
#         create table jobtq(
#         id integer primary key autoincrement,
#         findcompanyname text,
#         findsalary text,
#         findtechnologyrequest text,
#         findworkposition text,
#         finddescription text,
#         )
#     '''
#     conn = sqlite3.connect(dbpath)
#     cursor = conn.cursor()
#     cursor.execute(sql)
#     conn.commit()
#     conn.close()


class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        '''
        input: array of size n
        find element that appears more than n/2 times
        array is non empty, majority element always exists
        return that element

        '''

        ## sounds like I want to iterate through the array
        ## maybe store the results in a hash table
        # count how many times each elemnt appears

        # for each element, if count > n/2, return that element

        ## any other ways to do it? probably!

        number_counter = {}

        for item in nums:
            if item in number_counter:
                number_counter[item] += 1
            else:
                number_counter[item] = 1

        print(number_counter)

        n = len(nums)
        print(n/2)

        for key, value in number_counter.items():
            print(number_counter[key])
            if number_counter[key] > n/2:
                print("FOUND")
                return key


from src.common.constants import Constants
from src.common.form import Form

class Form_13(Form):
    URL = ConstantsFORM_13
    URL_DEBUG = URL + "#debug"

    CSS_ZASILKOVY_VYDEJ_CR = "[id^='/zasilkovyVydej/zasilkovyVydejCr']"
    CSS_ZASILKOVY_VYDEJ_ZAHRANICI = "[id^='/zasilkovyVydej/zasilkovyVydejZahranici']"

    def __init__(self, driver):

        file_naming_rules = {
            # regex pro name attribut file inputu : prefix pro nazev souboru s placeholderem pro index
            # na tomto formulari nejsou file inputy
        }

        super().__init__(driver, file_naming_rules)


"""Point cloud generation functions to test benchmarks of rotation invariant functions
"""
from dataclasses import dataclass
from functools import lru_cache

import numpy as np
import torch
from numpy.linalg import norm
from scipy.spatial.transform import Rotation
from scipy.spatial.transform import Rotation as R

def to_torch_tensor(np_array):
    """
    convert a numpy array to a torch tensor by putting it to the appropriate type
    and dimension
    """
    return torch.tensor(np_array).unsqueeze(0).to(torch.float32)

def to_numpy_array(torch_tensor):
    """
    convert a torch tensor to a numpy array by putting it to the appropriate type
    and dimension
    """
    return torch_tensor.squeeze().detach().numpy()

# Rotation and Permutation matrices
def generate_permutation_matrix(N):
    """
    Generate a random permutation matrix
    """
    return np.random.permutation(np.identity(N))

def generate_rotation_matrix(theta=None, axis=None):
    """
    Return a rotation matrix corresponding to a rotation of amplitude theta
    around the provided axis. If an argument is set to None, a random value is assigned
    """
    if theta is None:
        theta = np.random.rand(1)[0] * 2 * np.pi
    if axis is None:
        axis = np.random.rand(3) - 0.5
        axis /= norm(axis)
    return Rotation.from_rotvec(theta * axis).as_matrix()

def rotate(*args):
    """
    Return the rotated version of each tensor passed in parameter using the same rotation
    matrix

    """
    Q = generate_rotation_matrix()
    return [points_tens @ Q for points_tens in args]

# Centering
def center_batch(batch):
    """center a batch

    Args:
        batch (torch.tensor): [n_batch x N_points x 1 x 3]

    Returns:
        [type]: [description]
    """
    mean_input = batch.mean(axis=1).unsqueeze(1)
    return batch - mean_input

def center(sample):
    """
    Center batch to have a barycenter around 0

    Args:
        sample (np.array): N x 3 sample
    """
    return sample - sample.mean(axis=0)

def get_points_on_sphere(N):
    """
    Generate N evenly distributed points on the unit sphere centered at
    the origin. Uses the 'Golden Spiral'.
    Code by Chris Colbert from the numpy-discussion list.
    """
    phi = (1 + np.sqrt(5)) / 2  # the golden ratio
    long_incr = 2 * np.pi / phi  # how much to increment the longitude

    dz = 2.0 / float(N)  # a unit sphere has diameter 2
    bands = np.arange(N)  # each band will have one point placed on it
    z = bands * dz - 1 + (dz / 2)  # the height z of each band/point
    r = np.sqrt(1 - z * z)  # project onto xy-plane
    az = bands * long_incr  # azimuthal angle of point modulo 2 pi
    x = r * np.cos(az)
    y = r * np.sin(az)
    return np.array((x, y, z)).transpose()

def get_angle(u, v):
    """
    Return the angle between 3d vectors u and v
    """
    cos_angle = np.dot(u, v) / norm(u) / norm(v)
    return np.arccos(np.clip(cos_angle, -1, 1))

def get_n_regular_rotations(N):
    """
    Return N regular rotations matrices

    Args:
        N (int): number of rotation matrixes to return
    """
    # generate random points on the unit sphere
    reg_points = get_points_on_sphere(N)

    # take the first vector as the reference one
    ref_vec = reg_points[0]

    # computation of angle and cross product as described here
    # https://math.stackexchange.com/questions/2754627/rotation-matrices-between-two-points-on-a-sphere
    thetas = [get_angle(ref_vec, v) for v in reg_points]
    cross_vecs = np.cross(ref_vec, reg_points)
    rotations = [
        (R.from_rotvec(theta * cross_vec).as_matrix())
        for theta, cross_vec in zip(thetas, cross_vecs)
    ]
    return rotations

# Gaussian Point cloud

def get_gaussian_point_cloud(N_pts):
    return np.random.rand(N_pts, 3)

# Spiral Point cloud

def get_asym_spiral(spiral_amp=1.0, width_factor=1.0, N_pts=40):
    """
    Generate a spiral with the given amplitude

    Args:
        spiral_amp (float, optional): spiral amplitude

    Returns:
        np.array: spiral point cloud
    """
    zline = np.linspace(0, spiral_amp, N_pts)
    xline = [(i + 4) * np.sin(i) / 10 *
             width_factor for i in zline * 4 * np.pi]
    yline = [(i + 4) * np.cos(i) / 10 *
             width_factor for i in zline * 4 * np.pi]
    return np.array([xline, yline, zline]).transpose()

def get_spiral(spiral_amp=1.0, N_pts=40):
    """
    Generate a spiral with the given amplitude

    Args:
        spiral_amp (float, optional): spiral amplitude

    Returns:
        np.array: spiral point cloud
    """
    zline = np.linspace(0, spiral_amp, N_pts)
    xline = np.sin(zline * 4 * np.pi)
    yline = np.cos(zline * 4 * np.pi)
    return np.array([xline, yline, zline]).transpose()

@dataclass(frozen=True)
class SpiralGenerator:
    spiral_amp: float = 1.0
    scaling: float = 1.0
    shift: float = 0.0
    asym: bool = False
    width_factor: float = 1.0
    centering: bool = False

    def __post_init__(self):
        assert(not (self.centering and self.shift != 0))

    @lru_cache(None)
    def generate(self,):
        if self.asym:
            points = get_asym_spiral(
                spiral_amp=self.spiral_amp, width_factor=self.width_factor)
        else:
            points = get_spiral(spiral_amp=self.spiral_amp)

        [xline, yline, zline] = points.transpose()
        zline *= self.scaling
        zline += self.shift
        points = np.array([xline, yline, zline]).transpose()
        if self.centering:
            points = center(points)
        return points

def get_custom_spiral(spiral_amp=1.0, scaling=1.0, shift=0.0, asym=False, centering=False):
    assert(not (centering and shift != 0))

    if asym:
        points = get_asym_spiral(spiral_amp=spiral_amp)
    else:
        points = get_spiral(spiral_amp=spiral_amp)

    [xline, yline, zline] = points.transpose()
    zline *= scaling
    zline += shift
    points = np.array([xline, yline, zline]).transpose()
    if centering:
        points = center(points)
    return points

def get_src_shifted_spirals(
    spiral_amp=1.0, shift=0.5, asym=False, center_input=False, center_target=False
):
    """
    Return vertical src spiral cloud point and its vertically shifted version.
    """
    # torch.set_default_dtype(torch.float64) # works best in float64
    if asym:
        points = get_asym_spiral(spiral_amp=spiral_amp)
    else:
        points = get_spiral(spiral_amp=spiral_amp)
    target_points = np.array([xline, yline, (zline + shift)]).transpose()
    if center_input:
        points = center(points)
    if center_target:
        target_points = center(target_points)
    return points, target_points

def get_src_scaled_spirals(
    spiral_amp=1.0, z_scale=3, asym=False, center_input=False, center_target=False
):
    if asym:
        points = get_asym_spiral(spiral_amp=spiral_amp)
    else:
        points = get_spiral(spiral_amp=spiral_amp)
    [xline, yline, zline] = points.transpose()
    target_points = np.array([xline, yline, zline * z_scale]).transpose()
    if center_input:
        points = center(points)
    if center_target:
        target_points = center(target_points)
    return points, target_points

def get_src_inverted_spirals(spiral_amp=1.0):
    """
    Return inverted spiral with same positions
    """
    points = get_spiral(spiral_amp=spiral_amp)
    [xline, yline, zline] = points
    target_points = np.array([-xline, yline, zline]).transpose()

    return points, target_points


import prometheus_client

broker_state = prometheus_client.Enum(
    'state',
    'Kafka broker state (see https://github.com/confluentinc/librdkafka/blob/master/STATISTICS.md)',
    states=[
        # from https://github.com/confluentinc/librdkafka/blob/v2.2.0/src/rdkafka_broker.c#L83
        'INIT',
        'DOWN',
        'TRY_CONNECT',
        'CONNECT',
        'SSL_HANDSHAKE',
        'AUTH_LEGACY',
        'UP',
        'UPDATE',
        'APIVERSION_QUERY',
        'AUTH_HANDSHAKE',
        'AUTH_REQ',
    ],
    namespace='kafka',
    subsystem='broker',
    labelnames=['name']
)


import pandas as pd
import numpy as np

'''Анализ перемещения 3-х подвесок индукторов на разных сортаментах труб.
Вопрос: На каком типоразмере трубы больше всех перемещается подвеска?'''

# Отображение всех столбцов
desired_width = 500
pd.set_option('display.width', desired_width)
np.set_printoptions(linewidth=desired_width)
pd.set_option('display.max_columns', 10)

def calculation_of_time_for_moving_LTO(df):
    df['Time'] = 200
    df['Thickness'] = df['Thickness'] / 10
    df['Diametr'] = df['Diametr'] / 10
    df['speed_of_roll'] = df['speed_of_roll'].apply(lambda x: float(str(x).replace(',', '.')))
    # Расчет времени на производство трубы в часах
    time_of_produce_pipe_for_frame = \
        df[df['speed_of_roll'] > 100].groupby(['Thickness', 'Diametr'], as_index=False)['Time'].sum()
    time_of_produce_pipe_for_frame['Total_time'] = time_of_produce_pipe_for_frame['Time'] / 360000

    # Рассчет времени на перемещение головки (farward) и обьединение с общей таблицей диаметра и толщины стенки
    # Фильтрация по скорости стана больше 100 мм/мин
    time_of_move_forward_head = \
        df[(df['speed_of_roll'] > 100) & (df['signal_to_move_forward'] == 1.00)].groupby(
            ['Thickness', 'Diametr'], as_index=False)['Time'].sum()
    time_of_move_forward_head['Time_of_move_forward'] = time_of_move_forward_head['Time'] / 360000
    joined_table_for_frame = time_of_produce_pipe_for_frame.merge(time_of_move_forward_head,
                                                                      on=['Thickness', 'Diametr'], how='left')
    joined_table_for_frame['per_of_time_for_move_forward'] = (joined_table_for_frame['Time_of_move_forward'] /
                                                                joined_table_for_frame['Total_time']) * 100

    # Рассчет времени на перемещение головки (backward) и обьединение с общей таблицей диаметра и толщины стенки
    time_of_move_backward_head = \
        df[(df['speed_of_roll'] > 100) & (df['signal_to_move_backward'] == 1.00)].groupby(
            ['Thickness', 'Diametr'], as_index=False)['Time'].sum()
    time_of_move_backward_head['Time_of_move_backward'] = time_of_move_backward_head['Time'] / 360000
    joined_table_for_frame = joined_table_for_frame.merge(time_of_move_backward_head, on=['Thickness', 'Diametr'],
                                                              how='left')
    joined_table_for_frame['per_of_time_for_move_backward'] = (joined_table_for_frame['Time_of_move_backward'] /
                                                                 joined_table_for_frame['Total_time']) * 100
    joined_table_for_frame['Per_of_time_without_moving'] = 100 - joined_table_for_frame['per_of_time_for_move_backward'] - \
                                                  joined_table_for_frame['per_of_time_for_move_forward']
    end_table_for_frame = joined_table_for_frame.drop(['Time_x', 'Time_y', 'Time'], axis=1)
    end_table_for_frame = end_table_for_frame.drop(end_table_for_frame.index[[0]])
    return end_table_for_frame

df_1_frame = pd.read_csv('Data_1_frame.txt', sep=';', encoding='UTF-8')
df_2_frame = pd.read_csv('Data_2_frame.txt', sep=';', encoding='UTF-8')
df_3_frame = pd.read_csv('Data_3_frame.txt', sep=';', encoding='UTF-8')
frames = [df_1_frame,df_2_frame,df_3_frame]
for i in range(len(frames)):
    print('Frame LTO ' + str(i+1))
    print(calculation_of_time_for_moving_LTO(frames[i]))