import os
from models.detector import Detector
from pycocotools.cocoeval import COCOeval
import pycocotools.coco as coco
import pycocotools.mask as mask_util
import numpy as np
from tqdm import tqdm
from config import cfg as opt
os.environ['CUDA_VISIBLE_DEVICES'] = '3'
valid_ids = [
            1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13,
            14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
            24, 25, 27, 28, 31, 32, 33, 34, 35, 36,
            37, 38, 39, 40, 41, 42, 43, 44, 46, 47,
            48, 49, 50, 51, 52, 53, 54, 55, 56, 57,
            58, 59, 60, 61, 62, 63, 64, 65, 67, 70,
            72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
            82, 84, 85, 86, 87, 88, 89, 90]

## config recover weights
opt.weights = 'exp/coco_person/model_last.pth'
opt.vis_trehs = 0.01
split = 'val'

detector = Detector(opt)
data = coco.COCO(os.path.join(
            opt.data_dir, 'annotations',
            'instances_{}2017.json').format(split))

if opt.class_name!='*' :  ## for one class
    catIds = data.getCatIds(opt.class_name)
    imgIds = data.getImgIds(catIds=catIds)
    valid_ids = catIds

detections = []
for img_id in tqdm(data.getImgIds()):
    img_name = os.path.join(os.path.join(opt.data_dir, '{}2017'.format(split)),
                            data.loadImgs(ids=[img_id])[0]['file_name']).strip()
    boxs,masks = detector.run(img_name,vis=False)
    for i,det in enumerate(boxs):
        x, y, x1, y1, conf, cls = det[:6]
        detection = {
            "image_id": img_id,
            "category_id": int(valid_ids[int(cls)]),
            'segmentation':mask_util.encode(np.asfortranarray(masks[i])),
            #"bbox": [x, y, x1 - x, y1 - y],
            "score": float("{:.2f}".format(conf))
        }
        detections.append(detection)
coco_dets = data.loadRes(detections)
coco_eval = COCOeval(data, coco_dets, "segm")

if opt.class_name!='*':  ## for one class
    coco_eval.params.imgIds = imgIds
    coco_eval.params.catIds = catIds

coco_eval.evaluate()
coco_eval.accumulate()
coco_eval.summarize()


# selecting a Data-Structure to handle images effeciently
import numpy as np

# For handling the Folder/Files Structure
import os

# Reading images and performing Image processing
import cv2
from PIL import Image
import tensorflow as tf

# visualizing the images
from matplotlib import pyplot as plt
plt.switch_backend('Agg')

# GAN model
import tensorflow_hub as hub

# miscellaneous purpose
import math
import time
from skimage.metrics import structural_similarity as ssim

# SAVED_MODEL_PATH = "https://tfhub.dev/captain-pool/esrgan-tf2/1"
SAVED_MODEL_PATH = "esrgan-tf2_1"
model = hub.load(SAVED_MODEL_PATH)

def psnr(target, ref):
    """define a function for peak signal-to-noise ratio (PSNR)"""
    # assume RGB image
    target_data = target.astype(float)
    ref_data = ref.astype(float)

    diff = ref_data - target_data
    diff = diff.flatten('C')

    rmse = math.sqrt(np.mean(diff ** 2.))

    return 20 * math.log10(255. / rmse)

def mse(target, ref):
    """define function for mean squared error (MSE)"""
    # the MSE between the two images is the sum of the squared difference between the two images
    err = np.sum((target.astype('float') - ref.astype('float')) ** 2)
    err /= float(target.shape[0] * target.shape[1])
    return err

def compare_images(target, ref):
    """define function that combines all three image quality metrics"""
    un_changed = "Shape: "+str(target.shape)+"\n"+"D-Type: "+str(target.dtype)
    # ref = cv2.resize(ref,(target.shape[1],target.shape[0]))
    target = cv2.resize(target,(ref.shape[1],ref.shape[0]))
    return  f'PSNR: {psnr(target,ref)}\nMSE: {mse(target,ref)}\nSSIM: {ssim(target, ref, multichannel =True)}\n{un_changed}'

def image_preparation_for_model(image=None, path=None):
    ''' Function to read image and prepare it for the model
     to predict the super resolution image as an output'''
    if path:
        hr_image = cv2.imread(path)
        hr_image = cv2.cvtColor(hr_image,cv2.COLOR_BGR2RGB)
    else:
        hr_image = image

    hr_size = (np.array(hr_image.shape[:-1]) // 4) * 4

    hr_image = tf.image.crop_to_bounding_box(hr_image, 0, 0, hr_size[0], hr_size[1])
    hr_image = tf.cast(hr_image, tf.float32)
    hr_image = tf.expand_dims(hr_image, 0)

    return hr_image

def convert_to_viewable_image(nd_image):
    image_array = tf.squeeze(nd_image)
    image_array = np.clip(image_array, a_min = 0, a_max = 255)
    return image_array.astype("uint8")

def downscale_image(image):
    """
      Scales down images using bicubic downsampling.
      Args:
          image: 3D or 4D tensor of preprocessed image
    """
    image_size = []
    if len(image.shape) == 3:
        image_size = [image.shape[1], image.shape[0]]
    else:
        raise ValueError("Dimension mismatch. Can work only on single image.")

    image = tf.squeeze(tf.cast(tf.clip_by_value(image, 0, 255), tf.uint8))

    lr_image = np.asarray(Image.fromarray(image.numpy()).resize([image_size[0] // 4, image_size[1] // 4],Image.BICUBIC))
    lr_image = tf.expand_dims(lr_image, 0)
    lr_image = tf.cast(lr_image, tf.float32)
    return lr_image

def predict_normal(image_path,file_name):
    original_image = cv2.imread(image_path)
    original_image = cv2.cvtColor(original_image,cv2.COLOR_BGR2RGB)

    plt.figure(figsize=(15, 10))

    plt.subplot(1,2,1)
    plt.imshow(original_image)
    plt.title("ORIGINAL IMAGE",size=15,weight="bold")
    text = "Shape: "+str(original_image.shape)+"\n"+"D-Type: "+str(original_image.dtype)
    plt.xlabel(text,size=15,weight="bold")

    plt.subplot(1,2,2)
    processed_image = image_preparation_for_model(path=image_path)
    GAN_output = model(processed_image)
    gan_out = convert_to_viewable_image(GAN_output)
    plt.imshow(gan_out)
    plt.title("SUPER RESOLUTION IMAGE",size=15,weight="bold")
    plt.xlabel(compare_images(gan_out,original_image),size=15,weight="bold")

    plt.tight_layout()
    plt.savefig(file_name, bbox_inches="tight")
    plt.show()

def predict_degrade(image_path,file_name):
    original_image = cv2.imread(image_path)
    original_image = cv2.cvtColor(original_image,cv2.COLOR_BGR2RGB)

    plt.figure(figsize=(15, 10))

    plt.subplot(1,3,1)
    plt.imshow(original_image)
    plt.title("ORIGINAL IMAGE",size=15,weight="bold")
    text = "Shape: "+str(original_image.shape)+"\n"+"D-Type: "+str(original_image.dtype)
    plt.xlabel(text,size=15,weight="bold")
    plt.ioff()

    plt.subplot(1,3,2)
    degraded_image = downscale_image(original_image)
    d_img = convert_to_viewable_image(degraded_image)
    plt.imshow(d_img)
    plt.title("DRGRADED IMAGE",size=15,weight="bold")
    plt.xlabel(compare_images(d_img,original_image),size=15,weight="bold")
    plt.ioff()

    plt.subplot(1,3,3)
    GAN_output = model(degraded_image)
    gan_out = convert_to_viewable_image(GAN_output)
    plt.imshow(gan_out)
    plt.title("SUPER RESOLUTION IMAGE",size=15,weight="bold")
    plt.xlabel(compare_images(gan_out,original_image),size=15,weight="bold")
    plt.ioff()

    plt.tight_layout()
    plt.savefig(file_name, bbox_inches="tight")


import json
import typing
from datetime import datetime

from src import db
from src.sender import send_to_email, send_to_bot, send_to_rabbit_mq
from src.utils import utils

async def search_by_ref_code(referrer: str, user_id: int, lvl: int = 1) -> bool:
    """
    This function adds levels to each referral.
    :param referrer: The referral code of the invitee
    :param user_id: New user ID
    :param lvl: Its hierarchy level. Only 4 lvl
    """
    result = await db.get_referrer_by_referral_code(referral=referrer)
    ref_users = json.loads(result["ref_users"])
    for key, value in ref_users.items():
        if utils.is_there_user(ref_user=value, user_id=user_id):
            return True
    if lvl >= 4:
        ref_users["lvl_4"].append({
            "user_id": user_id,
            "time": utils.get_datetime_now()
        })
    else:
        ref_users[f"lvl_{lvl}"].append({
            "user_id": user_id,
            "time": utils.get_datetime_now()
        })
    status = await db.update_referral_lvl_by_user_id(
        user_id=user_id,
        ref_users=json.dumps(ref_users)
    )
    if status is None:
        raise Exception("Not add referral")
    if result["referrer"] is not None:
        return await search_by_ref_code(referrer=result["referrer"], user_id=user_id, lvl=lvl + 1)
    return True

async def get_user_information(user_id: int, username: str) -> typing.Dict:
    """Returns all information about the user"""
    referral_info = await db.get_referral_info_by_user_id(user_id=user_id)
    return {
        "id": user_id,
        "username": username,
        "datetime": datetime.fromtimestamp(int(referral_info["reg_time"]) / 1000),
        "timestamp": referral_info["reg_time"],
        "referral_code": referral_info["referral_code"],
        "referrer": referral_info["referrer"],
        "ref_users": referral_info["ref_users"]
    }

async def send_to(username: str, email: str, referral_code: str, referrer: str = None):
    await send_if_new(username=username, email=email, referral_code=referral_code, referrer=referrer)
    if referrer:
        await if_not_new(referrer=referrer, new_user=username)

async def send_if_new(username: str, email: str, referral_code: str, referrer: str = None) -> None:
    await send_to_rabbit_mq(
        message=json.dumps(
            {
                "status": 1,   # if 1 that new user
                "username": username,
                "email": email,
                "referralCode": referral_code,
                "referrer": referrer
            }
        )
    )
    await send_to_bot(
        message=(
            "New user\n"
            f"Username: {username}\n"
            f"Email: {email}\n"
            f"Referral code: {referral_code}\n"
            f"Referrer: {referrer if referrer is not None else 'Missing'}"
        )
    )
    await send_to_email(
        subject=f"Welcome '{username}' to our referral system!!!",
        message=f"Your referral code: {referral_code}\n{f'You have been acclaimed: {referrer}' if referrer is not None else ''}",
        email=email
    )

async def send_if_not_new(owner_email: str, owner_username: str, lvl: int, new_user: str) -> None:
    await send_to_email(
        subject=f"Hello, {owner_username}, you have a new referral!!!",
        message=f"Level: {lvl}\nUsername: {new_user}",
        email=owner_email
    )

async def if_not_new(referrer: str, new_user: str, lvl: int = 1) -> bool:
    result = await db.get_username_by_referral_code(referrer=referrer)
    ref_users = json.loads(result["ref_users"])
    if lvl >= 4:
        await send_if_not_new(
            owner_email=result["email"],
            owner_username=result["username"],
            lvl=4,
            new_user=new_user
        )
    else:
        await send_if_not_new(
            owner_email=result["email"],
            owner_username=result["username"],
            lvl=lvl,
            new_user=new_user
        )
    if result["referrer"] is not None:
        return await if_not_new(referrer=result["referrer"], new_user=new_user, lvl=lvl+1)
    return True


import configparser
import os

def hex_to_rgba_01(value):
    value = value.lstrip('#')
    lv = len(value)
    r, g, b = tuple(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3))
    r /= 255
    g /= 255
    b /= 255
    a = 1
    return [r, g, b, a]

class themeConfig:
    def __init__(self):
        settings = configparser.ConfigParser()
        settings.read("settings.ini")
        self.theme_folder = settings["THEME"]["theme"]
        self.theme = configparser.ConfigParser()

    def read_theme(self):
        theme_file = os.path.join("themes", self.theme_folder, "theme.ini")
        self.theme.read(theme_file)
        #colors
        self.color_wrong = hex_to_rgba_01(self.theme["COLORS"]["wrong"])
        self.color_right = hex_to_rgba_01(self.theme["COLORS"]["right"])
        self.color_neutral = hex_to_rgba_01(self.theme["COLORS"]["neutral"])
        self.color_neutral_muted = hex_to_rgba_01(self.theme["COLORS"]["neutral_muted"])
        self.color_background = hex_to_rgba_01(self.theme["COLORS"]["background"])

        #fonts
        self.font_info = os.path.join("themes", self.theme_folder, "fonts", self.theme["FONTS"]["info"])
        self.font_math = os.path.join("themes", self.theme_folder, "fonts", self.theme["FONTS"]["math"])
        self.font_math_italic = os.path.join("themes", self.theme_folder, "fonts", self.theme["FONTS"]["math_italic"])


import cv2
import os
from concurrent.futures import ThreadPoolExecutor
import sys
import getopt
import subprocess
from numpy import arange
from itertools import repeat
import moviepy.editor as editor

def Worker(a_InputFile, a_OutputFileName, a_Scale, a_FrameChunkCount, a_CurrID, a_TotalFrameCount):
    print("Starting processing on chunk", a_CurrID)
    BeginFrame = a_CurrID * a_FrameChunkCount + 1
    if a_CurrID == 0:
        BeginFrame = 0

    EndFrame = a_FrameChunkCount + (a_FrameChunkCount * a_CurrID)
    if EndFrame + 1 == a_TotalFrameCount:
        EndFrame += 1

    if EndFrame > a_TotalFrameCount:
        EndFrame = a_TotalFrameCount

    Cmd = ('veai.exe -i "' + a_InputFile + '" '
              '-o "' + os.path.dirname(os.path.abspath(a_InputFile)) + '\\' + a_OutputFileName + '_' + str(a_CurrID) + '.mp4" '
              '-f mp4 '
              '-m ghq-1.0.1 '
              '-s ' + str(a_Scale) + ' '
              '-c ' + str(a_CurrID) + ' '
              '-b ' + str(int(BeginFrame)) + ' '
              '-e ' + str(int(EndFrame)))

    Status = subprocess.call(Cmd, shell=True)
    print("Processing finished on chunk", a_CurrID)
    return Status

def Process(a_InputFile, a_OutputFileName, a_Scale, a_GPUCount, a_ConcatenateVids):
    if not os.path.exists('C:\\Program Files\\Topaz Labs LLC\\Topaz Video Enhance AI'):
        print("Topaz Video Enhance AI was not found on your system.")
        return

    os.chdir('C:\\Program Files\\Topaz Labs LLC\\Topaz Video Enhance AI')
    Capture = cv2.VideoCapture(a_InputFile)
    if Capture.isOpened() is False:
        print("Video stream could not be opened.")
        return

    FrameCount = int(Capture.get(cv2.CAP_PROP_FRAME_COUNT)) - 1
    print("Video frame count:", FrameCount)

    ChunkSize = float(FrameCount) / a_GPUCount
    ChunkSize = int(abs(ChunkSize))
    print("Chunk processing size:", ChunkSize)

    IDs = arange(0, a_GPUCount)
    print("Executing upscaling, this may take a while...")
    with ThreadPoolExecutor(max_workers=a_GPUCount) as Exec:
        Results = Exec.map(Worker, repeat(a_InputFile), repeat(a_OutputFileName),
                           repeat(a_Scale), repeat(ChunkSize), IDs, repeat(FrameCount))

    Success = True
    for Result in Results:
        if Result != 0:
            Success = False
            break

    if not Success:
        print("Upscaling failed.")
        return
    else:
        print("Upscaling successful")

    if a_ConcatenateVids:
        print("Concatenating chunks into single video file...")
        os.chdir(os.path.dirname(os.path.abspath(a_InputFile)) + '\\')
        Videos = []
        for Index in range(0, a_GPUCount):
            Videos.append(editor.VideoFileClip(a_OutputFileName + '_' + str(Index) + '.mp4'))

        FinalVideo = editor.concatenate_videoclips(Videos)
        FinalVideo.write_videofile(a_OutputFileName + '_' + 'Final.mp4')
        print("Done writing concatenated video file.")
        Input = input("Do you want to delete the chunk clips? (Y/N)")
        if Input == 'Y':
            for Index in range(0, a_GPUCount):
                os.remove(a_OutputFileName + '_' + str(Index) + '.mp4')

    print("Finished.")
    os.system('pause')

def Main(a_Args):
    try:
        Options, Arguments = getopt.getopt(a_Args, "hi:o:g:s:c")
    except getopt.GetoptError as err:
        print("Chunkify.py -h for instructions")
        return

    if len(Options) == 0:
        print("Chunkify.py -h for instructions")
        return

    ReqOptionCheck = False
    OutName = "video"
    GPUCount = 1
    Scale = 2.0
    InPath = ""
    ConcatenateVid = False
    for Option, Argument in Options:
        if Option == "-i":
            ReqOptionCheck = True
            InPath = Argument
        elif Option == "-o":
            OutName = Argument
        elif Option == "-g":
            GPUCount = int(Argument)
        elif Option == "-s":
            Scale = float(Argument) / 100
        elif Option == "-c":
            if Argument == "Y":
                ConcatenateVid = True
        else:
            print("Chunkify - Evenly divide upscaling workload over multiple GPUs\n"
                  "\n"
                  "-i (Required) <Video input path> - Specify the video to upscale.\n"
                  "-o <Output name> - Specify the name of the generated video (default is: video).\n"
                  "-g <GPU count> - Specify the amount of GPUs present on this system (default is 1).\n"
                  "-s <Scale> - Specify the desired upscaling percentage (100 for 100%, 600 for 600% etc)(default is 200).\n"
                  "-c - Provide flag to toggle whether to concatenate the created video chunks into one video.\n")

            return

    if ReqOptionCheck is True:
        Process(InPath, OutName, Scale, GPUCount, ConcatenateVid)
    else:
        print("Chunkify.py -h for instructions")

if __name__ == '__main__':
    Main(sys.argv[1:])


import time
import paho.mqtt.client as paho
import random
import json
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime

broker="broker.hivemq.com"

RECEIVING = False
MSG_NUMBER = -1
RECEIVED_MSGS = 0

HUMIDITY_TOPIC = "house/humidity_shr"

dates = []
humidities = []

def on_message(client, userdata, message):
    global RECEIVING, MSG_NUMBER, RECEIVED_MSGS

    if RECEIVING and message.topic == HUMIDITY_TOPIC:
        data = json.loads(message.payload.decode("utf-8"))
        print("Received message:", data)
        print("Topic:", message.topic)
        print("QoS:", message.qos, end='\n\n')

        dates.append(datetime.strptime(data["time"], "%Y-%m-%d %H:%M:%S"))
        humidities.append(int(data["humidity"]))
        RECEIVED_MSGS += 1

    if message.topic == "house/msgs_shr" and not RECEIVING:
        RECEIVING = True
        MSG_NUMBER = int(message.payload)

def plot_humidity(dates, humidities):
    fig, ax = plt.subplots(constrained_layout=True)

    ax.xaxis.set_minor_locator(mdates.AutoDateLocator())
    ax.xaxis.set_minor_formatter(mdates.DateFormatter("%Y-%m-%d %H:%M:%S"))
    ax.xaxis.grid(True, which='minor')

    plt.setp(ax.xaxis.get_minorticklabels(), rotation='45deg')
    plt.setp(ax.xaxis.get_majorticklabels(), visible=True)

    base_date = min(dates)

    ax.plot(dates, humidities)
    ax.set_title(f"Humidity (base date: {base_date.year}-{base_date.month}-{base_date.day})")
    ax.set_ylabel("Humidity")
    ax.set_xlabel("Time")
    plt.show()

client = paho.Client("client-isu-101")
client.on_message = on_message

print("Connecting to broker", broker)
client.connect(broker)
client.loop_start()
print("Subscribing")

# time.sleep(60)
client.subscribe([("house/msgs_shr", 2), ("house/humidity_shr", 0)], )

while RECEIVED_MSGS != MSG_NUMBER:
    pass

client.disconnect()
client.loop_stop()

plot_humidity(dates, humidities)


import matplotlib.pyplot as plt
import config as c

file = open(f"res{c.n}.txt", "r")
Data=[]
E=[] #количества ребер
for line in file:
    Data.append(line[:-1].split(' '))
    E.append(int(file.readline()))
Data = [(int(i[0]), int(i[1]), int(i[2]), float(i[3]), int(i[4])) for i in Data]
# Data_apr=[str(i[0])+'>' for i in Data] #априорная оценк
Data_apost_1=[i[1] for i in Data] #значения получившихся оценок
Data_apost_2=[i[2] for i in Data]
Data_apost_3=[i[3] for i in Data] #массив средних значений
Data_f_val = [i[4] for i in Data] #мощности максимальных потоков

#наглядно. варьируемость количества итераций при изменениях пути
x = [i for i in range(len(Data_apost_1))]
fig, ax = plt.subplots()
ax.bar(x, Data_apost_3)
ax.bar(x, Data_apost_1)
ax.bar(x, Data_apost_2)

fig.set_facecolor('floralwhite')
fig.set_figwidth(10)
fig.set_figheight(12)
plt.title(label='chart of variation in the number of steps for different path choices')
plt.xlabel('graphs')
plt.ylabel("number of steps for graph solving")
plt.show()

#наглядно. зависимость трудоемкости от значения максимального потока (зависимость от пропускной способности)
fig1, ax1 = plt.subplots()
ax1.scatter(Data_f_val, Data_apost_3)
fig1.set_facecolor('floralwhite')
fig1.set_figwidth(10)
fig1.set_figheight(12)
plt.xlabel('value of max flow')
plt.ylabel("number of steps for graph solving")
plt.title(label='graph of the dependence of the number of steps on the value of the max flow')
plt.show()

#наглядно. зависимость трудоемкости от количества ребер
fig3, ax3 = plt.subplots()
ax3.scatter(E, Data_apost_3)
fig3.set_facecolor('floralwhite')
fig3.set_figwidth(10)
fig3.set_figheight(12)
plt.xlabel('number og edge')
plt.ylabel("number of steps for graph solving")
plt.title(label='graph of the dependence of the number of steps on the value of the num of edge')
plt.show()

#зависимость трудоемкости от заданной в начале оценки
Dific=[E[i]*Data_f_val[i] for i in range(len(E))]
fig2, ax2 = plt.subplots()
ax2.scatter(Dific, Data_apost_3)
fig2.set_facecolor('floralwhite')
fig2.set_figwidth(10)
fig2.set_figheight(12)
plt.ylabel('number of steps for graph solving')
plt.xlabel("|f|*|E|")
plt.title(label='dependence of the number of iterations on the maximum flow, the number of vertices and edges')
plt.show()

#не наглядно. график с осями мощность макс. потока, число ребер, трудоемкость
fig4 = plt.figure()
ax4 = plt.axes(projection='3d')
ax4.scatter(Data_f_val, E, Data_apost_3)

plt.show()


from datetime import datetime
import toml, json, os, traceback, github3, argparse

from fpm_fetch_toml import GitlabLite, fetch_fpm_toml
from fpm_validate import check_registry_entry, check_fpm_toml

def cli():
    """Define and parse command lines args"""
    parser = argparse.ArgumentParser(description=
              "Parses entries in registry.toml and generates index.json",
              epilog="""
              For each entry in registry.toml:
               check that the toml entry is valid;
               fetch the corresponding fpm.toml from the git repo;
               check that the fpm.toml file is valid;
               if all valid, add to index.json.

               Default behaviour is to issue a warning for package errors;
               use check arguments to exit with non-zero status instead.
              """)

    parser.add_argument('--check-new', dest='check_new', action='store_true',
                   default=False,
                   help='check new packages: fail fatally if an unindexed package '
                       +'is parsed incorrectly.')

    parser.add_argument('--check-existing', dest='check_existing', action='store_true',
                   default=False,
                   help='check existing pacakges: fail fatally if an indexed package '
                       +'is parsed incorrectly.')

    parser.add_argument('--check-all', dest='check_all', action='store_true',
                   default=False,
                   help='check all pacakges: fail fatally if any package '
                       +'is parsed incorrectly.')

    return parser.parse_args()

def main():
    """Main script"""

    args = cli()

    # Fetch current index.json if exists
    if os.path.isfile('index.json'):
        with open('index.json', 'r') as myfile:
            data=myfile.read()
        index = json.loads(data)
    else:
        index = {"packages": {}}

    # Load registry.toml
    registry = toml.load("registry.toml")
    # Get authentication for Github API
    if os.getenv('CI'):
        user = os.getenv('GITHUB_ACTOR')
        tkn = os.getenv('GITHUB_TOKEN')
    else:
        account = toml.load("account.toml")
        user = account["github"]["user"]
        tkn = account["github"]["token"]

    # Setup and authenticate API objects
    api_context = {"github": github3.login(user, tkn),
                "gitlab": GitlabLite()}

    # Loop over packages from registry.toml
    n_registered = 0
    n_update = 0
    n_new = 0
    n_skip = 0
    n_breaking = 0
    n_failed = 0
    for pkg_name in registry:

        for pkg_version in registry[pkg_name]:

            n_registered += 1

            try:

                # Check registry toml entry
                pkg_info = registry[pkg_name][pkg_version]
                check_registry_entry(pkg_name,pkg_version,pkg_info)

                # We can skip versioned packages if already in index.json
                #  and git tags match
                if (f"{pkg_name}" in index["packages"]
                    and f"{pkg_version}" in index["packages"][pkg_name]
                    and "git-tag" in index["packages"][pkg_name][pkg_version]
                    and "tag" in registry[pkg_name][pkg_version]
                    and index["packages"][pkg_name][pkg_version]["git-tag"] ==
                        registry[pkg_name][pkg_version]["tag"]):

                    print("        Package version already indexed and up-to-date, skipping.")
                    n_skip += 1
                    continue

                # Fetch fpm.toml for package version
                if "tag" in pkg_info:
                    fpm_toml = fetch_fpm_toml(api_context,
                                              pkg_info["git"],pkg_info["tag"])
                    ref = pkg_info['tag']
                else:
                    fpm_toml = fetch_fpm_toml(api_context,pkg_info["git"])
                    ref = None

                # Build json index entry
                pkg_info_full = check_fpm_toml(fpm_toml)
                pkg_info_full["git"] = pkg_info["git"]
                pkg_info_full["git-tag"] = ref

                # Counting
                if (f"{pkg_name}" in index["packages"]
                    and f"{pkg_version}" in index["packages"][pkg_name]):

                    n_update += 1
                else:
                    n_new += 1

                # Save to index dict
                if f"{pkg_name}" not in index["packages"]:
                    index["packages"][pkg_name] = {}

                index["packages"][pkg_name][pkg_version] = pkg_info_full

            except Exception:
                print(f"        (!) Error processing package '"
                     +f"{pkg_name}-{pkg_version}, skipping.\n")
                traceback.print_exc()
                print("")

                # Counting
                if (f"{pkg_name}" in index["packages"]
                    and f"{pkg_version}" in index["packages"][pkg_name]):

                    n_breaking += 1
                else:
                    n_failed += 1

    # Update index date
    index["index-date"] = datetime.now().strftime("%c")

    # Save index to index.json
    json.dump(index, open('index.json', "w"), indent=4)

    # Dump counts
    n_indexed = sum(len(index["packages"][p].keys()) for p in index["packages"])
    print("\nIndexing complete.")
    print(f" {n_registered} packages are registered in registry.toml")
    print(f" {n_indexed} packages are indexed in index.json \n")
    print(f" {n_new} unindexed packages were added to the index sucessfully")
    print(f" {n_failed} unindexed packages failed to be indexed correctly\n")
    print(f" {n_update} indexed packages were re-indexed sucessfully")
    print(f" {n_skip} indexed versioned packages were up-to-date and skipped")
    print(f" {n_breaking} indexed packages failed to be re-indexed correctly\n")

    print(f"Github API remaining requests: {api_context['github'].ratelimit_remaining}")
    print(f"Gitlab API remaining requests: {api_context['gitlab'].ratelimit_remaining}")

    if n_breaking > 0 and (args.check_existing or args.check_all):
        raise Exception(f"There were indexed packages that failed to be re-indexed")

    if n_failed > 0 and (args.check_new or args.check_all):
        raise Exception(f"There were unindexed packages that failed to be indexed")

if __name__ == "__main__":
    main()


from pyecharts import Pie
from liquidView.psours import *

pObj = Pie("男女生占比图")

datas = queryEmpSex()

ats = []
das = []

for value in datas:
    ats.append(value[1])
    das.append(value[0])

pObj.add("男女生占比",ats,das)

pObj.render("p.html")


#!/usr/bin/env python
# -*-coding:utf-8-*-

import json
import shortuuid
import base64
from websdk.jwt_token import gen_md5
from websdk.tools import check_password
from libs.base_handler import BaseHandler
from websdk.db_context import DBContext
from models.admin import UserRoles, Stakeholder, Companylist, model_to_dict
from websdk.consts import const
from websdk.cache_context import cache_conn
from websdk.tools import convert
from websdk.web_logs import ins_log
import os
import pandas as pd

def sync_stakeholder_to_redis():
    redis_conn = cache_conn()
    with DBContext('r') as session:
        dict_info = session.query(Stakeholder).all()
    for msg in dict_info:
        data_dict = model_to_dict(msg)
        tempstr = data_dict["username"]
        redis_conn.hset('stakeholder_hash', data_dict["id"], tempstr)

class StakeholderHandler(BaseHandler):
    def get(self, *args, **kwargs):
        data_list = []
        key = self.get_argument('key', default=None, strip=True)
        value = self.get_argument('value', default=None, strip=True)
        page_size = self.get_argument('page', default=1, strip=True)
        limit = self.get_argument('limit', default=30, strip=True)
        limit_start = (int(page_size) - 1) * int(limit)
        user_list = []
        with DBContext('r') as session:
            conditions = []
            if key == "username":
                conditions.append(Stakeholder.username.like('%{}%'.format(value)))
            if key == "company":
                conditions.append(Stakeholder.company.like('%{}%'.format(value)))
            if key == "department":
                conditions.append(Stakeholder.department.like('%{}%'.format(value)))
            if key == "position":
                conditions.append(Stakeholder.position.like('%{}%'.format(value)))
            if key == "duty":
                conditions.append(Stakeholder.duty.like('%{}%'.format(value)))
            if key == "tel":
                conditions.append(Stakeholder.tel.like('%{}%'.format(value)))
            if key == "addr":
                conditions.append(Stakeholder.addr.like('%{}%'.format(value)))
            if key == "email":
                conditions.append(Stakeholder.email.like('%{}%'.format(value)))
            if key == "remarks":
                conditions.append(Stakeholder.remarks.like('%{}%'.format(value)))

            todata = session.query(Stakeholder).filter(*conditions).order_by(Stakeholder.ctime.desc()).offset(
                limit_start).limit(int(limit)).all()
            tocount = session.query(Stakeholder).filter(*conditions).count()

        for msg in todata:
            case_dict = {}
            data_dict = model_to_dict(msg)
            case_dict["id"] = data_dict["id"]
            case_dict["username"] = data_dict["username"]
            case_dict["company"] = data_dict["company"]
            case_dict["department"] = data_dict["department"]
            case_dict["position"] = data_dict["position"]
            case_dict["duty"] = data_dict["duty"]
            case_dict["tel"] = data_dict["tel"]
            case_dict["addr"] = data_dict["addr"]
            case_dict["email"] = data_dict["email"]
            case_dict["remarks"] = data_dict["remarks"]

            case_dict["ctime"] = str(data_dict["ctime"])
            data_list.append(case_dict)

        if len(data_list) > 0:
            self.write(dict(code=0, msg='获取成功', count=tocount, data=data_list))
        else:
            self.write(dict(code=-1, msg='没有相关数据', count=0, data=[]))

    def post(self, *args, **kwargs):
        data = json.loads(self.request.body.decode("utf-8"))
        username = data.get('username', None)
        company = data.get('company', None)
        department = data.get('department', None)
        position = data.get('position', None)
        duty = data.get('duty', None)
        tel = data.get('tel', None)
        addr = data.get('addr', None)
        email = data.get('email', None)
        remarks = data.get('remarks', None)
        if not username or not company:
            return self.write(dict(code=-1, msg='参数不能为空'))
        with DBContext('r') as session:
            user_info2 = session.query(Stakeholder).filter(Stakeholder.tel == tel).first()
            user_info3 = session.query(Stakeholder).filter(Stakeholder.email == email).first()
        # if user_info1:
        #     return self.write(dict(code=-2, msg='微信号已存在，请重新输入。'))

        if user_info2:
            return self.write(dict(code=-3, msg='手机号已存在，请重新输入。'))

        # if user_info3:
        #     return self.write(dict(code=-4, msg='邮箱已存在，请重新输入。'))

        with DBContext('w', None, True) as session:
            session.add(Stakeholder(
                username=username,
                department=department,
                company=company,
                position=position,
                duty=duty,
                tel=tel,
                addr=addr,
                email=email,
                remarks=remarks,
            ))
            session.commit()

        sync_stakeholder_to_redis()
        self.write(dict(code=0, msg='成功', count=0, data=[]))

    def delete(self, *args, **kwargs):
        data = json.loads(self.request.body.decode("utf-8"))
        id = data.get('id', None)
        if not id:
            return self.write(dict(code=-1, msg='ID不能为空'))

        redis_conn = cache_conn()
        redis_conn.hdel('stakeholder_hash', id)

        with DBContext('w', None, True) as session:
            session.query(Stakeholder).filter(Stakeholder.id == id).delete(synchronize_session=False)
        self.write(dict(code=0, msg='删除成功'))

    def put(self, *args, **kwargs):
        data = json.loads(self.request.body.decode("utf-8"))
        id = data.get('id', None)
        username = data.get('username', None)
        company = data.get('company', None)
        department = data.get('department', None)
        position = data.get('position', None)
        duty = data.get('duty', None)
        tel = data.get('tel', None)
        addr = data.get('addr', None)
        email = data.get('email', None)
        remarks = data.get('remarks', None)

        # if not key or not value or not user_id:
        #     return self.write(dict(code=-1, msg='不能为空'))

        try:
            with DBContext('w', None, True) as session:
                session.query(Stakeholder).filter(Stakeholder.id == id).update({
                    Stakeholder.username: username,
                    Stakeholder.company: company,
                    Stakeholder.department: department,
                    Stakeholder.position: position,
                    Stakeholder.duty: duty,
                    Stakeholder.tel: tel,
                    Stakeholder.addr: addr,
                    Stakeholder.email: email,
                    Stakeholder.remarks: remarks,
                })
                session.commit()
        except Exception as e:
            return self.write(dict(code=-2, msg='修改失败，请检查数据是否合法或者重复'))
        sync_stakeholder_to_redis()
        self.write(dict(code=0, msg='编辑成功'))

class Stakeholder_redisList(BaseHandler):
    def get(self, *args, **kwargs):
        data_list = []
        redis_conn = cache_conn()
        stakeholder_all = redis_conn.hgetall('stakeholder_hash')
        data_dict = convert(stakeholder_all)
        for k, v in data_dict.items():
            data_list.append({"k": k, "v": v})
            # ins_log.read_log('info', k)
        if len(data_list) > 0:
            self.write(dict(code=0, msg='获取成功', data=data_list))
        else:
            self.write(dict(code=-1, msg='没有相关数据', data=[]))

class StakeholderList(BaseHandler):
    def get(self, *args, **kwargs):
        data_list = []
        key = self.get_argument('key', default=None, strip=True)
        value = self.get_argument('value', default=None, strip=True)
        user_list = []
        if key == "company":
            with DBContext('r') as session:
                todata = session.query(Stakeholder).filter(Stakeholder.company == value).order_by(Stakeholder.ctime.desc()).all()
                tocount = session.query(Stakeholder).filter(Stakeholder.company == value).count()

        for msg in todata:
            case_dict = {}
            data_dict = model_to_dict(msg)
            case_dict["id"] = data_dict["id"]
            case_dict["username"] = data_dict["username"]
            case_dict["company"] = data_dict["company"]
            case_dict["department"] = data_dict["department"]
            case_dict["position"] = data_dict["position"]
            case_dict["duty"] = data_dict["duty"]
            case_dict["tel"] = data_dict["tel"]
            case_dict["addr"] = data_dict["addr"]
            case_dict["email"] = data_dict["email"]
            case_dict["remarks"] = data_dict["remarks"]
            case_dict["ctime"] = str(data_dict["ctime"])
            data_list.append(case_dict)

        if len(data_list) > 0:
            self.write(dict(code=0, msg='获取成功', count=tocount, data=data_list))
        else:
            self.write(dict(code=-1, msg='没有相关数据', count=0, data=[]))

class uploadStakeholder(BaseHandler):
    def post(self, *args, **kwargs):
        ###文件保存到本地
        Base_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
        upload_path = '{}/static/stakeholder/'.format(Base_DIR)
        file_body = self.request.files["file"][0]["body"]
        file_path = upload_path + "tempfile.xls"
        with open(file_path, 'wb') as up:
            up.write(file_body)
        df = pd.read_excel(file_path)
        allsum = len(df.index)
        ins_log.read_log('info', allsum)
        for i in range(0, allsum):
            username = str(df.iloc[i, 0]),
            company = str(df.iloc[i, 1]),
            department = str(df.iloc[i, 2]),
            position = str(df.iloc[i, 3]),
            duty = str(df.iloc[i, 4]),
            tel = str(df.iloc[i, 5]),
            addr = str(df.iloc[i, 6]),
            email = str(df.iloc[i, 7]),
            remarks = str(df.iloc[i, 8]),
            with DBContext('r') as session:
                tocount = session.query(Companylist).filter(Companylist.company == company).count()
            if tocount <= 0:
                with DBContext('w', None, True) as session:
                    session.add(Companylist(
                        company=company,
                    ))
                    session.commit()
            try:
                with DBContext('w', None, True) as session:
                    session.add(Stakeholder(
                        username=username,
                        company=company,
                        department=department,
                        position=position,
                        duty=duty,
                        tel=tel,
                        addr=addr,
                        email=email,
                        remarks=remarks,
                    ))
                session.commit()
            except:
                continue
        # session.commit()
        sync_stakeholder_to_redis()

stakeholder_urls = [
    (r"/v2/accounts/stakeholder/", StakeholderHandler),
    (r"/v2/accounts/stakeholderredislist/", Stakeholder_redisList),
    (r"/v2/accounts/stakeholderlist/", StakeholderList),
    (r"/v2/accounts/stakeholder/upload/", uploadStakeholder),
]

if __name__ == "__main__":
    pass


import datetime

import pytest
from bs4 import BeautifulSoup
from django.utils import timezone
from model_bakery import baker

from delivery_options.models import DeliveryOption
from documents import factories
from orders.models import Order, OrderItem, User

pytestmark = pytest.mark.django_db

def test_create_local_admin_credit_note(
    order, order_items, seller, platform_user, traidoo_region
):
    credit_note = factories.CreditNoteFactory(order, traidoo_region, seller).compose()
    credit_note.save()

    assert (
        credit_note.lines[0]["price"] == order.local_platform_owner_platform_fee.netto
    )
    assert credit_note.buyer == factories.CreditNoteFactory.as_dict(
        traidoo_region.setting.platform_user
    )
    assert credit_note.seller == factories.CreditNoteFactory.as_dict(
        User.central_platform_user()
    )
    assert len(credit_note.lines) == 1

def test_third_party_logistic_invoice(
    send_task,
    order,
    platform_user,
    traidoo_region,
    delivery_address,
    delivery_options,
    logistics_user,
    traidoo_settings,
    order_items,
    buyer,
    products,
):
    order.recalculate_items_delivery_fee()
    products[0].third_party_delivery = True
    products[0].save()
    order_items[0].delivery_option_id = DeliveryOption.SELLER
    order_items[0].save()

    user = baker.make_recipe("users.user", region=traidoo_region)
    baker.make("jobs.Job", user=user, order_item=order_items[0])

    order.recalculate_items_delivery_fee()

    factory = factories.ThirdPartyLogisticsInvoiceFactory(order, region=traidoo_region)

    documents = list(factory.compose())
    assert len(documents) == 1
    documents[0].save()
    document = documents[0]

    assert document.seller == factories.ThirdPartyLogisticsInvoiceFactory.as_dict(user)
    assert document.buyer == factories.ThirdPartyLogisticsInvoiceFactory.as_company(
        buyer
    )

    assert document.order_id == order.id
    assert len(document.lines) == 1
    order_items[0].refresh_from_db()
    assert document.lines[0] == {
        "amount": 1.0,
        "count": 1.0,
        "name": f"Lieferung von {order_items[0].product.name}",
        "number": order_items[0].product_id,
        "price": float(order_items[0].delivery_fee),
        "producer": user.company_name,
        "seller_user_id": user.id,
        "unit": "",
        "vat_rate": traidoo_settings.mc_swiss_delivery_fee_vat,
        "category": "",
    }

def test_producer_invoice(
    order,
    order_items,
    traidoo_region,
    container_types,
    delivery_address,
    delivery_options,
    logistics_user,
    seller,
    buyer,
    products,
):
    other_seller = baker.make_recipe("users.user")
    products[1].seller = other_seller
    products[1].save()

    factory = factories.ProducerInvoiceFactory(
        order, seller=seller, region=traidoo_region
    )
    document = factory.compose()
    document.save()

    assert document.seller == factories.ProducerInvoiceFactory.as_dict(seller)
    assert document.buyer == factories.ProducerInvoiceFactory.as_company(buyer)

    assert len(document.lines) == 2
    assert document.order_id == order.id
    assert document.lines[0] == {
        "amount": 3.0,
        "category": "Produkte",
        "count": 3.0,
        "name": products[0].name,
        "number": products[0].id,
        "organic_control_body": seller.organic_control_body,
        "price": 10.6,
        "producer": seller.company_name,
        "seller_user_id": seller.id,
        "unit": products[0].unit,
        "vat_rate": products[0].vat,
    }
    assert document.lines[1] == {
        "amount": 1,
        "category": "Pfand",
        "count": 3.0,
        "name": "Isolierbox",
        "number": container_types[0].id,
        "price": 3.2,
        "producer": "",
        "seller_user_id": seller.id,
        "unit": "Stück",
        "vat_rate": 19.0,
    }

def test_merge_same_products(
    buyer,
    traidoo_region,
    products,
    delivery_address,
    delivery_options,
    seller,
    logistics_user,
):
    order = Order(buyer=buyer, region=traidoo_region)
    order.save()
    order.recalculate_items_delivery_fee()

    order_items = [
        OrderItem(
            product=products[0],
            quantity=5,
            order=order,
            delivery_address=delivery_address,
            delivery_option=delivery_options[0],
            latest_delivery_date=(timezone.now().date() + datetime.timedelta(days=3)),
        ),
        OrderItem(
            product=products[0],
            quantity=5,
            order=order,
            delivery_address=delivery_address,
            delivery_option=delivery_options[0],
            latest_delivery_date=(timezone.now().date() + datetime.timedelta(days=2)),
        ),
        OrderItem(
            product=products[0],
            quantity=5,
            order=order,
            delivery_address=delivery_address,
            delivery_option=delivery_options[0],
            latest_delivery_date=(timezone.now().date() + datetime.timedelta(days=1)),
        ),
    ]

    [items.save() for items in order_items]
    order.recalculate_items_delivery_fee()

    factory = factories.ProducerInvoiceFactory(
        order=order, seller=seller, region=traidoo_region
    )

    assert len(factory._items) == 1
    assert factory._items[0].product == products[0]
    assert factory._items[0].quantity == 15
    assert factory._items[0].product_snapshot == order_items[0].product_snapshot
    assert factory._items[0].order == order
    assert factory._items[0].delivery_address == order_items[0].delivery_address
    assert factory._items[0].delivery_option == order_items[0].delivery_option
    assert factory._items[0].latest_delivery_date == order_items[0].latest_delivery_date

def test_use_buyer_delivery_address_when_self_collect(
    seller,
    logistics_user,
    products,
    delivery_options,
    buyer,
    traidoo_region,
    traidoo_settings,
):

    order = baker.make(
        Order,
        buyer=buyer,
        earliest_delivery_date=timezone.make_aware(datetime.datetime.today()),
        region=traidoo_region,
    )
    order.save()
    order_item = baker.make(
        OrderItem,
        product=products[0],
        quantity=1,
        order=order,
        delivery_address=None,
        delivery_option=delivery_options[2],
        latest_delivery_date=timezone.now().date() + datetime.timedelta(days=3),
    )
    order_item.save()

    delivery_documents_factories = [
        factories.DeliveryOverviewSellerFactory,
        factories.DeliveryOverviewBuyerFactory,
    ]

    for DeliveryDocumentFactory in delivery_documents_factories:
        html = (
            DeliveryDocumentFactory(order, traidoo_region, seller)
            .compose()
            .render_html()
        )
        html = BeautifulSoup(html, features="html.parser")
        assert len(html.find_all("p", text=lambda text: "von Best apples" in text)) == 1
        assert len(html.find_all("p", text=lambda text: "nach ACME" in text)) == 1


import glob
from PyPDF2 import PdfFileWriter, PdfFileReader
import os
import shutil
import re
from pathlib import Path

def merger(output_path, input_paths):
    pdf_writer = PdfFileWriter()

    for path in input_paths:
        pdf_reader = PdfFileReader(path)
        for page in range(pdf_reader.getNumPages()):
            pdf_writer.addPage(pdf_reader.getPage(page))

    with open(output_path, 'wb') as fh:
        pdf_writer.write(fh)

def pdf_splitter(path,no1,no2):
    fname = os.path.splitext(os.path.basename(path))[0]

    pdf = PdfFileReader(path)
    for page in range(no1,no2):
        pdf_writer = PdfFileWriter()
        pdf_writer.addPage(pdf.getPage(page))

        output_filename = '{}_page_{}.pdf'.format(
            fname, page+1)

        with open(output_filename, 'wb') as out:
            pdf_writer.write(out)

if __name__ == '__main__':
    path = input("Enter the path:")
    no1 = input("Enter the starting page number:")
    no1=int(no1)-1
    no2 = input("Enter the last page:")
    no2=int(no2)
    fname = os.path.splitext(os.path.basename(path))[0]
    pdf_splitter(path,no1,no2)
    paths = glob.glob('{}_page_*.pdf'.format(fname))
    paths.sort()
    new = input("Enter the name of the pdf file to be created:")
    merger(new, paths)
    for p in Path(".").glob('{}_page_*.pdf'.format(fname)):
        p.unlink()


from copy import deepcopy
from datetime import datetime, timezone
from io import StringIO
from pathlib import Path

import numpy as np
import pytest
from numpy.testing import assert_allclose, assert_array_equal
from scipy import sparse

from mne import pick_types, read_cov, read_evokeds
from mne._fiff.pick import _picks_by_type
from mne.epochs import make_fixed_length_epochs
from mne.io import read_raw_fif
from mne.time_frequency import tfr_morlet
from mne.utils import (
    _PCA,
    _apply_scaling_array,
    _apply_scaling_cov,
    _array_equal_nan,
    _cal_to_julian,
    _custom_lru_cache,
    _dt_to_julian,
    _freq_mask,
    _get_inst_data,
    _julian_to_cal,
    _julian_to_dt,
    _reg_pinv,
    _ReuseCycle,
    _time_mask,
    _undo_scaling_array,
    _undo_scaling_cov,
    compute_corr,
    create_slices,
    grand_average,
    hashfunc,
    numerics,
    object_diff,
    object_hash,
    object_size,
    random_permutation,
    sum_squared,
)
from mne.utils.numerics import _LRU_CACHE_MAXSIZES, _LRU_CACHES

base_dir = Path(__file__).parents[2] / "io" / "tests" / "data"
fname_raw = base_dir / "test_raw.fif"
ave_fname = base_dir / "test-ave.fif"
cov_fname = base_dir / "test-cov.fif"

def test_get_inst_data():
    """Test _get_inst_data."""
    raw = read_raw_fif(fname_raw)
    raw.crop(tmax=1.0)
    assert_array_equal(_get_inst_data(raw), raw._data)
    raw.pick(raw.ch_names[:2])

    epochs = make_fixed_length_epochs(raw, 0.5)
    assert_array_equal(_get_inst_data(epochs), epochs._data)

    evoked = epochs.average()
    assert_array_equal(_get_inst_data(evoked), evoked.data)

    evoked.crop(tmax=0.1)
    picks = list(range(2))
    freqs = [50.0, 55.0]
    n_cycles = 3
    tfr = tfr_morlet(evoked, freqs, n_cycles, return_itc=False, picks=picks)
    assert_array_equal(_get_inst_data(tfr), tfr.data)

    pytest.raises(TypeError, _get_inst_data, "foo")

def test_hashfunc(tmp_path):
    """Test md5/sha1 hash calculations."""
    fname1 = tmp_path / "foo"
    fname2 = tmp_path / "bar"
    with open(fname1, "wb") as fid:
        fid.write(b"abcd")
    with open(fname2, "wb") as fid:
        fid.write(b"efgh")

    for hash_type in ("md5", "sha1"):
        hash1 = hashfunc(fname1, hash_type=hash_type)
        hash1_ = hashfunc(fname1, 1, hash_type=hash_type)

        hash2 = hashfunc(fname2, hash_type=hash_type)
        hash2_ = hashfunc(fname2, 1024, hash_type=hash_type)

        assert hash1 == hash1_
        assert hash2 == hash2_
        assert hash1 != hash2

def test_sum_squared():
    """Test optimized sum of squares."""
    X = np.random.RandomState(0).randint(0, 50, (3, 3))
    assert np.sum(X**2) == sum_squared(X)

def test_compute_corr():
    """Test Anscombe's Quartett."""
    x = np.array([10, 8, 13, 9, 11, 14, 6, 4, 12, 7, 5])
    y = np.array(
        [
            [8.04, 6.95, 7.58, 8.81, 8.33, 9.96, 7.24, 4.26, 10.84, 4.82, 5.68],
            [9.14, 8.14, 8.74, 8.77, 9.26, 8.10, 6.13, 3.10, 9.13, 7.26, 4.74],
            [7.46, 6.77, 12.74, 7.11, 7.81, 8.84, 6.08, 5.39, 8.15, 6.42, 5.73],
            [8, 8, 8, 8, 8, 8, 8, 19, 8, 8, 8],
            [6.58, 5.76, 7.71, 8.84, 8.47, 7.04, 5.25, 12.50, 5.56, 7.91, 6.89],
        ]
    )

    r = compute_corr(x, y.T)
    r2 = np.array([np.corrcoef(x, y[i])[0, 1] for i in range(len(y))])
    assert_allclose(r, r2)
    pytest.raises(ValueError, compute_corr, [1, 2], [])

def test_create_slices():
    """Test checking the create of time create_slices."""
    # Test that create_slices default provide an empty list
    assert create_slices(0, 0) == []
    # Test that create_slice return correct number of slices
    assert len(create_slices(0, 100)) == 100
    # Test with non-zero start parameters
    assert len(create_slices(50, 100)) == 50
    # Test slices' length with non-zero start and window_width=2
    assert len(create_slices(0, 100, length=2)) == 50
    # Test slices' length with manual slice separation
    assert len(create_slices(0, 100, step=10)) == 10
    # Test slices' within length for non-consecutive samples
    assert len(create_slices(0, 500, length=50, step=10)) == 46
    # Test that slices elements start, stop and step correctly
    slices = create_slices(0, 10)
    assert slices[0].start == 0
    assert slices[0].step == 1
    assert slices[0].stop == 1
    assert slices[-1].stop == 10
    # Same with larger window width
    slices = create_slices(0, 9, length=3)
    assert slices[0].start == 0
    assert slices[0].step == 1
    assert slices[0].stop == 3
    assert slices[-1].stop == 9
    # Same with manual slices' separation
    slices = create_slices(0, 9, length=3, step=1)
    assert len(slices) == 7
    assert slices[0].step == 1
    assert slices[0].stop == 3
    assert slices[-1].start == 6
    assert slices[-1].stop == 9

def test_time_mask():
    """Test safe time masking."""
    N = 10
    x = np.arange(N).astype(float)
    assert _time_mask(x, 0, N - 1).sum() == N
    assert _time_mask(x - 1e-10, 0, N - 1, sfreq=1000.0).sum() == N
    assert _time_mask(x - 1e-10, None, N - 1, sfreq=1000.0).sum() == N
    assert _time_mask(x - 1e-10, None, None, sfreq=1000.0).sum() == N
    assert _time_mask(x - 1e-10, -np.inf, None, sfreq=1000.0).sum() == N
    assert _time_mask(x - 1e-10, None, np.inf, sfreq=1000.0).sum() == N
    # non-uniformly spaced inputs
    x = np.array([4, 10])
    assert _time_mask(x[:1], tmin=10, sfreq=1, raise_error=False).sum() == 0
    assert _time_mask(x[:1], tmin=11, tmax=12, sfreq=1, raise_error=False).sum() == 0
    assert _time_mask(x, tmin=10, sfreq=1).sum() == 1
    assert _time_mask(x, tmin=6, sfreq=1).sum() == 1
    assert _time_mask(x, tmin=5, sfreq=1).sum() == 1
    assert _time_mask(x, tmin=4.5001, sfreq=1).sum() == 1
    assert _time_mask(x, tmin=4.4999, sfreq=1).sum() == 2
    assert _time_mask(x, tmin=4, sfreq=1).sum() == 2
    # degenerate cases
    with pytest.raises(ValueError, match="No samples remain"):
        _time_mask(x[:1], tmin=11, tmax=12)
    with pytest.raises(ValueError, match="must be less than or equal to tmax"):
        _time_mask(x[:1], tmin=10, sfreq=1)

def test_freq_mask():
    """Test safe frequency masking."""
    N = 10
    x = np.arange(N).astype(float)
    assert _freq_mask(x, 1000.0, fmin=0, fmax=N - 1).sum() == N
    assert _freq_mask(x - 1e-10, 1000.0, fmin=0, fmax=N - 1).sum() == N
    assert _freq_mask(x - 1e-10, 1000.0, fmin=None, fmax=N - 1).sum() == N
    assert _freq_mask(x - 1e-10, 1000.0, fmin=None, fmax=None).sum() == N
    assert _freq_mask(x - 1e-10, 1000.0, fmin=-np.inf, fmax=None).sum() == N
    assert _freq_mask(x - 1e-10, 1000.0, fmin=None, fmax=np.inf).sum() == N
    # non-uniformly spaced inputs
    x = np.array([4, 10])
    assert _freq_mask(x[:1], 1, fmin=10, raise_error=False).sum() == 0
    assert _freq_mask(x[:1], 1, fmin=11, fmax=12, raise_error=False).sum() == 0
    assert _freq_mask(x, sfreq=1, fmin=10).sum() == 1
    assert _freq_mask(x, sfreq=1, fmin=6).sum() == 1
    assert _freq_mask(x, sfreq=1, fmin=5).sum() == 1
    assert _freq_mask(x, sfreq=1, fmin=4.5001).sum() == 1
    assert _freq_mask(x, sfreq=1, fmin=4.4999).sum() == 2
    assert _freq_mask(x, sfreq=1, fmin=4).sum() == 2
    # degenerate cases
    with pytest.raises(ValueError, match="sfreq can not be None"):
        _freq_mask(x[:1], sfreq=None, fmin=3, fmax=5)
    with pytest.raises(ValueError, match="No frequencies remain"):
        _freq_mask(x[:1], sfreq=1, fmin=11, fmax=12)
    with pytest.raises(ValueError, match="must be less than or equal to fmax"):
        _freq_mask(x[:1], sfreq=1, fmin=10)

def test_random_permutation():
    """Test random permutation function."""
    n_samples = 10
    random_state = 42
    python_randperm = random_permutation(n_samples, random_state)

    # matlab output when we execute rng(42), randperm(10)
    matlab_randperm = np.array([7, 6, 5, 1, 4, 9, 10, 3, 8, 2])

    assert_array_equal(python_randperm, matlab_randperm - 1)

def test_cov_scaling():
    """Test rescaling covs."""
    evoked = read_evokeds(ave_fname, condition=0, baseline=(None, 0), proj=True)
    cov = read_cov(cov_fname)["data"]
    cov2 = read_cov(cov_fname)["data"]

    assert_array_equal(cov, cov2)
    evoked.pick(
        [evoked.ch_names[k] for k in pick_types(evoked.info, meg=True, eeg=True)]
    )
    picks_list = _picks_by_type(evoked.info)
    scalings = dict(mag=1e15, grad=1e13, eeg=1e6)

    _apply_scaling_cov(cov2, picks_list, scalings=scalings)
    _apply_scaling_cov(cov, picks_list, scalings=scalings)
    assert_array_equal(cov, cov2)
    assert cov.max() > 1

    _undo_scaling_cov(cov2, picks_list, scalings=scalings)
    _undo_scaling_cov(cov, picks_list, scalings=scalings)
    assert_array_equal(cov, cov2)
    assert cov.max() < 1

    data = evoked.data.copy()
    _apply_scaling_array(data, picks_list, scalings=scalings)
    _undo_scaling_array(data, picks_list, scalings=scalings)
    assert_allclose(data, evoked.data, atol=1e-20)

@pytest.mark.parametrize("ndim", (2, 3))
def test_reg_pinv(ndim):
    """Test regularization and inversion of covariance matrix."""
    # create rank-deficient array
    a = np.array([[1.0, 0.0, 1.0], [0.0, 1.0, 0.0], [1.0, 0.0, 1.0]])
    for _ in range(ndim - 2):
        a = a[np.newaxis]

    # Test if rank-deficient matrix without regularization throws
    # specific warning
    with pytest.warns(RuntimeWarning, match="deficient"):
        _reg_pinv(a, reg=0.0)

    # Test inversion with explicit rank
    a_inv_np = np.linalg.pinv(a, hermitian=True)
    a_inv_mne, loading_factor, rank = _reg_pinv(a, rank=2)
    assert loading_factor == 0
    assert rank == 2
    assert_allclose(a_inv_np, a_inv_mne, atol=1e-14)

    # Test inversion with automatic rank detection
    a_inv_mne, _, estimated_rank = _reg_pinv(a, rank=None)
    assert_allclose(a_inv_np, a_inv_mne, atol=1e-14)
    assert estimated_rank == 2

    # Test adding regularization
    a_inv_mne, loading_factor, estimated_rank = _reg_pinv(a, reg=2)
    # Since A has a diagonal of all ones, loading_factor should equal the
    # regularization parameter
    assert loading_factor == 2
    # The estimated rank should be that of the non-regularized matrix
    assert estimated_rank == 2
    # Test result against the NumPy version
    a_inv_np = np.linalg.pinv(a + loading_factor * np.eye(3), hermitian=True)
    assert_allclose(a_inv_np, a_inv_mne, atol=1e-14)

    # Test setting rcond
    a_inv_np = np.linalg.pinv(a, rcond=0.5)
    a_inv_mne, _, estimated_rank = _reg_pinv(a, rcond=0.5)
    assert_allclose(a_inv_np, a_inv_mne, atol=1e-14)
    assert estimated_rank == 1

    # Test inverting an all zero cov
    a_inv, loading_factor, estimated_rank = _reg_pinv(np.zeros((3, 3)), reg=2)
    assert_array_equal(a_inv, 0)
    assert loading_factor == 0
    assert estimated_rank == 0

def test_object_size():
    """Test object size estimation."""
    assert object_size(np.ones(10, np.float32)) < object_size(np.ones(10, np.float64))
    for lower, upper, obj in (
        (0, 60, ""),
        (0, 30, 1),
        (0, 30, 1.0),
        (0, 70, "foo"),
        (0, 150, np.ones(0)),
        (0, 150, np.int32(1)),
        (150, 500, np.ones(20)),
        (30, 400, dict()),
        (400, 1000, dict(a=np.ones(50))),
        (200, 900, sparse.eye(20, format="csc")),
        (200, 900, sparse.eye(20, format="csr")),
    ):
        size = object_size(obj)
        assert lower < size < upper, "%s < %s < %s:\n%s" % (lower, size, upper, obj)
    # views work properly
    x = dict(a=1)
    assert object_size(x) < 1000
    x["a"] = np.ones(100000, float)
    nb = x["a"].nbytes
    sz = object_size(x)
    assert nb < sz < nb * 1.01
    x["b"] = x["a"]
    sz = object_size(x)
    assert nb < sz < nb * 1.01
    x["b"] = x["a"].view()
    x["b"].flags.writeable = False
    assert x["a"].flags.writeable
    sz = object_size(x)
    assert nb < sz < nb * 1.01

def test_object_diff_with_nan():
    """Test object diff can handle NaNs."""
    d0 = np.array([1, np.nan, 0])
    d1 = np.array([1, np.nan, 0])
    d2 = np.array([np.nan, 1, 0])

    assert object_diff(d0, d1) == ""
    assert object_diff(d0, d2) != ""
    assert object_diff(np.nan, np.nan) == ""
    assert object_diff(np.nan, 3.5) == " value mismatch (nan, 3.5)\n"

def test_hash():
    """Test dictionary hashing and comparison functions."""
    # does hashing all of these types work:
    # {dict, list, tuple, ndarray, str, float, int, None}
    d0 = dict(a=dict(a=0.1, b="fo", c=1), b=[1, "b"], c=(), d=np.ones(3), e=None)
    d0[1] = None
    d0[2.0] = b"123"

    d1 = deepcopy(d0)
    assert len(object_diff(d0, d1)) == 0
    assert len(object_diff(d1, d0)) == 0
    assert object_hash(d0) == object_hash(d1)

    # change values slightly
    d1["data"] = np.ones(3, int)
    d1["d"][0] = 0
    assert object_hash(d0) != object_hash(d1)

    d1 = deepcopy(d0)
    assert object_hash(d0) == object_hash(d1)
    d1["a"]["a"] = 0.11
    assert len(object_diff(d0, d1)) > 0
    assert len(object_diff(d1, d0)) > 0
    assert object_hash(d0) != object_hash(d1)

    d1 = deepcopy(d0)
    assert object_hash(d0) == object_hash(d1)
    d1["a"]["d"] = 0  # non-existent key
    assert len(object_diff(d0, d1)) > 0
    assert len(object_diff(d1, d0)) > 0
    assert object_hash(d0) != object_hash(d1)

    d1 = deepcopy(d0)
    assert object_hash(d0) == object_hash(d1)
    d1["b"].append(0)  # different-length lists
    assert len(object_diff(d0, d1)) > 0
    assert len(object_diff(d1, d0)) > 0
    assert object_hash(d0) != object_hash(d1)

    d1 = deepcopy(d0)
    assert object_hash(d0) == object_hash(d1)
    d1["e"] = "foo"  # non-None
    assert len(object_diff(d0, d1)) > 0
    assert len(object_diff(d1, d0)) > 0
    assert object_hash(d0) != object_hash(d1)

    d1 = deepcopy(d0)
    d2 = deepcopy(d0)
    d1["e"] = StringIO()
    d2["e"] = StringIO()
    d2["e"].write("foo")
    assert len(object_diff(d0, d1)) > 0
    assert len(object_diff(d1, d0)) > 0

    d1 = deepcopy(d0)
    d1[1] = 2
    assert len(object_diff(d0, d1)) > 0
    assert len(object_diff(d1, d0)) > 0
    assert object_hash(d0) != object_hash(d1)

    # generators (and other types) not supported
    d1 = deepcopy(d0)
    d2 = deepcopy(d0)
    d1[1] = (x for x in d0)
    d2[1] = (x for x in d0)
    pytest.raises(RuntimeError, object_diff, d1, d2)
    pytest.raises(RuntimeError, object_hash, d1)

    x = sparse.eye(2, 2, format="csc")
    y = sparse.eye(2, 2, format="csr")
    assert "type mismatch" in object_diff(x, y)
    y = sparse.eye(2, 2, format="csc")
    assert len(object_diff(x, y)) == 0
    y[1, 1] = 2
    assert "elements" in object_diff(x, y)
    y = sparse.eye(3, 3, format="csc")
    assert "shape" in object_diff(x, y)
    y = 0
    assert "type mismatch" in object_diff(x, y)

    # smoke test for gh-4796
    assert object_hash(np.int64(1)) != 0
    assert object_hash(np.bool_(True)) != 0

@pytest.mark.parametrize("n_components", (None, 0.9999, 8, "mle"))
@pytest.mark.parametrize("whiten", (True, False))
def test_pca(n_components, whiten):
    """Test PCA equivalence."""
    pytest.importorskip("sklearn")
    from sklearn.decomposition import PCA

    n_samples, n_dim = 1000, 10
    X = np.random.RandomState(0).randn(n_samples, n_dim)
    X[:, -1] = np.mean(X[:, :-1], axis=-1)  # true X dim is ndim - 1
    X_orig = X.copy()
    pca_skl = PCA(n_components, whiten=whiten, svd_solver="full")
    pca_mne = _PCA(n_components, whiten=whiten)
    X_skl = pca_skl.fit_transform(X)
    assert_array_equal(X, X_orig)
    X_mne = pca_mne.fit_transform(X)
    assert_array_equal(X, X_orig)
    assert_allclose(X_skl, X_mne)
    assert pca_mne.n_components_ == pca_skl.n_components_
    for key in (
        "mean_",
        "components_",
        "explained_variance_",
        "explained_variance_ratio_",
    ):
        val_skl, val_mne = getattr(pca_skl, key), getattr(pca_mne, key)
        assert_allclose(val_skl, val_mne)
    if isinstance(n_components, float):
        assert pca_mne.n_components_ == n_dim - 1
    elif isinstance(n_components, int):
        assert pca_mne.n_components_ == n_components
    elif n_components == "mle":
        assert pca_mne.n_components_ == n_dim - 1
    else:
        assert n_components is None
        assert pca_mne.n_components_ == n_dim

def test_array_equal_nan():
    """Test comparing arrays with NaNs."""
    a = b = [1, np.nan, 0]
    assert not np.array_equal(a, b)  # this is the annoying behavior we avoid
    assert _array_equal_nan(a, b)
    b = [np.nan, 1, 0]
    assert not _array_equal_nan(a, b)
    a = b = [np.nan] * 2
    assert _array_equal_nan(a, b)

def test_julian_conversions():
    """Test julian calendar conversions."""
    # https://aa.usno.navy.mil/data/docs/JulianDate.php
    # A.D. 1922 Jun 13  12:00:00.0  2423219.000000
    # A.D. 2018 Oct 3   12:00:00.0  2458395.000000

    jds = [2423219, 2458395, 2445701]
    dds = [
        datetime(1922, 6, 13, 12, 0, 0, tzinfo=timezone.utc),
        datetime(2018, 10, 3, 12, 0, 0, tzinfo=timezone.utc),
        datetime(1984, 1, 1, 12, 0, 0, tzinfo=timezone.utc),
    ]
    cals = [(1922, 6, 13), (2018, 10, 3), (1984, 1, 1)]

    for dd, cal, jd in zip(dds, cals, jds):
        assert dd == _julian_to_dt(jd)
        assert cal == _julian_to_cal(jd)

        assert jd == _dt_to_julian(dd)
        assert jd == _cal_to_julian(cal[0], cal[1], cal[2])

def test_grand_average_empty_sequence():
    """Test if mne.grand_average handles an empty sequence correctly."""
    with pytest.raises(ValueError, match="Please pass a list of Evoked"):
        grand_average([])

def test_grand_average_len_1():
    """Test if mne.grand_average handles a sequence of length 1 correctly."""
    # returns a list of length 1
    evokeds = read_evokeds(ave_fname, condition=[0], proj=True)

    with pytest.warns(RuntimeWarning, match="Only a single dataset"):
        gave = grand_average(evokeds)

    assert_allclose(gave.data, evokeds[0].data)

def test_reuse_cycle():
    """Test _ReuseCycle."""
    vals = "abcde"
    iterable = _ReuseCycle(vals)
    assert "".join(next(iterable) for _ in range(2 * len(vals))) == vals + vals
    # we're back to initial
    assert "".join(next(iterable) for _ in range(2)) == "ab"
    iterable.restore("a")
    assert "".join(next(iterable) for _ in range(10)) == "acdeabcdea"
    assert "".join(next(iterable) for _ in range(4)) == "bcde"
    # we're back to initial
    assert "".join(next(iterable) for _ in range(3)) == "abc"
    iterable.restore("a")
    iterable.restore("b")
    iterable.restore("c")
    assert "".join(next(iterable) for _ in range(5)) == "abcde"
    # we're back to initial
    assert "".join(next(iterable) for _ in range(3)) == "abc"
    iterable.restore("a")
    iterable.restore("c")
    assert "".join(next(iterable) for _ in range(4)) == "acde"
    assert "".join(next(iterable) for _ in range(5)) == "abcde"
    # we're back to initial
    assert "".join(next(iterable) for _ in range(3)) == "abc"
    iterable.restore("c")
    iterable.restore("a")
    with pytest.warns(RuntimeWarning, match="Could not find"):
        iterable.restore("a")
    assert "".join(next(iterable) for _ in range(4)) == "acde"
    assert "".join(next(iterable) for _ in range(5)) == "abcde"

@pytest.mark.parametrize("n", (0, 1, 10, 1000))
@pytest.mark.parametrize("d", (0.0001, 1, 2.5, 1000))
def test_arange_div(numba_conditional, n, d):
    """Test Numba arange_div."""
    want = np.arange(n) / d
    got = numerics._arange_div(n, d)
    assert_allclose(got, want)

def test_custom_lru_cache():
    """Test our _custom_lru_cache implementation."""
    n_calls = [0, 0]
    start_size = len(_LRU_CACHES)

    @_custom_lru_cache(2)
    def my_fun(*args):
        n_calls[0] += 1
        return ", ".join(arg.__class__.__name__ for arg in args)

    assert len(_LRU_CACHES) == start_size + 1
    fun_hash = list(_LRU_CACHES)[-1]
    assert _LRU_CACHE_MAXSIZES[fun_hash] == 2

    @_custom_lru_cache(1)
    def my_fun_2(*args):
        n_calls[1] += 1
        return ", ".join(arg.__class__.__name__ for arg in args)

    assert len(_LRU_CACHES) == start_size + 2
    fun_2_hash = list(_LRU_CACHES)[-1]
    assert _LRU_CACHE_MAXSIZES[fun_2_hash] == 1

    assert n_calls == [0, 0]
    assert my_fun(1, 2, 3) == "int, int, int"
    assert n_calls == [1, 0]
    assert my_fun_2(1, 2, 3.0) == "int, int, float"
    assert n_calls == [1, 1]
    # repeated calls use cached version
    assert my_fun(1, 2, 3) == "int, int, int"
    assert n_calls == [1, 1]
    assert my_fun_2(1, 2, 3.0) == "int, int, float"
    assert n_calls == [1, 1]
    assert len(_LRU_CACHES[fun_hash]) == 1
    assert len(_LRU_CACHES[fun_2_hash]) == 1
    assert my_fun(1, np.array([2]), 3) == "int, ndarray, int"
    assert n_calls == [2, 1]
    assert len(_LRU_CACHES[fun_hash]) == 2
    assert my_fun_2(1, sparse.eye(1, format="csc")) == "int, csc_matrix"
    assert n_calls == [2, 2]
    assert len(_LRU_CACHES[fun_2_hash]) == 1  # other got popped
    # we could add support for this eventually, but don't bother for now
    with pytest.raises(RuntimeError, match="Unsupported sparse type"):
        my_fun_2(1, sparse.eye(1, format="coo"))
    assert n_calls == [2, 2]  # never did any computation


import requests
from lxml import etree
import os

url = 'https://pic.netbian.com/4kyouxi/'
headers = {
    'User-Agent' :'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36'
}
page_text = requests.get(url=url,headers=headers).text
tree = etree.HTML(page_text)
if not os.path.exists('picLibs'):
    os.mkdir('picLibs')
li_list = tree.xpath('//div[@class="slist"]/ul/li')
for li in li_list:
    img_src = 'https://pic.netbian.com/'+li.xpath('./a/img/@src')[0]
    img_name = li.xpath('./a/img/@alt')[0]
    img_name = img_name.encode('iso-8859-1').decode('gbk')
    img_data = requests.get(img_src,headers).content
    img_path = 'picLibs/' + img_name + '.jpg'
    print(img_src + ' ' + img_name)
    with open(img_path,'wb') as fp:
        fp.write(img_data)
        print(img_name+ '：'+'下载成功！')


from selenium import webdriver
import selenium
from selenium.webdriver.common.keys import Keys
import time

driver = webdriver.Chrome()
driver.get ("https://www.anr.org.py/consulta-padron-nacional/")

#Tiempo de espera para dejar que cargue la página
time.sleep(3)

#Cambio al segundo frame
frame = driver.find_element_by_tag_name('iframe')
driver.switch_to.frame(frame)

def consulta (driver,cedula):
    """Función que retorna una lista con datos del numero de cedula ingresado como parametro"""
    cedula = cedula
    cedula_in = driver.find_element_by_xpath("//input[@name='cedula']")
    cedula_in.clear()
    cedula_in.send_keys(cedula)
    cedula_in.send_keys(Keys.RETURN)
    time.sleep(1.5)
    datos =driver.find_elements_by_xpath("//li[@class='consulta-item list-group-item']")
    data_list = []
    for x in datos:
        data_list.append(x.text)
    return data_list

#Numero de cedula SEBAS 5898204
print (consulta(driver,'5898204'))

#Numero de cedula ESTEBAN 5425495
print (consulta(driver,'5425495'))


import json
import numpy as np
from os.path import dirname, realpath

class Node:

    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.xRestraint = False
        self.yRestraint = False
        self.momentRestraint = False
        self.xLoad = 0
        self.yLoad = 0
        self.moment = 0

    def __repr__(self):
        return f'({self.x}, {self.y})'

    def __eq__(self, other):
        return True if self.x == other.x and self.y == other.y else False

    def x(self):
        return self.x

    def y(self):
        return self.y

    def setXRestraint(self, value):
        self.xRestraint = value

    def setYRestraint(self, value):
        self.yRestraint = value

    def setMomentRestraint(self, value):
        self.momentRestraint = value

    def setXLoad(self, value):
        self.xLoad = value

    def setYLoad(self, value):
        self.yLoad = value

    def setMoment(self, value):
        self.moment = value

class Element:

    def __init__(self, n1, n2):
        self.n1 = n1
        self.n2 = n2

    def __repr__(self):
        return f'[{self.node1}, {self.node2}]'

    def __eq__(self, other):
        if (self.n1 == other.n1 and self.n2 == other.n2) or (self.n1 == other.n2 and self.n2 == other.n1):
            return True
        else:
            return False

    def notIn(self, elements):
        for element in elements:
            sameP1 = (self.n1.x == element.node1.x and self.n1.y == element.node1.y)
            sameP2 = (self.n2.x == element.node2.x and self.n2.y == element.node2.y)
            switchedP1 = (self.n1.x == element.node2.x and self.n1.y == element.node2.y)
            switchedP2 = (self.n2.x == element.node1.x and self.n2.y == element.node1.y)
            if (sameP1 and sameP2) or (switchedP1 and switchedP2):
                return False
        return True

class Model:

    def __init__(self):
        self.nodes = []
        self.elements = []
        self.solution = [np.inf]
        self.brokenElements = None
        self.compressionLimit = 0
        self.tractionLimit = 0
        self.momentLimit = 0
        self.solution = None

    def addNode(self, node):
        self.nodes.append(node)

    def addElement(self, element):
        self.elements.append(element)

    def delNode(self):
        try:
            del self.nodes[-1]
        except Exception:
            pass

    def delElement(self):
        try:
            del self.elements[-1]
        except Exception:
            pass

    def setCompressionLimit(self, value):
        self.compressionLimit = value

    def setTractionLimit(self, value):
        self.tractionLimit = value

    def setMomentLimit(self, value):
        self.momentLimit = value

    def fromJSON(self, fileName):
        self.__init__()
        with open(fileName) as file:
            data = json.load(file)

        for i, node in enumerate(data['nodes coordinates']):
            x, y = node

            xRestraint = data['restraints'][i][0]
            yRestraint = data['restraints'][i][1]
            momentRestraint = data['restraints'][i][2]

            xLoad = data['loads'][i][0]
            yLoad = data['loads'][i][1]
            moment = data['loads'][i][2]

            self.addNode(Node(x, y))
            self.nodes[i].setXRestraint(bool(xRestraint))
            self.nodes[i].setYRestraint(bool(yRestraint))
            self.nodes[i].setMomentRestraint(bool(momentRestraint))
            self.nodes[i].setXLoad(xLoad)
            self.nodes[i].setYLoad(yLoad)
            self.nodes[i].setMoment(moment)

        for i, element in enumerate(data['connectivity']):
            node1, node2 = element
            n1 = self.nodes[node1-1]
            n2 = self.nodes[node2-1]
            element = Element(n1, n2)
            self.addElement(element)

        self.compressionLimit = abs(data['element properties'][0])
        self.tractionLimit = data['element properties'][1]
        self.momentLimit = data['moment capacity']

    def toJSON(self, fileName):
        nodesCoordinates = [[node.x, node.y] for node in self.nodes]
        restraints = [[int(n.xRestraint), int(n.yRestraint), int(n.momentRestraint)] for n in self.nodes]
        loads = [[n.xLoad, n.yLoad, n.moment] for n in self.nodes]
        connectivity = [[self.nodes.index(element.n1)+1, self.nodes.index(element.n2)+1] for element in self.elements]
        elementProperties = [-self.compressionLimit, self.tractionLimit]

        data = {
            'nodes coordinates': nodesCoordinates,
            'restraints': restraints,
            'loads': loads,
            'connectivity': connectivity,
            'element properties': elementProperties,
            'moment capacity': self.momentLimit
        }

        dirName = dirname(realpath(__file__))
        with open(f'{dirName}\{fileName}.json', 'w') as outfile:
            json.dump(data, outfile, indent=1)

    def toIFC(self, fileName):
        nodesCoordinates = [[node.x, node.y] for node in self.nodes]
        connectivity = [[self.nodes.index(element.n1)+1, self.nodes.index(element.n2)+1] for element in self.elements]

        numElements = len(connectivity)
        t = 0.05

        newCoords = []
        for e in range(numElements):
            n1, n2 = connectivity[e]
            x1, y1 = nodesCoordinates[n1-1]
            x2, y2 = nodesCoordinates[n2-1]
            dx = x2 - x1
            dy = y2 - y1
            L = np.sqrt(dx**2 + dy**2)
            cos = dx / L
            sin = dy / L
            x = t * sin
            y = t * cos
            p1 = (-t*1000, (x1+x)*1000, (y1-y)*1000)
            p2 = (-t*1000, (x1-x)*1000, (y1+y)*1000)
            p3 = (t*1000, (x1-x)*1000, (y1+y)*1000)
            p4 = (t*1000, (x1+x)*1000, (y1-y)*1000)
            p5 = (-t*1000, (x2+x)*1000, (y2-y)*1000)
            p6 = (-t*1000, (x2-x)*1000, (y2+y)*1000)
            p7 = (t*1000, (x2-x)*1000, (y2+y)*1000)
            p8 = (t*1000, (x2+x)*1000, (y2-y)*1000)
            V = (p1, p2, p3, p4, p5, p6, p7, p8)
            newCoords.append(V)

        dir_name = dirname(realpath(__file__))
        with open(f'{dir_name}/{fileName}.ifc', 'w') as outfile:
            outfile.write(
                "ISO-10303-21;\n"
                "HEADER;\n"
                "FILE_DESCRIPTION( ( 'ViewDefinition "
                    + "[notYetAssigned]' ,'Comment [manual "
                    + "creation of example file]' ) ,'2;1');\n"
                "FILE_NAME( 'IfcBuildingElementProxy_Tessellation.ifc', "
                    + "'2012-07-04T18:00:00', ('Thomas Liebich'), "
                    + "('buildingSMART International'), 'IFC text editor', "
                    + "'IFC text editor', 'reference file created for the "
                    + "IFC4 specification');\n"
                "FILE_SCHEMA(('IFC4'));\n"
                "ENDSEC;\n"
                "DATA;\n"
                "#100= IFCPROJECT ('0xScRe4drECQ4DMSqUjd6d',#110,'proxy with "
                    + "tessellation',$,$,$,$,(#201),#301);\n"
                "#110= IFCOWNERHISTORY (#111,#115,$,.ADDED.,1320688800,$,$, "
                    + "1320688800);\n"
                "#111= IFCPERSONANDORGANIZATION (#112,#113,$);\n"
                "#112= IFCPERSON ($,'Liebich','Thomas',$,$,$,$,$);\n"
                "#113= IFCORGANIZATION ($,'buildingSMART International', "
                    + "$,$,$);\n"
                "#115= IFCAPPLICATION (#113,'1.0','IFC text editor', "
                    + "'ifcTE');\n"
                "#201= IFCGEOMETRICREPRESENTATIONCONTEXT ($,'Model',3,1.0E-5, "
                    + "#210,$);\n"
                "#202= IFCGEOMETRICREPRESENTATIONSUBCONTEXT ('Body','Model', "
                    + "*,*,*,*,#201,$,.MODEL_VIEW.,$);\n"
                "#210= IFCAXIS2PLACEMENT3D (#901,$,$);\n"
                "#301= IFCUNITASSIGNMENT ((#311,#312));\n"
                "#311= IFCSIUNIT (*,.LENGTHUNIT.,.MILLI.,.METRE.);\n"
                "#312= IFCCONVERSIONBASEDUNIT (#313,.PLANEANGLEUNIT., "
                    + "'degree',#314);\n"
                "#313= IFCDIMENSIONALEXPONENTS (0,0,0,0,0,0,0);\n"
                "#314= IFCMEASUREWITHUNIT (IFCPLANEANGLEMEASURE(0.017453293), "
                    + "#315);\n"
                "#315= IFCSIUNIT (*,.PLANEANGLEUNIT.,$,.RADIAN.);\n"
                "#500= IFCBUILDING ('2FCZDorxHDT8NI01kdXi8P',$,'Test "
                    + "Building',$,$,#511,$,$,.ELEMENT.,$,$,$);\n"
                "#511= IFCLOCALPLACEMENT ($,#512);\n"
                "#512= IFCAXIS2PLACEMENT3D (#901,$,$);\n"
                "#519= IFCRELAGGREGATES ('2YBqaV_8L15eWJ9DA1sGmT',$,$,$,#100, "
                    + "(#500));\n"
                "#901= IFCCARTESIANPOINT ((0.,0.,0.));\n"
                "#902= IFCDIRECTION ((1.,0.,0.));\n"
                "#903= IFCDIRECTION ((0.,1.,0.));\n"
                "#904= IFCDIRECTION ((0.,0.,1.));\n"
                "#905= IFCDIRECTION ((-1.,0.,0.));\n"
                "#906= IFCDIRECTION ((0.,-1.,0.));\n"
                "#907= IFCDIRECTION ((0.,0.,-1.));\n"
                "#1000= IFCBUILDINGELEMENTPROXY ('1kTvXnbbzCWw8lcMd1dR4o',$, "
                    + "'P-1','sample proxy',$,#1001,#1010,$,$);\n"
                "#1001= IFCLOCALPLACEMENT (#511,#1002);\n"
                "#1002= IFCAXIS2PLACEMENT3D (#1003,$,$);\n"
                "#1003= IFCCARTESIANPOINT ((1000.,0.,0.));\n")

            elements = []
            n = 1000
            for i in range(numElements):
                n += 20
                elements.append(n)
            indexes = elements
            elements = str(elements)

            i = 1
            for j in range(numElements):
                elements = elements[:i] + '#' + elements[i:]
                i = elements.find(',', i, len(elements))
                i += 2

            elements = elements.replace('[', '(')
            elements = elements.replace(']', ')')

            outfile.write \
                (f"#1010= IFCPRODUCTDEFINITIONSHAPE ($,$,{elements});\n")

            for i in range(numElements):
                outfile.write(
                    f"#{indexes[i]}= IFCSHAPEREPRESENTATION (#202,'Body',"
                        + f"'Tessellation',(#{indexes[i]+1}));\n"
                    f"#{indexes[i]+1}= IFCTRIANGULATEDFACESET "
                        + f"(#{indexes[i]+2},$,.T.,((1,6,5),(1,2,6),(6,2,7),"
                        + "(7,2,3),(7,8,6),(6,8,5),(5,8,1),(1,8,4),(4,2,1),"
                        + "(2,4,3),(4,8,7),(7,3,4)),$);\n"
                    f"#{indexes[i]+2}= IFCCARTESIANPOINTLIST3D "
                        + f"({newCoords[i]});\n")

            outfile.write(
                "#10000= IFCRELCONTAINEDINSPATIALSTRUCTURE "
                + "('2TnxZkTXT08eDuMuhUUFNy',$,'Physical model',$,(#1000), "
                + "#500);\n"
                "ENDSEC;\n"
                "END-ISO-10303-21;")

    def eraseBrokenElements(self):
        self.brokenElements = None


#!/usr/bin/env python
# coding: utf-8

# In[1]:

import json

import pandas as pd
import numpy as np
import dash
from dash.dependencies import Input, Output
import plotly.express as px
import dash_bootstrap_components as dbc
from dash import dcc, html, callback
import matplotlib.pyplot as plt
import io
import base64
import joypy
import pathlib

# #### Instantiate the app

dash.register_page(__name__, path='/',name ='Analytics-1')
#get relative path of datasets
PATH = pathlib.Path(__file__).parent
DATA_PATH = PATH.joinpath("../datasets").resolve()
data = pd.read_csv(DATA_PATH.joinpath("dataframe.csv"))

columns1 = ['popularity', 'danceability', 'acousticness', 'energy', 'instrumentalness', 'key', 'liveness', 'loudness', 'speechiness', 'tempo', 'valence', 'length', 'rock_era']

layout = dbc.Container([
    dbc.Row([
        dbc.Col(children =[
        html.Br(),
        html.H1('Analytics-1',
                style={'textAlign': 'center', 'font-size': '21px', "margin": '0px 0px 0px 0px'}

        ),
        html.Br(),

        ], xs=12, sm=12, md=11, lg=11, xl=11, xxl=11)

    ], justify='center'),

    dbc.Row([

        dbc.Col(children=[
            html.H3('Attribute Selection Controls', style = {'textAlign':'center', 'font-size':'20px', "color":'SeaGreen', "margin":'0px 0px 0px 0px'}),

            html.Hr(style ={"color":'red', 'borderWidth':'2px', 'margin': '0px 0px 0px 0px'})
              ], xs = 12, sm = 12, md = 12, lg=12, xl=12, xxl= 12),

        dbc.Col([
            dcc.Checklist(id ='checklist', options=[col for col in data.columns if col not in ['rock_era', 'name','artist', 'release_date', 'time_signature']], inline=False,
                          value = ['acousticness', 'popularity', 'energy', 'danceability'],
#                                    ,'popularity', 'energy', 'danceability'],
                          labelStyle = {"display":'inline-block', 'align-items': 'middle', "width": '30%','margin': '0px 0px 0px 0px'},
                         labelClassName ='mr-4, text-info', style = {'transform':'scale(0.7)'}),

        ], width ={'size':'8px', 'offset':2})

    ], justify ='center'),

    dbc.Row([
        dbc.Col(children=[
            html.Br(),
            html.Br(),
            html.H4('Distributions Plot',
                   style = {'font-size': "20px", 'color':'#1214A1', 'textAlign': 'left' }),

            html.Br(),
            html.Br(),
            html.Img(id = 'matplot_graph', style = {'max-width':'100%', "margin":'0px 0px 0px -30px'})

            ],xs = 10, sm= 10, md = 6, lg=5, xl=5, xxl=5),

        dbc.Col( children=[
            html.Br(),

            html.H4('Correlation Heatmap', style = {'font-size': "18px", 'color':'#1214A1', 'margin':'23px 0px 0px 70px'}),
            html.P('Click on cell to get the corresponding scatterplot below',
                   style={'font-size': "12px", 'color': 'red', 'margin': '23px 0px 0px 70px'}),
            # html.H6('Click on cell to get the corresponding scatterplot',
            #         style = {'font-size': "10px", 'color':'red','textAlign': 'center'}),

            dcc.Graph(id = 'heatmap',  config={'responsive': True}),
            # html.H6('Click on cell to get the corresponding scatterplot',
            #         style = {'font-size': "10px", 'color':'red','textAlign': 'center', "margin": '0px 0px 100px -5px'}),

            html.H4('Scatter Plot', style = {'font-size': "18px", 'color':'#1214A1', 'margin':'23px 0px 0px 70px'}),

#             html.P(id = 'click-text'),
            dcc.Graph(id= 'scatter_plot',  config={'responsive': True})

        ] ,xs = 12, sm = 12, md = 6, lg=5, xl=5, xxl=5)
    ],justify = 'around'),

   ])

@callback(
    Output(component_id ='matplot_graph', component_property ='src'),
    Output(component_id='heatmap', component_property = 'figure'),
    Input(component_id = 'checklist', component_property = 'value'),

)

def update_ridgeplot(checkbox):

    if checkbox:
        data1 = data.copy(deep= True)
#         column = data1.columns
        columns = [col for col in checkbox]
        columns.append('rock_era')
        dataframe= data1[columns]
        fig, ax = joypy.joyplot (dataframe, by = 'rock_era',
                        figsize = (5.5,7.5), alpha = 0.8,)
                                 # labels=labels)
        legend = ax[0].legend()
        legend.set_title('')
        legend.get_frame().set_facecolor('none')
        legend.get_frame().set_visible(False)
        legend.get_title().set_fontsize(6)
        for label in legend.get_texts():
            label.set_fontsize(6)

        plt.rc('font', size = 10)

        buf = io.BytesIO()
        plt.savefig(buf, format = "png")
        plt.close(fig)
        buf.seek(0)

        pic = base64.b64encode(buf.read()).decode('utf-8')
        df_corr= round(dataframe.drop(['rock_era'], axis=1).corr(method = 'pearson'), 2)
                                       # "name", 'artist', 'time_signature'], axis=1).corr(numeric_only = False, method = 'pearson'), 2)
                                       #
        heatmap = px.imshow(df_corr, text_auto = True, color_continuous_scale =
                            'rdbu_r').update_layout(height = 500).update_coloraxes(showscale=False)

        return "data:image/png;base64,{}".format(pic), heatmap

@callback(
#     Output('click-text', 'children'),
    Output('scatter_plot', 'figure'),
    Input('heatmap', 'clickData'))

def capture_click_data(clickData):
    data2 = data.copy(deep = True)
    if clickData is None:
        return px.scatter(data_frame = data2, x = 'acousticness',
                              y='energy',
                             color = "rock_era").update_layout(legend=dict(yanchor="top",
                                                                           y=-0.15,
                                                                           xanchor="right",
                                                                           x=0.5),
                                                               legend_title_text="")
    x_value= clickData["points"][0]["x"]
    y_value = clickData["points"][0]["y"]

    if x_value == y_value:
        return dash.no_update

    else:
        x_value= clickData["points"][0]["x"]
        y_value = clickData["points"][0]["y"]
        scatter_data = data2[[x_value, y_value, 'rock_era']]
        fig2 = px.scatter(data_frame = scatter_data,
                         x= x_value,
                         y= y_value,
                         color ='rock_era', opacity = 0.9).update_layout(legend = {'yanchor':'top',
                                                                                'y':-0.15,
                                                                                'xanchor':'right',
                                                                                'x':0.5},
        legend_title_text ="").update_traces(marker = dict(size=6, line={'color':'DarkSlateGrey'}))

        return fig2


import os
from PIL import Image
import torch.utils.data as data
import torchvision.transforms as transforms

class SalObjDataset(data.Dataset):
    def __init__(self, image_root, gt_root, trainsize):
        self.trainsize = trainsize
        self.images = [image_root + f for f in os.listdir(image_root) if f.endswith('.jpg')]
        self.gts = [gt_root + f for f in os.listdir(gt_root) if f.endswith('.png') and not f.endswith('edge.png')]
        self.egs = [gt_root + f for f in os.listdir(gt_root) if f.endswith('edge.png')]
        self.images = sorted(self.images)
        self.gts = sorted(self.gts)
        self.egs = sorted(self.egs)
        self.size = len(self.images)

        self.img_transform = transforms.Compose([
            transforms.Resize((self.trainsize, self.trainsize)),
            transforms.ToTensor(),
            transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])
        self.gt_transform = transforms.Compose([
            transforms.Resize((self.trainsize, self.trainsize)),
            transforms.ToTensor()])
        self.eg_transform = transforms.Compose([
            transforms.Resize((self.trainsize, self.trainsize)),
            transforms.ToTensor()])

    def __getitem__(self, index):
        image = self.rgb_loader(self.images[index])
        gt = self.binary_loader(self.gts[index])
        eg = self.binary_loader(self.egs[index])
        image = self.img_transform(image)
        gt = self.gt_transform(gt)
        eg = self.eg_transform(eg)
        return {'sal_image': image, 'sal_label': gt, 'sal_edge': eg}

    def rgb_loader(self, path):
        with open(path, 'rb') as f:
            img = Image.open(f)
            return img.convert('RGB')

    def binary_loader(self, path):
        with open(path, 'rb') as f:
            img = Image.open(f)
            return img.convert('L')

    def __len__(self):
        return self.size

def get_loader(image_root, gt_root, trainsize, batchsize, shuffle=True, num_workers=1, pin_memory=False, drop_last=True):

    dataset = SalObjDataset(image_root, gt_root, trainsize)
    data_loader = data.DataLoader(dataset=dataset,
                                  batch_size=batchsize,
                                  shuffle=shuffle,
                                  num_workers=num_workers,
                                  pin_memory=pin_memory,
                                  drop_last=drop_last)
    return data_loader

class test_dataset:
    def __init__(self, image_root, testsize):
        self.testsize = testsize
        self.images = [image_root + f for f in os.listdir(image_root) if f.endswith('.jpg')]
        self.images = sorted(self.images)
        self.transform = transforms.Compose([
            transforms.Resize((self.testsize, self.testsize)),
            transforms.ToTensor(),
            transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])
        self.size = len(self.images)
        self.index = 0

    def load_data(self):
        image = self.rgb_loader(self.images[self.index])
        shape = image.size
        shape = (shape[1], shape[0])
        image = self.transform(image).unsqueeze(0)
        name = self.images[self.index].split('/')[-1]
        if name.endswith('.jpg'):
            name = name.split('.')[0]
        self.index += 1
        return image, shape, name

    def rgb_loader(self, path):
        with open(path, 'rb') as f:
            img = Image.open(f)
            return img.convert('RGB')


import typing

from django.contrib.contenttypes.models import ContentType
from rest_framework.decorators import action
from rest_framework.request import Request
from rest_framework.response import Response

from community.models import Rating

class CreateRatingMixin:
    @action(detail=True, methods=["POST"], url_name="create-rating")
    def create_rating(
        self, request: Request, *args: typing.Any, **kwargs: typing.Any
    ) -> Response:
        object_id: int = kwargs["pk"]
        content_type = ContentType.objects.get_for_model(
            model=request.parser_context["view"].queryset.model
        )
        rating_star = request.data["rating_star"]
        user = request.user
        rating = Rating(
            rating_star=rating_star,
            user=user,
            object_id=object_id,
            content_type=content_type,
        )
        rating.save()
        return Response({"status": 200})


from decimal import Decimal

import pytest

import requests

from ibptws.calculadoras import DeOlhoNoImposto
from ibptws.calculadoras import CEM

def test_deolhonoimposto_inicio():
    calc = DeOlhoNoImposto()
    assert calc.carga_federal().is_zero()
    assert calc.carga_federal_nacional().is_zero()
    assert calc.carga_federal_importado().is_zero()
    assert calc.carga_estadual().is_zero()
    assert calc.carga_municipal().is_zero()
    assert calc.total_tributos().is_zero()
    assert calc.total().is_zero()
    assert calc.percentual_sobre_total().is_zero()

def test_deolhonoimposto_um_item(monkeypatch):
    def mockreturn(endpoint, params={}):
        return pytest.instancia_resp_sucesso_produto
    monkeypatch.setattr(requests, 'get', mockreturn)

    valor = Decimal('10') # subtotal do produto

    # os valores das alíquotas retornadas estão em conftest.py
    carga_fed_nac = valor * (Decimal('4.2') / CEM)
    carga_fed_imp = valor * (Decimal('4.8') / CEM)
    carga_estadual = valor * (Decimal('18') / CEM)

    calc = DeOlhoNoImposto()
    calc.produto('12340101', 0, valor)

    assert calc.total() == valor, 'Total nao confere com o valor do unico item'
    assert calc.total() > calc.total_tributos(), 'Soma dos valores dos '\
            'itens menor ou igual ao valor total dos tributos'

    assert calc.carga_federal_nacional() == carga_fed_nac
    assert calc.carga_federal_importado() == carga_fed_imp
    assert calc.carga_federal() == carga_fed_nac + carga_fed_imp
    assert calc.carga_estadual() == carga_estadual
    assert calc.carga_municipal().is_zero()

    assert calc.total_tributos() == sum([
            carga_fed_nac, carga_fed_imp, carga_estadual,])

    assert calc.total() == valor

    # testa o reinicio da calculadora
    calc.reiniciar()
    assert calc.carga_federal().is_zero()
    assert calc.carga_federal_nacional().is_zero()
    assert calc.carga_federal_importado().is_zero()
    assert calc.carga_estadual().is_zero()
    assert calc.carga_municipal().is_zero()
    assert calc.total_tributos().is_zero()
    assert calc.total().is_zero()
    assert calc.percentual_sobre_total().is_zero()

def test_deolhonoimposto_multiplos_itens(monkeypatch):
    def mockreturn(endpoint, params={}):
        dados = {
                '12340101': pytest.instancia_resp_sucesso_produto,
                '12340202': pytest.instancia_resp_sucesso_produto_alt_a,
                '12340303': pytest.instancia_resp_sucesso_produto_alt_b,
                '0123': pytest.instancia_resp_sucesso_servico,
                '0124': pytest.instancia_resp_sucesso_servico_alt_a,}
        return dados.get(params.get('codigo'))
    monkeypatch.setattr(requests, 'get', mockreturn)

    calc = DeOlhoNoImposto()

    calc.produto('12340101', 0, Decimal('5.00'))
            # nacional     4,2% : 0,21
            # importado    4,8% : 0,24
            # estadual      18% : 0,9
            # muncipal       0% : 0          total tributos: 1,35

    calc.produto('12340202', 0, Decimal('15.50'))
            # nacional     4,2% : 0,651
            # importado   5,41% : 0,83855
            # estadual       0% : 0
            # muncipal       0% : 0          total tributos: 1,48955

    calc.produto('12340303', 0, Decimal('7.30'))
            # nacional     4,2% : 0,3066
            # importado   6,18% : 0,45114
            # estadual      12% : 0,876
            # muncipal       0% : 0          total tributos: 1,63374

    calc.servico('0123', Decimal('100'))
            # nacional   13,45% : 13,45
            # importado  14,05% : 14,05
            # estadual       0% :  0
            # muncipal    4,33% :  4,33      total tributos: 31,83

    calc.servico('0124', Decimal('575.77'))
            # nacional   13,45% : 77,441065
            # importado  14,05% : 80,895685
            # estadual       0% :  0
            # muncipal    3,55% : 20,439835  total tributos: 178,776585

    # total (soma dos valores dos itens) : R$ 703,57
    # valor total dos tributos           : R$ 215,079875
    # % total dos tributos sobre o valor : 30,569790497%

    carga_fed_nac = sum([
            Decimal('0.21'),
            Decimal('0.651'),
            Decimal('0.3066'),
            Decimal('13.45'),
            Decimal('77.441065'),])

    carga_fed_imp = sum([
            Decimal('0.24'),
            Decimal('0.83855'),
            Decimal('0.45114'), # inclui os zeros para ilustrar
            Decimal('14.05'),
            Decimal('80.895685'),])

    carga_estadual = sum([
            Decimal('0.9'),
            Decimal('0'),
            Decimal('0.876'),
            Decimal('0'),
            Decimal('0'),])

    carga_municipal = sum([
            Decimal('0'),
            Decimal('0'),
            Decimal('0'),
            Decimal('4.33'),
            Decimal('20.439835'),])

    total_tributos = sum([
            carga_fed_nac,
            carga_fed_imp,
            carga_estadual,
            carga_municipal,])

    total = Decimal('703.57')
    p_sobre_total = total_tributos / total

    assert calc.total() == total, 'Total nao confere com o valor do unico item'
    assert calc.total() > calc.total_tributos(), 'Soma dos valores dos '\
            'itens menor ou igual ao valor total dos tributos'

    assert calc.carga_federal_nacional() == carga_fed_nac
    assert calc.carga_federal_importado() == carga_fed_imp
    assert calc.carga_federal() == carga_fed_nac + carga_fed_imp
    assert calc.carga_estadual() == carga_estadual
    assert calc.carga_municipal() == carga_municipal

    assert calc.total_tributos() == total_tributos

    assert calc.total() == total
    assert calc.percentual_sobre_total() == p_sobre_total

    # testa o reinicio da calculadora
    calc.reiniciar()
    assert calc.carga_federal().is_zero()
    assert calc.carga_federal_nacional().is_zero()
    assert calc.carga_federal_importado().is_zero()
    assert calc.carga_estadual().is_zero()
    assert calc.carga_municipal().is_zero()
    assert calc.total_tributos().is_zero()
    assert calc.total().is_zero()
    assert calc.percentual_sobre_total().is_zero()