class Solution:
    def findGCD(self, nums: List[int]) -> int:
        greatest = max(nums)
        smallest = min(nums)

        return self.gcd(greatest, smallest)

    @staticmethod
    def gcd(a, b):
        while b > 0:
            tmp = a % b
            a = b
            b = tmp
        return a


import abc
import pandas as pd
from six import iteritems
from toolz import merge

from .base import PipelineLoader
from .frame import DataFrameLoader
from .utils import previous_event_frame, next_event_frame
from zipline.pipeline.common import TS_FIELD_NAME
from zipline.utils.numpy_utils import NaTD

WRONG_COLS_ERROR = "Expected columns {expected_columns} for sid {sid} but " \
                   "got columns {resulting_columns}."

WRONG_SINGLE_COL_DATA_FORMAT_ERROR = ("Data for sid {sid} is expected to have "
                                      "1 column and to be in a DataFrame, "
                                      "Series, or DatetimeIndex.")

WRONG_MANY_COL_DATA_FORMAT_ERROR = ("Data for sid {sid} is expected to have "
                                    "more than 1 column and to be in a "
                                    "DataFrame.")

SERIES_NO_DTINDEX_ERROR = ("Got Series for sid {sid}, but index was not "
                           "DatetimeIndex.")

DTINDEX_NOT_INFER_TS_ERROR = ("Got DatetimeIndex for sid {sid}.\n"
                              "Pass `infer_timestamps=True` to use the first "
                              "date in `all_dates` as implicit timestamp.")

DF_NO_TS_NOT_INFER_TS_ERROR = ("Got DataFrame without a '{"
                               "timestamp_column_name}' column for sid {sid}."
                               "\nPass `infer_timestamps=True` to use the "
                               "first date in `all_dates` as implicit "
                               "timestamp.")

class EventsLoader(PipelineLoader):
    """
    Abstract loader.

    Does not currently support adjustments to the dates of known events.

    Parameters
    ----------
    all_dates : pd.DatetimeIndex
        Index of dates for which we can serve queries.
    events_by_sid : dict[int -> pd.DataFrame or pd.Series or pd.DatetimeIndex]
        Dict mapping sids to objects representing dates on which earnings
        occurred.

        If a dict value is a Series, it's interpreted as a mapping from the
        date on which we learned an announcement was coming to the date on
        which the announcement was made.

        If a dict value is a DatetimeIndex, it's interpreted as just containing
        the dates that announcements were made, and we assume we knew about the
        announcement on all prior dates.  This mode is only supported if
        ``infer_timestamp`` is explicitly passed as a truthy value.
        Dict mapping sids to DataFrames, Series, or DatetimeIndexes.

        If the value is a DataFrame, it then represents dates on which events
        occurred along with other associated values. If the DataFrame
        contains a "timestamp" column, that column is interpreted as the date
        on which we learned about the event. If the DataFrames do not contain a
         "timestamp" column, we assume we knew about the event on all prior
         dates.  This mode is only supported if ``infer_timestamp`` is
         explicitly passed as a truthy value.

    infer_timestamps : bool, optional
        Whether to allow omitting the "timestamp" column.
    dataset : DataSet
        The DataSet object for which this loader loads data.

    """

    @abc.abstractproperty
    def expected_cols(self):
        raise NotImplemented('expected_cols')

    def __init__(self,
                 all_dates,
                 events_by_sid,
                 infer_timestamps=False,
                 dataset=None):
        self.all_dates = all_dates
        # Do not modify the original in place, since it may be used for other
        #  purposes.
        self.events_by_sid = (
            events_by_sid.copy()
        )
        dates = self.all_dates.values

        for k, v in iteritems(events_by_sid):
            # Already a DataFrame
            if isinstance(v, pd.DataFrame):
                if TS_FIELD_NAME not in v.columns:
                    if not infer_timestamps:
                        raise ValueError(
                            DF_NO_TS_NOT_INFER_TS_ERROR.format(
                                timestamp_column_name=TS_FIELD_NAME,
                                sid=k
                            )
                        )
                    self.events_by_sid[k] = v = v.copy()
                    v.index = [dates[0]] * len(v)
                else:
                    self.events_by_sid[k] = v.set_index(TS_FIELD_NAME)
                # Once data is in a DF, make sure columns are correct.
                cols_except_ts = (set(v.columns) -
                                  {TS_FIELD_NAME})

                # Check that all columns other than timestamp are as expected.
                if cols_except_ts != self.expected_cols:
                    raise ValueError(
                        WRONG_COLS_ERROR.format(
                            expected_columns=list(self.expected_cols),
                            sid=k,
                            resulting_columns=v.columns.values
                        )
                    )
            # Not a DataFrame and we only expect 1 column
            elif len(self.expected_cols) == 1:
                # First, must convert to DataFrame.
                if isinstance(v, pd.Series):
                    if not isinstance(v.index, pd.DatetimeIndex):
                        raise ValueError(
                            SERIES_NO_DTINDEX_ERROR.format(sid=k)
                        )
                    self.events_by_sid[k] = pd.DataFrame({
                        list(self.expected_cols)[0]: v})
                elif isinstance(v, pd.DatetimeIndex):
                    if not infer_timestamps:
                        raise ValueError(
                            DTINDEX_NOT_INFER_TS_ERROR.format(sid=k)
                        )
                    self.events_by_sid[k] = pd.DataFrame({
                        list(self.expected_cols)[0]: v
                    }, index=[dates[0]] * len(v))
                else:
                    # We expect 1 column, but we got something other than a
                    # Series, DatetimeIndex, or DataFrame.
                    raise ValueError(
                        WRONG_SINGLE_COL_DATA_FORMAT_ERROR.format(sid=k)
                    )
            else:
                # We expected multiple columns, but we got something other
                # than a DataFrame.
                raise ValueError(
                    WRONG_MANY_COL_DATA_FORMAT_ERROR.format(sid=k)
                )

        self.dataset = dataset

    def get_loader(self, column):
        if column in self.dataset.columns:
            return getattr(self, "%s_loader" % column.name)
        raise ValueError("Don't know how to load column '%s'." % column)

    def load_adjusted_array(self, columns, dates, assets, mask):
        return merge(
            self.get_loader(column).load_adjusted_array(
                [column], dates, assets, mask
            )
            for column in columns
        )

    def _next_event_date_loader(self, next_date_field, event_date_field_name):
        return DataFrameLoader(
            next_date_field,
            next_event_frame(
                self.events_by_sid,
                self.all_dates,
                next_date_field.missing_value,
                next_date_field.dtype,
                event_date_field_name,
                event_date_field_name
            ),
            adjustments=None,
        )

    def _next_event_value_loader(self,
                                 next_value_field,
                                 event_date_field_name,
                                 value_field_name):
        return DataFrameLoader(
            next_value_field,
            next_event_frame(
                self.events_by_sid,
                self.all_dates,
                next_value_field.missing_value,
                next_value_field.dtype,
                event_date_field_name,
                value_field_name
            ),
            adjustments=None,
        )

    def _previous_event_date_loader(self,
                                    prev_date_field,
                                    event_date_field_name):
        return DataFrameLoader(
            prev_date_field,
            previous_event_frame(
                self.events_by_sid,
                self.all_dates,
                NaTD,
                'datetime64[ns]',
                event_date_field_name,
                event_date_field_name
            ),
            adjustments=None,
        )

    def _previous_event_value_loader(self,
                                     previous_value_field,
                                     event_date_field_name,
                                     value_field_name):
        return DataFrameLoader(
            previous_value_field,
            previous_event_frame(
                self.events_by_sid,
                self.all_dates,
                previous_value_field.missing_value,
                previous_value_field.dtype,
                event_date_field_name,
                value_field_name
            ),
            adjustments=None,
        )


'''
Given an array with all elements greater than or equal to zero. Return the maximum product of two numbers possible.

Input:
The first line of input contains an integer T denoting the number of test cases.
The first line of each test case is N, size of array. The second line of each test case contains array elements.

Output:
Print the maximum product of two numbers possible.

Constraints:
1 ≤ T ≤ 100
2 ≤ N ≤ 107
0 ≤ A[i] ≤ 104

Example:
Input:
1
5
1 100 42 4 23

Output:
4200

Explanation:
Testcase 1: Two maximum numbers are 100 and 42 and their product is 4200.
'''

t = int(input())

for i in range(t):
    n = int(input())

    A = list(map(int , input().split()))

    A.sort()

    num1 = A[-1]
    num2 = A[-2]

    ans = num1 * num2

    print(ans)


from flask import Flask, jsonify, request
import json

app = Flask(__name__)

# após a barra do caminho, digitar uma id ou blalboa.com.br/app.ro
@app.route('/<int:id>')
def pessoas(id):
    return jsonify({'id' : id, 'nome' : 'Weslley', 'profissao' : 'Estudante'})

# @app.route('/soma/<int:valor1>/<int:valor2>/<int:valor3>/')
# def soma(valor1, valor2, valor3):
#     return jsonify({'soma' : valor1+valor2+valor3})

@app.route('/soma', methods = ['POST', 'GET'])
def soma():
    if request.method == 'POST':
        dados = json.loads(request.data)
        total = sum(dados['valores'])
    elif request.method == 'GET':
        total = 10 + 10
    return {'soma' : total}

if __name__ == "__main__":
    app.run(debug= True)

Python com Flask e REST API/primeira_api/app.py


for x in range(1,10):
    print(x)

mascotas = {
    "Choco":[5, "perro","m"],
    "Gordito":[3, "gato","m"],
    "Catalina":[10, "gato", "f"],
    "Flecha":[1, "gato","f"],
}

for key in mascotas.keys():
    print("Nombre: {}\n\tedad: {} \n\traza: {} \n\tsexo: {}".format(key, mascotas[key][0],mascotas[key][1],mascotas[key][2]))


try:
    from timagetk.algorithms import blockmatching
    from timagetk.algorithms import compose_trsf, apply_trsf
    from timagetk.components import SpatialImage
except ImportError:
    raise ImportError('Import Error')

__all__ = ['sequence_registration']

def sequence_registration(list_images, method=None, **kwds):
    """
    Sequence registration plugin. Available methods are :

    * sequence_rigid_registration
    * sequence_affine_registration

    Parameters
    ----------
    :param list list_images: list of *SpatialImage*

    :param str method: used method (example: 'sequence_registration_rigid')

    Returns
    ----------
    :return: list_compo_trsf -- list of *BalTransformation* transformation

    :return: list_res_img -- list of *SpatialImage*

    Example
    ----------
    >>> from timagetk.util import data_path
    >>> from timagetk.components import imread
    >>> from timagetk.plugins import sequence_registration
    >>> times = [0, 1, 2]
    >>> list_images = [imread(data_path('time_' + str(time) + '.inr'))
                        for time in times]
    >>> list_compo_trsf, list_res_img = sequence_registration(list_images,
                                                              method='sequence_rigid_registration')
    >>> list_compo_trsf, list_res_img = sequence_registration(list_images,
                                                              method='sequence_affine_registration')
    """
    poss_methods = ['sequence_rigid_registration', 'sequence_affine_registration']
    conds_init = isinstance(list_images, list) and len(list_images)>=3
    conds_list_img = [0 if isinstance(sp_img, SpatialImage) else 1
                        for sp_img in list_images]
    #--- end check
    if conds_init and 1 not in conds_list_img:
        if method is None:
            list_compo_trsf, list_res_img = sequence_registration_rigid(list_images)
            return list_compo_trsf, list_res_img
        elif method is not None:
            if method in poss_methods:
                try:
                    from openalea.core.service.plugin import plugin_function
                    func = plugin_function('openalea.image', method)
                    if func is not None:
                        return func(list_images, **kwds)
                except:
                    if method=='sequence_rigid_registration':
                        list_compo_trsf, list_res_img = sequence_registration_rigid(list_images)
                    elif method=='sequence_affine_registration':
                        list_compo_trsf, list_res_img = sequence_registration_affine(list_images)
                    return list_compo_trsf, list_res_img
            else:
                print('Available methods :'), poss_methods
                raise NotImplementedError(method)
    else:
        raise TypeError('list_images must be a list of SpatialImage')
        return

def sequence_registration_rigid(list_images):
    #--- check SpatialImage sequence
    conds_init = isinstance(list_images, list) and len(list_images)>=3
    conds_list_img = [0 if isinstance(sp_img, SpatialImage) else 1
                        for sp_img in list_images]
    #--- end check
    if conds_init and 1 not in conds_list_img:
        #--- pairwise registration
        pairwise_trsf = []
        for ind, sp_img in enumerate(list_images):
            if ind < len(list_images)-1:
                # --- rigid registration
                trsf_rig, res_rig = blockmatching(list_images[ind], list_images[ind+1],
                                                  param_str_2='-trsf-type rigid')
                pairwise_trsf.append(trsf_rig) #--- case rigid registration
        #--- composition of transformations
        list_compo_trsf, list_res_img = [], []
        for ind, trsf in enumerate(pairwise_trsf):
            if ind < len(pairwise_trsf)-1:
                comp_trsf = compose_trsf(pairwise_trsf[ind:]) # matrix multiplication
                list_compo_trsf.append(comp_trsf)
            elif ind == len(pairwise_trsf)-1:
                list_compo_trsf.append(pairwise_trsf[-1])
        #--- displacements compensation (whole sequence)
        for ind, trsf in enumerate(list_compo_trsf):
            tmp_img = apply_trsf(list_images[ind], trsf, template_img=list_images[-1]) # global reference : list_images[-1]
            list_res_img.append(tmp_img)
        list_res_img.append(list_images[-1]) # add global reference image
    return list_compo_trsf, list_res_img

def sequence_registration_affine(list_images):
    #--- check SpatialImage sequence
    conds_init = isinstance(list_images, list) and len(list_images)>=3
    conds_list_img = [0 if isinstance(sp_img, SpatialImage) else 1
                        for sp_img in list_images]
    #--- end check
    if conds_init and 1 not in conds_list_img:
        #--- pairwise registration
        pairwise_trsf = []
        for ind, sp_img in enumerate(list_images):
            if ind < len(list_images)-1:
                # --- rigid registration
                trsf_rig, res_rig = blockmatching(list_images[ind], list_images[ind+1],
                                                  param_str_2='-trsf-type rigid -py-ll 1')
                # --- affine registration, initialisation by a rigid transformation
                trsf_aff, res_aff = blockmatching(list_images[ind], list_images[ind+1],
                                                  left_transformation=trsf_rig,
                                                  param_str_2='-trsf-type affine')
                res_trsf = compose_trsf([trsf_rig, trsf_aff]) #--- composition of transformations
                pairwise_trsf.append(res_trsf) #--- case affine registration
                trsf_rig.free() #--- add
        #--- composition of transformations
        list_compo_trsf, list_res_img = [], []
        for ind, trsf in enumerate(pairwise_trsf):
            if ind < len(pairwise_trsf)-1:
                tmp_trsf = compose_trsf(pairwise_trsf[ind:]) # matrix multiplication
                list_compo_trsf.append(tmp_trsf)
            elif ind == pairwise_trsf.index(pairwise_trsf[-1]):
                list_compo_trsf.append(pairwise_trsf[-1])
        #--- displacements compensation (whole sequence)
        for ind, trsf in enumerate(list_compo_trsf):
            tmp_img = apply_trsf(list_images[ind], trsf, template_img=list_images[-1])
            list_res_img.append(tmp_img)
        list_res_img.append(list_images[-1]) # add reference image
    return list_compo_trsf, list_res_img


import matplotlib.pyplot as plt
import numpy as np
x=np.linspace(0,5,11)
y=x**2

print(x)
print("y is",y)

plt.plot(x,y,'r')
plt.xlabel('x-label')
plt.ylabel('y-label')
plt.show()


from django.urls import path
from AppBlog import views

urlpatterns = [
    path('pets/',views.pets, name='Pets'),
    path('veterinary/',views.veterinary, name='Veterinary'),
    path('client/',views.client, name='Clients'),
    path('',views.inicio, name='Inicio'),
    path('clientFormulario/', views.clienteFormulario, name='clientFormulario'),
    path('busquedaNumeroCliente/', views.busquedaNumeroCliente, name='busquedaNumeroCliente'),
    path('buscar/', views.buscar)
]


from app.accounts.services import get_verifiers
from app.positions.services import check_position_duplicate
from app.positions.services import create_position, create_section_division
from app.positions.services import delete_position_record, delete_secdiv_record
from app.positions.services import get_section_divisions_and_positions, get_verifier
from app.positions.services import update_secdiv_record, update_position_record
from flask import Blueprint, render_template, request
from json import dumps

positionsbp = Blueprint('positions', __name__, template_folder='templates')

@positionsbp.route('/positions')
def positions():
    section_divisions = get_section_divisions_and_positions()
    verifiers = get_verifiers()

    return render_template('positions.html', section_divisions=section_divisions, verifiers=verifiers)

@positionsbp.route('/positions/new-position', methods=['POST'])
def new_position():
    data = {
        'title': request.form['position-title'],
        'section_division': request.form['section-division']
    }

    create_position(data)

    return dumps({'status': 'OK'})

@positionsbp.route('/positions/new-section-division', methods=['POST'])
def new_section_division():
    data = {
        'name': request.form['name'],
        'verifier': request.form['verifier']
    }

    create_section_division(data)

    return dumps({'status': 'OK'})

@positionsbp.route('/positions/get-verifier', methods=['GET'])
def get_sec_div_verifier():
    sec_div = request.args.get('section_division')
    verifier = get_verifier(sec_div)

    data = {
        'verifier': verifier
    }

    return dumps({'status': 'OK', 'data': data})

@positionsbp.route('/positions/delete-secdiv')
def delete_secdiv():
    sec_div = request.args.get('sec_div')
    delete_secdiv_record(sec_div)

    return dumps({'status': 'OK'})

@positionsbp.route('/positions/update-secdiv', methods=['POST'])
def update_secdiv():
    current = request.form['current_name']
    new = request.form['name']
    verifier = request.form['verifier']

    update_secdiv_record(current, new, verifier)

    return dumps({'status': 'OK'})

@positionsbp.route('/positions/update-pos', methods=['POST'])
def update_position():
    current = request.form['cur_pos']
    cur_secdiv = request.form['cur_secdiv']
    new = request.form['position']
    secdiv = request.form['secdiv']

    if current != new or cur_secdiv != secdiv:
        duplicate = check_position_duplicate(new, secdiv)

        if duplicate:
            return dumps({'status': 'FAILED: DUPLICATE ENTRY'})

    update_position_record(current, new, secdiv)
    return dumps({'status': 'OK'})

@positionsbp.route('/positions/delete-position')
def delete_position():
    pos = request.args.get('pos')
    sec_div = request.args.get('secdiv')

    delete_position_record(sec_div, pos)

    return dumps({'status': 'OK'})


import random

class Agent():            #create a new class
    def __init__ (self, environment, agents):   #self represents the object
        self.environment = environment
        self.store = 0 #give the sheep empty stomachs
        self._x = random.randint(0,300)  #create self._x and assign a value -
        #use underscore to protect both self.x and self.y from being changed
        self._y = random.randint(0,300) #create self._y and assign a value
        self.agents = agents #list of agents into each agent

    def move (self): #create a move function
        if random.random() < 0.5:
            self._x = (self._x + 3) % 299 #using a torus boundary of 299 means
        else:                           #the agents never leave the animation
            self._x = (self._x - 3) % 299   #because if they go beyond the left
        if random.random() < 0.5:           #hand side they will re-enter on
            self._y = (self._y + 3) % 299   #the right hand side for example
        else:
            self._y = (self._y - 3) % 299

    def eat(self):
        if self.environment[self._y][self._x] > 10: #if the environment of the
                                            #agent is equal to more than 10:
           self.environment[self._y][self._x] -= 10  #minus 10 from the
                                                       #environment
           self.store += 10 #add 10 to the sheeps store

        if 0 < self.environment[self._y][self._x] < 10: #if the environment has
                                                        #less than 10 units:
           self.store += self.environment[self._y][self._x] #add the entire
           #environment to the sheeps store
           self.environment[self._y][self._x] -= self.environment[self._y][self._x]
           #empty the environment so it is equal to 0

    def sick(self):
        if self.store > 500: #if sheep has stored more than 500 it will sick
                            #it back up
           self.environment[self._y][self._x] = self.environment[self._y][self._x] + self.store
           #add the self store back into the environment
           self.store = 0 #empty the self store

    def run (self):
        if self.store > 250: #if the sheep has a store exceeding 250:
            self._x = (self._x + 20) % 299 #make the sheep move further along
                                            #the x axis
        if self.store > 250: #if the sheep has a store of more than 250:
            self._y = (self._y + 20) % 299 #make the sheep move further along
                                            #the y axis

    def share_with_neighbours (self, neighbourhood):
        for agent in self.agents: #for all agents
            dist = self.distance_between(agent) #dist = the distance between
                                                #agents
        if dist <= neighbourhood:   #if the distance between the agents is less
        #than or equal to the neighbourhood (specified on Model script):
            sum = self.store + agent.store #add the self store and the
                                            #neighbouring agents store
            average = sum / 2 #calculate the average of the stores
            self.store = average #set the self store to the average
            agent.store = average #set the neighbouring agents store to the
                                    #average also

    #make a function declaration to calculate the distance between the agents
    #called during the share_with_neighbours above

    def distance_between(self, agent):
        return (((self._x - agent._x)**2) + ((self._y - agent._y)**2))**0.5

#
#as each agent changes the environment (because the environment is a mutable
#object - a list) and the variable is therefore a link to the object passed in,
#all the agents link to the same environment object. As the agents change the
#environment data, it changes for all the agents. If environment object was an
#immutable object, this wouldnt be the case as changing it would result in a
#new copy being created
#


import sys
class Solution:
    """
    @param coins: a list of integer
    @param amount: a total amount of money amount
    @return: the fewest number of coins that you need to make up
    """
    def coinChange(self, coins, amount):
        # write your code here
        if not amount:
            return 0
        coins = set(coins)
        dp = [0] * (amount+1)
        # init
        for c in coins:
            if c < amount:
                dp[c] = 1

        for i in range(1, amount+1):
            #print(dp)
            if dp[i] != 0:
                continue
            minimum = self.find_min(dp, i, coins)
            if minimum != -1:
                dp[i] = minimum

        if not dp[-1]:
            return -1
        return dp[-1]

    def find_min(self, dp, i, coins):
        minimum = sys.maxsize
        for c in coins:
            if i < c or c == 0:
                continue
            if i > c and dp[i-c] == 0:
                continue
            minimum = min(minimum, dp[i-c])
        if minimum == sys.maxsize:
            return -1
        return minimum + 1

if __name__ == '__main__':
    s = Solution()
    coins = [1]
    amount = 1
    print(s.coinChange(coins, amount))


import random
import pygame
from pygame.locals import *
from Hangman.Person import Person
from Hangman.Button import Button

black = (0, 0, 0)
background_color = (161, 241, 255)
LETTERCLICKED = USEREVENT + 1
PLAY = USEREVENT + 2

class GameInstance:
    hidden_word = ""
    displayed_word = ""
    category = ""
    buttons = []
    words = {}
    playing = False
    incorrect_guesses = 0
    correct_guesses = 0

    def __init__(self, w, h):
        self.screen_width = w
        self.screen_height = h
        self.screen = pygame.display.set_mode((w, h))
        self.person = Person()
        self.font = 'LexendDeca-Regular.ttf'
        self.form_word_dict()

    def form_word_dict(self):
        file = open('words.txt', 'r')

        for line in file:
            if line:
                temp_arr = line.split(", ")
                self.words[temp_arr[0]] = temp_arr[1]

        file.close()

    def generate_word(self):
        self.hidden_word = random.choice(list(self.words.keys()))
        self.category = self.words[self.hidden_word]
        self.displayed_word = '_ ' * len(self.hidden_word)

    def generate_keyboard(self):
        buttons = []
        w = 20
        h = 20
        x_margin = 50
        y_margin = 30
        for i in range(97, 110):
            x = (i - 97) * (2 * w) + x_margin
            y = y_margin
            button = Button(LETTERCLICKED, chr(i), w, h, x, y)
            buttons.append(button)
        for j in range(110, 123):
            x = (j - 110) * (2 * w) + x_margin
            y = 2 * h + y_margin
            button = Button(LETTERCLICKED, chr(j), w, h, x, y)
            buttons.append(button)
        self.buttons = buttons

    def is_button_clicked(self):
        for but in self.buttons:
            if but.clicked():
                self.buttons.remove(but)

    def is_won(self):
        if self.displayed_word.replace(" ", "") == self.hidden_word and self.correct_guesses != 0:
            self.playing = False
            return True
        return False

    def is_lost(self):
        if self.incorrect_guesses == 6:
            self.playing = False
            return True
        return False

    def play(self):
        self.reset()
        self.playing = True

    def is_playing(self):
        return self.playing

    def update(self, guess):

            found = False
            for x in range(0, len(self.hidden_word)):
                if self.hidden_word[x] == guess.action:
                    l_displayed_word = list(self.displayed_word)
                    l_displayed_word[x*2] = guess.action
                    new = ''
                    for i in l_displayed_word:
                        new += i
                    self.displayed_word = new
                    found = True
            if found:
                self.correct_guesses += 1
            else:
                self.incorrect_guesses += 1
                self.person.hang(self.incorrect_guesses)

    def reset(self):
        self.buttons = []
        self.generate_keyboard()
        self.hidden_word = ""
        self.displayed_word = ""
        self.category = ""
        self.generate_word()
        self.incorrect_guesses = 0
        self.correct_guesses = 0
        pygame.event.clear()

    def draw_basics(self):

        self.screen.fill(background_color)
        self.screen.blit(self.person.image, self.person.rect)
        for but in self.buttons:
            self.screen.blit(but.surf, but.rect)
            self.screen.blit(but.surf2, but.rect2)

    def play_screen(self):
        self.draw_basics()

        word_font = pygame.font.Font(self.font, 20)
        guess_word_text = word_font.render(self.displayed_word, True, black)
        word_rect = guess_word_text.get_rect()
        word_rect.center = (self.person.rect.right + 50, self.person.rect.center[1])
        category_text = word_font.render(self.category, True, black)
        category_rect = category_text.get_rect()
        category_rect.center = (word_rect.center[0], word_rect.top - 20)

        self.screen.blit(category_text, category_rect)
        self.screen.blit(guess_word_text, word_rect)

    def option_screen(self, state):
        self.buttons = []
        width = 60
        height = 40
        play_but = Button(PLAY, 'Play', width, height, self.screen_width/4, self.screen_height/5 * 4)
        quit_but = Button(QUIT, 'Exit', width, height, self.screen_width/4 * 3, self.screen_height/5 * 4)
        self.buttons.append(play_but)
        self.buttons.append(quit_but)
        self.draw_basics()
        if state == 'won':
            s = 'You won this round!'
        elif state == 'lost':
            s = 'Uh Oh... He died.'
        elif state == 'start':
            s = 'Hang that Man!'
        else:
            s = 'Something went wrong'
        message1_font = pygame.font.Font(self.font, 40)
        message1 = message1_font.render(s, True, black)
        message1_rect = message1.get_rect()
        message1_rect.center = (self.screen_width/2, height + 20)
        self.screen.blit(message1, message1_rect)
        if state != 'start':
            message2_font = pygame.font.Font(self.font, 20)
            message2 = message2_font.render('The answer was ' + self.hidden_word, True, black)
            message2_rect = message2.get_rect()
            message2_rect.center = (self.person.rect.right + 30, self.person.rect.center[1])
            self.screen.blit(message2, message2_rect)


class TableCreator:
    def __init__(self):
        self.drop_table = False
        self.table_name = ''
        self.fields = {}
        pass

    def create_table(self):
        # sentence
        create_table_str = 'CREATE TABLE {} (\n{}\n);'.format(self.table_name, self.fields_to_str())
        file_name = '{}.sql'.format(self.table_name)
        file_path = './output/'
        file = '{}{}'.format(file_path, file_name)
        TableCreator.save_script(file, create_table_str)
        file_info = {
            "file_name":file_name,
            "file":file
        }
        return file_info

    @staticmethod
    def save_script(file, script=''):
        file_object = open(file, "w")
        file_object.write(script)

    def fields_to_str(self):
        fields_list = []
        for item in self.fields:
            field_stmt = '{} {}'.format(item['nombre'], item['tipo_dato_text'])
            fields_list.append(field_stmt)

        fields_str = ',\n'.join(fields_list)
        return fields_str


def kaprekarNumbers(p, q):
    return_string = ""
    for i in range(p, q + 1):
        som = 0
        square = str(i*i)
        print(i, square)
        # Split the square in 2 parts:
        right = square[-len(str(i)):]
        print(right)
        left = square[:(len(str(square))-len(right))]
        print("left: {}  | right: {}".format(left, right))
        if left == "":
            print("links None")
            som = int(right)
        else:
            som = int(left) + int(right)
        # else:
        #     som = int(left) + int(right)
        print("som: {}".format(som))

        if som == i:
            print("Kaprekar!")
            return_string += str(i) + " "
        print("-----------")
    print("return_string:{}...".format(return_string))
    if return_string == "":
        return "INVALID RANGE"
    else:
        return return_string

if __name__ == '__main__':
    p = int(input())
    q = int(input())
    print(kaprekarNumbers(p, q))

"""
https://www.hackerrank.com/challenges/kaprekar-numbers/problem

input
1
100

output:

1 9 45 55 99

input:
400
700

output:
INVALID RANGE
"""

Modified Kaprekar Numbers - Algorythms.py


import pandas as pd
import requests
from bs4 import BeautifulSoup
import pickle
import datetime
from datetime import timedelta
import re
import json
import time

url = r"https://ec.ltn.com.tw/article/breakingnews/3485576"
url = r"https://ec.ltn.com.tw/article/breakingnews/3485097"

url = r"https://ec.ltn.com.tw/list_ajax/international/2"

BaseUrl = r"https://ec.ltn.com.tw/list_ajax/international"

#財經首頁

# title:  財經首頁  href:  https://ec.ltn.com.tw
# title:  財經政策  href:  https://ec.ltn.com.tw/list/strategy       https://ec.ltn.com.tw/list_ajax/international/2
# title:  影音專區  href:  https://ec.ltn.com.tw/video
# title:  國際財經  href:  https://ec.ltn.com.tw/list/international
# title:  證券產業  href:  https://ec.ltn.com.tw/list/securities     https://ec.ltn.com.tw/list_ajax/securities/2
# title:  房產資訊  href:  https://ec.ltn.com.tw/list/estate
# title:  財經週報  href:  https://ec.ltn.com.tw/list/weeklybiz
# title:  基金查詢  href:  https://ec.ltn.com.tw/fund
# title:  投資理財  href:  https://ec.ltn.com.tw/list/investment     https://ec.ltn.com.tw/list_ajax/investment/2
# title:  匯率查詢  href:  https://ec.ltn.com.tw/exchangeRate
# title:  粉絲團  href:  https://www.facebook.com/ec.ltn.tw

CategoryType = {
    u'財經政策':r'https://ec.ltn.com.tw/list_ajax/strategy',
    u'國際財經':r'https://ec.ltn.com.tw/list_ajax/international',
    u'證券產業': r'https://ec.ltn.com.tw/list_ajax/securities',
    u'房產資訊':r'https://ec.ltn.com.tw/list_ajax/estate',
    u'財經週報':r'https://ec.ltn.com.tw/list_ajax/weeklybiz',
    u'投資理財':r'https://ec.ltn.com.tw/list_ajax/investment'
 }

def CreateDataRecod():
    DataFieldsNameList = ['Title','No','Group','Url','Date','Content']
    return pd.DataFrame(columns=DataFieldsNameList)

#  need to fix it
def test():
    Res=CreateDataRecod()
    temp_dict ={}
    for issue, url in CategoryType.items():
        print(issue, ' Start ')
        try:
            CategoryNews = GetMoreNews(url, LoopTimes=5)
            temp_dict.update({issue: CategoryNews})
            Res = Res.append(CategoryNews, ignore_index=True)
        except:
            print(issue ,'Error',url)
            print('STOP Collect News Data')
            break

        print(issue, ' End ')
        time.sleep(5)
    return Res

def GetNewsFromLTN():
    HomeUrl = r"https://ec.ltn.com.tw"
    res = requests.get(HomeUrl)
    if res.status_code == 200:
        content = res.content
        soup = BeautifulSoup(content, "html.parser")
        # 側邊選單:自由財經
        item = soup.findAll("div", class_="channel partner boxTitle boxText")
        Category = item[0].findAll('a')
        for _  in Category:
            print('title: ',_.get('title'))
            print('href: ', _.get('href'))

def GetMoreNews(BaseUrl,LoopTimes=5):
    Res = CreateDataRecod()
    #Today = datetime.datetime.today().date()-timedelta(days=1)
    Today = datetime.datetime.today().date()
    print(Today)
    LoopStatus = True
    init_loop = 0
    while LoopStatus:
        url = '/'.join([BaseUrl,str(init_loop)])
        print(url)
        PageNews = CollectPageNews(BaseUrl, init_loop)
        PageNews['Date'] = pd.to_datetime(PageNews['Date'])

        PageNews['IsToday'] =  PageNews['Date'].dt.date == Today
        if PageNews[PageNews['IsToday']]['IsToday'].count() == 0 :
            LoopStatus = False
            print('NO today Data')
        else:
            PageNews = PageNews.drop('IsToday', 1)
            Res = Res.append(PageNews, ignore_index=True)
            print('Add Data')

        init_loop = init_loop + 1
        if not(init_loop < LoopTimes) :
            LoopStatus = False
            print('Over limit Times')
        time.sleep(5)
    return Res

def CollectPageNews(BaseUrl,page=0):
    '''
    範例:  page_url='https://ec.ltn.com.tw/list_ajax/securities/2'
    :param BaseUrl:  BaseUrl = 'https://ec.ltn.com.tw/list_ajax/securities
    :param page:     page = 2
    :return:
    '''
    page_url = '/'.join([BaseUrl,str(page)])
    print(page_url)
    #res = requests.get(url)
    res = requests.get(page_url)
    temp_dict = []
    DataPageNews = CreateDataRecod()
    if res.status_code == 200:
        json_content = json.loads(res.content)
        #print(json_content)

        for _ in json_content:
            print('---------------------------------')
            #print(type(_))
            if bool(_):

                PageNews = CreateDataRecod()

                PageNews['Title'] = [_['LTNA_Title']]
                PageNews['No'] = [_['LTNA_No']]
                PageNews['Group'] = [_['LTNA_Group']]
                PageNews['Url'] = [_['url']]
                PageNews['Date'] = [_['createTime']]
                # Content = GetHtmlNewsTextOfLTN(_['url'],'\n','All')

                Content = GetHtmlNewsTextOfLTN(_['url'], '\n', 'Text')
                PageNews['Content'] = [Content]

                DataPageNews = DataPageNews.append(PageNews,ignore_index=True)

            #temp_dict.append({'Title':Title,'No':No,'Group':Group,'Url':Text_Url,'Date':Time,'Content':Content})
            time.sleep(5)
            pass
        pass
    else:
        assert not(res.status_code ==403), f'403 Error: {page_url} 禁止訪問 '
        # if res.status_code ==403 :
        #     print('403: 禁止訪問')
        #     raise Exception('403: 禁止訪問')
    return DataPageNews  #json_content

# 自由時報 (step 1)
def GetHtmlNewsTextOfLTN(url,join_token='\n', OutPutType='All'):
    '''
    :param url: 範例: url = 'https://ec.ltn.com.tw/article/breakingnews/3485576'
    :param join_token: 文章端落串接符號。預設 \n
    :param OutPutType: All: 輸出 [標題,內文] 的 List, Text: 數書內文 的字串
    :return:
    '''
    paragraph_list = []
    res = requests.get(url)
    if res.status_code == 200:
        content = res.content
        soup = BeautifulSoup(content, "html.parser")
        # 文章 div
        item = soup.findAll("div", class_="whitecon boxTitle boxText")
        # 內文:item
        # 標題
        title_text = item[0].findAll('h1')
        paragraph_list.append(title_text[0].text)

        # 內文
        item_sub2 = item[0].findAll('div', class_='text')
        item_sub3 = item_sub2[0].findAll('p')
        # 內文段落

        for paragraph in item_sub3:
            if not paragraph.attrs:
                # p tag 有其他的屬性, 要捨棄
                # 內文
                #print(paragraph.contents)
                if len(paragraph.contents) == 1:
                    paragraph_list.append(paragraph.text)
                    pass
                pass
            pass
        pass
    #  paragraph_list[0]: title
    #  paragraph_list[1:-1]: context
    if OutPutType == 'All':
        return  [paragraph_list[0],join_token.join(paragraph_list[1:])]
    elif OutPutType == 'Text':
        return join_token.join(paragraph_list[1:])


import argparse, os, sys, glob
import torch
import numpy as np
from omegaconf import OmegaConf
from PIL import Image
import imageio

from main import instantiate_from_config
import torchvision.transforms as T

from modules.affine_transformation.affine_transform import optimize_mask

def save_image(x, path):
    x = x.detach().cpu().squeeze()
    x = torch.clamp(x, -1., 1.)
    x = (x + 1.)/2.
    x = x.permute(1,2,0).numpy()
    x = (255*x).astype(np.uint8)
    x = Image.fromarray(x).save(path)

def save_mask(x, path):
    x = x.detach().cpu().squeeze(0)
    x = torch.clamp(x, 0, 1)
    # x = (x + 1.)/2.
    x = x.permute(1,2,0).numpy()
    x = (255*x).astype(np.uint8)
    x = np.repeat(x, 3, axis=-1)
    x = Image.fromarray(x).save(path)

def preprocess_image(image_path, size = (256,256)):
    image = Image.open(image_path)
    image = image.resize(size)
    if not image.mode == "RGB":
        image = image.convert("RGB")
    image = np.array(image).astype(np.uint8)
    image = torch.unsqueeze(T.ToTensor()(image), 0)

    image = 2*image - 1
    return image

def get_GIF(folder, num_frames = 16, GT = False):

    NUM_FRAMES = num_frames

    images = []
    for f in range(NUM_FRAMES):
        images.append(imageio.imread(folder + f'/{(f):05}.png'))
    save_path = folder + '/output.gif'
    imageio.mimsave(save_path, images)

    if not GT:
        masks = []
        for z in range(NUM_FRAMES-1):
            masks.append(imageio.imread(folder + f'/{(z):05}_mask.png'))

        save_path = folder + '/mask.gif'
        imageio.mimsave(save_path, masks)

def construct_affine_mat(translation = [0,0], rotation = 0, scaling = [1,1], shear = [0,0]):
    '''
    trans_para: [Translation, Rotation, Scaling, Shear]

    examples:
    Translation: [0, 0]
    Rotation: Theta
    Scaling: [1,1]
    shear: [0, 0]

    '''
    translation_mat = torch.eye(3)
    translation_mat[0, 2] = torch.tensor(translation[0])
    translation_mat[1, 2] = torch.tensor(translation[1])

    rotation_mat = torch.eye(3)
    rotation_mat[0,0] = torch.cos(torch.tensor(rotation))
    rotation_mat[0,1] = -torch.sin(torch.tensor(rotation))
    rotation_mat[1,0] = torch.sin(torch.tensor(rotation))
    rotation_mat[1,1] = torch.cos(torch.tensor(rotation))

    scale_mat = torch.eye(3)
    scale_mat[0, 0] = torch.tensor(scaling[0])
    scale_mat[1, 1] = torch.tensor(scaling[1])

    shear_mat = torch.eye(3)
    shear_mat[0, 1] = torch.tensor(shear[0])
    shear_mat[1, 0] = torch.tensor(shear[1])

    affine_mat =torch.matmul(shear_mat ,torch.matmul(scale_mat, torch.matmul(rotation_mat, translation_mat)))

    return affine_mat

# @torch.no_grad()
def sample_video(vqgan, path, frame_id, save_path = None, translate = (0,0)):
    i = frame_id

    index_num = f'{(i):05}'
    next_index_num = f'{(i+1):05}'

    inp_frame_path = path+'/'+index_num+'.png'
    x = preprocess_image(inp_frame_path).to(vqgan.device)

    # 1st forward pass for mask
    _, _, _ = vqgan(x)
    # torch.onnx.export(vqgan, x, 'bair.onnx', verbose = True, opset_version=12)
    curr_mask = vqgan.mask_gen
    cur_dev = curr_mask.device
    affine_mat = construct_affine_mat(translation = [translate[0]/256, translate[1]/256], rotation = 0, scaling = [1,1], shear = [0,0]).to(cur_dev)
    _, moved_mask = optimize_mask(curr_mask.squeeze(), None, mode = 'translation', iter = 1000, user_input = affine_mat)
    moved_mask = torch.unsqueeze(moved_mask, 0)
    moved_mask = torch.unsqueeze(moved_mask, 0)
    mask_GT = moved_mask

    mask_name = next_index_num +'_mask.png'
    mask_save_path = os.path.join(path, mask_name)
    save_mask(moved_mask, mask_save_path)

    # mask_name = index_num +'_mov_mask.png'
    # mask_save_path = os.path.join(save_path, mask_name)
    # save_mask(moved_mask, mask_save_path)

    # 2nd forwad pass for next frame
    mask_GT = mask_GT.to(vqgan.device)
    reconstruction, _, _ = vqgan(x, maskGT = mask_GT)

    next_index_num = f'{(i + 1):05}'
    image_name = next_index_num + '.png'
    save_p = os.path.join(path, image_name)
    save_image(reconstruction, save_p)

    # get_GIF(save_path, num_frames = num_frames)

def get_parser():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "-r",
        "--resume",
        type=str,
        nargs="?",
        help="load from logdir or checkpoint in logdir",
        default='/media/gabrie20/Work/projects/controllable_video_generation/logs/remote_checkpoints/'
    )
    parser.add_argument(
        "-b",
        "--base",
        nargs="*",
        metavar="base_config.yaml",
        help="paths to base configs. Loaded from left-to-right. "
        "Parameters can be overwritten or added with command-line options of the form `--key value`.",
        default=list(),
    )
    parser.add_argument(
        "-c",
        "--config",
        nargs="?",
        metavar="single_config.yaml",
        help="path to single config. If specified, base configs will be ignored "
        "(except for the last one if left unspecified).",
        const=True,
        default="/media/gabrie20/Work/projects/controllable_video_generation/web_app/models/bair_config.yaml",
    )
    parser.add_argument(
        "--ignore_base_data",
        action="store_true",
        help="Ignore data specification from base configs. Useful if you want "
        "to specify a custom datasets on the command line.",
    )

    parser.add_argument(
        "--num_frames",
        type=int,
        default=1,
        help="number of frames to generate in test phase",
    )
    parser.add_argument(
        "--ckpt",
        type=str,
        default='finetune_translation',
        help="checkpoint to load",
    )

    return parser

def load_model_from_config(config, sd, gpu=True, eval_mode=True):
    if "ckpt_path" in config.params:
        print("Deleting the restore-ckpt path from the config...")
        config.params.ckpt_path = None
    if "downsample_cond_size" in config.params:
        print("Deleting downsample-cond-size from the config and setting factor=0.5 instead...")
        config.params.downsample_cond_size = -1
        config.params["downsample_cond_factor"] = 0.5
    try:
        if "ckpt_path" in config.params.first_stage_config.params:
            config.params.first_stage_config.params.ckpt_path = None
            print("Deleting the first-stage restore-ckpt path from the config...")
        if "ckpt_path" in config.params.cond_stage_config.params:
            config.params.cond_stage_config.params.ckpt_path = None
            print("Deleting the cond-stage restore-ckpt path from the config...")
    except:
        pass

    model = instantiate_from_config(config)
    if sd is not None:
        missing, unexpected = model.load_state_dict(sd, strict=False)
        print(f"Missing Keys in State Dict: {missing}")
        print(f"Unexpected Keys in State Dict: {unexpected}")
    if gpu:
        model.cuda()
    if eval_mode:
        model.eval()
    return {"model": model}

def load_model_and_dset(config, ckpt, gpu, eval_mode):
    # get data

    # now load the specified checkpoint
    if ckpt:
        pl_sd = torch.load(ckpt, map_location="cpu")
        global_step = pl_sd["global_step"]
    else:
        pl_sd = {"state_dict": None}
        global_step = None
    model = load_model_from_config(config.model,
                                   pl_sd["state_dict"],
                                   gpu=gpu,
                                   eval_mode=eval_mode)["model"]
    return model, global_step

if __name__ == "__main__":
    sys.path.append(os.getcwd())

    parser = get_parser()

    opt, unknown = parser.parse_known_args()

    ckpt = None
    if opt.resume:
        if not os.path.exists(opt.resume):
            raise ValueError("Cannot find {}".format(opt.resume))
        if os.path.isfile(opt.resume):
            paths = opt.resume.split("/")
            try:
                idx = len(paths)-paths[::-1].index("logs")+1
            except ValueError:
                idx = -2 # take a guess: path/to/logdir/checkpoints/model.ckpt
            logdir = "/".join(paths[:idx])
            ckpt = opt.resume
        else:
            assert os.path.isdir(opt.resume), opt.resume
            logdir = opt.resume.rstrip("/")
            ckpt = os.path.join(logdir, "checkpoints", opt.ckpt + ".ckpt")
        print(f"logdir:{logdir}")
        base_configs = sorted(glob.glob(os.path.join(logdir, "configs/*-project.yaml")))
        opt.base = base_configs+opt.base

    if opt.config:
        if type(opt.config) == str:
            opt.base = [opt.config]
        else:
            opt.base = [opt.base[-1]]

    configs = [OmegaConf.load(cfg) for cfg in opt.base]
    cli = OmegaConf.from_dotlist(unknown)

    config = OmegaConf.merge(*configs, cli)

    gpu = True
    eval_mode = True

    vqgan, global_step = load_model_and_dset(config, ckpt, gpu, eval_mode)

    image_path = 'web_app/image'
    for f in os.listdir(image_path):
        if f != '00000.png' and f[-1] != 'l':
            os.remove(image_path + '/' + f)
    sample_video(vqgan, image_path, opt.num_frames, save_path = image_path)

    # torch.save(vqgan.state_dict(), 'bair_inference_model.pt')


from shall.ShallEntity import ShallEntity, P, R
from injector import inject
from src.shall.CheckReturnConstraints import CheckReturnConstraints
from src.shall.CheckReturnValue import CheckReturnValue
from src.shall.CheckSideEffects import CheckSideEffects

class Check():
    @inject
    def __init__(self,
                 checkReturnValue:CheckReturnValue[P,R],
                 checkReturnConstraints: CheckReturnConstraints[P,R],
                 checkSideEffects: CheckSideEffects[P,R]
                 ) -> None:
        self.checkReturnValue = checkReturnValue
        self.checkReturnConstraints = checkReturnConstraints
        self.checkSideEffects = checkSideEffects

    def check(self) -> None:
        paramlist = self.parameters[0]
        paramkwargs = self.parameters[1]
        print(self.explanation)
        callResult = self.callable(*paramlist, **paramkwargs)
        self.checkReturnValue.checkReturnValue(callResult)
        self.checkReturnConstraints.checkReturnConstraints( paramlist, paramkwargs)
        self.checkSideEffects.checkSideEffects(paramlist,paramkwargs)


from dataclasses import dataclass, field
from enum import Enum
from aws_lambda_powertools import Logger

logger = Logger()

class ApiEventTypes(Enum):
    CORS_PREFLIGHT = "OPTIONS"
    GET = "GET"
    POST = "POST"

class ApiEvent(Enum):
    A_WEEK = "week"
    THIS_WEEK = "thisweek"
    LAST_WEEK = "last_week"

@dataclass
class IncomingEvent:
    event: dict
    path: str = field(init=False)
    api_event: ApiEvent = field(init=False)
    week_number: int = field(init=False)
    total_payout: float = field(init=False)
    path_parts: list = field(init=False)
    IS_OPTIONS: bool = field(init=False)
    IS_GET: bool = field(init=False)
    IS_POST: bool = field(init=False)
    api_type: str = field(init=False)

    def __post_init__(self):
        self.path = self.event.get("resource", "")
        self.determine_event()
        self.determine_type()
        self._is_allowed_method()

    def determine_event(self):

        dispatch = {
            "/v1/week/{proxy+}": ApiEvent.A_WEEK,
            "/v1/lastweek/{proxy+}": ApiEvent.LAST_WEEK,
            "/v1/thisweek/{proxy+}": ApiEvent.THIS_WEEK,
            "/v1/lastweek": ApiEvent.LAST_WEEK,
            "/v1/thisweek": ApiEvent.THIS_WEEK
        }

        self.api_event = dispatch[self.path]

        self._parse_path_parts()

    def determine_type(self):
        """
        determines the type of the api call
        """

        self.method = self.event.get("httpMethod")

        self.IS_GET = self.method == ApiEventTypes.GET.value
        self.IS_OPTIONS = self.method == ApiEventTypes.CORS_PREFLIGHT.value
        self.IS_POST = self.method == ApiEventTypes.POST.value

    def _is_allowed_method(self):
        """
        GetEntity only allows Options and Get method calls.
        """
        if self.IS_OPTIONS:
            self.api_type = ApiEventTypes.CORS_PREFLIGHT

        elif self.IS_GET:
            self.api_type = ApiEventTypes.GET

        else:
            raise TypeError("Not a valid Type for GetEntity - must be GET or OPTIONS")

    def _parse_path_parts(self):
        logger.info(f"Parsing Proxy paths {self.event}")
        try:
            self.path_parts = self.event.get("pathParameters", {}).get("proxy", "")

            parts = self.path_parts.split("/")
            number_of_proxy_paths = len(parts)
            self.total_payout = 0

            if self.api_event == ApiEvent.A_WEEK:
                self.week_number = parts[0]
                if number_of_proxy_paths == 2:
                    self.total_payout=parts[1]

            elif number_of_proxy_paths == 1:
                self.total_payout = parts[0]

        except:
            logger.info("No Proxy parameters found)")
            self.path_parts = ""
            self.total_payout = 0
            self.week_number = self.api_event.value


# encoding: utf-8

from enum import Enum
from typing import List

from fastapi import Path, HTTPException, Query, Response
from pydantic import BaseModel, parse_obj_as
from sqlalchemy import Integer
from sqlalchemy.future import select

from dbsession import async_session
from endpoints import filter_fields, sql_db_only
from models.Block import Block
from models.Transaction import Transaction, TransactionOutput, TransactionInput
from server import app

DESC_RESOLVE_PARAM = "Use this parameter if you want to fetch the TransactionInput previous outpoint details." \
                     " Light fetches only the address and amount. Full fetches the whole TransactionOutput and " \
                     "adds it into each TxInput."

class TxOutput(BaseModel):
    id: int
    transaction_id: str
    index: int
    amount: int
    script_public_key: str
    script_public_key_address: str
    script_public_key_type: str
    accepting_block_hash: str | None

    class Config:
        orm_mode = True

class TxInput(BaseModel):
    id: int
    transaction_id: str
    index: int
    previous_outpoint_hash: str
    previous_outpoint_index: str
    previous_outpoint_resolved: TxOutput | None
    previous_outpoint_address: str | None
    previous_outpoint_amount: int | None
    signature_script: str
    sig_op_count: str

    class Config:
        orm_mode = True

class TxModel(BaseModel):
    subnetwork_id: str | None
    transaction_id: str | None
    hash: str | None
    mass: str | None
    block_hash: List[str] | None
    block_time: int | None
    is_accepted: bool | None
    accepting_block_hash: str | None
    accepting_block_blue_score: int | None
    inputs: List[TxInput] | None
    outputs: List[TxOutput] | None

    class Config:
        orm_mode = True

class TxSearch(BaseModel):
    transactionIds: List[str]

class PreviousOutpointLookupMode(str, Enum):
    no = "no"
    light = "light"
    full = "full"

@app.get("/transactions/{transactionId}",
         response_model=TxModel,
         tags=["Kaspa transactions"],
         response_model_exclude_unset=True)
@sql_db_only
async def get_transaction(response: Response,
                          transactionId: str = Path(regex="[a-f0-9]{64}"),
                          inputs: bool = True,
                          outputs: bool = True,
                          resolve_previous_outpoints: PreviousOutpointLookupMode =
                          Query(default=PreviousOutpointLookupMode.no,
                                description=DESC_RESOLVE_PARAM)):
    """
    Get block information for a given block id
    """
    async with async_session() as s:
        tx = await s.execute(select(Transaction, Block.blue_score) \
                             .join(Block, Transaction.accepting_block_hash == Block.hash, isouter=True)
                             .filter(Transaction.transaction_id == transactionId))

        tx = tx.first()

        tx_outputs = None
        tx_inputs = None

        if outputs:
            tx_outputs = await s.execute(select(TransactionOutput) \
                                         .filter(TransactionOutput.transaction_id == transactionId))

            tx_outputs = tx_outputs.scalars().all()

        if inputs:
            if resolve_previous_outpoints in ["light", "full"]:
                tx_inputs = await s.execute(select(TransactionInput, TransactionOutput)
                                            .outerjoin(TransactionOutput,
                                                       (TransactionOutput.transaction_id == TransactionInput.previous_outpoint_hash) &
                                                       (TransactionOutput.index == TransactionInput.previous_outpoint_index))
                                            .filter(TransactionInput.transaction_id == transactionId))

                tx_inputs = tx_inputs.all()

                if resolve_previous_outpoints in ["light", "full"]:
                    for tx_in, tx_prev_outputs in tx_inputs:
                        # it is possible, that the old tx is not in database. Leave fields empty
                        if not tx_prev_outputs:
                            tx_in.previous_outpoint_amount = None
                            tx_in.previous_outpoint_address = None
                            if resolve_previous_outpoints == "full":
                                tx_in.previous_outpoint_resolved = None
                            continue

                        tx_in.previous_outpoint_amount = tx_prev_outputs.amount
                        tx_in.previous_outpoint_address = tx_prev_outputs.script_public_key_address
                        if resolve_previous_outpoints == "full":
                            tx_in.previous_outpoint_resolved = tx_prev_outputs

                # remove unneeded list
                tx_inputs = [x[0] for x in tx_inputs]

            else:
                tx_inputs = await s.execute(select(TransactionInput) \
                                            .filter(TransactionInput.transaction_id == transactionId))
                tx_inputs = tx_inputs.scalars().all()

    if tx:
        return {
            "subnetwork_id": tx.Transaction.subnetwork_id,
            "transaction_id": tx.Transaction.transaction_id,
            "hash": tx.Transaction.hash,
            "mass": tx.Transaction.mass,
            "block_hash": tx.Transaction.block_hash,
            "block_time": tx.Transaction.block_time,
            "is_accepted": tx.Transaction.is_accepted,
            "accepting_block_hash": tx.Transaction.accepting_block_hash,
            "accepting_block_blue_score": tx.blue_score,
            "outputs": parse_obj_as(List[TxOutput], tx_outputs) if tx_outputs else None,
            "inputs": parse_obj_as(List[TxInput], tx_inputs) if tx_inputs else None
        }
    else:
        raise HTTPException(status_code=404, detail="Transaction not found", headers={
            "Cache-Control": "public, max-age=3"
        })

@app.post("/transactions/search",
          response_model=List[TxModel],
          tags=["Kaspa transactions"],
          response_model_exclude_unset=True)
@sql_db_only
async def search_for_transactions(txSearch: TxSearch,
                                  fields: str = "",
                                  resolve_previous_outpoints: PreviousOutpointLookupMode =
                                  Query(default=PreviousOutpointLookupMode.no,
                                        description=DESC_RESOLVE_PARAM)):
    """
    Get block information for a given block id
    """
    if len(txSearch.transactionIds) > 1000:
        raise HTTPException(422, "Too many transaction ids")

    if resolve_previous_outpoints in ["light", "full"] and len(txSearch.transactionIds) > 50:
        raise HTTPException(422, "Temporary issue: Transaction ids count is limited to 50 for light and full searches.")

    fields = fields.split(",") if fields else []

    async with async_session() as s:
        tx_list = await s.execute(select(Transaction, Block.blue_score)
                                  .join(Block, Transaction.accepting_block_hash == Block.hash, isouter=True)
                                  .filter(Transaction.transaction_id.in_(txSearch.transactionIds))
                                  .order_by(Transaction.block_time.desc()))

        tx_list = tx_list.all()

        if not fields or "inputs" in fields:
            # join TxOutputs if needed
            if resolve_previous_outpoints in ["light", "full"]:
                tx_inputs = await s.execute(select(TransactionInput, TransactionOutput)
                                            .outerjoin(TransactionOutput,
                                                       (TransactionOutput.transaction_id == TransactionInput.previous_outpoint_hash) &
                                                       (TransactionOutput.index == TransactionInput.previous_outpoint_index))
                                            .filter(TransactionInput.transaction_id.in_(txSearch.transactionIds)))

            # without joining previous_tx_outputs
            else:
                tx_inputs = await s.execute(select(TransactionInput)
                                            .filter(TransactionInput.transaction_id.in_(txSearch.transactionIds)))
            tx_inputs = tx_inputs.all()

            if resolve_previous_outpoints in ["light", "full"]:
                for tx_in, tx_prev_outputs in tx_inputs:

                    # it is possible, that the old tx is not in database. Leave fields empty
                    if not tx_prev_outputs:
                        tx_in.previous_outpoint_amount = None
                        tx_in.previous_outpoint_address = None
                        if resolve_previous_outpoints == "full":
                            tx_in.previous_outpoint_resolved = None
                        continue

                    tx_in.previous_outpoint_amount = tx_prev_outputs.amount
                    tx_in.previous_outpoint_address = tx_prev_outputs.script_public_key_address
                    if resolve_previous_outpoints == "full":
                        tx_in.previous_outpoint_resolved = tx_prev_outputs

            # remove unneeded list
            tx_inputs = [x[0] for x in tx_inputs]

        else:
            tx_inputs = None

        if not fields or "outputs" in fields:
            tx_outputs = await s.execute(select(TransactionOutput) \
                                         .filter(TransactionOutput.transaction_id.in_(txSearch.transactionIds)))
            tx_outputs = tx_outputs.scalars().all()
        else:
            tx_outputs = None

    return (filter_fields({
        "subnetwork_id": tx.Transaction.subnetwork_id,
        "transaction_id": tx.Transaction.transaction_id,
        "hash": tx.Transaction.hash,
        "mass": tx.Transaction.mass,
        "block_hash": tx.Transaction.block_hash,
        "block_time": tx.Transaction.block_time,
        "is_accepted": tx.Transaction.is_accepted,
        "accepting_block_hash": tx.Transaction.accepting_block_hash,
        "accepting_block_blue_score": tx.blue_score,
        "outputs": parse_obj_as(List[TxOutput],
                                [x for x in tx_outputs if x.transaction_id == tx.Transaction.transaction_id])
        if tx_outputs else None,  # parse only if needed
        "inputs": parse_obj_as(List[TxInput],
                               [x for x in tx_inputs if x.transaction_id == tx.Transaction.transaction_id])
        if tx_inputs else None  # parse only if needed
    }, fields) for tx in tx_list)


import torch
import numpy as np

def with_tensor(func):
    def wrapper(*args, **kwargs):
        found_tensor = False

        new_args = []
        for arg in args:
            if isinstance(arg, np.ndarray):
                t = torch.tensor(arg)
                if arg.dtype in [np.float32, np.float64]:
                    t = t.float()
                new_args.append(t)
            elif isinstance(arg, torch.Tensor):
                found_tensor = True
                new_args.append(arg)
            else:
                new_args.append(arg)

        new_kwargs = {}
        for key, value in kwargs.items():
            if isinstance(value, np.ndarray):
                t = torch.tensor(value)
                if arg.dtype in [np.float32, np.float64]:
                    t = t.float()
                new_kwargs[key] = t
            elif isinstance(value, torch.Tensor):
                found_tensor = True
                new_kwargs[key] = value
            else:
                new_kwargs[key] = value

        out = func(*new_args, **new_kwargs)

        # if at least one torch.tensor is in the input,
        # return the output in torch.tensor type
        if found_tensor:
            return out

        # if there are no tensors in the input but are only numpy arrays,
        # convert all tensors to numpy arrays
        if isinstance(out, tuple):
            return tuple([x.numpy() if isinstance(x, torch.Tensor) else x for x in out])
        elif isinstance(out, list):
            return list([x.numpy() if isinstance(x, torch.Tensor) else x for x in out])
        elif isinstance(out, dict):
            return {k: v.numpy() if isinstance(v, torch.Tensor) else v for k, v in out.items()}
        elif isinstance(out, torch.Tensor):
            return out.numpy()

    return wrapper


n = 5
row = 1
nst = 1
while row <= n:
    cst = 1
    while cst <= nst:
        print("*", end = " ")
        cst += 1  #till here we completed the task of 1 row

    print()
    nst += 1
    row += 1


'''

  There are a total of n levels to be played in the Game.
  A player can unlock a level by first completing easier levels.
  completing one level will unlock other level(s).
  The map of level complexity is defined as [B, A],
  where you need to finish level A to play level 1 8 Given hierarchy of game levels and a level X,
  output which all levels you need to finish to unlock level X. e

  For example:

  I)
  [Y,X]
  There are a total of 2 levels to complete.
  1) To choose level Y you should have finished level X.
  2) So the correct sequence order is[X,Y]

  II)
  [[X,W],[Y,W],[Z,X],[Z,Y],[U,V],[V,T]]
  There are a total of 4 levels to complete.
  To play level Z you should have finished both levels X and Y.
  Both levels X and Y should be completed after you finished level W.
  So one correct course order is [W,X,Y,Z]

  Please give hit to solve this question

        W     T
       / \    |
      X   Y   V
       \ /    |
        Z     U
'''

from collections import Counter, defaultdict, deque

class Solution:
  def unlockLevels(self, prereqs, target):
    childToParents, parentToChildren, inDegrees, sources = self.buildGraphs(prereqs)
    relevantCourses = self.getRelevantCourses(childToParents, target)

    queue = deque(list(sources))
    pathToTarget = []

    while queue:
      node = queue.popleft()
      if node not in relevantCourses: continue
      pathToTarget.append(node)

      for child in parentToChildren[node]:
        inDegrees[child] -= 1
        if inDegrees[child] == 0:
          queue.append(child)

    return pathToTarget

  def getRelevantCourses(self, graph, target):
    relevantCourses = set()
    queue = deque([target])

    while queue:
      node = queue.popleft()
      relevantCourses.add(node)
      for parent in graph[node]:
        queue.append(parent)

    return relevantCourses

  def buildGraphs(self, prereqs):
    childToParents = defaultdict(list)
    parentToChildren = defaultdict(list)
    inDegrees = defaultdict(int)
    sources = set()

    for child, parent in prereqs:
      childToParents[child].append(parent)
      parentToChildren[parent].append(child)
      inDegrees[child] += 1
      sources.add(parent)

    for parent in list(sources):
      if parent in childToParents: sources.discard(parent)

    return childToParents, parentToChildren, inDegrees, sources

def runSolution():
  solution = Solution()
  print(solution.unlockLevels([
    ['Y','X']
  ], 'Y'))
  print(solution.unlockLevels([
    ['X','W'],['Y','W'],['Z','X'],['Z','Y'],['U','V'],['V','T']
  ], 'Z'))
  pass
runSolution()


import requests
import sys
import argparse
import os
from dotenv import dotenv_values
import datetime

config = dotenv_values(".env")
current_year = datetime.datetime.now().year

def create_directory_structure(day, year):
    if not os.path.exists(f'{year}'):
        os.mkdir(str(year))
    path = f"{year}/Day{day}/"
    try:
        os.mkdir(path)
    except FileExistsError:
        pass

def create_standard_example_file(day, year):
    path = f"{year}/Day{day}/example.txt"
    with open(path, "w") as f:
        f.write("")

def copy_boilerplate_py_file(day, name, year):
    path = f"{year}/Day{day}/{name}.py"
    os.system(f"cp boilerplate.py {path}")

def save_data(day, year):
    out_path = f"{year}/Day{day}/input.txt"
    url = f"https://adventofcode.com/{year}/day/{day}/input"
    id = config.get("MY_ID")
    if not id:
        print("MY_ID not found in .env file")
        sys.exit(1)
    cookies = {"session": id}
    r = requests.get(url, cookies=cookies)
    with open(out_path, "w") as f:
        f.write(r.text)

def create_template_files(day, name, year):
    create_directory_structure(day, year)
    create_standard_example_file(day, year)
    copy_boilerplate_py_file(day, name, year)
    save_data(day, year)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        prog="setup.py",
        description="Create new folder and template files for a new day of Advent of Code",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
    )

    parser.add_argument("day", type=int, help="Advent of Code day")
    parser.add_argument("-y", "--year", type=int, default=current_year,
                        help="Year of the challenge")
    parser.add_argument("-n", "--name", type=str, default='day_{day}', help="Name of the file")
    args = parser.parse_args()

    if args.name == "day_{day}":
        args.name = f"day_{args.day}"

    create_template_files(args.day, args.name, args.year)


import os
import numpy as np
import pandas as pd
import datetime as dt
import sklearn.metrics as mt
from pathlib import Path
from tqdm import tqdm
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier
# datasets = ['botometer-feedback-2019', 'gilani-2017', 'Twibot-22']
for i in range(1):
  datasets = ['midterm-2018']
  #datasets = ['cresci-2015']
  path1 = '../../../datasets/'

  for dataset in tqdm(datasets):

      if dataset == 'Twibot-22':
          nodes = pd.read_json(path1 + dataset + '/user.json')
          labels = pd.read_csv(path1 + dataset+  '/label.csv')
          split = pd.read_csv(path1 + dataset + '/split.csv')
      else:
          nodes = pd.read_json(path1 + dataset+  '/node.json')
          labels = pd.read_csv(path1 + dataset + '/label.csv')
          split = pd.read_csv(path1 + dataset + '/split.csv')

      users = pd.merge(labels, nodes)
      users = pd.merge(users, split)

      scores = pd.DataFrame()

      #
      def scoring2(row):
          if row['listed_count'] is None:
              return 0
          else:
              return int(row['listed_count'])

      scores['listed_count'] = users['public_metrics'].apply(scoring2)

      #
      def scoring3(row):
          if row['followers_count'] is None:
              return 0
          else:
              return int(row['followers_count'])

      scores['followers'] = users['public_metrics'].apply(scoring3)
      #

      #
      def scoring7(row):
          if row['tweet_count'] is None:
              return 0
          else:
              return int(row['tweet_count'])

      scores['statuses_count'] = users['public_metrics'].apply(scoring7)
      #
      #
      def scoring8(row):
          if row['following_count'] is None:
              return 0
          else:
              return int(row['following_count'])
      #
      #
      scores['num_followings'] = users['public_metrics'].apply(scoring8)

    #  def scoring11(row):
    #      if  row['favourites_count'] is None:
     #         return 0
    #      else:
     #         return int(row['favourites_count'])

     # scores['favourites_count'] = users['public_metrics'].apply(scoring11)
      #

      def scoring13(row):
        if row == 'bot':
            return 1
        else:
            return 0

      scores['label'] = users['label'].apply(scoring13)

      scores['id'] = users['id']
      scores['split'] = users['split']

      train_set = scores[scores['split'] == 'train']
      del train_set['split']
      test_set = scores[scores['split'] == 'test']
      del test_set['split']
      train_label = train_set['label'].values
      del train_set['label']
      test_label = test_set['label'].values
      del test_set['label']
      del train_set['id']
      del test_set['id']
      train_set = train_set.values
      test_set = test_set.values
      Random_Forest = RandomForestClassifier(n_estimators=100)
      Random_Forest.fit(train_set, train_label)

      y_hat = Random_Forest.predict(test_set)

      acc = mt.accuracy_score(test_label, y_hat)
      precision = mt.precision_score(test_label, y_hat)
      f1_score = mt.f1_score(test_label, y_hat)
      auc = mt.roc_auc_score(test_label, y_hat)
      recall = mt.recall_score(test_label, y_hat)

      # print(acc, file=f)
      # print(precision, file=f)
      # print(recall, file=f)
      # print(f1_score, file=f)
      # print(auc, dataset, end='\n\n', file=f)
      final = []
      final.append(acc)
      final.append(precision)
      final.append(recall)
      final.append(f1_score)
      final.append(auc)
      final.append(dataset)

      acc = mt.accuracy_score(1 - test_label, y_hat)
      precision = mt.precision_score(1 - test_label, y_hat)
      f1_score = mt.f1_score(1 - test_label, y_hat)
      auc = mt.roc_auc_score(1 - test_label, y_hat)
      recall = mt.recall_score(1 - test_label, y_hat)
      final.append(acc)
      final.append(precision)
      final.append(recall)
      final.append(f1_score)
      final.append(auc)
      final.append(dataset)
      with open('./'+dataset+'.txt', 'a') as f:
        f.write(str(final))
        f.write('\r\n')


import math
from flask import flash
from flask_app.config.mysqlconnection import connectToMySQL

class Appointment:

    def __init__(self, data):
        self.id = data['id']
        self.title = data['title']
        self.start_time = data['start_time']
        self.end_time = data['end_time']
        self.description = data['description']
        self.frequency = data['frequency']
        self.users_id = data['users_id']
        self.created_at = data['created_at']
        self.updated_at = data['updated_at']

    @staticmethod
    def validateAddAppointment(data):
        is_valid = True
        if len(data['title']) < 2:
            is_valid = False

        return is_valid

    @classmethod
    def insertAppointments(cls, data):
        query = "INSERT INTO appointment (title, start_time, end_time, description, frequency, users_id) VALUES (%(title)s, %(start_time)s, %(end_time)s, %(description)s, %(frequency)s, %(users_id)s)"
        result = connectToMySQL("health_check").query_db(query, data)
        return result

    @classmethod
    def getAppointments(cls, data):
        query = "SELECT * from appointment WHERE users_id = %(users_id)s ORDER BY start_time"
        result = connectToMySQL("health_check").query_db(query, data)
        appointments = []
        for appointment in result:
            appointments.append(cls(appointment))
        return appointments

    @staticmethod
    def deleteAppointment(data):
        query = "DELETE from appointment WHERE id = %(id)s;"
        result = connectToMySQL("health_check").query_db(query, data)
        return result

    @classmethod
    def getOneAppointment(cls, data):
        query = "SELECT * from appointment WHERE users_id = %(users_id)s ORDER BY start_time limit 1"
        result = connectToMySQL("health_check").query_db(query, data)
        appointments = []
        for appointment in result:
            appointments.append(cls(appointment))

        if len(appointments) == 0 :
            appointments = "No appointment"
            print("No appointment")
        else:
            appointments = appointments[0]
        return appointments


#Create dataset of first 8 regions in dataset for visualization purposes, using homes_sold_mom
df_temp_2 = pd.DataFrame(list(zip(time_frame, homes_sold_mom['Homes Sold MoM _0'], homes_sold_mom['Homes Sold MoM _1'], homes_sold_mom['Homes Sold MoM _2'], homes_sold_mom['Homes Sold MoM _3'], homes_sold_mom['Homes Sold MoM _4'], homes_sold_mom['Homes Sold MoM _5'], homes_sold_mom['Homes Sold MoM _6'], homes_sold_mom['Homes Sold MoM _7'])),
               columns =['Time', df_list[0]['Region_0'][0], df_list[1]['Region_1'][0], df_list[2]['Region_2'][0], df_list[3]['Region_3'][0], df_list[4]['Region_4'][0], df_list[5]['Region_5'][0], df_list[6]['Region_6'][0], df_list[7]['Region_7'][0]])

# plot of first 8 regions in dataset, using homes_sold_mom
sns_plot = sns.lineplot(df_temp_2['Time'], df_temp_2.iloc[:,1], label = df_temp_2.columns[1])
sns_plot = sns.lineplot(df_temp_2['Time'], df_temp_2.iloc[:,2], label = df_temp_2.columns[2])
sns_plot = sns.lineplot(df_temp_2['Time'], df_temp_2.iloc[:,3], label = df_temp_2.columns[3])
sns_plot = sns.lineplot(df_temp_2['Time'], df_temp_2.iloc[:,4], label = df_temp_2.columns[4])
sns_plot = sns.lineplot(df_temp_2['Time'], df_temp_2.iloc[:,5], label = df_temp_2.columns[5])
sns_plot = sns.lineplot(df_temp_2['Time'], df_temp_2.iloc[:,6], label = df_temp_2.columns[6])
sns_plot = sns.lineplot(df_temp_2['Time'], df_temp_2.iloc[:,7], label = df_temp_2.columns[7])
sns_plot = sns.lineplot(df_temp_2['Time'], df_temp_2.iloc[:,8], label = df_temp_2.columns[8])

plt.legend()
plt.title("Time Series - Homes Sold Month-over-Month",fontsize = 15)
plt.xlabel("Time", fontsize = 15)
plt.ylabel("Homes Sold Month-over-Month", fontsize = 15)
sns.set(rc={'figure.figsize':(15,10)})
plt.xticks(range(5, 100, 12))
#plt.xlim()
plt.show()

#save image of visualization
sns_plot.figure.savefig("../data_visualizations/Time Series - Homes Sold Month-over-Month.png")


import glob
import os

"""
This script renames all img files in each class folder into consecutive integer in order
"""
def main():
    dataset_root = "/media/molly/MR_GRAY/DCNNCF_trainingset/FathomNet_mini"
    class_folders = dataset_root + "/*/"
    for folder_path in glob.glob(class_folders):
        imgs_path = folder_path + "*.jpg"
        i=1
        img_paths = sorted(glob.glob(imgs_path, recursive=True))
        for img_path in img_paths:
            correct_path = folder_path+str(i).zfill(4)+".jpg"
            if img_path != correct_path:
                os.rename(img_path, correct_path)
            i+=1

if __name__ == "__main__":
    main()


import datetime
import json
import os
import pickle
import random
import socket
import sys
import time
from collections import defaultdict

import numpy as np
import torch
from tqdm import tqdm

sys.path.extend(["./src", "./src/DeepCTR-Torch", "./src/tianshou"])

from core.inputs import get_dataset_columns
from core.state_tracker2 import StateTracker_Caser, StateTracker_GRU, StateTracker_SASRec, StateTrackerAvg2
from core.user_model_ensemble import EnsembleModel

# os.environ['CUDA_LAUNCH_BLOCKING'] = '1'

from core.configs import get_training_data, get_true_env

from tianshou.data import VectorReplayBuffer, Batch
from tianshou.env import DummyVectorEnv

from util.utils import create_dir
import logzero
from logzero import logger

def prepare_dir_log(args):
    # %% 1. Create dirs
    MODEL_SAVE_PATH = os.path.join(".", "saved_models", args.env, args.model_name)
    create_dirs = [os.path.join(".", "saved_models"),
                   os.path.join(".", "saved_models", args.env),
                   MODEL_SAVE_PATH,
                   os.path.join(MODEL_SAVE_PATH, "logs")]
    create_dir(create_dirs)

    nowtime = datetime.datetime.fromtimestamp(time.time()).strftime("%Y_%m_%d-%H_%M_%S")
    logger_path = os.path.join(MODEL_SAVE_PATH, "logs", "[{}]_{}.log".format(args.message, nowtime))
    logzero.logfile(logger_path)
    hostname = socket.gethostname()
    args.hostname = hostname
    logger.info(json.dumps(vars(args), indent=2))

    return MODEL_SAVE_PATH, logger_path

def construct_buffer_from_offline_data(args, df_train, env):
    num_bins = args.test_num

    df_user_num = df_train[["user_id", "item_id"]].groupby("user_id").agg(len)

    if args.env == 'KuaiEnv-v0':
        assert hasattr(env, "lbe_user")
        df_user_num_mapped = df_user_num.loc[env.lbe_user.classes_]
        df_user_num_mapped = df_user_num_mapped.reset_index(drop=True)
        assert len(env.mat) == len(df_user_num_mapped)

        assert hasattr(env, "lbe_item")
        df_numpy = df_train[["user_id", "item_id", args.yfeat]].to_numpy()
        indices = [False] * len(df_numpy)
        for k, (user, item, yfeat) in tqdm(enumerate(df_numpy), total=len(df_numpy)):
            if int(item) in env.lbe_item.classes_:
                indices[k] = True
        df_filtered = df_train[["user_id", "item_id", args.yfeat]].loc[indices]
        df_filtered[
            "user_id"] = dummy_user = 0  # set to dummy user. Since these users are not in the evaluational environment.
        df_filtered = df_filtered.reset_index(drop=True)
        # df_user_items = df_filtered.groupby("user_id").agg(list)

        df_filtered["item_id"] = env.lbe_item.transform(df_filtered["item_id"])

        num_each = int(np.ceil(len(df_filtered) / num_bins))
        env.max_turn = num_each
        buffer_size = num_each * num_bins
        buffer = VectorReplayBuffer(buffer_size, num_bins)

        ind_pair = zip(np.arange(0, buffer_size, num_each), np.arange(num_each, buffer_size + num_each, num_each))
        for ind_buffer, (left, right) in tqdm(enumerate(ind_pair), total=num_bins,
                                              desc="preparing offline data into buffer..."):
            seq = df_filtered.iloc[int(left):int(right)]

            items = [-1] + seq["item_id"].to_list()
            rewards = seq[args.yfeat].to_numpy()
            np_ui_pair = np.vstack([np.ones_like(items) * dummy_user, items]).T

            env.reset()
            env.cur_user = dummy_user
            dones = np.zeros(len(rewards), dtype=bool)

            for k, item in enumerate(items[1:]):
                obs_next, rew, done, info = env.step(item)
                if done:
                    env.reset()
                    env.cur_user = dummy_user
                dones[k] = done
                dones[-1] = True
                # print(env.cur_user, obs_next, rew, done, info)

            batch = Batch(obs=np_ui_pair[:-1], obs_next=np_ui_pair[1:], act=items[1:],
                          policy={}, info={}, rew=rewards, done=dones)

            ptr, ep_rew, ep_len, ep_idx = buffer.add(batch, buffer_ids=np.ones([len(batch)], dtype=int) * ind_buffer)

        return buffer

    elif args.env == 'YahooEnv-v0':
        df_user_num_mapped = df_user_num.iloc[:len(env.mat)]
    else:  # KuaiRand-v0 and CoatEnv-v0
        df_user_num_mapped = df_user_num

    df_user_num_sorted = df_user_num_mapped.sort_values("item_id", ascending=False)

    bins = np.zeros([num_bins])
    bins_ind = defaultdict(set)
    for user, num in df_user_num_sorted.reset_index().to_numpy():
        ind = bins.argmin()
        bins_ind[ind].add(user)
        bins[ind] += num
        np.zeros([num_bins])

    max_size = max(bins)
    buffer_size = max_size * num_bins
    buffer = VectorReplayBuffer(buffer_size, num_bins)

    # env, env_task_class, kwargs_um = get_true_env(args)
    env.max_turn = max_size
    df_user_items = df_train[["user_id", "item_id", args.yfeat]].groupby("user_id").agg(list)
    for indices, users in tqdm(bins_ind.items(), total=len(bins_ind), desc="preparing offline data into buffer..."):
        for user in users:
            items = [-1] + df_user_items.loc[user][0]
            rewards = df_user_items.loc[user][1]
            np_ui_pair = np.vstack([np.ones_like(items) * user, items]).T

            env.reset()
            env.cur_user = user
            dones = np.zeros(len(rewards), dtype=bool)

            for k, item in enumerate(items[1:]):
                obs_next, rew, done, info = env.step(item)
                if done:
                    env.reset()
                    env.cur_user = user
                dones[k] = done
                dones[-1] = True
                # print(env.cur_user, obs_next, rew, done, info)
            batch = Batch(obs=np_ui_pair[:-1], obs_next=np_ui_pair[1:], act=items[1:],
                          policy={}, info={}, rew=rewards, done=dones)
            ptr, ep_rew, ep_len, ep_idx = buffer.add(batch, buffer_ids=np.ones([len(batch)], dtype=int) * indices)

    return buffer

def prepare_buffer_via_offline_data(args):
    df_train, df_user, df_item, list_feat = get_training_data(args.env)
    # df_val, df_user_val, df_item_val, list_feat = get_val_data(args.env)
    # df_train = df_train.head(10000)
    if "time_ms" in df_train.columns:
        df_train.rename(columns={"time_ms": "timestamp"}, inplace=True)
        df_train = df_train.sort_values(["user_id", "timestamp"])
    if not "timestamp" in df_train.columns:
        df_train = df_train.sort_values(["user_id"])

    df_train[["user_id", "item_id"]].to_numpy()

    env, env_task_class, kwargs_um = get_true_env(args)
    buffer = construct_buffer_from_offline_data(args, df_train, env)
    env.max_turn = args.max_turn

    test_envs = DummyVectorEnv(
        [lambda: env_task_class(**kwargs_um) for _ in range(args.test_num)])
    test_envs_NX_0 = DummyVectorEnv(
        [lambda: env_task_class(**kwargs_um) for _ in range(args.test_num)])
    test_envs_NX_x = DummyVectorEnv(
        [lambda: env_task_class(**kwargs_um) for _ in range(args.test_num)])

    test_envs_dict = {"FB": test_envs, "NX_0": test_envs_NX_0, f"NX_{args.force_length}": test_envs_NX_x}

    args.device = torch.device("cuda:{}".format(args.cuda) if torch.cuda.is_available() else "cpu")
    # seed
    np.random.seed(args.seed)
    random.seed(args.seed)

    return env, buffer, test_envs_dict

def setup_offline_state_tracker(args, env, buffer, test_envs_dict):
    ensemble_models = prepare_user_model_and_env(args)
    saved_embedding = ensemble_models.load_val_user_item_embedding(freeze_emb=args.freeze_emb)
    if args.which_tracker.lower() == "avg":
        user_columns, action_columns, feedback_columns, have_user_embedding, have_action_embedding, have_feedback_embedding = \
            get_dataset_columns(saved_embedding["feat_user"].weight.shape[1],
                                saved_embedding["feat_item"].weight.shape[1],
                                env.mat.shape[0], env.mat.shape[1], envname=args.env)
    else:
        user_columns, action_columns, feedback_columns, have_user_embedding, have_action_embedding, have_feedback_embedding = \
            get_dataset_columns(args.embedding_dim, args.embedding_dim, env.mat.shape[0], env.mat.shape[1],
                                envname=args.env)

    args.action_shape = action_columns[0].vocabulary_size
    args.state_dim = action_columns[0].embedding_dim

    if args.use_userEmbedding:
        args.state_dim = action_columns[0].embedding_dim + saved_embedding.feat_user.weight.shape[1]

    train_max = buffer.rew.max()
    train_min = buffer.rew.min()
    test_max = test_envs_dict['FB'].get_env_attr("mat")[0].max()
    test_min = test_envs_dict['FB'].get_env_attr("mat")[0].min()

    if args.which_tracker.lower() == "caser":
        state_tracker = StateTracker_Caser(user_columns, action_columns, feedback_columns, args.state_dim,
                                           device=args.device,
                                           window_size=args.window_size,
                                           filter_sizes=args.filter_sizes, num_filters=args.num_filters,
                                           dropout_rate=args.dropout_rate).to(args.device)
        args.state_dim = state_tracker.final_dim
    elif args.which_tracker.lower() == "gru":
        state_tracker = StateTracker_GRU(user_columns, action_columns, feedback_columns, args.state_dim,
                                         device=args.device,
                                         window_size=args.window_size).to(args.device)
        args.state_dim = state_tracker.final_dim
    elif args.which_tracker.lower() == "sasrec":
        state_tracker = StateTracker_SASRec(user_columns, action_columns, feedback_columns, args.state_dim,
                                            device=args.device, window_size=args.window_size,
                                            dropout_rate=args.dropout_rate, num_heads=args.num_heads).to(args.device)
        args.state_dim = state_tracker.final_dim
    elif args.which_tracker.lower() == "avg":
        state_tracker = StateTrackerAvg2(user_columns, action_columns, feedback_columns, args.state_dim,
                                         saved_embedding,
                                         train_max, train_min, test_max, test_min, reward_handle=args.reward_handle,
                                         device=args.device, window_size=args.window_size,
                                         use_userEmbedding=args.use_userEmbedding).to(args.device)
        if args.reward_handle == "cat" or args.reward_handle == "cat2":
            args.state_dim += 1
    else:
        return None

    return state_tracker

def prepare_user_model_and_env(args):
    args.device = torch.device("cuda:{}".format(args.cuda) if torch.cuda.is_available() else "cpu")
    np.random.seed(args.seed)
    random.seed(args.seed)

    UM_SAVE_PATH = os.path.join(".", "saved_models", args.env, args.user_model_name)
    # MODEL_MAT_PATH = os.path.join(UM_SAVE_PATH, "mats", f"[{args.read_message}]_mat.pickle")
    MODEL_PARAMS_PATH = os.path.join(UM_SAVE_PATH, "params", f"[{args.read_message}]_params.pickle")

    with open(MODEL_PARAMS_PATH, "rb") as file:
        model_params = pickle.load(file)

    n_models = model_params["n_models"]
    model_params.pop('n_models')

    ensemble_models = EnsembleModel(n_models, args.read_message, UM_SAVE_PATH, **model_params)
    ensemble_models.load_all_models()

    # user_model = ensemble_models.user_models[0]
    # if hasattr(user_model, 'ab_embedding_dict') and args.is_ab:
    #     alpha_u = user_model.ab_embedding_dict["alpha_u"].weight.detach().cpu().numpy()
    #     beta_i = user_model.ab_embedding_dict["beta_i"].weight.detach().cpu().numpy()
    # else:
    #     print("Note there are no available alpha and beta！！")
    # alpha_u = None
    # beta_i = None
    # return ensemble_models, alpha_u, beta_i
    return ensemble_models


#!/usr/bin/env python3

import re
import shutil

import requests
from bs4 import BeautifulSoup

base_url = "https://downloads.openwrt.org/"

def get_rel(url, version):
    res = requests.get(url)
    if not res.status_code == 200:
        return
    c = res.content
    soup = BeautifulSoup(c, "lxml")
    links = soup.find_all("a")
    for l in links:
        filename = l.string.strip()
        if not re.search('combined-ext4.img.gz', filename):
            #print("ignoring {}".format(filename))
            continue
        if re.search('[^0-9][0-9]{2}\.[0-9]{2}[^0-9]', filename):
            local_filename = filename
        else:
            local_filename = re.sub('^openwrt-', 'openwrt-{}-'.format(version), filename)
        file_url = "{}{}".format(url, filename)
        print("Downloading {} -> {}".format(file_url, local_filename))
        r = requests.get(file_url, stream=True)
        with open(local_filename, 'wb') as f:
            shutil.copyfileobj(r.raw, f)

def main():
    res = requests.get("https://downloads.openwrt.org/")
    if not res.status_code == 200:
        return
    c = res.content
    soup = BeautifulSoup(c, "lxml")
    links = soup.find_all("a")
    for l in links:
        rel_url = "{}{}x86/kvm_guest/".format(base_url, l.attrs['href'])
        m = re.search('[^0-9]([0-9]{2}\.[0-9]{2})[^0-9]', l.attrs['href'])
        if not m:
            continue
        print(l.string.strip(), l.attrs['href'], rel_url)
        get_rel(rel_url, m.group(1))

main()


import discord
import pyttsx3
import time
from discord.ext import commands

bot = commands.Bot(command_prefix="-TTS ")
engine = pyttsx3.init()
female_voice = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-US_ZIRA_11.0"
male_voice = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-US_DAVID_11.0"
user_preferences = {}

def save_user_preference(user, preference):
	with open("user_preferences.txt", "a") as file:
		file.write('\n' + str(user) + '/' + preference)

def get_user_preference():
	with open("user_preferences.txt") as file:
		for line in file:
			line = line.rstrip('\n')
			user, preference = line.split('/')
			user_preferences[user] = preference
			print(str(user) + "/" + preference)

@bot.event
async def on_ready():
	get_user_preference()
	print("TTS Bot is ready!")

@bot.command(name="ping")
async def ping_pong(context):
	await context.message.channel.send("pong!")

@bot.command(name="join")
async def join_user_vc(context):
	voice_channel_to_join = context.author.voice.channel
	await voice_channel_to_join.connect()
	await context.message.channel.send("Joined!")

@bot.command(name="leave")
async def leave_user_vc(context):
	await context.voice_client.disconnect()

@bot.command(name="say")
async def say_phrase(context, *words):
	if len(words) > 30:
		context.message.channel.send("Too many words!")
	if str(context.author.id) in user_preferences.keys():
		if user_preferences[str(context.author.id)] == "female":
			engine.setProperty('voice', female_voice)
		else:
			engine.setProperty('voice', male_voice)
	engine.save_to_file("{}".format(" ".join(words)), "voice.mp3")
	engine.runAndWait()
	guild = context.guild
	voice_client: discord.VoiceClient = discord.utils.get(bot.voice_clients, guild=guild)
	audio_source = discord.FFmpegPCMAudio(executable="C:/ffmpeg-4.3.1-2020-11-19-full_build/bin/ffmpeg.exe", source='voice.mp3')
	if not voice_client.is_playing():
		voice_client.play(audio_source, after=None)

@bot.command(name="volume")
async def set_volume(context, volume):
	if float(volume) < 0.0 or float(volume) > 1.0:
		await context.message.channel.send("Volume range is 0.0 to 1.0")
		return
	engine.setProperty("volume", float(volume))

@bot.command(name="set_voice")
async def set_voice(context, gender):
	if gender.lower() == "male":
		user_preferences[context.author.id] = "male"
		save_user_preference(context.author.id, "male")
		await context.message.channel.send("Set your voice preference to male.")
	if gender.lower() == "female":
		user_preferences[context.author.id] = "female"
		save_user_preference(context.author.id, "female")
		await context.message.channel.send("Set your voice preference to female.")

@bot.command(name="check_preference")
async def check_preference(context):
	if str(context.author.id) in user_preferences.keys():
		await context.message.channel.send("Your preference is: " + user_preferences[str(context.author.id)])
	else:
		await context.message.channel.send("No preference set.")
@bot.command(name="debug_info")
async def debug(context):
	await context.message.channel.send(user_preferences.keys())
	await context.message.channel.send(user_preferences.values())
bot.run("")