from commons.utils import utils
import logging
import pandas.io.sql as psql
import pandas as pd
from datetime import datetime, timedelta, date
from sqlalchemy import create_engine
import pytz

# region Subscribers

def calcul_kpi_googletrend():
    logging.warning("calcul_kpi_googletrend - start")

    connection = create_engine(utils.get_connection_string())

    # get data with query
    squery = 'select "id_cryptocompare" as "id_cryptocompare", so."value_standalone", so."timestamp" from social_google_trend so;'

    df = psql.read_sql_query(squery, connection)

    # set index on column timestamp
    df.set_index('timestamp', 'id_cryptocompare', inplace=True)

    # group by crypto
    df2 = df.groupby('id_cryptocompare').last()
    dftoday = df2

    # today's date
    utc = pytz.UTC
    date_after = datetime.combine(date.today(), datetime.min.time())
    date_after = utc.localize(date_after)

    # array of periods on which we want to calculate kpis
    arr = [1, 3, 7, 15, 100]
    for elt in arr:
        date_before = date_after - timedelta(days=elt)
        df_tmp = df
        df_tmp.sort_index(inplace=True)

        # IF elt = 100, take the oldest (no need for truncate)
        if (elt == 100):
            df_tmp = df_tmp.groupby('id_cryptocompare').first()
        else:
            # truncate dataframe to get data on a specific period
            df_tmp = df_tmp.truncate(before=date_before, after=date_after).groupby('id_cryptocompare').first()

        # rename column to avoid problem
        df_tmp.columns = ['col_standalone_' + str(elt)]
        dftoday = dftoday.join(df_tmp)

        dftoday['col_standalone_' + str(elt)] = (dftoday['value_standalone'] - dftoday['col_standalone_' + str(elt)]) / dftoday['col_standalone_' + str(elt)]

    # rename columns
    dftoday.columns = ['value_standalone', 'search_1d_trend', 'search_3d_trend', 'search_7d_trend',
                       'search_15d_trend', 'search_1m_trend']
    dftoday = dftoday.drop('value_standalone', 1)

    # empty table
    connection.execute('delete from kpi_googletrend')

    # insert data into database (last kpis table)
    dftoday.to_sql(name='kpi_googletrend', con=connection, if_exists='append', index=True)

    # insert data into database (table with historical data)
    connection.execute('insert into kpi_googletrend_histo select * from kpi_googletrend')

    logging.warning("calcul_kpi_googletrend - end")

# endregion


for iii in range(int(input())):
    n,c,q=map(int,input().split())
    s=input()
    q1=[]

    for i in range(c):
        q2=list(map(int,input().split()))
        q1.append(q2)

    pre=[n]
    for i in range(c):
        x=pre[i]+q1[i][1]-q1[i][0]+1
        pre.append(x)

    # print(*pre)

    def qwe(x):
        if x<=n:
            return s[x-1]
        dis=-1
        ind=-1
        for i in range(c+1):
            if x<=pre[i]:
                dis=x-pre[i-1]
                ind=i-1
                break
        dis1=q1[ind][0]+dis-1
        # print(dis,dis1)
        return qwe(dis1)

    for i in range(q):
        x=int(input())
        print(qwe(x))

1705C - Mark and His Unfinished Essay .py


# get request
from requests import get
from time import sleep

nums = list(range(1,11))

result = []

for i in nums:
    url = f"https://api.tvmaze.com/shows/{i}"
    response = get(url)
    data = response.json()
    row = [
        data["name"],
        data["genres"],
        data["language"],
        data["premiered"],
        data["ended"]
    ]
    result.append(row)
    sleep(1)

print(result)

# write dataframe
import pandas as pd

df = pd.DataFrame(result, columns=["name", "genres", "language", "premiered", "ended"])

df

# export dataframe to csv
df.to_csv("tvmazeapi.csv")


import openai
from typing import Union
from .helpers import count_tokens

class APICaller:
    """Class to call the OpenAI API"""

    def __init__(
        self,
        api_key: str,
        model: str,
        temperature: Union[float, int],
        max_tokens: int,
        prompt: str,
    ):
        openai.api_key = api_key

        self.model = model
        self.temperature = temperature
        self.max_tokens = max_tokens
        self.prompt = prompt
        self.result = None

    def count_tokens(self) -> int:
        """Count the number of tokens in the prompt."""
        return count_tokens(self.prompt)

    def call_api(self):
        """Call the OpenAI API."""
        result = openai.Completion.create(
            model=self.model,
            prompt=self.prompt,
            max_tokens=self.max_tokens,
            temperature=self.temperature,
        )

        self.result = result

    def get_text_result(self) -> str:
        """Get the text result from the API call."""
        if self.result is None:
            self.call_api()

        return self.result["choices"][0]["text"]

    def __str__(self) -> str:
        """Return the string representation of the object."""
        return str(self.result)


from PyQt5 import QtCore, QtGui, uic, QtWidgets
from PyQt5.QtGui import QMovie
from pathlib import PurePath

window_main = ""
developmental = ""
resource_path = ""

def init(window_mainImport, developmentalImport, resource_pathImport):
    global window_main
    global developmental
    global resource_path
    window_main = window_mainImport
    developmental = developmentalImport
    resource_path = resource_pathImport

    print("Jade Status: INIT")

def setStatus(status):
    # ok
    # load
    # offline

    global window_main
    global resource_path
    if status == "ok":
        if developmental == False:
            pixmap = QtGui.QPixmap(str(resource_path("status_ok.png")))

        elif developmental == True:
            pixmap = QtGui.QPixmap(str(PurePath("assets/icons/status_ok.png")))

        window_main.status.setPixmap(pixmap)

    elif status == "load":
        if developmental == False:
            movie = QMovie(str(resource_path("status_load.gif")))

        elif developmental == True:
            movie = QMovie(str(PurePath("assets/animations/status_load.gif")))

        window_main.status.setMovie(movie)
        movie.start()
        window_main.status.show()

    elif status == "offline":
        if developmental == False:
            pixmap = QtGui.QPixmap(str(resource_path("status_offline.png")))

        elif developmental == True:
            pixmap = QtGui.QPixmap(str(PurePath("assets/icons/status_offline.png")))

        window_main.status.setPixmap(pixmap)

    else:
        print("Status not recognized.")


import numpy as np
from keras.preprocessing import image
from keras.applications import vgg16

model = vgg16.VGG16()

img = image.load_img('aero.jpg', target_size=(224,224,3))

x = image.img_to_array(img)

x = np.expand_dims(x, axis=0)

x = vgg16.preprocess_input(x)

predict = model.predict(x)

predited_classes = vgg16.decode_predictions(predict, top=4)

print('Predictions for this image')

for imagenet_id,name,likelihood in predited_classes[0]:
    print('Predictions: {} - {:2f}'.format(name,likelihood))


# v.1.1.1 - Nicholas Perez-Aguilar
import misc_funcs as mf
import SQLqueries as sql

def get_order_cnt(): # Get the number of orders for a given hour
    new_time = 0
    time = ""

    # Get the requested hour
    while(new_time > 2000 or new_time < 700):
        try:
            new_time = int(input("Pick an hour [0700 -> 2000]: "))
        except ValueError:
            print("Enter a valid number!\n")

    time = mf.time_conv_hr(new_time)

    # Get the query after passing in hour
    query = sql.hour_order_cnt(time)

    # Return search query
    return query

def cancelled_orders(): # Display cancelled message and return query
    mf.space()
    print("Cancelled Orders\n\nOSN\n---")
    query = sql.get_cancelled()

    return query

def get_groupings(): # Get the groupings ('Ambient, 'Frozen, etc.) and OSN's
    mf.space()
    print("\t\t\t\tGeneral Statistics\n")
    print("AMBIENT\t\tCHILLED\t\tFROZEN\t\tUNKNOWN\t\tNone")
    print("------\t\t-------\t\t------\t\t-------\t\t----")

    query = sql.get_type_groupings()

    return query

def print_gen_res(lgst, cnt, ac, cc, fc, uc, nc, al, cl, fl, ul, nl): # This will take all the lists and print the results
    atmp = ""
    ctmp = ""
    ftmp = ""
    utmp = ""
    ntmp = ""

    # Check each list to make sure that the length is not being exceeded
    for i in range(lgst):
        # Ambient
        if(i > (ac - 1)):
            atmp = ""
        else:
            atmp = al[i]

        # Chilled
        if(i > (cc - 1)):
            ctmp = ""
        else:
            ctmp = cl[i]

        # Frozen
        if(i > (fc - 1)):
            ftmp = ""
        else:
            ftmp = fl[i]

        # Unknown
        if(i > (uc - 1)):
            utmp = ""
        else:
            utmp = ul[i]

        # None
        if(i > (nc - 1)):
            ntmp = ""
        else:
            ntmp = nl[i]

#        print("Current i: " + str(i))
#        print("Largest: " + str(lgst))
#        print("Count: " + str(cnt))

        print(str(atmp) + "\t\t" + str(ctmp) + "\t\t" + str(ftmp) + "\t\t" + str(utmp) + "\t\t" + str(ntmp))

def get_deliveries_hour(): # Get query for deliveries in specified hour
    time = 0
    t_str = ""

    try:
        while(time < 700 or time > 2000):
            time = int(input("Enter hour to search: "))

        t_str = mf.time_conv_hr(time)
    except ValueError:
        print("Enter a valid number")

    mf.space()
    print("Deliveries for: {0}\n\nOSN\tLocation\n---\t--------".format(t_str))
    query = sql.get_deliveries_time(t_str)

    return query

def find_order(): # Query to find an order and it's locations
    osn = 0
    try:
        while(osn > 999 or osn < 100):
            osn = int(input("Enter OSN: "))
    except ValueError:
        print("Enter a valid number")

    query = sql.get_order_osn(osn)

    mf.space()
    print("Finding Order for: {0}\n\n Type \tLocation\tRow\tPosition\n------\t--------\t---\t--------".format(osn))

    return query

def get_BR(): # Get the backroom data
    choice = ""
    choices = ["First", "Second", "Dead"]

    mf.space()

    print("BR01\tBR02\tBR03\t|\tBR11\tBR12\tBR13\t|\tBR21\tBR22\tBR23\t|\tBR31\tBR32\tBR33")
    print("----\t----\t----\t|\t----\t----\t----\t|\t----\t----\t----\t|\t----\t----\t----")
#    choice = mf.Menu(choices)
#    if(choice == 1):
#        # Display description
#        print("Showing Current Back Room Orders: OSN | Pos\n")
#        print("BR01\tBR02\tBR03\tBR11\tBR12\tBR13")
#        print("----\t----\t----\t----\t----\t----")
#    elif(choice == 2):
#        # Display description
#        print("Showing Current Back Room Orders: OSN | Pos\n")
#        print("BR21\tBR22\tBR23\tBR31\tBR32\tBR33")
#        print("----\t----\t----\t----\t----\t----")
#    elif(choice == 3):
#        print("Dead Stage Data coming soon!")
#    else:
#        print("Something went wrong!")

    query = sql.get_BR_curr()

    return choice, query
    #print("|492 | 0|\n|-------|\n|469 | 0|")

def print_BR_res(lgst, b01c, b02c, b03c, b11c, b12c, b13c, b21c, b22c, b23c, b31c, b32c, b33c, b01, b02, b03, b11, b12, b13, b21, b22, b23, b31, b32, b33): # This will take all the lists and print the results
    b01tmp = ""
    b02tmp = ""
    b03tmp = ""
    b11tmp = ""
    b12tmp = ""
    b13tmp = ""
    b21tmp = ""
    b22tmp = ""
    b23tmp = ""
    b31tmp = ""
    b32tmp = ""
    b33tmp = ""
    tup = ()

    #print("Choice: " + str(choice))

    # Check each list to make sure that the length is not being exceeded
    for i in range(lgst):
        if(i > (b01c - 1)):
            b01tmp = ""
        else:
            tup = b01[i]
            tmp1 = tup[0]
            tmp2 = tup[1]
            b01tmp = (tmp1 + " | " + tmp2)

        if(i > (b02c - 1)):
            b02tmp = ""
        else:
            tup = b02[i]
            tmp1 = tup[0]
            tmp2 = tup[1]
            b02tmp = (tmp1 + " | " + tmp2)

        if(i > (b03c - 1)):
            b03tmp = ""
        else:
            tup = b03[i]
            tmp1 = tup[0]
            tmp2 = tup[1]
            b03tmp = (tmp1 + " | " + tmp2)

        if(i > (b11c - 1)):
            b11tmp = ""
        else:
            tup = b11[i]
            tmp1 = tup[0]
            tmp2 = tup[1]
            b11tmp = (tmp1 + " | " + tmp2)

        if(i > (b12c - 1)):
            b12tmp = ""
        else:
            tup = b12[i]
            tmp1 = tup[0]
            tmp2 = tup[1]
            b12tmp = (tmp1 + " | " + tmp2)

        if(i > (b13c - 1)):
            b13tmp = ""
        else:
            tup = b13[i]
            tmp1 = tup[0]
            tmp2 = tup[1]
            b13tmp = (tmp1 + " | " + tmp2)

        if(i > (b21c - 1)):
            b21tmp = ""
        else:
            tup = b21[i]
            tmp1 = tup[0]
            tmp2 = tup[1]
            b21tmp = (tmp1 + " | " + tmp2)

        if(i > (b22c - 1)):
            b22tmp = ""
        else:
            tup = b22[i]
            tmp1 = tup[0]
            tmp2 = tup[1]
            b22tmp = (tmp1 + " | " + tmp2)

        if(i > (b23c - 1)):
            b23tmp = ""
        else:
            tup = b23[i]
            tmp1 = tup[0]
            tmp2 = tup[1]
            b23tmp = (tmp1 + " | " + tmp2)

        if(i > (b31c - 1)):
            b31tmp = ""
        else:
            tup = b31[i]
            tmp1 = tup[0]
            tmp2 = tup[1]
            b31tmp = (tmp1 + " | " + tmp2)

        if(i > (b32c - 1)):
            b32tmp = ""
        else:
            tup = b32[i]
            tmp1 = tup[0]
            tmp2 = tup[1]
            b32tmp = (tmp1 + " | " + tmp2)

        if(i > (b33c - 1)):
            b33tmp = ""
        else:
            tup = b33[i]
            tmp1 = tup[0]
            tmp2 = tup[1]
            b33tmp = (tmp1 + " | " + tmp2)

#        print("Current i: " + str(i))
#        print("Largest: " + str(lgst))
#        print("Count: " + str(cnt))

        print(str(b01tmp) + "\t" + str(b02tmp) + "\t" + str(b03tmp) + "\t\t" + str(b11tmp) + "\t" + str(b12tmp) + "\t" + str(b13tmp) + "\t\t" + str(b21tmp) + "\t" + str(b22tmp) + "\t" + str(b23tmp) + "\t\t" + str(b31tmp) + "\t" + str(b32tmp) + "\t" + str(b33tmp))

#        if(choice == 1):
#            print(str(b01tmp) + "\t" + str(b02tmp) + "\t" + str(b03tmp) + "\t" + str(b11tmp) + "\t" + str(b12tmp) + "\t" + str(b13tmp))
#        elif(choice == 2):
#            print(str(b21tmp) + "\t" + str(b22tmp) + "\t" + str(b23tmp) + "\t" + str(b31tmp) + "\t" + str(b32tmp) + "\t" + str(b33tmp))
#        else:
#            print("Something went wrong!")

def find_order_BR(): # Query to find an order and it's locations
    osn = 0
    try:
        while(osn > 999 or osn < 100):
            osn = int(input("Enter OSN: "))
    except ValueError:
        print("Enter a valid number")

    query = sql.get_order_osn_BR(osn)

    mf.space()
    #print("Finding Order for: {0}".format(osn))

    return query, osn

def Print_Backroom_Staging(lgst, b01c, b02c, b03c, b11c, b12c, b13c, b21c, b22c, b23c, b31c, b32c, b33c, b01, b02, b03, b11, b12, b13, b21, b22, b23, b31, b32, b33): # This will take all the lists and print the results
    b01tmp = ""
    b02tmp = ""
    b03tmp = ""
    b11tmp = ""
    b12tmp = ""
    b13tmp = ""
    b21tmp = ""
    b22tmp = ""
    b23tmp = ""
    b31tmp = ""
    b32tmp = ""
    b33tmp = ""

    print("\n")
    print("BR01\tBR02\tBR03\t|\tBR11\tBR12\tBR13\t|\tBR21\tBR22\tBR23\t|\tBR31\tBR32\tBR33")
    print("----\t----\t----\t|\t----\t----\t----\t|\t----\t----\t----\t|\t----\t----\t----")

    # Check each list to make sure that the length is not being exceeded
    for i in range(lgst):
        if(i > (b01c - 1)):
            b01tmp = ""
        else:
            b01tmp = b01[i]

        if(i > (b02c - 1)):
            b02tmp = ""
        else:
            b02tmp = b02[i]

        if(i > (b03c - 1)):
            b03tmp = ""
        else:
            b03tmp = b03[i]

        if(i > (b11c - 1)):
            b11tmp = ""
        else:
            b11tmp = b11[i]

        if(i > (b12c - 1)):
            b12tmp = ""
        else:
            b12tmp = b12[i]

        if(i > (b13c - 1)):
            b13tmp = ""
        else:
            b13tmp = b13[i]

        if(i > (b21c - 1)):
            b21tmp = ""
        else:
            b21tmp = b21[i]

        if(i > (b22c - 1)):
            b22tmp = ""
        else:
            b22tmp = b22[i]

        if(i > (b23c - 1)):
            b23tmp = ""
        else:
            b23tmp = b23[i]

        if(i > (b31c - 1)):
            b31tmp = ""
        else:
            b31tmp = b31[i]

        if(i > (b32c - 1)):
            b32tmp = ""
        else:
            b32tmp = b32[i]

        if(i > (b33c - 1)):
            b33tmp = ""
        else:
            b33tmp = b33[i]

        print(str(b01tmp) + "\t" + str(b02tmp) + "\t" + str(b03tmp) + "\t\t" + str(b11tmp) + "\t" + str(b12tmp) + "\t" + str(b13tmp) + "\t\t" + str(b21tmp) + "\t" + str(b22tmp) + "\t" + str(b23tmp) + "\t\t" + str(b31tmp) + "\t" + str(b32tmp) + "\t" + str(b33tmp))


#opens csv file
input_file = open("songs.csv", "r")
FILES = input_file.readlines()

#intitiating all attributes required for proper function of class
class SongList:
    def __init__(self, list = []):
        self.list = list
        self.file = FILES

        self.count_list = []
        self.learnt_count = []

        self.remainder = [1]

        self.sort_list = []
        self.sort_list_2 = []

        self.sort_artist_list = []
        self.sort_artist_list_2 = []

        self.sort_year_list = []
        self.sort_year_list_2 = []

        self.learnt_list = []
        self.not_learnt_list = []

    #method gets song based on input
    def get_song(self, title):
        for lines in self.list:
            if title in lines:
                return (lines)

    #method adds song into universal list
    def add_song(self, song_name_add, artist_name_add, year_add):
        new_status = "*\n"
        if self.remainder[-1] == 0:
            self.remainder.remove(self.remainder[-1])
        song_to_add = ("{},{},{},{}".format(song_name_add, artist_name_add, year_add, new_status))
        self.file.append(song_to_add)
        self.list.append(song_to_add)
        # self.export.append(song_to_add)

    #method gets the number of songs still required to learn
    def get_num_required(self):
        songs_left = max(self.count_list) - max(self.learnt_count)
        self.remainder.append(songs_left)
        return (songs_left)

    #method gets the number of songs learnt
    def get_num_learnt(self):
        songs_learnt = max(self.learnt_count)
        return (songs_learnt)

    #method gets the total number of songs
    def get_num_total(self):
        total_songs = max(self.count_list)
        return (total_songs)

    #method marks songs in list as learnt
    def mark_learnt(self):
        for songs in self.list:
            component = songs.split(',')
            status = component[3]
            if status == "*":
                new_status = "Learnt"
                new = component[0] + "," + component[1] + "," + component[2] + "," + new_status
                self.learnt_list.append(new)
        print(self.learnt_list)

    #method mark songs in list as not learnt (not used too much)
    def mark_not_learnt(self):
        for songs in self.list:
            component = songs.split(',')
            status = component[3]
            if status == "":
                new_status = "Not Learnt"
                new = component[0] + "," + component[1] + "," + component[2] + "," + new_status
                self.not_learnt_list.append(new)
        print(self.not_learnt_list)

    #method loads the song from the csv file and then appending them to the universal list
    def load_songs(self):
        input_file = open("songs.csv", "r")
        file_read = input_file.readlines()
        count_list = []
        learnt_count = 0
        song_number_count = 0
        for lines in self.file:
            song_number_count += 1
            new_lines = lines.split(",")
            song_name = new_lines[0]
            artist_name = new_lines[1]
            year = new_lines[2]
            status = new_lines[3].replace("n", "*").replace("y", "").replace("\n", "")
            final_song_list = ("{},{},{},{}".format(song_name, artist_name, year, status))
            count_list.append(song_number_count)
            if "*" not in status:
                learnt_count += 1
            self.list.append(final_song_list)
            # self.export.append(final_song_list)
            self.learnt_count.append(learnt_count)
            self.count_list.append(max(count_list))

    #method which sorts song in a particular order (title, artist, year)

    def sort(self):
        for lines in self.list:
            each_line = lines.split(",")
            list_sort = each_line[0] + "," + each_line[1] + "," + each_line[2] + "," + each_line[3]
            self.sort_list.append(list_sort)
        self.sort_list.sort()
        for sorted_items in self.sort_list:
            order = sorted_items.split(",")
            final_sort = order[0] + "," + order[1] + "," + order[2] + "," + order[3]
            self.sort_list_2.append(final_sort)
        return (self.sort_list_2)

    def sort_artist(self):
        for lines in self.list:
            each_line = lines.split(",")
            artist_sort = each_line[1] + "," + each_line[0] + "," + each_line[2] + "," + each_line[3]
            self.sort_artist_list.append(artist_sort)
        self.sort_artist_list.sort()
        for sorted_items in self.sort_artist_list:
            order = sorted_items.split(",")
            final_artist_sort = order[1] + "," + order[0] + "," + order[2] + "," + order[3]
            self.sort_artist_list_2.append(final_artist_sort)
        return (self.sort_artist_list_2)

    def sort_year(self):
        for lines in self.list:
            each_line = lines.split(",")
            year_sort = each_line[2] + "," + each_line[0] + "," + each_line[1] + "," + each_line[3]
            self.sort_year_list.append(year_sort)
        self.sort_year_list.sort()
        for sorted_items in self.sort_year_list:
            order = sorted_items.split(",")
            final_year_sort = order[1] + "," + order[2] + "," + order[0] + "," + order[3]
            self.sort_year_list_2.append(final_year_sort)
        return (self.sort_year_list_2)

    #method saves all songs added into the csv file
    def save_songs(self):
        input_file = open("songs.csv", "w")
        for songs in self.list:
            lines = songs + '\n'
            input_file.write("{}".format(lines))

    #str method returns universal list
    def __str__(self):
        return ("{}".format(self.list))


'''
Created on Mar 4, 2014

@author: kylerogers
'''

class PageHelper:

    @staticmethod
    def get_request_count(request, default_count_per_page, max_count_per_page):
        '''
        Finds the requested number of brothers and corrects it if there are any issues
        If the number is invalid, it will return standard_brothers_per_page
        '''
        brothers_count = request.GET.get('count',str(default_count_per_page))
        try:
            brothers_count = int(brothers_count)
            if brothers_count > max_count_per_page:
                brothers_count = max_count_per_page
        except:
            brothers_count = default_count_per_page
        return brothers_count

    @staticmethod
    def get_page_number(request):
        '''
        Finds the page number and corrects it if there are any issues
        If the page number is invalid, it will return 1
        '''
        page_number = request.GET.get('page','1')
        try:
            page_number = int(page_number)
            if page_number < 1:
                page_number = 1
        except:
            page_number = 1
        return page_number

    @staticmethod
    def calculate_page_range(total_pages, page_number, max_pages_listed_on_screen):
        '''
        This determines which page numbers to show at the bottom of the brothers list pages.
        It returns a list of integers that should be displayed on the page based on the total
        number of pages and the current page number.
        '''
        if total_pages == 1: # If there is only the one page, there is no need to display page numbers
            return []
        elif total_pages <= max_pages_listed_on_screen: # In this case, just display all of the available pages
            min_page_number_displayed = 1
            max_page_number_displayed = total_pages + 1
        elif page_number - max_pages_listed_on_screen / 2 <= 1: # We are near the beginning. In this case, display from page 1 to max_pages_listed_on_screen
            min_page_number_displayed = 1
            max_page_number_displayed = min_page_number_displayed + max_pages_listed_on_screen
        elif page_number + max_pages_listed_on_screen / 2 >= total_pages: # We are near the end. In this case, display from (end - max_pages_listed_on_screen) to end
            max_page_number_displayed = total_pages + 1
            min_page_number_displayed = max_page_number_displayed - max_pages_listed_on_screen
        else: # We are somewhere in the middle. In this case, just display some pages on either side
            min_page_number_displayed = page_number - max_pages_listed_on_screen / 2
            max_page_number_displayed = min_page_number_displayed + max_pages_listed_on_screen

        page_numbers_list = range(min_page_number_displayed,max_page_number_displayed)
        return page_numbers_list


from CustomErrors import *
import pandas as pd
class ReadICNew():
    def __init__(self, filePath):

        self.filePath = filePath
        cleanPath = self.filePath.replace("\\", "/")
        cleanPath = cleanPath.replace("//", "/")
        pathList = cleanPath.split("/")
        self.fileName = pathList[-1]

        self.fluorideIndex = None
        self.acetateIndex = None
        self.formateIndex = None
        self.chlorideIndex = None
        self.nitriteIndex = None
        self.bromideIndex = None
        self.nitrateIndex = None
        self.sulfateIndex = None
        self.phosphateIndex = None

        self.lithiumIndex = None
        self.sodiumIndex = None
        self.ammoniumIndex = None
        self.potassiumIndex = None
        self.magnesiumIndex = None
        self.calciumIndex = None
        self.strontiumIndex = None

        self.fluoride = None
        self.acetate = None
        self.formate = None
        self.chloride = None
        self.nitrite = None
        self.bromide = None
        self.nitrate = None
        self.sulfate = None
        self.phosphate = None
        self.anionDate = None
        self.anionTime = None

        self.lithium = None
        self.sodium = None
        self.ammonium = None
        self.potassium = None
        self.magnesium = None
        self.calcium = None
        self.strontium = None
        self.cationDate = None
        self.cationTime = None

        self.sortChem = None
        self.rowContainsAnion = False
        self.rowContainsCation = False

        self.anionNameIndex = None
        self.cationNameIndex = None

        self.headerLine = None
        self.anion = False
        self.cation = False

        self.data = None

    def readBatch(self):

        # get the filename
        fileNameList = self.fileName.split(".")

        if len(fileNameList) != 4:
            raise ICPFileNotNamedCorrectly(self.fileName)

        self.runDate = fileNameList[0]
        self.projectId = fileNameList[1]
        self.operator = fileNameList[2]

        self.projectId = self.projectId.replace(" ","")

        # fix the date
        year = self.runDate[0:2]
        month = self.runDate[2:4]
        day = self.runDate[4:6]
        year = "20" + year
        self.runDate = year + "-" + month + "-" + day

        with open(self.filePath) as file:
            l = 0
            for line in file:
                # print(line)
                line = line.split(",")
                if l == 0:
                    i = 0
                    for item in line:
                        if "name" in item.lower():
                            self.nameIndex = i
                        if "amount" in item.lower():
                            amountStartIndex = i
                            break
                        i = i + 1
                    for i in range(amountStartIndex + 1, len(line)):
                        if line[i] != "":
                            amountStopIndex = i
                            break
                        i = i + 1
                # now locate the line where the other headers are and the line where the data start
                for i in range(len(line)):
                    line[i] = line[i].lower()
                if ("lithium" in line) or ("sodium" in line) or ("ammonium" in line) or ("potassium" in line) or (
                        "magnesium" in line) or ("calcium" in line) or ("strontium" in line):
                    self.headerLine = l
                    self.cation = True
                    print("cation header line: " + str(l))

                elif ("fluoride" in line) or ("acetate" in line) or ("formate" in line) or ("chloride" in line) or (
                        "nitrite" in line) or ("sulfate" in line) or ("bromide" in line) or ("nitrate" in line) or (
                        "phosphate" in line):
                    self.headerLine = l
                    print("anion header line: " + str(l))
                    self.anion = True

                if self.headerLine != None:
                    if l == self.headerLine:
                        if self.cation:
                            for i in range(amountStartIndex, amountStopIndex):
                                # get the index of each
                                if "lithium" in line[i].lower():
                                    self.lithiumIndex = i
                                elif "sodium" in line[i].lower():
                                    self.sodiumIndex = i
                                elif "ammonium" in line[i].lower():
                                    self.ammoniumIndex = i
                                elif "potassium" in line[i].lower():
                                    self.potassiumIndex = i
                                elif "magnesium" in line[i].lower():
                                    self.magnesiumIndex = i
                                elif "calcium" in line[i].lower():
                                    self.calciumIndex = i
                                elif "strontium" in line[i].lower():
                                    self.strontiumIndex = i

                        if self.anion:
                            for i in range(amountStartIndex, amountStopIndex):
                                if "fluoride" in line[i].lower():
                                    self.fluorideIndex = i
                                elif "acetate" in line[i].lower():
                                    self.acetateIndex = i
                                elif "formate" in line[i].lower():
                                    self.formateIndex = i
                                elif "chloride" in line[i].lower():
                                    self.chlorideIndex = i
                                elif "nitrite" in line[i].lower():
                                    self.nitriteIndex = i
                                elif "bromide" in line[i].lower():
                                    self.bromideIndex = i
                                elif "nitrate" in line[i].lower():
                                    self.nitrateIndex = i
                                elif "sulfate" in line[i].lower():
                                    self.sulfateIndex = i
                                elif "phosphate" == line[i].lower():
                                    self.phosphateIndex = i
                        break
                l = l + 1

        dataDict = {}
        # make a data dictionary
        if self.nameIndex != None:
            dataDict["sort_chem"] = []
        if self.lithiumIndex != None:
            dataDict["lithium"] = []
        if self.sodiumIndex != None:
            dataDict["sodium"] = []
        if self.ammoniumIndex != None:
            dataDict["ammonium"] = []
        if self.potassiumIndex != None:
            dataDict["potassium"] = []
        if self.magnesiumIndex != None:
            dataDict["magnesium"] = []
        if self.calciumIndex != None:
            dataDict["calcium"] = []
        if self.strontiumIndex != None:
            dataDict["strontium"] = []

        if self.fluorideIndex != None:
            dataDict["fluoride"] = []
        if self.acetateIndex != None:
            dataDict["acetate"] = []
        if self.formateIndex != None:
            dataDict["formate"] = []
        if self.chlorideIndex != None:
            dataDict["chloride"] = []
        if self.nitriteIndex != None:
            dataDict["nitrite"] = []
        if self.bromideIndex != None:
            dataDict["bromide"] = []
        if self.nitrateIndex != None:
            dataDict["nitrate"] = []
        if self.sulfateIndex != None:
            dataDict["sulfate"] = []
        if self.phosphateIndex != None:
            dataDict["phosphate"] = []

        # save all the relevant data in a new dict
        with open(self.filePath) as file:
            l = 0
            for row in file:
                if l > (self.headerLine):
                    row = row.split(",")

                    if self.nameIndex != None:
                        if row[self.nameIndex] != "":
                            dataDict["sort_chem"].append(row[self.nameIndex])
                            # cations
                            if self.lithiumIndex != None:
                                dataDict["lithium"].append(row[self.lithiumIndex])
                            if self.sodiumIndex != None:
                                dataDict["sodium"].append(row[self.sodiumIndex])
                            if self.ammoniumIndex != None:
                                dataDict["ammonium"].append(row[self.ammoniumIndex])
                            if self.potassiumIndex != None:
                                dataDict["potassium"].append(row[self.potassiumIndex])
                            if self.magnesiumIndex != None:
                                dataDict["magnesium"].append(row[self.magnesiumIndex])
                            if self.calciumIndex != None:
                                dataDict["calcium"].append(row[self.calciumIndex])
                            if self.strontiumIndex != None:
                                dataDict["strontium"].append(row[self.strontiumIndex])

                            # anions
                            if self.fluorideIndex != None:
                                dataDict["fluoride"].append(row[self.fluorideIndex])
                            if self.acetateIndex != None:
                                dataDict["acetate"].append(row[self.acetateIndex])
                            if self.formateIndex != None:
                                dataDict["formate"].append(row[self.formateIndex])
                            if self.chlorideIndex != None:
                                dataDict["chloride"].append(row[self.chlorideIndex])
                            if self.nitriteIndex != None:
                                dataDict["nitrite"].append(row[self.nitriteIndex])
                            if self.bromideIndex != None:
                                dataDict["bromide"].append(row[self.bromideIndex])
                            if self.nitrateIndex != None:
                                dataDict["nitrate"].append(row[self.nitrateIndex])
                            if self.sulfateIndex != None:
                                dataDict["sulfate"].append(row[self.sulfateIndex])
                            if self.phosphateIndex != None:
                                dataDict["phosphate"].append(row[self.phosphateIndex])

                l = l + 1

                # locate the name index
                # locate the amount index to the next thing
        self.data = pd.DataFrame.from_dict(dataDict)
        # print(self.data)
        # print("here")

    def fixDate(self, date):
        date = date.replace(" ", "") # remove any extra space
        newDate = ""
        for c in date: # change the delimiter from anything else to "-"
            if not c.isalnum():
                newDate = newDate + "-"
            else:
                newDate = newDate + c

        newDateList = newDate.split("-")
        month = newDateList[0]
        day = newDateList[1]
        year = newDateList[2]
        if len(day) == 1:
            day = str(0) + str(day)
        if len(month) == 1:
            month = str(0) + str(month)
        newDate = year + "-" + month + "-" + day

        return newDate

    def fixTime(self, time, meridian):
        time = time.replace(" ", "")
        if "pm" in meridian.lower():
            hour,minute,second = time.split(":")
            hour = int(hour) + 12
            time = str(hour) + ":" + minute + ":" + second
        return time

    def replaceNA(self, string):
        if str(string).lower() == "n.a.":
            return None
        elif str(string).lower() == "nan":
            return None
        else:
            return string

    def isNan(self, num):
        return num == "nan"

    def resetValues(self):
        self.sortChem = None
        self.fluoride = None
        self.acetate = None
        self.formate = None
        self.chloride = None
        self.nitrite = None
        self.bromide = None
        self.nitrate = None
        self.sulfate = None
        self.phosphate = None

        self.lithium = None
        self.sodium = None
        self.ammonium = None
        self.potassium = None
        self.magnesium = None
        self.calcium = None
        self.strontium = None

    def readRow(self, row):
        self.resetValues()

        # print(row)
        if self.nameIndex != None:
            self.sortChem = self.replaceNA(row["sort_chem"])
        if self.fluorideIndex != None:
            self.fluoride = self.replaceNA(row["fluoride"])
        if self.acetateIndex != None:
            self.acetate = self.replaceNA(row["acetate"])
        if self.formateIndex != None:
            self.formate = self.replaceNA(row["formate"])
        if self.chlorideIndex != None:
            self.chloride = self.replaceNA(row["chloride"])
        if self.nitriteIndex != None:
            self.nitrite = self.replaceNA(row["nitrite"])
        if self.bromideIndex != None:
            self.bromide = self.replaceNA(row["bromide"])
        if self.nitrateIndex != None:
            self.nitrate = self.replaceNA(row["nitrate"])
        if self.sulfateIndex != None:
            self.sulfate = self.replaceNA(row["sulfate"])
        if self.phosphateIndex != None:
            self.phosphate = self.replaceNA(row["phosphate"])

        if self.lithiumIndex != None:
            self.lithium = self.replaceNA(row["lithium"])
        if self.sodiumIndex != None:
            self.sodium = self.replaceNA(row["sodium"])
        if self.ammoniumIndex != None:
            self.ammonium = self.replaceNA(row["ammonium"])
        if self.potassiumIndex != None:
            self.potassium = self.replaceNA(row["potassium"])
        if self.magnesiumIndex != None:
            self.magnesium = self.replaceNA(row["magnesium"])
        if self.calciumIndex != None:
            self.calcium = self.replaceNA(row["calcium"])
        if self.strontiumIndex != None:
            self.strontium = self.replaceNA(row["strontium"])


class KthLargest:

    def __init__(self, k: int, nums: List[int]):
        self.h = nums[:k]
        self.k = k

        heapify(self.h)

        for i in range(k, len(nums)):
            self.add(nums[i])

    def add(self, val: int) -> int:
        if len(self.h) < self.k:
            heappush(self.h, val)
        elif self.h[0] < val:
            heappop(self.h)
            heappush(self.h, val)

        return self.h[0]


import os
import sys
import re

DEBUG = True

STORAGE_PATH = None

TAGS_3D_REGEX = ''

def pathIs3D(path):
    return bool(re.search(TAGS_3D_REGEX, path))

class Progress:
    def __init__(self, title=''):
        self.title = title
        self.pct = 0
        self.message = ''
        self.heading = ''

    def __enter__(self):
        print('[- {0} -]'.format(self.title))
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        print('DONE')

    def msg(self, message=None, heading=None, pct=None):
        self.pct = pct is not None and pct or self.pct
        self.heading = heading is not None and heading or self.heading
        self.message = message is not None and message or self.message
        print('{0}% {1}: {2}'.format(self.pct, self.heading, self.message))
        return True

def getSep(path):
    if '\\' not in path:
        return '/'
    if '/' not in path:
        return '\\'
    if path.rindex('\\') > path.rindex('/'):
        return '\\'
    return '/'

def _getSettingDefault(key):
    defaults = {
        'feature.count': 1,
        'feature.ratingBumper': 'video',
        'feature.ratingStyleSelection': 'random',
        'feature.ratingStyle': 'Classic',
        'feature.volume': 100,
        'trivia.format': 'slide',
        'trivia.duration': 10,
        'trivia.qDuration': 8,
        'trivia.cDuration': 6,
        'trivia.aDuration': 6,
        'trivia.sDuration': 10,
        'trivia.transition': 'fade',
        'trivia.transitionDuration': 400,
        'trivia.musicFile': '',
        'trivia.musicDir': '',
        'trailer.source': 'content',
        'trailer.scrapers': 'Content,KodiDB,iTunes',
        'trailer.order': 'newest',
        'trailer.count': 1,
        'trailer.limitGenre': True,
        'trailer.filter3D': True,
        'trailer.quality': '720p',
        'trailer.dir': '',
        'trailer.file': '',
        'trailer.volume': 100,
        'audioformat.method': 'af.detect',
        'audioformat.fallback': 'af.format',
        'audioformat.file': '',
        'audioformat.format': 'Other',
        'audioformat.volume': 100,
        'video.volume': 100,
        # Non-sequence defaults
        'bumper.fallback2D': False,
        'trivia.music': 'content',
        'trivia.musicVolume': 75,
        'trivia.musicFadeIn': 3.0,
        'trivia.musicFadeOut': 3.0,
        'trailer.ratingMax': 'MPAA.G',
        'trailer.preferUnwatched': True,
        'rating.system.default': 'MPAA'
    }

    return defaults.get(key)

try:
    import xbmcvfs
    import xbmc
    import xbmcaddon
    import stat
    import time

    STORAGE_PATH = xbmcvfs.translatePath(xbmcaddon.Addon().getAddonInfo('profile'))
    _T = xbmcaddon.Addon().getLocalizedString

    def T(ID, eng=''):
        return _T(ID)

    class VFS:
        def __getattr__(self, attr):
            return getattr(xbmcvfs, attr)

        def listdir(self, path):
            lists = xbmcvfs.listdir(path)
            return [x for x in lists[0] + lists[1]]

        class File(xbmcvfs.File):
            def __init__(self, *args, **kwargs):
                xbmcvfs.File.__init__(self)
                self._size = self.size()  # size() returns size at open, so we need to keep track ourselves
                self._pos = 0

            def __enter__(self):
                return self

            def __exit__(self, exc_type, exc_value, traceback):
                self.close()

            def flush(self):
                pass

            def tell(self):
                return self._pos

            def read(self, nbytes=-1):
                if nbytes == 0:
                    return ''
                elif nbytes < 0:
                    nbytes = 0

                self._pos += nbytes
                if self._pos >= self._size or not nbytes:
                    self._pos = self._size - 1

                return xbmcvfs.File.read(self, nbytes)

            def write(self, data):
                self._pos += len(data)
                self._size = max(self._pos, self._size)
                return xbmcvfs.File.write(self, data)

            def seek(self, offset, whence=0):
                if whence == 0:
                    self._pos = 0
                elif whence == 2:
                    self._pos = self._size - 1
                self._pos += offset
                return xbmcvfs.File.seek(self, offset, whence)

    vfs = VFS()

    def pathJoin(*args):
        args = list(args)
        sep = getSep(args[0])
        ret = [args.pop(0).rstrip('/\\')]
        tail = args.pop(-1).lstrip('/\\')
        for a in args:
            ret.append(a.strip('/\\'))
        repl = sep == '\\' and re.escape(sep) or sep
        ret.append(re.sub(r'[/\\]+', repl, tail))
        return sep.join(ret)

    def isDir(path):
        vstat = xbmcvfs.Stat(path)
        return stat.S_ISDIR(vstat.st_mode())

    def translatePath(path):
        if path.startswith('special://'):
            return xbmcvfs.translatePath(path)

        return path

    def LOG(msg):
        xbmc.log('[- CinemaVision -] (API): {0}'.format(msg), xbmc.LOGINFO)

    try:
        xbmc.Monitor().waitForAbort

        def wait(timeout):
            return xbmc.Monitor().waitForAbort(timeout)
    except:
        def wait(timeout):
            start = time.time()
            while not xbmc.Monitor().abortRequested and time.time() - start < timeout:
                xbmc.sleep(100)
            return xbmc.Monitor().abortRequested

    def getSettingDefault(key):
        default = xbmcaddon.Addon().getSetting(key)

        if default == '':
            return _getSettingDefault(key)

        if key == 'trailer.source':
            return ['content', 'dir', 'file'][int(default)]
        elif key == 'trailer.ratingLimit':
            return ['none', 'max', 'match'][int(default)]
        elif key == 'trailer.order':
            return ['newest', 'random'][int(default)]
        elif key == 'trivia.format':
            return ['slide', 'video'][int(default)]
        elif key == 'trivia.music':
            return ['off', 'content', 'dir', 'file'][int(default)]
        elif key == 'audioformat.method':
            return ['af.detect', 'af.format', 'af.file'][int(default)]
        elif key == 'audioformat.fallback':
            return ['af.format', 'af.file'][int(default)]
        elif key == 'trivia.transition':
            return ['none', 'fade', 'slideL', 'slideR', 'slideU', 'slideD'][int(default)]
        elif key == 'audioformat.format':
            return [
                'Auro-3D', 'Dolby Digital', 'Dolby Digital Plus', 'Dolby TrueHD',
                'Dolby Atmos', 'DTS', 'DTS-HD Master Audio', 'DTS-X', 'Datasat', 'THX', 'Other'
            ][int(default)]
        elif key == 'feature.ratingBumper':
            return ['none', 'video', 'image'][int(default)]
        elif key == 'feature.ratingStyleSelection':
            return ['random', 'style'][int(default)]
        elif default in ['true', 'false']:
            return default == 'true'
        elif default.isdigit():
            return int(default)

        try:
            return float(default.replace(',', '.'))
        except ValueError:
            pass

        return default

    def contentScrapers():
        ret = []
        for stype, scraper, default in (
            ('trailers', 'iTunes', True),
            ('trailers', 'KodiDB', True),
            ('trailers', 'TMDB', True),
            ('trailers', 'Content', False)
        ):
            sett = xbmcaddon.Addon().getSetting('scraper.{0}.{1}'.format(stype, scraper))
            if sett in ('true', 'false'):
                sett = sett == 'true'
            else:
                sett = default

            if sett:
                ret.append((stype, scraper))

        return ret

    videoExtensions = tuple(xbmc.getSupportedMedia('video').split('|') + ['.cvurl'])
    musicExtensions = tuple(xbmc.getSupportedMedia('music').split('|'))
    imageExtensions = tuple(xbmc.getSupportedMedia('picture').split('|'))

except:
    raise
    import zipfile

    STORAGE_PATH = '~'

    def T(ID, eng=''):
        return eng

    def vfs():
        pass

    class InsideZipFile(zipfile.ZipFile):
        def __init__(self, *args, **kwargs):
            zipfile.ZipFile.__init__(self, *args, **kwargs)
            self._inner = None

        def setInner(self, inner):
            self._inner = inner

        def read(self, bytes=-1):
            return self._inner.read(bytes)

    vfs.mkdirs = os.makedirs

    def exists(path):
        if '.zip' in path:  # This would fail in an uncontrolled setting
            zippath, inpath = path.split('.zip', 1)
            zippath = zippath + '.zip'
            inpath = inpath.lstrip(os.path.sep)
            z = zipfile.ZipFile(zippath, 'r')
            try:
                z.getinfo(inpath)
                return True
            except KeyError:
                return False

        return os.path.exists(path)

    vfs.exists = exists

    def File(path, mode):
        if '.zip' in path:  # This would fail in an uncontrolled setting
            zippath, inpath = path.split('.zip', 1)
            zippath = zippath + '.zip'
            inpath = inpath.lstrip(os.path.sep)
            z = InsideZipFile(zippath, 'r')
            i = z.open(inpath)
            z.setInner(i)
            return z

        return open(path, mode)

    vfs.File = File

    def listdir(path):
        if path.lower().endswith('.zip'):
            z = zipfile.ZipFile(path, 'r')
            items = z.namelist()
            z.close()
            return items
        return os.listdir(path)

    vfs.listdir = listdir

    def pathJoin(*args):
        return os.path.join(*args)

    def isDir(path):
        return os.path.isdir(path)

    def translatePath(path):
        return path

    def LOG(msg):
        print('[- CinemaVison -] (API): {0}'.format(msg))

    def wait(timeout):
        time.sleep(timeout)
        return False

    def getSettingDefault(key):
        return _getSettingDefault(key)

    def contentScrapers():
        return []

    videoExtensions = ('.mp4',)
    musicExtensions = ('.mp3', '.wav')
    imageExtensions = ('.jpg', '.png')

def listFilePaths(path):
    ret = []
    for f in vfs.listdir(path):
        full = pathJoin(path, f)
        if not isDir(full):
            ret.append(full)
    return ret

def strRepr(str_obj):
    ret = repr(str_obj).lstrip('u')
    return ret.endswith('"') and ret.strip('"') or ret.strip("'")

def datetimeTotalSeconds(td):
    return float((td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6)) / 10**6

def DEBUG_LOG(msg):
    if DEBUG:
        LOG(msg)

def ERROR(msg=None):
    if msg:
        LOG(msg)
    import traceback
    traceback.print_exc()

def MINOR_ERROR(msg=''):
    short = str(sys.exc_info()[1])
    LOG('MINOR ERROR: {0}{1}'.format(msg and '{0} - '.format(msg) or '', short))


import pygame
import menu
import colors
import dialogs_list

color = colors.Color()

class Diologs(object):
    def __init__(self, id, setting):
        language = {"Русский": "ru", "English": "en"}
        self.person = id['person_' + language[setting.language]]
        self.with_who = id['with_who']
        self.who_talk = id['who_talk']
        self.fill = id['fill']
        self.message = id[language[setting.language]]
        self.cicle(setting)

    def cicle(self, setting):
        for i in range(len(self.who_talk)):
            windows(setting, self.person[self.who_talk[i]], text_separation(self.message[i]), self.with_who, self.fill)

def windows(setting, who_says, text, who_second, fill):
    clock = pygame.time.Clock()
    Ayur = Character("left", "Ayur\\right\\right-stand-", 35, setting.wight)
    if who_second != "" and who_second != "NB" and who_second != "Au":
        second_person = Character("right", who_second, 40, setting.wight)
    while 1:
        clock.tick(10)
        setting.screen.blit(fill[0], (fill[1], 0))
        Ayur.draw(setting.screen)
        if who_second != "" and who_second != "NB" and who_second != "Au":
            second_person.draw(setting.screen)
        font = pygame.font.SysFont('Comic Sans MS', 40)
        pygame.draw.rect(setting.screen, color.WHITE, (-1, 450, setting.wight + 2, 400))
        pygame.draw.rect(setting.screen, color.GREY_BLUE, (-1, 450, setting.wight + 2, 50))
        menu.text(setting.screen, font, str(who_says) + ":", setting.wight / 4, 470, color.BLACK)
        font = pygame.font.SysFont('Comic Sans MS', 25)
        y = 530
        for i in text:
            message = font.render(i, True, color.BLACK)
            text_rect = message.get_rect(center=(0, y))
            text_rect.left = setting.wight / 6
            setting.screen.blit(message, text_rect)
            y += 30
        menu.text(setting.screen, font, "E", setting.wight - 20, 700, color.PURPLE)
        pygame.display.update()
        if button(setting):
            break

def button(setting):
    for event in pygame.event.get():
        if event.type == pygame.QUIT and menu.are_you_sure(setting):
            exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_e or event.key == pygame.K_RETURN:
                return True
    return False

def show_character(setting, who, emotion, left_right):
    img = str(who)
    if left_right == "left":
        pygame.draw.rect(setting.screen, color.WHITE, (50, 50, 300, 500))
    else:
        pygame.draw.rect(setting.screen, color.WHITE, (setting.wight - 350, 50, 300, 500))

def text_separation(text):
    text = text.split(' ')
    message = []
    box = ""
    for i in text:
        if len(box + i) + 1 > 58:
            message.append(box)
            box = i
        else:
            box += " " + i
    message.append(box)
    return message

class Character(object):
    def __init__(self, position, directory, breath, wight):
        self.animation = 0
        if position == "left":
            self.position = 90
        else:
            self.position = wight - 200
        self.directory = directory
        self.image = pygame.image.load(str(directory)+"1.png")
        self.breath = breath

    def draw(self, screen, size = (176, 650)):
        if self.animation > self.breath:
            self.animation = 0
        img = str(self.directory) + str(self.animation // (self.breath // 2 + 1) + 1) + ".png"
        img = pygame.image.load(img)
        img = pygame.transform.scale(img, size)
        rect = self.image.get_rect(center=(self.position, 300))
        screen.blit(img, rect)
        self.animation += 1


import typing

import discord
import aiosqlite
from discord.ext import commands
from discord import app_commands
from bot import Unreal

class EconomyCog(commands.Cog):
    name = "Economy"
    bot: Unreal
    eco = app_commands.Group(
        name="economy", description="Commands related to economy system."
    )

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

    async def cog_load(self):
        self.db = db = await aiosqlite.connect("db/economy.sqlite")
        async with db.execute(
            """CREATE TABLE IF NOT EXISTS economy
            (user_id TEXT PRIMARY KEY, coins BIGINT DEFAULT 100, cash BIGINT DEFAULT 0)
            """
        ):
            await db.commit()

    async def _create_account(self, user_id):
        try:
            async with self.db.execute(
                """INSERT INTO economy (user_id)
                VALUES (?)
                """,
                (str(user_id),),
            ):
                await self.db.commit()
            return True
        except:
            return False

    async def _fetch_account(self, user_id):
        async with self.db.execute(
            """SELECT coins, cash FROM economy WHERE user_id = ?
            """,
            (str(user_id),),
        ) as cur:
            return await cur.fetchone()

    async def _add_bal(self, user_id, coins=0, cash=0):
        try:
            async with self.db.execute(
                f"""UPDATE economy
                SET coins = coins + {coins}, cash = cash + {cash}
                WHERE user_id = {str(user_id)}
                """
            ):
                await self.db.commit()
            return False
        except:
            return True

    @eco.command(
        name="register",
    )
    async def register_cmd(self, i: discord.Interaction) -> None:
        """Register yourself to the Chuck Economy System!"""
        uid = i.user.id
        _ch = await self._fetch_account(uid)
        if _ch:
            await i.response.send_message("You already have an account!")
        else:
            await self._create_account(uid)
            em = discord.Embed(
                title="Welcome to Chuck Economy System!", colour=discord.Colour.gold()
            )
            await i.response.send_message(embed=em)

async def setup(bot: Unreal):
    await bot.add_cog(EconomyCog(bot))


env = {
    "metadata":
    {
      "host": "codexbackend_db_1",
      "port": 27017
      },
    "files":
    {
      "host": "codexbackend_db_1",
      "port": 27017
      },
    "temp_files":
    {
      "host": "codexbackend_db_2",
      "port": 27017
      },
    "versions":
    {
      "host": "codexbackend_db_1",
      "port": 27017
      },
    "redis":
    {
      "host": "codexbackend_redis_1",
      "port": 6379
      },
    "temporal_files_db": False,
    "db_temp_files_name": "DB_temp_files",
    "db_files_name": "DB_files",
    "db_versions_name": "DB_versions",
    "db_metadata_name": "DB_metadata",
    "db_metadata_collection": "meta_container",
    "vt_private_apikey": "",
    "vt_public_apikey": "",
    'yara-script1': '/myapp/yara/YaraGenerator/yaraGenerator.py',
    'yara-script2': '/myapp/yara/yarGen-master/yarGen.py',
    'csv-upx-file': '',
    'auto_get_av_result': False,
    'debug': False,
    'spend_credit_to_fix_inconsistency': False,
    "mailsender":
    {
        "fromaddr": "",
        "smtp_host": "smtp.gmail.com",
        "smtp_ssl_port": 465,
        "username": '',
        "password": ''
        }
    }


import re

from ccks_all.esret import jaccard_sim, expand_sim_es

def dsc_token(text: str):
    fds = re.findall(r"《([^《|》]*)》", text)
    for fd_str in fds:
        fd_str = fd_str.strip()
        ind = text.find(fd_str)
        yield fd_str, ind

# que = "《会计制度设计(第五版)》(李端生 编)【简介_书评"
que = "《枫之谷2》可爱冒险登场!今年内韩服开测"
que = "《枫之谷2》可爱冒险登场!今年内韩服开测"
dsc_entity = dsc_token(que)

for keyword in dsc_entity:
    sres = expand_sim_es(keywords=keyword[0], index_str="subject_text", jaccard_filt=0.6)
    for sre in sres:
        print(str(sre))
        print(jaccard_sim(keyword[0], sre))


# -*- coding: utf-8 -*-
"""
While29. e haqiqiy musbat soni berilgan. Ketma - ketlik xadlari quyidagicha aniqlanadi:
a1=1; a2=2; ak = ( ak – 2 + 2 * ak - 1 ) / 3; k = 3, 4, …
|ak – ak-1| < e shartni qanoatlantiruvchi eng kichik k sonini aniqlovchi programma tuzilsin.
ak va ak – 1 ham ekranga chiqarilsin.

Created on Wed Jun 30 07:07:04 2021

@author: Mansurjon Kamolov
"""

e=float(input('e='))
if e>0 :
    a=1
    ak=2
    k=2
    while abs(ak-a)<e:
        k+=1
        ak=a+2*ak
        a=ak

        print(k, ak, a)

else:
    print('e soni musbat bo\'lishi kerak!')


import socket
import dns.resolver
import re

def is_valid_ip(address):  # 判断IP地址
    pattern = r'^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$'
    if re.match(pattern, address):
        return True
    else:
        return False

def resolve_dns_with_fallback(domain):
    try:
        # 创建 DNS 解析器
        resolver = dns.resolver.Resolver()

        # 尝试解析 A 记录
        try:
            a_records = resolver.resolve(domain, 'A')
            server_address_a = str(a_records[0])
            return server_address_a
        except dns.resolver.NoAnswer:
            pass  # 没有 A 记录，继续尝试解析 CNAME 记录
        except dns.exception.DNSException as e:
            print("Error resolving A record:", e)

        # 尝试解析 CNAME 记录
        try:
            cname_records = resolver.resolve(domain, 'CNAME')
            cname_target = str(cname_records[0].target).rstrip('.')
            # 递归解析 CNAME 记录的目标
            return resolve_dns_with_fallback(cname_target)
        except dns.resolver.NoAnswer:
            pass  # 没有 CNAME 记录，继续尝试解析 AAAA 记录
        except dns.exception.DNSException as e:
            print("Error resolving CNAME record:", e)

        # 尝试解析 AAAA 记录
        try:
            aaaa_records = resolver.resolve(domain, 'AAAA')
            server_address_aaaa = str(aaaa_records[0])
            return server_address_aaaa
        except dns.resolver.NoAnswer:
            pass  # 没有 AAAA 记录，解析失败
        except dns.exception.DNSException as e:
            print("Error resolving AAAA record:", e)

        return None  # 所有尝试都失败，返回 None

    except dns.exception.DNSException as e:
        print("Error:", e)
        return None

def scanner(ip):
    target_ports = [21, 22, 23, 25, 53, 69, 80, 107, 135, 139, 110, 443, 888, 666, 1433, 3306, 3309, 3389, 8080,
                    8888, 19132, 25565]
    for port in target_ports:
        run(ip,port)

def run(ip,port):
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(1)
        s.connect((ip, port))
        print(f"端口 {port} 开放")
        s.close()
    except socket.timeout:
        print(f"端口 {port} X")
    except socket.error as e:
        if e.errno == 10061:  # 端口未开放
            print(f"端口 {port} x")
        else:
            print(f"忽略错误: {e}")

ip = input("请输入ip或者域名\n")
port2 = int(input("请输入端口\n"))
if is_valid_ip(ip):
    print(ip)
else:
    ip = resolve_dns_with_fallback(ip)
    print(ip)
run(ip,port2)
while True:
    user_input = input("请选择一个选项（1扫端口、2扫默认端口、3关闭）：")

    if user_input == "1":
        port2 = int(input("请输入端口\n"))
        run(ip, port2)

    elif user_input == "2":
        print("你选择了选项2")
        scanner(ip)

    elif user_input == "3":
        print("关闭程序")
        # 在这里添加选项3的代码
        break  # 结束循环

    else:
        print("无效的输入，请输入1、2或3")


import unittest

import requests.exceptions

import responses

from seaworthy.checks import docker_client, dockertest
from seaworthy.client import ContainerHttpClient, wait_for_response
from seaworthy.definitions import ContainerDefinition
from seaworthy.helpers import DockerHelper, fetch_images

# Small (<4MB) image that echoes HTTP requests and runs without configuration
IMG = 'jmalloc/echo-server'

@dockertest()
def setUpModule():  # noqa: N802 (The camelCase is mandated by unittest.)
    with docker_client() as client:
        fetch_images(client, [IMG])

def echo_container(name, **kw):
    kw.setdefault('wait_patterns', ('Echo server listening on port 8080.',))
    return ContainerDefinition(name, IMG, **kw)

class DummySession:
    def __init__(self):
        self.requests = []
        self.was_closed = False

    def request(self, *args, **kwargs):
        self.requests.append((args, kwargs))

    def close(self):
        self.was_closed = True

    def check_was_closed(self):
        was_closed, self.was_closed = self.was_closed, False
        return was_closed

class TestContainerHttpClient(unittest.TestCase):
    def make_helper(self):
        dh = DockerHelper()
        self.addCleanup(dh.teardown)
        return dh.containers

    @responses.activate
    def test_defaults(self):
        """
        When the container client is configured with a host address and port,
        requests are made to that address and port.
        """
        client = ContainerHttpClient('127.0.0.1', '12345')

        responses.add(responses.GET, 'http://127.0.0.1:12345/', status=200)
        response = client.request('GET')

        self.assertEqual(response.status_code, 200)

        [call] = responses.calls
        self.assertEqual(call.request.url, 'http://127.0.0.1:12345/')

    @responses.activate
    def test_url_defaults(self):
        """
        When the container client is configured with a host address and port,
        and some URL defaults are set, requests are made to that address and
        port with the expected URL.
        """
        client = ContainerHttpClient('127.0.0.1', '12345', url_defaults={
            'scheme': 'https',
            'fragment': 'test',
        })

        responses.add(responses.GET, 'https://127.0.0.1:12345/baz', status=200)
        response = client.request('GET', '/baz', url_kwargs={
            'query': (('foo', 'bar'),),
        })

        self.assertEqual(response.status_code, 200)

        [call] = responses.calls
        self.assertEqual(
            call.request.url, 'https://127.0.0.1:12345/baz?foo=bar#test')

    @responses.activate
    def test_paths(self):
        """
        The path is appended to the URL correctly with various leading or
        trailing ``/`` characters.
        """
        client = ContainerHttpClient('127.0.0.1', '12345')

        # Root path
        responses.add(responses.GET, 'http://127.0.0.1:12345/', status=200)
        client.request('GET', '')  # Requests adds a trailing /
        client.request('GET', '/')

        self.assertEqual(
            responses.calls[0].request.url, 'http://127.0.0.1:12345/')
        self.assertEqual(
            responses.calls[1].request.url, 'http://127.0.0.1:12345/')

        # Leading slashes are ignored
        responses.add(
            responses.GET, 'http://127.0.0.1:12345/a/b/c', status=200)
        client.request('GET', '/a/b/c')
        client.request('GET', 'a/b/c')

        self.assertEqual(
            responses.calls[2].request.url, 'http://127.0.0.1:12345/a/b/c')
        self.assertEqual(
            responses.calls[3].request.url, 'http://127.0.0.1:12345/a/b/c')

        # Trailing slashes are respected
        responses.add(
            responses.GET, 'http://127.0.0.1:12345/a/b/c/', status=200)
        client.request('GET', '/a/b/c/')

        self.assertEqual(
            responses.calls[4].request.url, 'http://127.0.0.1:12345/a/b/c/')

        # Double slashes are not ignored
        responses.add(
            responses.GET, 'http://127.0.0.1:12345//a//b', status=200)
        client.request('GET', '//a//b')

        self.assertEqual(
            responses.calls[5].request.url, 'http://127.0.0.1:12345//a//b')

    @responses.activate
    def test_relative_paths(self):
        """
        The path can be specified as a relative or absolute path.
        """
        client = ContainerHttpClient(
            '127.0.0.1', '12345', url_defaults={'path': ['foo']})

        responses.add(
            responses.GET, 'http://127.0.0.1:12345/foo/bar/baz', status=200)
        client.request('GET', 'bar/baz')

        self.assertEqual(responses.calls[0].request.url,
                         'http://127.0.0.1:12345/foo/bar/baz')

        responses.add(
            responses.GET, 'http://127.0.0.1:12345/foobar', status=200)
        client.request('GET', '/foobar')

        self.assertEqual(responses.calls[1].request.url,
                         'http://127.0.0.1:12345/foobar')

    @responses.activate
    def test_methods(self):
        """
        When the HTTP method-specific methods are called, the correct request
        method is used.
        """
        client = ContainerHttpClient('127.0.0.1', '45678')

        responses.add(responses.GET, 'http://127.0.0.1:45678/', status=200)
        responses.add(
            responses.OPTIONS, 'http://127.0.0.1:45678/foo', status=201)
        responses.add(responses.HEAD, 'http://127.0.0.1:45678/bar', status=403)
        responses.add(responses.POST, 'http://127.0.0.1:45678/baz', status=404)
        responses.add(responses.PUT, 'http://127.0.0.1:45678/test', status=418)
        responses.add(
            responses.PATCH, 'http://127.0.0.1:45678/a/b/c', status=501)
        responses.add(
            responses.DELETE, 'http://127.0.0.1:45678/d/e/f', status=503)

        get_response = client.get()
        options_response = client.options('/foo')
        head_response = client.head('/bar')
        post_response = client.post('/baz')
        put_response = client.put('/test')
        patch_response = client.patch('/a/b/c')
        delete_response = client.delete('/d/e/f')

        self.assertEqual(get_response.status_code, 200)
        self.assertEqual(options_response.status_code, 201)
        self.assertEqual(head_response.status_code, 403)
        self.assertEqual(post_response.status_code, 404)
        self.assertEqual(put_response.status_code, 418)
        self.assertEqual(patch_response.status_code, 501)
        self.assertEqual(delete_response.status_code, 503)

        self.assertEqual(len(responses.calls), 7)

    def test_session(self):
        """
        When a custom session object is given, that object is used to make
        requests and is closed when ``close()`` is called.
        """
        session = DummySession()
        client = ContainerHttpClient('127.0.0.1', '12345', session=session)

        client.request('GET', '/foo')
        client.request('POST', '/bar')
        self.assertEqual(session.requests, [
            (('GET', 'http://127.0.0.1:12345/foo'), {}),
            (('POST', 'http://127.0.0.1:12345/bar'), {}),
        ])

        client.close()
        self.assertTrue(session.check_was_closed())

    def test_session_context_manager(self):
        """
        When a custom session object is given, that object is used to make
        requests and is closed when the context is exited when the container
        client is used as a context manager.
        """
        session = DummySession()
        client = ContainerHttpClient('127.0.0.1', '12345', session=session)

        with client:
            client.request('GET', '/foo')
            self.assertEqual(session.requests, [
                (('GET', 'http://127.0.0.1:12345/foo'), {}),
            ])

        self.assertTrue(session.check_was_closed())

    @dockertest()
    def test_for_container_first_port(self):
        """
        The ``for_container()`` class method returns a container client that
        connects to the container's first port when a specific port is not
        specified.
        """
        ch = self.make_helper()
        container = echo_container('first_port', create_kwargs={
            'ports': {'8080/tcp': ('127.0.0.1', None)}
        }, helper=ch)
        container.setup()
        self.addCleanup(container.teardown)

        client = ContainerHttpClient.for_container(container)
        self.addCleanup(client.close)

        response = client.request('GET', '/foo')

        self.assertEqual(response.status_code, 200)
        response_lines = response.text.splitlines()
        self.assertIn('HTTP/1.1 GET /foo', response_lines)

        addr, port = container.get_first_host_port()
        self.assertIn('Host: {}:{}'.format(addr, port), response_lines)

    @dockertest()
    def test_for_container_specific_port(self):
        """
        The ``for_container()`` class method returns a container client that
        connects to the container port specified.
        """
        ch = self.make_helper()
        container = echo_container('first_port', create_kwargs={
            'ports': {
                '8080/tcp': ('127.0.0.1', None),
                '5353/udp': ('127.0.0.1', None),
            }
        }, helper=ch)
        container.setup()
        self.addCleanup(container.teardown)

        client = ContainerHttpClient.for_container(
            container, container_port='8080')
        self.addCleanup(client.close)

        response = client.request('GET', '/foo')

        self.assertEqual(response.status_code, 200)
        response_lines = response.text.splitlines()
        self.assertIn('HTTP/1.1 GET /foo', response_lines)

        addr, port = container.get_host_port('8080')
        self.assertIn('Host: {}:{}'.format(addr, port), response_lines)

class TestWaitForResponseFunc(unittest.TestCase):
    @responses.activate
    def test_success(self):
        """
        When a request succeeds before the timeout, all is happy.
        """
        client = ContainerHttpClient('127.0.0.1', '12345')
        responses.add(responses.GET, 'http://127.0.0.1:12345/', status=200)
        # A failure here will raise an exception.
        # 100ms is long enough for a first-time success.
        wait_for_response(client, 0.1)

    @responses.activate
    def test_success_with_status_code(self):
        """
        When a request succeeds before the timeout and has the expected status
        code, all is happy.
        """
        client = ContainerHttpClient('127.0.0.1', '12345')
        responses.add(responses.GET, 'http://127.0.0.1:12345/', status=200)
        # A failure here will raise an exception.
        # 100ms is long enough for a first-time success.
        wait_for_response(client, 0.1, expected_status_code=200)

    @responses.activate
    def test_error_then_success(self):
        """
        When an exception is raised before the timeout, we retry and are happy
        with any successful request before the timeout.
        """
        client = ContainerHttpClient('127.0.0.1', '12345')
        responses.add(
            responses.GET, 'http://127.0.0.1:12345/', body=Exception('KABOOM'))
        responses.add(responses.GET, 'http://127.0.0.1:12345/', status=200)
        # A failure here will raise an exception.
        # Because responses is fast 110ms gives us time to fail, wait 100ms,
        # then succeed.
        wait_for_response(client, 0.11)

    @responses.activate
    def test_error_timeout(self):
        """
        When exceptions are raised without a successful request before the
        timeout, we time out.
        """
        client = ContainerHttpClient('127.0.0.1', '12345')
        responses.add(
            responses.GET, 'http://127.0.0.1:12345/', body=Exception('KABOOM'))
        with self.assertRaises(TimeoutError) as cm:
            # 190ms is enough time to fail, wait 100ms, fail again, wait 100ms,
            # then time out.
            wait_for_response(client, 0.19)
        self.assertEqual(
            str(cm.exception), 'Timeout waiting for HTTP response.')

    @responses.activate
    def test_unexpected_status_code_timeout(self):
        """
        When requests are received without the correct status code before the
        timeout, we time out.
        """
        client = ContainerHttpClient('127.0.0.1', '12345')
        responses.add(
            responses.GET, 'http://127.0.0.1:12345/', status=503)
        with self.assertRaises(TimeoutError) as cm:
            # 190ms is enough time to fail, wait 100ms, fail again, wait 100ms,
            # then time out.
            wait_for_response(client, 0.19, expected_status_code=200)
        self.assertEqual(
            str(cm.exception), 'Timeout waiting for HTTP response.')

    @responses.activate
    def test_timeout(self):
        """
        When we don't get a response before the timeout, we time out.

        FIXME: Because responses doesn't do timeouts, we fake it by manually
        raising the exception we expect. We really should use requests itself
        for this.
        """
        client = ContainerHttpClient('127.0.0.1', '12345')

        responses.add(
            responses.GET, 'http://127.0.0.1:12345/',
            body=requests.exceptions.Timeout())
        with self.assertRaises(TimeoutError) as cm:
            # The timeout doesn't actually matter here because we raise the
            # exception ourselves.
            wait_for_response(client, 0.1)
        self.assertEqual(
            str(cm.exception), 'Timeout waiting for HTTP response.')


#!/usr/bin/env python

"""Module for fetching data of Cryptocurrencies which were recently
added in the last 24 hours on CoinMarketCap website."""

from datetime import datetime
import os
import time
from typing import Any, Dict, List, Optional, Tuple, Union
import bs4
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
from cmc.modules.base import CMCBaseClass
from cmc.utils.exceptions import ScrapeError
from cmc.utils.models import RecentlyAddedData

class RecentlyAdded(CMCBaseClass):
    """Class for scraping the data of CryptoCurrencies that appear
    in the recently added table."""

    def __init__(self, proxy: Optional[str] = None, as_dict: bool = False) -> None:
        """
        Args:
            proxy (Optional[str], optional): Proxy to be used for Selenium and requests Session. Defaults to None.
            as_dict (bool): Return the data as a dictionary. Defaults to False.
        """
        super().__init__(proxy)
        self.base_url = "https://coinmarketcap.com/new/"
        self.out = as_dict

    @property
    def __get_page_data(self) -> bs4.BeautifulSoup:
        """Scrape the table from recently added CryptoCurrencies page data
        and return the scraped data.

        Raises:
            ScrapeError: Raised when data cannot be scraped from the webpage.

        Returns:
            bs4.BeautifulSoup: Scraped page data.
        """
        driver = webdriver.Chrome(
            service=self.service,
            options=self.driver_options,
            service_log_path=os.devnull,
        )
        try:
            driver.get(self.base_url)
            driver.execute_script("window.scrollTo(0, document.body.scrollHeight)")
            time.sleep(1)
            result = driver.find_element(
                By.XPATH,
                '//*[@id="__next"]/div/div[1]/div[2]/div/div[2]/table/tbody',
            )
            page_data = result.get_attribute("innerHTML")
            driver.quit()
            soup = BeautifulSoup(page_data, features="lxml")
            return soup
        except:
            raise ScrapeError

    @property
    def get_data(
        self,
    ) -> Union[Dict[int, Dict[str, Any]], Dict[int, RecentlyAddedData]]:
        """Scrape the CryptoCurrencies which are recently added in the
        last 24 hours.

        Returns:
            Union[Dict[int, Dict[str, Any]], Dict[int, RecentlyAddedData]]: Scraped data of trending CryptoCurrencies.
        """
        recently_added: Dict[int, Any] = {}
        page_data = self.__get_page_data
        data = page_data.find_all("tr")
        for num, content in enumerate(data):
            td = content.find_all("td")
            name: str = td[2].find("p", class_="sc-1eb5slv-0 iworPT").text
            symbol: str = (
                td[2].find("p", class_="sc-1eb5slv-0 gGIpIK coin-item-symbol").text
            )
            cmc_link: str = td[2].find("a", class_="cmc-link")["href"]
            try:
                price: str = td[3].find("div", class_="sc-131di3y-0 cLgOOr").text
            except:
                price: str = td[3].span.text  # type: ignore
            try:
                if td[4].find("span", class_="sc-15yy2pl-0 hzgCfk").span["class"][0]:
                    percent_1h: Tuple[str, ...] = (
                        "down",
                        td[4].find("span", class_="sc-15yy2pl-0 hzgCfk").text,
                    )
            except:
                percent_1h: Tuple[str, ...] = (  # type: ignore
                    "up",
                    td[4].find("span", class_="sc-15yy2pl-0 kAXKAX").text,
                )
            try:
                if td[5].find("span", class_="sc-15yy2pl-0 hzgCfk").span["class"][0]:
                    percent_24h: Tuple[str, ...] = (
                        "down",
                        td[5].find("span", class_="sc-15yy2pl-0 hzgCfk").text,
                    )
            except:
                percent_24h: Tuple[str, ...] = (  # type: ignore
                    "up",
                    td[5].find("span", class_="sc-15yy2pl-0 kAXKAX").text,
                )
            fully_diluted_market_cap: str = td[6].text
            volume_24h: str = td[7].text
            blockchain: str = td[8].find("div", class_="s8fs2i-2 TBaWj").text
            added: str = td[9].text
            result = {
                "name": name,
                "symbol": symbol,
                "cmc_name": cmc_link.split("/")[-2],
                "url": self.cmc_url + cmc_link,
                "price": price,
                "percent_1h": percent_1h,
                "percent_24h": percent_24h,
                "fully_diluted_market_cap": fully_diluted_market_cap,
                "volume_24h": volume_24h,
                "blockchain": blockchain,
                "added": added,
                "timestamp": datetime.now(),
            }
            if self.out:
                recently_added[num + 1] = result
            else:
                recently_added[num + 1] = RecentlyAddedData(**result)
        return recently_added


import functools

__author__ = 'gauth_000'

def max_sum_contiguous(numbers):
    negative=True
    intermediate=cumulative=0
    for num in numbers:
        if num>=0:
            negative=False
        intermediate+=num
        if intermediate<0:
            intermediate=0
        if cumulative<intermediate:
            cumulative=intermediate
    if negative:
        return max(numbers)
    return cumulative

def max_sum_discontiguous(numbers):
    try:
        return functools.reduce(lambda x, y:x+y, filter(lambda x:x>=0, numbers))
    except TypeError:
        return max(numbers)

for i in range(int(input())):
    input()
    numbers=list(map(int, input().strip().split()))
    print(max_sum_contiguous(numbers), max_sum_discontiguous(numbers))


import kivy
kivy.require('1.0.6') # replace with your current kivy version !

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from PIL import Image
import time
import os
import uuid

from pyimagesearch.face_blurring import anonymize_face_pixelate
import numpy as np
import argparse
import cv2

#begin UI Build

Builder.load_string('''
<CameraClick>:
    orientation: 'vertical'
    Camera:
        id: camera
        resolution: (1080, 1920)
        play: True
    Button:
        text: 'Capture'
        size_hint_y: None
        height: '48dp'
        on_press: root.capture()
''')

#End UI Build

class CameraClick(BoxLayout):
    def capture(self):
        camera = self.ids['camera']
        #timestr = time.strftime("%Y%m%d_%H%M%S")
        camera.export_to_png("exif.png")
        print("Captured")
        image = Image.open('exif.png')
        data = list(image.getdata())
        image_no_exif = Image.new(image.mode, image.size)
        image_no_exif.putdata(data)
        randomstring = str(uuid.uuid4())
        filename = randomstring + '.png'
        image_no_exif.save(filename)
        os.remove('exif.png')

        prototxtPath = os.path.sep.join(["face_detector", "deploy.prototxt"])
        weightsPath = os.path.sep.join(["face_detector",
        	"res10_300x300_ssd_iter_140000.caffemodel"])
        net = cv2.dnn.readNet(prototxtPath, weightsPath)

        # load the input image from disk, clone it, and grab dimensions

        image = cv2.imread(filename)
        orig = image.copy()
        (h, w) = image.shape[:2]

        # construct a blob from the image
        blob = cv2.dnn.blobFromImage(image, 1.0, (300, 300),
        	(104.0, 177.0, 123.0))

        net.setInput(blob)
        detections = net.forward()

        # loop over the detections
        for i in range(0, detections.shape[2]):
        	confidence = detections[0, 0, i, 2]

        	# filter out weak detections
        	if confidence > 0.5:
        		# compute the (x, y)-coordinates of the bounding box for the
        		# object
        		box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
        		(startX, startY, endX, endY) = box.astype("int")

        		# extract the face ROI
        		face = image[startY:endY, startX:endX]

        		face = anonymize_face_pixelate(face,
        			blocks= 12)

        		# store the blurred face in the output image
        		image[startY:endY, startX:endX] = face

        cv2.imwrite(filename , image)

class TestCamera(App):

    def build(self):
        return CameraClick()

TestCamera().run()


# Required: install cli53. Github repo: https://github.com/barnybug/cli53

import commands
from datetime import datetime
import json
import pyconfluence as pyco
import time

def recreate_all_vm_dns(e):
    """Recreate DNS record sets and CNAMEs belonging to enviroment VMs.

    Parameters:
    e = Skytap Environment object.
    create = if False, end the function after deletion.
    """

    vm_hostname = "error"
    ip = None

    timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    with open("dns.log", "a") as logfile:
        logfile.write("\n\n\n[" + timestamp + "] Starting DNS writing function for " + e.name + ".\n")

    print ("Managing DNS settings for " + e.name + "...")

    for v in e.vms:
        for i in v.interfaces:
            vm_hostname = i.hostname
            int_data = json.loads(i.json())
            try:
                valid_vpns = ["vpn-661182", "vpn-3631944", "vpn-3288770",
                              "vpn-15108689"]
                for n in int_data["nat_addresses"]["vpn_nat_addresses"]:
                    if (n["vpn_id"] in valid_vpns):
                        ip = n["ip_address"]
            except (KeyError, TypeError, IndexError):
                # Default to US in case of buggery
                ip = i.ip

        dns_name = (vm_hostname + "-" + str(e.id) + ".skytap")

        if ip:
            created = False

            timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            with open("dns.log", "a") as logfile:
                logfile.write("[" + timestamp + "] Beginning to create record set for " + vm_hostname + ".\n")

            print ("Creating record set for " + vm_hostname + "...")

            while not created:
                timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                with open("dns.log", "a") as logfile:
                    logfile.write("[" + timestamp + "] Requesting creation of " + vm_hostname + " record set.\n")
                status, output = commands.getstatusoutput("cli53 rrcreate "
                                                          "Z2M6JEL5C4DYRL \'"
                                                          "" + vm_hostname + "-"
                                                          "" + str(e.id) + ""
                                                          " 3600 A " + ip + ""
                                                          "\'")
                time.sleep(2)
                timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                with open("dns.log", "a") as logfile:
                    logfile.write("[" + timestamp + "] Requesting list of all record sets to check for creation success.\n")
                status, output = commands.getstatusoutput("aws route53 "
                                                          "list-resource-record-sets "
                                                          "--hosted-zone-id "
                                                          "/hostedzone/Z2M6JEL5C4DYRL")
                try:
                    timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                    with open("dns.log", "a") as logfile:
                        logfile.write("[" + timestamp + "] Checking record set list for instance of " + vm_hostname + " record set.\n")

                    data = json.loads(output)
                    for rrs in data["ResourceRecordSets"]:
                        if (rrs["ResourceRecords"][0]["Value"] == (ip) and
                                rrs["Name"] == vm_hostname + "-" + str(e.id) + ".skytap.fulcrum.net."):
                            created = True

                            timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                            with open("dns.log", "a") as logfile:
                                logfile.write("[" + timestamp + "] Successfully created record set for " + vm_hostname + ".\n")

                            print ("Created record set: " + vm_hostname + "-" + str(e.id) + ".skytap.fulcrum.net")

                except: # If an exception is caught, then we'll try again.
                    timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                    with open("dns.log", "a") as logfile:
                        logfile.write("[" + timestamp + "] Failed to create record set for " + vm_hostname + ", and will retry. Error returned from AWS: " + output + "\n")

                    print ("AWS output caused an error. Retrying in 4 seconds...")
                    time.sleep(2)

                if not created:
                    time.sleep(2)

        env_dns_alias = None

        if "env_dns_alias" in e.user_data:
            env_dns_alias = e.user_data.env_dns_alias

        if env_dns_alias:
            created = False

            timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            with open("dns.log", "a") as logfile:
                logfile.write("[" + timestamp + "] Beginning to create CNAME for " + vm_hostname + ".\n")

            print ("Creating CNAME for " + vm_hostname + "...")
            while not created:
                timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                with open("dns.log", "a") as logfile:
                    logfile.write("[" + timestamp + "] Requesting creation of " + vm_hostname + " CNAME.\n")
                status, output = commands.getstatusoutput("cli53 rrcreate "
                                                          "Z2M6JEL5C4DYRL \'"
                                                          "" + vm_hostname + "-"
                                                          "" + env_dns_alias + ""
                                                          " 3600 CNAME "
                                                          "" + vm_hostname + "-"
                                                          "" + str(e.id) + "\'")
                time.sleep(2)
                timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                with open("dns.log", "a") as logfile:
                    logfile.write("[" + timestamp + "] Requesting list of all record sets to check for creation success.\n")
                status, output = commands.getstatusoutput("aws route53 "
                                                          "list-resource-record-sets "
                                                          "--hosted-zone-id "
                                                          "/hostedzone/Z2M6JEL5C4DYRL")
                try:
                    timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                    with open("dns.log", "a") as logfile:
                        logfile.write("[" + timestamp + "] Checking record set list for instance of " + vm_hostname + " CNAME.\n")

                    data = json.loads(output)
                    for rrs in data["ResourceRecordSets"]:
                        if ((vm_hostname + "-" + str(e.id) + ".skytap.fulcrum.net").lower() in rrs["ResourceRecords"][0]["Value"] and
                                (vm_hostname + "-" + env_dns_alias + ".skytap.fulcrum.net").lower() in rrs["Name"]):
                            created = True

                            timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                            with open("dns.log", "a") as logfile:
                                logfile.write("[" + timestamp + "] Successfully created CNAME for " + vm_hostname + ".\n")

                            print ("Created CNAME: " + vm_hostname + "-" + env_dns_alias + ".skytap.fulcrum.net")
                except:
                    timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                    with open("dns.log", "a") as logfile:
                        logfile.write("[" + timestamp + "] Failed to create CNAME for " + vm_hostname + ", and will retry. Error returned from AWS: " + output + "\n")

                    print ("AWS output caused an error. Retrying in 4 seconds...")
                    time.sleep(2)

                if not created:
                    time.sleep(2)

    timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    with open("dns.log", "a") as logfile:
        logfile.write("[" + timestamp + "] Finished setting up DNS settings for this environment.\n")
# def delete_listed_dns(name):
#     """Delete DNS names as listed in a Confluence page."""
#     to_delete = []
#     to_delete_cname = []
#
#     content = pyco.get_page_content(pyco.get_page_id(name, "AutoDocs"))
#     env_id = content[content.find("Environment ID: ")+16:content.find("Environment ID: ")+23]
#
#     cname = None
#
#     if "Grey</ac:parameter><ac:parameter ac:name=\"title\">" in content:
#         cname = content[content.find("Grey</ac:parameter><ac:parameter ac:name=\"title\">")+49:content.find("</ac:parameter></ac:structured-macro>

Additional Details")]
#
#     children = json.loads(pyco.get_page_children(pyco.get_page_id(name, "AutoDocs")))
#     for vm in children["results"]:
#         to_delete.append(vm["title"][:vm["title"].find(" - ")] + "-" + str(env_id) + ".skytap")
#         if cname:
#             to_delete_cname.append(vm["title"][:vm["title"].find(" - ")] + "-" + cname + ".skytap")
#
#     for vm in to_delete:
#         status, output = commands.getstatusoutput("cli53 rrdelete Z2M6JEL5C4DYRL"
#                                                   " " + vm + " A")
#
#     for vm in to_delete_cname:
#         status, output = commands.getstatusoutput("cli53 rrdelete "
#                                                   "Z2M6JEL5C4DYRL "
#                                                   "" + vm + " CNAME")