from __future__ import annotations

from typing import TYPE_CHECKING, Any, Literal

from transformers import AutoTokenizer

from partial_tagger.data.collators import TransformerCollator
from partial_tagger.encoders.transformer import (
    TransformerModelEncoderFactory,
    TransformerModelWithHeadEncoderFactory,
)
from partial_tagger.training import Trainer

if TYPE_CHECKING:
    from partial_tagger.encoders.base import BaseEncoderFactory

def create_trainer(
    model_name: str = "roberta-base",
    dropout: float = 0.2,
    tokenizer_args: dict[str, Any] | None = None,
    encoder_type: Literal["default", "with_head"] = "default",
) -> Trainer:
    """Creates an instance of Trainer."""

    encoder_factory: BaseEncoderFactory

    if encoder_type == "default":
        encoder_factory = TransformerModelEncoderFactory(model_name, dropout)
    elif encoder_type == "with_head":
        encoder_factory = TransformerModelWithHeadEncoderFactory(model_name, dropout)
    else:
        raise ValueError(f"{encoder_type} is not supported.")

    collator = TransformerCollator(
        AutoTokenizer.from_pretrained(model_name), tokenizer_args
    )
    return Trainer(collator=collator, encoder_factory=encoder_factory)


import random

class Vertices:
    def __init__(self,x,y, volumePedido, valorPedido, qtdPacotes):
        self.volumePedido = volumePedido
        self.valorPedido = valorPedido
        self.qtdPacotes = qtdPacotes
        self.x = x
        self.y = y

    def __str__(self):
        return str(self.v) + " " + str(self.p) + " " + str(self.n) + "\n"

class Veiculo:
    def __init__(self, volumeMáximo, valorMáximo, qtdVeiculos, vf, vd, tc, td, ph, pkm, pf):
        self.volumeMáximo = volumeMáximo
        self.valorMáximo = valorMáximo
        self.qtdVeiculos = qtdVeiculos
        self.vf = vf
        self.vd = vd
        self.tc = tc
        self.td = td
        self.ph = ph
        self.pkm = pkm
        self.pf = pf


import torch
from torch import nn
from modules import ConvSC, Inception

# stride를 만들어내는 모듈..
def stride_generator(N, reverse=False):
    strides = [1, 2]*10
    if reverse: return list(reversed(strides[:N]))
    else: return strides[:N]

# N_S개 만큼 Stride를 생성한 후, ConvSC 생성해서
# 총 N_S의 깊이를 가진 Encoder 모듈 생성.
class Encoder(nn.Module):
    def __init__(self,C_in, C_hid, N_S):
        super(Encoder,self).__init__()
        strides = stride_generator(N_S)
        self.enc = nn.Sequential(
            ConvSC(C_in, C_hid, stride=strides[0]),
            *[ConvSC(C_hid, C_hid, stride=s) for s in strides[1:]]
        )

    def forward(self,x):
        enc1 = self.enc[0](x)
        latent = enc1
        for i in range(1,len(self.enc)):
            latent = self.enc[i](latent)
        return latent,enc1

# Mid_Xnet으로부터 받은 C_hid의 채널을 토대로 최종적으로 C_out 크기의
# 채널으로 변환 여기서 C_out은 초기 C와 같음.
# 여기서는 C_hid의 채널 수로 일정하게 조금씩 Upsampling 되다가
# 마지막에 encoder에서 추출한 공간 정보를 concat한다.
class Decoder(nn.Module):
    def __init__(self,C_hid, C_out, N_S):
        super(Decoder,self).__init__()
        strides = stride_generator(N_S, reverse=True)
        self.dec = nn.Sequential(
            *[ConvSC(C_hid, C_hid, stride=s, transpose=True) for s in strides[:-1]],
            ConvSC(2*C_hid, C_hid, stride=strides[-1], transpose=True)
        )
        self.readout = nn.Conv2d(C_hid, C_out, 1)

    def forward(self, hid, enc1=None):
        for i in range(0,len(self.dec)-1):
            hid = self.dec[i](hid)
        Y = self.dec[-1](torch.cat([hid, enc1], dim=1))
        Y = self.readout(Y)
        return Y

# Translator를 나타내는 중앙 인셉션 네트워크 부분.
# 인셉션 네트워크에도 인코더, 디코더 부분이 존재하여 스킵 연결을 통해, 인코더에서 뽑은 코딩을
# 디코더에 주입하여 Temporal 정보를 학습함.
class Mid_Xnet(nn.Module):
    def __init__(self, channel_in, channel_hid, N_T, incep_ker = [3,5,7,11], groups=8):
        super(Mid_Xnet, self).__init__()

        self.N_T = N_T
        enc_layers = [Inception(channel_in, channel_hid//2, channel_hid, incep_ker= incep_ker, groups=groups)]
        for i in range(1, N_T-1):
            enc_layers.append(Inception(channel_hid, channel_hid//2, channel_hid, incep_ker= incep_ker, groups=groups))
        enc_layers.append(Inception(channel_hid, channel_hid//2, channel_hid, incep_ker= incep_ker, groups=groups))

        dec_layers = [Inception(channel_hid, channel_hid//2, channel_hid, incep_ker= incep_ker, groups=groups)]
        for i in range(1, N_T-1):
            dec_layers.append(Inception(2*channel_hid, channel_hid//2, channel_hid, incep_ker= incep_ker, groups=groups))
        dec_layers.append(Inception(2*channel_hid, channel_hid//2, channel_in, incep_ker= incep_ker, groups=groups))

        self.enc = nn.Sequential(*enc_layers)
        self.dec = nn.Sequential(*dec_layers)

    def forward(self, x):
        B, T, C, H, W = x.shape
        x = x.reshape(B, T*C, H, W)

        # encoder
        skips = []
        z = x
        for i in range(self.N_T):
            z = self.enc[i](z)
            if i < self.N_T - 1:
                skips.append(z)

        # decoder
        z = self.dec[0](z)
        for i in range(1, self.N_T):
            z = self.dec[i](torch.cat([z, skips[-i]], dim=1))

        y = z.reshape(B, T, C, H, W)
        return y

class SimVP(nn.Module):
    def __init__(self, shape_in, hid_S=16, hid_T=256, N_S=4, N_T=8, incep_ker=[3,5,7,11], groups=8):
        super(SimVP, self).__init__()
        T, C, H, W = shape_in
        self.enc = Encoder(C, hid_S, N_S)
        self.hid = Mid_Xnet(T*hid_S, hid_T, N_T, incep_ker, groups)
        self.dec = Decoder(hid_S, C, N_S)

    def forward(self, x_raw):
        B, T, C, H, W = x_raw.shape
        x = x_raw.view(B*T, C, H, W)

        embed, skip = self.enc(x)
        _, C_, H_, W_ = embed.shape

        z = embed.view(B, T, C_, H_, W_)
        hid = self.hid(z)
        hid = hid.reshape(B*T, C_, H_, W_)

        Y = self.dec(hid, skip)
        Y = Y.reshape(B, T, C, H, W)
        return Y


from django.shortcuts import render
from .models import Twit,Company
import  datetime
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views import View
from django.http import HttpResponse,HttpResponseRedirect,Http404
import jdatetime
from django.db.models import Q # new
import datetime
# Create your views here.

def signal_week(mdate):
        week = []
        print('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&',mdate,type(mdate))
        for i in  range(5):
            print(mdate+datetime.timedelta(days=-i-1))
            nextday = mdate+datetime.timedelta(days=i+1)
            jnextday = jdatetime.date.fromgregorian(date=nextday)
            print(':::::::::::::::::::::::::::::::::::::::::::',jnextday)
            query = Twit.objects.filter(created_on__year=str(nextday.year)).filter(created_on__month=str(nextday.month)).filter(created_on__day=str(nextday.day))
            if query:
                week.append({
                    'date' : jnextday,
                    'len' : len(query)
                })
            if not week :
                for i in range (5):
                    PerivousDay = mdate+datetime.timedelta(days=-i-1)
                    JPerivousDay = jdatetime.date.fromgregorian(date=PerivousDay)
                    query = Twit.objects.filter(created_on__year=str(PerivousDay.year)).filter(created_on__month=str(PerivousDay.month)).filter(created_on__day=str(PerivousDay.day))
                    if query:
                        week.append({
                            'date' : JPerivousDay,
                            'len' : len(query)
                        })

        print(week)
        return week

def index (request):

    # test = Twit.objects.filter(id =1)
    print(datetime.date.today())
    # twits = Twit.objects.filter(created_on__date=datetime.date.today())
    today = datetime.datetime.today()
    # twits = Twit.objects.filter(created_on__year=today.year, created_on__month=today.month, created_on__day=today.day)
    twits = Twit.objects.filter(created_on__year=today.year, created_on__month=today.month, created_on__day=today.day,\
            status=1,avaiable=True,company__status=1)
    if len(twits) == 0:
        # twits = Twit.objects.all().order_by('-created_on')[:20]
        twits = Twit.objects.filter(status=1,avaiable=True,company__status=1).order_by('-created_on')[:20]

    companeis = Company.objects.filter(status=1)

    print('twits : ',len(twits))
    return render(request, 'home.html',{
        'twits':twits,
        'companeis': companeis,
        'jdate' : jdatetime.date.today(),
        'week' : signal_week(today)
    })

class UnavailableTiwtView(LoginRequiredMixin,View):
    def get_object(self, pk):
        try:
            return Twit.objects.get(pk=pk)
        except Twit.DoesNotExist:
            raise Http404
    def get(self,request,pk) :
        print("get pk : ",pk)
        twit = self.get_object(pk)
        twit.status =0
        twit.save()
        return HttpResponseRedirect('/')

    def post(self,request,pk):
        pass

class CompanyDetailView(View):
    def get(self,request):
        pass

class Search(View):
    def get(self,request):
        return HttpResponseRedirect('/')
    def post(self,request):
        today = datetime.datetime.today()
        if request.POST.get('search'):
            search_text = request.POST.get('search')
            data = Twit.objects.filter(
                Q(description__contains=search_text)|
                Q(company__name__contains=search_text)|
                Q(category__name__contains=search_text)).filter(status=1,avaiable=True,company__status=1)
            companeis = Company.objects.filter(status=1)
            print('******************twits***************** : ',len(data))
            return render(request, 'search.html',{
                'twits':data,
                'companeis': companeis,
                'jdate' : jdatetime.date.today(),
                'search_text': search_text,
                'week' : signal_week(today)
            })

        else:
            return HttpResponseRedirect('/')

class SearchByDate(View):

    def post(self,request):
        pass

    def get(self,request,year,month,day):
        try:
            date = jdatetime.date(int(year),int(month),int(day))
            mdate = date.togregorian()

            year,month,day = str(mdate).split('-')
            week = signal_week(mdate)

        except:
            print("errror when convert data:" + str(year) + "-"+str(month) + "-" + str(day))
            return HttpResponseRedirect('/')
        finally:
            data = Twit.objects.filter(created_on__year=str(year)).filter(created_on__month=str(month)).filter(created_on__day=str(day))
            companeis = Company.objects.filter(status=1)
            print('******************twits***************** : ',len(data))
            return render(request, 'search.html',{
                'twits':data,
                'companeis': companeis,
                'jdate' : date,
                'search_text': date,
                'week' : week,
            })
        return HttpResponseRedirect('/')


# -*- coding: utf-8 -*-
"""
Created on Sun Aug 12 10:37:33 2018

@author: Gerardo Cervantes
"""

import xml.etree.cElementTree as ET
from src.coordinates import Coordinates
from src.hotkeys import Hotkeys

class SharedPreferences():

    COORDINATES_TAG = 'coordinates'
    SPLIT_TAG = 'split_key'
    RESET_TAG = 'reset_key'
    ROUTE_TAG = 'route'

    def write_preferences(self, file_name, coordinates, route_name, hotkeys):
        xml_str = self.create_xml(coordinates, route_name, hotkeys)
        with open(file_name, "wb") as f:
            f.write(xml_str)

    def create_xml(self, coordinates, route_name, hotkeys):
        root = ET.Element("root")

        ET.SubElement(root, self.ROUTE_TAG).text = self.to_valid_xml_str(route_name)
        ET.SubElement(root, self.SPLIT_TAG).text = self.to_valid_xml_str(hotkeys.get_split_key())
        ET.SubElement(root, self.RESET_TAG).text = self.to_valid_xml_str(hotkeys.get_reset_key())

        xml_coordinates = ET.SubElement(root, self.COORDINATES_TAG)
        x, y, width, height = coordinates.get_coordinates()

        ET.SubElement(xml_coordinates, "x").text = str(x)
        ET.SubElement(xml_coordinates, "y").text = str(y)
        ET.SubElement(xml_coordinates, "width").text = str(width)
        ET.SubElement(xml_coordinates, "height").text = str(height)

        xml_str = ET.tostring(root, encoding='utf8', method='xml')
        return xml_str

    def to_valid_xml_str(self, text):
        if text == '':
            return ' '
        return text

    def parse_xml(self, file_name):
        try:
            tree = ET.parse(file_name)
        except FileNotFoundError:
            return None, None, None
        root = tree.getroot()
        route_name = root.find(self.ROUTE_TAG).text
        split_key = root.find(self.SPLIT_TAG).text
        reset_key = root.find(self.RESET_TAG).text
        coordinates_xml = root.find(self.COORDINATES_TAG)

        x = coordinates_xml.find("x").text
        y = coordinates_xml.find("y").text
        width = coordinates_xml.find("width").text
        height = coordinates_xml.find("height").text

        coordinates = Coordinates()
        coordinates.set_coordinates(x, y, width, height)

        hotkeys = Hotkeys()
        hotkeys.set_split_key(split_key)
        hotkeys.set_reset_key(reset_key)

        return coordinates, route_name, hotkeys

if __name__ == "__main__":
    shared_prefs = SharedPreferences()
    coordinates = Coordinates()
    coordinates.set_coordinates(20, 25, 50, 30)
    hotkeys = Hotkeys()
    file_name = 'example_pref_file.zd'
    shared_prefs.write_preferences(file_name, coordinates, '', hotkeys)
    coordinates, route_name, hotkeys = shared_prefs.parse_xml(file_name)
    print(coordinates)
    print(hotkeys.get_split_key())
    print(hotkeys.get_reset_key())
    print(route_name)
#    xml_str = shared_prefs.create_xml(coordinates, 'Home', 'Other', 'Route')
#    shared_prefs.xml_print(xml_str)


import json

f = open('dados.json')

Dados = json.load(f)

Dados = [x for x in Dados if x['valor'] > 0]

menor = float("inf")

#menor faturamento diário
for x in Dados:
  atual = x['valor']
  if(menor > atual):
    menor = atual
print('O menor valor de faturamento ocorrido em um dia do mês foi de ', menor)

#maior faturamento diário
maior = 0.0

for x in Dados:
  atual = x['valor']
  if(maior < atual):
    maior = atual
print('O maior valor de faturamento ocorrido em um dia do mês foi de ', maior)

#faturamento diário superior à média mensal

totalValor = 0.0

for x in Dados:
  atual = x['valor']
  totalValor = totalValor + float(atual)

media = totalValor/30

dias = 0

for x in Dados:
  atual = x['valor']
  if(atual > media):
    dias = dias + 1

print('O número de dias no mês em que o valor do faturamento diário superou à média mensal foi de ', dias)

f.close()


import numpy as np
import cv2

cap = cv2.VideoCapture(0)
faceCascade = cv2.CascadeClassifier("face.xml")

while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()

    # Our operations on the frame come here
    gray = frame

    # find face
    # Detect faces in the image
    faces = faceCascade.detectMultiScale(
        gray,
        scaleFactor=1.1,
        minNeighbors=5,
        minSize=(30, 30),
        flags = cv2.CASCADE_SCALE_IMAGE
    )

    #print ('Found {0} faces!'.format(len(faces)))

    # Draw a rectangle around the faces
    for (x, y, w, h) in faces:
        cv2.rectangle(gray, (x, y), (x+w, y+h), (0, 255, 0), 2)

    # Display the resulting frame
    cv2.imshow('frame',gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()


from django.core.exceptions import ObjectDoesNotExist
from django.http import StreamingHttpResponse, HttpResponse
from rest_framework.response import Response
from .models import AudioSlice, Audio
from .serializers import AudioSerializer, AudioSliceSerializer
from rest_framework.decorators import api_view
from rest_framework.decorators import parser_classes
from rest_framework.parsers import MultiPartParser
from .utils import utils as ut
from audio.dbmanager.redis_dao import *
from audio.services.preprocessor import AudioPreprocessor
from audio.dbmanager.youtube_handler import *
import re
import time

range_re = re.compile(r'bytes\s*=\s*(\d+)\s*-\s*(\d*)', re.I)
file_count = 0

"""
timeline
t0 : page 1에서 사용자가 오디오 요청을 보낼 때
t1 : page 2에서 사용자가 오디오의 구간을 선택할 때
"""

"""
t0 > CELERY RESULT BACKEND
사용자의 오디오 요청에 대한 전처리 실행 후 기록 --> view 함수에
"""
# preprocessor = AudioPreprocessor()
# # task_id는 audio의 id
# # audio_id = uuid.uuid4()  # 처음 들어오는 경우, 그게 아니면 database에서 꺼내오기
# AudioPreprocessor().preprocess.apply_async((3, 56), task_id="hiek", expires=datetime.now() + timedelta(days=1))

"""
t1 > USER INFO RECORD : (audio <----> choreo <----> product) Inter-server communication
KEY "a30gk3" <-- uuid.uuid4()
VAL (HSET)
{ audio_id : e317fce <-- 클라이언트에게 받을 것
start : 13  <-- audio_handler가 계산하도록
end : 31 <-- audio_handler가 계산하도록
progress : 0.0 }  <-- 어느정도 진행되었는지 percentage
"""

"""
t1 > SIMILARITY : (audio <----> choreo) Inter-server communication
KEY e317fce-14 <-- 노래 구간 id
VAL [ "af3g0s39_13 : 89", "ldf9a8i_4 : 90", "fk02j3bu_9 : 99", ... ] <-- 노래구간 id 와 점수가 매핑된 요소들로 구성된 list
"""

"""
t1 > AMPLITUDE : (audio <----> choreo) Inter-server communication
KEY e317fce-14 <-- 노래 구간 id
VAL [ 7 2 9 8 6 ] <-- 점수 list
"""

"""
===================================================================================================================
"""

# def upload_file(request):
#     if request.method == 'POST':
#         form = UploadFileForm(request.POST, request.FILES)
#         if form.is_valid():
#             instance = ModelWithFileField(file_field=request.FILES['file'])
#             instance.save()
#             return HttpResponseRedirect('/success/url/')
#     else:
#         form = UploadFileForm()
#     return render(request, 'upload.html', {'form': form})

@api_view(['POST'])
@parser_classes([MultiPartParser])
def meta(request):
    data = MultiPartParser.parse(request)
    print(data)
    res = write_from_meta()
    return Response(AudioSerializer(Audio.objects.all(), many=True).data)

@api_view(['POST'])
async def youtube_url(request):
    download_url = request.data.get("download_url")
    try:
        # 이미 있는 경우

        return Response(AudioSerializer(Audio.objects.get(download_url=download_url)).data)
    except ObjectDoesNotExist:
        try:
            print(f"started at {time.strftime('%X')}")
            _id, _title, _duration = await write_from_link(download_url)
            audio = Audio(audio_id=_id, title=_title, download_url=download_url, duration=_duration)
            audio.save()
            serializer = AudioSerializer(audio)
            # 이게 tasks에 해당됨
            AudioPreprocessor(audio=audio).preprocess()
            # 파일 찾아서 정보와 함께 보내주기
            return Response(serializer.data)
        except:
            print("===========download failure=============")
            return Response("cannot open file.", status=400)

    # response = StreamingHttpResponse(streaming_content=request.FILES["audio_file"])
    # response['Content-Disposition'] = f'attachment; filename="{request.data["audio_file"]}"'
    # return response

@api_view(['POST'])
@parser_classes([MultiPartParser])
# @renderer_classes([MultiPartRenderer])
def file(request):
    """
    :param request:
    :return: audio_id 와 file을 streaming 형태로
    """
    ext = request.data.get("ext")
    global file_count
    filename = "up" + str(file_count)
    if ext != "wav":
        ut.get_console_output(
            'ffmpeg -n -i "{}/{}.{}" "{}/{}.wav"'.format("../../media/ORG", filename, ext, "../../media/WAV",
                                                         filename))

    # 바로 파일 저장 - store in the volume
    file_count += 1

    response = StreamingHttpResponse(streaming_content=request.data["audio_file"])
    response['Content-Disposition'] = f'attachment; filename="{request.data["audio_file"]}"'
    return response

@api_view(['POST'])
def skeletal_after_interval(request):
    """
    :param request: audio_id, start_sec, end_sec
    :return:
    """
    audio_id = request.data.get('audio_id')
    user_start_sec = request.data['start_sec']
    user_end_sec = request.data['end_sec']

    UserRedisHandler.set_user_info(audio_id, user_start_sec, user_end_sec)

    if bool(AudioSlice.objects.filter(audio_slice_id__contains=audio_id)):
        start_arr = AudioSlice.objects.values_list('start_sec', flat=True)
        start_audio_slice_id = AudioSlice.objects.get(
            start_sec=ut.find_nearest(start_arr, user_start_sec)).only('audio_slice_id')
        end_audio_slice_id = request.data.get('audio_id') + AudioSlice.objects.get(
            start_sec=ut.find_nearest(start_arr, user_end_sec)).only('audio_slice_id').split("_")[1]

    else:
        audio_handler = AudioPreprocessor(Audio.objects.get(audio_id=audio_id))
        audio_handler.preprocess()
        start_audio_slice_id = audio_handler.get_slice_id(ut.find_nearest(audio_handler.beat_track, user_start_sec))
        end_audio_slice_id = audio_handler.get_slice_id(ut.find_nearest(audio_handler.beat_track, user_end_sec))

    interval_number = int(end_audio_slice_id.split("ㅡ")[1]) - int(start_audio_slice_id.split("ㅡ")[1])

    # Task 1. Similarity process & get into redis
    # smlr_app = Celery('redis_dao', backend=cc.result_smlr_backend, broker=cc.broker_smlr_url)
    # smlr_app.config_from_object('celery_config') --꼭 안해도 될 듯
    # 여기에 혜린이가 한 부분을 어떻게 어떻게 만들어서..
    # cluster_smlr.apply_async(filter_kmeans_labels, filter_feat, 0, 6))

    # Task 2. Amplitude process & get into redis
    # ampl_app = Celery(backend=cc.result_ampl_backend, broker=cc.broker_ampl_url)
    # get_amplitude.apply_async((3, 56), task_id=audio_id, expires=datetime.now() + timedelta(days=1))

    return Response(
        AudioSliceSerializer(start_audio_slice_id=start_audio_slice_id, end_audio_slice_id=end_audio_slice_id,
                             interval_number=interval_number).data)

# app = Celery('redis_dao', backend=cc.result_backend, broker=cc.broker_url)
# app.config_from_object('celery_config')

# def youtube(request):
#     # task_id는 audio의 id
#     audio_id = uuid.uuid4()  # 처음 들어오는 경우, 그게 아니면 database에서 꺼내오기
#     preprocess.apply_async((3, 56), task_id=audio_id, expires=datetime.now() + timedelta(days=1))

# def serve(request):
#     return FileResponse(open(request.data.get('music'), 'rb'))

@api_view(['POST'])
def get_music(request):
    with open(request.data.get('music'), 'rb') as f:
        # 필요한 응답헤더 세팅
        return set_audio_response('오디오파일 경로, wav 확장자까지 꼭 입력할 것', "오디오 파일 id(youtube id)", "wav",
                                  "오디오파일 duration float 형태로")

def set_audio_response(audio_src, audio_id, ext, duration):
    response = HttpResponse(open(audio_src, "rb"))
    response["Access-Control-Allow-Origin"] = "*"
    response['Content-Type'] = "application/octet-stream"
    response['Content-Disposition'] = f'attachment; filename="{audio_id}.{ext}"'  # wav만 보내지 않아도 되도록
    response['audio_id'] = audio_id
    response['duration'] = duration
    return response

    # data = {
    #     "audio_id": "dfsdff",
    #     "interval_number": 14,
    #     "music": open(request.data.get('music'), 'rb')
    # }
    # return HttpResponse(data)
    # response = HttpResponse(content=open(request.data.get('music'), 'rb'))
    # response['Content-Type'] = 'application/json'
    # return FileResponse(open(request.data.get('music'), 'rb'))


from MainA1 import Mainfun
from unigramIndex import Linkedlist
import string
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
import pickle

class QueryProcess:
    def __init__(self):
        '''Attribute for each Query processing results, Totdocmatch for total documentmatch,
        comparison for total comparison done in a merging algo, and fnamelist for list of all matched file'''
        self.Totdocmatch = 0
        self.comparison = 0
        self.fnamelist = []

    '''function  for preprocessing of a query including converting into
    lower letter, remove punctuation, tokenization, remove stopping words and Lemmatization'''
    def preprocess(self, query):
        #normalisation
        result1 = query.lower()
        result2 = result1.translate(str.maketrans("","", string.punctuation))

        #tokenization
        tokens = word_tokenize(result2)

        #removing the stopping words
        stop_words = set(stopwords.words('english'))
        result3 = [w for w in tokens if w not in stop_words]

        #Lemmatization
        lem = WordNetLemmatizer()
        result4query = []
        for word in result3:
            lmword = lem.lemmatize(word)
            result4query.append(lmword)

        return(result4query)

    def MergingAlgo(self, postlink, operatorseq, maxDocID, filename):
        length = len(operatorseq)
        #retrieve first posting list
        post1 = postlink[0]

        #Process the query from Left to Right, Iterate the query starting from query operator list
        for i in range(length):

            #REtrieve the operator and second postinglist
            operator = operatorseq[i]
            post2 = postlink[i+1]

            if (operator == 'AND'):
                p1 = post1.headptr
                p2 = post2.headptr

                #Calling the specific intersection Merge Algo
                post1 = self.MergeAND(p1, p2)

                '''checking the resultant postinglist will be null or not,
                if it is null then this post1 will move further to the next index in query list'''
                if(post1.freq == 0):
                    post1 = postlink[i+1]
                    i=i+1
            elif(operator == 'OR'):
                p1 = post1.headptr
                p2 = post2.headptr

                #Calling the specific Union Merge Algo
                post1 = self.MergeOR(p1, p2)

                '''checking the resultant postinglist will be null or not,
                if it is null then this post1 will move further to the next index in query list'''
                if(post1.freq == 0):
                    post1 = postlink[i+1]
                    i=i+1
            elif(operator == 'AND NOT'):
                tp2 = post2.headptr
                #Computing the complement of second posting list
                resulttp = self.ListCompliment(tp2, maxDocID)
                p1 = post1.headptr
                p2 = resulttp.headptr

                #Calling the specific intersection Merge Algo
                post1 = self.MergeAND(p1, p2)

                '''checking the resultant postinglist will be null or not,
                if it is null then this post1 will move further to the next index in query list'''
                if(post1.freq == 0):
                    post1 = postlink[i+1]
                    i=i+1
            elif(operator == 'OR NOT'):
                tp2 = post2.headptr
                #Computing the complement of second posting list
                resulttp = self.ListCompliment(tp2, maxDocID)
                p1 = post1.headptr
                p2 = resulttp.headptr

                #Calling the specific Union Merge Algo
                post1 = self.MergeOR(p1, p2)

                '''checking the resultant postinglist will be null or not,
                if it is null then this post1 will move further to the next index in query list'''
                if(post1.freq == 0):
                    post1 = postlink[i+1]
                    i=i+1

        '''After completing the merging Algo, the final resultant posting list will be post1
        retreiving the Document name acc. to the docID present in the final posting list'''
        self.Totdocmatch = post1.freq
        pt = post1.headptr
        while(pt is not None):
            self.fnamelist.append(filename[pt.IDval])
            pt = pt.next

    def MergeAND(self, ptr1, ptr2):
        answer = Linkedlist()
        #ptr1 and ptr2 , iterate the both pointer till the end of the linkedlist, both linkedlist are already in sorted form
        while(ptr1 is not None and ptr2 is not None):
            if(ptr1.IDval == ptr2.IDval):

                #here when both pointer node value matches, then add the nodevalue to the answer linked list
                answer.addnode(ptr1.IDval)

                #move both pointer by one node
                ptr1 = ptr1.next
                ptr2 = ptr2.next

                #here counting the comarison, in this algo this is the first comparison so just add 1 to the comparison variable
                self.comparison = self.comparison + 1

            elif(ptr1.IDval < ptr2.IDval):

                #here the ptr1 is behind the ptr2, so just move ptr1 by one node
                ptr1 = ptr1.next

                #here counting the comarison, in this algo this is the second comparison so just add 2 to the comparison variable
                self.comparison = self.comparison + 2

            else:
                #here in the else, the ptr2 is behind the ptr1, so just move ptr2 by one node
                ptr2 = ptr2.next

                #here counting the comarison, in this algo 2 comparison are already done in above, so just add 2 to the comparison variable
                self.comparison = self.comparison + 2

        return answer

    def MergeOR(self, ptr1, ptr2):
        answer = Linkedlist()

        #ptr1 and ptr2 , iterate the both pointer till the end of the linkedlist, both linkedlist are already in sorted form
        while(ptr1 is not None and ptr2 is not None):

            if(ptr1.IDval < ptr2.IDval):
                #add the nodevalue to the answer linked list
                answer.addnode(ptr1.IDval)

                #here the ptr1 is behind the ptr2, so just move ptr1 by one node
                ptr1 = ptr1.next

                #here counting the comarison, in this algo this is the first comparison so just add 1 to the comparison variable
                self.comparison = self.comparison + 1

            elif(ptr1.IDval > ptr2.IDval):
                #add the nodevalue to the answer linked list
                answer.addnode(ptr2.IDval)

                #the ptr2 is behind the ptr1, so just move ptr2 by one node
                ptr2 = ptr2.next

                #here counting the comarison, in this algo this is the second comparison so just add 2 to the comparison variable
                self.comparison = self.comparison + 2
            else:
                #here in the else, when both pointer node value matches, then add the nodevalue to the answer linked list
                answer.addnode(ptr1.IDval)

                #move both pointer by one node
                ptr1 = ptr1.next
                ptr2 = ptr2.next

                #here counting the comarison, in this algo 2 comparison are already done in above, so just add 2 to the comparison variable
                self.comparison = self.comparison + 2

        #if ptr2 becomes none but ptr1 is not none, so just add the remaining node value of ptr1 to the answer linkedlsit
        while(ptr1 is not None):
            answer.addnode(ptr1.IDval)
            ptr1 = ptr1.next

        #if ptr1 becomes none but ptr2 is not none, so just add the remaining node value of ptr2 to the answer linkedlsit
        while(ptr2 is not None):
            answer.addnode(ptr2.IDval)
            ptr2 = ptr2.next

        return answer

    #Function for finding the complement of a linkedlist
    def ListCompliment(self, ptr, maxDocID):
        i = 0
        answer = Linkedlist()
        #here maxDOCID is representing the number that the max docID that allocate to the document(0-maxdocID)
        while(i < maxDocID and ptr is not None):
            #if the docID present in the list, so just move to the next node
            if(i == ptr.IDval):
                i = i+1
                ptr = ptr.next
            #if the docID not present in the list, so just add to the answer linkedlist
            elif(i < ptr.IDval):
                answer.addnode(i)
                i=i+1
        #adding the remaining docID to the answer linkedlist
        while(i < maxDocID):
            answer.addnode(i)
            i=i+1

        return(answer)

if __name__ == '__main__':
    #Deserailization of MainA1 class object, in which unigram data structure has stored
    with open('store.dat' , 'rb') as fr:
        tempomainobj = pickle.load(fr)

    #retriving the unigram data structure, list of all doc, max doc ID
    dictlist = tempomainobj.postinglist
    filename = tempomainobj.docname
    maxDocID = tempomainobj.docID

    #Input the no. of query from the User
    n = int(input("Enter the number of Query: "))

    for i in range(n):
        #input the query and query operator
        query = input("Input Query: ")
        queryoperatorseq = input("Input Query operator: ").split(', ')

        #Preprocessing of Query
        Queryobj = QueryProcess()
        prepresult = Queryobj.preprocess(query)

        #Retriving the postinglist of each tokenize word of a query in postlink[] list
        postlink = []
        for qword in prepresult:
            LinkL = dictlist.get(qword)
            postlink.append(LinkL)

        #Process the Query and query operator by merging Algoruthm
        Queryobj.MergingAlgo(postlink, queryoperatorseq, maxDocID, filename)

        #print the desirable result of a query
        print('Number of document matched: ', end=' ')
        print(Queryobj.Totdocmatch)
        print('Number of comparison Done in Merging Algorithm: ', end=' ')
        print(Queryobj.comparison)
        print('List of matched document name:')
        print(Queryobj.fnamelist)


import cv2
import os

import numpy as np
import imutils

def open_picture(image):
    """We open picture"""

    img = cv2.imread(image)
    return img

def show_picture(name, image, mode, destroy):
    cv2.imshow(name, image)
    cv2.waitKey(mode)
    if mode == 1:
        time.sleep(0.2)
    if destroy == "y":
        cv2.destroyAllWindows()

def save_picture(name, image):
    path = "dataset/data_analysing/{}"
    cv2.imwrite(path.format(str(name)), image)

def blanck_picture(img):

    """Create a black background picture same dimension of original picture"""

    blank_image = np.zeros((img.shape[0],img.shape[1],3), np.uint8)
    blank_image[0:img.shape[0], 0:img.shape[1]] = 0, 0, 0

    return blank_image

def find_object(img):

    """
        We binarising picture
        for only have a form of our object.
        We search contours now
    """

    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    _, thresh = cv2.threshold(gray,250,255,cv2.THRESH_BINARY_INV)

    contours, _ = cv2.findContours(thresh, cv2.RETR_TREE,
                                   cv2.CHAIN_APPROX_SIMPLE)
    return contours

def recup_object(contours, img):

    """
        We search the max contours.
        Sometimes there are noise of litle
        area of the rest of the background
        of pixels (5x5) of background.
        We don't want it !

        After we make a crop of that.
    """

    maxi = 0
    for cnts in contours:
        if cv2.contourArea(cnts) > maxi:
            maxi = cv2.contourArea(cnts)

    for cnts in contours:
        if cv2.contourArea(cnts) == maxi:

            x, y, w, h = cv2.boundingRect(cnts)
            crop = img[y:y+h, x:x+w]

            return crop

def main_croping(picture):

    img = open_picture(picture)

    contours = find_object(img)
    crop = recup_object(contours, img)

    return crop


from unittest import TestCase

from mapper.file_mapper import FileMapper
from container.file import File

class TestFileMapper(TestCase):
    def test_get_files_from_diff_should_return_four_files(self):
        diff = '4\t0\t.gitignore\n' \
               '8\t8\tIZIFarmaProm/build.gradle\n' \
               '1\t1\tIZIFarmaProm/src/dev/res/values/strings.xml\n' \
               '2\t6\tIZIFarmaProm/src/main/AndroidManifest.xml\n' \
               ' '
        file_mapper = FileMapper(diff)
        actual = file_mapper.map_files('', get_file_content_mock)

        self.assertEqual(4, actual.__len__())

    def test_get_files_from_diff_should_return_correct_array(self):
        diff = '4\t0\t.gitignore\n' \
               ' '
        file_mapper = FileMapper(diff)
        diffed_files = file_mapper.map_files('', get_file_content_mock)
        actual = diffed_files[0]
        expected = File('.gitignore', None, 4, 0)

        self.assertEqual(expected.file_path, actual.file_path)
        self.assertEqual(expected.deleted_lines, actual.deleted_lines)
        self.assertEqual(expected.added_lines, actual.added_lines)

def get_file_content_mock(project_path, file_path):
    pass


"""
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.
"""
"""
Time complexity:- O(max(n,m))
Space Complexity:- O(1)
"""

from typing import Optional

# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class Solution:
    def addTwoNumbers(
        self, l1: Optional[ListNode], l2: Optional[ListNode]
    ) -> Optional[ListNode]:
        # Create a dummy head and a tail pointer for the result linked list
        dummyHead = ListNode(0)
        tail = dummyHead
        carry = 0  # Initialize the carry to 0

        while l1 or l2 or carry != 0:
            # Get the current digits of l1 and l2 (or 0 if one of them is None)
            digit1 = l1.val if l1 else 0
            digit2 = l2.val if l2 else 0

            # Calculate the sum of the digits and the carry
            _sum = digit1 + digit2 + carry
            digit = _sum % 10
            carry = _sum // 10

            # Create a new node with the calculated digit
            newNode = ListNode(digit)

            # Append the new node to the result linked list
            tail.next = newNode
            tail = tail.next

            # Move to the next nodes in l1 and l2 (if available)
            l1 = l1.next if l1 else None
            l2 = l2.next if l2 else None

        # Get the result linked list starting from the node after the dummy head
        result = dummyHead.next

        # Remove the reference to the rest of the linked list
        dummyHead.next = None

        return result  # Return the result linked list


# -*- coding: utf-8 -*-
"""
Created on Wed Oct 28 07:07:43 2015

@author: RAHUL JAIN
"""

from xml.dom.minidom import parse
import xml.dom.minidom
DOMTree = xml.dom.minidom.parse("chemsep1.xml")
compounds = DOMTree.documentElement
compound = compounds.getElementsByTagName("compound")
i = 1
for comp in compound:
   compName = comp.getElementsByTagName("CompoundID")[0].getAttribute("value")
   CompName = compName.replace(" ","")
   CompName = CompName.replace("-","")
   CompName = CompName.replace(",","")
   CompName = CompName.replace("1","One")
   CompName = CompName.replace("2","Two")
   CompName = CompName.replace("3","Three")
   CompName = CompName.replace("4","Four")
   CompName = CompName.replace("5","Five")
   CriticalTemp = comp.getElementsByTagName("CriticalTemperature")[0].getAttribute("value")
   CriticalPres = comp.getElementsByTagName("CriticalPressure")[0].getAttribute("value")
   CriticalVol = comp.getElementsByTagName("CriticalVolume")[0].getAttribute("value")
   CriticalComp = comp.getElementsByTagName("CriticalCompressibility")[0].getAttribute("value")
   try:
     NormalBoilPoint = comp.getElementsByTagName("NormalBoilingPointTemperature")[0].getAttribute("value")
   except IndexError:
     NormalBoilPoint = "0"
   try:
     NormalMeltingPoint = comp.getElementsByTagName("NormalMeltingPointTemperature")[0].getAttribute("value")
   except IndexError:
     NormalMeltingPoint = "0"
   try:
     TripPntTemp = comp.getElementsByTagName("TriplePointTemperature")[0].getAttribute("value")
   except IndexError:
     TripPntTemp = "0"
   try:
     TripPntPres = comp.getElementsByTagName("TriplePointPressure")[0].getAttribute("value")
   except IndexError:
     TripPntPres = "0"
   MolWt =  comp.getElementsByTagName("MolecularWeight")[0].getAttribute("value")
   try:
     LiqVolAtBoilPnt = comp.getElementsByTagName("LiquidVolumeAtNormalBoilingPoint")[0].getAttribute("value")
   except IndexError:
     LiqVolAtBoilPnt = "0"
   try:
     AcenFactor = comp.getElementsByTagName("AcentricityFactor")[0].getAttribute("value")
   except IndexError:
     AcenFactor = "0"
   try:
     SolParam = comp.getElementsByTagName("SolubilityParameter")[0].getAttribute("value")
   except IndexError:
     SolParam = "0"
   try:
     DipoleMoment = comp.getElementsByTagName("DipoleMoment")[0].getAttribute("value")
   except IndexError:
     DipoleMoment = "0"
   try:
     IGHF = comp.getElementsByTagName("HeatOfFormation")[0].getAttribute("value")
   except IndexError:
     IGHF = "0"
   try:
     GEF = comp.getElementsByTagName("GibbsEnergyOfFormation")[0].getAttribute("value")
   except IndexError:
     GEF = "0"
   try:
     AbsEntropy = comp.getElementsByTagName("AbsEntropy")[0].getAttribute("value")
   except IndexError:
     AbsEntropy = "0"
   try:
     HeatFusionMeltPnt = comp.getElementsByTagName("HeatOfFusionAtMeltingPoint")[0].getAttribute("value")
   except IndexError:
     HeatFusionMeltPnt = "0"
   try:
     HOC = comp.getElementsByTagName("HeatOfCombustion")[0].getAttribute("value")
   except IndexError:
     HOC = "0"
   try:
     UniquacR = comp.getElementsByTagName("UniquacR")[0].getAttribute("value")
   except IndexError:
     UniquacR = "0"
   try:
     UniquacQ = comp.getElementsByTagName("UniquacQ")[0].getAttribute("value")
   except IndexError:
     UniquacQ = "0"
   try:
     RacketParam = comp.getElementsByTagName("RacketParameter")[0].getAttribute("value")
   except IndexError:
     RacketParam = "0"

   try:
     LiqDen = comp.getElementsByTagName("LiquidDensity")[0]
     LiqDenEqn = LiqDen.getElementsByTagName("eqno")[0].getAttribute("value")
     A=LiqDen.getElementsByTagName("A")[0].getAttribute("value")
     B=LiqDen.getElementsByTagName("B")[0].getAttribute("value")
     C=LiqDen.getElementsByTagName("C")[0].getAttribute("value")
     D=LiqDen.getElementsByTagName("D")[0].getAttribute("value")
     try:
          E=LiqDen.getElementsByTagName("E")[0].getAttribute("value")
     except IndexError:
          E = "0"
   except IndexError:
     LiqDenEqn = "0"
     A = "0"
     B = "0"
     C = "0"
     D = "0"
     E = "0"
   try:
      VapPres = comp.getElementsByTagName("VaporPressure")[0]
      VapPresEqn = VapPres.getElementsByTagName("eqno")[0].getAttribute("value")
      VA=VapPres.getElementsByTagName("A")[0].getAttribute("value")
      VB=VapPres.getElementsByTagName("B")[0].getAttribute("value")
      VC=VapPres.getElementsByTagName("C")[0].getAttribute("value")
      try:
          VD=VapPres.getElementsByTagName("D")[0].getAttribute("value")
      except IndexError:
          VD = "0"
      try:
          VE=VapPres.getElementsByTagName("E")[0].getAttribute("value")
      except IndexError:
          VE = "0"
   except IndexError:
     VapPresEqn = "0"
     VA = "0"
     VB = "0"
     VC = "0"
     VD = "0"
     VE = "0"
   try:
      LiqCp = comp.getElementsByTagName("LiquidHeatCapacityCp")[0]
      LiqCpEqn = LiqCp.getElementsByTagName("eqno")[0].getAttribute("value")
      LCpA=LiqCp.getElementsByTagName("A")[0].getAttribute("value")
      LCpB=LiqCp.getElementsByTagName("B")[0].getAttribute("value")
      LCpC=LiqCp.getElementsByTagName("C")[0].getAttribute("value")
      try:
          LCpD=LiqCp.getElementsByTagName("D")[0].getAttribute("value")
      except IndexError:
          LCpD = "0"
      try:
          LCpE=LiqCp.getElementsByTagName("E")[0].getAttribute("value")
      except IndexError:
          LCpE = "0"
   except IndexError:
     LiqCpEqn = "0"
     LCpA = "0"
     LCpB = "0"
     LCpC = "0"
     LCpD = "0"
     LCpE = "0"
   try:
      HOV = comp.getElementsByTagName("HeatOfVaporization")[0]
      HOVEqn = HOV.getElementsByTagName("eqno")[0].getAttribute("value")
      HOVA=HOV.getElementsByTagName("A")[0].getAttribute("value")
      HOVB=HOV.getElementsByTagName("B")[0].getAttribute("value")
      HOVC=HOV.getElementsByTagName("C")[0].getAttribute("value")
      try:
          HOVD=HOV.getElementsByTagName("D")[0].getAttribute("value")
      except IndexError:
          HOVD = "0"
      try:
          HOVE=HOV.getElementsByTagName("E")[0].getAttribute("value")
      except IndexError:
          HOVE = "0"
   except IndexError:
     HOVEqn = "0"
     HOVA = "0"
     HOVB = "0"
     HOVC = "0"
     HOVD = "0"
     HOVE = "0"
   if (float(NormalBoilPoint) >  298.15 ):
     HA = float(HOVA)
     HB = float(HOVB)
     HC = float(HOVC)
     HD = float(HOVD)
     HE = float(HOVE)
     Tr = 298.15/float(CriticalTemp)
     SHOV = HA*(pow((1-Tr),(HB + HC*Tr + HD*pow(Tr,2) + HE*pow(Tr,3))))
     AbsEnthalpy = float(IGHF) -  SHOV
   else:
     AbsEnthalpy = float(IGHF)
   SH = str(AbsEnthalpy)
   try:
      VapCp = comp.getElementsByTagName("IdealGasHeatCapacityCp")[0]
      VapCpEqn = VapCp.getElementsByTagName("eqno")[0].getAttribute("value")
      VCpA=VapCp.getElementsByTagName("A")[0].getAttribute("value")
      VCpB=VapCp.getElementsByTagName("B")[0].getAttribute("value")
      VCpC=VapCp.getElementsByTagName("C")[0].getAttribute("value")
      try:
          VCpD=VapCp.getElementsByTagName("D")[0].getAttribute("value")
      except IndexError:
          VCpD = "0"
      try:
          VCpE=VapCp.getElementsByTagName("E")[0].getAttribute("value")
      except IndexError:
          VCpE = "0"
   except IndexError:
     VapCpEqn = "0"
     VCpA = "0"
     VCpB = "0"
     VCpC = "0"
     VCpD = "0"
     VCpE = "0"

   try:
      LiqVis = comp.getElementsByTagName("LiquidViscosity")[0]
      LiqVisEqn = LiqVis.getElementsByTagName("eqno")[0].getAttribute("value")
      LiqVisA=LiqVis.getElementsByTagName("A")[0].getAttribute("value")
      LiqVisB=LiqVis.getElementsByTagName("B")[0].getAttribute("value")
      LiqVisC=LiqVis.getElementsByTagName("C")[0].getAttribute("value")
      try:
          LiqVisD=LiqVis.getElementsByTagName("D")[0].getAttribute("value")
      except IndexError:
          LiqVisD = "0"
      try:
          LiqVisE=LiqVis.getElementsByTagName("E")[0].getAttribute("value")
      except IndexError:
          LiqVisE = "0"
   except IndexError:
     LiqVisEqn = "0"
     LiqVisA = "0"
     LiqVisB = "0"
     LiqVisC = "0"
     LiqVisD = "0"
     LiqVisE = "0"

   try:
      VapVis = comp.getElementsByTagName("VaporViscosity")[0]
      VapVisEqn = VapVis.getElementsByTagName("eqno")[0].getAttribute("value")
      VapVisA=VapVis.getElementsByTagName("A")[0].getAttribute("value")
      VapVisB=VapVis.getElementsByTagName("B")[0].getAttribute("value")
      VapVisC=VapVis.getElementsByTagName("C")[0].getAttribute("value")
      try:
          VapVisD=VapVis.getElementsByTagName("D")[0].getAttribute("value")
      except IndexError:
          VapVisD = "0"
      try:
          VapVisE=VapVis.getElementsByTagName("E")[0].getAttribute("value")
      except IndexError:
          VapVisE = "0"
   except IndexError:
     VapVisEqn = "0"
     VapVisA = "0"
     VapVisB = "0"
     VapVisC = "0"
     VapVisD = "0"
     VapVisE = "0"

   try:
      LiqK = comp.getElementsByTagName("LiquidThermalConductivity")[0]
      LiqKEqn = LiqK.getElementsByTagName("eqno")[0].getAttribute("value")
      LiqKA=LiqK.getElementsByTagName("A")[0].getAttribute("value")
      LiqKB=LiqK.getElementsByTagName("B")[0].getAttribute("value")
      LiqKC=LiqK.getElementsByTagName("C")[0].getAttribute("value")
      try:
          LiqKD=LiqK.getElementsByTagName("D")[0].getAttribute("value")
      except IndexError:
          LiqKD = "0"
      try:
          LiqKE=LiqK.getElementsByTagName("E")[0].getAttribute("value")
      except IndexError:
          LiqKE = "0"
   except IndexError:
     LiqKEqn = "0"
     LiqKA = "0"
     LiqKB = "0"
     LiqKC = "0"
     LiqKD = "0"
     LiqKE = "0"

   try:
      VapK = comp.getElementsByTagName("VaporThermalConductivity")[0]
      VapKEqn = VapK.getElementsByTagName("eqno")[0].getAttribute("value")
      VapKA=VapK.getElementsByTagName("A")[0].getAttribute("value")
      VapKB=VapK.getElementsByTagName("B")[0].getAttribute("value")
      VapKC=VapK.getElementsByTagName("C")[0].getAttribute("value")
      try:
          VapKD=VapK.getElementsByTagName("D")[0].getAttribute("value")
      except IndexError:
          VapKD = "0"
      try:
          VapKE=VapK.getElementsByTagName("E")[0].getAttribute("value")
      except IndexError:
          VapKE = "0"
   except IndexError:
     VapKEqn = "0"
     VapKA = "0"
     VapKB = "0"
     VapKC = "0"
     VapKD = "0"
     VapKE = "0"

   f = open('File5.txt','a')
   f.write('model '+CompName)
   f.write('\n')
   f.write('extends General_Properties(')
   f.write('\n')
   f.write('SN ' + '=' + str(i) +',')
   f.write('\n')
   f.write('name' + '=' + '"'+ CompName + '",')
   f.write('\n')
   f.write('Tc ' + '=' + CriticalTemp + ',')
   f.write('\n')
   f.write('Pc ' + '=' + CriticalPres + ',')
   f.write('\n')
   f.write('Vc ' + '=' + CriticalVol + ',')
   f.write('\n')
   f.write('Cc ' + '=' + CriticalComp + ',')
   f.write('\n')
   f.write('Tb ' + '=' + NormalBoilPoint + ',')
   f.write('\n')
   f.write('Tm ' + '=' + NormalMeltingPoint + ',')
   f.write('\n')
   f.write('TT ' + '=' + TripPntTemp + ',')
   f.write('\n')
   f.write('TP ' + '=' + TripPntPres + ',')
   f.write('\n')
   f.write('MW ' + '=' + MolWt + ',')
   f.write('\n')
   f.write('LVB ' + '=' + LiqVolAtBoilPnt + ',')
   f.write('\n')
   f.write('AF ' + '=' + AcenFactor + ',')
   f.write('\n')
   f.write('SP ' + '=' + SolParam + ',')
   f.write('\n')
   f.write('DM ' + '=' + DipoleMoment + ',')
   f.write('\n')
   f.write('SH ' + '=' + SH + ',')
   f.write('\n')
   f.write('IGHF ' + '=' + IGHF + ',')
   f.write('\n')
   f.write('GEF ' + '=' + GEF + ',')
   f.write('\n')
   f.write('AS ' + '=' + AbsEntropy + ',')
   f.write('\n')
   f.write('HFMP ' + '=' + HeatFusionMeltPnt + ',')
   f.write('\n')
   f.write('HOC ' + '=' + HOC + ',')
   f.write('\n')
   f.write('LiqDen = {'+LiqDenEqn+","+A+","+B+","+C+","+D+","+E+'},')
   f.write('\n')
   f.write('VP = {'+VapPresEqn+","+VA+","+VB+","+VC+","+VD+","+VE+'},')
   f.write('\n')
   f.write('LiqCp = {'+LiqCpEqn+","+LCpA+","+LCpB+","+LCpC+","+LCpD+","+LCpE+'},')
   f.write('\n')
   f.write('HOV = {'+HOVEqn+","+HOVA+","+HOVB+","+HOVC+","+HOVD+","+HOVE+'},')
   f.write('\n')
   f.write('VapCp = {'+VapCpEqn+","+VCpA+","+VCpB+","+VCpC+","+VCpD+","+VCpE+'},')
   f.write('\n')
   f.write('LiqVis = {'+LiqVisEqn+","+LiqVisA+","+LiqVisB+","+LiqVisC+","+LiqVisD+","+LiqVisE+'},')
   f.write('\n')
   f.write('VapVis = {'+VapVisEqn+","+VapVisA+","+VapVisB+","+VapVisC+","+VapVisD+","+VapVisE+'},')
   f.write('\n')
   f.write('LiqK = {'+LiqKEqn+","+LiqKA+","+LiqKB+","+LiqKC+","+LiqKD+","+LiqKE+'},')
   f.write('\n')
   f.write('VapK = {'+VapKEqn+","+VapKA+","+VapKB+","+VapKC+","+VapKD+","+VapKE+'},')
   f.write('\n')
   f.write('Racketparam = '+RacketParam +',')
   f.write('\n')
   f.write('UniquacR = '+ UniquacR + ',')
   f.write('\n')
   f.write('UniquacQ = '+ UniquacQ + ');')
   f.write('\n')
   f.write('end '+CompName+';')
   f.write('\n')
   f.write('\n')
#   f.write('function Psat')
#   f.write('\n')
#   f.write('input Real T;')
#   f.write('\n')
#   f.write('output Real Vp;')
#   f.write('\n')
#   f.write('algorithm')
#   f.write('\n')
#   f.write('Vp := exp(VP[2] + VP[3] / T + VP[4] * log(T) + VP[5] * T ^ VP[6]);')
#   f.write('\n')
#   f.write('end Psat;')
#   f.write('\n')
#   f.write('\n')
#
#   f.write('function LCp')
#   f.write('\n')
#   f.write('input Real T;')
#   f.write('\n')
#   f.write('output Real Cp;')
#   f.write('\n')
#   f.write('algorithm')
#   f.write('\n')
#   f.write('Cp := (LiqCp[2] + exp(LiqCp[3] / T + LiqCp[4] + LiqCp[5] * T + LiqCp[6] * T ^ 2)) / 1000;')
#   f.write('\n')
#   f.write('end LCp;')
#   f.write('\n')
#   f.write('\n')
#
#   f.write('function HV')
#   f.write('\n')
#   f.write('input Real T;')
#   f.write('\n')
#   f.write('output Real Hv;')
#   f.write('\n')
#   f.write('protected')
#   f.write('\n')
#   f.write('Real Tr = T / Tc;')
#   f.write('\n')
#   f.write('algorithm')
#   f.write('\n')
#   f.write('Hv := HOV[2] * (1 - Tr) ^ (HOV[3] + HOV[4] * Tr + HOV[5] * Tr ^ 2 + HOV[6] * Tr ^ 3) / 1000;')
#   f.write('\n')
#   f.write('end HV;')
#   f.write('\n')
#   f.write('\n')
#
#   f.write('function HLiq')
#   f.write('\n')
#   f.write('input Real T;')
#   f.write('\n')
#   f.write('output Real Ent;')
#   f.write('\n')
#   f.write('protected')
#   f.write('\n')
#   f.write('Real Temp = 298.15;')
#   f.write('\n')
#   f.write('algorithm')
#   f.write('\n')
#   f.write('Ent := 0;')
#   f.write('\n')
#   f.write('while Temp < T loop')
#   f.write('\n')
#   f.write('Ent := Ent + LCp(Temp) * 1;')
#   f.write('\n')
#   f.write('Temp := Temp + 1;')
#   f.write('\n')
#   f.write('end while;')
#   f.write('\n')
#   f.write('Ent := SH / 1000 + Ent;')
#   f.write('\n')
#   f.write('end HLiq;')
#   f.write('\n')
#   f.write('\n')
#
#   f.write('function HVap')
#   f.write('\n')
#   f.write('input Real T;')
#   f.write('\n')
#   f.write('output Real Ent;')
#   f.write('\n')
#   f.write('algorithm')
#   f.write('\n')
#   f.write('Ent := HLiq(T) + HV(T);')
#   f.write('\n')
#   f.write('end HVap;')
#   f.write('\n')

   i = i + 1
f.close()


# encoding: utf-8

import badgrlog
import datetime

from django.utils import timezone
from rest_framework import permissions
from rest_framework.response import Response
from rest_framework import serializers
from rest_framework import status

from backpack.models import BackpackCollection, BackpackBadgeShare, BackpackCollectionShare
from backpack.serializers_v1 import CollectionSerializerV1, LocalBadgeInstanceUploadSerializerV1
from backpack.serializers_v2 import BackpackAssertionSerializerV2, BackpackCollectionSerializerV2, \
    BackpackImportSerializerV2, BackpackAssertionAcceptanceSerializerV2
from entity.api import BaseEntityListView, BaseEntityDetailView
from issuer.models import BadgeInstance
from issuer.permissions import AuditedModelOwner, VerifiedEmailMatchesRecipientIdentifier, BadgrOAuthTokenHasScope
from issuer.public_api import ImagePropertyDetailView
from apispec_drf.decorators import apispec_list_operation, apispec_post_operation, apispec_get_operation, \
    apispec_delete_operation, apispec_put_operation, apispec_operation
from mainsite.permissions import AuthenticatedWithVerifiedIdentifier

logger = badgrlog.BadgrLogger()

_TRUE_VALUES = ['true', 't', 'on', 'yes', 'y', '1', 1, 1.0, True]
_FALSE_VALUES = ['false', 'f', 'off', 'no', 'n', '0', 0, 0.0, False]

def _scrub_boolean(boolean_str, default=None):
    if boolean_str in _TRUE_VALUES:
        return True
    if boolean_str in _FALSE_VALUES:
        return False
    return default

class BackpackAssertionList(BaseEntityListView):
    model = BadgeInstance
    v1_serializer_class = LocalBadgeInstanceUploadSerializerV1
    v2_serializer_class = BackpackAssertionSerializerV2
    create_event = badgrlog.BadgeUploaded
    permission_classes = (AuthenticatedWithVerifiedIdentifier, VerifiedEmailMatchesRecipientIdentifier, BadgrOAuthTokenHasScope)
    http_method_names = ('get', 'post')
    valid_scopes = {
        'get': ['r:backpack', 'rw:backpack'],
        'post': ['rw:backpack'],
    }
    include_defaults = {
        'include_expired': {'v1': 'true', 'v2': 'false'},
        'include_revoked': {'v1': 'false', 'v2': 'false'},
        'include_pending': {'v1': 'false', 'v2': 'false'},
    }

    def get_objects(self, request, **kwargs):
        version = kwargs.get('version', 'v1')
        include_expired = request.query_params.get(
            'include_expired', self.include_defaults['include_expired'][version]
        ).lower() in ['1', 'true']
        include_revoked = request.query_params.get(
            'include_revoked', self.include_defaults['include_revoked'][version]
        ).lower() in ['1', 'true']
        include_pending = request.query_params.get(
            'include_pending', self.include_defaults['include_pending'][version]
        ).lower() in ['1', 'true']

        def badge_filter(b):
            if ((b.acceptance == BadgeInstance.ACCEPTANCE_REJECTED) or
                    (not include_expired and b.expires_at != None and b.expires_at < timezone.now()) or
                    (not include_revoked and b.revoked) or
                    (not include_pending and b.pending)):
                return False
            return True

        return list(filter(badge_filter, self.request.user.cached_badgeinstances()))

    @apispec_list_operation('Assertion',
        summary="Get a list of Assertions in authenticated user's backpack ",
        tags=['Backpack']
    )
    def get(self, request, **kwargs):
        mykwargs = kwargs.copy()
        mykwargs['expands'] = []
        expands = request.GET.getlist('expand', [])

        if 'badgeclass' in expands:
            mykwargs['expands'].append('badgeclass')
        if 'issuer' in expands:
            mykwargs['expands'].append('issuer')

        return super(BackpackAssertionList, self).get(request, **mykwargs)

    @apispec_post_operation('Assertion',
        summary="Upload a new Assertion to the backpack",
        tags=['Backpack']
    )
    def post(self, request, **kwargs):
        if kwargs.get('version', 'v1') == 'v1':
            try:
                return super(BackpackAssertionList, self).post(request, **kwargs)
            except serializers.ValidationError as e:
                self.log_not_created(e)
                raise e
        raise NotImplementedError("use BackpackImportBadge.post instead")

    def log_not_created(self, error):
        request = self.request
        user = request.user
        image_data = ''
        user_entity_id = ''
        error_name = ''
        error_result = ''

        if request.data.get('image', None) is not None:
            image_data = request.data.get('image', '')[:1024]

        if user is not None:
            user_entity_id = user.entity_id

        if len(error.detail) <= 1:
            #grab first error
            e = error.detail[0]
            error_name = e.get('name', '')
            error_result = e.get('result', '')

        invalid_badge_upload_report = badgrlog.InvalidBadgeUploadReport(image_data, user_entity_id, error_name, error_result)
        logger.event(badgrlog.InvalidBadgeUploaded(invalid_badge_upload_report))

    def get_context_data(self, **kwargs):
        context = super(BackpackAssertionList, self).get_context_data(**kwargs)
        context['format'] = self.request.query_params.get('json_format', 'v1')  # for /v1/earner/badges compat
        return context

class BackpackAssertionDetail(BaseEntityDetailView):
    model = BadgeInstance
    v1_serializer_class = LocalBadgeInstanceUploadSerializerV1
    v2_serializer_class = BackpackAssertionSerializerV2
    permission_classes = (AuthenticatedWithVerifiedIdentifier, VerifiedEmailMatchesRecipientIdentifier, BadgrOAuthTokenHasScope)
    http_method_names = ('get', 'delete', 'put')
    valid_scopes = {
        'get': ['r:backpack', 'rw:backpack'],
        'put': ['rw:backpack'],
        'delete': ['rw:backpack'],
    }

    def get_context_data(self, **kwargs):
        context = super(BackpackAssertionDetail, self).get_context_data(**kwargs)
        context['format'] = self.request.query_params.get('json_format', 'v1')  # for /v1/earner/badges compat
        return context

    @apispec_get_operation('BackpackAssertion',
                           summary="Get detail on an Assertion in the user's Backpack",
                           tags=['Backpack']
                           )
    def get(self, request, **kwargs):
        mykwargs = kwargs.copy()
        mykwargs['expands'] = []
        expands = request.GET.getlist('expand', [])

        if 'badgeclass' in expands:
            mykwargs['expands'].append('badgeclass')
        if 'issuer' in expands:
            mykwargs['expands'].append('issuer')

        return super(BackpackAssertionDetail, self).get(request, **mykwargs)

    @apispec_delete_operation('BackpackAssertion',
                              summary='Remove an assertion from the backpack',
                              tags=['Backpack']
                              )
    def delete(self, request, **kwargs):
        obj = self.get_object(request, **kwargs)
        related_collections = list(BackpackCollection.objects.filter(backpackcollectionbadgeinstance__badgeinstance=obj))

        if obj.source_url is None:
            obj.acceptance = BadgeInstance.ACCEPTANCE_REJECTED
            obj.save()
        else:
            obj.delete()

        for collection in related_collections:
            collection.save()

        request.user.save()
        return Response(status=status.HTTP_204_NO_CONTENT)

    @apispec_put_operation('BackpackAssertion',
                           summary="Update acceptance of an Assertion in the user's Backpack",
                           tags=['Backpack']
                           )
    def put(self, request, **kwargs):
        fields_whitelist = ('acceptance',)
        data = {k: v for k, v in list(request.data.items()) if k in fields_whitelist}

        obj = self.get_object(request, **kwargs)
        if not self.has_object_permissions(request, obj):
            return Response(status=status.HTTP_404_NOT_FOUND)

        context = self.get_context_data(**kwargs)

        update_serializer = BackpackAssertionAcceptanceSerializerV2(obj, data, context=context)
        update_serializer.is_valid(raise_exception=True)
        update_serializer.save(updated_by=request.user)

        main_serializer_class = self.get_serializer_class()
        serializer = main_serializer_class(update_serializer.instance, context=context)

        return Response(serializer.data)

class BackpackAssertionDetailImage(ImagePropertyDetailView, BadgrOAuthTokenHasScope):
    model = BadgeInstance
    prop = 'image'
    valid_scopes = ['r:backpack', 'rw:backpack']

class BackpackCollectionList(BaseEntityListView):
    model = BackpackCollection
    v1_serializer_class = CollectionSerializerV1
    v2_serializer_class = BackpackCollectionSerializerV2
    permission_classes = (AuthenticatedWithVerifiedIdentifier, AuditedModelOwner, BadgrOAuthTokenHasScope)
    valid_scopes = {
        'get': ['r:backpack', 'rw:backpack'],
        'post': ['rw:backpack'],
    }

    def get_objects(self, request, **kwargs):
        return self.request.user.cached_backpackcollections()

    @apispec_get_operation('Collection',
                           summary='Get a list of Collections',
                           tags=['Backpack']
                           )
    def get(self, request, **kwargs):
        return super(BackpackCollectionList, self).get(request, **kwargs)

    @apispec_post_operation('Collection',
                            summary='Create a new Collection',
                            tags=['Backpack']
                            )
    def post(self, request, **kwargs):
        return super(BackpackCollectionList, self).post(request, **kwargs)

class BackpackCollectionDetail(BaseEntityDetailView):
    model = BackpackCollection
    v1_serializer_class = CollectionSerializerV1
    v2_serializer_class = BackpackCollectionSerializerV2
    permission_classes = (AuthenticatedWithVerifiedIdentifier, AuditedModelOwner, BadgrOAuthTokenHasScope)
    valid_scopes = {
        'get': ['r:backpack', 'rw:backpack'],
        'post': ['rw:backpack'],
        'put': ['rw:backpack'],
        'delete': ['rw:backpack']
    }

    @apispec_get_operation('Collection',
                           summary='Get a single Collection',
                           tags=['Backpack']
                           )
    def get(self, request, **kwargs):
        return super(BackpackCollectionDetail, self).get(request, **kwargs)

    @apispec_put_operation('Collection',
                           summary='Update a Collection',
                           tags=['Backpack']
                           )
    def put(self, request, **kwargs):
        return super(BackpackCollectionDetail, self).put(request, **kwargs)

    @apispec_delete_operation('Collection',
                              summary='Delete a collection',
                              tags=['Backpack']
                              )
    def delete(self, request, **kwargs):
        return super(BackpackCollectionDetail, self).delete(request, **kwargs)

class BackpackImportBadge(BaseEntityListView):
    v2_serializer_class = BackpackImportSerializerV2
    permission_classes = (AuthenticatedWithVerifiedIdentifier, BadgrOAuthTokenHasScope,)
    http_method_names = ('post',)
    valid_scopes = ['rw:backpack']

    @apispec_operation(
        summary="Import a new Assertion to the backpack",
        tags=['Backpack'],
        parameters=[
            {
                "in": "body",
                "name": "body",
                "required": True,
                "schema": {
                    "type": "object",
                    "properties": {
                        "url": {
                            "type": "string",
                            "format": "url",
                            "description": "URL to an OpenBadge compliant badge",
                            'required': False
                        },
                        "image": {
                            'type': "string",
                            'format': "data:image/png;base64",
                            'description': "base64 encoded Baked OpenBadge image",
                            'required': False
                        },
                        "assertion": {
                            'type': "json",
                            'description': "OpenBadge compliant json",
                            'required': False
                        },
                    }
                },
            }
        ]
    )
    def post(self, request, **kwargs):
        context = self.get_context_data(**kwargs)
        serializer_class = self.get_serializer_class()
        serializer = serializer_class(data=request.data, context=context)
        serializer.is_valid(raise_exception=True)
        new_instance = serializer.save(created_by=request.user)
        self.log_create(new_instance)

        response_serializer = BackpackAssertionSerializerV2(new_instance, context=context)
        return Response(response_serializer.data, status=status.HTTP_201_CREATED)

class ShareBackpackAssertion(BaseEntityDetailView):
    model = BadgeInstance
    permission_classes = (permissions.AllowAny,)  # this is AllowAny to support tracking sharing links in emails
    http_method_names = ('get',)
    allow_any_unauthenticated_access = True

    def get(self, request, **kwargs):
        """
        Share a single badge to a support share provider
        ---
        parameters:
            - name: provider
              description: The identifier of the provider to use. Supports 'facebook', 'linkedin'
              required: true
              type: string
              paramType: query
        """
        redirect = _scrub_boolean(request.query_params.get('redirect', "1"))

        provider = request.query_params.get('provider')
        if not provider:
            return Response({'error': "unspecified share provider"}, status=status.HTTP_400_BAD_REQUEST)
        provider = provider.lower()

        source = request.query_params.get('source', 'unknown')

        badge = self.get_object(request, **kwargs)
        if not badge:
            return Response(status=status.HTTP_404_NOT_FOUND)

        include_identifier = _scrub_boolean(request.query_params.get('include_identifier', False))

        share = BackpackBadgeShare(provider=provider, badgeinstance=badge, source=source)
        share_url = share.get_share_url(provider, include_identifier=include_identifier)
        if not share_url:
            return Response({'error': "invalid share provider"}, status=status.HTTP_400_BAD_REQUEST)

        share.save()
        logger.event(badgrlog.BadgeSharedEvent(badge, provider, datetime.datetime.now(), source))

        if redirect:
            headers = {'Location': share_url}
            return Response(status=status.HTTP_302_FOUND, headers=headers)
        else:
            return Response({'url': share_url})

class ShareBackpackCollection(BaseEntityDetailView):
    model = BackpackCollection
    permission_classes = (permissions.AllowAny,)  # this is AllowAny to support tracking sharing links in emails
    http_method_names = ('get',)

    def get(self, request, **kwargs):
        """
        Share a collection to a supported share provider
        ---
        parameters:
            - name: provider
              description: The identifier of the provider to use. Supports 'facebook', 'linkedin'
              required: true
              type: string
              paramType: query
        """
        redirect = _scrub_boolean(request.query_params.get('redirect', "1"))

        provider = request.query_params.get('provider')
        if not provider:
            return Response({'error': "unspecified share provider"}, status=status.HTTP_400_BAD_REQUEST)
        provider = provider.lower()

        source = request.query_params.get('source', 'unknown')

        collection = self.get_object(request, **kwargs)
        if not collection:
            return Response(status=status.HTTP_404_NOT_FOUND)

        share = BackpackCollectionShare(provider=provider, collection=collection, source=source)
        share_url = share.get_share_url(provider, title=collection.name, summary=collection.description)
        if not share_url:
            return Response({'error': "invalid share provider"}, status=status.HTTP_400_BAD_REQUEST)

        share.save()

        if redirect:
            headers = {'Location': share_url}
            return Response(status=status.HTTP_302_FOUND, headers=headers)
        else:
            return Response({'url': share_url})


#!/usr/bin/env python
# -*- coding=utf-8 -*-
# Author: kaname
# QQ: 1394041054

""" C4d analyzer """
# RUN:
    # 1. From C4Dloader.py to loading RBAnalzer.py to do it.
    # 2. AnalyzeC4d.py loading C4Dloader.py to do it.

import os
import sys
import subprocess
import string
import logging
import time
import shutil

reload(sys)
sys.setdefaultencoding('utf-8')

from C4d import C4d
from C4dLoader import C4dLoader
from C4dPluginManager import C4dPlugin, C4dPluginMgr
from CommonUtil import RBCommon as CLASS_COMMON_UTIL

class AnalyzeC4d(C4d):
    def __init__(self, **paramDict):
        C4d.__init__(self, **paramDict)
        self.format_log('AnalyzeC4d.init', 'start')

        self.G_TIPS_TXT_NODE=os.path.join(self.G_WORK_RENDER_TASK_CFG, 'tips.json').replace('\\','/')

        for key, value in self.__dict__.items():
            self.G_DEBUG_LOG.info(key + '=' + str(value))

        self.format_log('done','end')

    def RB_CONFIG(self):
        self.G_DEBUG_LOG.info('[.hldoing]')
        self.G_DEBUG_LOG.info('[.配置插件开始]')
        self.G_DEBUG_LOG.info('[C4d.Plugin.config.start......]')

        self.plugin_config()
        self.G_DEBUG_LOG.info('[.hldone]')
        self.G_DEBUG_LOG.info('[.配置插件完成]')
        self.G_DEBUG_LOG.info('[C4d.Plugin.config.end......]')

    def RB_RENDER(self):
        self.G_DEBUG_LOG.info('[c4d.RBanalyse.start.....]')
        self.G_FEE_PARSER.set('render','start_time',str(int(time.time())))

        cg_ver = self.G_CG_VERSION
        task_id = self.G_TASK_ID
        cg_file = self.G_INPUT_CG_FILE
        task_json = self.G_TASK_JSON
        asset_json = self.G_ASSET_JSON
        tips_json = self.G_TIPS_TXT_NODE

        c4d_loader = C4dLoader(cg_ver, task_id, cg_file, task_json, asset_json, tips_json)
        c4d_loader.execute()

        self.G_FEE_PARSER.set('render','end_time',str(int(time.time())))
        self.G_DEBUG_LOG.info('[c4d.RBanalyse.end.....]')


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jan  7 10:43:00 2022

@author: Christopher Corbell
"""

from tttoe.board import Board

class GameTree:
    """
    A GameTree can generate a tree of tic tac toe Board nodes.
    The tree is generate as tiers of boards at each ply.
    Boards are labeled to indicate their paths through the tree.

    Board 'aliases' can be used to prune isomorphic subtrees
    that arise from different parents at the same play;
    only one of such isomorphs is continued, the others have
    their .alias field set to the label of that one for reference.
    This is optional behavior; set 'skipAliases' to True in
    the generateTree() call to identify and skip such isomorphs.

    (Note that isomorphic children of the -same- parent board are always
     skipped, only unique children of each parent are considered)
    """
    def __init__(self, rootBoard:Board=None):
        if None == rootBoard:
            self.root = Board()
            self.root.label = '0'
            self.plies = []
        else:
            self.root = rootBoard
            self.plies = []

    def generateTree(self, skipAliases:bool):

        lastPly = [self.root]
        currentPly = []

        depth = 0
        while depth < 9:

            for parent in lastPly:
                if True == skipAliases:
                    if not (None == parent.alias):
                        print (f"skipping parent {parent.label}, alias of {parent.alias}...")
                        continue

                if parent.isWin():
                    print (f"skipping parent {parent.label}, {parent.winString()}")
                    continue

                #if parent.isDraw():
                #    continue
                children = GameTree.generateChildBoards(parent)
                print (f"...generated {len(children)} child boards from parent {parent.label}")
                currentPly.extend(children)

            if skipAliases:
                GameTree.determineAliases(currentPly)

            self.plies.append(currentPly)
            lastPly = currentPly
            currentPly = []
            depth += 1

    def print_tree_size(self):
        totalSize = 1
        for n in range(0, len(self.plies)):
            print(f"ply {n+1} size: {len(self.plies[n])}")
            totalSize += len(self.plies[n])

        print(f"total tree size (including root, excluding isomorphic branches): {totalSize}")

    def print_tree(self):
        print (self.root)

        for n in range(0, len(self.plies)):
            print ('===========================================')
            print (f'ply {n+1}:')
            for board in self.plies[n]:
                print (board)
                print('')

    def print_ply(self, index):
        if index == 0:
            print ('=========================================== 1 board at root')
            print (f"{self.root}\n")
        else:
            print (f'=========================================== {len(self.plies[index-1])} boards in ply {index}')
            for board in self.plies[index - 1]:
                print(f"{board}\n")

    def generateChildBoards(parent: Board):
        """
        Given a parent game board, generate all of its next-move boards
        up to isomorphism. Boards are canonical and are labeled
        with increasing integers appended to the parent label.
        For example, if parent is labeled '0.3' and there are 4 child
        boards, they will be labeled '0.3.0, '0.3.1', 0.3.2', 0.3.3'.

        Parameters
        ----------
        parent : Board
            A parent board.

        Returns
        -------
        childBoards : [Board]
            A list of all possible child boards (next plays of the game
            from the parent board state) up to isomorphism.

        """
        childBoardCanonicalStrings = []
        blocks = set()

        isPlayingX = parent.nextPlayer() == Board.X_TOKEN
        emptyIndices = parent.empty_indices()

        for playIndex in emptyIndices:
            childBoard = parent.copy()
            if isPlayingX:
                childBoard.xplay(playIndex)
            else:
                childBoard.oplay(playIndex)

            childStr = childBoard.canonicalString()
            if childBoard.block:
                blocks.add(childStr)
            if not childStr in childBoardCanonicalStrings:
                childBoardCanonicalStrings.append(childStr)
            del childBoard

        childBoards = []
        index = 0
        for gridString in childBoardCanonicalStrings:
            child = Board()
            child.grid = list(gridString)
            child.label = parent.label + "." + str(index)
            if gridString in blocks:
                print(f"- block played in board {child.label}")
                child.block = True
            index += 1
            childBoards.append(child)
        return childBoards

    def determineAliases(plyboards):
        """
        Given a list of child-board lists of the same ply,
        determine aliases of isomorphic boards. This assumes
        all boards are already canonical so we can simply compare
        lexical string representation.

        As a subtle improvement, we use the block property of
        each board to prefer blocks as alias targets (so continuing
        isomorphic branches explicitly have blocking plays as parent nodes)
        (A block is a play which removes a winning next-move opportunity)

        Parameters
        ----------
        childBoardLists : [[Board]]
            A list of Board lists, expected to be returned by
            generateChildBoards for the same ply level (game-tree depth)

        Returns
        -------
        None; alias value is set on Board objects passed in

        """

        # resolve aliases to block-play boards first
        block_indices = [idx for idx, element in enumerate(plyboards) if element.block]
        for block_index in block_indices:
            target = plyboards[block_index]
            for otherIndex in range(0, len(plyboards)):
                if otherIndex in block_indices:
                    continue

                other = plyboards[otherIndex]
                if not None == other.alias: # already determined
                    continue
                if target.lexstring() == other.lexstring():
                    other.alias = target.label

        # now resolve everything else
        targetIndex = 0
        for targetIndex in range(0, len(plyboards) - 1):
            target = plyboards[targetIndex]
            if target.block: # already processed
                continue
            if not None == target.alias: # already determined to be alias
                continue

            for laterIndex in range(targetIndex+1, len(plyboards)):
                later = plyboards[laterIndex]
                if not None == later.alias: # already determined
                    continue
                if target.lexstring() == later.lexstring():
                    # found an alias
                    later.alias = target.label


from functions import *
from create_directory import *
from Crypto.Cipher import AES
import os
import shutil
import time

home = user_home()

if os.path.exists(home + "DataShareSecure") == False:
    print("\nNous vous prions de lire le fichier \"Readme.txt\" et de suivre ces consignes.\n")
    sys.exit()

print("BIENVENUE DANS CE PROGRAMME DE DECHIFFREMENT DE FICHIERS\n")

print("######### BON À SAVOIR ##########\n")

print("Vous exécutez ce programme stipule que:\n\n"
      "1- Vous avez pris connaissance du fonctionnement de DataShareSecure grâce au \"Readme.txt\" \n"
      "2- Vous avez exécuté le programme \"Public_Key_Manage.py\" au moins une fois et disposer donc d'une "
                                                        "paire de clés\n"
      "3- Vous désirez déchiffrer des fichiers que vous avez reçus d'un correspondant\n")

print("Si vous ne remplissez pas toutes les conditions du \"BON À SAVOIR\", je vous invite à fermer ce programme.\n"
      "Et à prendre le temps de remplir ces conditions.\n")

choix = input("Remplissez-vous les conditions sus-cités ? (O)ui ou (N)on : ")

if choix == 'O' or choix =='o':
    print("\nBien. Nous pouvons donc continuer\n")

    vide_directory(home + "DataShareSecure/Encrypted")
    vide_directory(home + "DataShareSecure/Decrypted")

    os.chdir(home + "DataShareSecure/Received")

    path = home + 'DataShareSecure/Received/key_used'

    with open(path, "r") as file:
        key_encrypted = file.read()

    key = dechiffrer(key_encrypted)
    buffer_size = 65536  # 64kb

    ########## MOVE FILE ############

    print("######## DECHIFFREMENT DES FICHIERS ET VERIFIVATION DES SIGNATURES ######## \n")

    file_dir = []

    file = [f for f in os.listdir(home + "DataShareSecure/Received") if os.path.isfile(f)]
    for f in file:
        if ".dss" in f:
            shutil.copy(f, home + "DataShareSecure/Encrypted")
        elif ".asc" in f:
            shutil.copy(f, home + "DataShareSecure/Decrypted")

    ########## DECRYPT ###############

    print("\n############# DECHIFFREMENT DES FICHIERS REÇUES ############\n")

    os.chdir(home + "DataShareSecure/Encrypted")

    files_dir = []

    files = [f for f in os.listdir(home + "DataShareSecure/Encrypted") if os.path.isfile(f)]
    for f in files:
        files_dir.append(f)

    for x in files_dir:
        with open(home + "DataShareSecure/Encrypted/" + x, "rb") as f:
            f.seek(0)
            path = home + 'DataShareSecure/Decrypted/' + x
            output_file = open(path[:-4], "wb")
            iv = f.read(16)
            cipher_encrypt = AES.new(key, AES.MODE_CFB, iv=iv)
            buffer = f.read(buffer_size)
            while len(buffer) > 0:
                decrypted_bytes = cipher_encrypt.decrypt(buffer)
                output_file.write(decrypted_bytes)
                buffer = f.read(buffer_size)

    print("Vos fichiers déchiffrés sont enregistrés dans le repertoire \"Decrypted\". \n")

    ########## VERIFY SIGNATURE ###############

    print("\n############ VERIFICATION DES FICHERS REÇUES #################\n")

    os.chdir(home + "DataShareSecure/Decrypted/")

    files_dir = []

    files = [f for f in os.listdir(home + "DataShareSecure/Decrypted/") if os.path.isfile(f)]
    for f in files:
        if ".asc" in f:
            files_dir.append(f)

    for x in files_dir:
        with open(home + "DataShareSecure/Decrypted/" + x, "rb") as f:
            file = x[:-4]
            verified = gpg.verify_file(f, file)
            print(file + " : ", verified.status + "")

    print("\nNOUS VOICI À LA FIN\n")


import nltk
from nltk.tokenize import *
import numpy as np

#--------------------------------------------------------
alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
punctuation = ['?',',','!','.',':',';']

char_count= [0] * len(alphabet)
punctuation_count = [0] * len(punctuation)

#--------------------------------------------------------
#             PART OF SPEECH STUFF
#--------------------------------------------------------
#part of speech ratios + lexical variety
# - determiners
# - prepositions
# - pronouns
# - modal auxiliary-verbs -> CAN, COULD, WILL, WOULD
# - adverbs
# - coord-conjuctions
# - nouns
# - proper-nouns
# - adjectives
# - verbs
# - lexical variety = nouns + proper_nouns + adjectives + verbs + adverbs
pronouns_list = ['PRP', 'PRP$', 'WP', 'WP$']
adverbs_list = ['RB' ,'RBR', 'RBS', 'WRB']
adjectives_list = ['JJ', 'JJR', 'JJS']
verbs_list = ['VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ']

pos_ratios = [0] * 11

avg_sentence_length = 0
avg_word_length = 0
total_words = 0
#--------------------------------------------------------

def main():
    np.set_printoptions(suppress=True)

    features = []

    text = open("training_set\Abraham Lincoln\Abraham Lincoln___Lincoln Letters.txt").read()

    #total useful char
    t_u_c = total_useful_char(text)

    total_puctuation = count_punctuation(text)

    total_words = len(word_tokenize(text))

    #FEATURES 1 - 26
    letters_frequency(text, t_u_c)

    #FEATURES 27 - 32
    punctuation_frequency(text, total_puctuation)

    #FEATIRES 33 - 44
    part_of_speech_ratios(text, total_words)

    #FEATURES 44 - 45
    avg_sentence_length = average_sentence_length(text)
    avg_word_length = average_word_length(text)

    features.extend(char_count)
    features.extend(punctuation_count)
    features.extend(pos_ratios)
    features.append(avg_sentence_length)
    features.append(avg_word_length)
    features.append(total_words)

    features = np.array(features).reshape(-1,1)

    print("\n\n FEATURES final array: \n", features)
    print(features.shape)

def average_word_length(text):

    words = word_tokenize(text)
    sum = 0

    for word in words:
        sum += len(word)

    return sum/len(words)

def average_sentence_length(text):

    sentences = sent_tokenize(text)
    sum = 0

    for sentence in sentences:
        sum += len(word_tokenize(sentence))

    return sum/len(sentences)

def count_punctuation(text):
    return text.count('?') + text.count(',') + text.count('!') + text.count('.') + text.count(':') + text.count(';')

def total_useful_char(text):
    return len(text) - text.count(" ") - text.count("\n")

def letters_frequency(text, tChar):

    for char in text.lower():
        if char in alphabet:
            char_count[alphabet.index(char)] += 1

    for letter in char_count:
        char_count[char_count.index(letter)] /= tChar

def punctuation_frequency(text, total_puctuation):

    for char in text:
        if char in punctuation:
            punctuation_count[punctuation.index(char)] += 1

    for element in punctuation_count:
        punctuation_count[punctuation_count.index(element)] /= total_puctuation

def part_of_speech_ratios(text, total_words):

    words = word_tokenize(text)
    tagged_words = nltk.pos_tag(words)

    # lexical variety = nouns + proper_nouns + adjectives + verbs + adverbs

    for tagged_word in tagged_words:

        is_a_pronoun = [pronoun for pronoun in pronouns_list if(pronoun in tagged_word)]
        is_a_adverb = [adverb for adverb in adverbs_list if(adverb in tagged_word)]
        is_a_adjective = [adjective for adjective in adjectives_list if(adjective in tagged_word)]
        is_a_verb = [verb for verb in verbs_list if(verb in tagged_word)]

        if 'DT' in tagged_word:
            pos_ratios[0] += 1
        elif 'IN' in tagged_word:
            pos_ratios[1] += 1
        elif is_a_pronoun:
            pos_ratios[2] += 1
        elif 'MD' in tagged_word:
            pos_ratios[3] += 1
        elif is_a_adverb:
            pos_ratios[4] += 1
            pos_ratios[10] += 1
        elif 'CC' in tagged_word:
            pos_ratios[5] += 1
        elif ('NN' in tagged_word or 'NNS' in tagged_word):
            pos_ratios[6] += 1
            pos_ratios[10] += 1
        elif ('NNP' in tagged_word or 'NNPS' in tagged_word):
            pos_ratios[7] += 1
            pos_ratios[10] += 1
        elif is_a_adjective:
            pos_ratios[8] += 1
            pos_ratios[10] += 1
        elif is_a_verb:
            pos_ratios[9] += 1
            pos_ratios[10] += 1

    for element in pos_ratios:
        pos_ratios[pos_ratios.index(element)] /= total_words

if __name__ == '__main__':
    main()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar  8 22:42:38 2022

@author: sanggupark
"""

import numpy as np
import traci
from dataclasses import dataclass
import math
from shapely.geometry import LineString, Point
from SimpleMath import create_vehicle_shape

@dataclass(init = True)
class Object_sensed:
    ID: str
    xpos: float
    ypos: float
    vel: float
    angle: float
    width: float
    length: float
    acc_max: float = 4.0
    dec_max: float = 7.0
    dec_min: float = 2.0
    response: float = 0.2
    blinker: int = 0

def lidar_sensing(ego, veh_other):

    xpos = ego.xpos
    ypos = ego.ypos
    length = ego.length
    rad = np.radians(ego.angle)
    p_tail = Point([xpos-(length)*math.sin(rad),
                    ypos-(length)*math.cos(rad)])

    # FOV control
    if "LF" in ego.behavior:
        angles = np.linspace(rad+(ego.sensor.fov/4), rad-(ego.sensor.fov/4), 100)
    elif "LC_R" in ego.behavior:
        angles = np.linspace(rad+(ego.sensor.fov/2.0), rad-(ego.sensor.fov/2.0), 100)
    elif "LC_L" in ego.behavior:
        angles = np.linspace(rad+(ego.sensor.fov/2.0), rad-(ego.sensor.fov/2.0), 100)

    distance = ego.sensor.radius * 1.00
    lines = []
    for angle in angles:
        line = LineString([[p_tail.x, p_tail.y], [p_tail.x + distance*math.sin(angle), p_tail.y + distance*math.cos(angle)]])
        lines.append(line)

    vehicles_sensed = []
    follower = traci.vehicle.getFollower(ego.ID, dist=5.0)[0]

    """ LIDAR Sensing """
    for veh in veh_other:
        is_detected = False
        poly_veh = create_vehicle_shape(veh)
        if veh.ID != ego.ID:
            for line in lines:
                is_detected = poly_veh.intersects(line)
                if is_detected:
                    break
            if is_detected and not (veh.ID == follower):
                vehicles_sensed.append(veh)

    return vehicles_sensed

def blinker_sensing(ego, vehicles_sensed):
    """ Blinker Sensing """
    for veh in vehicles_sensed:
        blinker = traci.vehicle.getSignals(veh.ID)

        # If LF """
        if blinker == 0:
            veh.blinker = 0
        # If LC_R """
        elif blinker == 1:
            veh.blinker = -1
        # If LC_L """
        elif blinker == 2:
            veh.blinker = 1

    return vehicles_sensed

def update_prev_info(ego, vehicles_sensed):
    """ Update Old info """
    for veh in vehicles_sensed:
        if 'auv' in veh.ID:
            object_add = Object_sensed(veh.ID, veh.xpos, veh.ypos, veh.vel, veh.angle, veh.width, veh.length, blinker=veh.blinker)
        elif 'huv' in veh.ID:
            blinker = traci.vehicle.getSignals(veh.ID)

            if blinker == 1:
                blinker = -1
            elif blinker == -1:
                blinker = 1
            else:
                blinker = 0

            object_add = Object_sensed(veh.ID, veh.xpos, veh.ypos, veh.vel, veh.angle, veh.width, veh.length, blinker=-traci.vehicle.getSignals(veh.ID))

        if len(ego.objects_sensed):
            flag = False
            for obj in ego.objects_sensed:
                if obj.ID == object_add.ID:
                    # replacement due to overlaps
                    ego.objects_sensed[np.where(ego.objects_sensed==obj)] = object_add
                    flag = True
            if not flag:
                # add if no overlaps
                ego.objects_sensed = np.append(ego.objects_sensed, object_add)
        else:
            # if the list is empty
            ego.objects_sensed = np.append(ego.objects_sensed, object_add)

    return


from tkinter import *
from tkinter.messagebox import *
def sum():
    r=''
    r=int(e.get())
    if r=='':
        showinfo('messae','Enter the value')
    else:
        t=r*r
        l2.configure(bg='#209f49',text='Area of circle: {:.1f}'.format(t))

root=Tk()
root.title('Calculate')
root.geometry('280x220')
root.configure(bg='white')

l1=Label(text='Enter the radius of circle',font='times 20')
l2=Label(font='times 20')
e=Entry(width=15,bd='5px',font='times 20',bg='#6ec1ff')
b3=Button(root,text='Ok',width=10,font=('times',15,'bold'),bd='3px',bg='#6ec1ff',command=sum)

l2.grid(row=4,column=0)
b3.grid(row=2,column=0)
l1.grid(row=0,column=0)
e.grid(row=1,column=0)
root.mainloop()


'''
eg> nodes
value - key
a     - 5
b     - 15
c     - 3
d     - 10
e     - 25

in huffing tree:
Each node is either a leaf with one of the key and value specified or has 2 children with value '*' and key with value addition of both children node.
This important property will be exploited to make an easy tree

There will be total n leaf nodes and n-1 non-leaf nodes (in our case 5 leaf and 4 non-leaf nodes)

eg. of formed tree

						58
					    (*)
				33			25
				(*)			(E)
		18			15
		(*)			(B)
10			8
(D)		    (*)
		5		3
		(A)		(C)

Array Structure:
	0    1    2    3    4    5    6    7    8
    *    *    E    *    B    D    *    A    C
    58   33   25   18   15   10   8    5    3

'''

data=[
	('a',5),
	('b',15),
	('c',3),
	('d',10),
	('e',25),
]

from operator import itemgetter
data = sorted(data, key = itemgetter(1))
print('INPUT DATA:')
print (data)

data2=[]

while(len(data)>1):
	a=data[0]
	b=data[1]
	c=('*',a[1]+b[1])
	data.pop(0)
	data.pop(0)
	data.append(c)
	data = sorted(data, key = itemgetter(1))
	if(a[0]!='*'):
		data2.append(a)
	if(b[0]!='*'):
		data2.append(b)
	data2.append(c)
#a=data[0]
data.pop(0)
#data2.append(a)
print('\nTREE DATA:')
print(data2)
data2=sorted(data2, key = itemgetter(1))
data2=data2[::-1]
print('\nSORTED TREE DATA or TREE STRUCTURE')
print(data2)

'''
In assembly code this can be achieved by storing all the elements in array and finally sorting them as mentioned in previous assembly functions.

Achieved Array Structure:
	0    1    2    3    4    5    6    7    8
    *    *    E    *    B    D    *    A    C
    58   33   25   18   15   10   8    5    3
'''

###TREE PERCOLATION and CREATING NEW BINARIES
indexes=[1]
for i in range(len(data2)):
	if(data2[i][0]=='*'):
		indexes.append(2*indexes[i])
		indexes.append(2*indexes[i]+1)
print('\nINDICES')
print(indexes)

'''
Data Structures:

	0    1    2    3    4    5    6    7    8

ARRAY
    *    *    E    *    B    D    *    A    C
    58   33   25   18   15   10   8    5    3

INDICES
	1	 2	  3    4	5	 8	  9    18   19

These indices are what should be the actual indices is this was a complete(balanced) binary tree.

						58
					    (*)
						(1)
				33			25
				(*)			(E)
				(2)			(3)
		18			15
		(*)			(B)
		(4)			(5)
10			8
(D)		    (*)
(8)			(9)
		5		3
		(A)		(C)
		(18)	(19)

Now only step left is to find out the frequencies.

Compressed representations will simply be the binary representation of these numbers with the significant bit removed.
eg (For this tree)
letters    freq    index   binary repr.   compressed repr.
a 			5 		18       10010          0010
b 			15      5        101            01
c 			3       19       10011          0011
d 			10      8        1000           000
e 			25      3        11             1

'''
print('\nCompressed bit representations')
for i in range(len(data2)):
	if(data2[i][0]!='*'):
		print(str(data2[i][0])+': '+bin(indexes[i])[3:])

'''
Thanks
~~Work originally done by ANIKET AGRAWAL
~~NOT COPIED FROM ANY SOURCES
'''


# Дано: последовательность строк.
#
# Задание: вы должны объединить эти строки в блок текста, разделив изначальные строки запятыми.
# В качестве шутки над праворукими роботами, вы должны заменить все вхождения слова "right" на слова "left",
# даже если это часть другого слова. Все строки даны в нижнем регистре.

right: str = "right"
left: str = "left"

def is_exist_left(value):
    try:
        value.index(left)
        return True
    except:
        return False

def is_exist_right(value):
    try:
        value.index(right)
        return True
    except:
        return False

value_list: list = ["left", "right", "left", "stop", "bright aright", "ok", "enough", "jokes"]

result: str = ''
for value in value_list:
    if(is_exist_right(value)):
        value = value.replace(right, left)
        result += value + ","
    elif(is_exist_left(value)):
        value = value.replace(left, right)
        result += value + ","
    else:
        result += value + ","

print("Результат: ", result[:-1])