from __future__ import division
from __future__ import absolute_import
from __future__ import print_function

from pgportfolio.marketdata.coinlist import CoinList
import numpy as np
import pandas as pd
from pgportfolio.tools.data import panel_fillna
from pgportfolio.constants import *
import sqlite3
from datetime import datetime
import logging

from pandas_datareader import data as pdr
from datetime import date
from ta import add_all_ta_features
from ta.utils import dropna

class StockHistoryManager:
    # if offline ,the coin_list could be None
    # NOTE: return of the sqlite results is a list of tuples, each tuple is a row
    def __init__(self, coin_number, end, stocks, volume_average_days=1, volume_forward=0, online=True):
        self.__storage_period = FIVE_MINUTES  # keep this as 300
        self._coin_number = coin_number
        self.__volume_forward = volume_forward
        self.__volume_average_days = volume_average_days
        self.__coins = stocks

    def coins(self):
        return self.__coins

    def get_global_data_matrix(self, start, end, features=('close',)):
        """
        :return a numpy ndarray whose axis is [feature, coin, time]
        """
        return self.get_global_dataframe(start, end, features).values

    # returns the securities and tech ind into a multiIndex dataframe
    def get_global_dataframe(self, start, end, features, stocks):
        #Sample start and end
        df_list = []                # list of all dataframes for stocks

        # features = [feature.capitalize() for feature in features]

        def getData(ticker):
            startdt = datetime.fromtimestamp(start)         # convert timestamp to date and time
            enddt = datetime.fromtimestamp(end)
            print("getting stock data from: " + ticker)
            data = pdr.DataReader(ticker,start=startdt, end=enddt, data_source='yahoo')     # get the security data from yfinance
            df = pd.DataFrame(data, columns = ['Close','High','Low','Open','Volume'])       # construct dataframe with security data
            df = add_all_ta_features(df, open="Open", high="High", low="Low", close="Close", volume="Volume", fillna='bfill')  # add all tech ind, with back fill for NaN values
            df.fillna(method='ffill', inplace=True)         # forward fill NaN if necessary
            df.columns = df.columns.str.lower()             # lowercase columns for proper input
            df = df[features]                               # crop the dataframe to include only features the user wants
            df_list.append(df)                  # puts dataframe into the list

        for tik in stocks:          # calls each security to be added to the dataframe
            df = getData(tik)

        df = pd.concat(df_list, axis=1, join='outer')           # concatenate the list of dataframes into one Multi Index dataframe
        df.fillna(method='bfill', inplace=True)
        df.fillna(method='ffill', inplace=True)

        df.index.name = None            # remove the name index
        index = pd.MultiIndex.from_product([df.index])
        columns = pd.MultiIndex.from_product([stocks, features])

        # contains the final dataframe in proper format for the neural netwoek
        panel = pd.DataFrame(df.values, index=index, columns=columns, dtype="float64")
        print(panel)
        return panel

    # select top coin_number of coins by volume from start to end
    def select_coins(self, start, end):
        pass


#! /usr/bin/env python3
"""
plot the time vs miRNA ratio box plot
"""

import os, sys, re
import json
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

fn = '/data/cqs/chenh19/findadapt/findadapt_bench/2023_realdata/findadapt_res.time_mem_summary.txt'

def get_miRNA_ratio(lb):
    pw = '/data/cqs/chenh19/findadapt/findadapt_bench/2023_realdata/findadapt_res'
    fn_log = f'{pw}/{lb}.log'
    # total matched reads for inferring = 601, n_processed = 90000, matched reads density = 149.8

    with open(fn_log) as f:
        ratio = None
        for i in f:
            p = r'.*total matched reads for inferring = (\d+), n_processed = (\d+)'
            m = re.match(p, i)
            if m:
                matched, total_parsed = m.groups()
                total_parsed = int(total_parsed)
                matched = int(matched)
                ratio = matched / total_parsed

    if ratio is None:
        print(f'invalid miRNA ratio value found: {fn_log}')

    return ratio

fn = '/data/cqs/chenh19/findadapt/findadapt_bench/fq_size_vs_memory/findadapt_res.time_mem_summary.txt'

with open(fn) as f:
    header = f.readline().strip().split('\t')
    idx_fq = header.index('fq')
    idx_time = header.index('wall_time')
    idx_lb = header.index('lb')

    ratio_l = []
    ratio_d = {}
    time_l = []
    for i in f:
        line = i.strip().split('\t')
        time = line[idx_time]
        time = float(time)
        fq = line[idx_fq]

        lb = line[idx_lb]
        ratio_value = get_miRNA_ratio(lb)

        if not ratio_value:
            continue

        # so it is right open, (right border value is not included in the class)
        if ratio_value < 0.005:
            ratio_class = '0-0.5%'
        elif ratio_value < 0.01:
            ratio_class = '0.5-1%'
        elif ratio_value < 0.05:
            ratio_class = '1-5%'
        elif ratio_value < 0.1:
            ratio_class = '5-10%'
        elif ratio_value >= 0.1:
            ratio_class = '>10%'

        ratio_d[lb] = ratio_value
        ratio_l.append(ratio_class)
        time_l.append(time)

    with open(f'findadapt_fq_files_miRNA_ratio.json', 'w') as f:
        json.dump(ratio_d, f)

# Wall Time
order = ['0-0.5%', '0.5-1%', '1-5%', '5-10%', '>10%']
flierprops = dict(marker='o', markersize=1, linestyle='none')
fig = plt.figure(figsize=(4.5, 3),dpi=300)
a = sns.boxplot(x=ratio_l,  y=time_l, linewidth=0.4, flierprops=flierprops, order=order)
a.set_xlabel('')
a.set_ylabel('Time (s)', fontsize=12)
a.set_yscale('log')
a.set_yticks([0.1, 0.5, 1, 5, 10, 50, 100])
a.get_yaxis().set_major_formatter(ticker.ScalarFormatter())

plt.xticks(fontsize=7, rotation=30, ha='right')
plt.yticks(fontsize=10)
fig.savefig(f"findadapt_time_vs_realdata_miRNA_ratio.png", bbox_inches='tight')


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

import numpy as np, math, operator
import time

def fwa(W, bitwidth):
    max_val = 2**(bitwidth-1) - 1
    alpha = np.abs(W).max(axis=1) / max_val
    alpha_old = alpha*1.1
    while(np.linalg.norm(alpha-alpha_old)>1e-9):
        q = W / alpha[:, np.newaxis]
        q = np.round(q)
        q = np.clip(q, -max_val, max_val)
        alpha_old = alpha
        alpha = np.sum(W*q, axis=1) / np.sum(q*q, axis=1)
    return q, alpha

def split(Q, bitwidth):
    Q_sign = np.sign(Q)
    Q_abs = np.abs(Q)
    B_sav = []
    for idx in range(bitwidth-1):
        B = (Q_abs - Q_abs.astype(np.int)//2*2)
        B *= Q_sign
        B_sav.append(B)
        Q_abs = (Q_abs.astype(np.int)//2).astype(np.float32)

    # B_sum = get_int_B(B_sav[::-1])
    # assert((B_sum*4-Q).sum()==0)

    return B_sav[::-1]

# optimal fixed-point weight approximation
def ofwa(W, bitwidth, max_epoch=50):
    assert(bitwidth >= 3)
    Q, alpha = fwa(W, bitwidth)
    B_sav = split(Q, bitwidth)
    alpha *= (2**(bitwidth-2))

    ### iterative optimization
    [m, n] = W.shape
    for _ in range(max_epoch):
        print(_)
        alpha_old = np.copy(alpha)
        B_sum = get_int_B(B_sav)
        # given Ws, optimize alpha
        alpha = np.sum(W*B_sum, axis=1) / np.sum(B_sum*B_sum, axis=1)

        if np.linalg.norm(alpha_old-alpha) <= 1e-9:
            break
        # given alpha, optimize Ws
        for bit in range(bitwidth-1):
            W_res = W - get_int_B_exclusive(B_sav, bit) * alpha[:, np.newaxis]
            B = get_ot_given_a(W_res*(2**bit), alpha)
            B_sav[bit] = B

    B_sum = get_int_B(B_sav)

    return B_sav, B_sum, alpha

def ofwa_rr(X, Y, B_sav, alpha, bitwidth, max_epoch=100):

    '''
    # X: K,C,d,d
    # Y: K,M
    # B: M,N    M kernels

    objective:
    min(Y-XWA)^2
    '''
    # X: K,N   (N=C*d*d)
    X = X.reshape(X.shape[0], -1)
    K, N = X.shape

    A = np.dot(X.T, X) # N,N

    for epoch in range(max_epoch):
        # given Bi, optimize alpha
        B_sum = get_int_B(B_sav)
        XB = np.dot(X, B_sum.T) # k,m
        alpha = np.einsum("ij,ij->j", Y, XB)
        alpha = alpha / np.einsum("ij,ij->j", XB, XB)

        # given alpha, optimize Bi
        for bit in range(bitwidth-1):
            B = B_sav[bit]
            B_others = get_int_B_exclusive(B_sav, bit) * alpha[:, np.newaxis]
            Y_res = Y - np.dot(X, B_others.T)

            T = np.dot(Y_res.T, X) # M,N
            ## fix alpha, optimize B
            # parallel degree: M
            for n in range(N):
                B[:, n] = 0
                ABn = np.dot(A[n], B.T)
                lump = 2 * (ABn * (alpha/(2**bit))- T[:, n]) # M
                B[:, n] = -np.sign(lump)
                B[np.abs(lump) < (alpha/(2**bit)) * A[n,n], n] = 0

    B_sum = get_int_B(B_sav)

    return B_sum, alpha

def get_int_B(B_sav):
    B_sum = B_sav[0].copy()
    for idx in range(1, len(B_sav)):
        B_sum += B_sav[idx] / (2**idx)
    return B_sum

def get_int_B_exclusive(B_sav, bit):
    mask = [1.0]*len(B_sav)
    mask[bit] = 0
    B_sum = B_sav[0] * mask[0]
    for idx in range(1, len(B_sav)):
        B_sum += B_sav[idx] * mask[idx] / (2**idx)
    return B_sum

def get_ot_given_a(W, alpha):
    [m, n] = W.shape
    B=W.copy()
    B=(B>=0).astype(np.float32)*2-1
    abs_W2 = np.abs(W) * 2
    B[abs_W2<alpha[:, np.newaxis]] = 0

    return B


#!/usr/bin/env python

# Requires PyQt5 and compiltion of GUI files via pyuic
from setuptools import setup, Extension
from setuptools.command.build_py import build_py

try:
    from pyqt_distutils.build_ui import build_ui
except ImportError:
    print("Please install pyqt_distutils")
    print( "(sudo) pip(3) install pyqt-distutils")
    exit()

class custom_build_py(build_py):
    def run(self):
        self.run_command('build_ui')
        build_py.run(self)

with open("README.md", "r") as fh:
    long_description = fh.read()

setup(name='Akvo',
      version='1.7.3',
      python_requires='>3.7.0', # due to pyLemma
      description='Surface nuclear magnetic resonance workbench',
      long_description=long_description,
      long_description_content_type='text/markdown',
      author='Trevor P. Irons',
      author_email='Trevor.Irons@lemmasoftware.org',
      url='https://akvo.lemmasoftware.org/',
      #setup_requires=['PyQt5'],
      setup_requires=[
        # Setuptools 18.0 properly handles Cython extensions.
        #'PyQt',
        'pyqt_distutils',
        'PyQt5',
        'setuptools>=18.0',
      ],
#      ext_modules = cythonise("akvo/tressel/*.pyx"),
#      build_requires=['cython'],
      install_requires=[
#         'cython',
#          'rpy2',
          'matplotlib',
          'scipy',
          'padasip',
          'seaborn',
          'numpy',
          'pyqt5',
          'pyyaml',
          'ruamel.yaml',
          'pandas',
          'pyqt-distutils',
          'cmocean',
          'pyLemma >= 0.4.0'
      ],
      packages=['akvo', 'akvo.tressel', 'akvo.gui'],
      license='GPL 4.0',
      entry_points = {
              'console_scripts': [
                  'akvo = akvo.gui.akvoGUI:main',
                  'akvoK0 = akvo.tressel.calcAkvoKernel:main',
                  'akvoQT = akvo.tressel.invertTA:main',
              ],
          },
      #cmdclass = cmdclass,
      # for forced build of pyuic
      cmdclass={
          'build_ui': build_ui,
          'build_py': custom_build_py,
      },
      # Mechanism to include auxiliary files
      # commenting out may be necessary?
      #include_package_data=True,
      package_data={
        'akvo.gui': ['*.png'],
        'akvo.gui': ['*.ui'],
        '': ['*.png'],
      },
      classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: GNU Lesser General Public License v3 or later (LGPLv3+)",
        "Operating System :: OS Independent",
      ],
    )


"""
Extract activations from a model, almost completely and shamelessly copied from
https://github.com/dieuwkehupkes/diagnosing_lms/tree/interventions.
"""

# STD
from argparse import ArgumentParser

# EXT
from diagnnose.config.setup import ConfigSetup
from diagnnose.extractors.base_extractor import Extractor
from diagnnose.models.language_model import LanguageModel
from diagnnose.typedefs.corpus import LabeledCorpus, LabeledSentence
from diagnnose.models.import_model import import_model_from_json
from diagnnose.corpora.import_corpus import convert_to_labeled_corpus

def init_argparser() -> ArgumentParser:
    parser = ArgumentParser()

    # create group to load config from a file
    from_config = parser.add_argument_group('From config file',
                                            'Provide full experiment setup via config file')
    from_config.add_argument('-c', '--config',
                             help='Path to json file containing extraction config.')

    # create group to provide info via commandline arguments
    # Required args are not set to be required here as they can come from --config
    from_cmd = parser.add_argument_group('From commandline',
                                         'Specify experiment setup via commandline arguments')
    from_cmd.add_argument('--model',
                          help='Path to model parameters')
    from_cmd.add_argument('--vocab',
                          help='Path to model vocabulary')
    from_cmd.add_argument('--lm_module',
                          help='Path to folder containing model module')
    from_cmd.add_argument('--corpus_path',
                          help='Path to labeled corpus')
    from_cmd.add_argument('--activation_names',
                          help='Activations to be extracted', nargs='*')
    from_cmd.add_argument('--output_dir',
                          help='Path to folder to which extracted embeddings will be written.')
    from_cmd.add_argument('--device',
                          help='(optional) Torch device name on which model will be run.'
                               'Defaults to cpu.')
    from_cmd.add_argument('--init_lstm_states_path',
                          help='(optional) Location of initial lstm states of the model. '
                               'If no path is provided zero-initialized states will be used at the'
                               'start of each sequence.')
    from_cmd.add_argument('--print_every', type=int,
                          help='(optional) Print extraction progress every n steps.'
                               'Defaults to 20.')
    from_cmd.add_argument('--cutoff', type=int,
                          help='(optional) Stop extraction after n sentences. '
                               'Defaults to -1 to extract entire corpus.')

    return parser

def subj_selection_func(pos: int, token: str, sentence: LabeledSentence):
    """ Select activations only when they occur on the subject's position. """
    return pos == sentence.misc_info["subj_pos"]

def pos_4_selection_func(pos: int, token: str, sentence: LabeledSentence):
    """ Select activations only on position 4. """
    return pos == 4

if __name__ == "__main__":
    required_args = {'model', 'vocab', 'lm_module', 'corpus_path', 'activation_names', 'output_dir'}
    arg_groups = {
        'model': {'model', 'vocab', 'lm_module', 'device'},
        'corpus': {'corpus_path'},
        'init_extract': {'activation_names', 'output_dir', 'init_lstm_states_path'},
        'extract': {'cutoff', 'print_every'},
    }
    argparser = init_argparser()

    config_object = ConfigSetup(argparser, required_args, arg_groups)
    config_dict = config_object.config_dict

    model: LanguageModel = import_model_from_json(**config_dict['model'])
    corpus: LabeledCorpus = convert_to_labeled_corpus(**config_dict['corpus'])

    extractor = Extractor(model, corpus, **config_dict['init_extract'])
    extractor.extract(**config_dict['extract'], selection_func=pos_4_selection_func)

    # In case you want to extract average eos activations as well, uncomment this line
    # extractor.extract_average_eos_activations(print_every=config_dict['extract']['print_every'])


"""
Module to call all API endpoints
Author: Moises Gonzalez
Date: 02/Jul/2023
"""
import requests
import json
import logging
from pathlib import Path

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

URL = "http://127.0.0.1:8000"

with open('config.json', 'r') as f:
    config = json.load(f)

test_data_path = Path(config['test_data_path'])
output_model_path = Path(config['output_model_path'])
test_data_file = test_data_path / "testdata.csv"

def call_api_endpoint(url: str = URL):
    """
    function to call the API endpoints

    Args:
        url: url to call the endpoints to
    """

    logger.info("Calling all functions")
    response1 = requests.get(url + f"/prediction?data={str(test_data_file)}")
    response2 = requests.get(url + "/scoring")
    response3 = requests.get(url + "/summarystats")
    response4 = requests.get(url + "/diagnostics")

    responses = f"\npredictions status_code-> {response1.status_code}\n" \
                f"{response1.content.decode('utf-8')}\n" \
                f"\nscoring status_code-> {response2.status_code}\n" \
                f"{response2.content.decode('utf-8')}\n" \
                f"\nsummarystats status_code-> {response3.status_code}\n" \
                f"{response3.content.decode('utf-8')}\n" \
                f"\ndiagnostics status_code-> {response4.status_code}\n" \
                f"{response4.content.decode('utf-8')}"

    api_returns = output_model_path / "apireturns.txt"
    with open(api_returns, "w") as txt:
        txt.write(responses)
    logger.info(f"API responses saved to -> {api_returns}")

if __name__ == "__main__":
    call_api_endpoint()


import random

class RockPaperScissors:
    def __init__(self):
        self.user_name_list, self.user_score_list = [], []
        self.user_score = 0
        self.user_name = input("Enter your name: ")
        print("Hello,", self.user_name)
        self.options_list = input()
        self.default_win_conditions = {"rock": "scissors", "paper": "rock", "scissors": "paper"}
        self.winning_cases = {
            'dragon': ['snake', 'scissors', 'fire', 'rock', 'gun', 'lightning', 'devil'],
            'water': ['scissors', 'fire', 'rock', 'gun', 'lightning', 'devil', 'dragon'],
            'air': ['fire', 'rock', 'gun', 'lightning', 'devil', 'dragon', 'water'],
            'paper': ['rock', 'gun', 'lightning', 'devil', 'dragon', 'water', 'air'],
            'sponge': ['gun', 'lightning', 'devil', 'dragon', 'water', 'air', 'paper'],
            'wolf': ['lightning', 'devil', 'dragon', 'water', 'air', 'paper', 'sponge'],
            'tree': ['devil', 'dragon', 'water', 'air', 'paper', 'sponge', 'wolf'],
            'human': ['dragon', 'water', 'air', 'paper', 'sponge', 'wolf', 'tree'],
            'snake': ['water', 'air', 'paper', 'sponge', 'wolf', 'tree', 'human'],
            'scissors': ['air', 'paper', 'sponge', 'wolf', 'tree', 'human', 'snake'],
            'fire': ['paper', 'sponge', 'wolf', 'tree', 'human', 'snake', 'scissors'],
            'rock': ['sponge', 'wolf', 'tree', 'human', 'snake', 'scissors', 'fire'],
            'gun': ['wolf', 'tree', 'human', 'snake', 'scissors', 'fire', 'rock'],
            'lightning': ['tree', 'human', 'snake', 'scissors', 'fire', 'rock', 'gun'],
            'devil': ['human', 'snake', 'scissors', 'fire', 'rock', 'gun', 'lightning']
        }

    def readfile(self):
        with open("rating.txt", "r") as file:
            for i in file:
                data = i.split(" ")
                self.user_name_list.append(data[0])
                self.user_score_list.append(data[1])

        self.user_score = int(self.user_score_list[self.user_name_list.index(self.user_name)])

    def basic(self):
        self.readfile()

        while True:
            option = input()
            comp_selected = random.choice(["rock", "paper", "scissors"])
            if option == "!exit":
                exit("Bye!")
            elif option == "!rating":
                print(f'Your rating: {self.user_score}')
            elif option in self.default_win_conditions:
                if option == comp_selected:
                    print(option)
                    self.user_score += 50
                    print(f'There is a draw ({option})')
                elif self.default_win_conditions[option] == comp_selected:
                    # print(self.default_win_conditions[option])
                    self.user_score += 100
                    print(f'Well done. The computer chose {comp_selected} and failed')
                else:
                    # print(self.default_win_conditions[option])
                    print(f'Sorry, but the computer chose {comp_selected}')
            else:
                print('Invalid input')

    def advanced(self):
        self.readfile()

        while True:
            option = input()
            comp_selected = random.choice(["rock", "paper", "scissors", "water", "dragon", "devil",
                                           "lightning", "gun", "fire", "snake", "human", "tree", "wolf", "sponge",
                                           "air"])
            if option == "!exit":
                exit("Bye!")
            elif option == "!rating":
                print(f'Your rating: {self.user_score}')
            elif option in self.winning_cases:
                if option == comp_selected:
                    # print(option)
                    self.user_score += 50
                    print(f'There is a draw ({option})')
                elif comp_selected in self.winning_cases[option]:
                    # print(self.winning_cases[option])
                    self.user_score += 100
                    print(f'Well done. The computer chose {comp_selected} and failed')
                else:
                    # print(self.winning_cases[option])
                    print(f'Sorry, but the computer chose {comp_selected}')
            else:
                print('Invalid input')

    def make_decision(self):
        if self.options_list is not '':
            print("Okay, let's start")
            self.advanced()
        else:
            print("Okay, let's start")
            self.basic()

if __name__ == "__main__":
    RockPaperScissors().make_decision()


########## BOOLEANS ##########
# Two possible values: True or False (note capitilisation - must be written as such)
isAlive = True

# Comparisons
# >, <, >=, <= all return a boolean
# == equal to (comparing to see if both the same), != not equal to
# 4.0 == 4 will show true (int and float is the same)

# False, 0.0, 0, None, empty strings/data structures = falsy, everything else is truthy!
bool(0)  # False
bool('Hello')  # True, even string '0' is truthy

# The 'in' operator
# Looks to see if an item is a member of a sequence (works for strings, not for int)
'a' in 'bat'  # True
'A' in 'abbA'  # True
4 in [4, 5, 99]  # True
43 in [4, 5, 99]  # False

# Python uses Unicode for encoding characters used in the string data type
# The function ord() will return the number for any character
ord('a')  # 97
ord('A')  # 65


'''La empresa XXXXXX S.A. tiene la siguiente tabla
de parametros para pagar las comisiones de sus empleados
o ejecutivos de venta:
1. Entre 2000000 - 10000000 el 7%
2. Entre 10000000 - 20000000 el 10%
3. Mayor 20000000 el 20%
'''
nombre = (input('Ingrese nombre vendedor '))
comision = int(input('Ingrese total ventas '))
if comision >= 2000000 and comision < 10000000:
    extra = comision*0.07
    print(float('{:.2f}'.format(extra)))
elif comision > 10000000 and comision < 20000000:
    extra = comision*0.10
    print(float('{:.2f}'.format(extra)))
elif comision >= 20000000:
    extra = comision*0.20
    print(float('{:.2f}'.format(extra)))
else:
    print('No tiene comision')


from .serializers import *
import logging
from rest_framework import generics, status
from rest_framework.response import Response
from rest_framework_simplejwt.tokens import RefreshToken

logger = logging.getLogger(__name__)

def get_tokens_for_user(user):
    refresh = RefreshToken.for_user(user)

    return {
        'refresh': str(refresh),
        'access': str(refresh.access_token),
    }

class RegisterUserAPIView(generics.CreateAPIView):
    serializer_class = RegisterUserSerializer

    def post(self, request, *args, **kwargs):
        try:
            serializer = RegisterUserSerializer(data=request.data)
            if serializer.is_valid():
                self.perform_create(serializer)
                return_data = serializer.data
                return_data['token'] = get_tokens_for_user(serializer.instance)
                response = Response(return_data, status=status.HTTP_201_CREATED)
                return response
            return Response({"message": serializer.errors}, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            logger.error(e.__cause__)
            logger.error(e)
            return Response({"message": e.__cause__}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class UserLoginAPIView(generics.GenericAPIView):
    serializer_class = UserLoginSerializer

    def post(self, request, *args, **kwargs):
        try:
            serializer = UserLoginSerializer(data=request.data)
            if serializer.is_valid():
                ret_data = UserSerializers(serializer.instance, many=False).data
                ret_data['token'] = get_tokens_for_user(serializer.instance)
                resp = Response(ret_data, status=status.HTTP_200_OK)
                return resp
            return Response({"message": serializer.errors}, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            logger.error(e.__cause__)
            logger.error(e)
            return Response({"message": e.__cause__}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


from config import *
import pygame
from bullet import Bullet

class Player(pygame.sprite.Sprite):
    def __init__(self, x, y, file_paths: list, lives,speed_x, sound_bullet, jumping_path, dead_path, character_type) -> None:
        pygame.sprite.Sprite.__init__(self)
        self.frame_index = 0

        #loading running animation propperly
        self.file_paths = []
        for i in file_paths:
            image = pygame.image.load(i).convert_alpha()
            image = pygame.transform.scale(image, PLAYER_SIZE)
            self.file_paths.append(image)

        self.image = self.file_paths[self.frame_index]
        self.x = x
        self.y = y
        self.lives = lives
        self.rect = self.image.get_rect()
        self.rect.center = (x, y)

        self.speed_x = speed_x
        self.speed_y = 0

        self.sound_bullet = pygame.mixer.Sound(sound_bullet)
        self.run = True
        self.cooldown_animation = 80
        self.current_time_animations = pygame.time.get_ticks()

        self.jumping = False
        self.jumping_img = pygame.image.load(jumping_path).convert_alpha()
        self.jumping_img = pygame.transform.scale(self.jumping_img, PLAYER_SIZE)
        self.character_type = character_type

        self.death_img = pygame.image.load(dead_path).convert_alpha()
        self.death_img = pygame.transform.scale(self.death_img, PLAYER_SIZE)

        self.action = 0
        self.dead = False

    def update(self):
        self.update_animations()
        if self.character_type == "enemy":
            if self.lives == 0:
                self.kill()
            self.rect.x -= self.speed_x * ENEMY_SPEED
        self.rect.y += self.speed_y

        if self.rect.bottom >= SCREEN_HEIGHT - FLOOR:   #compruba si la nave no sobrepase el limite izquierdo. Si sobrepasa se ejecuta la siguiente linea de codigo.
            self.rect.bottom = SCREEN_HEIGHT - FLOOR  #Establece la posición izquierda de la nave en 0, evitando que se desplace más hacia la izquierda y se salga de la pantalla.
        elif self.rect.top <= ROOF:  #compruba si la nave no sobrepase el limite derecho. Si sobrepasa se ejecuta la siguiente linea de codigo.
            self.rect.top = ROOF

        if self.character_type == "player":

            self.rect.x += self.speed_x
            if self.rect.x  == 180:
                self.speed_x = 0

    def shoot(self, sprites, bullets):
        bullet = Bullet(BULLET_PATH, BULLET_SIZE, (self.rect.midright[0], self.rect.midright[1] +5),BULLET_COLLITION, BULLET_SPEED)   #genero la instancia laser
        pygame.mixer.Sound.play(self.sound_bullet)
        sprites.add(bullet)
        bullets.add(bullet)

    def update_animations(self):
        if self.jumping == True:
            self.image = self.jumping_img
        else:
            self.jumping = False
            self.image = self.file_paths[self.frame_index]
        if pygame.time.get_ticks() - self.current_time_animations > self.cooldown_animation:
            self.current_time_animations = pygame.time.get_ticks()
            self.frame_index += 1
        if self.frame_index == len(self.file_paths):
            self.frame_index = 0

        if self.dead == True:
            self.image = self.death_img


"""
Throw-away script to analyze flappy state logs.
"""

from itertools import ifilter
import pickle
from pylab import *
import sys

from flappy import State

def analyze_gravity(state_log):
  dec_sequences = [[]]
  inc_sequences = [[]]
  for i in xrange(1, len(state_log)):
    crt, last = state_log[i], state_log[i - 1]
    if not crt or not last:
      if inc_sequences[-1]:
        inc_sequences.append([])
      if dec_sequences[-1]:
        dec_sequences.append([])
      continue
    if crt.bird_y < last.bird_y:
      if not dec_sequences[-1]:
        dec_sequences[-1].append(last)
      dec_sequences[-1].append(crt)
      if inc_sequences[-1]:
        inc_sequences.append([])
    elif crt.bird_y > last.bird_y:
      if not inc_sequences[-1]:
        inc_sequences[-1].append(last)
      inc_sequences[-1].append(crt)
      if dec_sequences[-1]:
        dec_sequences.append([])
  def format_seq(seq):
    x, y = [], []
    for s in seq:
      x.append(s.timestamp - seq[0].timestamp)
      y.append(-s.bird_y + seq[0].bird_y)
    plot(x, y)
  def format_sseq(sseq):
    sseq = [s for s in sseq if len(s) > 3]
    for seq in sseq:
      format_seq(seq)
  def plot_gravity_est():
    xs = [x * 0.05 for x in range(20)]
    ys = []
    for x in xs:
      ys.append(-640.0 * (x**2))
    plot(xs, ys, linestyle='dashed')
  subplot(1, 3, 1)
  format_sseq(inc_sequences)
  xlabel('time')
  ylabel('bird y')
  title('descent')
  plot_gravity_est()
  subplot(1, 3, 2)
  title('climb')
  xlabel('time')
  ylabel('bird y')
  format_sseq(dec_sequences)

def analyze_pipes(state_log):
  sequences = [[]]
  for i in xrange(1, len(state_log)):
    crt, last = state_log[i], state_log[i - 1]
    if not crt or not last:
      if sequences[-1]:
        sequences.append([])
      continue
    step = crt.pipe_x + crt.pipe_width - last.pipe_x - last.pipe_width
    if step > 100 or step >= 0:
      if sequences[-1]:
        sequences.append([])
      continue
    sequences[-1].append(crt)
  def format_seq(seq):
    x, y = [], []
    for s in seq:
      x.append(s.timestamp - seq[0].timestamp)
      y.append(s.pipe_x + s.pipe_width - seq[0].pipe_x - seq[0].pipe_width)
    plot(x, y)
  def format_sseq(sseq):
    sseq = [s for s in sseq if len(s) > 3]
    for seq in sseq:
      format_seq(seq)
  subplot(1, 3, 3)
  format_sseq(sequences)
  xlabel('time')
  ylabel('pipe x')
  title('distance to pipe')

def main(argv):
  log = pickle.loads(open(argv[1], "r").read())
  concat_log = []
  for ts, s in log:
    concat_log += s
  analyze_gravity(concat_log)
  analyze_pipes(concat_log)
  show()

if __name__ == '__main__':
  main(sys.argv)


import numpy as np
import sys
import scipy.spatial.distance as dist

import pyparticles.forces.force as fr

class VanDerWaals( fr.Force ) :
    def __init__(self , size , dim=3 , m=None , Consts=1.0 ):

        self.__dim = dim
        self.__size = size

        self.__C = Consts # Hamaker coefficient (A)

        self.__A = np.zeros( ( size , dim ) )
        self.__F = np.zeros( ( size , dim ) )
        self.__Fm = np.zeros( ( size , size ) )

        self.__R = np.zeros( ( size , 1 ) )
        if m != None :
            self.set_messes( m )

    def set_masses( self , m ):
        self.__R[:] = m

    def update_force( self , p_set ):

        self.__D[:] = dist.squareform( dist.pdist( p_set.X , 'euclidean' ) )

        return self.__A

    def getA(self):
        return self.__A

    A = property( getA )

    def getF(self):
        return self.__F

    F = property( getF )


import os
import time
import logging
import os.path as osp

import torch.distributed as dist

def setup_logger(logpth):
    logfile = 'Deeplab_v3plus-{}.log'.format(time.strftime('%Y-%m-%d-%H-%M-%S'))
    logfile = osp.join(logpth, logfile)
    FORMAT = '%(levelname)s %(filename)s(%(lineno)d): %(message)s'
    log_level = logging.INFO
    if dist.is_initialized() and dist.get_rank()!=0:
        log_level = logging.WARNING
    logging.basicConfig(level=log_level, format=FORMAT, filename=logfile)
    logging.root.addHandler(logging.StreamHandler())

class Logger(object):
    def __init__(self, args, logger_str):
        self._logger_name = args.save_path
        # if os.path
        self._logger_str = logger_str
        self._save_path = os.path.join(
            self._logger_name, self._logger_str+'.txt')
        # self._save_path = os.path.abspath(_save_path)
        self._file = open(self._save_path, 'w')

    def log(self, string, save=True):
        print(string)
        if save:
            self._file.write('{:}\n'.format(string))
            self._file.flush()

    def close(self):
        self._file.close()


'''
Mini-Project1 - COMP 551 - Winter 2019
Mahyar Bayran
Luis Pinto
Rebecca Salganik
'''

import json # we need to use the JSON package to load the data, since the data is stored in JSON format
import numpy as np
import matplotlib.pyplot as pt
from proj1_task1 import splitData
from proj1_task2 import closed_form
import time

with open("proj1_data.json") as fp:
    data = json.load(fp)

def bias(x):
	one = np.ones(len(x))
	newx = np.column_stack((x,one))
	return newx

def error_print(y_train,y_val,):
	error_training = np.square(np.subtract(y_train,y_training)).mean()
	error_validation = np.square(np.subtract(y_val, y_validation)).mean()
	print('The mean-squared error on the training set is:', error_training)
	print('The mean-squared error on the validation set is:', error_validation)

#for Task 3.2
[x1_t,x2_t,x3_t,y_training] = splitData(data,0,10000,'Task3.2')
x1training = bias(x1_t)
x2training = bias(x2_t)
x3training = bias(x3_t)

[x1_v, x2_v, x3_v, y_validation] = splitData(data,10000,11000,'Task3.2')
x1validation = bias(x1_v)
x2validation = bias(x2_v)
x3validation = bias(x3_v)

def task32(xt,xv,y):
	w = closed_form(xt,y)
	y_predicted_train = np.matmul(xt,w)
	y_predicted_val = np.matmul(xv,w)
	error_print(y_predicted_train,y_predicted_val)

print('Task 3.2: Linear regression using closed-form approach')
start = time.time()
print('Errors for set with no text features:')
task32(x1training,x1validation,y_training)
end = time.time()
print('Time elapsed using no text features: ', end-start)
start = time.time()
print('Errors for set with top 60 words:')
task32(x2training,x2validation,y_training)
end = time.time()
print('Time elapsed using top 60 words: ', end-start)
start = time.time()
print('Errors for set with top 160 words:')
task32(x3training,x3validation,y_training)
end = time.time()
print('Time elapsed using top 160 words: ', end-start)


import numpy as np
from scipy.optimize import root_scalar
from scipy.optimize import fsolve

class sieplasma(object):
    def __init__(self, theta_E_g, eta, zl, c, Dl, Ds, Dls, psi0_plasma_num, theta_0_num, B, C, delta_rs, deltab_10, deltab_20):

        self.theta_E_g = theta_E_g
        self.eta = eta
        self.psi0_plasma_num = psi0_plasma_num
        self.theta_0_num = theta_0_num
        self.B = B
        self.C = C
        self.delta_rs = delta_rs
        self.deltab_10 = deltab_10
        self.deltab_20 = deltab_20

        def f(r):
            tmp_f = r - theta_E_g + C/r * (r/B/theta_0_num)**C * psi0_plasma_num * np.exp(-(r/B/theta_0_num)**C)
            return tmp_f

        zero = root_scalar(f, bracket=[theta_E_g*.1, theta_E_g*1.9], method='bisect')
        self.theta_E = zero.root
        self.r = zero.root
        r = self.r

        def g(phi_k):
            tmp_g =  theta_E_g*eta*np.sin(2.*phi_k)/np.sqrt(1.-eta*np.cos(2.*phi_k)) - deltab_10*np.sin(phi_k) + deltab_20*np.cos(phi_k)
            return tmp_g

        phi_arr = np.array([np.pi/4, 5/4*np.pi])
        zeros_g = fsolve(g, phi_arr)
        self.zeros_phi = zeros_g
        zeros_phi = self.zeros_phi

        tmp_psi = theta_E_g*r*np.sqrt(1.-eta*np.cos(2.*zeros_phi)) + \
                  psi0_plasma_num*np.exp(-(r/B/theta_0_num)**C)
        self.psi = tmp_psi

        tmp_dpsi = theta_E_g*r*(np.sqrt( 1. - eta*np.cos(2*zeros_phi)) - 1)
        self.dpsi = tmp_dpsi

        tmp_psi0 = theta_E_g*r + psi0_plasma_num*np.exp(-(r/B/theta_0_num)**C)
        self.psi0 = tmp_psi0

        tmp_psi_plasma = psi0_plasma_num*np.exp(-(r/B/theta_0_num)**C)
        self.psi_plasma = tmp_psi_plasma

        tmp_ddpsi_dr = theta_E_g*(np.sqrt( 1. - eta*np.cos(2*zeros_phi)) - 1)
        self.ddpsi_dr = tmp_ddpsi_dr

        tmp_ddpsi_dphi = theta_E_g*r*eta*np.sin(2.*zeros_phi)/np.sqrt(1.-eta*np.cos(2.*zeros_phi))
        self.ddpsi_dphi = tmp_ddpsi_dphi

        tmp_d2dpsi_dphi2 = theta_E_g*r*eta*( 2*np.cos(2.*zeros_phi)/np.sqrt(1.-eta*np.cos(2.*zeros_phi)) - (1.-eta*np.cos(2.*zeros_phi))**(-3/2)*eta*np.sin(2*zeros_phi)**2)
        self.d2dpsi_dphi2 = tmp_d2dpsi_dphi2

        tmp_d2psi0 = self.psi_plasma * ( - C*(C-1)/r**2*(r/B/theta_0_num)**C + (C/r*(r/B/theta_0_num)**C)**2 )
        self.d2psi0_dr2 = tmp_d2psi0

        delta_r = 1/(1 - self.d2psi0_dr2 )*(self.ddpsi_dr + deltab_10*np.cos(zeros_phi) + deltab_20*np.sin(zeros_phi) )

        self.delta_r = delta_r

        r_ = r + delta_r

        psi = theta_E_g*r_*np.sqrt(1.-eta*np.cos(2.*zeros_phi)) + psi0_plasma_num*np.exp(-(r_/B/theta_0_num)**C)
        psi_plasma = psi0_plasma_num*np.exp(-(r_/B/theta_0_num)**C)
        d2psi_dr2 = psi_plasma * ( - C*(C-1)/r_**2*(r_/B/theta_0_num)**C + (C/r_*(r_/B/theta_0_num)**C)**2 )
        dpsi_dr = theta_E_g*np.sqrt(1.-eta*np.cos(2.*zeros_phi)) - C/r_*(r_/B/theta_0_num)**C*psi0_plasma_num*np.exp(-(r_/B/theta_0_num)**C)
        d2psi_dphi2 = theta_E_g*r_*eta*( 2*np.cos(2.*zeros_phi)/np.sqrt(1.-eta*np.cos(2.*zeros_phi)) - (1.-eta*np.cos(2.*zeros_phi))**(-3/2)*eta*np.sin(2*zeros_phi)**2)
        dpsi_dphi = theta_E_g*r_*eta*np.sin(2.*zeros_phi)/np.sqrt(1.-eta*np.cos(2.*zeros_phi))
        d2psi_dphidr = theta_E_g*eta*np.sin(2.*zeros_phi)/np.sqrt(1.-eta*np.cos(2.*zeros_phi))

        mu = r_*( (1 - d2psi_dr2)*(r_ - dpsi_dr - 1/r_*d2psi_dphi2) - 1/r_*(1/r_*dpsi_dphi - d2psi_dphidr )**2  )**(-1)

        R = np.abs(mu[0]/mu[1])
        self.R = R

        t = (1 + zl)/c*Dl*Ds/Dls*(1/2* ( (r_*np.cos(zeros_phi) - deltab_10)**2 + (r_*np.sin(zeros_phi) - deltab_20)**2  ) - psi )

        self.t = t/24/60/60*0.000004848136811095**2

        dt = np.abs(t[0]-t[1])/24/60/60*0.000004848136811095**2 #convert seconds to days and arcsec^2 to rad
        self.dt = dt


def solution(number, k):
    stack = [number[0]]
    for n in number[1:]:
        while k > 0 and stack and stack[-1] < n:
            stack.pop()
            k -= 1
        stack.append(n)
    if k > 0:
        stack = stack[:-k]
    return ''.join(stack)


from django.contrib import admin
from django.urls import path, include
from Crud import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('company/', include('company.urls')),
    path('department/', include('department.urls')),
    path('employee/',include('employee.urls')),
    path('project/',include('project.urls')),
    path('', views.index),
]


import numpy as np
import argparse
import cv2

ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required = True, help = "Image pathname")
args = vars(ap.parse_args())

image = cv2.imread(args["image"])
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

eq = cv2.equalizeHist(image)

cv2.imshow("Histogram Equalisation", np.hstack([image, eq]))
cv2.waitKey(0)


"""pytest configuration."""
import pathlib
from typing import Generator, Optional, Tuple

import pytest
from sqlalchemy.orm import Session

from remote_command_server.database import Base, database_connection

@pytest.fixture()
def db() -> Generator[Session, None, None]:
    """
    Fixture for creating a fresh test database in memory.

    All tables are created, but they have no entries.
    """

    db: Optional[Session] = None
    try:
        db_connection = database_connection("sqlite:///:memory:")
        Base.metadata.create_all(bind=db_connection.engine)
        db = db_connection.LocalSession()
        yield db
    finally:
        if db:
            db.close()

@pytest.fixture()
def file_based_db(
    tmp_path: pathlib.Path,
) -> Generator[Tuple[Session, pathlib.Path], None, None]:
    """
    Fixture for creating a fresh test database in a temporary file.

    All tables are created, but they have entries.
    """

    db: Optional[Session] = None
    try:
        db_file = tmp_path.absolute() / "test.sqlite3"
        db_connection = database_connection(f"sqlite:///{db_file}")
        Base.metadata.create_all(bind=db_connection.engine)
        db = db_connection.LocalSession()
        yield db, db_file
    finally:
        if db:
            db.close()


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/3/28 8:39 下午
# @Author  : 宋继贤
# @Description  :
# @File    : utils.py
# @Software: PyCharm

import torch
import gensim

def build_optimizer(args, model):
    optimizer = getattr(torch.optim, args.optim)(
        model.parameters(),
        lr=args.lr,
        weight_decay=args.weight_decay,
        amsgrad=args.amsgrad
    )
    return optimizer

def set_lr(optimizer, lr):
    for group in optimizer.param_groups:
        group['lr'] = lr

def load_embedding(w2v_file, vocab_size=859, embedding_size=256):
    w2v = gensim.models.Word2Vec.load(w2v_file).wv
    embedding = torch.zeros((vocab_size, embedding_size), dtype=torch.float32)
    for i in range(1, vocab_size):
        embedding[i] = torch.from_numpy(w2v[str(i - 1)].copy())
    return embedding


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/12/24 13:57
# @Author  : Tian Hao
# @Email   : hao.tian@intcolon.cn
# @File    : tools.py
# @Software: PyCharm
# @Desc    : 时间处理

import calendar
import datetime

from BaiduIndex.tools.DBHelper import DBHelper

def get_time_range_list(start_date, end_date):
    """
    根据开始时间和结束时间按月份获取每月第一天和最后一天
    :param start_date: 起始时间 --> str
    :param end_date: 结束时间 --> str
    :return: date_range_list -->list
    """
    date_range_list = []
    start_date = datetime.datetime.strptime(start_date, '%Y-%m-%d')
    end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d')
    while 1:
        next_month = start_date + datetime.timedelta(days=calendar.monthrange(start_date.year, start_date.month)[1])
        month_end = next_month - datetime.timedelta(days=1)
        if month_end < end_date:
            date_range_list.append((datetime.datetime.strftime(start_date,
                                                               '%Y-%m-%d'),
                                    datetime.datetime.strftime(month_end,
                                                               '%Y-%m-%d')))
            start_date = next_month
        else:
            return date_range_list

class QueryData(object):
    def __init__(self):
        self.db_helper = DBHelper()

    def get_region_id(self):
        # 查询省份ID
        query_sql = "SELECT id FROM province_id ORDER BY id"
        return self.db_helper.query_task(query_sql)

    def get_keyword(self, table_name):
        keywords_list = []
        sql = 'SELECT distinct(keyword) FROM {}'.format(table_name)
        keywords = self.db_helper.query_task(sql)
        for keyword in keywords:
            keywords_list.append(str.lower(str(keyword[0])).strip())
        return keywords_list[2400:]

if __name__ == '__main__':
    startDate = "2020-03-01"
    endDate = "2020-09-01"
    print(get_time_range_list(startDate, endDate))


# coding=utf-8
# borrowed from FilamentManager
# master commit hash: bd1a9c0 on 1 Dec 2017
from __future__ import absolute_import

__author__ = "Sven Lohrmann <malnvenshorn@gmail.com> based on work by Gina Häußge <osd@foosel.net>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2017 Sven Lohrmann - Released under terms of the AGPLv3 License"

import re

########## DEPRECATED use newodometer

class FilamentOdometer(object):
	regexE = re.compile(r'.*E(-?\d+(\.\d+)?)')
	regexT = re.compile(r'^T(\d+)')

	class ToolExtrusion:
		lastExtrusion = 0.0
		totalExtrusion = 0.0
		maxExtrusion = 0.0
		myValue = 0.0

	def __init__(self):
		self.g90_extruder = True
		self.reset()

	def reset(self):
		self.relativeMode = False
		self.relativeExtrusion = False
		self.currentToolName = "Tool0"
		self.allToolExtrusions = {self.currentToolName : self.ToolExtrusion()} # Tool0 must always be there, default extruder
		# self.lastExtrusion = [0.0]
		# self.totalExtrusion = [0.0]
		# self.maxExtrusion = [0.0]

	def reset_extruded_length(self):
		# tools = len(self.maxExtrusion)
		# self.maxExtrusion = [0.0] * tools
		# self.totalExtrusion = [0.0] * tools
		for toolName in self.allToolExtrusions:
			self.allToolExtrusions[toolName].totalExtrusion = 0.0
			self.allToolExtrusions[toolName].maxExtrusion = 0.0
			self.allToolExtrusions[toolName].myValue = 0.0

	def parse(self, gcode, cmd):
		if gcode is None:
			return

		if gcode == "G1" or gcode == "G0":  # move
			e = self._get_float(cmd, self.regexE)
			if e is not None:
				if (e > 0.0):
					self._getCurrentToolExtrusion().myValue += e

				if self.relativeMode or self.relativeExtrusion:
					# e is already relative, nothing to do
					pass
				else:
					# e -= self.lastExtrusion[self.currentTool]
					e -= self._getCurrentToolExtrusion().lastExtrusion
				# self.totalExtrusion[self.currentTool] += e
				# self.lastExtrusion[self.currentTool] += e
				# self.maxExtrusion[self.currentTool] = max(self.maxExtrusion[self.currentTool],
				# 										  self.totalExtrusion[self.currentTool])
				self._getCurrentToolExtrusion().totalExtrusion += e
				self._getCurrentToolExtrusion().lastExtrusion += e
				self._getCurrentToolExtrusion().maxExtrusion = max(self._getCurrentToolExtrusion().maxExtrusion,
																   self._getCurrentToolExtrusion().totalExtrusion)

		elif gcode == "G90":  # set to absolute positioning
			self.relativeMode = False
			if self.g90_extruder:
				self.relativeExtrusion = False
		elif gcode == "G91":  # set to relative positioning
			self.relativeMode = True
			if self.g90_extruder:
				self.relativeExtrusion = True
		elif gcode == "G92":  # set position
			e = self._get_float(cmd, self.regexE)
			if e is not None:
				# self.lastExtrusion[self.currentTool] = e
				self._getCurrentToolExtrusion().lastExtrusion = e
		elif gcode == "M82":  # set extruder to absolute mode
			self.relativeExtrusion = False
		elif gcode == "M83":  # set extruder to relative mode
			self.relativeExtrusion = True
		elif gcode.startswith("T"):  # select tool
			toolIndex = self._get_int(cmd, self.regexT)
			if toolIndex is not None:
				self.currentToolName = "Tool" + str(toolIndex)
				if ( (self.currentToolName in self.allToolExtrusions) == False):
					self.allToolExtrusions[self.currentToolName] = self.ToolExtrusion()
					# if len(self.lastExtrusion) <= self.currentTool:
					# 	for i in xrange(len(self.lastExtrusion), self.currentTool + 1):
					# 		self.lastExtrusion.append(0.0)
					# 		self.totalExtrusion.append(0.0)
					# 		self.maxExtrusion.append(0.0)

	def set_g90_extruder(self, flag=True):
		self.g90_extruder = flag

	def get_extrusion(self, toolName):
		# return self.maxExtrusion
		return self.allToolExtrusions[toolName].maxExtrusion

	def getExtrusionForAllTools(self):
		result = 0.0
		for toolName in self.allToolExtrusions:
			result += self.allToolExtrusions[toolName].maxExtrusion
		return result

	def get_current_tool(self):
		return self.currentToolName

	def _getCurrentToolExtrusion(self):
		return self.allToolExtrusions[self.currentToolName]

	def _get_int(self, cmd, regex):
		result = regex.match(cmd)
		if result is not None:
			return int(result.group(1))
		else:
			return None

	def _get_float(self, cmd, regex):
		result = regex.match(cmd)
		if result is not None:
			return float(result.group(1))
		else:
			return None


from pygame import mixer   # for audio playing
from tkinter import *      # for gui
import os
from mutagen.mp3 import MP3    # extracting metadata from file
import tkinter.messagebox      # for messages showing error for example
from tkinter import filedialog
from tkinter import ttk
from ttkthemes import themed_tk as tk
import time
import threading

# create a window for the mp3 player
root = tk.ThemedTk()
root.get_themes()
root.set_theme("keramik")

status_bar = ttk.Label(root, text="Welcome to Acoustic!", relief=SUNKEN, anchor=W, font='Arial 10 bold')
status_bar.pack(side=BOTTOM, fill=X)

# Create the menu bar
menu_bar = Menu(root)
subMenu = Menu(menu_bar, tearoff=0)
root.config(menu=menu_bar)
root.title("Acoustic")                           # change the title displayed on top of the window
root.iconbitmap(r'images/acoustic_logo.ico')     # change the logo

mixer.init()                                     # initiate the mixer module

# Root Window contains the status bar, left frame and right frame
# Left frame contains the list box
# Right frame contains the top, middle and bottom frames

left_frame = ttk.Frame(root)
left_frame.pack(side=LEFT, padx=30)

right_frame = ttk.Frame(root)
right_frame.pack()

top_frame = ttk.Frame(right_frame)
top_frame.pack()

length_label = ttk.Label(top_frame, text='Total Length: --:--', font='Arial 10 bold')
length_label.pack(pady=10)

current_duration_label = ttk.Label(top_frame, text='Current Duration: --:--', font='Arial 10 bold')
current_duration_label.pack()

# Playlist contains the full path + filename
# Playlist box contains just the filename
# Full path + filename is required to play music inside play_music function
playlist = []

# function to choose file from directory and adding functionality to the 'open' cascade
def browse_file():
    global song_path
    song_path = filedialog.askopenfilename()
    add_to_playlist(song_path)

def add_to_playlist(song_name):
    song_name = os.path.basename(song_name)
    index = 0
    playlist_box.insert(index, song_name)
    playlist.insert(index, song_path)
    index += 1

def about_us():
    tkinter.messagebox.showinfo('About Acoustic', 'This is a music player build using tkinter on Python')

def show_details(play_song):
    file_data = os.path.splitext(play_song)

    if file_data[1] == '.mp3':
        audio = MP3(play_song)
        total_length = audio.info.length
    else:
        a = mixer.Sound(play_song)
        total_length = a.get_length()

    # div - total_length/60, mod - total_length%60
    mins, secs = divmod(total_length, 60)
    mins = round(mins)
    secs = round(secs)
    # proper format to display the length
    time_format = '{:02d}:{:02d}'.format(mins, secs)
    length_label['text'] = "Total Length: " + ' - ' + time_format

    # Threading is necessary because the while loop in start_count will stop the other parts of the program until it is finished
    t1 = threading.Thread(target=start_count, args=(total_length,))
    t1.start()

def start_count(t):
    global paused
    # mixer.music.get_busy() stops the duration count when we press the stop button
    # continue - ignores all of the statements below it and we check if the music is paused or not
    current_time = 0
    while current_time <= t and mixer.music.get_busy():
        if paused:
            continue
        else:
            mins, secs = divmod(current_time, 60)
            mins = round(mins)
            secs = round(secs)
            time_format = '{:02d}:{:02d}'.format(mins, secs)
            current_duration_label['text'] = "Current Duration: " + ' - ' + time_format
            time.sleep(1)
            current_time += 1

def play_music(event):
    global paused
    if paused:
        mixer.music.unpause()
        status_bar['text'] = "Music resumed."
        paused = FALSE
    else:
        try:
            # when switching the song in the playlist we need to stop the song that is already playing because
            # if it is not stopped another thread will be started and the duration label will not display
            # the time correctly
            stop_music()
            time.sleep(1)
            selected_song = playlist_box.curselection()
            selected_song = int(selected_song[0])
            play_song = playlist[selected_song]
            mixer.music.load(play_song)
            mixer.music.play()
            status_bar['text'] = "Playing music " + ' ' + os.path.basename(play_song)
            show_details(play_song)
        except:
            tkinter.messagebox.showerror("File not found", "Acoustic could not find the file, please check again.")

def stop_music():
    mixer.music.stop()
    status_bar['text'] = "Music stopped."

paused = FALSE

# function that pauses the music
def pause_music(event):
    global paused
    paused = TRUE
    mixer.music.pause()
    status_bar['text'] = "Music paused."

def rewind_music(event):
    play_music(event)
    status_bar['text'] = "Music rewound."

muted = FALSE

# function for the mute and unmute functionality
def mute_music(event):
    global muted
    if muted:  # Unmute the music
        mixer.music.set_volume(0.5)
        volume_btn.configure(image=volume_photo)
        scale_vol.set(50)
        muted = FALSE
    else:  # Mute the music
        mixer.music.set_volume(0)
        volume_btn.configure(image=mute_photo)
        scale_vol.set(0)
        muted = TRUE

# set_volume function of mixer takes value only from 0 to 1 exp: 0.1, 0.25
def set_vol(val):
    volume = float(val) / 100
    mixer.music.set_volume(volume)

def del_song():
    selected_song = playlist_box.curselection()
    selected_song = int(selected_song[0])
    playlist_box.delete(selected_song)
    playlist.pop(selected_song)

# center frame for play,stop,pause buttons and status bar
center_frame = ttk.Frame(right_frame)
center_frame.pack(pady=30, padx=30)

# Create the sub-menu
menu_bar.add_cascade(label="File", menu=subMenu)
subMenu.add_command(label="Open", command=browse_file)
subMenu.add_command(label="Exit", command=root.destroy)

subMenu = Menu(menu_bar, tearoff=0)
menu_bar.add_cascade(label="Help", menu=subMenu)
subMenu.add_command(label="About us", command=about_us)

playlist_box = Listbox(left_frame)
playlist_box.pack()

add_photo = PhotoImage(file='images/add_button.png')
add_btn = ttk.Button(left_frame, image=add_photo, command=browse_file)
add_btn.pack(side=LEFT)

del_photo = PhotoImage(file='images/remove_button.png')
del_btn = ttk.Button(left_frame, image=del_photo, command=del_song)
del_btn.pack(side=RIGHT)

play_photo = PhotoImage(file='images/play_button.png')          # specify what is the image to be inserted
play_btn = ttk.Button(center_frame, image=play_photo)               # convert the image into a button
play_btn.bind("<Button-1>", play_music)
play_btn.grid(row=0, column=0, padx=10)

stop_photo = PhotoImage(file='images/stop_button.png')          # specify what is the image to be inserted
stop_btn = ttk.Button(center_frame, image=stop_photo, command=stop_music)               # convert the image into a button
stop_btn.grid(row=0, column=1, padx=10)

pause_photo = PhotoImage(file='images/pause_button.png')
pause_btn = ttk.Button(center_frame, image=pause_photo)
pause_btn.bind("<Button-1>", pause_music)
pause_btn.grid(row=0, column=2, padx=10)

# bottom frame for mute,rewind,scale of volume
bottom_frame = ttk.Frame(right_frame)
bottom_frame.pack()

rewind_photo = PhotoImage(file='images/rewind_button.png')
rewind_btn = ttk.Button(bottom_frame, image=rewind_photo)
rewind_btn.bind("<Button-1>", rewind_music)
rewind_btn.grid(row=0, column=0)

mute_photo = PhotoImage(file='images/mute_btn.png')
volume_photo = PhotoImage(file='images/sound_btn.png')
volume_btn = ttk.Button(bottom_frame, image=volume_photo)
volume_btn.bind("<Button-1>", mute_music)
volume_btn.grid(row=0, column=1, padx=10, pady=10)

# adding a scale for the sound level
scale_vol = ttk.Scale(bottom_frame, from_=0, to=100, orient=HORIZONTAL, command=set_vol)
scale_vol.set(50)   # implement the default value of scale when music player starts
mixer.music.set_volume(0.5)
scale_vol.grid(row=0, column=2, pady=15, padx=30)

def on_close():
    stop_music()
    root.destroy()

# makes sure that when you exit the program while
# it is playing music it doesnt display an error relating the thread function
root.protocol("WM_DELETE_WINDOW", on_close)
root.mainloop()


import random

print("Horse race!")

num_horses = int(input("How many horses will be in the race?"))

# create two empty lists: horse names and horse distances
names = list()
distances = list()

# now populate the lists with the horses and their starting distance
# for example, range(3) will produce (0,1,2), then i will iterate through that
for i in range(num_horses):
    names.append(input("What is the name of horse #"+str(i+1)+"?"))
    distances.append(0)

print("Are you ready to race? Press ENTER to start.")
input()
print("Here we go...")

done = False
winning_horse = 0
while not done:
    input("Press enter for the next lap")

    for i in range(num_horses):
        # you are competing with randomness!
        distances[i] += random.randint(0, 40)
        if distances[i] > distances[winning_horse]:
            winning_horse = i
        # it's a 200 yard race, so the first one past ends the race
        if distances[i] >= 200:
            done = True

    if done:
        break

    for i in range(num_horses):
        print(names[i] + " is at " + str(distances[i]) + " yards",end='')
        if i == winning_horse:
            print(" and is in the lead!")
        else:
            print()
    print()

print(names[winning_horse]+" is the winner!")

input("Press ENTER to exit")


# [프로그래머스]-파이썬-연습문제-(푸드-파이트-대회)-LV1-(1-내풀이-정답).py
# https://github.com/irishNoah/Algorithm-Study
# https://school.programmers.co.kr/learn/courses/30/lessons/134240

'''
*** 제한 > 시간 : ?초 (기본 1초) / 메모리 : ?MB (기본 128MB)

*** 조건
>>> 2 ≤ food의 길이 ≤ 9
>>> 1 ≤ food의 각 원소 ≤ 1,000
>>> food에는 칼로리가 적은 순서대로 음식의 양이 담겨 있습니다.
>>> food[i]는 i번 음식의 수입니다.
>>> food[0]은 수웅이가 준비한 물의 양이며, 항상 1입니다.
>>> 정답의 길이가 3 이상인 경우만 입력으로 주어집니다.

*** 설계 [총 11분 소요] / 총 풀이 시간[총 14분 소요]
>>> for문 활용해서 food[1]부터 food[끝]까지 answer += str(idx) * (food[idx] // 2) 실행
>>> for문 이후, result에 answer + "0" + answer[::-1] 할당 후 return

'''
#===================================================================================

def solution(food):
    answer = ""

    for idx in range(1, len(food)):
        answer += str(idx) * (food[idx] // 2)

    result = answer + "0" + answer[::-1]
    return result

#===================================================================================

food = [1,7,1,2]
print(solution(food)) # "111303111"

# def solution(food):
#     answer = ""
#
#     return answer

알고리즘/파이썬(Python)/888-기타&연습/009-[프로그래머스]-파이썬-연습문제-(푸드-파이트-대회)-LV1-(1-내풀이-정답).py


import sys
read = sys.stdin.readline

N = int(input())
graph = list(map(int, read().split()))
maxDp = [graph.copy()] + [[0,0,0]]
minDp = [graph.copy()] + [[0,0,0]]
for t in range(1, N):
    i = t % 2
    graph = list(map(int, read().split()))
    maxDp[i][0] = max(maxDp[i-1][:2]) + graph[0]
    maxDp[i][1] = max(maxDp[i-1]) + graph[1]
    maxDp[i][2] = max(maxDp[i-1][1:]) + graph[2]

    minDp[i][0] = min(minDp[i-1][:2]) + graph[0]
    minDp[i][1] = min(minDp[i-1]) + graph[1]
    minDp[i][2] = min(minDp[i-1][1:]) + graph[2]

print(max(maxDp[(N % 2) -1]), min(minDp[(N % 2) -1]))


from flask_wtf import FlaskForm
from wtforms import StringField, TextAreaField, validators

class CategoryForm(FlaskForm):
    # Minimum in name is only one because some languages such as Japanese can easily have
    # one character long words such as ухх as in picture.
    name = StringField(
        "Category",
        [
            validators.Length(min=1, max=64),
            validators.data_required()
        ]
    )

    description = TextAreaField(
        "Description",
        [validators.Length(max=1024)]
    )

    class Meta:
        csrf = False


"""Ne changer les adresses que dans la fonction prog
Le dossier proteines ne doit contenir que les proteines, et il sera vidé à la fin
Le dossier photos doit être vide au début
"""
import os

def photo(photo_folder_path,protein_folder_path):
    photo_list = os.listdir(photo_folder_path)
    protname = get_protname(protein_folder_path)
    #if no protein
    if (protname == 0):
        return 0
    #if first photo
    if(photo_list is None or not(photo_list)):
        cmd.save(photo_folder_path+'/'+protname+'.png')
        return 0
    #if not first photo = photo we really want to keep
    os.remove(protein_folder_path+'/'+protname+'.pdb')
    cmd.save(photo_folder_path+'/'+protname+'.png')

def get_protname(protein_folder_path):
    prot_list = os.listdir(protein_folder_path)
    if(prot_list is not None and not(prot_list)):
        return 0
    else:
        protname_with_ext = prot_list[0]
        protname = '.'.join(protname_with_ext.split('.')[:-1])
        return protname

def selector(protein_folder_path,prog_folder_path,protname):
    cmd.delete('all')
    cmd.load(protein_folder_path+'/'+protname+'.pdb')
    cmd.select('antibody_chains', 'chain L, chain H')
    cmd.save(prog_folder_path+'/'+protname+'.pdb', 'antibody_chains')
    cmd.delete('all')

def apbs(apbs_path,prog_folder_path,protname):
    os.system('cd ' + prog_folder_path)
    os.system('pdb2pqr30 --ff=AMBER --apbs-input result.in '+protname+'.pdb result.pqr')
    os.system(apbs_path+' result.in')

def slicer(prog_folder_path,protname):
    cmd.load('result.pqr.dx')
    cmd.run('slice.pml')

def trash(prog_folder_path,protname):
    os.remove('result.in')
    os.remove('result.log')
    os.remove(prog_folder_path + '/' + protname+'.pdb')
    os.remove('result.pqr')
    os.remove('result.pqr.dx')
    os.remove('io.mc')

def prog():
    prog_folder_path = 'C:/Users/chadm/Desktop/PT/prog'
    protein_folder_path = 'C:/Users/chadm/Desktop/PT/proteins'
    photo_folder_path = 'C:/Users/chadm/Desktop/PT/photos'
    apbs_path = 'C:/Users/chadm/Downloads/APBS-3.0.0_Windows/APBS-3.0.0_Windows/bin/apbs.exe'
    photo(photo_folder_path,protein_folder_path)
    protname = get_protname(protein_folder_path)
    if(protname == 0):
        print('ERROR : The folder is empty')
        return 1
    selector(protein_folder_path,prog_folder_path,protname)
    apbs(apbs_path,prog_folder_path,protname)
    slicer(prog_folder_path,protname)
    trash(prog_folder_path,protname)

cmd.extend('prog', prog)


from twisted.trial.unittest import TestCase
from twisted.python.filepath import FilePath

from epsilon.extime import Time

from nevow import loaders, rend
from nevow.testutil import renderPage, renderLivePage

from axiom.store import Store
from axiom.dependency import installOn

from xmantissa.people import Person, EmailAddress

from xquotient.exmess import Message, MessageDetail, PartDisplayer
from xquotient.inbox import Inbox, InboxScreen
from xquotient import compose
from xquotient.test.util import MIMEReceiverMixin, PartMaker, ThemedFragmentWrapper
from xquotient.qpeople import MessageList, MessageLister

from xquotient.test.util import DummyMessageImplementation
from xquotient.test.test_inbox import testMessageFactory

def makeMessage(receiver, parts, impl):
    """
    Create a new L{exmess.Message}, either by parsing C{parts} or by wrapping
    one around C{impl}.
    """
    if impl is None:
        return receiver.feedStringNow(parts)
    else:
        return testMessageFactory(store=impl.store,
                                  receivedWhen=Time(),
                                  sentWhen=Time(),
                                  spam=False,
                                  subject=u'',
                                  impl=impl)

class RenderingTestCase(TestCase, MIMEReceiverMixin):
    aBunchOfRelatedParts = PartMaker(
        'multipart/related', 'related',
        *(list(PartMaker('text/html', '
html-' + str(i) + '
')
               for i in xrange(100)) +
          list(PartMaker('image/gif', '')
               for i in xrange(100)))).make()

    def setUp(self):
        """
        Make a copy of the very minimal database for a single test method to
        mangle.
        """
        receiver = self.setUpMailStuff()
        makeMessage(receiver, self.aBunchOfRelatedParts, None)

    def test_messageRendering(self):
        """
        Test rendering of message detail for an extremely complex message.
        """
        msg = self.substore.findUnique(Message)
        msg.classifyClean()
        return renderLivePage(
                   ThemedFragmentWrapper(
                       MessageDetail(msg)))

    def test_inboxRendering(self):
        """
        Test rendering of the inbox with a handful of extremely complex
        messages in it.
        """
        def deliverMessages():
            for i in xrange(5):
                makeMessage(
                    self.createMIMEReceiver(), self.aBunchOfRelatedParts, None)
        self.substore.transact(deliverMessages)

        inbox = self.substore.findUnique(Inbox)

        composer = compose.Composer(store=self.substore)
        installOn(composer, self.substore)

        return renderLivePage(
                   ThemedFragmentWrapper(
                       InboxScreen(inbox)))

    def test_inboxComposeFragmentRendering(self):
        """
        Test rendering of the L{xquotient.compose.ComposeFragment} returned
        from L{xquotient.inbox.InboxScreen.getComposer}
        """
        installOn(compose.Composer(store=self.substore), self.substore)

        inbox = self.substore.findUnique(Inbox)
        inboxScreen = InboxScreen(inbox)

        composeFrag = inboxScreen.getComposer()

        return renderLivePage(
            ThemedFragmentWrapper(composeFrag))

    def test_peopleMessageListRendering(self):
        mlister = MessageLister(store=self.substore)
        installOn(mlister, self.substore)

        p = Person(store=self.substore, name=u'Bob')

        EmailAddress(store=self.substore, person=p, address=u'bob@internet')

        for i in xrange(5):
            testMessageFactory(
                store=self.substore, subject=unicode(str(i)),
                receivedWhen=Time(), spam=False, sender=u'bob@internet')

        self.assertEqual(len(list(mlister.mostRecentMessages(p))), 5)
        return renderPage(
            rend.Page(docFactory=loaders.stan(MessageList(mlister, p))))

class MockPart(object):
    """
    A mock L{xquotient.mimestorage.Part} which implements enough functionality
    to satisfy L{xquotient.exmess.PartDisplayer}
    """
    def __init__(self, unicodeBody, contentType='text/plain'):
        """
        @param unicodeBody: the body of the part
        @type unicodeBody: C{unicode}

        @param contentType: the content type of the part.  defaults to
        text/plain
        @type contentType: C{str}
        """
        self.unicodeBody = unicodeBody
        self.contentType = contentType

    def getUnicodeBody(self):
        return self.unicodeBody

    def getBody(self, decode=False):
        return str(self.unicodeBody)

    def getContentType(self):
        return self.contentType

class PartDisplayerTestCase(TestCase):
    """
    Tests for L{xquotient.exmess.PartDisplayer}
    """
    def setUp(self):
        self.partDisplayer = PartDisplayer(None)

    def test_scrubbingInvalidDocument(self):
        """
        Pass a completely malformed document to L{PartDisplayer.scrubbedHTML}
        and assert that it returns C{None} instead of raising an exception.
        """
        self.assertIdentical(None, self.partDisplayer.scrubbedHTML(''))

    def test_scrubbingSimpleDocument(self):
        """
        Pass a trivial document to L{PartDisplayer.scrubbedHMTL} and make sure
        it comes out the other side in-tact.
        """
        self.assertEquals('

', self.partDisplayer.scrubbedHTML('

'))

    def test_renderablePartReplacesInvalidCharsinHTML(self):
        """
        Test that L{xquotient.exmess.PartDisplayer.renderablePart} replaces
        XML-illegal characters in the body of the text/html part it is passed
        """
        part = MockPart(u'
\x00 hi \x01
', 'text/html')
        tag = self.partDisplayer.renderablePart(part)
        self.assertEquals(tag.content, '
0x0 hi 0x1
')

    def test_renderablePartDoesntReplaceInvalidCharsElsewhere(self):
        """
        Test that L{xquotient.exmess.PartDisplayer.renderablePart} doesn't
        replace XML-illegal characters if the content-type of the part isn't
        text/html
        """
        part = MockPart(u'\x00', 'text/plain')
        tag = self.partDisplayer.renderablePart(part)
        self.assertEquals(tag.content, '\x00')


import requests
from bs4 import BeautifulSoup
import smtplib
import email.message

Req = "https://store.playstation.com/pt-br/product/UP0082-PPSA10664_00-FF16SIEA00000002"

#Substituir o "browserA' pelo seu Browser agent > https://www.whatismybrowser.com/detect/what-is-my-user-agent/
headers = {'User-Agent': "browserA"}

store = requests.get(Req, headers=headers)

soup = BeautifulSoup(store.content, 'html.parser')

ff = soup.find('h1', class_ = 'psw-m-b-5').get_text()
valor = soup.find('span', class_= 'psw-l-line-left psw-l-line-wrap').get_text()

nvalor = valor[2:6]
nvalor = nvalor.replace(',','')
nvalor = float(nvalor)

def gomail():
    email_content = """
    Final Fantasy XVI acaba de entrar no valor desejado, aproveite! >>>
    https://store.playstation.com/pt-br/product/UP0082-PPSA10664_00-FF16SIEA00000002
    """
    cont = email.message.Message()
    cont['Subject'] = 'FFXVI BARATINHO!'

    # Substitua o 'email' pelo seu email
    cont['From'] = 'email'

    # Substitua o 'email' pelo seu email
    cont['To'] = 'email'

    # Substitua 'pw' pela senha do seu email
    senha = 'pw'
    cont.add_header('Content-Type', 'text/html')
    cont.set_payload(email_content)

    # Substitua o "outlook.com" pelo dominio do seu email
    envio = smtplib.SMTP('smtp.outlook.com: 587')

    envio.ehlo()
    envio.starttls()
    envio.login(cont['From'], senha)
    envio.sendmail(cont['From'], [cont['To']], cont.as_string())
    envio.quit()

#200 reais é o valor máximo que eu pagaria por esse novo final fantasy, mas você pode substituir o "200" pelo valor que desejar :)
if (nvalor < 200):
    gomail()


import os

a = Analysis(
    ['main.py'],
    datas=[
        ('theme', 'theme'),
        ('i18n.ini', '.'),
        ('icon-256px.ico', '.'),
        ('icon-128px.webp', '.'),
    ],
    hiddenimports=[
        'PIL._tkinter_finder',
    ],
    hookspath=[
        'pyi-hooks',
    ],
    excludes=[
        '_asyncio',
        '_bz2',
        '_decimal',
        '_hashlib',
        '_lzma',
        '_multiprocessing',
        '_overlapped',
        '_queue',
        '_ssl',
        'pyexpat',
        'unicodedata',
    ],
)

a.binaries = [
    x
    for x in a.binaries
    if not any(x[0].startswith(y) for y in(
        'api-ms-win-',
        'ucrtbase.dll',
    ))
]

a.datas = [
    x
    for x in a.datas
    if not any(x[0].startswith(y) for y in(
        os.path.join('tcl', 'encoding'),
        os.path.join('tcl', 'http'),
        os.path.join('tcl', 'msgs'),
        os.path.join('tcl', 'opt'),
        os.path.join('tcl', 'tzdata'),
        os.path.join('tcl8'),
        os.path.join('tk', 'images'),
        os.path.join('tk', 'msgs'),
    ))
]

print('Binaries:')
for i in a.binaries:
    print(i)

print('Datas:')
for i in a.datas:
    print(i)

pyz = PYZ(a.pure, a.zipped_data)

if os.environ.get('REGUI_ONEFILE'):
    exe = EXE(
        pyz,
        a.scripts,
        a.binaries,
        a.zipfiles,
        a.datas,
        [],
        name='realesrgan-gui',
        debug=False,
        bootloader_ignore_signals=False,
        strip=False,
        upx=True,
        console=False,
        disable_windowed_traceback=False,
        argv_emulation=False,
        icon='icon-256px.ico',
    )
else:
    exe = EXE(
        pyz,
        a.scripts,
        [],
        exclude_binaries=True,
        name='realesrgan-gui',
        debug=False,
        bootloader_ignore_signals=False,
        strip=False,
        upx=True,
        console=False,
        disable_windowed_traceback=False,
        argv_emulation=False,
        icon='icon-256px.ico',
    )
    coll = COLLECT(
        exe,
        a.binaries,
        a.zipfiles,
        a.datas,
        name='realesrgan-gui',
        strip=False,
        upx=True,
    )


'''Implement a method to perform basic string compression using
   the counts of repeated characters method.'''

def string_compression(input):

  if len(input) == 0:
    return ""

  counter = 1
  output = ''

  for i in range(1,len(input)):

    if input[i] == input[i-1]:
      counter += 1

    else:
      output += input[i-1] + str(counter)
      counter = 1

  output += input[-1] + str(counter)

  return output

print (string_compression("aaaacbbbtttbbccc"))


#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time    : 2021/8/6 上午10:04
# @Author  : PeiP Liu
# @FileName: BertModel.py
# @Software: PyCharm

import torch
import torch.nn as nn
from torch.nn import LayerNorm as BertLayerNorm
import sys
sys.path.append("..")
import torch.nn.functional as F

class BERT_SC(nn.Module):
    def __init__(self, bert_model, idx2label, hidden_size=768, device='cpu'):
        super(BERT_SC, self).__init__()
        self.bert_model = bert_model
        self.hidden_size = hidden_size
        self.num_label = len(idx2label)
        self.device = device

        self.dropout = nn.Dropout(0.5)
        self.bert_sigmod = nn.Sigmoid()
        self.softmax = nn.Softmax(dim=-1)

        self.hid2label = nn.Linear(self.hidden_size, self.num_label)
        # init the weight and bias of feature-emission layer
        nn.init.xavier_uniform_(self.hid2label.weight)
        nn.init.constant_(self.hid2label.bias, 0.0)
        self.apply(self.init_bert_weight)

    def init_bert_weight(self, module):
        # cf https://github.com/Louis-udm/NER-BERT-CRF/blob/master/NER_BERT_CRF.py
        # rf https://www.cnblogs.com/BlueBlueSea/p/12875517.html
        if isinstance(module, (nn.Linear, nn.Embedding)):
            module.weight.data.normal_(mean=0.0, std=0.02)
        elif isinstance(module, BertLayerNorm):
            module.bias.data.zero_()
            module.weight.data.fill_(1.0)
        if isinstance(module, nn.Linear) and module.bias is not None:
            module.bias.data.zero_()

    def get_bert_features(self, input_ids, seg_ids, atten_mask):
        # rf https://huggingface.co/transformers/model_doc/bert.html#bertmodel
        outputs = self.bert_model(input_ids, token_type_ids=seg_ids,
                                  attention_mask=atten_mask, output_hidden_states=True, output_attentions=True)
        # last_hidden_states = outputs[0]
        last_hidden_states = outputs.last_hidden_state # (batch_size, seq_length, hidden_size)

        # pooler_outputs = outputs[1]
        # the feature of [CLS], and it represents the feature of whole sentence
        # We can better average or pool the sequence of hidden-states for the whole sequence.
        pooler_outputs = outputs.pooler_output  # (batch_size, hidden_size)

        return pooler_outputs, last_hidden_states  # the feature of [CLS] and all the tokens

    def tfidf_seq(self, bert_seq_features, tfidf_token_masks):
        batch_size, seq_len, feature_dim = bert_seq_features.shape
        seq_reps = torch.zeros((batch_size, feature_dim), dtype=torch.float32).to(self.device)
        for i_seq in range(batch_size):
            i_seq_feature = bert_seq_features[i_seq]
            i_seq_mask = tfidf_token_masks[i_seq]

            assert len(i_seq_feature) == len(i_seq_mask)

            extended_i_seq_mask = i_seq_mask.unsqueeze(1)  # (seq_len, 1)

            masked_seq_feature = i_seq_feature * extended_i_seq_mask  # (seq_len, feature_dim)

            i_seq_rep = masked_seq_feature.sum(0)  # 对所有tf-idf的token-embedding进行了sum-pooling

            seq_reps[i_seq] = i_seq_rep

        return seq_reps

    def forward(self, input_ids, input_mask, seg_ids, tfidf_token_masks, sents_labels, mode):
        bert_cls_features, bert_seq_features = self.get_bert_features(input_ids, seg_ids, input_mask)

        if tfidf_token_masks.count_nonzero().detach().item() == 0:  # 非0数据为0，即没有非0数据，即都是0。此时，我们使用CLS来表示序列信息
            seq_rep = self.bert_sigmod(self.dropout(bert_cls_features))
        else:
            seq_rep = self.tfidf_seq(bert_seq_features, tfidf_token_masks)  # 对于有tf-idf选择的词汇，我们使用tf-idf来表示序列特征
            seq_rep = self.bert_sigmod(self.dropout(seq_rep))

        class_result = self.softmax(self.hid2label(seq_rep))

        if mode == 'train':
            try:
                object_score = F.cross_entropy(class_result, sents_labels, ignore_index=2)
                return object_score
            except:
                print('There is something wrong with the prediction result!')
        else:
            return torch.argmax(class_result, dim=-1).detach().cpu().tolist()


import triton
import triton.language as tl

def conv2d_forward_config(
    BLOCK_SIZE_BATCH_HEIGHT_WIDTH: int,
    BLOCK_SIZE_IN_FEAT: int,
    BLOCK_SIZE_OUT_FEAT: int,
    n_warps: int = 4,
    n_stages: int = 2,
    ) -> triton.Config:
    """
    Creates a triton.Config object for conv2d_forward_kernel
    given meta-parameters for auto-tuning.

    Args:
        BLOCK_SIZE_BATCH_HEIGHT_WIDTH: Block size across the batch, height, and
            width dimensions.
        BLOCK_SIZE_IN_FEAT: Block size across the input feature dimension.
        BLOCK_SIZE_OUT_FEAT: Block size across the output feature dimension.
        n_warps: Number of warps to use for the kernel when compiled for GPUs.
        n_stages: Number of stages the compiler uses to software-pipeline.

    Returns:
        Kernel configuration.
    """
    return triton.Config({'BLOCK_SIZE_BATCH_HEIGHT_WIDTH': BLOCK_SIZE_BATCH_HEIGHT_WIDTH,
                          'BLOCK_SIZE_IN_FEAT': BLOCK_SIZE_IN_FEAT,
                          'BLOCK_SIZE_OUT_FEAT': BLOCK_SIZE_OUT_FEAT},
                          num_warps=n_warps, num_stages=n_stages)

@triton.autotune(
    configs=[
        conv2d_forward_config(128, 32, 128, n_warps=8, n_stages=2),
        conv2d_forward_config(256, 32, 64, n_warps=8, n_stages=2),
        conv2d_forward_config(256, 32, 32, n_warps=4, n_stages=4),
        conv2d_forward_config(256, 64, 32, n_warps=4, n_stages=4),
        conv2d_forward_config(256, 32, 16, n_warps=2, n_stages=4),
        conv2d_forward_config(64, 32, 128, n_warps=8, n_stages=4),
        conv2d_forward_config(128, 32, 64, n_warps=4, n_stages=4),
        conv2d_forward_config(64, 32, 64, n_warps=4, n_stages=4),
        conv2d_forward_config(128, 32, 16, n_warps=4, n_stages=4),
        conv2d_forward_config(128, 128, 128, n_warps=8, n_stages=3),
        conv2d_forward_config(256, 128, 64, n_warps=8, n_stages=3),
        conv2d_forward_config(256, 128, 32, n_warps=4, n_stages=4),
        conv2d_forward_config(64, 128, 128, n_warps=4, n_stages=4),
        conv2d_forward_config(128, 128, 64, n_warps=4, n_stages=4),
        conv2d_forward_config(128, 64, 32, n_warps=2, n_stages=4),
        conv2d_forward_config(64, 64, 64, n_warps=2, n_stages=4),
    ],
    key=['batch_dim', 'in_feat_dim', 'in_height', 'in_width',
         'out_feat_dim', 'out_height', 'out_width',
         'kernel_height', 'kernel_width',
         'stride_height', 'stride_width',
         'padding_height', 'padding_width',
         'groups'],
)
@triton.jit
def conv2d_forward_kernel(
    input_pointer, weight_pointer, output_pointer,
    batch_dim, in_feat_dim, in_height, in_width,
    out_feat_dim, out_height, out_width,
    input_batch_stride, input_in_feat_stride, input_height_stride, input_width_stride,
    weight_out_feat_stride, weight_in_feat_stride, weight_height_stride, weight_width_stride,
    output_batch_stride, output_out_feat_stride, output_height_stride, output_width_stride,
    kernel_height: tl.constexpr, kernel_width: tl.constexpr,
    stride_height: tl.constexpr, stride_width: tl.constexpr,
    padding_height: tl.constexpr, padding_width: tl.constexpr,
    groups: tl.constexpr,
    BLOCK_SIZE_BATCH_HEIGHT_WIDTH: tl.constexpr, BLOCK_SIZE_IN_FEAT: tl.constexpr,
    BLOCK_SIZE_OUT_FEAT: tl.constexpr,
    ):
    """
    2D-convolves over the input using weights.

    Args:
        input_pointer: Pointer to the input to convolve over.
            The input must be of shape [batch_dim, in_feat_dim, in_height, in_width].
        weight_pointer: Pointer to the weights input is convolved over by.
            The weights must be of shape [out_feat_dim, in_feat_dim, kernel_height, kernel_width].
        output_pointer: Pointer to a container the result is written to.
            The container must be of shape [batch_dim, out_feat_dim, out_height, out_width].
        batch_dim: Batch dimension of the input and output.
        in_feat_dim: Dimensionality of the input features.
        in_height: Input height.
        in_width: Input width.
        out_feat_dim: Dimensionality of the output features.
        out_height: Output height.
        out_width: Output width.
        input_batch_stride: Stride necessary to jump one element along the
            input's batch dimension.
        input_in_feat_stride: Stride necessary to jump one element along the
            input's feature dimension.
        input_height_stride: Stride necessary to jump one element along the
            input's height dimension.
        input_width_stride: Stride necessary to jump one element along the
            input's width dimension.
        weight_out_feat_stride: Stride necessary to jump one element along the
            weights' output feature dimension.
        weight_in_feat_stride: Stride necessary to jump one element along the
            weights' input feature dimension.
        weight_height_stride: Stride necessary to jump one element along the
            weights' height dimension.
        weight_width_stride: Stride necessary to jump one element along the
            weights' width dimension.
        output_batch_stride: Stride necessary to jump one element along the
            output's batch dimension.
        output_out_feat_stride: Stride necessary to jump one element along the
            output's feature dimension.
        output_height_stride: Stride necessary to jump one element along the
            output's height dimension.
        output_width_stride: Stride necessary to jump one element along the
            output's width dimension.
        kernel_height: Kernel height.
        kernel_width: Kernel width.
        stride_height: Stride of kernel across the height dimension.
        stride_width: Stride of kernel across the width dimension.
        padding_height: Padding applied to the input across the height dimension.
        padding_width: Padding applied to the input across the width dimension.
        groups: Number of groups for the convolution.
        BLOCK_SIZE_BATCH_HEIGHT_WIDTH: Block size across the batch, height, and
            width dimensions.
        BLOCK_SIZE_IN_FEAT: Block size across the input feature dimension.
        BLOCK_SIZE_OUT_FEAT: Block size across the output feature dimension.
    """
    batch_height_width_pid = tl.program_id(0)
    out_feat_pid = tl.program_id(1)
    group_pid = tl.program_id(2)

    in_group_dim = in_feat_dim // groups
    out_group_dim = out_feat_dim // groups

    batch_height_width_offset = (batch_height_width_pid * BLOCK_SIZE_BATCH_HEIGHT_WIDTH +
                                 tl.arange(0, BLOCK_SIZE_BATCH_HEIGHT_WIDTH))
    batch_height_offset = batch_height_width_offset // out_width
    batch_offset = batch_height_offset // out_height

    output_feat_offset = (out_feat_pid * BLOCK_SIZE_OUT_FEAT +
                          tl.arange(0, BLOCK_SIZE_OUT_FEAT))
    output_height_offset = batch_height_offset % out_height
    output_width_offset = batch_height_width_offset % out_width

    input_pointer += (input_batch_stride * batch_offset +
                      input_in_feat_stride * group_pid * in_group_dim)[:, None]
    weight_pointer += (weight_out_feat_stride * output_feat_offset +
                       weight_out_feat_stride * group_pid * out_group_dim)[None, :]

    accum = tl.zeros((BLOCK_SIZE_BATCH_HEIGHT_WIDTH, BLOCK_SIZE_OUT_FEAT),
                     dtype=tl.float32)

    for h in range(kernel_height):
        for w in range(kernel_width):
            for c in range(0, in_group_dim, BLOCK_SIZE_IN_FEAT):
                input_feat_offset = c + tl.arange(0, BLOCK_SIZE_IN_FEAT)
                input_height_offset = (h - padding_height +
                                       stride_height * output_height_offset)
                input_width_offset = (w - padding_width +
                                      stride_width * output_width_offset)

                curr_input_pointer = (input_pointer +
                                     (input_in_feat_stride * input_feat_offset)[None, :] +
                                     (input_height_stride * input_height_offset)[:, None] +
                                     (input_width_stride * input_width_offset)[:, None])
                curr_weight_pointer = (weight_pointer +
                                      (weight_in_feat_stride * input_feat_offset)[:, None] +
                                      (weight_height_stride * h) +
                                      (weight_width_stride * w))

                input_mask = ((batch_offset < batch_dim)[:, None] &
                              (input_feat_offset < in_group_dim)[None, :] &
                              (0 <= input_height_offset)[:, None] &
                              (input_height_offset < in_height)[:, None] &
                              (0 <= input_width_offset)[:, None] &
                              (input_width_offset < in_width)[:, None])
                weight_mask = ((input_feat_offset < in_group_dim)[:, None] &
                               (output_feat_offset < out_group_dim)[None, :])

                input_block = tl.load(curr_input_pointer, mask=input_mask)
                weight_block = tl.load(curr_weight_pointer, mask=weight_mask)

                accum += tl.dot(input_block, weight_block)

    output_pointer += ((output_batch_stride * batch_offset)[:, None] +
                       (output_out_feat_stride * (group_pid * out_group_dim + output_feat_offset))[None, :] +
                       (output_height_stride * output_height_offset)[:, None] +
                       (output_width_stride * output_width_offset)[:, None])
    output_mask = ((batch_offset < batch_dim)[:, None] &
                   (output_feat_offset < out_group_dim)[None, :] &
                   (output_height_offset < out_height)[:, None] &
                   (output_width_offset < out_width)[:, None])

    tl.store(output_pointer, accum, mask=output_mask)


class Solution:
    def deckRevealedIncreasing(self, deck: List[int]) -> List[int]:
        deck.sort()
        deq = collections.deque(range(len(deck)))
        loc = []
        ans = [0] * len(deck)
        while deq:
            loc.append(deq.popleft())
            if deq:
                deq.append(deq.popleft())

        for i in range(len(loc)):
            ans[loc[i]] = deck[i]

        return ans

taewan/week 7/950. Reveal Cards In Increasing Order.py