from __future__ import print_function
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import matplotlib.pyplot as plt
import argparse
import os
import sys
import tempfile
import numpy as np

FLAGS = None

def weight_variable(shape):
    initial = tf.truncated_normal(shape, stddev=0.1)
    return tf.Variable(initial)

def bias_variable(shape):
    initial = tf.constant(0.1, shape=shape)
    return tf.Variable(initial)

def conv2d(x, W):
    """conv2d returns a 2d convolution layer with full stride and padding."""
    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

def max_pool_2x2(x):
    """max_pool_2x2 downsamples a feature map by 2X."""
    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
                        strides=[1, 2, 2, 1], padding='SAME')
def conv2dtransp(x, W, o1, o2):
     # conv2dtransp returns a 2d transposed convolution layer with stride of 2 and padding
     temp_batch_size = tf.shape(x)[0]
     output_shape = [temp_batch_size, o1, o1, o2]
     return tf.nn.conv2d_transpose(x, W, output_shape, strides=[1, 2, 2, 1], padding='SAME')

def deep(x):
    """ deep builts a graph for the autoencoder """

    # Reshape to use within a convolutional neural net.
    with tf.name_scope('reshape'):
      x_image = tf.reshape(x, [-1, 28, 28, 1])

    # First convolutional layer - maps one grayscale image to 8 feature maps.
    # Output size :28x28x8
    with tf.name_scope('conv1'):
      W_conv1 = weight_variable([3, 3, 1, 8])
      b_conv1 = bias_variable([8])
      h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)

    # Pooling layer - downsamples by 2X.
    # Output size: 14x14x8
    with tf.name_scope('pool1'):
     h_pool1 = max_pool_2x2(h_conv1)

    # Second convolutional layer -- maps  8 feature maps to 4.
    # Output size : 14x14x4
     with tf.name_scope('conv2'):
       W_conv2 = weight_variable([3, 3, 8, 4])
       b_conv2 = bias_variable([4])
       h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)

    # Second pooling layer.
    # Output size : 7x7x4
    with tf.name_scope('pool2'):
       h_pool2 = max_pool_2x2(h_conv2)

    # Third convolutional layer -- maps  4 feature maps to 2.
    # Output size : 7x7x2
    with tf.name_scope('conv3'):
      W_conv3 = weight_variable([3, 3, 4, 2])
      b_conv3 = bias_variable([2])
      h_conv3 = tf.nn.relu(conv2d(h_pool2, W_conv3) + b_conv3)

    # First transposed convolutional layer -- maps  2 feature maps to 4.
    # Output size : 14x14x4
    with tf.name_scope('transpconv1'):
      W_trconv1 = weight_variable([2, 2, 4, 2])
      b_trconv1 = bias_variable([4])
      h_trconv1 = tf.nn.relu(conv2dtransp(h_conv3, W_trconv1, 14, 4) + b_trconv1)

    # Fourth convolutional layer -- maps  4 feature maps to 4.
    # Output size : 14x14x4
    with tf.name_scope('conv4'):
      W_conv4 = weight_variable([3, 3, 4, 4])
      b_conv4 = bias_variable([4])
      h_conv4 = tf.nn.relu(conv2d(h_trconv1, W_conv4) + b_conv4)

    # Second transposed convolutional layer -- maps  4 feature maps to 8.
    # Output size : 28x28x8
    with tf.name_scope('transpconv2'):
      W_trconv2 = weight_variable([2, 2, 8, 4])
      b_trconv2 = bias_variable([8])
      h_trconv2 = tf.nn.relu(conv2dtransp(h_conv4, W_trconv2, 28, 8) + b_trconv2)

    # Fifth convolutional layer -- maps  8 feature maps to 8.
    # Output size : 28x28x8
    with tf.name_scope('conv5'):
      W_conv5 = weight_variable([3, 3, 8, 8])
      b_conv5 = bias_variable([8])
      h_conv5 = tf.nn.relu(conv2d(h_trconv2, W_conv5) + b_conv5)

    # Output convolutional layer -- maps  8 feature maps to 1
    # Output size : 28x28x1
    with tf.name_scope('outputconv'):
       W_out = weight_variable([3, 3, 8, 1])
       b_out = bias_variable([1])
       h_out = tf.nn.relu(conv2d(h_conv5, W_out) + b_out)
    return h_out

def main(_):
    mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)
    display_step = 1000
    # Create the model
    learning_rates = tf.placeholder(tf.float32)
    # scale every image to values between 0 and 1
    x_image = tf.placeholder(tf.float32, [None, 784])/ 255
    new_xs = deep(x_image)
    # for the reconstructed images
    img_autoenc = tf.summary.image("autoencoder", new_xs, max_outputs=2)

    new_x = tf.reshape(new_xs, [64, 784])

    with tf.name_scope('loss'):
      loss = tf.reduce_mean(tf.square(new_x - x_image))

    learning_rates = [1e-1, 1e-2, 1e-3]
    for rate in learning_rates:
        with tf.name_scope('Adam_optimizer'):
            optimizer = tf.train.AdamOptimizer(rate).minimize(loss)
        with tf.Session() as sess:
            sess.run(tf.global_variables_initializer())
            writer = tf.summary.FileWriter(FLAGS.log_dir + '/learningRate'
                                   + str(rate), sess.graph)
            num_steps = 20000
            epochs = []
            x_loss = []
            for i in range(num_steps + 1):
               batch, _ = mnist.train.next_batch(64)
               # Run optimization op (backprop) and cost op (to get loss value)
               _, l = sess.run([optimizer, loss], feed_dict={x_image: batch})
               # Display logs per step
               if i % display_step == 0:
                   # Displaying the images in tensorboard
                   train_loss, img = sess.run([loss, img_autoenc],
                                          feed_dict={x_image: batch})
                   writer.add_summary(img, i)
                   print('Step %i: Minibatch Loss: %f' % (i, l))
                   epochs.append(i)
                   x_loss.append(l)
            writer.close()
            plt.plot(epochs, x_loss, label=rate)

    # for plotting the learning curves
    plt.xlabel('epochs')
    plt.ylabel('loss')
    plt.legend(loc='lower right')
    plt.show()

if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.add_argument('--data_dir', type=str,
                      default='/tmp/tensorflow/mnist/input_data',
                      help='Directory for storing input data')
  parser.add_argument('--log_dir', type=str,
                      default=os.path.join(os.getenv('HOME', '/home'),
                                           'lab/tensorflow'),
                      help='Summaries log directory')
  FLAGS, unparsed = parser.parse_known_args()
  tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)


# -*- coding: utf-8 -*-
"""
Created on Fri Oct  4 17:48:18 2019

@author: train
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import sys
import argparse
import tensorflow as tf
import numpy as np
import align.detect_face
import cv2

# 从摄像头读取视频流　并检测人脸(可设置单个脸检测)
def main(args):
    with tf.Graph().as_default():
        gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=args.gpu_memory_fraction)
        sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False))
        with sess.as_default():
            pnet, rnet, onet = align.detect_face.create_mtcnn(sess, None)

    minsize = 20 # minimum size of face
    threshold = [ 0.6, 0.7, 0.7 ]  # three steps's threshold
    factor = 0.709 # scale factor

    cap = cv2.VideoCapture(0)
    size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),
        int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
    print('size:'+repr(size))

    while True:
        ret,frame = cap.read()
        img = frame
        img = img[:,:,0:3]

        bounding_boxes, _ = align.detect_face.detect_face(img, minsize, pnet, rnet, onet, threshold, factor)

        nrof_faces = bounding_boxes.shape[0]
        if nrof_faces>0:
            det = bounding_boxes[:,0:4]
            det_arr = []
            img_size = np.asarray(img.shape)[0:2]
            if nrof_faces>1:
                if args.detect_multiple_faces:
                    for i in range(nrof_faces):
                        det_arr.append(np.squeeze(det[i]))
                else:
                    bounding_box_size = (det[:,2]-det[:,0])*(det[:,3]-det[:,1])
                    img_center = img_size / 2
                    offsets = np.vstack([ (det[:,0]+det[:,2])/2-img_center[1], (det[:,1]+det[:,3])/2-img_center[0] ])
                    offset_dist_squared = np.sum(np.power(offsets,2.0),0)
                    index = np.argmax(bounding_box_size-offset_dist_squared*2.0) # some extra weight on the centering
                    det_arr.append(det[index,:])
            else:
                det_arr.append(np.squeeze(det))

            bb = np.zeros((nrof_faces,4),dtype=np.int32)
            for i, det in enumerate(det_arr):
                det = np.squeeze(det)
                bb[i][0] = np.maximum(det[0]-args.margin/2, 0)
                bb[i][1] = np.maximum(det[1]-args.margin/2, 0)
                bb[i][2] = np.minimum(det[2]+args.margin/2, img_size[1])
                bb[i][3] = np.minimum(det[3]+args.margin/2, img_size[0])
                cv2.rectangle(frame, (bb[i][0], bb[i][1]), (bb[i][2],bb[i][3]), (0, 255, 0), 2)
                cv2.putText(frame, "No Body", (bb[i][0],bb[i][1]), cv2.FONT_HERSHEY_COMPLEX, 1, (0,255,0), 2)
#
        cv2.imshow("Video",frame)
        c = cv2.waitKey(1)

        if c==27:
            break
    cap.release()
    cv2.destroyAllWindows()

def parse_arguments(argv):
    parser = argparse.ArgumentParser()

    parser.add_argument('--image_size', type=int,
        help='Image size (height, width) in pixels.', default=160)
    parser.add_argument('--margin', type=int,
        help='Margin for the crop around the bounding box (height, width) in pixels.', default=44)
    parser.add_argument('--random_order',
        help='Shuffles the order of images to enable alignment using multiple processes.', action='store_true')
    parser.add_argument('--gpu_memory_fraction', type=float,
        help='Upper bound on the amount of GPU memory that will be used by the process.', default=1.0)
    parser.add_argument('--detect_multiple_faces', type=bool,
                        help='Detect and align multiple faces per image.', default=True)
    return parser.parse_args(argv)

if __name__ == '__main__':
    main(parse_arguments(sys.argv[1:]))


import douiftelegrambot
import json
from pathlib import Path

TOKEN_FILEPATH = f"{Path(__file__).parent}/token.json"

def main() -> None:
    print("Start System.")
    token = read_token()
    main_system = douiftelegrambot.MainSystem(token)
    print("Initial finish.")
    main_system.start_system()

def read_token() -> dict:
    result = json.load(open(TOKEN_FILEPATH, mode="r", encoding="utf8"))
    return result

if __name__ == "__main__":
    main()


class Node(object):
    def __init__(self, value):

        self.value = value
        self.nextnode = None

def cycle_check(node):
    head_node = node
    while node is not None:
        if node.nextnode == head_node:
            return True
            break
        node = node.nextnode
    return False

# CREATE CYCLE LIST
a = Node(1)
b = Node(2)
c = Node(3)

a.nextnode = b
b.nextnode = c
c.nextnode = a  # Cycle Here!

print(cycle_check(a))


import ipfshttpclient

# contributing to one document by multiple nodes

with ipfshttpclient.connect() as client:
    hash = client.add('conv.txt')['Hash']
    client.key.rm('example_key')
    key = client.key.gen('example_key', 'rsa')['Id']
    print('key list', client.key.list())
    published = client.name.publish('/ipfs/' + hash, key=key)

    # find
    print(client.name.resolve(key))
    print('file hash', hash)


import random
import arcade
import math
import os

# --- Constants ---
SPRITE_SCALING_PREY = 0.9
SPRITE_SCALING_PRED = 0.7

PREY_COUNT = 10
PRED_COUNT = 5

PRED_SPEED = 1.2

MAX_PREY = 30

SCREEN_WIDTH = 1200
SCREEN_HEIGHT = 800
SCREEN_TITLE = "Pred VS Prey"

PRED_ANGLE_SPEED = 5
SPRITE_SPEED = 0.5
PRED_IMAGE = ":resources:images/topdown_tanks/tank_red.png"
PREY_IMAGE = ":resources:images/topdown_tanks/tank_blue.png"

class Animal(arcade.Sprite):

    def __init__(self, *args):
        super(Animal, self).__init__(*args)
        self.breed_point = 0
        self.angle = 0
        self.max_breed = 0
        self.image = None
        self.scale_size = 0
        self.max_count = 0
        self.init_count = 0

    def make_animal(self, image, scale_size):
        return Animal(image, scale_size)

    def breed(self):
        if self.breed_point >= self.max_breed:
            new_animal = self.make_animal(self.image, self.scale_size)
            new_animal.center_x = self.center_x + random.randrange(-2, 2)
            new_animal.center_y = self.center_y + random.randrange(-2, 2)
            new_animal.change_x = random.randrange(-1, 1, 2) * self.change_x
            new_animal.change_y = random.randrange(-1, 1, 2) * self.change_y
            new_animal.angle = math.degrees(math.atan2(new_animal.change_y, new_animal.change_x)) + 90
            self.breed_point = 0
            return new_animal
        else:
            self.breed_point += random.randrange(1, 2)
        return 1

    def find_closest(self, diff_list):
        min_dist = 10000
        closest = None
        for pred_sprite in diff_list:
            x_diff = pred_sprite.center_x - self.center_x
            y_diff = pred_sprite.center_y - self.center_y
            distance = math.sqrt(x_diff ** 2 + y_diff ** 2)
            if distance < min_dist:
                min_dist = distance
                closest = pred_sprite
        return closest, min_dist

class Prey(Animal):
    def __init__(self, *args):
        super(Prey, self).__init__(*args)
        self.angle = math.degrees(math.atan2(self.change_y, self.change_x)) + 90
        self.scale_size = SPRITE_SCALING_PREY
        self.max_breed = 700
        self.image = PREY_IMAGE
        self.dist_juke = 200
        self.dist_go_away = 500
        self.change_x = 0.6
        self.change_y = 0.4
        self.breed_point = 0
        self.center_x = random.randrange(SCREEN_WIDTH)
        self.center_y = random.randrange(SCREEN_HEIGHT)

    def make_animal(self, image, scale_size):
        return Prey(image, scale_size)

    def juke_kill(self, pred_list):
        pred_sprite, min_dist = self.find_closest(pred_list)
        self.center_x += self.change_x
        self.center_y += self.change_y

        if min_dist <= self.dist_go_away:
            if random.randrange(100) == 0:
                start_x = self.center_x
                start_y = self.center_y

                # Get the destination location for the bullet
                dest_x = pred_sprite.center_x
                dest_y = pred_sprite.center_y

                x_diff = dest_x - start_x
                y_diff = dest_y - start_y
                angle = math.atan2(y_diff, x_diff)

                self.change_x = -math.cos(angle) * SPRITE_SPEED * 4
                self.change_y = -math.sin(angle) * SPRITE_SPEED * 4
                changed_angle = math.degrees(math.atan2(self.change_y, self.change_x))
                self.angle = changed_angle + 90

        if min_dist <= self.dist_juke:
            if random.randrange(100) == 0:
                start_x = self.center_x
                start_y = self.center_y

                # Get the destination location for the bullet
                dest_x = pred_sprite.center_x
                dest_y = pred_sprite.center_y

                # Do math to calculate how to get the bullet to the destination.

                x_diff = dest_x - start_x
                y_diff = dest_y - start_y
                angle = math.atan2(y_diff, x_diff)

                # Taking into account the angle, calculate our change_x
                # and change_y. Velocity is how fast the bullet travels.
                self.change_x = math.sin(angle) * SPRITE_SPEED * 8
                self.change_y = math.cos(angle) * SPRITE_SPEED * 8
                changed_angle = math.degrees(math.atan2(self.change_y, self.change_x))
                self.angle = changed_angle + 90

class Pred(Animal):

    def __init__(self, *args):
        super(Pred, self).__init__(*args)
        self.breed_point = 0
        self.max_breed = 900
        self.hungry_point = 500
        self.angle = 0
        self.image = PRED_IMAGE
        self.scale_size = SPRITE_SCALING_PRED
        self.center_x = random.randrange(SCREEN_WIDTH)
        self.center_y = random.randrange(SCREEN_HEIGHT)

    def make_animal(self, image, scale_size):
        return Pred(image, scale_size)

    def hunger(self):
        if self.hungry_point <= 0:
            self.kill()
        else:
            self.hungry_point -= 1

    def follow_prey(self, prey_list):
        prey_sprite, min_dist = self.find_closest(prey_list)
        self.center_x += self.change_x
        self.center_y += self.change_y

        # Random 1 in 100 chance that we'll change from our old direction and
        # then re-aim toward the prey
        if random.randrange(50) == 0:
            start_x = self.center_x
            start_y = self.center_y

            # Get the destination location for the bullet
            dest_x = prey_sprite.center_x
            dest_y = prey_sprite.center_y

            x_diff = dest_x - start_x
            y_diff = dest_y - start_y
            angle = math.atan2(y_diff, x_diff)
            self.angle = math.degrees(angle) + 90

            # Taking into account the angle, calculate our change_x
            # and change_y. Velocity is how fast the bullet travels.
            self.change_x = math.cos(angle) * PRED_SPEED * 1.3 * (SCREEN_WIDTH / (min_dist * 4))
            self.change_y = math.sin(angle) * PRED_SPEED * 1.3 * (SCREEN_HEIGHT / (min_dist * 4))

class MyGame(arcade.Window):

    def __init__(self):
        """ Initializer """
        # Call the parent class initializer
        super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)

        file_path = os.path.dirname(os.path.abspath(__file__))
        os.chdir(file_path)

        # Variables that will hold sprite lists
        self.prey_list = None
        self.pred_list = None
        self.winner = None

        # Don't show the mouse cursor
        self.set_mouse_visible(False)

        arcade.set_background_color(arcade.color.AMAZON)

    def setup(self):
        """ Set up the game and initialize the variables. """

        # Sprite lists
        self.prey_list = arcade.SpriteList()
        self.pred_list = arcade.SpriteList()

        for i in range(PREY_COUNT):
            prey_sprite = Prey(PREY_IMAGE, SPRITE_SCALING_PREY)
            self.prey_list.append(prey_sprite)

        for i in range(PRED_COUNT):
            pred = Pred(PRED_IMAGE, SPRITE_SCALING_PRED)
            self.pred_list.append(pred)

    def on_draw(self):
        """ Draw everything """
        self.clear()
        self.pred_list.draw()
        self.prey_list.draw()

        for i, prey in enumerate(self.prey_list):
            angle_rad = math.radians(prey.angle)
            arcade.draw_line(prey.center_x, prey.center_y, prey.center_x + 20 * math.sin(angle_rad),
                             prey.center_y - 20 * math.cos(angle_rad), arcade.color.BLUE, 1)
            output = f"Prey Breed: {prey.breed_point}"
            arcade.draw_text(output, 10, i * 20, arcade.color.WHITE, 14)

        for i, pred in enumerate(self.pred_list):
            angle_rad = math.radians(pred.angle)
            arcade.draw_line(pred.center_x, pred.center_y, pred.center_x + 20 * math.sin(angle_rad),
                             pred.center_y - 20 * math.cos(angle_rad), arcade.color.BLUE, 1)
            output = f"Breed: {pred.breed_point}"
            arcade.draw_text(output, 900, i * 20, arcade.color.WHITE, 14)
            output = f"Hungry: {pred.hungry_point}"
            arcade.draw_text(output, 1050, i * 20, arcade.color.WHITE, 14)

        if self.winner is not None:
            output = self.winner + " win!"
            arcade.draw_text(output, SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, arcade.color.WHITE, 14)
            arcade.pause(1)

    def on_update(self, delta_time):
        """ Movement and game logic """

        if len(self.pred_list) == 0:
            self.winner = "Prey"
        if len(self.prey_list) == 0:
            self.winner = "Predator"

        # new_prey = arcade.SpriteList()
        for prey_sprite in self.prey_list:
            if len(self.prey_list) < MAX_PREY:
                ret = prey_sprite.breed()
                if ret != 1:
                    self.prey_list.append(ret)

            prey_sprite.juke_kill(self.pred_list)

            if prey_sprite.center_x > SCREEN_WIDTH:
                prey_sprite.change_x = -prey_sprite.change_x

            if prey_sprite.center_y > SCREEN_HEIGHT:
                prey_sprite.change_y = -prey_sprite.change_y

            if prey_sprite.center_x < 0:
                prey_sprite.change_x = -prey_sprite.change_x

            if prey_sprite.center_y < 0:
                prey_sprite.change_y = -prey_sprite.change_y

        for pred in self.pred_list:
            pred.hunger()
            ret = pred.breed()
            if ret != 1:
                self.prey_list.append(ret)
            if len(self.prey_list) > 0:
                pred.follow_prey(self.prey_list)
            if pred.center_x > SCREEN_WIDTH:
                pred.center_x = SCREEN_WIDTH

            if pred.center_y > SCREEN_HEIGHT:
                pred.center_y = SCREEN_HEIGHT

            if pred.center_x < 0:
                pred.center_x = 0

            if pred.center_y < 0:
                pred.center_y = 0
        # Generate a list of all sprites that collided with the prey.
        for pred in self.pred_list:
            hit_list = arcade.check_for_collision_with_list(pred, self.prey_list)
            if hit_list is not None:
                for prey in hit_list:
                    prey.kill()
                pred.hungry_point += 100 * len(hit_list)

def main():
    """ Main function """
    window = MyGame()
    window.setup()
    arcade.run()

if __name__ == "__main__":
    main()


# Ejercicio 1

number = int(input("Por favor, introduce un número: "))

if ( number == 0 ):
    print("El número es cero")
elif ( number > 0 ):
    print("El número es positivo")
else:
    print("El número es negativo")

# Ejercicio 2

name = input("Por favor, introduce tu nombre: ")
if ( len(name) > 10 ):
    print("Tu nombre es mayor a 10 caracteres")
else:
    print("Tu nombre es menor a 10 caracteres")

# Ejercicio 3

name = input("Por favor, introduce tu nombre: ")

text_long_nombre = "Tu nombre es mayor a 10 caracteres" if len(name) > 10 else "Tu nombre es menor a 10 caracteres"
print(text_long_nombre)

# Ejercicio 4

x = int(input("Por favor, introduce un número entero positivo: "))
if ( x < 0 ):
    print("El número introducido no es positivo")
    exit()
y = int(input("Por favor, introduce un número entero positivo: "))
if ( y < 0 ):
    print("El número introducido no es positivo")
    exit()
if ( x >= y ):
    print("El primer número es mayor o igual que el segundo")
else:
    print("El primer número es menor que el segundo")

# Ejercicio 5

x = int(input("Por favor, introduce un número entero positivo: "))
if ( x < 0 ):
    print("El número introducido no es positivo")
    exit()
y = int(input("Por favor, introduce un número entero positivo: "))
if ( y < 0 ):
    print("El número introducido no es positivo")
    exit()
if ( x >= y ):
    if ( x % y == 0 ):
        print("La división es exacta y el cociente es: ", x // y)
    else:
        print("La división no es exacta y el cociente es: ", x // y, " y el resto es: ", x % y)

# Ejercicio 6

x = int(input("Por favor, introduce un número entero positivo: "))
if ( x < 0 ):
    print("El número introducido no es positivo")
    exit()
y = int(input("Por favor, introduce un número entero positivo: "))
if ( y < 0 ):
    print("El número introducido no es positivo")
    exit()
if ( x >= y ):
    if ( x % y == 0 ):
        print("La división es exacta y el cociente es: ", x // y)
    else:
        print("La división no es exacta y el cociente es: ", x // y, " y el resto es: ", x % y)

# Ejercicio 7

# Haz que un usuario introduzca dos números enteros positivos. Comprueba si el mayor es múltiplo del menor.
# Devuelve por pantalla el resultado en cada caso.

X = int(input("Por favor, introduce un número entero positivo: "))
if ( X < 0 ):
    print("El número introducido no es positivo")
    exit()
Y = int(input("Por favor, introduce un número entero positivo: "))
if ( Y < 0 ):
    print("El número introducido no es positivo")
    exit()
if ( X >= Y ):
    if ( X % Y == 0 ):
        print("El mayor es múltiplo del menor")
    else:
        print("El mayor no es múltiplo del menor")

# Ejercicio 8

# Haz que un usuario introduzca una palabra y comprueba si dicha palabra empieza por mayúscula. Devuelve
# por pantalla el resultado en cada caso.

word = input("Por favor, introduce una palabra: ")
if ( word[0].isupper() ):
    print("La palabra empieza por mayúscula")
else:
    print("La palabra NO empieza por mayúscula")

# Ejercicio 9

# Haz un usuario introduza una letra y comprueba si se trata de una vocal. Si el usuario introduce un string
# de más de un carácter, infórmale de que no se puede procesar el dato, pues debe tener como máximo tamaño
# PISTA: Convierte la letra introducida a minúsculas para tener que realizar menos comprobaciones

letter = input("Por favor, introduce una letra: ")
if ( len(letter) > 1 ):
    print("No se puede procesar el dato, pues debe tener como máximo tamaño 1")
    exit()
if ( letter.lower() == "a" or letter.lower() == "e" or letter.lower() == "i" or letter.lower() == "o" or letter.lower() == "u" ):
    print("Es una vocal")
else:
    print("No es una vocal")

# Ejercicio 10

# ax2 + bx + c = 0
# haz que el usuario introduzca los valores de los coeficientes a, b, c. Con ello,
# 1. Comprueba que el coeficiente a es distinto de 0
# 2. En función del discriminante, calcula cuántas soluciones va a tener la ecuación de segundo grado
# ax2 + bx + c = 0.
# 3. Devuelve por pantalla el resultado en cada caso (tanto el número de soluciones en los números reales
# como el valor de éstas).
# PISTA: Para calcular la raíz cuadrada, vas a necesitar la función math.sqrt() de la librería math

import math

a = int(input("Por favor, introduce el valor del coeficiente a: "))
if ( a == 0 ):
    print("El coeficiente a no puede ser 0")
    exit()
b = int(input("Por favor, introduce el valor del coeficiente b: "))
c = int(input("Por favor, introduce el valor del coeficiente c: "))

discriminante = b**2 - 4*a*c
if ( discriminante < 0 ):
    print("No tiene soluciones reales")
elif ( discriminante == 0 ):
    print("Tiene una solución real")
    print("x = ", -b / (2*a))
else:
    print("Tiene dos soluciones reales")
    print("x1 = ", (-b + math.sqrt(discriminante)) / (2*a))
    print("x2 = ", (-b - math.sqrt(discriminante)) / (2*a))


import os
from maya import cmds
from ..utils import QualityAssurance, reference

class NonExistingTextures(QualityAssurance):
    """
    Animation curves will be checked to see if they are not set driven keys.
    Non set driven keys should not be present in the scene and will be deleted
    when fixing this error.
    """
    def __init__(self):
        QualityAssurance.__init__(self)

        self._name = "Non Existing Textures"
        self._message = "{0} file(s) contain a link to a not existing texture"
        self._categories = ["Textures"]
        self._selectable = True

    # ------------------------------------------------------------------------

    def _find(self):
        """
        :return: Meshes with non-deformer history
        :rtype: generator
        """
        fileNodes = self.ls(type="file")
        for fileNode in fileNodes:
            path = cmds.getAttr("{0}.fileTextureName".format(fileNode))
            if not os.path.exists(path):
                yield fileNode

    def _fix(self, fileNode):
        """
        :param str fileNode:
        """
        cmds.setAttr("{0}.disableFileLoad".format(fileNode), 1)


# This script reads a grayscale image called aspect_name.png, and
# manipulates the pixel values to create tables of composition
# (scaled between 0 and 1) and temperature.
# The resulting composition and temperature tables are then plotted
# and saved to ASCII text files that can be read by ASPECT.

# This script can be called with the command
# python ./make_ascii_files_from_png.py

from PIL import Image
import numpy as np
import matplotlib.pyplot as plt

# Open grayscale image
image = Image.open('aspect_name.png')
array = np.array(image.getdata())

# Get only the grayscale bit and flip along the y axis
nx, ny = image._size
grayscale = np.flip(array[:, 0].reshape((ny, nx)),
                    0).flatten()

# Create grids
x_spacing = 1000.  # m/pixel
y_spacing = 1000.  # m/pixel

xs = np.linspace(0., x_spacing*(nx-1), nx)
ys = np.linspace(0., y_spacing*(ny-1), ny)
xygrid = np.meshgrid(xs, ys)

xv = xygrid[0].flatten()
yv = xygrid[1].flatten()

# Create composition and temperature data from pixel values
compositions = 1. - (grayscale/255.)
composition_data = np.array([xv, yv, compositions]).T

temperatures = 1500. + 2.*compositions * (yv/1000. - 250.)
temperature_data = np.array([xv, yv, temperatures]).T

# Save ASCII files
header = f'POINTS: {nx} {ny}\nColumns: x y phase'
np.savetxt('aspect_name_initial_composition.txt',
           header=header, X=composition_data, fmt='%.1f')

np.savetxt('aspect_name_initial_temperature.txt',
           header=header, X=temperature_data, fmt='%.1f')

# Plot initial composition and temperature
xs_pad = np.linspace(0., x_spacing*(nx), nx+1)/1000
ys_pad = np.linspace(0., y_spacing*(ny), ny+1)/1000.

fig = plt.figure(figsize=(16, 5))
ax = [fig.add_subplot(1, 2, i) for i in range(1, 3)]

for i in range(2):
    ax[i].set_aspect(1.)
    ax[i].set_xlim(0., 800.)
    ax[i].set_ylim(0., 500.)
    ax[i].set_xlabel('x (km)')
    ax[i].set_ylabel('y (km)')

cmap = plt.get_cmap('cividis')
msh = ax[0].pcolormesh(xs_pad, ys_pad,
                       compositions.reshape((ny, nx)),
                       cmap=cmap)
fig.colorbar(msh, ax=ax[0])
ax[0].set_title('Composition')

cmap = plt.get_cmap('RdBu_r')
msh = ax[1].pcolormesh(xs_pad, ys_pad,
                       temperatures.reshape((ny, nx)),
                       cmap=cmap)
fig.colorbar(msh, ax=ax[1])
ax[1].set_title('Initial temperature (K)')

fig.savefig('prescribed_velocities_ascii_data_initial_conditions.png')
plt.show()


import re

with open("input.txt") as f:
    splits = f.read().split("\n\n")

rules = {}
for line in splits[0].split("\n"):
    k, v = line.split(": ")
    rules[k] = v

def regex_q1(rule):
    if '"' in rule:  # rule is "a" or "b"
        return rule[1]
    elif "|" not in rule:
        return "".join([regex_q1(rules[r]) for r in rule.split()])
    else:
        or1, or2 = rule.split("|")  # the input rules contain at most one |
        return "(" + regex_q1(or1) + "|" + regex_q1(or2) + ")"

def regex_q2(rule):
    if rule == "42 | 42 8":
        return regex_q2(rules["42"]) + "+"
    elif rule == "42 31 | 42 11 31":
        r42 = regex_q2(rules["42"])
        r31 = regex_q2(rules["31"])
        # re can't ensure that we have the same number of 42 and 31 patterns
        # So try to match exactly 1 to 10 occurrences of 42 with the same number of 31
        # 10 is enough given the length of the messages
        return "(?:" + "|".join(f"{r42}{{{i}}}{r31}{{{i}}}" for i in range(1, 10)) + ")"
    if '"' in rule:
        return rule[1]
    elif "|" not in rule:
        return "".join([regex_q2(rules[r]) for r in rule.split()])
    else:
        or1, or2 = rule.split("|")
        return "(?:" + regex_q2(or1) + "|" + regex_q2(or2) + ")"

regex1 = re.compile(r"^" + regex_q1(rules["0"]) + "$")
print(sum([bool(regex1.match(msg)) for msg in splits[1].split("\n")]))

rules["8"] = "42 | 42 8"
rules["11"] = "42 31 | 42 11 31"
regex2 = re.compile(r"^" + regex_q2(rules["0"]) + "$")
print(sum([bool(regex2.match(msg)) for msg in splits[1].split("\n")]))


import os
from pathlib import Path
from jira import JIRA

from entities.excel_tables.worklogs_by_author_table import WorklogsByAuthorTable
from entities.excel_tables.worklogs_by_issue_for_author_table import WorklogsByIssueForAuthorTable
from entities.excel_tables.worklogs_table import WorklogsTable
import platform

from entities.jira.issues import Issues

class JiraClient(object):
    """Класс клиента для работы с джирой."""

    def __init__(self, host, login, password):
        self.host = host
        self.basic_auth = (login, password)
        self.jira = JIRA(server=self.host, basic_auth=self.basic_auth)

        self.issues = Issues(connection=self.jira)

    def search_issues(self, jql):
        """Поиск задач в джира, подходящих под заданный jql запрос."""
        return self.issues.search_issues(jql=self.decode_query(query=jql))

    def worklogs_to_excel(self, filename, jql, startrow=0, startcol=0):
        """Запись собранных ворклогов в эксель файл.

        Args:
            filename: Наименование файла с отчетом.
            jql: Текст запроса, для результатов которого необходимо записать ворклоги.
            startrow: Номер левого ряда для таблицы.
            startcol: Номер левой строки для таблицы.

        """
        worklogs_table = WorklogsTable(jira_client=self)
        for issues_list in self.issues.all_issues.values():
            for issue in issues_list:
                worklogs_table.insert_data_for_issue_into_table(issue=issue)
        worklogs_table.insert_jql_into_table(jql=self.decode_query(query=jql))

        worklogs_by_author_table = WorklogsByAuthorTable(jira_client=self)
        for info in self.issues.worklogs_by_author.by_author.values():
            worklogs_by_author_table.insert_data_for_author_into_table(by_author=info)

        worklogs_by_issue_for_author_table = WorklogsByIssueForAuthorTable(jira_client=self)
        for by_author in self.issues.worklogs_by_author.by_author.values():
            for by_issue in by_author.worklogs_by_issue.values():
                worklogs_by_issue_for_author_table.insert_data_for_issue_into_table(issue=by_issue)

        directory = str(Path(__file__).parent.parent.absolute()) + os.sep + 'reports' + os.sep

        worklogs_table.to_excel(directory=directory,
                                filename=filename,
                                startrow=startrow, startcol=startcol, sheet_name='Worklogs')

        worklogs_by_issue_for_author_table.to_excel(directory=directory,
                                                    filename=filename,
                                                    startrow=startrow, startcol=startcol, sheet_name='WorklogsByIssue')

        worklogs_by_author_table.to_excel(directory=directory,
                                          filename=filename,
                                          startrow=startrow, startcol=startcol, sheet_name='WorklogsByAuthor')

    @staticmethod
    def sec_to_hours_mins(s):
        hours = int(s // 3600)
        mins = (s % 3600) // 60
        if mins == 0:
            return hours
        else:
            mins = str(mins / 60)[2:]
            return float("{}.{}".format(hours, mins))

    @staticmethod
    def sec_to_mins(s):
        return int(str(s // 60)[:-2])

    def decode_query(self, query):
        if platform.system() == 'Windows':
            for encode, decode in [['cp866', 'utf-8'], ['cp1251', 'utf-8'], ['cp866', 'cp1251']]:
                decoded_query = self.try_decode(string=query, encode=encode, decode=decode)
                if decoded_query is not None:
                    return decoded_query
        return query

    @staticmethod
    def try_decode(string, encode, decode, exceptions=(UnicodeEncodeError, UnicodeDecodeError)):
        try:
            return string.encode(encode).decode(decode)
        except exceptions:
            return None

    def close_connection(self):
        print('Закрытие сессии Jira')
        self.jira.close()


import util
from collections import deque

'''
Both part 1 & part 2 solution were copied from Reddit r/adventofcode
Because after 6 straigth hours trying to find a fucking solution to this
fucking puzzle, I gave up !!!!!!!!!
Shame on me !!!!
'''

def path_length(tree, node):
    children = tree.get(node,[])
    return len(children) + sum((path_length(tree, c) for c in children))

def path(connexions, links, you='YOU',santa='SAN'):
    ''' Breadth-First
    Freely inspired from
    https://www.reddit.com/r/adventofcode/comments/e6tyva/2019_day_6_solutions/f9w4q1z?utm_source=share&utm_medium=web2x
    '''
    start = [k for k,v in connexions.items() if you in v].pop()
    end = [k for k,v in connexions.items() if santa in v].pop()
    dists = {start:0}
    objs = deque([start])
    seen = {start}
    while end not in dists:
        n = objs.pop()
        dist = dists[n]
        for neighbor in links[n]:
            if neighbor in seen:
                continue
            seen.add(neighbor)
            objs.appendleft(neighbor)
            dists[neighbor] = dist + 1
    return dists[end]

def upsert(container,key,value):
    d = container.get(key,[])
    d.append(value)
    container[key] = d

def solve():
    orbits = util.load_data(fun=lambda x: x.split(')'))
    connexions = {}
    links = {}
    for k, v in orbits:
        upsert(connexions, k, v)
        upsert(links, v, k)
        upsert(links, k, v)

    print(f'Part1: {sum(path_length(connexions, c) for c in connexions)}')
    print(f'Part2: {path(connexions, links)}')

if __name__ == '__main__':
    solve()


from typing import Union

from django.conf import settings

from infoblox.models.Permission.IdentityGroup import IdentityGroup
from infoblox.models.Permission.Role import Role
from infoblox.models.Permission.Network import Network

from infoblox.models.Infoblox.NetworkContainer import NetworkContainer as NetworkContainerModel
from infoblox.models.Infoblox.Network import Network as NetworkModel

from infoblox.models.Permission.repository.Permission import Permission as Repository
from infoblox.models.Permission.repository.PermissionPrivilege import PermissionPrivilege as PermissionPrivilegeRepository

from infoblox.helpers.Exception import CustomException
from infoblox.helpers.Log import Log

class Permission:

    # IdentityGroupRoleNetwork

    def __init__(self, permissionId: int, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.id: int = int(permissionId)
        self.identityGroup: IdentityGroup
        self.role: Role
        self.network: Network

        self.__load()

    ####################################################################################################################
    # Public methods
    ####################################################################################################################

    def delete(self) -> None:
        try:
            Repository.delete(self.id)
            del self
        except Exception as e:
            raise e

    ####################################################################################################################
    # Public static methods
    ####################################################################################################################

    @staticmethod
    def hasUserPermission(groups: list, action: str, assetId: int = 0, container: str = "", network: Union[str, NetworkModel] = None, containers: list = None, networks: list = None) -> bool:
        networks = networks or []
        containers = containers or []

        permissionNetworks = []

        # Superadmin's group.
        for gr in groups:
            if gr.lower() == "automation.local":
                return True

        try:
            if network or container:
                if network:
                    if isinstance(network, NetworkModel):
                        permissionNetworks.append(network.network)
                        container = network.network_container

                    if isinstance(network, str):
                        if "/" not in network: # if not already in CIDR notation.
                            network = NetworkModel(assetId, network).network

                        if not networks:
                            n = NetworkModel(assetId, network)
                            permissionNetworks.append(n.network)
                            container = n.network_container
                        else:
                            permissionNetworks.append(network)
                            container = [net for net in networks if net["network"] == network][0]["network_container"]

                permissionNetworks.append(container) # [network, container] if network // [container] if container.

                if settings.INHERIT_GRANDPARENTS_PERMISSIONS:
                    if not containers:
                        containers = NetworkContainerModel.listData(assetId, silent=True)

                    permissionNetworks.extend(NetworkContainerModel.genealogy(network=container, networkContainerList=containers))

            # User permissions for all permissionNetworks.
            if PermissionPrivilegeRepository.countUserPermissions(groups, action, assetId, permissionNetworks):
                return True

            return False
        except Exception as e:
                raise e

    @staticmethod
    def permissionsDataList() -> list:
        try:
            return Repository.list()
        except Exception as e:
            raise e

    @staticmethod
    def authorizationsList(groups: list) -> dict:
        superadmin = False
        for gr in groups:
            if gr.lower() == "automation.local":
                superadmin = True
                break

        if superadmin:
            # Superadmin's permissions override.
            authorizations = {
                "any": [
                    {
                        "assetId": 0,
                        "network": "any"
                    }
                ]
            }
        else:
            try:
                authorizations = PermissionPrivilegeRepository.authorizationsList(groups)
            except Exception as e:
                raise e

        return authorizations

    @staticmethod
    def addFacade(identityGroupIdentifier: str, role: str, networkInfo: dict) -> None:
        networkAssetId = networkInfo.get("assetId", "")
        networkName = networkInfo.get("name", "")

        try:
            # Get existent or new network (permissions database).
            if role == "admin" or role == "workflow":
                # Role admin -> "any" network, which always exists.
                network = Network(assetId=networkAssetId, network="any")
            else:
                try:
                    # Try retrieving network.
                    network = Network(assetId=networkAssetId, network=networkName)
                except CustomException as e:
                    if e.status == 404:
                        try:
                            # If network does not exist, create it (permissions database).
                            network = Network(
                                id=Network.add(networkAssetId, networkName)
                            )
                        except Exception:
                            raise e
                    else:
                        raise e

            Permission.__add(
                identityGroup=IdentityGroup(identityGroupIdentifier=identityGroupIdentifier),
                role=Role(role=role),
                network=network
            )
        except Exception as e:
            raise e

    @staticmethod
    def modifyFacade(permissionId: int, identityGroupIdentifier: str, role: str, networkInfo: dict) -> None:
        networkAssetId = networkInfo.get("assetId", "")
        networkName = networkInfo.get("name", "")

        try:
            # Get existent or new network (permissions database).
            if role == "admin" or role == "workflow":
                # Role admin -> "any" network, which always exists.
                network = Network(assetId=networkAssetId, network="any")
            else:
                try:
                    # Try retrieving network.
                    network = Network(assetId=networkAssetId, network=networkName)
                except CustomException as e:
                    if e.status == 404:
                        try:
                            # If network does not exist, create it (permissions database).
                            network = Network(
                                id=Network.add(networkAssetId, networkName)
                            )
                        except Exception:
                            raise e
                    else:
                        raise e

            Permission(permissionId).__modify(
                identityGroup=IdentityGroup(identityGroupIdentifier=identityGroupIdentifier),
                role=Role(role=role),
                network=network
            )
        except Exception as e:
            raise e

    ####################################################################################################################
    # Private methods
    ####################################################################################################################

    def __load(self) -> None:
        try:
            info = Repository.get(self.id)

            self.identityGroup = IdentityGroup(id=info["id_group"])
            self.role = Role(id=info["id_role"])
            self.network = Network(id=info["id_network"])
        except Exception as e:
            raise e

    def __modify(self, identityGroup: IdentityGroup, role: Role, network: Network) -> None:
        try:
            Repository.modify(
                self.id,
                identityGroupId=identityGroup.id,
                roleId=role.id,
                networkId=network.id
            )

            self.__load()
        except Exception as e:
            raise e

    ####################################################################################################################
    # Private static methods
    ####################################################################################################################

    @staticmethod
    def __add(identityGroup: IdentityGroup, role: Role, network: Network) -> None:
        try:
            Repository.add(
                identityGroupId=identityGroup.id,
                roleId=role.id,
                networkId=network.id
            )
        except Exception as e:
            raise e


"""Represents a forwarded invitation from another agent."""

from marshmallow import fields

from .....messaging.agent_message import AgentMessage, AgentMessageSchema
from .....protocols.connections.v1_0.messages.connection_invitation import (
    ConnectionInvitation,
    ConnectionInvitationSchema,
)
from ..message_types import FORWARD_INVITATION, PROTOCOL_PACKAGE

HANDLER_CLASS = (
    f"{PROTOCOL_PACKAGE}.handlers.forward_invitation_handler.ForwardInvitationHandler"
)

class ForwardInvitation(AgentMessage):
    """Class representing an invitation to be forwarded."""

    class Meta:
        """Metadata for a forwarded invitation."""

        handler_class = HANDLER_CLASS
        message_type = FORWARD_INVITATION
        schema_class = "ForwardInvitationSchema"

    def __init__(
        self, *, invitation: ConnectionInvitation = None, message: str = None, **kwargs
    ):
        """Initialize invitation object.

        Args:
            invitation: The connection invitation
            message: Comments on the introduction
        """
        super().__init__(**kwargs)
        self.invitation = invitation
        self.message = message

class ForwardInvitationSchema(AgentMessageSchema):
    """ForwardInvitation request schema class."""

    class Meta:
        """ForwardInvitation request schema metadata."""

        model_class = ForwardInvitation

    invitation = fields.Nested(ConnectionInvitationSchema(), required=True)
    message = fields.Str(
        required=False,
        allow_none=True,
        metadata={
            "description": "Comments on the introduction",
            "example": "Hello Bob, it's Alice",
        },
    )


from pathlib import Path

import dash_core_components as dcc
import dash_html_components as html

from ...api_doc import ApiDoc
from ...helpers import (
    ExampleContainer,
    HighlightedSource,
    load_source_with_environment,
)
from ...metadata import get_component_metadata
from .radio_check_inline import inline_inputs
from .size import inputs as input_size
from .text_label import text_input as input_text_label
from .textarea import textareas as input_textarea
from .validation import inputs as input_validation

HERE = Path(__file__).parent

input_simple_source = (HERE / "simple.py").read_text()
input_text_label_source = (HERE / "text_label.py").read_text()
input_size_source = (HERE / "size.py").read_text()
input_validation_source = (HERE / "validation.py").read_text()
input_radio_check_source = (HERE / "radio_check.py").read_text()
input_textarea_source = (HERE / "textarea.py").read_text()
input_radio_check_inline_source = (HERE / "radio_check_inline.py").read_text()
input_radio_check_standalone_source = (
    HERE / "radio_check_standalone.py"
).read_text()

def get_content(app):
    return [
        html.H2("Input components"),
        html.P(
            dcc.Markdown(
                "*dash-bootstrap-components* has its own versions of some of "
                "the input components available in *dash-core-components*. "
                "They have been designed to share the same interface as the "
                "corresponding components in *dash-core-components* for "
                "familiarity, but have a few additional Bootstrap specific "
                "features."
            )
        ),
        html.H4("Input"),
        html.P(
            dcc.Markdown(
                "The input component allows for text or numeric input, its "
                "basic usage is the same as `dcc.Input`, but Bootstrap styles "
                "will be applied for you."
            )
        ),
        ExampleContainer(
            load_source_with_environment(
                input_simple_source, "text_input", {"app": app}
            )
        ),
        HighlightedSource(input_simple_source),
        html.H4("Labels and Text"),
        html.P(
            [
                dcc.Markdown(
                    "Use the `FormGroup` component along with `Label` and "
                    "`FormText` to control the layout of your `Input` "
                    "components."
                ),
                "See the ",
                dcc.Link("documentation for forms", href="/l/components/form"),
                " for more details.",
            ]
        ),
        ExampleContainer(input_text_label),
        HighlightedSource(input_text_label_source),
        html.H4("Input size"),
        html.P(
            dcc.Markdown(
                "You can control the size of the `Input` using the `bs_size` "
                "keyword argument. It accepts the values `sm`, `md` or `lg` "
                "for small, medium or large sizes respectively."
            )
        ),
        ExampleContainer(input_size),
        HighlightedSource(input_size_source),
        html.H4("Input validation"),
        html.P(
            dcc.Markdown(
                "Add valid / invalid styles to your `Input` components using "
                "the `valid` and `invalid` keyword arguments."
            )
        ),
        ExampleContainer(input_validation),
        HighlightedSource(input_validation_source),
        html.H4("Textarea"),
        html.P(
            dcc.Markdown(
                "The `Textarea` component works like the "
                "*dash-core-components* analogue, but accepts the additional "
                "arguments `valid`, `invalid`, and `bs_size` much like "
                "`Input`."
            )
        ),
        ExampleContainer(input_textarea),
        HighlightedSource(input_textarea_source),
        html.H4("RadioItems and Checklist"),
        html.P(
            dcc.Markdown(
                "`RadioItems` and `Checklist` components also work like "
                "*dash-core-components* but again with Bootstrap styles "
                "added. In addition the `inline` keyword can be used to "
                "easily make inline checklists or radioitems. Use these "
                "components with `FormGroup` for automatic spacing and "
                "padding."
            )
        ),
        ExampleContainer(
            load_source_with_environment(
                input_radio_check_source, "inputs", {"app": app}
            )
        ),
        HighlightedSource(input_radio_check_source),
        html.P(
            dcc.Markdown(
                "Use the `inline` keyword to make the radioitems or "
                "checklists fit next to each other on a line."
            )
        ),
        ExampleContainer(inline_inputs),
        HighlightedSource(input_radio_check_inline_source),
        html.P(
            dcc.Markdown(
                "If you need more granular control over checkboxes "
                "and radio buttons, you can also create standalone "
                "components. Bind callbacks to the `checked` keyword "
                "to react to changes in the input state. To attach "
                "a label, create a FormGroup with `check=True` and "
                "use the label's `html_for` keyword to bind it to "
                "the checkbox."
            )
        ),
        ExampleContainer(
            load_source_with_environment(
                input_radio_check_standalone_source,
                "standalone_radio_check",
                {"app": app},
            )
        ),
        HighlightedSource(input_radio_check_standalone_source),
        ApiDoc(
            get_component_metadata("src/components/input/Input.js"),
            component_name="Input",
        ),
        ApiDoc(
            get_component_metadata("src/components/input/Textarea.js"),
            component_name="Textarea",
        ),
        ApiDoc(
            get_component_metadata("src/components/input/RadioItems.js"),
            component_name="RadioItems",
        ),
        ApiDoc(
            get_component_metadata("src/components/input/Checklist.js"),
            component_name="Checklist",
        ),
        ApiDoc(
            get_component_metadata("src/components/input/Checkbox.js"),
            component_name="Checkbox",
        ),
        ApiDoc(
            get_component_metadata("src/components/input/RadioButton.js"),
            component_name="RadioButton",
        ),
    ]


#Problema 1061

dia_vetor0 = input().split(" ")
dia_inicio = int(dia_vetor0[1])

horario_inicio = input().split(":")
hora_inicio = int(horario_inicio[0])
minuto_inicio = int(horario_inicio[1])
segundo_inicio = int(horario_inicio[2])

dia_vetor1 = input().split(" ")
dia_termino = int(dia_vetor1[1])

horario_termino = input().split(":")
hora_fim = int(horario_termino[0])
minuto_fim = int(horario_termino[1])
segundo_fim = int(horario_termino[2])

dias_em_seg_inicio = dia_inicio * 24 * 60 * 60
horas_em_seg_inicio = hora_inicio * 60 * 60
minutos_em_seg_inicio = minuto_inicio * 60

dias_em_seg_fim = dia_termino * 24 * 60 * 60
horas_em_seg_fim = hora_fim * 60 * 60
minutos_em_seg_fim = minuto_fim * 60

tempo_inicio = dias_em_seg_inicio + horas_em_seg_inicio + minutos_em_seg_inicio + segundo_inicio
tempo_fim = dias_em_seg_fim + horas_em_seg_fim + minutos_em_seg_fim + segundo_fim

duracao = tempo_fim - tempo_inicio

dias = duracao // 86400
print("{} dia(s)".format(dias))
resto_dias = duracao % 86400

horas = resto_dias // 3600
print("{} hora(s)".format(horas))
resto_horas = resto_dias % 3600

minutos = resto_horas // 60
print("{} minuto(s)".format(minutos))

segundos = resto_horas % 60
print("{} segundo(s)".format(segundos))


#!/usr/bin/python3.6

import argparse
from prettytable import PrettyTable

algorithm_name = "MOEA_D"
problem_name = "MenuPlanning"
mutation_prob = [0.05]
crossover_prob = [1]
population_sizes = [25, 80, 140, 190, 250]
neighbourhood_sizes = [0.4, 0.3, 0.25, 0.2, 0.16]
evaluations = 100000000
number_of_days = 20
seed = 13
output_dir = "experimentsResults/MPP_TFM"
METCO_PATH = "/home/amarrero/oplink/algorithms/team"
preaction= f"Preaction: mkdir -p {output_dir}\n"
primer_plato = "PrimerPlato: /home/amarrero/oplink/algorithms/team/src/plugins/problems/MenuPlanning/databaseMenus/primerosplatos.txt\n"
segundo_plato = "SegundoPlato: /home/amarrero/oplink/algorithms/team/src/plugins/problems/MenuPlanning/databaseMenus/segundosplatos.txt\n"
postre = "Postre: /home/amarrero/oplink/algorithms/team/src/plugins/problems/MenuPlanning/databaseMenus/postres.txt\n"
EXTENSION =  ".sexp"

def configure_experiment(name, reps):
    result_table = PrettyTable()
    result_table.title = f"Experiment {name} configuration"
    result_table.field_names = ["Configuration's name", "Population size", "Portion", "Neighbourhood size", "Crossover Probability", "Mutation Probability"]
    result_table.align["Portion"] = "r"
    result_table.align["Neighbourhood size"] = "r"
    diff_experiments = 0
    for pop_size in population_sizes:
        for neighb_size in neighbourhood_sizes:
            for crossover in crossover_prob:
                for mutation in mutation_prob:
                    for i in range(1):
                        size = round(pop_size * neighb_size)
                        m = str(mutation).replace(".", "_")
                        config_name = f"{name}_{algorithm_name}_p{pop_size}_n{size}"
                        result_table.add_row([config_name, pop_size, neighb_size, size, crossover, mutation])
                        path = f"MetcoPath: {METCO_PATH}\n"
                        repetitions = f"Repetitions: 30\n"
                        experiment = f"Name_of_experiment: {name}\n"
                        experimentCamel = f"NameOfExperiment: {name}\n"
                        algorithm = f"Algorithms: {algorithm_name}\n"
                        problem = f"Individual: {problem_name}\n"
                        evals = f"Evaluations: {evaluations}\n"
                        population_size = f"PopSize: {pop_size}\n"
                        neihb = f"Neihb: {size}\n"
                        prob_mut = f"ProbMut: {mutation}\n"
                        prob_cross = f"ProbCross: {crossover}\n"
                        num_days = f"NumDays: {number_of_days}\n"
                        individual_params = f"IndividualParams: {number_of_days} {primer_plato} {segundo_plato} {postre}"
                        execution = f"Execution:  %MetcoPath/src/skeleton/main/metcoSeq %MetcoPath/scripts/run/{output_dir}/ " \
                        "%MetcoPath/src/skeleton/main/ PlainText " \
                        "%NameOfExperiment_%Algorithms_PopSize_%PopSize_Neihb_%Neihb_days_%NumDays_%Individual_%Evaluations.%rep " \
                        "%Algorithms %Individual EVALUATIONS %Evaluations 10000000 0 %PopSize %Neihb %ProbMut %ProbCross 13 0 ! " \
                        "%NumDays %PrimerPlato %SegundoPlato %Postre $ NoOp\n\n"
                        machine_file = f"machinefile: experimentConfigFiles/MPP_TFM/machinefile\n"
                        output_file = f"OutputFile: {output_dir}/%NameOfExperiment_%Algorithms_PopSize_%PopSize_Neihb_%Neihb_days_%NumDays_%Individual_%Individiual_%Evaluations"

                        diff_experiments += 1
                        with open(f"{config_name}{EXTENSION}", "w") as output:
                            output.write(path)
                            output.write(repetitions)
                            output.write(experiment)
                            output.write(experimentCamel)
                            output.write(preaction)
                            output.write(algorithm)
                            output.write(problem)
                            output.write(evals)
                            output.write(population_size)
                            output.write(neihb)
                            output.write(prob_mut)
                            output.write(prob_cross)
                            output.write(num_days)
                            output.write(primer_plato)
                            output.write(segundo_plato)
                            output.write(postre)
                            output.write(individual_params)
                            output.write("\n")
                            output.write(execution)
                            output.write(machine_file)
                            output.write(output_file)

    print(f"You have {diff_experiments} different experiments and every configuration will be repeated 30 times: {diff_experiments * 1} independent executions")
    print(result_table)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Configuring MMP Experiments")
    parser.add_argument("name", help="Name of the experiment")
    parser.add_argument("repetitions", help="Repetitions for each configuration")
    args = parser.parse_args()
    name = args.name
    reps = int(args.repetitions)
    configure_experiment(name, reps)


class Solution:
    def lengthOfLIS(self, nums: List[int]) -> int:

        # let dp[i] be len of LIS ending with nums[i] in nums[0:i+1]

        # base case:
        # dp[0] = 1

        # optimality relation:
        # for 0 <= j < i, if nums[j] < nums[i], dp[i] = dp[j] + 1
        # thus, dp[i] = 1 + max_{0<=j<i: nums[j] < nums[i]} dp[j]
        # O(n^2)

        # binary search: O(n log n)

        n = len(nums)

        # stack of top of piles of cards
        top = [nums[0]]

        for i in range(1, n):
            # binary search for the left most pile whose top is larger than nums[i]
            # if not exists, add a new pile
            if top[-1] < nums[i]:
                top.append(nums[i])
            else:
                # top[0:idx] < nums[i]
                idx = bisect_left(top, nums[i])
                # put nums[i] on top the pile
                top[idx] = nums[i]

        return len(top)


def solve(n, m):
    sum = 0
    while (m >= 1):
        digit = m % 10
        sum += digit
        m = int(m / 10)

    if sum % 3 == 0:
        print("{} sim".format(sum))
    else:
        print("{} nao".format(sum))

while (True):
    try:
        n, m = input().split()
        solve(int(n), int(m))
    except EOFError:
        break


import operator
from operator import itemgetter

def match(str):
	if str.find("Chinese") >= 0 :
		return "Chinese"
	elif str.find("Italian") >= 0 :
		return "Italian"
	elif str.find("Korean") >= 0 :
		return "Korean"
	elif str.find("American") >= 0 or str.find("Burgers") >= 0 :
		return "American"
	elif str.find("Japanese") >= 0 :
		return "Japanese"
	elif str.find("Indian") >= 0 :
		return "Indian"
	else :
		return "other"

data = []

if __name__ == "__main__":
	with open('business.json') as f:
		index = 0
		for lines in f:
			index += 1
			#if index == 40:
				#print lines.strip().split("\":")
			business_id = lines.strip().split("\":")[1].strip().split("\"")[1]
			school = lines.strip().split("\":")[3].strip().split("\"")[1]
			category = lines.strip().split("\":")[5].strip().split("[\"")[1].strip().split("\"]")[0]
			photo_url = lines.strip().split("\":")[6].strip().split("\"")[1]
			review_count = lines.strip().split("\":")[8].strip().split(" ")[0].strip().split(",")[0]
			name = lines.strip().split("\":")[9].strip().split("\"")[1]
			url =  lines.strip().split("\":")[11].strip().split("\"")[1]
			stars =  lines.strip().split("\":")[14].strip().split(" ")[0].strip().split(",")[0]

			if match(category) != "other":
				data.append((school,match(category),business_id,photo_url,review_count,name,url,stars))
			#print match(category)
			#print business_id
			#print school
			#print category
			#print photo_url
			#print review_count
			#print name
			#print url
			#print stars

				#print lines.strip().split("\":")[5].strip().split("[\"")[1].strip().split("\"]")[0]
		data.sort(key=itemgetter(0,1))

		# print data

	file = open("yelp-business-treemap.json", "w")

	file.write("{\n")
	file.write("\"name\": \"YAD Business\",\n")
	file.write("\"children\": [\n")

	index = 0

	for lines in data:

		if index == 0:
	# School
			file.write("{\n")
			file.write("\"name\": "+"\""+data[0][0]+"\""+",\n")
			file.write("\"children\": [\n")
	# Style
			file.write("{\n")
			file.write("\"name\": "+"\""+data[0][1]+"\""+",\n")
			file.write("\"children\": [\n")

		elif data[index][0] != data[index-1][0] and index != len(data)-1:
			file.write("]\n")
			file.write("}\n")
			file.write("]\n")
			file.write("},")
	# School
			file.write("{\n")
			file.write("\"name\": "+"\""+data[index][0]+"\""+",\n")
			file.write("\"children\": [\n")
	# Style
			file.write("{\n")
			file.write("\"name\": "+"\""+data[index][1]+"\""+",\n")
			file.write("\"children\": [\n")

		elif data[index][1] != data[index-1][1]:
			file.write("]\n")
			file.write("},\n")
			file.write("{\n")
			file.write("\"name\": "+"\""+data[index][1]+"\""+",\n")
			file.write("\"children\": [\n")
###########################################################

	# Restaurant

		if index != 0 and data[index][1] == data[index-1][1] and data[index][0] == data[index-1][0] :
			file.write(",\n")
		file.write("{")
		file.write("\"name\": "+"\""+data[index][5]+"\""+",")
		file.write("\"review_count\": "+"\""+data[index][4]+"\""+",")
		file.write("\"photo_url\": "+"\""+data[index][3]+"\""+",")
		file.write("\"url\": "+"\""+data[index][6]+"\""+",")
		file.write("\"star\": "+"\""+data[index][7]+"\"")
		file.write("}")
		index += 1

		if index == len(data):
			file.write("]\n")
			file.write("}\n")
			file.write("]\n")
			file.write("}]\n")
			file.write("}")


#!/usr/bin/python
from __future__ import print_function, absolute_import

import subprocess, sys, os, math, shutil
from os import listdir
from os.path import isfile, join

from pymol import cmd

#######################################
###########  P R E P A R E ############
#######################################

# Prepare structures via Pymol for Mopac or Gaussian
# Use in Pymol command prompt:
# run wSterimol.py
# run sterimoltools.py
# run setup.py
# run prepare_file.py
# prepare (directory, setup_path, verbose)
# example: prepare conformers

def prepare_file(directory = "temp", setup_path = "default", verbose = "False"):
    # If the directory exists
    if os.path.exists(directory):
        # Log generation
        log = Log()
        log.write("\n\n########################################\n###########  P R E P A R E  ############\n########################################\n\n")
        #verbose
        if verbose.lower() in ['true', '1', 't', 'y', 'yes']: verbose = True
        else: verbose = False
        # Retrieve all the files in the directory
        files = [f for f in listdir(directory) if isfile(join(directory, f))]
        if len(files) > 0:
            # get setup.ini
            setup = Setup(log, setup_path)
            if setup.isLoaded() == True:
                # modify the files
                for filename in files:
                    filesplit = filename.split(".")
                    if len(filesplit) > 1: # there is an extension
                        if filesplit[len(filesplit)-1] == "pdb": # is a pdb
                            if setup.software == "GAUSSIAN": # GAUSSIAN software
                                out = getinData(join(directory, "%s.pdb" % filesplit[0]))
                                # create file
                                lines = []
                                lines.append("%%mem=%sGB\n" % setup.memories )
                                lines.append("%%nprocshared=%s\n" % setup.procsshared)
                                lines.append("%%chk=%s.chk\n" % filesplit[0])
                                lines.append("# %s \n" % setup.leveloftheory) #maxcycles as a walltime
                                lines.append("\n")
                                lines.append("Generated by prepare_file.py\n")
                                lines.append("\n")
                                lines.append("%s %s\n" % (setup.charge,setup.spin) )
                                for i in range(len(out.ATOMTYPES)):
                                    lines.append(" %-2s              %13.8f %13.8f %13.8f\n" % ( out.ATOMTYPES[i], out.CARTESIANS[i][0], out.CARTESIANS[i][1], out.CARTESIANS[i][2] ))
                                lines.append("\n")
                                if setup.singlepointcalculation != "": # create a link to calculate the energy in a higher level of theory
                                    lines.append("--Link1--\n")
                                    lines.append("%%mem=%sGB\n" % setup.memories )
                                    lines.append("%%nprocshared=%s\n" % setup.procsshared)
                                    lines.append("%%chk=%s.chk\n" % filesplit[0])
                                    lines.append("# %s geom=check guess=read\n" % setup.singlepointcalculation)
                                    lines.append("\n")
                                    lines.append("Generated by prepare_file.py\n")
                                    lines.append("\n")
                                    lines.append("%s %s\n" % (setup.charge,setup.spin) )
                                    lines.append("\n")
                                #write
                                file = open(join(directory, "%s.com" % filesplit[0]),"w")
                                for line in lines:
                                    file.write(line)
                                file.close()
                                #remove pdb, useless
                                try: os.remove(join(directory, "%s.pdb" % filesplit[0]))
                                except: log.write("Error: The file [%s] couldn't be deleted" % join(directory, "%s.pdb" % filesplit[0]))
                            elif setup.software == "MOPAC": # MOPAC software
                                # horribly modify the pdb to be accepted by mopac, but works
                                lines = []
                                lines.append("%s charge=%s %s\n" % (setup.SE, setup.charge, setup.scf) )
                                lines.append("Generated by weighted sterimol script\n")
                                lines.append("\n")
                                #write
                                file = open(join(directory, filename),"r")
                                lines.extend(file.readlines())
                                file.close()
                                file = open(join(directory, filename),"w")
                                for line in lines:
                                    file.write(line)
                                file.close()
                                shutil.move(join(directory, filename), join(directory, filename.split(".")[0] + ".mop"))
                            elif setup.software == "ORCA": # ORCA software
                                out = getinData(join(directory, "%s.pdb" % filesplit[0]))
                                # create file
                                lines = []
                                lines.append("%s \n" % setup.leveloftheory) # "!PBEh-3c opt" for example
                                lines.append("Generated by prepare_file.py\n")
                                lines.append("%% pal nprocs %s end\n" % setup.procsshared) # "16" for instance
                                lines.append("%% maxcore %s\n" % setup.memories) # "4000" for instance  in MB
                                lines.append("%%scf maxiter 500\n")
                                lines.append("     end\n")
                                lines.append("% output\n")
                                lines.append("    printlevel mini\n")
                                lines.append("    print[ P_SCFInfo ] 1\n")
                                lines.append("    print[ P_SCFIterInfo ] 1\n")
                                lines.append("    print[ P_OrbEn ] 0\n")
                                lines.append("    print[ P_Cartesian ] 0\n")
                                lines.append("end\n")
                                lines.append("% elprop\n")
                                lines.append("    Dipole False\n")
                                lines.append("end\n")
                                lines.append("* xyz %s %s \n" % (setup.charge,setup.spin))
                                for i in range(len(out.ATOMTYPES)):
                                    lines.append(" %-2s%13.8f %13.8f %13.8f \n" % ( out.ATOMTYPES[i], out.CARTESIANS[i][0], out.CARTESIANS[i][1], out.CARTESIANS[i][2]))
                                lines.append("*\n")
                                #write
                                file = open(join(directory, "%s.inp" % filesplit[0]),"w")
                                for line in lines:
                                    file.write(line)
                                file.close()
                                #remove pdb
                                try: os.remove(join(directory, "%s.pdb" % filesplit[0]))
                                except: log.write("Error: The file [%s] couldn't be deleted" % join(directory, "%s.pdb" % filesplit[0]))
                            else:
                                log.write("Error: Software in setup.ini is not recognised. [%s]" % setup.software)
                                return False
                log.write("----------------------------\n---- Normal Termination ----\n----------------------------\n")
                log.finalize()
                return True
            else:
                log.write("Error: Failed to load setup.ini in [%s]. Fix it to continue." % setup_path)
                return False
        else:
            log.write("Error: No file to modify in the directory [%s]" % directory)
            return False
    else:
        print("FATAL ERROR: Specified directory doesn't exist [%s]" % directory)
        return False

cmd.extend("prepare",prepare_file)


import threading
#Thread 모듈
import queue
#데이터를 하나씩 처리하기위한 큐
import complexWeather as cw
#기상청 API를 사용하기 위해 만들어둔 커스텀 모듈
import time
#시간 지연을 위한 모듈
import os
#폴더및 파일을 생성시 사용하는 모듈
import json
#json형태의 데이터를 처리하는 데이터
from time_z import weatherTime
#기상청API에 필요한 시간형식을 위한 모듈

from datetime import datetime
#블루투스 통신을 위한 모듈
from bluetooth import *

defaul_POP = 60

class weatherCall(threading.Thread):
    #서버측에서 기상청API에 접속을 한다.

    def __init__(self):
        threading.Thread.__init__(self)
        self.count = 0 #몇번쨰 요청을 했는지 파악하기 위한 변수
        self.POP_data =50 #강수확률
        self.T3H_data = -1 #3시간최고온도
        self.REH_data = -1 #습도도

    def run(self):
        while True:
            wt = weatherTime()

            self.count += 1
            testWeather = cw.weatherUrl()
            #기상청 API를 요청하는 구문
            a = testWeather.parsedUrl(testWeather.ForestSpaceCheck)
            #테스트라는 폴더의 존재를 확인하여
            #존재하지않을시에 생성을 한다.
            if os.path.isdir('test'):
                pass

            else:
                os.makedirs('test')
            #test폴더안에 날짜 시간별로 기상청 API의 데이터를 저장한다.
            with open('test/{}.json'.format(wt.date() + wt.time()), 'w', encoding='utf-8') as make_file:
                json.dump(a, make_file, ensure_ascii=False, indent="\t")
            #강수확률 데이터 저장
            self.POP_data =int(float(self.findCategory(parsed_data=a,category='POP'))) #강수확률
            #3시간 온도 저장
            self.T3H_data = int(float(self.findCategory(parsed_data=a,category='T3H'))) #3시간 기온
            #습도 저장
            self.REH_data =int(float(self.findCategory(parsed_data=a,category='REH'))) #습도
            print(self.POP_data)
            print(self.T3H_data)
            print(self.REH_data)

            #요청이 될때 날씨 정보를 GUI에게 보내준다.
            self.sendWeahterInformation()
            print('sendWeatherInformation')

            #3시간에 한번씩 돌린다.
            time.sleep(3*60*60)

    def sendWeahterInformation(self):
    #기상정보를 보내는 함수
            sendall('server/weatherInformation/{},{},{}'.format(self.POP_data,self.T3H_data,self.REH_data))

    def findCategory(self,parsed_data = None, category=None):
    #데이터 파싱을 위한 함수
        if parsed_data ==None:
            pass
        if category ==None:
            pass

        for i in range(len(parsed_data)):

            if parsed_data[i]['category'] == category:
                return parsed_data[i]['fcstValue']

class multiThreadServer(threading.Thread):
    #메인서버로서 여러개의 클라이언트를
    #멀티쓰레드 기법을 사용해서 한다.
    weatherCall
    #쓰레드를 관리하는 리스트이다.
    global th_list
    def __init__(self,sock,address):
        threading.Thread.__init__(self)
        #클라이언트 접속시 사용되는 소켓을 생성시에 넣는다.
        #그 값을 이제 클래스 내부에서 사용한다.
        self.sock = sock
        #daemon은 MainTrhead가 종료되면 백그라운드에 있는
        #쓰레드들도 끝난다.
        self.daemon=True
        #데이터를 하나씩 처리하기 위한큐
        self.queue = queue.Queue()
        #접속된 클라이언트들의 주소
        self.address =address
        #접속 된 클라이언들의 주소를 사용하기 편하게 파싱을 한다.
        self.parsing_address = str(address).replace(':','_')
        '''
        :를 사용했지만 text파일 생성시 이름에서:앞에만 짤리는 오류를 발견 '-'로 대체함
        블루투스는 :로 주소가 나눠진다. 따라서 :를 '-'로 대체를 하여 사용을 한다.
        '''

        # self.dispaly_connection =False #디스플레이의 요청에 따라 그래프를 그려준다.
        # self.diplay_graph_list =['solidHumidity','temperature','humidity','light']
        # self.display_solidHumidry=False
        # self.dispaly_temperature=False
        # self.display_humidity = False
        # self.display_light =False
        #
        self.defaultSolidHumidity = -1 #사용자 지정 토양습도값
        self.check_solidHumidity = -1 #두개의 변수 음의 값인 이유는 자동비교를 막기 위한 수단이다.

    def run(self):

        try:

            #self.sock.send(encodeServer('hello SCW'))
            while True:

                time.sleep(0.1)
                #lock.acquire()
                data = self.sock.recv(1024).decode('utf-8')
                que_data=self.queue.put(data)
                get_data = self.queue.get().split('/')
                print(get_data)
                #문자열 통신에서 명령어는 pi종류/센서/상태/개수/데이터
                #데이터는 ,(comma)기준으로 나눠진다.

                if len(get_data) <=6:
                    if get_data[0] == 'sensorpi':

                        #초장기 토양습도센서를 받는 방법
                        if get_data[1] == 'solidhumidity':

                            if get_data[2] == '1':

                                 sensor_counts=int(get_data[3])
                                 sensor_data =get_data[4].split(',')
                                 print(sensor_data)
                            else:
                                pass

                        #초장기의 조도센서 받는 구문
                        elif get_data[1] ==  'cds':
                            print(get_data[1])

                            if get_data[2] == '1':

                                    sensor_counts = int(get_data[3])
                                    sensor_data = get_data[4].split(',')
                                    print(sensor_data)
                            else:
                                pass
                        #초장기 온도를 받는 구분
                        elif get_data[1] == 'temperature':
                            print(get_data[1])
                            if get_data[2] == '1':

                                sensor_counts = int(get_data[3])
                                sensor_data = get_data[4].split(',')
                            else:
                                pass

                        #초장기 습도를 받는 구문
                        elif get_data[1] == 'humidity':

                            print(get_data[1])

                            if get_data[2] == '1':

                                sensor_counts = int(get_data[3])
                                sensor_data = get_data[4].split(',')
                        #센서파이에서 넘어오는 값들을 처리하는 메인서버 구문이다.
                        elif get_data[1] =='sensordata':
                            print('databaseworking')
                            sensor_check = get_data[2].split('%') #데이터는 시간,습도, 토양습도, 온도,조도, 강수확률순으로 저장한다.
                            #자동비교를 위해 변수에 넘어온 토양습도 값을 저장한다.
                            self.check_solidHumidity = int(sensor_check[1])
                            print(self.check_solidHumidity)
                            print('BeforeCompare')
                            #위에 self.check_solidHumidity의 값으로 비교를 한다.
                            self.compareValve()
                            print("AfrterCompare")
                            #넘어온 값들을 문자열 파싱을 하여 GUI에게 보낸다.
                            sensor_check = str(sensor_check).replace('[','')
                            sensor_check = str(sensor_check).replace(']','')
                            sensor_check = sensor_check+','+str(self.parsing_address)

                            print(sensor_check)
                            send_sensordata = "server/display/{}%{}".format(get_data[2],self.parsing_address)
                            # time.sleep(5) #테스트용

                            print(send_sensordata)
                            #파싱된 센서들의 값을 저장하는 구문이다.
                            sensor_check = sensor_check+'\n'
                            #이 데이터들을 전 클라이언트들에게 보낸다.
                            sendall(send_sensordata)
                            with open('sensorDatabase.txt','a+t',encoding='utf-8') as sd:
                                sd.writable()
                                sd.write(sensor_check)

                        else:
                            pass

                    #'valvepi/valvenumber/1/0'
                    #벨브파이의 상태를 받아 전달하는 명령어이다.
                    elif get_data[0] == 'valvepi':

                            if get_data[1] == 'valvenumber':

                                if get_data[2] == '1':
                                    if get_data[3] == '0':
                                        sendall('server/valvestate/1/0')

                                    else:
                                        sendall('server/valvestate/1/1')

                                elif get_data[2] == '2':

                                    if get_data[3] == '0':

                                        sendall('server/valvestate/2/0')

                                    else:

                                        sendall('server/valvestate/2/1')

                                elif get_data[2] == '3':

                                    if get_data[3] == '0':

                                        sendall('server/valvestate/3/0')

                                    else:

                                        sendall('server/valvestate/3/1')

                                elif get_data[2] == '4':

                                    if get_data[3] == '0':

                                        sendall('server/valvestate/4/0')

                                    else:

                                        sendall('server/valvestate/4/1')

                            #벨브의 자동및 수동 모드의 상태를 알려주는 문자열이다.
                            elif get_data[1] =='valvecustum':
                                if get_data[2] =='auto':
                                    sendall('server/valvecustum/auto')
                                elif get_data[2] =='manual':
                                    sendall('server/valvecustum/manual')
                            #GUI 클라이언트에 벨브파이의 상태를 전송하는 구문이다.
                            elif get_data[1] =='displaypi':
                                if get_data[2] =='ar':
                                    sendall('valvepi/ar/{}'.format(get_data[3]))

                    elif get_data[0] == 'displaypi':
                    #GUI에서 기상청 정보를 요청할떄 사용되는 데이터이다.
                        if get_data[1] == 'weatherRequest':
                            weatherCall.sendWeahterInformation()

                    #GUI에서 사용자가 토양습도 설정시 이 데이터들을 보내준다.
                        elif get_data[1] == 'default':
                            self.defaultSolidHumidity=int(get_data[2])
                            for i in th_list:
                                i.defaultSolidHumidity=int(get_data[2])

                        #'displaypi/command/valve04/on'
                        #GUI에서 벨브를 키고 끌때 사용되는 명령어이다.
                        elif get_data[1] == 'command':
                            if get_data[2] =='valve01':
                                if get_data[3] == 'on':
                                    sendall('server/valvepi/valve01/on')

                                else:
                                    sendall('server/valvepi/valve01/off')
                            elif get_data[2] == 'valve02':

                                if get_data[3] == 'on':
                                    sendall('server/valvepi/valve02/on')

                                else:
                                    sendall('server/valvepi/valve02/off')

                            elif get_data[2] == 'valve03':

                                if get_data[3] == 'on':
                                    sendall('server/valvepi/valve03/on')

                                else:
                                    sendall('server/valvepi/valve03/off')

                            elif get_data[2] == 'valve04':

                                if get_data[3] == 'on':
                                    sendall('server/valvepi/valve04/on')

                                else:
                                    sendall('server/valvepi/valve04/off')
                        elif get_data[1] == 'custum':
                            if get_data[2] =='manual':
                                sendall('server/custum/manual')
                            elif get_data[2] == 'auto':
                                sendall('server/custum/auto')

                        elif get_data[1] == 'valvepi':
                            #G
                            if get_data[2] =='allrequest':
                                sendall('server/valvepi2/allrequest')

                        #초장기 각각의 데이터의 요청에 따라 GUI에 그려주는 것을 구상을 했지만 값들을 다 보여주는게
                        #사용자한테 편리하다는 것을 판단을 함
                        # if get_data[1] == '1':
                        #   for i in self.diplay_graph_list: #self.diplay_graph_list =['solidHumidity','temperature','humidity','light']
                        #     if get_data[2] == str(i):
                        #         str(i)
                        #         if i == self.diplay_graph_list[0]:
                        #             self.display_solidHumidry=True
                        #         elif i == self.diplay_graph_list[1]:
                        #             self.diaply_temperature=True
                        #         elif i == self.diplay_graph_list[2]:
                        #             self.display_humidity=True
                        #         elif i == self.diplay_graph_list[3]:
                        #             self.display_light=True
                        #         else:
                        #             pass
                        # elif get_data[1] == '0':
                        #     for i in self.diplay_graph_list:  # self.diplay_graph_list =['solidHumidity','temperature','humidity','light']
                        #         if get_data[2] == str(i):
                        #             str(i)
                        #             if i == self.diplay_graph_list[0]:
                        #                 self.display_solidHumidry = False
                        #             elif i == self.diplay_graph_list[1]:
                        #                 self.dispay_temperature = False
                        #             elif i == self.diplay_graph_list[2]:
                        #                 self.display_humidity = False
                        #             elif i == self.diplay_graph_list[3]:
                        #                 self.display_light = False
                        #             else:
                        #                 pass
                        #

                        # 그래프를 그릴때 address(즉 블루투스당 그래프를 그려야할지 고민을 해봐야겠다.)

                        # elif self.display_solidHumidry:
                        #     self.sock.send()
                        #
                        # elif self.display_humidity:
                        #     self.sock.send()
                        # elif self.diaply_temperature:
                        #     self.sock.send()
                        #
                        # elif self.display_light:
                        #     self.sock.send()

                else:
                    pass

        except IOError:
        #만약 접속 에러가 발생했을때 그 thread를 관리하는 리스트에서
        #삭제를 한다.
            for i in th_list:

                if i.name == self.name:
                    th_list.remove(i)

                    print('{} exit'.format(self.name))

            print('remove')

            self.sock.close()

        except ConnectionResetError:
            # 만약 접속 에러가 발생했을때 그 thread를 관리하는 리스트에서
            # 삭제를 한다.
            for i in th_list:

                if i.name == self.name:
                    th_list.remove(i)

                    print('{} exit'.format(self.name))

            print('remove')

            self.sock.close()

    #센서파이 전부다 습도 비교
    #센서파이와 기상처 api습도,강수량,강수확률 비교
    #인공지능 모델과 비교
    #조도센서 받기
    #온도센서 받기
    #토양습도센서
    #디스플레이 센서에서 받은 값을 서버한테 넘겨주는 명령어를 만들어야한다.
    #

    def compareValve(self):
    #사용자 토양습도값과 센서파이들의 토양습도값들을 비교한다.

        print(self.check_solidHumidity > 0 and self.defaultSolidHumidity >0)
        print(self.check_solidHumidity)
        print(self.defaultSolidHumidity)
        if self.check_solidHumidity > 0 and self.defaultSolidHumidity >0 :

            compare_value = self.defaultSolidHumidity -self.check_solidHumidity
            #만약 물을 줘야한다면 밑에 조건문이 작동
            if compare_value >=0:
                print('compareon')
                sendall('server/valveCompare/{}/{}'.format(self.address,compare_value))
            #물을 안줘도 될때 아래 조건문이 작동
            elif compare_value <0:
                print('compareoff')
                sendall('server/valveStop/{}'.format(self.address))

def encodeServer(strk):
    #encdoing하는 함수
    strk = str(strk)
    a = strk.encode('utf-8')
    return a

def sendall(str):
    #모든 클라이언들에게 정보 전송
    #보내는 와중에 문자열들이 끼어들면 안되기 떄문에
    #LOCk을사용해 동기화를 시킨다.
    lock.acquire()
    try:

        for i in th_list:

            i.sock.send(encodeServer(str))

    except Exception:
        pass
    lock.release()

# def commandinput(inputs, command_list):
#
#
#
#             while True:
#                 input_str = input(inputs).strip()
#
#                 for i in command_list:
#                     print(i)
#                     if input_str == str(i):
#                         return str(i)
#                     else:
#                         print('명령어 리스트없는 값입니다.'.format(command_list))
#                         pass

port=2
#빈칸으로 호스트를 호출할시에 자기자신의 주소를 집어넣는다.
host = ''
#port = 1803
#multi_trhead를 활용하기 위한 리스트 생성
th_list = []
#기상청 API에서 데이터를 받기위한 thread 생성
weatherCall=weatherCall()
#기상청 APIthread 시작
weatherCall.start()
sock=BluetoothSocket(RFCOMM)
#sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.bind((host, port))
sock.listen(2)
#데이터를 보내는 과정의 큐를 사용함
sending_que = queue.Queue()
while True:
    #비동기화 통신에서 동기화가 필요할때 사용하는 값
    lock = threading.Lock()
    #클라이언트가 서버에 접속을 했을시에
    #클라이언트 이름과 주소를 반환하는 함수이다.
    #accept함수는 클라이언트가 접속을 할때까지 기다린다.
    client, address = sock.accept()
    print('주소가 {}인 클라이언트({})의 접속했습니다'.format(address,client))
    #접속시 그 클라이언트을 넣은 Thread를 생성한다.
    clientThread=multiThreadServer(client,address[0])
    #Thread관리를 위한 리스트에 집어넣는다.
    th_list.append(clientThread)
    print(clientThread)
    #Thread시작.
    clientThread.start()

    #새로운 클라이언트 접속시 날씨 데이터를 전송해준다.
    print('reSendingWeather')
    #접속시 날씨 데이터를 업데이트를 해준다.
    weatherCall.sendWeahterInformation()


# 287. Find the Duplicate Number
import collections
class Solution:
    # bit manipulation
    def findDuplicate(self, nums):
        a = 1 << (len(nums))
        for i in nums:
            if a & 1 << i:
                return i
            a = a | 1 << i

    # sorting: does not satisfy the conditions
    def findDuplicate2(self, nums):
        nums.sort()
        for i in range(len(nums)-1):
            if nums[i] == nums[i+1]:
                return nums[i]

    # counter: does not satisfy the conditions
    def findDuplicate3(self, nums):
        count = collections.Counter(nums)
        for k, v in count.items():
            if v > 1:
                return k

    # set: does not satisfy the conditions
    def findDuplicate5(self, nums):
        seen = set()
        for i in nums:
            if i in seen:
                return i
            seen.add(i)

    # cycle detection
    def findDuplicate4(self, nums):
        tor, rab = 0, 0

        while True:
            tor = nums[tor]
            rab = nums[nums[rab]]
            if tor == rab:
                break

        tor = 0
        while tor != rab:
            tor = nums[tor]
            rab = nums[rab]

        return tor

sol = Solution()
print(sol.findDuplicate4([2,2,2,2,2]))

leetcode/0-250/173-287. Find the Duplicate Number.py


from django.db import models
from django.db.models.fields import DateField
from hostels.models import Hostel
from hotels.models import Hotels
from house.models import Home
from django.contrib.auth.models import User

# Create your models here.

class Ratings(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    hostel = models.ForeignKey(Hostel, on_delete=models.CASCADE, null=True)
    hotel = models.ForeignKey(Hotels, on_delete=models.CASCADE, null=True)
    home = models.ForeignKey(Home, on_delete=models.CASCADE, null=True)
    ratings = models.IntegerField()
    comment = models.TextField(max_length=1000, null=True)
    likes = models.IntegerField(default=0, null=True)
    date = models.DateField(null=True)

class Replies(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    comment = models.ForeignKey(Ratings, on_delete=models.CASCADE)
    reply = models.TextField(max_length=1000, null=True)
    likes = models.IntegerField(null=True)
    date = models.DateField()


# -*- coding: utf-8 -*-
def parseErrorCode(code):
    """에러코드 메시지

        :param code: 에러 코드
        :type code: str
        :return: 에러코드 메시지를 반환

        ::

            parseErrorCode("00310") # 모의투자 조회가 완료되었습니다
    """
    code = str(code)
    ht = {
        "0" : "정상처리",
        "-10" : "실패",
        "-100" : "사용자정보교환에 실패하였습니다. 잠시후 다시 시작하여 주십시오.",
        "-101" : "서버 접속 실패",
        "-102" : "버전처리가 실패하였습니다.",
        "-105" : "함수입력값 오류",
        "-106" : "통신연결 종료",
        "-200" : "시세조회 과부하 (조회횟수 제한 초과)",
        "-201" : "REQUEST_INPUT_st Failed",
        "-202" : "요청 전문 작성 실패",
        "-204" : "조회가능한 종목수 초과 (한번에 조회 가능한 종목개수는 최대 100종목)",
        "-205" : "데이터 수신 실패",
        "-206" : "조회가능한 FID수 초과 (한번에 조회 가능한 FID개수는 최대 100개)",
        "-300" : "주문 입력값 오류(허용되지 않는 입력값)",
        "-301" : "계좌비밀번호를 입력하십시오.",
        "-302" : "타인계좌는 사용할 수 없습니다.",
        "-303" : "주문가격이 20억원을 초과합니다.",
        "-304" : "주문가격은 50억원을 초과할 수 없습니다.",
        "-305" : "주문수량이 총발행주수의 1%를 초과합니다.",
        "-306" : "주문수량은 총발행주수의 3%를 초과할 수 없습니다.",
        "-307" : "주문전송 실패",
        "-308" : "주문전송 과부하 (주문횟수 제한 초과)",
        "-340" : "계좌정보 없음",
        "-500" : "종목코드 없음"
    }
    return ("[%s] " + ht[code]) % code if code in ht else code


num = int(input())
numbers = [int(i) for i in input().split()]
numbers.sort()
count = 0
tmp = 0
for n in numbers:
    if tmp == n:
        None
    else:
        count += 1
        tmp = n

print(count)


import numpy as np
from PIL import Image
import gzip
import os

from keras.layers import Input, Dense
from keras.models import Model

import matplotlib.pyplot as plt

np.random.seed(0)

def get_data():

    files = os.listdir('./data/denoising/train')
    train_imgs = np.zeros((len(files),258,540))
    for idx, filename in enumerate(files):
        img = Image.open('./data/denoising/train/'+filename).convert('L')
        img = img.resize((540,258),Image.ANTIALIAS)
        train_imgs[idx,:] = np.asarray(img)

    files = os.listdir('./data/denoising/train_cleaned')
    train_denoised_imgs = np.zeros((len(files),258,540))
    for idx, filename in enumerate(files):
        img = Image.open('./data/denoising/train_cleaned/'+filename).convert('L')
        img = img.resize((540,258),Image.ANTIALIAS)
        train_denoised_imgs[idx,:] = np.asarray(img)

    files = os.listdir('./data/denoising/test')
    test_imgs = np.zeros((len(files),258,540))
    for idx, filename in enumerate(files):
        img = Image.open('./data/denoising/test/'+filename).convert('L')
        img = img.resize((540,258),Image.ANTIALIAS)
        test_imgs[idx,:] = np.asarray(img)

    return train_imgs, train_denoised_imgs, test_imgs

if __name__ == "__main__":

    train, train_denoised, test = get_data()

    #normalize
    train /= 255.0
    train_denoised /= 255.0
    test /= 255.0

    #reshape
    train = train.reshape(-1, (train.shape[1] * train.shape[2]))
    train_denoised = train_denoised.reshape(-1, (train_denoised.shape[1] * train_denoised.shape[2]))
    test = test.reshape(-1, (test.shape[1] * test.shape[2]))

    input_shape = train.shape[1]

    #autoencoder
    input_img = Input(shape=(input_shape,))
    encoded = Dense(128, activation='relu')(input_img)
    encoded = Dense(64, activation='relu')(encoded)
    encoded = Dense(32, activation='relu')(encoded)

    decoded = Dense(64, activation='relu')(encoded)
    decoded = Dense(128, activation='relu')(decoded)
    decoded = Dense(input_shape, activation='sigmoid')(decoded)

    autoencoder = Model(input=input_img, output=decoded)
    autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')

    autoencoder.fit(train, train_denoised, nb_epoch=1, batch_size=64, shuffle=True, verbose=2)

    #denoise test data
    denoised_imgs = autoencoder.predict(test)

    denoised_imgs = denoised_imgs.reshape((-1, 258, 540))
    #denoised_imgs *= 255.0

    #im = Image.fromarray(denoised_imgs[1,:,:])
    #im = im.convert("L")
    #im.save('./denoised.png')

    #create submission
    submission = gzip.open("fc_autoenc.csv.gz","wt")
    submission.write("id,value\n")

    files = os.listdir('./data/denoising/test')
    for idx, filename in enumerate(files):
        img_idx = int(filename[:-4])
        img = Image.open('./data/denoising/test/'+filename).convert('L')
        img_dim = img.size

        denoised_im = Image.fromarray(denoised_imgs[idx,:,:])
        denoised_im = denoised_im.convert("L")
        denoised_im = denoised_im.resize(img_dim,Image.ANTIALIAS)
        denoised_im = np.asarray(denoised_im)

        for j in range(denoised_im.shape[1]):
            for i in range(denoised_im.shape[0]):
                submission.write("{}_{}_{},{}\n".format(img_idx,i+1,j+1,denoised_im[i,j]))

    submission.close()