#! /usr/bin/env python3
# transfer .pdg to pdf

import sys
import zipfile
from PIL import Image
import os
import shutil
import fitz
from nipype.interfaces.io import glob

def pdg2pdf(pdgfile:zipfile.ZipFile, target: str):
    # extract all .pdg file
    for file in pdgfile.namelist():
        if file[-4:] == ".pdg":
            pdgfile.extract(file, "temp")
    pdgfile.close()
    toc:list[str] = []
    content:list[str] = []
    cov1:str = ''
    cov2:str = ''
    bok:list[str] = []
    fow:list[str] = []
    leg:list[str] = []
    # file_path is the path of .pdg file

    file_path = "temp/"
    if os.path.isdir("temp/" + os.listdir(file_path)[0]):
        file_path = os.path.join('temp/', os.listdir('temp')[0])
        file_path+='/'

    for file in os.listdir(file_path):
        if file.endswith('.pdg'):
            if file.startswith('!'):
                toc.append(file)
            elif file.startswith('fow'):
                fow.append(file)
            elif file.startswith('leg'):
                leg.append(file)
            elif file == 'cov001.pdg':
                cov1 = 'cov001.pdg'
            elif file == 'cov002.pdg':
                cov2  = 'cov002.pdg'
            elif file.startswith('bok'):
                bok.append(file)
            else:
                content.append(file)
    content.sort()
    fow.sort()
    leg.sort()
    toc.sort()
    image_path_list:list[str] = []
    image_list:list[Image.Image] = []

    if cov1 != '':
        image_path_list.append(file_path + cov1)
        image_list.append(Image.open(file_path + cov1))

    for b in bok:
        image_path_list.append(file_path + b)
        image_list.append(Image.open(file_path + b))

    for l in leg:
        image_path_list.append(file_path + l)
        image_list.append(Image.open(file_path + l))

    for f in fow:
        image_path_list.append(file_path + f)
        image_list.append(Image.open(file_path + f))

    for t in toc:
        image_path_list.append(file_path + t)
        image_list.append(Image.open(file_path + t))

    for c in content:
        image_path_list.append(file_path + c)
        image_list.append(Image.open(file_path + c))

    if cov2 != '':
        image_path_list.append(file_path + cov2)
        image_list.append(Image.open(file_path + cov2))

    doc = fitz.open()
    length = len(image_path_list)
    now = 0
    for img in image_path_list:
        now += 1
        print("\rProcessing: " + str(now) + "/" + str(length) + "    " + "{:.2f}".format(now / length * 100) + "%", end="")
        imgdoc = fitz.open(img, filetype="png")
        pdfbytes = imgdoc.convert_to_pdf()
        imgpdf = fitz.open("pdf", pdfbytes)
        doc.insert_pdf(imgpdf)
    doc.save(target)
    doc.close()

    # image_list[0].save(target, "PDF", save_all=True, append_images=image_list[1:])

    # delele all temp file
    shutil.rmtree("temp")
def main():
    param:list[str] = sys.argv
    if len(param) != 3:
        print("Usage: python pdg2pdf.py filename output.pdf")
        return
    file_path:str = param[1]
    if file_path[-4:] != ".zip":
        print("Usage: Input FileType must be .zip")
        return
    pdgfile:zipfile.ZipFile = zipfile.ZipFile(file_path)
    pdg2pdf(pdgfile, param[2])

if __name__ == '__main__':
    main()


import markdown
import sys
import os
import pycmarkgfm
from configparser import ConfigParser
import copy
import shutil

default_vars = {}

def build_file(path: str):
    print(f"Processing {path}")
    markdown_text = ""
    replacements = copy.copy(default_vars)

    template = "$CONTENT$"

    with open(path, "r") as f:
        for line in f:
            if line.startswith("$$"):
                key = line[line.find("$$") + 2 : line.find(" ")]
                value = line[line.find(" ") + 1:-1]
                print(f"{key}: {value}")
                replacements[key] = value

            elif line.startswith("&&"):
                value = line[line.find("&&") + 2:-1]
                value = os.path.join("./private/templates", value)
                print(f"Wants template: {value}")
                if os.path.exists(value):
                    template_file = open(value, "r")
                    template = template_file.read()
                    template_file.close()
            else:
                markdown_text += line

    #html_text = markdown.markdown(markdown_text, extensions=[GithubFlavoredMarkdownExtension()])
    html_text = pycmarkgfm.gfm_to_html(markdown_text)
    template = template.replace("$CONTENT$", html_text)

    for replacement in replacements:
        template = template.replace(f"${replacement}$", replacements[replacement])

    this_path = os.getcwd()
    out_path = os.path.relpath(path, "./private")
    out_path = os.path.join(".", out_path)
    out_path = out_path.replace(".article", ".html")

    print(f"Out: {out_path}")

    os.makedirs(os.path.dirname(out_path), exist_ok=True)

    file_out = open(out_path, "w")
    file_out.write(template)
    file_out.close()

KEEP_DIRS = [
    "private",
    ".vscode",
    "img",
    ".git",
    "default.css",
    "styles.css",
    ".gitignore",
    "requirements.txt",
    ".venv"
]

if __name__ == "__main__":
    config = ConfigParser()
    config.read("private/defaults.ini")

    for option in config.options("DEFAULTS"):
        default_vars[option.upper()] = config.get("DEFAULTS", option)

    for file in os.listdir("."):
        if file not in KEEP_DIRS:
            delete_path = os.path.join('.', file)
            print(f"Deleting {delete_path}")
            if os.path.isdir(delete_path):
                shutil.rmtree(delete_path)
            else:
                os.remove(delete_path)

    for dirpath, dirnames, filenames in os.walk("private/"):
        for filename in filenames:
            path = os.path.join(dirpath, filename)

            fname = os.path.basename(path)

            if ".article" in path and not fname.startswith("-"):
                build_file(path)


from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals

from apitools.base.py import list_pager

from googlecloudsdk.api_lib.util import apis
from googlecloudsdk.api_lib.util import waiter

class Client(object):
  """API client for Cloud Domains operations."""

  def __init__(self, client, messages=None):
    self.client = client
    self._service = self.client.projects_locations_operations
    self.messages = messages or client.MESSAGES_MODULE

  @classmethod
  def FromApiVersion(cls, version):
    return cls(apis.GetClientInstance('domains', version))

  def Get(self, operation_ref):
    request = self.messages.DomainsProjectsLocationsOperationsGetRequest(
        name=operation_ref.RelativeName())
    return self._service.Get(request)

  def List(self, parent_ref, limit=None, page_size=None, list_filter=None):
    request = self.messages.DomainsProjectsLocationsOperationsListRequest(
        name=parent_ref.RelativeName(),
        filter=list_filter)
    return list_pager.YieldFromList(
        self._service,
        request,
        batch_size=page_size,
        limit=limit,
        field='operations',
        batch_size_attribute='pageSize')

  def WaitForOperation(self, operation_ref, message):
    return waiter.WaitFor(
        waiter.CloudOperationPollerNoResources(self._service),
        operation_ref,
        message,
        wait_ceiling_ms=15 * 1000)


class Computer:

    def __init__(self,name,cpu,gpu,mb,ssd,psu,ram):
        self.name = name
        self.cpu = cpu
        self.gpu = gpu
        self.mb  = mb
        self.ssd = ssd
        self.psu = psu
        self.ram = ram

    def _reportSpecs(self):
        print("=====================")
        print(f"{self.name} มี SpecsComputer ดังนี้ \nCPU : {self.cpu} \nGPU : {self.gpu} \nMB  : {self.mb} \nSSD : {self.ssd}GB \nPSU : {self.psu} \nRAM : {self.ram}GB")
        print("=====================")

class Game(Computer):
    def _re4remake(self):
        print(f"คอมสเปคนี้สามารถเล่น RE4remake ได้ไหม")
        print("เล่นได้") if self.ram >= 8 else print("ไม่สามารถเล่นได้")
        print("-------------------")

    def _stardew(self):
        print("คอมสเปคนี้สามารถเล่น Stardew valley ได้ไหม")
        print("เล่นได้") if self.ram >= 8 else print("ไม่สามารถเล่นได้")
        print("-------------------")

    def _ow2(self):
        print("คอมสเปคนี้สามารถเล่น Overwatch2 ได้ไหม")
        print("เล่นได้") if self.ram >= 8 else print("ไม่สามารถเล่นได้")
        print("-------------------")

obj1 = Game("แดง","Intel i3-10105f","GTX1050","Auros B356",250,'550W',16)
obj1._reportSpecs()
obj1._re4remake()
obj1._ow2()

obj2 = Game("เขียว", "AMD Ryzen 5 5600", "Radeon rx 570","Auros B550",500,'550W',32)
obj2._reportSpecs()
obj2._ow2()
obj2._stardew()


import os
import librosa
import numpy as np
import python_speech_features
import argparse
from os.path import join
from glob import glob
from tqdm import tqdm
import moviepy.editor as mp

parser = argparse.ArgumentParser()
parser.add_argument("--person", type=str, default='M003')
parser.add_argument("--mead_feature_path", type=str, default='/root/Datasets/Features')
parser.add_argument("--extract_mfcc", type=bool, default=False)
parser.add_argument("--extract_mfcc13", type=bool, default=True)

if __name__ == '__main__':
    args = parser.parse_args()
    audio_folder = join(args.mead_feature_path, args.person, "audios")
    filelist = sorted(glob(join(audio_folder, '**/*.wav'), recursive=True))

    if args.extract_mfcc:
        for idx, filename in tqdm(enumerate(filelist)):
            outputPath = filename.replace('audios','mfcc')[:-4]
            os.makedirs(outputPath, exist_ok=True)

            speech, sr = librosa.load(filename, sr=16000)
            print(len(speech))
            speech = np.insert(speech, 0, np.zeros(1920))
            speech = np.append(speech, np.zeros(1920))
            mfcc = python_speech_features.mfcc(speech,16000,winstep=0.01)

            time_len = mfcc.shape[0]
            print(mfcc.shape)
            for input_idx in range(int((time_len-28)/4)+1):
                input_feat = mfcc[4*input_idx:4*input_idx+28,:]
                np.save(join(outputPath, f'{input_idx+1:05d}.npy'), input_feat)
            break

    if args.extract_mfcc13:
        for idx, filename in tqdm(enumerate(filelist)):
            outputPath = filename.replace('audios','mfcc')[:-4]
            os.makedirs(outputPath, exist_ok=True)

            imagePath = outputPath.replace('mfcc', 'images')
            num_frames = len(os.listdir(imagePath))

            audio_signal, sr = librosa.load(filename, sr=16000)
            hop_length = int(sr/ 30)

            check = 1
            while(check):
                features = librosa.feature.mfcc(audio_signal, sr, n_mfcc=13, hop_length= hop_length, n_fft = 1200)
                features = features.T
                if features.shape[0] == num_frames:
                    check = 0
                    for input_idx in range(num_frames):
                        np.save(join(outputPath, f'{input_idx+1:05d}.npy'), features[input_idx])
                else:
                    if features.shape[0] > num_frames:
                        hop_length += 1
                    else:
                        hop_length -= 1


from pathlib import Path
import click
from typing import Union
from get_pop.definitions import CWD
from get_pop.get_pop import get_pop
from get_pop.static.constants import state_index
import os
import sys

clean_states = [x["abbrv"] for x in state_index] + ["all"]

@click.command()
@click.argument("states", nargs=-1, type=click.Choice(clean_states))
@click.option(
    "--save-dir",
    "-d",
    default=CWD,
    help="Path of directory where CSV files will be output. Defaults to saving in the current "
    "working directory",
)
@click.option(
    "--quiet",
    "-q",
    is_flag=True,
    default=False,
    help="Disables stdout during program run",
)
def main(states: tuple, save_dir: Union[str, Path], quiet: bool) -> None:
    """
    CLI API using click library. Generates CSVs of county-level state data based on
    provided arguments.

    Args:
        states (tuple): Tuple of one or more two-letter state abbreviations. Click takes a user's input
            from the command line and stores it as a tuple.
        save_dir (Union[str, Path]): (Optional) Path to directory where CSVs will be saved. Defaults to saving them in
            the current working directory

    Returns:
        None
    """
    if quiet:
        f = open(os.devnull, "w")
        sys.stdout = f

    states_list = list(states)  # convert from tuple to list
    get_pop(states_list, save_dir=save_dir)


import pygame
import random

# definindo constantes
BLOCK_SIZE = 30
BOARD_WIDTH = 10
BOARD_HEIGHT = 20
SCREEN_WIDTH = BLOCK_SIZE * (BOARD_WIDTH + 6)
SCREEN_HEIGHT = BLOCK_SIZE * BOARD_HEIGHT

# definindo cores
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
YELLOW = (255, 255, 0)

# peças possíveis
SHAPES = [
    [[1, 1],
     [1, 1]],
    [[0, 2, 0],
     [2, 2, 2]],
    [[0, 3, 3],
     [3, 3, 0]],
    [[4, 4, 0],
     [0, 4, 4]],
    [[0, 5, 0],
     [5, 5, 5]],
    [[6, 6, 6, 6]]
]

# cores das peças
COLORS = [
    WHITE,
    BLUE,
    GREEN,
    YELLOW,
    RED,
    (128, 0, 128)  # roxo
]

# classe para as peças
class Piece:
    def __init__(self, shape, color):
        self.shape = shape
        self.color = color
        self.x = BOARD_WIDTH // 2 - len(shape[0]) // 2
        self.y = 0

    # gira a peça
    def rotate(self):
        self.shape = [[self.shape[j][i] for j in range(len(self.shape))] for i in range(len(self.shape[0]) - 1, -1, -1)]

    # move a peça para baixo
    def move_down(self):
        self.y += 1

    # move a peça para a esquerda
    def move_left(self):
        self.x -= 1

    # move a peça para a direita
    def move_right(self):
        self.x += 1
    # move a peça pra cima
    def move_up(self):
        self.y -= 1

# classe para o jogo
class Tetris:
    def __init__(self):
        # inicializa o pygame
        pygame.init()

        # configura a janela
        self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
        pygame.display.set_caption("Tetris")

        # inicializa o relógio
        self.clock = pygame.time.Clock()

        # inicializa o tabuleiro
        self.board = [[0] * BOARD_WIDTH for _ in range(BOARD_HEIGHT)]

        # inicializa as peças
        self.piece = None
        self.next_piece = None
        self.new_piece()

        # inicializa a pontuação
        self.score = 0

    # cria uma nova peça
    def new_piece(self):
        self.piece = self.next_piece or Piece(random.choice(SHAPES), random.choice(COLORS))
        self.next_piece = Piece(random.choice(SHAPES), random.choice(COLORS))

     # verifica se uma posição é válida
    def is_valid_position(self, x, y, shape):
        for i in range(len(shape)):
            for j in range(len(shape[0])):
                if shape[i][j] != 0:
                    if not (0 <= x + j < BOARD_WIDTH and 0 <= y + i < BOARD_HEIGHT and self.board[y + i][x + j] == 0):
                        return False
        return True

    # insere uma peça no tabuleiro
    def place_piece(self):
        for i in range(len(self.piece.shape)):
            for j in range(len(self.piece.shape[0])):
                if self.piece.shape[i][j] != 0:
                    self.board[self.piece.y + i][self.piece.x + j] = self.piece.color

    # remove as linhas completas
    def remove_lines(self):
        num_lines_removed = 0
        for i in range(BOARD_HEIGHT):
            if all(self.board[i]):
                num_lines_removed += 1
                del self.board[i]
                self.board.insert(0, [0] * BOARD_WIDTH)
        self.score += num_lines_removed ** 2

    # atualiza o jogo
    def update(self):
        # move a peça para baixo
        self.piece.move_down()
        if not self.is_valid_position(self.piece.x, self.piece.y, self.piece.shape):
            # se a posição não é válida, a peça não pode se mover mais
            self.piece.move_up()
            self.place_piece()
            self.remove_lines()
            self.new_piece()
            if not self.is_valid_position(self.piece.x, self.piece.y, self.piece.shape):
                # se a nova peça já ocupa uma posição inválida, o jogo acaba
                pygame.quit()
                quit()

    # desenha o tabuleiro
    def draw_board(self):
        for i in range(BOARD_HEIGHT):
            for j in range(BOARD_WIDTH):
                pygame.draw.rect(self.screen, self.board[i][j], (j * BLOCK_SIZE, i * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0)

    # desenha uma peça
    def draw_piece(self, piece):
        for i in range(len(piece.shape)):
            for j in range(len(piece.shape[0])):
                if piece.shape[i][j] != 0:
                    pygame.draw.rect(self.screen, piece.color, ((piece.x + j) * BLOCK_SIZE, (piece.y + i) * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0)

    # desenha a próxima peça
    def draw_next_piece(self, piece):
        font = pygame.font.SysFont(None, 30)
        text = font.render("Próxima peça:", True, WHITE)
        self.screen.blit(text, (SCREEN_WIDTH - BLOCK_SIZE * 6, BLOCK_SIZE))
        for i in range(len(piece.shape)):
            for j in range(len(piece.shape[0])):
                if piece.shape[i][j] != 0:
                    pygame.draw.rect(self.screen, piece.color, ((SCREEN_WIDTH - BLOCK_SIZE * 5) + j * BLOCK_SIZE, BLOCK_SIZE * (2 + i), BLOCK_SIZE, BLOCK_SIZE), 0)

    # desenha a pontuação
    def draw_score(self):
        font = pygame.font.SysFont(None, 30)
        text = font.render("Pontuação: {}".format(self.score), True, WHITE)
        self.screen.blit(text, (SCREEN_WIDTH - BLOCK_SIZE * 6, SCREEN_HEIGHT - BLOCK_SIZE))

    # executa o jogo
    def run(self):
        while True:
            # verifica os eventos
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    quit()
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_LEFT:
                        self.piece.move_left()
                        if not self.is_valid_position(self.piece.x, self.piece.y, self.piece.shape):
                            self.piece.move_right()
                    elif event.key == pygame.K_RIGHT:
                        self.piece.move_right()
                        if not self.is_valid_position(self.piece.x, self.piece.y, self.piece.shape):
                            self.piece.move_left()
                    elif event.key == pygame.K_UP:
                        self.piece.rotate()
                        if not self.is_valid_position(self.piece.x, self.piece.y, self.piece.shape):
                            self.piece.rotate_back()
                    elif event.key == pygame.K_DOWN:
                        self.piece.move_down()
                        if not self.is_valid_position(self.piece.x, self.piece.y, self.piece.shape):
                            self.piece.move_up()
            # atualiza o jogo
            self.update()
            # desenha a tela
            self.screen.fill(BLACK)
            self.draw_board()
            self.draw_piece(self.piece)
            self.draw_next_piece(self.next_piece)
            self.draw_score()
            pygame.display.update()
            # espera um pouco antes de atualizar novamente
            pygame.time.delay(100)

if __name__ == "__main__":
    game = Tetris()
    game.run()


# oxit staff serializer
import traceback

from django.contrib.auth.models import User, Group
from django.db import transaction
from rest_framework import serializers
from rest_framework.validators import UniqueValidator
from rest_framework.exceptions import ValidationError

from management.serializers.GeneralSerializer import PageSerializer, SelectSerializer
from pms.models import Profile

class StaffSerializer(serializers.Serializer):
    uuid = serializers.UUIDField(read_only=True)
    firstName = serializers.CharField()
    lastName = serializers.CharField()
    mobilePhone = serializers.CharField()
    email = serializers.CharField()
    group = SelectSerializer(read_only=True)
    groupId = serializers.IntegerField(write_only=True, allow_null=True)
    address = serializers.CharField()

    def update(self, instance, validated_data):
        try:
            with transaction.atomic():

                user = instance.user
                user.first_name = validated_data.get('firstName')
                user.last_name = validated_data.get('lastName')
                user.email = validated_data.get('email')
                user.username = validated_data.get('email')
                user.groups.clear()
                user.groups.add(Group.objects.get(id=validated_data.get('groupId')))
                user.save()
                instance.mobilePhone = validated_data.get('mobilePhone')
                instance.address = validated_data.get('address')
                instance.save()

                return instance

        except Exception as e:
            traceback.print_exc()
            raise ValidationError("lütfen tekrar deneyiniz")

    def create(self, validated_data):
        try:
            with transaction.atomic():
                user = User.objects.create_user(username=validated_data.get('email'), email=validated_data.get('email'))
                user.first_name = validated_data.get('firstName')
                user.last_name = validated_data.get('lastName')
                user.set_password('oxit2016')
                y = validated_data.get('groupId')
                user.groups.add(y)
                user.save()
                profile = Profile.objects.create(user=user)
                profile.mobilePhone = validated_data.get('mobilePhone')
                profile.address = validated_data.get('address')
                profile.save()
                return profile

        except Exception as e:
            traceback.print_exc()
            raise ValidationError("lütfen tekrar deneyiniz")

    def validate_email(self, email):

        user = None
        if self.instance is not None:

            user = Profile.objects.get(uuid=self.context['request'].query_params['id']).user

            if User.objects.exclude(id=user.id).filter(username=email).count() > 0:
                raise serializers.ValidationError("Bu email sistemde kayıtlıdır")

        else:

            # if isinstance(list(self.context)[0], str):
            #     user = Profile.objects.get(uuid=list(self.context)[1].query_params['id']).user
            # else:
            #     user = Profile.objects.get(uuid=list(self.context)[0].query_params['id']).user
            if User.objects.filter(username=email).count() > 0:
                raise serializers.ValidationError("Bu email sistemde kayıtlıdır")
        return email

class StaffPageableSerializer(PageSerializer):
    data = StaffSerializer(many=True)

    def update(self, instance, validated_data):
        pass

    def create(self, validated_data):
        pass


import tkinter as tk
import os
import subprocess, sys
import ctypes, sys
import shlex
import tkinter.scrolledtext
import re
from tkinter import Tk

""""
########################################################################
TEST TEST TEST
########################################################################
"""

""""
########################################################################
#TEST TEST TEST
########################################################################
"""

class IORedirector(object):
    '''A general class for redirecting I/O to this Text widget.'''
    def __init__(self,text_area):
        self.text_area = text_area

class StdoutRedirector(IORedirector):
    '''A class for redirecting stdout to this Text widget.'''
    def write(self,str):
        self.text_area.write(str,False)

########################################################################
#TEST TEST TEST
########################################################################
"""

class RedirectText(object):
    """"""
    #----------------------------------------------------------------------
    def __init__(self, text_ctrl):

        self.output = text_ctrl

    #----------------------------------------------------------------------
    def write(self, string):
        """"""
        self.output.insert(tkinter.END, string)

"""
"""This Asks for Admin Rights, Which will be needed to run some of the commands"""

def is_admin():
    try:
        return ctypes.windll.shell32.IsUserAnAdmin()
    except:
        return False

if is_admin():
    print("we are admin")
else:
    # Re-run the program with admin rights
    ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)

"""Setting up the directory paths to use later on"""

parentDirectory = "C:\\Users\\Public\\"
directory = "ScriptsForPython"

fullDirectory = parentDirectory + directory
searchPath = fullDirectory + "\\SearchForUsers.ps1"
passwordResetPath = fullDirectory + "\\PasswordReset.ps1"

""" If path does not exist, then create it """

if not os.path.exists(fullDirectory):
    os.mkdir(fullDirectory)
else:
    print("The Directory Already Exists, WELCOME BACK :)")

#####################################################################################################

"""This is where I start building the forms"""

class SysAdminHelper(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        ##self = Tk()
        ##self.wm_iconbitmap(False, '/Resources/hrc.png')
        ##self.iconphoto(False, tk.PhotoImage(file='hrc.png'))
        ##self.iconbitmap('/hrc.ico')
        ##self.tk.call('wm', 'iconphoto', self._w, tk.PhotoImage(file='/Resources/hrc.png'))
        ##self.iconphoto(False, 'hrc.ico')
        ##self.iconbitmap("hrc.ico")
        self.iconbitmap(r'C:\PythonResources\hrc.ico')
        ##img = self.PhotoImage(file='hrc.ico')
        ##self.tk.call('wm', 'iconphoto', self._w, img)

        self.title("Making Workflow Easier :)")
        self.geometry("800x480")
        self._frame = None
        self.switch_frame(StartPage)

    def switch_frame(self, frame_class):
        """Destroys current frame and replaces it with a new one."""
        new_frame = frame_class(self)
        if self._frame is not None:
            self._frame.destroy()
        self._frame = new_frame
        self._frame.pack()

  #####################################################################################################

""" This is my Home page, I am creating all the navigation buttons that will take you to the corresponding page"""
class StartPage(tk.Frame):

    def __init__(self,master):
        """   this is the "main frame from tkinter """
        tk.Frame.__init__(self,master)
        """this is the label on the front page"""
        tk.Label(self, text="What Can I Do For You?").pack(side="top", fill="x", pady=10)
        """Where I start defining my buttons"""
        nmapBtn = tk.Button(self, text="Search with Nmap",
                    command=lambda: master.switch_frame(NmapPage))
        passwordBtn = tk.Button(self, text="Reset User's Password",
                    command=lambda: master.switch_frame(PasswordPage))
        systemInfoBtn = tk.Button(self, text = "Run sysinfo on a machine",
                    command=lambda: master.switch_frame(systemInfoPage))
        toDoBtn = tk.Button(self, text = "To Do List",
                    command=lambda: exec(open("ToDoList.py").read()))

        """running a command to get public IP address, and assigning it a variable"""

        publicIP = subprocess.check_output('curl \"http://myexternalip.com/raw\"')
        privateIP = subprocess.check_output('ipconfig | findstr /i \"ipv4\" ', shell=True)
        length = len(privateIP)
        numericPrivateIP = " ".join(re.split("[^0-9. ]*", str(privateIP)))
        shorterIP = numericPrivateIP[length -14 :]
        shortestIP = shorterIP[14:]

        ipLbl = tk.Label(self, text="This is your public IP Address").pack()
        tk.Label(self, text=publicIP).pack()
        tk.Label(self, text="This is your private IP Address").pack()
        tk.Label(self, text=shortestIP.replace(" ", "")).pack()

        """this is where I put the buttons in order"""
        passwordBtn.pack()
        systemInfoBtn.pack()
        nmapBtn.pack()
        toDoBtn.pack()
#####################################################################################################

"""My Nmap Page"""
class NmapPage(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self,master)
        headerLbl = tk.Label(self, text="Alright, let's start searching the network!")
        searchBtn = tk.Button(self, text="Search")
        tk.Button(self, text="Go Home",
                    command=lambda: master.switch_frame(StartPage)).pack()

        headerLbl.pack(pady='5')
        searchBtn.pack(pady='5')

        myIp = subprocess.check_output('ipconfig | findstr /i \"ipv4\" ', shell=True)
        ipOutput = tk.Text(self)
        ipLabel = tk.Label(self, text="This is your current private IP Address")
        ipLabel.pack(pady='10')
        ipOutput.pack()
        ipOutput.insert(tk.END, myIp)

#####################################################################################################

"""Password Reset Page"""
class PasswordPage(tk.Frame):
    def __init__(self,master):
        tk.Frame.__init__(self,master)
        mainText = "Password Reset Page"
        font = "Helvetica 20 bold"
        mainLbl = tk.Label(self,
                            text = mainText,
                            bg = "blue",
                            font = font).pack()
        headerLbl = tk.Label(self, text="Uh oh.. someone forgot their password! \n That's Alright. I can fix that XD")
        instructionsLbl = tk.Label(self, text= "Click the \"Lookup\" button after entering the name of the person you are working with",  pady="50")
        lookupBtn = tk.Button(self, text = "Lookup",
                                command=lambda: master.switch_frame(LookupPage))
        homeBtn = tk.Button(self, text = "Go Home",
                                command=lambda: master.switch_frame(StartPage))

        """Arranging my buttons"""

        headerLbl.pack(pady='5')
        instructionsLbl.pack(pady='5')
        lookupBtn.pack(pady='5')
        homeBtn.pack(pady='5')

"""Inside Password Page, moving to the look up function"""
#####################################################################################################
class LookupPage(tk.Frame):
    def __init__(self, master):

        tk.Frame.__init__(self,master)
        mainText = "User Lookup"
        font= "Helvetica 20 bold"
        mainLbl = tk.Label(self,
                            text = mainText,
                            bg = "blue",
                            font = font).pack()
        headerLbl = tk.Label(self, text = "Type the name as close as you can \n If you aren't sure how to spell it just type the first few characters")
        self.lookupName = tk.Entry(self)
        homeBtn = tk.Button(self, text= "Go Home",
                            command=lambda: master.switch_frame(StartPage))
        submitBtn = tk.Button(self, text= "Submit",
                                command=self.on_button)
        ##scrollbar = tk.Scrollbar(self).pack(side="right", fill="y")

        headerLbl.pack(pady='5')
        self.lookupName.pack(pady='5')
        submitBtn.pack(pady='5')
        homeBtn.pack(pady='5')

    """assigning a variable for the inputted data"""
##---------------------------------------------------------------
    def on_button(self):
        userName = self.lookupName.get()
        print (userName)

        """using that variable (userName) to inject into PowerShell Command"""
##---------------------------------------------------------------
        with open(searchPath, "w") as file:
            file.write("$Name ='" + userName + "*'" + "\nGet-ADuser -Filter {name -like $Name} -Properties * | Select-Object name, samaccountname, emailaddress | Sort-Object samaccountname")

        """Calling PowerShell to open with the file that was just created"""
##---------------------------------------------------------------
        p1 = subprocess.check_output(['powershell.exe ', searchPath])
        ##stdout = p1.communicate()
        ##sys.stdout = StdoutRedirector(self)
        #write(stdout)
        self.text_box = tk.Text(self)
        self.text_box.pack()
        self.text_box.insert(tk.END, p1)
        #out_label = tk.Label("test").pack()

"""System Info Page"""
#####################################################################################################

class systemInfoPage(tk.Frame):

    def __init__(self,master):
        tk.Frame.__init__(self,master)
        mainText = "Run Systeminfo command on remote computer"
        font= "Helvetica 20 bold"
        mainLbl = tk.Label(self,
                            text = mainText,
                            bg = "blue",
                            font = font).pack(pady='5')

        tk.Label(self, text="What is the IP Address or Hostname of the machine you'd like a report on?").pack()

        """Creating a text input box to accept input from user and use later on"""
        ##---------------------------------------------------------------
        self.entry = tk.Entry(self)
        self.button = tk.Button(self, text="test Entry",
                    command=self.on_button)
        homeBtn = tk.Button(self, text="Go Home",
                            command=lambda: master.switch_frame(StartPage))

        self.entry.pack(pady='5')
        self.button.pack(pady='5')
        homeBtn.pack(pady='5')

    def on_button(self):
        sysInfoMachine = self.entry.get()
        print(sysInfoMachine)
        """i = 0
        while i < 1:
            sysinfoCmd = os.system('cmd /k "systeminfo"')
            i + 1
            break
"""
        ##### systeminfo /s computername for remote computer
        cmd = subprocess.check_output('systeminfo')
        self.output = tk.Text(self)
        self.output.pack()
        self.output.insert(tk.END, cmd)
        print(cmd)

if __name__ == "__main__":
    app = SysAdminHelper()
    app.mainloop()


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

from RailML import railML
from RailML.Common import Metadata
from RailML.Common import Common
from RailML.Infrastructure import Infrastructure
from RailML.Interlocking import Interlocking
from RailML import aRailML

from RNA import RNA
from ATA import ATA
from ATG import ATG
from ACG import ACG
from AGG import AGG
from tkinter import *

root = Tk()

root.title('Railway Network Analyzer')
root.geometry('500x450')
root.configure(bg='#DDDDDD')

frame1 = Label(root, bg='#DDDDDD')
frame1.pack()
frame3 = LabelFrame(frame1, text='Example', padx=40, pady=20)
frame2 = LabelFrame(frame1, text='Configuration', padx=40, pady=10)

slider = StringVar()
slider.set('300.00')

slider2 = StringVar()
slider2.set('300.00')

languages = ['Example_1', 'Example_2', 'Example_3', 'Example_4', 'Example_5', 'Example_6', 'Example_7', 'Example_8', 'Example_9']

n = StringVar(frame3)
n.set(languages[0])

Checkbutton1 = IntVar(value = 1)
Checkbutton2 = IntVar(value = 1)
Checkbutton3 = IntVar(value = 1)
Checkbutton4 = IntVar(value = 1)
Checkbutton5 = IntVar(value = 1)
Checkbutton6 = IntVar(value = 1)
Checkbutton7 = IntVar(value = 0)
Checkbutton8 = IntVar(value = 0)

var_r = StringVar()
var_r.set('')

var_l = StringVar()
var_l.set('')

r = Label(root, textvariable = var_r)
r.pack()

l = Label(frame3, textvariable = var_l)
l.grid (row = 2, column = 0)

option_menu = OptionMenu(frame3, n ,*languages)
slide_bar =  Scale(frame2, from_= 300, to =  500, orient = HORIZONTAL, label = 'Distance Lc-Ptf')
slide_bar2 =  Scale(frame2, from_= 200, to =  500, orient = HORIZONTAL, label = 'Max Track length')

slide_bar.set(300)
slide_bar2.set(200)

RML = railML.railML()

def callback(selection):
    print(n.get())

def launchSystem():
    #Label(root, text=f'Running RNA ... {Checkbutton1.get()}').pack()
    #Label(root, text=f'Running RNA ... ').pack()
    # Call RNA
    try:
        config = [Checkbutton1.get(),Checkbutton2.get(),Checkbutton3.get(),Checkbutton4.get(),Checkbutton5.get(),Checkbutton6.get(),Checkbutton7.get(),Checkbutton8.get(),slide_bar.get(),slide_bar2.get()]

        #print(n.get()[-1])

        INPUT_FILE= "C:\PhD\RailML\Layouts\\"+str(n.get())+"\\"+str(n.get())+".railml"
        OUTPUT_FILE= "C:\PhD\RailML\Layouts\\"+str(n.get())+"\\"+str(n.get())+"_B.railml"

        x = RNA.RNA(RML,INPUT_FILE,OUTPUT_FILE,False,True,config,int(n.get()[-1]))
        #Label(root, text=f'{x}').pack()
        var_r.set(f'Analysis for {n.get()} done > {x[1]}')
        var_l.set(x[0])
        #Label(root, text=f'Analysis done!').pack()
        # Call ACG
        try:
            ACG.ACG()
        except Exception as e:
            print(f'ACG had an error: {e}')
        # Call AGG
        try:
            AGG.AGG()
        except Exception as e:
            print(f'AGG had an error: {e}')
    except Exception as e:
        print(f'RNA had an error: {e}')

    # Call ATA
    try:
        ATA.ATA()
        # Call ATG
        try:
            ATG.ATG()
        except Exception as e:
            print(f'ATG had an error: {e}')
    except Exception as e:
        print(f'ATA had an error: {e}')

button = Button(frame2, text='no RNA!', state=DISABLED, padx=20, pady=5, command = launchSystem)

def isChecked():
    if (Checkbutton1.get() == 1 or Checkbutton2.get() == 1 or Checkbutton3.get() == 1 or Checkbutton4.get() == 1 or Checkbutton5.get() == 1 or Checkbutton6.get() == 1):
        button['state'] = NORMAL
        button.configure(text='Run RNA!',command = launchSystem)
    elif (Checkbutton1.get() == 0 and Checkbutton2.get() == 0 and Checkbutton3.get() == 0 and Checkbutton4.get() == 0 and Checkbutton5.get() == 0 and Checkbutton6.get() == 0):
        button['state'] = DISABLED
        button.configure(text='No RNA!',command = launchSystem)

def main():

    #root.withdraw()
    #root.geometry("500x300")
    frame3.pack(padx = 10 , pady = 10 , side = LEFT)

    #option_menu.pack()
    #label = Label(frame3, text='')

    option_menu.grid(row=1, column=0)
    slide_bar.pack()#grid(row=1, column=0)
    slide_bar2.pack()

    frame2.pack(padx = 10 , pady = 10 , side = RIGHT)

    Checkbutton(frame2, text="Analyze bufferStops", variable=Checkbutton1, onvalue=1, offvalue=0, command=isChecked).pack()
    Checkbutton(frame2, text="Analyze lineborders", variable=Checkbutton2, onvalue=1, offvalue=0, command=isChecked).pack()
    Checkbutton(frame2, text="Analyze railJoints", variable=Checkbutton3, onvalue=1, offvalue=0, command=isChecked).pack()
    Checkbutton(frame2, text="Analyze level crossings", variable=Checkbutton4, onvalue=1, offvalue=0, command=isChecked).pack()
    Checkbutton(frame2, text="Analyze platforms", variable=Checkbutton5, onvalue=1, offvalue=0, command=isChecked).pack()
    Checkbutton(frame2, text="Analyze switches", variable=Checkbutton6, onvalue=1, offvalue=0, command=isChecked).pack()
    Checkbutton(frame2, text="One direction only", variable=Checkbutton7, onvalue=1, offvalue=0, command=isChecked).pack()
    Checkbutton(frame2, text="Simplify signals", variable=Checkbutton8, onvalue=1, offvalue=0, command=isChecked).pack()

    button.pack()

    root.mainloop()

if __name__ == '__main__':
    main()


import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, mean_squared_error
from sklearn.model_selection import train_test_split

if __name__ == '__main__':
    customers = pd.read_csv('../data/ecommerce_customers.csv')
    toggle = False
    if toggle:
        print(customers.head())
        print(customers.info())
        print(customers.describe())

        plot1 = sns.jointplot(customers['Time on Website'], customers['Yearly Amount Spent'])
        plot1.savefig('../imgs/time_site_vs_yearly_spend.png')
        # Does this figure make sense? Not really, I'd expect positive linear relationship.

        plot2 = sns.jointplot(customers['Time on App'], customers['Yearly Amount Spent'])
        plot2.savefig('../imgs/time_app_vs_yearly_spend.png')
        # The app has a better positive linear relationship

        plot3 = sns.jointplot(customers['Time on App'], customers['Length of Membership'], kind='hex')
        plot3.savefig('../imgs/time_app_vs_len_member_hex.png')

        pairplot = sns.pairplot(customers)
        pairplot.savefig('../imgs/pairplot.png')
        # Based off this plot, length of membership looks to have the strongest correlation
        # weaker correlation between Time on App and Avg. Session Length

        lmplot = sns.lmplot(data=customers, x='Length of Membership', y='Yearly Amount Spent')
        lmplot.savefig('../imgs/lmplot.png')

    x_cols = ['Avg. Session Length', 'Time on App',
       'Time on Website', 'Length of Membership']
    y = customers['Yearly Amount Spent'].copy()
    X = customers[x_cols].copy()

    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.3, random_state=101)
    lm = LinearRegression()
    lm.fit(X_train, y_train)
    print(lm.coef_)
    # [25.98154972 38.59015875  0.19040528 61.27909654]
    y_pred = lm.predict(X_test)

    lm_results = sns.jointplot(y_test, y_pred)
    lm_results.set_axis_labels(xlabel='True Value', ylabel='Predicted Value')
    lm_results.savefig('../imgs/lm_results.png')

    mae = round(mean_absolute_error(y_test, y_pred), 2)
    mse = round(mean_squared_error(y_test, y_pred), 2)
    rmse = round(np.sqrt(mse), 2)

    print('Mean Absolute Error: ', mae)
    print('Mean Squared Error: ', mse)
    print('Root Mean Squared Error: ', rmse)

    '''
    Mean Absolute Error:  7.23
    Mean Squared Error:  79.81
    Root Mean Squared Error:  8.93
    '''
    residuals = y_test.values - y_pred
    residuals_plot = plt.hist(residuals, bins=35)
    #res_hist_plot.savefig('../imgs/residuals_hist_plot.png')

    coeffecients = pd.DataFrame(lm.coef_,X.columns)
    coeffecients.columns = ['Coeffecient']
    print(coeffecients)

    '''
                            Coeffecient
    Avg. Session Length     25.981550
    Time on App             38.590159
    Time on Website          0.190405
    Length of Membership    61.279097

    '''


class Solution:
    def maxJump(self, stones: List[int]) -> int:
        answer = stones[1] -stones[0]
        i = 0
        j = 2
        while j < len(stones):
            diff = stones[j] - stones[i]
            if answer < diff:
                answer = diff
            i += 1
            j += 1

        return answer


import copy
from Node import Node

def move_gen(node, num_bits, clauses):
    '''
        This function accepts a state and returns all the states
        that can be reached from the given state by changing num_bits.

        Arguments:
        ----------
            - node: node/state whose neighbours have to be found
            - num_bits: Number of bits to be changed
            - clauses: A list of clauses in the formula

        Returns:
        --------
            List of Valid neighbours/state which can be visited from
            the given state.
    '''
    neighbors = []

    # 1 bit to be changed
    if num_bits == 1:
        for i in range(len(node)):
            copy_node = copy.deepcopy(node)
            neighbors.append(Node(copy_node))
            # Changing the value of the ith bit
            neighbors[i].values[i] = neighbors[i].values[i] ^ 1
            # Calculate the number of clauses satisfied
            neighbors[i].e = evaluate_node(neighbors[i], clauses)

    # 2 bits to be changed
    if num_bits == 2:
        for i in range(len(node)):
            for j in range(i+1, len(node)):
                copy_node = copy.deepcopy(node)
                # Changing the value of ith and jth bit
                copy_node[i] = copy_node[i] ^ 1
                copy_node[j] = copy_node[j] ^ 1
                neighbors.append(Node(copy_node))
                # Calculate the number of clauses satisfied
                neighbors[-1].e = evaluate_node(neighbors[-1], clauses)

    # 3 bits to be changed
    if num_bits == 3:
        # Reversing all bits
        node = [literal ^ 1 for literal in node]
        for i in range(len(node)):
            copy_node = copy.deepcopy(node)
            neighbors.append(Node(copy_node))
            # Changing the ith bit
            neighbors[i].values[i] = neighbors[i].values[i] ^ 1
            # Calculate the number of clauses satisfied
            neighbors[i].e = evaluate_node(neighbors[i], clauses)

    # 4 bits to be changed
    if num_bits == 4:
        neighbor = []
        # Changing all bits
        for i in range(len(node)):
            neighbor.append(node[i]^1)
        neighbors.append(Node(neighbor))
        # Calculate the number of clauses satisfied
        neighbors[-1].e = evaluate_node(neighbors[-1], clauses)

    return neighbors

def evaluate_node(node, clauses):
    '''
        This function calculates the number of clauses satisfied.

        Arguments:
        ----------
            - node: The node whose value is to be evaluated.
            - clauses: A list of clauses in the formula

        Returns:
        --------
            The number of clauses statisfied.
    '''
    num_satisfied = 0           # Initialize statisfied clauses to 0

    # Calculate the value of each clause by taking OR of each literal
    for clause in clauses:
        result = 0
        for literal in clause:
            result = result | literal.calculate_value(node.values)

        # If satisfied then increment num_satisfied
        if result:
            num_satisfied += 1

    # Return the negative of num_satisfied to make it a minimization problem
    return -num_satisfied

def is_tautology(clause):
    '''
        This function checks whether a given clause is a tautology.
        The function checks whether the clause contains a variable
        and its negation.

        Arguments:
        ----------
            -clause: A list of Literals

        Returns:
        --------
            True if the given clause is a tautology else False.
    '''
    # Remove the negation of all the literals in the clause
    for i in range(len(clause)):
        clause[i].is_not = clause[i].is_not | 1

    # Check if there is a duplicate variable in the clause
    if len(set(clause)) == len(clause):
        return False

    return True

def goal_test(node, num_clauses):
    '''
        This function checks whether the state is the target(goal)
        state or not. If it is a target state it returns true otherwise
        false. The target state should have all the clauses satisfied.

        Arguments:
        ----------
            - node: node which needs to be checked
            - num_clauses: The total number of clauses to be satisfied

        Returns:
        --------
            True if the given state is the target state else False.
    '''

    return node.e == -num_clauses

def newmovegen(node,clauses,memory):
    '''
        (Move Gen Function for Tabu Search)
        This function accepts a state and returns all the states
        that can be reached from the given state by changing one
        bits of non-tabu variables.

        Arguments:
        ----------
            - node: node/state whose neighbours have to be found
            - clauses: List of clauses to be satisfied
            - memory: memory vector for Tabu Search

        Returns:
        --------
            List of Valid neighbours/state which can be visited from
            the given state.
    '''

    neighbors = []

    # Finding all the possible neighbors to the given node
    for i in range(len(node)):
        copy_node = copy.deepcopy(node)
        neighbors.append(Node(copy_node))
        # Changing the ith bit
        neighbors[i].values[i] = neighbors[i].values[i] ^ 1
        # Calculate the number of clauses satisfied
        neighbors[i].e = evaluate_node(neighbors[i], clauses)

    # Deleting the tabu neighbors/nodes
    for i, j in enumerate(memory[::-1]):
        if j != 0:
           del neighbors[len(memory)-i-1]

    return neighbors


class vCenterVMFromTemplateResourceModel(object):
    def __init__(self):
        self.vcenter_name = ''
        self.vcenter_template = ''
        self.vm_cluster = ''
        self.vm_storage = ''
        self.ip_regex = ''
        self.vm_resource_pool = ''
        self.vm_location = ''
        self.auto_power_on = ''
        self.auto_power_off = ''
        self.wait_for_ip = ''
        self.auto_delete = ''


import sys
sys.setrecursionlimit(1000000)
def pow_linear(num,n):
    if n == 0:
        return 1
    return num* pow_linear(num,n-1)
# print(pow_linear(4,2))

def power_general_linear(num,n):
    if n == 0:
        return 1
    elif n > 0:
        return num * power_general_linear(num, n-1)
    else:
        return power_general_linear(num,n + 1)/num
def power_logarithmic(num,n):
    # base case
    if n == 0:
        return 1
    if n % 2 == 0:
        return power_logarithmic(num,n//2)**2
    else:
        return num * (power_logarithmic(num, (n-1)//2) ** 2)

from time import time
t_0 = time()
num1 = pow_linear(2, 35000)
t_1 = time()
num2 = power_logarithmic(2, 35000)
t_2 = time()
print ('function vers1 takes %f' % (t_1-t_0))
print('===========================')
print ('function vers2 takes %f' % (t_2-t_1))

# Math

# b^n = {
# TH1: n == 0 => 1
# TH2: n is even: => b^(n/2)^2
# TH3: n is odd: => b^(n-1/2)^2 *b
# }


# betty.kristen.main.py
from _spy.vitollino.main import Cena, Texto, Elemento, STYLE
Campo='https://turismo.buenosaires.gob.ar/sites/turismo/files/campo_de_golf_1200_c.jpg'
Dogin='http://3.bp.blogspot.com/-4A5-CTXo8Jk/VUqmCKVdwfI/AAAAAAAAzzI/aiYW51qUD-s/s1600/dog_PNG147.png'
Carinha='https://myrealdomain.com/images/pessoa-correndo-4.png'
Pombo='http://www.pombocorreiodf.com.br/wp-content/uploads/2018/03/pombo-voando.png'
Lixeira_Vidro='https://metadistribuidorars.com.br/wp-content/uploads/2019/01/984.png'
Lixeira_Papel='https://assets.xtechcommerce.com/uploads/images/medium/5d66494a592658739ffd0904b0a12e00.png'
Lixeira_Metal='http://www.belosch.com.br/arquivos/produtos/_fotoMarcaVisu012R1JDBVZL_5a2e75a7515d2ebe63d498a1eaef6624.png'
Lixeira_Plastico='https://dotstore.s3-sa-east-1.amazonaws.com/582/produtos/detalhe/02%20basculantes%20-%20copia.png'
STYLE['width']=1350
STYLE['height']='600px'

def Quadra():
	Cena_Campo= Cena(img=Campo)
	Cena_Campo.vai()
	Elemento_Dogin=Elemento(img=Dogin, tit="DOGIN1",style=dict(left=100, top=500, width="120px",height="20"))
	Elemento_Dogin.entra(Cena_Campo)
	Elemento_Carinha=Elemento(img=Carinha, tit="CARINHA1",style=dict(left=500, top=300, width="190px",height="300px"))
	Elemento_Carinha.entra(Cena_Campo)
	Elemento_Pombo=Elemento(img=Carinha, tit="POMBO1",style=dict(left=200, top=100, width="190px",height="300px"))
	Elemento_Pombo.entra(Cena_Campo)
	Elemento_Lixeira_Vidro=Elemento(img=Lixeira_Vidro, tit="LIXEIRA_VIDRO1",style=dict(left=700, top=450, width="200px",height="150px"))
	Elemento_Lixeira_Vidro.entra(Cena_Campo)
	Elemento_Lixeira_Papel=Elemento(img=Lixeira_Papel, tit="LIXEIRA_PAPEL1",style=dict(left=900, top=450, width="100px",height="150px"))
	Elemento_Lixeira_Papel.entra(Cena_Campo)
	Elemento_Lixeira_Metal=Elemento(img=Lixeira_Metal, tit="LIXEIRA_METAL1",style=dict(left=980, top=450, width="120px",height="150px"))
	Elemento_Lixeira_Metal.entra(Cena_Campo)
	Elemento_Lixeira_Plastico=Elemento(img=Lixeira_Plastico, tit="LIXEIRA_PLASTICO1",style=dict(left=1100, top=450, width="100px",height="150px"))
	Elemento_Lixeira_Plastico.entra(Cena_Campo)

Quadra()


import csv
import pandas as pd
from matplotlib import pyplot as plt
from matplotlib import style

# 背景
style.use('ggplot')

Analysis = './AAPL.csv'

data = pd.read_csv(Analysis, parse_dates=True, index_col='Date')  # Date當作水平顯示(x軸)
price = data['Close']
price.head()

# pandas的moving average功能
# 畫出MA5
moving_avg5 = price.rolling(5).mean()
# 畫出MA20
moving_avg20 = price.rolling(20).mean()
# 畫出MA20標準差
moving_avg20_mstd = price.rolling(20).std()

plt.plot(price, color='b')
plt.plot(moving_avg5, color='cornflowerblue', linewidth=1, label='MA5')
plt.plot(moving_avg20, color='orange', linewidth=1, label='MA20')
# 'moving_avg20.index': 沿著moving_avg20的日期(x軸)
# alpha：透明度
plt.fill_between(moving_avg20.index, moving_avg20-2*moving_avg20_mstd, moving_avg20+2*moving_avg20_mstd, color='b', alpha=0.2)

plt.legend()
plt.show()


import shutil
import tempfile
import time
import numpy as np
import cv2
import os, sys
import redis
import simplejson as json

r=redis.Redis(host='130.211.248.50',port=6379,db=0) #change depending on the ip address

#cap = cv2.VideoCapture('countdown.mp4')
cap = cv2.VideoCapture("rtsp://admin:@192.168.1.193/h264Preview_01_main")
if (cap.isOpened() == False):
  print("Unable to read camera feed")
#frame_width = int(cap.get(3))
#frame_height = int(cap.get(4))
ret, frame = cap.read()
frame_height,frame_width,x = frame.shape
print(frame)
print(frame.shape)
count=0
out = cv2.VideoWriter('outpy.avi',cv2.VideoWriter_fourcc('M','P','4','2'), 10, (frame_width,frame_height))
adc1=r.set('fam', json.dumps(frame.tolist()))
while(True):
  ret, frame = cap.read()
  if ret == True:
    print(frame)
    lo=r.lset('red_frame', count, json.dumps(frame.tolist()))
    print(type(lo))
    print(lo)
    out.write(frame)
    cv2.imshow('frame',frame)
    print(frame.dtype)
    count=count+1
    #f1=json.dumps(frame.tolist())

    if cv2.waitKey(1) & 0xFF == ord('q'):
      break
  else:
    break


import time
import logging
from logging import Logger
from typing import ClassVar, Iterator

import pika
from pydantic import AnyUrl, Field

from ..tap import SourceTap, SourceSettings, DestinationTap, DestinationSettings
from ..message import MessageBase
from ..helpers import namespaced_topic

pipelineLogger = logging.getLogger("pipeline")

class RabbitMQDsn(AnyUrl):
    allowed_schemes = {
        "amqp",
    }

class RabbitMQSourceSettings(SourceSettings):
    rabbitmq: RabbitMQDsn = Field("amqp://localhost", title="RabbitMQ host")

class RabbitMQSource(SourceTap):
    """RabbitMQSource reads from RabbitMQ

    RabbitMQ options:
        --rabbitmq (env: RABBITMQ): RabbitMQ host

    Source options:
        --in-topic (env: INTOPIC): queue to read from
        --timeout (env: TIMEOUT): seconds to exit if no new messages

    >>> import logging
    >>> from unittest.mock import patch
    >>> settings = RabbitMQSourceSettings()
    >>> with patch('pika.ConnectionParameters') as c1:
    ...     with patch('pika.BlockingConnection') as c2:
    ...         RabbitMQSource(settings=settings, logger=logging)
    RabbitMQSource(queue="in-topic")
    """

    settings: RabbitMQSourceSettings

    kind: ClassVar[str] = "RABBITMQ"

    def __init__(
        self, settings: RabbitMQSourceSettings, logger: Logger = pipelineLogger
    ) -> None:
        super().__init__(settings, logger)
        self.settings = settings
        self.topic = settings.topic
        self.name = namespaced_topic(settings.topic, settings.namespace)
        self.timeout = settings.timeout
        parameters = pika.ConnectionParameters(settings.rabbitmq)
        self.rabbit = pika.BlockingConnection(parameters)
        self.channel = self.rabbit.channel()
        self.channel.queue_declare(queue=self.name)
        self.delivery_tag = None
        self.msg = None
        self.logger.info("RabbitMQSource initialized.")

    def __repr__(self) -> str:
        return f'RabbitMQSource(queue="{self.name}")'

    def __len__(self) -> int:
        return -1

    def read(self) -> Iterator[MessageBase]:
        timedOut = False
        lastMessageBaseTime = time.time()

        while not timedOut:
            try:
                method, header, body = self.channel.basic_get(self.name)
            except pika.exceptions.AMQPConnectionError:
                self.logger.warning("Trying to restore connection to RabbitMQ...")
                parameters = pika.ConnectionParameters(self.settings.rabbitmq)
                self.rabbit = pika.BlockingConnection(parameters)
                self.channel = self.rabbit.channel()
                self.logger.warning("Connection to RabbitMQ restored.")
                method, header, body = self.channel.basic_get(self.name)
            except Exception as ex:
                self.logger.error(ex)
                break

            if method:
                self.delivery_tag = method.delivery_tag
                self.logger.info("Read message %s", self.delivery_tag)
                yield MessageBase.deserialize(body)
                lastMessageBaseTime = time.time()
            time.sleep(0.01)
            if self.timeout > 0 and time.time() - lastMessageBaseTime > self.timeout:
                self.logger.info("RabbitMQSource timed out.")
                timedOut = True

    def acknowledge(self) -> None:
        self.logger.info("acknowledged message %s", self.delivery_tag)
        self.channel.basic_ack(self.delivery_tag)

    def close(self) -> None:
        self.logger.info("RabbitMQSource closed.")
        self.channel.close()
        self.rabbit.close()

class RabbitMQDestinationSettings(DestinationSettings):
    rabbitmq: RabbitMQDsn = Field("amqp://localhost", title="RabbitMQ host")

class RabbitMQDestination(DestinationTap):
    """RabbitMQDestination writes to RabbitMQ

    options:
        --rabbitmq (env: RABBITMQ): RabbitMQ host

    standard options:
        --out-topic (env: OUTTOPIC): queue to write to

    >>> import logging
    >>> from unittest.mock import patch
    >>> settings = RabbitMQDestinationSettings()
    >>> with patch('pika.ConnectionParameters') as c1:
    ...     with patch('pika.BlockingConnection') as c2:
    ...        RabbitMQDestination(settings=settings, logger=logging)
    RabbitMQDestination(queue="out-topic")
    """

    settings: RabbitMQDestinationSettings

    kind: ClassVar[str] = "RABBITMQ"

    def __init__(self, settings: RabbitMQDestinationSettings, logger: Logger) -> None:
        super().__init__(settings, logger)
        self.settings = settings
        self.topic = settings.topic
        self.name = namespaced_topic(settings.topic, settings.namespace)
        parameters = pika.ConnectionParameters(settings.rabbitmq, heartbeat=5)
        self.rabbit = pika.BlockingConnection(parameters)
        self.channel = self.rabbit.channel()
        self.channel.queue_declare(queue=self.name)
        self.logger.info("RabbitMQDestination initialized.")

    def __repr__(self) -> str:
        return f'RabbitMQDestination(queue="{self.name}")'

    def __len__(self) -> int:
        return -1

    def write(self, message: MessageBase) -> int:
        serialized = message.serialize()
        try:
            self.channel.basic_publish(
                exchange="", routing_key=self.name, body=serialized
            )
        except pika.exceptions.StreamLostError:
            self.logger.warning("Trying to restore connection to RabbitMQ...")
            self.rabbit = pika.BlockingConnection(
                pika.ConnectionParameters(self.settings.rabbitmq)
            )
            self.channel = self.rabbit.channel()
            self.logger.warning("Connection to RabbitMQ restored.")
            self.channel.basic_publish(
                exchange="",
                routing_key=self.name,
                body=message.serialize(compress=self.settings.compress),
            )
        return len(serialized)

    def close(self) -> None:
        self.logger.info("RabbitMQDestination closed.")
        self.channel.close()
        self.rabbit.close()


#! C:\Users\yeshw\Desktop\Umass\Geology_497\Lab3
"""
This code analyzes the data in the file MinkRiver.dat. It uses mannings equation
to calculate 5 potential flow velocities using different roughness values, it then
plots the data in the minkriver data file to approximate the roughness value of the river

Yesh 2/19/20
"""

import numpy as np
import matplotlib.pylab as plt

loc1Dat= [[1.6912,1.5982],
         [0.9642,1.1151],
         [1.254,1.512],
         [1.3764,1.3266],
         [1.1394,1.3791],
         [1.703,1.7386],
         [1.1346,1.2492],
         [0.60396,0.97686],
         [1.6697,2.0005],
         [0.55459,0.72213]]
loc2Dat = np.loadtxt('Mink River.dat' ,skiprows = 2, delimiter = ',')

loc1Dat = np.array(loc1Dat)
loc2Dat = np.array(loc2Dat)

K = 1.0
roughnessValues = [0.01,0.025,0.05,0.075,0.100]
h = np.arange(0,3.01,0.01)
S = 0.001
Vs = []

for i in np.arange(0, len(roughnessValues)):
    Vs.append((K/roughnessValues[i])*(h**(2/3))*(S**(1/2)))

#print(Vs[0])
plt.figure()
plt.scatter(loc2Dat[:,1],loc2Dat[:,0], s=10, facecolors='black',
            edgecolors='black', label = 'Location 2')
plt.scatter(loc1Dat[:,1],loc1Dat[:,0], s=10, facecolors='none',
            edgecolors='r', label = 'Location 1')
plt.plot(h,Vs[0],'--',lineWidth = 1.0, color="black", label = 'V1')
plt.plot(h,Vs[1],'-.',lineWidth = 1.0, color="blue", label = 'V2')
plt.plot(h,Vs[2],':',lineWidth = 1.0, color="green", label = 'V3')
plt.plot(h,Vs[3],'-.',lineWidth = 1.0, color="red", label = 'V4')
plt.plot(h,Vs[4],',',lineWidth = 1.0, color="magenta", label = 'V5')
plt.xlabel('Stream Stage (m)')
plt.ylabel('Flow Velocity (m/s)')
plt.xlim(0, 2.5)
plt.ylim(0, 5)
plt.legend()
plt.show()

print("Location 1 roughness coefficient = ", 0.025)
print("Location 2 roughness coefficient = ", 0.05)

#plt.scatter(loc2Dat[:,1],loc2Dat[:,0])


import itertools as it

from MorseAndFiltrations.DMF_to_filtration import DMF_to_filtration

def filtration_to_DMF(filtration):
    critical = [0]*len(filtration)
    pairings = []
    indices_for_clearing = []
    for ind,simplex in enumerate(filtration):
        if(len(simplex) == 1):
            critical[ind] = 1
        elif not simplex_in_pairings(simplex, pairings):
            pair = find_youngest_facet(simplex, filtration, pairings)
            if(pair == None):
                critical[ind] = 1
            else:
                tmp = filtration.index(pair)
                if(filtration[find_oldest_cofacet(pair, filtration)]==simplex):
                    pairings.append([list(pair),simplex])
                    critical[tmp] = 0
                else:
                    critical[ind] = 1
                if(len(pair) > 1):
                    indices_for_clearing.append(tmp)
    indices_for_clearing.sort()
    return [filtration[i] for i in range(len(filtration)) if critical[i] == 1], pairings, indices_for_clearing

def filtration_to_emergent_face(filtration):
    pairings = []
    indices_for_clearing = []
    for ind,simplex in enumerate(filtration):
        if(len(simplex) == 1):
            continue
        elif not simplex_in_pairings(simplex, pairings):

            pair = find_youngest_facet(simplex, filtration, pairings)
            tmp = filtration.index(pair)
            if(filtration[find_oldest_cofacet(pair, filtration)]==simplex):
                pairings.append([list(pair),simplex])
            if(len(pair) > 1):
                indices_for_clearing.append(tmp)

    indices_for_clearing.sort()
    return pairings, indices_for_clearing

def simplex_in_pairings(simplex, pairings):
    simplex = list(simplex)
    for pair in pairings:
        if(simplex in pair):
            return True
    return False

def find_oldest_cofacet(simplex, filtration):
    for i,elem in enumerate(filtration):
        if(len(elem) - 1 == len(simplex)):
            if all(s in elem  for s in simplex):
                return i

def find_youngest_facet(simplex, filtration, pairings):
    combis = [comb for comb in it.combinations(simplex, len(simplex)-1)]
    combis.sort()
    curr_max_index = -1

    for combi in combis:
        tmp = filtration.index(list(combi))

        if tmp > curr_max_index:
            curr_max_index = tmp

    if(curr_max_index == -1 or simplex_in_pairings(filtration[curr_max_index], pairings)):
        return None

    return filtration[curr_max_index]


import time
import datetime
import webbrowser
import os
import urllib.request as req

#from common.constants import liveEngageConstants
#from common import passDecrypt
#from datetime import datetime, timezone

def convertToEpoch(dateToConvert):
    pattern = '%Y-%m-%d %H:%M:%S'
    epStartDateTime = int(time.mktime(time.strptime(str(dateToConvert), pattern)) ) *1000
    return epStartDateTime

def epochStartDate(nowMinusStart):
    startDate =  datetime.date.today() - datetime.timedelta(days=nowMinusStart)
    startTime = datetime.time(0 ,0 ,0)
    startDateTime = convertToEpoch(datetime.datetime.combine(startDate, startTime))
    return startDateTime

def epochEndDate(nowMinusEnd):
    endDate =  datetime.date.today() - datetime.timedelta(days=nowMinusEnd)
    endTime = datetime.time(23 ,59 ,59)
    endDateTime = convertToEpoch(datetime.datetime.combine(endDate, endTime))
    return endDateTime

def getEndTime(runDateTime):
    endTime = (runDateTime - datetime.timedelta(minutes=1440)).isoformat()
    endTime = endTime[0:19] + '+00:00'
    return endTime

def getStartTime(runDateTime):
    startTime = (runDateTime).isoformat()
    startTime = startTime[0:19] + '+00:00'
    return startTime

# old proxyauth scipt that only seems to work at certain times of the day
# def proxyAuth():
#    webbrowser.open(liveEngageConstants.proxyURL, new=1)
#    time.sleep(10)
#    browserExe = "iexplore.exe"
#    os.system("taskkill /f /im "+browserExe)

def fileIDString(start ,end):
    strDate =  str(datetime.date.today())
    fileIDString = strDate + "_" + str(start) + "_" + str(end)
    return fileIDString

def queryDate(todayMinus):
    strDate = str(datetime.date.today() - datetime.timedelta(days=todayMinus))
    return strDate

def proxyAuth():
    proxyString = r'http://' + os.getlogin() + ':' + passDecrypt.proxyPass() + '@dia2.santanderuk.gs.corp:80'
    # proxyString = proxyString.encode('unicode_escape').decode().replace('\\\\', '\\')
    proxy = req.ProxyHandler({'http': proxyString})
    auth = req.HTTPBasicAuthHandler()
    opener = req.build_opener(proxy, auth, req.HTTPHandler)
    req.install_opener(opener)
    conn = req.urlopen('http://google.com')
    return_str = conn.read()

# proxyString = r'http://' + os.getlogin() + ':' + passDecrypt.proxyPass() + '@dia2.santanderuk.gs.corp:80'
# print(proxyString)

print(getEndTime(datetime.datetime.utcnow()))
print(getStartTime(datetime.datetime.utcnow()))

#endTime = (datetime.datetime.now() - datetime.timedelta(minutes=15)).isoformat()

#print(endTime)


##### Task 2
"""Read the data from the file task02.csv
Allow the user to search for a stock symbol.
If the stock symbol is found, display the name of the company
If a multiple stocks match the symbol, say there are multiple stocks available
If there is no match, say "no match found"

Example:
Enter stock symbol: AA
There are 21 stocks with that symbol
Enter stock symbol: AAPL
Apple Inc.
Enter stock symbol: YANG
No matches"""

def find(stock):
    filename = 'task02.csv'
    file = open(filename, 'r')
    alist = []
    count = 0
    for i in file:
        if stock in i:
            count = count + 1
            test = i.strip()
            lineData = test.split(",")

            alist.append(lineData[1])

    if len(alist) > 1:
        print(f"There are {len(alist)} stocks with that symbol")
    elif len(alist) == 1:
        print(alist)
    elif len(alist) == 0:
        print("No matches")

x = input("Enter a stock symbol: ")
find(x)


import util
import parse

def should_run(section,frame):
	args = parse.args(section)

	# handle overwriting of arguments
	if util.flag(frame.get('force','false')):
		return True
	args += [('skip',frame.get('skip','false'))]
	args += [('run',frame.get('run','true'))]
	args += [('when',frame.get('when','true'))]

	for k,v in args:
		if k not in ('skip','run','when'): continue
		v = frame.render(v)
		#print('DEBUG COND',k,v,util.flag(v))
		if k=='skip':
			if util.flag(v):
				return False
		elif k=='run':
			if not util.flag(v):
				return False
		elif k=='when':
			if not v.strip():
				return False
	return True


wRegistery_log = None

import threading
import time
import traceback

from python.Util.Conf import Config

class WorkerStatus:
    NEW = -1
    INITILAZED = 0
    IDLE = 1
    RUNNING = 2
    ERROR = 3
    LOST = 4
    FINALIZED = 5

class WorkerEntry:
    """
    contain worker information and task queue
    """
    def __init__(self, wid, w_uuid, max_capacity):
        self.wid = wid
        self.policy = Config()
        self.w_uuid = w_uuid
        self.registration_time =time.time()
        self.last_contact_time = self.registration_time
        self.idle_time = 0

        self.init_times = 0
        self.fin_times = 0

        self.max_capacity = max_capacity
        self.assigned = 0

        self.status = WorkerStatus.NEW
        self.alive_lock = threading.RLock()
        self.alive = True

    def capacity(self):
        return self.max_capacity-self.assigned

    def isLost(self):
        if self.policy.getPolicyattr('LOST_WORKER_TIMEOUT'):
            return time.time()-self.last_contact_time > self.policy.getPolicyattr('LOST_WORKER_TIMEOUT')
        return False

    def getStatus(self):
        return self.status
    def isIdle_timeout(self):
        return self.idle_time and self.policy.getPolicyattr('IDLE_WORKER_TIMEOUT') and time.time()-self.idle_time > self.policy.getPolicyattr('IDLE_WORKER_TIMEOUT')

    def setStatus(self,status):
        self.alive_lock.acquire()
        self.status = status
        self.alive_lock.release()

    def reinit(self):
        self.alive_lock.acquire()
        try:
            self.init_times+=1
            return self.init_times < Config.getPolicyattr('INITIAL_TRY_TIME')
        finally:
            self.alive_lock.release()
    def refin(self):
        self.alive_lock.acquire()
        try:
            self.init_times += 1
            return self.init_times < Config.getPolicyattr('FIN_TRY_TIME')
        finally:
            self.alive_lock.release()

class WorkerRegistry:
    def __init__(self):
        self.__all_workers={}           # wid: worker_entry
        self.__all_workers_uuid = {}    # w_uuid: wid
        self.last_wid = 0
        self.lock = threading.RLock()

        self.alive_workers = set([])       # w_uuid

    def size(self):
        return len(self.__all_workers)

    def add_worker(self, w_uuid, max_capacity):
        wRegistery_log.debug('[WorkerRegistry] Before add worker')
        self.lock.acquire()
        try:
            if self.__all_workers_uuid.has_key(w_uuid):
                wid = self.__all_workers_uuid[w_uuid]
                wRegistery_log.warning('worker already registered: wid=%d, worker_uuid=%s',wid,w_uuid)
                return None
            else:
                self.last_wid+=1
                w = WorkerEntry(self.last_wid, w_uuid, max_capacity)
                w.alive = True
                self.__all_workers[self.last_wid] = w
                self.__all_workers_uuid[w_uuid] = self.last_wid
                self.alive_workers.add(w_uuid)
                wRegistery_log.info('new worker registered: wid=%d, worker_uuid=%s',self.last_wid, w_uuid)
                return w
        except:
            wRegistery_log.error('[WorkerRegistry]: Error occurs when adding worker, msg=%s', traceback.format_exc())
        finally:
            self.lock.release()
            wRegistery_log.debug('[WorkerRegistry] After add worker')

    def remove_worker(self, wid):
        """
        remove worker, if worker alive, return worker's uuid to finalize worker, otherwise stop worker
        :param wid:
        :return: bool, uuid
        """
        self.lock.acquire()
        try:
            w_uuid = self.__all_workers[wid].w_uuid
        except KeyError:
            wRegistery_log.warning('attempt to remove not registered worker: wid=%d', wid)
            return False,None
        else:
            if self.__all_workers[wid].alive:
                # finalize worker
                wRegistery_log.info('attempt to remove alive worker: wid=%d',wid)
                #return False,w_uuid
            wRegistery_log.info('worker removed: wid=%d',wid)
            try:
                del(self.__all_workers[wid])
                del(self.__all_workers_uuid[w_uuid])
            except KeyError:
                wRegistery_log.warning('[WorkerRegistry]: can not find worker when remove worker=%d, uuid=%s', wid, w_uuid)
                return False, None
        finally:
            self.lock.release()
        return True ,None

    def get_entry(self,wid):
        if self.__all_workers.has_key(wid):
            return self.__all_workers[wid]
        else:
            #print 'Can not find worker %s, this is all workers %s'%(wid, self.__all_workers.keys())
            return None

    def get_by_uuid(self, w_uuid):
        return self.get_entry(self.__all_workers_uuid[w_uuid])

    def get_worker_list(self):
        return self.__all_workers.values()

    def get_capacity(self, wid):
        return self.__all_workers[wid].max_capacity

    def worker_reinit(self, wid):
        return self.get_entry(wid).reinit()

    def worker_refin(self, wid):
        return self.get_entry(wid).refin()

    def sync_capacity(self, wid, capacity):
        # TODO the num of assigned task is incompatable with worker
        wentry = self.get_entry(wid)
        if capacity != wentry.max_capacity - wentry.assigned:
            wentry.alive_lock.acquire()
            wentry.assigned = wentry.max_capacity - capacity
            wentry.alive_lock.release()

    def checkIdle(self,exp=[]):
        """
        check if all workers is in IDLE status
        :return:
        """
        if exp:
            wRegistery_log.debug('[Registry] check idle exclude worker %s, type of exp = %s'%(exp,type(exp[0])))
        flag = True
        for uuid in self.alive_workers:
            wentry = self.get_by_uuid(uuid)
            if str(wentry.wid) in exp or int(wentry.wid) in exp:
                continue
            elif wentry.status in [WorkerStatus.RUNNING, WorkerStatus.INITILAZED]:
                wRegistery_log.info('[Registry] worker %s is in status=%s, cannot finalize'%(wentry.wid, wentry.status))
                flag = False
                return flag
        return flag

    def checkFinalize(self,exp=[]):
        for uuid in self.alive_workers:
            entry = self.get_by_uuid(uuid)
            if entry.status != WorkerStatus.FINALIZED:
                return False
        return True

    def setContacttime(self, uuid, time):
        wid = self.__all_workers_uuid[uuid]
        self.__all_workers[wid].last_contact_time = time

    def setStatus(self,wid,status):
        wid = int(wid)
        wentry = self.get_entry(wid)
        if wentry.alive:
            wentry.alive_lock.acquire()
            wentry.status = status
            wentry.alive_lock.release()
        else:
            wRegistery_log.warning('[Registry] Worker %s is not alive')
            wentry.alive_lock.acquire()
            wentry.alive = True
            wentry.status = status
            wentry.alive_lock.release()
            self.alive_workers.add(wentry.w_uuid)

    def checkLostWorker(self):
        """
        check if there are lost workers, and do some handle
        :return:
        """
        lostworker = []
        for w in self.__all_workers.values():
            if w.isLost():
                lostworker.append(w.wid)
                w.alive = False
                self.alive_workers.remove(w.w_uuid)
        return lostworker

    def checkIDLETimeout(self):
        list = []
        timeout = Config.getCFGattr('IDLE_WORKER_TIMEOUT')
        if not timeout or timeout==0:
            return None
        else:
            for w in self.__all_workers.values():
                if w.alive and w.worker_status == WorkerStatus.IDLE:
                    if w.idle_time != 0:
                        if time.time()-w.idle_time > Config.getPolicyattr('IDLE_WORKER_TIMEOUT'):
                            list.append(w.wid)
                    else:
                        w.idle_time = time.time()
        return list

    def __iter__(self):
        return self.__all_workers.copy().__iter__()


from django import template
from AccountingApp.functions.core_algorithm import cleared_person

register = template.Library()

def set_cleared(person):
    person.cleared = cleared_person(person)
    person.save()

class CustomTag:
    def __init__(self, is_person_cleared):
        self.cleared_person = is_person_cleared
        self.set_cleared = set_cleared

@register.simple_tag
def call_method(method_name, *args):
    tag = CustomTag(cleared_person)
    method = getattr(tag, method_name)
    return method(*args)


import tkinter
from tkinter import *

class ParentWindow(Frame):
    def __init__(self, master):
        Frame.__init__(self)

        self.master = master
        self.master.resizable(width=False, height=False)
        self.master.geometry('{}x{}'.format(700, 400))
        self.master.title('Learning Tkinter!')
        self.master.config(bg='darkgray')

        self.varfName = StringVar()
        self.varlName = StringVar()

        #calling
        self.txtfName = Entry(self.master, text = self.varfName, font = ("Helvetica", 16), fg = 'black', bg = 'lightblue')
        self.txtfName.pack()

        self.txtlName = Entry(self.master, text = self.varlName, font = ("Helvetica", 16), fg = 'black', bg = 'lightblue')
        self.txtlName.pack()

if __name__ == "__main__":
    root = Tk()
    App = ParentWindow(root)
    # keeping main loop active until user kills it
    root.mainloop()


# PyTest позволяет запустить один и тот же тест с разными входными параметрами.
# Для этого используется декоратор @pytest.mark.parametrize()
# Наш сайт доступен для разных языков. Напишем тест, который проверит, что для сайта
# с русским и английским языком будет отображаться ссылка на форму логина.
# Передадим в наш тест ссылки на русскую и английскую версию главной страницы сайта.

# В @pytest.mark.parametrize() нужно передать параметр, который должен изменяться,
# и список значений параметра. В самом тесте наш параметр тоже нужно передавать в качестве аргумента.
# Обратите внимание, что внутри декоратора имя параметра оборачивается в кавычки,
# а в списке аргументов теста кавычки не нужны.

import pytest
from selenium.webdriver.common.by import By

@pytest.mark.parametrize('language', ["ru", "en-gb"])
def test_guest_should_see_login_link(browser, language):
    link = f"http://selenium1py.pythonanywhere.com/{language}/"
    browser.get(link)
    browser.find_element(By.CSS_SELECTOR, "#login_link")

# Запуск - pytest -s -v test_fixture9.py


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

import datetime
import platform as plat
import os
import keras
import matplotlib as plt

import numpy as np
from general_func.file_wav import *
from general_func.file_dict import *
from help_func.get_interval_index import get_interval_list

import random

MAX_AUDIO_LENGTH = 110
AUDIO_FEATURE_LENGTH = 200
CLASS_NUM = 4
FOLDER_SPLIT_NUM = 5

class DataCross():

    def __init__(self, path, LoadToMem=False, MemWavCount=10000):

        '''
        参数：
            path：数据存放位置根目录
            type: to distinguish the 4-1 folder
        '''
        system_type = plat.system()  # 由于不同的系统的文件路径表示不一样，需要进行判断
        self.datapath = path  # 数据存放位置根目录

        self.slash = ''
        if (system_type == 'Windows'):
            self.slash = '\\'  # 反斜杠
        elif (system_type == 'Linux'):
            self.slash = '/'  # 正斜杠
        else:
            print('*[Warning] Unknown System\n')
            self.slash = '/'  # 正斜杠

        if (self.slash != self.datapath[-1]):  # 在目录路径末尾增加斜杠
            self.datapath = self.datapath + self.slash

        self.folds = []
        self.__LoadDataList()

        self.list_normal = []
        self.list_wheeze = []
        self.list_crackle = []
        self.list_both = []
        self.list_all = []
        self.class_num = CLASS_NUM
        self.DataNum = 0

        self.feat_dimension = AUDIO_FEATURE_LENGTH
        self.frame_length = 400

        pass

    def __LoadDataList(self):
        '''
        加载用于计算的数据列表
        参数：
        '''
        # the classic codes to browse all the subfolders.
        folder_list= []
        if (os.path.exists(self.datapath)):
            directory = os.listdir(self.datapath)
            for name in directory:
                m = os.path.join(self.datapath,name)
                if os.path.isdir(m):
                    folder_list.append(m)

        if FOLDER_SPLIT_NUM!=len(folder_list):
            print('*[Error] Dataset misplacement!')
            assert(0)
        else:
            try:
                for fpath in folder_list:
                    normal_path = os.path.join(fpath,'normal')
                    normal_list = os.listdir(normal_path)
                    normal_list = [os.path.join(normal_path, element) for element in normal_list ]
                    wheeze_path = os.path.join(fpath, 'wheeze')
                    wheeze_list = os.listdir(wheeze_path)
                    wheeze_list = [os.path.join(wheeze_path, element) for element in wheeze_list ]
                    crackle_path = os.path.join(fpath, 'crackle')
                    crackle_list = os.listdir(crackle_path)
                    crackle_list = [os.path.join(crackle_path,element) for element in crackle_list]
                    # print(len(crackle_list))
                    both_path = os.path.join(fpath, 'both')
                    both_list = os.listdir(both_path)
                    both_list = [os.path.join(both_path, element) for element in both_list ]
                    tmp_dict = {'normal':normal_list,'wheeze':wheeze_list,'crackle':crackle_list,'both':both_list}
                    self.folds.append(tmp_dict)
            except:
                print('*[Error] Dataset misformation!')
                assert (0)

    def SplitType(self, type = 'train', order = 1):
        ''''
        parameter: order belongs to [0, FOLDERSPLIT_NUM)

        '''
        #empty the lists
        self.list_normal = []
        self.list_wheeze = []
        self.list_crackle = []
        self.list_both = []
        self.list_all = []

        if order>=FOLDER_SPLIT_NUM:
            print('index out of the boundry.')
            assert(0)

        random.seed(datetime.datetime.now())
        if type == 'train':
            for i in [ x for x in range(FOLDER_SPLIT_NUM) if x!=int(order)]:
                self.list_normal = self.list_normal + self.folds[i]['normal']
                self.list_wheeze = self.list_wheeze + self.folds[i]['wheeze']
                self.list_crackle = self.list_crackle + self.folds[i]['crackle']
                self.list_both = self.list_both + self.folds[i]['both']
            self.list_all = self.list_all + [{element:'normal'} for element in self.list_normal] \
                                          + [{element: 'wheeze'} for element in self.list_wheeze] \
                                          + [{element: 'crackle'} for element in self.list_crackle] \
                                          + [{element: 'both'} for element in self.list_both]
            self.DataNum = (len(self.list_normal) , len(self.list_wheeze) , len(self.list_crackle) , len(self.list_both))
            random.shuffle(self.list_normal)
            random.shuffle(self.list_wheeze)
            random.shuffle(self.list_crackle)
            random.shuffle(self.list_both)
        elif type  == 'eval':
            i = int(order)
            for n in self.folds[i]['normal']:
                self.list_normal.append({n:'normal'})
            for w in self.folds[i]['wheeze']:
                self.list_wheeze.append({w:'wheeze'})
            for c in self.folds[i]['crackle']:
                self.list_crackle.append({c:'crackle'})
            for b in self.folds[i]['both']:
                self.list_both.append({b:'both'})
            self.list_all = self.list_both + self.list_normal + self.list_crackle + self.list_wheeze
            self.DataNum = len(self.list_all)
            del self.list_normal, self.list_wheeze, self.list_crackle, self.list_both
        else:
            print('incorrect parameters.')
            assert(0)
        random.shuffle(self.list_all)

    def GetData(self, n_start, n_amount=1, mode='balanced'):
        '''
        :param n_start:
        :param n_amount:
        :param mode:
        :return:
        :note:  cycles less than 1s are also inclusive in the testing phase.
        '''

        # category = (self.list_normal, self.list_wheeze, self.list_crackle, self.list_both)
        # link = ('00', '01', '10', '11')
        # label = (0, 1, 2, 3)
        char2digit = {'normal': 0, 'wheeze': 1, 'crackle': 2, 'both': 3}
        data_label = []

        # while True:
        #     path = ''
        #     if mode == 'balanced':
        #         print('balanced mode is not available.')
        #     if mode == 'non-repetitive':
        #         path = list(self.list_all[n_start].keys)[0]
        #         str = list(self.list_all[n_start].keys)[0]
        #         try:
        #             data_label = np.array([char2digit[str]])
        #         except:
        #             print('label errors.')
        #             assert(0)
        #     wavsignal, fs = read_wav_data(path)
        #     if (wavsignal.shape[1] / fs > 1.0):
        #         break

        path = ''
        if mode == 'balanced':
            print('balanced mode is not available.')
            assert(0)
        if mode == 'non-repetitive':
            path = list(self.list_all[n_start].keys())[0]
            str = list(self.list_all[n_start].values())[0]
            try:
                data_label = np.array([char2digit[str]])
            except:
                print('*[ERROR] label errors.')
                assert (0)
        wavsignal, fs = read_wav_data(path)

        data_input = GetFrequencyFeatures(wavsignal, fs, self.feat_dimension, self.frame_length)
        data_input = data_input.reshape(data_input.shape[0], data_input.shape[1], 1)

        return data_input, data_label

    def __GetData4tTrain(self, n_start, n_amount=1):
        '''
        读取数据，返回神经网络输入值和输出值矩阵(可直接用于神经网络训练的那种)
        参数：
            n_start：从编号为n_start数据开始选取数据
            n_amount：选取的数据数量，默认为1，即一次一个wav文件
        返回：
            四个音频四个label，
        note:
            data less than 1s are not deleted.
        '''
        category = (self.list_normal, self.list_wheeze, self.list_crackle, self.list_both)
        label = (0, 1, 2, 3)
        data_label = []

        data_input = np.zeros(shape=(4, MAX_AUDIO_LENGTH, self.feat_dimension, 1), dtype=np.float)
        data_label = np.zeros(shape=(4, 1), dtype=np.int16)
        path = ''
        for p in range(len(category)):
            path = category[p][n_start % len(category[p])]
            data_label[p] = np.array([label[p]])
            wavsignal, fs = read_wav_data(path)
            datum_input = GetFrequencyFeatures(wavsignal, fs, self.feat_dimension, self.frame_length)
            if len(datum_input)<= MAX_AUDIO_LENGTH:
                pass
            else:
                span = len(datum_input) - MAX_AUDIO_LENGTH
                begin = np.random.randint(span)
                datum_input = datum_input[begin:begin+MAX_AUDIO_LENGTH]
            data_input[p, 0:len(datum_input)] = datum_input.reshape(datum_input.shape[0], datum_input.shape[1], 1)

        return data_input, data_label

    def data_genetator4tTrain(self, batch_size=32):
        '''
        数据生成器函数，用于Keras的generator_fit训练
        batch_size: 一次产生的数据量
        '''

        iterations_per_epoch = max(self.DataNum) // (batch_size // 4) + 1
        while True:
            ran_num = random.randint(0, iterations_per_epoch - 1) * (batch_size // 4)  # 获取discrete随机数
            assert (batch_size % 4 == 0)
            X = np.zeros((batch_size, MAX_AUDIO_LENGTH, self.feat_dimension, 1), dtype=np.float)
            y = np.zeros((batch_size, 1), dtype=np.int16)
            for i in range(batch_size // 4):
                data_input, data_label = self.__GetData4tTrain(n_start=(ran_num + i))  # 从随机数开始连续向后取一定数量数据
                lp = i * 4  # loading point
                X[lp:lp + 4] = data_input
                y[lp:lp + 4] = data_label
            yield [X, keras.utils.to_categorical(y, num_classes=self.class_num)], keras.utils.to_categorical(y,
                                                                                num_classes=self.class_num)  # 功能只是转成独热编码
        pass

    def StatisticData(self):
        length = []
        for i in range(sum(self.DataNum)):
            data_input, data_labels = self.GetDataEval(i, mode='non-repetitive')
            length.append(data_input.shape[0])
        print('mean value:',np.mean(length))
        binwidth = 20
        plt.hist(length, bins=np.arange(min(length), max(length) + binwidth, binwidth))
        plt.show()

if (__name__ == '__main__'):
    path = '/home/zhaok14/example/PycharmProjects/setsail/individual_spp/dataset/5-folds'
    l = DataCross(path)
    # l.SplitType(type='train',order=2)
    # print(l.folds)
    x= l in locals() or 'var' in globals() #??????
    str = ['train', 'eval']
    l5 = []
    for i in range(5):
        lst = []
        for s in str:
            l.SplitType(type=s,order=i)
            print('{} order cross validation, {} set: '.format(i,s))
            print('data amounts:',l.DataNum)
            data=l.data_genetator4tTrain(4)
            a,_=data.__next__()

            if s == 'train':
                print('overall sum',sum(l.DataNum))
                lst.append(sum(l.DataNum))
            if s == 'eval':
                print('sum unnecessarily.')
                lst.append(l.DataNum)
        l5.append(lst[0]+lst[1])
    print('check if mutually identical:',l5)