"""
Views for the course home page.
"""

from django.contrib.auth.decorators import login_required
from django.core.context_processors import csrf
from django.template.loader import render_to_string
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_control
from django.views.decorators.csrf import ensure_csrf_cookie
from opaque_keys.edx.keys import CourseKey
from web_fragments.fragment import Fragment

from courseware.courses import get_course_info_section, get_course_with_access
from lms.djangoapps.courseware.views.views import CourseTabView
from openedx.core.djangoapps.plugin_api.views import EdxFragmentView
from util.views import ensure_valid_course_key

from ..utils import get_course_outline_block_tree
from .course_dates import CourseDatesFragmentView
from .course_outline import CourseOutlineFragmentView
from .course_sock import CourseSockFragmentView
from .welcome_message import WelcomeMessageFragmentView

class CourseHomeView(CourseTabView):
    """
    The home page for a course.
    """
    @method_decorator(login_required)
    @method_decorator(ensure_csrf_cookie)
    @method_decorator(cache_control(no_cache=True, no_store=True, must_revalidate=True))
    @method_decorator(ensure_valid_course_key)
    def get(self, request, course_id, **kwargs):
        """
        Displays the home page for the specified course.
        """
        return super(CourseHomeView, self).get(request, course_id, 'courseware', **kwargs)

    def render_to_fragment(self, request, course=None, tab=None, **kwargs):
        course_id = unicode(course.id)
        home_fragment_view = CourseHomeFragmentView()
        return home_fragment_view.render_to_fragment(request, course_id=course_id, **kwargs)

class CourseHomeFragmentView(EdxFragmentView):
    """
    A fragment to render the home page for a course.
    """

    def _get_resume_course_info(self, request, course_id):
        """
        Returns information relevant to resume course functionality.

        Returns a tuple: (has_visited_course, resume_course_url)
            has_visited_course: True if the user has ever visted the course, False otherwise.
            resume_course_url: The URL of the last accessed block if the user has visited the course,
                otherwise the URL of the course root.

        """

        def get_last_accessed_block(block):
            """
            Gets the deepest block marked as 'last_accessed'.
            """
            if not block['last_accessed']:
                return None
            if not block.get('children'):
                return block
            for child in block['children']:
                last_accessed_block = get_last_accessed_block(child)
                if last_accessed_block:
                    return last_accessed_block
            return block

        course_outline_root_block = get_course_outline_block_tree(request, course_id)
        last_accessed_block = get_last_accessed_block(course_outline_root_block)
        has_visited_course = bool(last_accessed_block)
        if last_accessed_block:
            resume_course_url = last_accessed_block['lms_web_url']
        else:
            resume_course_url = course_outline_root_block['lms_web_url']

        return (has_visited_course, resume_course_url)

    def render_to_fragment(self, request, course_id=None, **kwargs):
        """
        Renders the course's home page as a fragment.
        """
        course_key = CourseKey.from_string(course_id)

        # Render the outline as a fragment
        outline_fragment = CourseOutlineFragmentView().render_to_fragment(request, course_id=course_id, **kwargs)

        # Get resume course information
        has_visited_course, resume_course_url = self._get_resume_course_info(request, course_id)

        # Render the welcome message as a fragment
        welcome_message_fragment = WelcomeMessageFragmentView().render_to_fragment(
            request, course_id=course_id, **kwargs
        )

        # Render the course dates as a fragment
        dates_fragment = CourseDatesFragmentView().render_to_fragment(request, course_id=course_id, **kwargs)

        # TODO: Use get_course_overview_with_access and blocks api
        course = get_course_with_access(request.user, 'load', course_key, check_if_enrolled=True)

        # Render the verification sock as a fragment
        course_sock_fragment = CourseSockFragmentView().render_to_fragment(request, course=course, **kwargs)

        # Get the handouts
        handouts_html = get_course_info_section(request, request.user, course, 'handouts')

        # Render the course home fragment
        context = {
            'request': request,
            'csrf': csrf(request)['csrf_token'],
            'course': course,
            'course_key': course_key,
            'outline_fragment': outline_fragment,
            'handouts_html': handouts_html,
            'has_visited_course': has_visited_course,
            'resume_course_url': resume_course_url,
            'dates_fragment': dates_fragment,
            'welcome_message_fragment': welcome_message_fragment,
            'course_sock_fragment': course_sock_fragment,
            'disable_courseware_js': True,
            'uses_pattern_library': True,
        }
        html = render_to_string('course_experience/course-home-fragment.html', context)
        return Fragment(html)


import pandas as pd
import numpy as np

LABELS_AS_TXT = [
    'Non-Bullying',
    'Cultural',
    'Sexual',
    'Personal'
]

data_frame = pd.read_csv('../Data/new_data.csv')
labels, label_counts = np.unique(np.array(data_frame['label']), return_counts=True)
labels = list(map(lambda lab_num: LABELS_AS_TXT[lab_num], labels))
label_pcts = (label_counts / data_frame.shape[0]) * 100.0
label_pcts = list(map(lambda pct_val: '{:.01f}'.format(pct_val), label_pcts))
results = pd.DataFrame(
    {
        'Labels': labels,
        'Count': label_counts,
        'Percentage': label_pcts
    }
)

print(results)


# A class to store a binary tree node
class Node:
    def __init__(self, data, left=None, right=None):
        self.data = data
        self.left = left
        self.right = right

# Function to print the root-to-leaf path with a given sum in a binary tree
def printPath(root, sum):

    # base case
    if sum == 0:
        return True

    # base case
    if root is None:
        return False

    # recur for the left and right subtree with reduced sum
    left = printPath(root.left, sum - root.data)
    right = printPath(root.right, sum - root.data)

    # print the current node if it lies on a path with a given sum
    if left or right:
        print(root.data, end=' ')

    return left or right

# Function to calculate the maximum root-to-leaf sum in a binary tree
def getRootToLeafSum(root, s, lst):

    # base case: tree is empty
    if root is None:
        return [s, lst[:]]

    # calculate the maximum node-to-leaf sum for the left child
    k = lst[:]
    k.append(root.data)
    su = s+root.data
    left = getRootToLeafSum(root.left, su, k)

    # calculate the maximum node-to-leaf sum for the right child
    right = getRootToLeafSum(root.right, su, k)

    # consider the maximum sum child
    if left[0] > right[0]:
        return left
    return right

# Function to print maximum sum root-to-leaf path in a given binary tree
def findMaxSumPath(root):

    sum = getRootToLeafSum(root, 0, [])

    print("The maximum sum is", sum)
    # print("The maximum sum path is ", end='')

    # printPath(root, sum)

if __name__ == '__main__':

    root = None
    ''' Construct the following tree
              1
            /   \
           /     \
          2       3
         / \     / \
        8   4   5   6
           /   / \   \
         10   7   9   5
    '''

    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.left = Node(8)
    root.left.right = Node(4)
    root.right.left = Node(5)
    root.right.right = Node(6)
    root.left.right.left = Node(10)
    root.right.left.left = Node(7)
    root.right.left.right = Node(9)
    root.right.right.right = Node(5)

    findMaxSumPath(root)


# coding=utf-8
import requests
from bs4 import BeautifulSoup
import json
import os
import os.path
import re
def get_special(time_messege):
    print(time_messege)
    time = re.findall('\d',time_messege)
    if(len(time) == 2):
        left_time = int(time[0])
        right_time = int(time[1])
    elif(len(time) == 3):
        left_time = int(time[0])
        right_time = int(time[1]+time[2])
    elif(len(time) == 4):
        left_time = int(time[0]+time[1])
        right_time = int(time[2]+time[3])
    else:
        special = ["error"]
        return special
    special = [i for i in range(1,left_time)]
    if(time_messege[-2] == "单"):
        for i in range(left_time,right_time+1):
            if i%2 == 0:
                special.append(i)
    if(time_messege[-2] == "双"):
        for i in range(left_time,right_time+1):
            if i%2 == 1:
                special.append(i)
    special = special+[i for i in range(right_time+1,16)]
    return special
week_day = ['Mon','Tue','Wed','Thu','Fri']

file_rootdir = 'file/'
lists = os.listdir(file_rootdir)
for eachstation in lists:
    station_dir = os.path.join(file_rootdir,eachstation)
    html_dir = os.path.join(station_dir,"class_messege")
    list = os.listdir(html_dir)
    for eachone in list:
        path = os.path.join(html_dir, eachone)
        class_file = open(path, "r", encoding="utf-8")
        class_file = class_file.read()
        json_path = os.path.join(station_dir,"json",eachone[0]+".json")
        json_file = open(json_path, "a", encoding="utf-8")
        day = week_day[int(eachone[0])-1]
        data = [{"_id":day}]
        soup = BeautifulSoup(class_file,'lxml')
        tabel = soup.find('table',"portlet-table")
        class_rooms = tabel.find_all('tr')
        for eachone in class_rooms[2:]:
           all_mesege = eachone.find_all('td')
           class_room = all_mesege[0].text[-4:].strip()
           data[0][class_room] = []
           time = 1
           flag = 0
           for class_messege in all_mesege[1:]:
               list = {}
               #去除空白字符
               if(len(class_messege.text.strip()) == 0):
                   if(flag):
                       flag = 0
                       continue
                   if(time > 9):
                       continue
                   list['flag'] = True
                   if(time == 9):
                       list['time'] = "9-11"
                   else:
                       list['time'] = str(time)+"-"+str(time+1)
                   list['special'] = []
                   data[0][class_room].append(list)
                   time += 2
                   flag = 1
                   continue
               messege = re.findall('[(].*[)]',class_messege.text)[0]
               time_messege = re.findall('\d-\d.*周',messege)[0][:-1]
               special = get_special(time_messege)
               timing_messege = re.findall('第.*节',messege)[0][1:-1]
               left_time = timing_messege[0]
               right_time = timing_messege[2:]
               time = int(right_time)+1
               if(left_time == '9'):
                   real_time = "9-11"
               else:
                   real_time = str(left_time)+"-"+str(right_time)
               list['flag'] = False
               list['time'] = real_time
               list['special'] = special
               data[0][class_room].append(list)
        json_file.write(json.dumps(data[0], indent=4, separators=(',', ': ')))
        json_file.close()


#!/usr/bin/env python

import rospy
from threading import Thread
from copy import deepcopy

# ROS
from gazebo_msgs.srv import GetModelState
from geometry_msgs.msg import Twist
from nav_msgs.msg import Odometry
from system_msgs.msg import events_message

class GasSensor(object):

    def __init__(self):
        self.__state = 'GS_OFF'
        self.__current_pose = Twist()
        self.__points_with_gas = []                                                                     # Array with points with gas

        # Get parameters
        self.__update_radius = rospy.get_param('gas_update_radius', default=3.0)                        # Radius in wich the robot does not republish gas leak
        self.__robot_name = rospy.get_param('robot_name', default='robot')
        self.__gas_models = rospy.get_param('gas_models', default=[])
        self.__sensor_range = rospy.get_param('gs_sensor_range', default=1.0)
        self.__sensor_update_rate = rospy.get_param('gs_sensor_update_rate', default=1.0)

        self.__models_service = rospy.ServiceProxy('/gazebo/get_model_state', GetModelState)             # Get model service from Gazebo
        self.__models_service.wait_for_service()

        self.__pub = rospy.Publisher("gas_sensor/out", events_message, queue_size=10)
        rospy.Subscriber("odom", Odometry, self.robot_pose)                                              # Topic to monitor robot position
        rospy.Subscriber("gas_sensor/in", events_message, self.event_receiver)                           # Topic to receive occured events

    def robot_pose(self, msg):
        '''
            Periodically update robot position according the Odometry
        '''
        self.__current_pose.linear.x = msg.pose.pose.position.x
        self.__current_pose.linear.y = msg.pose.pose.position.y

    def event_receiver(self, msg):
        '''
            Callback for received messages. Responsible for changing the sensor state
        '''
        if (msg.event == 'start') and (self.__state == 'GS_OFF'):
            self.__state = 'GS_ON'
            thread = Thread(target = self.gs_on)
            thread.start()                                                  # Start the sensor
        elif (msg.event == 'stop') and (self.__state == 'GS_ON'):
            self.__state = 'GS_OFF'                                         # Stop the sensor
        elif (msg.event == 'erro') and (self.__state == 'GS_ON'):
            self.__state = 'GS_ERROR'                                       # Stop the sensor to simulate that it is not working
            self.__pub.publish(msg)                                         # Re-send the msg to the output
        elif (msg.event == 'reset') and (self.__state == 'GS_ERROR'):
            self.__state = 'GS_OFF'                                         # Reset the sensor
            self.__pub.publish(msg)                                         # Re-send the msg to the output
        else:
            rospy.logwarn("GAS_SENSOR command not allowed!")

    def gs_on(self):
        '''
            Function for gas recognition
        '''
        rate = rospy.Rate(self.__sensor_update_rate)
        while (not rospy.is_shutdown()) and (self.__state == 'GS_ON'):
            sensor = self.__find_gas()
            for g in sensor:
                if sensor[g]['status'] == True:
                    # Verify if is a new point to publish
                    if self.__points_with_gas:
                        count = 0
                        for point in self.__points_with_gas:
                            dist = ((self.__current_pose.linear.x - point.linear.x)**2 + (self.__current_pose.linear.y - point.linear.y)**2)**(0.5)
                            if dist < self.__update_radius:
                                break
                            else:
                                count += 1
                        if count == len(self.__points_with_gas):
                            # Send the signal that a gas leak have been found and its location
                            self.__points_with_gas.append(deepcopy(self.__current_pose))
                            msg = events_message()
                            msg.event = 'gas_leak'
                            msg.position.append(self.__current_pose)
                            self.__pub.publish(msg)                                                    # Publish the found gas location
                    else:
                        # Send the signal that a gas leak have been found and its location
                        self.__points_with_gas.append(deepcopy(self.__current_pose))
                        msg = events_message()
                        msg.event = 'gas_leak'
                        msg.position.append(self.__current_pose)
                        self.__pub.publish(msg)                                                         # Publish the found gas location

            rate.sleep()

    def __find_gas(self):
        '''
            Function to verify if a gas_leak from the list is into the range of the sensor
            robot_name: name of the robot model on Gazebo
            gas_models: list of gas models on Gazebo
            sensor_range: range in which the robot recognize a gas_leak
        '''
        # Get position of the victims related to the robot position
        g_status = {}                                                                # Dictionary with the status of each victim and xyz position
        for v in self.__gas_models:
            try:
                g_status[v] = {}
                answer = self.__models_service(v, self.__robot_name)                        # Call the service to receive the victim position
                g_status[v]['x_pos'] = answer.pose.position.x
                g_status[v]['y_pos'] = answer.pose.position.y
                g_status[v]['z_pos'] = answer.pose.position.z

                # Find the distance between robot and victim
                hip = (g_status[v]['x_pos']**2 + g_status[v]['y_pos']**2)**(0.5)
                dist = (hip**2 + g_status[v]['z_pos']**2)**(0.5)

                # Mark the victim as found if it is into the range
                if dist < self.__sensor_range:
                    g_status[v]['status'] = True
                else:
                    g_status[v]['status'] = False

            except rospy.ServiceException as e:
                rospy.loginfo("Get Model State service call failed:  {}".format(e))

        return g_status                                                               # Return the status of all victims

if __name__ == '__main__':
    try:
        rospy.init_node('gas_sensor', anonymous=False)                  # Initialize the node of the sensor
        gs = GasSensor()                                                # Initialize Gas Sensor
        rospy.spin()

    except rospy.ROSInterruptException:
        pass


import math
import random
import numpy as np
from sklearn.datasets import load_iris

## Arvore de decisao ##
iris = load_iris()

def prob_esquerda(corte,atributo,data_info): ## estuda o valor de corte para o filho da esquerda ##
  samples = 0
  classe = [0,0,0]
  data_filho = []
  for w in range(len(iris.data)):
    if w not in data_info:
      continue
    else:
      if iris.data[w][atributo] <= corte:
        data_filho.append(w)
        samples += 1
        if iris.target[w] == 0:
          classe[0] += 1
        elif iris.target[w] == 1:
          classe[1] += 1
        else:
          classe[2] += 1

  value = [classe[0], classe[1], classe[2]]
  probabilidade = [p/samples for p in classe if p]
  return probabilidade,samples,data_filho,value

def prob_direita(corte,atributo,data_info): ## estuda o valor de corte para o filho da direita ##
  samples = 0
  classe = [0,0,0]
  data_filho = []
  for w in range(len(iris.data)):
    if w not in data_info:
      continue
    else:
      if iris.data[w][atributo] > corte:
        data_filho.append(w)
        samples += 1
        if iris.target[w] == 0:
          classe[0] += 1
        elif iris.target[w] == 1:
          classe[1] += 1
        else:
          classe[2] += 1

  value = [classe[0], classe[1], classe[2]]
  probabilidade = [p/samples for p in classe if p]
  return probabilidade,samples,data_filho,value

def entropia(probabilidades): ## calculo da entropia ##
  return sum(-p * math.log(p,2) for p in probabilidades if p)

def ganho_informacao(entropia_pai,entropia_esq,entropia_dir,n_pai,n_esq,n_dir): ## ganho de informacao ##
  peso1 = n_esq/n_pai
  peso2 = n_dir/n_pai
  return entropia_pai - (peso1*entropia_esq  + peso2*entropia_dir)

def buid_tree(info,data_filho,u,t,info_data,atributo,X_train,y_train): ## constrói a arvore de decisao ##
  P = []
  I = []
  for w in range(4):
    v = []
    indice = []
    i = 0
    for i in y_train:
      if i not in data_filho:
        continue
      else:
        v.append(iris.data[i][w])
        indice.append(iris.target[i])

    k = 0
    while k < (len(v)-1):
      l = k+1
      while l < (len(v)):
        if v[k] >= v[l]:
          aux = v[k]
          v[k] = v[l]
          v[l] = aux

          aux = indice[k]
          indice[k] = indice[k]
          indice[k] = aux
        l += 1
      k += 1

    media = (v[indice.index(indice[0]+1)-1] + v[indice.index(indice[0]+1)]) / 2
    P.append(media)
    probabilidades_esq,n_esq,data_esq,value_esq = prob_esquerda(P[w],w,data_filho)
    probabilidades_dir,n_dir,data_dir,value_dir = prob_direita(P[w],w,data_filho)

    n_pai = info[u][1]
    entropia_pai = info[u][0]
    entropia_esq = entropia(probabilidades_esq)
    entropia_dir = entropia(probabilidades_dir)

    I.append(ganho_informacao(entropia_pai,entropia_esq,entropia_dir,n_pai,n_esq,n_dir))

    info[t+1] = [entropia_esq,n_esq,value_esq,value_esq.index(max(value_esq))]
    info[t+2] = [entropia_dir,n_dir,value_dir,value_dir.index(max(value_dir))]

    info_data[t+1] = data_esq
    info_data[t+2] = data_dir

  atributo[u] = [I.index(max(I)),P[I.index(max(I))]]

def cria_grafo(lista_de_vertices, lista_de_arestas):
    grafo = {}
    for vertice in lista_de_vertices:
        grafo[vertice] = []
    for aresta in lista_de_arestas:
        grafo[aresta[0]].append(aresta[1])
    return grafo

def decisao(grafo,vertice,visitados,fila,Q,dados,atributo,info,profundidade,classe):
  while Q:
    vertice = Q.pop(0)

    if info[vertice][0] == 0.0:
      classe.append(info[vertice][3])

    elif profundidade == 4:
      classe.append(info[vertice][3])

    for u in grafo[vertice]:
      if dados[atributo[vertice][0]] <= atributo[vertice][1]:
        visitados.append(u)
        Q.append(u)
        fila.append(u)
        profundidade += 1
        decisao(grafo,vertice,visitados,fila,Q,dados,atributo,info,profundidade,classe)

      else:
        visitados.append(grafo[vertice][1])
        Q.append(grafo[vertice][1])
        fila.append(grafo[vertice][1])
        profundidade += 1
        decisao(grafo,vertice,visitados,fila,Q,dados,atributo,info,profundidade,classe)

      if Q:
        del(fila[len(fila)-1])
        a = fila[len(fila)-1]
        Q = [a]
        decisao(grafo,a,visitados,fila,Q,dados,atributo,info,profundidade,classe)

  return visitados

def train_test_dados(data,tam_treino,total):
    y_train = []
    x_train = []
    y_test = []
    x_test = []

    y_train = random.sample(range(0, total), tam_treino)
    y_train.sort()
    for w in y_train:
        x_train.append(data[w])

    for j in range(total):
      if j not in y_train:
        y_test.append(j)
        x_test.append(data[j])

    return x_train, y_train, x_test, y_test

def accuracy(classification,target):
  total = 0
  acertos = 0
  for i in range(len(classification)):
    if classification[i] == -1:
      continue
    else:
      if classification[i] == target[i]:
        acertos += 1
      total += 1

  return acertos/total

tamData = len(iris.data)
porcentagem_treino = 0.7 # porcentagem de treino
tamTreino = int(tamData*porcentagem_treino)

X_train, y_train, X_test, y_test = train_test_dados(iris.data,tamTreino,tamData)
if porcentagem_treino == 1:
  X_test, y_test = X_train, y_train

print('Conjunto treino:',y_train)
print('Conjunto teste:', y_test)
print()

target = [0,0,0]
for i in y_train:
  if iris.target[i] == 0:
    target[0] += 1
  elif iris.target[i] == 1:
    target[1] += 1
  else:
    target[2] += 1

prob_raiz = [target[0]/len(y_train),target[1]/len(y_train),target[2]/len(y_train)]
entropia_raiz = sum(-p * math.log(p,2) for p in prob_raiz if p)
info = {0:[entropia_raiz,len(y_train),[target[0],target[1],target[2]], target.index(max(target))]} ## no raiz ##
vertices = [0]
arestas = []
info_data = {}
atributo = {}
profundidade_no = 5

u = 0
tam = 0
while u < profundidade_no:
  if u == 0:
    data_filho = y_train
    buid_tree(info,data_filho,u,tam,info_data,atributo,X_train,y_train)
  elif info[u][0] == 0.0:
    u += 1
    continue
  else:
    buid_tree(info,info_data[u],u,tam,info_data,atributo,X_train,y_train)

  arestas.append((u,tam+1))
  arestas.append((u,tam+2))
  vertices.append(tam+1)
  vertices.append(tam+2)
  tam += 2

  u += 1
grafo = cria_grafo(vertices, arestas)

classification = []
for i in range(len(iris.data)):
  if i not in y_test:
    classification.append(-1)
    continue
  else:
    visitados = [0]
    Q = [0]
    fila = [0]
    vertice = []
    profundidade = 0
    classe = []

    decisao(grafo,vertice,visitados,fila,Q,iris.data[i],atributo,info,profundidade,classe)
    classification.append(classe[0])

j = 0
for i in range(len(classification)):
  if classification[i] == -1:
    continue
  else:
    print(y_test[j], '-', iris.target_names[classification[i]])
    j += 1

print()
print("Acurácia:", accuracy(classification,iris.target))


MC = "morse_code"

def load_char():
    # load content of the txt file
    with open(MC, mode="r", encoding="utf-8") as f:
        # using dictionary comprehension
        mc_dict = {line.split(" ")[0]: line.split(" ")[1].strip("\n") for line in f.readlines()}
    return mc_dict

def get_input():
    """Takes an input from the user and returns it as a STR."""
    while True:
        print("Please enter the text to convert:")
        input_text = input("> ").lower()

        # make sure something was entered
        if input_text == "":
            print("Please enter some text.")
        else:
            return input_text

def main():
    # load the chart into a dict
    morse_chart = load_char()
    print("Welcome to the Morse code converter.\n")

    while True:
        # get input from the user
        input_text = get_input()
        converted_text = ""

        # process characters
        for char in input_text:
            # only add valid convertible characters, ignore everything else
            if char in morse_chart:
                # add a space after each character
                converted_text += morse_chart[char] + " "

        # check for empty output
        if len(converted_text) > 0:
            print(f"Your input in morse code: {converted_text}")
        else:
            print("The input did not contain any convertible character.")

        # condition to break out of the loop
        print("Do you want to convert something else? (y/n)")
        if input("> ").lower() == "n":
            break

    print("Goodbye.")

if __name__ == "__main__":
    main()


#BOJ1043<거짓말>

#kt = know truth
num_ppl, num_pty = map(int, input().split())
kt_ppl, *kt_ppl_list = map(int, input().split())
parties = []
for _ in range(num_pty):
    pty = list(map(int, input().split()))
    parties.append(pty)

if kt_ppl == 0:
    print(len(parties))
else:
    exception = 0
    for kt_person in kt_ppl_list: #진실을 아는 사람들을 순회
        for i in range(len(parties)): #파티 순회
            party = parties[i]
            if kt_person in party[1:]: #만약 해당 파티에 진실을 아는 사람이 포함되어 있으면
                for j in range(1, len(party)): #이미 진실을 아는 사람 제외하고 다른 사람도 진실을 아는 사람들 리스트에 추가
                    if party[j] not in kt_ppl_list:
                        kt_ppl_list.append(party[j])

    for party in parties: #다시 파티 순회
        for kt_person in kt_ppl_list:
            if kt_person in party[1:]: #만약 파티에 진실을 아는 사람이 있으면
                exception += 1 #진실을 말하면 안되는 파티, exception을 1 증가시키고 다음 파티로 넘어감
                break

    print(len(parties) - exception)


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

# In[1]:

import os
import time
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
import torch
import torchvision
import torch.nn as nn
import torch.nn.functional as F
from torchvision.utils import make_grid
from torchvision import transforms
from torchvision.datasets import ImageFolder
from torch.utils.data import TensorDataset, DataLoader
from torch.utils.data.dataloader import DataLoader
import torch.optim as optim
from sklearn.metrics import confusion_matrix

from google_drive_downloader import GoogleDriveDownloader as gdd

# https://drive.google.com/file/d/1vQLLGjVa2HAcxUba2o-C1SLpMAlPyC9u/view?usp=sharing

def test_func(X):
    gdd.download_file_from_google_drive( file_id='1vQLLGjVa2HAcxUba2o-C1SLpMAlPyC9u',
                                    dest_path='../trained-model.ckpt',
                                    unzip=False, showsize = True)
    predicted_labels=[]
    X=X.reshape(X.shape[0],1,150,150)
    X=X/255
    device=torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
    class ConvolutionalNetwork(nn.Module):
        def __init__(self):
            super().__init__()
            self.conv1=nn.Conv2d(1, 6, (3,3), 1)
            self.conv2=nn.Conv2d(6, 16, (3,3), 1)
            self.conv3=nn.Conv2d(16, 32, (3,3), 1)
            self.conv4=nn.Conv2d(32, 96, (3,3), 1)
    #         self.conv1=nn.Conv2d(1, 6, (3,3), 1)
    #         self.conv2=nn.Conv2d(6, 16, (3,3), 1)
    #         self.conv3=nn.Conv2d(16, 30, (3,3), 1)
    #         self.conv4=nn.Conv2d(30, 48, (3,3), 1)
            self.fc1=nn.Linear(7*7*96, 84)
            self.fc2=nn.Linear(84, 84)
            self.fc3=nn.Linear(84,84)
            self.fc4=nn.Linear(84,25)

        def forward(self, X):
            X=F.relu(self.conv1(X))
            X=F.max_pool2d(X, 2, 2)
            X=F.relu(self.conv2(X))
            X=F.max_pool2d(X, 2, 2)
            X=F.relu(self.conv3(X))
            X=F.max_pool2d(X, 2, 2)
            X=F.relu(self.conv4(X))
            X=F.max_pool2d(X, 2, 2)
            X=X.view(-1, 7*7*96)
            X=F.relu(self.fc1(X))
            X=F.relu(self.fc2(X))
            X=F.relu(self.fc3(X))
            X=self.fc4(X)
            return F.log_softmax(X, dim=1)
    # create your dataloader
    dataloader=DataLoader(torch.Tensor(X),batch_size=10, shuffle=False)
    model=ConvolutionalNetwork()
    model.load_state_dict(torch.load('../trained-model.ckpt'))
    model.eval()
    with torch.no_grad():
        for images in dataloader:
            #print(images)
            images=images.to(device)
            outputs=model(images)
            _, predicted=torch.max(outputs.data, 1)
            #print(predicted)
            predicted_labels.append(predicted.tolist())
    #print(predicted_labels)
    predicted_labels=[item for sublist in predicted_labels for item in sublist]
        #     true_values=[item for sublist in true_values for item in sublist]
    return predicted_labels

# Now load the labels here for checking the accuracy of the test data.
test_images=np.load('Path for Test Images')
predicted_val=test_func(test_images)
labels=np.load('Path for Test Labels').T
true_val=labels
correct_count=0
for i in range(len(true_val)):
      if(predicted_val[i]==true_val[i]):
             correct_count += 1
accuracy=(correct_count / len(true_val))*100
print('Accuracy on Test Data = ', accuracy)

# In[ ]:


import sys
from collections import deque
sys.stdin = open("input.txt", "r")
input = sys.stdin.readline

def bfs(x, y):
    dx = [-1, -1, 0, 1, 1, 1, 0, -1]
    dy = [0, 1, 1, 1, 0, -1, -1, -1]

    dq = deque()
    dq.append((x, y, 0))
    check_set = set()
    check_set.add((x, y))

    while dq:
        t = dq.popleft()
        if board[t[0]][t[1]] == 1:
            return t[2]
        for h in range(8):
            xx = t[0] + dx[h]
            yy = t[1] + dy[h]
            if 0 <= xx < n and 0 <= yy < m and (xx, yy) not in check_set:
                dq.append((xx, yy, t[2] + 1))
                check_set.add((xx, yy))

if __name__ == "__main__":
    n, m = map(int, input().split())
    board = [list(map(int, input().split())) for _ in range(n)]
    max_cnt = 0

    for i in range(n):
        for j in range(m):
            if board[i][j] != 1:
                max_cnt = max(max_cnt, bfs(i, j))
    print(max_cnt)


# Problem 5 - Blockchain

import sys
sys.path.append("c:/Users/M/Anaconda3/Lib/site-packages/")

# Your work here

import hashlib
import datetime

class Node:

    def __init__(self, block, previous=None):
        self.block = block
        self.previous = None

class Blockchain:
    def __init__(self):
        self.head = None
        self.tail = None

    def add_block(self, data):

        previous_hash = None

        if self.tail:
            previous_hash = self.tail.block.hash

        block = Block(data, previous_hash)

        node = Node(block, self.tail)
        if self.head == None:
            self.head = node

        else:
            block.previous = self.tail
            block.previous_hash = self.tail.block.hash

        self.tail = node

class Block:

    def __init__(self, data, previous_hash=None, timestamp=datetime.datetime.utcnow()):
        self.timestamp = timestamp
        self.data = data
        self.previous_hash = previous_hash
        self.hash = self.calc_hash(self.data)

    def calc_hash(self, data):
        sha = hashlib.sha256()

        hash_str = "We are going to encode this string of data!".encode('utf-8')

        sha.update(hash_str)

        return sha.hexdigest()

print("Begin Blockchain testing...\n")
chain = Blockchain()
chain.add_block("test data")

print("chain.tail - ", chain.tail)
print("chain.head - ", chain.head)
print("\nPrint true or false for chain.tail == chain.head")
print(chain.tail == chain.head)

print("\nchain.tail.block.previous_hash - ", chain.tail.block.previous_hash)
print("\nPrint true or false for chain.tail.block.previous_hash == None")
print(chain.tail.block.previous_hash == None)

first_block_hash = chain.tail.block.hash

chain.add_block("more data")
print("\nchain.tail - ", chain.tail)
print("chain.head - ", chain.head)
print("\nPrint true or false for chain.tail != chain.head")
print(chain.tail != chain.head)

print("\nchain.tail.block.previous_hash - ", chain.tail.block.previous_hash)
print("\nPrint true or false for chain.tail.block.previous_hash != None")
print(chain.tail.block.previous_hash != None)

second_block_hash = chain.tail.block.hash
second_block_prev_hash = chain.tail.block.previous_hash

print("\nfirst_block_hash       - ", first_block_hash)
print("second_block_prev_hash - ", second_block_prev_hash)
print("\nPrint true or false for first_block_hash == second_block_prev_hash")
print(first_block_hash == second_block_prev_hash)

print("\nsecond_block_hash      - ", second_block_hash)
print("second_block_prev_hash - ", second_block_prev_hash)
print("\nPrint true or false for second_block_hash != second_block_prev_hash")
print(second_block_hash != second_block_prev_hash)

print('\nTest completed...')

# the above test cases should print the following:
"""
Begin Blockchain testing...

chain.tail -  <__main__.Node object at 0x0000027769B5D940>
chain.head -  <__main__.Node object at 0x0000027769B5D940>

Print true or false for chain.tail == chain.head
True

chain.tail.block.previous_hash -  None

Print true or false for chain.tail.block.previous_hash == None
True

chain.tail -  <__main__.Node object at 0x0000027769B5D9B0>
chain.head -  <__main__.Node object at 0x0000027769B5D940>

Print true or false for chain.tail != chain.head
True

chain.tail.block.previous_hash -  a20200a94c75010576e2d6a83e6fa69271901a9d805894b28bd91e6054fbfd10

Print true or false for chain.tail.block.previous_hash != None
True

first_block_hash       -  a20200a94c75010576e2d6a83e6fa69271901a9d805894b28bd91e6054fbfd10
second_block_prev_hash -  a20200a94c75010576e2d6a83e6fa69271901a9d805894b28bd91e6054fbfd10

Print true or false for first_block_hash == second_block_prev_hash
True

second_block_hash      -  a20200a94c75010576e2d6a83e6fa69271901a9d805894b28bd91e6054fbfd10
second_block_prev_hash -  a20200a94c75010576e2d6a83e6fa69271901a9d805894b28bd91e6054fbfd10

Print true or false for second_block_hash != second_block_prev_hash
False

Test completed...

"""


from collections import defaultdict
from itertools import permutations
def solution(A):
    if len(A) > 0:
        digitSum = defaultdict(list)
        for number in A:
            tmpSum = 0
            for digit in str(number):
               tmpSum += int(digit)

            digitSum[tmpSum].append(number)
        result = -1
        for key,value in digitSum.items():
            if len(value) >=2:
                value = sorted(value , reverse=True)
                result = max(result,value[0]+value[1])
        return result
    else:
        return -1

A = [51,71,17,42]
print(solution(A))


import sqlite3
import os
import matplotlib.pyplot as plt
import numpy as np
import json
import requests

#Making Maturity Table (IDs)
def maturityTable():
    path = os.path.dirname(os.path.abspath(__file__))
    conn = sqlite3.connect(path+'/'+"Movies.db")
    cur = conn.cursor()

    cur.execute("CREATE TABLE IF NOT EXISTS Maturity (id INTEGER PRIMARY KEY NOT NULL, Options TEXT)")
    conn.commit()
    return cur,conn

# Filling Maturity Table (IDs)
def fillMaturityTable(cur, conn):
    options_list = ["G", "PG", "PG-13", "R", "NC-17", "Other"]

    for i in range(len(options_list)):
        cur.execute("INSERT or IGNORE INTO Maturity (id,Options) VALUES (?,?)",(i ,options_list[i]))
    conn.commit()

# Making Movie Scores Table
def movieMaturities(cur, conn):
    cur.execute('CREATE TABLE IF NOT EXISTS Maturity_Scores (movie_id INTEGER PRIMARY KEY UNIQUE, maturity_id NUMERIC)')
    conn.commit()

# Getting imbd's movie ids
def retrieveImbdID(cur, conn):
    formatted_ids = []
    cur.execute("SELECT imdb_id FROM IMDB_Ratings")
    imdb_identification = cur.fetchall()
    for id in imdb_identification:
        formatted_ids.append(id[0])

    return formatted_ids

def retrieveWatchModeScore(cur, conn, formatted_ids):
    us_rating_list = []
    base_url = "https://api.watchmode.com/v1/title/{}/details/?apiKey={}"
    for id in formatted_ids:
        formatted_url = base_url.format(id, "phFnsumueQAmsHJRRABMsBSGUNfpnGBkcci9kyr8")
        data = requests.get(formatted_url)
        data_list = json.loads(data.text)
        try:
            maturity = data_list['us_rating']
            cur.execute(f"SELECT movie_id from IMDB_Ratings WHERE imdb_id = ?", (id,))
            movieid = cur.fetchone()[0]
            tups = (movieid, maturity)
            us_rating_list.append(tups)
        except:
            continue

    return us_rating_list

# Filling Maturity_scores Table
def fillMaturity_ScoresTable(cur, conn, us_rating_list):
    options_list = ["G", "PG", "PG-13", "R", "NC-17", "Other"]

    cur.execute("SELECT max(movie_id) FROM Maturity_Scores")
    count = cur.fetchone()[0]
    if count ==  None:
        count = 0

    for i in range(count, count+25):
        id = us_rating_list[i][0]
        score = us_rating_list[i][1]
        if score in options_list:
            cur.execute(f"SELECT id from Maturity WHERE Options = ?", (score,))
            maturity = cur.fetchone()[0]
        else:
            cur.execute("SELECT id from Maturity WHERE Options = 'Other'")
            maturity = cur.fetchone()[0]
        cur.execute("INSERT or IGNORE INTO Maturity_Scores (movie_id,maturity_id) VALUES (?,?)",(id, maturity))
    conn.commit()

#Retrieve Pie Chart Data
def retrievePieChartData(cur, conn):
    cur.execute('''SELECT c.movie_title, a.Options FROM Maturity a
                JOIN Maturity_Scores b ON a.id = b.maturity_id
                JOIN Movies c ON c.movie_id = b.movie_id''')

    #SELECT c.movie_title, a.Options FROM Maturity a JOIN Maturity_Scores b ON a.id = b.maturity_id JOIN Movies c ON c.movie_id = b.movie_id

    data = cur.fetchall()
    return data

#Making Pie Chart and Text File
def pieChartAndText(file, data):
    movie_name = []
    maturity_rating = []
    options_list = ["G", "PG", "PG-13", "R", "NC-17", "Other"]
    g_count = 0
    pg_count = 0
    pg13_count = 0
    r_count = 0
    nc17_count = 0
    other_count = 0

    for i in data:
        movie_name.append(i[0])
        maturity_rating.append(i[-1])

    for rating in maturity_rating:
        if rating == "G":
            g_count += 1
        elif rating == "PG":
            pg_count +=1
        elif rating == 'PG-13':
            pg13_count +=1
        elif rating == "R":
            r_count += 1
        elif rating == "NC-17":
            nc17_count +=1
        elif rating == "Other":
            other_count +=1

    labels = options_list
    sizes = [g_count, pg_count, pg13_count, r_count, nc17_count, other_count]
    explode = (0, 0, 0.15, 0, 0, 0)
    colors = ('c', 'm', 'y', 'g', 'r', 'orange')

    fig1, ax1 = plt.subplots()
    ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',shadow=True, startangle=90, colors = colors, wedgeprops = {"edgecolor" : "black",
                      'linewidth': .5,
                      'antialiased': True})

    ax1.axis('equal')
    plt.title('Percentage of Movies within Auidence Maturity Categories')
    plt.show()

    dir = os.path.dirname(file)
    with open(os.path.join(dir, file), "w") as f:
         f.write(f'The total number of G rated movies is {str(g_count)}. \n')
         f.write(f'The total number of PG rated movies is {str(pg_count)}. \n')
         f.write(f'The total number of PG-13 rated movies is {str(pg13_count)}. \n')
         f.write(f'The total number of R rated movies is {str(r_count)}. \n')
         f.write(f'The total number of NC-17 movies is {str(nc17_count)}. \n')
         f.write(f'The total number of not rated movies is {str(other_count)}. \n')

def main():
    #Run 2 times
    cur, conn = maturityTable()
    fillMaturityTable(cur, conn)
    movieMaturities(cur, conn)
    formatted_ids = retrieveImbdID(cur, conn)

    #After 2 runs, comment out these two lines
    us_rating_list = retrieveWatchModeScore(cur, conn, formatted_ids)
    fillMaturity_ScoresTable(cur, conn, us_rating_list)

    #After commenting out retrieveWatchModeScore and fillMaturity_ScoresTable, remove the comment from pieChartAndText
    data = retrievePieChartData(cur, conn)
    # pieChartAndText('Maturity.txt', data)

if __name__ == "__main__":
    main()


import numpy

class NoiseMaker(object):
    def __init__(self, data_set, num_batches, noise):
        self.data_set = data_set
        self.num_batches = num_batches
        self.noise = noise

    def make_examples(self, rng):
        # create an array which is the size of the number of batches
        new_example_batches = [None] * self.num_batches
        # go through all of the batches
        for ith_batch in xrange(self.num_batches):
            # get the images and the digits for this batch
            x, t = self.data_set.next()
            batch_size = len(x)
            # create an array which is the size of this batch
            new_examples = [None] * batch_size
            # get the original digits
            new_digits = self.data_set.t[ith_batch*batch_size: (ith_batch+1)*batch_size]
            # go through each image in the batch
            for i in xrange(batch_size):
                img = x[i]
                digit = t[i]
                # add the noise and save the image
                new_examples[i] = self.noise.apply_noise(img, rng)
            # add the batch to the new batches
            new_example_batches[ith_batch] = (new_examples, new_digits)
        return new_example_batches

class AbstractNoise(object):
    def apply_noise(self, img, rng):
        raise NotImplementedError("You can't use abstract noise.")

class DropoutNoise(AbstractNoise):
    def __init__(self, dropout_prob):
        self.dropout_prob = dropout_prob

    def apply_noise(self, img, rng):
        d = rng.binomial(1, self.dropout_prob, img.shape)
        return d*img

class RotationNoise(AbstractNoise):
    def __init__(self, dropout_prob):
        self.dropout_prob = dropout_prob

    def apply_noise(self, img, rng):
        img_shape = numpy.sqrt(len(img))
        img = img.reshape((img_shape, img_shape))
        img = numpy.rot90(img)
        img = img.reshape((img_shape * img_shape))
        return img


from machine import ADC

class LM35:
    def __init__(self, pin):
        self.__temperature_pin = ADC(pin)
        self.__conversion_factor = 3.3 / (65535)
        self.READ_COUNTER = 50

    def read_celcius(self):
        raw = 0.0
        for i in range(self.READ_COUNTER):
            raw += self.__temperature_pin.read_u16()
            delay(1)
        raw_average = raw/self.READ_COUNTER
        convert_voltage = raw_average * self.__conversion_factor
        temp = convert_voltage / (10.0 / 1000)
        return temp

    def read_fahrenheit(self):
        temp_celcius = self.read_celcius()
        temp_fahrenheit = (temp_celcius * (9/5)) + 32
        return temp_fahrenheit

    def read_kelvin(self):
        return self.read_celcius() + 273.15


import numpy as np
import random

picture = {
    "Jack": 11,
    "Queen": 12,
    "King": 13,
    "Ace": 14,
}
suitColor = {
    'Hearts': 'red',
    'Clubs': 'black',
    'Diamonds': 'red',
    'Spades': 'black'
}

class Card:
    def __init__(self, no, suit):
        self.no = no
        self.suit = suit
        self.value = self.no
        if (no in picture):
            self.value = picture[no]
        self.color = suitColor[suit]

    def getCard(self):
        print(self.no + " of " + self.suit)

    def __ge__(self, other):
        if self.value >= other.value:
            return True
        else:
            return False

    def __le__(self, other):
        if self.value <= other.value:
            return True
        else:
            return False

    def __gt__(self, other):
        if self.value > other.value:
            return True
        else:
            return False

    def __lt__(self, other):
        if (self.value < other.value):
            return True
        else:
            return False

def maxCard(card1, card2):
    if card1 >= card2:
        return card1
    else:
        return card2

def minCard(card1, card2):
    if card1 <= card2:
        return card1
    else:
        return card2

def initDeck():
    numbers = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace']
    suits = ['Hearts', 'Clubs', 'Diamonds', 'Spades']
    deck = [Card(n, s) for s in suits for n in numbers]
    return deck

def run(deck):
    drink_duration = random.randint(1, 15)
    hand = random.sample(deck, 4)

    red_or_black = input("Red or Black: ").lower()

    if red_or_black != hand[0].color:
        hand[0].getCard()
        return "DRINK for " + str(drink_duration) + " second(s)"
    hand[0].getCard()

    high_or_low = input("Higher or Lower: ").lower()

    if high_or_low == "higher" and hand[0] > hand[1]:
        hand[1].getCard()
        return "DRINK for " + str(drink_duration) + " second(s)"
    elif high_or_low == "lower" and hand[0] < hand[1]:
        hand[1].getCard()
        return "DRINK for " + str(drink_duration) + " second(s)"
    hand[1].getCard()

    high_card = maxCard(hand[0], hand[1])
    low_card = minCard(hand[0], hand[1])
    in_or_out = input("Inside or Outside: ").lower()

    if in_or_out == "outside" and (hand[2].value in range(low_card.value, high_card.value)):
        hand[2].getCard()
        return "DRINK for " + str(drink_duration) + " second(s)"
    elif in_or_out == "inside" and not (hand[2].value in range(low_card.value, high_card.value)):
        hand[2].getCard()
        return "DRINK for " + str(drink_duration) + " second(s)"

    hand[2].getCard()
    suit_guess = input("Guess the Suit: ").lower()

    if suit_guess != hand[3].suit.lower():
        hand[3].getCard()
        return "DRINK for " + str(drink_duration) + " second(s)"
    hand[3].getCard()

    return "Success"

def play_round():
    deck = initDeck()

    result = run(deck)
    print(result)
    main()

def main():
    choice = input("play another round? y/n: ")
    print("Starting game ...\n")

    if choice == "y":
        play_round()
    else:
        return

main()


import cv2
import time
import os
import numpy as np
import hand_tracking_module as htm

red=(0,25,225)
green=(0,217,0)
blue=(225,128,0)
black=(10,10,10)
white=(255,255,255)

folderpath="paint"
mylist=os.listdir(folderpath)
overlay=[]
for im in mylist:
	image=cv2.imread(f'{folderpath}/{im}')
	overlay.append(image)

header=overlay[0]

cap=cv2.VideoCapture(0)
detector=htm.HandDetector(detectionCon=0.75)

color=red

brushthickness=15
eraserthickness=25
xp,yp=0,0
imgCanvas=np.zeros((480,640,3),np.uint8)

while True:
	success,img=cap.read()
	w=int((img.shape[0]*960)/img.shape[1])
	img=cv2.resize(img,(960,w))
	imgCanvas=cv2.resize(imgCanvas,(960,w))
	#flip image
	img=cv2.flip(img,1)

	img=detector.findHands(img)
	lmlist=detector.findPosition(img,draw=False)

	if len(lmlist)!=0:
		x1,y1= lmlist[8][1:]
		x2,y2= lmlist[12][1:]
		fingers=detector.fingersUp()

		if fingers[1] and fingers[2]:
			xp,yp=x1,y1
			if all(x>=1 for x in fingers)==False:
				cv2.rectangle(img, (x1,y1),(x2,y2),color,cv2.FILLED)

			colors=[red,green,blue,black,white]

			for count,c in enumerate(colors):
				if y1<82:
					if count*180<x1<(count+1)*180:
						header=overlay[count]
						color=c

		if fingers[1] and fingers[2]==False:
			if color==white:
				cv2.circle(img,(x1,y1),25,color,2)
				cv2.line(imgCanvas,(xp,yp),(x1,y1),(0,0,0),eraserthickness)

			else:
				cv2.circle(img,(x1,y1),15,color,cv2.FILLED)
				cv2.line(img,(xp,yp),(x1,y1),color,brushthickness)
				cv2.line(imgCanvas,(xp,yp),(x1,y1),color,brushthickness)
			xp,yp=x1,y1
		if all(x>=1 for x in fingers):
			imgCanvas=np.zeros((480,640,3),np.uint8)
			imgCanvas=cv2.resize(imgCanvas,(960,w))

	# adding images img and imgCanvas ->>
	imgGray=cv2.cvtColor(imgCanvas, cv2.COLOR_BGR2GRAY)
	_,imgInv=cv2.threshold(imgGray,5,255,cv2.THRESH_BINARY_INV)
	imgInv= cv2.cvtColor(imgInv,cv2.COLOR_GRAY2BGR)
	img=cv2.bitwise_and(img, imgInv)
	img=cv2.bitwise_or(img, imgCanvas)

	img[0:82,0:]=header
	cv2.imshow('image',img)
	if cv2.waitKey(1)==27:
		break
cap.release()


from appMedica.models import Cita
from django import forms
from django.forms import ModelForm, Form
from .models import Boleta

class DateInput(forms.DateInput):
    input_type = 'date'

class TimeInput(forms.TimeInput):
    input_type = 'time'

class registroCitaFormSec(ModelForm):
    class Meta:
        model = Cita
        fields = [
            "fechaCita",
            "horaInicioCita",
            "duracionCita",
            "pacienteCita",
            "medicoCita"
        ]
        widgets = {
            'fechaCita': DateInput(),
            'horaInicioCita': TimeInput()
        }

class BoletaForm(ModelForm):
    comisionDelMedico = forms.IntegerField(max_value=100)
    class Meta:
        model = Boleta
        fields = [
            "cita",
            "valorDeLaCita",
            "comisionDelMedico"
        ]


#!/usr/bin/python

import os
import sys
import dbus
import dbus.service
import time
import json
import bluetooth
import SocketServer
from bluetooth import *
from SimpleHTTPServer import SimpleHTTPRequestHandler
from dbus.mainloop.glib import DBusGMainLoop

class Hid:
    MY_ADDRESS="B8:27:EB:60:2E:1E"
    MY_DEV_NAME="ARemote_Controller"

    P_CTRL =17
    P_INTR =19
    PROFILE_DBUS_PATH="/bluez/acontrol/bthid_profile"
    SDP_RECORD_PATH = sys.path[0] + "/sdp_record.xml"
    UUID="00001124-0000-1000-8000-00805f9b34fb"
    CONTROL_CMDS=[
            0x10, # previous track
            0x40, # next track
            0x20, # play / pause
            ]
    def read_sdp_service_record(self):
        try:
            fh = open(Hid.SDP_RECORD_PATH, "r")
        except:
            sys.exit("SDP record ERROR!")
        return fh.read()

    def close(self):
        self.ccontrol.close()
        self.cinterrupt.close()

    def send_cmd(self, key):
        self.input_report[2] = self.CONTROL_CMDS[key]
        self.cinterrupt.send(str(self.input_report));

    def release_cmd(self):
        self.input_report[2] = 0x00
        self.cinterrupt.send(str(self.input_report));

    def __init__(self):
        self.input_report=bytearray([
                0xa1,
                0x03,
                0x00,
                0x00,
                0x00])
        os.system("hciconfig hcio class 0x00250c")
        os.system("hciconfig hcio name " + self.MY_DEV_NAME)
        os.system("hciconfig hcio piscan")

        service_record=self.read_sdp_service_record()

        opts = {
            "ServiceRecord": service_record,
            "Role":"server",
            "RequireAuthentication": False,
            "RequireAuthorization": False
        }

        bus = dbus.SystemBus()
        manager = dbus.Interface(bus.get_object("org.bluez","/org/bluez"), "org.bluez.ProfileManager1")

        profile = dbus.service.Object(bus, Hid.PROFILE_DBUS_PATH)

        manager.RegisterProfile(Hid.PROFILE_DBUS_PATH, Hid.UUID, opts)

        bus_name = dbus.service.BusName("org.acontrol.bthidservice", bus=dbus.SystemBus())
        dbus.service.Object(bus_name, "/org/acontrol/bthidservice")

        self.scontrol=BluetoothSocket(L2CAP)
        self.sinterrupt=BluetoothSocket(L2CAP)

        self.scontrol.bind((self.MY_ADDRESS, self.P_CTRL))
        self.sinterrupt.bind((self.MY_ADDRESS, self.P_INTR))

        self.scontrol.listen(1)
        self.sinterrupt.listen(1)

        self.ccontrol,cinfo = self.scontrol.accept()
        self.cinterrupt,cinfo = self.sinterrupt.accept()

class JsonResponseHandler(SimpleHTTPRequestHandler):
    def do_POST(self):
        content_len = int(self.headers.get("content-length"))
        requestBody = self.rfile.read(content_len).decode('UTF-8')
        jsonData = json.loads(requestBody)
        self.send_response(200)
        self.send_header("Content-type", "Application/json")
        self.end_headers()
        hid.send_cmd(jsonData["control"])
        time.sleep(0.01)
        hid.release_cmd()

if __name__ == "__main__":
    try:
        DBusGMainLoop(set_as_default=True)
        hid = Hid()
        server = SocketServer.TCPServer(("", 8000), JsonResponseHandler)
        server.serve_forever()
    except KeyboardInterrupt as ex:
        server.server_close()
        hid.close()
    except BluetoothError as ex:
        print("Bluetooth ERROR!")


import copy
from pathlib import Path
from loguru import logger

import numpy as np
import torch
import wandb
from einops import rearrange
from pytorch_lightning import Callback
from pytorch_lightning.callbacks import Callback
from dataset.ds_utils.dataset_common_utils import need_to_upsample256
from diffusion_utils.taokit.wandb_utils import wandb_scatter_fig
from eval.test_exps.common_stuff import sampling_cond_str
from diffusion_utils.taokit.vis_utils import upsample_pt

def update_cfg_dict(_kwargs, update_info_dict, cfg_name):
    _kwargs_new = copy.deepcopy(_kwargs)
    _kwargs_new.update(update_info_dict)
    logger.warning("{}: {}".format(cfg_name, _kwargs_new))
    return _kwargs_new

def _get_wandbimg(samples):
    assert isinstance(
        samples, torch.Tensor
    )  # if it is tensor, split along first dimension
    # n_log_step, n_row, C, H, W
    denoise_grid = rearrange(samples, "n b c h w -> b n c h w")
    denoise_grid = rearrange(denoise_grid, "b n c h w -> (b n) c h w")
    wandb_list = [wandb.Image(_i.float()) for _i in denoise_grid]
    return wandb_list

class ImageLogger(Callback):
    def __init__(
        self,
        batch_frequency,
        max_images,
        disabled=False,
        log_on_batch_idx=False,
        log_first_step=False,
    ):
        super().__init__()

        self.batch_frequency = batch_frequency
        self.max_images = max_images

        self.disabled = disabled
        self.log_on_batch_idx = log_on_batch_idx
        self.log_first_step = log_first_step

    def log_img(self, pl_module, batch, batch_idx, split="train"):
        check_idx = batch_idx if self.log_on_batch_idx else pl_module.global_step
        is_train = pl_module.training#important issue!!!

        if self.check_frequency(check_idx) and self.max_images > 0:
            if is_train:
                pl_module.eval()

            with torch.no_grad():
                if hasattr(pl_module, "log_images"):
                    batch = pl_module.log_images(batch)
                    self.log_wandb(pl_module, batch=batch)
                else:
                    logger.warning(
                        "log_images function is missing in pl_module, skip the vis.."
                    )

            if is_train:
                pl_module.train()

    def log_sample_and_prog(
        self, log, samples, inter_dict, _key, prog_vis_num, need_to_upsample256=False
    ):
        log[f"{_key}_max"] = samples.max().item()
        log[f"{_key}_min"] = samples.min().item()
        if need_to_upsample256:
            samples = [wandb.Image(upsample_pt(_i).float()) for _i in samples]
        else:
            samples = [wandb.Image(_i.float()) for _i in samples]
        log[_key] = samples

        # pred_x0_unclipped
        if "pred_x0_unclipped_max" in inter_dict:
            prog_pred_x0_unclipped_max = inter_dict["pred_x0_unclipped_max"]
            prog_pred_x0_unclipped_min = inter_dict["pred_x0_unclipped_min"]
            timestep = len(prog_pred_x0_unclipped_max)
            max_list = [prog_pred_x0_unclipped_max[i] for i in range(timestep)]
            min_list = [prog_pred_x0_unclipped_min[i] for i in range(timestep)]
            x_list = list(range(timestep))
            log.update(
                wandb_scatter_fig(
                    x_list=x_list, y_list=max_list, dict_key=f"{_key}_unclipped_max"
                )
            )
            log.update(
                wandb_scatter_fig(
                    x_list=x_list, y_list=min_list, dict_key=f"{_key}_unclipped_min"
                )
            )

        # progressive
        prog = inter_dict["pred_x0"]  # [timestep_vis, b, 3 ,w, h]
        prog = prog[
            :, :prog_vis_num
        ]  # [timestep_vis, b, 3 ,w, h], truncate to progressive_vis_num
        prog_wandblist = _get_wandbimg(prog)
        log[f"{_key}_prog"] = prog_wandblist
        return log

    def log_wandb(self, pl_module, batch, vis_num=16, prog_vis_num=9):
        logdict_wandb = dict()
        vis_num = min(len(batch["image"]), vis_num)
        logdict_wandb["inputs"] = batch["image"][:vis_num].to(
            pl_module.device)  # [B,3,W,H]
        _dataset = pl_module.trainer.datamodule.train_dataloader().dataset
        try:
            captions = [f"{_dataset.label_list[_dataset.targets[_id]]}:{_dataset.targets[_id]}:{_id}" for _id in batch['id'][:vis_num]]
        except:
            captions = ['dump caption'] * vis_num
        logdict_wandb["inputs"] = [wandb.Image(_img.float(), caption=_caption) for _img,_caption in zip(logdict_wandb["inputs"],captions)]
        pl_module.logger.experiment.log({"imagelogger/inputs_vis": logdict_wandb["inputs"]})

        batch = {k:v[:vis_num].to(pl_module.device) for k,v in batch.items()}

        condition_kwargs, sampling_kwargs, fid_kwargs = pl_module.get_default_config()
        ######         update some common params #################################
        fid_kwargs.update(
            save_dir=str(Path(pl_module.trainer.logdir).expanduser().resolve())
        )
        sampling_kwargs.update(
            dict(
                num_timesteps=pl_module.hparams.model.num_timesteps_imagelogger,
                sampling_method=pl_module.hparams.model.sampling_imagelogger,
            )
        )

        with pl_module.ema_scope("Plotting Native Sampling"):
            cond_scale_list = list(set([0, pl_module.hparams.cond_scale]))
            for cond_scale in cond_scale_list:
                condition_cfg_now = update_cfg_dict(
                    condition_kwargs,
                    update_info_dict=dict(cond_scale=cond_scale),
                    cfg_name="condition_kwargs",
                )
                sampling_cfg_now = update_cfg_dict(
                    sampling_kwargs,
                    update_info_dict=dict(return_inter_dict=True),
                    cfg_name="sampling_kwargs",
                )
                samples, inter_dict = pl_module.sampling_progressive(
                    batch_size=len(batch["image"]),
                    batch_data=batch,
                    condition_kwargs=condition_cfg_now,
                    sampling_kwargs=sampling_cfg_now,
                )

                logdict_wandb = self.log_sample_and_prog(
                    log=logdict_wandb,
                    _key=f"native_{sampling_cond_str(sampling_cfg_now,condition_cfg_now)}",
                    samples=samples,
                    inter_dict=inter_dict,
                    prog_vis_num=prog_vis_num,
                    need_to_upsample256=need_to_upsample256(
                        pl_module.hparams.data.name
                    ),
                )

        #########################
        wandb_dict = dict()
        for k, v in logdict_wandb.items():
            if isinstance(
                v, list
            ):  # already constructed a list of wandb.Image, so directly use it here.
                wandb_dict[k] = v
            elif isinstance(v, wandb.Image):
                wandb_dict[k] = v
            else:
                wandb_dict[k] = v

        wandb_dict = {f"imagelogger/{k}": v for k, v in wandb_dict.items()}
        pl_module.logger.experiment.log(wandb_dict)

    def check_frequency(self, check_idx):
        if ((check_idx % self.batch_frequency) == 0) and (
            check_idx > 0 or self.log_first_step
        ):
            return True
        else:
            return False

    def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx):
        if not self.disabled and (pl_module.global_step > 0 or self.log_first_step):
            self.log_img(pl_module, batch, batch_idx, split="train")


import cv2
import argparse

# RgbVideo_address = "/media/hkuit164/Backup/rgb.mp4"
# thermalVideo_address = "/media/hkuit164/Backup/thermal.mp4"

def parse_args():
    parser = argparse.ArgumentParser(description='RtspDataCollection')
    # general
    parser.add_argument('--folder',
                        help='folder name',
                        required=True,
                        type=str)

    parser.add_argument('--name',
                        help="file name",
                        required=True,
                        type=str)
    args = parser.parse_args()
    return args

args = parse_args()

RgbVideo_address = args.folder + args.name + "_rgb.mp4"
thermalVideo_address = args.folder + args.name + "_thermal.mp4"

if __name__ == '__main__':

    # 開啟 RTSP 串流
    RgbVideoCap = cv2.VideoCapture('rtsp://admin:fyp202020@192.168.8.111:554/Streaming/Channels/101/?transportmode=unicast --input-rtsp-latency=0')
    TherVideoCap = cv2.VideoCapture('rtsp://admin:fyp202020@192.168.8.111:554/Streaming/Channels/201/?transportmode=unicast --input-rtsp-latency=0')

    fourcc = cv2.VideoWriter_fourcc(*'XVID')
    fps = 15

    save_size = (1080,720)
    RgbVideo = cv2.VideoWriter(RgbVideo_address, fourcc, fps, save_size)
    thermalVideo = cv2.VideoWriter(thermalVideo_address, fourcc, fps, save_size)
    #thermalVideo.set(cv2.CAP_PROP_BUFFERSIZE,0)
    #concatVideo = cv2.VideoWriter("/media/hkuit164/Backup/concatVideo.mp4", fourcc, fps, save_size)
    # 建立視窗
    cv2.namedWindow('Rgb_display', cv2.WINDOW_AUTOSIZE)
    cv2.namedWindow('Thermal_display', cv2.WINDOW_AUTOSIZE)

    for i in range(30):
        ret, Rgbimage = RgbVideoCap.read()

    while True:
        # 從 RTSP 串流讀取一張影像
        ret, Rgbimage = RgbVideoCap.read()
        ret, Therimage = TherVideoCap.read()
        if ret:
            # 顯示影像
            #im_v = cv2.vconcat([Rgbimage, Therimage])
            cv2.imshow('Rgb_display', cv2.resize(Rgbimage, (720, 540)))
            RgbVideo.write(cv2.resize(Rgbimage, save_size))
            #concatVideo.write(cv2.resize(im_v, (1080, 720)))
            cv2.moveWindow('Rgb_display', 0,0)
            cv2.imshow('Thermal_display', cv2.resize(Therimage,  (720, 540)))
            thermalVideo.write(cv2.resize(Therimage, save_size))
            cv2.moveWindow('Thermal_display', 740,0)
            key = cv2.waitKey(1)
        if key == ord('q'):
            # 若沒有影像跳出迴圈
            break

    # 釋放資源
    RgbVideoCap.release()
    TherVideoCap.release()

    # 關閉所有 OpenCV 視窗
    cv2.destroyAllWindows()


###########################################################
#
#   Computer Project #4
#   Algorithm
#       print menue of options
#       prompt for option
#       if the function requires input, prompt for input
#       run the function corrisponding to the option
#       output the result rounded to 10 decimal places
#       ask for another option
#       if option is x then exit and display the closing message
#############################################################

import math
EPSILON = 0.0000001

MENU = '''\nOptions below:
    ‘F’: Factorial of N.
    ‘E’: Approximate value of e.
    ‘P’: Approximate value of Pi.
    ‘S’: Approximate value of the sinh of X.
    ‘M’: Display the menu of options.
    ‘X’: Exit.
'''

def factorial(n):
    n = int(n)
    #transforms input to int
    if(n<=1 and n>=0):
        return 1
    #if n == 1 or 0 return 1

    if(n < 0):
        return None
    #if n is negative return None

    fact = n*(n-1)
    n-=1

    while n > 1:
        fact *= (n-1)
        n-=1
    return fact
    #calculate the factorial of n and returns it

def e():
    n = 1
    e = 1
    while(1/factorial(n) >= EPSILON):
        e += 1/factorial(n)
        #calls the factorial function to find the factorial of the denominator
        n+=1

    return round(e,10)
    #calculate e and return it

def pi():
    n = 0
    pi = 0
    sig = (-1)**n/((2*n)+1)

    while (math.fabs(sig) > EPSILON):
        sig = (-1)**n/((2*n)+1)
        if math.fabs(sig) > EPSILON:
            pi += sig
        #makes sure that sig is more than EPSILON before adding it to pi
        n+=1
    return round(pi*4,10)
    #return the value of pi rounded to 10 decimal places

def sinh(x):
    try:
        x = float(x)
        #makes sure that x is floatable
    except:
        return None
    n = 0
    sig = (x**((2*n)+1))/(factorial(2*n+1))
    sinh = 0
    while(math.fabs(sig) > EPSILON):
        sig = (x**((2*n)+1))/(factorial(2*n+1))
        if math.fabs(sig) > EPSILON:
            sinh += sig
        #makes sure sig is more than EPSILON before adding it to sinh
        n+=1
    return round(sinh,10)
    #returns the sinh value rounded to 10 decimal places
def main():
    print(MENU)
    func = ''

    while(func != 'x'):
        func = input("\nChoose an option: \n").lower()
        if(func == 'f'):
            print('Factorial')
            try:
                N = int(input('Input non-negative integer N: \n'))
                if(N<0):
                    print("Invalid N.")
                    continue
            #makes sure that N is a valid, positive integer
            except:
                print("Invalid N.")
                continue

            calc = factorial(N)
            mth = math.factorial(N)
            diff = calc-mth

            print(f'Calculated: {calc}')
            print(f'Math: {mth}')
            print(f'Diff: {diff}')
            #prints the result

        elif(func == 'e'):

            print('e')

            calc = e()
            mth = math.e
            diff = math.fabs(calc-mth)

            print(f'Calculated: {calc:.10f}')
            print(f'Math: {mth:.10f}')
            print(f'Diff: {diff:.10f}')
            #prints the result

        elif(func == 'p'):
            print('pi')

            calc = pi()
            mth = math.pi
            diff = math.fabs(calc-mth)

            print(f'Calculated: {calc:.10f}')
            print(f'Math: {mth:.10f}')
            print(f'Diff: {diff:.10f}')
            #prints the result

        elif(func == 's'):
            print('sinh')
            try:
                x = float(input('X in radians: \n'))
            except:
                print("Invalid X.")
                continue

            calc = sinh(x)
            mth = math.sinh(x)
            diff = math.fabs(calc-mth)

            print(f'Calculated: {calc:.10f}')
            print(f'Math: {mth:.10f}')
            print(f'Diff: {diff:.10f}')
            #prints the result

        elif(func == 'm'):
            print('''Options below:
    ‘F’: Factorial of N.
    ‘E’: Approximate value of e.
    ‘P’: Approximate value of Pi.
    ‘S’: Approximate value of the sinh of X.
    ‘M’: Display the menu of options.
    ‘X’: Exit.
''')

        elif(func != 'x'):
            print(f"Invalid option: {func.upper()}")
            print(MENU)

    print("Thank you for playing.")

if __name__ == '__main__':
    main()


import sys
sys.path.insert(0, "/Users/tom/Dropbox/msc-ml/project/src/")
sys.path.insert(0, "/cs/student/msc/ml/2017/thosking/dev/msc-project/src/")

from tqdm import tqdm
import numpy as np
import json

import helpers.loader as loader
import helpers.metrics as metrics
import helpers.preprocessing as preprocessing
import tensorflow as tf

import flags

from langmodel.lm import LstmLmInstance
# from qa.mpcm import MpcmQaInstance
from qa.qanet.instance import QANetInstance
from discriminator.instance import DiscriminatorInstance

FLAGS = tf.app.flags.FLAGS

class FileLoaderModel():
    def __init__(self, path):
        self.path = path
        with open(path+'/squad_dev_baseline.txt', 'r', encoding='utf-8') as fp:
            self.questions = [line.strip() for line in fp.readlines()]
        with open(path+'/dev.txt.shuffle.combined.id', 'r', encoding='utf-8') as fp:
            self.ids = [line.strip() for line in fp.readlines()]
        print(len(self.questions), len(self.ids))

    def get_q(self, id):
        if id in self.ids:
            ix = self.ids.index(id)
            return self.questions[ix]
        else:
            return None

def main(_):
    model = FileLoaderModel('./models/BASELINE')
    squad = loader.load_squad_triples(FLAGS.data_path, True, as_dict=True)

    disc_path = FLAGS.model_dir+'saved/discriminator-trained-latent'

    glove_embeddings = loader.load_glove(FLAGS.data_path)

    if FLAGS.eval_metrics:
        lm = LstmLmInstance()
        # qa = MpcmQaInstance()
        qa = QANetInstance()

        lm.load_from_chkpt(FLAGS.model_dir+'saved/lmtest')
        # qa.load_from_chkpt(FLAGS.model_dir+'saved/qatest')
        qa.load_from_chkpt(FLAGS.model_dir+'saved/qanet')

        discriminator = DiscriminatorInstance(trainable=False, path=disc_path)

    f1s=[]
    bleus=[]
    qa_scores=[]
    qa_scores_gold=[]
    lm_scores=[]
    nlls=[]
    disc_scores=[]
    sowe_similarities=[]

    qgolds=[]
    qpreds=[]
    ctxts=[]
    answers=[]
    ans_positions=[]

    metric_individuals=[]
    res=[]

    missing=0

    for id,el in tqdm(squad.items()):

        unfilt_ctxt_batch = [el[0]]
        a_text_batch = [el[2]]
        a_pos_batch = [el[3]]

        ctxts.extend(unfilt_ctxt_batch)
        answers.extend(a_text_batch)
        ans_positions.extend(a_pos_batch)

        pred_str = model.get_q(id)

        if pred_str is None:
            missing +=1
            continue
        gold_str = el[1]

        if FLAGS.eval_metrics:
            qa_pred = qa.get_ans(unfilt_ctxt_batch, [pred_str])
            gold_qa_pred = qa.get_ans(unfilt_ctxt_batch, [gold_str])

            qa_score = metrics.f1(el[2].lower(), qa_pred[0].lower())
            qa_score_gold = metrics.f1(el[2].lower(), gold_qa_pred[0].lower())
            lm_score = lm.get_seq_perplexity([pred_str]).tolist()
            disc_score = discriminator.get_pred(unfilt_ctxt_batch, [pred_str], a_text_batch, a_pos_batch).tolist()[0]

        f1s.append(metrics.f1(gold_str, pred_str))
        bleus.append(metrics.bleu(gold_str, pred_str))
        qgolds.append(gold_str)
        qpreds.append(pred_str)

        # calc cosine similarity between sums of word embeddings
        pred_sowe = np.sum(np.asarray([glove_embeddings[w] if w in glove_embeddings.keys() else np.zeros((FLAGS.embedding_size,)) for w in preprocessing.tokenise(pred_str ,asbytes=False)]) ,axis=0)
        gold_sowe = np.sum(np.asarray([glove_embeddings[w] if w in glove_embeddings.keys() else np.zeros((FLAGS.embedding_size,)) for w in preprocessing.tokenise(gold_str ,asbytes=False)]) ,axis=0)
        this_similarity = np.inner(pred_sowe, gold_sowe)/np.linalg.norm(pred_sowe, ord=2)/np.linalg.norm(gold_sowe, ord=2)

        sowe_similarities.append(this_similarity)

        this_metric_dict={
            'f1':f1s[-1],
            'bleu': bleus[-1],
            'nll': 0,
            'sowe': sowe_similarities[-1]
            }
        if FLAGS.eval_metrics:
            this_metric_dict={
            **this_metric_dict,
            'qa': qa_score,
            'lm': lm_score,
            'disc': disc_score}
            qa_scores.append(qa_score)
            lm_scores.append(lm_score)
            disc_scores.append(disc_score)
        metric_individuals.append(this_metric_dict)

        res.append({
            'c': el[0],
            'q_pred': pred_str,
            'q_gold': gold_str,
            'a_pos': el[3],
            'a_text': el[2],
            'metrics': this_metric_dict
        })

    metric_dict={
        'f1':np.mean(f1s),
        'bleu':np.mean(bleus),
        'nll':0,
        'sowe': np.mean(sowe_similarities)
        }
    if FLAGS.eval_metrics:
        metric_dict={**metric_dict,
        'qa':np.mean(qa_scores),
        'lm':np.mean(lm_scores),
        'disc': np.mean(disc_scores)}
    # print(res)
    with open(FLAGS.log_dir+'out_eval_BASELINE'+("_train" if not FLAGS.eval_on_dev else "")+'.json', 'w', encoding='utf-8') as fp:
        json.dump({"metrics":metric_dict, "results": res}, fp)

    print("F1: ", np.mean(f1s))
    print("BLEU: ", np.mean(bleus))
    print("NLL: ", 0)
    print("SOWE: ", np.mean(sowe_similarities))
    if FLAGS.eval_metrics:
        print("QA: ", np.mean(qa_scores))
        print("LM: ", np.mean(lm_scores))
        print("Disc: ", np.mean(disc_scores))

    print(missing," ids were missing")

if __name__ == "__main__":
    tf.app.run()


import torch
import torch.nn.functional as F

from underwater_unet.unet_blocks import DoubleConv, DownConv, UpConv, OutConv

def test_DoubleConv():
    # Create a DoubleConv instance
    model = DoubleConv(in_channels=3, out_channels=64)

    # Generate a random tensor of size [batch_size, channels, height, width]
    x = torch.randn(1, 3, 64, 64)

    # Forward pass
    y = model(x)

    # Check the output dimensions
    assert y.shape == (1, 64, 64, 64)

    # Check if mid_channels defaults to out_channels when not provided
    assert model.double_conv[0].out_channels == 64

    # Create another instance with mid_channels specified
    model2 = DoubleConv(in_channels=3, out_channels=64, mid_channels=32)

    # Check if mid_channels is set correctly
    assert model2.double_conv[0].out_channels == 32

def test_DownConv():
    model = DownConv(in_channels=3, out_channels=64)
    x = torch.rand(1, 3, 128, 128)
    y = model(x)
    assert y.shape == (1, 64, 64, 64), f"Expected shape (1, 64, 64, 64) but got {y.shape}"
    assert isinstance(y, torch.Tensor), f"Expected output type torch.Tensor but got {type(y)}"

def test_UpConv():
    model = UpConv(in_channels=128, out_channels=64)

    x1 = torch.randn(1, 64, 32, 32)
    x2 = torch.randn(1, 64, 64, 64)

    y = model(x1, x2)

    assert y.shape == (1, 64, 64, 64), f"Expected shape (1, 64, 64, 64) but got {y.shape}"

    assert isinstance(y, torch.Tensor), f"Expected output type torch.Tensor but got {type(y)}"

    upsampled_x1 = F.interpolate(x1, scale_factor=2, mode='bilinear', align_corners=True)
    assert torch.allclose(upsampled_x1, model.up(x1), atol=1e-5), "Bilinear upsampling not applied correctly"

def test_OutConv():
    in_channels = 128
    out_channels = 64
    model = OutConv(in_channels=in_channels, out_channels=out_channels)

    x = torch.randn(1, in_channels, 64, 64)

    # Forward pass
    y = model(x)

    assert y.shape[1] == out_channels, f"Expected {out_channels} channels but got {y.shape[1]} channels"

    assert y.shape[2:] == x.shape[2:], f"Expected spatial dimensions {x.shape[2:]} but got {y.shape[2:]}"

    assert isinstance(y, torch.Tensor), f"Expected output type torch.Tensor but got {type(y)}"


import argparse
import cv2
import numpy as np
import yaml

parser = argparse.ArgumentParser()
parser.add_argument('file', help='video file to be scanned')
parser.add_argument('-l', '--loglevel', dest='loglevel', action='store', metavar='L',
    default = "info", help = 'specify log level, defalt to INFO')
args = parser.parse_args()

cap = cv2.VideoCapture(args.file)
video_width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)   # float
video_height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT) # float
fps = cap.get(cv2.CAP_PROP_FPS)

resize_width = 480
resize_height = 480

if resize_width/video_width <= resize_height/video_height:
    resize_factor = resize_width/video_width
    resize_height = int(video_height * resize_factor)
else:
    resize_factor = resize_height/video_height
    resize_width = int(video_width * resize_factor)

frame_count = 0
grid_size = 24

def mouse_event_handler(event, x, y, flags, param):
    global start_x, start_y
    if event == cv2.EVENT_LBUTTONDOWN:
        start_x = x
        start_y = y

while(1):
    ret, frame = cap.read()

    if not ret:
        break

    frame_count += 1

    img_resized = cv2.resize(frame, (0,0), fx=resize_factor, fy=resize_factor)

    debug_info = 'frame: %d' % (frame_count)
    cv2.putText(img_resized, debug_info, (10, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (255, 0, 255))

    # output grid
    for x in xrange(grid_size, resize_width, grid_size):
        pt1 = (x, 0)
        pt2 = (x, resize_height)
        cv2.line(img_resized, pt1, pt2, (150, 0, 150))
    for y in xrange(grid_size, resize_height, grid_size):
        pt1 = (0, y)
        pt2 = (resize_width, y)
        cv2.line(img_resized, pt1, pt2, (150, 0, 150))

    cv2.imshow('frame', img_resized)
    key = cv2.waitKey(100000) & 0xff
    if key == 27:
        break


import re
import string

import torch
from torch.utils.data import Dataset, DataLoader

vocab = string.ascii_lowercase + ' .'

def one_hot(s: str):
    """
    Converts a string into a one-hot encoding
    :param s: a string with characters in vocab (all other characters will be ignored!)
    :return: a once hot encoding Tensor r (len(vocab), len(s)), with r[j, i] = (s[i] == vocab[j])
    """
    import numpy as np
    if len(s) == 0:
        return torch.zeros((len(vocab), 0))
    return torch.as_tensor(np.array(list(s.lower()))[None, :] == np.array(list(vocab))[:, None]).float()

class SpeechDataset(Dataset):
    """
    Creates a dataset of strings from a text file.
    All strings will be of length max_len and padded with '.' if needed.

    By default this dataset will return a string, this string is not directly readable by pytorch.
    Use transform (e.g. one_hot) to convert the string into a Tensor.
    """

    def __init__(self, dataset_path, transform=None, max_len=250):
        with open(dataset_path) as file:
            Data = file.read()

        #code below seems to just make text lower case, remove spacing after period.  Tokenize?
        Data = Data.lower()
        reg = re.compile('[^%s]' % vocab)
        period = re.compile(r'[ .]*\.[ .]*')
        space = re.compile(r' +')
        sentence = re.compile(r'[^.]*\.')
        self.data = space.sub(' ',period.sub('.',reg.sub('', Data)))  #removes spacing after period?

        #print (f'the size of data is {len(self.data)}')
        if max_len is None:
            self.range = [(m.start(), m.end()) for m in sentence.finditer(self.data)]
        else:
            self.range = [(m.start(), m.start()+max_len) for m in sentence.finditer(self.data)]
            self.data += self.data[:max_len]

        if transform is not None:

            self.data = transform(self.data)

    def __len__(self):
        return len(self.range)

    def __getitem__(self, idx):
        s, e = self.range[idx]
        #print (f'self range is {self.range[idx]}')
        #print (f'index is {idx}, s is {s}, and e is {e}')
        #print (f'self.range[idx] is {self.range[idx]}, and e-s is {e-s}')
        #index is 752, s is 79351, and e is 79418
        if isinstance(self.data, str):
            #print (f'Based on above numbers, returning self.data[s:e]: {self.data[s:e]} ')
            return self.data[s:e]        #if it's a string, return s to e substring only
        #print ("NOT A STRING")
        #print (f'returning self.data[:, s:e]  : {self.data[:, s:e].shape}')
        #shape of self.data[:, s:e] is ([28, s-e])
        return self.data[:, s:e]   #how to randomize this?

def load_data(dataset_path, num_workers=0, batch_size=32, **kwargs):
    dataset = SpeechDataset(dataset_path, **kwargs)
    print("load_data()------->LOADED DATASET SANTOS, this one below:")
    print(dataset_path)
    return DataLoader(dataset, num_workers=num_workers, batch_size=batch_size, shuffle=True, drop_last=True)

if __name__ == "__main__":
    print ("Starting execution of utils.py")

    """
    data = SpeechDataset('data/valid.txt', max_len=None)
    print('Dataset size BEFORE TRANSFORM is ', len(data))

    print (f'data[0] is {data[0]}')
    print (f'data[1] is {data[1]}')  #is i did not know mr.
    print (f'data[2] is {data[2]}')  #is cronkite personally.
    print (f'data[1][x] is {data[1][14]}')
    print (f'data[2][x] is {data[2][15]}')

    print (f'data[0] size is {len(data[0])}')
    print (f'data[1] size is {len(data[1])}')  #data[1] size is 18
    print (f'data[2] size is {len(data[2])}')  #data[2] size is 20

    #for i in range(min(len(data), 10)):
     #   print(data[i])

    print("-------------------------------")

    #print("From main()------>tranforming data to one hot now")

    data = SpeechDataset('data/valid.txt', transform=one_hot, max_len=None)

    print (f'data[0] size is {data[0].shape}')
    print (f'data[1] size is {data[1].shape}')
    print (f'data[2] size is {data[2].shape}')

    print('TRANSFORMED Dataset size ', len(data))  #856
    #print('TRANSFORMED Dataset shape ', data.dtype)

    #for i in range(min(len(data), 3)):
     #   print(data[i])

     """

    print("--------------------------------------------------------------------")
    print ("USING THE LOADER NOW")
    train_data = load_data('data/train.txt',  transform=one_hot)

    #train_data = load_data('data/valid.txt',  max_len=None)
    #Transform did not work, raised stack exception: load_data('data/valid.txt',  transform=one_hot, max_len=None)
    for s in train_data:
      print (s.shape)#torch.Size([32, 28, 250])


#########################
# DESARROLLADOR
# RMPG - LUIS ANGEL VALLEJO PEREZ
#########################
import sys
import os
import shutil
from resources import *
from PyQt5 import  *
from PyQt5.QtCore import QPropertyAnimation, Qt
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QIcon, QPixmap, QMouseEvent
from VPrincipal import *
# comment importamos concesionarios
from Reports_Logic.Rio_Bravo.Home_KWRB import *
from Reports_Logic.KenworthEste.Home_KWESTE import *
from Reports_Logic.KREI.Home_KREI import *
from Reports_Logic.Kenworth_Sonora.Home_KWSonora import *
#------------
from datetime import *
import webbrowser

class my_app(QMainWindow, Variables):
    def __init__(self):
        super(my_app, self).__init__()
        self.ui = Ui_VPrincipal()
        self.ui.setupUi(self)
        self.setWindowFlags(self.windowFlags() | Qt.FramelessWindowHint)
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.setWindowTitle("Menu de Sucursales")
        # self.ui.centralwidget.setStyleSheet("background-color:rgb(255, 255, 255);")
        self.ui.imgPrincipalMenu.setPixmap(QPixmap(":/Source/LOGO_KREI.png"))
        self.setWindowIcon(QIcon(":/Source/LOGO_KREI_3.ico"))
        self.ui.btc_btc_cerrar.setIcon(QIcon(":Source/Icon_Close.png"))
        self.ui.btc_btc_minimizar.setIcon(QIcon(":Source/Icon_Minimize.png"))
        self.ui.panel_encabezado.setStyleSheet("margin-top:5px;")
        self.ui.btn_btn_kwrb.clicked.connect(self.VentanaRioBravo)
        self.ui.btn_btn_kweste.clicked.connect(self.VentanaKWESTE)
        self.ui.btn_btn_kwkrei.clicked.connect(self.VentanaKREI)
        self.ui.btn_btn_kwsonora.clicked.connect(self.VentanaSonora)

        self.ui.btc_btc_cerrar.clicked.connect(self.cerrar)
        self.ui.btc_btc_minimizar.clicked.connect(self.minimizar)

#-------------------------------------------------
    def VentanaRioBravo(self):
        self.Ventana = Home_KWRB()
        self.Ventana.show()
#-------------------------------------------------
    def VentanaKWESTE(self):
        self.Ventana = Home_KWESTE()
        self.Ventana.show()
#-------------------------------------------------
    def VentanaKREI(self):
        self.Ventana = Home_KREI()
        self.Ventana.show()
#-------------------------------------------------
    def VentanaSonora(self):
        self.Ventana = Home_KenworthSonora()
        self.Ventana.show()
#-------------------------------------------------
    def cerrar(self):
        self.close()

    def minimizar(self):
        self.showMinimized()
if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = my_app()
    window.show()
    sys.exit(app.exec_())


import os

def number_of_files(directory: str):
    main_dir = os.listdir(directory)
    count = 0
    for item in main_dir:
        if os.path.isfile(directory + f'\\{item}'):
            count += 1
    return count

def tab_generator(count: int):
    tab_str = ''
    for _ in range(count):
        tab_str += '\t'
    return tab_str

def display_sub_dirs(directory: str, iteration: int = 0):
    sub_dirs = [os.path.join(directory, d) for d in os.listdir(directory) if os.path.isdir(os.path.join(directory, d))]
    for item in sub_dirs:
        subdir_files = os.listdir(item)
        print(tab_generator(iteration) + item)
        for file in subdir_files:
            if os.path.isfile(os.path.join(item, file)):
                print(tab_generator(iteration) + '\t' + file)
        display_sub_dirs(item, iteration+1)

print(number_of_files('C:\\dev'))

display_sub_dirs('C:\\dev')


import numpy as np
import ndnn.node as nd
import ndnn.graph as ng
import ndnn.loss as nl
import ndnn.sgd as ns
import ndnn.dataset as nds
import ndnn.store as nst

train_file = "data/senti.binary.train"
dev_file = "data/senti.binary.dev"
test_file = "data/senti.binary.test"

model_file = "attention.mdl"
store = nst.ParamStore(model_file)
params = store.load()

embed = params[0]
att_w = params[1]

# Word Vector Dimension
word_dict = {}
word_variance = {}
def load(file_name):
    lines = open(file_name, "rb").readlines()
    for line in lines:
        pieces = line.split()
        words = pieces[0:-1]
        for word in words:
            if word not in word_dict:
                word_dict[word] = len(word_dict)

# Load data
load(train_file)
load(dev_file)
load(test_file)

lines = open(train_file, "rb").readlines()
for line in lines:
    pieces = line.split()
    words = pieces[0:-1]
    for word in words:
        if word not in word_variance:
            word_variance[word] = []
    word_idx = [word_dict[word] for w in words]
    word_embed = embed[word_idx, :]
    word_map = np.matmul(word_embed, att_w)
    lmax = np.max(word_map, axis=-1, keepdims=True)
    ex = np.exp(word_map - lmax)
    softmax = ex / np.sum(ex, axis=-1, keepdims=True)

    for idx, word in enumerate(words):
        word_variance[word].append(softmax[idx])

stats = []

for w in word_variance:
    data = word_variance[w]
    mean = np.mean(data)
    var = np.var(data)

    stats.append((mean, var, w))

stats.sort(key=lambda x:x[0])

print(stats[:10])
print(stats[-10:])

stats.sort(key=lambda x:x[1])
print(stats[:10])


import base64
import time

# Function that decodes the bytes of payload from the wearable device
def decodeMACPayload(payload):
    # Value of MAC Payload in hex format
    mac_payload = base64.b64decode(payload).hex()

    # Get the integer part and the decimal part of the air temperature from the payload
    integer_temperature = int(str(int(mac_payload[-8:-4], 16))[:2])
    decimal_temperature = int(str(int(mac_payload[-8:-4], 16))[2:])

    # Determine the value of air temperature
    air_temperature = integer_temperature + 0.01*decimal_temperature

    # Get the integer part and the decimal part of the relative humidity from the payload
    integer_humidity = int(str(int(mac_payload[-4:], 16))[:2])
    decimal_humidity = int(str(int(mac_payload[-4:], 16))[2:])

    # Determine the value of relative humidity
    relative_humidity = integer_humidity + 0.01*decimal_humidity

    # Value of total energy expenditure in kCal
    decimal_energy_exp = int(mac_payload[34:42], 16) * 0.1

    # Get the value of VOC index from the payload
    voc_index = int(mac_payload[-16:-12], 16)

    # Get the value of current timestamp in UNIX format
    unix_timestamp = int(time.time())

    return [air_temperature, relative_humidity, voc_index, unix_timestamp, decimal_energy_exp]


from my_funs import *

# set local path to ontologies
path_to_ontologies = '/home/axel/Documents/ontologies/ont_selection'

# sqlite3 and GEOmetadb, download db using R
import sqlite3
conn = sqlite3.connect('GEOmetadb.sqlite')
# the next line address UTF8 issues
#conn.text_factory = bytes
conn.text_factory = lambda x: str(x, 'latin1')

# getting relevant data from GEOmetadb
# get gses with from relevant techniques
#gse = pd.read_sql_query("SELECT * FROM gse ", conn)

gse = pd.read_sql_query("SELECT * FROM gse WHERE type = 'Expression profiling by array' OR type = 'Expression profiling by high throughput sequencing';", conn)

# get gsms from relevant species
species = ("Homo sapiens", "Mus musculus", "Rattus norvegicus",
             "Rattus rattus",
             "Mus musculus;	Rattus norvegicus",
             "Mus musculus;	Rattus rattus",
             "Homo sapiens;	Mus musculus")
gsm = pd.read_sql_query("SELECT * FROM gsm WHERE organism_ch1 in "+str(species)+" OR source_name_ch1 in "+str(species) , conn)

#rename series_id column of gsm table to gse
gsm.rename(columns={'series_id': 'gse'}, inplace=True)

#join gse and gsm
gsem = pd.merge(gse, gsm, on='gse')
gsem_selection = gsem[['title_x', 'gse', 'submission_date_x', 'summary',
                       'type_x', 'organism_ch1']].drop_duplicates()
gsem_selection.set_index('gse', inplace=True)

# get list of ontologies
owls =  get_owls(path_to_ontologies)

# create a df with all ontologies integrated, identified terms and parent terms
df = update_all(gsem_selection, owls)

# write to csv
df.to_csv("gsem_selection_onts.tsv", sep="\t")


"""Console script for crystfelparser."""

from collections import defaultdict
from xmlrpc.client import Boolean
from tqdm import tqdm
import numpy as np
import argparse
import sys

from crystfelparser.utils import save_dict_to_hdf5

# Just round up and down the time, we can extend this to a larger time window

def round_time(raw_spots, dt=0):
    """
    Function for rouding the time/angle

    Args:
      raw_spots: matrix where each row is [SPOT_X, SPOT_Y, FRAME]
      dt: time window to flatten into a single frame [-dt,+dt]

    Returns:
      A numpy array where each row is [SPOT_X, SPOT_Y, FRAME_ROUNDED]
    """

    # we could remove duplicates here
    # set_of_floats=set(list(map(tuple,raw_spots[:,:3])))
    max_frame = int(np.max(raw_spots[:, 2]))
    expanded_list = []
    for spot in raw_spots:
        # round to the time to the earest integer
        rounded = np.round(spot[2])
        # set the lower bound
        min_round = max(0, rounded - dt)
        # set the upper bound
        max_round = min(rounded + dt + 1, max_frame + 1)

        for new_time in np.arange(min_round, max_round):
            expanded_list.append((spot[0], spot[1], new_time))

    return np.asarray(expanded_list)

def match_spots_frame_expanded(spots, n_frame):
    """
    Given the list of spots found by XDS and a specific frame number,
    return the list of centers found matching the frame number given

    Args:
      spots: matrix where each row is [SPOT_X, SPOT_Y, FRAME]
      n_frame: the frame to select

    Returns:
      A numpy array containing the spots for the selected frame
    """

    # find all the spots in the same frame
    idx_rows = np.where(list(map(int, spots[:, 2])) == n_frame)
    tmp_list = spots[idx_rows, ([0], [1])].T

    # I use set to remove possible duplicates
    return np.asarray(list(set(list(map(tuple, tmp_list)))))

def get_list_spots_fromfile(filename, colspot=False, timerounded=True, shift_min=True, dt=3):
    """
    Load spot centers from a file and return a dictionary where each key
    is a frame number

    Args:
      filename: filepath containing the output from XDS [e.g. SPOT.XDS, XDS.XDS_ASCII.HKL]
      colspot: flag to specify if the file is XDS.XDS_ASCII.HKL or SPOT.XDS [Default: False]
      timerounded: flag to round or not the frame number [default: True]
      shift_min: flag to shif the minimum frame to zero [default: True]
      dt: window of frames to collaps within a central frame [-dt, dt] [default: 3]

    Returns:
      A dictionary with the spots per frame, where each frame is a frame number
    """

    dict_spots = defaultdict(lambda: [])

    if colspot:
        # reading SPOT.XDS
        spots_reflections_raw = np.loadtxt(filename)
    else:
        # eading XDS_ASCII.HKL
        spots_reflections_raw = []
        with open(filename, encoding='utf-8') as f:
            lines = f.readlines()
            for line in lines:
                if line.split()[0][0] != "!":
                    spots_reflections_raw.append(
                        list(map(float, line.split()[5:8])))
        spots_reflections_raw = np.asarray(spots_reflections_raw)

    if timerounded:
        spots_reflections_raw = round_time(spots_reflections_raw, dt)

    # get unique frames
    # frames=set(rounded_spots[:,2])
    frames = set(spots_reflections_raw[:, 2].astype(int))
    min_framenum = 0
    if shift_min:
        min_framenum = min(frames)

    for fr in tqdm(frames):
        dict_spots[fr -
                   min_framenum] = match_spots_frame_expanded(spots_reflections_raw, fr)

    return dict_spots

###################################################
# Script to be called from the command line

def str2bool(v):
    if isinstance(v, bool):
        return v
    if v.lower() in ('yes', 'true', 't', 'y', '1'):
        return True
    elif v.lower() in ('no', 'false', 'f', 'n', '0'):
        return False
    else:
        raise argparse.ArgumentTypeError('Boolean value expected.')

def parse_args():
    """Parser"""
    parser = argparse.ArgumentParser(
        description='Console script to parse XDS_ASCII.HKL (or SPOT.XDS)'
    )

    parser.add_argument(
        '--file', default="XDS_ASCII.HKL", help='XDS file to parse [e.g. XDS_ASCII.HKL]'
    )

    parser.add_argument("--colspot", type=str2bool, nargs='?', const=True, default=False,
                        help="Reading a SPOT.XDS file (COLSPOT output) [Default: False]."
                        )

    parser.add_argument(
        '--dt', type=int, default=0, help='Time window to flatten [-dt, dt] [Default: 0]'
    )

    parser.add_argument(
        '--output',
        default="parsed_xds.h5",
        help='Parsed file, stored in hdf5 format [default: parsed_xds.h5]',
    )

    if len(sys.argv) == 1:
        parser.print_help(sys.stderr)
    else:
        args = parser.parse_args()
        # args.func(**vars(args))

        return args

def main():
    """ """
    # read from the parser
    inputs = parse_args()

    # parse the input stream
    print("Parsing {}".format(inputs.file))

    timerounded = False
    if inputs.dt > 0:
        timerounded = True

    # for now shift_min is always True
    parsed_stream = get_list_spots_fromfile(
        inputs.file, inputs.colspot, timerounded, True, inputs.dt)

    # save the input stream to a .h5 file
    save_dict_to_hdf5(parsed_stream, inputs.output)
    print("Parsed frames saved in {}".format(inputs.output))

if __name__ == "__main__":
    sys.exit(main())


'''
Jaqlyn A
Dec 3 2021
Celsius-Fahrenheit Conversion
'''

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

def c_to_f(c):
    f = c * (9/5) + 32
    return f

def f_to_c(f):
    c = f - 32 * (5/9)
    return c

while True:
    user_choice = input('Would you like to convert °C to °F (1) or °F to °C (2)? ')
    if user_choice == '1':
        while True:
            user_celsius = input('Enter your °C temperature: ')
            try:
                user_celsius = float(user_celsius)
                print('Your new temperature would be ' + str(c_to_f(user_celsius)) + '°F.')
                break
            except ValueError:
                print('Please enter a number value.')
                continue
    elif user_choice == '2':
        while True:
            user_fahrenheit = input('Enter your °F temperature: ')
            try:
                user_fahrenheit = float(user_fahrenheit)
                print('Your new temperature would be ' + str(f_to_c(user_fahrenheit)) + '°C.')
                break
            except ValueError:
                print('Please enter a number value.')
                continue
    else:
        print('Please enter 1 or 2.')
        continue


from email.mime import audio
from pytube import YouTube
from moviepy.editor import *

def download_from_yt():
    file1 = open('myfile.txt', 'r')
    Lines = file1.readlines()

    for line in Lines:
        yt = YouTube(line)
        stream = yt.streams.get_audio_only()
        stream.download()
        print(f'Done {stream.title}')

def convert_to_mp3():
    for filename in os.listdir("files"):
        clip = AudioFileClip(f'files/{filename}')
        clip.write_audiofile(f'files/ready/{filename}.mp3')
        print(f'Done {filename}.mp3')

print("1. Download\n2.Convert")
x = input()

if (x == "1"):
    download_from_yt()
else:
    convert_to_mp3()


#
# @lc app=leetcode id=16 lang=python3
#
# [16] 3Sum Closest
#

# @lc code=start
class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        nums.sort()
        length = len(nums)
        best_s = 100000
        for i, num in enumerate(nums):
            if i > 0 and num == nums[i - 1]:
                continue
            l, r = i + 1, length - 1
            while l < r:
                s = nums[l] + nums[r] + num
                if s == target:
                    return s

                if abs(target - s) < abs(target - best_s):
                    best_s = s

                if s <= target:
                    l += 1
                    while nums[l] == nums[l - 1] and l < r:
                        l += 1
                else:
                    r -= 1

        return best_s

# @lc code=end