import json

import cv2
import shared
import mediapipe as mp
from mediapipe.framework.formats import location_data_pb2
import dlib
from sklearn import neighbors as KNN
from math import sqrt
from calibration import load_matrix, tranform_screen_point_to_floor, get_camera_coordinates

back_button = [0,40,0,100]
video_stream = None
out_video_stream = None
is_face_detection = False
is_face_recognition = False
is_pose_detection = True

mp_drawing = mp.solutions.drawing_utils
mp_drawing_styles = mp.solutions.drawing_styles

class Human:
    #screenspace data
    ss_face_bound_box = (0, 0, 0, 0)

    ss_left_leg_pos = (0, 0)
    ss_right_leg_pos = (0, 0)
    ss_floor = (0, 0)
    ss_height = 0
    ss_head = (0,0)

    face_image = None
    features = None
    id = -1

    pose_landmarks = None

    #worldspace data
    ws_height = 0
    ws_position = [0, 0]

class Recognizer:
    # models
    mp_pose_model = mp.solutions.pose.Pose(min_detection_confidence=0.5, min_tracking_confidence=0.5)
    mp_face_detection_model = mp.solutions.face_detection.FaceDetection(model_selection=1, min_detection_confidence=0.1)
    face_recognition_model = dlib.face_recognition_model_v1("bin/rec.dat")
    face_shape_predictor_model = dlib.shape_predictor("bin/pred68.dat")

    # pairs of (feature, id). For classification
    database = []
    face_classifier = None
    names = {}

    def loadClassifier(self):
        if len(self.database) == 0:
            return
        self.face_classifier = KNN.KNeighborsClassifier(n_neighbors=max(1, int(sqrt(len(self.database)))), algorithm='ball_tree', weights='distance')
        features, ids, _ = zip(*self.database)
        self.face_classifier.fit(features, ids)

        for record in self.database:
            self.names[record[1]] = record[2]

    def cross_prod(self, a, b):
        return [a[1]*b[2] - a[2]*b[1], a[2]*b[0] - a[0]*b[2], a[0]*b[1] - a[1]*b[0]]

    # both arguments coordinates are from 0 to 1
    def getWsPosition(self, point_ss_pos, floor_ss_pos):
        cam_pos = get_camera_coordinates()
        cam_floor = [cam_pos[0], 0, cam_pos[2]]

        # ss - screen space
        # ws - world space
        point_projected_pos = tranform_screen_point_to_floor(point_ss_pos[0], point_ss_pos[1])
        point_projected_pos = [point_projected_pos[0], 0, point_projected_pos[1]]

        floor_ws_pos = tranform_screen_point_to_floor(floor_ss_pos[0], floor_ss_pos[1])
        floor_ws_pos = [floor_ws_pos[0], 0, floor_ws_pos[1]]

        # we have similar triangles

        #                         * cam_pos
        #                       / |
        #                      /  |
        #              point  /   |
        #                    *    |
        #                   /|    |
        #                  / |    |
        # projected_point *__*____*  cam_floor
        #                   floor_point

        # to get head we need linear interpolate between projected_point and cam_pos
        # with alpha = len(projected_point - floor_point) / len(projected_point - cam_floor)
        fix_plane = True
        if fix_plane:
            # however, our projected_point may be not in plane of (floor_point, cam_floor, cam_pos). to fix this,
            # we reproject our "projected_point" again =)
            normal = self.cross_prod([cam_pos[0] - cam_floor[0], cam_pos[1] - cam_floor[1], cam_pos[2] - cam_floor[2]],
                                     [floor_ws_pos[0] - cam_floor[0],
                                      floor_ws_pos[1] - cam_floor[1],
                                      floor_ws_pos[2] - cam_floor[2]])

            normal_len = sqrt(normal[0] ** 2 + normal[1] ** 2 + normal[2] ** 2)
            normal = [normal[0]/normal_len, normal[1]/normal_len, normal[2]/normal_len]

            d1 = cam_floor[0] * normal[0] + cam_floor[1] * normal[1] + cam_floor[2] * normal[2]
            d2 = point_projected_pos[0] * normal[0] + point_projected_pos[1] * normal[1] + point_projected_pos[2] * normal[2]

            point_projected_pos = [
                point_projected_pos[0] - normal[0] * (d2 - d1),
                point_projected_pos[1] - normal[1] * (d2 - d1),
                point_projected_pos[2] - normal[2] * (d2 - d1)]

            d3 = point_projected_pos[0] * normal[0] + point_projected_pos[1] * normal[1] + point_projected_pos[2] * normal[2]

        numenator = (point_projected_pos[0] - floor_ws_pos[0]) ** 2 + (point_projected_pos[2] - floor_ws_pos[2]) ** 2
        denumenator = (point_projected_pos[0] - cam_floor[0]) ** 2 + (point_projected_pos[2] - cam_floor[2]) ** 2
        alpha = sqrt(numenator / denumenator)

        point_ws = [
            (1 - alpha) * point_projected_pos[0] + alpha * cam_pos[0],
            (1 - alpha) * point_projected_pos[1] + alpha * cam_pos[1],
            (1 - alpha) * point_projected_pos[2] + alpha * cam_pos[2]]
        return point_ws
    def process(self, image):
        # transform image to RGB
        rgb_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        # run model-s
        face_results = None
        pose_results = None
        if is_face_detection:
            face_results = self.mp_face_detection_model.process(rgb_image)
        if is_pose_detection:
            pose_results = self.mp_pose_model.process(rgb_image)

        result = []
        if is_pose_detection and pose_results.pose_landmarks != None:
            result = []
            # we need 30 and 29 for feet and 0 for head
            h = Human()
            h.ss_left_leg_pos = [pose_results.pose_landmarks.landmark[29].x, pose_results.pose_landmarks.landmark[29].y]
            h.ss_right_leg_pos = [pose_results.pose_landmarks.landmark[30].x, pose_results.pose_landmarks.landmark[30].y]
            h.ss_floor = [
                (h.ss_left_leg_pos[0] + h.ss_right_leg_pos[0]) / 2.0,
                (h.ss_left_leg_pos[1] + h.ss_right_leg_pos[1]) / 2.0]
            h.pose_landmarks = pose_results.pose_landmarks
            ss_nose = [pose_results.pose_landmarks.landmark[0].x, pose_results.pose_landmarks.landmark[0].y]
            h.ss_head = [ss_nose[0] + 0.02, ss_nose[1] - 0.07]
            h.ws_position = self.getWsPosition(floor_ss_pos=h.ss_floor, point_ss_pos=h.ss_head)
            h.ws_height = h.ws_position[1]
            result.append(h)

        # deal with faces first
        if is_face_detection and face_results.detections != None:
            for face_detection in face_results.detections:
                location_data = face_detection.location_data
                if location_data.format == location_data_pb2.LocationData.RELATIVE_BOUNDING_BOX:
                    bb = location_data.relative_bounding_box

                    h = Human()
                    # setup bound-box
                    h.ss_face_bound_box = [
                        int(bb.xmin * image.shape[1]),
                        int(bb.ymin * image.shape[0]),
                        int(bb.width * image.shape[1]),
                        int(bb.height * image.shape[0])]
                    # setup image
                    h.face_image = image[
                                   h.ss_face_bound_box[1]: h.ss_face_bound_box[1] + h.ss_face_bound_box[3],
                                   h.ss_face_bound_box[0]: h.ss_face_bound_box[0] + h.ss_face_bound_box[2]]

                    # calculate features from detector. they will be simular for same people
                    rect = dlib.rectangle(
                        h.ss_face_bound_box[0],
                        h.ss_face_bound_box[1],
                        h.ss_face_bound_box[0] + h.ss_face_bound_box[2],
                        h.ss_face_bound_box[1] + h.ss_face_bound_box[3])
                    if is_face_recognition:
                        shape = self.face_shape_predictor_model(rgb_image, rect)
                        h.features = shared.to_list(self.face_recognition_model.compute_face_descriptor(rgb_image, shape, 0))

                    # classify them
                    if is_face_recognition and self.face_classifier != None:
                        data = self.face_classifier.kneighbors([h.features], n_neighbors=1)
                        dist = data[0][0][0]
                        ind = self.face_classifier.predict([h.features])[0]
                        if (dist < 0.5):
                            h.id = ind

                    result.append(h)
        return result

recognizer = None

def visualisation_mouse_callback(event, x, y, flags, params):
    if event == cv2.EVENT_LBUTTONDOWN:
        if y > back_button[0] and y < back_button[1] and x > back_button[2] and x < back_button[3]:
            shared.APPLICATION_STATE = shared.MENU_STATE
            out_video_stream.release()
def build_visualisation():
    # open video stream
    global video_stream
    global out_video_stream
    global recognizer
    cv2.namedWindow(shared.VISUALISE_WINDOW_NAME)
    cv2.setMouseCallback(shared.VISUALISE_WINDOW_NAME, visualisation_mouse_callback)
    video_stream = shared.VideoCapture(shared.camera_src)#rtsp://admin:88888888@192.168.0.43:10554/tcp/av0_0")
    fourcc = cv2.VideoWriter_fourcc(*'XVID')
    out_video_stream = cv2.VideoWriter("output.avi", fourcc, 25.0, shared.window_DIM)

    recognizer = Recognizer()

    # create classifier
    with open("database.json", "r") as f:
        recognizer.database = json.loads(f.read())
        recognizer.loadClassifier()

    load_matrix()

def show_visualisation():
    global recognizer
    image = video_stream.read()

    image = shared.undistort(image)
    #process our algorithm
    visualised_humans_data = recognizer.process(image)

    # draw faces bound boxes
    for human in visualised_humans_data:
        if human.pose_landmarks != None:
            print("ws_height", human.ws_height)
            print("ws_pos", human.ws_position)

            estimated_head_position = [int(human.ss_head[0] * image.shape[1]), int(human.ss_head[1] * image.shape[0])]
            estimated_floor_position = [int(human.ss_floor[0] * image.shape[1]),
                                        int(human.ss_floor[1] * image.shape[0])]
            cv2.circle(image, estimated_head_position, 10, (0, 0, 255), -1)
            cv2.circle(image, estimated_floor_position, 10, (0, 255, 0), -1)
            text = "coord:" + str([round(human.ws_position[0], 1), round(human.ws_position[2], 1)])
            cv2.putText(image, text, (estimated_head_position[0] + 20, estimated_head_position[1] + 20), cv2.FONT_HERSHEY_PLAIN, 3, (0, 255, 0), 2)
            text = "height:" + str(round(human.ws_height * 100)) + "cm"
            cv2.putText(image, text, (estimated_head_position[0] + 20, estimated_head_position[1] + 60), cv2.FONT_HERSHEY_PLAIN, 3, (0, 255, 0), 2)

        if human.ss_face_bound_box != (0, 0, 0, 0):
            box = human.ss_face_bound_box
            cv2.rectangle(image, (box[0], box[1]), (box[0] + box[2], box[1] + box[3]), (0, 255, 0), 10)
            text = "id " + str(human.id)
            if human.id in recognizer.names:
                text += "(" + recognizer.names[human.id] + ")"
            cv2.putText(image, text, (box[0], box[1] - 10), cv2.FONT_HERSHEY_PLAIN, 1, (0, 255, 0), 2)

    image = cv2.resize(image, shared.window_DIM)
    if out_video_stream != None:
        out_video_stream.write(image)

    image[back_button[0]:back_button[1], back_button[2]:back_button[3]] = 180
    cv2.putText(image, 'back', (10, 30), cv2.FONT_HERSHEY_PLAIN, 2, (0), 3)
    cv2.imshow(shared.VISUALISE_WINDOW_NAME, image)


import cv2
import numpy as np

cap = cv2.VideoCapture(0)

# config save video
fourcc = cv2.VideoWriter_fourcc(*"XVID")
# 25: fps(frame per seconds)
out = cv2.VideoWriter("image/02.save_to_video.avi", fourcc, 25, (640, 360))

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

    if not ret:
        break

    # 1: vertical flip by frame
    # 0: horizontal flip by frame
    frame_output = cv2.flip(frame, 0)
    cv2.imshow("input", frame)
    cv2.imshow("output", frame_output)

    # save output
    out.write(frame_output)

    # wait bread
    key = cv2.waitKey(1)
    if key == 27:
        break
# destroy
out.release()
cap.release()
cv2.destroyAllWindows()


"""
Faça um programa que leia um ângulo qualquer e mostre na tela o valor do seno, cosseno e tangente desse ângulo.
"""
from math import sin, cos, tan, radians
# lendo ângulo
angulo = int(input("Digite o ângulo: "))

# valores de seno e cosseno
seno = sin(radians(angulo))
print("O ângulo de %d tem o seno de %.2f" %(angulo, seno))
cosseno = cos(radians(angulo))
print("O ângulo de %d tem o seno de %.2f" %(angulo, cosseno))
tangente = tan(radians(angulo))
print("O ângulo de %d tem o seno de %.2f" %(angulo, tangente))


import traceback, requests
from ...distributor import DistributorCron
from ...requests import Request
from ...responses import *
from ...server_config import CQHTTP_URL
from apscheduler.schedulers.blocking import BlockingScheduler
# fail to use AyncIO, 不知道BlockingScheduler会不会有bug（比如执行1min以上的代码）
# from apscheduler.schedulers.asyncio import AsyncIOScheduler

def cron_task():
    print('start task')

    # request打包
    request = Request()
    request.platform = 'CQ'
    request.user_id = ''
    request.from_scheduler = True

    # 初始化分拣中心
    distributor = DistributorCron()

    # 发送消息
    def send(message: str, user_id=None, group_id=None):
        if group_id is None:
            requests.get(f'{CQHTTP_URL}/send_private_msg',
                         {'user_id': user_id, 'message': message})
        else:
            requests.get(f'{CQHTTP_URL}/send_group_msg',
                         {'group_id': group_id, 'message': message})

    # 执行response
    def execute(response_list):
        for response in response_list:
            try:
                if isinstance(response, ResponseGrpMsg) or isinstance(response, ResponseMsg):
                    msg = response.text
                    for at_id in response.at_list:
                        msg += '[CQ:at,qq=%s]' % str(at_id)

                    # 过长文本多次发送
                    max_length = 2000
                    while len(msg) > 0:
                        msg_left = msg[max_length:]  # msg超出maxL的部分
                        msg = msg[:max_length]  # msg只保留maxL内的部分
                        if isinstance(response, ResponseGrpMsg):  # 群聊
                            send(group_id=response.group_id, message=msg)
                        else:  # 用户
                            send(user_id=response.user_id, message=msg)
                        if msg_left != '':  # 这轮超出部分为0时
                            msg = msg_left
                        else:
                            msg = ''

                elif isinstance(response, ResponseGrpImg) or isinstance(response, ResponseImg):
                    img_msg = '[CQ:image,file=file:///%s]' % response.file.replace(':', ':\\')
                    if isinstance(response, ResponseGrpImg):
                        send(group_id=response.group_id, message=img_msg)
                    else:
                        send(user_id=response.user_id, message=img_msg)
                elif isinstance(response, ResponseMusic):
                    send(user_id=response.user_id,
                         message=f'[CQ:music,type={response.platform},id={response.music_id}]')
                else:
                    pass
            except:
                # 诸如发送失败等问题
                traceback.print_exc()

    execute(response_list=distributor.handle(request=request))
    distributor.refresh_and_save()

def main():
    scheduler = BlockingScheduler()
    scheduler.add_job(cron_task, 'cron', hour='*', minute='*')
    scheduler.start()


# Условие: /Images/Task 1.png

import math
x = float(input("X: "))
a = float(input("A: "))

if x > a:
    print(x * (x - a) ** 0.5)
elif x == a:
    print(x / math.sin(a * x))
elif x < a:
    print(math.exp(-a * x) * math.cos(a * x))

Labs/3 (Алгоритмические конструкции ветвления)/Solution 1.py


import torch
from torch import nn
from torch.nn import init
import torch.nn.functional as F
import math
from torch.autograd import Variable
import numpy as np

from .deeplab_resnet import resnet50_locate
from .vgg import vgg16_locate
import torch.npu
import os
NPU_CALCULATE_DEVICE = 0
if os.getenv('NPU_CALCULATE_DEVICE') and str.isdigit(os.getenv('NPU_CALCULATE_DEVICE')):
    NPU_CALCULATE_DEVICE = int(os.getenv('NPU_CALCULATE_DEVICE'))
if torch.npu.current_device() != NPU_CALCULATE_DEVICE:
    torch.npu.set_device(f'npu:{NPU_CALCULATE_DEVICE}')

config_vgg = {'convert': [[128,256,512,512,512],[64,128,256,512,512]], 'deep_pool': [[512, 512, 256, 128], [512, 256, 128, 128], [True, True, True, False], [True, True, True, False]], 'score': 128}  # no convert layer, no conv6

config_resnet = {'convert': [[64,256,512,1024,2048],[128,256,256,512,512]], 'deep_pool': [[512, 512, 256, 256, 128], [512, 256, 256, 128, 128], [False, True, True, True, False], [True, True, True, True, False]], 'score': 128}

class ConvertLayer(nn.Module):
    def __init__(self, list_k):
        super(ConvertLayer, self).__init__()
        up = []
        for i in range(len(list_k[0])):
            up.append(nn.Sequential(nn.Conv2d(list_k[0][i], list_k[1][i], 1, 1, bias=False), nn.ReLU(inplace=True)))
        self.convert0 = nn.ModuleList(up)

    def forward(self, list_x):
        resl = []
        for i in range(len(list_x)):
            resl.append(self.convert0[i](list_x[i]))
        return resl

class DeepPoolLayer(nn.Module):
    def __init__(self, k, k_out, need_x2, need_fuse):
        super(DeepPoolLayer, self).__init__()
        self.pools_sizes = [2,4,8]
        self.need_x2 = need_x2
        self.need_fuse = need_fuse
        pools, convs = [],[]
        for i in self.pools_sizes:
            pools.append(nn.AvgPool2d(kernel_size=i, stride=i))
            convs.append(nn.Conv2d(k, k, 3, 1, 1, bias=False))
        self.pools = nn.ModuleList(pools)
        self.convs = nn.ModuleList(convs)
        self.relu = nn.ReLU()
        self.conv_sum = nn.Conv2d(k, k_out, 3, 1, 1, bias=False)
        if self.need_fuse:
            self.conv_sum_c = nn.Conv2d(k_out, k_out, 3, 1, 1, bias=False)

    def forward(self, x, x2=None, x3=None):
        x_size = x.size()
        resl = x
        for i in range(len(self.pools_sizes)):
            y = self.convs[i](self.pools[i](x))
            resl = torch.add(resl, F.interpolate(y, x_size[2:], mode='bilinear', align_corners=True))
        resl = self.relu(resl)
        if self.need_x2:
            resl = F.interpolate(resl, x2.size()[2:], mode='bilinear', align_corners=True)
        resl = self.conv_sum(resl)
        if self.need_fuse:
            resl = self.conv_sum_c(torch.add(torch.add(resl, x2), x3))
        return resl

class ScoreLayer(nn.Module):
    def __init__(self, k):
        super(ScoreLayer, self).__init__()
        self.score = nn.Conv2d(k ,1, 1, 1)

    def forward(self, x, x_size=None):
        x = self.score(x)
        if x_size is not None:
            x = F.interpolate(x, x_size[2:], mode='bilinear', align_corners=True)
        return x

def extra_layer(base_model_cfg, vgg):
    if base_model_cfg == 'vgg':
        config = config_vgg
    elif base_model_cfg == 'resnet':
        config = config_resnet
    convert_layers, deep_pool_layers, score_layers = [], [], []
    convert_layers = ConvertLayer(config['convert'])

    for i in range(len(config['deep_pool'][0])):
        deep_pool_layers += [DeepPoolLayer(config['deep_pool'][0][i], config['deep_pool'][1][i], config['deep_pool'][2][i], config['deep_pool'][3][i])]

    score_layers = ScoreLayer(config['score'])

    return vgg, convert_layers, deep_pool_layers, score_layers

class PoolNet(nn.Module):
    def __init__(self, base_model_cfg, base, convert_layers, deep_pool_layers, score_layers):
        super(PoolNet, self).__init__()
        self.base_model_cfg = base_model_cfg
        self.base = base
        self.deep_pool = nn.ModuleList(deep_pool_layers)
        self.score = score_layers
        if self.base_model_cfg == 'resnet':
            self.convert = convert_layers

    def forward(self, x):
        x_size = x.size()
        conv2merge, infos = self.base(x)
        if self.base_model_cfg == 'resnet':
            conv2merge = self.convert(conv2merge)
        conv2merge = conv2merge[::-1]

        edge_merge = []
        merge = self.deep_pool[0](conv2merge[0], conv2merge[1], infos[0])
        for k in range(1, len(conv2merge)-1):
            merge = self.deep_pool[k](merge, conv2merge[k+1], infos[k])

        merge = self.deep_pool[-1](merge)
        merge = self.score(merge, x_size)
        return merge

def build_model(base_model_cfg='vgg'):
    if base_model_cfg == 'vgg':
        return PoolNet(base_model_cfg, *extra_layer(base_model_cfg, vgg16_locate()))
    elif base_model_cfg == 'resnet':
        return PoolNet(base_model_cfg, *extra_layer(base_model_cfg, resnet50_locate()))

def weights_init(m):
    if isinstance(m, nn.Conv2d):
        m.weight.data.normal_(0, 0.01)
        if m.bias is not None:
            m.bias.data.zero_()


import pytest
import numpy as np
import raf
from raf.testing import check_type, run_infer_type, get_dist_comm_info, with_dialect
from tvm.relay import TensorType, FuncType, TupleType

@with_dialect(["tvm", "cuda"])
@pytest.mark.skipif(not raf.build.with_cuda(), reason="CUDA is not enabled")
@pytest.mark.parametrize("shape", [(128, 128), (64, 64), (32, 64, 128)])
@pytest.mark.parametrize("dtype", ["float32", "float16"])
@pytest.mark.parametrize("n", [2, 3, 4])
def test_fuse_tensor_type(shape, dtype, n):
    class Model(raf.Model):
        def build(self):
            pass

        @raf.model.trace
        def forward(self, x):
            y = raf.fuse_tensor([x] * n)
            return y

    model = Model()
    _, _, local_rank = get_dist_comm_info()
    device = f"cuda({local_rank})"
    x = np.ones(shape=shape, dtype=dtype)
    x = raf.array(x, device=device)
    m_func = model._internal(x).mod["main"]
    m_func = run_infer_type(m_func)
    t_a = TensorType(shape, dtype=dtype)
    size = 1
    for axis in shape:
        size *= axis
    size *= n
    t_b = TensorType((size,), dtype=dtype)
    desire_type = FuncType([t_a], t_b)
    check_type(m_func, desire_type)

@with_dialect(["tvm", "cuda"])
@pytest.mark.skipif(not raf.build.with_cuda(), reason="CUDA is not enabled")
@pytest.mark.parametrize(
    "shapes,shape_indices",
    [
        [(32, 32, 64, 64), (2, 4)],
        [(16, 32, 64, 64, 128), (2, 5)],
        [(32, 32, 64, 64, 32), (3, 5)],
    ],
)
@pytest.mark.parametrize("dtype", ["float32", "float16"])
def test_defuse_tensor_type(shapes, shape_indices, dtype):
    tuple_shape = []
    tensor_types = []
    total_size = 0
    sizes = []
    start_index = 0
    for end_index in shape_indices:
        size = 1
        for axis in shapes[start_index:end_index]:
            size *= axis
        total_size += size
        sizes.append(size)
        tuple_shape.append(tuple(shapes[start_index:end_index]))
        tensor_types.append(TensorType(shapes[start_index:end_index], dtype=dtype))
        start_index = end_index

    class Model(raf.Model):
        def build(self):
            pass

        @raf.model.trace
        def forward(self, x):
            y = raf.defuse_tensor(x, sizes, shapes, shape_indices)
            return y

    model = Model()
    _, _, local_rank = get_dist_comm_info()
    device = f"cuda({local_rank})"
    x = np.ones(shape=(total_size,), dtype=dtype)
    x = raf.array(x, device=device)
    m_func = model._internal(x).mod["main"]
    m_func = run_infer_type(m_func)
    t_a = TensorType((total_size,), dtype=dtype)
    t_b = TupleType(tensor_types)
    desire_type = FuncType([t_a], t_b)
    check_type(m_func, desire_type)

if __name__ == "__main__":
    pytest.main([__file__])


from numpy import *
from ..util import make_gen

def mask_peaks(peaks):
    """
    Given a window of peaks, mask all but the maximum to zero
    """
    return array(peaks) * (arange(len(peaks)) == argmax(peaks))

def suppress_peaks(data, thresh):
    """
    Find peaks in data, suppressing neighboring, smaller peaks in the event that we
    are using some kind of nois detector (such as subsample_matched_filter()) that
    can have multiple peaks output for a single event. This function will find all
    peaks exceeding a threshold, but for each contiguous range of peaks it will
    emit only the maximum of the range, truncating all others to zero.

    Parameters
    ----------
    data : 1-D signal (array or iterator)
        The signal stream to suppress peaks in
    thresh : number
        The threshold to define peaky areas

    Return values
    -------------
    peakstream : 1-D signal
        A stream of peaks with all other values set to zero
    """
    data = make_gen(data)

    while True:
        # Always reset our data window
        data_win = [next(data)]

        try:
            # Read stuff into data_win as long as the data exceeds threshold
            while abs(data_win[-1]) > thresh:
                data_win += [next(data)]
        except StopIteration:
            # Yield any values if we have them
            if len(data_win):
                for val in mask_peaks(data_win):
                    yield val

            # Finally, re-raise the StopIteration
            raise StopIteration()

        # The number of thresh-surpassing points is len(data_win) - 1:
        if len(data_win) > 1:
            for val in mask_peaks(data_win[:-1]):
                yield val

        # No matter what, we always yield a 0 here for the last data point that
        # didn't exceed thresh
        yield data_win[0] * 0


from keras.models import load_model
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'

import PIL.Image
from PIL import Image, ImageOps #Install pillow instead of PIL
import numpy as np
if not hasattr(PIL.Image, 'Resampling'):  # Pillow<9.0
    PIL.Image.Resampling = PIL.Image
# Disable scientific notation for clarity
np.set_printoptions(suppress=True)

# Load the model
model = load_model('backend\keras_model.h5', compile=False)

# Load the labels
class_names = open('backend\labels.txt', 'r').readlines()
print(class_names)
# Create the array of the right shape to feed into the keras model
# The 'length' or number of images you can put into the array is
# determined by the first position in the shape tuple, in this case 1.
data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)

# Replace this with the path to your image
image = Image.open('images\img4.jpg').convert('RGB')

#resize the image to a 224x224 with the same strategy as in TM2:
#resizing the image to be at least 224x224 and then cropping from the center
size = (224, 224)
image = ImageOps.fit(image, size, Image.Resampling.LANCZOS)

#turn the image into a numpy array
image_array = np.asarray(image)

# Normalize the image
normalized_image_array = (image_array.astype(np.float32) / 127.0) - 1

# Load the image into the array
data[0] = normalized_image_array

# print(data)
# run the inference
prediction = model.predict(data)
index = np.argmax(prediction)
class_name = class_names[index]
print('Class:', class_name, end='')


from typing import Optional, Tuple
import torch
from torch import nn
import numpy as np
from torch.nn import Parameter, MultiheadAttention

def split_heads(x: torch.Tensor, n_heads: int) -> torch.Tensor:
    """
    Parameters
    ----------
    x : torch.Tensor (batch_size, length, dim)
        Input tensor.
    n_heads : int
        Number of attention heads.
    """
    batch_size, dim = x.size(0), x.size(-1)
    x = x.view(batch_size, -1, n_heads, dim // n_heads)  # (batch_size, length, n_heads, d_head)
    x = x.transpose(1, 2)  # (batch_size, n_heads, length, d_head)
    return x

# def combine_heads(x: torch.Tensor) -> torch.Tensor:
#     """
#     Parameters
#     ----------
#     x : torch.Tensor (batch_size, n_heads, length, d_head)
#         Input tensor.
#     """
#     #https://stackoverflow.com/questions/48915810/what-does-contiguous-do-in-pytorch
#     batch_size, n_heads, d_head = x.size(0), x.size(1), x.size(3)
#     x = x.transpose(1, 2).contiguous().view(batch_size, -1, d_head * n_heads)  # (batch_size, length, n_heads * d_head)
#     return x

# def add_mask(x: torch.Tensor, mask: Optional[torch.Tensor] = None) -> torch.Tensor:
#     """
#     Mask away by setting such weights to a large negative number, so that they evaluate to 0
#     under the softmax.
#     Parameters
#     ----------
#     x : torch.Tensor (batch_size, n_heads, *, length) or (batch_size, length)
#         Input tensor.
#     mask : torch.Tensor, optional (batch_size, length)
#         Mask metrix, ``None`` if it is not needed.
#     """
#     if mask is not None:
#         if len(x.size()) == 4:
#             expanded_mask = mask.unsqueeze(1).unsqueeze(1)  # (batch_size, 1, 1, length)
#         x = x.masked_fill(expanded_mask.bool(), -np.inf)
#     return

class ScaledDotProductAttention(nn.Module):
    """
    Scaled Dot-Product Attention
    Parameters
    ----------
    scale : float
        Scale factor (``sqrt(d_head)``).
    dropout : float, optional
        Dropout, ``None`` if no dropout layer.
    """
    def __init__(self, scale: float, dropout: float = 0.5) -> None:
        super(ScaledDotProductAttention, self).__init__()

        self.scale = scale
        self.softmax = nn.Softmax(dim=-1)
        self.dropout = None if dropout is None else nn.Dropout(dropout)

    def forward(
        self,
        Q: torch.Tensor,
        K: torch.Tensor,
        V: torch.Tensor,
        mask: Optional[torch.Tensor] = None
    ) -> Tuple[torch.Tensor]:
        """
        Parameters
        ----------
        Q : torch.Tensor (batch_size, n_heads, length, d_head)
            Query
        K : torch.Tensor (batch_size, n_heads, length, d_head)
            Key
        V : torch.Tensor (batch_size, n_heads, length, d_head)
            Value
        mask : torch.Tensor (batch_size, 1, 1, length)
            Mask metrix, None if it is not needed
        Returns
        -------
        context : torch.Tensor (batch_size, n_heads, length, d_head)
            Context vector.
        att : torch.Tensor (batch_size, n_heads, length, length)
            Attention weights.
        """

        q = Q / Q.norm(dim=-1, keepdim=True)
        k = K / K.norm(dim=-1, keepdim=True)

        kv = (k * V).sum(dim=-2, keepdim=True)

        att = q * kv
        att = self.dropout(att)
        # context = ...

        return att

class HydraAttention(nn.Module):

    def __init__(self, dim: int, n_heads: int = 8, dropout: Optional[float] = None) -> None:
        super(HydraAttention, self).__init__()

        assert dim % n_heads == 0

        self.n_heads = n_heads
        self.d_head = dim // n_heads

        # linear projections
        self.W_Q = nn.Linear(in_features=dim, out_features=dim)
        self.W_K = nn.Linear(in_features=dim, out_features=dim)
        self.W_V = nn.Linear(in_features=dim, out_features=dim)

        # scaled dot-product attention
        scale = self.d_head ** 0.5  # scale factor
        # self.attention = ScaledDotProductAttention(scale=scale, dropout=dropout)

        self.layer_norm = nn.LayerNorm(dim)
        # self.fc = nn.Linear(...)

        self.dropout = None if dropout is None else nn.Dropout(dropout)

    def forward(
            self, x: torch.Tensor, mask: Optional[torch.Tensor] = None
    ) -> Tuple[torch.Tensor]:

        Q = self.W_Q.forward(x)
        K = self.W_K.forward(x)
        V = self.W_V.forward(x)

        Q, K, V = split_heads(Q, self.n_heads), split_heads(K, self.n_heads), split_heads(V,
                                                                                self.n_heads)  # (batch_size, n_heads, length, d_head)

        q = Q / Q.norm(dim=-1, keepdim=True)
        k = K / K.norm(dim=-1, keepdim=True)

        kv = (k * V).sum(dim=-2, keepdim=True)

        att = q * kv
        att = att if self.dropout is None else self.dropout(att)

        # out = self.layer_norm(att)  # LayerNorm

        return att

if __name__ == "__main__":

    attention = HydraAttention(dim=2, n_heads=2, dropout=0.2)
    query = torch.rand(20, 2)

    res = attention(query)
    print(res[0].shape)
    print(res[1].shape)

    att = MultiheadAttention(embed_dim=2, num_heads=2, dropout=0.2)
    res2 = attention(query)

    print(res2[0].shape)
    print(res2[1].shape)


# Imports
import decimal
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
import pprint

# Constantes

# Vecteur largeur des portes
L = np.array([125, 100, 67, 75, 86, 57, 24, 34, 75, 34])
# Nombre de pieces
n = len(L)
# Vecteur repartition initiale des mouches
M = np.array([123, 479, 535, 3645, 352, 45, 556, 2, 356, 876])
# Probabilite qune mouche ne change pas de piece
reste_p = 0
# Probabilite  qune mouche change de piece
bouge_p = 1 - reste_p
# Valeur initiale z
z = 0.99
# Precision
precision = 1e-12
# Type d'affichage des lignes
courbe = True

# Intialisation

def initMatriceTransition():
    T = np.zeros((n, n))
    for i in range(n):
        T[i, i] = reste_p
        T[(i + 1) % n, i] = bouge_p * L[i] / (L[i] + L[(i - 1) % n])
        T[(i - 1) % n, i] = bouge_p * L[(i - 1) % n] / (L[i] + L[(i - 1) % n])

    return T

def puissanceInverse(A, z):
    r = abs(decimal.Decimal(str(precision)).as_tuple().exponent)
    I = np.identity(n)
    try:
        R = np.linalg.inv(A - z * I)
        q = z
        x = M
        convergence = False
        evolution = dict()
        evolution[q] = x / np.linalg.norm(x)
        while not convergence:
            y = np.dot(R, x)
            x = y / np.linalg.norm(y)
            prec_q = q
            q = np.dot(x, np.dot(A, x))
            evolution[q] = np.around(x, r)
            cauchy = np.linalg.norm(q - prec_q)
            convergence = cauchy <= precision
        return q, x, evolution
    except np.linalg.LinAlgError:
        print(z, 'est valeur propre')
        raise

def numerise(x):
    return np.sum(M) / np.sum(x) * x

# function to add value labels
def addlabels(x,y):
    for i in range(len(x)):
        plt.text(i + 1, y[i], y[i], ha = 'center')

def construitStationaire(q, x):
    values = numerise(x)
    rooms = np.arange(1, n + 1)
    plt.bar(rooms, values)
    addlabels(rooms, np.around(values, 4))
    plt.title('Répartition stationaire des mouches par piece\n' +
              'init = ' + str(M) + ' n = ' + str(np.sum(M)) + ' z = ' + str(z))
    plt.xlabel("Piece")
    plt.ylabel("Nombre de mouches")

def construitEvolution(evolution):
    plt.figure()
    legende = []
    for i in range(n):
        evolution_salle_i = []
        for q in evolution:
            evolution_salle_i.append(numerise(evolution[q])[i])
        if courbe:
            cubic_interploation_model = interp1d(np.arange(len(evolution)), evolution_salle_i, kind = "cubic")
            # Plotting the Graph
            X = np.linspace(0, len(evolution) - 1, 500)
            Y = cubic_interploation_model(X)
            plt.plot(X, Y)
        else:
            plt.plot(evolution_salle_i)
        legende.append('Piece ' + str(i + 1))
    plt.legend(legende)
    plt.title('Evolution du nombre de mouche par piece\n' +
              'init = ' + str(M) + ' n = ' + str(np.sum(M)) + ' z = ' + str(z))
    plt.xlabel('Itération')
    plt.ylabel('Nombre de mouches')

def afficheResultats(q, x, evolution):
    print('\nRegime stationaire :\n', 'Le vecteur propre associé à la valeur propre', q, 'est :\n', x)
    print('\nEn évolution :')
    for q in evolution:
        x = evolution[q]
        print('q =', q, '=> x =', numerise(x))
    construitStationaire(q, x)
    construitEvolution(evolution)
    plt.show()

def balayement(start = 0.01, end = 0.99, step = 0.01, digit = 4):
    r = np.arange(start, end, step)
    d = {}
    for i in r:
        q, x, e = puissanceInverse(A, i)
        rounded = round(q, digit)
        num = numerise(x)
        d[rounded] = [num, sum(num)]
    return d

A = initMatriceTransition()
print('Matrice de transition A :\n', A)

try:
    q, x, evolution = puissanceInverse(A, z)
    b = balayement()
    pprint.pprint(b)
    afficheResultats(q, x, evolution)
except np.linalg.LinAlgError:
    print('le z choisis est déjà une valeur propre')


# US Medical Insurance Costs
# Project goals:
# 1) Determine least expensive region
# 2) Average age of person with one child
# 3) Compare BMI of smokers vs non smoker
import csv
from collections import defaultdict

with open("C:\\Users\\ayamr\\Documents\\Coding\\Python portfolio\\Insurance.csv") as insurance_data:
# Save data into seperate lists for analysis
    reader = csv.DictReader(insurance_data)
    age = []
    sex = []
    bmi = []
    children = []
    smoker = []
    region = []
    charges = []
    for col in reader:
        age.append(col['age'])
        sex.append(col['sex'])
        bmi.append(col['bmi'])
        children.append(col['children'])
        smoker.append(col['smoker'])
        region.append(col['region'])
        charges.append(col['charges'])
    reader2 = csv.DictReader(insurance_data)
# Save data into a list of dictionaries
    for row in reader2:
        data = [row for row in reader2]
# Function to determine least expensive region by average cost of insurance
def least_expensive():
    charges_float = [float(x) for x in charges]
    duplicate_dict={}
    for i in region:
        duplicate_dict[i]=region.count(i) # counts number of times a region apears in the data
    d = defaultdict(float)
    for k, v in zip(region, charges_float):
        d[k] += v # create dictionary with regions as keys and amounts as values where the values are total amounts for each unique regions
    region_average = {k: d[k]/duplicate_dict[k] for k in d.keys() & duplicate_dict} # divides the total amount per regions by the number of instances of the regions to get an average
    region_average_sorted = {k: v for k, v in sorted(region_average.items(), key=lambda item: item[1])} # sorts low to high
    cheapest_region = list(region_average_sorted.keys())[0]
    cheapest_amount = list(region_average_sorted.values())[0]
    pricey_region = list(region_average_sorted.keys())[-1]
    pricey_amount = list(region_average_sorted.values())[-1]
    print("The cheapest region for health insurance is the " + cheapest_region + " region with an average cost of $" + str(cheapest_amount) + ". The most expensive region is the " + pricey_region + " region with an average cost of $" + str(pricey_amount) +".")
# least_expensive()
# Function to determine the average age of a person with one child
def one_child_age():
    age_child = list(zip(age,children)) # zipped list of ages and children
    total_age = []
    for index, tuple in enumerate(age_child):
        howold = tuple[0]
        child = tuple[1]
        if child == '1':
            total_age.append(howold)  # adds all ages to total_age list that have a child value of 1
    sum_of_ages = sum(int(i) for i in total_age)
    avg_age_one_child = sum_of_ages / children.count('1') # divides total ages by total instances of 1 child for average
    print("The average age of a person with one child is " + str(avg_age_one_child) + " years old.")
# one_child_age()

# Function to compare the BMI of smokers versus non smokers
def compare_BMI():
    average_BMI = (sum(float(i) for i in bmi)) / len(bmi)
    smoker_bmi = list(zip(smoker, bmi))
    smoker_bmi_list = []
    non_smoker_bmi_list = []
    for index, tuple in enumerate(smoker_bmi):
        smkr = tuple[0]
        weight = tuple[1]
        if smkr == 'yes':
            smoker_bmi_list.append(weight)
        else:
            non_smoker_bmi_list.append(weight)
    smoker_bmi_avg = sum(float(i) for i in smoker_bmi_list) / len(smoker_bmi_list)
    non_smoker_bmi_avg = sum(float(i) for i in non_smoker_bmi_list) / len(non_smoker_bmi_list)
    print("The average BMI for a smoker is " + str(smoker_bmi_avg) + ". The average BMI for a non smoker is " + str(non_smoker_bmi_avg) + ".")
# compare_BMI()


from resnet20 import ResNetCIFAR
from train_util import train, test, test2
import torch
import numpy as np
import matplotlib.pyplot as pt
device = 'cuda' if torch.cuda.is_available() else 'cpu'
import pickle
from math import sqrt
import os

method = 'AdamW'
lr = 0.001
reg_norms = np.linspace(-6, -4.5, num=5)
reg_norms = 10 ** (reg_norms + 4)
epochs = 2
tot_train_size = 50000
batch_size = 128
# reg = reg_norm * \sqrt{b / B T}
ams = [False, True]
i=int(os.environ['SLURM_ARRAY_TASK_ID'])
for amsgrad in ams:
    reg_norm = reg_norms[i-1]
    reg = reg_norm * sqrt(batch_size / epochs / tot_train_size)
    print("reg = {}".format(reg))
    net = ResNetCIFAR(num_layers=20)
    net = net.to(device)
    loss, acc = train(net,opt_method= method, epochs = epochs, batch_size = batch_size, \
                  lr = lr, reg = reg, amsgrad = amsgrad, log_every_n=300)
    name = "summary_stats/net_{0}_{1}_amsgrad_{2}_epoch_{3}".format(method, int(reg_norm * 1e7), amsgrad,epochs)
    open_file = open("{0}.p".format(name), "wb" )
    pickle.dump([acc, loss], open_file)
    open_file.close()


import random
import requests

from bs4 import BeautifulSoup
from newspaper import Article as ArticleParser
from requests.exceptions import InvalidSchema

from django.core.exceptions import ObjectDoesNotExist
from django.db import IntegrityError

from journalist.core import journalist_globals as jg
from journalist.core.utils import update_log
from journalist.core.articles_factory import article_editor
from journalist.core.utils.user_agents import get_random_user_agent
from journalist.models import Topic, Article, READY
from journalist.models import GCCache as cache

CURRENT_USER_AGENT = get_random_user_agent()
REQUESTS_COUNT = 0

def get_tor_session():
    """ Connects to the tor network. Changes IP every 10 minutes.
    """
    session = requests.session()
    session.proxies = {'http':  'socks5://127.0.0.1:9050',
                       'https': 'socks5://127.0.0.1:9050'}
    return session

def get_page(url):
    """ Sends a request to the url and returns a response or None.
    Rotates random user agents every random intervals.
    """
    global CURRENT_USER_AGENT
    global REQUESTS_COUNT

    headers = {'User-Agent': CURRENT_USER_AGENT}
    session = get_tor_session()

    try:
        response = session.get(url, headers=headers)
    except InvalidSchema as e:
        update_log.error('Error in session.get()')
        update_log.error(e)
        return None
    else:
        # Use a user agent for a random amount of requests
        REQUESTS_COUNT += 1
        r_limit = random.randint(5, 10)
        if REQUESTS_COUNT >= r_limit:
            update_log.info("Changing user agent at {} requests.".format(
                REQUESTS_COUNT))

            # Make sure our new user agent is not the one we allready have.
            for a in range(0, 10):
                new_ua = get_random_user_agent()
                if new_ua != CURRENT_USER_AGENT:
                    CURRENT_USER_AGENT = get_random_user_agent()
                    REQUESTS_COUNT = 0

        if response.status_code == 200:
            return response
        else:
            update_log.warning('Got response code ({})'.format(
                response.status_code))
            return None

def test_connection():
    """ Flight test before we begin...
    """
    # Check user agent
    response = get_page("https://httpbin.org/user-agent")
    if response is not None:
        update_log.info(response.text)

    # Check IP
    response = get_page("http://httpbin.org/ip")
    if response is not None:
        update_log.info(response.text)

def get_urls():
    """ Get a list of urls (sources) for each topic to scrape.
    """
    topics = Topic.objects.filter(active=True)
    urls = {}
    for topic in topics:
        urls[topic.title] = set()
        sources = topic.sources.filter(active=True).values()
        for source in sources:
            urls[topic.title].update(get_urls_from_source(source))
    return urls

def get_urls_from_source(source):
    """ Returns a set of tuples: {(url, lang), (url, lang) ...} so that every
    url-language combination is unique.
    Checks the url_blacklist so we don't scrape a URL more than once.
    """

    urls = set()

    blacklist = cache.get_item('url_blacklist')
    if blacklist is None:
        blacklist = cache.set_item('url_blacklist', "")

    update_log.info('Checking {}'.format(source['root_url']))
    response = get_page(source['root_url'])
    if response is not None:
        soup = None
        if source['root_url'].endswith('.xml'):

            # XML Parsing =====================================================
            xml = response.text
            print('==> Response:')
            print(xml)
            soup = BeautifulSoup(xml)
            if soup is not None:
                links = soup.find_all('loc')
                if len(links) == 0:
                    update_log.warning('No links were fount in this page.')
                for link in links:
                    link_text = link.text
                    print(link_text)
                    if (
                        link_text.startswith(source['url_filter']) and
                        link_text > source['url_filter'] and
                        link_text not in blacklist.value
                    ):
                        urls.add((link_text, source['language']))
            else:
                update_log.warning('Cannot parse this page.')
        else:

            # HTML parsing ====================================================
            soup = BeautifulSoup(response.content, 'html.parser')
            if soup is not None:
                links = soup.find_all('a', href=True)
                if len(links) == 0:
                    update_log.warning('No links were fount in this page.')
                for link in links:
                    if (
                        link['href'].startswith(source['url_filter']) and
                        link['href'] > source['url_filter'] and
                        link['href'] not in blacklist.value
                    ):
                        urls.add((link['href'], source['language']))
            else:
                update_log.warning('Cannot parse this page.')

    if len(urls) == 0:
        update_log.warning('Fount nothing new in {}'.format(
            source['root_url']))

    return urls

def add_url_to_blacklist(url):
    """ Adds a url to the blacklist so that we never try to scrape it again.
    """
    blacklist = cache.get_item('url_blacklist')

    if blacklist is None:
        blacklist = cache.set_item('url_blacklist', url)
        return True

    new_url = ', {}'.format(url)
    blacklist.set_value(blacklist.value + new_url)

    return True

def parse_article(url, min_words_count=jg.MIN_WORDS_TO_SCRAPE):
    """ We download an article by ourselves so that we do it behind the Tor
    network and with a random user agent (Don't let Newspaper do it!).
    Then we fool Newspaper to think that it was the one who downloaded it so we
    can parse it and return the article.

    Returns None if the article is smaller than min_words_count.
    """

    try:
        response = get_page(url)
    except Exception as err:
        update_log.error('Error in get_page()')
        update_log.error(err)
        return None

    if response is not None:
        article = ArticleParser(url="http://something")
        article.html = response.content
        article.download_state = 2

        try:
            article.parse()
        except Exception as err:
            update_log.error('Error in article.parse()')
            update_log.error(err)
            return None
        else:
            add_url_to_blacklist(url)
            if len(article.text.split(' ')) >= min_words_count:
                return article

    return None

def get_articles_from_topics(topics):
    """ This is where it all starts. Scrapes articles from all URLS fount in
    the topics. Edits them and saves them to the database.
    """

    update_log.info('Testing connection.')
    test_connection()

    update_log.info('Looking for latest articles.')

    articles_urls = get_urls()

    if len(articles_urls) > 0:
        for topic_name, url_list in articles_urls.items():
            update_log.info('Fount {} new URLs to scrape for: {}'.format(
                len(url_list), topic_name))
            for url, lang in url_list:
                try:
                    article = Article.objects.get(source=url)
                    update_log.warning('Article allready exists: {}'.format(
                        article.original_title))
                except ObjectDoesNotExist:
                    article_parsed = parse_article(url)
                    if article_parsed is not None:
                        try:
                            new_article = Article.objects.create(
                                source=url,
                                topic_id=int(topics[topic_name]),
                                original_title=article_parsed.title,
                                original_text=article_parsed.text,
                                original_language=lang
                            )
                        except IntegrityError as err:
                            update_log.error('Error in saving new article.')
                            update_log.error(err)
                            continue
                        else:
                            update_log.info('Saved new article: {}'.format(
                                article_parsed.title))
                            article_editor.edit_article(new_article)
                else:
                    if article.status != READY:
                        article_editor.edit_article(new_article)

    update_log.info('Finished scraping.')

    return None


from tkinter import *
from PIL import ImageTk, Image

'''alt+B to start program in Sublime
'''

'''This program assists me in understanding Game Theory Optimal solutions for Spin N Gos: 3-handed hyper turbos.
'''

'''Heads up nash equilibrium solutions 10- bbs'''
def display_nash():

	global nash
	nash = var6.get()

	if nash == "NASHJAM":
		imagenash = "C:/Python3.8/Spins/NASHJAM.png"
	elif nash == "NASHCALL":
		imagenash = "C:/Python3.8/Spins/NASHCALL.png"

	file = ImageTk.PhotoImage(Image.open(imagenash))
	label = Label(image=file)
	label.image = file
	label.grid(row=5, columnspan=6, pady=50)

'''show images from folder'''
def display_img():
	global actn
	actn = var4.get()

	if pos == "SB":
		image = '_'.join([ply,pos,bb])
	elif pos == "BBvsBTN":
		image = '_'.join([ply,pos,bb, "raise"])
	else:
		image = '_'.join([ply,pos,bb,actn])

	imagefile = "C:/Python3.8/Spins/" + image + ".png"

	file = ImageTk.PhotoImage(Image.open(imagefile))
	label = Label(image=file)
	label.image = file
	label.grid(row=5, columnspan=6, pady=50)

	var6.set(0)

'''response to villain: raise or limped pot?'''
def display_rspns():
	for i in r4:
		r4[i].grid_remove()
		var4.set(0)

	global bb
	bb = var3.get()

	if pos == "SB":
		values4 = {}
		display_img()
		return
	elif pos == "BBvsBTN":
		values4 = {}
		display_img()
		return
	else:
		values4 = {"raise" : "raise", "limp" : "limp"}

	count = 0

	label_4 = Label(root, text="Response?", width=10,font=("bold", 10))
	label_4.grid(row=4,column=count)
	for (t,v) in values4.items():
		count += 1
		r4[count] = Radiobutton(root, text=t, variable=var4, value=v, indicator=0, background="light blue", command=display_img)
		r4[count].grid(row=4, column=count, sticky=W)

'''Show number of effective big blinds'''
def display_bb():

	for i in r3:
		r3[i].grid_remove()
		var3.set(0)

	for i in r4:
		r4[i].grid_remove()
		var4.set(0)

	global pos
	pos = var2.get()

	if ply == "HU" and pos == "SB":
		values3 = {"9-11bb" : "9-11bb", "11-13bb" : "11-13bb", "13-17bb" : "13-17bb"}
	elif ply == "HU" and pos == "BB":
		values3 = {"11-13bb" : "11-13bb", "13-17bb" : "13-17bb"}
	elif ply == "3H" and pos == "SB":
		values3 = {"12-14bb" : "12-14bb", "14-17bb" : "14-17bb", "17-22bb" : "17-22bb", "22-25bb" : "22-25bb"}
	elif ply == "3H" and pos == "BB":
		values3 = {"10-12bb" : "10-12bb", "12-14bb" : "12-14bb", "14-17bb" : "14-17bb", "17-21bb" : "17-21bb", "21-25bb" : "21-25bb"}
	elif ply == "3H" and pos == "BBvsBTN":
		values3 = {"11-14bb" : "11-14bb", "14-17bb" : "14-17bb", "17-21bb" : "17-21bb", "21-25bb" : "21-25bb"}

	count = 0

	label_3 = Label(root, text="BBs?", width=10,font=("bold", 10))
	label_3.grid(row=3,column=count)
	for (t,v) in values3.items():
		count += 1
		r3[count] = Radiobutton(root, text=t, variable=var3, value=v, indicator=0, background="light blue", command=display_rspns)
		r3[count].grid(row=3, column=count, sticky=W)

'''Positions: Small Blind, Big Blind, Button'''
def display_pstn():

	for i in r2:
		r2[i].grid_remove()
		var2.set(0)

	for i in r3:
		r3[i].grid_remove()
		var3.set(0)

	for i in r4:
		r4[i].grid_remove()
		var4.set(0)

	global ply
	ply = var.get()

	if ply == "HU":
		values2 = {"SB" : "SB", "BB" : "BB"}
	else:
		values2 = {"SB" : "SB", "BB" : "BB", "BBvsBTN" : "BBvsBTN"}

	count = 0

	label_2 = Label(root, text="Position?",width=10,font=("bold", 10))
	label_2.grid(row=2, column=count)
	for (t, v) in values2.items():
		count += 1
		r2[count] = Radiobutton(root, text=t, variable=var2, value=v, indicator=0, background="light blue", command=display_bb)
		r2[count].grid(row=2, column=count, sticky=W)

'''initialize'''
root = Tk()
root.geometry('640x710')
root.title("Jackpot SitNGos")

r2 = dict()
r3 = dict()
r4 = dict()
var = StringVar()
var2 = StringVar()
var3 = StringVar()
var4 = StringVar()

var6 = StringVar()
global file

values = {"2" : "HU", "3" : "3H"}
count = 0

label_1 = Label(root, text="Players?",width=10,font=("bold", 10))
label_1.grid(row=1, column=count)

label_6 = Label(root, text="NASH?",width=10,font=("bold", 10))
label_6.grid(row=6, column=count)
Radiobutton(root, text="NASH JAM", variable=var6, value="NASHJAM", indicator=0, background="pink", command=display_nash).grid(row=6, column=1, sticky=W)
Radiobutton(root, text="NASH CALL", variable=var6, value="NASHCALL", indicator=0, background="pink", command=display_nash).grid(row=6, column=2, sticky=W)

for (t, v) in values.items():
	count += 1
	Radiobutton(root, text=t, variable=var, value=v, indicator=0, background="light blue", command=display_pstn).grid(row=1, column=count, sticky=W)

root.mainloop()


def solution(s):
    answer = []
    t = s[2:-2].split('},{')
    t.sort(key = len)
    for i in t:
        for j in i.split(','):
            if int(j) not in answer:
                answer.append(int(j))
    return answer


import cv2
import numpy as np
from PIL import Image
import stepic
import random
from math import ceil, floor
from Crypto.Cipher import AES
import binascii
import image_slicer
# Temporary.. Need to consolidate all the common functions in a single file
import multi_text_receiver
import Image_on_image as ioi

def main():
	cap = cv2.VideoCapture('output.avi')
	# input_hash = raw_input('Enter the key for your data: ')
	# index = int(multi_text_receiver.decodeIndexHash(binascii.unhexlify(input_hash))) # <- Index at which our data is hidden
	index = 155
	frameCount = cap.get(cv2.CAP_PROP_FRAME_COUNT)
	frames = getAllFrames(cap)
	secret_img = extract(frames, index)
	secret_img.save('secret.png')

def getAllFrames(cap):
	frames = []
	while True:
		ret, temp = cap.read()
		if not ret:
			break
		frames += [temp]
	return frames

def reassemble_image(t, slice_size = (73,73), rows = 2, cols = 2):
    tiles = [] # The tiles of the image to be assembled
    number = 0
    for j in range(0,rows):
        for i in range(0,cols):
            coord_x = i*slice_size[0]
            coord_y = j*slice_size[1]
            coords = (coord_x, coord_y)
            position = (i+1,j+1)
            tile = image_slicer.Tile(t[number], number, position, coords)
            tiles.append(tile)
            number+=1
    res = image_slicer.join(tuple(tiles))
    return res

def extract(frames, index):
	img = Image.fromarray(frames[index])
	indexData = stepic.decode(img).decode()
	indexData = indexData.split('.')
	metaData = indexData[0].split(';')
	secret_img_size = (int(metaData[0]), int(metaData[1]))
	noOfTiles = int(metaData[2])
	slice_size = (int(metaData[3]), int(metaData[4]))
	t = []
	for i in indexData[1:len(indexData)-1]:
		temp = frames[int(i)]
		# Image.fromarray(temp).save('recvd'+i+'.png')
		res = ioi.extract_image(Image.fromarray(temp)).resize((slice_size[0], slice_size[1]))
		t.append(res)
	extracted_image = reassemble_image(t, slice_size, secret_img_size[0]/slice_size[0], secret_img_size[1]/slice_size[1])
	return extracted_image

if __name__ == '__main__':
	main()


import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt

#Angehangenes Gewicht
Masse = 1900

#Kraft auf den Stab
f=Masse*9.81

# Datenfile erzeugen
Abstand, mit_Gewicht, ohne_Gewicht = np.genfromtxt('Einseitig_Eckig.txt',unpack=True)

Abstand /=1000

#Durchbiegung des Stabes
durchbiegung = mit_Gewicht - ohne_Gewicht

durchbiegung /= 1000

print ('Ausschlag ohne Gewicht', ohne_Gewicht)

print('')
print('Ausschlag mit Gewicht', mit_Gewicht)

print('')
print ('Durchbiegung: ', durchbiegung)

print('')
print (Abstand)

def EModul(L, x):
	return (L*(x**2)-x**3/3)

#erstellt Ausgleichsgerade
def func(m, x, b):
	return  m * x + b

#dies dient zum testen der curve_fit Funktion
BspEM = EModul(0.51 ,Abstand)

parameters, pcov = curve_fit(func, durchbiegung, BspEM)

print('')
print ('L*x**2-x**3/3: ', BspEM)

d=0
for x in Abstand:
	print(d)
	print('Abstand: ',Abstand[d],' Auslenkung o Ge: ', ohne_Gewicht[d], ' Auslenkung m Ge: ',  mit_Gewicht[d], ' Differenz m-o: ', durchbiegung[d], ' f(x): ', BspEM[d] )
	d +=1

print('')
print (parameters)
#plt.errorbar(durchbiegung, BspEM, xerr=0.1, yerr=0.01, fmt='x')
plt.plot(durchbiegung, BspEM, 'x')
plt.plot(durchbiegung, func(durchbiegung, *parameters))
plt.xlabel(r'Durchbiegung in [1/m]')
plt.ylabel(r'Lx² - x³/3in [1/m]')
plt.show()


import jieba
import os
data = []   #存。txt文件名
for files in os.listdir("./"): #读取当前文件夹。txt文件名
    if os.path.splitext(files)[1] == '.txt':
        data.append(files)
words = []  #存放词汇
for index in data :
    txt = open(index,'r',encoding='utf-8').read()
    words += jieba.lcut(txt) #解析词汇，并存入
counts = {} #存放词汇出现次数
for word in words:
    if len(word) == 1:
        continue
    else:
        counts[word] = counts.get(word,0)+1 #遍历所有词汇，每出现一次架+1

items = list(counts.items())
items.sort(key=lambda x:x[1],reverse=True) #根据词语出现的次数从大到小排序
result = {}
for i in range(100):
    word,count = items[i]
    result[word] = count

with open("result.txt","w") as f:
    f.write(str(result))


'''
valid parenthesis
Given a string containing just the characters '(', ')', '{', '}',
'[' and ']', determine if the input string is valid.

An input string is valid if:

Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
https://leetcode.com/problems/valid-parentheses/description/
'''

class Solution(object):
    def isValid(self, s):

        valid = {')': '(', ']': '[', '}': '{'}

        stack = []

        for c in s:
            if c in valid:
                top_element = stack.pop() if stack else '#'
                if top_element != valid[c]:
                    return False
            else:
                stack.append(c)

        return not stack


# =================================================================
# =                  Author: Brad Heffernan                       =
# =================================================================

import os
import distro
import sys
import shutil
import psutil
import datetime
# import time
import subprocess
import threading  # noqa
import gi
# import configparser
gi.require_version('Gtk', '3.0')
from gi.repository import GLib, Gtk  # noqa

distr = distro.id()

sudo_username = os.getlogin()
home = "/home/" + str(sudo_username)

sddm_default = "/etc/sddm.conf"
sddm_default_original = "/usr/local/share/arcolinux/sddm/sddm.conf"

sddm_default_d1 = "/etc/sddm.conf"
sddm_default_d2 = "/etc/sddm.conf.d/kde_settings.conf"
sddm_default_d2_dir = "/etc/sddm.conf.d/"
sddm_default_d_sddm_original_1 = "/usr/local/share/arcolinux/sddm.conf.d/sddm.conf"
sddm_default_d_sddm_original_2 = "/usr/local/share/arcolinux/sddm.conf.d/kde_settings.conf"

if os.path.exists("/etc/sddm.conf.d/kde_settings.conf"):
    sddm_conf = "/etc/sddm.conf.d/kde_settings.conf"
else:
    sddm_conf = "/etc/sddm.conf"

arcolinux_mirrorlist = "/etc/pacman.d/arcolinux-mirrorlist"
arcolinux_mirrorlist_original = "/usr/local/share/arcolinux/arcolinux-mirrorlist"
pacman = "/etc/pacman.conf"
pacman_arco ="/usr/share/arcolinux-tweak-tool/data/arco/pacman.conf"
pacman_eos ="/usr/share/arcolinux-tweak-tool/data/eos/pacman.conf"
pacman_garuda ="/usr/share/arcolinux-tweak-tool/data/garuda/pacman.conf"
blank_pacman_arco ="/usr/share/arcolinux-tweak-tool/data/arco/blank/pacman.conf"
blank_pacman_eos ="/usr/share/arcolinux-tweak-tool/data/eos/blank/pacman.conf"
blank_pacman_garuda ="/usr/share/arcolinux-tweak-tool/data/garuda/blank/pacman.conf"
oblogout_conf = "/etc/oblogout.conf"
# oblogout_conf = home + "/oblogout.conf"
gtk3_settings = home + "/.config/gtk-3.0/settings.ini"
gtk2_settings = home + "/.gtkrc-2.0"
grub_theme_conf = "/boot/grub/themes/Vimix/theme.txt"
xfce_config = home + "/.config/xfce4/xfconf/xfce-perchannel-xml/xsettings.xml"
slimlock_conf = "/etc/slim.conf"
termite_config = home + "/.config/termite/config"
neofetch_config = home + "/.config/neofetch/config.conf"
lightdm_conf = "/etc/lightdm/lightdm.conf"
bd = ".att_backups"
config = home + "/.config/arcolinux-tweak-tool/settings.ini"
config_dir = home + "/.config/arcolinux-tweak-tool/"
polybar = home + "/.config/polybar/"
desktop = ""
autostart = home + "/.config/autostart/"
zsh_config = ""
fish_config = ""
if os.path.isfile(home + "/.config/fish/config.fish"):
    fish_config = home + "/.config/fish/config.fish"
if os.path.isfile(home + "/.zshrc"):
    zsh_config = home + "/.zshrc"
bash_config = ""
if os.path.isfile(home + "/.bashrc"):
    bash_config = home + "/.bashrc"
account_list = ["Standard","Administrator"]
i3wm_config = home + "/.config/i3/config"
awesome_config = home + "/.config/awesome/rc.lua"
qtile_config = home + "/.config/qtile/config.py"

seedhostmirror = "Server = https://ant.seedhost.eu/arcolinux/$repo/$arch"
aarnetmirror = "Server = https://mirror.aarnet.edu.au/pub/arcolinux/$repo/$arch"

atestrepo = "[arcolinux_repo_testing]\n\
SigLevel = Required DatabaseOptional\n\
Include = /etc/pacman.d/arcolinux-mirrorlist"

arepo = "[arcolinux_repo]\n\
SigLevel = Required DatabaseOptional\n\
Include = /etc/pacman.d/arcolinux-mirrorlist"

a3drepo = "[arcolinux_repo_3party]\n\
SigLevel = Required DatabaseOptional\n\
Include = /etc/pacman.d/arcolinux-mirrorlist"

axlrepo = "[arcolinux_repo_xlarge]\n\
SigLevel = Required DatabaseOptional\n\
Include = /etc/pacman.d/arcolinux-mirrorlist"

chaotics_repo = "[chaotic-aur]\n\
SigLevel = Required DatabaseOptional\n\
Include = /etc/pacman.d/chaotic-mirrorlist"

endeavouros_repo = "[endeavouros]\n\
SigLevel = PackageRequired\n\
Include = /etc/pacman.d/endeavouros-mirrorlist"

nemesis_repo = "[nemesis_repo]\n\
SigLevel = Optional TrustedOnly\n\
Server = https://erikdubois.github.io/$repo/$arch"

arch_testing_repo = "[testing]\n\
Include = /etc/pacman.d/mirrorlist"

arch_core_repo = "[core]\n\
Include = /etc/pacman.d/mirrorlist"

arch_extra_repo = "[extra]\n\
Include = /etc/pacman.d/mirrorlist"

arch_community_testing_repo = "[community-testing]\n\
Include = /etc/pacman.d/mirrorlist"

arch_community_repo = "[community]\n\
Include = /etc/pacman.d/mirrorlist"

arch_multilib_testing_repo = "[multilib-testing]\n\
Include = /etc/pacman.d/mirrorlist"

arch_multilib_repo = "[multilib]\n\
Include = /etc/pacman.d/mirrorlist"

# =====================================================
#               Create log file
# =====================================================

log_dir="/var/log/arcolinux/"
att_log_dir="/var/log/arcolinux/att/"

def create_log(self):
    print('Making log in /var/log/arcolinux')
    now = datetime.datetime.now()
    time = now.strftime("%Y-%m-%d-%H-%M-%S" )
    destination = att_log_dir + 'att-log-' + time
    command = 'sudo pacman -Q > ' + destination
    subprocess.call(command,
                    shell=True,
                    stdout=subprocess.PIPE,
                    stderr=subprocess.STDOUT)
    #GLib.idle_add(show_in_app_notification, self, "Log file created")

# =====================================================
#               NOTIFICATIONS
# =====================================================

def show_in_app_notification(self, message):
    if self.timeout_id is not None:
        GLib.source_remove(self.timeout_id)
        self.timeout_id = None

    self.notification_label.set_markup("" +
                                       message + "")
    self.notification_revealer.set_reveal_child(True)
    self.timeout_id = GLib.timeout_add(3000, timeOut, self)

def timeOut(self):
    close_in_app_notification(self)

def close_in_app_notification(self):
    self.notification_revealer.set_reveal_child(False)
    GLib.source_remove(self.timeout_id)
    self.timeout_id = None

# =====================================================
#               PERMISSIONS
# =====================================================

def test(dst):
    for root, dirs, filesr in os.walk(dst):
        # print(root)
        for folder in dirs:
            pass
            # print(dst + "/" + folder)
            for file in filesr:
                pass
                # print(dst + "/" + folder + "/" + file)
        for file in filesr:
            pass
            # print(dst + "/" + file)

def permissions(dst):
    try:
        # original_umask = os.umask(0)
        # calls = subprocess.run(["sh", "-c", "cat /etc/passwd | grep " +
        #                         sudo_username],
        #                        shell=False,
        #                        stdout=subprocess.PIPE,
        #                        stderr=subprocess.STDOUT)
        groups = subprocess.run(["sh", "-c", "id " +
                                 sudo_username],
                                shell=False,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.STDOUT)
        for x in groups.stdout.decode().split(" "):
            if "gid" in x:
                g = x.split("(")[1]
                group = g.replace(")", "").strip()
        # print(group)
        # name = calls.stdout.decode().split(":")[0].strip()
        # group = calls.stdout.decode().split(":")[4].strip()

        subprocess.call(["chown", "-R",
                         sudo_username + ":" + group, dst], shell=False)

    except Exception as e:
        print(e)
# =====================================================
#               COPY FUNCTION
# =====================================================

def copy_func(src, dst, isdir=False):
    if isdir:
        subprocess.run(["cp", "-Rp", src, dst], shell=False)
    else:
        subprocess.run(["cp", "-p", src, dst], shell=False)
    # permissions(dst)

# =====================================================
#               SOURCE
# =====================================================

def source_shell(self):
    process = subprocess.run(["sh", "-c", "echo \"$SHELL\""],
                             stdout=subprocess.PIPE)

    output = process.stdout.decode().strip()
    print(output)
    if output == "/bin/bash":
        subprocess.run(["bash", "-c", "su - " + sudo_username +
                        " -c \"source " + home + "/.bashrc\""],
                       stdout=subprocess.PIPE)
    elif output == "/bin/zsh":
        subprocess.run(["zsh", "-c", "su - " + sudo_username +
                        " -c \"source " + home + "/.zshrc\""],
                       stdout=subprocess.PIPE)
    elif output == "/usr/bin/fish":
        subprocess.run(["fish", "-c", "su - " + sudo_username +
                        " -c \"source " + home + "/.config/fish/config.fish\""],
                       stdout=subprocess.PIPE)

def get_shell():
    process = subprocess.run(["su", "-", sudo_username,"-c","echo \"$SHELL\""],
                             #shell=False,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.STDOUT)

    output = process.stdout.decode().strip().strip('\n')
    if output == "/bin/bash" or output == "/usr/bin/bash":
        return "bash"
    elif output == "/bin/zsh" or output == "/usr/bin/zsh":
        return "zsh"
    elif output == "/bin/fish" or output == "/usr/bin/fish":
        return "fish"

def run_as_user(script):
    subprocess.call(["su - " + sudo_username + " -c " + script], shell=False)

# =====================================================
#               MESSAGEBOX
# =====================================================

def MessageBox(self, title, message):
    md2 = Gtk.MessageDialog(parent=self,
                            flags=0,
                            message_type=Gtk.MessageType.INFO,
                            buttons=Gtk.ButtonsType.OK,
                            text=title)
    md2.format_secondary_markup(message)
    md2.run()
    md2.destroy()

# =====================================================
#               CONVERT COLOR
# =====================================================

def rgb_to_hex(rgb):
    if "rgb" in rgb:
        rgb = rgb.replace("rgb(", "").replace(")", "")
        vals = rgb.split(",")
        return "#{0:02x}{1:02x}{2:02x}".format(clamp(int(vals[0])),
                                               clamp(int(vals[1])),
                                               clamp(int(vals[2])))
    return rgb

def clamp(x):
    return max(0, min(x, 255))

# =====================================================
#               GLOBAL FUNCTIONS
# =====================================================

def _get_position(lists, value):
    data = [string for string in lists if value in string]
    position = lists.index(data[0])
    return position

def _get_positions(lists, value):
    data = [string for string in lists if value in string]
    position = []
    for d in data:
        position.append(lists.index(d))
    return position

def _get_variable(lists, value):
    data = [string for string in lists if value in string]

    if len(data) >= 1:

        data1 = [string for string in data if "#" in string]

        for i in data1:
            if i[:4].find('#') != -1:
                data.remove(i)
    if data:
        data_clean = [data[0].strip('\n').replace(" ", "")][0].split("=")
    return data_clean

# Check  value exists

def check_value(list, value):
    data = [string for string in list if value in string]
    if len(data) >= 1:
        data1 = [string for string in data if "#" in string]
        for i in data1:
            if i[:4].find('#') != -1:
                data.remove(i)
    return data

def check_backups(now):
    if not os.path.exists(home + "/" + bd + "/Backup-" +
                          now.strftime("%Y-%m-%d %H")):
        os.makedirs(home + "/" + bd + "/Backup-" +
                    now.strftime("%Y-%m-%d %H"), 0o777)
        permissions(home + "/" + bd + "/Backup-" + now.strftime("%Y-%m-%d %H"))

# =====================================================
#               Check if File Exists
# =====================================================

def file_check(file):
    if os.path.isfile(file):
        return True

    return False

def path_check(path):
    if os.path.isdir(path):
        return True

    return False

# =====================================================
#               GTK3 CONF
# =====================================================

def gtk_check_value(my_list, value):
    data = [string for string in my_list if value in string]
    if len(data) >= 1:
        data1 = [string for string in data if "#" in string]
        for i in data1:
            if i[:4].find('#') != -1:
                data.remove(i)
    return data

def gtk_get_position(my_list, value):
    data = [string for string in my_list if value in string]
    position = my_list.index(data[0])
    return position

# =====================================================
#               OBLOGOUT CONF
# =====================================================
# Get shortcuts index

def get_shortcuts(conflist):
    sortcuts = _get_variable(conflist, "shortcuts")
    shortcuts_index = _get_position(conflist, sortcuts[0])
    return int(shortcuts_index)

# Get commands index

def get_commands(conflist):
    commands = _get_variable(conflist, "commands")
    commands_index = _get_position(conflist, commands[0])
    return int(commands_index)

# =====================================================
#               LIGHTDM CONF
# =====================================================

def check_lightdm_value(list, value):
    data = [string for string in list if value in string]
    # if len(data) >= 1:
    #     data1 = [string for string in data if "#" in string]

    return data

# =====================================================
#               SDDM CONF
# =====================================================

def check_sddm_value(list, value):
    data = [string for string in list if value in string]
    return data

# =====================================================
#               HBLOCK CONF
# =====================================================

def hblock_get_state(self):
    lines = int(subprocess.check_output('wc -l /etc/hosts',
                                        shell=True).strip().split()[0])
    if os.path.exists("/usr/local/bin/hblock") and lines > 100:
        return True

    self.firstrun = False
    return False

def do_pulse(data, prog):
    prog.pulse()
    return True

def set_hblock(self, toggle, state):
    GLib.idle_add(toggle.set_sensitive, False)
    GLib.idle_add(self.label7.set_text, "Run..")
    GLib.idle_add(self.progress.set_fraction, 0.2)

    timeout_id = None
    timeout_id = GLib.timeout_add(100, do_pulse, None, self.progress)

    if not os.path.isfile("/etc/hosts.bak.att"):
            shutil.copy("/etc/hosts", "/etc/hosts.bak.att")

    try:

        install = 'pacman -S arcolinux-hblock-git --needed --noconfirm'
        enable = "/usr/local/bin/hblock"

        if state:
            if os.path.exists("/usr/local/bin/hblock"):
                GLib.idle_add(self.label7.set_text, "Database update...")
                subprocess.call([enable],
                                shell=False,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.STDOUT)
            else:
                GLib.idle_add(self.label7.set_text, "Install Hblock......")
                subprocess.call(install.split(" "),
                                shell=False,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.STDOUT)
                GLib.idle_add(self.label7.set_text, "Database update...")
                subprocess.call([enable],
                                shell=False,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.STDOUT)

        else:
            GLib.idle_add(self.label7.set_text, "Remove update...")
            subprocess.run(["sh", "-c",
                            "HBLOCK_SOURCES=\'\' /usr/local/bin/hblock"],
                           shell=False,
                           stdout=subprocess.PIPE,
                           stderr=subprocess.STDOUT)

        GLib.idle_add(self.label7.set_text, "Complete")
        GLib.source_remove(timeout_id)
        timeout_id = None
        GLib.idle_add(self.progress.set_fraction, 0)

        GLib.idle_add(toggle.set_sensitive, True)
        if state:
            GLib.idle_add(self.label7.set_text, "HBlock Active")
        else:
            GLib.idle_add(self.label7.set_text, "HBlock Inactive")

    except Exception as e:
        MessageBox(self, "ERROR!!", str(e))
        print(e)

# =====================================================
#               UBLOCK ORIGIN
# =====================================================

def ublock_get_state(self):
    if os.path.exists("/usr/lib/firefox/browser/extensions/uBlock0@raymondhill.net.xpi"):
        return True
    return False

def set_firefox_ublock(self, toggle, state):
    GLib.idle_add(toggle.set_sensitive, False)
    GLib.idle_add(self.label7.set_text, "Run..")
    GLib.idle_add(self.progress.set_fraction, 0.2)

    timeout_id = None
    timeout_id = GLib.timeout_add(100, do_pulse, None, self.progress)

    try:

        install_ublock = "pacman -S firefox-ublock-origin --needed --noconfirm"
        uninstall_ublock = 'pacman -Rs firefox-ublock-origin --noconfirm'

        if state:
            GLib.idle_add(self.label7.set_text, "Installing ublock Origin...")
            subprocess.call(install_ublock.split(" "),
                            shell=False,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.STDOUT)
        else:
            GLib.idle_add(self.label7.set_text, "Removing ublock Origin...")
            subprocess.call(uninstall_ublock.split(" "),
                            shell=False,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.STDOUT)

        GLib.idle_add(self.label7.set_text, "Complete")
        GLib.source_remove(timeout_id)
        timeout_id = None
        GLib.idle_add(self.progress.set_fraction, 0)

        GLib.idle_add(toggle.set_sensitive, True)
        if state:
            GLib.idle_add(self.label7.set_text, "uBlock Origin installed")
        else:
            GLib.idle_add(self.label7.set_text, "uBlock Origin removed")

    except Exception as e:
        MessageBox(self, "ERROR!!", str(e))
        print(e)

# =====================================================
#               ALACRITTY
# =====================================================

def install_alacritty(self):
    install = 'pacman -S alacritty --needed --noconfirm'

    if os.path.exists("/usr/bin/alacritty"):
        pass
    else:
        subprocess.call(install.split(" "),
                        shell=False,
                        stdout=subprocess.PIPE,
                        stderr=subprocess.STDOUT)

# =====================================================
#               ZSH + PACKAGES (ARCOLINUXD)
# =====================================================

def install_zsh(self):
    install = 'pacman -S zsh zsh-completions zsh-syntax-highlighting arcolinux-zsh-git oh-my-zsh-git --needed --noconfirm'

    if os.path.exists("/usr/bin/zsh") and os.path.exists("/etc/skel/.zshrc") :
        pass
    else:
        subprocess.call(install.split(" "),
                        shell=False,
                        stdout=subprocess.PIPE,
                        stderr=subprocess.STDOUT)

# =====================================================
#               FISH + PACKAGES (ARCOLINUXD)
# =====================================================

def install_fish(self):
    install = 'pacman -S fish arcolinux-fish-git --needed --noconfirm'

    if os.path.exists("/usr/bin/fish") and os.path.exists("/etc/skel/.config/fish/config.fish") :
        pass
    else:
        subprocess.call(install.split(" "),
                        shell=False,
                        stdout=subprocess.PIPE,
                        stderr=subprocess.STDOUT)

def remove_fish(self):
    install = 'pacman -Rs fish --noconfirm'

    if not os.path.exists("/usr/bin/fish") :
        pass
    else:
        subprocess.call(install.split(" "),
                        shell=False,
                        stdout=subprocess.PIPE,
                        stderr=subprocess.STDOUT)

# =====================================================
#               ARCOLINUX-DESKTOP-TRASHER
# =====================================================

def install_adt(self):
    install = 'pacman -S arcolinux-desktop-trasher-git --noconfirm'

    if os.path.exists("/usr/local/bin/arcolinux-desktop-trasher"):
        pass
    else:
        subprocess.call(install.split(" "),
                        shell=False,
                        stdout=subprocess.PIPE,
                        stderr=subprocess.STDOUT)

# =====================================================
#               GRUB CONF
# =====================================================

def get_grub_wallpapers():
    if os.path.isdir("/boot/grub/themes/Vimix"):
        lists = os.listdir("/boot/grub/themes/Vimix")

        rems = ['select_e.png', 'terminal_box_se.png', 'select_c.png',
                'terminal_box_c.png', 'terminal_box_s.png',
                'select_w.png', 'terminal_box_nw.png',
                'terminal_box_w.png', 'terminal_box_ne.png',
                'terminal_box_sw.png', 'terminal_box_n.png',
                'terminal_box_e.png']

        ext = ['.png', '.jpeg', '.jpg']

        new_list = [x for x in lists if x not in rems for y in ext if y in x]

        new_list.sort()
        return new_list

def set_grub_wallpaper(self, image):
    if os.path.isfile(grub_theme_conf):
        if not os.path.isfile(grub_theme_conf + ".bak"):
            shutil.copy(grub_theme_conf, grub_theme_conf + ".bak")
        try:
            with open(grub_theme_conf, "r") as f:
                lists = f.readlines()
                f.close()

            val = _get_position(lists, "desktop-image: ")
            lists[val] = "desktop-image: \"" + os.path.basename(image) + "\"" + "\n"

            with open(grub_theme_conf, "w") as f:
                f.writelines(lists)
                f.close()

            show_in_app_notification(self, "Settings Saved Successfully")
            # MessageBox(self, "Success!!", "Settings Saved Successfully")
        except:  # noqa
            pass

# =====================================================
#               NEOFETCH CONF
# =====================================================

def neofetch_set_value(lists, pos, text, state):
    if state:
        if text in lists[pos]:
            if "#" in lists[pos]:
                lists[pos] = lists[pos].replace("#", "")
    else:
        if text in lists[pos]:
            if "#" not in lists[pos]:
                lists[pos] = "#" + lists[pos]

    return lists

def neofetch_set_backend_value(lists, pos, text, value):
    if text in lists[pos] and "#" not in lists[pos]:
        lists[pos] = text + value + "\"\n"

# ====================================================================
#                       CUSTOM FUNCTION
# ====================================================================

def get_desktop(self):
    base_dir = os.path.dirname(os.path.realpath(__file__))

    desktop = subprocess.run(["sh", base_dir + "/get_desktop.sh", "-n"],
                             shell=False,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.STDOUT)
    dsk = desktop.stdout.decode().strip().split("\n")
    self.desktop = dsk[-1].strip()

def copytree(self, src, dst, symlinks=False, ignore=None):  # noqa

    if not os.path.exists(dst):
        os.makedirs(dst)
    for item in os.listdir(src):
        s = os.path.join(src, item)
        d = os.path.join(dst, item)
        if os.path.exists(d):
            try:
                shutil.rmtree(d)
            except Exception as e:
                print(e)
                os.unlink(d)
        if os.path.isdir(s):
            try:
                shutil.copytree(s, d, symlinks, ignore)
            except Exception as e:
                print(e)
                print("ERROR2")
                self.ecode = 1
        else:
            try:
                shutil.copy2(s, d)
            except:  # noqa
                print("ERROR3")
                self.ecode = 1

# =====================================================
#               CHECK RUNNING PROCESS
# =====================================================

def checkIfProcessRunning(processName):
    for proc in psutil.process_iter():
        try:
            pinfo = proc.as_dict(attrs=['pid', 'name', 'create_time'])
            if processName == pinfo['pid']:
                return True
        except (psutil.NoSuchProcess,
                psutil.AccessDenied,
                psutil.ZombieProcess):
            pass
    return False

def restart_program():
    python = sys.executable
    os.execl(python, python, *sys.argv)


# -*- coding: utf-8 -*-
"""
Created on Wed Dec 15 20:16:22 2021

@author: sandr
"""

import socket

"""
accept() - aceita a conexao
bind(endereco) - associa o socket servidor a um endereco
close() - fecha o socket
connect(endereco) - conecta um cliente a um endereco
listen() - comeca a escutar
recv(tamanho do pacote) - receber a mensagem
"""

#https://docs.python.org/pt-br/3.8/howto/sockets.html

HOST = 'localhost' #127.0.0.1
PORTA = 50000

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# FAMILIA DE ENDERECOS: AF_INET - endereco IPv4 / AF_INET6 - enedereco IPv6
# TIPO DE SOCKET: SOCK_STREAM - para socket TCP / SOCK_DGRAM - para socket UDP

s.bind((HOST, PORTA))
s.listen()

print("Aguardando um cliente se conectar...")

conectado, endereco = s.accept()

print("Conectado no endereco:", endereco)

while True:
    dados = conectado.recv(1024)
    if not dados:
        print("Conexao fechada")
        conectado.close()
        break
    conectado.sendall(dados)


import cv2
import numpy as np

from google.cloud import vision_v1p3beta1 as vision
from google.oauth2 import service_account

credentials = service_account.Credentials.from_service_account_file('./google-api-credential.json')
client = vision.ImageAnnotatorClient(credentials=credentials)

def get_image_entity(image):
    if isinstance(image, str):
        image_entity = vision.types.Image()
        image_entity.source.image_uri = image
    elif isinstance(image, np.ndarray):
        cv2.imwrite('temp.jpg', image)
        with open('temp.jpg', 'rb') as file:
            image_content = file.read()
        image_entity = vision.types.Image(content=image_content)
    else:
        raise Exception('No parser found')
    return image_entity

def get_text_annotations(image_entity, is_handwritten=False):
    if is_handwritten:
        context = vision.types.ImageContext(language_hints=['en-t-i0-handwrit'])
        response = client.document_text_detection(image=image_entity, image_context=context)
    else:
        response = client.document_text_detection(image=image_entity)
    return response.text_annotations


import numpy as np
from typing import Union, Iterable

from linkeddeepdict import LinkedDeepDict
from neumann import atleast1d

from .problem import NavierProblem
from .loads import LoadGroup, NavierLoadError
from .preproc import lhs_Navier, rhs_Bernoulli
from .postproc import postproc
from .proc import linsolve_Bernoulli, linsolve_Timoshenko

class NavierBeam(NavierProblem):
    """
    A class to handle simply-supported plates and their solution
    using Navier's approach.

    Parameters
    ----------
    length : float
        The length of the beam.
    N : int, Optional
        The number of harmonic terms involved in the approximation.
        Default is 100.
    EI : float
        Bending stiffness. Default is None.
    GA : float, Optional
        Shear stiffness. Only for Timoshenko beams. Default is None.

    Examples
    --------
    To define an Euler-Bernoulli beam of length 10.0 and
    bending stiffness 2000.0 with 100 harmonic terms involved:

    >>> from sigmaepsilon.fourier import NavierBeam
    >>> beam = NavierBeam(10.0, 100, EI=2000.0)

    To define a Timoshenko beam of length 10.0, bending stiffness
    2000.0 and shear stiffness 1500.0 with 100 harmonic terms involved:

    >>> from sigmaepsilon.fourier import NavierBeam
    >>> beam = NavierBeam(10.0, 100, EI=2000.0, GA=1500.0)

    """

    def __init__(
        self, length: float, N: int = 100, *, EI: float = None, GA: float = None
    ):
        super().__init__()
        self.length = length
        self.EI = EI
        self.GA = GA
        self.N = N

    def solve(
        self, loads: Union[dict, LoadGroup], points: Union[float, Iterable]
    ) -> LinkedDeepDict:
        """
        Solves the problem and calculates all postprocessing quantities at
        one ore more points.

        Parameters
        ----------
        loads : Union[dict, LoadGroup]
            The loads. If it is an array, it should be a 2d float array.
        points : float or Iterable
            A float or an 1d iterable of coordinates, where the results are
            to be evaluated. If it is a scalar, the resulting dictionary
            contains 1d arrays for every quantity, for every load case. If
            there are multiple points, the result attached to a load case is
            a 2d array, where the first axis goes along the points.

        Returns
        -------
        LinkedDeepDict
            A nested dictionary with a same layout as the input.
        """
        # STIFFNESS
        LHS = lhs_Navier(self.length, self.N, D=self.EI, S=self.GA)

        # LOADS
        if isinstance(loads, LoadGroup):
            _loads = loads
        elif isinstance(loads, dict):
            _loads = LoadGroup.from_dict(loads)
        else:
            raise NavierLoadError()
        _loads.problem = self
        LC = list(_loads.cases())
        RHS = np.vstack(list(lc.rhs() for lc in LC))

        # SOLUTION
        if self.GA is None:
            _RHS = rhs_Bernoulli(RHS, self.length)
            coeffs = linsolve_Bernoulli(LHS, _RHS)
            del _RHS
            # (nLHS, nRHS, nMN)
        else:
            coeffs = linsolve_Timoshenko(LHS, RHS)
            # (nLHS, nRHS, nMN, 2)

        # POSTPROCESSING
        points = atleast1d(points)
        res = postproc(self.length, self.N, points, coeffs, RHS, self.EI, self.GA)
        # (nLHS, nRHS, nP, nX)
        result = LinkedDeepDict()
        for i, lc in enumerate(LC):
            result[lc.address] = res[0, i, :, :]
        result.lock()
        return result


# Two Sum -- https://leetcode.com/problems/two-sum/
"""
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.
"""

class Solution(object):
        def twoSum(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
            """
            sub_targets = []
            sol = []

            for val_ind in range(0, len(nums)):
                #print(f"Index-{val_ind} Value-{nums[val_ind]}")
                val = nums[val_ind]

                # if val is already larger than target, skip current iter of loop
                if val >= target:
                   continue
                #if val is possible candidate, append to list of lists with mappings to iter through
                elif val < target:
                    sub_targets.append([val, val_ind])

            # Check sub_targets for possible solution
            for lst in sub_targets:
                val_1 = lst[0]
                for lst2 in sub_targets:
                    val_2 = lst2[0]
                    if val_1 == val_2:
                        break
                    elif val_1 + val_2 == target:
                        sol.append([lst[1], lst2[1]])
                        print("Possible Solutions are:", sol)
                        break

# test case
test_list = [2,7,11,15]
test_target = 9

# Run Above
if __name__ == '__main__':
    Solution.twoSum(Solution, nums=test_list, target=test_target)


# Arquivo de apoio ao Main.py com as classes que são importadas.
# Classe herdada Entrevistado.
class Entrevistado:
    def __init__(self, idade, genero):
        self.idade = idade
        self.genero = genero

# Classe herdeira Questoes.
class Questoes(Entrevistado):
    def __init__(self, idade, genero, q1, q2, q3, q4, dataehora):
        super().__init__(idade, genero)
        self.q1 = q1
        self.q2 = q2
        self.q3 = q3
        self.q4 = q4
        self.dataehora = dataehora


"""
Este modelo entrena una red de capas densas
"""

# %%
import tensorflow as tf
import gym
from tensorflow import keras
from keras.callbacks import TensorBoard
from Generacion_Partidas import PartidasRandom
from keras.utils import to_categorical
from concurrent.futures import ProcessPoolExecutor
import numpy as np
from time import time

def BuildModel(input_size, outputs = 2):
    model = keras.Sequential([
        keras.layers.Dense(32, activation=tf.nn.relu, input_shape = (input_size, )),
        keras.layers.Dropout(0.2),
        keras.layers.Dense(64, activation=tf.nn.relu),
        keras.layers.Dropout(0.2),
        keras.layers.Dense(128, activation=tf.nn.relu),
        keras.layers.Dropout(0.2),
        keras.layers.Dense(64, activation=tf.nn.relu),
        keras.layers.Dropout(0.2),
        keras.layers.Dense(32, activation=tf.nn.relu),
        keras.layers.Dropout(0.2),
        keras.layers.Dense(outputs, activation=tf.nn.softmax)
    ])

    model.compile(optimizer=tf.train.AdamOptimizer(),
                  loss='categorical_crossentropy',
                  metrics = ["accuracy"])

    return model

def TrainModel(training_data):

    obs = np.array([obs for data in partidas_train for obs in data["observations"]])
    mov = np.array([obs for data in partidas_train for obs in data["movimientos"]])
    mov = to_categorical(mov)

    # if not model:
    #     print("Starting a new model")
    #     model = BuildModel(input_size = 4)

    # tensorboard = TensorBoard(log_dir="logs/{}".format(time())) # tensorboard --logdir=logs

    model.fit(obs, mov,
              epochs = 50,
              batch_size = 128,
              callbacks=[])

    return model

partidas_train = PartidasRandom(num_partidas = 5000000, score_minimo = 180)

model = TrainModel(partidas_train)

model.save("./models/test1")

def PlayModel(model):
    env = gym.make('CartPole-v0')
    record = 0
    for _ in range(100):
        done = False
        observation = env.reset()
        env.render()
        current_points = 0
        for i in range(500):
            action = np.argmax(model.predict(observation.reshape((1,4))))
            # if action==1:
            #     action = 0
            # else:
            #     action = 1
            observation, reward, done, info = env.step(action)
            current_points += 1
            env.render()

            if done:
                if current_points > record:
                    print(f"Record with {current_points}")
                    record = current_points
                break