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

# FGGoogleMotionChart.py (python)
# -------------------------------
#
# Display google motion chart based on csv data files
#
# Example of csv file
# -------------------
# filename: user.data.of.eucalyptus.in.india.20110101-20121231.csv
# content:
# name, count, sum, min, avg
# steenoven, 2, 398426.0, 198126.0, 199213.0
# ...
#
# Input (GET/POST)
# ----------------
# metrics
# s_date
# e_date
# title

# https://developers.google.com/chart/interactive/docs/gallery/motionchart
# Note for Developers: Because of Flash security settings, this (and all Flash-based visualizations) might not work correctly when accessed from a file location in the browser (e.g., file:///c:/webhost/myhost/myviz.html) rather than from a web server URL (e.g., http://www.myhost.com/myviz.html). This is typically a testing issue only. You can overcome this issue as described on the Adobe web site.

class FGGoogleMotionChart:
	def display(self, users, s_date):
		from datetime import date, timedelta, datetime

		#Variables
		title = "General%20Utilization%20of%20number%20of%20instances%20of%20eucalyptus%20in%20India"
		gchart_pname = "motionchart"
		gchart_cname = "google.visualization.MotionChart"
		cnt = 0

		# COLUMNS of REPORT
		column_names = ['ownerid', 'instances'] # When we draw graphs/charts we need to show value names. The first line of csv file has column names but we adjust the names here. This would be removed once we have good column names in csv file.
		column_name0 = column_names[0]
		column_name1 = column_names[1]

		# Make tables for the report
		i = 0
		rows = []
		row_size = 0
		s_date = datetime.strptime(s_date, '%Y-%m-%d %H:%M:%S')
		for uname in users:
			rows.append([users[uname]['fullname'], 'new Date(' + s_date.strftime("%Y") + ',' + s_date.strftime("%m") + ')', str(users[uname]['count'])]) # csv_line[0] = ownerId, csv_line[1] = instances
			row_size = row_size + 1

		column_size = 3

		ymd = s_date.strftime("%Y") + "-" + s_date.strftime("%m") + "-" + s_date.strftime("%d")
		gchart_options = """ {};
			options['state'] =
			'{\"xZoomedDataMin\":0,\"yAxisOption\":\"2\",\"yZoomedDataMin\":0,\"time\":\"""" + ymd + """\",\"yLambda\":1,\"iconType\":\"VBAR\",\"nonSelectedAlpha\":0.4,\"xZoomedIn\":false,\"showTrails\":false,\"dimensions\":{\"iconDimensions\":[\"dim0\"]},\"yZoomedIn\":false,\"xZoomedDataMax\":19,\"iconKeySettings\":[],\"xLambda\":1,\"colorOption\":\"2\",\"playDuration\":15000,\"xAxisOption\":\"2\",\"sizeOption\":\"_UNISIZE\",\"orderedByY\":false,\"uniColorForNonSelected\":false,\"duration\":{\"timeUnit\":\"D\",\"multiplier\":1},\"yZoomedDataMax\":139,\"orderedByX\":true};';
			options['width'] = 650;
			options['height'] = 480"""

		# HTML
		output = """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

		  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
		    <title>%(title)s</title>

		"""
		output = output + output_add
		output = output % vars()
		return output


import streamlit as st
import fitz  # PyMuPDF
import io

st.title("Welcome to Legal Translations and Querying by Quantum Games!")

# Upload a PDF document
uploaded_file = st.file_uploader("Upload a PDF document", type=["pdf"])

if uploaded_file is not None:
    st.write("Uploaded PDF:")
    with fitz.open(stream=uploaded_file.read(), filetype="pdf") as doc:
        text = ""
        for page in doc:
            text += page.getText()
        st.write(text)

# Move the "Translate" button inside the Streamlit app
if st.button("Translate"):
    # Add translation logic here (if needed)
    # This block will be executed when the "Translate" button is clicked
    st.write("Translation results go here.")


#!/usr/bin/env python3
print('/INTITIALIZING...')
import boto3
import sys
import datetime
import urllib
import os

ec2r = boto3.resource('ec2')
ec2c = boto3.client('ec2')
s3 = boto3.resource("s3")

print("""...
	/DONE
GENERATING INSTANCE NAME + USERDATA""")

#Create string using date and time, then format it to suit bucket requirements
newBName = 'test-bucket-'+str(datetime.datetime.now())
newBName = newBName.replace("-",".")
newBName = newBName.replace(":",".")
newBName = newBName.replace(" ","-")

print(newBName + """...
	/DONE
/CREATING BUCKET...""")

#Creation of Bucket
try:
	#Create bucket using string
	response = s3.create_bucket(Bucket=newBName, CreateBucketConfiguration={'LocationConstraint':'eu-west-1'})
	print (response)
except Exception as error:
	print (error)

print("""...
	/DONE
/DOWNLOADING FILE...""")

#Downloading file from url
urllib.urlretrieve("http://devops.witdemo.net/image.jpg", "local.jpg")

print("""...
	/DONE
/UPLOADING FILE TO BUCKET...""")

#Uploading file to bucket
s3.meta.client.upload_file("local.jpg", newBName, 'image.jpg', ExtraArgs={'ACL':'public-read'})

print("""...
	/DONE""")

#Assigning UserData code to be executed upon instance start
user_data=	"""#!/bin/bash
sudo yum update -y
sudo yum -y install httpd
systemctl enable httpd
sudo service httpd start
sudo su
cd /var/www/html/
echo '' > index.html
echo '' >> index.html
echo '' >> index.html
echo '
Here is the image:
 ' >> index.html
echo '' >> index.html
echo ' >> index.html"""

#print(user_data)
#keypair = ec2c.create_key_pair(KeyName=newBName)

print("""...
	/DONE
/CREATING EC2 INSTANCE...""")
#Creation of instance
print('/CREATING INSTANCE...')
instance = ec2r.create_instances(
	ImageId='ami-047bb4163c506cd98',
	MinCount=1,
	MaxCount=1,
	KeyName='key',
	SecurityGroupIds=['sg-05b30b49b7d12d1eb'],
	InstanceType='t2.micro',
	UserData = user_data)

print("""...
	/DONE
...
/WAITING FOR INSTANCE TO BE 'RUNNING'""")

instance[0].wait_until_running()
instance[0].reload()
ip=instance[0].public_ip_address
print(ip)
privip=instance[0].private_ip_address
print(privip)
#avzone=instance[0].availability_zone
#print(avzone)

os.system('ssh -i key.pem ec2.user@'+str(ip))
os.system('sudo su')
os.system('cd /var/www/html/')
os.system("echo '
Private IP Address: "+str(instance[0].private_ip_address)+"
' >> index.html")
os.system("echo '
Public IP address: "+str(instance[0].public_ip_address)+"
' >> index.html")
os.system("echo '
Image ID: "+str(instance[0].image_id)+"
' >> index.html")
os.system("echo '
Launch Time: "+str(instance[0].launch_time)+"
' >> index.html")
os.system("echo '
Kernal ID: "+str(instance[0].kernal_id)+"
' >> index.html")
os.system("echo ' >> index.html")

print("""...
	/DONE
...
	/EXITING""")


print('Início do Programa')

import random

arq = open('NUMEROS.txt', 'w')

for i in range(1,2001):
    n = random.randint(1,100000)
    arq.write("{}\n".format(n))

arq.close()

print("{} gravados no arquivo NUMEROS.txt!".format(i))
print('Fim do Programa')


import xarray as xr
import cv2
import sys, os, shutil
import logging
logging.basicConfig(level=logging.INFO)
import numpy as np
import cv2
import pyrealsense2 as rs
import os
import sys
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = os.path.dirname(BASE_DIR)
sys.path.append(ROOT_DIR) # config
sys.path.append(os.path.join(ROOT_DIR, 'utils')) # utils
sys.path.append(os.path.join(ROOT_DIR, 'libs')) # libs
from model_pose_ren import ModelPoseREN
import util
from util import get_center_fast as get_center
import argparse
import os.path
#from sensor_utils import read_bag
import cv2
import sys, os, shutil
from tqdm import tqdm
from graphic_utils import drawAngles, graphicAngles, namejoints, nameangles, segmentImage
import dataset3_utils
from PIL import Image
from graphic_utils import segmentImage, show_results

from numpy import array, int32
import numpy as np
import struct

def pgm_binary_write ( img, filename, maxval ):

    img = int32(img).tolist()
    f = open(filename,'w')
    width = 0
    height = 0
    for row in img:
        height = height + 1
        width = len(row)
    file_handle = open ( filename, 'wb' )
    #
    #  Set up the header.
    #
    pgm_header = "P5 " + str(width) + " " + str(height) + " " + str(maxval) + "\n"
    file_handle.write ( bytearray ( pgm_header, 'ascii' ) )
    #
    #  Convert 2D array to 1D vector.
    #
    grayV = np.reshape ( img, width * height )
    #
    #  Pack entries of vector into a string of bytes, replacing each integer
    #  as an unsigned 1 byte character.
    #
    grayB = struct.pack ( '%sB' % len(grayV), *grayV )
    file_handle.write ( grayB )

    file_handle.close ( )

    return

def pgmwrite(img, filename, maxVal=255, magicNum='P2'):
    """  This function writes a numpy array to a Portable GrayMap (PGM)
    image file. By default, header number P2 and max gray level 255 are
    written. Width and height are same as the size of the given list.
    Line1 : MagicNum
    Line2 : Width Height
    Line3 : Max Gray level
    Image Row 1
    Image Row 2 etc. """
    img = int32(img).tolist()
    f = open(filename,'w')
    width = 0
    height = 0
    for row in img:
        height = height + 1
        width = len(row)
    f.write(magicNum + '\n')
    f.write(str(width) + ' ' + str(height) + '\n')
    f.write(str(maxVal) + '\n')
    for i in range(height):
        count = 1
        for j in range(width):
            f.write(str(img[i][j]) + ' ')
            if count >= 17:
            # No line should contain gt 70 chars (17*4=68)
            # Max three chars for pixel plus one space
                count = 1
                f.write('\n')
            else:
                count = count + 1
    f.write('\n')
    f.close()

def init_device(inputfile):
    try:
        # Create pipeline
        pipeline = rs.pipeline()

        # Create a config object
        config = rs.config()
        # Tell config that we will use a recorded device from filem to be used by the pipeline through playback.
        rs.config.enable_device_from_file(config, inputfile, repeat_playback = False)

        # Configure the pipeline to stream the depth stream
        config.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30)
        config.enable_stream(rs.stream.color, 1920, 1080, rs.format.bgr8, 30)

        # Start streaming from file
        profile = pipeline.start(config)
        depth_sensor = profile.get_device().first_depth_sensor()
        depth_scale = depth_sensor.get_depth_scale()
        print("Depth Scale is: " , depth_scale)
        return pipeline, depth_scale
    except:
        print("can't init device")

# def show_filtered_depth(img):
#     img = np.minimum(img, 450)
#     img = (img - img.min()) / (img.max() - img.min())
#     img = np.uint8(img*255)
#     img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
#     return img

def processBag(input, output, hand='l'):
    colorFrame0 = None
    i=0
    pipeline = rs.pipeline()
    # Create a config object
    config = rs.config()

    # Tell config that we will use a recorded device from file to be used by the pipeline through playback.
    rs.config.enable_device_from_file(config, input, repeat_playback = False)

    # Start streaming from file
    profile = pipeline.start(config)

    depth_sensor = profile.get_device().first_depth_sensor()
    depth_scale = depth_sensor.get_depth_scale()
    print("Depth Scale is: " , depth_scale)

    #step 1: depth images are preprocessed and stored into the list
    depths = list()
    resultlist = list()
    lower_ = 1
    upper_ = 650
    dataset = 'hands17'
    fx, fy, ux, uy = 463.889, 463.889, 320, 240

    #hand_model = ModelPoseREN(dataset,
    #    lambda img: get_center(img, lower=lower_, upper=upper_),
    #    param=(fx, fy, ux, uy), use_gpu=True)
    while True:
        try:
            # Get frameset of depth
            frames = pipeline.wait_for_frames()
        except:
            pipeline.stop()
            break
        frame = frames.get_depth_frame()
        depth_image = np.asarray(frame.get_data(), dtype=np.float32)

        depth = depth_image * depth_scale * 1000

        depth[depth == 0] = 10000
        if hand == 'l':
            depth = depth[:, ::-1]  # flip
        print(depth.min(), depth.max())

        # results, _ = hand_model.detect_image(depth)
        # img_show = show_results(depth, results, dataset)
        # if hand == 'l':
        #     img_show = img_show[:, ::-1]
        # cv2.imshow('result', img_show)
        # k = cv2.waitKey(1)

        depths.append(depth)
    i = 0

    for d in depths:
        result = Image.fromarray(d)
        #bw = result.convert("L")
        pgmwrite(result, output + '/' + str(i) + '.pgm', 1024)
        #result.save(output + '/' + str(i) + '.pgm')
        i += 1

def main(input, hand):
    output ='/media/cejnog/DATA/pgm/' + os.path.splitext(input)[0].split('/')[-1]
    if not os.path.isdir(output):
        os.mkdir(output)
    processBag(input, output, hand)

if __name__ == '__main__':
    for file in sorted(dataset3_utils.bag_files):
        print('/media/cejnog/DATA/pgm/' +  os.path.splitext(dataset3_utils.bag_files[file])[0].split('/')[-1] + '/')
        if os.path.isdir('/media/cejnog/DATA/pgm/' + os.path.splitext(dataset3_utils.bag_files[file])[0].split('/')[-1] + '/'):
            continue

        if os.path.isdir('../../pgm/' + os.path.splitext(dataset3_utils.bag_files[file])[0].split('/')[-1] + '/'):
            continue
        print(file)
        hand = 'l' if 'l' in dataset3_utils.bag_files[file] else 'r'
        main(dataset3_utils.bag_files[file], hand)


def sum_of_dirs(records):
    directories = {'/': [0]}
    path = []
    curr_dir = '/'
    if_ls = False
    for line in records.splitlines():
        line = line.split()
        if line[0] == '$':
            if line[1] == 'cd':
                if_ls = False
                if line[2] != "..":
                    path.append(line[2])
                else:
                    path.pop()
                curr_dir = '/'.join(path)
            else:
                if_ls = True

        else:
            if if_ls:
                if line[0] == 'dir':
                    directories[curr_dir + '/' + line[1]] = [0]
                    for ind, place in enumerate(path):
                        ps = '/'.join(path[0:ind+1])
                        directories[ps].insert(0, (curr_dir + '/' + line[1]))
                else:
                    directories[curr_dir][-1] += int(line[0])

    dirs_sum = 0
    for k, v in directories.items():
        if len(v) == 1:
            if v[0] <= 100000:
                dirs_sum += v[0]
        else:
            suma = v[-1]
            for x in range(0, len(v) - 1):
                suma += directories[v[x]][-1]
            if suma <= 100000:
                dirs_sum += suma

    return dirs_sum

with open('7.txt', 'r') as input_str:
    data = input_str.read()

print(f"part 1. answer: {sum_of_dirs(data)}")


"""
Task:
4. Пользователь вводит целое положительное число.
Найдите самую большую цифру в числе.
Для решения используйте цикл while и арифметические операции.
"""

is_correct = False

number = input("Введите целое положительное число: ")
biggest_digit = 0

# костыль
while not is_correct:
    if not number.isdigit():
        number = input("Пожалуйта, введите число цифрами: ")
        continue
    elif int(number) < 0:
        number = input("Пожалуйта, введите положительное число цифрами: ")
        continue
    else:
        is_correct = True

if len(number) == 1:
    biggest_digit = int(number)
else:
    i = 0
    while i < len(number):
        if biggest_digit > int(number[i]):
            biggest_digit = biggest_digit
        else:
            biggest_digit = int(number[i])

        i = i + 1

print(f"Самая большая цифра: {biggest_digit}")


import numpy as np
import math
import matplotlib.pyplot as plt
from scipy.special import factorial

countOfData = [10, 50, 1000]

plt.suptitle('Normal Distribution')
mu, sigma = 0, 1
for i in range(len(countOfData)):
    plt.subplot(1, 3, i + 1)
    N = np.random.normal(mu, sigma, countOfData[i])
    count, bins, ignored = plt.hist(N, 30, normed=True, edgecolor='black')
    plt.plot(bins, 1 / np.sqrt(2 * np.pi) * np.exp(-(bins ** 2) / 2), linewidth=2, color='r')
    plt.title(r'Normal Distribution: $\mu=0$, $\sigma=1$, N=%i' % countOfData[i])
    plt.xlabel('NormalNumbers')
    plt.ylabel('Density')
    plt.subplots_adjust(wspace=0.5)
plt.show()

plt.suptitle('Laplace Distribution')
mu, sigma = 0, math.sqrt(2)
for i in range(len(countOfData)):
    plt.subplot(1, 3, i + 1)
    L = np.random.laplace(mu, sigma, countOfData[i])
    count, bins, ignored = plt.hist(L, 30, normed=True, edgecolor='black')
    plt.plot(bins, 1 / np.sqrt(2) * np.exp(-np.sqrt(2) * np.fabs(bins)), linewidth=2, color='r')
    plt.title(r'Laplace Distribution: $\mu=0$, $\sigma=1.41$, N=%i' % countOfData[i])
    plt.xlabel('LaplaceNumbers')
    plt.ylabel('Density')
    plt.subplots_adjust(wspace=0.5)
plt.show()

plt.suptitle('Poisson Distribution')
base = 10
for i in range(len(countOfData)):
    plt.subplot(1, 3, i + 1)
    P = np.random.poisson(10, countOfData[i])
    count, bins, ignored = plt.hist(P, 30, normed=True, edgecolor='black')
    plt.plot(bins,  np.exp(-10) * np.power(10, bins) / factorial(bins), linewidth=2, color='r')
    plt.title(r'Poisson Distribution: $base=10$, N=%i' % countOfData[i])
    plt.xlabel('PoissonNumbers')
    plt.ylabel('Density')
    plt.subplots_adjust(wspace=0.5)
plt.show()

plt.suptitle('Cauchy Distribution')
for i in range(len(countOfData)):
    plt.subplot(1, 3, i + 1)
    C = np.random.standard_cauchy(countOfData[i])
    count, bins, ignored = plt.hist(C, 30, normed=True, edgecolor='black')
    plt.plot(bins, 1 / (np.pi * (bins ** 2 + 1)), linewidth=2, color='r')
    plt.title(r'Standard Cauchy Distribution: N=%i' % countOfData[i])
    plt.xlabel('CauchyNumbers')
    plt.ylabel('Density')
    plt.subplots_adjust(wspace=0.5)
plt.show()

plt.suptitle('Uniform Distribution')
a = -np.sqrt(3)
b = np.sqrt(3)
for i in range(len(countOfData)):
    plt.subplot(1, 3, i + 1)
    U = np.random.uniform(-np.sqrt(3), np.sqrt(3), countOfData[i])
    count, bins, ignored = plt.hist(U, 30, normed=True, edgecolor='black')
    ar = np.arange(-3., 3., 0.01)
    listU = []
    for elem in ar:
        listU.append(1 / (2 * np.sqrt(3))) if np.fabs(elem) <= np.sqrt(3) else listU.append(0)
    plt.plot(ar, listU, linewidth=2, color='r')
    plt.title(r'Uniform Distribution: $a=-1.73$, $b=1.73$, N=%i' % countOfData[i])
    plt.xlabel('UniformNumbers')
    plt.ylabel('Density')
    plt.subplots_adjust(wspace=0.9)
plt.show()


from django.shortcuts import render, redirect
from django.http import HttpResponse
from myapp.models import Employee
# Create your views here.
def home(request):
	return render(request, 'home.html')

def submit(request):
	e_name = request.POST.get('name')
	e_salary = request.POST.get('salary')
	try:
		obj = Employee(ename=e_name, esalary=e_salary)
		obj.save()
	except Exception as e:
		print(e)

	return HttpResponse("
Form successfully submitted!
")

def show(request):
	# return render(request,'show.html')
	mydata=Employee.objects.all()
	my_dict={
		'data': mydata
	}

	return render(request,'show.html',my_dict)

def delete(request):
	del_entry = request.POST.getlist('datatodelete')

	for item in del_entry:
		Employee.objects.filter(ename=item).delete()

	return HttpResponse("
Data has been Deleted!
")

def update(request):
	name = request.POST.get('name')
	newsalary = request.POST.get('newsalary')
	Employee.objects.filter(ename=name).update(esalary=newsalary)

	return HttpResponse("
Employee salary has been updated!
")


lst=(input("Please enter a list : ")).split(" ")
src = lst.copy()
rev=[]

while len(src) > 0:
    rev.append(src.pop())

out = ""
for l in lst:
    out = out + str(l) + " "
print(out)

out = ""
for r in rev:
    out = out + str(r) + " "

print(out)


from machine import Pin, ADC, PWM

vret_pin = ADC(Pin(26)) #vret means voltage return and is the voltage on the current sensor resistor side, real vout is vout-vret
vout_pin = ADC(Pin(28)) #the numbers on the pins are the numbers next to GP (general purpose)
vin_pin = ADC(Pin(27))
pwm = PWM(Pin(0))
pwm.freq(100000)
pwm_en = Pin(1, Pin.OUT)

count = 0
pwm_out = 0
pwm_ref = out = 25000
#Ts--> 1 kHz control frequency. It's better to design the control period as integral multiple of switching period.
#e->error; 0->this time; 1->last time; 2->last last time
ui_max=62300 #anti-windup limitation
ui_min=120 #anti-windup limitation
Ts=0.001
kpi=30
kii=50
kdi=0
out1 = 0
e1 = 0
e2 = 0
CL_mode = 1
current_aim = 0.1
current_limit = 0.3

def saturate(duty):
    if duty > 62500:
        duty = 62500 #max duty cycle is set to 95.3% here
    if duty < 100:
        duty = 100 #min duty cycle is set to 0.15% here
    return duty

def saturation(sat_input, uplim, lowlim): # Saturation function
    if sat_input > uplim:
        sat_input = uplim
    elif sat_input < lowlim:
        sat_input = lowlim
    return sat_input

while True:

    pwm_en.value(1)

    vin = ((12490/2490)*3.3)*(vin_pin.read_u16())/(2**16 - 1) #making digital 16-bit measurements into voltage
    vout = ((12490/2490)*3.3)*(vout_pin.read_u16())/(2**16 - 1) #making digital 16-bit measurements into voltage and calculating the voltage vout from the voltage at the pins
    vret = 3.3*(vret_pin.read_u16())/(2**16 - 1) #making digital 16-bit measurements into voltage
    count = count + 1

    actual_vout = vout - vret
    current_ret = vret/1.02 #1.02 is the current sensor resistor value
    actual_current = current_ret

    # Closed Loop Buck
    # The current loop gives a duty cycle demand based upon the error between demanded current and measured current
    # We can/should apply only current pid closed loop and not both voltage pid because the LED works with current and the voltage pid would work well with resistors not LEDS
    if CL_mode == 1: #close loop mode
        current_aim = saturation(current_aim, current_limit, 0)
        e = current_aim - actual_current
        e_integration = e
        if (out1 >= ui_max) or (out1 <= ui_min): #anti-windup, if last-time pid output reaches the limitation, this time there won't be any intergrations.
            e_integration = 0
        dout = kpi * e + kii * Ts * e_integration + kdi / Ts * (e - 2 * e1 + e2)  #incremental PID programming avoids integrations.there is another PID program called positional PID.
        out = out1 + dout #this time's control output
        out = saturation(out, 62500, 100)
        out1 = out # update last time's control output
        e2 = e1  #update last last time's error
        e1 = e  # update last time's error
        pwm_ref = out
    else: #open loop mode
        oc = actual_current - current_limit
        if oc>0:
            pwm_ref = pwm_ref-0.001
        else:
            pwm_ref = pwm_ref+0.001

    pwm_out = saturate(pwm_ref)
    pwm.duty_u16(int(pwm_out))
    pwm_out = pwm_out/(2**16 - 1) #making duty cycle from 0 to 65535 to 0 to 1

    if count > 2000:
        print("Vin = {:.0f}".format(vin)) #This line prints the value of the variable vin to the console. The value is formatted with no decimal places using the "{:.0f}" format specifier.
        print("Vout = {:.0f}".format(vout))
        print("Vret = {:.0f}".format(vret))
        print("Actual_vout = {:.0f}".format(actual_vout))
        print("Actual_current = {:}".format(actual_current))
        print("Duty = {:}".format(pwm_out))

        count = 0

Energy system modules codes/WorkingLEDdriver_final.py


import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix, roc_curve, auc

# Cargamos el conjunto de datos Iris
iris = datasets.load_iris()
X = iris.data
y = iris.target

# Dividimos los datos en conjuntos de entrenamiento y prueba
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

# Estandarizamos las características
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

# Definimos la cuadrícula de hiperparámetros a explorar
param_grid = {'C': [0.1, 1, 10, 100], 'kernel': ['linear', 'rbf', 'poly']}

# Creamos un clasificador SVM
svm = SVC(probability=True)

# Creamos un objeto GridSearchCV para la búsqueda de cuadrícula
grid_search = GridSearchCV(svm, param_grid, cv=5, scoring='accuracy', n_jobs=-1)

# Entrenamos el modelo SVM con búsqueda de cuadrícula
grid_search.fit(X_train, y_train)

# Obtenemos el mejor modelo con los hiperparámetros óptimos
best_svm = grid_search.best_estimator_

print("Parámetros óptimos:", grid_search.best_params_)

# Realizamos predicciones en el conjunto de prueba
y_pred = best_svm.predict(X_test)

# Calculamos la exactitud (accuracy)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)

# Calculamos la matriz de confusión
conf_matrix = confusion_matrix(y_test, y_pred)
print("Confusion Matrix:")
print(conf_matrix)

# Generamos el informe de clasificación
class_report = classification_report(y_test, y_pred)
print("Classification Report:")
print(class_report)

# Calculamos la curva ROC y el área bajo la curva (AUC) para cada clase
n_classes = len(iris.target_names)
fpr = dict()
tpr = dict()
roc_auc = dict()
for i in range(n_classes):
    y_score = best_svm.decision_function(X_test)
    fpr[i], tpr[i], _ = roc_curve((y_test == i).astype(int), y_score[:, i])
    roc_auc[i] = auc(fpr[i], tpr[i])

# Dibujar la curva ROC y mostrar el AUC
plt.figure(figsize=(10, 6))
for i in range(n_classes):
    plt.plot(fpr[i], tpr[i], label=f'ROC curve (class {iris.target_names[i]}) (AUC = {roc_auc[i]:.2f})')
plt.plot([0, 1], [0, 1], 'k--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver Operating Characteristic (ROC)')
plt.legend(loc="lower right")
plt.show()


import sys, os

DOMAIN_ROOT = os.environ.get('DOMAIN_ROOT')
PROJECTNAME = 'myproject'  # fill with your project name
SRCDIR = os.path.join(DOMAIN_ROOT, PROJECTNAME)
VENV = os.path.join(DOMAIN_ROOT, '.virtualenv')
INTERP = os.path.join(VENV, 'bin', 'python3')

if sys.executable != INTERP:
    os.execl(INTERP, INTERP, *sys.argv)

sys.path.insert(0, os.path.join(VENV, 'lib', 'python3.6', 'site-packages'))
sys.path.insert(0, SRCDIR)

# pwd now is the project root directory
os.chdir(SRCDIR)

# Launch the django project
os.environ['DJANGO_SETTINGS_MODULE'] = PROJECTNAME + '.settings'
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()


# -*- coding: utf-8 -*-
import pandas as pd

def main():
    drinks = pd.read_csv("http://logopt.com/data/drinks.csv")
    print(drinks.head())
    print(drinks.groupby("country")[["beer_servings", "spirit_servings", "wine_servings"]].agg("mean"))

if __name__ == '__main__':
    main()


"""jobs URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.auth.views import LogoutView

from job_service.views import main_view, all_vacancies, spec_vacancies, one_vacancy, one_company, \
     custom_handler400, custom_handler403, custom_handler404, custom_handler500, \
     start_create_company, create_company, edit_company, \
     list_vacancy, create_vacancy, edit_vacancy, one_vacancy_send, \
     RegisterView, LoginView, \
     search_vacancies, start_create_resume, create_resume, edit_resume

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', main_view.as_view(), name="main"),
    path('vacancies/<int:vacancy>', one_vacancy.as_view(), name="vac"),
    path('vacancies/<int:vacancy>/send/', one_vacancy_send.as_view(), name="vac_send"),
    path('vacancies/', all_vacancies.as_view()),
    path('vacancies/cat/<str:specialization>', spec_vacancies.as_view()),
    path('companies/<int:company>', one_company.as_view()),
    path('mycompany/letsstart/', start_create_company.as_view()),
    path('mycompany/create/', create_company.as_view(), name="create_company"),
    path('mycompany/', edit_company.as_view(), name="edit_company"),
    path('mycompany/vacancies/', list_vacancy.as_view()),
    path('mycompany/vacancies/create/', create_vacancy.as_view(), name="create_vacancy"),
    path('mycompany/vacancies/<int:vacancy>/', edit_vacancy.as_view(), name="edit_vacancy"),

    path('search', search_vacancies.as_view(), name="search_results"),
    path('myresume/letsstart', start_create_resume.as_view()),
    path('myresume/create', create_resume.as_view(), name="create_resume"),
    path('myresume/', edit_resume.as_view(), name="edit_resume"),

    path('register/', RegisterView.as_view(), name="registration"),
    path('login/', LoginView.as_view(),  name="auth"),
    path('logout/', LogoutView.as_view())

]

handler400 = custom_handler400
handler403 = custom_handler403
handler404 = custom_handler404
handler500 = custom_handler500

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL,
                          document_root=settings.MEDIA_ROOT)


import pathlib
import importlib

def get_files(path):
    path = pathlib.Path(path) if isinstance(path, str) else path
    files = {}
    for p in path.glob("*.py"):
        if "checkpoint" not in p.stem and not p.stem.startswith("_") and p.stem != "manager":
            files[p.stem] = str(p)

    return files

def get_child_folders(location):
    folders = {}
    path = pathlib.Path(location)
    folder_paths = [p for p in path.glob("*/**") if
                        not p.stem.startswith("_") and
                        not p.stem.startswith(".") and
                        '-' not in str(p) and
                        p.parent == path]
    for fp in folder_paths:
        folders[fp.stem] = get_files(fp)

    return folders

def get_spec(file, name):
    return importlib.util.spec_from_file_location(name, file)


# class attribute
class InstanceCounter:
    count = 0

    def __init__(self, val):
        self.val = val
        InstanceCounter.count += 1
        #count +=1  , wrong

    def set_val(self, newval):
        self.val = newval

    def get_val(self):
        return self.val

    def get_count(self):
        return InstanceCounter.count

a = InstanceCounter(5)
print("val of obj: {0}, count: {1}".format(a.get_val(), a.get_count()))

b = InstanceCounter(10)
print("val of obj: {0}, count: {1}".format(b.get_val(), b.get_count()))

c = InstanceCounter(100)
print("val of obj: {0}, count: {1}".format(c.get_val(), c.get_count()))

"""
val of obj: 5, count: 1
val of obj: 10, count: 2
val of obj: 100, count: 3
"""

print(c.count, InstanceCounter.count) # 3, 3
c.count = 10
print(c.count, InstanceCounter.count) # 10, 3


import math
import sys
import os
import datetime

filenames = ['gill3_canon_clusters.txt','legters1_canon_clusters.txt','muller2_canon_clusters.txt']

def main():
	errorToProb = {}
	for fn in filenames:
		f = open(fn, 'r')
		for line in f.readlines():
			tokens = line.split('\t')
			if len(tokens) < 2:
				continue
			probability = tokens[0]
			errorList = tokens[1:]
			errorList.sort()
			error = ''
			for i in range(0,len(errorList)):
				error = error + errorList[i]
				if i < len(errorList)-1:
					error = error + ","
			if error not in errorToProb.keys():
				errorToProb[error] = []
			errorToProb[error].append(probability)

	for er in errorToProb.keys():
		probList = errorToProb[er]
		avgProb = 0.0
		for prob in probList:
			avgProb = avgProb+float(prob)
		avgProb = avgProb/float(len(probList))

		errorList = er.split(',')
		sys.stdout.write(str(avgProb).replace("\n",""))
		sys.stdout.write('\t')
		for i in range(1, len(errorList)):
			sys.stdout.write(errorList[i].replace("\n",""))
			if i < len(errorList)-1:
				sys.stdout.write('\t')
		sys.stdout.write('\n')
		sys.stdout.flush()

if __name__ == "__main__": main()


# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: percent
#       format_version: '1.3'
#       jupytext_version: 1.15.2
#   kernelspec:
#     display_name: Python 3 (ipykernel)
#     language: python
#     name: python3
# ---

# %% [markdown] lang="de" tags=["slide"] slideshow={"slide_type": "slide"}
#
#

#  Erzeugen von Pandas Data Frames
#

#

#
Dr. Matthias Hölzl

#

#
#

# %% tags=["subslide", "keep"] slideshow={"slide_type": "subslide"}
import os
from pathlib import Path

import numpy as np
import pandas as pd

# %% tags=["subslide", "keep"] slideshow={"slide_type": "subslide"}
PANDAS_DIR_FROM_ENV = os.getenv("PANDAS_DIR_PATH")
if PANDAS_DIR_FROM_ENV:
    pandas_dir_path = Path(PANDAS_DIR_FROM_ENV)
else:
    pandas_dir_path = Path("data/pandas").absolute()
print(f"Pandas data: {pandas_dir_path}")

# %% tags=["keep"]
csv_file = pandas_dir_path / "example_data.csv"
excel_file1 = pandas_dir_path / "excel_data.xlsx"
excel_file2 = pandas_dir_path / "excel_other_sheet.xlsx"

# %%
os.listdir(pandas_dir_path)

# %% [markdown] lang="de" tags=["slide"] slideshow={"slide_type": "slide"}
# ## Erzeugen von Data Frames

# %% [markdown] lang="de"
# ### Aus einer Liste oder einem NumPy Array

# %% tags=["keep"]
df = pd.DataFrame([[1, 2], [3, 4], [5, 6], [7, 8]], columns=["A", "B"])

# %%
df

# %%
type(df)

# %% tags=["keep", "subslide"] slideshow={"slide_type": "subslide"}
def create_data_frame():
    rng = np.random.default_rng(42)
    array = rng.normal(size=(5, 4), loc=5.0, scale=2.0)
    index = ["A", "B", "C", "D", "E"]
    columns = ["w", "x", "y", "z"]
    return pd.DataFrame(array, index=index, columns=columns)

# %% tags=["keep", "subslide"] slideshow={"slide_type": "subslide"}
df = create_data_frame()
df

# %% [markdown] lang="de" tags=["slide"] slideshow={"slide_type": "slide"}
# ### Aus einer CSV Datei

# %%
df_csv = pd.read_csv(csv_file)

# %%
df_csv

# %% tags=["subslide"] slideshow={"slide_type": "subslide"}
df_csv = pd.read_csv(csv_file, index_col=0)

# %%
df_csv

# %% [markdown] lang="de" tags=["subslide"] slideshow={"slide_type": "subslide"}
#
# ### Aus einer Datenbank
#
# - Mit `pd.read_sql()` kann man eine SQL Abfrage ausführen und das Ergebnis in einen
#   Data Frame laden.
# - Mit `pd.read_sql_table()` kann man eine SQL Tabelle in einen Data Frame laden.
# - In der SQLite Datenbank `example_data.db` (im Verzeichnis `data/pandas`) ist eine
#   Tabelle `example_data` gespeichert.

# %% tags=["subslide"] slideshow={"slide_type": "subslide"}
#
df_sql = pd.read_sql(
    "SELECT * FROM 'example_data'",
    "sqlite:///data/pandas/example_data.db",
    index_col="index",
)

# %%
df_sql

# %% tags=["subslide"] slideshow={"slide_type": "subslide"}
df_sql2 = pd.read_sql(
    'SELECT * FROM "example_data" WHERE "Col 0" > 0',
    "sqlite:///data/pandas/example_data.db",
    index_col="index",
)

# %%
df_sql2

# %% [markdown] lang="de" tags=["subslide"] slideshow={"slide_type": "subslide"}
#
# - Pandas verwendet SQLAlchemy um auf die Datenbank zuzugreifen.
# - Wir können die Query auch mit SQLAlchemy erzeugen
# - Dabei können wir
#   - die Tabellendefinition aus der Datenbank auslesen
#   - die SQLAlchemy Expression Language verwenden

# %% tags=["subslide"] slideshow={"slide_type": "subslide"}
import sqlalchemy as sa

# %%
engine = sa.create_engine("sqlite:///data/pandas/example_data.db")

# %%
metadata = sa.MetaData()

# %%
example_data_table = sa.Table("example_data", metadata, autoload_with=engine)

# %% [markdown] lang="de" tags=["subslide"] slideshow={"slide_type": "subslide"}
#
# - Query mit SQLAlchemy Expression Language

# %%
with engine.connect() as conn:
    result = conn.execute(
        sa.select(example_data_table).where(example_data_table.c["Col 0"] > 0)
    )
    print(len(result.all()))

# %% [markdown] lang="de" tags=["subslide"] slideshow={"slide_type": "subslide"}
#
# - Einlesen mit `pd.read_sql()` und SQLAlchemy Expression Language

# %%
def_sql3 = pd.read_sql(
    sa.select(example_data_table).where(example_data_table.c["Col 0"] > 0),
    engine,
    index_col="index",
)

# %%
def_sql3

# %% [markdown] lang="de" tags=["subslide"] slideshow={"slide_type": "subslide"}
#
# - Einlesen mit `pd.read_sql_table()`

# %%
df_sql4 = pd.read_sql_table(
    "example_data", "sqlite:///data/pandas/example_data.db", index_col="index"
)

# %%
df_sql4

# %% [markdown] lang="de" tags=["slide"] slideshow={"slide_type": "slide"}
# ### Aus einer Excel Datei

# %%
df_excel = pd.read_excel(excel_file1, index_col=0)

# %%
df_excel

# %% tags=["subslide"] slideshow={"slide_type": "subslide"}
df_excel2 = pd.read_excel(excel_file2)

# %%
df_excel2

# %% tags=["subslide"] slideshow={"slide_type": "subslide"}
df_excel2 = pd.read_excel(
    excel_file2,
    index_col=0,
    sheet_name="Another Sheet",
    header=0,
    skiprows=[1],
)

# %% tags=["subslide"] slideshow={"slide_type": "subslide"}
df_excel2.head(18)

# %% [markdown] lang="de" tags=["slide"] slideshow={"slide_type": "slide"}
#
# ### Andere Formate:
#
# - `pd.read_clipboard`
# - `pd.read_html`
# - `pd.read_json`
# - `pd.read_pickle`
# - `pd.read_sql` (verwendet SQLAlchemy um auf die Datenbank zuzugreifen)
# - ...

# %% [markdown] lang="de" tags=["subslide"] slideshow={"slide_type": "subslide"}
#
# ## Mini-Workshop: Erzeugen von Data Frames
#
# In der Datei `california-housing.csv` (im Verzeichnis `data/pandas`) ist eine Tabelle
# mit Immobilienpreisen in Kalifornien gespeichert. Laden Sie diese Tabelle in einen
# Pandas DataFrame.

# %%
df_california = pd.read_csv(pandas_dir_path / "california-housing.csv", index_col=0)

# %%
df_california

# %% [markdown] lang="de" tags=["subslide"] slideshow={"slide_type": "subslide"}
#
# Die Excel-Datei `housing-data.xlsx` (im Verzeichnis `data/pandas`) enthält zwei
# Sheets: `Boston` und `California`. Laden Sie diese Tabellen in Pandas Data Frames.

# %%
df_boston = pd.read_excel(
    pandas_dir_path / "housing-data.xlsx", sheet_name="Boston", index_col=None
)

# %%
df_boston

# %%
df_california2 = pd.read_excel(
    pandas_dir_path / "housing-data.xlsx",
    sheet_name="California",
    index_col=None,
    skiprows=[1],
)

# %%
df_california2

# %% [markdown] lang="de" tags=["subslide"] slideshow={"slide_type": "subslide"}
#
# In der Datei "weather.db" (im Verzeichnis `data/pandas`) ist eine SQLite Datenbank
# gespeichert. Die Tabelle `weather` enthält Wetterdaten für verschiedene Städte.
# Laden Sie diese Tabelle in einen Pandas Data Frame.
#
# *Hinweis:* Der Connection-String für eine SQLite Datenbank lautet
# `sqlite:///pfad/zur/datei.db`.

# %%
df_weather = pd.read_sql_table("weather", "sqlite:///data/pandas/weather.db")

# %%
df_weather

Python/Folien/Pandas/03 Erzeugen von Pandas Data Frames.py


#!/usr/bin/env

from mysys import read_mysys

MYSYS = read_mysys.read()

def calc_ave_dd(seq, cdt):
    dd = {
        'rg_c_alpha': [1., 'rg'],
        'rg_whole_length': [1., 'rg'],
        'rg_backbone': [1., 'rg'],
        'e2ed': [1., 'e2ed'],
        }                            # ppty_name: [denominator, interested_col]

    if seq in MYSYS:
        dd.update(
            {
                'dssp_E': [float(MYSYS[seq].len), 'structure'],
                'dssp_H': [float(MYSYS[seq].len), 'structure'],
                'dssp_T': [float(MYSYS[seq].len), 'structure'],
                'dssp_G': [float(MYSYS[seq].len), 'structure'],
                'dssp_I': [float(MYSYS[seq].len), 'structure'],
                'dssp_B': [float(MYSYS[seq].len), 'structure'],
                'dssp_C': [float(MYSYS[seq].len), 'structure'],
                'dssp_S': [float(MYSYS[seq].len), 'structure'],
                'dssp_X': [float(MYSYS[seq].len), 'structure'],

                'upup'  : [float(MYSYS[seq].hbg), 'upup' ],

                # g_mindist_excl1 double counts the contact, so divided by 2
                'unun'  : [float(MYSYS[seq].scnpg * 2),'unun'],
                'upun'  : [1., 'upun'],
                'upvp'  : [float(MYSYS[seq].hbg), 'upvp' ],
                'upvn'  : [float(MYSYS[seq].hbg), 'upvn' ],
                'unvp'  : [float(MYSYS[seq].scnpg), 'unvp' ],
                'unvn'  : [float(MYSYS[seq].scnpg), 'unvn' ],

                'cis_x_pro'  : [1, 'cis_x_pro' ],
                'cis_non_x_pro'  : [1, 'cis_non_x_pro' ],
                'trans_x_pro'  : [1, 'trans_x_pro' ],
                'trans_non_x_pro'  : [1, 'trans_non_x_pro' ],
                }
            )

    seqcdt = seq + cdt
    if seqcdt in MYSYS:
        dd.update(
            {
                'upv' : [float(MYSYS[seqcdt].nm_upv), 'upv'],
                'unv' : [float(MYSYS[seqcdt].nm_unv), 'unv'],
                }
            )
    return dd

def calc_alx_dd(seq):
    return {                         # ppty_name: [denominator, x_col, y_col]
        'rg_c_alpha' : [1, 'time', 'rg_c_alpha'],
        'dssp_E'     : [float(MYSYS[seq].len), 'time', 'structure'],
        'conf_entropy' : [1, 'time', 'entropy'],
        'e2ed' : [1, 'time', 'e2ed'],
        'pmf_e2ed' : [1, 'x', 'pmf'],
        'rg_c_alpha': [1., 'time', 'rg'],
        'seqspacing' : [1, 'dij', 'ave_d'],
        # 'rdf_upup': ['radius', 'rdf'],
        # 'rdf_upun': ['radius', 'rdf'],
        # 'rdf_unun': ['radius', 'rdf'],
        # 'rdf_upvp': ['radius', 'rdf'],
        # 'rdf_upvn': ['radius', 'rdf'],
        # 'rdf_unvp': ['radius', 'rdf'],
        # 'rdf_unvn': ['radius', 'rdf'],

        'rdf_un1vn': [1, 'radius', 'rdf'],
        'rdf_un2vn': [1, 'radius', 'rdf'],
        'rdf_un3vn': [1, 'radius', 'rdf'],
        'rdf_un1vp': [1, 'radius', 'rdf'],
        'rdf_un2vp': [1, 'radius', 'rdf'],
        'rdf_un3vp': [1, 'radius', 'rdf'],

        'rdf_c1vn': [1, 'radius', 'rdf'],
        'rdf_c2vn': [1, 'radius', 'rdf'],
        'rdf_c3vn': [1, 'radius', 'rdf'],
        'rdf_c1vp': [1, 'radius', 'rdf'],
        'rdf_c2vp': [1, 'radius', 'rdf'],
        'rdf_c3vp': [1, 'radius', 'rdf'],

        'rg_whole_length': [1., 'time', 'rg'],

        }


DATA_SOURCE = 'stars.speck'
DATA_OUT = 'starsDim.speck'

MAX_LUM = 100

def shouldInclude(b):
	return b < MAX_LUM

outfile = open(DATA_OUT, "w")
outfile.write('# MODIFIED TO OMIT STARS TOO BRIGHT\n\n')

infile = open(DATA_SOURCE, "r")
linesToCopy = 22 #Copy the lines at the top of the file
for line in infile.readlines():
	if linesToCopy > 0:
		linesToCopy -= 1
		outfile.write(line)
		continue

	parts = line.strip().split()
	if shouldInclude(float(parts[4])):
		outfile.write(line)


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

"""
@author: Li Tian
@contact: 694317828@qq.com
@software: pycharm
@file: autoencoder_2.py
@time: 2019/6/21 8:48
@desc: 使用He初始化，ELU激活函数，以及$l_2$正则化构建了一个MNIST栈式自动编码器
"""

import tensorflow as tf
from tensorflow.contrib.layers import fully_connected
from tensorflow.examples.tutorials.mnist import input_data
import matplotlib.pyplot as plt
import sys

n_inputs = 28 * 28      # for MNIST
n_hidden1 = 300
n_hidden2 = 150         # codings
n_hidden3 = n_hidden1
n_outputs = n_inputs

learning_rate = 0.001
l2_reg = 0.001

n_epochs = 30
batch_size = 150

X = tf.placeholder(tf.float32, shape=[None, n_inputs])
with tf.contrib.framework.arg_scope(
    [fully_connected],
    activation_fn=tf.nn.elu,
    weights_initializer=tf.contrib.layers.variance_scaling_initializer(),
    weights_regularizer=tf.contrib.layers.l2_regularizer(l2_reg)
):
    hidden1 = fully_connected(X, n_hidden1)
    hidden2 = fully_connected(hidden1, n_hidden2)   # codings
    hidden3 = fully_connected(hidden2, n_hidden3)
    outputs = fully_connected(hidden3, n_outputs, activation_fn=None)

reconstruction_loss = tf.reduce_mean(tf.square(outputs - X))    # MSE

reg_losses = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)
loss = tf.add_n([reconstruction_loss] + reg_losses)

optimizer = tf.train.AdamOptimizer(learning_rate)
training_op = optimizer.minimize(loss)

init = tf.global_variables_initializer()
saver = tf.train.Saver()

with tf.Session() as sess:
    mnist = input_data.read_data_sets('D:/Python3Space/BookStudy/book2/MNIST_data/')
    init.run()
    for epoch in range(n_epochs):
        n_batches = mnist.train.num_examples // batch_size
        for iteration in range(n_batches):
            print("\r{}%".format(100 * iteration // n_batches), end="")
            sys.stdout.flush()
            X_batch, y_batch = mnist.train.next_batch(batch_size)
            sess.run(training_op, feed_dict={X: X_batch})
        loss_train = reconstruction_loss.eval(feed_dict={X: X_batch})
        print("\r{}".format(epoch), "Train MSE:", loss_train)
        saver.save(sess, "D:/Python3Space/BookStudy/book4/model/my_model_all_layers.ckpt")

# 可视化
def plot_image(image, shape=[28, 28]):
    plt.imshow(image.reshape(shape), cmap="Greys", interpolation="nearest")
    plt.axis("off")

def show_reconstructed_digits(X, outputs, model_path = None, n_test_digits = 2):
    with tf.Session() as sess:
        if model_path:
            saver.restore(sess, model_path)
        X_test = mnist.test.images[:n_test_digits]
        outputs_val = outputs.eval(feed_dict={X: X_test})

    fig = plt.figure(figsize=(8, 3 * n_test_digits))
    for digit_index in range(n_test_digits):
        plt.subplot(n_test_digits, 2, digit_index * 2 + 1)
        plot_image(X_test[digit_index])
        plt.subplot(n_test_digits, 2, digit_index * 2 + 2)
        plot_image(outputs_val[digit_index])
    plt.show()

show_reconstructed_digits(X, outputs, "D:/Python3Space/BookStudy/book4/model/my_model_all_layers.ckpt")


#In case data is passed as a parameter

from sys import argv
#from string import ascii_uppercase

file_name = argv[1]
fp = open(file_name,'r+')

contents = [ line.strip('\n') for line in fp]

#print (contents)

alpha = list(map(chr, range(97, 107)))     #from i to j

for item in contents:

    stack = []
    for c in item:

        try:
            if type(int(c)) ==int:
                stack.append(c)
        except ValueError:
            if c in alpha:
                stack.append(str(alpha.index(c)))

    if len(stack)> 0:
        print (''.join(stack))
    else:
        print ('NONE')

'''
Hidden Digits

Challenge Description:

In this challenge you're given a random string containing hidden and visible digits. The digits are hidden behind lower case latin letters as follows: 0 is behind 'a', 1 is behind ' b ' etc., 9 is behind 'j'. Any other symbol in the string means nothing and has to be ignored. So the challenge is to find all visible and hidden digits in the string and print them out in order of their appearance.
Input sample:

Your program should accept as its first argument a path to a filename. Each line in this file contains a string. You may assume that there will be no white spaces inside the string. E.g.

abcdefghik
Xa,}A#5N}{xOBwYBHIlH,#W
(ABW>'yy^'M{X-K}q,
6240488

Output sample:

For each test case print out all visible and hidden digits in order of their appearance. Print out NONE in case there is no digits in the string. E.g.

012345678
05
NONE
6240488
'''


import logging
import os

HERE = os.path.dirname(__file__)
LOGFILE = os.path.join(HERE, "logfile.txt")

console_handler = logging.StreamHandler()
console_handler.setLevel(logging.DEBUG)
file_handler = logging.FileHandler(LOGFILE)
file_handler.setLevel(logging.INFO)

logging.basicConfig(
    level=logging.DEBUG,
    # format='%(asctime)s %(message)s',
    format=(
        '[%(asctime)s]'
        # ' {%(pathname)s:%(lineno)d}'
        ' %(levelname)s'
        ' - %(message)s'
    ),
    handlers=[console_handler, file_handler]
)

logging.debug("This is a debug log")
logging.info("This is a info log")
logging.warning("This is a warning log")
logging.error("This is a error log")
logging.critical("This is a critical log")


import torch
import torch.nn as nn
from mmcv.runner import BaseModule
from mmdet.models.backbones.resnet import Bottleneck, BasicBlock
from mmcv.cnn import build_norm_layer
from mmdet3d.models import builder

import pdb

class Up(nn.Module):
    def __init__(self, in_channels, out_channels, scale_factor=2, norm_cfg=dict(type='BN')):
        super().__init__()

        self.up = nn.Upsample(scale_factor=scale_factor, mode='bilinear',
                              align_corners=True)

        assert norm_cfg['type'] in ['BN', 'SyncBN']
        if norm_cfg['type'] == 'BN':
            self.conv = nn.Sequential(
                nn.Conv2d(in_channels, out_channels,
                          kernel_size=3, padding=1, bias=False),
                nn.BatchNorm2d(out_channels),
                nn.ReLU(inplace=True),
                nn.Conv2d(out_channels, out_channels,
                          kernel_size=3, padding=1, bias=False),
                nn.BatchNorm2d(out_channels),
                nn.ReLU(inplace=True)
            )
        else:
            self.conv = nn.Sequential(
                nn.Conv2d(in_channels, out_channels,
                          kernel_size=3, padding=1, bias=False),
                build_norm_layer(norm_cfg, out_channels, postfix=0)[1],
                nn.ReLU(inplace=True),
                nn.Conv2d(out_channels, out_channels,
                          kernel_size=3, padding=1, bias=False),
                build_norm_layer(norm_cfg, out_channels, postfix=0)[1],
                nn.ReLU(inplace=True)
            )

    def forward(self, x1, x2):
        x1 = self.up(x1)
        x1 = torch.cat([x2, x1], dim=1)
        return self.conv(x1)

class BevEncode(nn.Module):
    def __init__(self, numC_input, numC_output, num_layer=[2, 2, 2], num_channels=None,
                 backbone_output_ids=None,  norm_cfg=dict(type='BN'), out_with_activision=False,
                 bev_encode_block='BottleNeck', multiview_learning=False, feature_fuse_type='SUM',
                 bev_encoder_fpn_type='lssfpn'):
        super(BevEncode, self).__init__()

        # build downsample modules for multiview learning
        self.multiview_learning = multiview_learning
        if self.multiview_learning:
            downsample_conv_list = []
            for i in range(len(num_layer)-1):
                downsample_conv_list.append(
                    nn.Sequential(
                        nn.Conv2d(numC_input, numC_input * 2**(i+1),
                                  kernel_size=3, stride=2**(i+1), padding=1, bias=False),
                        build_norm_layer(norm_cfg, numC_input *
                                         2**(i+1), postfix=0)[1],
                        nn.ReLU(inplace=True)))
            self.downsample_conv_list = nn.Sequential(*downsample_conv_list)
        self.feature_fuse_type = feature_fuse_type

        # build backbone
        assert len(num_layer) >= 3
        num_channels = [numC_input * 2 ** (i+1) for i in range(
            len(num_layer))] if num_channels is None else num_channels

        # default: [128, 256, 512]

        # 输出最后三层特征
        self.backbone_output_ids = range(len(
            num_layer) - 3, len(num_layer)) if backbone_output_ids is None else backbone_output_ids

        layers = []
        if bev_encode_block == 'BottleNeck':
            curr_numC = numC_input
            for i in range(len(num_layer)):
                layer = [Bottleneck(curr_numC, num_channels[i]//4, stride=2,
                                    downsample=nn.Conv2d(
                                        curr_numC, num_channels[i], 3, 2, 1),
                                    norm_cfg=norm_cfg)]
                curr_numC = num_channels[i]
                layer.extend([Bottleneck(curr_numC, curr_numC//4,
                                         norm_cfg=norm_cfg) for _ in range(num_layer[i]-1)])
                layers.append(nn.Sequential(*layer))

        # [1/2, 1/4, 1/8]
        elif bev_encode_block == 'Basic':
            curr_numC = numC_input
            for i in range(len(num_layer)):
                layer = [BasicBlock(curr_numC, num_channels[i], stride=2,
                                    downsample=nn.Conv2d(
                                        curr_numC, num_channels[i], 3, 2, 1),
                                    norm_cfg=norm_cfg)]
                curr_numC = num_channels[i]
                layer.extend([BasicBlock(curr_numC, curr_numC, norm_cfg=norm_cfg)
                             for _ in range(num_layer[i]-1)])
                layers.append(nn.Sequential(*layer))
        else:
            assert False

        self.layers = nn.Sequential(*layers)

        # build neck
        self.bev_encoder_fpn_type = bev_encoder_fpn_type
        if self.bev_encoder_fpn_type == 'lssfpn':
            self.up1 = Up(num_channels[-1] + num_channels[-3],
                          numC_output * 2, scale_factor=4, norm_cfg=norm_cfg)
        elif self.bev_encoder_fpn_type == 'fpnv1':
            img_neck_cfg = dict(
                type='FPNv1',
                in_channels=num_channels[-3:],
                out_channels=numC_output*2,
                num_outs=1,
                start_level=0,
                out_ids=[0])
            self.up1 = builder.build_neck(img_neck_cfg)
        else:
            assert False
        assert norm_cfg['type'] in ['BN', 'SyncBN']

        if norm_cfg['type'] == 'BN':
            self.up2 = nn.Sequential(
                nn.Upsample(scale_factor=2, mode='bilinear',
                            align_corners=True),
                nn.Conv2d(numC_output * 2, numC_output,
                          kernel_size=3, padding=1, bias=False),
                nn.BatchNorm2d(numC_output),
                nn.ReLU(inplace=True),
            )
        else:
            # 移除掉输出层的 linear conv, 使得输出为激活后的特征值
            self.up2 = nn.Sequential(
                nn.Upsample(scale_factor=2, mode='bilinear',
                            align_corners=True),
                nn.Conv2d(numC_output * 2, numC_output,
                          kernel_size=3, padding=1, bias=False),
                build_norm_layer(norm_cfg, numC_output, postfix=0)[1],
                nn.ReLU(inplace=True),
            )

        self.out_with_activision = out_with_activision
        if not self.out_with_activision:
            self.up2.add_module('4', nn.Conv2d(
                numC_output, numC_output, kernel_size=1, padding=0))
            # self.up2.add_module('linear_output', nn.Conv2d(
            #     numC_output, numC_output, kernel_size=1, padding=0))

        self.fp16_enabled = False

    def forward(self, bev_feat_list):
        feats = []
        x_tmp = bev_feat_list[0]
        for lid, layer in enumerate(self.layers):
            x_tmp = layer(x_tmp)
            # x_tmp = checkpoint.checkpoint(layer,x_tmp)
            if lid in self.backbone_output_ids:
                feats.append(x_tmp)
            if lid < (len(self.layers)-1) and self.multiview_learning:
                if self.feature_fuse_type == 'SUM':
                    bev_feat_from_img_view = bev_feat_list[lid + 1]
                    bev_feat_from_img_view = self.downsample_conv_list[lid](
                        bev_feat_from_img_view)
                    x_tmp = x_tmp + bev_feat_from_img_view
                else:
                    assert False

        if self.bev_encoder_fpn_type == 'lssfpn':
            res = self.up1(feats[-1], feats[-3])
        elif self.bev_encoder_fpn_type == 'fpnv1':
            res = self.up1(feats)
        else:
            assert False

        res = self.up2(res)

        return res


# -*- coding: utf-8 -*-

"""Implementation of ApiException."""

import typing
from typing import Optional

from nisystemlink.clients import core

class ApiException(Exception):
    """Represents errors that occur when calling SystemLink APIs."""

    def __init__(
        self,
        message: Optional[str] = None,
        error: Optional[core.ApiError] = None,
        http_status_code: Optional[int] = None,
        inner: Optional[Exception] = None,
    ) -> None:
        """Initialize an exception.

        Args:
            message: The message describing the error.
            error: The error returned by the API.
            http_status_code: The HTTP status code, if this exception was the result of
                an HTTP error.
            inner: The inner exception that caused the error.
        """
        self._message = message
        self._error = error
        self._http_status_code = http_status_code
        self._inner = inner

    @property
    def message(self) -> Optional[str]:  # noqa:D401
        """The error message."""
        return self._message

    @property
    def error(self) -> Optional[core.ApiError]:  # noqa: D401
        """The error information returned by the SystemLink API, or None if the API did
        not return one or the error occurred trying to call the API.
        """
        if self._error is None:
            return None
        else:
            return self._error.copy()

    @property
    def http_status_code(self) -> Optional[int]:  # noqa: D401
        """The HTTP status code, if this exception was the result of an HTTP error."""
        return self._http_status_code

    @property
    def inner_exception(self) -> Optional[Exception]:  # noqa: D401
        """The exception that caused this failure, if any."""
        return self._inner

    def __str__(self) -> str:
        txt = self._message or "API exception occurred"
        if self._error:
            txt += "\n\n" + str(self._error)
        return txt

    def __eq__(self, other: object) -> bool:
        other_ = typing.cast(ApiException, other)
        return all(
            (
                isinstance(other, ApiException),
                self._message == other_._message,
                self._error == other_._error,
                self._http_status_code == other_._http_status_code,
                self._inner == other_._inner,
            )
        )

    def __hash__(self) -> int:
        return hash((self._message, self._error, self._inner))


from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
from datetime import datetime
import pickle

# Checks ID from pre-polled list
def check_ID(card_id):
    with open('ids.txt', 'rb') as filehandle:
        ids_list = pickle.load(filehandle)

    card_id = str(card_id)  # placeholder

    if card_id in ids_list:
        return True
    else:
        return False

# Upon pour, updates google sheet with pour information

def gs_pour(card_id, pour_amount):

    # the following block sets up the spreadsheet API and connects to spreadsheet
    time_now = datetime.now().strftime('%Y-%m-%d %H:%M')
    SCOPES = 'https://www.googleapis.com/auth/spreadsheets'
    store = file.Storage('token.json')
    creds = store.get()
    # if no creds, generates them
    if not creds or creds.invalid:
        flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
        creds = tools.run_flow(flow, store)
    # builds spreadsheet service
    service = build('sheets', 'v4', http=creds.authorize(Http()))

    SPREADSHEET_ID = '1hopTf_z_OzquBngV11XTryX9qX4AiYPi1hsOucpfVbk'
    TOTAL_BEERS_RANGE = 'keg_contents!A2:C'
    keg_update = {
        'majorDimension': 'COLUMNS',
        'values': [
            [card_id],
            [pour_amount],
            [time_now]
        ]
    }
    # put the data into the sheet
    new_beers_resp = service.spreadsheets().values().append(spreadsheetId=SPREADSHEET_ID, range=TOTAL_BEERS_RANGE,
                                                            body=keg_update, valueInputOption='RAW', insertDataOption='OVERWRITE').execute()
    return


def grade(n):
    # print(input("수행점수를 입력하시오"))
    if n > 90:
        return ("A")
    elif n > 70:
        return ("B")
    elif n > 60:
        return ("C")
    elif n > 50:
        return ("D")
    else:
        return ("F")

#    90점 이상이면 A, 70점 이상이면 B, 60점 이상이면 C,
#     50점 이상이면 D, 그 외에는 F를 반환하는 함수를 작성하시오.
#     단, 점수 n은 0이상 100이하의 정수이다.

    # return "Z"

for n in [100, 95, 27, 44, 56, 62, 50, 70, 0]:
    print("%3d --> %s" % (n, grade(n)))

""" 수행 예:
100 --> A
 95 --> A
 27 --> F
 44 --> F
 56 --> D
 62 --> C
 50 --> D
 70 --> B
  0 --> F
"""


from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium import webdriver
import time
import collections
import unittest

collections.Callable = collections.abc.Callable

class form_User_Test(unittest.TestCase):

    def setUp(self):
        chrome_driver_path = "/home/vboxuser/Descargas/dchrome/chromedriver"
        webdriver.chrome.driver = chrome_driver_path

    def test_form(self):
        driver = webdriver.Chrome()
        driver.get("https://memo.mrbotcr.com/login")

        # Inicio de sesión
        usuario = driver.find_element(By.NAME, "email")
        usuario.send_keys("yarifp214@gmail.com")
        usuario.send_keys(Keys.ENTER)
        clave = driver.find_element(By.NAME, "passwd")
        clave.send_keys(".Maria25A")
        clave.send_keys(Keys.ENTER)
        time.sleep(3)
        driver.get("https://memo.mrbotcr.com/user/yarifp18/forms")
        time.sleep(3)
        titulo = driver.find_element(By.NAME, "form_name")
        titulo.send_keys("mrbot")
        Descrip = driver.find_element(By.NAME, "form_desc")
        Descrip.send_keys("848484")
        time.sleep(3)

        #1
        select = Select(driver.find_element(By.XPATH, '//*[@id="multimedia"]'))

        select.select_by_value("4")

        other_element = driver.find_element(By.XPATH, '//*[@id="multimedia"]')
        other_element.send_keys(Keys.ENTER)

        time.sleep(2)
        # Espera a que el segundo menú desplegable sea visible y pueda interactuar con él
        WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, '//*[@id="multimedia"]')))

        # 2
        select1 = Select(driver.find_element(By.XPATH, '//*[@id="form_cloned"]'))

        select1.select_by_value("c96820da-6f5b-11ed-97d2-371f69c2d1de")

        other_element1 = driver.find_element(By.XPATH, '//*[@id="form_cloned"]')
        other_element1.send_keys(Keys.ENTER)

        time.sleep(2)
        # Espera a que el segundo menú desplegable sea visible y pueda interactuar con él
        WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, '//*[@id="form_cloned"]')))

        click_derecho = driver.find_element(By.NAME, "btn_save_form")
        click_derecho.click()
        time.sleep(20)
        driver.quit()

if __name__ == '__main__':
    unittest.main()


# Author: Ronald Yip
# First draft: Dec 2022
# Last update: Dec 2022
# Note: the response capture in implemented  with selenium-wire and indeed selenium better their BiDidirectional API for Python in the future

from seleniumwire import webdriver
from seleniumwire.webdriver import Chrome
import seleniumwire as selenium

import gzip
import zlib
import brotli

import warnings
import datetime
import re
import json
import time
from urllib.parse import urlparse
from urllib.parse import urljoin

class Browser(Chrome):
    def get(self, url: str):
        del self.requests
        if url[0:1] == '/' and re.search('[^:]+://.+', self.current_url):
            uri = urlparse(self.current_url)
            url = urljoin('{uri.scheme}://{uri.netloc}/'.format(uri=uri), url)
        return super().get(url)

    def retry(self, url: str, max_attempt: int = 3, cooldown: int = 3, cooldown_pow = 2):
        for i in range(0, max_attempt):
            try:
                time.sleep(cooldown * (i ** cooldown_pow))
                r = self.get(url)
                return r
            except Exception as e:
                warnings.warn(str(e), stacklevel=2)
            raise Exception(f'retry failed for {url}')

    def retry_until_requests(self, url: str, pat: str = '', timeout: [int, float] = 20, max_attempt: int = 4, cooldown: int = 3, timeout_pow = 0.75, cooldown_pow = 2):
        for i in range(0, max_attempt):
            time.sleep(cooldown * (i ** cooldown_pow))
            try:
                self.get(url)
                r = self.wait_for_request(pat, timeout * ((i+1) ** timeout_pow))
                return r
            except Exception as e:
                warnings.warn(str(e), stacklevel=2)
        raise Exception(f'wait_for_request failed for {url}')

    def retry_until_no_request(self, url: str, pat: str = '', timeout: [int, float] = 20, timer: int = 2, max_attempt: int = 4, cooldown: int = 3, check_interval = 0.1, timeout_pow = 0.75, cooldown_pow = 2):
        for i in range(0, max_attempt):
            time.sleep(cooldown * (i ** cooldown_pow))
            self.get(url)
            start_time = datetime.datetime.now()
            while (datetime.datetime.now() - start_time).total_seconds() <= timeout * ((i+1) ** timeout_pow):
                r = ([None] + [r for r in self.requests if re.search(pat, r.url) and r.response and r.response.status_code < 300])[-1]
                if r and r.response and (datetime.datetime.now() - r.response.date).total_seconds() > timer:
                    return [r for r in self.requests if re.search(pat, r.url)]
                time.sleep(check_interval)
            warnings.warn(f'Timed out after {timeout * ((i+1) ** timeout_pow)}s waiting for request matching {pat}', stacklevel=2)

        raise Exception(f'retry_until_no_request failed for {url}')

    def archive_mhtml(self, filename):
        with open(filename, 'wb') as f:
            f.write(bytes(self.execute_cdp_cmd('Page.captureSnapshot', {})['data'], 'utf-8'))

def summarize_response(r):
    decoder_map = {k: v.decompress for k,v in {'br': brotli, 'gzip': gzip, 'deflate': zlib}.items()}
    decoder = decoder_map.get(r.response.headers.get('content-encoding')) or (lambda _:_)
    charset = (re.search('charset=([^;]*)', r.headers.get('content-type') or '') or [None,'utf-8'])[1]
    decoded_response = None
    try:
        decoded_response = decoder(r.response.body).decode(encoding=charset)
    except Exception:
        warnings.warn(f'Error decoding response from {r.url}, original bytes used instead', stacklevel=2)
        decoded_response = str(r.response.body)
    return {'url': r.url, 'method': r.method, 'payload': r.body.decode(),
          'status_code': r.response.status_code, 'response': decoded_response}

def archive_response(response, filename):
    cache = [summarize_response(r) for r in response] if type(response) == list else summarize_response(r)
    with open(filename, 'wb') as f:
        f.write(bytes(json.dumps(cache), 'utf-8'))

def alloc_browser(headless=True):
    options = webdriver.ChromeOptions()
    options.add_argument("--no-sandbox")
    options.headless = headless
    driver = webdriver.Chrome(options=options)
    driver.__class__ = Browser
    return driver


# STaTE
# File: tc/views.py
# Purpose: This file defines what html file and data to return when an http request is made to the tc Django app

from django.db import models
from django.contrib import messages
from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import Group, User
from django.http import HttpResponse
from django.shortcuts import render, redirect, get_object_or_404

from .forms import ClassForm, ClassEditForm, SimEditForm, MissionEditForm
from .models import TestConductor, Class
from simapp.models import Sim, Mission

import json
import numpy
import random
import string
import threading
import time

###############################################################################
def index(request):

    if request.user.is_authenticated and request.user.is_staff:
        return redirect('tc:home')
    else:
        return redirect('home:login')

###############################################################################
@login_required(login_url='/login/')
@staff_member_required
def tcHome(request):

    classes = Class.objects.all()

    # Create new TestConductor object if none exists for current staff user
    if not TestConductor.objects.filter(user = request.user).exists():
        TestConductor.objects.create(user = request.user).save()
    tcobj = TestConductor.objects.get(user = request.user)

    if request.method == 'POST':
        form = ClassForm(request.POST)
        classes1 = Class.objects.all()
        classes = numpy.asarray(classes1)
        var = False
        if(form.is_valid()):
            class_namef = form.cleaned_data.get('class_name')
            nospacename = class_namef.replace(" ", "")
            test = form.cleaned_data.get('test')
            missions = numpy.asarray(request.POST.getlist('missions'))
            classesstr = str(classes)

            ifequal = 0
            for classi in classes:
                classstr = str(classi)
                if(str(classstr) == nospacename):
                    ifequal = ifequal+1

            if(len(classes)<=0):
                form.save()
                classget = Class.objects.get(class_name = class_namef)
                nospacename = class_namef.replace(" ", "")
                rcg = ''.join(random.choices(string.ascii_uppercase +string.digits, k=8))
                classget.class_name = nospacename
                classget.code = rcg
                classget.tc.add(tcobj)
                if(len(numpy.asarray(request.POST.getlist('missions'))))>=1:
                    for x in missions:
                        classget.missions.add(x)
                classget.save()
                tcobj = TestConductor.objects.get(user = request.user)
                tcobj.classes.add(classget)
                tcobj.save()
                return redirect('tc:home')
            elif(len(classes)>0 and ifequal==0 and test==True):
                form.save()
                classget = Class.objects.get(class_name = class_namef)
                nospacename = class_namef.replace(" ", "")
                rcg = ''.join(random.choices(string.ascii_uppercase +string.digits, k=8))
                classget.class_name = nospacename
                classget.code = rcg
                classget.tc.add(tcobj)
                if(len(numpy.asarray(request.POST.getlist('missions'))))>=1:
                    for x in missions:
                        classget.missions.add(x)
                classget.save()
                classget.save()
                tcobj = TestConductor.objects.get(user = request.user)
                tcobj.classes.add(classget)
                tcobj.save()
                return redirect('tc:home')
            elif(len(classes)>0 and ifequal>=1 and test ==True):
               messages.info(request, 'Class Already Exists. Add Class UNSUCCESSFUL')
               return redirect('tc:home')
    else:
        form = ClassForm()

    if request.method == 'POST':
        form2 = ClassEditForm(request.POST)
        classes1 = Class.objects.all()
        classes = numpy.asarray(classes1)
        if(form2.is_valid()):
            class_namef = form.cleaned_data.get('class_name')
            test = form2.cleaned_data.get('test')
            delete = form2.cleaned_data.get('delete')
            randomizecode = form2.cleaned_data.get('randomizecode')

            ifequal = 0
            for classi in classes:
                classstr = str(classi)
                if(str(classstr) == class_namef):
                    ifequal = ifequal+1

            if(len(classes)>0 and ifequal>=1):
                for classi in classes:
                    if(str(classi) == class_namef):
                        classget = Class.objects.get(class_name = class_namef)
                        if(delete==False):
                            if(randomizecode == False):
                                if(len(form2.cleaned_data.get('code'))>0):
                                    classget.code = form2.cleaned_data.get('code')
                                    if(len(numpy.asarray(request.POST.getlist('missions'))))>=1:
                                        classget.missions.add(numpy.asarray(request.POST.getlist('missions')))
                                    classget.save()
                                    return redirect('tc:home')
                                else:
                                    if(len(numpy.asarray(request.POST.getlist('missions'))))>=1:
                                        for x in missions:
                                            classget.missions.add(x)
                                    classget.save()
                                    return redirect('tc:home')
                            elif(randomizecode == True and (len(form2.cleaned_data.get('code'))>=1)):
                                 messages.info(request, 'Cannot enter code and randomize code. Please make one choice. Edit Unsuccessful.')
                            else:
                                rcg = ''.join(random.choices(string.ascii_uppercase +string.digits, k=8))
                                classget.code = rcg
                                if(len(numpy.asarray(request.POST.getlist('missions'))))>=1:
                                    for x in missions:
                                        classget.missions.add(x)
                                classget.save()
                                return redirect('tc:home')
                        else:
                            classget.delete()

            return redirect('tc:home')
    else:
        form2 = ClassEditForm()

    return render(request, 'tc/tcHome.html', {"classes":classes, 'form': form, 'form2': form2, 'tcobj':tcobj})

###############################################################################
@login_required(login_url='/login/')
@staff_member_required
def classHome(request, class_name):

    group = Class.objects.all().filter(class_name = class_name).values_list('sims', flat=True)
    data = numpy.asarray(group)
    if (data.all()!=None):
        sims = ['']*(len(data))
        for e in range(len(data)):
            sims[e] = Sim.objects.get(pk=data[e])
    else:
        sims=[]
    #############################################################################
    group2 = Class.objects.all().filter(class_name = class_name).values_list('missions', flat=True)
    data2 = numpy.asarray(group2)
    if (data2.all()!=None):
        missions = ['']*(len(data2))
        for e in range(len(data2)):
            missions[e] = Mission.objects.get(pk=data2[e])
    else:
        missions=[]

    ######################sim edit page#########################################
    if request.method == 'POST' and request.POST.get("form_type") == 'formOne':
        form3 = SimEditForm(request.POST)
        if(form3.is_valid()):
            sim_namef = request.POST.get('sim_name')
            delete = form3.cleaned_data.get('delete')
            simget = Class.objects.get(class_name = class_name).sims.get(sim_name=sim_namef)
            if(delete==False):
                simget.save()
            else:
                simThread = None
                thread_id = simget.sim_identifier
                for thread in threading.enumerate():
                    if thread.ident == thread_id:
                        simThread = thread
                if simThread != None:
                    simThread.stop()
                    simThread.join()
                simget.delete()
        return redirect('../home/'+class_name)
    else:
        form3 = SimEditForm()

    ###############################################################################
    if request.method == 'POST' and request.POST.get("form_type") == 'formTwo':
        form4 = MissionEditForm(request.POST)
        if(form4.is_valid()):
            mission_namef = request.POST.get('missionname')
            delete = form4.cleaned_data.get('delete')
            missionget = Mission.objects.get(mission_name = mission_namef)
            if(delete==False):
                missionget.save()
            else:
                missionget.delete()
        return redirect('../home/'+class_name)
    else:
        form4 = MissionEditForm()
########################################################
    # 3/5/23 Removed "missions":missions
    return render(request, 'tc/classHome.html', {"class_name": class_name, "sims":sims, "missions":missions, "form3":form3, "form4":form4})

###############################################################################
def getGroups(request):

    group = list(request.user.groups.values_list('name', flat = True))
    data = numpy.asarray(group)
    return render(request, 'tc: home.html', {"data":data})

def downloadSimReport(request):
    if request.method == 'GET':
        simkey= request.GET.get('simkey')
        sim = get_object_or_404(Sim, pk = simkey)

        # Get simcraft thread
        simThread = None
        thread_id = sim.sim_identifier
        for thread in threading.enumerate():
            if thread.ident == thread_id:
                simThread = thread

        data = {}
        data['sim_name'] = sim.sim_name
        data['report'] = 'Report for Simulation: ' + sim.sim_name + '\n\n'

        if simThread != None:

            # Add ACS FO and Console Log
            data['report'] += 'Report for ACS subsytem: \n'
            data['report'] += '\tACS Flight Operator: ' + str(sim.ACS_fo) + '\n'
            data['report'] += '\tACS Console Log:\n'
            for item in simThread.subsystems['ACS'].consoleLog:
                data['report'] += '\t\t' + item + '\n'
            data['report'] += '\n'

            # Add EPS FO and Console Log
            data['report'] += 'Report for EPS subsytem: \n'
            data['report'] += '\tEPS Flight Operator: ' + str(sim.EPS_fo) + '\n'
            data['report'] += '\tEPS Console Log:\n'
            for item in simThread.subsystems['EPS'].consoleLog:
                data['report'] += '\t\t' + item + '\n'
            data['report'] += '\n'

            # Add TCS FO and Console Log
            data['report'] += 'Report for TCS subsytem: \n'
            data['report'] += '\tTCS Flight Operator: ' + str(sim.TCS_fo) + '\n'
            data['report'] += '\tTCS Console Log:\n'
            for item in simThread.subsystems['TCS'].consoleLog:
                data['report'] += '\t\t' + item + '\n'
            data['report'] += '\n'

            # Add COMMs FO and Console Log
            data['report'] += 'Report for Comms subsytem: \n'
            data['report'] += '\tComms Flight Operator: ' + str(sim.COMMS_fo) + '\n'
            data['report'] += '\tComms Console Log:\n'
            for item in simThread.subsystems['COMMS'].consoleLog:
                data['report'] += '\t\t' + item + '\n'
            data['report'] += '\n'

            # Add Payload FO and Console Log
            data['report'] += 'Report for Payload subsytem: \n'
            data['report'] += '\tPayload Flight Operator: ' + str(sim.flight_director) + '\n'
            data['report'] += '\tPayload Console Log:\n'
            for item in simThread.subsystems['Payload'].consoleLog:
                data['report'] += '\t\t' + item + '\n'
            data['report'] += '\n'

        return HttpResponse(json.dumps(data)) # Sending an success response
    else:
        return HttpResponse("Request method is not GET")

###############################################################################
@login_required(login_url='/login/')
@staff_member_required
def tcSim(request, simkey):
    return redirect('tc:acs', simkey)

###############################################################################
@login_required(login_url='/login/')
@staff_member_required
def acs(request, simkey):

    simobj = get_object_or_404(Sim, pk = simkey)
    return render(request, 'tc/acs.html', {'sim': simobj, 'simkey': simkey})

###############################################################################
@login_required(login_url='/login/')
@staff_member_required
def eps(request, simkey):

    simobj = get_object_or_404(Sim, pk = simkey)
    return render(request, 'tc/eps.html', {'sim': simobj, 'simkey': simkey})

###############################################################################
@login_required(login_url='/login/')
@staff_member_required
def tcs(request, simkey):

    simobj = get_object_or_404(Sim, pk = simkey)
    return render(request, 'tc/tcs.html', {'sim': simobj, 'simkey': simkey})

###############################################################################
@login_required(login_url='/login/')
@staff_member_required
def payload(request, simkey):

    simobj = get_object_or_404(Sim, pk = simkey)
    return render(request, 'tc/payload.html', {'sim': simobj, 'simkey': simkey})

###############################################################################
@login_required(login_url='/login/')
@staff_member_required
def comms(request, simkey):

    simobj = get_object_or_404(Sim, pk = simkey)
    return render(request, 'tc/comms.html', {'sim': simobj, 'simkey': simkey})

###############################################################################
def acsFetchdata(request, simkey):
    if request.method == 'GET':
        sim = get_object_or_404(Sim, pk = simkey)

        # Get simcraft thread
        simThread = None
        thread_id = sim.sim_identifier
        for thread in threading.enumerate():
            if thread.ident == thread_id:
                simThread = thread

        data = {}

        if simThread != None:
            # Define data to be returned

            data['roll'] = simThread.subsystems['ACS'].orientation['roll']
            data['pitch'] = simThread.subsystems['ACS'].orientation['pitch']
            data['yaw'] = simThread.subsystems['ACS'].orientation['yaw']
            data['longitude'] = simThread.subsystems['ACS'].currentLongitude

            data['cmg_roll'] = simThread.subsystems['ACS'].rollActive
            data['cmg_pitch'] = simThread.subsystems['ACS'].pitchActive
            data['cmg_yaw'] = simThread.subsystems['ACS'].yawActive

            data['cmg_status'] = simThread.subsystems['ACS'].cmgStatus
            data['orientation_relay'] = simThread.subsystems['ACS'].orientationRelay

            data['telemetry_Transferring'] = simThread.subsystems['ACS'].telemetryTransferring
            data['telemetry_Transferred'] = simThread.subsystems['ACS'].telemetryTransferComplete

        return HttpResponse(json.dumps(data)) # Sending an success response
    else:
        return HttpResponse("Request method is not GET")

###############################################################################
def epsFetchdata(request, simkey):
    if request.method == 'GET':
        sim = get_object_or_404(Sim, pk = simkey)

        # Get simcraft thread
        simThread = None
        thread_id = sim.sim_identifier
        for thread in threading.enumerate():
            if thread.ident == thread_id:
                simThread = thread

        data = {}

        if simThread != None:
            # Define data to be returned

            data['acs_power'] = simThread.subsystems['EPS'].distribution['ACS']
            data['eps_power'] = simThread.subsystems['EPS'].distribution['EPS']
            data['tcs_power'] = simThread.subsystems['EPS'].distribution['TCS']
            data['comms_power'] = simThread.subsystems['EPS'].distribution['COMMS']
            data['payload_power'] = simThread.subsystems['EPS'].distribution['Payload']

            data['articulation'] = simThread.subsystems['EPS'].solarPanelAngle
            data['total_power'] = simThread.subsystems['EPS'].totalPower

            data['telemetry_Transferring'] = simThread.subsystems['EPS'].telemetryTransferring
            data['telemetry_Transferred'] = simThread.subsystems['EPS'].telemetryTransferComplete

        return HttpResponse(json.dumps(data)) # Sending an success response
    else:
        return HttpResponse("Request method is not GET")

###############################################################################
def tcsFetchdata(request, simkey):
    if request.method == 'GET':
        sim = get_object_or_404(Sim, pk = simkey)

        # Get simcraft thread
        simThread = None
        thread_id = sim.sim_identifier
        for thread in threading.enumerate():
            if thread.ident == thread_id:
                simThread = thread

        data = {}

        if simThread != None:
            # Define data to be returned

            data['CMG-Temp'] = simThread.subsystems['TCS'].ACSThermal["CMG"]
            data['Alignment-Temp'] = simThread.subsystems['TCS'].ACSThermal["Alignment System"]

            data['Distribution-Temp'] = simThread.subsystems['TCS'].EPSThermal["Power Distribution"]
            data['Battery-Temp'] = simThread.subsystems['TCS'].EPSThermal["Battery"]
            data['Articulation-Temp'] = simThread.subsystems['TCS'].EPSThermal["Articulation System"]

            data['Computer-Temp'] = simThread.subsystems['TCS'].COMMSThermal["On-board Computer"]
            data['Processor-Temp'] = simThread.subsystems['TCS'].COMMSThermal["Signal Processor"]

            data['Optical-Temp'] = simThread.subsystems['TCS'].PayloadThermal["Optical Electronics"]
            data['Gimbal-Temp'] = simThread.subsystems['TCS'].PayloadThermal["Gimbal System"]
            data['Imager-Temp'] = simThread.subsystems['TCS'].PayloadThermal["Imager"]

            data['telemetry_Transferring'] = simThread.subsystems['TCS'].telemetryTransferring
            data['telemetry_Transferred'] = simThread.subsystems['TCS'].telemetryTransferComplete

        return HttpResponse(json.dumps(data)) # Sending an success response
    else:
        return HttpResponse("Request method is not GET")

###############################################################################
def commsFetchdata(request, simkey):
    if request.method == 'GET':
        sim = get_object_or_404(Sim, pk = simkey)

        # Get simcraft thread
        simThread = None
        thread_id = sim.sim_identifier
        for thread in threading.enumerate():
            if thread.ident == thread_id:
                simThread = thread

        data = {}

        if simThread != None:
            # Define data to be returned

            data['Telemetry-ACS'] = simThread.subsystems['COMMS'].allTelemetryData['ACS']
            data['Telemetry-EPS'] = simThread.subsystems['COMMS'].allTelemetryData['EPS']
            data['Telemetry-TCS'] = simThread.subsystems['COMMS'].allTelemetryData['TCS']
            data['Telemetry-Payload'] = simThread.subsystems['COMMS'].allTelemetryData['Payload']

            data['On-Board-Computer'] = simThread.subsystems['COMMS'].checks['On-board Computer']
            data['Antenna-Status'] = simThread.subsystems['COMMS'].checks['Antenna Status']

            data['Bandwidth'] = simThread.subsystems['COMMS'].frequency
            data['Gain'] = simThread.subsystems['COMMS'].currentGain

            data['Target'] = simThread.telemetry['ACS']
            data['Image'] = simThread.telemetry['Payload']
            data['Status'] = simThread.subsystems['COMMS'].allTelemetryDataGood

        return HttpResponse(json.dumps(data)) # Sending an success response
    else:
        return HttpResponse("Request method is not GET")

###############################################################################
def payloadFetchdata(request, simkey):
    if request.method == 'GET':
        sim = get_object_or_404(Sim, pk = simkey)

        # Get simcraft thread
        simThread = None
        thread_id = sim.sim_identifier
        for thread in threading.enumerate():
            if thread.ident == thread_id:
                simThread = thread

        data = {}

        if simThread != None:
            # Define data to be returned

            data['Connection'] = simThread.subsystems['Payload'].statusGood

            data['In-Range'] = simThread.subsystems['Payload'].slewImageFlag
            data['Target-Acquired'] = simThread.subsystems['Payload'].acquireTargetFlag
            data['Image-Received'] = simThread.subsystems['Payload'].captureImageFlag

            data['Gimbal-Status'] = simThread.subsystems['Payload'].gimbalStatus
            data['Imager-Status'] = simThread.subsystems['Payload'].imagerStatus

            data['Optical-Electronics'] = simThread.subsystems['Payload'].checks['Optical Electronics']
            data['Bus-Connection'] = simThread.subsystems['Payload'].checks['Bus Connection']
            data['Gimbal-Connection'] = simThread.subsystems['Payload'].checks['Gimble Connection']

            data['telemetry_Transferring'] = simThread.subsystems['Payload'].telemetryTransferring
            data['telemetry_Transferred'] = simThread.subsystems['Payload'].telemetryTransferComplete

        return HttpResponse(json.dumps(data)) # Sending an success response
    else:
        return HttpResponse("Request method is not GET")


def format_data_for_text_message(data_list:list) -> str:
    """
    Take the data from the list and turn it into a
    formatted paragraph that can be sent as a message
    """
    message_text = str()
    if len(data_list) > 0:
        for elem in data_list:
            message_text += f"""\n*{data_list.index(elem)+1}:* {elem["event_type"]} ({elem["created_at"][11:19]})\n"""
    else:
        message_text = "*No data matched the specified parameters*"

    return message_text


from os import PathLike
from pathlib import Path
from typing import cast, List, Sequence, Tuple, TYPE_CHECKING, Union

import pydicom
from pydicom.dataset import Dataset
from pydicom.sr.codedict import _CodesDict, codes
from pydicom.sr.coding import Code

from dcmannotate import Ellipse, PointMeasurement
from dcmannotate.annotations import Annotations, AnnotationSet
from dcmannotate.utils import Point

if TYPE_CHECKING:  # avoid circular import
    from dcmannotate.dicomvolume import DicomVolume  # pragma: no cover
from dcmannotate.measurements import Measurement

def find_value_type(ds: Dataset, type: str) -> Dataset:
    """Iterate through a dataset with a ContentSequence to find a tag with the given ValueType.

    Args:
        ds (Dataset): Input dataset
        type (str): The ValueType we are looking for.

    Raises:
        ValueError: If we didn't find it.

    Returns:
        Dataset: The tag we found.
    """
    for k in ds.ContentSequence:
        if k.ValueType == type:
            assert isinstance(k, Dataset)
            return k
    raise ValueError(f"Expected to find ValueType {type}")

def find_content_items(sr: Dataset, code: Code) -> List[Dataset]:
    """Recursively hunt through a dataset to find content items with a particular code."""
    found_items = []
    for k in sr.ContentSequence:
        if (
            hasattr(k, "ConceptNameCodeSequence")
            and k.ConceptNameCodeSequence[0].CodeValue == code.value
        ):
            found_items.append(k)
        if hasattr(k, "ContentSequence"):
            found_items += find_content_items(k, code)
    return found_items

def get_measurements(dataset: Union[Dataset, str, Path]) -> Tuple[List[Measurement], str]:
    """Retrieves measurements from this SR dataset.

    Args:
        dataset (Union[Dataset, str, Path]): The dataset or a path to it

    Returns:
        Tuple[List[Measurement], str]: A list of measurements and the ReferencedSOPInstanceUID.
    """
    assert type(codes.DCM) is _CodesDict

    ds: Dataset
    if isinstance(dataset, (str, PathLike)):
        ds = pydicom.dcmread(dataset)
    else:
        ds = dataset
    measurement_groups = find_content_items(ds, cast(Code, codes.DCM.MeasurementGroup))
    result: List[Measurement] = []
    referenced_sop_instance_uid = ""
    for m in measurement_groups:
        n = find_value_type(m, "NUM")
        gtype = n.ContentSequence[0].GraphicType
        data = n.ContentSequence[0].GraphicData
        if not referenced_sop_instance_uid:
            referenced_sop_instance_uid = (
                find_value_type(n.ContentSequence[0], "IMAGE")
                .ReferencedSOPSequence[0]
                .ReferencedSOPInstanceUID
            )
        try:
            code = find_value_type(m, "CODE")
        except ValueError:
            code = None
        if code and code.ConceptCodeSequence[0].CodeValue == "CORNERSTONEFREETEXT":
            value = code.ConceptCodeSequence[0].CodeMeaning
            unit = None
        else:
            value = float(n.MeasuredValueSequence[0].NumericValue)
            unit = n.MeasuredValueSequence[0].MeasurementUnitsCodeSequence[0].CodeMeaning

        if gtype == "POINT":
            result.append(PointMeasurement(data[0], data[1], unit, value))
        if gtype == "ELLIPSE":
            result.append(
                Ellipse(
                    Point(data[0], data[5]),
                    (data[6] - data[4]) / 2.0,
                    (data[3] - data[1]) / 2.0,
                    unit,
                    value,
                )
            )
    return result, referenced_sop_instance_uid

def read_annotations(
    volume: Union["DicomVolume", Sequence[Dataset]],
    sr_files: Sequence[Union[Dataset, str, Path]],
) -> AnnotationSet:
    """Read annotations in and verify that they reference the volume.

    Args:
        volume (DicomVolume): The volume being annotated
        sr_files (Sequence[Dataset | str | Path]): The annotation files.

    Returns: AnnotationSet
    """
    assert len(sr_files) > 0
    annotations = []
    for f in sr_files:
        measurements, uid = get_measurements(f)
        for s in volume:
            if s.SOPInstanceUID == str(uid):
                annotations.append(Annotations(measurements, s))
                break
        else:
            raise Exception("ReferencedSOPInstanceUID for this SR does not exist in volume.")
    return AnnotationSet(annotations)