# -*- coding: utf-8 -*-
"""
Created on Sun Feb 14 12:35:08 2021

@author: lefti
"""

#importing the libraries

import tensorflow as tf
from keras.preprocessing.image import ImageDataGenerator

# Preprocessing the data
train_datagen = ImageDataGenerator(rescale=1./255,
                                   shear_range=0.2,
                                   zoom_range=0.2,
                                   horizontal_flip=True)

training_set = train_datagen.flow_from_directory( 'dataset/Training_set',
                                                    target_size=(256,256),
                                                    batch_size =32,
                                                    class_mode='binary')
test_datagen =ImageDataGenerator(rescale=1./255)
test_set = test_datagen.flow_from_directory('dataset/test',
                                                  target_size= (256,256),
                                                  batch_size =32,
                                                  class_mode = 'binary'
                                                  )

#building the Convolutional neural network
#initialise the cnn
cnn = tf.keras.models.Sequential()
#adding the first and input layer
cnn.add(tf.keras.layers.Conv2D(filters=32,
                               kernel_size=4,
                               activation='relu',
                               input_shape =[256,256,3]))
#adding the pooling to first layer
cnn.add(tf.keras.layers.MaxPool2D(pool_size=2,strides=2))

#add layer 2
cnn.add(tf.keras.layers.Conv2D(filters= 32,
                               kernel_size=4,
                               activation='relu'))
#add pooling to layer2
cnn.add(tf.keras.layers.MaxPool2D(pool_size=2,strides=2))

#flattening the layers
cnn.add(tf.keras.layers.Flatten())

#creating full connection
cnn.add(tf.keras.layers.Dense(units=150,activation='relu'))

#output layer
cnn.add(tf.keras.layers.Dense(units=1,activation='sigmoid'))

#compiling the cnn
cnn.compile(optimizer = 'adam', loss='binary_crossentropy',metrics=['accuracy'])

#training the cnn
cnn.fit(x=training_set,validation_data = test_set,epochs=32)

Deep Learning/CNN/Electric bus or cars classification/carbusclassification.py


import cv2
import time
import tensorflow as tf
from tensorflow.python.platform import gfile
import numpy as np

def model_restore_from_pb(pb_path,node_dict):
    config = tf.ConfigProto(log_device_placement=True,#印出目前的運算是使用CPU或GPU
                            allow_soft_placement=True,#當設備不存在時允許tf選擇一个存在且可用的設備來繼續執行程式
                            )
    config.gpu_options.allow_growth = True#依照程式執行所需要的資料來自動調整
    #config.gpu_options.per_process_gpu_memory_fraction = 0.6#手動限制GPU資源的使用
    sess = tf.Session(config=config)
    with gfile.FastGFile(pb_path, 'rb') as f:
        graph_def = tf.GraphDef()
        graph_def.ParseFromString(f.read())
        sess.graph.as_default()
        tf.import_graph_def(graph_def, name='')  # 匯入計算圖
    sess.run(tf.global_variables_initializer())
    for key,value in node_dict.items():
        node = sess.graph.get_tensor_by_name(value)
        node_dict[key] = node
    return sess,node_dict

def video_init(is_2_write=False,save_path=None):
    writer = None
    cap = cv2.VideoCapture(0)
    height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)#default 640x480
    width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
    #total_frames = cap.get(cv2.CAP_PROP_FRAME_COUNT)

    # width = 480
    # height = 640
    # cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
    # cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)

    '''
    ref:https://docs.opencv.org/master/dd/d43/tutorial_py_video_display.html
    FourCC is a 4-byte code used to specify the video codec.
    The list of available codes can be found in fourcc.org.
    It is platform dependent. The following codecs work fine for me.
    In Fedora: DIVX, XVID, MJPG, X264, WMV1, WMV2. (XVID is more preferable. MJPG results in high size video. X264 gives very small size video)
    In Windows: DIVX (More to be tested and added)
    In OSX: MJPG (.mp4), DIVX (.avi), X264 (.mkv).
    FourCC code is passed as `cv.VideoWriter_fourcc('M','J','P','G')or cv.VideoWriter_fourcc(*'MJPG')` for MJPG.
    '''

    if is_2_write is True:
        #fourcc = cv2.VideoWriter_fourcc('x', 'v', 'i', 'd')
        #fourcc = cv2.VideoWriter_fourcc('X', 'V', 'I', 'D')
        fourcc = cv2.VideoWriter_fourcc(*'XVID')
        if save_path is None:
            save_path = 'demo.avi'
        writer = cv2.VideoWriter(save_path, fourcc, 20, (int(width), int(height)))

    return cap,height,width,writer

def generate_anchors(feature_map_sizes, anchor_sizes, anchor_ratios, offset=0.5):
    '''
    generate anchors.
    :param feature_map_sizes: list of list, for example: [[40,40], [20,20]]
    :param anchor_sizes: list of list, for example: [[0.05, 0.075], [0.1, 0.15]]
    :param anchor_ratios: list of list, for example: [[1, 0.5], [1, 0.5]]
    :param offset: default to 0.5
    :return:
    '''
    anchor_bboxes = []
    for idx, feature_size in enumerate(feature_map_sizes):
        cx = (np.linspace(0, feature_size[0] - 1, feature_size[0]) + 0.5) / feature_size[0]
        cy = (np.linspace(0, feature_size[1] - 1, feature_size[1]) + 0.5) / feature_size[1]
        cx_grid, cy_grid = np.meshgrid(cx, cy)
        cx_grid_expend = np.expand_dims(cx_grid, axis=-1)
        cy_grid_expend = np.expand_dims(cy_grid, axis=-1)
        center = np.concatenate((cx_grid_expend, cy_grid_expend), axis=-1)

        num_anchors = len(anchor_sizes[idx]) +  len(anchor_ratios[idx]) - 1
        center_tiled = np.tile(center, (1, 1, 2* num_anchors))
        anchor_width_heights = []

        # different scales with the first aspect ratio
        for scale in anchor_sizes[idx]:
            ratio = anchor_ratios[idx][0] # select the first ratio
            width = scale * np.sqrt(ratio)
            height = scale / np.sqrt(ratio)
            anchor_width_heights.extend([-width / 2.0, -height / 2.0, width / 2.0, height / 2.0])

        # the first scale, with different aspect ratios (except the first one)
        for ratio in anchor_ratios[idx][1:]:
            s1 = anchor_sizes[idx][0] # select the first scale
            width = s1 * np.sqrt(ratio)
            height = s1 / np.sqrt(ratio)
            anchor_width_heights.extend([-width / 2.0, -height / 2.0, width / 2.0, height / 2.0])

        bbox_coords = center_tiled + np.array(anchor_width_heights)
        bbox_coords_reshape = bbox_coords.reshape((-1, 4))
        anchor_bboxes.append(bbox_coords_reshape)
    anchor_bboxes = np.concatenate(anchor_bboxes, axis=0)
    return anchor_bboxes

def decode_bbox(anchors, raw_outputs, variances=[0.1, 0.1, 0.2, 0.2]):
    '''
    Decode the actual bbox according to the anchors.
    the anchor value order is:[xmin,ymin, xmax, ymax]
    :param anchors: numpy array with shape [batch, num_anchors, 4]
    :param raw_outputs: numpy array with the same shape with anchors
    :param variances: list of float, default=[0.1, 0.1, 0.2, 0.2]
    :return:
    '''
    anchor_centers_x = (anchors[:, :, 0:1] + anchors[:, :, 2:3]) / 2
    anchor_centers_y = (anchors[:, :, 1:2] + anchors[:, :, 3:]) / 2
    anchors_w = anchors[:, :, 2:3] - anchors[:, :, 0:1]
    anchors_h = anchors[:, :, 3:] - anchors[:, :, 1:2]
    raw_outputs_rescale = raw_outputs * np.array(variances)
    predict_center_x = raw_outputs_rescale[:, :, 0:1] * anchors_w + anchor_centers_x
    predict_center_y = raw_outputs_rescale[:, :, 1:2] * anchors_h + anchor_centers_y
    predict_w = np.exp(raw_outputs_rescale[:, :, 2:3]) * anchors_w
    predict_h = np.exp(raw_outputs_rescale[:, :, 3:]) * anchors_h
    predict_xmin = predict_center_x - predict_w / 2
    predict_ymin = predict_center_y - predict_h / 2
    predict_xmax = predict_center_x + predict_w / 2
    predict_ymax = predict_center_y + predict_h / 2
    predict_bbox = np.concatenate([predict_xmin, predict_ymin, predict_xmax, predict_ymax], axis=-1)
    return predict_bbox

def single_class_non_max_suppression(bboxes, confidences, conf_thresh=0.2, iou_thresh=0.5, keep_top_k=-1):
    '''
    do nms on single class.
    Hint: for the specific class, given the bbox and its confidence,
    1) sort the bbox according to the confidence from top to down, we call this a set
    2) select the bbox with the highest confidence, remove it from set, and do IOU calculate with the rest bbox
    3) remove the bbox whose IOU is higher than the iou_thresh from the set,
    4) loop step 2 and 3, util the set is empty.
    :param bboxes: numpy array of 2D, [num_bboxes, 4]
    :param confidences: numpy array of 1D. [num_bboxes]
    :param conf_thresh:
    :param iou_thresh:
    :param keep_top_k:
    :return:
    '''
    if len(bboxes) == 0: return []

    conf_keep_idx = np.where(confidences > conf_thresh)[0]

    bboxes = bboxes[conf_keep_idx]
    confidences = confidences[conf_keep_idx]

    pick = []
    xmin = bboxes[:, 0]
    ymin = bboxes[:, 1]
    xmax = bboxes[:, 2]
    ymax = bboxes[:, 3]

    area = (xmax - xmin + 1e-3) * (ymax - ymin + 1e-3)
    idxs = np.argsort(confidences)

    while len(idxs) > 0:
        last = len(idxs) - 1
        i = idxs[last]
        pick.append(i)

        # keep top k
        if keep_top_k != -1:
            if len(pick) >= keep_top_k:
                break

        overlap_xmin = np.maximum(xmin[i], xmin[idxs[:last]])
        overlap_ymin = np.maximum(ymin[i], ymin[idxs[:last]])
        overlap_xmax = np.minimum(xmax[i], xmax[idxs[:last]])
        overlap_ymax = np.minimum(ymax[i], ymax[idxs[:last]])
        overlap_w = np.maximum(0, overlap_xmax - overlap_xmin)
        overlap_h = np.maximum(0, overlap_ymax - overlap_ymin)
        overlap_area = overlap_w * overlap_h
        overlap_ratio = overlap_area / (area[idxs[:last]] + area[i] - overlap_area)

        need_to_be_deleted_idx = np.concatenate(([last], np.where(overlap_ratio > iou_thresh)[0]))
        idxs = np.delete(idxs, need_to_be_deleted_idx)

    # if the number of final bboxes is less than keep_top_k, we need to pad it.
    # TODO
    return conf_keep_idx[pick]

def mask_detection(is_2_write=False,save_path=None):
    #----var
    pb_path = "face_mask_detection.pb"
    node_dict = {'input':'data_1:0',
                 'detection_bboxes':'loc_branch_concat_1/concat:0',
                 'detection_scores':'cls_branch_concat_1/concat:0'}
    conf_thresh = 0.5
    iou_thresh = 0.4
    frame_count = 0
    FPS = "0"
    #====anchors config
    feature_map_sizes = [[33, 33], [17, 17], [9, 9], [5, 5], [3, 3]]
    anchor_sizes = [[0.04, 0.056], [0.08, 0.11], [0.16, 0.22], [0.32, 0.45], [0.64, 0.72]]
    anchor_ratios = [[1, 0.62, 0.42]] * 5
    id2class = {0: 'Mask', 1: 'NoMask'}

    #----video streaming init
    cap, height, width, writer = video_init(is_2_write=is_2_write,save_path=save_path)

    #----model init

    #====generate anchors
    anchors = generate_anchors(feature_map_sizes, anchor_sizes, anchor_ratios)
    # for inference , the batch size is 1, the model output shape is [1, N, 4],
    # so we expand dim for anchors to [1, anchor_num, 4]
    anchors_exp = np.expand_dims(anchors, axis=0)

    #====model restore from pb file
    sess,node_dict = model_restore_from_pb(pb_path, node_dict)
    tf_input = node_dict['input']
    model_shape = tf_input.shape#[N,H,W,C]
    print("model_shape = ", model_shape)
    detection_bboxes = node_dict['detection_bboxes']
    detection_scores = node_dict['detection_scores']

    while (cap.isOpened()):

        #----get image
        ret, img = cap.read()

        if ret:
            #----image processing
            img_resized = cv2.resize(img, (model_shape[2], model_shape[1]))
            img_resized = cv2.cvtColor(img_resized, cv2.COLOR_BGR2RGB)
            img_resized = img_resized.astype('float32')
            img_resized /= 255

            #----mask detection
            y_bboxes_output, y_cls_output = sess.run([detection_bboxes, detection_scores],
                                                     feed_dict={tf_input: np.expand_dims(img_resized, axis=0)})

            #remove the batch dimension, for batch is always 1 for inference.
            y_bboxes = decode_bbox(anchors_exp, y_bboxes_output)[0]
            y_cls = y_cls_output[0]
            # To speed up, do single class NMS, not multiple classes NMS.
            bbox_max_scores = np.max(y_cls, axis=1)
            bbox_max_score_classes = np.argmax(y_cls, axis=1)

            # keep_idx is the alive bounding box after nms.
            keep_idxs = single_class_non_max_suppression(y_bboxes,
                                                         bbox_max_scores,
                                                         conf_thresh=conf_thresh,
                                                         iou_thresh=iou_thresh,
                                                         )
            #====draw bounding box
            for idx in keep_idxs:
                conf = float(bbox_max_scores[idx])
                class_id = bbox_max_score_classes[idx]
                bbox = y_bboxes[idx]
                # clip the coordinate, avoid the value exceed the image boundary.
                xmin = max(0, int(bbox[0] * width))
                ymin = max(0, int(bbox[1] * height))
                xmax = min(int(bbox[2] * width), width)
                ymax = min(int(bbox[3] * height), height)

                if class_id == 0:
                    color = (0, 255, 0)  # (B,G,R)
                else:
                    color = (0, 0, 255)  # (B,G,R)
                cv2.rectangle(img, (xmin, ymin), (xmax, ymax), color, 2)
                cv2.putText(img, "%s: %.2f" % (id2class[class_id], conf), (xmin + 2, ymin - 2),
                            cv2.FONT_HERSHEY_SIMPLEX, 0.8, color)

            #----FPS count
            if frame_count == 0:
                t_start = time.time()
            frame_count += 1
            if frame_count >= 10:
                FPS = "FPS=%1f" % (10 / (time.time() - t_start))
                frame_count = 0
            #cv2.putText(影像, 文字, 座標, 字型, 大小, 顏色, 線條寬度, 線條種類)
            cv2.putText(img, FPS, (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 3)

            #----image display
            cv2.imshow("demo by JohnnyAI", img)

            #----image writing
            if writer is not None:
                writer.write(img)

            #----'q' key pressed?
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
        else:
            print("get image failed")
            break

    #----release
    cap.release()
    if writer is not None:
        writer.release()
    cv2.destroyAllWindows()

if __name__ == "__main__":
    save_path = r"E:\demo.avi"
    mask_detection(is_2_write=False, save_path=save_path)


import copy
import datetime
import json
import numbers
import os
import pickle
import tempfile
import types
import unittest

from lib.attributes import Attributes
from lib.database import Database

class AttributesTestCase(unittest.TestCase):
    def setUp(self):
        parentpath = (
            os.path.abspath(
                os.path.join(
                    os.path.dirname(os.path.realpath(__file__)),
                    os.pardir
                )
            )
        )
        manifestpath = os.path.join(parentpath, 'manifest.json')
        self.rawattributes = None
        with open(manifestpath, 'r') as file_:
            self.rawattributes = json.load(file_)['attributes']

        configpath = os.path.join(parentpath, 'config.json')
        self.rawsettings = None
        with open(configpath, 'r') as file_:
            contents = json.load(file_)
            self.rawsettings = contents['options']['datasource']
            self.rawgoptions = {
                'today': contents['options']['datasource']
            }

    def test_init(self):
        # Arrange
        expected = len(self.rawattributes)

        # Act
        attributes = Attributes(
            self.rawattributes, database=None, goptions=self.rawgoptions
        )

        # Assert
        self.assertEqual(expected, len(attributes.attributes))
        for attribute in attributes.attributes:
            self.assertNotEqual('', attribute.name)
            self.assertNotEqual('', attribute.initial)
            self.assertIsInstance(attribute.weight, numbers.Number)
            self.assertIsInstance(attribute.enabled, bool)
            self.assertIsInstance(attribute.essential, bool)
            self.assertIsInstance(attribute.persist, bool)
            self.assertIsInstance(attribute.dependencies, list)
            self.assertIsInstance(attribute.options, dict)
            self.assertIsInstance(attribute.reference, types.ModuleType)

    def test_pickling(self):
        # Arrange
        attributes = Attributes(
            self.rawattributes, database=None, goptions=self.rawgoptions
        )
        expected = len(attributes.attributes)

        # Act
        pickled = pickle.dumps(attributes)
        unpickled = pickle.loads(pickled)

        # Assert
        self.assertIsInstance(unpickled, Attributes)
        self.assertEqual(expected, len(unpickled.attributes))
        for attribute in unpickled.attributes:
            self.assertNotEqual('', attribute.name)
            self.assertNotEqual('', attribute.initial)
            self.assertIsInstance(attribute.weight, numbers.Number)
            self.assertIsInstance(attribute.enabled, bool)
            self.assertIsInstance(attribute.essential, bool)
            self.assertIsInstance(attribute.persist, bool)
            self.assertIsInstance(attribute.dependencies, list)
            self.assertIsInstance(attribute.options, dict)
            self.assertIsInstance(attribute.reference, types.ModuleType)

    def test_keystring(self):
        # Arrange
        keystring = 'DuAlIcH'

        # Act
        attributes = Attributes(
            self.rawattributes, database=None, keystring=keystring,
            goptions=self.rawgoptions
        )

        # Assert
        for attribute in attributes.attributes:
            index = str.find(keystring.lower(), attribute.initial)
            if index == -1:
                self.assertFalse(attribute.enabled)
            else:
                self.assertTrue(attribute.enabled)
                if keystring[index].isupper():
                    self.assertTrue(attribute.persist)
                else:
                    self.assertFalse(attribute.persist)

    def test_is_persitence_enabled(self):
        # Arrange
        keystring = 'dualmichs'

        # Act
        attributes = Attributes(
            self.rawattributes, database=None, keystring=keystring,
            goptions=self.rawgoptions
        )

        # Assert
        self.assertFalse(attributes.is_persistence_enabled)

        # Arrange
        keystring = 'dualMichs'

        # Act
        attributes = Attributes(
            self.rawattributes, database=None, keystring=keystring
        )

        # Assert
        self.assertTrue(attributes.is_persistence_enabled)

    def test_init_repository(self):
        with tempfile.TemporaryDirectory() as directory:
            # Arrange
            project_id = 10868464
            repository_path = os.path.join(directory, str(project_id))
            expected = os.path.join(
                directory, str(project_id), 'squib'
            )

            # Act
            attributes = Attributes(
                self.rawattributes, database=Database(self.rawsettings),
                goptions=self.rawgoptions
            )
            try:
                attributes.database.connect()
                actual = attributes._init_repository(
                    project_id, repository_path
                )

                # Assert
                self.assertTrue(len(os.listdir(repository_path)) > 0)
                self.assertTrue(expected in actual)
            finally:
                attributes.database.disconnect()

    def test_cleanup(self):
        with tempfile.TemporaryDirectory() as directory:
            # Arrange
            project_id = 10868464
            repository_home = os.path.join(directory, str(project_id))
            attributes = Attributes(
                self.rawattributes, database=Database(self.rawsettings),
                goptions=self.rawgoptions
            )
            try:
                attributes.database.connect()
                attributes._init_repository(project_id, repository_home)

                # Act
                attributes._cleanup(repository_home)

                # Assert
                self.assertFalse(os.path.exists(repository_home))
            finally:
                attributes.database.disconnect()

    def test_run_timeout(self):
        with tempfile.TemporaryDirectory() as directory:
            # Arrange
            project_id = 10868464
            repository_path = directory
            rawattributes = copy.deepcopy(self.rawattributes)
            for attribute in rawattributes:
                if 'architecture' in attribute['name']:
                    attribute['options']['timeout'] = '1S'  # Sabotage
            expected = (0, {'architecture': None})

            # Act
            attributes = Attributes(
                rawattributes,
                database=Database(self.rawsettings),
                keystring='a',
                goptions=self.rawgoptions
            )
            try:
                attributes.database.connect()
                actual = attributes.run(project_id, repository_path)

                # Assert
                self.assertEqual(expected, actual)
            finally:
                attributes.database.disconnect()

    def test_score(self):
        # Global Arrange
        attributes = Attributes(
            self.rawattributes, database=None, goptions=self.rawgoptions
        )

        # Arrange
        rresults = {
            'architecture': 9.00,
            'community': 9.00,
            'continuous_integration': True,
            'documentation': 9.00,
            'history': 9.00,
            'license': True,
            'management': 9.00,
            'state': 'active',
            'unit_test': 9.00,
        }
        expected = 100.00

        # Act
        actual = attributes.score(rresults)

        # Assert
        self.assertEqual(expected, actual)

        # Arrange
        rresults = {
            'architecture': 9.00,
            'community': 9.00,
            'continuous_integration': True,
            'documentation': 0,
            'history': 9.00,
            'license': True,
            'management': 9.00,
            'state': 'active',
            'unit_test': 9.00,
        }
        expected = 80.00

        # Act
        actual = attributes.score(rresults)

        # Assert
        self.assertEqual(expected, actual)

        # Arrange
        rresults = {
            'architecture': 9.00,
            'community': 9.00,
            'continuous_integration': True,
            'documentation': 9.00,
            'history': 9.00,
            'license': False,
            'management': 9.00,
            'state': 'active',
            'unit_test': 9.00,
        }
        expected = 0

        # Act
        actual = attributes.score(rresults)

        # Assert
        self.assertEqual(expected, actual)

    def test_requires_source(self):
        # Arrange
        keystring = 'mchs'

        # Act
        attributes = Attributes(
            self.rawattributes, database=None, keystring=keystring,
            goptions=self.rawgoptions
        )

        # Assert
        self.assertFalse(attributes.requires_source)

        # Arrange
        keystring = 'dualmichs'

        # Act
        attributes = Attributes(
            self.rawattributes, database=None, keystring=keystring
        )

        # Assert
        self.assertTrue(attributes.requires_source)


from utils import get_logger
from crawler.frontier import Frontier
from crawler.worker import Worker

class Crawler(object):
    def __init__(self, config, resume, frontier_factory=Frontier, worker_factory=Worker):
        self.config = config
        self.logger = get_logger("CRAWLER")
        self.frontier = frontier_factory(config, resume)
        self.workers = list()
        self.worker_factory = worker_factory
        self.logger.info(f"Crawler initialized with {self.config.THREAD_COUNT} worker threads.")

    def start_async(self):
        self.logger.info("Starting asynchronous crawling...")
        self.workers = [
            self.worker_factory(worker_id, self.config, self.frontier)
            for worker_id in range(self.config.THREAD_COUNT)]
        for worker in self.workers:
            worker.start()
        self.logger.info(f"Started {self.config.THREAD_COUNT} workers. Asynchronous crawling is now in progress...")

    def start(self):
        try:
            self.logger.info("Starting crawl.")
            self.start_async()
            self.join()
        except KeyboardInterrupt:
            self.logger.info("Received keyboard interrupt. Stopping workers...")
            for worker in self.workers:
                worker.stop()
            self.logger.info("Workers have been stopped.")
        finally:
            self.join()

    def join(self):
        self.logger.info("Joining worker threads...")
        for worker in self.workers:
            worker.join()
        self.logger.info("Worker threads have finished their jobs. Crawl is complete.")


#!/usr/bin/python

# layout.py

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

from dialog1 import Dialog1
from dialog2 import Dialog2
from fei2 import MyForm

HOST = 'Tonys-MacBook-Air.local'
PORT = 0x1233
MSGSIZE = 18192

class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, wx.Size(1170, 700))
        self.Centre()
        panel = wx.Panel(self, -1)

        png1 = wx.Image("table1.png", wx.BITMAP_TYPE_ANY)
        png1 = png1.Rescale(540,320).ConvertToBitmap()
        png2 = wx.Image("table2.png", wx.BITMAP_TYPE_ANY)
        png2 = png2.Rescale(540,320).ConvertToBitmap()
        png3 = wx.Image("pnl1.png", wx.BITMAP_TYPE_ANY)
        png3 = png3.Rescale(540,320).ConvertToBitmap()
        png4 = wx.Image("pnl2.png", wx.BITMAP_TYPE_ANY)
        png4 = png4.Rescale(540,320).ConvertToBitmap()
        # ConvertToBitmap()
        wx.BitmapButton(panel, id=1, bitmap=png1, pos=(30, 5), size=(png1.GetWidth()+5, png1.GetHeight()+5))
        wx.BitmapButton(panel, id=2, bitmap=png2, pos=(600, 5), size=(png2.GetWidth()+5, png2.GetHeight()+5))
        wx.BitmapButton(panel, id=3, bitmap=png3, pos=(30, 345), size=(png3.GetWidth()+5, png3.GetHeight()+5))
        wx.BitmapButton(panel, id=4, bitmap=png4, pos=(600, 345), size=(png4.GetWidth()+5, png4.GetHeight()+5))

        self.Bind(wx.EVT_BUTTON, self.OnShowCustomDialog1, id=1)
        self.Bind(wx.EVT_BUTTON, self.OnShowCustomDialog4, id=2)
        self.Bind(wx.EVT_BUTTON, self.OnShowCustomDialog2, id=3)
        self.Bind(wx.EVT_BUTTON, self.OnShowCustomDialog3, id=4)

        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.s.connect((HOST, PORT))

    def OnShowCustomDialog1(self, event):

        Dialog1.mesg = self.s

        self.s.send('rateb 0')
        quality = self.s.recv(MSGSIZE)
        Dialog1.content = quality
        self.s.send('wtime 0')
        Dialog1.time1=self.s.recv(MSGSIZE)

        self.s.send('nameb 0')
        ticker = self.s.recv(MSGSIZE)
        Dialog1.ticker = ticker
        self.s.send('wtime 0')
        Dialog1.time2=self.s.recv(MSGSIZE)

        self.s.send('varis 99###')
        var = self.s.recv(MSGSIZE)
        Dialog1.var = var
        self.s.send('wtime 0')
        Dialog1.time3=self.s.recv(MSGSIZE)
        # self.s.send('varinfo 99')
        # var = self.s.recv(MSGSIZE)
        # print var
        dia = Dialog1(self, -1, 'buttons')
        # dia.ShowModal()
        # dia.Destroy()

    def OnShowCustomDialog4(self, event):
        # self.s.send('ratebucket 0')
        # quality = self.s.recv(MSGSIZE)

        self.s.send('riskd 0')
        tickers = self.s.recv(MSGSIZE)
        MyForm.content = tickers

        # self.s.send('shift 0')
        # ticker = self.s.recv(MSGSIZE)
        # MyForm.shift = ticker

        # self.s.send('dropp 0')
        # ticker1 = self.s.recv(MSGSIZE)
        # MyForm.dropp = ticker1

        # self.s.send('reset 0')
        # quality = self.s.recv(MSGSIZE)
        # MyForm.reset = quality

        MyForm.mesg = self.s
        # self.s.send('varinfo 99')
        # var = self.s.recv(MSGSIZE)
        # print var
        dia = MyForm(self, -1, 'buttons')
        # dia.ShowModal()
        # dia.Destroy()

    def OnShowCustomDialog2(self, event):
        self.s.send('pnlpc 0')
        data = self.s.recv(MSGSIZE)

        self.s.send('wtime 0')
        time_start = self.s.recv(MSGSIZE)

        strr = data.split()
        strLength = len(strr)

        fig = plt.figure(figsize=(30, 6), dpi=110)
        fig.suptitle('PnL Histrogram       Time:   ' + time_start)
        ax = fig.add_subplot(111, projection='3d')
        xpos = np.ones(strLength)
        ypos = np.ones(strLength)
        zpos = np.ones(strLength)
        dx = np.zeros(strLength)
        dy = np.ones(strLength)
        dz = np.ones(strLength)
        cs = ['r'] * strLength;

        xposs = range(strLength)
        maxNum = 0
        minNum = 0
        for i in range(strLength):
            xpos[i] = xposs[i] + 1
            dz[i] = string.atof(strr[i])
            dx[i] = 0.5
            ypos[i] = strLength / 2
            if dz[i] > 0:
                cs[i] = 'g'
            if dz[i] > maxNum:
                maxNum = dz[i];
            if dz[i] < minNum:
                minNum = dz[i];

        ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color=cs, edgecolor="none")
        ax.autoscale_view(True,True,True)
        # ax.set_xlim([40,60])
        ax.set_ylim([0,strLength])
        ax.set_zlim([minNum,maxNum])
        ax.set_zlabel('PnL')
        ax.set_yticks(())
        plt.show()

    def OnShowCustomDialog3(self, event):
        self.s.send('distr 0')
        data = self.s.recv(MSGSIZE)

        self.s.send('wtime 0')
        time_start = self.s.recv(MSGSIZE)

        strr = data.split()
        strLength = len(strr)

        fig = plt.figure(figsize=(30, 6), dpi=110)
        fig.suptitle('PnL Distribution        Time:   ' + time_start)
        ax = fig.add_subplot(111, projection='3d')
        xpos = np.ones(strLength)
        ypos = np.ones(strLength)
        zpos = np.ones(strLength)
        dx = np.zeros(strLength)
        dy = np.ones(strLength)
        dz = np.ones(strLength)
        cs = ['b'] * strLength;

        xposs = range(strLength)

        max = 0
        for i in range(strLength):
            if i == 0 or i == strLength-1:
                continue
            xpos[i] = xposs[i] + 1
            dz[i] = string.atof(strr[i])
            dx[i] = 0.5
            ypos[i] = strLength / 2
            if dz[i] > max:
                max = dz[i]

        ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color=cs)
        ax.autoscale_view(True,True,True)
        ax.set_ylim([0,strLength])
        ax.set_zlim([0,max * 1.3])
        ax.set_zlabel('PnL')
        ax.set_yticks(())
        plt.show()

class MyApp(wx.App):
    def OnInit(self):
        frame = MyFrame(None, -1, 'Financial Project FInal GUI.py')
        frame.Show(True)
        frame.Centre()
        return True

app = MyApp(0)
app.MainLoop()


#!/usr/bin/python3
# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*-

import os
import configparser
from core.util import FvpUtil
from core.peripheral import FvpPeripheral

class FvpVmEnvironment:

    class NetworkInfo:
        virtioNetworkType = None                    # str        "bridge", "nat", "route" => ""

    class PeripheralInfo:
        obj = None                                  # reference to FvpPeripheral object
        persistent = None                           # bool
        connectWhenStart = None                     # bool
        uiShortcut = None                           # bool

    def __init__(self):
        self.networkInfo = FvpVmEnvironment.NetworkInfo()
        self.peripheralInfoList = []

    def checkValid(self):
        """if FvpVmEnvironment object is invalid, raise exception"""

        validVirtioNetworkType = ["bridge", "nat", "route", ""]

        if self.networkInfo.virtioNetworkType is None or self.networkInfo.virtioNetworkType not in validVirtioNetworkType:
            raise Exception("virtioNetworkType is invalid")

        for p in self.peripheralInfoList:
            try:
                p.obj.checkValid()
            except Exception as e:
                raise Exception("peripheral \"%s\" is invalid, %s" % (p.obj.pName, e.strerror))

    def getVirtioNetworkType(self):
        return self.networkInfo.virtioNetworkType

    def addPeripheral(self, peripheralObj, persistent, connectWhenStart, uiShortcut):
        # forbid name duplication
        for pInfo in self.peripheralInfoList:
            assert pInfo.obj.pName != peripheralObj.pName

        # add data
        pInfo = self.PeripheralInfo()
        pInfo.obj = peripheralObj
        pInfo.persistent = persistent
        pInfo.connectWhenStart = connectWhenStart
        pInfo.uiShortcut = uiShortcut
        self.peripheralInfoList.append(pInfo)

    def getPeripheralList(self):
        return self.peripheralInfoList

#    def remove(self, peripheralName):
#        pass
#
#
#    def getObj(self, peripheralName):
#        return self.objDict[peripheralName]
#
#    def setPersistent(self, peripheralName, flag):
#        self.infoDict[peripheralName].persistent = flag
#
#    def isPersistent(self, peripheralName):
#        return self.infoDict[peripheralName].persistent
#
#    def setConnectWhenStart(self, peripheralName, flag):
#        self.infoDict[peripheralName].connectWhenStart = flag
#
#    def isConnectWhenStart(self, peripheralName):
#        return self.infoDict[peripheralName].connectWhenStart

    def load(self, vmDir):
        fileName = os.path.join(vmDir, "fqemu.env")

        # clear self
        self.networkInfo.virtioNetworkType = ""
        self.peripheralInfoList = []

        # check file
        if not os.path.exists(fileName):
            return

        # read from cfg file
        cfg = configparser.RawConfigParser()
        cfg.read(os.path.join(vmDir, "fqemu.env"))

        self.networkInfo.virtioNetworkType = cfg.get("networkInfo", "virtioNetworkType")

        for secName in cfg.sections():
            if secName.startswith("peripheral"):
                p = FvpVmEnvironment.PeripheralInfo()

                p.obj = FvpPeripheral()
                p.obj.pType = cfg.get(secName, "pType")
                p.obj.pName = cfg.get(secName, "pName")
                for (name, value) in cfg.items(secName):
                    if name.startswith("param_"):
                        p.obj.paramDict[name[6:]] = value

                p.connectWhenStart = bool(cfg.get(secName, "connectWhenStart"))
                p.uiShortcut = False                                                    # fixme
                p.persistent = True

                self.peripheralInfoList.append(p)

        # type conversion
        for p in self.peripheralInfoList:
            if p.obj.pType == "file":
                if "readonly" in p.obj.paramDict:
                    p.obj.paramDict["readonly"] = FvpUtil.str2bool(p.obj.paramDict["readonly"])
            elif p.obj.pType == "folder":
                if "readonly" in p.obj.paramDict:
                    p.obj.paramDict["readonly"] = FvpUtil.str2bool(p.obj.paramDict["readonly"])

    def save(self, vmDir):
        fileName = os.path.join(vmDir, "fqemu.env")

        # save config file
        cfg = configparser.RawConfigParser()

        # save network parameter
        cfg.add_section("networkInfo")
        cfg.set("networkInfo", "virtioNetworkType", self.networkInfo.virtioNetworkType)

        # save peripheral list
        i = 0
        for p in self.peripheralInfoList:
            if not p.persistent:
                continue
            secName = "peripheral%d" % (i)
            cfg.add_section(secName)
            cfg.set(secName, "pType", p.obj.pType)
            cfg.set(secName, "pName", p.obj.pName)
            for k, v in p.paramDict:
                cfg.set(secName, "param_%s" % (k), str(v))
            cfg.set(secName, "connectWhenStart", str(p.connectWhenStart))
            i = i + 1

        cfg.write(open(fileName, "w"))


import tensorflow as tf
import tensorflow.keras as keras
from replay_memory.ReplayBuffer import ReplayBuffer
from utils.networks import ActorNetwork, CriticNetwork

## Actor-critic networks parameters :

# actor learning rate
alpha = 0.001

# critic learning rate
beta = 0.002

## DDPG algorithms paramters

# discount factor
gamma = 0.99

# target netwroks soft update factor
tau = 0.005

# replay buffer max memory size
max_size = 10**6

# exploration noise factor
noise_factor = 0.1

# training batch size
batch_size = 64

## DDPG agent class
class DDPGAgent:
    def __init__(self, env, input_dims):
        self.gamma = gamma
        self.tau = tau
        self.batch_size = batch_size
        self.noise_factor = noise_factor

        self.env = env
        self.n_actions = env.action_space.shape[0]
        self.max_action = env.action_space.high[0]
        self.min_action = env.action_space.low[0]

        self.memory = ReplayBuffer(max_size, input_dims, self.n_actions)

        self._initialize_networks(self.n_actions)
        self.update_parameters(tau=1)

    # Choose action based on actor network
    # Add exploration noise if in traning mode
    def choose_action(self, state, evaluate=False):
        state = tf.convert_to_tensor([state], dtype=tf.float32)
        actions = self.actor(state)
        if not evaluate:
            actions += tf.random.normal(shape=[self.n_actions], mean=0, stddev=self.noise_factor)
        actions = tf.clip_by_value(actions, self.min_action, self.max_action)
        return actions[0]

    def remember(self, state, action, reward, new_state, done):
        self.memory.store_transition(state, action, reward, new_state, done)

    # Main DDPG algorithms learning process
    def learn(self):
          if self.memory.counter < self.batch_size:
              return

          # Sample batch size of experiences from replay buffer
          states, actions, rewards, new_states, dones = self.memory.sample(self.batch_size)
          states = tf.convert_to_tensor(states, dtype=tf.float32)
          actions = tf.convert_to_tensor(actions, dtype=tf.float32)
          rewards = tf.convert_to_tensor(rewards, dtype=tf.float32)
          new_states = tf.convert_to_tensor(new_states, dtype=tf.float32)

          # Calculate critic network loss
          with tf.GradientTape() as tape:
              target_actions = self.target_actor(new_states)
              new_critic_value = tf.squeeze(self.target_critic(new_states, target_actions), 1)
              critic_value = tf.squeeze(self.critic(states, actions), 1)
              target = rewards + self.gamma * new_critic_value * (1 - dones)
              critic_loss = tf.keras.losses.MSE(target, critic_value)

          # Apply gradient decente with the calculated critic loss
          critic_network_gradient = tape.gradient(critic_loss, self.critic.trainable_variables)
          self.critic.optimizer.apply_gradients(zip(
              critic_network_gradient, self.critic.trainable_variables
          ))

          # Calculate actor network loss
          with tf.GradientTape() as tape:
              new_actions = self.actor(states)
              actor_loss = - self.critic(states, new_actions)
              actor_loss = tf.math.reduce_mean(actor_loss)

          # Apply gradient decente with the calculated actor loss
          actor_network_gradient = tape.gradient(actor_loss, self.actor.trainable_variables)
          self.actor.optimizer.apply_gradients(zip(
                  actor_network_gradient, self.actor.trainable_variables
              ))

          # Update actor/critic target networks
          self.update_parameters()

    # Update actor/critic target networks parameters with soft update rule
    def update_parameters(self, tau=None):
        if tau is None:
            tau = self.tau

        weights = []
        targets = self.target_actor.weights
        for i, weight in enumerate(self.actor.weights):
            weights.append(tau * weight + (1 - tau) * targets[i])
        self.target_actor.set_weights(weights)

        weights = []
        targets = self.target_critic.weights
        for i, weight in enumerate(self.critic.weights):
            weights.append(tau * weight + (1 - tau) * targets[i])
        self.target_critic.set_weights(weights)

    def save_models(self):
        print("---- saving models ----")
        self.actor.save_weights(self.actor.checkpoints_file)
        self.critic.save_weights(self.critic.checkpoints_file)
        self.target_actor.save_weights(self.target_actor.checkpoints_file)
        self.target_critic.save_weights(self.target_critic.checkpoints_file)

    def load_models(self):
        print("---- loading models ----")
        self.actor.load_weights(self.actor.checkpoints_file)
        self.critic.load_weights(self.critic.checkpoints_file)
        self.target_actor.load_weights(self.target_actor.checkpoints_file)
        self.target_critic.load_weights(self.target_critic.checkpoints_file)

    def _initialize_networks(self, n_actions):
        model = "ddpg"
        self.actor = ActorNetwork(n_actions, name="actor", model=model)
        self.critic = CriticNetwork(name="critic", model=model)
        self.target_actor = ActorNetwork(n_actions, name="target_actor", model=model)
        self.target_critic = CriticNetwork(name="target_critic", model=model)

        self.actor.compile(keras.optimizers.Adam(learning_rate=alpha))
        self.critic.compile(keras.optimizers.Adam(learning_rate=beta))
        self.target_actor.compile(keras.optimizers.Adam(learning_rate=alpha))
        self.target_critic.compile(keras.optimizers.Adam(learning_rate=beta))


from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import Search
from .forms import SearchForm
import folium
import geocoder

# Create your views here.

def index(request):
    if request.method == "POST":
        form = SearchForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('/')

    else:
        form = SearchForm()
    address = Search.objects.all().last()
    # address = request.POST.get('address')
    location = geocoder.osm(address)
    print(location.osm)

    lat = location.lat
    lng = location.lng
    country = location.country
    print(f" Longitude: {lng} - Latitude: {lat} <--> {country}")

    if (lat == None) or (lng == None):
        address.delete()
        return HttpResponse('Address is not valid!')

    # Create map object
    mapObj = folium.Map(location=[44.0, 50.0], zoom_start=2)

    folium.Marker([lat, lng], tooltip="Click for more", popup=country).add_to(mapObj)

    # Get HTML Representation of Map Object
    mapObj = mapObj._repr_html_()
    context = {
        'mapObj': mapObj,
        'form': form,
    }
    return render(request, 'index.html', context)


'''
This file is part of "El Botadero"
copy
right 2018 Rodrigo Garcia <strysg@riseup.net>
AGPL liberated.
'''
from flask_sqlalchemy import SQLAlchemy
from flask import g, current_app
from flask_sqlalchemy import BaseQuery

def setup_db(app, db=None, destroy=True, db_path='sqlite:///db.sqlite3', testing=False):
    ''' Re-Initializes database module.
    :param app: Flask instance app.
    :param destroy: If True forces drop all tables then create again
    '''
    if testing:
        if not db_path.startswith('sqlite:///'):
            db_path = 'sqlite:///' + db_path

    app.config['SQLALCHEMY_DATABASE_URI'] = db_path
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    #from .models import db
    db = SQLAlchemy(app)
    db.init_app(app)

    if destroy:
        db.drop_all()
    g.db = db
    # importando modelos definidos en modulos externos
    print ('Importando modelos ... ')
    from .models import Archivo, HtmlPage

    db.create_all()
    db.session.commit()
    # Archivo.create(name='prueba1.py', extension='py')
    # Archivo.create(name='prueba2.py', extension='py')
    # print('Archivo.query.all():', str(Archivo.query.all()))
    print ('Base de datos creada!', str(app.config['SQLALCHEMY_DATABASE_URI']), '>>>', str(db))

    return g.db

def get_db():
    """Connect to the application's configured database. The connection
    is unique for each request and will be reused if this is called
    again.
    """
    return g.db

def close_db(e=None):
    """If this request connected to the database, close the
    connection.
    """
    db = g.pop('db', None)

    if db is not None:
        db.close()

class CRUDMixin(object):

    def __repr__(self):
        return "<{}>".format(self.__class__.__name__)

    @classmethod
    def create(cls, **kwargs):
        instance = cls(**kwargs)
        return instance.save()

    def save(self):
        """Saves the object to the database."""
        db.session.add(self)
        db.session.commit()
        return self

    def delete(self):
        """Delete the object from the database."""
        db.session.delete(self)
        return db.session.commit()


import setuptools

with open("README.md") as fp:
    long_description = fp.read()

setuptools.setup(
    name="serverless_app_pipeline_cdk",
    version="0.0.1",
    description="An empty CDK Python app",
    long_description=long_description,
    long_description_content_type="text/markdown",
    author="author",
    package_dir={"": "serverless_app_pipeline_cdk"},
    packages=setuptools.find_packages(where="serverless_app_pipeline_cdk"),
    install_requires=[
        "aws-cdk.core",
        "aws_cdk.aws_codedeploy",
        "aws_cdk.aws_codebuild",
        "aws_cdk.aws_codepipeline",
        "aws_cdk.aws_codecommit",
        "aws_cdk.aws_codepipeline_actions",
        "aws_cdk.aws_secretsmanager",
        "aws_cdk.aws_kms",
        "aws_cdk.aws_s3",
        "aws_cdk.aws_iam",
        "aws_cdk.aws_wafv2",
        "aws_cdk.aws_cloudfront",
        "aws_cdk.aws_certificatemanager",
    ],
    python_requires=">=3.6",
    classifiers=[
        "Development Status :: 4 - Beta",
        "Intended Audience :: Developers",
        "License :: OSI Approved :: Apache Software License",
        "Programming Language :: JavaScript",
        "Programming Language :: Python :: 3 :: Only",
        "Programming Language :: Python :: 3.6",
        "Programming Language :: Python :: 3.7",
        "Programming Language :: Python :: 3.8",
        "Topic :: Software Development :: Code Generators",
        "Topic :: Utilities",
        "Typing :: Typed",
    ],
)


import random

import discord
from discord.ext import commands

import cogs.mods.itunes as itunes
import cogs.mods.base as base

class ArtistSearch:

    def __init__(self, bot):
        self.bot = bot

    @commands.command(name='search_artist', aliases=['creator', 'artist', 'person', 'musician', 'people', 'search_person', 'search_musician', 'search_creator', 'searchartist', 'artist_search'])
    @commands.cooldown(10, 4, commands.BucketType.guild)
    @commands.cooldown(1, 3, commands.BucketType.user)
    async def search_artist(self, ctx, *, artist_name=None):

        # Sometimes doesnt work??? IDK

        if not artist_name:
            cmdprefix = (await self.bot.command_prefix(self.bot, ctx.message))[-1]
            embed = discord.Embed(
                color=random.randint(0x000000, 0xffffff),
                title=f'Help for `{cmdprefix}{ctx.invoked_with}`',
                description=f'`{cmdprefix}{ctx.invoked_with} <artist name>`'
            )
            embed.set_image(
                url='https://i.gyazo.com/7d33394b56834ca32dc4c5db068806fe.png'
            )
            embed.set_footer(
                text="Trackrr Music Search",
                icon_url="https://media.discordapp.net/attachments/452763485743349761/452763575878942720/TrackrrLogo.png"
            )
            return await ctx.send(embed=embed)

        async with ctx.channel.typing():
            try:
                embed = await itunes.search_artist(artist_name)
            except base.NotFound:
                embed = discord.Embed(
                    title=f'Trackrr',
                    description=f'No results found for `{artist_name}`!'
                )
            embed.set_footer(
                text="Trackrr Music Search | Data pulled from Apple Music",
                icon_url="https://media.discordapp.net/attachments/452763485743349761/452763575878942720/TrackrrLogo.png"
            )
            await ctx.send(embed=embed)

def setup(bot):
    bot.add_cog(ArtistSearch(bot))


from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
import random
from dataloader import DataLoader
import logging
from datetime import datetime
from mysql import MySQL

FORMAT = '%(asctime)s |%(levelname)s| %(message)s'
logging.basicConfig(level=logging.DEBUG, format=FORMAT, filename='./log/' + datetime.now().strftime('AFTS_%Y%m%d.log'))
retryCount = 0

def autoFill(id, cursor):
    options = Options()
    options.add_argument("--no-sandbox")
    options.add_argument("--headless")
    try:
        chrome = webdriver.Chrome(options=options)
        chrome.get("https://zh.surveymonkey.com/r/EmployeeHealthCheck")
        agreexpath = "//div[contains(@class,'radio-button-container')]//label//span[contains(@class,'radio-button-display')]"
        agreeCheck = WebDriverWait(chrome, 15).until(
            EC.visibility_of_element_located((By.XPATH, agreexpath)))
        # agreeCheck
        agreeCheck.click()

        # employId
        employeeId = chrome.find_elements_by_xpath(
            "//div[contains(@class,'question-body open-ended-single')]//input")[0]
        employeeId.send_keys(id)

        # foreheadTemp check
        foreheadCheckBtn = chrome.find_elements_by_xpath(
            "//div[contains(@class,'radio-button-container')]//label//span[contains(@class,'radio-button-display')]")[2]
        foreheadCheckBtn.click()

        # foreheadTemp
        Temperature = chrome.find_elements_by_xpath(
            "//div[contains(@class,'question-body open-ended-single')]//input")[1]
        foreheadDegree = str(round(random.uniform(35.1, 36.9), 1))
        Temperature.send_keys(foreheadDegree)

        # contacted people who returned from aboard in the last 14 days
        noContactBtn = chrome.find_elements_by_xpath(
            "//div[contains(@class,'radio-button-container')]//label//span[contains(@class,'radio-button-display')]")[5]
        noContactBtn.click()

        # declaration radio button
        declarationBtn = chrome.find_elements_by_xpath(
            "//div[contains(@class,'radio-button-container')]//label//span[contains(@class,'radio-button-display')]")[6]
        declarationBtn.click()

        # submit btn to next page
        submitBtn = chrome.find_elements_by_xpath(
            "//button[contains(text(), '下一頁')]")[0]
        submitBtn.click()

        # successful landing page
        compleredTxtPath = "(//span[@class='title-text'])"
        compleredTxt = WebDriverWait(chrome, 10, 1).until(
            EC.visibility_of_element_located((By.XPATH, compleredTxtPath))).text
        logging.info('Success: User ' + id + ' be filled. filled degree : ' + foreheadDegree)
        # print(id + " filled degree :" + foreheadDegree)
        sql = "UPDATE afts.OPERATION_HIST SET STATUS = 'DONE' WHERE (CONTEXT_ID = '{0}-{1}');".format(id, datetime.today().strftime("%y%m%d"))
        cursor.execute(sql)
        chrome.quit()
    except TimeoutException:
        chrome.quit()
        global retryCount
        retryCount += 1
        if(retryCount == 2):
            logging.error('Timeout:user ' + id + ' cannot be filled. Process end.')
            retryCount = 0
            pass
        else:
            logging.warning('Timeout:user ' + id + ' cannot be filled. Retrying...')
            autoFill(id, cursor)

# def readFile():
#     fileHandler = open("Id.txt", "r");
#     IdList = fileHandler.read().splitlines();
#     fileHandler.close();
#     return IdList;

if __name__ == "__main__":
    dt = DataLoader()
    users = dt.get_users()
    dt.update_load_status(users)
    print(users)
    db = MySQL()
    con = db.connect()
    with con:
        with con.cursor() as cursor:
            for user in users:
                autoFill(user, cursor)
        con.commit()


"""
-*- coding: utf-8 -*-

File: OCTantApp.py

Class OCTantApp

.. inheritance-diagram:: OCTantApp

Application entrance point.

:Log:

+-------------+--------+------------------------------------------------------+
| Date        | Author | Description                                          |
+=============+========+======================================================+
| Feb-2018    | AACA   | - File created as run.py                             |
+-------------+--------+------------------------------------------------------+
| 4-Aug-2018  | FOE    | - Isolated minimal solution.                         |
+-------------+--------+------------------------------------------------------+
| 21-Aug-2018 | FOE    | - Updated main window class from OCTToolsMainWindow  |
|             |        |   to IOT_GUI_MainWindow (later rebranded as          |
|             |        |   IOT_GUI_ToolsWindow                                |
+-------------+--------+------------------------------------------------------+
| 22-Aug-2018 | FOE    | - Run is now a class. File rebranded to OCTToolsApp  |
|             |        |   from run.py                                        |
|             |        | - The application main window is no longer the tools |
|             |        |   menu window (IOT_GUI_ToolsWindow), but the document|
|             |        |   window (IOT_GUI_DocumentWindow).                   |
+-------------+--------+------------------------------------------------------+
| 9-Sep-2018  | FOE    | - "Separated" the entry points as a script, from the |
|             |        |   entry point as an installed program.               |
|             |        | - Added "src" to the path for "installed" execution. |
+-------------+--------+------------------------------------------------------+
| 23-Sep-2018 | FOE    | - Updated comments and added Sphinx                  |
|             |        |   documentation to the class                         |
+-------------+--------+------------------------------------------------------+
| 14-Nov-2018 | FOE    | - Connected the tools window to the document window. |
+-------------+--------+------------------------------------------------------+
| 13-Feb-2019 | FOE    | - Updated support for version control. See version.py|
+-------------+--------+------------------------------------------------------+
| 28-Feb-2019 | FOE    | - Rebranded as OCTantApp.py                          |
|             |        | - Adapted to new package OCTant structure.           |
|             |        | - Importing statements for classes within the        |
|             |        |   OCTant package have been updated.                  |
+-------------+--------+------------------------------------------------------+
|  3-Mar-2019 | FOE    | - Tools window is now a child dock of DocumentWindow |
|             |        |   which is left as the only QMainWindow of the app.  |
+-------------+--------+------------------------------------------------------+
| 17-Mar-2019 | FOE    | - Added properties appsettings and appsettingsfile.  |
|             |        | - docWindow attribute converted to docwindow         |
|             |        |   property.                                          |
|             |        | - Cleaner exit with call to deleteLater              |
|             |        | - Removed method show. Now the document window show  |
|             |        |   is called accesing the docwindow property.         |
|             |        | - Class OCTantApp now becomes a QApplication         |
|             |        |   (previously we had 2 separated objects; one for the|
|             |        |   QApplication and another just for "holding" the    |
|             |        |   the main window.)                                  |
+-------------+--------+------------------------------------------------------+
| 31-Mar-2019 | FOE    | - Fixed comments of property docwindow which were    |
|             |        |   referring to Settings.                             |
+-------------+--------+------------------------------------------------------+

.. seealso:: None
.. note:: None
.. todo:: None

.. sectionauthor:: Felipe Orihuela-Espina <f.orihuela-espina@inaoep.mx>
.. codeauthor:: Arlem Aleida Castillo Avila <acastillo@inaoep.mx>
.. codeauthor:: Felipe Orihuela-Espina <f.orihuela-espina@inaoep.mx>

"""

## Import
import sys
#Add paths
if not sys.path[0] == '..':
    sys.path.insert(0, '..')
#sys.path.append('..')
                    #This line is not needed while
                    #working in the interpreter, as the main file is in the
                    #same directory. However, it is needed by pynsist when
                    #it creates the installer, so that it "sees" the src
                    #folder.

from PyQt5.QtWidgets import QApplication
#, QMainWindow, QWidget, QHBoxLayout, QTabWidget, QPushButton, QGraphicsView, QLabel, QAction, QFileDialog
#from PyQt5.QtGui import QIcon, QPixmap
#from PyQt5 import uic

from version import __version__
from DocumentWindow import DocumentWindow
#from ToolsDock import ToolsDock

import octant as oc

## Class definition
class OCTantApp(QApplication):
    #Sphinx documentation
    """Application entrance point.

    Application entrance point.

    .. seealso:: None
    .. note:: None
    .. todo:: None

    """

        #Private class attributes shared by all instances

    #Class constructor
    #def __init__(self, **kwargs):
    def __init__(self, kwargs): #DO NOT use the classical ** before kwargs in this case!
        print("OCTant App v" + __version__ + ": Initiating...")
        #Call superclass constructor
        super().__init__(kwargs) #For Python 3

        #Initialize private attributes unique to this instance
        self.document = None #The current document. Initialize a document
        self.docwindow = DocumentWindow(theparentapp = self)
        #self.docwindow.parentapp = self #Connect the window with the application

        self.appsettingsfile = '..\\..\\resources\\OCTantApp.config'
        self.appsettings = oc.data.Settings()

        print("Reading application settings from " +  self.appsettingsfile + ".")
        self.appsettings.read(self.appsettingsfile)
        #print(tmp.appsettings)

        #Finally, show the main window
        self.docwindow.show()

        return

#    def show(self):
#        #self.toolsWindow.show()
#        self.docwindow.show()

    #Properties getters/setters
    #
    # Remember: Sphinx ignores docstrings on property setters so all
    #documentation for a property must be on the @property method
    @property
    def document(self): #document getter
        """
        The application opened document.

        :getter: Gets the application opened document
        :setter: Sets the application opened document
        :type: class:`octant.data.Document`
        """
        return self.__document

    @document.setter
    def document(self,newDoc): #document setter
        if newDoc is None:
            newDoc = oc.data.Document() #Initialize a document
        if (type(newDoc) is oc.data.Document):
            self.__document = newDoc
        else:
            warnMsg = self.getClassName() + ':document: Unexpected document type.'
            warnings.warn(warnMsg,SyntaxWarning)
        return None

    @property
    def docwindow(self): #appsettings getter
        """
        Access the application main window

        :getter: Gets the application main window
        :setter: Sets the application main window
        :type: class:`octant.app.DocumentWindow`
        """
        return self.__docwindow

    @docwindow.setter
    def docwindow(self,newDocWindow): #document setter
        if newDocWindow is None:
            newDocWindow = DocumentWindow() #Initialize settings
        if (type(newDocWindow) is DocumentWindow):
            self.__docwindow = newDocWindow
        else:
            warnMsg = self.getClassName() + ':docwindow: Unexpected docwindow type.'
            warnings.warn(warnMsg,SyntaxWarning)
        return None

    @property
    def appsettings(self): #appsettings getter
        """
        The application settings.

        :getter: Gets the application settings
        :setter: Sets the application settings
        :type: class:`octant.data.Settings`
        """
        return self.__appsettings

    @appsettings.setter
    def appsettings(self,newSettings): #document setter
        if newSettings is None:
            newSettings = oc.data.Settings() #Initialize settings
        if (type(newSettings) is oc.data.Settings):
            self.__appsettings = newSettings
        else:
            warnMsg = self.getClassName() + ':appsettings: Unexpected settings type.'
            warnings.warn(warnMsg,SyntaxWarning)
        return None

    @property
    def appsettingsfile(self): #appsettings getter
        """
        The settings file name.

        :getter: Gets the current settings file name.
        :setter: Sets the current settings file name.
        :type: str
        """
        return self.__appsettingsfile

    @appsettingsfile.setter
    def appsettingsfile(self,newFilename): #document setter
        if newFilename is None:
            newFilename = '..\\..\\resources\\OCTantApp.config' #Initialize
        if (type(newFilename) is str):
            self.__appsettingsfile = newFilename
        else:
            warnMsg = self.getClassName() + ':appsettingsfile: Unexpected settings filename type.'
            warnings.warn(warnMsg,SyntaxWarning)
        return None

#This is the application entrance point. Note that it is NOT a method of the OCTantApp class
def main():

    from OCTantApp import OCTantApp #Make the import explicit so that class type is OCTantApp instead of __main__.OCTantApp

    #Instancia para iniciar una aplicación
    myApp = OCTantApp(sys.argv) #The application object. OCTantApp is a QApplication
    #myApp = OCTantApp() #OCTantApp is a QApplication
    myApp.aboutToQuit.connect(myApp.deleteLater) #Ensures the application is
                                    #deleted after closing, and in practice
                                    #removes a closing exception.
    #Starts the event loop and exit upon quitting
    #QApplication quits when the last primary window (window with no parent) is closed
    myApp.exec_()
    sys.exit(0)

# The following two lines, allow me to run the program from the interpreter
#"as a script", while the above method main() allow me to have an entrance
#point so that it is possible to call the method from an installed version
#of the application
if __name__ == "__main__":
    main()


import torch
import torch.nn as nn
import torch.nn.functional as F

class transformer(nn.Module):

    def __init__(self, in_chans=256, k=4, dc=28):
        super(transformer, self).__init__()
        r = 2*k+1
        self.conv1 = nn.Conv2d(in_chans*2, 256, 3, 1, 1, bias=True)
        self.conv2 = nn.Conv2d(256, 192, 3, 1, 1, bias=True)
        self.conv3 = nn.Conv2d(192, 128, 3, 1, 1, bias=True)
        self.conv4 = nn.Conv2d(128, 96, 3, 1, 1, bias=True)
        self.conv5 = nn.Conv2d(96, 64, 3, 1, 1, bias=True)
        self.conv6 = nn.Conv2d(64, dc, 3, 1, 1, bias=True)
        self.pool = nn.AdaptiveAvgPool2d(r)

        self.relu = nn.ReLU(inplace=True)

    def forward(self, x):
        b = x.shape[0]
        x = self.relu(self.conv1(x))
        x = self.relu(self.conv2(x))
        x = self.relu(self.conv3(x))
        x = self.relu(self.conv4(x))
        x = self.relu(self.conv5(x))
        x = self.conv6(x)
        x = self.pool(x)

        return x.view(b, 1, 1, 2, -1)

def upflow8(flow, mode='bilinear'):
    new_size = (8 * flow.shape[2], 8 * flow.shape[3])
    return  8 * F.interpolate(flow, size=new_size, mode=mode, align_corners=True)

if __name__ == '__main__':
    pass


import argparse
import json
import logging
import os
import sys
from ..server import DynnameAPI
from ..config import load_config
from ..net import get_ips

def _get_cert_path(cert_dir, fqdn):
    if fqdn.endswith('.'):
        fqdn = fqdn[:-1]
    path = os.path.join(cert_dir, fqdn)
    if not os.path.exists(path):
        return None
    return path

logger = logging.getLogger(__name__)

parser = argparse.ArgumentParser(description='Command line tool for dynna.me')
parser.add_argument('-g', '--get', action='store_true',
                    help='Action: get proxy info')
parser.add_argument('-u', '--update', action='store_true',
                    help='Action: update proxy info')
parser.add_argument('--acme-validation', type=str, default=None,
                    help='ACME validation')
parser.add_argument('-d', '--debug', action='store_true',
                    help='Debug mode')
parser.add_argument('--cert-dir', type=str, default=None,
                    help='Path to the certificate directory')
parser.add_argument('-v', '--verbose', action='store_true',
                    help='Verbose mode')
parser.add_argument('-c', '--config', type=str, default='~/.dynname.json',
                    help='Path of the dynname config')

args = parser.parse_args(sys.argv[1:])

log_level = logging.DEBUG if args.verbose else logging.WARNING
LOG_FORMAT = '%(asctime)-15s %(levelname)s %(message)s'
logging.basicConfig(level=log_level, format=LOG_FORMAT)

config = load_config(args.config)
api = DynnameAPI(config)
if args.get:
    proxy = api.get_proxy() if 'proxy_id' in config else {}
    if args.cert_dir and 'fqdns' in proxy:
        proxy['cert_dirs'] = [_get_cert_path(args.cert_dir, fqdn) for fqdn in proxy['fqdns']]
    print(json.dumps(proxy))
elif args.update:
    proxy_ip = None
    if 'proxy_nic' in config and config['proxy_nic'] is not None:
        ips = get_ips()
        proxy_nic = config['proxy_nic']
        if proxy_nic in ips:
            proxy_ip = ips[proxy_nic]
        else:
            logger.warn(f'No nic: {proxy_nic}')
    if args.acme_validation is None and proxy_ip is None:
        logger.info('No properties to update')
        sys.exit(0)
    api.update_proxy(acme_validation=args.acme_validation, proxy_ip=proxy_ip)
else:
    print('Action not defined', file=sys.stderr)
    parser.print_help()


from flask import Flask, escape, render_template, request, url_for
import requests
from requests.auth import HTTPBasicAuth
import time
import configparser
from ibm_watson import SpeechToTextV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
import json
import re

#carrega configuracoes
config = configparser.ConfigParser()
config.read('config.ini')
print('configurações:/n')
print(config['SPEECH2TEXT'])

#configura o speech2text
authenticator = IAMAuthenticator(config['SPEECH2TEXT']['API_KEY'])
speech_to_text = SpeechToTextV1(
   authenticator=authenticator)
speech_to_text.set_service_url(config['SPEECH2TEXT']['URL'])

app = Flask(__name__)

@app.route('/')
def index():
	return render_template('ouvir.html')

@app.route('/interpretar', methods= ['GET','POST'])
def interpretar():
    data = request.data

    auth_var = HTTPBasicAuth('apikey', config['SPEECH2TEXT']['API_KEY'])

    x = requests.post(
        (config['SPEECH2TEXT']['URL'] + '/v1/recognize?model=pt-BR_NarrowbandModel'),
        auth=auth_var,
        data = data,
        headers = {"Content-Type": "audio/ogg; codecs=opus"})

    json_resposta = x.text

    interpretacao = json.loads(json_resposta, encoding='utf-8')['results'][0 ]['alternatives'][0]['transcript']
    print('interpretacao: ', interpretacao)
    texto = re.sub(r'[^ a-zA-ZãÃáÁàÀâÂçÇéÉêÊíÍõÕóÓôÔúÚ]', "", interpretacao)
    comAcentos = "ÄÅÁÂÀÃäáâàãÉÊËÈéêëèÍÎÏÌíîïìÖÓÔÒÕöóôòõÜÚÛüúûùÇç"
    semAcentos = "AAAAAAaaaaaEEEEeeeeIIIIiiiiOOOOOoooooUUUuuuuCc"

    print('velho: ', texto)
    for i, l in enumerate(texto):
        if l in comAcentos:
            x = comAcentos.index(l)
            y = semAcentos[x]
            texto = texto.replace(texto[i], y)

    print('novo: ', texto)
    auth_var = HTTPBasicAuth('apikey', config['TEXT2SPEECH']['API_KEY'])

    print("{\"text\":\"" + texto + "\"}")
    fala = requests.post(
        (config['TEXT2SPEECH']['URL'] + '/v1/synthesize?voice=pt-BR_IsabelaV3Voice'),
        auth=auth_var,
        data = "{\"text\":\"" + texto + "\"}",
        headers = {"Content-Type": "application/json", "Accept":"audio/ogg; codecs=opus"})

    with open("static/fala_watson.ogg", "wb") as f:
        f.write(fala.content)

    return fala.content

if __name__ == "__main__":
    app.run(host="127.0.0.1", port="5000", debug=True)


import logging
import os
import time
import signal
from os.path import dirname, join
from cgl.plugins.Qt import QtCore, QtGui, QtWidgets
# from cgl.core.startup import do_app_init
from cgl.ui.util import UISettings

class ThemeFileWatcher(QtCore.QFileSystemWatcher):
    def __init__(self, theme_file):
        self.theme_file = theme_file
        QtCore.QFileSystemWatcher.__init__(self, [theme_file])
        self.fileChanged.connect(self.reread_theme)

    def reread_theme(self):
        logging.info("Theme file changed reloading")

        time.sleep(0.5)
        _read_theme_file(self.theme_file)
        if not self.files():
            # PYCHARM will remove the file and replace it, so we need to put it back
            self.addPath(self.theme_file)

def _do_qt_init():
    """
    set up the QT app
    Returns: QtGui.Application

    """
    app = QtWidgets.QApplication([])
    return app

# noinspection PyUnresolvedReferences
# def _load_resources():
#     """
#     load the resource file
#
#     Returns:
#
#     """
#     # noinspection PyUnresolvedReferences
#     if Qt.__binding__ in ["PySide", "PySide2"]:
#         import ui.PySide_rc

# noinspection SpellCheckingInspection
def _load_ui_themes(gui=None):
    """
    load the ui theme from the css

    Returns:

    """

    theme = ":theme.css"
    # look for development files
    theme_env = "LUMBERJACK_THEME_DEV"
    if theme_env in os.environ and os.environ[theme_env] == "1":
        logging.debug("THEME DEV MODE")
        rsc_dir = join(dirname(dirname(dirname(__file__))), "resources")
        if os.path.isdir(rsc_dir):
            theme = join(rsc_dir, "theme.css")
            app = QtWidgets.QApplication.instance()
            # need to stash this some where so it doesnt get GCC'd
            app.theme_watcher = ThemeFileWatcher(theme)

        else:
            logging.warning("Cant find the development files for resources at %s", rsc_dir)
            logging.warning("FALLING BACK")

    logging.debug("Using theme %s", theme)
    _read_theme_file(theme, gui)

def _read_theme_file(theme, gui=None):
    logging.debug("theme: %s", theme)
    css_f = QtCore.QFile(theme)
    css_f.open(QtCore.QIODevice.ReadOnly)
    theme_data = ""
    in_ = QtCore.QTextStream(css_f)
    theme_dev = False
    if ":" not in theme:
        # theme dev mode, fix the file
        theme_dev = True
        logging.info("in theme dev mode")
    while not in_.atEnd():
        line = in_.readLine()  # A QByteArray
        if theme_dev:
            rsc_dir = join(dirname(dirname(dirname(__file__))), "resources")
            line = line.replace("url(:", "url(%s/" % rsc_dir)
        theme_data += line
    css_f.close()

    app = QtWidgets.QApplication.instance()
    logging.info('setting theme: %s' % gui)
    if gui:
        gui.setStyleSheet(theme_data)
    else:
        app.setStyleSheet(theme_data)

def do_freeze_fix():
    import sys
    if getattr(sys, 'frozen', False) and sys.platform == "darwin":
        os.environ["QT_PLUGIN_PATH"] = "."
        QtWidgets.QApplication.setLibraryPaths([os.path.dirname(sys.executable)+"/plugins",
                                                os.path.dirname(sys.executable)])
        # print QtWidgets.QApplication.libraryPaths()

def _load_ui_settings():
    UISettings.settings()

def _load_lang():
    locale = QtCore.QLocale()
    full_locale = locale.bcp47Name()
    if "LUMBERJACK_LOCALE" in os.environ:
        full_locale = os.environ["LUMBERJACK_LOCALE"]
        logging.info("LOCAL OVERRIDE %s" % full_locale)
    if "-" in full_locale:
        lang, _ = full_locale.split("-")
    else:
        lang = full_locale
    if lang == "en":  # we write in english by default, maybe one day we will deal with British/US english
        logging.info("English language")
        return
    region_lang = ":i18n/%s.qm" % full_locale
    lang_lang = ":i18n/%s.qm" % lang
    lang_file = QtCore.QFile(region_lang)
    if not lang_file.exists():
        logging.debug("language %s does not exist" % region_lang)
        lang_file.close()
        lang_file = QtCore.QFile(lang_lang)
        if not lang_file.exists():
            logging.info("language %s does not exist" % lang_lang)
            lang_file.close()
            logging.debug("falling back to english")
            return
    logging.debug("found lang file %s " % lang_file.fileName())
    app = QtWidgets.QApplication.instance()
    trans = QtCore.QTranslator(app)
    trans.load(lang_file.fileName())
    app = QtWidgets.QApplication.instance()
    app.installTranslator(trans)

def do_gui_init():
    # do_app_init()
    do_freeze_fix()
    signal.signal(signal.SIGINT, signal.SIG_DFL)
    app = _do_qt_init()
    # _load_resources()
    _load_ui_themes()
    _load_ui_settings()
    _load_lang()
    return app

def do_maya_gui_init(gui):
    _load_ui_themes(gui)
    _load_ui_settings()

def do_nuke_gui_init(gui):
    _load_ui_themes(gui)
    _load_ui_settings()


import json

#   Speichert das eingegebene Jahresziel in eigener JSON Datei
def ziel_speichern(ziel):
    datei = "Jahresziel.json"
    #   Ziel holt Daten durch Formular mit Jahresziel Eingabe und überschreibt Datenbankabfrage
    inhalt = {"Jahresziel":ziel}
    with open(datei, "w") as open_file:
        json.dump(inhalt, open_file, indent=1)

#   Ruft Jahresziel Dict aus JSON ab
def ziel_laden():
    datei_name = "Jahresziel.json"

    try:
        with open(datei_name) as open_file:
            datei_inhalt = json.load(open_file)
    except FileNotFoundError:
        datei_inhalt = {}

    return datei_inhalt


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 27 18:55:11 2022

@author: aggelen
"""

import sys
sys.path.append('../..')

from spayk.Organization import Tissue
from spayk.Models import IzhikevichNeuronGroup
from spayk.Stimuli import PoissonSpikeTrain

import numpy as np
import matplotlib.pyplot as plt
plt.close('all')

# stimuli
no_syn = 5
no_inh = 2
s_rts = 10*np.ones(no_syn)
inh_neuron_idx = np.random.choice(no_syn, size=no_inh, replace=False)
s_rts[inh_neuron_idx] = np.random.choice(np.arange(30,45), size=no_inh)
input_spike_train = PoissonSpikeTrain(dt=0.1, t_stop=1000, no_neurons=no_syn, spike_rates=10*np.ones(no_syn))
neuron_types = np.zeros(no_syn)
neuron_types[inh_neuron_idx] = 1
input_spike_train.raster_plot(color_array=neuron_types)

#%% Synaptic Model
no_neurons = 1
E = np.zeros(no_syn)
E[inh_neuron_idx] = -75

group_params = {'no_neurons': no_neurons,
                'behaviour': 'synaptic',
                'no_syn': no_syn,
                'E': E}

neurongroup1 = IzhikevichNeuronGroup(group_params)
neurongroup1.autoconnect()

tissue = Tissue([neurongroup1])

tissue.keep_alive(stimuli=input_spike_train)
tissue.logger.plot_v()


import datetime
import json
from flask_caching import Cache
import concurrent.futures
from flask import Flask, session, url_for, request, render_template, redirect, g
import os
import dbContext
import utils
import pickle

app = Flask(__name__, template_folder='templates')
app.secret_key = os.urandom(24)
cache = Cache(app, config={'CACHE_TYPE': 'simple'})

# Load the trained ML pickle file
monday = pickle.load(open('./static/pickle_files/monday_station.pkl', 'rb'))
tuesday = pickle.load(open("./static/pickle_files/tuesday_station.pkl", "rb"))
wednesday = pickle.load(
    open("./static/pickle_files/wednesday_station.pkl", "rb"))
thursday = pickle.load(
    open("./static/pickle_files/thursday_station.pkl", "rb"))
friday = pickle.load(open("./static/pickle_files/friday_station.pkl", "rb"))
saturday = pickle.load(
    open("./static/pickle_files/saturday_station.pkl", "rb"))
sunday = pickle.load(open("./static/pickle_files/sunday_station.pkl", "rb"))

# router to the prediction service
@app.route("/prediction", methods=['GET', 'POST'])
def prediction_model():
    import numpy as np

    # Store the request from JS
    data = request.args.get('post', 0, type=str)
    print(data)
    data = data.split()
    temperature = float(data[0])
    pressure = int(data[1])
    humidity = int(data[2])
    wind_speed = float(data[3])
    date = (data[4])
    d = datetime.datetime.strptime(date, "%Y-%m-%d")
    date = d.strftime("%A")
    minute = (data[5])
    station = int(data[6])
    d = datetime.datetime.strptime(minute, "%H:%M")
    hours = int(d.hour)
    minute = int(d.minute)

    print("Data to be sent to the prediction model ", data)
    print(type(data))
    prediction_input = [[station, temperature,
                         pressure, humidity, wind_speed, hours, minute]]
    if date == "Monday":
        x = monday.predict(prediction_input)
    elif date == "Tuesday":
        x = tuesday.predict(prediction_input)
    elif date == "Wednesday":
        x = wednesday.predict(prediction_input)
    elif date == "Thursday":
        x = thursday.predict(prediction_input)
    elif date == "Friday":
        x = friday.predict(prediction_input)
    elif date == "Saturday":
        x = saturday.predict(prediction_input)
    elif date == "Sunday":
        x = sunday.predict(prediction_input)

    print("Predicted available bikes for selected station is", int(x[0]))

    # Fetch the ML model output and return as JSON to client
    prediction = [int(x[0])]
    return json.dumps(prediction)

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        session.pop('user', None)
        if dbContext.login(request.form['email'], request.form['password']):
            session['user'] = request.form['email']
            return redirect(url_for('dashboard'))
        else:
            return render_template('index.html', results=False)
    if session.get('from_register_page'):
        return render_template('index.html', from_register_page=True)
    return render_template('index.html')

@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        validation_results = utils.validate_register_information(request.form['firstName'], request.form['lastName'],
                                                                 request.form['email'], request.form['password'],
                                                                 request.form['confirmPassword'])
        if not validation_results.results:
            return render_template('register.html', errors=validation_results.data)

        results = dbContext.register(request.form['firstName'], request.form['lastName'], request.form['email'],
                                     request.form['password'])
        if results[0]:
            session['from_register_page'] = True
            return redirect(url_for('index', from_register_page=True))
        else:
            return render_template('register.html', errors=results[1])
    return render_template('register.html')

@app.route('/searchStation', methods=['GET'])
def search_station():
    try:
        # return "Pew Pew", 404
        data = dbContext.get_station(name=request.args.get('name'))
        if len(data) < 1:
            return "Station not found.", 404
        return json.dumps(data[0])

    except Exception as e:
        return f"Something went wrong. Please try again. {e}", 500

@app.route('/dashboard')
@cache.cached(timeout=300)  # Cache the page for 5 minutes
def dashboard():
    if g.user:
        stations = None
        bikes = None
        weather = None
        current_availability = None
        with concurrent.futures.ThreadPoolExecutor() as executor:
            # Retrieve the data using multiple threads
            station_data_future = executor.submit(dbContext.get_station_data)
            availability_data_future = executor.submit(
                dbContext.get_availability_data)
            weather_data_future = executor.submit(dbContext.get_weather_data)
            current_availability_future = executor.submit(
                dbContext.get_stations_availability)

            # Get the results from the futures
            stations = station_data_future.result()
            bikes = availability_data_future.result()
            weather = weather_data_future.result()
            current_availability = current_availability_future.result()

        return render_template('dashboard.html', weather=weather, bikes=bikes, stations=stations,
                               current_availability=json.dumps(current_availability))
    return redirect(url_for('index'))

@app.before_request
def before_request():
    g.user = None
    if 'user' in session:
        g.user = session['user']

@app.template_filter("tojson")
def tojson_filter(value):
    return json.dumps(value)

if __name__ == '__main__':
    app.run(debug=True)


import os
import xml.etree.ElementTree
from bs4 import BeautifulSoup
import cv2
import random
import shutil
import time
import numpy as np

start = time.time()

target_path = 'D:\신지영_업무\\0709_어트리뷰트인수인계\\attribute_crop_images\\upper\origin'
test_set_path = 'D:\신지영_업무\\0709_어트리뷰트인수인계\\attribute_crop_images\\upper\Test_Set'
file_path = 'D:\신지영_업무\\0709_어트리뷰트인수인계\\attribute_crop_images\\upper\\file_list.txt'

crop_img_list = []
xml_list = []
file_name_list = []
attri_list = []
shortshirt_list = []
longshirt_list = []
shirtdk_list = []
type_name_list = ['shortshirt', 'longshirt', 'shirtdk']
color_name_list = ['red', 'green', 'yellow', 'blue', 'brown', 'pink', 'gray', 'black', 'white','unknown']

attri_target_count = 0
shortshirt = 0
longshirt = 0
shirtdk = 0
top_red = 0
top_green = 0
top_yellow = 0
top_blue = 0
top_brown = 0
top_pink = 0
top_gray = 0
top_black = 0
top_white = 0
top_color_unknown = 0
xml_count = 0

red_list = []
green_list = []
yellow_list = []
blue_list = []
brown_list = []
pink_list = []
grey_list = []
black_list = []
white_list = []
unknown_list = []

target_file_list = os.listdir(target_path)
for x in target_file_list:
    if x.endswith('png'):
        crop_img_list.append(x)
    elif x.endswith('xml'):
        xml_list.append(x)
        temp = x.split('.')
        file_name_list.append(temp[0])

def split_label(label):
    temp = str(label)
    temp0 = temp.split('<')
    temp1, result = temp0[1].split('>')
    return result

def split_name(name):
    temp = str(name)
    try:
        temp0 = temp.split("\"")
        result = temp0[1]
    except:
        return False
    return result

def comparison(value):
    sort_list = value.copy()
    empty_list = value.copy()
    sort_list.sort()
    return_count = 0
    count = 0
    count_list = []
    result = []
    num_len = len(value)
    if num_len <= 3:
        for x in value:
            if sort_list[0] == x:
                return count
            else:
                count += 1
    else:
        for x in sort_list:
            count = 0
            for y in empty_list:
                if y == x:
                    result.append(str(count))
                    return_count +=1
                    empty_list.pop(count)
                    break
                else:
                    count += 1
            if return_count == 3:
                break
    return result

file_attri = []
print("xml을 읽어 속성 값 count 시작")

for xml in xml_list:
    if xml.endswith('xml'):
        xml_path = os.path.join(target_path, xml)
        file = open(xml_path, 'r', encoding='utf-8')
        lines = ''
        while True:
            line = file.readline()
            if not line: break
            lines += line
        file.close()
        bs = BeautifulSoup(lines, 'lxml')
        str_temp = '%s' % file_name_list[xml_count]
        temp = []
        temp_str = ''
        for box in bs.find_all('box'):
            label = 'upper'
            lines = str(box).splitlines()
            for x in lines[1:]:
                result = split_label(x)
                if result != 'false':
                    label_name = split_name(x)
                    if label_name:
                        if label_name == 'top':
                            if result == 'short_sleeve':
                                shortshirt += 1
                                shortshirt_list.append(file_name_list[xml_count])
                                temp_str += 'short_sleeve,'
                            elif result == 'long_sleeve':
                                longshirt += 1
                                longshirt_list.append(file_name_list[xml_count])
                                temp_str += 'long_sleeve,'
                            else:
                                shirtdk += 1
                                shortshirt_list.append(file_name_list[xml_count])
                                temp_str += 'shirtdk,'
                            attri = result
                        else:
                            if label_name == 'top_red':
                                top_red += 1
                                temp_str += 'top_red'
                                red_list.append(file_name_list[xml_count])
                            elif label_name == 'top_yellow':
                                top_yellow += 1
                                yellow_list.append(file_name_list[xml_count])
                                temp_str += 'top_yellow'
                            elif label_name == 'top_green':
                                top_green += 1
                                green_list.append(file_name_list[xml_count])
                                temp_str += 'top_green'
                            elif label_name == 'top_blue':
                                top_blue += 1
                                blue_list.append(file_name_list[xml_count])
                                temp_str += 'top_blue'
                            elif label_name == 'top_black':
                                top_black += 1
                                black_list.append(file_name_list[xml_count])
                                temp_str += 'top_black'
                            elif label_name == 'top_brown':
                                top_brown += 1
                                brown_list.append(file_name_list[xml_count])
                                temp_str += 'top_brown'
                            elif label_name == 'top_pink':
                                top_pink += 1
                                pink_list.append(file_name_list[xml_count])
                                temp_str += 'top_pink'
                            elif label_name == 'top_grey':
                                top_grey += 1
                                grey_list.append(file_name_list[xml_count])
                                temp_str += 'top_grey'
                            elif label_name == 'top_white':
                                top_white += 1
                                white_list.append(file_name_list[xml_count])
                                temp_str += 'top_white'
                            elif label_name == 'top_color_unknown':
                                top_color_unknown += 1
                                unknown_list.append(file_name_list[xml_count])
                                temp_str += 'top_color_unknown'
                            attri = label_name
                    temp = temp_str
                    if not (str(attri) in str_temp):
                        str_temp += ',%s' % str(attri)
    file_attri.append(temp)
    attri_list.append(str_temp)
    xml_count += 1

total_list = [longshirt, shortshirt, shirtdk, top_red, top_brown,
              top_color_unknown, top_white, top_black, top_grey,
              top_blue, top_green, top_yellow, top_pink]
total_name_list = ['longshirt', 'shortshirt', 'shirtdk', 'top_red', 'top_brown',
              'top_color_unknown', 'top_white', 'top_black', 'top_grey',
              'top_blue', 'top_green', 'top_yellow', 'top_pink']
min_name = comparison(total_list)
temp = len(min_name)
maximum = total_list[int(temp)-1]
attri_min_name_list = []
attri_min_list = []
pop_file_name_list = []

for x in min_name:
    temp = int(x)
    attri_min_list.append(total_list.pop(temp))
    attri_min_name_list.append(total_name_list.pop(temp))
min_count = 0
result_list = []
unknown_copy_list = unknown_list.copy()
shirtdk_copy_list = shirtdk_list.copy()
brown_copy_list = brown_list.copy()
print("테스트셋에 들어갈 파일 분류 시작")

while True: #분류진행 코드
    if min_count == 0:
        if top_color_unknown >= 1:
            temp = len(unknown_copy_list)
            list_len = int(temp)
            if list_len > 1:
                random_num = random.randint(0, list_len-1)
                target_file = unknown_copy_list.pop(random_num)
                top_color_unknown -= 1
            else:
                target_file = unknown_copy_list[0]
            if not(target_file in result_list):
                result_list.append(target_file)
        else:
            print("첫 번째 최소값 분류 완료")
            min_count += 1
    elif min_count == 1: #shirtdk
        if shirtdk >= 1:
            temp = len(shirtdk_copy_list)
            list_len = int(temp)
            if list_len > 1:
                random_num = random.randint(0, list_len - 1)
                target_file = shirtdk_copy_list.pop(random_num)
                shirtdk -= 1
            else:
                target_file = shirtdk_copy_list[0]
            if not(target_file in result_list):
                result_list.append(target_file)
        else:
            print("두 번째 최소값 분류 완료")
            min_count += 1
    elif min_count == 2: #top_brown
        if top_brown >= 1:
            temp = len(brown_copy_list)
            list_len = int(temp)
            if list_len > 1:
                random_num = random.randint(0, list_len-1)
                target_file = brown_copy_list.pop(random_num)
                top_brown -= 1
            else:
                target_file = brown_copy_list[0]
            result_list.append(target_file)
            if not (target_file in result_list):
                result_list.append(target_file)
        else:
            print("세 번째 최소값 분류 완료")
            break
temp = ''
for x in result_list:
    temp += x+'\n'
file = open(file_path, 'w')
file.write(temp)
file.close()

print("EXIT")
print(time.time()-start)


import numpy as np
import torch
from collections import Counter
from torch.utils.data import DataLoader,Dataset

device = 'cuda' if torch.cuda.is_available() else 'cpu'
Word_Frequency = 3  # 设定语料库中单词出现的阈值,大于阈值则保留
Max_DictSize = 10000  # 设定保留的最大字典大小, 不包括UNK
Nums_Neg = 5  # 负采样的样本个数
Windows_Size = 3 # 滑窗大小: 以中心词为Centre, 左右所包括的单词数量。如：win_size=1, i love you, love为中心，左边所包括单词为i,右边为you

class Vocabolary():
    def __init__(self, text):
        # load and reprocess dataset 'text8.test.txt'
        self.text = text
        self.word2index, self.index2word, self.word_count = self.process()

        # 将单词出现频次转为频率
        total_count = np.array(self.word_count,dtype=np.float32).sum() # 所有单词出现的总频次
        self.word_fre = np.array(self.word_count,dtype=np.float32) / total_count # 单词的频率等于单词的出现频次除以所有单词出现的总频次
        self.word_fre = self.word_fre ** (3.0/4.0)  # 论文中频率转为原来的0.75次方

    def process(self):
        word_counts = dict(Counter(self.text))
        word_counts = [(key, value) for key, value in word_counts.items() if value > Word_Frequency] # 去除低频词
        word_counts = word_counts[:Max_DictSize-1]  # 只保留Max_DictSize-1字典大小的单词及其出现的频次

        word2index = {w: i for i, (w, _) in enumerate(word_counts)}
        index2word = {i: w for i, (w, _) in enumerate(word_counts)}
        word_count = [count for _,count in word_counts]

        word2index.update({"UNK":Max_DictSize})
        index2word.update({Max_DictSize:"UNK"})
        return word2index, index2word, word_count

    @property
    def vocab_size_(self):
        return len(self.word2index)

    def index(self,word):
        assert isinstance(word,str)
        return self.word2index.get(word,Max_DictSize-1) # 根据单词返回在字典中的index，不存在则返回UNK所在的index

    def word(self,index):
        assert isinstance(index,int) and index >= 0 and index <=Max_DictSize
        return self.index2word[index]

def get_Vocab_text(file_path,test = False):
    with open(file_path, 'r') as file:
        text = file.read()

    # for debug
    if test:
        Word_Frequency = 0
        text = text[:20]

    text = text.lower().split()  # 转换小写并按空格分割单词, 文本转为用words list表示
    # nltk.download('stopwords')
    # from nltk.corpus import stopwords  # 加载停用词，如 the, this, am,
    # text = [word for word in text if word not in stopwords.words("english")] # 对文本去除停用词,比较耗时,
    vocab = Vocabolary(text)

    # 将文本的words list -> 文本的index list
    index_text = [vocab.index(word) for word in text]
    return index_text,vocab

class MyDataset(Dataset):
    def __init__(self,train_text,vocab):
        super(MyDataset, self).__init__()

        self.text_encoded = train_text
        self.word_freq = torch.Tensor(vocab.word_fre)  # 用于后续负采样，频次越大，被抽中的作为负样本概率越大(如某些语气词出现多次，可以作为负样本). 一个pos_targets就采样Nums_Neg个负样本, 正负样本比例1:Nums_Neg

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

    def __getitem__(self, idx):
        input = [self.text_encoded[idx]]
        pos_targets = self.get_target(idx)
        neg_targets = torch.multinomial(self.word_freq,num_samples=len(pos_targets) * Nums_Neg ,replacement = True) # torch.multinomial，input要抽样对象(表示权重)，n_samples抽样次数，replacement是否有放回抽样

        # 保证负采样不出现在pos_targets中:
        while len(set(pos_targets) & set(neg_targets)) > 0:
            neg_targets = torch.multinomial(self.word_freq,num_samples=len(pos_targets) * Nums_Neg ,replacement = True)

        input,pos_targets,neg_targets = torch.LongTensor(input),torch.LongTensor(pos_targets),torch.LongTensor(neg_targets)
        assert len(pos_targets) == len(neg_targets) // Nums_Neg  # 正负样本比例1:Nums_Neg
        return input.to(device),pos_targets.to(device),neg_targets.to(device)

    def get_target(self,idx): # idx,中心词的下标,获取正训练样本
        pos_index = list(range(idx-Windows_Size,idx)) + list(range(idx+1,idx+1+Windows_Size)) # 获取左右窗口大小Windows_Size的单词
        pos_index = [ i % len(self.text_encoded) for i in pos_index] # 防止如起点，终点等出现数组越界问题
        return [self.text_encoded[pi] for pi in pos_index]

# for debug
if __name__ == '__main__':
    index_text,vocab = get_Vocab_text('./text8.test.txt',test=True)
    test = MyDataset(index_text,vocab)
    print(test[0])


import pyautogui as pag
import time

play = (23, 1027)
speed = (1138, 983)
speed1x5 = (1138, 849)

if __name__ == "__main__":
    s = pag.confirm('Are you sure to start ?')#if click ok then return “OK”
    pag.moveTo(200,600)
    pag.click()
    time.sleep(1)
    pag.click()
    pag.moveTo(speed)
    time.sleep(0.2)
    pag.moveTo(speed1x5)
    time.sleep(0.2)
    pag.click()

def mian():
    s = pag.confirm('Are you sure to start ?')#if click ok then return “OK”
    if s == "OK":
        while(True):
            pag.moveTo(800, 600)
            pag.moveTo(800, 650)
            ifEqual = pag.pixelMatchesColor(1495, 755, (69, 144, 125))
            if ifEqual: #if it is finish ,then click next one
                time.sleep(5)
                pag.moveTo(130, 800) #下一节
                pag.click()
                print("进入下一节")
                time.sleep(1)
                pag.moveTo(420, 800)#选择1.0倍速
                pag.click()
                time.sleep(1)
                pag.moveTo(420, 723)#选择1.5倍速
                pag.click()
                print("开启1.5倍速")
                time.sleep(120)
            ifBreak = pag.pixelMatchesColor(515, 320, (243, 175, 21))
            if ifBreak:#判断是否弹框
                pag.moveTo(948, 786)
                pag.click()
            time.sleep(3)