import logging, base64, io

from fastapi import APIRouter, Request
from fastapi.responses import HTMLResponse
from oic.oic.message import (
    AuthorizationRequest,
    AccessTokenRequest,
    AccessTokenResponse,
    IdToken,
)
import qrcode

from fastapi import APIRouter, Request, Depends
from sqlalchemy.ext.asyncio import AsyncSession
from ..db.session import get_async_session
from ..core.config import settings

from ..core.acapy.client import AcapyClient
from ..core.oidc.issue_token_service import Token
from ..authSessions.crud import AuthSessionCRUD, AuthSessionCreate
from ..verificationConfigs.crud import VerificationConfigCRUD

ChallengePollUri = "/poll"
AuthorizeCallbackUri = "/callback"
VerifiedCredentialAuthorizeUri = "/authorize"
VerifiedCredentialTokenUri = "/token"

logger = logging.getLogger(__name__)

router = APIRouter()

@router.post(VerifiedCredentialAuthorizeUri, response_model=dict)
async def post_authorize(request: Request):
    """Called by oidc platform."""
    logger.debug(f">>> post_authorize")
    logger.debug(f"payload ={request}")

    return {}

@router.get(f"{ChallengePollUri}/{{pid}}")
async def poll_pres_exch_complete(
    pid: str, session: AsyncSession = Depends(get_async_session)
):
    """Called by authorize webpage to see if request is verified and token issuance can proceed."""

    auth_sessions = AuthSessionCRUD(session)
    auth_session = await auth_sessions.get_by_pres_exch_id(pid)

    return {"verified": auth_session.verified}

@router.get(VerifiedCredentialAuthorizeUri, response_class=HTMLResponse)
async def get_authorize(
    request: Request,
    state: str,
    session: AsyncSession = Depends(get_async_session),
):
    """Called by oidc platform."""
    logger.debug(f">>> get_authorize")

    # Verify OIDC forward payload
    model = AuthorizationRequest().from_dict(request.query_params._dict)
    model.verify()

    client = AcapyClient()
    ver_config_id = model.get("pres_req_conf_id")

    auth_sessions = AuthSessionCRUD(session)
    ver_configs = VerificationConfigCRUD(session)
    ver_config = await ver_configs.get(ver_config_id)
    logger.warn(ver_config)

    # Create presentation_request to show on screen
    response = client.create_presentation_request(ver_config.generate_proof_request())

    new_auth_session = AuthSessionCreate(
        request_parameters=model.to_dict(),
        ver_config_id=ver_config_id,
        pres_exch_id=response.presentation_exchange_id,
        presentation_exchange=response.dict(),
    )

    # save OIDC AuthSession
    auth_session = await auth_sessions.create(new_auth_session)

    # QR CONTENTS
    controller_host = settings.SELF_CONTROLLER_HOST_URL
    url_to_message = (
        controller_host + "/url/pres_exch/" + str(auth_session.pres_exch_id)
    )

    # CREATE an image
    buff = io.BytesIO()
    qrcode.make(url_to_message).save(buff, format="PNG")
    image_contents = base64.b64encode(buff.getvalue()).decode("utf-8")

    return f"""

            <title>Some HTML in here</title>

AUTHORIZATION REQUEST

Scan this QR code for a connectionless present-proof request

 User waits on this screen until Proof has been presented to the vcauth service agent, then is redirected to

            callback url (redirect to kc)

    """

@router.get(AuthorizeCallbackUri, response_class=HTMLResponse)
async def get_authorize_callback(
    request: Request,
    pid: str,
    session: AsyncSession = Depends(get_async_session),
):
    """Called by Authorize page when verification is complete"""
    logger.debug(f">>> get_authorize_callback")
    logger.debug(f"payload ={request}")

    redirect_uri = "http://localhost:8880/auth/realms/vc-authn/broker/vc-authn/endpoint"

    auth_sessions = AuthSessionCRUD(session)
    auth_session = await auth_sessions.get(pid)

    url = (
        redirect_uri
        + "?code="
        + str(auth_session.uuid)
        + "&state="
        + str(auth_session.request_parameters["state"])
    )
    return f"""

            <title>Resulting redirect</title>

The presentation is {"" if auth_session.verified else "NOT"} VERIFIED

            {url}

    """

@router.post(VerifiedCredentialTokenUri)
async def post_token(
    request: Request,
    session: AsyncSession = Depends(get_async_session),
):
    """Called by oidc platform to retreive token contents"""
    logger.info(f">>> post_token")
    form = await request.form()
    model = AccessTokenRequest().from_dict(form._dict)

    client = AcapyClient()

    auth_sessions = AuthSessionCRUD(session)
    auth_session = await auth_sessions.get(model.get("code"))

    ver_configs = VerificationConfigCRUD(session)
    ver_config = await ver_configs.get(auth_session.ver_config_id)

    presentation = client.get_presentation_request(auth_session.pres_exch_id)

    claims = Token.get_claims(presentation, auth_session, ver_config)

    token = Token(
        issuer="placeholder", audiences=["keycloak"], lifetime=10000, claims=claims
    )

    id_token = IdToken().from_dict(
        token.idtoken_dict(auth_session.request_parameters["nonce"])
    )
    id_token_jwt = id_token.to_jwt()
    values = {
        "token_type": "bearer",
        "id_token": id_token_jwt,
        "access_token": "invalid",
        "aud": "keycloak",
    }

    response = AccessTokenResponse().from_dict(values)
    logger.info(response)
    return response


import random
from typing import List, Tuple
import fitz  # install with 'pip install pymupdf'

from .NoteExtractor import NoteExtractorInterface

class PdfNotesExtractor(NoteExtractorInterface):
    def __init__(self, filePath):
        self.noteBody = fitz.open(filePath)

    def getRandomlyChosenNotes(self, numToReturn=3):
        """
        Returns a randomly selected number (based on the numToReturn arg) of
        notes/highlights from the collection of notes (self.noteBody)
        """
        allNotes = self._getAllHighlights()

        if len(allNotes) < numToReturn:
            return allNotes
        else:
            result = []
            for _ in range(numToReturn):
                note = random.choice(allNotes)
                result.append(note)
                allNotes.remove(note)

    def _getAllHighlights(self):
        highlights = []
        for page in self.noteBody:
            highlights += self._handle_page(page)

        return highlights

    def _handle_page(self, page):
        wordlist = page.getText("words")  # list of words on page
        wordlist.sort(key=lambda w: (w[3], w[0]))  # ascending y, then x

        highlights = []
        annot = page.firstAnnot
        while annot:
            # annot.type == 8 means its a highlight:
            # https://pymupdf.readthedocs.io/en/latest/vars.html#annotationtypes
            if annot.type[0] == 8:
                highlights.append(self._parse_highlight(annot, wordlist))
            annot = annot.next
        return highlights

    def _parse_highlight(self, annot, wordlist):
        points = annot.vertices
        # find how many quadrilaterals are in the doc
        quad_count = int(len(points) / 4)
        sentences = []
        for i in range(quad_count):
            # where the highlighted part is by intersecting
            # the rectangles
            r = fitz.Quad(points[i * 4 : i * 4 + 4]).rect
            words = [w for w in wordlist if fitz.Rect(w[:4]).intersects(r)]
            sentences.append(" ".join(w[4] for w in words))
        sentence = " ".join(sentences)
        return sentence


import numpy as np
import torch
from os.path import isfile
from prettyparse import Usage
from torch.optim.adamw import AdamW
from torch.optim.lr_scheduler import CyclicLR
from torch.utils.data import DataLoader
from tqdm import tqdm

from autodo.scripts.base_script import BaseScript
from autodo.stage_three_dataset import StageThreeDataset
from autodo.stage_three_model import MyUNet

class TrainStageThreeScript(BaseScript):
    usage = Usage('''
        Train the stage three network

        :model_file str
            Model file to load from/save to

        :-b --best-model-file
            Save best model file
    ''', best_model_file=lambda x: x.best_model_file or x.model_file) | StageThreeDataset.usage

    def run(self):
        args = self.args
        dataset = StageThreeDataset.from_args(args)
        train_stage_three(dataset, args.best_model_file, args.model_file)

main = TrainStageThreeScript.run_main

def train_stage_three(dataset, best_model_file, model_file):
    bestaccuracy = 0.9
    device = 'cudo:0' if torch.cuda.is_available() else 'cpu'
    net = MyUNet(3, device).to(device)
    net.train()
    for parameter in net.parameters():
        if len(parameter.shape) > 1:
            torch.nn.init.xavier_uniform_(parameter)
    if isfile(best_model_file):
        net.load_state_dict(torch.load(best_model_file))
    train_loader = DataLoader(dataset, batch_size=4, shuffle=True)
    optimizer = AdamW(net.parameters(), lr=0.0001)
    scheduler = CyclicLR(
        optimizer, 0.000001, 0.0001, step_size_up=200,
        mode='triangular2', cycle_momentum=False, last_epoch=-1
    )
    L1 = torch.nn.L1Loss(size_average=False)

    for epoch in range(50):
        for (images, targets, out_masks) in tqdm(train_loader):
            images = images.to(device)
            targets = targets.to(device)
            out_masks = out_masks.to(device)
            optimizer.zero_grad()
            outputs = net(images)
            loss = L1(outputs * out_masks, targets * out_masks) / 4
            outputs = (outputs * out_masks).cpu().detach().numpy()
            targets = (targets * out_masks).cpu().detach().numpy()
            if np.mean(np.linalg.norm(targets * 100, axis=1)) > 0:
                truth_norm = np.linalg.norm(targets * 100, axis=1).flatten()
                error_norm = np.linalg.norm(outputs * 100 - targets * 100, axis=1).flatten()
                truth_norm, error_norm = truth_norm[truth_norm > 0], error_norm[error_norm > 0]
                accuracy = sum((error_norm / truth_norm) < 0.1) / len(error_norm)
                print('mean error', np.mean(error_norm / truth_norm), 'accuracy', accuracy, end='\t')
            else:
                accuracy = 0.0
            print('L1loss', loss.cpu().detach().numpy(), end='\r')
            if accuracy > bestaccuracy:
                bestaccuracy = accuracy
                torch.save(net.state_dict(), best_model_file)
            else:
                pass
                # print('totalloss', str(loss.detach().numpy())[:4]+' ', end = '\n')
            loss.backward()
            optimizer.step()
            scheduler.step(None)
            # if idx%5==0:
            #    print('\n', outputs[0].cpu().detach().numpy(), targets[0].cpu().detach().numpy(), '\n')
            # idx+=1
        torch.save(net.state_dict(), model_file)
        print(epoch)


import sqlite3
import csv
import os.path
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
db_path = os.path.join(BASE_DIR, "db.sqlite3")
conn = sqlite3.connect(db_path)
c = conn.cursor()
c.execute("SELECT rowid, * FROM inventory")
columns = [column[0] for column in c.description]
results = []
for row in c.fetchall():
    results.append(dict(zip(columns, row)))
with open("output.csv", "w", newline='') as new_file:
    fieldnames = columns
    writer = csv.DictWriter(new_file,fieldnames=fieldnames)
    writer.writeheader()
    for line in results:
        writer.writerow(line)
conn.close()


import os
from PIL import Image

if __name__ == '__main__':
    # 获取目录下文件名
    file_full_path = os.path.dirname(os.path.abspath(__file__))
    files = os.listdir(file_full_path)
    # 图标大小
    size = (256, 256)

    for inName in files:
        # 分离文件名与扩展名
        tmp = os.path.splitext(inName)
        # 因为python文件跟图片在同目录，所以需要判断一下
        if tmp[1] == '.png':
            outName = tmp[0] + '.ico'
            # 打开图片并设置大小
            im = Image.open(os.path.join(file_full_path, inName)).resize(size)
            try:
                # 图标文件保存
                im.save(os.path.join(file_full_path, outName))
                print('{} --> {}'.format(inName, outName))
            except IOError:
                print('connot convert :', inName)


# Programa Python para embaralhar um baralho de cartas

# importando módulos
import itertools, random

# montando um baralho de cartas
deck = list(itertools.product(range(1,14),['Spade','Heart','Diamond','Club']))

# shuffle the cards
random.shuffle(deck)

# draw five cards
print("Você tem:")
for i in range(5):
   print(deck[i][0], " de ", deck[i][1])


from __future__ import print_function
import argparse
import random
import numpy as np
import torch
import sys

sys.path.append('./auxiliary/')
from dataset_3D import *
from model_3D import *
from utils import *
from ply import *
import os
import scipy.io as sio
import pandas as pd
from loss import *
import meshio_custom
import sklearn.preprocessing as sklp

sys.path.append('./utils/')
from split_mesh import *

parser = argparse.ArgumentParser()
parser.add_argument('--batchSize', type=int, default=1, help='input batch size')
parser.add_argument('--workers', type=int, help='number of data loading workers', default=6)
parser.add_argument('--model', type=str, default = './log/SVR_subnet2_usage2/network.pth',  help='your path to the trained model')
parser.add_argument('--num_points',type=int,default=10000)
parser.add_argument('--tau',type=float,default=0.1)
parser.add_argument('--tau_decay',type=float,default=2)
parser.add_argument('--pool',type=str,default='max',help='max or mean or sum' )
parser.add_argument('--num_vertices', type=int, default=2562) # 2562
parser.add_argument('--subnet',type=int,default=2)
parser.add_argument('--manualSeed', type=int, default=6185)
opt = parser.parse_args()
print (opt)

os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = '2'
torch.cuda.set_device(3)

sys.path.append("./extension/")
import dist_chamfer as ext
distChamfer = ext.chamferDist()

blue = lambda x:'\033[94m' + x + '\033[0m'
print("Random Seed: ", opt.manualSeed)
random.seed(opt.manualSeed)
torch.manual_seed(opt.manualSeed)

dataset_test = ShapeNet(npoints=opt.num_points, SVR=True, normal=True, train=False,class_choice='lumbar_vertebra_05')
dataloader_test = torch.utils.data.DataLoader(dataset_test, batch_size=opt.batchSize,
                                         shuffle=False, num_workers=int(opt.workers))
print('testing set', len(dataset_test.datapath))
len_dataset = len(dataset_test)

# name = 'sphere' + str(opt.num_vertices) + '.mat'
# mesh = sio.loadmat('./data/' + name)
name = 'sphere' + str(opt.num_vertices) + '.obj'
mesh = meshio_custom.read_obj('./data/' + name)

# faces = np.array(mesh['f'])
faces = mesh['faces']
faces_cuda = torch.from_numpy(faces.astype(int)).type(torch.cuda.LongTensor)

# vertices_sphere = np.array(mesh['v'])
vertices_sphere = mesh['vertices']
vertices_sphere = (torch.cuda.FloatTensor(vertices_sphere)).transpose(0,1).contiguous()
vertices_sphere = vertices_sphere.contiguous().unsqueeze(0)

network = SVR_TMNet_Split()
network.apply(weights_init)
network.cuda()

if opt.model != '':
    model_dict = network.state_dict()
    pretrained_dict = {k: v for k, v in torch.load(opt.model).items() if (k in model_dict) }
    model_dict.update(pretrained_dict)
    network.load_state_dict(model_dict)
    print(" Previous weight loaded ")
print(network)
network.eval()

with torch.no_grad():
    for i, data in enumerate(dataloader_test, 0):
        img, points, normals, faces_gt, points_orig, name, cat = data
        cat = cat[0]
        fn = name[0]
        img = img.cuda()
        img = img.unsqueeze(dim=0)
        img = img.float()

        points = points.cuda()
        choice = np.random.choice(points.size(1), opt.num_vertices, replace=False)
        points_choice = points[:, choice, :].contiguous()
        normals_choice = normals[:, choice, :].contiguous()
        points = points.float()
        points_choice = points_choice.float()
        vertices_input = (vertices_sphere.expand(img.size(0), vertices_sphere.size(1),
                                                 vertices_sphere.size(2)).contiguous())

        vol_part = split_volume(img, level=0)
        b_f_list_gt, points_choice_parts, b_f_list_gen, vertices_input_parts, range_part = split_mesh(points_choice, vertices_input, level=0)
        pointsRec_parts = network(vol_part, vertices_input_parts, mode='deform1')  # vertices_sphere 3*2562
        pointsRec, _, _, _, _ = combine_meshes(pointsRec_parts, vertices_input_parts, points_choice_parts, range_part, b_f_list_gen, True, level=0, scale=1.)

        _, _, _, idx2 = distChamfer(points.float() , pointsRec.float()) # PointsRec > Points

        pointsRec_samples, index = samples_random(faces_cuda, pointsRec, opt.num_points)
        error = network(vol_part, pointsRec_samples.detach().transpose(1, 2),mode='estimate')
        faces_cuda_bn = faces_cuda.unsqueeze(0)
        # faces_cuda_bn = prune(faces_cuda_bn, error, opt.tau, index, opt.pool)
        triangles_c1 = faces_cuda_bn[0].cpu().data.numpy()

        pointsRec = torch.squeeze(pointsRec)
        normals_gen = torch.zeros(pointsRec.shape).cuda()
        v10 = pointsRec[triangles_c1[:, 1]] - pointsRec[triangles_c1[:, 0]]
        v20 = pointsRec[triangles_c1[:, 2]] - pointsRec[triangles_c1[:, 0]]
        normals_gen_value = torch.cross(v10, v20)
        normals_gen[triangles_c1[:,0]] += normals_gen_value[:]
        normals_gen[triangles_c1[:,1]] += normals_gen_value[:]
        normals_gen[triangles_c1[:,2]] += normals_gen_value[:]
        normals_gen_len = torch.sqrt(normals_gen[:,0]*normals_gen[:,0]+normals_gen[:,1]*normals_gen[:,1]+normals_gen[:,2]*normals_gen[:,2])
        normals_gen = normals_gen / normals_gen_len.reshape(-1, 1)
        pointsRec = torch.unsqueeze(pointsRec, 0)

        '''
        for j in range(0, normals_gen.shape[0] - 1):
            if torch.dot(normals_gen[j, :].cpu().float(), normals[0, idx2[0, j], :].float()).item() < 0.0:
                normals_gen[j, :] = -normals_gen[j, :]
                '''

        ###################################################################################################
        if opt.subnet > 1:
            b_f_list_gt2, points_choice_parts2, b_f_list_gen2, pointsRec_parts, range_part2 = split_mesh(points_choice, pointsRec.transpose(2,1), level=1)
            vol_parts = split_volume(img, level=1)
            pointsRec2_parts = network(vol_parts, pointsRec_parts, mode='deform2')
            pointsRec2, _, _, _, _ = combine_meshes(pointsRec2_parts, pointsRec_parts, points_choice_parts2, range_part2, b_f_list_gen2, faces_cuda_bn, False, level=1, scale=1.)
            pointsRec2_sd, trianglesRec2, CD_loss_part2 = combine_meshes_simp_dec(pointsRec2_parts, pointsRec2,points_choice_parts2, b_f_list_gen2,faces_cuda_bn)
            pointsRec2_sd = torch.tensor(pointsRec2_sd).unsqueeze(0).float().cuda()
            trianglesRec2 = torch.tensor(trianglesRec2).unsqueeze(0).int().cuda()
            triangles_c2_sd = trianglesRec2[0].cpu().data.numpy()
            # _, _, _, idx2_2 = distChamfer(points.float(), pointsRec2.float())  # PointsRec > Points

            pointsRec2_samples, index = samples_random(faces_cuda_bn, pointsRec2, opt.num_points)
            error = network(vol_part, pointsRec2_samples.detach().transpose(1, 2),mode='estimate2')
            faces_cuda_bn = faces_cuda_bn.clone()
            # faces_cuda_bn = prune(faces_cuda_bn, error, opt.tau/opt.tau_decay, index, opt.pool)
            triangles_c2 = faces_cuda_bn[0].cpu().data.numpy()

            pointsRec2 = torch.squeeze(pointsRec2)
            normals_gen2 = torch.zeros(pointsRec2.shape).cuda()
            v10 = pointsRec2[triangles_c2[:, 1]] - pointsRec2[triangles_c2[:, 0]]
            v20 = pointsRec2[triangles_c2[:, 2]] - pointsRec2[triangles_c2[:, 0]]
            normals_gen2_value = torch.cross(v10, v20)
            normals_gen2[triangles_c2[:, 0]] += normals_gen2_value[:]
            normals_gen2[triangles_c2[:, 1]] += normals_gen2_value[:]
            normals_gen2[triangles_c2[:, 2]] += normals_gen2_value[:]
            normals_gen2_len = torch.sqrt(
                normals_gen2[:, 0] * normals_gen2[:, 0] + normals_gen2[:, 1] * normals_gen2[:, 1] + normals_gen2[:, 2] * normals_gen2[:, 2])
            normals_gen2 = normals_gen2 / normals_gen2_len.reshape(-1, 1)
            pointsRec2 = torch.unsqueeze(pointsRec2, 0)
            '''
            for j in range(0, normals_gen2.shape[0] - 1):
                if torch.dot(normals_gen2[j, :].cpu().float(), normals[0, idx2_2[0, j], :].float()).item() < 0.0:
                    normals_gen2[j, :] = -normals_gen2[j, :]
                    '''
        ###################################################################################################
        if opt.subnet > 2:
            b_f_list_gt3, points_choice_parts3, b_f_list_gen3, pointsRec2_parts, range_part3 = split_mesh(points_choice,
                                                                                pointsRec2.transpose(
                                                                                2, 1),
                                                                                level=1)
            pointsRec3_parts = network(vol_part, pointsRec2_parts, mode='deform3')

            # if i == 0:
            # combine_meshes_simp_dec(pointsRec2_parts, points_choice_parts2, b_f_list_gen2, faces_cuda_bn)

            pointsRec3, _, _, _, _ = combine_meshes(pointsRec3_parts, np.array(pointsRec2_parts),
                                                                        points_choice_parts3, range_part3,
                                                                        b_f_list_gen3, faces_cuda_bn, False, level=1,
                                                                        scale=1.)
            pointsRec3, trianglesRec3, CD_loss_part3 = combine_meshes_simp_dec(pointsRec3_parts, pointsRec3,
                                                                               points_choice_parts3, b_f_list_gen3,
                                                                               faces_cuda_bn)
            _, _, _, idx2_2 = distChamfer(points.float(), pointsRec2.float())  # PointsRec > Points
            pointsRec3 = torch.tensor(pointsRec3).unsqueeze(0).float().cuda()
            trianglesRec3 = torch.tensor(trianglesRec3).unsqueeze(0).float().cuda()

            pointsRec3_samples, index = samples_random(trianglesRec3.detach().int(), pointsRec3, opt.num_points)
            error = network(vol_part, pointsRec3_samples.detach().transpose(1, 2), mode='estimate3')
            faces_cuda_bn = faces_cuda_bn.clone()
            # faces_cuda_bn = prune(faces_cuda_bn, error, opt.tau/opt.tau_decay, index, opt.pool)
            # triangles_c2 = faces_cuda_bn[0].cpu().data.numpy()

            pointsRec3 = torch.squeeze(pointsRec3)
            trianglesRec3 = trianglesRec3.long()
            normals_gen3 = torch.zeros(pointsRec3.shape).cuda()
            v10 = pointsRec3[trianglesRec3[:, 1]] - pointsRec3[trianglesRec3[:, 0]]
            v20 = pointsRec3[trianglesRec3[:, 2]] - pointsRec3[trianglesRec3[:, 0]]
            normals_gen3_value = torch.cross(v10, v20)
            normals_gen3[trianglesRec3[:, 0]] += normals_gen3_value[:]
            normals_gen3[trianglesRec3[:, 1]] += normals_gen3_value[:]
            normals_gen3[trianglesRec3[:, 2]] += normals_gen3_value[:]
            normals_gen3_len = torch.sqrt(
                normals_gen3[:, 0] * normals_gen3[:, 0] + normals_gen3[:, 1] * normals_gen3[:, 1] + normals_gen3[:, 2] * normals_gen3[:, 2])
            normals_gen3 = normals_gen3 / normals_gen3_len.reshape(-1, 1)
            pointsRec3 = torch.unsqueeze(pointsRec3, 0)

        print(cat,fn)
        if not os.path.exists(opt.model[:-4]):
            os.mkdir(opt.model[:-4])
            print('created dir', opt.model[:-4])

        if not os.path.exists(opt.model[:-4] + "/" + str(cat)):
            os.mkdir(opt.model[:-4] + "/" + str(cat))
            print('created dir', opt.model[:-4] + "/" + str(cat))
        b = np.zeros((np.shape(faces)[0],4)) + 3
        b[:,1:] = faces

        '''
        triangles_c1_tosave = triangles_c1[triangles_c1.sum(1).nonzero()[0]]
        b_c1 = np.zeros((np.shape(triangles_c1_tosave)[0],4)) + 3
        b_c1[:,1:] = triangles_c1_tosave
        if opt.subnet>1:
            triangles_c2_tosave = triangles_c2[triangles_c2.sum(1).nonzero()[0]]
            b_c2 = np.zeros((np.shape(triangles_c2_tosave)[0],4)) + 3
            b_c2[:,1:] = triangles_c2_tosave
        if opt.subnet>2:
            triangles_c3_tosave = triangles_c3[triangles_c3.sum(1).nonzero()[0]]
            b_c3 = np.zeros((np.shape(triangles_c3_tosave)[0],4)) + 3
            b_c3[:,1:] = triangles_c3_tosave
            '''

        meshio_custom.write_obj(opt.model[:-4] + "/" + str(cat) + "/" + fn+"_GT.obj",
                                points.cpu().data.squeeze().numpy(), triangles=faces_gt.cpu().data.squeeze().numpy().astype(int))
        meshio_custom.write_obj(opt.model[:-4] + "/" + str(cat) + "/" + fn+"_gen.obj",
                                pointsRec.cpu().data.squeeze().numpy(),
                                triangles=faces, normals=normals_gen.cpu().numpy())
        '''
        meshio_custom.write_obj(opt.model[:-4] + "/" + str(cat) + "/" + fn+"_gen_pruned.obj",
                                pointsRec.cpu().data.squeeze().numpy(),
                                triangles=triangles_c1, normals=normals_gen)
                                '''
        '''
        write_ply(filename=opt.model[:-4] + "/" + str(cat) + "/" + fn+"_GT",
                  points=pd.DataFrame(points.cpu().data.squeeze().numpy()), as_text=True)
        write_ply(filename=opt.model[:-4] + "/" + str(cat) + "/" + fn+"_gen",
                  points=pd.DataFrame(pointsRec.cpu().data.squeeze().numpy()), as_text=True,
                  faces = pd.DataFrame(b.astype(int)), normal = True)
        write_ply(filename=opt.model[:-4] + "/" + str(cat) + "/" + fn+"_gen_pruned",
                  points=pd.DataFrame(pointsRec.cpu().data.squeeze().numpy()), as_text=True,
                  faces = pd.DataFrame(b_c1.astype(int)), normal = True)
                    '''
        if opt.subnet>1:
            '''
            write_ply(filename=opt.model[:-4] + "/" + str(cat) + "/" + fn+"_gen2",
                      points=pd.DataFrame(pointsRec2.cpu().data.squeeze().numpy()), as_text=True,
                      faces = pd.DataFrame(b_c1.astype(int)))
            write_ply(filename=opt.model[:-4] + "/" + str(cat) + "/" + fn+"_gen2_pruned",
                      points=pd.DataFrame(pointsRec2.cpu().data.squeeze().numpy()), as_text=True,
                      faces = pd.DataFrame(b_c2.astype(int)))
                      '''
            '''
            meshio_custom.write_obj(opt.model[:-4] + "/" + str(cat) + "/" + fn + "_gen2.obj",
                                    pointsRec2.cpu().data.squeeze().numpy(),
                                    triangles=triangles_c2)
                                    '''
            meshio_custom.write_obj(opt.model[:-4] + "/" + str(cat) + "/" + fn + "_gen2.obj",
                                    pointsRec2_sd.cpu().data.squeeze().numpy(),
                                    triangles=triangles_c2_sd)
            '''
            meshio_custom.write_obj(opt.model[:-4] + "/" + str(cat) + "/" + fn + "_gen2_pruned.obj",
                                    pointsRec2.cpu().data.squeeze().numpy(),
                                    triangles=triangles_c2, normals=normals_gen2)
                                    '''
        if opt.subnet>2:
            '''
            write_ply(filename=opt.model[:-4] + "/" + str(cat) + "/" + fn+"_gen3",
                      points=pd.DataFrame(pointsRec3.cpu().data.squeeze().numpy()), as_text=True,
                      faces = pd.DataFrame(b_c3.astype(int)))
                      '''
            meshio_custom.write_obj(opt.model[:-4] + "/" + str(cat) + "/" + fn + "_gen3.obj",
                                    pointsRec3.cpu().data.squeeze().numpy(),
                                    triangles=trianglesRec3.cpu().data.squeeze().numpy(),
                                    normals=normals_gen3.cpu().data.squeeze().numpy())


from fcm_django.models import FCMDevice
from services.firebase.firebase_cloud_messaging.templates import notification

def send_notification(user_ids, title, template, data, *args):
    message = getattr(notification, template)(args)
    default_data = {
        "click_action": "FLUTTER_NOTIFICATION_CLICK",
        "android": {
            "notification": {
                "channel_id": "high_importance_channel"
            }
        }
    }
    if data:
        default_data.update(data)
    try:
        devices = FCMDevice.objects.filter(user__in=user_ids)
        result = devices.send_message(
            title=title,
            body=message,
            data=default_data,
            sound=True
        )
        return result
    except Exception as e:
        print(e)


import numpy as np
import gensim.models as word2vec
import jieba
import re

# 设置卷积核
def set_cnn_filter(n_gram):
    array = np.random.rand(n_gram * 300, 300)

    return array

# 保存卷积核
def save_cnn_filter(path, array, n_gram):
    pathname = path + str(n_gram) + '_gram.npy'
    np.save(pathname, array)

# 获得卷积核
def get_cnn_filter(path, n_gram):
    pathname = path + str(n_gram) + '_gram.npy'
    array = np.load(pathname)

    return array

# 加载模型
def load_word2vec_model(model_path):
    model = word2vec.Word2Vec.load(model_path)
    return model

# 输出词向量
def get_vector(word, model):
    return model.wv.__getitem__(word)

# 增加专业名词
def set_user_dict(car_path):
    jieba.load_userdict(car_path)

# 获取结巴分词
def get_split(sentence):

    # 标点符号
    remove_chars = '[·’!"#$%&\'()*+,-./:;<=>?@，。?★、…【】《》？“”‘’！[\\]^_`{|}~]+'

    # 去除标点符号
    sentence = re.sub(remove_chars, "", sentence)

    # 分词
    words = [w for w in jieba.cut(sentence, cut_all=False)]

    return words

# relu函数
def relu(x):
    return np.where(x < 0, 0, x)

# max-polling函数
def poll(array):
    return array.max(axis=0)

def poll_sum(arrays):
    return arrays[0] + arrays[1] + arrays[2]

# 卷积神经网络
def nbt_cnn(sentence, model, cnn_filter_path, bs):
    # n-gram表征
    poll_arrays = []

    # 设置卷积核
    n_gram = 0
    for j in range(3):
        # n-gram
        n_gram += 1

        # 偏项
        b = bs[n_gram - 1]

        # 获取卷积核
        cnn_filter = get_cnn_filter(cnn_filter_path, n_gram)

        # 分词
        words = get_split(sentence)

        # 获得词向量
        vectors = []
        for k in words:
            vector = get_vector(k, model)
            vectors.append(vector)

        # 词向量
        words_vector = []

        # 1-gram
        if n_gram == 1:
            words_vector = vectors
        elif n_gram == 2:
            for k in range(len(vectors) - 1):
                gram = vectors[k].tolist()
                gram_1 = vectors[k + 1].tolist()
                gram.extend(gram_1)
                words_vector.append(np.asarray(gram))
        else:
            for k in range(len(vectors) - 2):
                gram = vectors[k].tolist()
                gram_1 = vectors[k + 1].tolist()
                gram_2 = vectors[k + 2].tolist()
                gram.extend(gram_1)
                gram.extend(gram_2)
                words_vector.append(np.asarray(gram))

        # 将句子向量转换成矩阵
        words_array = np.asarray(words_vector)

        # 卷积
        cnn_array = words_array.dot(cnn_filter)

        # 线性整流函数relu
        relu_array = relu(cnn_array + b)

        # 池化函数max-polling
        poll_array = poll(relu_array)
        poll_arrays.append(poll_array)

    # 语句表征
    r = poll_sum(poll_arrays)

    return r

if __name__ == '__main__':
    # 保存路径
    my_cnn_filter_path = '../../data/representation_data/'

    # # 设置卷积核
    # my_n_gram = 0
    # for i in range(3):
    #     # n-gram
    #     my_n_gram += 1
    #
    #     # 设置卷积核
    #     my_cnn_filter = set_cnn_filter(my_n_gram)
    #
    #     # 保存卷积核
    #     save_cnn_filter(my_cnn_filter_path, my_cnn_filter, my_n_gram)

    # 模型路径
    my_model_path = r'../../data/result_data/word2vec.model'

    # 加载模型
    my_model = load_word2vec_model(my_model_path)

    # 词向量
    # print_vector('奔驰')

    # 专业名词路径
    my_car_path = '../../data/jieba_data/car_name.txt'
    set_user_dict(my_car_path)

    # 句子
    my_sentence = '车快半年了，车内的味道还是很大。'

    # 偏项
    my_bs = [0.2, 0.3, 0.4]

    # 卷积神经网络
    my_r = nbt_cnn(my_sentence, my_model, my_cnn_filter_path, my_bs)
    print(my_r)


import numpy as np
#import matplotlib.pyplot as plt
from scipy.misc import imfilter, imread
from skimage import color, data, restoration
from scipy.signal import convolve2d as conv2

def main():
  image = imread("/Users/gsamaras/Downloads/boat.tif")
  #plt.imshow(arr, cmap='gray')
  #plt.show()
  #blurred_arr = imfilter(arr, "blur")
  psf = np.ones((5, 5)) / 25
  image = conv2(image, psf, 'same')
  image += 0.1 * image.std() * np.random.standard_normal(image.shape)

  deconvolved = restoration.wiener(image, psf, 1, clip=False)
  #print deconvolved
  plt.imshow(deconvolved, cmap='gray')
  plt.show()
  #print image

if __name__ == "__main__":
    main()


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

from __future__ import (division, absolute_import, print_function,
                        unicode_literals, annotations)
from multiprocessing import Pool
import sys
import psutil
import tensorflow as tf

num_cpus = psutil.cpu_count(logical=False)

filename = '/tmp/model'

def evaluate_next_batch(i):
    # Pin the process to a specific core if we are on Linux to prevent
    # contention between the different processes since TensorFlow uses
    # multiple threads.
    if sys.platform == 'linux':
        psutil.Process().cpu_affinity([i])
    model = tf.keras.models.load_model(filename)
    mnist = tf.keras.datasets.mnist.load_data()
    x_test = mnist[1][0] / 255.0
    return model.predict(x_test)

def main():
    # Time the code below.

    pool = Pool(num_cpus)

    for _ in range(10):
        pool.map(evaluate_next_batch, range(num_cpus))

if __name__ == '__main__':
    main()


from os import system, name
from typing import List
from .cards import Card, CardTypes
from .player import Player

def get_input_int(user_message: str, min_input: int = 1, max_input: int = 999999) -> int:
    """Asks for an integer input from the user.

    Args:
        user_message (str): Message for the user

    Returns:
        int: Integer that the user puts in.
    """
    val = 0
    while True:
        _input = input(user_message)
        try:
            val = int(_input)
        except:
            print("This was not a valid integer. Please try again.")
            continue

        if min_input <= val <= max_input:
            return val

        if min_input > val:
            print(f"The entered value should exceed {min_input}")
        else:
            print(f"The maximum input should not exceed {max_input}")

def clear_screen() -> int:
    """
    Clears the screen of the user.
    """
    if name == 'nt':
        system('cls')
    else:
        system('clear')
    return 0

def create_card_deck() -> List[Card]:
    """Creates the card deck and returns it

    Returns:
        List[Card]: List with instances of type Card
    """
    cards = []
    for i in range(13):
        for suit in ['Red diamond', 'Black clubs', 'Red heart', 'Black spade']:
            if i < 9:
                cards.append(Card(i + 2, f"{suit} {i + 2}", CardTypes.NUMBER))
            elif i == 9:
                cards.append(Card(10, f'{suit} Jack', CardTypes.PICTURE))
            elif i == 10:
                cards.append(Card(10, f'{suit} Lady', CardTypes.PICTURE))
            elif i == 11:
                cards.append(Card(10, f'{suit} King', CardTypes.PICTURE))
            else:
                cards.append(Card(11, f'{suit} Ass', CardTypes.ASS))
    return cards

def draw_card(player: Player, cards: List[Card]) -> None:
    """Function draws a card and adds it to the card deck
    of the player.

    Args:
        player (Player): Object of class Player
        cards (List[Card]): List of cards
    """
    new_card = cards.pop()
    if player.is_host:
        print(f"The host got a new card:     {new_card}")
    else:
        print(f"You got a new card:          {new_card}")
    player.add(new_card)

def player_plays(player: Player, cards: List[Card]) -> bool:
    """Function asks the user for decisions until the user
    has stopped or is busted.

    Args:
        player (Player): Instance of class Player
        cards (List[Card]): List with elements of class Card

    Returns:
        bool: True, if user has not lost
    """
    decision = "y"
    while decision != 'n':
        print(f"\nYour current score is: {player.score}\nYou have the following cards:")
        for card in player.cards:
            print(f"\t{str(card)}")

        decision = input("Do you want to draw a card or stop (y/n)?").lower()
        if decision == 'y':
            draw_card(player, cards)
            if player.score >= 21:
                print("You lost")
                return False
        else:
            print("You decided to end the game")
            print(f"You have a score of {player.score}")
            return True

def host_plays(host: Player, cards: List[Card]) -> True:
    """Function that plays for the host.

    Args:
        host (Player): Object of class Player
        cards (list): List of cards

    Returns:
        True: True if Host has not lost the game
    """
    done = False
    while not done:
        if host.score < 17:
            draw_card(host, cards)
            for card in host.cards:
                print(f"\t{str(card)}")
        elif host.score >= 17:
            return True

        if host.has_blackjack():
            print("Host has a blackjack! He won!")
            return True

        if host.score >= 21:
            print(f"Host has a score of {host.score}. You won")
            return False


import time
import requests
import urllib.parse
import datetime
import xlwt
import write_excel

def decrypt(t: str, e: str) -> str:
    n, i, a, result = list(t), list(e), {}, []
    ln = int(len(n)/2)
    start, end = n[ln:], n[:ln]
    a = dict(zip(end, start))
    return ''.join([a[j] for j in e])

COOKIES = 'BAIDUID=8759768F974CE3E6C2884260097331A4:FG=1; PSTM=1574683224; H_PS_PSSID=1445_21116_29567_29220; BIDUPSID=43233656E2011B10D268D7B02D7A956A; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; delPer=0; PSINO=2; Hm_lvt_d101ea4d2a5c67dab98251f0b5de24dc=1574939615; BDUSS=hWWDJ0Z01VOWZINGdPaWRkTUotYmR4WlRhcEhJNTVDQzA3SUpDNzBSWHRPQWRlRVFBQUFBJCQAAAAAAAAAAAEAAAA3VXuxu6rPxNPQxMzGpAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAO2r313tq99daE; CHKFORREG=f47c79690c889b9fe3bb335ced026f76; bdindexid=j4g6p93elqe6o7phocmmfn53o2; Hm_lpvt_d101ea4d2a5c67dab98251f0b5de24dc=1574940479'
headers = {
    'Accept': 'application/json, text/plain, */*',
    'Accept-Encoding': 'gzip, deflate',
    'Accept-Language': 'zh-CN,zh;q=0.9',
    'Cache-Control': 'no-cache',
    'Cookie': COOKIES,
    'DNT': '1',
    'Host': 'zhishu.baidu.com',
    'Pragma': 'no-cache',
    'Proxy-Connection': 'keep-alive',
    'Referer': 'zhishu.baidu.com',
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.90 Safari/537.36',
    'X-Requested-With': 'XMLHttpRequest',
}
session = requests.Session()
session.headers.update(headers)

def get_ptbk(uniqid: str) -> str:
    with session.get(
        url=f"http://index.baidu.com/Interface/ptbk?uniqid={uniqid}"
    ) as response:
        ptbk = response.json()["data"]
        return ptbk

def get_index_data(keyword: str, start: str, end: str) -> str:
    keyword = urllib.parse.quote(keyword)
    with session.get(
        url=f"http://index.baidu.com/api/SearchApi/index?area=0&word=[[%7B%22name%22:%22{keyword}%22,%22wordType%22:1%7D]]&startDate={start}&endDate={end}"
    ) as response:
        data = response.json()["data"]
        all_data = data["userIndexes"][0]["all"]["data"]

        uniqid = data["uniqid"]
        ptbk = get_ptbk(uniqid)
        result = decrypt(ptbk, all_data).split(',')
        return result

def GetDesktopPath():
    import os
    return os.path.join(os.path.expanduser("~"), 'Desktop')

# 获取从开始日期 start 到截止日期 end 中的所有日期
def get_date_list(start:str, end: str):
    # 也可以是%Y%m%d
    datestart = datetime.datetime.strptime(start,'%Y-%m-%d')
    dateend = datetime.datetime.strptime(end,'%Y-%m-%d')

    data_list = []
    while datestart<dateend:
        datestart+=datetime.timedelta(days=1)
        data_list.append(datestart.strftime('%Y-%m-%d'))
    return data_list

start = "2020-7-01"
end = "2020-9-30"

d_name = []
d_name.append("名称")
d_name += get_date_list(start, end)

myExcel = write_excel.Excel()

myExcel.write_title(d_name)

line = 1
with open('./百度指数修改名单.txt',"r",encoding='UTF-8') as lines:  # 一次性读入txt文件，并把内容放在变量lines中
    array = lines.readlines()  # 返回的是一个列表，该列表每一个元素是txt文件的每一行
    for name in array:
        temp = []
        arr_name = name.split(" ")
        if len(arr_name) == 2:
            name = arr_name[1].replace("\n","")
        else:
            name = arr_name[0].replace("\n","")
        try:
            data = get_index_data(
                keyword=name,
                start=start,
                end=end
            )
            temp.append(name)
            temp += data
            time.sleep(1)

            myExcel.write_content_line(temp)

            break
        except Exception as e:
            print(name)
            continue
myExcel.save_excel("123")


# Importando bibliotecas importantes da FastAPI

from email.policy import default
from typing import Union
from fastapi import FastAPI, Body, HTTPException, Path, Form
from pydantic import BaseModel,Field
from fastapi.responses import HTMLResponse
from fastapi.exceptions import RequestValidationError
from fastapi.exception_handlers import (
    http_exception_handler,
    request_validation_exception_handler,
)
from fastapi.responses import PlainTextResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
from fastapi.encoders import jsonable_encoder

app = FastAPI()

mock_database = [{'id' : 1, 'name' : "banana", 'qtd' : 4},
                 {'id': 2, 'name' : "pêra", 'qtd' : 7},
                 {'id': 3, 'name' : "manga", 'qtd' : 1}]

# --------------------------------------- Declarando a classe do produto -------------------------------------------------------
class ProductUpdate(BaseModel):
    name: str = Field(default = "Placeholder", title="O nome do produto", max_length=300, example="Maçã")
    qtd : int = Field(default = 0,  title = "A quantidade do produto", ge=0, description="A quantidade não pode ser negativa", example=4)

class ProductBase(ProductUpdate):
    id : int = Field(title = "Id do produto", description = "Identificador do produto", ge = 1)
    # name: str = Field(default = "Placeholder", title="O nome do produto", max_length=300, example="Maçã")
    # qtd : int = Field(default = 0,  title = "A quantidade do produto", ge=0, description="A quantidade não pode ser negativa", example=4)

# ----------------- Declarando função importante para mostrar erros em caso de dado não encontrado -----------------------------
def product_not_in_db(product_id):
    if product_id not in [product['id'] for product in mock_database]:
        raise HTTPException(status_code=404, detail="Produto não encontrado!")

#  -----------------------------------  Handlers que enviam erros --------------------------------------------------------------
@app.exception_handler(StarletteHTTPException)
async def custom_http_exception_handler(request, exc):
    return await http_exception_handler(request, exc)

@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc):
    return await request_validation_exception_handler(request, exc)

# --------------------------------------- Implementando o CRUD ------------------------------------------------------------------

@app.get("/", tags=["home page"])
async def main():
    """
    Apenas uma home page com gosto de macarrão
    """
    content = """

Buon giorno mondo!

    """
    return HTMLResponse(content=content)

@app.get("/products/{product_id}", status_code=200, response_model = ProductBase, tags=["product"])
async def read_item(product_id: int = Path(title="O id do produto que você quer consultar", ge=0)):
    """
    Procura o produto baseado em seu id de identificação e retorna desse forma:

    {"name":"manga",

    "price_unit":3.5,

    "qtd":1,

    "is_available":false}

    """
    product_not_in_db(product_id)
    for product in mock_database:
        if product['id'] == product_id:
            produto = product

    return produto

@app.get("/products/", status_code=200, response_model = list[ProductBase], tags=["product"])
async def read_item():
    """
    Lista todos os produtos e os retorna dessa forma:

    {"name":"manga",

    "qtd":1}
    """
    return mock_database

@app.post("/products/", status_code=201, response_model=ProductBase, tags=["product"])
async def create_item(*, product: ProductBase = Body(
        examples = {
            "normal": {
                "summary": "Um exemplo normal de sucesso",
                "description": "Um exemplo normal de produto que funciona corretamente",
                "value": {
                    "id": 1,
                    "name": "banana",
                    "qtd": 4,
                }
            },
            "convertido": {
                "summary": "Um exemplo com conversão de dados",
                "description": "A FastAPI converte string de quantidade para números automaticamente e vice-versa",
                "value": {
                    "id": "1",
                    "name" : "banana",
                    "qtd" : "4"
                }
            },
            "incorreto" : {
                "summary" : "Um exemplo de dado incorreto",
                "description" : "Nessa situação, quando a tipagem é errada um erro é retornado",
                "value":{
                    "id" : "um",
                    "name" : "banana",
                    "qtd" : "quatro"
                }
            },

        })):
    """
    Crie um produto com as seguintes informações abaixo:

    - **id**: id de cada produto
    - **name**: nome de cada produto
    - **qtd**: quantidade do produto no inventário
    """
    product = product.dict()
    mock_database.append(product)
    return product

@app.put("/products/{product_id}", tags=["product"])
async def overwrite_item(
    product_id: int = Path(title="O id do produto que você quer editar", ge=0),
    product: ProductUpdate = Body(
        examples = {
            "normal": {
                "summary": "Um exemplo normal de sucesso",
                "description": "Um exemplo normal de produto que funciona corretamente",
                "value": {
                    "name": "banana",
                    "qtd": 4,
                }
            },
            "convertido": {
                "summary": "Um exemplo com conversão de dados",
                "description": "A FastAPI converte string de quantidade para números automaticamente e vice-versa",
                "value": {
                    "name" : "banana",
                    "qtd" : "4"
                }
            },
            "incorreto" : {
                "summary" : "Um exemplo de dado incorreto",
                "description" : "Nessa situação, quando a tipagem é errada um erro é retornado",
                "value":{
                    "name" : "banana",
                    "qtd" : "quatro"
                }
            },

        })):

    """
    Atualize totalmente as informações de um produto com as seguintes informações abaixo:

    - **id**: id de cada produto (mas você não pode atualizá-lo. O id a ser considerado é o que
    escreve no campo product_id separadamente)
    - **name**: nome de cada produto
    - **qtd**: quantidade do produto no inventário
    """
    product_not_in_db(product_id)
    for produto in mock_database:
        if produto['id'] == product_id:
            produto['name'] = product.name
            produto['qtd'] = product.qtd

    return {'product_id': product_id, 'product': product}

@app.patch("/products/{product_id}", response_model=ProductBase, tags=["product"])
async def update_item(
    product_id: int,
    product: ProductUpdate = Body(examples = {
        "nome": {
            "summary" : "Um exemplo modificando apenas o nome",
            "value" :{
                "name" : "maçã"
            }
        },
        "quantidade" : {
            "summary" : "Um exemplo modificando apenas a quantidade",
            "value" : {
                "qtd" : 0
            }
        }
        })):
    """
    Atualize parcialmente as informações de um produto com as seguintes informações abaixo:

    - **id**: id de cada produto
    - **name**: nome de cada produto
    - **qtd**: quantidade do produto no inventário
    """

    for produto in mock_database:
        if produto['id'] == product_id:
            produto_escolhido = produto

    stored_product_data = produto_escolhido
    stored_product_model = ProductUpdate(**stored_product_data)
    update_data = product.dict(exclude_unset=True)
    update_data['id'] = product_id
    updated_product = stored_product_model.copy(update=update_data)
    temp_product =  ProductBase(id=product_id, name= updated_product.name, qtd = updated_product.qtd)

    for i in range(len(mock_database)):
        if mock_database[i]['id'] == product_id:
            mock_database[i] = temp_product.dict()

    return temp_product

@app.delete("/products/{product_id}", tags=["product"])
async def delete_item(product_id: int = Path(title="O id do produto que você quer deletar", ge=0)):
    """
    Apaga um produto da base de dados.
    """
    product_not_in_db(product_id)

    for produto in mock_database:
        if produto['id'] == product_id:
            mock_database.remove(produto)

    return {'Produto removido com sucesso. Antigo id': product_id}


import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np

import os
from collections import Counter
from argparse import Namespace

param = Namespace(
    train_file_path="语料/train_seg/train",
    checkpoint_path='checkpoint2',
    seq_size=32,
    batch_size=64,
    embedding_size=128, # embedding dimension
    lstm_size=128, # hidden dimension
    gradients_norm=5, # gradient clipping
    top_k=5,
    num_epochs=50,
    learning_rate=0.001
)

corpus_path = "语料/train_text/"  # 未分词分类预料库路径
seg_path = "语料/train_seg/train"  # 分词后分类语料库路径

catelist = os.listdir(seg_path)  # 获取未分词目录下所有子目录

word_to_int = {}

with open("word_dict.txt",'r',encoding = "utf-8") as fdict:
    for line in fdict.readlines():
        linelist = line.split()
        num = int(linelist[0])
        word = linelist[1]
        word_to_int[word] = num

int_to_word = {k: w for w,k in word_to_int.items()}

from torch.utils import data

class MyDataset(data.Dataset):
    def __init__(self,filepath, batch_size,seq_size):
        text = []
        file_list = os.listdir(filepath)
        for file_path in file_list:
            full_name = filepath + "/" + file_path
            #print("当前处理的文件是:",full_name)
            with open(full_name, "r", encoding="utf-8") as f:
                for line in f.readlines():
                    linelist = line.split()
                    newlist = []
                    for word in linelist:
                        if(len(word)>1):
                            newlist.append(word)
                    text += newlist

        int_data =[word_to_int[word] for word in text]
        num_bacthes = int(len(int_data) / (seq_size * batch_size) )
        x_data = int_data[:num_bacthes*batch_size *seq_size]
        y_data = np.zeros_like(x_data)
        y_data[:-1] = x_data[1:]
        y_data[-1] = x_data[0]

        self.x_data = np.reshape(x_data,(-1,seq_size))
        self.y_data = np.reshape(y_data,(-1,seq_size))

    def __len__(self):
        return len(self.x_data)
    def __getitem__(self, id):
        x = self.x_data[id]
        y = self.y_data[id]
        return x,y

class LSTMModule(nn.Module):
    def __init__(self,numWord,seq_size,embedding_size,lstm_size):
        super(LSTMModule,self).__init__()
        self.seq_size = seq_size
        self.lstm_size = lstm_size
        self.embedding =  nn.Embedding(numWord,embedding_size)

        self.lstm = nn.LSTM(embedding_size,lstm_size,batch_first = True)
        self.linear = nn.Linear(lstm_size,numWord)
    def forward(self,x,prestate):

        embedding = self.embedding(x)
        output,state = self.lstm(embedding,prestate)
        logits = self.linear(output)
        return logits, state
    #set zero state, used for setting up
    def zero_state(self,batch_size):
        return (torch.zeros(1,batch_size,self.lstm_size), torch.zeros(1,batch_size,self.lstm_size))

import time,sys

def train():
    if(torch.cuda.is_available()):
        device = torch.device('cuda')
    else:
        device = torch.device('cpu')
    train_data = MyDataset(param.train_file_path,param.batch_size,param.seq_size)
    train_loader = data.DataLoader(dataset = train_data,batch_size = param.batch_size,shuffle = False)
    network = LSTMModule(len(word_to_int), param.seq_size, param.embedding_size, param.lstm_size )
    network = network.to(device)

    criterion = nn.CrossEntropyLoss()
    optimizer = torch.optim.Adam(network.parameters(), lr = param.learning_rate)
    iter = 0
    losses = []
    start_time = time.time()
    minloss = float("inf")
    for epoch in range(param.num_epochs):
        state_h, state_c = network.zero_state(param.batch_size)
        state_h, state_c = state_h.to(device),state_c.to(device)

        for i,(x,y) in enumerate(train_loader):
            iter += 1
            network.train()     #use train mode
            optimizer.zero_grad()    # 梯度清零
            x = x.long()
            y = y.long()
            x = torch.LongTensor(x).to(device)
            y = torch.LongTensor(y).to(device)      #转化模型输入为longtensor
            logits, (state_h,state_c) = network(x,(state_h,state_c))
            #print(logits.size(),y.size())

            loss = criterion(logits.transpose(1,2), y)

            loss_value = loss.item()

            state_h = state_h.detach()
            state_c = state_c.detach()

            loss.backward()

            _ = torch.nn.utils.clip_grad_norm_(network.parameters(),param.gradients_norm)

            optimizer.step()
            losses.append(loss_value)

            if iter %1000 == 0:
                torch.save(network.state_dict(),'{}/model-{}.pth'.format(param.checkpoint_path, iter))
            if loss_value < minloss:
                minloss = loss_value
                torch.save(network.state_dict(),'{}/model-final.pth'.format(param.checkpoint_path))
if __name__ == "__main__":
    train()


import requests
import sqlite3
import matplotlib.pyplot as plt

# Download 1000 posts
url = 'https://jsonplaceholder.typicode.com/posts'
response = requests.get(url)
posts = response.json()[:1000]

# Count letters in the 'body' field
letter_counts = {}
for post in posts:
    body = post['body']
    for letter in body:
        if letter.isalpha():
            letter = letter.lower()
            letter_counts[letter] = letter_counts.get(letter, 0) + 1

# Generate a frequency histogram
letters = list(letter_counts.keys())
counts = list(letter_counts.values())

plt.bar(letters, counts)
plt.xlabel('Letters')
plt.ylabel('Frequency')
plt.title('Letter Frequency in Posts Body')
plt.show()

# Connect to SQLite database (creates a new one if not exists)
conn = sqlite3.connect('example.db')

# Create a cursor object to execute SQL queries
cursor = conn.cursor()

# Create a table to store post data if it doesn't exist
cursor.execute('''
    CREATE TABLE IF NOT EXISTS posts (
        id INTEGER PRIMARY KEY,
        userId INTEGER,
        title TEXT,
        body TEXT
    )
''')

# Commit the changes
conn.commit()

# Clear the 'posts' table
cursor.execute('DELETE FROM posts')

# Commit the changes
conn.commit()

# Insert posts into the table
for post in posts:
    cursor.execute('''
        INSERT INTO posts (userId, title, body)
        VALUES (?, ?, ?)
    ''', (post['userId'], post['title'], post['body']))

# Commit the changes
conn.commit()

# Validate if the number of rows matches the expected number of posts
cursor.execute('SELECT * FROM posts')
rows = cursor.fetchall()
expected_num_posts = len(posts)
if len(rows) == expected_num_posts:
    print(f"Successfully inserted {expected_num_posts} posts into the database.")
else:
    print(f"Error: Expected {expected_num_posts} posts, but found {len(rows)} posts in the database.")

# Close the connection
conn.close()


# -*- coding: UTF-8 -*-

'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'                                                                         '
' Copyright 2018 Gauthier Brière (gauthier.briere "at" gmail.com)         '
'                                                                         '
' This file is part of cn5X++                                               '
'                                                                         '
' cn5X++ is free software: you can redistribute it and/or modify it         '
'  under the terms of the GNU General Public License as published by      '
' the Free Software Foundation, either version 3 of the License, or       '
' (at your option) any later version.                                     '
'                                                                         '
' cn5X++ is distributed in the hope that it will be useful, but           '
' WITHOUT ANY WARRANTY; without even the implied warranty of              '
' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the           '
' GNU General Public License for more details.                            '
'                                                                         '
' You should have received a copy of the GNU General Public License       '
' along with this program.  If not, see <http://www.gnu.org/licenses/>.   '
'                                                                         '
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

import sys, time
from math import *
from PyQt5.QtCore import QCoreApplication, QObject, QThread, QTimer, QEventLoop, pyqtSignal, pyqtSlot, QIODevice
from PyQt5.QtSerialPort import QSerialPort, QSerialPortInfo
from cn5X_config import *
from grblComSerial import grblComSerial

class grblCom(QObject):
  '''
  Gestion du thread de communication serie avec Grbl
  '''

  # Reprise des signaux venant du thread de Com a faire suivre
  sig_log     = pyqtSignal(int, str) # Message de fonctionnement du composant grblComSerial, renvoie : logSeverity, message string
  sig_connect = pyqtSignal()         # Emis a la reception de la connexion
  sig_init    = pyqtSignal(str)      # Emis a la reception de la chaine d'initialisation de Grbl, renvoie la chaine complete
  sig_ok      = pyqtSignal()         # Emis a la reception de la chaine "ok"
  sig_error   = pyqtSignal(int)      # Emis a la reception d'une erreur Grbl, renvoie le N° d'erreur
  sig_alarm   = pyqtSignal(int)      # Emis a la reception d'une alarme Grbl, renvoie le N° d'alarme
  sig_status  = pyqtSignal(str)      # Emis a la reception d'un message de status ("<...|.>"), renvoie la ligne complete
  sig_config  = pyqtSignal(str)      # Emis a la reception d'une valeur de config ($XXX)
  sig_data    = pyqtSignal(str)      # Emis a la reception des autres donnees de Grbl, renvoie la ligne complete
  sig_emit    = pyqtSignal(str)      # Emis a l'envoi des donnees sur le port serie
  sig_recu    = pyqtSignal(str)      # Emis a la reception des donnees sur le port serie
  sig_debug   = pyqtSignal(str)      # Emis a chaque envoi ou reception

  # Signaux de pilotage a envoyer au thread
  sig_abort        = pyqtSignal()
  sig_gcodeInsert  = pyqtSignal(str, object)
  sig_gcodePush    = pyqtSignal(str, object)
  sig_realTimePush = pyqtSignal(str, object)
  sig_clearCom     = pyqtSignal()
  sig_startPooling = pyqtSignal()
  sig_stopPooling  = pyqtSignal()

  def __init__(self):
    super().__init__()
    self.__threads       = None
    self.__Com           = None
    self.__connectStatus = False
    self.__grblInit      = False
    self.__pooling       = True
    self.__grblVersion   = ""
    self.__grblStatus    = ""
    self.__threads = []

  def startCom(self, comPort: str, baudRate: int):
    '''
    Gestion des communications serie et des timers dans des threads distincts
    '''

    self.sig_debug.emit("grblCom.startCom(self, {}, {})".format(comPort, baudRate))

    self.sig_log.emit(logSeverity.info.value, 'grblCom: Starting grblComSerial thread.')
    newComSerial = grblComSerial(comPort, baudRate, self.__pooling)
    thread = QThread()
    thread.setObjectName('grblComSerial')
    self.__threads.append((thread, newComSerial))  # need to store worker too otherwise will be gc'd
    newComSerial.moveToThread(thread)

    # Connecte les signaux provenant du grblComSerial
    newComSerial.sig_log.connect(self.sig_log.emit)
    newComSerial.sig_connect.connect(self.on_sig_connect)
    newComSerial.sig_init.connect(self.on_sig_init)
    newComSerial.sig_ok.connect(self.sig_ok.emit)
    newComSerial.sig_error.connect(self.sig_error.emit)
    newComSerial.sig_alarm.connect(self.sig_alarm.emit)
    newComSerial.sig_status.connect(self.on_sig_status)
    newComSerial.sig_config.connect(self.sig_config.emit)
    newComSerial.sig_data.connect(self.sig_data.emit)
    newComSerial.sig_emit.connect(self.sig_emit.emit)
    newComSerial.sig_recu.connect(self.sig_recu.emit)
    newComSerial.sig_debug.connect(self.sig_debug.emit)

    # Signaux de pilotage a envoyer au thread
    self.sig_abort.connect(newComSerial.abort)
    self.sig_gcodeInsert.connect(newComSerial.gcodeInsert)
    self.sig_gcodePush.connect(newComSerial.gcodePush)
    self.sig_realTimePush.connect(newComSerial.realTimePush)
    self.sig_clearCom.connect(newComSerial.clearCom)
    self.sig_startPooling.connect(newComSerial.startPooling)
    self.sig_stopPooling.connect(newComSerial.stopPooling)

    # Start the thread...
    thread.started.connect(newComSerial.run)
    thread.start()  # this will emit 'started' and start thread's event loop

    # Memorise le communicateur
    self.__Com = newComSerial

  @pyqtSlot(bool)
  def on_sig_connect(self, value: bool):
    self.sig_debug.emit("grblCom.on_sig_connect(self, {})".format(value))
    ''' Maintien l'etat de connexion '''
    self.__connectStatus = value
    self.sig_connect.emit()

  @pyqtSlot(str)
  def  on_sig_init(self, buff: str):
    self.sig_debug.emit("grblCom.on_sig_init(self, {})".format(buff))
    self.__grblInit = True
    self.__grblVersion = buff.split("[")[0]
    self.sig_init.emit(buff)

  def grblVersion(self):
    ''' Renvoi la chaine Grbl vXXX '''
    return self.__grblVersion

  @pyqtSlot(str)
  def on_sig_status(self, buff: str):
    self.sig_debug.emit("grblCom.on_sig_status(self, {})".format(buff))
    ''' Memorise le status de Grbl a chaque fois qu'on en voi un passer '''
    self.__grblStatus = buff[1:].split('|')[0]
    self.sig_status.emit(buff)

  def grblStatus(self):
    ''' Renvoi le dernier status Grbl vu '''
    return self.__grblStatus

  def stopCom(self):
    self.sig_debug.emit("grblCom.stopCom(self)")
    ''' Stop le thread des communications serie '''
    self.clearCom() # Vide la file d'attente
    self.sig_log.emit(logSeverity.info.value, self.tr("Envoi signal sig_abort au thread de communications serie..."))
    self.sig_abort.emit()
    # Attente de la fin du (des) thread(s)
    for thread, worker in self.__threads:
        thread.quit()  # this will quit **as soon as thread event loop unblocks**
        thread.wait()  # <- so you need to wait for it to *actually* quit
    self.sig_log.emit(logSeverity.info.value, self.tr("Thread(s) enfant(s) termine(s)."))
    self.__grblInit = False
    self.__threads = []

  def gcodeInsert(self, buff: str, flag=COM_FLAG_NO_FLAG):
    if self.__connectStatus and self.__grblInit:
      self.sig_gcodeInsert.emit(buff, flag)
    else:
      self.sig_log.emit(logSeverity.warning.value, self.tr("grblCom: Grbl non connecte ou non initialise, [{}] impossible a envoyer").format(buff))

  def gcodePush(self, buff: str, flag=COM_FLAG_NO_FLAG):
    if self.__connectStatus and self.__grblInit:
      self.sig_gcodePush.emit(buff, flag)
    else:
      self.sig_log.emit(logSeverity.warning.value, self.tr("grblCom: Grbl non connecte ou non initialise, [{}] impossible a envoyer").format(buff))

  def realTimePush(self, buff: str, flag=COM_FLAG_NO_FLAG):
    if self.__connectStatus and self.__grblInit:
      self.sig_realTimePush.emit(buff, flag)
    else:
      self.sig_log.emit(logSeverity.warning.value, self.tr("grblCom: Grbl non connecte ou non initialise, [{}] impossible a envoyer").format(buff))

  def clearCom(self):
    self.sig_clearCom.emit()

  @pyqtSlot()
  def startPooling(self):
    self.__pooling = True
    self.sig_startPooling.emit()

  @pyqtSlot()
  def stopPooling(self):
    self.__pooling = False
    self.sig_stopPooling.emit()

  def isOpen(self):
    return self.__connectStatus


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

urlpatterns = [
    path('', views.introcric,name='introcric'),
    path('IntroRPS/', views.introRPS,name='introRPS'),
    path('Registeration/', views.register,name='registeration'),
    path('Login/', views.login,name='Login'),
    path('Home/',views.user,name='home'),

    #cricket
    path('cricket/', views.toss,name='cricket'),
    path('batting/', views.battingprofile,name='batting'),
    path('balling/', views.ballingprofile,name='balling'),
    path('battingstart/', views.battingstart,name='battingstart'),   #playerbat first
    path('battingsecond/', views.battingsecond,name='battingsecond'),   #playerbat second
    path('ballingstart/', views.ballingstart,name='ballingstart'),    #opp bat first
    path('ballingsecond/', views.ballingsecond,name='ballingsecond'),    #opp bat second

    #Stone Paper Scissor
    path('RPS/', views.RPS,name='RPS'),
]


from lxml import etree
from pykml import parser
from pykml.factory import KML_ElementMaker as KML
from shapely.geometry import LinearRing
from shapely.geometry import Polygon
from shapely.validation import explain_validity
import copy
import math
import os
import zipfile

# This function reads the filename provided and returns the parsed
# KML content. The file is assumed to be a .kmz file.
def ReadKMZ(filename):
  with zipfile.ZipFile(filename) as kmz_file:
    with kmz_file.open('doc.kml', 'r') as kml_file:
      doc = parser.parse(kml_file).getroot()
      return doc

# This function reads the KML file provided and returns the parsed
# KML content. The file is assumed to be a .kml file.
def ReadKML(filename):
  with open(filename, 'r') as kml_file:
    doc = parser.parse(kml_file).getroot()
    return doc

# This function attempts to combine the coordinate lists into a single
# list of coordinates. It does so by brute force: comparing the first
# and last elements of each list to the other lists, and combining
# the new list to the first neighbor when the values are the same.
def ConsolidateLists(coordinateLists):
  print('Comparing %d lists...' % len(coordinateLists))
  final = []
  for lst in coordinateLists:
    if lst[0] == lst[-1]:
      print('    --> on RING %s...%s' % (lst[0], lst[-1]))
    else:
      print('    --> on %s...%s' % (lst[0], lst[-1]))
    if len(final) == 0:
      final.append(lst)
      continue
    found = False
    for f in final:
      #print('%s...%s compare %s...%s' % (f[0], f[-1], lst[0], lst[-1]))
      if f[0] == lst[len(lst)-1]:
        print('Joining new element list %s...%s with %s...%s' % (lst[0], lst[-1], f[0], f[-1]))
        lst.extend(f[1:])
        del(f[:])
        f.extend(lst)
        found = True
        print('    = New list = %s...%s' % (f[0], f[-1]))
        break
      elif f[len(f)-1] == lst[0]:
        print('Joining list %s...%s with new element list %s...%s' % (f[0], f[-1], lst[0], lst[-1]))
        f.extend(lst[1:])
        print('    = New list = %s...%s' % (f[0], f[-1]))
        found = True
        break
      elif f[0] == lst[0]:
        print('Reverse joining list %s...%s with new element list %s...%s' % (f[0], f[-1], lst[0], lst[-1]))
        r = list(reversed(lst))
        r.extend(f[1:])
        del(f[:])
        f.extend(r)
        print('    = New list = %s...%s' % (f[0], f[-1]))
        found = True
        break
      elif f[len(f)-1] == lst[len(lst)-1]:
        print('Reverse joining new list %s...%s with list %s...%s' % (f[0], f[-1], lst[0], lst[-1]))
        r = list(reversed(lst))
        f.extend(r[1:])
        found = True
        print('    = New list = %s...%s' % (f[0], f[-1]))
        break
    if not found:
      #print('  Appending...')
      final.append(lst)
  print('Have %d final lists' % len(final))
  return final

def Distance(p0, p1):
  c0 = p0.split(',')
  c1 = p1.split(',')

  c0x = float(c0[0])
  c0y = float(c0[1])
  c1x = float(c1[0])
  c1y = float(c1[1])

  return math.sqrt((c1x-c0x)*(c1x-c0x) + (c1y-c0y)*(c1y-c0y))

# Close any nearly-closed rings by appending the first point to the last point.
def CloseRings(coordinateLists, distance):
  print('Closing near-closed rings')
  final = []
  for lst in coordinateLists:
    if lst[0] == lst[len(lst)-1]:
      final.append(lst)
      continue

    latlngLst0 = lst[0].split(',')
    latlngLstN = lst[len(lst)-1].split(',')
    if Distance(lst[0], lst[len(lst)-1]) < distance:
      print('Closing ring %s...%s' % (lst[0], lst[len(lst)-1]))
      lst.append(lst[0])
    final.append(lst)
  return final

# This function splices lists whose endpoints are within a fraction of a degree of touching.
def SpliceLists(coordinateLists, threshold):
  print('Splicing %d lists...' % len(coordinateLists))
  final = []
  n = 0
  for lst in coordinateLists:
    if len(final) == 0:
      final.append(lst)
      continue
    found = False

    # If the list is already a ring, just continue.
    if lst[0] == lst[len(lst)-1]:
      final.append(lst)
      continue

    #print('   on list [%d] %s...%s' % (len(lst), lst[0], lst[len(lst)-1]))

    for f in final:
      latlngLst0 = lst[0].split(',')
      latlngLstN = lst[len(lst)-1].split(',')
      latlngF0 = f[0].split(',')
      latlngFN = f[len(f)-1].split(',')

      if (abs(float(latlngLst0[0]) - float(latlngF0[0])) < threshold and
          abs(float(latlngLst0[1]) - float(latlngF0[1])) < threshold and
          latlngLst0[0] == latlngF0[0]):
        print('EXACT splice found %s...%s' % (f[0], f[-1]))
        print('  with             %s...%s' % (lst[0], lst[-1]))
        # Strip the last point from the new segment.
        r = list(reversed(f))
        r.extend(lst[1:])
        del(f[:])
        f.extend(r)
        found = True
        break
      elif (abs(float(latlngLstN[0]) - float(latlngFN[0])) < threshold and
          abs(float(latlngLstN[1]) - float(latlngFN[1])) < threshold):
        found = True
        print('reverse splice     list %s...%s ' % (f[0], f[len(f)-1]))
        print('  with new element list %s...%s\n' % (lst[0], lst[len(lst)-1]))
        r = list(reversed(lst))
        f.extend(r)
        found = True
        break
      elif (abs(float(latlngLst0[0]) - float(latlngF0[0])) < threshold and
            abs(float(latlngLst0[1]) - float(latlngF0[1])) < threshold):
        print('splice 0,0 list         %s...%s' % (f[0], f[len(f)-1]))
        print('  with new element list %s...%s\n' % (lst[0], lst[len(lst)-1]))
        r = list(reversed(lst))
        r.extend(f)
        del(f[:])
        f.extend(r)
        found = True
        break
      elif (abs(float(latlngLstN[0]) - float(latlngF0[0])) < threshold and
            abs(float(latlngLstN[1]) - float(latlngF0[1])) < threshold):
        print('splice new list  [%d]     %s...%s' % (len(lst), lst[0], lst[len(lst)-1]))
        print('  with element list [%d]  %s...%s\n' % (len(f), f[0], f[len(f)-1]))
        lst.extend(f)
        del(f[:])
        f.extend(lst)
        print('  new list [%d] = %s...%s' % (len(f), f[0], f[-1]))
        found = True
        break
      elif (abs(float(latlngFN[0]) - float(latlngLst0[0])) < threshold and
            abs(float(latlngFN[1]) - float(latlngLst0[1])) < threshold):
        print('splice list   [%d]   %s...%s' % (len(f), f[0], f[len(f)-1]))
        print('  with new element list [%d] %s...%s\n' % (len(lst), lst[0], lst[len(lst)-1]))
        f.extend(lst)
        print('  new list [%d] = %s...%s' % (len(f), f[0], f[-1]))
        found = True
        break
    n += 1

    if not found:
      final.append(lst)
  print('Have %d final lists' % len(final))
  return final

# Need a method to close rings?

# This function finds the wanted border segments from the NOAA border definition.
def FindBorderSegments(doc):
  folders = list(doc.Document.Folder)
  coordinates = []
  for f in folders:
    print('Found folder %s' % f.name.text)
    placemarks = list(f.Placemark)
    line = ''
    for p in placemarks:
      if f.name.text == 'Territorial Sea':
        desc = p.description.text
        if (desc.find('B0008') != -1 or
            desc.find('B0011') != -1 or
            desc.find('B0102') != -1 or
            desc.find('B0084') != -1 or
            desc.find('B0153') != -1 or
            desc.find('B0172') != -1 or
            desc.find('B0169') != -1 or
            desc.find('B0384') != -1 or
            desc.find('B0168') != -1):
          continue

        ls = list(p.MultiGeometry.LineString)
        #print('keep place %s = %s with %d segments' % (p.attrib['id'], p.name.text, len(ls)))
        for l in ls:
          line = l.coordinates.text
          points = line.split(' ')
          #print('  seg size %d' % len(points))
          coords = []
          for pt in points:
            if pt is not '':
              c = pt.split(',')
              # Trim outline near AK
              if (desc.find('B0174') != -1 and
                  float(c[0]) > -133.207 and float(c[1]) < 54.646):
                continue
              # Trim outline near ME
              if (desc.find('B0138') != -1 and
                  float(c[0]) > -67.3014 and float(c[1]) > 44.2):
                continue
              # Normalize -180 to 180 to get equivalence and correct segment merging later on.
              if c[0] == '-180' or c[0] == '180':
                c[0] = '180'
              coords.append('%s,%s,0' % (c[0].strip(), c[1].strip()))
          coordinates.append(coords)

      if f.name.text.find('Maritime') != -1:
        desc = p.description.text
        if (desc.find('B0075') != -1 or
            desc.find('B0021') != -1 or
            desc.find('B0020') != -1 or
            desc.find('B0018') != -1 or
            desc.find('B0081') != -1 or
            desc.find('B0082') != -1):
          ls = list(p.MultiGeometry.LineString)
          print('keep place %s = %s with %d segments' % (p.attrib['id'], p.name.text, len(ls)))
          for l in ls:
            line = l.coordinates.text
            points = line.split(' ')
            if desc.find('B0018') != -1:
              points = points[2:]
            coords = []
            for pt in points:
              if pt is not '':
                c = pt.split(',')
                coords.append('%s,%s,0' % (c[0].strip(), c[1].strip()))
            print('  have segment [%d] %s...%s' % (len(coords), coords[0], coords[-1]))
            coordinates.append(coords)

  print('Found %d segments' % len(coordinates))
  return coordinates

# Add the border line segments for the US-Mexico and US-CA borders.
def AddBorderSegments(mexicoDoc, canadaDoc, coordinateLists):
  mexicoFolders = list(mexicoDoc.Document.Folder)
  for f in mexicoFolders:
    p = f.Placemark
    if f.name.text == 'US_Mex_Boundary':
      line = p.LineString.coordinates.text
      points = line.split(' ')
      print('Adding US-Mex boundary size %d' % len(points))
      coords = []
      for pt in points:
        if pt.strip() is not '':
          c = pt.split(',')
          # Note: The furthest west point doesn't match well with the NOAA
          # boundaries. Eliminating it from the polygon creates the right
          # shape.
          if float(c[0]) < -117.4:
            print('Trimmed westernmost point of US-MEX border %s' % c)
            continue
          coords.append('%s,%s,0' % (c[0].strip(), c[1].strip()))
      coordinateLists.append(coords)

  canadaBorderPlacemarks = list(canadaDoc.Document.Placemark)
  for p in canadaBorderPlacemarks:
    if (p.name.text == 'AK-CA Boundary' or
        p.name.text == 'CONUS-CA Boundary'):
      line = p.LineString.coordinates.text
      points = line.split(' ')
      # Adjustment: the FCC US-CA border extends out into the Atlantic. Clip
      # the border so it is closer to the territorial sea for creating
      # authorization areas.
      if p.name.text == 'CONUS-CA Boundary':
        points = points[3:]
      print('Adding %s size %d' % (p.name.text, len(points)))
      coords = []
      for pt in points:
        if pt is not '':
          c = pt.split(',')
          coords.append('%s,%s,0' % (c[0].strip(), c[1].strip()))
      coordinateLists.append(coords)

def FixAntiMeridianPolygon(ls):
  """Detects and fix a 180deg crossing polygon.

  Args:
    ls: a linestring as a list of 'lon,lat,alt' strings.

  Returns:
    None if not a anti-meridian polygon otherwise the western part linestring.

  Side effects:
    If detected anti-meridian, the given linestring is modified to be the easter
    part.
  """
  coords = []
  found_anti_meridian = False
  for c in ls:
    xy = c.split(',')
    coords.append([float(xy[0]), float(xy[1])])
    if float(xy[0]) == 180:
      found_anti_meridian = True
  lr = LinearRing(coords)
  polygon = Polygon(lr)
  # The invalid polygon is the case of Semisopochnoi Island, which
  # zone crosses the antimeridian.
  if not polygon.is_valid:
    print('POLYGON IS NOT VALID! : %d' % len(ls))
    explain_validity(polygon)
    if found_anti_meridian:
      print('Polygon spans anti-meridian - Splitting in 2')
      # To deal with this case, we'll split the zone into two pieces,
      # one of which is in the eastern hemisphere and one in the
      # western hemisphere. This is purely a tooling issue to make
      # the zone easier to manage with other software.
      new_piece = []
      begin_anti_meridian = -1
      end_anti_meridian = -1
      for i in range(0, len(ls)):
        xy = ls[i].split(',')
        if float(xy[0]) == 180:
          # Note: the '-' is to reverse the sign so shapely sees
          # the coordinates correctly.
          new_piece.append('-' + ls[i])
          if begin_anti_meridian == -1:
            begin_anti_meridian = i
          else:
            end_anti_meridian = i
            new_piece.append(new_piece[0])
        elif begin_anti_meridian >= 0 and end_anti_meridian == -1:
          new_piece.append(ls[i])

      del ls[begin_anti_meridian+1 : end_anti_meridian]
      return new_piece
  return None

# Find the data directory
cur_dir = os.path.dirname(os.path.realpath(__file__))
root_dir = os.path.dirname(cur_dir)
zones_dir = os.path.join(root_dir, 'data', 'zones')

noaaDoc = ReadKMZ(os.path.join(zones_dir, 'parts', 'USMaritimeLimitsAndBoundariesKML.kmz'))
mexicoDoc = ReadKMZ(os.path.join(zones_dir, 'parts', 'us_mex_boundary.kmz'))
canadaDoc = ReadKML(os.path.join(zones_dir, 'uscabdry.kml'))

coordinateLists = FindBorderSegments(noaaDoc)
AddBorderSegments(mexicoDoc, canadaDoc, coordinateLists)

print('Total segments = %d' % len(coordinateLists))

# Note: this deep copy is for debugging purposes: to add the source data
# to the output KML file for comparison to the derived data.
coordx = copy.deepcopy(coordinateLists)

consolidatedStringsA = ConsolidateLists(coordinateLists)
# Run it through again: if we splice one in the middle of two existing
# segments, it won't latch on. Repeat a couple times to get all the
# way done...
consolidatedStringsB = ConsolidateLists(consolidatedStringsA)
consolidatedStringsC = ConsolidateLists(consolidatedStringsB)
consolidatedStrings = ConsolidateLists(consolidatedStringsC)

closedRings = CloseRings(consolidatedStrings, .001)

# Also run splice a few times to catch middle-splices that don't
# catch both ends.
spliceStringsA = SpliceLists(closedRings, .002)
spliceStringsB = SpliceLists(spliceStringsA, .002)

# Note: Google Earth can't display polygons with a large number
# of points. Use KML Viewer to view output from further steps:
# http://ivanrublev.me/kml/
# Google Earth can show the LineString boundaries for
# comparison to the various source data files.
coordy = copy.deepcopy(spliceStringsB)
print('====================')
shortSplicedStrings = SpliceLists(spliceStringsB, .002)

# At this point the only holes remaining are fairly large ones.
# We will do another splice with a larger margin of error to
# close those gaps.
longSplicedStrings = SpliceLists(shortSplicedStrings, .3)

# One final call to close rings. The two rings that need closed
# have a couple largish gaps, so use a big threshold.
lineStrings = CloseRings(longSplicedStrings, 1)

# Split polygons crossing anti-meridians.
for ls in lineStrings:
  if ls[0] != ls[-1]:
    print('NOT A RING!')
  new_ls = FixAntiMeridianPolygon(ls)
  if new_ls is not None:
    lineStrings.append(new_ls)

# Reverse rings if necessary.
for k, ls in enumerate(lineStrings):
  coords = []
  for c in ls:
    xy = c.split(',')
    coords.append([float(xy[0]), float(xy[1])])
  lr = LinearRing(coords)
  if not lr.is_ccw:
    print('Reversing non-CCW ring')
    r = list(reversed(ls))
    lineStrings[k] = r

# Cleanup the coordinates to be rounded correctly with 9 precision numbers
# (ie about 0.1mm)
for k, ls in enumerate(lineStrings):
  new_ls = []
  for c in ls:
    xy = c.split(',')
    new_ls.append('%.9f,%.9f,0' % (float(xy[0]), float(xy[1])))
  lineStrings[k] = new_ls

# Create output KML
doc = KML.kml(
  KML.Document(
    KML.name('US Area'),
    KML.Style(
      KML.LineStyle(
        KML.color('ff0000ff'),
        KML.width(2)
      ),
      KML.PolyStyle(
        KML.color('66000066')
      ),
      id="stl"
    ),
    KML.Style(
      KML.LineStyle(
        KML.color('ff00ffff'),
        KML.width(4)
      ),
      KML.PolyStyle(
        KML.color('00006666')
      ),
      id="stlx"
    ),
    KML.Style(
      KML.LineStyle(
        KML.color('ff00ff00'),
        KML.width(2)
      ),
      KML.PolyStyle(
        KML.color('00006666')
      ),
      id="stly"
    ),
  )
)

num = 1
for ls in lineStrings:
  print('Have final poly len=%d' % len(ls))
  geo_name = '%d' % num
  num += 1
  pm = KML.Placemark(
    KML.name('%s' % geo_name),
    KML.styleUrl('#stl'),
    KML.Polygon(
      KML.extrude(1),
      KML.altitudeMode('clampToGround'),
      KML.outerBoundaryIs(
        KML.LinearRing(
          KML.coordinates(' '.join(ls))
        )
      )
    )
  )
  doc.Document.append(pm)

# For debugging: optionally include the paths of the original source data.
#ns = 10000
#for ls in coordx:
#  # print('x coordinates=[%s ... %s] (%d)' % (ls[0], ls[len(ls)-1], len(ls)))
#  pm = KML.Placemark(
#    KML.name('%d' % ns),
#    KML.styleUrl('#stlx'),
#    KML.LineString(
#      KML.extrude(1),
#      KML.altitudeMode('clampToGround'),
#      KML.coordinates(' '.join(ls))
#    )
#  )
#  ns += 1
#  doc.Document.append(pm)

# For debugging: optionally include the joined paths
#ns = 20000
#for ls in coordy:
#  # print('y coordinates=[%s ... %s] (%d)' % (ls[0], ls[len(ls)-1], len(ls)))
#  pm = KML.Placemark(
#    KML.name('%d' % ns),
#    KML.styleUrl('#stly'),
#    KML.LineString(
#      KML.extrude(1),
#      KML.altitudeMode('clampToGround'),
#      KML.coordinates(' '.join(ls))
#    )
#  )
#  ns += 1
#  doc.Document.append(pm)

# For debugging: optionally include the spliced paths
#ns = 30000
#for ls in lineStrings:
#  # print('z coordinates=[%s ... %s] (%d)' % (ls[0], ls[len(ls)-1], len(ls)))
#  pm = KML.Placemark(
#    KML.name('%d' % ns),
#    KML.styleUrl('#stly'),
#    KML.LineString(
#      KML.extrude(1),
#      KML.altitudeMode('clampToGround'),
#      KML.coordinates(' '.join(ls))
#    )
#  )
#  ns += 1
#  doc.Document.append(pm)

with open(os.path.join(zones_dir, 'usborder-tmp.kml'), 'w+') as outputFile:
  outputFile.write(etree.tostring(doc, encoding='utf-8', pretty_print=True).decode())


#!/usr/bin/env python2
import MDAnalysis
import numpy as np
from numpy.linalg import norm

u = MDAnalysis.Universe('../../ionized.psf', '../output-dcd/NPT-250-pf10ps.dcd')
#print(u)
#print(list(u.atoms[:100].residues))

sel_prot = u.select_atoms("protein and backbone")
sel_memb = u.select_atoms("segid L.* and prop z > 0.0")

dist = []
f = open("separation.dat","w")
for ts in u.trajectory:
    print("Frame: %5d, Time: %8.3f ps" % (ts.frame, u.trajectory.time))
    A = sel_prot.center_of_mass()
    B = sel_memb.center_of_mass()
    dummy = A - B
    dist.append((u.trajectory.time, norm(dummy)))
    f.write(str(ts.frame) + " " + str(norm(dummy)) + "\n")
f.close()
print(dist)


from dataclasses import dataclass, field
from typing import Optional
from ojp.extension_type import ExtensionType
from ojp.mobility_enum import MobilityEnum

__NAMESPACE__ = "http://datex2.eu/schema/2_0RC1/2_0"

@dataclass
class Mobility:
    mobility_type: Optional[MobilityEnum] = field(
        default=None,
        metadata={
            "name": "mobilityType",
            "type": "Element",
            "namespace": "http://datex2.eu/schema/2_0RC1/2_0",
            "required": True,
        }
    )
    mobility_extension: Optional[ExtensionType] = field(
        default=None,
        metadata={
            "name": "mobilityExtension",
            "type": "Element",
            "namespace": "http://datex2.eu/schema/2_0RC1/2_0",
        }
    )


#Crie um programa que leia nome, ano de nascimento e carteira de trabalho e cadastre-os
# (com idade) em um dicionário, se por acaso a CTPS for diferente de ZERO, o dicionário receberá
# também o ano de contratação e o salário. Calcule e acrescente, além da idade, com quantos anos a
# pessoa vai se aposentar.

import datetime
trab = {}
trab['nome'] = str(input('Nome: '))
ano = int(input('Ano de nascimento: '))
trab['idade'] = datetime.date.today().year - ano
trab['ctps'] = int(input('Carteira de Trabalho (0 não tem): '))
if trab['ctps']!= 0:
    trab['contratação'] = int(input('Ano de contratação: '))
    trab['salário'] = float(input('Salário: '))
    trab['aposentadoria'] = trab['contratação'] - ano + 35

for k, v in trab.items():
    print(f'{k} tem o valor {v}')


import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from google.colab import drive
drive.mount('/content/gdrive')
import pickle
from sklearn.preprocessing import OneHotEncoder
import datetime

path = '/content/gdrive/My Drive/DL_Project_Data/data.data'
with open(path, 'rb') as f:
  dataset = pickle.load(f)
images_temp = dataset['images']
alphabet = dataset['alphabets']
alphabet = np.reshape(np.array(alphabet), (234000, 1))
images = np.zeros((234000, 32, 32, 1))
for i in range(234000):
  images[i, :, :, 0] = images_temp[32*i:32*(i+1), :]
enc = OneHotEncoder(sparse=False)
alphabet_onehot = enc.fit_transform(alphabet)
train_data = images
train_labels = alphabet_onehot
ydim=26
zdim=100

def lkrelu(x, slope=0.01):
    return tf.maximum(slope * x, x)

def get_shape(tensor): # static shape
    return tensor.get_shape().as_list()

def batch_normalization(*args, **kwargs):
    with tf.name_scope('bn'):
        bn = tf.layers.batch_normalization(*args, **kwargs)
    return bn

def sample(X, y, length):
  max_len = len(X)
  idx =  np.random.randint(low=0, high=max_len, size=(length))
  return X[idx], y[idx]

# Define Discriminator
class Discriminator(object):
    def __init__(self, stddev=0.02):
        self.stddev = stddev

    def __call__(self, xs, ys, is_training, reuse=None):
        batch_dim = tf.shape(xs)[0]
        with tf.variable_scope('discriminator', initializer=tf.truncated_normal_initializer(stddev=self.stddev), reuse=reuse):
            with tf.variable_scope('conv1'):
                filters_1 = tf.get_variable('filters', [5, 5, 1, 32])
                conv_1 = tf.nn.conv2d(xs, filters_1, [1, 2, 2, 1], padding='SAME')

                # Adds y as a channel to conv_1 as described in ICGAN paper
                conv_1_concat_ys = tf.concat([conv_1, tf.tile(tf.reshape(ys, [-1, 1, 1, ys.get_shape()[-1]]),
                                                                [1, tf.shape(conv_1)[1], tf.shape(conv_1)[2], 1])], axis=3)
                a_1 = lkrelu(conv_1_concat_ys, slope=0.2)

            with tf.variable_scope('conv2'):
                filters_2 = tf.get_variable('filters', [5, 5, 32 + ydim, 32])
                conv_2 = tf.nn.conv2d(a_1, filters_2, [1, 2, 2, 1], padding='SAME')
                bn_2 = batch_normalization(conv_2,  center=False,
                            scale=False, training=is_training)
                a_2 = lkrelu(bn_2, slope=0.2)

            with tf.variable_scope('conv3'):
                filters_3 = tf.get_variable('filters', [5, 5, 32, 16])
                conv_3 = tf.nn.conv2d(a_2, filters_3, [1, 2, 2, 1], padding='SAME')
                bn_3 = batch_normalization(conv_3,  center=False,
                                            scale=False, training=is_training)
                a_3 = lkrelu(bn_3, slope=0.2)

            with tf.variable_scope('output'):
                  a_h = tf.layers.dense(tf.layers.flatten(a_3), 64)
                  a_o = tf.layers.dense(a_h, 1, activation='sigmoid')
        return a_o

# Define Generator
class Generator(object):
    def __init__(self, stddev=0.02):
        self.stddev = stddev

    def __call__(self, zs, ys, is_training):
        batch_dim = tf.shape(zs)[0]
        with tf.variable_scope('generator', initializer=tf.truncated_normal_initializer(stddev=self.stddev)):
            inputs = tf.concat([zs, ys], axis=1)
            with tf.variable_scope('volume'):
                z_p = tf.layers.dense(inputs, 4*4*128, activation='relu')
                bn_p = tf.layers.batch_normalization(z_p, training=is_training)
                reshaped_a_p = tf.reshape(bn_p, [-1, 4, 4, 128])
            with tf.variable_scope('deconv1'):
                deconv_1 = tf.layers.conv2d_transpose(reshaped_a_p, filters=64, kernel_size=5, strides=2, padding='same', activation='relu')
                bn_1 = tf.layers.batch_normalization(deconv_1, training=is_training)
            with tf.variable_scope('deconv2'):
                deconv_2 = tf.layers.conv2d_transpose(bn_1, filters=32, kernel_size=5, strides=2, padding='same', activation='relu')
                bn_2 = tf.layers.batch_normalization(deconv_2, training=is_training)

            with tf.variable_scope('deconv3'):
                deconv_3 = tf.layers.conv2d_transpose(bn_2, filters=16, kernel_size=5, strides=2, padding='same', activation='relu')
                bn_3 = tf.layers.batch_normalization(deconv_3, training=is_training)
                deconv_4 = tf.layers.conv2d_transpose(bn_3, filters=1, kernel_size=5, strides=1, padding='same', activation='tanh')
        return deconv_4

class CDCGAN(object):
    def __init__(self, zdim, ydim, xshape, lr=0.00005, beta1=0.5):
        self.is_training = tf.placeholder(tf.bool)

        self.zs = tf.placeholder(tf.float32, [None, zdim])
        self.g_ys = tf.placeholder(tf.float32, [None, ydim])

        self.xs = tf.placeholder(tf.float32, [None] + xshape)
        self.d_ys = tf.placeholder(tf.float32, [None, ydim])

        self.generator = Generator()
        self.discriminator = Discriminator()

        self.generator_output = self.generator(self.zs, self.g_ys, self.is_training)
        self.real_discriminator_output = self.discriminator(self.xs, self.d_ys, self.is_training)
        self.fake_discriminator_output = self.discriminator(self.generator_output, self.g_ys, self.is_training, reuse=True)

        self.generator_loss = -tf.reduce_mean(tf.log(self.fake_discriminator_output))
        self.discriminator_loss = -tf.reduce_mean(tf.log(self.real_discriminator_output) + tf.log(1.0 - self.fake_discriminator_output))

        g_update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS, scope='generator')
        with tf.control_dependencies(g_update_ops):
            self.generator_train_step = tf.train.RMSPropOptimizer(lr).minimize(self.generator_loss,
                                        var_list=tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='generator'))
        d_update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS, scope='discriminator')
        with tf.control_dependencies(d_update_ops):
            self.discriminator_train_step = tf.train.RMSPropOptimizer(lr).minimize(self.discriminator_loss,
                                            var_list=tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='discriminator'))

    def train_step(self, sess, xs, d_ys, zs, g_ys, is_training=True):
        _, dloss_curr = sess.run([self.discriminator_train_step, self.discriminator_loss],
                                    feed_dict={self.xs : xs, self.d_ys : d_ys, self.zs : zs, self.g_ys : d_ys, self.is_training : is_training})
        _, gloss_curr = sess.run([self.generator_train_step, self.generator_loss],
                                    feed_dict={self.zs : zs, self.g_ys : g_ys, self.is_training : is_training})
        return (gloss_curr, dloss_curr)

    def sample_generator(self, sess, zs, ys, is_training=True):
        return sess.run(self.generator_output, feed_dict={self.zs : zs, self.g_ys : ys, self.is_training : is_training})

batch_size = 128
epochs = 100000
draw_step = 500
model = CDCGAN(zdim, ydim, [32, 32, 1])
sess = tf.Session()
sess.run(tf.global_variables_initializer())
track_d_loss = []
track_g_loss = []
saver = tf.train.Saver()
sched = 10000
for epoch in range(epochs):
    if epoch % sched == 1 or epoch == 0:
      start = datetime.datetime.now()
    batch_xs, batch_ys = sample(train_data, train_labels, batch_size)
    gloss, dloss = model.train_step(sess, np.reshape(batch_xs, [-1, 32, 32, 1]),
                    batch_ys, np.random.uniform(-1, 1, (batch_size, zdim)), batch_ys)
    track_d_loss.append(dloss)
    track_g_loss.append(gloss)

    if epoch % sched == 0:
        saver.save(sess, './GAN_session.saved')
        imgs = model.sample_generator(sess, zs=np.repeat(np.random.uniform(-1, 1, (26, zdim)), 26, axis=0),
                                      ys=np.tile(np.eye(ydim), [26, 1]))

        fig = plt.figure()
        fig.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0.1)
        for i in range(26*26):
            fig.add_subplot(26, 26, i + 1)
            plt.imshow(imgs[i, :, :, 0], cmap='gray')
            plt.axis('off')
        plt.savefig('./iter_{}.png'.format(epoch))
        plt.show()
        plt.close()
        end = datetime.datetime.now()
        print('Epoch: {}/{},\t G loss: {:.4f}, D loss: {:.4f}\t| time: {}'.
          format(epoch, epochs, gloss, dloss, end-start))