#!/usr/bin/env python
# encoding: utf-8
# Created by BIT09 at 2023/4/27
import os
import matplotlib.pyplot as plt
import torch
import torch.nn.functional as F
from torch.nn import Linear
from torch_geometric.datasets import TUDataset
from torch_geometric.loader import DataLoader
from torch_geometric.nn import GNNExplainer
from torch_geometric.nn import GraphConv
from torch_geometric.nn import global_mean_pool

# Build the model
class GNN(torch.nn.Module):
    def __init__(self, hidden_channels):
        super(GNN, self).__init__()
        torch.manual_seed(12345)
        self.conv1 = GraphConv(dataset.num_node_features, hidden_channels)
        self.conv2 = GraphConv(hidden_channels, hidden_channels)

        self.conv3 = GraphConv(hidden_channels, hidden_channels)
        self.linear = Linear(hidden_channels, dataset.num_classes)

    def forward(self, x, edge_index, batch):
        x = self.conv1(x, edge_index)
        x = x.relu()
        x = self.conv2(x, edge_index)
        x = x.relu()
        x = self.conv3(x, edge_index)
        x = global_mean_pool(x, batch)
        x = F.dropout(x, p=0.5, training=self.training)
        x = self.linear(x)
        return x

# Creating the function to train the model
def Train(data_loader, loss_func):
    model.train()
    # Iterate in batches over the training dataset
    for data in data_loader:
        # Perform a single forward pass
        out = model(data.x, data.edge_index, data.batch)
        # Compute the loss
        loss = loss_func(out, data.y)
        # Derive gradients
        loss.backward()
        # Update parameters based on gradients
        optimizer.step()
        # Clear gradients
        optimizer.zero_grad()

# function to test the model
def Test(data_loader):
    model.eval()
    correct = 0
    # Iterate in batches over the training/test dataset
    for data in data_loader:
        out = model(data.x, data.edge_index, data.batch)
        # Use the class with highest probability.
        pred = out.argmax(dim=1)
        # Check against ground-truth labels.
        correct += int((pred == data.y).sum())
    # Derive ratio of correct predictions.
    return correct / len(test_loader.dataset)

if __name__ == '__main__':
    # Load the dataset
    dataset = TUDataset(root='../../data_root/TUDataset', name='MUTAG')
    # print details about the graph
    print(f'Dataset: {dataset}:')
    print("Number of Graphs: ", len(dataset))
    print("Number of Freatures: ", dataset.num_features)
    print("Number of Classes: ", dataset.num_classes)

    data = dataset[0]
    print(data)
    print("No. of nodes: ", data.num_nodes)
    print("No. of Edges: ", data.num_edges)
    print(f'Average node degree: {data.num_edges / data.num_nodes:.2f}')
    print(f'Has isolated nodes: {data.has_isolated_nodes()}')
    print(f'Has self-loops: {data.has_self_loops()}')
    print(f'Is undirected: {data.is_undirected()}')

    # Create train and test dataset
    torch.manual_seed(12345)
    dataset = dataset.shuffle()

    train_dataset = dataset[:50]
    test_dataset = dataset[50:]
    print(f'Number of training graphs: {len(train_dataset)}')
    print(f'Number of test graphs:{len(test_dataset)}')

    '''graphs in graph classification datasets are usually small,
    a good idea is to batch the graphs before inputting
    them into a Graph Neural Network to guarantee full GPU utilization__
    _In pytorch Geometric adjacency matrices are stacked in a diagonal fashion
    (creating a giant graph that holds multiple isolated subgraphs), a
    nd node and target features are simply concatenated in the node dimension:
    '''
    train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)
    test_loader = DataLoader(test_dataset, batch_size=64, shuffle=False)

    for step, data in enumerate(train_loader):
        print(f'Step {step + 1}')
        print('==============')
        print(f'Number of graphs in the current batch: {data.num_graphs}')
        print(data)
        print()

    # Build the model
    model = GNN(hidden_channels=64)
    print(model)

    # set the optimizer
    optimizer = torch.optim.Adam(model.parameters(), lr=0.02)

    # set the loss function
    criterion = torch.nn.CrossEntropyLoss()

    # Train the model for 150 epochs
    for epoch in range(1, 100):
        Train(train_loader, loss_func=criterion)
        train_acc = Test(train_loader)
        test_acc = Test(test_loader)
        if epoch % 10 == 0:
            '''print(f'Epoch {epoch:>3} | Train Loss: {total_loss/len(train_loader):.3f} '
                  f'| Train Acc: {acc/len(train_loader)*100:>6.2f}% | Val Loss: '
                  f'{val_loss/len(train_loader):.2f} | Val Acc: '
                  f'{val_acc/len(train_loader)*100:.2f}%')
            '''
            print(f'Epoch: {epoch:03d}, Train Acc: {train_acc:.4f}, Test Acc: {test_acc:.4f}')

    # Explain the graph
    explainer = GNNExplainer(model, epochs=100, return_type='log_prob')
    data = dataset[0]
    node_feat_mask, edge_mask = explainer.explain_graph(data.x, data.edge_index)
    ax, G = explainer.visualize_subgraph(-1, data.edge_index, edge_mask, data.y)
    plt.show()


"""Remote Diagnostics and Configuration"""
import io
import struct
import logging

from knxmap import KNX_MESSAGE_TYPES, _LAYER_TYPES, KNX_STATUS_CODES
from .main import KnxMessage

LOGGER = logging.getLogger(__name__)

class KnxRemoteDiagnosticRequest(KnxMessage):
    def __init__(self, message=None, sockname=None):
        super(KnxRemoteDiagnosticRequest, self).__init__()
        if message:
            self.message = message
            self.unpack_knx_message(message)
        else:
            self.header['service_type'] = KNX_MESSAGE_TYPES.get('REMOTE_DIAGNOSTIC_REQUEST')
            try:
                self.source, self.port = sockname
                self.pack_knx_message()
            except TypeError:
                self.source = None
                self.port = None

    def _pack_knx_body(self):
        #self.body = self._pack_hpai()
        # selector
        import socket
        hpai = bytearray(struct.pack('!B', 8))  # structure_length
        hpai.extend(struct.pack('!B', 0x01))  # protocol code
        hpai.extend(socket.inet_aton(self.source))
        hpai.extend(struct.pack('!H', self.port))
        #hpai.extend(struct.pack('!B', 0x02)) # structure length
        #hpai.extend(struct.pack('!B', 0x01)) # programming mode selector
        hpai.extend(struct.pack('!B', 0x08)) # structure length
        hpai.extend(struct.pack('!B', 0x02)) # programming mode selector
        hpai.extend(struct.pack('!B', 0x00))
        hpai.extend(struct.pack('!B', 0x00))
        hpai.extend(struct.pack('!B', 0x54))
        hpai.extend(struct.pack('!B', 0xff))
        hpai.extend(struct.pack('!B', 0xa0))
        hpai.extend(struct.pack('!B', 0x52))
        return hpai
        #return self.body

    def _unpack_knx_body(self, message):
        try:
            message = io.BytesIO(message)
            self.body = self._unpack_hpai(message)
        except Exception as e:
            LOGGER.exception(e)

class KnxRemoteDiagnosticResponse(KnxMessage):
    def __init__(self, message=None):
        super(KnxRemoteDiagnosticResponse, self).__init__()
        if message:
            self.message = message
            self.unpack_knx_message(message)
        else:
            self.header['service_type'] = KNX_MESSAGE_TYPES.get('REMOTE_DIAGNOSTIC_RESPONSE')
            self.pack_knx_message()

    def _pack_knx_body(self):
        raise NotImplementedError

    def _unpack_knx_body(self, message):
        try:
            message = io.BytesIO(message)
            self.body = self._unpack_hpai(message)
            self.dib_dev_info = self._unpack_dib_dev_info(message)
            self.dib_supp_sv_families = self._unpack_dib_supp_sv_families(message)
        except Exception as e:
            LOGGER.exception(e)

class KnxRemoteBasicConfigurationRequest(KnxMessage):
    pass

class KnxRemoteResetRequest(KnxMessage):
    pass


import os
from pylab import *
mpl.rcParams['font.sans-serif'] = ['SimHei']  # 添加这条可以让图形显示中文

with open("acc_imp12.txt","r") as f:
    datas = f.readlines()
acc = []
for data in datas:
    data = data.strip('\n')
    data = data.split('\t')
    acc_data = float(data[1])
    acc.append(acc_data)

x= range(1,201)
plt.plot(x, acc, 'b.-')

# 显示标签，如果不加这句，即使在plot中加了label='一些数字'的参数，最终还是不会显示标签
plt.legend(loc="upper right")
plt.xlabel('epoch')
plt.ylabel('accuracy rate')

plt.show()


# see https://fastapi.tiangolo.com/advanced/response-cookies/

from fastapi import FastAPI, Response
import fastapi.responses
import asyncio

app = FastAPI()

@app.get("/response_parameter") # $ routeSetup="/response_parameter"
async def response_parameter(response: Response): # $ requestHandler
    response.set_cookie("key", "value") # $ CookieWrite CookieName="key" CookieValue="value"
    response.set_cookie(key="key", value="value") # $ CookieWrite CookieName="key" CookieValue="value"
    response.headers.append("Set-Cookie", "key2=value2") # $ CookieWrite CookieRawHeader="key2=value2"
    response.headers.append(key="Set-Cookie", value="key2=value2") # $ CookieWrite CookieRawHeader="key2=value2"
    response.headers["X-MyHeader"] = "header-value"
    response.status_code = 418
    return {"message": "response as parameter"} # $ HttpResponse mimetype=application/json responseBody=Dict

@app.get("/resp_parameter") # $ routeSetup="/resp_parameter"
async def resp_parameter(resp: Response): # $ requestHandler
    resp.status_code = 418
    return {"message": "resp as parameter"} # $ HttpResponse mimetype=application/json responseBody=Dict

@app.get("/response_parameter_no_type") # $ routeSetup="/response_parameter_no_type"
async def response_parameter_no_type(response): # $ requestHandler routedParameter=response
    # NOTE: This does in fact not work, since FastAPI relies on the type annotations,
    # and not on the name of the parameter
    response.status_code = 418
    return {"message": "response as parameter"} # $ HttpResponse mimetype=application/json responseBody=Dict

class MyXmlResponse(fastapi.responses.Response):
    media_type = "application/xml"

@app.get("/response_parameter_custom_type", response_class=MyXmlResponse) # $ routeSetup="/response_parameter_custom_type"
async def response_parameter_custom_type(response: MyXmlResponse): # $ requestHandler
    # NOTE: This is a contrived example of using a wrong annotation for the response
    # parameter. It will be passed a `fastapi.responses.Response` value when handling an
    # incoming request, so NOT a `MyXmlResponse` value. Cookies/Headers are still
    # propagated to the final response though.
    print(type(response))
    assert type(response) == fastapi.responses.Response
    response.set_cookie("key", "value") # $ CookieWrite CookieName="key" CookieValue="value"
    response.headers["Custom-Response-Type"] = "yes, but only after function has run"
    xml_data = "<foo>FOO</foo>"
    return xml_data # $ HttpResponse responseBody=xml_data mimetype=application/xml

# Direct response construction

# see https://fastapi.tiangolo.com/advanced/response-directly/
# see https://fastapi.tiangolo.com/advanced/custom-response/

@app.get("/direct_response") # $ routeSetup="/direct_response"
async def direct_response(): # $ requestHandler
    xml_data = "<foo>FOO</foo>"
    resp = fastapi.responses.Response(xml_data, 200, None, "application/xml") # $ HttpResponse mimetype=application/xml responseBody=xml_data
    resp = fastapi.responses.Response(content=xml_data, media_type="application/xml") # $ HttpResponse mimetype=application/xml responseBody=xml_data
    return resp # $ SPURIOUS: HttpResponse mimetype=application/json responseBody=resp

@app.get("/direct_response2", response_class=fastapi.responses.Response) # $ routeSetup="/direct_response2"
async def direct_response2(): # $ requestHandler
    xml_data = "<foo>FOO</foo>"
    return xml_data # $ HttpResponse responseBody=xml_data

@app.get("/my_xml_response") # $ routeSetup="/my_xml_response"
async def my_xml_response(): # $ requestHandler
    xml_data = "<foo>FOO</foo>"
    resp = MyXmlResponse(content=xml_data) # $ HttpResponse mimetype=application/xml responseBody=xml_data
    return resp # $ SPURIOUS: HttpResponse mimetype=application/json responseBody=resp

@app.get("/my_xml_response2", response_class=MyXmlResponse) # $ routeSetup="/my_xml_response2"
async def my_xml_response2(): # $ requestHandler
    xml_data = "<foo>FOO</foo>"
    return xml_data # $ HttpResponse responseBody=xml_data mimetype=application/xml

@app.get("/html_response") # $ routeSetup="/html_response"
async def html_response(): # $ requestHandler
    hello_world = "
Hello World!
"
    resp =  fastapi.responses.HTMLResponse(hello_world) # $ HttpResponse mimetype=text/html responseBody=hello_world
    return resp # $ SPURIOUS: HttpResponse mimetype=application/json responseBody=resp

@app.get("/html_response2", response_class=fastapi.responses.HTMLResponse) # $ routeSetup="/html_response2"
async def html_response2(): # $ requestHandler
    hello_world = "
Hello World!
"
    return hello_world # $ HttpResponse responseBody=hello_world mimetype=text/html

@app.get("/redirect") # $ routeSetup="/redirect"
async def redirect(): # $ requestHandler
    next = "https://www.example.com"
    resp = fastapi.responses.RedirectResponse(next) # $ HttpResponse HttpRedirectResponse redirectLocation=next
    return resp # $ SPURIOUS: HttpResponse mimetype=application/json responseBody=resp

@app.get("/redirect2", response_class=fastapi.responses.RedirectResponse) # $ routeSetup="/redirect2"
async def redirect2(): # $ requestHandler
    next = "https://www.example.com"
    return next # $ HttpResponse HttpRedirectResponse redirectLocation=next

@app.get("/streaming_response") # $ routeSetup="/streaming_response"
async def streaming_response(): # $ requestHandler
    # You can test this with curl:
    # curl --no-buffer http://127.0.0.1:8000/streaming_response
    async def content():
        yield b"Hello "
        await asyncio.sleep(0.5)
        yield b"World"
        await asyncio.sleep(0.5)
        yield b"!"

    resp = fastapi.responses.StreamingResponse(content()) # $ HttpResponse responseBody=content()
    return resp # $ SPURIOUS: HttpResponse mimetype=application/json responseBody=resp

# setting `response_class` to `StreamingResponse` does not seem to work
# so no such example here

@app.get("/file_response") # $ routeSetup="/file_response"
async def file_response(): # $ requestHandler
    # has internal dependency on PyPI package `aiofiles`
    # will guess MIME type from file extension

    # We don't really have any good QL modeling of passing a file-path, whose content
    # will be returned as part of the response... so will leave this as a TODO for now.
    resp = fastapi.responses.FileResponse(__file__) # $ HttpResponse getAPathArgument=__file__
    return resp # $ SPURIOUS: HttpResponse mimetype=application/json responseBody=resp

@app.get("/file_response2", response_class=fastapi.responses.FileResponse) # $ routeSetup="/file_response2"
async def file_response2(): # $ requestHandler
    return __file__ # $ HttpResponse getAPathArgument=__file__


from iota import Iota

api = Iota('https://nodes.devnet.iota.org:443', testnet = True)

# Define the tail transaction hash of the bundle whose messages you want to read
tail_hash = input('tail hash?')

print('Looking for bundle on the Tangle...')
bundle = api.get_bundles([tail_hash])

message = bundle['bundles'][0].tail_transaction.signature_message_fragment

print(message.decode(errors='ignore'))


import subprocess
import sys
import os
import z3
def main():
    tool_name = 'build/c2z3'
    filename = 'test/test.c'
    target = 'test/test.ll'
    cmd = ['clang', '-emit-llvm', '-S' , '-Xclang', '-disable-O0-optnone', filename, '-o', target]
    tmp_path = 'tmp/'
    is_success = subprocess.run(cmd)
    if not is_success:
        print('Fail to convert %s into LLVM IR' % filename)
        exit(0)
    cmd = [tool_name, target]
    try:
        print(subprocess.check_output(cmd).decode())
    except subprocess.TimeoutExpired:
        pass
    for smt_filename in [os.path.join(tmp_path, i) for i in os.listdir(tmp_path) if i.endswith('.smt2')]:
        formulas = z3.parse_smt2_file(smt_filename)
        print('*'*50)
        for f in formulas:
            print(z3.simplify(f))

if __name__ == '__main__':
    main()


from django.db import models
from items.models import Item
from players.models import Player

# Create your models here.

class Inventory(models.Model):
    STATUS_CHOICES = (
        ('Ativo', 'Ativo'),
        ('Inativo', 'Inativo'),
    )
    status = models.CharField('Status', max_length=20, choices=STATUS_CHOICES, null=True, blank=True, default='Ativo')
    player = models.ForeignKey(Player, on_delete=models.CASCADE)
    inventory_item = models.ManyToManyField(Item, through='InventoryItem', blank=True)

    class Meta:
        verbose_name = 'Inventario'
        verbose_name_plural = 'Inventarios'
        ordering =['id']

    def __str__(self):
        return "%s" % (self.status)

class InventoryItem(models.Model):
    quantity = models.IntegerField('Quantidade',null=True, blank=True,default=0)
    inventory = models.ForeignKey(Inventory, on_delete=models.CASCADE)
    item = models.ForeignKey(Item, on_delete=models.CASCADE)

    class Meta:
        verbose_name = 'Item do inventario'
        verbose_name_plural = 'Itens do inventario'
        ordering =['id']

    def __str__(self):
        return "%s" % (self.quantity)


# -*- coding: utf-8 -*-
"""
StreamsContainer
================
Contains classes associated with the DPF StreamsContainer.
"""
import warnings
import traceback

from ansys.dpf.core.server_types import BaseServer
from ansys.dpf.core import server as server_module
from ansys.dpf.gate import (
    streams_capi,
    data_processing_capi,
    data_processing_grpcapi,
)
from ansys.dpf.core import errors

class StreamsContainer:
    """Python wrapper for operator input or output of streams.

    Streams define open, ready-to-use, data sources.
    Once the files in the streams are opened, they stay opened and
    they keep some data in cache to make the next evaluations faster.
    To close the opened files, release the handles.

    Note
    ----
    Only available for an InProcess server configuration.

    Examples
    --------
    >>> from ansys.dpf import core as dpf
    >>> from ansys.dpf.core import examples
    >>> model = dpf.Model(examples.find_multishells_rst())
    >>> streams_provider = model.metadata.streams_provider
    >>> sc = streams_provider.outputs.streams_container()
    """

    def __init__(self, streams_container=None, server: BaseServer = None):
        # step 1: get server
        self._server = server_module.get_or_create_server(server)
        if self._server.has_client():
            txt = """
            StreamsContainer only available for server with InProcess communication protocol
            """
            raise errors.ServerTypeError(txt)

        # step2: if object exists, take the instance, else create it
        self._internal_obj = None
        if streams_container is not None:
            if isinstance(streams_container, StreamsContainer):
                self._server = streams_container._server
                core_api = self._server.get_api_for_type(
                    capi=data_processing_capi.DataProcessingCAPI,
                    grpcapi=data_processing_grpcapi.DataProcessingGRPCAPI,
                )
                core_api.init_data_processing_environment(self)
                self._internal_obj = core_api.data_processing_duplicate_object_reference(
                    streams_container
                )
            else:
                self._internal_obj = streams_container
        self.owned = False

    @property
    def _server(self):
        return self._server_instance

    @_server.setter
    def _server(self, value):
        self._server_instance = value
        # step 2: get api
        self._api = self._server.get_api_for_type(capi=streams_capi.StreamsCAPI, grpcapi=None)
        if not self._api:
            raise NotImplementedError("StreamsContainer unavailable for LegacyGrpc servers")
        # step3: init environment
        self._api.init_streams_environment(self)  # creates stub when gRPC

    def release_handles(self):
        """Release the streams."""
        self._api.streams_release_handles(self)

    def __del__(self):
        """Delete the entry."""
        try:
            # delete
            if not self.owned:
                self._deleter_func[0](self._deleter_func[1](self))
        except:  # pylint: disable=bare-except
            warnings.warn(traceback.format_exc())


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul  9 00:24:49 2018

@author: wei
"""

from log import logger
from tkinter import Tk, Frame, Label
from db._realtime import shell
from thermo.node import Node
import db._config as cfg
from datetime import datetime as dt

class App(Frame):
    def __init__(self, master=None):
        super().__init__(master=None)

        self.initUI()

    def initUI(self):
        self.master.title("ORC Realtime System")

        main = Frame(self.master)
        main.pack()
        footer = Frame(self.master)
        footer.pack()

        Label(footer, text='developer:HW Lu, laboratory:429, professor:TC Hung, agency:National Taipei Technology University').pack()

        self.frame_left = Frame(main)
        self.frame_left.pack(side="left")

        frame_right = Frame(main)
        frame_right.pack(side="right")

        self.frame_ts = Frame(frame_right)
        self.frame_ts.pack(side="top")

        self.frame_right = Frame(frame_right)
        self.frame_right.pack(side="bottom")

    def add_label(self):
        Label(self.frame_left, text='frame_left').pack()
        Label(self.frame_ts, text='frame_ts').pack()
        Label(self.frame_right, text='frame_right').pack()

def calc_nodes():
    ''' calc nodes '''
    for name, value in shell.items():
        if isinstance(value, Node):
            shell[name].pt()
    ''' calc WORK '''
    for name, node in cfg.FM.items():
        item0 = shell[f"{node[0]}"]
        item1 = shell[f"{node[1]}"]
        mDot = shell["mDot"]
        shell[f"{name}"] = (item1.h - item0.h) * mDot

    ''' calc efficiency '''
    shell["Eff"] = ((shell["Wout"] - shell["Win"]) / shell["Qin"]) * 100

    ''' other '''
    shell["count"] = shell["count"] + 1
    shell["time"] = dt.now().time()
    shell["ts"] = dt.now().timestamp()
    print(f"{shell['count']}----" * 5)

if __name__ == '__main__':

    logger.info('program starting!')

    import db
    import dev
    from GUIObj import Scan_button
    import widget
    import widget.simulation as sim

    if db.device["mode"] == "test":
        device = dev.TEST()
    elif db.device["mode"] == "V34972A":
        device = dev.V34972A()
    else:
        raise "ConfigError(device['mode']), please use manual/V34972A/DAQ970A"

    logger.info('init UI')

    window = Tk()
    app = App()
    # app.add_label()

    logger.info('add componement in layout')

    PnID = widget.PnID(app.frame_left)
    sim.MDot(app.frame_left)
    TnSD = widget.TnSD(app.frame_ts)
    file = widget.CsvFile()

    logger.info('add update func in scan')

    Scan_button(app.frame_right, device.scan, calc_nodes, file.save_data, PnID.update, TnSD.update)

    window.bind("<Escape>", lambda x: window.destroy())

    window.mainloop()

    logger.info('program finish.')


# Detects the encoding of a given file and changes the encoding to utf-8 without BOM
# Note that the program replaces the file given as the input with the one encoded with utf-8.
# If the input file is encoded with utf-8 without BOM, the program does nothing
#
# usage:
# python any2utf8.py file.txt
# -> If the encoding of file.txt is SHIFT_JIS, the program replaces the file with the one encoded with utf-8.

import sys
import codecs
import unicodedata

# Please run 'pip install chardet' if you haven't already.
import chardet

# def detect_encoding_test():
#     with codecs.open("sjis_testfile", mode="w", encoding='SHIFT_JIS') as testfile:
#         text = 'characters unique to sjis'
#         #print(text)
#         testfile.write(text)
#
#     enc = detect_encoding('sjis_testfile')
#     print(enc)
#     myassert(enc,"SHIFT_JIS")

def detect_encoding(file_pathname):
    with open(file_pathname, mode='rb') as file:
        read_bytes = file.read()
        det = chardet.detect(read_bytes)
        # print(det)
        return det['encoding']

def convert_encoding_and_replace_file(file_pathname,src_encoding,dest_encoding):
    src_string = ''
    with codecs.open(file_pathname, mode='r', encoding=src_encoding) as file:
        src_string = file.read()

    with codecs.open(file_pathname, mode='w', encoding=dest_encoding) as output_file:
        output_file.write(src_string)

def convert_to_utf8(pathname):

    enc = detect_encoding(pathname)

    print(enc)

    target_encoding = 'utf-8'

    if( enc == target_encoding ):
        print('The specified file is encoded with ' + target_encoding + '. Conversion is not necessary.')
        return

    convert_encoding_and_replace_file(pathname,enc,'utf-8')

def normalize_nfkc(utf8_file_pathname):

    text = ''
    with codecs.open(utf8_file_pathname, mode='r', encoding='utf-8') as file:
        text = file.read()
        text = unicodedata.normalize('NFKC',text)

    with codecs.open(utf8_file_pathname, mode='w', encoding='utf-8') as output_file:
        output_file.write(text)

def run():

    if( len(sys.argv) < 2 ):
        return # a file pathname needs to be specified.

    pathname = sys.argv[1]

    convert_to_utf8(pathname)

    if 3 <= len(sys.argv) and sys.argv[2] == '--nfkc':
        normalize_nfkc(pathname)

# detect_encoding_test()
run()


# Data Encoding Module
# Author: Elton Kjeld Schiott
# This class encodes the data bits for a QR code given an input string,
# version, and error correction level.
## @mainpage Mainpage
#
##
# @file Data.py
# @title Data
# @date 2/11/2016
# @brief This class encodes data bits for a QR code.
# @details This class encodes the data bits for a QR code given an input
# string, version, error correction level, and mode.\n
# State variables:\n
# String data - contains the binary string that reprsents the encoded
# input string.
# @code
#   data = Data.getDataBits(5,'H',BYTE, inputString)
# @endcode

# @uses Constant.py
from Constant import char_cap, required_bytes, mindex, lindex, num_list, alphanum_list, grouping_list, mode_indicator

## @brief Method to obtain data bits for a QR code.
#  @date 2/11/2016
#  @details Method accepts four parameters.
#  @param version Integer between 1 and 40 that specifies the size of
#  the QR code.
#  @param ecl Accepts one of four values: 'L', 'M', 'Q', 'H' that
#  specify the level of error correction to be encoded.
#  @param mode Accepts one of four values: NUMERIC, ALPHANUMERIC, BYTE,
#  KANJI that specify the acceptable characters and encoding mode for
#  the QR code.
#  @param inputString Accepts an input string to be encoded into data
#  bits for a QR code.
#  @return Encoded data bits.
#  Method accepts four parameters
#  version: QR code version
#  ecl: QR code error correction level
#  mode: QR code encoding mode
#  inputString: String to be encoded.
def getDataBits(version, ecl, inputString):

	modeEncoding = {
			'numeric': numericEncoding,
			'alphanumeric': alphanumericEncoding,
			'byte': byteEncoding,
			}

	version, mode = analyse(version, ecl, inputString)

	data = mode_indicator[mode]+getCharacterCount(version, mode, inputString)+modeEncoding[mode](inputString)

	# Add a Terminator
	requiredBits = 8 * required_bytes[version-1][lindex[ecl]]
	bits = requiredBits - len(data)
	data += '0000' if bits >= 4 else '0' * bits

    # Make the Length a Multiple of 8
	data += (8-(len(data)%8))*'0'

    # Add Pad Bytes if the String is Still too Short
	while len(data) < requiredBits:
		data += '1110110000010001' if requiredBits - len(data) >= 16 else '11101100'

	dataCode = [data[i:i+8] for i in range(len(data)) if i%8 == 0]
	dataCode = [int(i,2) for i in dataCode]

	groups = grouping_list[version-1][lindex[ecl]]
	dataCodewords = []
	index = 0
	for n in range(groups[0]):
		dataCodewords.append(dataCode[index:index+groups[1]])
		index += groups[1]
	for n in range(groups[2]):
		dataCodewords.append(dataCode[index:index+groups[3]])
		index += groups[3]

	return version, dataCodewords

## @brief Method to create a suitable binary string for given data.
#  @details Method accepts two parameters.
#  @param data Accepts an integer or string to be converted.
#  @param length Accepts an integer that specifies the length of string
#  to be generated.
#  @return a converted binary string of appropriate length.
def binString(data, length):
    pass

## @brief Method to determine the appropriate mode and version for a QR code.
#  @details Method accepts three parameters, and determines the appropriate version
#  given a desired version and error correction level. If the given
#  version is too small to hold the data, an appropriate one is selected.
#  @param version Integer between 1 and 40 that specifies the desired size of the QR code.
#  @param ecl Accepts one of four values: 'L', 'M', 'Q', 'H' that specify the
#  level of error correction to be encoded.
#  @param inputString Accepts an input string to be encoded into data bits for a
#  QR code.
#  @return Appropriate version
def analyse(version, ecl, inputString):
	if all(i in num_list for i in inputString):
		mode = 'numeric'
	elif all(i in alphanum_list for i in inputString):
		mode = 'alphanumeric'
	else:
		mode = 'byte'

	modeIndex = mindex[mode]
	length = len(inputString)
	for i in range(40):
		if char_cap[ecl][i][modeIndex] > length:
			version = i + 1 if i+1 > version else version
			break

	return version, mode

## @brief Method to encode the Input String in numeric mode
#  @details The input string entered is assumed to be of 'numeric' mode. Each
#  char in the input string is encoded.
#  @param inputString Accepts an input string to be encoded into data bits for a
#  QR code.
#  @return string representing encoded input string
def numericEncoding(inputString):
	strList = [inputString[i:i+3] for i in range(0,len(inputString),3)]
	data = ''
	for i in strList:
		requiredLength = 10
		if len(i) == 1:
			requiredLength = 4
		elif len(i) == 2:
			requiredLength = 7
		temp = bin(int(i))[2:]
		data += ('0'*(requiredLength - len(temp)) + temp)
	return data

## @brief Method to encode the Input String in alphanumeric mode
#  @details The input string entered is assumed to be of 'alphanumeric' mode. Each
#  char in the input string is encoded.
#  @param inputString Accepts an input string to be encoded into data bits for a
#  QR code.
#  @return string representing encoded input string
def alphanumericEncoding(inputString):
	strList = [alphanum_list.index(i) for i in str]
	data = ''
	for i in range(1, len(strList), 2):
		temp = bin(strList[i-1] * 45 + strList[i])[2:]
		temp = '0'*(11-len(temp)) + temp
		data += temp
	if i != len(strList) - 1:
		temp = bin(strList[-1])[2:]
		temp = '0'*(6-len(temp)) + temp
		data += temp

	return data

## @brief Method to encode the Input String as byte code
#  @details The URL or input string entered is assumed to be of 'byte' mode. Each
#  char in the input string is encoded into a byte code.
#  @param inputString Accepts an input string to be encoded into data bits for a
#  QR code.
#  @return byte code string representing input string/url
def byteEncoding(inputString):
	data = ''
	for i in inputString:
		temp = bin(ord(i.encode('iso-8859-1')))[2:]
		temp = '0'*(8-len(temp)) + temp
		data += temp
	return data

## @brief Method to get the character count of the QR code
#  @details Gets the character count string given a version, mode, and input string
#  @param inputString Accepts an input string to be encoded into data bits for a
#  QR code.
#  @param version Integer between 1 and 40 that specifies the desired size of the QR code.
#  @param mode Accepts one of four values: NUMERIC, ALPHANUMERIC, BYTE,
#  KANJI that specify the acceptable characters and encoding mode for
#  the QR code.
#  @return character count string
def getCharacterCount(version, mode, inputString):
	if 1 <= version <= 9:
		charCount = (10, 9, 8, 8)[mindex[mode]]
	elif 10 <= version <= 26:
		charCount = (12, 11, 16, 10)[mindex[mode]]
	else:
		charCount = (14, 13, 16, 12)[mindex[mode]]

	cci = bin(len(inputString))[2:]
	cci = '0' * (charCount - len(cci)) + cci
	return cci


from termcolor import colored, cprint
import argparse
import platform
import random
import sys
import os

def getWords(lenght, file) :
    with open(file, "r") as f :
        allWords = f.read().split("\n")

    correctWords = []

    for word in allWords :
        if len(word) == lenght :
            correctWords.append(word.lower().strip())

    return correctWords

def printGuessed(guessed, solution, guesses) :
    id = 0

    solution = solution.upper()

    for guess in guessed :
        id += 1
        print("%s. " % (str(id).zfill(len(str(guesses)))), end="") #Adding leading zeros to large numbers. (001, 002, 003)

        i = -1
        removed = 0
        solutionList = list(solution)

        for letter in guess : #Makes sure a word with a two of the same letter gets marked correctly.
            i += 1

            letter = letter.upper()

            if letter == solution[i] :
                solutionList.pop(i - removed)
                removed += 1

        i = -1

        for letter in guess :
            i += 1

            letter = letter.upper()

            if letter == solution[i] :
                textColor = "white"
                background = "on_green"
            elif letter in solutionList :
                textColor = "grey"
                background = "on_yellow"
                solutionList.pop(i - removed)
                removed += 1
            else :
                textColor = "white"
                background = "on_grey"

            cprint(letter.upper(), textColor, background, end="")
        print("")

def wordee(worldLenght, guesses, wordsFile="words.txt", cheater=False, forceSolution=None) :
    if not os.path.isfile(file) :
        print(f"{file} was not found.")
        input("Press [ENTER] to exit.")
        return False

    words = getWords(worldLenght, wordsFile)

    if len(words) < 1 :
        print(f"Oh no! There weren't any {worldLenght} letter words found in {file}.")
        input("Press [ENTER] to exit.")
        return False

    if not forceSolution :
        solution = random.choice(words)
        wordlistCheck = True
    else :
        solution = forceSolution.lower().strip()
        wordlistCheck = True

        if not solution in words :
            wordlistCheck = False

    print("Welcome to Wordee!")

    if cheater :
        print("=== SOLUTION: %s ===" % (solution))

    input("Press [ENTER] to start.")

    guessed = []
    text = ""

    guessID = 0
    over = False
    while True :
        if platform == "Windows" : #Clear the screen
            os.system("cls")
        else :
            os.system("clear")

        printGuessed(guessed, solution, guesses)
        print(text, end="")

        if over :
            break

        guess = input("Guess %d: " % (guessID+1)).strip()
        text = ""

        if not len(guess) == len(solution) :
            text = "Invalid lenght! You are looking for a %d letter word.\n" % (len(solution))
            continue

        if wordlistCheck and not guess.lower() in words :
            text = "Not found in wordlist.\n"
            continue

        guessed.append(guess)
        guessID += 1

        if guess.lower() == solution :
            text = "\nYou won! The solution was %s.\n" % (solution)
            over = True

        if guessID == guesses :
            text = "\nYou ran out of guesses. The solution was %s. Better luck next time!\n" % (solution)
            over = True

    input("Press [ENTER] to exit..")
    return True

if __name__ == "__main__" :
    parser = argparse.ArgumentParser()

    parser.add_argument("-g", "--guesses", help="Amount of allowed guesses")
    parser.add_argument("-l", "--lenght", help="Word lenght")
    parser.add_argument("-f", "--file", help="Wordlist file")
    #parser.add_argument("-c", "--cheater", help="Show the correct solution")
    parser.add_argument("-s", "--solution", help="Force a solution")
    args = parser.parse_args()

    guesses = args.guesses
    lenght = args.lenght
    file = args.file
    forceSolution = args.solution

    if not guesses :
        guesses = 6
    if not lenght :
        lenght = 5
    if not file :
        file = "words.txt"

    try :
        guesses = int(guesses)
        lenght = int(lenght)
    except ValueError :
        print("Invalid arguments.")
        sys.exit()

    try :
        wordee(lenght, guesses, wordsFile=file, cheater=False, forceSolution=forceSolution)
    except KeyboardInterrupt :
        sys.exit()


from __future__ import division
from ast2000solarsystem_27_v4 import AST2000SolarSystem
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.style as style
style.use('fivethirtyeight')
seed = 11466

star_system = AST2000SolarSystem(seed)
gravitational_constant = 4 * np.pi**2                                            # [AU**3 * yr**-2 * M_solar**-1]
planet_mass = star_system.mass                                                   # [Solar masses]
star_mass = star_system.star_mass                                                # [Solar masses]
star_radius = star_system.star_radius                                            # [Km]
planet_semimajor_axes = star_system.a                                            # [AU]
star_temperature = star_system.temperature

stefan_boltzmann_sigma = 5.670373e-8                                             # [W * m**-2 * K**-4]
astrounits_to_meters = 1.496e11

def calculate_irradiance(planet):
    star_luminosity = 4 * np.pi * (star_radius * 1000)**2 * stefan_boltzmann_sigma * star_temperature**4
    irradiance = star_luminosity / (4 * np.pi * (planet_semimajor_axes[planet] * astrounits_to_meters)**2)

    return irradiance

def calculate_solar_cell_area(irradiance, power_output=40, efficiency=0.12):
    """Lander needs 40W during daytime, panels have efficiency 12%"""
    area_needed = power_output / (irradiance * efficiency)

    return area_needed

def find_planet_temperature(planet):
    planet_temperature = ((star_radius**2 * star_temperature**4) / 4 *(planet_semimajor_axes[planet] * astrounits_to_meters)**2)**0.25

    return planet_temperature


import pytest

import pytz
import dateutil
import numpy as np

from datetime import datetime
from dateutil.tz import tzlocal

import pandas as pd
import pandas.util.testing as tm
from pandas import (DatetimeIndex, date_range, Series, NaT, Index, Timestamp,
                    Int64Index, Period)

class TestDatetimeIndex(object):

    def test_astype(self):
        # GH 13149, GH 13209
        idx = DatetimeIndex(['2016-05-16', 'NaT', NaT, np.NaN])

        result = idx.astype(object)
        expected = Index([Timestamp('2016-05-16')] + [NaT] * 3, dtype=object)
        tm.assert_index_equal(result, expected)

        result = idx.astype(int)
        expected = Int64Index([1463356800000000000] +
                              [-9223372036854775808] * 3, dtype=np.int64)
        tm.assert_index_equal(result, expected)

        rng = date_range('1/1/2000', periods=10)
        result = rng.astype('i8')
        tm.assert_index_equal(result, Index(rng.asi8))
        tm.assert_numpy_array_equal(result.values, rng.asi8)

    def test_astype_with_tz(self):

        # with tz
        rng = date_range('1/1/2000', periods=10, tz='US/Eastern')
        result = rng.astype('datetime64[ns]')
        expected = (date_range('1/1/2000', periods=10,
                               tz='US/Eastern')
                    .tz_convert('UTC').tz_localize(None))
        tm.assert_index_equal(result, expected)

        # BUG#10442 : testing astype(str) is correct for Series/DatetimeIndex
        result = pd.Series(pd.date_range('2012-01-01', periods=3)).astype(str)
        expected = pd.Series(
            ['2012-01-01', '2012-01-02', '2012-01-03'], dtype=object)
        tm.assert_series_equal(result, expected)

        result = Series(pd.date_range('2012-01-01', periods=3,
                                      tz='US/Eastern')).astype(str)
        expected = Series(['2012-01-01 00:00:00-05:00',
                           '2012-01-02 00:00:00-05:00',
                           '2012-01-03 00:00:00-05:00'],
                          dtype=object)
        tm.assert_series_equal(result, expected)

        # GH 18951: tz-aware to tz-aware
        idx = date_range('20170101', periods=4, tz='US/Pacific')
        result = idx.astype('datetime64[ns, US/Eastern]')
        expected = date_range('20170101 03:00:00', periods=4, tz='US/Eastern')
        tm.assert_index_equal(result, expected)

        # GH 18951: tz-naive to tz-aware
        idx = date_range('20170101', periods=4)
        result = idx.astype('datetime64[ns, US/Eastern]')
        expected = date_range('20170101', periods=4, tz='US/Eastern')
        tm.assert_index_equal(result, expected)

    def test_astype_str_compat(self):
        # GH 13149, GH 13209
        # verify that we are returning NaT as a string (and not unicode)

        idx = DatetimeIndex(['2016-05-16', 'NaT', NaT, np.NaN])
        result = idx.astype(str)
        expected = Index(['2016-05-16', 'NaT', 'NaT', 'NaT'], dtype=object)
        tm.assert_index_equal(result, expected)

    def test_astype_str(self):
        # test astype string - #10442
        result = date_range('2012-01-01', periods=4,
                            name='test_name').astype(str)
        expected = Index(['2012-01-01', '2012-01-02', '2012-01-03',
                          '2012-01-04'], name='test_name', dtype=object)
        tm.assert_index_equal(result, expected)

        # test astype string with tz and name
        result = date_range('2012-01-01', periods=3, name='test_name',
                            tz='US/Eastern').astype(str)
        expected = Index(['2012-01-01 00:00:00-05:00',
                          '2012-01-02 00:00:00-05:00',
                          '2012-01-03 00:00:00-05:00'],
                         name='test_name', dtype=object)
        tm.assert_index_equal(result, expected)

        # test astype string with freqH and name
        result = date_range('1/1/2011', periods=3, freq='H',
                            name='test_name').astype(str)
        expected = Index(['2011-01-01 00:00:00', '2011-01-01 01:00:00',
                          '2011-01-01 02:00:00'],
                         name='test_name', dtype=object)
        tm.assert_index_equal(result, expected)

        # test astype string with freqH and timezone
        result = date_range('3/6/2012 00:00', periods=2, freq='H',
                            tz='Europe/London', name='test_name').astype(str)
        expected = Index(['2012-03-06 00:00:00+00:00',
                          '2012-03-06 01:00:00+00:00'],
                         dtype=object, name='test_name')
        tm.assert_index_equal(result, expected)

    def test_astype_datetime64(self):
        # GH 13149, GH 13209
        idx = DatetimeIndex(['2016-05-16', 'NaT', NaT, np.NaN])

        result = idx.astype('datetime64[ns]')
        tm.assert_index_equal(result, idx)
        assert result is not idx

        result = idx.astype('datetime64[ns]', copy=False)
        tm.assert_index_equal(result, idx)
        assert result is idx

        idx_tz = DatetimeIndex(['2016-05-16', 'NaT', NaT, np.NaN], tz='EST')
        result = idx_tz.astype('datetime64[ns]')
        expected = DatetimeIndex(['2016-05-16 05:00:00', 'NaT', 'NaT', 'NaT'],
                                 dtype='datetime64[ns]')
        tm.assert_index_equal(result, expected)

    def test_astype_object(self):
        rng = date_range('1/1/2000', periods=20)

        casted = rng.astype('O')
        exp_values = list(rng)

        tm.assert_index_equal(casted, Index(exp_values, dtype=np.object_))
        assert casted.tolist() == exp_values

    @pytest.mark.parametrize('tz', [None, 'Asia/Tokyo'])
    def test_astype_object_tz(self, tz):
        idx = pd.date_range(start='2013-01-01', periods=4, freq='M',
                            name='idx', tz=tz)
        expected_list = [Timestamp('2013-01-31', tz=tz),
                         Timestamp('2013-02-28', tz=tz),
                         Timestamp('2013-03-31', tz=tz),
                         Timestamp('2013-04-30', tz=tz)]
        expected = pd.Index(expected_list, dtype=object, name='idx')
        result = idx.astype(object)
        tm.assert_index_equal(result, expected)
        assert idx.tolist() == expected_list

    def test_astype_object_with_nat(self):
        idx = DatetimeIndex([datetime(2013, 1, 1), datetime(2013, 1, 2),
                             pd.NaT, datetime(2013, 1, 4)], name='idx')
        expected_list = [Timestamp('2013-01-01'),
                         Timestamp('2013-01-02'), pd.NaT,
                         Timestamp('2013-01-04')]
        expected = pd.Index(expected_list, dtype=object, name='idx')
        result = idx.astype(object)
        tm.assert_index_equal(result, expected)
        assert idx.tolist() == expected_list

    @pytest.mark.parametrize('dtype', [
        float, 'timedelta64', 'timedelta64[ns]', 'datetime64',
        'datetime64[D]'])
    def test_astype_raises(self, dtype):
        # GH 13149, GH 13209
        idx = DatetimeIndex(['2016-05-16', 'NaT', NaT, np.NaN])
        msg = 'Cannot cast DatetimeIndex to dtype'
        with tm.assert_raises_regex(TypeError, msg):
            idx.astype(dtype)

    def test_index_convert_to_datetime_array(self):
        def _check_rng(rng):
            converted = rng.to_pydatetime()
            assert isinstance(converted, np.ndarray)
            for x, stamp in zip(converted, rng):
                assert isinstance(x, datetime)
                assert x == stamp.to_pydatetime()
                assert x.tzinfo == stamp.tzinfo

        rng = date_range('20090415', '20090519')
        rng_eastern = date_range('20090415', '20090519', tz='US/Eastern')
        rng_utc = date_range('20090415', '20090519', tz='utc')

        _check_rng(rng)
        _check_rng(rng_eastern)
        _check_rng(rng_utc)

    def test_index_convert_to_datetime_array_explicit_pytz(self):
        def _check_rng(rng):
            converted = rng.to_pydatetime()
            assert isinstance(converted, np.ndarray)
            for x, stamp in zip(converted, rng):
                assert isinstance(x, datetime)
                assert x == stamp.to_pydatetime()
                assert x.tzinfo == stamp.tzinfo

        rng = date_range('20090415', '20090519')
        rng_eastern = date_range('20090415', '20090519',
                                 tz=pytz.timezone('US/Eastern'))
        rng_utc = date_range('20090415', '20090519', tz=pytz.utc)

        _check_rng(rng)
        _check_rng(rng_eastern)
        _check_rng(rng_utc)

    def test_index_convert_to_datetime_array_dateutil(self):
        def _check_rng(rng):
            converted = rng.to_pydatetime()
            assert isinstance(converted, np.ndarray)
            for x, stamp in zip(converted, rng):
                assert isinstance(x, datetime)
                assert x == stamp.to_pydatetime()
                assert x.tzinfo == stamp.tzinfo

        rng = date_range('20090415', '20090519')
        rng_eastern = date_range('20090415', '20090519',
                                 tz='dateutil/US/Eastern')
        rng_utc = date_range('20090415', '20090519', tz=dateutil.tz.tzutc())

        _check_rng(rng)
        _check_rng(rng_eastern)
        _check_rng(rng_utc)

class TestToPeriod(object):

    def setup_method(self, method):
        data = [Timestamp('2007-01-01 10:11:12.123456Z'),
                Timestamp('2007-01-01 10:11:13.789123Z')]
        self.index = DatetimeIndex(data)

    def test_to_period_millisecond(self):
        index = self.index

        period = index.to_period(freq='L')
        assert 2 == len(period)
        assert period[0] == Period('2007-01-01 10:11:12.123Z', 'L')
        assert period[1] == Period('2007-01-01 10:11:13.789Z', 'L')

    def test_to_period_microsecond(self):
        index = self.index

        period = index.to_period(freq='U')
        assert 2 == len(period)
        assert period[0] == Period('2007-01-01 10:11:12.123456Z', 'U')
        assert period[1] == Period('2007-01-01 10:11:13.789123Z', 'U')

    def test_to_period_tz_pytz(self):
        from pytz import utc as UTC

        xp = date_range('1/1/2000', '4/1/2000').to_period()

        ts = date_range('1/1/2000', '4/1/2000', tz='US/Eastern')

        result = ts.to_period()[0]
        expected = ts[0].to_period()

        assert result == expected
        tm.assert_index_equal(ts.to_period(), xp)

        ts = date_range('1/1/2000', '4/1/2000', tz=UTC)

        result = ts.to_period()[0]
        expected = ts[0].to_period()

        assert result == expected
        tm.assert_index_equal(ts.to_period(), xp)

        ts = date_range('1/1/2000', '4/1/2000', tz=tzlocal())

        result = ts.to_period()[0]
        expected = ts[0].to_period()

        assert result == expected
        tm.assert_index_equal(ts.to_period(), xp)

    def test_to_period_tz_explicit_pytz(self):
        xp = date_range('1/1/2000', '4/1/2000').to_period()

        ts = date_range('1/1/2000', '4/1/2000', tz=pytz.timezone('US/Eastern'))

        result = ts.to_period()[0]
        expected = ts[0].to_period()

        assert result == expected
        tm.assert_index_equal(ts.to_period(), xp)

        ts = date_range('1/1/2000', '4/1/2000', tz=pytz.utc)

        result = ts.to_period()[0]
        expected = ts[0].to_period()

        assert result == expected
        tm.assert_index_equal(ts.to_period(), xp)

        ts = date_range('1/1/2000', '4/1/2000', tz=tzlocal())

        result = ts.to_period()[0]
        expected = ts[0].to_period()

        assert result == expected
        tm.assert_index_equal(ts.to_period(), xp)

    def test_to_period_tz_dateutil(self):
        xp = date_range('1/1/2000', '4/1/2000').to_period()

        ts = date_range('1/1/2000', '4/1/2000', tz='dateutil/US/Eastern')

        result = ts.to_period()[0]
        expected = ts[0].to_period()

        assert result == expected
        tm.assert_index_equal(ts.to_period(), xp)

        ts = date_range('1/1/2000', '4/1/2000', tz=dateutil.tz.tzutc())

        result = ts.to_period()[0]
        expected = ts[0].to_period()

        assert result == expected
        tm.assert_index_equal(ts.to_period(), xp)

        ts = date_range('1/1/2000', '4/1/2000', tz=tzlocal())

        result = ts.to_period()[0]
        expected = ts[0].to_period()

        assert result == expected
        tm.assert_index_equal(ts.to_period(), xp)

    def test_to_period_nofreq(self):
        idx = DatetimeIndex(['2000-01-01', '2000-01-02', '2000-01-04'])
        pytest.raises(ValueError, idx.to_period)

        idx = DatetimeIndex(['2000-01-01', '2000-01-02', '2000-01-03'],
                            freq='infer')
        assert idx.freqstr == 'D'
        expected = pd.PeriodIndex(['2000-01-01', '2000-01-02',
                                   '2000-01-03'], freq='D')
        tm.assert_index_equal(idx.to_period(), expected)

        # GH 7606
        idx = DatetimeIndex(['2000-01-01', '2000-01-02', '2000-01-03'])
        assert idx.freqstr is None
        tm.assert_index_equal(idx.to_period(), expected)


import cv2
import os
import numpy as np

codigo_turma=0 #Usaremos na verificação da pasta
#Reconhecimento baseado apenas o LBPH

lbph = cv2.face.LBPHFaceRecognizer_create(radius=1, neighbors=8, grid_x=12, grid_y=12,threshold=50) #1.7976931348623157e+100

def getFotoMatricula( pasta):  #O parametro turma se refere ao código da turma que é o mesmo que o nome da pasta
    lista_face = []
    lista_matricula = []

    caminhos = [os.path.join(pasta,foto ) for foto in os.listdir(pasta)]
    for f in os.listdir(pasta):
        caminhos.append(os.path.join(pasta, f))

    for caminhoFoto in caminhos:
        imagem_face = cv2.cvtColor(cv2.imread(caminhoFoto), cv2.COLOR_BGR2GRAY)
        matricula = int(caminhoFoto.split('.')[1])
        lista_face.append(imagem_face)
        lista_matricula.append(matricula)
    return np.array(lista_matricula), lista_face

#Obtendo o nome da turma a ser aprendida com o usuário
while(codigo_turma == 0):
    turma = input("Digite o nome da turma que deseja realizar o aprendizado: ")
    nome_da_turma_cinza = turma + 'cinza'      #Salvamos na pasta  turma concatenada com a palavra cinza
    if(os.path.isdir(nome_da_turma_cinza)):
        codigo_turma = 1
    else:
        print("O nome da turma informado deve ser o mesmo nome da pasta, onde se encontram as fotos a serem convertidas!\n")
        print("Por exemplo, digite turma1, caso as fotos convertidas estejam na pasta turma1cinza \n")
matriculas, faces = getFotoMatricula(nome_da_turma_cinza)

print("Imagens e matrículas da " + nome_da_turma_cinza + " carregadas com sucesso")
print("Aprendendo...")

lbph.train(faces, matriculas)
lbph.write('aprendiLBPH' + nome_da_turma_cinza + '.yml')

print("treinamento da turma " + turma + " concluído.")


import re
import pandas as pd
import numpy as np
import zipfile
import os
import sys

tables_columns_properties_file = ""
tables_references_file = ""
anonymization_types = ['None','Omit','Default value','Set Null','Random','RandomPseudonym','RandomPseudonymPerTable','RandomFromSet','RandomPseudonymFromSet']

delimiter = '\t' #delimiter is tab because comma caused confusion when things like "decimal(8,2)" appeared
extension = '.txt'

#input files can be forwarded as command line arguments in the following order: TABLE_PROPERTIES, TABLE_REFERENCES
if(len(sys.argv) == 2):
    tables_columns_properties_file = sys.argv[0]
    tables_references_file = sys.argv[1]

#if input files aren't forwarded as command line args, they should be read from the input folder
else: #set default paths
    tables_columns_properties_file = "input\\input_properties"+extension
    tables_references_file = "input\\input_references"+extension

#A function which reads and parses the 'references' file. The data is parsed as a dictionary where keys are table names and the values are objects of format {referencing_column: {referenced_table: ..., referenced_column: ...} }
def read_references_file():
    reference_vectors = []
    references_dict = {}
    with open(tables_references_file) as fp:
        headers=fp.readline().strip('\n').split(delimiter)
        line=fp.readline()
        while line:
            parts=line.strip('\n').split(delimiter)
            if len(parts) != len(headers):
                raise Exception('References file not configured properly')
            reference_vectors.append(parts)
            referencing_table = parts[0]
            referencing_column = parts[1]
            referenced_table = parts[2]
            referenced_column = parts[3]

            if referencing_table not in references_dict:
                references_dict[referencing_table]={}
            if referencing_column not in references_dict[referencing_table].keys():
                references_dict[referencing_table][referencing_column]={}
            references_dict[referencing_table][referencing_column]['referenced_table']=referenced_table
            references_dict[referencing_table][referencing_column]['referenced_column']=referenced_column
            line=fp.readline()
    return reference_vectors,references_dict

#A function for reading and parsing the file where table properties are stated. The properties are: table name, column name, data type, nullable, anonymization type, default value
def read_anonymization_file():
    TABLES = {}
    randomPseudonymDatatypes = {}
    randomPseudonymFromSetDatatypes = []
    randomPseudonymPerTable = {}
    with open(tables_columns_properties_file) as fp:
        headers = fp.readline().split(delimiter)
        line = fp.readline()
        table = {}
        while line:
            parts = line.rstrip('\n').split(delimiter)
            if len(parts) != len(headers):
                raise Exception(str(len(parts))+' inputs received for '+str(len(headers))+' headers!')
            tablename=parts[0]
            columnname=parts[1]
            datatype=parts[2].replace('"','')
            nullable=parts[3]
            anonymization = parts[4]

            #check if anonymization type valid
            if anonymization not in anonymization_types:
                raise Exception('An unknown anonymization type ['+anonymization+'] was encountered.')

            #see if table shift
            #if dctionary is not empty
            if bool(table) and table['tablename'] != tablename:
                TABLES[table['tablename']] = table
                table={}

            #if dctionary is empty
            if not bool(table):
                table['tablename']=tablename
                table['columns']={}
            table['columns'][columnname]={}
            table['columns'][columnname]['columnname']= columnname
            table['columns'][columnname]['datatype']= datatype
            table['columns'][columnname]['nullable']= nullable
            table['columns'][columnname]['anonymization']= anonymization
            table['columns'][columnname]['defaultvalue']= parts[5]

            if 'NULL' in parts[5] and 'NO' in nullable:
                raise Exception('The column '+columnname+' for which you tried to set Default value NULL is NOT NULLABLE')
            if anonymization not in anonymization_types:
                raise Exception('Encountered unknown anonymisation type ['+anonymization+']. Acceptable types are :'+str(anonymization_types))
            if anonymization == 'Set Null' and 'NO' in nullable:
                raise Exception('Anonymization type "Set null" cant be set for the column ['+columnname+'] because it is NOT NULL.')
            if anonymization == 'RandomPseudonym':
                if datatype not in randomPseudonymDatatypes.keys():
                    randomPseudonymDatatypes[datatype]=[]
                randomPseudonymDatatypes[datatype].append({'tablename':tablename,'columnname':columnname})
            if anonymization == 'RandomPseudonymPerTable':
                if datatype not in randomPseudonymPerTable.keys():
                    randomPseudonymPerTable[datatype]=[]
                randomPseudonymPerTable[datatype].append({'tablename':tablename,'columnname':columnname})
            if anonymization == 'RandomPseudonymFromSet':
                randomPseudonymFromSetDatatypes.append({'tablename':tablename,'columnname':columnname,'datatype':datatype})
            line = fp.readline()
    return (TABLES,randomPseudonymDatatypes,randomPseudonymPerTable,randomPseudonymFromSetDatatypes)

references,references_dict = read_references_file()

tables,randomPseudonymDatatypes_dict,randomPseudonymPerTable_dict,randomPseudonymFromSetDatatypes_list = read_anonymization_file()

from random_generators import *
generate_DDL_DML_statements(tables,references_dict,randomPseudonymDatatypes_dict,randomPseudonymPerTable_dict,randomPseudonymFromSetDatatypes_list)


"""vane_cli.py uni tests"""
import argparse
import os
import glob
from io import StringIO
from unittest.mock import call
import pytest
import vane
from vane import vane_cli

# Disable redefined-outer-name for using log fixture functions
# pylint: disable=redefined-outer-name

@pytest.fixture
def loginfo(mocker):
    """Fixture to mock logger calls from vane.vane_cli"""
    return mocker.patch("vane.vane_logging.logging.info")

@pytest.fixture
def logerr(mocker):
    """Fixture to mock logger calls from vane.vane_cli"""
    return mocker.patch("vane.vane_logging.logging.error")

@pytest.fixture
def logwarning(mocker):
    """Fixture to mock logger calls from vane.vane_cli"""
    return mocker.patch("vane.vane_logging.logging.warning")

def test_setup_vane(loginfo, mocker):
    """Validates functionality of setup_vane method"""

    # mocking these methods since they have been tested in tests_tools tests

    mocker_object = mocker.patch("vane.tests_tools.import_yaml")
    mocker_object.side_effect = ["Duts_file", "Test_parameters"]
    mocker.patch("vane.tests_tools.return_test_defs", return_value="Test definitions")
    mocker.patch("vane.tests_tools.return_show_cmds", return_value="show_commands")
    mocker.patch("vane.tests_tools.init_duts", return_value="Dut object")

    vane_cli.setup_vane()

    # assert the vane.configs got set correctly
    assert vane.config.test_duts == "Duts_file"
    assert vane.config.test_parameters == "Test_parameters"
    assert vane.config.test_defs == "Test definitions"
    assert vane.config.dut_objs == "Dut object"

    # assert logs to ensure the method executed without errors
    loginfo_calls = [
        call("Starting Test Suite setup"),
        call("Discovering show commands from definitions"),
    ]
    loginfo.assert_has_calls(loginfo_calls, any_order=False)

def test_run_tests(loginfo, mocker):
    """Validates functionality of run_tests method"""

    # mocking these methods since they have been tested in tests_client tests
    mocker_object = mocker.patch("vane.tests_client.TestsClient")
    mocker.patch("vane.vane_cli.setup_vane")

    vane_cli.run_tests("path/to/definitions/file", "path/to/duts/file")

    mocker_object.assert_called_once_with("path/to/definitions/file", "path/to/duts/file")

    # Assert that the generate_test_definitions, setup_test_runner,
    # and test_runner method was called on the
    # returned TestClient instance

    test_client_instance = mocker_object.return_value
    test_client_instance.generate_test_definitions.assert_called_once()
    test_client_instance.setup_test_runner.assert_called_once()
    test_client_instance.test_runner.assert_called_once()

    loginfo.assert_called_with("Using class TestsClient to create vane_tests_client object")

def test_write_results(loginfo, mocker):
    """Validates functionality of write_results method"""

    # mocking these methods since they have been tested in report_client tests
    mocker_object = mocker.patch("vane.report_client.ReportClient")

    vane_cli.write_results("path/to/definitions/file")

    mocker_object.assert_called_once_with("path/to/definitions/file")

    # Assert that the write_result_doc method was called on the
    # returned ReportClient instance

    report_client_instance = mocker_object.return_value
    report_client_instance.write_result_doc.assert_called_once()

    loginfo.assert_called_with("Using class ReportClient to create vane_report_client object")

def test_write_steps():
    """Validates the functionality of the script which writes .md and .json with test steps
    for test files. REQUIRES there to be a tests/unittests/fixtures/test_steps/test_steps.py
    existing in this folder for test to pass"""

    assert not os.path.exists("tests/unittests/fixtures/test_steps/test_steps.md")
    assert not os.path.exists("tests/unittests/fixtures/test_steps/test_steps.json")

    vane_cli.write_test_steps(["tests/unittests/fixtures/test_steps"])
    expected_output = [
        "#  Testcase for verification of syslog logging server and\n",
        "            source-interface information\n",
        "\n",
        "1.  Running show logging command on dut and collecting the text output\n",
        "2.  Checking logging source interface and Logging to string in output\n",
        "3.  Collecting logging interface and IP address from command output\n",
        "4.  Collecting information of syslog logging port and vrf details from command\n",
        "            output\n",
        "5.  Comparing source-interface, port and vrf details from actual output\n",
        "        with the expected output details\n",
        "\n",
        "#  Testcase for veification of syslog events on configured server\n",
        "\n",
        "1.  Creating Testops class object and initializing the variable\n",
        "2.  Running Tcpdump on syslog server and entering in config mode\n",
        "            and existing to verify logging event are captured.\n",
        "3.  Comparing the actual output and expected output. Generating docx report\n",
    ]

    assert os.path.exists("tests/unittests/fixtures/test_steps/test_steps.md")
    assert os.path.exists("tests/unittests/fixtures/test_steps/test_steps.json")

    with open(
        "tests/unittests/fixtures/test_steps/test_steps.md", "r", encoding="utf-8"
    ) as file_pointer:
        content = file_pointer.readlines()
        # trimming out the date and time details from the md file
        # as they will vary per test run
        final_content = content[5:]
        assert final_content == expected_output

    os.remove("tests/unittests/fixtures/test_steps/test_steps.md")
    os.remove("tests/unittests/fixtures/test_steps/test_steps.json")

def test_show_markers(mocker):
    """Validates the functionality of show_markers method"""

    # mocking pytest.main's call to get mockers and setting our set of values
    mocker.patch("pytest.main")

    mock_stdout = mocker.Mock(spec=StringIO)
    value = (
        "@pytest.mark.filesystem: EOS File System Test Suite\n\n"
        "@pytest.mark.daemons: EOS daemons Test Suite\n\n"
        "@pytest.mark.extensions: EOS extensions Test Suite\n\n"
        "@pytest.mark.users: EOS users Test Suite\n\n"
        "@pytest.mark.tacacs: TACACS Test Suite"
    )
    mock_stdout.getvalue.return_value = value

    # Patch the 'StringIO' class to return the mock object
    mocker.patch("vane.vane_cli.StringIO", return_value=mock_stdout)

    expected_output = [
        {"marker": "filesystem", "description": "EOS File System Test Suite"},
        {"marker": "daemons", "description": "EOS daemons Test Suite"},
        {"marker": "extensions", "description": "EOS extensions Test Suite"},
        {"marker": "users", "description": "EOS users Test Suite"},
        {"marker": "tacacs", "description": "TACACS Test Suite"},
    ]
    actual_output = vane_cli.show_markers()
    assert actual_output == expected_output

def test_create_duts_from_topo():
    """Validates functionality of create_duts_from_topo method.
    REQUIRES there to be a tests/unittests/fixtures/test_topology.yaml
    in this folder for test to pass"""

    topology_file = "tests/unittests/fixtures/test_topology.yaml"
    vane_cli.create_duts_from_topo(topology_file)
    # validates the creation of the duts file, its content is tested in the test
    # written for test_tools.generate_duts_file
    assert os.path.isfile("tests/unittests/fixtures/test_topology.yaml_duts.yaml")
    os.remove("tests/unittests/fixtures/test_topology.yaml_duts.yaml")

def test_download_test_results(loginfo):
    """Validates if a zip archive got created and stored in the TEST RESULTS
    ARCHIVE folder"""

    dir_path = "reports/TEST RESULTS ARCHIVES"
    source_path = "reports/TEST RESULTS"
    if os.path.isdir(dir_path) and os.path.isdir(source_path):
        length = len(list(os.listdir(dir_path)))
        vane_cli.download_test_results()
        new_length = len(os.listdir(dir_path))

        # assert if a zip got created
        assert new_length == (length + 1)

        # delete the most recent zip that got created for the test
        list_of_files = glob.glob(dir_path + "/*")
        latest_file = max(list_of_files, key=os.path.getctime)
        os.remove(latest_file)

        loginfo.assert_called_with("Downloading a zip file of the TEST RESULTS folder")

def test_main_definitions_and_duts(loginfo, logwarning, mocker):
    """Tests the --definitions-file and --duts-file flag"""

    mocker.patch("vane.vane_cli.run_tests")
    mocker.patch("vane.vane_cli.write_results")
    mocker.patch("vane.vane_cli.download_test_results")

    # mocking parse cli to test --definitions-file and --duts-file flag
    mocker.patch(
        "vane.vane_cli.parse_cli",
        return_value=argparse.Namespace(
            definitions_file="definitions_sample.yaml",
            duts_file="duts_sample.yaml",
            generate_duts_file=None,
            generate_duts_from_topo=None,
            generate_test_steps=None,
            markers=False,
            nrfu=False,
        ),
    )
    vane_cli.main()

    assert vane.config.DEFINITIONS_FILE == "definitions_sample.yaml"
    assert vane.config.DUTS_FILE == "duts_sample.yaml"

    # assert info logs to ensure all the above methods executed without errors
    loginfo_calls = [
        call("Reading in input from command-line"),
        call("\n\n!VANE has completed without errors!\n\n"),
    ]
    loginfo.assert_has_calls(loginfo_calls, any_order=False)

    # assert warning logs to ensure all the above methods executed without errors
    logwarning_calls = [
        call("Changing Definitions file name to definitions_sample.yaml"),
        call("Changing DUTS file name to duts_sample.yaml"),
    ]
    logwarning.assert_has_calls(logwarning_calls, any_order=False)

def test_main_create_duts_file(loginfo, mocker):
    """Tests the --generate-duts-file flag"""

    mocker.patch("vane.tests_tools.create_duts_file")

    # mocking parse cli to test --generate-duts-file
    mocker.patch(
        "vane.vane_cli.parse_cli",
        return_value=argparse.Namespace(
            definitions_file="definitions_sample.yaml",
            duts_file="duts_sample.yaml",
            generate_duts_file=["topology.yaml", "inventory.yaml", "duts_name.yaml"],
            generate_duts_from_topo=None,
            generate_test_steps=None,
            markers=False,
            nrfu=False,
        ),
    )
    vane_cli.main()

    # assert info logs to ensure all the above methods executed without errors
    loginfo_calls = [
        call("Reading in input from command-line"),
        call(
            "Generating DUTS File from topology: topology.yaml and "
            "inventory: inventory.yaml file.\n"
        ),
    ]
    loginfo.assert_has_calls(loginfo_calls, any_order=False)

def test_main_generate_duts_from_topo(loginfo, logwarning, mocker):
    """Tests the --generate-duts-from-topo flag"""

    mocker.patch("vane.vane_cli.run_tests")
    mocker.patch("vane.vane_cli.write_results")
    mocker.patch("vane.vane_cli.download_test_results")
    mocker.patch("vane.vane_cli.create_duts_from_topo")

    # mocking parse cli to test --generate-duts-from-topo
    mocker.patch(
        "vane.vane_cli.parse_cli",
        return_value=argparse.Namespace(
            definitions_file="definitions_sample.yaml",
            duts_file="duts_sample.yaml",
            generate_duts_file=None,
            generate_duts_from_topo=["topology.yaml"],
            generate_test_steps=None,
            markers=False,
            nrfu=False,
        ),
    )
    vane_cli.main()

    # assert info logs to ensure all the above methods executed without errors
    loginfo_calls = [
        call("Reading in input from command-line"),
        call("Generating DUTS File from topology: topology.yaml file.\n"),
        call("\n\n!VANE has completed without errors!\n\n"),
    ]
    loginfo.assert_has_calls(loginfo_calls, any_order=False)

    # assert warning logs to ensure all the above methods executed without errors
    logwarning_calls = [
        call("Changing Definitions file name to definitions_sample.yaml"),
        call("Changing DUTS file name to duts_sample.yaml"),
    ]
    logwarning.assert_has_calls(logwarning_calls, any_order=False)

def test_main_write_test_steps(loginfo, mocker):
    """Tests the --generate-test-steps flag"""

    mocker.patch("vane.vane_cli.run_tests")
    mocker.patch("vane.vane_cli.write_results")
    mocker.patch("vane.vane_cli.download_test_results")
    mocker.patch("vane.vane_cli.write_test_steps")

    # mocking parse cli to test --generate-test-steps
    mocker.patch(
        "vane.vane_cli.parse_cli",
        return_value=argparse.Namespace(
            definitions_file="definitions_sample.yaml",
            duts_file="duts_sample.yaml",
            generate_duts_file=None,
            generate_duts_from_topo=None,
            generate_test_steps="test_directory",
            markers=False,
        ),
    )
    vane_cli.main()

    # assert info logs to ensure all the above methods executed without errors
    loginfo_calls = [
        call("Reading in input from command-line"),
        call("Generating test steps for test cases within test_directory test directory\n"),
    ]
    loginfo.assert_has_calls(loginfo_calls, any_order=False)


from keras.models import  load_model,model_from_json
import numpy as np
import cv2

#lallalalalalal
json_file = open('./model.json')
load_model_json = json_file.read()
json_file.close()
model = model_from_json(load_model_json)

model.load_weights('./model_weights.h5')

face_img = cv2.imread('./wo3.jpg',1)

'''
face_img = face_img.reshape(1,48,48,1)
result = model.predict_proba(face_img)
print(result)
'''

fac_img_gray = cv2.cvtColor(face_img,cv2.COLOR_BGR2GRAY)

cascPath ='./haarcascade_frontalface_alt.xml'
cascade = cv2.CascadeClassifier(cascPath)
facelands = cascade.detectMultiScale(fac_img_gray,
                                     scaleFactor=1.1,
                                     minNeighbors=1,
                                     minSize=(30,30))
print(facelands)

if(len(facelands)>0):
    for faceland in facelands:
        x,y,w,h = faceland
        images = []

        image = cv2.resize(fac_img_gray[y:y+h,x:x+w],(48,48))
        print(np.max(image))
       #    image = image/255.0
        cv2.imshow('fac',image)
        cv2.waitKey(0)
        image = image.reshape(1,48,48,1)

        result = np.array([0.0]*7)

        pre_lists = model.predict_proba(image,batch_size=1,verbose=1)
        #result += np.array([pre for pre_list in pre_lists for pre in pre_list])
        print(pre_lists)


from modules.Trajectory import Trajectory
import modules.modern_robotics as mr

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()
ax = fig.add_subplot(111, projection="3d")
ax.set_xlabel("X")
ax.set_ylabel("Y")
ax.set_zlabel("Z")
ax.axes.set_xlim3d(left=-2, right=2)
ax.axes.set_ylim3d(bottom=-2, top=2)
ax.axes.set_zlim3d(bottom=-2, top=2)

traj = Trajectory(0,[1.5,0.5,0])
traj.append(0.1, [1,0.5019, 0.1 ])
traj.append(0.2, [0.5,0.30706, 0.2 ])

possible, intersection_point, time_until_intersection = traj.checkSphereIntersection([0,0.180212,0], 0.4087037)
if possible:
    print(f"point: {intersection_point} time: {time_until_intersection}")
    intersection_transf = mr.RpToTrans(np.identity(3), intersection_point)
    ax.scatter(1.5, 0.5, 0)
    ax.scatter(0,0.180212,0)
    ax.scatter(intersection_point[0], intersection_point[1], intersection_point[2])
    u,v = np.mgrid[0:2*np.pi:40j, 0:np.pi:20j]
    x = np.cos(u)*np.sin(v)*0.4087037
    y = np.sin(u)*np.sin(v)*0.4087037 + 0.180212
    z = np.cos(v)*0.4087037
    ax.plot_wireframe(x, y, z, color="y")
    t = np.arange(0,2,0.01)
    x_traj = traj.betas["x"][0] + traj.betas["x"][1]*t + traj.betas["x"][2]*(t**2)
    y_traj = traj.betas["y"][0] + traj.betas["y"][1]*t + traj.betas["y"][2]*(t**2)
    z_traj = traj.betas["z"][0] + traj.betas["z"][1]*t + traj.betas["z"][2]*(t**2)
    ax.plot3D(x_traj, y_traj, z_traj, color="r")
    plt.show()

test_transf = np.array([[1,0,0,0],\
                        [0,1,0,0.5],\
                        [0,0,1,1],\
                        [0,0,0,1]])

test_point = np.array([0,0.1,0.3,1])

rot_camera_to_90 = mr.RollPitchYawToRot(0,0,np.pi/4)
transf_camera_to_90 = mr.RpToTrans(rot_camera_to_90, [0,0,0])

transf_90_to_base = np.array([[0, 0,1, 0.07274],\
                                  [0,-1,0, 0.06474],\
                                  [1, 0,0, -0.0175],\
                                  [0, 0,0,       1]])

transf_camera_to_base = transf_90_to_base @ transf_camera_to_90

print(transf_90_to_base @ (transf_camera_to_90 @ test_point))

print(transf_camera_to_base @ test_point)


import email
from email.mime import image
import json
from bs4 import BeautifulSoup
import requests
import time
from dhooks import Webhook,File,Embed
import datetime as rawr

def login(user,password):
    FL=requests.session()

    Payload={'name': user,
            'pass' : password,
            'form_build_id': 'form-2DtEyRuGlZMGewjq5ykhTK6-09NiId72r88x62wDEqM',
            'form_id': 'user_login_form',
            'op': 'sign in'}

    loginPost=FL.post('https://www.footlocker.com.kw/en/user/login',data=Payload)
    loginSoup=BeautifulSoup(loginPost.text,'lxml')
    usernum=str(loginSoup.find_all('a')[3]).split('/')[7].split('"')[0]

    UserPage=FL.get(f'https://www.footlocker.com.kw/en/user/{usernum}')
    userSoup=BeautifulSoup(UserPage.text,'lxml')
    token=str(userSoup.find('script',type="application/json")).split('Token":')[1].split('"')[1]
    print(f'TOKEN:[{token}]')

    FL.headers.update({
        'authorization':f'Bearer {token}',
        'content-type': 'application/json',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36',
        'accept': 'application/json, text/plain, */*',

    })

    # with open ('./log', 'w', encoding='utf-8') as f:
    #         f.write(loginPost.text)
    if "My Account" in loginPost.text:
            print (f'Login Success[{user}]')

    return FL

class footLockerKW:
    def __init__(self,url,taskNO,session,email,discordurl):
        self.session=session
        self.url=url
        self.taskNO=taskNO
        self.email=email
        self.hook=discordurl
        self.sku=""
        self.qouteid=""
        self.name=""
        self.imageurl=""
        self.checkout=""

    def send(self):
            embed = {
                "avatar_url": "https://seeklogo.com/images/F/Foot_Locker-logo-5615BC5594-seeklogo.com.png",
                'embeds': [{
                    "title": f"{self.email}",
                    'color':'16734349',
                    # "image": {
                    # "url": self.imageurl
                    # },
                    "fields": [
                    {"name": f"{self.name} added to cart", "value": f'SKU: {self.sku}', "inline": False},

                    ],
                    'timestamp': str(rawr.datetime.utcfromtimestamp(time.time())),
                    'footer': {
                        "text": 'added',
                        "icon_url": 'https://seeklogo.com/images/F/Foot_Locker-logo-5615BC5594-seeklogo.com.png',
                    },
                }]
            }
            r = requests.post(self.hook, json=embed)

    def log(self, status):
        print(f"<{self.email}>[Task:{self.taskNO}] {status}")

    def monitor(self):
        ProductPage=self.session.get(self.url).text

        while "Page not found" in ProductPage:
            ProductPage=self.session.get(self.url).text
            self.log("Product not available")
            time.sleep(5)

        if self.atc()=="200":
            self.send()
            self.log("Item succesfully added to cart")
            print(self.session.get("https://www.footlocker.com.kw/en/checkout").url)

    def atc(self):

        while self.sku=="":
            try:
                ProductPage=self.session.get(self.url).text
                ProductPageSoup = BeautifulSoup(ProductPage , 'lxml')
                self.sku = ProductPageSoup.find(id="pdp-layout")['data-sku']
                self.name =str(ProductPageSoup.find_all('script', type="application/ld+json")[1]).split(',')[5].split(":")[1]
                self.imageurl=str(ProductPageSoup.find_all('script', type="application/ld+json")[1]).split(',')[6].split('"image": ')[1]

            except:
                pass
        while self.qouteid=="":
            try:
                cartPage=self.session.get('https://www.footlocker.com.kw/rest/kwt_en/V1/carts/mine/getCart')
                cartSoup=BeautifulSoup(cartPage.text,'lxml')
                self.qouteid=str(cartSoup.find('p')).split('"id"')[1].split(':')[1].split(',')[0]
            except:
                pass

        self.log('QuoteID:[{self.qouteid}]')
        self.log(f'SKU: [{self.sku}]')
        #print(FL.headers)

        with open ('./log', 'w', encoding='utf-8') as f:
            f.write(ProductPage)

        Payload={
            "cartItem":{
                "sku":self.sku,"qty":"1","product_option":{
                    "extension_attributes":{
                        "configurable_item_options":[
                            {
                                "option_id":"625","option_value":1663
                                }
                                ]
                                }
                                },"quote_id":self.qouteid
                                }
                                }

        productPost=self.session.post('https://www.footlocker.com.kw/rest/kwt_en/V1/carts/mine/items', json=Payload,headers=self.session.headers)

        if str(productPost.status_code)!="200":
            option_values=[1624,1630,1666,1669,1675]

            for x in range(len(option_values)):
                Payload={
            "cartItem":{
                "sku":self.sku,"qty":"1","product_option":{
                    "extension_attributes":{
                        "configurable_item_options":[
                            {
                                "option_id":"625","option_value":option_values[x]
                                }
                                ]
                                }
                                },"quote_id":self.qouteid
                                }
                                }

                if str(productPost.status_code)!="200":
                    self.log('Checking another size')
                    productPost=self.session.post('https://www.footlocker.com.kw/rest/kwt_en/V1/carts/mine/items', json=Payload,headers=self.session.headers)
                    time.sleep(5)
                else:
                    break

        return str(productPost.status_code)

#l=login('spam.hussein2@gmail.com','Man@kaka52')
#footLockerKW('https://www.footlocker.com.kw/en/buy-jordan-retro-4-mens-shoes-white-black.html','x',login('husseinalanjawi@gmail.com','Man@kaka52')).monitor()
#footLockerKW('https://www.footlocker.com.kw/en/buy-jordan-retro-4-mens-shoes-white-black.html','x',l,"husseinalanjawi@gmail.com","https://discord.com/api/webhooks/989341736843214858/8BJJOhaUF4DDkA-B3C4pnEoshtI5Nn02xcz-w3c60esf_zHZCiAQioH7vlvY8R1MqmPS").monitor()
#footLockerKW('https://www.footlocker.com.kw/en/buy-air-jordan-1-retro-high-og-mens-shoes-white-red.html','x',l).monitor()


# -*- coding: latin-1 -*-
import math
import numpy as np
#import pylab as plote
TABELA1 = open ('configura.txt', 'w') #Tabela 1 contendo colunas: Elemento qui, posições e indice
TABELA2 = open ('proprieda.txt', 'w') #Tabela 2 contendo colunas: energia potêncial, temperatura e energia cinética
# retornar tabela 1 para .xyz e tabela 2 para .dat
TABELA2.writelines(['#ENER. POTENCIAL(eV)\t' , 'ENER. CINÉTICA(eV)\t' , 'TEMPERATURA(K)\n'])

def forcas_energia_pot(r0,aresta,corte,num):
    E = np.float(0.997e0)                       # E da equacao de Lennard-Jones em Kj/mol
    s = np.float(3.4e0)                         # sigma da equação de Lennard-Jones
    U = np.float(0.0e0)                         #energia potencial
    F = np.zeros((num,3),float)                 #???
    unitario = np.zeros((3),float)
    for i in range(num-1):
        for j in range (i+1,num):
            rx = r0[j][0] - r0[i][0]                  #Calcula a norma
            if np.abs(rx) > (aresta/2.0e0):
               rx = np.abs(rx) - aresta
            ry = r0[j][1] - r0[i][1]
            if np.abs(ry) > (aresta/2.0e0):
               ry = np.abs(ry) - aresta
            rz = r0[j][2] - r0[i][2]
            if np.abs(rz) > (aresta/2.0e0):
               rz = np.abs(rz) - aresta
            r = math.sqrt(rx*rx + ry*ry + rz*rz) # distancia entre 2 atomos, dada em A[Angtrom] = e-10 m
            unitario[0] = rx / r
            unitario[1] = ry / r
            unitario[2] = rz / r
            if r <= corte:
               f1 = s / r                                                                             # 3.4/[A ou e-10m]
               f2 = math.pow(f1,12) - math.pow(f1,6)                                                  #Lennard-Jones
               f3 = np.float(48.0e0) * (E / s) * (math.pow(f1,13) - np.float(0.5e0) * math.pow(f1,7)) #Derivada da equação da energia Potencial
               U = U + np.float(4.0e0) * E * f2 * 1.04e-2                                             #Energia Potencial total do processo,e a soma de todas as energias potenciais (em eV)
               F[i] = F[i] + f3 * unitario * 1.0e-10 / 6.022                                          #Calculos de forças
               F[j] = F[j] - f3 * unitario * 1.0e-10 / 6.022

    return F, U

def integracao_das_equacoes_de_movimento(F,r0,v0,massa,dt,mdt2):
    v = np.zeros((num,3),float)
    r = np.zeros((num,3),float)

    for j in range(num):
        r[j] = r0[j] + (v0[j] * dt + F[j] * mdt2 / massa) * np.float(1.0e10)
        v[j] = v0[j] + F[j] * dt / massa

    return r, v

def posicoes(num,aresta_cubo):
    l = aresta_cubo / math.pow(num,(1.0/3.0))
    nterco = np.int(math.pow(num,(1.0/3.0)))
    if num != np.int(math.pow(nterco,3)):
       nterco = np.int(nterco) + np.int(1)
    r0 = np.zeros((num,3),dtype=float)
    npart = 0
    for n in range(nterco):
        for m in range(nterco):
            for w in range(nterco):
                r0[npart][0] = np.float(n) * l
                r0[npart][1] = np.float(m) * l
                r0[npart][2] = np.float(w) * l
                npart = npart + 1
    return r0

def centro_de_massa_em_repolso(v, num , massa):
    pcm = np.zeros((3),float) #momento linear do centro de massa

    for j in range(num):
        pcm = pcm + v[j] * massa

    vcm = pcm / (num * massa)

    for j in range(num):
        v[j] = v[j] - vcm

    v0 = v

    return v0

def distribuicao_aleatoria(massa,num,K):
    #Rb = np.float(1.38064852e-23)                                    #constante de Boltzmann = 1,38064852 Ã— 10-23 m2 kg s-2 K-1
    V0 = math.sqrt(2 * K / (num * massa))                            #Calcula a velocidade inicial das molÃ©culas
    v0 = np.random.random((num,3)) - 0.5e0
    #normaliza vetores
    for i in range(num):
        modulo = np.sqrt(v0[i][0]*v0[i][0] + v0[i][1]*v0[i][1] + v0[i][2]*v0[i][2])
        if modulo != 0.0e0:
           v0[i] = v0[i] / modulo
    v0 = v0 * V0
    return v0

def recalcular_temperatura(v0,num,massa):
    K = np.float(0.0e0)
    Rb = np.float(1.38064852e-23)                                                            #constante de Boltzmann = 1,38064852x10-23 (m2 kg s-2 K-1)

    for i in range(num):
        V2 = math.sqrt (v0[i][0] * v0[i][0] + v0[i][1] * v0[i][1] + v0[i][2] * v0[i][2] )    #**velocidade em modulo de cada átomo
        K = K + 1.0e0/2.0e0 * massa * V2                                                     #energia cinética de cada partícula
    T = 2 * K /(3 * num * Rb)                                                                #recalcula a temperatura
    return T, K

def reescala_veloci(v0,Talvo,T):
    v0 = v0 * np.sqrt(Talvo/T)
    return v0

def correcao_posicao_particulas(num, r0, aresta_cubo):
    for j in range (num):
        if r0[j][0] >= aresta_cubo:
            r0[j][0] = r0[j][0] - aresta_cubo
        else:
            if r0[j][0] < 0.0e0:
               r0[j][0] = r0[j][0] + aresta_cubo

        if r0[j][1] >= aresta_cubo:
            r0[j][1] = r0[j][1] - aresta_cubo
        else:
            if r0[j][1] < 0.0e0:
               r0[j][1] = r0[j][1] + aresta_cubo

        if r0[j][2] >= aresta_cubo:
            r0[j][2] = r0[j][2] - aresta_cubo
        else:
            if r0[j][2] < 0.0e0:
               r0[j][2] = r0[j][2] + aresta_cubo
    return r0

print("PROGRAMA DE DINÃMICA ÃTOMICA\n")
print("VALORES DEFINIDOS:\n")
print("E=0.997 kJ/mol , s=3.4 A, V0 definida pela temperatura inicial\n")
print("Distancia de equilibrio: 3.81 A \n")

num = int(input("Informe o numero de particulas do sistema:\n"))
T = float(input("Informe a temperatura em Kelvin:\n"))
tmax = float(input("Informe o tempo maximo de simulacao(tmax):\n")) #colocar se é em min ou s
dt = float(input("Informe o passo (dt) :\n"))                       #colocar se é em min ou s
L = float(input("Informe o comprimento da caixa:\n"))               #colocar se é em m

Talvo = T                               # temperatura ideal
r = np.float(3.81e0)                    #distancia de equilibrio
rc = r * np.float(2.5e0)                #Raio de corte #AUMENTAR RAIO DE CORTE PARA TESTES
aresta_cubo = L * rc

#Rmax = float(input("Entre com Rmax:\n"))
#dr = float(input("Entre com dr:\n"))

r0 = posicoes(num,aresta_cubo)          #Subrotína de distribuição dos átomos na caixa

aresta_cubo2 = aresta_cubo / np.float(2.0e0)

"""
print("X_0\n",X0)
print("Y_0\n",Y0)
print("Z_0\n",Z0)
"""

TABELA1.writelines([str(num), '\n', '\n'])
for i in range (num):
    TABELA1.writelines(['Ar  \t' , str(r0[i][0]), '\t' , str(r0[i][1]), '\t' , str(r0[i][2]), '\n' ])

t=0

uma = 1.66e-27      # unidade de massa atomica em kilogramas
massa = 39.94 * uma # massa do átomo de argonio

K = 3 / 2 * num / 6.022e23 * 8.31 * T # num/6.022e23 = numero de moles
#8.31 J/mol*K e T = K

v0 = distribuicao_aleatoria(massa,num,K)

"""
print("v0x_0 \n", v0x)
print("v0y_0 \n", v0y)
print("v0z_0 \n", v0z)
"""

#chama rotina para calcular forcas e energia potencial do sistema
F, U = forcas_energia_pot(r0,aresta_cubo,rc,num)
"""
print("Fx_0 \n", Fx)
print("Fy_0 \n", Fy)
print("Fz_0 \n", Fz)
print("U_0 \n", U )
"""
#determina o numero de iteracoeses totais, tendo conhecimento do intervalo de tempo e do tempo maximo
itmax = int (tmax/dt)
dt = dt * np.float(1.0e-15) #em fs ou e^(-15)s
dt2 = dt * dt
mdt2 = 0.5 * dt2
numesc = 10

#laÃ§o da dinÃ¢mica molecular
for i in range(itmax):
    #integra as equacoes de movimento
    r0, v = integracao_das_equacoes_de_movimento(F,r0,v0,massa,dt,mdt2)

    #agora vamos fazer o centro de massa do sistema ficar em repouso
    v0 = centro_de_massa_em_repolso(v,num,massa)

    #Recalcular a temperatura e energia cinética
    T, C = recalcular_temperatura(v0,num,massa)
    C = C * 6.242e+18

    #verifica se a particula sai do cubo e faz correcoes
    r0 = correcao_posicao_particulas(num,r0,aresta_cubo)

    #chama rotina para calcular forcas e energia potencial do sistema
    F, U = forcas_energia_pot(r0,aresta_cubo,rc,num)

    #reescala velocidades caso temperatura atual seja distinta da temperatura alvo
    v0 = reescala_veloci(v0,Talvo,T)

    esc = int(i / numesc)
    if ((i - esc*numesc) == 0):
       TABELA2.writelines([str(i), '\t', str(U) , '\t' , str(C) , '\t\t' , str(T) , '\n'])
       TABELA1.writelines([str(num), '\n', '\n'])
       for j in range(num):
           TABELA1.writelines(['Ar  \t' , str(r0[j][0]) , '\t' , str(r0[j][1]) , '\t' , str(r0[j][2]) , '\n' ])

TABELA1.close()
TABELA2.close()

"""
print (U)
print (Fx, Fy, Fz)
print (ax,ay, az)
uma = 1.66e-27 # em kilogramas
massa = 39.948 * uma

resp=int(Rmax/dr)

x = np.zeros(resp)
y = np.zeros(resp)
z = np.zeros(resp)
factor1 = np.zeros(resp)
factor2 = np.zeros(resp)
factor3 = np.zeros(resp)

for i in range(0,resp):
    factor1 = s/x[i]
    factor2 = math.pow(factor1,12) - math.pow(factor1,6)
    factor3 = 48.0e0 * (E/ x[i]) * (math.pow(factor1,12) - 0.5e0 * math.pow(factor1,6))
    x[i] = 0.1e0 + np.float(i) * dr
    y[i]= 4.0e0 * E * factor2
    z[i]= 48.0e0 * (E / x[i]) * factor2

plote.figure(1,figsize=(5,5))
plote.title('Grafico Potencial')
#plote.axis([min(x),max(x),min(y),max(y)])
plote.axis([2,max(x),min(y),10])
plote.plot(x,y,'g',linewidth=3)

plote.figure(2,figsize=(5,5))
plote.title('Grafico Forca')
#plote.axis([min(x),max(x),min(y),max(y)])
plote.axis([0,max(x),min(z),2])
plote.plot(x,z,'r',linewidth=3)

"""