import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt
import os
import codecs

df = pd.read_csv("docs/links.txt")

# list_actor = []
# for i in df["actor1"]:
#     if i not in list_actor:
#         list_actor.append(i)
# for i in df["actor2"]:
#     if i not in list_actor:
#         list_actor.append(i)
# list_actor.append(0)
# #trier actor en ordre croissant
# list_actor.sort()

top_500_actors = pd.read_csv("top_500/links.txt")
list_500_actors = []
for i in top_500_actors["actor1"]:
    if i not in list_500_actors:
        list_500_actors.append(i)
for i in top_500_actors["actor2"]:
    if i not in list_500_actors:
        list_500_actors.append(i)

# représenter un résaux d'acteur avec un graphe ou les poids sont le number_of_commune_movies entre deux acteurs
def transform_to_graph(df,list_actor):
    """Transform the df dataframe in a graph with the weight between two actor as the number of film in commun"""
    g = nx.Graph()
    for actor in list_actor:
        g.add_node(actor)
    for index, row in df.iterrows():
        if row["number_of_common_movies"] > 0:
            g.add_edge(row["actor1"], row["actor2"], weight = row["number_of_common_movies"])
    return g

# x = transform_to_graph(df,list_actor)
# nx.write_gml(x, "graph/graph.gml")
#
# df1 = pd.read_csv("text_analysis/cosine_similarity_TF_IDF.txt")
#
# y = transform_to_graph(top_500_actors,list_500_actors)
#
# nx.write_gml(y, "graph/top_500_actors.gml")

top_500_tmdb_actor = pd.read_csv("top_500_tmdb/links.txt")
print(top_500_tmdb_actor.head())
list_500_tmdb = []
for i in top_500_tmdb_actor["actor1"]:
    if i not in list_500_tmdb:
        list_500_tmdb.append(i)
for i in top_500_tmdb_actor["actor2"]:
    if i not in list_500_tmdb:
        list_500_tmdb.append(i)
g = transform_to_graph(top_500_tmdb_actor,list_500_tmdb)
nx.write_gml(g, "graph/top_500_tmdb_actors.gml")


import time

def frange(start, stop, step):
    i = start
    while i < stop:
        yield i
        i += step

class OptiFunc(object):
    def __init__(self, func, grad=None, params=None, infunc=None, ingrad=None, name=None):
        self.par = params
        self.func = func
        self.gradient = grad
        self.infunc = infunc
        self.ingrad = ingrad
        self.name = name

    def value(self, x):
        if self.par is None:
            return self.func(x)
        if self.infunc is None:
            return self.func(x, self.par)
        return self.func(x, self.par, self.infunc)

    def grad(self, x):
        if self.gradient is None:
            return 0
        if self.par is None:
            return self.gradient(x)
        if self.ingrad is None:
            return self.gradient(x, self.par)
        return self.gradient(x, self.par, self.ingrad)

def passive_search(ofunc, gradd, beg, end, eps):
    iter = 0
    tmin = beg
    fmin = ofunc.value(tmin)
    range_list = frange(beg, end, eps)
    n = 0
    for t in range_list:
        iter += 1
        cur = ofunc.value(t)
        n += 1
        if cur <= fmin:
            fmin = cur
            tmin = t
        else:
            break
    return [tmin, n, iter]

#  https://en.wikipedia.org/wiki/Bisection_method
def dichotomi_search(ofunc, gradd, beg, end, eps):
    delta = eps / 2
    left, right = beg, end
    n = 0  # function calculate counter
    iter = 0
    while right - left > 2*eps:
        c = (right + left - delta) / 2.0
        d = (right + left + delta) / 2.0
        if ofunc.value(c) < ofunc.value(d):
            right = d
        else:
            left = c
        n += 2
        iter += 1
    tmin = (left + right) / 2.0
    return [tmin, n, iter]

#  https://en.wikipedia.org/wiki/Golden_section_search
def gold_section_method(ofunc, gradd, beg, end, eps):
    if end - beg < 2*eps:
        return (end + beg) / 2.0
    left, right = beg, end
    c = left + (right - left) * (3 - 5**.5) / 2.0
    d = right - (right - left) * (3 - 5**.5) / 2.0
    fc, fd = ofunc.value(c), ofunc.value(d)
    n = 2  # function calculate counter
    iter = 0
    while right - left > 2*eps:
        if fc < fd:
            right = d
            if right - left < 2*eps:
                break
            d, fd = c, fc
            c = left + (right - left) * (3 - 5**(.5)) / 2.0
            fc = ofunc.value(c)
        else:
            left = c
            if right - left < 2*eps:
                break
            c, fc = d, fd
            d = right - (right - left) * (3 - 5**(.5)) / 2.0
            fd = ofunc.value(d)
        n += 1
        iter += 1
    return [(right + left) / 2.0, n, iter]

def fib(n):
    a, b = 0, 1
    for i in range(n):
        temp = b
        b += a
        a = temp
    return b

def fibbonachi_method(ofunc, gradd, beg, end, eps):
    m = 0
    while fib(m + 2) < (end - beg) / eps:
        m += 1
    left, right = beg, end
    c = left + (right - left)*(fib(m)/fib(m + 2))
    d = left + (right - left)*(fib(m + 1)/fib(m + 2))
    fc, fd = ofunc.value(c), ofunc.value(d)
    n = 2 # function calculate counter
    iter = 0
    for i in range(m):
        if fc < fd:
            right = d
            d, fd = c, fc
            c = left + (right - left)*(fib(m - i)/fib(m - i + 2))
            fc = ofunc.value(c)
        else:
            left = c
            c, fc = d, fd
            d = left + (right - left)*(fib(m - i + 1)/fib(m - i + 2))
            fd = ofunc.value(d)
        n += 1
        iter += 1
    return [(right + left) / 2.0, n, iter]

def tangents_search(ofunc, gradd, beg, end, eps):
    count = 0
    if end - beg < 2 * eps:
        return [(end + beg) / 2.0, count]

    left = beg
    right = end
    atemp = ofunc.grad(left)*left - ofunc.value(left)
    btemp = ofunc.value(right) - ofunc.grad(right)*right
    ctemp = ofunc.grad(left) - ofunc.grad(right)
    mid = (atemp + btemp) / ctemp
    iter = 0
    while ofunc.grad(mid) > eps and (right - left) > 2 * eps:
        if ofunc.grad(mid) < 0:
            left = mid
        else:
            right = mid
        a = ofunc.grad(left)*left - ofunc.value(left)
        b = ofunc.value(right) - ofunc.value(right)*right
        c = ofunc.grad(left) - ofunc.grad(right)
        count += 1
        mid = (a + b) / c
        iter += 1
    return [mid, count, iter]

def nuton_raffson(ofunc, gradd, beg, end, eps):
    lastp = beg
    point = lastp - ofunc.grad(lastp) / gradd(lastp)
    count = 1
    iter = 0
    while abs(lastp - point) > 2*eps and abs(ofunc.grad(point)) > eps:
        lastp = point
        point = lastp - ofunc.grad(lastp) / gradd(lastp)
        count += 1
        iter += 1
    return [point, count, iter]

def tangents_method(ofunc, gradd, beg, end, eps):
    count = 1
    lastlastp = beg
    lastp = end
    point = lastp - ofunc.grad(lastp) * (lastlastp - lastp) / (ofunc.grad(lastlastp) - ofunc.grad(lastp))
    iter = 0
    while abs(lastp - point) > 2 * eps and abs(ofunc.grad(point)) > eps:
        lastlastp = lastp
        lastp = point
        point = lastp - ofunc.grad(lastp) * (lastlastp - lastp) / (ofunc.grad(lastlastp) - ofunc.grad(lastp))
        count += 1
        iter += 1
    return [point, count, iter]

# F(X)= 3x^4 - 10x^3 + 21x^2 + 12x
def fun1746(x):
    f = 3*x**4 - 10*x**3 + 21*x**2 + 12*x
    return f

def fun1746_g(x):
    return 12*x**3 - 30*x**2 + 42*x + 12

def fun1746_gg(x):
    return 36*x**2 - 60*x**1 + 42

def sqr_x(x):
    f = x**2
    return f

def sqr_d(x):
    return 2*x

def sqr_dd(x):
    return 2

allmethods = [
    passive_search,
    dichotomi_search,
    gold_section_method,
    fibbonachi_method,
    tangents_search,
    tangents_method,
    nuton_raffson
]

methods_names = {
    'passive_search': 'Метод пассивного поиска',
    'dichotomi_search': 'Метод дихотомии',
    'gold_section_method': 'Метод золотого сечения',
    'fibbonachi_method': 'Метод через последовательность Фиббоначи',
    'tangents_search': 'Метод касательных',
    'tangents_method': 'Метод хорд/секущих',
    'nuton_raffson': 'Метод Ньютона-Раффсона'
}

def run_method(output, method, ofunc, gradd, beg, end, eps):
    print("#### Метод: ", methods_names.get(method.__name__), file=output)
    start = time.time()
    ans = method(ofunc, gradd, beg, end, eps)
    print("__Ответ__:  ", file=output)
    print("`Xmin` =", ans[0], end="  \n", file=file)
    print("`F(Xmin)` = ", ofunc.value(ans[0]), end="  \n", file=file)
    print("__Производительность__:  ", file=output)
    print("`Вызовов функций` =", ans[1], end="  \n", file=file)
    print("`Итерации` =", ans[2], end="  \n", file=output)
    print("`Время` = ", round((time.time() - start)*1000, 3), "(ms)", file=file)
    print("\n\n", file=file)

def run_all_methods(output, ofunc, gradd, beg, end, eps):
    print("## ", ofunc.name, "  \n#####Отрезок [", beg, ",", end, "]", "`\u03B5`=", eps, end="  \n\n---  \n\n", file=file)
    for each in allmethods:
        run_method(output, each, ofunc, gradd, beg, end, eps)

if __name__ == '__main__':
    file = open('onedmethods.md','w', encoding='utf-8')
    ofunc = OptiFunc(fun1746, fun1746_g, name='Номер 17.46')
    run_all_methods(file, ofunc, fun1746_gg, 0, 0.5, 0.01)
    run_all_methods(file, ofunc, fun1746_gg, -2, 4, 0.01)
    ofunc = OptiFunc(sqr_x, sqr_d, name='F(x)= x*x')
    run_all_methods(file, ofunc, sqr_dd, -5, 5, 0.01)


from pyspark.sql import SparkSession
from pyspark.sql.functions import stddev, year
import matplotlib.pyplot as plt
import pandas as pd

spark = SparkSession.builder.appName("DistrictVariabilityByYear").getOrCreate()

file_path = "gs://stone-ground-400412/output.csv"
df = spark.read.csv(file_path, header=True)

df = df.withColumn("price", df["price"].cast("double"))

selected_districts = ["GREATER LONDON", "TYNE AND WEAR", "WEST MIDLANDS", "MERSEYSIDE", "GREATER MANCHESTER", "SHROPSHIRE"]
df_selected_districts = df.filter(df["County"].isin(selected_districts))
df_selected_districts.show()

district_year_variability = df_selected_districts.groupBy("County", "Property_Type").agg(stddev("price").alias("Variability"))

district_year_variability = district_year_variability.orderBy("County", "Property_Type")

district_year_variability.show(truncate=False)

pandas_df = district_year_variability.toPandas()

plt.figure(figsize=(12, 6))
for district in selected_districts:
    df_district = pandas_df[pandas_df["County"] == district]
    plt.plot(df_district["Property_Type"], df_district["Variability"], label=district)

plt.xlabel('Tipo de propiedad')
plt.ylabel('Desviación estándar según la variabilidad')
plt.title('Variacón del mercado de los condados según el tipo de propiedad')
plt.xticks(rotation=45, ha='right')
plt.legend()
plt.tight_layout()
plt.show()

spark.stop()


#!/usr/bin/env python3

import sys
import pathlib

tokens = [
    "EBD"   , "FOR"   , "NEXT"  , "DATA"  , "VPOKE" , "INPUT" , "DIM"   , "READ"  ,
    "LET"   , "GOTO"  , "RUN"   , "IF"    , "RESTOR", "GOSUB" , "RETURN", "REM"   ,

    "STOP"  , "ON"    , "WAIT"  , "LOAD"  , "SAVE"  , "VERIFY", "DEF"   , "POKE"  ,
    "PRINT#", "PRINT" , "CONT"  , "LIST"  , "CLS"   , "CMD"   , "SYS"   , "OPEN"  ,

    "CLOSE" , "GET"   , "NEW"   , "TAB("  , "TO"    , "FN"    , "SPC("  , "THEN"  ,
    "NOT"   , "STEP"  , "+"     , "-"     , "*"     , "/"     , "???"   , "AND"   ,

    "OR"    , ">"     , "="     , "<"     , "SGN"   , "INT"   , "ABS"   , "USR"   ,
    "FRE"   , "POS"   , "SQR"   , "RND"   , "LOG"   , "EXP"   , "COS"   , "SIN"   ,

    "TAN"   , "ATN"   , "PEEK"  , "LEN"   , "STR$"  , "VAL"   , "ASC"   , "CHR$"  ,
    "LEFT$" , "RIGHT$", "MID$"  , "GO"    ,
    ]

if len(sys.argv) < 2:
    sys.exit(-1)

file_name = sys.argv[1]

state = 0
ptr   = 0x0801
addr  = 0

for byte in pathlib.Path(file_name).read_bytes():
    if state == 0:
        if byte != 1:
            print("ERROR");
        state = 1
    elif state == 1:
        if byte != 8:
            print("ERROR");
        addr = 0x0800
        state = 2
    elif state == 2:
        if addr != ptr:
            print("ERROR");
        ptr = byte
        state = 3
    elif state == 3:
        ptr = ptr + (byte << 8)
        state = 4
    elif state == 4:
        val = byte
        state = 5
    elif state == 5:
        val = val + (byte << 8)
        print(val, end='')
        print(' ', end='')
        state = 6
    elif state == 6:
        if byte == 0:
            print()
            state = 2
        elif byte < 0x80:
            print(chr(byte), end='')
        elif byte >= 0x80 and byte <= 0xcb:
            print(tokens[byte-0x80], end='')
    addr += 1


from typing import List

import aiofiles
from fastapi import APIRouter, UploadFile, File
from fastapi.responses import HTMLResponse
from pathlib import Path

from config import IMAGE_EXTENSIONS, WEBSITE_PATH

router = APIRouter(
    prefix='/admin',
)

@router.get('/upload')
async def page_for_uploading():
    content = f"""

        <form action="{WEBSITE_PATH}/admin/upload-files" enctype="multipart/form-data" method="post">
            <input name="in_files" type="file" multiple>
            <input type="submit">
        </form>

    """
    return HTMLResponse(content=content)

@router.post('/upload-files')
async def upload_files(in_files: List[UploadFile] = File(...)):
    page = ""

    for in_file in in_files:
        filename = in_file.filename.lower()
        async with aiofiles.open(f'originals/{filename}', 'wb') as out_file:
            content = await in_file.read()
            await out_file.write(content)

        link_to_file = f'{WEBSITE_PATH}/{filename}'
        page += f"""{link_to_file}
"""

    page += ""
    return HTMLResponse(content=page)

@router.get('/images')
async def images_list():
    images = []
    directory = Path('originals')

    for extension in IMAGE_EXTENSIONS:
        for image_path in directory.glob(f'*.{extension}'):
            images.append(image_path.name)

    page = "
Images:

"
    for image in images:
        page += f"""
{image}
"""
    page += "
"

    return HTMLResponse(content=page)


class Solution:
    def isValid(self, s: str) -> bool:
        mapping = {')':'(', ']':'[', '}':'{'}
        stack = []

        for c in s:
            if not c in mapping:
                stack.append(c)
            elif not stack or stack.pop() != mapping[c]:
                return False

        return not stack


from socket import create_connection
from time import sleep

sock = create_connection(("127.0.0.1", 7777))

# -1 + 1 = 0 (init index)
index = -1
while True:
  index = (index + 1) % 3
  sock.send(f"{index+1}".encode())

  data = sock.recv(1024)
  if not data:
    print("Empty Data")
    continue

  temp = int.from_bytes(data[0:4], "big")
  humid = int.from_bytes(data[4:8], "big")
  lumi = int.from_bytes(data[8:12], "big")

  print(f"Temp={temp}, Humid={humid}, Lumi={lumi}")

  sleep(1)


import os
import numpy as np
import torch
import os.path as osp
import torch.nn as nn
import torch.nn.functional as F
class TemporalEncoder(nn.Module):
    def __init__(
            self,
            n_layers=1,
            hidden_size=2048,
            add_linear=False,
            bidirectional=False,
            use_residual=True
    ):
        super(TemporalEncoder, self).__init__()

        self.gru = nn.GRU(
            input_size=2048,
            hidden_size=hidden_size,
            bidirectional=bidirectional,
            num_layers=n_layers
        )

        self.linear = None
        if bidirectional:
            self.linear = nn.Linear(hidden_size*2, 2048)
        elif add_linear:
            self.linear = nn.Linear(hidden_size, 2048)
        self.use_residual = use_residual

    def forward(self, x):
        n,t,f = x.shape
        x = x.permute(1,0,2) # NTF -> TNF
        y, _ = self.gru(x)
        if self.linear:
            y = F.relu(y)
            y = self.linear(y.view(-1, y.size(-1)))
            y = y.view(t,n,f)
        if self.use_residual and y.shape[-1] == 2048:
            y = y + x
        y = y.permute(1,0,2) # TNF -> NTF
        return y

class VIBEX(nn.Module):
    def __init__(
            self,
            seqlen,
            mean_param,
            batch_size=64,
            n_layers=1,
            hidden_size=2048,
            add_linear=False,
            bidirectional=False,
            use_residual=True, device='cuda',
    ):

        super(VIBEX, self).__init__()

        self.seqlen = seqlen
        self.batch_size = batch_size

        self.encoder = TemporalEncoder(
            n_layers=n_layers,
            hidden_size=hidden_size,
            bidirectional=bidirectional,
            add_linear=add_linear,
            use_residual=use_residual,
        )
        self.regressor = SMPLXRegressor(seqlen, mean_param)
        # regressor can predict cam, pose and shape params in an iterative way
        # self.regressor = Regressor()

    def forward(self, input, J_regressor=None):
        # input size NTF
        batch_size, seqlen = input.shape[:2]

        features = self.encoder(input)
        features = features.reshape(-1, features.size(-1))

        smplx_output = self.regressor(features)
        # smpl_output = self.regressor(feature, J_regressor=J_regressor)
        # for s in smpl_output:
        #     s['theta'] = s['theta'].reshape(batch_size, seqlen, -1)
        #     s['verts'] = s['verts'].reshape(batch_size, seqlen, -1, 3)
        #     s['kp_2d'] = s['kp_2d'].reshape(batch_size, seqlen, -1, 2)
        #     s['kp_3d'] = s['kp_3d'].reshape(batch_size, seqlen, -1, 3)
        #     s['rotmat'] = s['rotmat'].reshape(batch_size, seqlen, -1, 3, 3)

        return smplx_output
class SMPLXRegressor(nn.Module):
    def __init__(self, seqlen, mean_params=None):
        super(SMPLXRegressor, self).__init__()
        self.seqlen = seqlen
        self.mean_params = mean_params
        self.fc1 = nn.Linear(512 * 4 + mean_params.shape[1], 1024)
        self.drop1 = nn.Dropout()
        self.fc2 = nn.Linear(1024, 1024)
        self.drop2 = nn.Dropout()

        #--Predict pose (318), shape (10), expression (10), camera (3)
        self.decpose = nn.Linear(1024, 318)
        self.decshape = nn.Linear(1024, 10)
        self.decexp = nn.Linear(1024, 10)
        self.deccam = nn.Linear(1024, 3)

        nn.init.xavier_uniform_(self.decpose.weight, gain=0.01)
        nn.init.xavier_uniform_(self.decshape.weight, gain=0.01)
        nn.init.xavier_uniform_(self.decexp.weight, gain=0.01)
        nn.init.xavier_uniform_(self.deccam.weight, gain=0.01)

    def forward(self, x, init_pose=None, init_shape=None, init_cam=None, n_iter=3, J_regressor=None):
        batch_size = x.shape[0]
        _init = self.mean_params.expand(batch_size, -1)

        pred_pose = _init[:, :318]
        pred_shape = _init[:, 318: 328]
        pred_exp = _init[:, 328: 338]
        pred_cam = _init[:, 338: 341]
        for i in range(n_iter):
            xc = torch.cat([x, pred_pose, pred_shape, pred_exp, pred_cam],1)
            xc = self.fc1(xc)
            xc = self.drop1(xc)
            xc = self.fc2(xc)
            xc = self.drop2(xc)

            pred_pose = self.decpose(xc) + pred_pose
            pred_shape = self.decshape(xc) + pred_shape
            pred_exp = self.decexp(xc) + pred_exp
            pred_cam = self.deccam(xc) + pred_cam
            pred_param = torch.cat([pred_pose, pred_shape, pred_shape, pred_exp, pred_cam], 1)

        return pred_param

class Regressor(nn.Module):
    def __init__(self, smpl_mean_params=''):
        super(Regressor, self).__init__()

        npose = 24 * 6

        self.fc1 = nn.Linear(512 * 4 + npose + 13, 1024)
        self.drop1 = nn.Dropout()
        self.fc2 = nn.Linear(1024, 1024)
        self.drop2 = nn.Dropout()
        self.decpose = nn.Linear(1024, npose)
        self.decshape = nn.Linear(1024, 10)
        self.deccam = nn.Linear(1024, 3)
        nn.init.xavier_uniform_(self.decpose.weight, gain=0.01)
        nn.init.xavier_uniform_(self.decshape.weight, gain=0.01)
        nn.init.xavier_uniform_(self.deccam.weight, gain=0.01)

        self.smpl = SMPL(
            SMPL_MODEL_DIR,
            batch_size=64,
            create_transl=False
        )

        mean_params = np.load(smpl_mean_params)
        init_pose = torch.from_numpy(mean_params['pose'][:]).unsqueeze(0)
        init_shape = torch.from_numpy(mean_params['shape'][:].astype('float32')).unsqueeze(0)
        init_cam = torch.from_numpy(mean_params['cam']).unsqueeze(0)
        self.register_buffer('init_pose', init_pose)
        self.register_buffer('init_shape', init_shape)
        self.register_buffer('init_cam', init_cam)

    def forward(self, x, init_pose=None, init_shape=None, init_cam=None, n_iter=3, J_regressor=None):
        batch_size = x.shape[0]

        if init_pose is None:
            init_pose = self.init_pose.expand(batch_size, -1)
        if init_shape is None:
            init_shape = self.init_shape.expand(batch_size, -1)
        if init_cam is None:
            init_cam = self.init_cam.expand(batch_size, -1)

        pred_pose = init_pose
        pred_shape = init_shape
        pred_cam = init_cam
        for i in range(n_iter):
            xc = torch.cat([x, pred_pose, pred_shape, pred_cam], 1)
            xc = self.fc1(xc)
            xc = self.drop1(xc)
            xc = self.fc2(xc)
            xc = self.drop2(xc)
            pred_pose = self.decpose(xc) + pred_pose
            pred_shape = self.decshape(xc) + pred_shape
            pred_cam = self.deccam(xc) + pred_cam

        # pred_rotmat = rot6d_to_rotmat(pred_pose).view(batch_size, 24, 3, 3)

        pred_output = self.smpl(
            betas=pred_shape,
            body_pose=pred_rotmat[:, 1:],
            global_orient=pred_rotmat[:, 0].unsqueeze(1),
            pose2rot=False
        )

        pred_vertices = pred_output.vertices
        pred_joints = pred_output.joints

        if J_regressor is not None:
            J_regressor_batch = J_regressor[None, :].expand(pred_vertices.shape[0], -1, -1).to(pred_vertices.device)
            pred_joints = torch.matmul(J_regressor_batch, pred_vertices)
            pred_joints = pred_joints[:, H36M_TO_J14, :]

        pred_keypoints_2d = projection(pred_joints, pred_cam)

        pose = rotation_matrix_to_angle_axis(pred_rotmat.reshape(-1, 3, 3)).reshape(-1, 72)

        output = [{
            'theta'  : torch.cat([pred_cam, pose, pred_shape], dim=1),
            'verts'  : pred_vertices,
            'kp_2d'  : pred_keypoints_2d,
            'kp_3d'  : pred_joints,
            'rotmat' : pred_rotmat
        }]
        return output


"""
Module for working with time envelopes.

Author: Boris Bantysh
E-mail: bbantysh60000@gmail.com
License: GPL-3.0
"""
from warnings import warn
from abc import ABC, abstractmethod
from typing import Optional, Callable, List
from fractions import Fraction

import numpy as np
from scipy.stats import norm

class Envelope(ABC):
    """Abstract envelope class.

    :param time_start: Time the envelope is starting (None for -infinity).
    :param time_stop: Time the envelope is stopping (None for +infinity).
    :param period: Envelope period (None for non-periodic envelope, 0. for constant envelope).
    """

    def __init__(
            self,
            time_start: Optional[float] = None,
            time_stop: Optional[float] = None,
            period: Optional[float] = None
    ):
        self.time_start = time_start
        self.time_stop = time_stop
        self.period = period

    def is_in_bounds(self, t: float) -> bool:
        """Checks if time point is in envelope acting bounds.

        :param t: Time point.
        :return: True if the time value is inside envelope bounds.
        """
        if self.time_start is not None and t < self.time_start:
            return False
        if self.time_stop is not None and t > self.time_stop:
            return False
        return True

    def __call__(self, t: float) -> complex:
        """Returns the envelope value at specific time point.

        :param t: Time point.
        :return: Envelope value.
        """
        return self._get_value(t) if self.is_in_bounds(t) else 0.

    def drv(self, t: float) -> complex:
        """Returns the envelope derivative at specific time point.

        :param t: Time point.
        :return: Derivative value.
        """
        return self._get_derivative(t) if self.is_in_bounds(t) else 0.

    @abstractmethod
    def _get_value(self, t: float) -> complex:
        pass

    @abstractmethod
    def _get_derivative(self, t: float) -> complex:
        pass

    def conj(self):
        """Returns the complex conjugate envelope"""
        return ConjugateEnvelope(self)

class ConjugateEnvelope(Envelope):
    """Complex conjugate envelope.

    :param parent_envelope: Envelope to conjugate.
    """

    def __init__(self, parent_envelope: Envelope):
        super().__init__(
            time_start=parent_envelope.time_start,
            time_stop=parent_envelope.time_stop,
            period=parent_envelope.period
        )

        self.__parent_envelope = parent_envelope

    def _get_value(self, t: float) -> complex:
        parent_value = self.__parent_envelope._get_value(t)
        if isinstance(parent_value, float):
            return parent_value
        else:
            return parent_value.conjugate()

    def _get_derivative(self, t: float) -> complex:
        parent_value = self.__parent_envelope._get_derivative(t)
        if isinstance(parent_value, float):
            return parent_value
        else:
            return parent_value.conjugate()

    def conj(self):
        return self.__parent_envelope

class ConstantEnvelope(Envelope):
    """Constant value envelope.

    :param value: Envelope value.
    :param time_start: Time the envelope is starting (None for -infinity).
    :param time_stop: Time the envelope is stopping (None for +infinity).
    """

    def __init__(self, value: complex, time_start: float = None, time_stop: float = None):
        super().__init__(time_start, time_stop, 0.)
        self.value = value

    def _get_value(self, t: float) -> complex:
        return self.value

    def _get_derivative(self, t: float) -> complex:
        return 0.

    def smoothen(self, front_width: float):
        """Returns the smooth version of the envelope, when it starts and ends smoothly.

        :param front_width: The front width of the envelope.
        :return: New envelope with smooth bounds.
        """
        return PulseEnvelope(front_width, self.value, self.time_start, self.time_stop)

class CustomEnvelope(Envelope):
    """Custom envelope

    :param fun: Function handler to calculate the envelope value at specific time point.
    :param fun_derivative: Function handler to calculate the envelope time derivative value at specific time point.
    :param fun_dt: Delta time to compute the envelope derivative using the finite difference.
    Is used when `fun_derivative` is None.
    :param time_start: Time the envelope is starting (None for -infinity).
    :param time_stop: Time the envelope is stopping (None for +infinity).
    :param period: Envelope period (None for non-periodic envelope, 0. for constant envelope).
    """

    def __init__(
            self,
            fun: Callable[[float], complex],
            fun_derivative: Callable[[float], complex] = None,
            fun_dt: float = None,
            time_start: Optional[float] = None,
            time_stop: Optional[float] = None,
            period: Optional[float] = None
    ):
        super().__init__(time_start, time_stop, period)
        self.fun = fun
        if fun_derivative is None:
            fun_derivative = lambda t: (fun(t + fun_dt) - fun(t)) / fun_dt
        self.fun_derivative = fun_derivative

    def _get_value(self, t: float) -> complex:
        return self.fun(t)

    def _get_derivative(self, t: float) -> complex:
        return self.fun_derivative(t)

class ProductEnvelope(Envelope):
    """The product of multiple envelopes.

    :param multipliers: Product multipliers.
    :param time_start: Time the envelope is starting (None to compute from the multipliers).
    :param time_stop: Time the envelope is stopping (None to compute from the multipliers).
    :param period: Envelope period (None to compute from the multipliers).
    """

    def __init__(
            self,
            multipliers: List[Envelope],
            time_start: Optional[float] = None,
            time_stop: Optional[float] = None,
            period: Optional[float] = None
    ):
        if time_start is None:
            time_start_list = [envelope.time_start for envelope in multipliers if envelope.time_start is not None]
            time_start = None if len(time_start_list) == 0 else max(time_start_list)
        if time_stop is None:
            time_stop_list = [envelope.time_stop for envelope in multipliers if envelope.time_stop is not None]
            time_stop = None if len(time_stop_list) == 0 else min(time_stop_list)
        if period is None:
            period = get_common_period(multipliers)
        super().__init__(time_start, time_stop, period)
        self.multipliers = multipliers

    def _get_value(self, t: float) -> complex:
        return complex(np.prod([envelope(t) for envelope in self.multipliers], dtype=complex))

    def _get_derivative(self, t: float) -> complex:
        drv = complex(0.)
        for idx, envelope in enumerate(self.multipliers):
            m1 = complex(np.prod([e(t) for e in self.multipliers[:idx] + self.multipliers[idx + 1:]], dtype=complex))
            drv += m1 * envelope.drv(t)
        return drv

class SumEnvelope(Envelope):
    """The sum of multiple envelopes.

    :param terms: Sum terms.
    :param time_start: Time the envelope is starting (None to compute from the terms).
    :param time_stop: Time the envelope is stopping (None to compute from the terms).
    :param period: Envelope period (None to compute from the terms).
    """

    def __init__(
            self,
            terms: List[Envelope],
            time_start: Optional[float] = None,
            time_stop: Optional[float] = None,
            period: Optional[float] = None
    ):
        if time_start is None:
            time_start_list = [envelope.time_start for envelope in terms]
            time_start = None if None in time_start_list else min(time_start_list)
        if time_stop is None:
            time_stop_list = [envelope.time_stop for envelope in terms]
            time_stop = None if None in time_stop_list else max(time_stop_list)
        super().__init__(time_start, time_stop, period)

        self.terms = terms

    def _get_value(self, t: float) -> complex:
        return sum(envelope(t) for envelope in self.terms)

    def _get_derivative(self, t: float) -> complex:
        return sum(envelope.drv(t) for envelope in self.terms)

    def conj(self):
        return SumEnvelope(
            terms=[term.conj() for term in self.terms],
            time_start=self.time_start,
            time_stop=self.time_stop,
            period=self.period
        )

    def expand(self):
        """Expands the envelope to it terms.

        :return: List of terms.
        """
        return self.terms

class PulseEnvelope(SumEnvelope):
    """Smooth pulse envelope.

    :param front_width: The pulse front width.
    :param amplitude: The pulse amplitude.
    :param time_start: Time the envelope is starting (None for -infinity).
    :param time_stop: Time the envelope is stopping (None for +infinity).
    """

    def __init__(
            self,
            front_width: float,
            amplitude: complex = 1.,
            time_start: Optional[float] = None,
            time_stop: Optional[float] = None
    ):
        super().__init__(self.get_terms(front_width, amplitude, time_start, time_stop))

    @staticmethod
    def get_terms(
            front_width: float,
            amplitude: complex = 1.,
            time_start: Optional[float] = None,
            time_stop: Optional[float] = None
    ):
        """Compute the terms of a smooth pulse envelope.

        :param front_width: The pulse front width.
        :param amplitude: The pulse amplitude.
        :param time_start: Time the envelope is starting (None for -infinity).
        :param time_stop: Time the envelope is stopping (None for +infinity).
        :return: List of envelope terms.
        """
        if time_start is not None and time_stop is not None:
            assert time_stop - time_start > 10 * front_width, "Pulse length must be larger than the 10 widths"

        terms = []

        if time_start is not None and front_width > 0.:
            terms.append(CustomEnvelope(
                fun=lambda t: amplitude * norm.cdf(t, loc=time_start, scale=front_width),
                fun_derivative=lambda t: amplitude * norm.pdf(t, loc=time_start, scale=front_width),
                time_start=time_start - 5 * front_width,
                time_stop=time_start + 5 * front_width
            ))

        terms.append(ConstantEnvelope(
            value=amplitude,
            time_start=None if time_start is None else time_start + 5 * front_width,
            time_stop=None if time_stop is None else time_stop - 5 * front_width
        ))

        if time_stop is not None and front_width > 0.:
            terms.append( CustomEnvelope(
                fun=lambda t: amplitude * (1. - norm.cdf(t, loc=time_stop, scale=front_width)),
                fun_derivative=lambda t: -amplitude * norm.pdf(t, loc=time_stop, scale=front_width),
                time_start=time_stop - 5 * front_width,
                time_stop=time_stop + 5 * front_width
            ))

        return terms

class PeriodicEnvelope(Envelope):
    """Periodic envelope: `A * exp(-1j*w*t + p) + b`.

    :param amplitude: Envelope amplitude `A`.
    :param frequency: Envelope frequency `w`.
    :param phase: Envelope phase `p`.
    :param shift: Envelope shift `b`.
    :param time_start: Time the envelope is starting (None for -infinity).
    :param time_stop: Time the envelope is stopping (None for +infinity).
    """

    def __init__(
            self,
            amplitude: float,
            frequency: float,
            phase: Optional[float] = 0.,
            shift: Optional[float] = 0.,
            time_start: Optional[float] = None,
            time_stop: Optional[float] = None
    ):
        period = 2 * np.pi / frequency
        if time_start is not None and time_stop is not None and period > time_stop - time_start:
            period = None

        super().__init__(time_start=time_start, time_stop=time_stop, period=period)

        self.amplitude = amplitude
        self.frequency = frequency
        self.phase = phase
        self.shift = shift

    def __new__(
            cls,
            amplitude: float,
            frequency: float,
            phase: Optional[float] = 0.,
            shift: Optional[float] = 0.,
            time_start: Optional[float] = None,
            time_stop: Optional[float] = None
    ):
        if frequency == 0:
            value = shift + amplitude * (np.cos(phase) + 1j * np.sin(phase))
            return ConstantEnvelope(value, time_start, time_stop)
        return super().__new__(cls)

    def _get_value(self, t: float) -> complex:
        phase = self.frequency * t - self.phase
        return self.shift + self.amplitude * (np.cos(phase) - 1j * np.sin(phase))

    def _get_derivative(self, t: float) -> complex:
        phase = self.frequency * t - self.phase
        return self.amplitude * self.frequency * (-np.sin(phase) - 1j * np.cos(phase))

    def to_window(self, time_start: Optional[float] = None, time_stop: Optional[float] = None):
        """Crops the periodic envelope to specific window.

        :param time_start: Time the envelope is starting (None for -infinity).
        :param time_stop: Time the envelope is stopping (None for +infinity).
        :return: New instance of the envelope with specified window.
        """
        return self.__class__(
            amplitude=self.amplitude,
            frequency=self.frequency,
            phase=self.phase,
            shift=self.shift,
            time_start=time_start,
            time_stop=time_stop
        )

    def smoothen(self, front_width: float):
        """Returns the smooth version of the envelope, when it starts and ends smoothly.

        :param front_width: The front width of the envelope.
        :return: New envelope with smooth bounds.
        """
        pulse_envelope = PulseEnvelope(front_width, time_start=self.time_start, time_stop=self.time_stop)
        return SumEnvelope([
            ProductEnvelope([self.to_window(term.time_start, term.time_stop), term])
            for term in pulse_envelope.terms
        ])

def get_common_period(envelopes: List[Envelope]) -> Optional[float]:
    """Computes the common period of a number of envelopes.

    :param envelopes: List of envelopes.
    :return: Common period (None for non-periodic envelope, 0. for constant envelope).
    """
    periods = [envelope.period for envelope in envelopes]
    if None in periods:
        return None

    non_zero_periods = [period for period in periods if period > 0.]
    if len(non_zero_periods) == 0:
        return 0.

    period = non_zero_periods[0]

    if len(non_zero_periods) == 1:
        return period

    for period_j in non_zero_periods[1:]:
        q1, _ = Fraction.from_float(period_j / period).limit_denominator(1000).as_integer_ratio()
        period = q1 * period

    for envelope in envelopes:
        if envelope.time_start is not None:
            t0 = envelope.time_start
        elif envelope.time_stop is not None:
            t0 = envelope.time_stop - period
        else:
            t0 = 0.
        if abs(envelope(t0 + period) - envelope(t0)) > 1e-6:
            warn("Failed to approximate envelope period. Use non-periodic evolution.")
            return None
    return period


from django.urls import path

from internaladmin.views import AdminStatisticsView, AdminBuildMirrorStatusView

urlpatterns = [
    path("statistics/", AdminStatisticsView.as_view(), name="admin_statistics"),
    path(
        "mirror_status/",
        AdminBuildMirrorStatusView.as_view(),
        name="admin_build_mirror_status",
    ),
]


import json

import nonebot
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from nonebot import require
from .config import Config
from .data_source import get_leetcode_question_everyday

global_config = nonebot.get_driver().config
nonebot.logger.info("global_config:{}".format(global_config))
plugin_config = Config(**global_config.dict())

if hasattr(plugin_config, 'leetcode_qq_friends') and hasattr(plugin_config,'leetcode_qq_groups') and hasattr(plugin_config,'leetcode_inform_time'):
    nonebot.logger.success("plugin_config:{}".format(plugin_config))
else:
    nonebot.logger.critical("plugin_config:{}".format(plugin_config))
    raise Exception("leetcode config error, please check env file")

scheduler = require("nonebot_plugin_apscheduler").scheduler  # type:AsyncIOScheduler

#
# @scheduler.scheduled_job("cron", hour="*/2", id="xxx", args=[1], kwargs={"arg2": 2})
# async def run_every_2_hour(arg1, arg2):
#     pass

async def send_leetcode_everyday():
    question = get_leetcode_question_everyday()
    # 转化成json格式
    jsonText = json.loads(question)
    # 题目题号
    no = jsonText.get('questionFrontendId')
    # 题名（中文）
    leetcodeTitle = jsonText.get('translatedTitle')
    # 提名 (英文)
    titleSlug = jsonText.get('titleSlug')
    # 题目难度级别
    level = jsonText.get('difficulty')
    # 题目内容
    context = jsonText.get('translatedContent')
    # 题目链接
    link = "https://leetcode-cn.com/problems/{}/".format(titleSlug)
    message = "no:{}\ntitle:{}\nlevel:{}\n".format(no, leetcodeTitle, level)
    message += "link:{}\n".format(link)

    # 给配置的列表里的qq好友发leetcode通知
    for qq in plugin_config.leetcode_qq_friends:
        await nonebot.get_bot().send_private_msg(user_id=qq, message=message)
    # 给群发送leetcode通知
    for qq_group in plugin_config.leetcode_qq_groups:
        await nonebot.get_bot().send_group_msg(group_id=qq_group, message="[CQ:at,qq={}]{}".format("all", message))

#调试用，可以每秒看到函数调用情况
scheduler.add_job(send_leetcode_everyday, "interval", seconds=1, id="114514")

# 根据配置的参数，注册定时任务,每天发送
for index, time in enumerate(plugin_config.leetcode_inform_time):
    nonebot.logger.info("id:{},time:{}".format(index, time))
    scheduler.add_job(send_leetcode_everyday, "cron", hour=time.hour, minute=time.minute, id=str(index))


# -*- coding: utf-8 -*-
import os
import time
#[用户名，时间区间列表，端口列表]
def time_port_stat(dir_prefix):   #定义一个函数
    file_dir=dir_prefix +"china students\\"
    txt_filename=[fname for fname in os.listdir(file_dir) if fname.endswith('.txt')]#搜索指定目录下txt文
    for e in txt_filename:
        file_path=file_dir+e
        fread=open(file_path,'r')             #打开txt文档
        fread_txt=fread.read()               #读取txt文档
        fread.close()
        txt_list=fread_txt.split('\n')
        txt_list.pop()
        for i in range(len(txt_list)):
            txt_list[i]=txt_list[i].split("\t")
        txt_sorted=sorted(txt_list,key=lambda x:x[1])#数据排序
        del(txt_list)   #删除原数据
        users_lists=[]  #"去重之前的用户列表
        for i in range(len(txt_sorted)):
            users_lists.append(txt_sorted[i][1])   #把内容加到列表里面
        statis_info = []
        users_list=list(set(users_lists))
        users_list.sort()
        fw=open(result , "w")
        for account in users_list:
            each_user=[]
            time_temp=[]
            time_list=[]
            port_list=[]
            port_dic={}
            tag=0    #每个账号第一次出现用tag=1表示,不匹配用tag=0表示
            for item in txt_sorted:
                if tag==0 and len(port_list)>0:
                    break
                if item[1]==account:
                    tag=1
                    time_temp.append(item[0])
                    port_list.append(item[6])
                else:
                    tag=0
            time_list.append(min(time_temp))
            time_list.append(max(time_temp))
            port_norepeat=list(set(port_list))
            for e in port_norepeat:
                port_dic[e]=port_list.count(e)
                each_row=account+'\t'+(time_list[0])[15:22]+"\t"+(time_list[1])[15:22]+"\t"+str(port_dic)[1:len(str(port_dic))-1]+"\n"
            fw.write(each_row)
            del each_row
            del time_temp
            del time_list
            del port_list
            del port_norepeat
            del port_dic
            del each_user
        fw.close()
def travel(filename):
    fread_directory=open(filename,'r')
    floders_path=fread_directory.read().split('\n')
    floders_path.pop()
    for path_prefix in floders_path:
        time_port_stat(path_prefix)
        print(path_prefix," fineshed")


import numpy as np
from Interfaces import Queue

class ArrayQueue(Queue):
    def __init__(self):
        self.n = 0
        self.j = 0
        self.a = self.new_array(1)

    def new_array(self, n: int) ->np.array:
        return np.zeros(n, np.object)

    def resize(self):
        temp_stack = self.new_array(max(1, 2 * self.n))
        for i in range(0, self.n):
            temp_stack[i] = self.a[(self.j + i) % len(self.a)]
        self.a = temp_stack
        self.j = 0

    def add(self, x : np.object) :
        temp = self.n
        if (self.n + 1) > len(self.a):
            self.resize()
            self.n = temp
        self.a[(self.j + self.n) % len(self.a)] = x
        self.n = self.n + 1
        return True

    def remove(self) -> np.object :
        try:
            if self.n == 0:
                raise Exception
            else:
                x = self.a[self.j]
                self.j = (self.j + 1) % len(self.a)
                self.n -= 1
                if len(self.a) >= 3 * self.n:
                    self.resize()
                return x
        except Exception:
            print("Queue is empty!")

    def size(self) :
        return self.n

    def __str__(self):
        s = "["
        for i in range(0, self.n):
            s += "%r" % self.a[(i + self.j) % len(self.a)]
            if i  < self.n-1:
                s += ","
        return s + "]"

    def __iter__(self):
        self.iterator = 0
        return self

    def __next__(self):
        if self.iterator < self.n:
            x = self.a[self.iterator]
            self.iterator +=1
        else:
             raise StopIteration()
        return x
'''
if __name__ == "__main__":
    x = ArrayQueue()
    x.remove()
    x.add(1)
    print(x)
    x.add(2)
    print(x)
    x.add(3)
    print(x)
    x.add(4)
    print(x)
    x.add(5)
    print(x)

    x.remove()
    print(x)
    x.remove()
    print(x)
    x.remove()
    print(x)
    x.remove()
    print(x)
    x.remove()
    print(x)
'''


#!/usr/bin/env python3

import matplotlib.pyplot as plt
import numpy as np

theta = np.linspace(0, 2*np.pi, 500)
r = 2*np.sin(3*theta)

ax = plt.subplot(111, polar=True)

ax.plot(theta, r, 'b-', theta, theta/(np.pi), 'g-')
ax.grid(True)

ax.set_title(r"Rose Plot $r = 2\sin(2\theta)$ and Archimedean Spiral $r =\theta/2\pi$")
plt.show()


#dbot
#Mathieu Dombrock

import discord
import re
import random
import string
import requests
import json
import pickle
import glob
from pathlib import Path

client = discord.Client()

@client.event
async def on_message(message):
	global banned_words
	bot_command = "?"
	memories = []
	memories_file = 'memories.pk'
	help_list = []
	tut_dir = 'tutorials/'
	ftype = ".txt"

	msgin_original = message.content #some functions need case sensitive input
	msgin = message.content.lower()
	msgin = msgin.split(" ")
	msgin_original = msgin_original.split(" ")
	print(msgin)
	tag = '{0.author.mention} : \n'.format(message)

	print("chan: "+str(message.channel))
	if message.author == client.user:#make sure we are not talking to ourselves
		return

	for word in banned_words:
		if str(word).lower() in str(msgin_original).lower():
			msgout = tag+"**WOAH THERE!**\n\n**RULES:**\n```4.) NO HATE SPEECH OF ANY KIND (SEE RULE #1 & #3)```\n"
			msgout += "This incident has been logged.\nIf you feel like this happened in error, please contact a helper and let us know what happened."
			log_path = "deletion-log.txt"
			with open(log_path, 'r') as file:
				old = file.read()
			with open(log_path, 'w') as file:
				file.write(str(message.author)+": "+str(msgin_original)+"\n"+"OFFENDING WORD: "+str(word)+"\n-------\n"+old)
			await client.delete_message(message)
			await client.send_message(message.channel, msgout)
			return

	if str(message.channel)=="welcome":
		tutorial_location = 'tutorials/welcome-message.txt'
		file = open(tutorial_location, "r")
		msgout = file.read()
		await client.send_message(message.channel, msgout)
		return

	if random.randrange(50)<2:
		msgout = tag+"Thanks for being here!"
		await client.send_message(message.channel, msgout)

	help_list.append(["tutorial <topic>","Display a preset tutorial message."])
	help_list.append(["tutorial list","List available tutorial topics."])
	if (bot_command+'tutorial') in msgin[0] or (bot_command+'tut') in msgin[0]:
		if ('list') in msgin[1]:
			print("printing tut list")
			tut_list = (glob.glob(tut_dir+"*.txt"))
			msgout = "**TUTORIALS AVAILABLE:**"
			for title in tut_list:
				title = title.replace(tut_dir,"")
				title = title.replace(ftype,"")
				msgout += "\n**"+title+"**"
		else:
			tutorial_location = 'tutorials/'+msgin[1]+'.txt'
			print(tutorial_location)
			#tutorail_file = Path(tutorial_location)
			if Path(tutorial_location).is_file():
				file = open(tutorial_location, "r")
				msgout = file.read()
				#msgout += "\n \n[If you have suggestions for a new tutorial or concerns about this one, please let us know in #suggestions-and-meta]"
			else:
				msgout = tag+"I can't find any saved tutorials on "+msgin[1]+"... sorry :/"
		await client.send_message(message.channel, msgout)

	help_list.append(["test","See if I am working. Or more specifically, still responding to messages."])
	if ((bot_command+'test') in msgin[0]):
		msgout = "Yeah, yeah I, oh, I'm still alive."
		await client.send_message(message.channel, msgout)

	help_list.append(["roll <x>d<y>","Example: roll 1d3"])
	if ((bot_command+'roll') in msgin[0]):
		msgin = msgin[1].split("d")
		result = ""
		results = ""
		for x in range(int(msgin[0])):
			result = random.randrange( 0, int(msgin[1]) ) +1
			results += str(result)+"\n"
		msgout = tag+results
		await client.send_message(message.channel, msgout)

	help_list.append(["choose <choice1> <choice2> <choice3> <...>","Helps you make a choice. \nExample: choose Debian Ubuntu CentOS\nOutput: Ubuntu"])
	if ((bot_command+'choose') in msgin[0]):
		print("choose")
		msgin = msgin[1:]
		print(msgin)
		msgout = tag+"Choosing from: "+', '.join(msgin)+"\n"+random.choice(msgin)
		await client.send_message(message.channel, msgout)

	help_list.append(["google <search-term>","I'm feeling lucky"])
	if ((bot_command+'google') in msgin[0]):
		r = requests.get("http://www.google.com/search?q="+' '.join(msgin[1:])+"&btnI");
		msgout = r.url
		msgout = tag+str(msgout)
		await client.send_message(message.channel, msgout)

	help_list.append(["wiki <search-term>","searches wikipedia"])
	if ((bot_command+'wiki') in msgin[0]):
		r = requests.get("https://en.wikipedia.org/w/api.php?action=opensearch&search="+' '.join(msgin[1:])+"&limit=1&namespace=0&format=json");
		msgout = json.loads(r.text)
		msgout = tag+str(msgout[3]).strip("[\"']")
		await client.send_message(message.channel, msgout)

	help_list.append(["remember <topic/key> <memory/value>","Remember the following\nExample: remember Dre hip-hop mastermind"])
	if ((bot_command+'remember') in msgin[0]):
		subject = msgin[1]
		memory = ' '.join(msgin_original[2:])
		msgout = tag+'Remembered '+subject+" as "+memory
		memories.append([subject, memory])
		#open a pickle file
		with open(memories_file, 'wb') as fi:
		# dump your data into the file
			pickle.dump(memories, fi)
		await client.send_message(message.channel, msgout)

	help_list.append(["recall <topic/key>","recall a memory\nExample: recall Dre"])
	if ((bot_command+'recall') in msgin[0]):
		with open(memories_file, 'rb') as fi:
			memories = pickle.load(fi)
		found = False
		for x in memories:
			if x[0] == msgin[1]:
				found = True
				subject = x[0]
				memory = x[1]
				msgout = tag+"I Recall "+subject+" as "+memory
		if found == False:
			msgout = tag+"I don't recall that."
		await client.send_message(message.channel, msgout)

	#help must be last to ensure the help list is loaded
	help_list.append(["help","Displays Help Message."])
	if ((bot_command+'help') in msgin[0]):
		msgout = "```CSS\nDiscover-Bot```"
		for x in sorted(help_list):
			msgout += "```\n"
			msgout += bot_command+'\n'.join(x).replace("\n", "\n--")+"\n\n"
			msgout += "\n```"
		msgout += "\nhttps://github.com/matdombrock/Discover-Bot\n"
		await client.send_message(message.channel, msgout)

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')

def load_banned_words(location):
	print("Loading Baned Words List")
	banned_words = []
	with open(location) as f:
		banned_words = f.read().splitlines()
	return banned_words

banned_words = load_banned_words('banned_words.txt')
client.run('change-me')


from setuptools import find_packages, setup
from pathlib import Path

here = Path(__file__).parent
readme = (here / "README.md").read_text()

setup(
    name='BerkeleyPhotonicsGenerator',
    version='0.8.5',
    author='Pavan Bhargava and Sidney Buchbinder',
    author_email='pvnbhargava@berkeley.edu',
    description='A Python framework for generating masks and simulating integrated optical systems',
    long_description=readme,
    long_description_content_type="text/markdown",
    install_requires=[
        'setuptools>=18.5',
        'PyYAML>=5.1',
        'numpy>=1.10',
        'pytest>=4',
        'matplotlib>=3',
        'gdspy @ https://github.com/heitzmann/gdspy/archive/900ec9efecd066e3440e502bd8a046789bbab552.zip',
        'scipy>=1.1.0',
        'memory_profiler>=0.54.0',
        'Jinja2>=2.10.1',
    ],
    url='https://github.com/BerkeleyPhotonicsGenerator/BPG',
    license='BSD-3-Clause',
    packages=find_packages(exclude=("tests", "docs")),
    scripts=['BPG/bpg'],
    include_package_data=True,
)


import random
class Quiz:
    def __init__(self, question, answer):
        self.question = question
        self.answer = answer

    def check_true_answer(self, user_answer):
        if user_answer.lower() == self.answer.lower():
            return True
        else:
            return False

    def __str__(self):
        return f"{self.question}? "

class TrueFalse(Quiz):
    def __init__(self, question, answer):
        super().__init__(question, answer)

    def show_choice(self):
        print("1)True\n2)False")

    def check_true_answer(self, user_answer):
        if user_answer.lower() == 'true' or user_answer.lower() == 'false':
            if user_answer.lower() == self.answer.lower():
                return True
            else:
                return False
        else:
            return "wrong format"

class MultipleChoice(Quiz):
    def __init__(self, question, answer, choice_list):
        super().__init__(question, answer)
        self.choice_list = choice_list

    def show_choice(self):
        print("this is multiplechoice question please select true answer from below!")
        for i, j in enumerate(self.choice_list):
            print(i, j)

    def check_true_answer(self, user_answer):
        if user_answer in self.choice_list:

            if user_answer.lower() == self.answer.lower():
                return True
            else:
                return False
        else:
            return "wrong format"

class ShortAnswer(Quiz):
    def __init__(self, question, answer):
        super().__init__(question, answer)

    def show_choice(self):
        print("this is short answer question please enter a short answer for this question")

    def check_true_answer(self, user_answer):
        if len(user_answer) <= 20:
            if user_answer.lower() == self.answer.lower():
                return True
            else:
                return False
        else:
            return "wrong format"

class Score:
    def __init__(self, score):
        self.score = score
        self.status = None

    def check_status(self):
        if self.score > 40:
            self.status = True
            print("You win!")
        else:
            self.status = False
            print("You loose!")

    def __str__(self):
        return f"Your score is {self.score}"

    def __add__(self, other):
        return self.score + other

    def __abs__(self, other):
        return self.score - other

quizes_truefalse = []
q1 = TrueFalse('sana is girl?','true')
q2 = TrueFalse('is water solid?','false')
q3 = TrueFalse('is sam a boy?','true')
q4 = TrueFalse('2+2 = 5?','false')
q5 = TrueFalse('Is Iran an islamic country?','true')

quizes_truefalse.append(q1)
quizes_truefalse.append(q2)
quizes_truefalse.append(q3)
quizes_truefalse.append(q4)
quizes_truefalse.append(q5)

quizes_multiple = []
q6 = MultipleChoice('what temp water is boiling?','100',['100','80','90','110'])
q7 = MultipleChoice('what is Iran captil?','tehran',['tabriz','rasht','tehran','esfahan'])
q8 = MultipleChoice('who is Iran present?','raeisi',['hashemi','raeisi','ahmadi','ruhani'])
q9 = MultipleChoice('how many days are maktab classes?','3',['4','3','5','2'])
q10 = MultipleChoice('how many years late corona?','3',['1','5','2','3'])
quizes_multiple.append(q6)
quizes_multiple.append(q7)
quizes_multiple.append(q8)
quizes_multiple.append(q9)
quizes_multiple.append(q10)

quizes_shortanswer = []
q11 = quizes_shortanswer.append(ShortAnswer('what is french captial?','paris'))
q12 = quizes_shortanswer.append(ShortAnswer('what is Iran captial?','tehran'))
q13 = quizes_shortanswer.append(ShortAnswer('what is turkey captial?','istanbul'))
q14 = quizes_shortanswer.append(ShortAnswer('what is england captial?','london'))
q15 = quizes_shortanswer.append(ShortAnswer('what is armnestan captial?','iravan'))

quizes = []
for i in range(2):
    q = random.choice(quizes_multiple)
    quizes.append(q)
    while q not in quizes:
        q = random.choice(quizes_multiple)
        quizes.append(q)

for i in range(2):
    q = random.choice(quizes_truefalse)
    quizes.append(q)
    while q not in quizes:
        q = random.choice(quizes_truefalse)
        quizes.append(q)
q = random.choice(quizes_shortanswer)
quizes.append(q)
score = 0
correct = 0
wrong = 0
remaining = len(quizes)
for i,j in enumerate(quizes):
    print(j)
    j.show_choice()
    answer = input("enter answer: ")
    if answer:
        if j.check_true_answer(answer):
            print("Corroct answer!")
            s1 = Score(score)
            score = s1.__add__(10)
            # score += 10
            correct += 1
        else:
            print("Wrong answer!")
            s1 = Score(score)
            score = s1.__abs__(3)
            wrong += 1
    else:
        score = s1.__add__(0)

    print("Q\tCorroct\tWrong\tScore\tRemaining")
    print(f"{i+1}\t\t{correct}\t\t{wrong}\t\t{score}\t\t{4-i}")
# s2 = Score(score)
s1.check_status()


class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        stack = collections.deque()

        for v in tokens:
            if v in '+-*/':
                n2, n1 = stack.pop(), stack.pop()
                stack.append(str(int(eval(n1+v+n2))))
            else:
                stack.append(v)
        return stack[0]


n=int(input())
sqr=n*n
temp=n
s=0
while(n>0):
    r=n%10
    s=s*10+r
    n=n//10
sqr1=s*s
s1=0
r1=0
while(sqr1>0):
    r1=sqr1%10
    s1=s1*10+r1
    sqr1=sqr1//10
if(s1==sqr):
    print(True)
else:
    print(False)


"""Init

Revision ID: 331cf6ffd8ca
Revises:
Create Date: 2023-08-02 17:22:37.665793

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '331cf6ffd8ca'
down_revision = None
branch_labels = None
depends_on = None

def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('categories',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('name', sa.String(), nullable=False),
    sa.PrimaryKeyConstraint('id')
    )
    op.create_table('products',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('name', sa.String(), nullable=False),
    sa.Column('protein', sa.Float(), nullable=False),
    sa.Column('fats', sa.Float(), nullable=False),
    sa.Column('carbohydrates', sa.Float(), nullable=False),
    sa.Column('category', sa.Integer(), nullable=True),
    sa.ForeignKeyConstraint(['category'], ['categories.id'], ondelete='RESTRICT'),
    sa.PrimaryKeyConstraint('id')
    )
    # ### end Alembic commands ###

def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('products')
    op.drop_table('categories')
    # ### end Alembic commands ###


from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
from sklearn.model_selection import train_test_split
import streamlit as st
import pickle
import pandas as pd

# Load the CSV file

X = pd.read_csv("genres.csv")

y = pd.read_csv("popularity.csv")

# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

st.title("Evaluating KNN Performance in Movie Recommender System")

# Get user input for number of neighbors
n_neighbors = st.slider("Number of neighbors:", 2, 30, 10, 1)

# Fit a KNN model to the training data
knn = KNeighborsClassifier(n_neighbors=n_neighbors)
knn.fit(X_train, y_train)

# Make predictions on the testing data
y_pred = knn.predict(X_test)

# Calculate the evaluation metrics
accuracy = accuracy_score(y_test, y_pred)
precision = precision_score(y_test, y_pred)
recall = recall_score(y_test, y_pred)
f1 = f1_score(y_test, y_pred)

# Print the evaluation metrics
st.write("Evaluation Metrics for k =", n_neighbors)
st.write("Accuracy:", accuracy)
st.write("Precision:", precision)
st.write("Recall:", recall)
st.write("F1-score:", f1)


from __future__ import annotations
from typing import Optional, NamedTuple

from ngsolve import *
from . import io
from .sensor import Sensor
from .formulations import formulation_factory, _Formulation
from .configuration import SolverConfiguration, DreAmLogger
from math import isnan

import logging
logger = logging.getLogger('DreAm.Solver')

class IterationError(NamedTuple):
    error: float
    iteration_number: Optional[int]
    time: Optional[float]

    def __repr__(self) -> str:

        error_digit = DreAmLogger._iteration_error_digit
        time_step_digit = DreAmLogger._time_step_digit

        string = f"Iteration Error: {self.error:{error_digit}e}"
        if self.iteration_number is not None:
            string += f" - Iteration Number: {self.iteration_number}"
        if self.time is not None:
            string += f" - Time Step: {self.time:.{time_step_digit}f}"

        return string

class SolverStatus:

    def __init__(self, solver_configuration: SolverConfiguration) -> None:
        self.solver_configuration = solver_configuration
        self.reset()

    @property
    def is_converged(self) -> bool:
        return self._is_converged

    @property
    def is_nan(self) -> bool:
        return self._is_nan

    @property
    def iteration_error(self) -> IterationError:
        return self._iteration_error

    @iteration_error.setter
    def iteration_error(self, value: IterationError):
        min_convergence = self.solver_configuration.convergence_criterion

        self._iteration_error = value
        self._is_converged = value.error < min_convergence

        if isnan(value.error):
            self._is_nan = True
            logger.error("Solution process diverged!")

    def reset_convergence_status(self):
        self._is_converged = False
        self._is_nan = False

    def reset(self):
        self.reset_convergence_status()
        self.iteration_error_list = []

    def check_convergence(self,
                          step_direction,
                          residual,
                          time: Optional[float] = None,
                          iteration_number: Optional[int] = None) -> None:

        error = sqrt(InnerProduct(step_direction, residual)**2)
        self.iteration_error = IterationError(error, iteration_number, time)

        if logger.hasHandlers():
            logger.info(self.iteration_error)

class CompressibleHDGSolver:

    def __init__(self, mesh: Mesh,
                 solver_configuration: SolverConfiguration,
                 directory_tree: Optional[io.ResultsDirectoryTree] = None):

        if directory_tree is None:
            directory_tree = io.ResultsDirectoryTree()

        self._formulation = formulation_factory(mesh, solver_configuration)
        self._status = SolverStatus(self.solver_configuration)
        self._sensors = []
        self._drawer = io.Drawer(self.formulation)
        self._directory_tree = directory_tree

    @property
    def formulation(self) -> _Formulation:
        return self._formulation

    @property
    def dmesh(self):
        return self.formulation.dmesh

    @property
    def mesh(self):
        return self.formulation.mesh

    @property
    def solver_configuration(self):
        return self.formulation.cfg

    @property
    def boundary_conditions(self):
        return self.formulation.dmesh.bcs

    @property
    def domain_conditions(self):
        return self.formulation.dmesh.dcs

    @property
    def sensors(self) -> list[Sensor]:
        return self._sensors

    @property
    def status(self) -> SolverStatus:
        return self._status

    @property
    def drawer(self) -> io.Drawer:
        return self._drawer

    @property
    def directory_tree(self) -> io.ResultsDirectoryTree:
        return self._directory_tree

    def setup(self, reinitialize: bool = True):

        if self.formulation.dmesh.is_grid_deformation:
            self.formulation.dmesh.set_grid_deformation()

        if reinitialize:
            self.formulation.initialize()

        self.residual = self.formulation.gfu.vec.CreateVector()
        self.temporary = self.formulation.gfu.vec.CreateVector()

        self._set_linearform()
        self._set_bilinearform()

        if reinitialize and self.domain_conditions.initial_conditions:
            self._solve_initial()

    def solve_stationary(self,
                         increment_at_iteration: int = 10,
                         increment_time_step_factor: int = 10,
                         state_name: str = "stationary",
                         stop_at_iteration: bool = False) -> bool:

        self.solver_configuration.time.simulation = 'stationary'
        max_iterations = self.solver_configuration.max_iterations

        self.status.reset()
        saver = self.get_saver()

        for it in range(max_iterations):

            self.formulation.update_gridfunctions()
            self._update_pseudo_time_step(it, increment_at_iteration, increment_time_step_factor)

            self._solve_update_step()
            self.status.check_convergence(self.temporary, self.residual, iteration_number=it)

            self.drawer.redraw()

            if stop_at_iteration:
                input("Iteration stopped. Hit any key to continue.")

            if self.status.is_nan:
                break

            self._update_solution()

            if self.status.is_converged:
                break

        for sensor in self.sensors:
            sensor.take_single_sample()

        if self.solver_configuration.save_state:
            saver.save_state(name=state_name)

        self.drawer.redraw()

        self.formulation.update_gridfunctions()

    def solve_transient(self, state_name: str = "transient",  save_state_every_num_step: int = 1):

        self.solver_configuration.time.simulation = 'transient'

        self.status.reset()
        saver = self.get_saver()

        for idx, t in enumerate(self.solver_configuration.time):
            self._solve_timestep(t)

            for sensor in self.sensors:
                sensor.take_single_sample(t)

            if self.solver_configuration.save_state:
                if idx % save_state_every_num_step == 0:
                    saver.save_state(name=f"{state_name}_{t}")

            if self.status.is_nan:
                break

    def solve_perturbation(self) -> GridFunction:

        lf = LinearForm(self.formulation.fes)
        self.formulation.add_perturbation_linearform(lf)
        perturbation_gfu = self._solve_mass(lf)
        for gfu in self.formulation.gridfunctions.values():
            gfu.vec.data += perturbation_gfu.vec

        self.drawer.redraw()
        logger.info("Perturbation applied!")
        return perturbation_gfu

    def add_sensor(self, sensor: Sensor):
        sensor.assign_solver(self)
        self.sensors.append(sensor)

    def get_saver(self, directory_tree: Optional[io.ResultsDirectoryTree] = None) -> io.SolverSaver:
        saver = io.SolverSaver(self)
        if directory_tree is not None:
            saver.tree = directory_tree
        return saver

    def get_loader(self, directory_tree: Optional[io.ResultsDirectoryTree] = None) -> io.SolverLoader:
        loader = io.SolverLoader(self)
        if directory_tree is not None:
            loader.tree = directory_tree
        return loader

    def _set_linearform(self):

        fes = self.formulation.fes
        self.f = LinearForm(fes)
        self.formulation.add_forcing_linearform(self.f)
        self.f.Assemble()

    def _set_bilinearform(self):

        fes = self.formulation.fes

        condense = self.solver_configuration.static_condensation
        mu = self.solver_configuration.dynamic_viscosity

        self.blf = BilinearForm(fes, condense=condense)

        self.formulation.add_time_bilinearform(self.blf)
        self.formulation.add_convective_bilinearform(self.blf)

        if not mu.is_inviscid:
            self.formulation.add_diffusive_bilinearform(self.blf)

        self.formulation.add_boundary_conditions_bilinearform(self.blf)
        self.formulation.add_domain_conditions_bilinearform(self.blf)

    def _solve_mass(self, linearform: LinearForm) -> GridFunction:
        formulation = self.formulation
        gfu = GridFunction(formulation.fes)

        blf = BilinearForm(formulation.fes)
        formulation.add_mass_bilinearform(blf)

        blf.Assemble()
        linearform.Assemble()

        blf_inverse = blf.mat.Inverse(formulation.fes.FreeDofs(), inverse="sparsecholesky")

        gfu.vec.data = blf_inverse * linearform.vec
        return gfu

    def _solve_initial(self):
        lf = LinearForm(self.formulation.fes)
        self.formulation.add_initial_linearform(lf)
        self.formulation.gfu.vec.data = self._solve_mass(lf).vec
        self.formulation.update_gridfunctions(initial_value=True)

    def _solve_update_step(self):

        linear_solver = self.solver_configuration.linear_solver
        fes = self.formulation.fes
        gfu = self.formulation.gfu

        self.blf.Apply(gfu.vec, self.residual)
        self.residual.data -= self.f.vec
        self.blf.AssembleLinearization(gfu.vec)

        inv = self.blf.mat.Inverse(fes.FreeDofs(self.blf.condense), inverse=linear_solver)
        if self.blf.condense:
            self.residual.data += self.blf.harmonic_extension_trans * self.residual
            self.temporary.data = inv * self.residual
            self.temporary.data += self.blf.harmonic_extension * self.temporary
            self.temporary.data += self.blf.inner_solve * self.residual
        else:
            self.temporary.data = inv * self.residual

    def _update_solution(self):
        damping_factor = self.solver_configuration.damping_factor
        gfu = self.formulation.gfu

        gfu.vec.data -= damping_factor * self.temporary

    def _update_pseudo_time_step(self,
                                 iteration_number: int,
                                 increment_at_iteration: int = 10,
                                 increment_time_step_factor: int = 10):

        cfg = self.solver_configuration.time

        max_time_step = cfg.max_step
        old_time_step = cfg.step.Get()

        if max_time_step > old_time_step:
            if (iteration_number % increment_at_iteration == 0) and (iteration_number > 0):
                new_time_step = old_time_step * increment_time_step_factor

                if new_time_step > max_time_step:
                    new_time_step = max_time_step

                cfg.step = new_time_step
                logger.info(f"Successfully updated time step at iteration {iteration_number}")
                logger.info(f"Updated time step 𝚫t = {new_time_step}. Previous time step 𝚫t = {old_time_step}")

    def _solve_timestep(self, time, stop_at_iteration: bool = False) -> bool:

        max_iterations = self.solver_configuration.max_iterations

        self.status.reset_convergence_status()

        for it in range(max_iterations):

            self._solve_update_step()
            self.status.check_convergence(self.temporary, self.residual, time, it)

            if self.status.is_nan:
                break

            self._update_solution()

            if stop_at_iteration:
                input("Iteration stopped. Hit any key to continue.")

            if self.status.is_converged:
                break

        self.formulation.update_gridfunctions()

        self.drawer.redraw()


# pip3 install transformers
# pip install -q emoji pythainlp==2.2.4 sefr_cut tinydb seqeval sentencepiece pydantic jsonlines
# pip3 install --no-deps thai2transformers==0.1.2
# pip3 install torch

from flask import Flask, jsonify, request
import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import os

labels_list = ['ถนน           ', 'ความสะอาด', 'แสงสว่าง   ', 'ความปลอดภัย', 'จราจร             ', 'อื่น ๆ      ']

app = Flask(__name__)

@app.route('/')
def index():
    return "
สวัสดี
"

@app.route('/get_label', methods=['POST'])
def get_label():
    #get data from app
    txt = request.get_json()
    msg = txt['input']
    print(msg)

    # Load the saved model
    model_path = os.path.join(os.getcwd(), 'model') # forgot change path!!!
    tokenizer = AutoTokenizer.from_pretrained(model_path)
    model = AutoModelForSequenceClassification.from_pretrained(model_path)

    # Preprocess the input text
    encoded_input = tokenizer(msg, truncation=True, padding=True, max_length=416, return_tensors='pt')

    # Make predictions
    with torch.no_grad():
        logits = model(**encoded_input).logits
        probabilities = torch.sigmoid(logits)
        probabilities = probabilities.cpu().numpy()[0]

    # Create a dictionary of labels and probabilities
    label_prob_dict = {}
    for i, label in enumerate(labels_list):
        label_prob_dict[label] = probabilities[i]

    # Sort the dictionary by probability in descending order
    label_prob_dict = {k: v/6 for k, v in sorted(label_prob_dict.items(), key=lambda item: item[1], reverse=True)}

    # Normalize the probabilities and ensure that the sum is 100
    prob_sum = sum(label_prob_dict.values())
    label_prob_dict = {k: v/prob_sum for k, v in label_prob_dict.items()}

    results = {k: round(v, 4) for k, v in label_prob_dict.items()}
    print(results)

    data = results
    response = jsonify(data)
    response.headers.add('Access-Control-Allow-Origin', '*')
    return response

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080)


from .models import Product,ProductAttribute
from django.db.models import Min,Max
def get_filters(request):
	cats=Product.objects.distinct().values('Price_range__title','Price_range__id')
	brands=Product.objects.distinct().values('brand__title','brand__id')
	colors=ProductAttribute.objects.distinct().values('color__title','color__id','color__color_code')
	sizes=ProductAttribute.objects.distinct().values('Ram_and_memory__title','Ram_and_memory__id')
	minMaxPrice=ProductAttribute.objects.aggregate(Min('price'),Max('price'))
	data={
		'cats':cats,
		'brands':brands,
		'colors':colors,
		'sizes':sizes,
		'minMaxPrice':minMaxPrice,
	}
	return data


class Solution:
    def countHighestScoreNodes(self, parents: List[int]) -> int:
        n=len(parents)
        #make dict to store all children
        children=defaultdict(list)
        for i,parent in enumerate(parents):
            children[parent].append(i)

        best=-1
        bestn=0

        #find number of nodes in subtree and multiply it with the remaining nodes
        def helper(node):
            nonlocal best
            nonlocal bestn
            total=1
            product=1
            for child in children[node]:
                x=helper(child)
                product*=x
                total+=x
            if n-total>0:
                product*=n-total
            if product==best:
                bestn+=1
            if product>best:
                best=product
                bestn=1
            return total

        helper(0)
        return bestn


import os
import shutil

java_spring = "/\\192.168.0.113\\Video2\\jike\\107-小马哥讲Spring核心编程思想\\1-99"

test ="C:\\Users\\charl\\Desktop\\mp3"

all_pdf = "/\\192.168.0.113\\Video2"

all_pdf2 = "C:\\Users\\charl\\Desktop\\80-网络编程实战"

target ="C:\\Users\\charl\\Desktop\\mp3"

def  allfiles(path):
    for filename in os.listdir(path):
        f = os.path.join(path,filename)
        if os.path.isfile(f):
            if f.__contains__(".mp3"):
                print(filename)
        elif os.path.isdir(f):
            allfiles(f)

# allfiles(all_pdf2)

def copy_file(src,target,filename):
    path = os.path.join(target,filename)
    shutil.copy(src,path)


# -*- coding: utf-8 -*-
'''
eventsync.redmine.issues.py
Created on 18.03.2013
@author: escaP

Issue handling on the side of Redmine, building upon the basic redmine API.
'''
import logging
import string
from .redmineapi import Issue, Tracker, IssueStatus
from eventsync.redmine.resourceaddons import custom_fields
from dateutil.rrule import rrule, WEEKLY, MONTHLY, DAILY
from eventsync.redmine.localsettings import READABLE_DATE_FORMAT, READABLE_TIME_FORMAT

logg = logging.getLogger(__name__)

# maybe find a better way to cache these API objects
tracker_termin = Tracker.find_first_by_name("Termin")
tracker_termin_ext = Tracker.find_first_by_name("Termin extern")
tracker_template = Tracker.find_first_by_name("Terminvorlage")

def _make_time_constraint(start_dt=None, end_dt=None):
    start_timestr = start_dt.strftime("%Y-%m-%d") if start_dt else "1970-01-01"
    end_timestr = end_dt.strftime("%Y-%m-%d") if end_dt else "2037-12-31"
    if start_dt or end_dt:
        redmine_time_constraint = "><{}|{}".format(start_timestr, end_timestr)
        logg.debug("time constraints given, start %s end %s, encoded %s", start_timestr, end_timestr, redmine_time_constraint)
        return redmine_time_constraint
    else:
        return None

def get_event_issues(fetch_closed=False, start_dt=None, end_dt=None):
    """Fetch event issues from redmine server updated in a given time span
    ]start_dt, end_dt[.
    If no parameter is given, all issues are fetched.

    :param fetch_closed: Redmine fetches open issues by default, also get closed ones when True.
    :param start_dt: datetime which marks the start of the time interval
    :param end_dt: datetime, end of the time interval
    """
    fargs = {}
    time_constraint = _make_time_constraint(start_dt, end_dt)
    if fetch_closed:
        fargs["status_id"]= "*"
    if time_constraint:
        fargs["updated_on"] = time_constraint
    termine = Issue.find(tracker_id=tracker_termin.id, **fargs)
    termine_ext = Issue.find(tracker_id=tracker_termin_ext.id, **fargs)
    return termine + termine_ext

def get_cancelled_issues(start_dt=None, end_dt=None):
    """Fetch cancelled issues from redmine server updated in a given time span
    ]start_dt, end_dt[.
    If no parameter is given, all issues are fetched.

    :param start_dt: datetime which marks the start of the time interval
    :param end_dt: datetime, end of the time interval
    """
    fargs = {}
    time_constraint = _make_time_constraint(start_dt, end_dt)
    if time_constraint:
        fargs["updated_on"] = time_constraint
    cancelled_status_id = next(IssueStatus.filter(lambda s: s.name == "Abgesagt")).id
    c_termine = Issue.find(tracker_id=tracker_termin.id, status_id=cancelled_status_id, **fargs)
    c_termine_ext = Issue.find(tracker_id=tracker_termin_ext.id, status_id=cancelled_status_id, **fargs)
    return c_termine + c_termine_ext

def get_event_templates(start_dt=None, end_dt=None):
    """Fetch event template issues from redmine server created in a given time span
    ]start_dt, end_dt[.
    If no parameter is given, all issues are fetched.

    :param start_dt: datetime which marks the start of the time interval
    :param end_dt: datetime, end of the time interval
    """
    fargs = {}
    time_constraint = _make_time_constraint(start_dt, end_dt)
    if time_constraint:
        fargs["created_on"] = time_constraint
    event_templates = Issue.find(tracker_id=tracker_template.id,  **fargs)
    return event_templates

def create_rrule_from_issue(issue_template):
    """Create a rrule from an event template issue."""
    start_dt = issue_template.start_date
    end_dt = issue_template.due_date

    opts = {
        "Jede Woche": dict(freq=WEEKLY, byweekday=start_dt.weekday()),
        "Tag im Monat": dict(freq=MONTHLY, bymonthday=start_dt.day),
        "Abstand in Tagen": dict(freq=DAILY, interval=issue_template.intervall),
        "Abstand in Wochen": dict(freq=WEEKLY, interval=issue_template.intervall),
        "1. Wochentag im Monat": dict(freq=MONTHLY, byweekday=start_dt.weekday(), bysetpos=1),
        "2. Wochentag im Monat": dict(freq=MONTHLY, byweekday=start_dt.weekday(), bysetpos=2),
        "3. Wochentag im Monat": dict(freq=MONTHLY, byweekday=start_dt.weekday(), bysetpos=3),
        "4. Wochentag im Monat": dict(freq=MONTHLY, byweekday=start_dt.weekday(), bysetpos=4),
    }
    chosen_opts = opts[issue_template.wiederholungsart]
    return rrule(dtstart=start_dt, until=end_dt, **chosen_opts)

def new_issue_from_template(issue_template):
    custom_fields = list(filter(lambda cf: cf.name.lower() not in ["intervall", "wiederholungsart", "terminart"], issue_template.custom_fields))
    logg.info("custom fields: %s, %s", custom_fields ,[(cf.name, cf.value) for cf in custom_fields])
    issue = Issue(dict(custom_fields=custom_fields))
    # XXX: works better when we assign it again, don't ask me why...
    issue.custom_fields = custom_fields
    issue.project_id = issue_template.project.id
    if issue_template.terminart == "Termin":
        issue.tracker_id = tracker_termin.id
    elif issue_template.terminart == "Termin":
        issue.tracker_id = tracker_termin_ext.id
    else:
        raise Exception("Whoops, not possible ;)")
    logg.info("issue created: %s", issue)
    logg.info("dict: %s", issue.__dict__)
    return issue

def create_issues_from_template(issue_template):
    rrule = create_rrule_from_issue(issue_template)
    subject_tmpl = string.Template(issue_template.subject)
    description_tmpl = string.Template(issue_template.description)
    created_issues = []
    for dt in rrule:
        issue = new_issue_from_template(issue_template)
        readable_date_str = dt.strftime(READABLE_DATE_FORMAT)
        custom_fields = {k: cf.value for k, cf in issue._custom_fields.items()}
        logg.info("custom_fields %s", custom_fields)
        issue.subject = subject_tmpl.substitute(datum=readable_date_str, **custom_fields)
        issue.description = description_tmpl.substitute(datum=readable_date_str, **custom_fields)
        issue.start_date = dt
        issue.due_date = dt
        logg.info("creating issue from template %s", issue.attributes)
        created_issues.append(issue)

    return created_issues


#!/usr/bin/env python3

"""Generators for the `gKmg` Clustering Datasets

Copyleft (C) 2018-2022, Marek Gagolewski <https://www.gagolewski.com>

A generalised version of SIPU's G2 sets
(see https://cs.joensuu.fi/sipu/datasets/G2.txt),
but with a correction for dimensionality.

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""

#%%
import numpy as np
import scipy.spatial.distance

#%%
def generate_gKmg(d, n, mu, s, random_state=None):
    """Generates K=len(n) groups of points in R^d together with their
    corresponding labels.

    The i-th group, i=1,...,K, consists of n[i-1] points
    that are sampled from the Gaussian distribution with mean mu[i-1,:]
    and covariance matrix diag(s[i]).
    """
    assert mu.shape[0] == n.shape[0] == s.shape[0]
    assert mu.shape[1] == d
    assert (s>0).all()
    assert (n>0).all()

    K = mu.shape[0] # number of groups

    if random_state is None:
        random_state = np.random.randint(0, 2**32)

    # Each point group is generated separately,
    # with different (yet predictable) random_state,
    # so that changing n[i] generates the same points

    X = []
    for i in range(K):
        rand = np.random.RandomState((random_state+i) % (2**32))
        X.append(rand.randn(n[i], d)*s[i] + mu[i,:])

    X = np.vstack(X)

    labels0 = np.repeat(np.arange(1, K+1), n) #[1,1,...,1,2,...,2,...,K,...,K]

    labels1 = np.argmax(scipy.spatial.distance.cdist(X, mu), axis=1)+1

    return X, labels0, labels1

#%%
# import matplotlib.pyplot as plt
# import genieclust
# random_state = 666
# mu1 = 500  # cluster1 center
# mu2 = 600  # cluster2 center
# d = 2
# s = 10
# s_cor = s*d

# for n  in [30, 50]:
#     X, labels = generate_gKmg(
#         d,
#         np.r_[n, n],
#         np.array([ [mu1]*d, [mu2]*d ]),
#         np.r_[s_cor, s_cor],
#         random_state)
#     genieclust.plots.plot_scatter(X, labels+n-30, alpha=0.5)

# plt.show()

#%%
if __name__ == "__main__":

    # This is how we generate the (perfectly balanced) g2mg sets
    # included in the Benchmark Suite.

    random_state = 123 # one of few unsuspicious RNG seeds :) [*]
    mu1 = 500  # cluster1 centre
    mu2 = 600  # cluster2 centre
    n   = 1024 # number of points in each cluster
    Ds = [2**k for k in range(0, 8)] # [1, 2, 4, ..., 128]
    Ss = list(range(10, 100, 10))     # [10, 20, ..., 90]

    for d in Ds:
        for s in Ss:
            base_name = "g2mg/g2mg_%d_%s"%(d,s)
            print(base_name)
            s_cor = s*np.sqrt(d/2)
            X, labels0, labels1 = generate_gKmg(
                d,
                np.r_[n, n],
                np.array([ [mu1]*d, [mu2]*d ]),
                np.r_[s_cor, s_cor],
                random_state)

            data_file = base_name+".data.gz"
            # round -> no "." -> reduced file size
            np.savetxt(data_file, np.round(X, 0), fmt="%d")

            labels0_file = base_name+".labels0.gz"
            np.savetxt(labels0_file, labels0, fmt="%d")

            labels1_file = base_name+".labels1.gz"
            np.savetxt(labels1_file, labels1, fmt="%d")

            readme_file = base_name+".txt"
            readme = """\
g2mg clustering benchmark
Two %d-dimensional clusters, each with %d points that have
i.i.d. Gaussian components with standard deviation %d*sqrt(%d/2).

Author: Marek Gagolewski (http://www.gagolewski.com)
Copyleft 2020
Licensed under the Creative Commons Attribution 4.0 International License

`labels0` gives reference labels based on which probability distribution's
mixture component was used to generate the corresponding points.
`labels1` gives reference labels based on the distance to
the true cluster centre (i.e., arg max_ p_i(x)).
There is no noise class.
""" % (d, n, s, d)
            with open(readme_file, "w") as f:
                f.write(readme)

    # [*] the other ones being 42, 666, 1234, 12345, and 123456.
    # EOF.


import time
import datetime
from unittest import TestCase
from models import ShortUrls

class TestCreateShortUrl(TestCase):
    def test_create_short_url(self):
        short_url = ShortUrls.create_short_url(
            "https://www.canada.ca", "test1234", "actor"
        )
        assert short_url == "test1234"

    def test_create_short_url_with_existing_url__returns_same_shorten_url(self):
        url_a = ShortUrls.create_short_url("https://www.canada.ca", "test1234", "actor")
        url_b = ShortUrls.create_short_url("https://www.canada.ca", "test1234", "actor")
        assert url_a == url_b

    def test_get_short_url(self):
        ShortUrls.create_short_url("https://www.canada.ca", "test", "actor")
        short_url = ShortUrls.get_short_url("test")
        assert short_url["original_url"]["S"] == "https://www.canada.ca"
        assert short_url["created_by"]["S"] == "actor"
        assert short_url["click_count"]["N"] == "0"
        short_url = ShortUrls.get_short_url("test")
        assert short_url["click_count"]["N"] == "1"
        short_url = ShortUrls.get_short_url("test")
        assert short_url["click_count"]["N"] == "2"

    def test_update_last_access_at(self):
        """Test that we are setting the last_access_date properly and it is being updated each time the shortned url is retrieved"""
        ShortUrls.create_short_url("https://www.canada.ca", "xyz", "actor")
        time.sleep(1)
        short_url = ShortUrls.get_short_url("xyz")
        assert short_url["last_access_date"]["N"] == short_url["created_at"]["N"]
        short_url = ShortUrls.get_short_url("xyz")
        time.sleep(1)
        assert short_url["last_access_date"]["N"] != short_url["created_at"]["N"]
        previous_last_access_date = int(short_url["last_access_date"]["N"])
        short_url = ShortUrls.get_short_url("xyz")
        assert short_url["last_access_date"]["N"] != previous_last_access_date

    def test_update_ttl_time(self):
        """Test that we are setting the ttl properly and it is being updated each time the shortned url is retrieved"""
        ShortUrls.create_short_url("https://www.canada.ca", "abc", "actor")
        time.sleep(1)
        short_url = ShortUrls.get_short_url("abc")
        previous_ttl = int(short_url["ttl"]["N"])
        short_url = ShortUrls.get_short_url("abc")
        assert short_url["ttl"]["N"] != str(previous_ttl)

    def test_ttl_is_valid(self):
        short_url = ShortUrls.get_short_url("test")
        epoch_time_now = int(time.time())
        assert int(short_url["ttl"]["N"]) > epoch_time_now

    def test_ttl_is_invalid(self):
        future_epoch_time = int(
            time.mktime(
                (
                    datetime.datetime.today() + datetime.timedelta(days=(365 * 5))
                ).timetuple()
            )
        )
        short_url = ShortUrls.get_short_url("test")
        assert short_url["ttl"]["N"] < str(future_epoch_time)

    def test_create_short_url_with_different_url_but_same_hash__raises_value_error_for_collision(
        self,
    ):
        with self.assertRaises(ValueError):
            ShortUrls.create_short_url("https://www.canada.ca", "test1234", "actor")
            ShortUrls.create_short_url("https://nrc.gc.ca", "test1234", "actor")


# -*- coding: utf-8 -*-
# @Author: ZhuZefeng
# @Date:   2018-12-20 17:56:56
# @Last Modified by:   ZhuZefeng
# @Last Modified time: 2018-12-27 11:46:35

"""
为应用程序accounting定义URL模式
"""

from django.urls import path, re_path
from .           import views

app_name = 'accounting'

urlpatterns = [
               #accounting程序的主页
               path('', views.index, name='index'),

               #显示所有销售订单的页面
               path('orders', views.orders, name='orders'),

               #新增销售订单的页面
               path('new_order', views.new_order, name='new_order'),

               #显示所有客户信息的页面
               path('clients', views.clients, name='clients'),

               #新增客户的页面
               path('new_client', views.new_client, name='new_client'),

               #显示所有产品信息的页面
               path('products', views.products, name='products'),

               #新增产品的页面
               #path('new_product', views. new_product, name=' new_product'),

              ]


class Solution:
    def arrayPairSum(self, nums):
        nums = sorted(nums)

        s = 0
        idx = len(nums)/2
        for i in range(int(idx)):
            s += nums[i * 2]
        return s
        """
        :type nums: List[int]
        :rtype: int
        """


from unittest import mock

import nicolas.formatting

@mock.patch("shutil.get_terminal_size")
def test_that_header_returns_full_terminal_width(terminal_size_mock):
    expected_columns = 80
    test_text = "Test"

    terminal_size_mock.return_value = (expected_columns, 24)
    output = nicolas.formatting.header(test_text)

    assert test_text in output
    assert all(len(line) is expected_columns for line in output.splitlines())

@mock.patch("shutil.get_terminal_size")
def test_that_header_returns_full_terminal_width_with_odd_input(
        terminal_size_mock):
    expected_columns = 80
    test_text = "Testing"

    terminal_size_mock.return_value = (expected_columns, 24)
    output = nicolas.formatting.header(test_text)

    assert test_text in output
    assert all(len(line) is expected_columns for line in output.splitlines())

def test_that_tabbed_returns_with_values_alligned():
    data = {"x": "data", "yy": "data!!"}
    spaces = 4

    result = nicolas.formatting.tabbed(data, spacing=spaces)

    assert result.splitlines()[0].count(" ") == 5
    assert result.splitlines()[-1].count(" ") == 4


from django.shortcuts import get_object_or_404, render, redirect
from django.template.loader import render_to_string
from django.http import HttpResponseRedirect, JsonResponse
from django.urls import reverse_lazy

from django.views.generic import TemplateView, ListView, DetailView, CreateView, View

from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib import messages

from .models import Article, Review
from quizes.models import Quiz
from .service import (
        add_like_to_the_article,
        add_dislike_to_the_article,
        add_like_to_the_article_review,
        add_dislike_to_the_article_review,
)

from .forms import ReviewForm, ReplyToReviewForm

class ArticlesListView(ListView):
    model = Article
    template_name = 'articles/view_articles.html'
    context_object_name = 'articles'

class SearchArticle(View):
    def get(self, request):
        name_of_necessary_article = request.GET.get('search')
        articles = Article.objects.filter(title__icontains=name_of_necessary_article)
        if articles:
            return render(request, 'articles/view_articles.html', {'articles':articles})

        messages.error(request, 'Нет подходящих результатов.')
        return HttpResponseRedirect(reverse_lazy('articles:view-articles'))

class ViewArticle(DetailView):
    model = Article
    template_name = 'articles/view_article.html'
    context_object_name = 'article'
    slug_field = 'slug'
    slug_url_kwarg = 'article_slug'

    def get_context_data(self, **kwargs):
        """Adding the Review form and Reviews"""
        context = super().get_context_data(**kwargs)
        article = context.get('article')

        # Adding article reviews
        reviews = Review.objects.filter(article=article).order_by('-date_of_creating')
        context['reviews'] = reviews

        quizes = Quiz.objects.get()

        # Adding review form
        form = ReviewForm()
        reply_form = ReplyToReviewForm()
        context['form'] = form
        context['reply_form'] = reply_form
        return context

class ViewQuizToArticle(LoginRequiredMixin, View):
    def post(self, request, template_name='quizes/create_quiz.html'):
        form = QuizForm(request.POST)

        if form.is_valid():
            try:
                context = get_questions(request, form)
            except ValueError as e:
                messages.error(self.request, e)
                return render(request, template_name, {'form': form})
            return render(request, template_name='quizes/created_quiz.html', context=context)
        return render(request, template_name, {'form': form})

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        return context

class AddLikeToArticle(LoginRequiredMixin, View):
    def post(self, request, article_slug, *args, **kwargs):
        article = get_object_or_404(Article, slug=article_slug)
        add_like_to_the_article(request, article)
        return redirect(reverse_lazy('articles:view-article', args=[str(article.slug)]) + f'#likes_and_dislikes_for_article_{article.slug}')

class AddDislikeToArticle(LoginRequiredMixin, View):
    def post(self, request, article_slug, *args, **kwags):
        article = get_object_or_404(Article, slug=article_slug)
        add_dislike_to_the_article(request, article)
        return redirect(reverse_lazy('articles:view-article', args=[str(article.slug)]) + f'#likes_and_dislikes_for_article_{article.slug}')

class AddReviewToArticle(LoginRequiredMixin, CreateView):
    model = Review
    form_class = ReviewForm

    def post(self, request, article_slug):
        article = get_object_or_404(Article, slug=article_slug)
        user = request.user

        form = ReviewForm(request.POST)
        if form.is_valid():
            review = form.save(commit=False)
            review.article = article
            review.user = user
            review.save()

        return HttpResponseRedirect(reverse_lazy('articles:view-article', args=[str(article.slug)])+ f'#comment_{review.pk}')

class ReplyToReview(LoginRequiredMixin, CreateView):
    model = Review
    form_class = ReplyToReviewForm

    def post(self, request, article_slug, review_pk):
        article = get_object_or_404(Article, slug=article_slug)
        parent_review = get_object_or_404(Review, pk=review_pk)
        user = request.user

        form = ReplyToReviewForm(request.POST)
        if form.is_valid():
            review = form.save(commit=False)
            review.article = article
            review.user = user
            review.parent = parent_review
            review.save()
        return redirect(reverse_lazy('articles:view-article', args=[str(article.slug)]) + f'#comment_{review.pk}')

class AddLikeToReview(LoginRequiredMixin, View):
    def post(self, request, article_slug, review_pk, *args, **kwargs):
        article = get_object_or_404(Article, slug=article_slug)
        review = get_object_or_404(Review, pk=review_pk)
        add_like_to_the_article_review(request, review)
        return redirect(reverse_lazy('articles:view-article', args=[str(article.slug)]) + f'#comment_{review.pk}')

class AddDislikeToReview(LoginRequiredMixin, View):
    def post(self, request, article_slug, review_pk):
        article = get_object_or_404(Article, slug=article_slug)
        review = get_object_or_404(Review, pk=review_pk)
        add_dislike_to_the_article_review(request, review)
        return redirect(reverse_lazy('articles:view-article', args=[str(article.slug)]) + f'#comment_{review.pk}')