from abc import ABC
import Labirintite
import string
from heuristica import HeuristicaLabirinto

class AbstractEstado(ABC):
    def __init__(self, is_objetivo, custo_transicao=lambda s,a,st: 1):
        self.isObjetivo = is_objetivo
        self.custoTransicao = custo_transicao

    #@abstractmethod
    def acoesPossiveis(self):
        """ AbstractEstado -> (AbstractAcao)
        Cria um generator de ações válidas para self.
        """
        return

    #@abstractmethod
    def transicaoPor(self, acao):
        """ AbstractEstado, AbstractAcao -> AbstractEstado
        Computa o estado adjacente a self ao aplicar uma acao válida.
        """
        return

    def adjacentes(self):
        """ AbstractEstado -> (AbstractEstado)
        Cria um generator de estados adjacentes a self, o estado atual.
        """
        return (self.transicaoPor(acao) for acao in self.acoesPossiveis())

class EstadosLabirintite(AbstractEstado):
    """
    Com base em seu design, implemente uma classe que corresponda à interface de `AbstractEstado`
    (ver `espaco_estado.py` no GitLab), e que seja capaz de gerar o espaço de estados de seu jogo.
    """
    def __init__(self, custo_transicao=lambda s,a,st: 1):
        #self.isObjetivo = is_objetivo
        self.custoTransicao = custo_transicao

        #Estado inicial é padrão
        self.estadoInicial = estado('B',2)
        self.estadoAtual = None
        self.estadoFinal = None

        #Lista de todos os estados possiveis
        self.todosEstadosPossiveis = []

    def acoesPossiveis(self):
        """ AbstractEstado -> (AbstractAcao)
        Cria um generator de ações válidas para self.
        """
        def generator():

            yield
            #
        return

    def transicaoPor(self, acao):
        """ AbstractEstado, AbstractAcao -> AbstractEstado
        Computa o estado adjacente a self ao aplicar uma acao válida.
        """
        return

    def adjacentes(self):
        """ AbstractEstado -> (AbstractEstado)
        Cria um generator de estados adjacentes a self, o estado atual.
        """
        return (self.transicaoPor(acao) for acao in self.acoesPossiveis())

    def todos_estados(self, matriz):
        lista_estados = []
        alfabeto = list(string.ascii_uppercase)

        cod_num = 0
        for coluna in matriz:
            cod_letra = 0
            for linha in coluna:
                bit = matriz[cod_letra][cod_num]
                if bit == 0:
                    estado_aux = estado(alfabeto[cod_letra], cod_num)
                    lista_estados.append(estado_aux)
                elif (bit == 99):
                    estado_saida = estado(alfabeto[cod_letra], cod_num, True)
                    self.estadoFinal = estado_saida
                    lista_estados.append(estado_saida)
                cod_letra += 1
            cod_num += 1
        self.todosEstadosPossiveis = lista_estados

    def transicao(origem, destino):
        x, x_aux = origem.getLetra(), destino.getLetra()
        vx, vx_aux = origem.getValorLetra(), destino.getValorLetra()
        n, n_aux = origem.getNumero(), destino.getNumero()

        if (x == x_aux):
            if n_aux > n:
                #Para frente
                d = 'DIREITA'
            elif n_aux < n:
                #Para tras
                d = 'ESQUERDA'
        elif n == n_aux:
            if vx_aux > vx:
                #Para cima
                d = 'CIMA'
            elif vx_aux < vx:
                #Para baixo
                d = 'BAIXO'

        return transicao(origem,d, destino)

    def estados_adjacentes(self):
        estados = self.todosEstadosPossiveis

        for e in estados:
            for e_aux in estados:
                adjacente = False
                #Adjacentes a X n: X+1 n, X-1 n, X n+1, X n-1

                x, x_aux = e.getLetra(), e_aux.getLetra()
                vx, vx_aux = e.getValorLetra(), e_aux.getValorLetra()
                n, n_aux = e.getNumero(), e_aux.getNumero()

                if ( x == x_aux ):
                    if ( n_aux + 1 == n ) or ( n_aux - 1 == n ):
                        adjacente = True
                elif ( n == n_aux ):
                    if ( vx_aux + 1 == vx ) or (vx_aux - 1 == vx):
                        adjacente = True

                if adjacente: e.estadosAdjacentes.append(e_aux)

    def estados_heuristica(self):
        estados = self.todosEstadosPossiveis

        for e in estados:
            h = HeuristicaLabirinto(e,self.estadoFinal)
            h.getValorH()
            e.heuristica = h

class estado():
    #Modelagem para entender conceitos
    #Baseado na wiki do jogo

    def __init__(self, cod_letra, cod_numero, isObjetivo=False, custo=1):

        #Cod ex A1, B2, Zn...
        self.CodigoObjeto = cod_letra + str(cod_numero)
        self.letra = cod_letra
        self.numero = cod_numero

        #Variavel que diz se é o objetivo(Saida do labirinto)
        self.isObjetivo = isObjetivo

        #Uma transição é representada por: T = (EA, <DIREÇAO>).
        self.Transicao = None

        self.estadosAdjacentes = []

        self.heuristica = None

    def __repr__(self):
        return '<E = ({})>'.format(self.CodigoObjeto)

    def getCodigo(self):
        return self.CodigoObjeto

    def getLetra(self):
        return self.letra

    def getValorLetra(self):
        return self.converteLetra(self.letra)

    def getNumero(self):
        return self.numero

    def preencher(self, mapa_matriz):
        letra = self.CodigoObjeto[0]
        numero = self.CodigoObjeto[1]

        nLetra = converteLetra(letra)
        #Bater com a matriz do mapa
        pontoNoMapa = mapa_matriz[nLetra-1, numero-1]
        pass

    def converteLetra(self, letra):
        alfabeto = list(string.ascii_uppercase)
        letra = letra.upper()
        numeroSaida = 1
        for iLetra in alfabeto:
            if iLetra == letra:
                return numeroSaida
            else:
                numeroSaida += 1
        raise "Letra invalida"

    def definirEstado(self, CodigoObjeto, isParede, EstadoAtual, Transicao):
        self.CodigoObjeto = CodigoObjeto
        self.isParede = isParede
        self.EstadoAtual = EstadoAtual
        self.Transicao = Transicao

class transicao():

    def __init__(self, estadoAtual, direcao, destino):
        self.estadoAtual = estadoAtual
        self.direcao = direcao
        self.destino = destino

    def __repr__(self):
        return '<T = ({}, {})>'.format(self.estadoAtual, self.direcao)

    def getEstadoAtual(self):
        return self.estadoAtual

    def getDirecao(self):
        return self.direcao

    def getDestino(self):
        return self.destino


#!/usr/bin/env python

import numpy as np
import matplotlib.pyplot as plt
import matplotlib

import MITgcmutils as mit

plt.ion()

matplotlib.rcParams['ps.useafm'] = True
matplotlib.rcParams['pdf.use14corefonts'] = True
matplotlib.rcParams['text.usetex'] = True

dir0 = '../run/'

file1 = 'diagU*'
file2 = 'diagV*'
file3 = 'diagKEU*'
file4 = 'diagKEV*'
file5 = 'diagKEs*'

flag_uv = 5 # 1: u , 2: v, 3:KEu, 4:KEv, 5:KEE
flag_grid = 1

#%==================== LOAD FIELDS ===================================

# load grid
if flag_grid:
  XC    = mit.rdmds(dir0+'XC*')
  YC    = mit.rdmds(dir0+'YC*')
  XG    = mit.rdmds(dir0+'XG*')
  YG    = mit.rdmds(dir0+'YG*')
  DXC   = mit.rdmds(dir0+'DXC*')
  DYC   = mit.rdmds(dir0+'DYC*')
  hFacC = mit.rdmds(dir0+'hFacC*')
  hFacS = mit.rdmds(dir0+'hFacS*')
  hFacW = mit.rdmds(dir0+'hFacW*')
  RAS   = mit.rdmds(dir0+'RAS*')
  RAW   = mit.rdmds(dir0+'RAW*')
  RAC   = mit.rdmds(dir0+'RAC*')
  RAZ   = mit.rdmds(dir0+'RAZ*')
  RC    = mit.rdmds(dir0+'RC*')
  RF    = mit.rdmds(dir0+'RF*')
  DRC   = mit.rdmds(dir0+'DRC*')
  DRF   = mit.rdmds(dir0+'DRF*')
  Depth = mit.rdmds(dir0+'Depth*')

if flag_uv == 1:
  filer = file1
elif flag_uv == 2:
  filer = file2
elif flag_uv == 3:
  filer = file3
elif flag_uv == 4:
  filer = file4
elif flag_uv == 5:
  filer = file5

i = 4
iters1 = mit.mds.scanforfiles(dir0 + filer)

utot   = mit.rdmds(dir0 + filer,iters1[i],rec=0)
uadv   = mit.rdmds(dir0 + filer,iters1[i],rec=1)
upress = mit.rdmds(dir0 + filer,iters1[i],rec=2)
u_eta  = mit.rdmds(dir0 + filer,iters1[i],rec=3)
udissh = mit.rdmds(dir0 + filer,iters1[i],rec=4)
udissv = mit.rdmds(dir0 + filer,iters1[i],rec=5)
uext   = mit.rdmds(dir0 + filer,iters1[i],rec=6)
u_ab   = mit.rdmds(dir0 + filer,iters1[i],rec=7)

utot = utot/86400

si_z,si_y,si_x = utot.shape
ix = np.int(si_x/2)

def yzplot(psi,*args, **kwargs):

  vmax = np.max(np.abs((psi)))
  vmax = kwargs.get('vmax', vmax)
  vmin = -vmax
  psi = np.where(psi<vmin,vmin,psi)
  psi = np.where(psi>vmax,vmax,psi)

  title = kwargs.get('title',None)

  fgrid = kwargs.get('fgrid', 0)

  if fgrid:
    xx = YC[:,ix]*1e-3
    yy = RC[:,0,0]
  else:
    si_y,si_x = psi.shape
    xx = np.arange(si_x)
    yy = np.arange(si_y)

  plt.figure()
  plt.contourf(xx,yy,psi,100,cmap=plt.cm.seismic,vmin=vmin,vmax=vmax,extend='both')
  plt.colorbar(format='%.0e')
  plt.title(title)
  if fgrid:
    plt.xlabel('x (km)')
    plt.ylabel('z (m)')

psi = utot[:,:,ix]
yzplot(psi,title=r"tottend (m\,s$^{-2}$)",fgrid=flag_grid,vmax=1e-6)

psi = uadv + upress + udissv + udissh + u_eta + u_ab + uext
psi = psi[:,:,ix]
yzplot(psi,title=r"sum (m\,s$^{-2}$)",fgrid=flag_grid,vmax=1e-6)

error = np.abs(uadv) + np.abs(upress) + np.abs(udissv) + np.abs(udissh) + np.abs(u_eta) + np.abs(u_ab) + np.abs(uext)
error2 = error[:,:,ix]/np.abs(utot[:,:,ix])

psi3 = (psi - utot[:,:,ix])/utot[:,:,ix]/error2
yzplot(psi3,title=r"relative error (m\,s$^{-2}$)",fgrid=flag_grid,vmax=1e-7)


from Interface.Menu import menu, cabecalho
from Gerenciamento_Usuário.Cadastros_Usuarios import cadastro_usuario, login, remove_usuario, editar_usuario, recuperar_senha
from Sistema_Criptografia.Criptografia import run_encrypt, run_decrypt
from time import sleep

op_inicial = ['Cadastrar usuário', 'Fazer login', 'Recuperar senha', 'Sair do sistema']
op_login = ['Criptografar', 'Descriptografar', 'Conta', 'Voltar']
op_conta = ['Editar usuário', 'Excluir usuário', 'Voltar']

def menu_inicial():
    while True:
        controle = menu('SISTEMA DE CRIPTOGRAFIA', op_inicial)
        if controle == 1:
            cadastro_usuario()
        elif controle == 2:
            login_user, user, key = login()
            if login_user:
                menu_login(user, key)
        elif controle == 3:
            recuperar_senha()
        elif controle == 4:
            cabecalho('Saindo do sistema... Até logo!')
            break
        else:
            print('\n\033[31mERRO! Digite uma opção válida!\033[m')
        sleep(2)

def menu_login(user, key):
    while True:
        controle = menu(f'BEM VINDO {user}', op_login)
        if controle == 1:
            run_encrypt(key)
        elif controle == 2:
            run_decrypt()
        elif controle == 3:
            if menu_conta(user):
                break
        elif controle == 4:
            break
        else:
            print('\n\033[31mERRO! Digite uma opção válida!\033[m')
        sleep(2)

def menu_conta(user):
    while True:
        controle = menu('CONTA', op_conta)
        if controle == 1:
            if editar_usuario(user):
                return True
        elif controle == 2:
            if remove_usuario(user):
                return True
        elif controle == 3:
            return False
        else:
            print('\n\033[31mERRO! Digite uma opção válida!\033[m')
        sleep(2)


import cv2
import logging, coloredlogs

face_cascade = cv2.CascadeClassifier('./classifiers/haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('./classifiers/haarcascade_eye.xml')
smile_cascade = cv2.CascadeClassifier('./classifiers/haarcascade_smile.xml')

def detect_n_plot(frame, detect_eyes=True, detect_smile=True, logger=None):
    """
    @Parameters:
        frame: Original frame
        detect_eyes: Whether detect eyes or not
        detect_smile: Whether detect smiles or not
        logger: for logging
    @Returns:
        Frame with boxes surrounding faces and eyes
    """

    # Convert frames to grayscale images because the
    # cascade classifier fits matrices with a single
    # color channel
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # Detect faces
    faces = face_cascade.detectMultiScale(
        gray,
        scaleFactor=1.1,
        minNeighbors=5,
        minSize=(30, 30),
        flags=cv2.CV_8U
    )

    # Plot a rectangle around each face
    for (face_x, face_y, face_w, face_h) in faces:

        if logger:
            logger.info("Face detected at coordinates ({}, {})".format(face_x, face_y))

        cv2.rectangle(frame, (face_x, face_y), (face_x + face_w, face_y + face_h), (0, 255, 0), 2)

        cv2.putText(frame, "Face", (face_x, face_y - 5), cv2.FONT_HERSHEY_DUPLEX, 1, (0, 255, 0))

        # Take the face Region-of-Interest
        roi_frame = frame[face_y : face_y + face_h, face_x : face_x + face_w]
        roi_gray = gray[face_y : face_y + face_h, face_x : face_x + face_w]

        if detect_eyes:
            eyes = eye_cascade.detectMultiScale(
                roi_gray,
                scaleFactor=1.1,
                minNeighbors=5,
                minSize=(30, 30),
                flags=cv2.CV_8U
            )

            for (eye_x, eye_y, eye_w, eye_h) in eyes:
                if logger:
                    logger.info("Eyes detected at coordinates ({}, {})".format(eye_x, eye_y))

                cv2.rectangle(roi_frame, (eye_x, eye_y), (eye_x + eye_w, eye_y + eye_h), (255, 0, 0), 2)

        if detect_smile:
            smiles = smile_cascade.detectMultiScale(
                roi_gray,
                scaleFactor=1.1,
                minNeighbors=5,
                minSize=(30, 30),
                flags=cv2.CV_8U
            )

            for (smile_x, smile_y, smile_w, smile_h) in smiles:
                cv2.rectangle(roi_frame, (smile_x, smile_y), (smile_x + smile_w, smile_y + smile_h), (0, 0, 255), 2)

    return frame

if __name__ == '__main__':

    logger = logging.getLogger(__name__)
    coloredlogs.install(level='DEBUG', logger=logger)   # To show only logs from the above logger

    logger.info("Starting Video Capture ...")

    # Capture video from default webcam
    video_cap = cv2.VideoCapture(0)

    # Iterate over an infinite loop
    while True:
        # Read a single frame
        _, frame = video_cap.read()

        # Detect faces and eyes in this frame
        result = detect_n_plot(frame, detect_smile=False, logger=logger)

        # Show the detection result
        cv2.imshow("Real-time detection", result)

        # Set the 'q' button to quit the program
        if cv2.waitKey(30) & 0xFF == ord('q'):
            break

    video_cap.release()
    cv2.destroyAllWindows()


def hanoi(n, from_pos, to_pos, support_pos):
    if n == 1:
        print(from_pos, "->", to_pos)
        return

    # n-1개의 원반을 시작 기둥에서 보조 기둥으로 이동.(목표기둥은 보조기둥화)
    hanoi(n - 1, from_pos, support_pos, to_pos)

    # 제일 큰 원반을 시작기둥에서  목표 기둥으로 이동.
    print(from_pos, "->", to_pos)

    # n-1개의  보조 기둥의 원반을 목표 기둥으로 이동.(시작 기둥은 보조 기둥화)
    hanoi(n - 1, support_pos, to_pos, from_pos)

#hanoi(1, 1, 3, 2)
hanoi(2, 1, 3, 2)
#hanoi(3, 1, 3, 2)


# -*- coding: gbk -*-
"""
Created on Fri Nov 16 14:32:09 2012

@author: che
"""
######################删除文本里的字母数字等符号#####
import re, os
path_txt = r'D:\dataset\acl10_12_txt'
path_txt2 = r'D:\dataset\acl10_12_txt2'
def delw():
    filelist=os.listdir(path_txt)
    while(len(filelist)>0):
        try:
            name=filelist.pop()
            path=path_txt+'\\'+name
            path2=path_txt2+'\\'+name
            content=open(path,'r')
            r = re.sub('[^a-zA-Z]', " ", content.read())
            #r = re.sub('[0-9\[\!\$\?\-\(\)\.\_\`\=\'\:\;\"\{\}\+\\n\’\×\+\*\?\°\~\<\>\/\\"\,\[\]\@\#\\\&\*\%]', " ",
            #        content.read())
            content2=open(path2,'w')
            content2.write(r)
            content.close()
            content2.close()
        except:
            continue
    finish = '转换完成'
    return finish
if __name__ == '__main__':
    delw()


from django import forms
from django.db.models import Q
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType

import django_filters
from actstream.models import Action
from rest_framework import serializers, viewsets, permissions, mixins, status
from rest_framework.decorators import action
from rest_framework.response import Response

from kitsune.notifications.models import (
    PushNotificationRegistration,
    Notification,
    RealtimeRegistration,
)
from kitsune.sumo.api_utils import OnlyCreatorEdits, DateTimeUTCField, GenericRelatedField

class OnlyOwner(permissions.BasePermission):
    """
    Only allow objects to affected by their owner.

    TODO: This should be tied to user and object permissions better, but
    for now this is a bandaid.
    """

    def has_object_permission(self, request, view, obj):
        user = getattr(request, "user", None)
        owner = getattr(obj, "owner", None)
        # Only the creator can modify things.
        return user == owner

class NotificationSerializer(serializers.ModelSerializer):
    is_read = serializers.ReadOnlyField()
    timestamp = DateTimeUTCField("%Y-%m-%dT%H:%M:%SZ", source="action.timestamp")
    actor = GenericRelatedField(source="action.actor")
    verb = serializers.CharField(source="action.verb")
    action_object = GenericRelatedField(source="action.action_object")
    target = GenericRelatedField(source="action.target")

    class Meta:
        model = PushNotificationRegistration
        fields = (
            "action_object",
            "actor",
            "id",
            "is_read",
            "target",
            "timestamp",
            "verb",
        )

class NotificationFilter(django_filters.FilterSet):
    is_read = django_filters.BooleanFilter(method="filter_is_read", widget=forms.TextInput)

    class Meta(object):
        model = Notification
        fields = [
            "is_read",
        ]

    def filter_is_read(self, queryset, name, value):
        if value:
            return queryset.exclude(read_at=None)
        return queryset.filter(read_at=None)

class NotificationViewSet(
    mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet
):
    queryset = Notification.objects.all()
    serializer_class = NotificationSerializer
    permission_classes = [
        permissions.IsAuthenticated,
        OnlyOwner,
    ]
    filterset_class = NotificationFilter
    pagination_class = None

    def get_queryset(self, *args, **kwargs):
        qs = super(NotificationViewSet, self).get_queryset(*args, **kwargs)
        return qs.filter(owner=self.request.user)

    @action(detail=True, methods=["post"])
    def mark_read(self, request, pk=None):
        """Mark the notification as read."""
        notification = self.get_object()
        notification.is_read = True
        notification.save()
        return Response(status=status.HTTP_204_NO_CONTENT)

    @action(detail=True, methods=["post"])
    def mark_unread(self, request, pk=None):
        """Mark the notification as unread."""
        notification = self.get_object()
        notification.is_read = False
        notification.save()
        return Response(status=status.HTTP_204_NO_CONTENT)

class PushNotificationRegistrationSerializer(serializers.ModelSerializer):
    # Use usernames to reference users.
    creator = serializers.SlugRelatedField(
        slug_field="username", required=False, queryset=User.objects.all()
    )

    class Meta:
        model = PushNotificationRegistration
        fields = (
            "creator",
            "id",
            "push_url",
        )

    def validate(self, data):
        authed_user = getattr(self.context.get("request"), "user")
        creator = data.get("creator")

        if creator is None:
            data["creator"] = authed_user
        elif creator != authed_user:
            raise serializers.ValidationError(
                {"creator": "Can't register push notifications for another user."}
            )

        return data

class PushNotificationRegistrationViewSet(
    mixins.CreateModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet
):
    queryset = PushNotificationRegistration.objects.all()
    serializer_class = PushNotificationRegistrationSerializer
    permission_classes = [
        permissions.IsAuthenticated,
        OnlyCreatorEdits,
    ]

class RealtimeRegistrationSerializer(serializers.ModelSerializer):
    endpoint = serializers.CharField(write_only=True)
    creator = serializers.SlugRelatedField(
        slug_field="username", required=False, queryset=User.objects.all()
    )
    content_type = serializers.SlugRelatedField(
        slug_field="model", queryset=ContentType.objects.all()
    )

    class Meta:
        model = RealtimeRegistration
        fields = [
            "id",
            "creator",
            "created",
            "endpoint",
            "content_type",
            "object_id",
        ]

    def validate(self, data):
        data = super(RealtimeRegistrationSerializer, self).validate(data)
        authed_user = getattr(self.context.get("request"), "user")
        creator = data.get("creator")

        if creator is None:
            data["creator"] = authed_user
        elif creator != authed_user:
            raise serializers.ValidationError(
                "Can't register push notifications for another user."
            )

        return data

class RealtimeActionSerializer(serializers.ModelSerializer):
    action_object = GenericRelatedField(serializer_type="full")
    actor = GenericRelatedField(serializer_type="full")
    target = GenericRelatedField(serializer_type="full")
    verb = serializers.CharField()
    timestamp = DateTimeUTCField()

    class Meta:
        model = PushNotificationRegistration
        fields = (
            "action_object",
            "actor",
            "id",
            "target",
            "timestamp",
            "verb",
        )

class RealtimeRegistrationViewSet(
    mixins.CreateModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet
):
    queryset = RealtimeRegistration.objects.all()
    serializer_class = RealtimeRegistrationSerializer
    permission_classes = [
        permissions.IsAuthenticated,
        OnlyCreatorEdits,
    ]

    @action(detail=True, methods=["get"])
    def updates(self, request, pk=None):
        """Get all the actions that correspond to this registration."""
        reg = self.get_object()

        query = Q(actor_content_type=reg.content_type, actor_object_id=reg.object_id)
        query |= Q(target_content_type=reg.content_type, target_object_id=reg.object_id)
        query |= Q(
            action_object_content_type=reg.content_type, action_object_object_id=reg.object_id
        )

        actions = Action.objects.filter(query)
        serializer = RealtimeActionSerializer(actions, many=True)

        return Response(serializer.data)


import numpy as np

def give_bmi(
    height: list[int | float],
    weight: list[int | float]
) -> list[int | float]:
    """
    docstring
    """
    try:
        pairs = np.stack((height, weight), axis=1)
        res = [x[1] / (x[0] ** 2) for x in pairs]
        return res
    except Exception as err:
        print("Error:", err)

def apply_limit(bmi: list[int | float], limit: int) -> list[bool]:
    """
    docstring
    """
    try:
        arr = np.array(bmi)
        res = [x > limit for x in arr]
        return res
    except Exception as err:
        print("Error:", err)


"""
    Author: Matthew Vallance 001225832
    Purpose: Methods for dealing with friends - describe better...
    Date: 15/01/22
"""

class Friends:
    def __init__(self):
        self.common_friends_matrix = []

    # Can get data through inheritance perhaps?
    def get_common_friends(self, all_users_friends):
        # Run through the list of users and their friends
        for user in all_users_friends:
            common_friends = []
            user_to_compare_friends = user[1]

            # Run through the list of users and their friends again, to work out common friends for each other user
            for friend in all_users_friends:
                user_to_compare_friends_2 = friend[1]

                # Intersection of the two sets of friends - gets a count of the common friends
                friends_intersection = user_to_compare_friends & user_to_compare_friends_2
                common_friends.append(len(friends_intersection))
            # Put the commons friends matrix into an appropriate data structure
            self.common_friends_matrix.append([user[0], common_friends])

        return self.common_friends_matrix

    def recommend_friend(self, common_friends, user): # HOW TO GET THIS FROM CLASS, NOT PASS
        # Check to see if the common friends matrix is filled
        if len(common_friends) == 0:
            print("You need to run menu option 2 first.")
            return False

        if user == '': # ADD PROPER CHECKS HERE
            print("Invalid username.")
            return False

        # Setup variables
        user_friends = 0

        # Find a match for the given user and get common friends count
        for friends in common_friends:
            if friends[0] == user:
                user_friends = friends[1]

        # Split into a sorted/unsorted user_friends array to use later
        user_friends_unsorted = user_friends
        user_friends = sorted(user_friends)

        # Get second highest number in common friends
        second_highest_number = user_friends[-2]

        # Get the name(s) of the recommended friend(s)
        recommended_friends = []
        count = 0
        for number in user_friends_unsorted:
            if number == second_highest_number:
                recommended_friends.append(common_friends[count][0])
            count += 1

        return recommended_friends


from scannertools import audio
from scannertools.transcript_alignment import align_transcript_pipeline, TranscriptAligner
from query.models import Video
from esper.kube import make_cluster, cluster_config, worker_config
from esper.load_aligned_transcript import callback

import scannerpy
import os
import pickle
import math
import tempfile
import re
import sys

SEG_LENGTH = 60

if __name__ == "__main__":

#     video_start = int(sys.argv[1])

    # set test video list
#     video_list = ['MSNBCW_20160614_180000_MSNBC_Live']
#     videos = [Video.objects.filter(path__contains=video_name)[0] for video_name in video_list]

    videos = Video.objects.filter(path__contains='2018')
    addtional_field = pickle.load(open('/app/data/addtional_field_all.pkl', 'rb'))
    videos = [video for video in videos if addtional_field[video.id]['valid_transcript']]

    # second run for bad align videos
#     res_stats = pickle.load(open('/app/result/align_stats_first.pkl', 'rb'))
#     videos = [video for video in videos if video.id in res_stats and res_stats[video.id]['word_missing'] > 0.2]
#     print("Videos total: ", len(videos))

    # remove already dumped videos
    res_stats = pickle.load(open('/app/result/align_stats_final.pkl', 'rb'))
    videos = [video for video in videos if video.id not in res_stats]
    print('Unfinished videos:', len(videos))

    # remove videos have inequal audio/frame time
    videos_valid = []
    for video in videos:
        audio_time = addtional_field[video.id]['audio_duration']
        frame_time = video.num_frames / video.fps
        if audio_time / frame_time < 1.1 and audio_time / frame_time > 0.9:
            videos_valid.append(video)
    videos = videos_valid
    print("Videos valid: ", len(videos))

#     videos = videos[:10]

    # remove videos not saved in database
    db = scannerpy.Database()
    meta = db._load_db_metadata()
    tables_in_db= {t.name for t in meta.tables}
    videos_uncommitted = []
    tables_committed = []
    for video in videos:
        table_name = '{}_align_transcript'.format(video.path)
        if table_name not in tables_in_db:
            videos_uncommitted.append(video)
        else:
            table = db.table(table_name)
            if not table.committed():
                videos_uncommitted.append(video)
            else:
                tables_committed.append(table)
    videos = videos_uncommitted
    print("Videos uncommitted:", len(videos_uncommitted))

    '''batch load'''
    db.batch_load(tables_committed, 'align_transcript', callback)
    exit()

    # load audios from videos
    audios = [audio.AudioSource(video.for_scannertools(),
                                frame_size=SEG_LENGTH,
                                duration=addtional_field[video.id]['audio_duration'])
              for video in videos]

    # set up transcripts
    captions = [audio.CaptionSource('tvnews/subs10/'+video.item_name(),
                                    max_time=addtional_field[video.id]['audio_duration'],
                                    window_size=SEG_LENGTH)
                for video in videos]

    # set up run opts
    run_opts = {'pipeline_instances_per_node': 32, 'checkpoint_frequency': 5, 'io_packet_size': 30, 'work_packet_size': 30}

    # set up align opts
    align_opts = {'win_size': 300,
                  'seg_length' : 60,
                  'max_misalign' : 10,
                  'num_thread' : 1,
                  'estimate' : False,
                  'align_dir' : None,
                  'res_path' : None,
#                   'align_dir' : '/app/result/aligned_transcript',
#                   'res_path' : '/app/result/test_align.pkl',
    }

    '''local run'''
    db = scannerpy.Database()
    result = align_transcript_pipeline(db=db, audio=audios, captions=captions, cache=False,
                                                   run_opts=run_opts, align_opts=align_opts)

    '''kubernete run'''
#     cfg = cluster_config(
#         num_workers=100,
#         worker=worker_config('n1-standard-32'))

#     with make_cluster(cfg, no_delete=True) as db_wrapper:
#         db = db_wrapper.db
#         align_transcript_pipeline(db=db, audio=audios, captions=captions, cache=False,
#                                                        run_opts=run_opts, align_opts=align_opts)

    align_dir = align_opts['align_dir']
    res_path = align_opts['res_path']
    if align_dir is None or res_path is None:
        exit()
    if os.path.exists(res_path):
        res_stats = pickle.load(open(res_path, 'rb'))
    else:
        res_stats = {}

    for idx, res_video in enumerate(result):
        video_name, srt_ext, video_id = videos[idx].item_name(), videos[idx].srt_extension, videos[idx].id
        if res_video is None:
            continue

        align_word_list = []
        num_word_aligned = 0
        num_word_total = 0
        res_video_list = res_video.load()
        for seg_idx, seg in enumerate(res_video_list):
            align_word_list += seg['align_word_list']
            num_word_aligned += seg['num_word_aligned']
            if 'num_word_total' in seg:
                num_word_total += seg['num_word_total']
            else:
                num_word_total += len(seg['align_word_list'])
            print(seg_idx, len(seg['align_word_list']))

        res_stats[video_id] = {'word_missing': 1 - 1. * num_word_aligned / num_word_total}
        print(idx, video_name)
        print('num_word_total: ', num_word_total)
        print('num_word_aligned: ', num_word_aligned)
        print('word_missing by total words: ', 1 - 1. * num_word_aligned / num_word_total)
        print('word_missing by total aligned: ', 1 - 1. * num_word_aligned / len(align_word_list))

        output_path = os.path.join(align_dir, '{}.{}.srt'.format(video_name, 'word'))
        TranscriptAligner.dump_aligned_transcript_byword(align_word_list, output_path)
        pickle.dump(res_stats, open(res_path, 'wb'))


import bpy
import os
from . import helper as H
from . import logger as L

def print_node_inputs(node):
	for i, node in enumerate(node.inputs):
		print(i, node.name)

def print_node_outputs(node):
	for i, node in enumerate(node.outupts):
		print(i, node.name)

def feed_input_indices(context, input_indices):
	channels = [c.channel for c in context.scene.lm_texture_channels]
	names = [n.name for n in context.scene.lm_texture_channels]
	for channel, value in input_indices.items():
		if channel in channels:
			input_indices[channel].update({'name':names[channels.index(channel)]})

	return input_indices

def create_bsdf_material(asset, material, texture_set=None):
	context = asset.context
	log = L.Logger(context='CREATE_BSDF_MATERIAL')
	input_indices = {'Base Color':{'index':0},
					'Metallic':{'index':6},
					'Roughness':{'index':9},
					'Alpha':{'index':21},
					'Normal':{'index':22}}

	input_indices = feed_input_indices(context, input_indices)

	tree = material.node_tree
	nodes = tree.nodes

	location = (0, 0)
	incr = 300

	nodes.clear()

	output = nodes.new('ShaderNodeOutputMaterial')
	output.location = location
	location = (location[0] - incr, location[1])

	shader = nodes.new('ShaderNodeBsdfPrincipled')
	shader.location = location

	# Override default Material parameters
	if context.scene.lm_override_material_color:
		shader.inputs[0].default_value = (context.scene.lm_default_material_color[0], context.scene.lm_default_material_color[1], context.scene.lm_default_material_color[2], 1)
	if context.scene.lm_override_material_roughness:
		shader.inputs[7].default_value = context.scene.lm_default_material_roughness
	if context.scene.lm_override_material_specular:
		shader.inputs[5].default_value = context.scene.lm_default_material_specular
	location = (location[0] - incr - 400, location[1])

	tree.links.new(shader.outputs[0], output.inputs[0])

	if texture_set is not None:
		for channel, input_idx in input_indices.items():
			try:
				t = texture_set[channel]['file']
			except KeyError as k:
				log.warning('No texture found for channel "{}" in the material "{}".'.format(channel, material.name))
				continue

			log.info('Assigning "{}" to material "{}" in the "{}" channel.'.format(os.path.join(os.path.basename(os.path.dirname(t)), os.path.basename(t)), material.name, channel))

			if t is None:
				continue
			if channel == 'Alpha':
				material.blend_method = 'HASHED'
				material.alpha_threshold = 0.2

			material_texture = context.scene.lm_asset_list[asset.asset_name].material_list[material.name].texture_list.add()
			material_texture.file_path = t
			material_texture.channel = channel

			dir_name = os.path.dirname(t)
			file_name = os.path.basename(t)

			texture = nodes.new('ShaderNodeTexImage')

			initial_scene_textures = list(bpy.data.images)

			bpy.ops.image.open(filepath=t, directory=dir_name, show_multiview=False)

			new_scene_textures = list(bpy.data.images)

			new_image = H.get_different_items(initial_scene_textures, new_scene_textures)

			if not len(new_image):
				for i in bpy.data.images:
					if i.filepath == t:
						i.name = file_name
						new_image = i.name
						break
				else:
					new_image = file_name
			else:
				new_image[0].name = file_name
				new_image = new_image[0].name

			material_texture.name = new_image
			material_texture.image = bpy.data.images[new_image]

			texture.image = bpy.data.images[new_image]
			texture.label = os.path.splitext(new_image)[0]

			texture.location = location

			inverted = texture_set[channel]['inverted']

			if texture_set[channel]['normal_map']:
				normal_map = nodes.new('ShaderNodeNormalMap')
				normal_map.location = (location[0] + incr, location[1])

				if inverted:
					combine = nodes.new('ShaderNodeCombineRGB')
					combine.location = location
					location = (location[0] - incr/2, location[1])

					invert = nodes.new('ShaderNodeInvert')
					invert.location = location
					location = (location[0] - incr/2, location[1])

					separate = nodes.new('ShaderNodeSeparateRGB')
					separate.location = location
					location = (location[0] - incr, location[1])

					texture.location = location

					tree.links.new(texture.outputs[0], separate.inputs[0])

					tree.links.new(separate.outputs[0], combine.inputs[0])
					tree.links.new(separate.outputs[1], invert.inputs[1])
					tree.links.new(separate.outputs[2], combine.inputs[2])

					tree.links.new(invert.outputs[0], combine.inputs[1])

				texture.image.colorspace_settings.name = 'Linear'

				if inverted:
					tree.links.new(combine.outputs[0], normal_map.inputs[1])
				else:
					tree.links.new(texture.outputs[0], normal_map.inputs[1])

				tree.links.new(normal_map.outputs[0], shader.inputs[input_idx['index']])
			else:
				if texture_set[channel]['linear']:
					texture.image.colorspace_settings.name = 'Linear'

				if inverted:
					invert = nodes.new('ShaderNodeInvert')
					invert.location = location
					location = (location[0] - incr, location[1])

					tree.links.new(texture.outputs[0], invert.inputs[1])
					tree.links.new(invert.outputs[0], shader.inputs[input_idx['index']])
				else:
					tree.links.new(texture.outputs[0], shader.inputs[input_idx['index']])

			location = (location[0], location[1] - incr)
	return output


lista = []
pessoas = []
maior = menor = 0
while True:
    lista.append(str(input('Digite o nome: ')))
    lista.append(float(input('Digite o peso: ')))
    if len(pessoas) == 0:
        maior = menor = lista[1]
    else:
        if lista[1] > maior:
            maior = lista[1]
        if lista[1] < menor:
            menor = lista[1]
    pessoas.append(lista[:])
    lista.clear()
    opção = str(input('Quer continuar? [S/N ]')).strip().upper()[0]
    if opção == 'N':
        break
print(f'Quantidade: {len(pessoas)}')
print(f'Maior Peso {maior}')
print(f'Menor Peso {menor}')


import asyncio
import json
import re

import lxml.html
import pyppeteer

import pandas as pd

file_path = 'tmp.csv'
tmp = pd.read_csv(file_path, sep='\t')

URLS = ['http://'+ x[2:-1] for x in list(tmp['d1'].append(tmp['d2'].append(tmp['d3'])).dropna())]

async def get_metadata_from_url(browser, url):
    page = await browser.newPage()
    await page.setViewport({'width': 1680, 'height': 1050})
    await page.setUserAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36')

    try:
        await page.goto(url, timeout=20000)  # 10 seconds
    except Exception as e:
        return {"url": url, "titles": None, "keywords": None, "error": str(e)}

    html = await page.content()

    tree = lxml.html.fromstring(html)

    title = tree.find('.//title')
    if title is not None:
        title = title.text_content().strip()

    keywords = tree.find('.//meta[@name="keywords"]')
    if keywords is not None:
        keywords = keywords.attrib.get('content', '').strip()

    await page.close()

    return {
        'url': url,
        'title': title,
        'keywords': keywords,
    }

def chunkify(seq, size):
    return (seq[pos:pos + size] for pos in range(0, len(seq), size))

async def main():
    browser = await pyppeteer.launch(
        headless=False,
        args=['--window-size=10,10']
    )

    # # список урлов из файла
    # with open('titles-urls.txt', 'r') as f:
    #     URLS = [line.strip() for line in f.read().split('\n') if line.strip()]

    results = []
    chunks = chunkify(URLS, 10)
    for chunk in chunks:
        tasks = [get_metadata_from_url(browser, url) for url in chunk]
        chunk_results = await asyncio.gather(*tasks)

        for result in chunk_results:
            for k, v in result.items():
                print(f'{k:<10s} {v}')
            print('-' * 80)

        results += chunk_results

    with open('titles-pyppeteer.json', 'w') as f:
        json.dump(results, f)
    print('results saved: titles-pyppeteer.json')

    await browser.close()

if __name__ == '__main__':
    asyncio.get_event_loop().run_until_complete(
        main()
    )


#binary tree is essentially a linked list starting with a node that has pointers to the left and right
#each pointer points to the left or the right
#in a full tree each node either points to zero nodes or two nodes
#a perfect tree represents a tree that is level all the way across
#top node pointing to other nodes is known as the parent node pointing to a child node
#nodes with the same parent are known as siblings
#every node can onlu have one parent
# {
#     "value": 4,
#     "left": None,
#     "right" None
# }

class Node:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

class BinarySearchTree:
    def __init__(self):
#instead of head, the top node is referred to as the root node (self.root)
        self.root = None

#insert method BST
    def insert(self, value):
        new_node = Node(value)
        if self.root is None:
            self.root = new_node
            return True
        temp = self.root
        while (True):
            if new_node.value == temp.value:
                return False
            if new_node.value < temp.value:
                if temp.left is None:
                    temp.left = new_node
                    return True
                temp = temp.left
            else:
                if temp.right is None:
                    temp.right = new_node
                    return True
                temp = temp.right

    def contains(self, value):
        temp = self.root
        while temp is not None:
            if value < temp.value:
                temp = temp.left
            elif value > temp.value:
                temp = temp.right
            else:
                return True
        return False

my_tree = BinarySearchTree()
my_tree.insert(47)
my_tree.insert(21)
my_tree.insert(76)
my_tree.insert(18)
my_tree.insert(27)
my_tree.insert(52)
my_tree.insert(82)

print(my_tree.contains(27))
print(my_tree.contains(17))
# print(my_tree.root.left.value)
# print(my_tree.root.right.value)

#within a binary search tree, nodes need to be laid out in a certain way
#if the child node is greater in value than the parent node it will go on the right,
#if it is less than it will go on the left

#binary search tree Big O is O(log n)
#lookup, insery and remove are treated as O(log n)


#!/usr/bin/python

import os

import app

class Main(app.App):
    def parse_args(self):
        opts, args = super(Main, self).parse_args()

        try:
            repo = args[0]
        except IndexError:
            self.parser.error('Missing arguments REPO.')

        opts.instancedir = os.path.abspath(os.path.join(repo, '../../'))

        return opts, args

if __name__ == '__main__':
    Main().main()


from rest_framework.test import APIClient

from testing.testcases import TestCase
from society_manage.models import CreditDistribution
from society.constants import SocietyStatus

class StudentTests(TestCase):
    def test_get_student(self):
        user = self.createUser(username='ncj')
        student = self.createStudent(user=user)
        url = '/api/student/{}/'.format(student.id)
        client = APIClient(enforce_csrf_checks=True)
        client.force_authenticate(user)
        response = client.get(url, decode=False)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data['name'], student.name)
        self.assertEqual(response.data['grade'], student.grade)
        self.assertEqual(response.data['class_num'], student.class_num)

    def test_permission(self):
        user1 = self.createUser(username='ncj')
        student1 = self.createStudent(user=user1)
        user2 = self.createUser(username='ncj2')
        url = '/api/student/{}/'.format(student1.id)
        client = APIClient(enforce_csrf_checks=True)
        client.force_authenticate(user2)
        response = client.get(url, decode=False)
        self.assertEqual(response.status_code, 403)

    def test_object_permission(self):
        user1 = self.createUser(username='ncj')
        student1 = self.createStudent(user=user1)
        user2 = self.createUser(username='ncj2')
        student2 = self.createStudent(user=user2)
        url = '/api/student/{}/'.format(student1.id)
        client = APIClient(enforce_csrf_checks=True)
        client.force_authenticate(user2)
        response = client.get(url, decode=False)
        self.assertEqual(response.status_code, 403)

    def test_update_student_profile(self):
        user = self.createUser('qltnb')
        student = self.createStudent(user=user)
        url = '/api/student/{}/'.format(student.id)
        client = APIClient(enforce_csrf_checks=True)
        client.force_authenticate(user)
        data = {
            'class_num': '2',
            'grade': '3',
            'qq': '123',
            'name': '上科大龙田酱'
        }
        response = client.patch(url, data=data, decode=True)
        self.assertEqual(response.status_code, 200)
        student.refresh_from_db()
        self.assertEqual(student.class_num, 2)
        self.assertEqual(student.grade, 3)
        self.assertEqual(student.qq, '123')
        self.assertEqual(student.name, '上科大龙田酱')
        response = self.client.patch(url, data=data, decode=True)
        self.assertEqual(response.status_code, 403)

class StudentCreditTests(TestCase):
    def setUp(self):
        self.user1 = self.createUser('jw')
        self.student1 = self.createStudent(self.user1)

    def test_get_credit_distribution(self):
        url = '/api/student/credit/'

        client = APIClient(enforce_csrf_checks=True)
        client.force_authenticate(self.user1)

        res = client.get(url, decode=True)
        self.assertEqual(res.status_code, 200)

        society_user = self.createUser('society')
        society = self.createSociety(society_user, members=None)
        credit_distribution = CreditDistribution.objects.create(
            society=society,
            year=2019,
            semester=1
        )
        credit_distribution.receivers.add(self.student1)

        credit_distribution2 = CreditDistribution.objects.create(
            society=society,
            year=2019,
            semester=2
        )
        credit_distribution2.receivers.add(self.student1)

        res = client.get(url, decode=True)
        self.assertEqual(res.status_code, 200)
        self.assertEqual(res.data['results'][0]['society']['name'], society.name)
        self.assertEqual(res.data['results'][0]['semester'], credit_distribution2.semester)
        self.assertEqual(res.data['results'][0]['year'], credit_distribution2.year)

        self.assertEqual(res.data['results'][1]['year'], credit_distribution.year)

        # test is_authenticated permission
        res = self.client.get(url)
        self.assertEqual(res.status_code, 403)

        client.force_authenticate(society_user)
        res = client.get(url)
        self.assertEqual(res.status_code, 403)

class StudentSocietyTests(TestCase):
    def setUp(self):
        self.user1 = self.createUser('jw')
        self.user2 = self.createUser('society1')
        self.user3 = self.createUser('society2')
        self.student1 = self.createStudent(self.user1)
        self.society1 = self.createSociety(user=self.user2, members=[self.student1], status=SocietyStatus.ACTIVE)
        self.society2 = self.createSociety(user=self.user3, status=SocietyStatus.ACTIVE)

    def test_student_list_societies(self):
        url = '/api/student/society/'

        client = APIClient(enforce_csrf_checks=True)
        res = client.get(url, decode=True)
        self.assertEqual(res.status_code, 403)

        client.force_authenticate(self.user1)
        res = client.get(url, decode=True)
        self.assertEqual(res.data['count'], 1)
        self.assertEqual(res.data['results'][0]['id'], 1)


import json
import uuid

from regression import test_utils as utils
from regression import parent_node_dict
from pgadmin.utils.route import BaseTestGenerator
from pgadmin.browser.server_groups.servers.databases.tests import utils as \
    database_utils
from pgadmin.browser.server_groups.servers.databases.schemas.tests import \
    utils as schema_utils
from pgadmin.browser.server_groups.servers.databases.schemas.tables.tests \
    import utils as tables_utils

class IndexesAddTestCase(BaseTestGenerator):
    """This class will add new index to existing table column"""
    scenarios = [
        ('Add index Node URL', dict(url='/browser/index/obj/'))
    ]

    def setUp(self):
        self.db_name = parent_node_dict["database"][-1]["db_name"]
        schema_info = parent_node_dict["schema"][-1]
        self.server_id = schema_info["server_id"]
        self.db_id = schema_info["db_id"]
        db_con = database_utils.connect_database(self, utils.SERVER_GROUP,
                                                 self.server_id, self.db_id)
        if not db_con['data']["connected"]:
            raise Exception("Could not connect to database to add a table.")
        self.schema_id = schema_info["schema_id"]
        self.schema_name = schema_info["schema_name"]
        schema_response = schema_utils.verify_schemas(self.server,
                                                      self.db_name,
                                                      self.schema_name)
        if not schema_response:
            raise Exception("Could not find the schema to add a table.")
        self.table_name = "table_for_column_%s" % (str(uuid.uuid4())[1:6])
        self.table_id = tables_utils.create_table(self.server, self.db_name,
                                                  self.schema_name,
                                                  self.table_name)

    def runTest(self):
        """This function will add index to existing table column."""
        self.index_name = "test_index_add_%s" % (str(uuid.uuid4())[1:6])
        data = {"name": self.index_name,
                "spcname": "pg_default",
                "amname": "btree",
                "columns": [
                    {"colname": "id", "sort_order": False, "nulls": False}]}
        response = self.tester.post(
            self.url + str(utils.SERVER_GROUP) + '/' +
            str(self.server_id) + '/' + str(self.db_id) +
            '/' + str(self.schema_id) + '/' + str(self.table_id) + '/',
            data=json.dumps(data),
            content_type='html/json')
        self.assertEquals(response.status_code, 200)

    def tearDown(self):
        # Disconnect the database
        database_utils.disconnect_database(self, self.server_id, self.db_id)


from pathlib import Path
import sys

parent_dir = Path(__file__).parent
file_name = Path(__file__).stem

sys.stdin = open(f"{parent_dir}\{file_name} input.txt")
input = sys.stdin.readline

def find_longest_palindrome_in_row(matrix):
    # 가장 먼 곳에서부터 가까이 오면서 회문 판별하기
    longest_len = 1

    for row in range(N):
        for col in range(N):
            # 먼 곳에서부터 오면서
            for end in range(N - 1, col, -1):
                # 처음과 같은 걸 찾는다.
                if matrix[row][col] == matrix[row][end]:
                    length = end - col + 1
                    # 구간이 현재 최대 길이보다 짧다면 건너띈다.
                    if length < longest_len:
                        break
                    # 처음과 같은 문자를 기점으로 점점 좁혀오고,
                    for diff in range(length // 2):
                        # 중간에 틀린 게 있으면 종료 후, 다시 처음과 같은 걸 찾는다.
                        if matrix[row][col + diff] != matrix[row][end - diff]:
                            break
                    else:
                        longest_len = length if length > longest_len else longest_len
            # 처음과 같아지면 다음 글자로 완전히 넘어간다.

    return longest_len

def find_longest_palindrome_in_col(matrix):
    # 가장 먼 곳에서부터 가까이 오면서 회문 판별하기
    longest_len = 1

    # 먼 곳에서부터 오면서
    for col in range(N):
        for row in range(N):
            for end in range(N - 1, row, -1):
                # 처음과 같은 걸 찾는다.
                if matrix[row][col] == matrix[end][col]:
                    length = end - row + 1
                    if length < longest_len:
                        break
                    # 그 애를 기점으로 점점 좁혀오고,
                    for diff in range(length // 2):
                        # 중간에 틀린 게 있으면 종료 후, 다시 처음과 같은 걸 찾는다.
                        if matrix[row + diff][col] != matrix[end - diff][col]:
                            break
                    else:
                        longest_len = length if length > longest_len else longest_len
            # 처음과 같아지면 다음 글자로 완전히 넘어간다.

    return longest_len

N = 100

T = 10
for test_case in range(1, T + 1):
    input()
    matrix = [list(input()) for _ in range(N)]
    longest_in_row = find_longest_palindrome_in_row(matrix)
    longest_in_col = find_longest_palindrome_in_col(matrix)

    if longest_in_row > longest_in_col:
        print("#{} {}".format(test_case, longest_in_row))
    else:
        print("#{} {}".format(test_case, longest_in_col))


# This is the main training setup for training a Pensieve model, but
# stopping at intervals to add new training data based on performance
# (increases generalizability, we hope!)
import sys
import subprocess
import numpy as np
import os
from bayes_opt import BayesianOptimization
# Inputs:
#
# - experiment results directory
# - training data directory (with traces in subdirectories)
# - total epochs
# - bayesian optimizer interval (e.g., every 5000 epochs) - this is how many epoch each training run will go

# Defaults
# Improvement: Probably better if replaced with argparse and passed in (later)
# TOTAL_EPOCHS = 10000
# BAYESIAN_OPTIMIZER_INTERVAL = 1000
TRAINING_DATA_DIR = "../data/generated_traces_ts_float-BO/train_4_rebuf_4_3/"
VAL_TRACE_DIR = '../data/generated_traces_ts_float-BO/val'
RESULTS_DIR = "../BO-results/randomize-BW-rebuf_4_3"
#NN_MODEL='../new-DR-results/sanity-check-2/model_saved/nn_model_ep_33200.ckpt'

# num_training_runs = int(TOTAL_EPOCHS / BAYESIAN_OPTIMIZER_INTERVAL)

MIN_BW = 1
MAX_BW = 500

# def map_lin_to_log(x):
#     x_log = (np.log(x) - np.log(MIN_BW)) / (np.log(MAX_BW) - np.log(MIN_BW))
#     return x_log

# def map_log_to_lin(x):
#     x_lin = np.exp((np.log(MAX_BW)-np.log(MIN_BW))*x + np.log(MIN_BW))
#     return x_lin

def map_log_to_lin(x):
    x_lin = 2**(10*x)
    return x_lin

def latest_actor_from(path):
    """
    Returns latest tensorflow checkpoint file from a directory.
    Assumes files are named:
    nn_model_ep_<EPOCH#>.ckpt.meta
    """
    mtime = lambda f: os.stat( os.path.join( path ,f ) ).st_mtime
    files = list( sorted( os.listdir( path ) ,key=mtime ) )
    actors = [a for a in files if "nn_model_ep_" in a]
    actor_path = str( path + '/' + actors[-1] )
    return os.path.splitext( actor_path )[0]

def black_box_function(x):
    '''
    :param x: input is the current params
    :return: reward is the mpc-rl reward
    '''
    # TODO: this need to be args.summary_dir
    # TODO: do i need to load the actor_path here?
    path = os.path.join( RESULTS_DIR, 'model_saved' )
    latest_model_path = latest_actor_from(path)
    #print(latest_model_path)

    x_map = map_log_to_lin(x)

    command = " python rl_test.py  \
                --CURRENT_PARAM={current_max_tp_param} \
                --test_trace_dir='../data/example_traces/' \
                --summary_dir='../MPC_RL_test_results/' \
                --model_path='{model_path}' \
                ".format(current_max_tp_param=x_map, model_path=latest_model_path)

    r = float(subprocess.check_output(command, shell=True, text=True).strip())
    return r

# the 1st round of training
command = "python multi_agent.py \
                    --TOTAL_EPOCH=8000\
                    --train_trace_dir={training_dir} \
                    --val_trace_dir='{val_dir}'\
                    --summary_dir={results_dir}\
                    --description='first-run'" \
                    .format(training_dir=TRAINING_DATA_DIR, val_dir=VAL_TRACE_DIR,
                            results_dir=RESULTS_DIR)
os.system( command )

# Example Flow:
for i in range(15):
    # if i > 0:
    pbounds = {'x': (0 ,1)}
    optimizer = BayesianOptimization(
        f=black_box_function ,
        pbounds=pbounds
        #random_state=2
    )

    optimizer.maximize(
        init_points=13,
        n_iter=2,
        kappa=20,
        xi=0.1
    )
    next = optimizer.max
    param = next.get( 'params' ).get( 'x' )
    #bo_best_param = round( param ,2 )
    bo_best_param = map_log_to_lin(param)
    print( "BO chose this best param........", param, bo_best_param )

    # Use the new param, add more traces into Pensieve, train more based on before
    path = os.path.join( RESULTS_DIR ,'model_saved' )
    latest_model_path = latest_actor_from( path )

    command = "python multi_agent.py \
                    --TOTAL_EPOCH=5000\
                    --train_trace_dir={training_dir} \
                    --val_trace_dir='{val_dir}'\
                    --summary_dir={results_dir}\
                    --description='first-run' \
                    --nn_model={model_path} \
                    --CURRENT_PARAM={bo_output_param}"  \
                    .format(training_dir=TRAINING_DATA_DIR, val_dir=VAL_TRACE_DIR,
                            results_dir=RESULTS_DIR, model_path=latest_model_path, bo_output_param=bo_best_param)
    os.system(command)

    print("Get the file and pass it to the training script, if it exists.\n")
    print("Running training:", i)
    i += 1

print("Hooray!")


import hashlib
import sys
# your gen-py dir
sys.path.append('./gen-py')
from ril.ttypes import *
import json

class FileData():

    def __init__(self, instanceName=None):
        self.inputfilename=f"/var/lib/data-test/{instanceName}_inputs.json"
        self.outputfilename=f"/var/lib/data-test/{instanceName}_outputs.json"
        self.outputs={}
        try:
            with open(self.inputfilename) as f:
                self.inputs = json.load(f)
        except:
            self.inputs ={}
        self.step_idx = 0

    def doStep(self):
        self.step_idx+=1

    def read(self, var_ref):
        if (str(var_ref) in self.inputs):
            var_inputs = self.inputs.get(str(var_ref))
            if (len(var_inputs) > self.step_idx):
                return var_inputs[self.step_idx]
            else:
                return None
        else:
            return None

    def write(self, var_ref, value):
        if (not str(var_ref) in self.outputs):
            self.outputs[str(var_ref)] = []
        var_outputs = self.outputs.get(str(var_ref))
        if (len(var_outputs) <= self.step_idx ):
            var_outputs.append(value)
        else:
            var_outputs[self.step_idx] = value

    def dump(self):
        with open(self.outputfilename, 'w') as outfile:
            json.dump( self.outputs, outfile)


import datetime
import logging
import os
import time
from collections import namedtuple

from .milight import Mode, Off
from .colors import C_WARM_WHITE, WARM_WHITE, WHITE, ORANGE, RED

class Gradient:
    def __init__(self, mode1: Mode, mode2: Mode):
        self.mode1 = mode1
        self.mode2 = mode2

    def at(self, ratio):
        return self.mode1.mix(self.mode2, ratio=float(ratio))

O = "office"
K = "dining"
E = "entrance"

def OKE(mode):
    return {k: mode for k in (O, K, E)}

DUSK = ORANGE._replace(brightness=75)
DAY = WHITE
NIGHTLIGHT = RED._replace(brightness=25)
DO_NOTHING = None
OFF = Off()

SUNRISE_1 = Gradient(
    C_WARM_WHITE._replace(brightness=0), C_WARM_WHITE._replace(brightness=80)
)
SUNRISE_2 = Gradient(WARM_WHITE._replace(brightness=85), DAY)
SUNSET_0 = Gradient(DAY, WARM_WHITE._replace(brightness=85))
SUNSET_1 = Gradient(C_WARM_WHITE._replace(brightness=85), DUSK)
SUNSET_2 = Gradient(DUSK, DUSK.mix(NIGHTLIGHT, ratio=0.3))
SUNSET_3 = Gradient(DUSK.mix(NIGHTLIGHT, ratio=0.3), NIGHTLIGHT)
SUNSET = Gradient(C_WARM_WHITE, NIGHTLIGHT)

# fmt: off
early_morning = {
    "4:00-7:45": {O: OFF, K: OFF, E: NIGHTLIGHT},
    "7:45-8:30": OKE(SUNRISE_1),
    "8:30-09:00": OKE(SUNRISE_2),
    "8:30-20:00": OKE(DAY),
}

late_morning = {
    "4:00-10:45": {O: OFF, K: OFF, E: NIGHTLIGHT},
    "10:45-11:30": OKE(SUNRISE_1),
    "11:30-12:00": OKE(SUNRISE_2),
    "12:00-20:00": OKE(DAY),
}

early_night = {
    "20:00-21:30": OKE(SUNSET_0),
    "21:30-23:00": OKE(SUNSET_1),
    "23:00-23:59": OKE(SUNSET_2),
    "00:00-00:30": OKE(SUNSET_3),
    "00:30-04:00": {O: OFF, K: OFF, E: NIGHTLIGHT},
}

late_night = {
    "20:00-21:30": OKE(SUNSET_0),
    "21:30-23:00": OKE(SUNSET_1),
    "23:00-23:59": OKE(DO_NOTHING),
    "00:00-01:30": OKE(DO_NOTHING),
    "01:30-04:00": {O: OFF, K: OFF, E: NIGHTLIGHT},
}
# fmt: on
weekdays = dict(enumerate(["mon", "tue", "wed", "thu", "fri", "sat", "sun"], 1))

def combine(*schedules):
    sched = {}
    for s in schedules:
        sched.update(s)
    return sched

schedule = {
    "mon": combine(early_morning, early_night),
    "tue": combine(early_morning, early_night),
    "wed": combine(early_morning, early_night),
    "thu": combine(early_morning, early_night),
    "fri": combine(early_morning, late_night),
    "sat": combine(late_morning, late_night),
    "sun": combine(late_morning, early_night),
}

def get_mode(color, ratio):
    if isinstance(color, Gradient):
        return color.at(ratio)
    else:
        return color

def parse_time(time: str) -> datetime.time:
    return datetime.datetime.strptime(time, "%H:%M").time()

def minute_of_day(time: datetime.time) -> int:
    return time.hour * 60 + time.minute

class Scheduler:
    Period = namedtuple("Period", ["start_time", "end_time", "zones"])

    def __init__(self, controller, schedule, delay=3, pausefile=None):
        self.controller = controller
        self.schedule = {k: self.parse_schedule(s) for k, s in schedule.items()}
        self.modes = {}
        self.delay = delay
        self.pausefile = pausefile

    def run(self):
        while True:
            if self.pausefile is None or not os.path.exists(self.pausefile):
                self.set_lights(datetime.datetime.now())
            time.sleep(self.delay)

    def set_lights(self, now: datetime.datetime):
        # Pretend that midnight-4am belongs to previous day
        weekday = weekdays[(now - datetime.timedelta(hours=4)).isoweekday()]
        time = now.time()
        logging.debug("Using schedule for {} at {:%H:%M}".format(weekday.upper(), time))
        sched = self.schedule[weekday]
        self.modes = self.get_modes_at(sched, time)
        for zone, mode in self.modes.items():
            if mode is not None:
                logging.debug("Setting {!r} to {!r}".format(zone, mode))
                self.controller.set(zone, mode)

    def period_progress(self, period, at_time):
        start = minute_of_day(period.start_time)
        end = minute_of_day(period.end_time)
        at = minute_of_day(at_time)
        return (at - start) / (end - start)

    def get_modes_at(self, schedule, time: datetime.time):
        for period in schedule:
            if time >= period.start_time and time <= period.end_time:
                ratio = self.period_progress(period, time)
                modes = {}
                for name, color in period.zones.items():
                    modes[name] = get_mode(color, ratio)
                return modes

    def parse_schedule(self, schedule):
        sched = []
        for times, zones in schedule.items():
            start, end = [parse_time(t) for t in times.split("-")]
            sched.append(self.Period(start, end, zones))
        return sorted(sched, key=lambda s: s.start_time)


"""
Plot the monod function and holling tyoe II for growth and predation rates
"""
import numpy as np
import matplotlib.pyplot as plt

def f_monod(PO4,u_max,kP,color):
    PO4 = np.array(PO4)
    mu = (PO4/(PO4+kP))*u_max
    plt.scatter(PO4,mu,5,color=color)
    return mu

def f_hollingII(P,sum_P,g_max,kZ,color):
    P = np.array(P)
    sum_P = np.array(sum_P)
    g = (P/(sum_P+kZ))*g_max
    plt.scatter(P,g,5,color=color)
    return g


import os
import requests
from flask import Flask, render_template, request, jsonify
from flask_socketio import SocketIO, emit
def call(new):
    newnew=""
    for i in range (0,len(new)-1):
        if (new[i]==" " and new[i+1]==" "):
            newnew=newnew
        else:
            newnew=newnew+new[i]
    if (new[-1]!=" "):
        newnew=newnew+new[-1]
    if (newnew[0]==" "):
        newnew=newnew[1 : : ]
    return newnew

def soloCanal(soloCanales):
  salasChat=[]
  for i in soloCanales:
    salasChat.append(i["canal"])
  return salasChat

app = Flask(__name__)
app.config["SECRET_KEY"] = os.getenv("SECRET_KEY")
socketio = SocketIO(app)
channels=[]
channelsA=[]
channelsA.append({"canal":"jose","chat":["jajaja","jijiji"],"usuarios":[]})
channels.append("jose")
mensajes=["jajaj"]
@app.route("/")
def index():
    return render_template("start.html")
    # return render_template("createRoom.html",nName="jose",channels=channels)

@app.route("/newChannels",methods=["POST"])
def newChannels():
    newChannel = call(request.form.get("newChannel"))
    userName = request.form.get("username")
    for k in channelsA:
        if newChannel == k["canal"]:
            print(k["canal"],k["chat"])
            return jsonify({"success":False,"newChannel":channels})

    channelsA.append({"canal":newChannel,"chat":[],"usuarios":[]})
    channels.append(newChannel)
    print(channelsA[-1]["canal"],channelsA[-1]["chat"])
    return jsonify({"success":True,"newChannel":channelsA[-1]["canal"]})

    # if (newChannel in channels):
    #     return jsonify({"success":False,"newChannel":channels})
    # else:
    #     channels.append(newChannel)
    #     return jsonify({"success":True,"newChannel":channels[-1]})

@app.route("/chatList",methods=["POST"])
def chatList():
     if request.method == "POST":
        nickName=request.form.get("nickName")
        return render_template("createRoom.html",nName=nickName,channels=soloCanal(channelsA))
     return "error"

@app.route("/chatList/<Source>", methods=["GET","POST"] )
def bookdata(Source):
    # return jsonify({"success":True,"Source":Source})
    userName=request.form.get("userName")
    for k in channelsA:
        if Source == k["canal"]:
            print("::::::::::::::::::::::::::::::::::")
            print(userName)

            return render_template("index.html",mensajes=k["chat"],source=Source,userName=userName)

@socketio.on("submit mensaje")
def vote(data):
    contenido = data["contenido"]
    roomName = data["nombreCanal"]
    userName=data["userName"]
    print("---------------------------------------------")
    print({"contenido": contenido,"roomName":roomName,"userName":userName})
    for k in channelsA:
        if roomName == k["canal"]:
            k["chat"].append(contenido)
            k["usuarios"].append(userName)
    # mensajes.append(contenido)
    emit("announce mensaje", {"contenido": contenido,"roomName":roomName,"userName":userName}, broadcast=True)

# if __name__ == "__main__":
#     socketio.run(app)


import pymongo
from loguru import logger

from DB.db import client

db: pymongo.database.Database = client.session_url_tokens
def create_new_session(guild, url_token):
    try:
        db.session_url_tokens.replace_one({'_id': str(guild.id)}, {'_id': str(guild.id), 'url_token': str(url_token)})
        logger.info(f"Token updated guild.id - {guild.id}")
    except Exception as ex:
        logger.error(f"Cant get server info {ex}")


from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class World(Base):
    __tablename__ = 'world'
    id = Column(Integer, primary_key=True)
    randomnumber = Column(Integer)

sa_worlds = World.__table__

class Fortune(Base):
    __tablename__ = 'fortune'
    id = Column(Integer, primary_key=True)
    message = Column(String)

sa_fortunes = Fortune.__table__


#! /usr/bin/env python3

"""
$ bintut -b0.3 ret2lib

... skipped ...

Traceback (most recent call last):
  File "/home/blind7/safe/trustworthy/public-repo/bintut.git/bintut/entry.py", line 56, in <module>
    start_tutor(course, bits, burst, aslr, level)
  File "/home/blind7/safe/trustworthy/public-repo/bintut.git/bintut/courses/main.py", line 72, in start_tutor
    payload = make_payload(offset, addr, course)
  File "/home/blind7/safe/trustworthy/public-repo/bintut.git/bintut/courses/exploits.py", line 42, in make_payload
    payload = Fill(offset) + Ret2Fun()
  File "/home/blind7/safe/trustworthy/public-repo/bintut.git/bintut/courses/exploits.py", line 120, in __add__
    return Payload(self.compose() + other.compose())
  File "/home/blind7/safe/trustworthy/public-repo/bintut.git/bintut/courses/exploits.py", line 200, in compose
    binsh = resolver.get('/bin/sh')
  File "/home/blind7/safe/trustworthy/public-repo/bintut.git/bintut/courses/exploits.py", line 309, in get
    return self.get_bin_sh_address()
  File "/home/blind7/safe/trustworthy/public-repo/bintut.git/bintut/courses/exploits.py", line 351, in get_bin_sh_address
    raise RuntimeError('Failed to find /bin/sh!')
RuntimeError: Failed to find /bin/sh!
"""

from binascii import hexlify
from shutil import which

from ropper import Loader, Ropper

if __name__ == '__main__':
    # Arch:   /usr/lib32/libc-2.28.so
    # Fedora: /usr/lib/libc-2.26.so
    libc = Loader.open('/usr/lib32/libc.so.6' if which('pacman') else '/lib/libc.so.6')
    ropper = Ropper()

    code = hexlify(b'/bin/sh').decode('utf-8')
    print(code)

    opcode, size = ropper._formatOpcodeString(code)
    for sec in libc.executableSections + libc.dataSections:
        print(sec.name, ropper._searchOpcode(sec, libc, opcode, size))


import time

try:
    import brickpi3
except Exception:
    print("WARNING: no brickpi3 found (not running on raspberry pi?)")
    brickpi3 = None

try:
    import getch
except Exception:
    print("WARNING: no getch found")
    getch = None

import sys

if brickpi3 is not None:
    class Robot (brickpi3.BrickPi3):
        def __init__(self, speed=100):
            super(Robot, self).__init__()

            self.movement_state = 'stop'
            self.default_speed = speed
            self.current_speed = 0

        def rotate(self, speed=None):
            if speed<0:
                self.left(speed*-1)
            elif speed > 0:
                self.right(speed)
            else:
                self.stop()

        def forward(self, speed=None):
            if speed is None:
                print('using default speed')
                speed = self.default_speed

            self.set_motor_power(self.PORT_A + self.PORT_D, speed)
            self.current_speed = speed
            self.movement_state = 'forward'

        def backward(self, speed=None):
            if speed is None:
                print('using default speed')
                speed = self.default_speed

            self.set_motor_power(self.PORT_A + self.PORT_D, -speed)
            self.current_speed = speed
            self.movement_state = 'backward'

        def left(self, speed=None):
            if speed is None:
                print('using default speed')
                speed = self.default_speed

            self.set_motor_power(self.PORT_A, speed)
            self.set_motor_power(self.PORT_D, -speed)
            self.current_speed = speed
            self.movement_state = 'left'

        def right(self, speed=None):
            if speed is None:
                print('using default speed')
                speed = self.default_speed

            self.set_motor_power(self.PORT_A, -speed)
            self.set_motor_power(self.PORT_D, speed)
            self.current_speed = speed
            self.movement_state = 'right'

        def stop(self):
            while(self.current_speed > 0):
                self.current_speed -= 1

                if self.movement_state == 'forward':
                    self.forward(self.current_speed)
                elif self.movement_state == 'backward':
                    self.backward(self.current_speed)
                elif self.movement_state == 'left':
                    self.left(self.current_speed)
                elif self.movement_state == 'right':
                    self.right(self.current_speed)

                time.sleep(0.01)

            self.movement_state = 'stop'

        def __move_by_bpdegree(self, direction, bpdegree):
            # optional for setting rotation speed
            BP.set_motor_limits(BP.PORT_A + BP.PORT_D, 50, 200)

            # reset motor positions
            self.offset_motor_encoder(BP.PORT_A, BP.get_motor_encoder(BP.PORT_A))
            self.offset_motor_encoder(BP.PORT_D, BP.get_motor_encoder(BP.PORT_D))

            port_A_pos = self.get_motor_encoder(self.PORT_A)
            port_D_pos = self.get_motor_encoder(self.PORT_D)

            port_A_new_pos = port_A_pos + bpdegree
            port_D_new_pos = port_D_pos + bpdegree

            print("curr portA: %s curr portD: %s" % (port_A_pos, port_D_pos))
            print("next portA: %s next portD: %s" % (port_A_new_pos, port_D_new_pos))

            if direction == 'left':
                self.set_motor_position(self.PORT_A, port_A_new_pos)
                self.set_motor_position(self.PORT_D, -port_D_new_pos)
                self.movement_state = 'left'
            elif direction == 'right':
                self.set_motor_position(self.PORT_A, -port_A_new_pos)
                self.set_motor_position(self.PORT_D, port_D_new_pos)
                self.movement_state = 'right'

        def move_by_degree(self, direction, degree):
            bpdegree = self.degree_to_bpdegree(degree)

            if direction == 'left_by_degree':
                self.move_by_bpdegree('left', bpdegree)
            elif direction == 'right_by_degree':
                self.move_by_bpdegree('right', bpdegree)

        def bpdegree_to_degree(self, bpdegree):
            return (bpdegree * 1.66) / 10

        def degree_to_bpdegree(self, degree):
            return (degree * 0.6) * 10

        def __move_for_duration(self, duration, speed=None):
            if speed is None:
                speed = self.default_speed

            if direction == 'left':
                self.__move_for_duration(self.left, duration, speed)
            elif direction == 'right':
                self.__move_for_duration(self.right, duration, speed)
            elif direction == 'forward':
                self.__move_for_duration(self.forward, duration, speed)
            elif direction == 'backward':
                self.__move_for_duration(self.backward, duration, speed)

            time.sleep(duration)

            self.stop()

        def __move_with_key(self, key):
            if key == '' and self.movement_state != 'stop':
                self.stop()
            elif key == 'w':
                self.forward()
            elif key == 'a':
                self.left()
            elif key == 'd':
                self.right()
            elif key == 's':
                if self.movement_state == 'stop':
                    self.backward()
                else:
                    self.stop()

        def drive_with_keys(self):
            try:
                while True:
                    char = getch.getch()
                    self.__move_with_key(char)
                    time.sleep(0.01)
            except KeyboardInterrupt:
                self.reset_all()

        def cli(self):
            directions = ['left', 'right', 'forward', 'backward']
            directions_by_degree = ['left_by_degree', 'right_by_degree']

            try:
                while True:
                    left_motor = self.get_motor_encoder(self.PORT_A)
                    right_motor = self.get_motor_encoder(self.PORT_D)
                    print("Left motor: %6d - Right motor: %6d" % (left_motor, right_motor))
                    inp = input("> ")

                    operation = inp.split(' ')
                    command = operation[0]

                    if command in directions:
                        speed = int(operation[1])
                        duration = float(operation[2])
                        self.__move_for_duration(command, duration, speed)
                    elif command in directions_by_degree:
                        degree = int(operation[1])
                        self.move_by_degree(command, degree)
                    elif command == 'info':
                        self.get_info()

                    else:
                        print('No such action')

            except KeyboardInterrupt:
                self.reset_all()

"""
call this module with >  python3 robot.py speed  to drive the
brickpi with WASD and a specific speed
otherwise >  python3 robot.py  will open the command line interface:

commands:
left speed duration
right speed duration
forward speed duration
backward speed duration

left_by_degree degree
right_by_degree degree
"""
if __name__ == '__main__':
    args = sys.argv

    if len(args) >= 2:
        speed = int(args[1])
        BP = Robot(speed)
        BP.drive_with_keys()

    else:
        speed = 80
        BP = Robot(speed)
        BP.cli()


from ics import Calendar
from shutil import copyfile
from app.excel_cells import EXCEL_KEYS
import datetime
import openpyxl
import requests
import os
dir_path = os.path.dirname(os.path.realpath(__file__))

def receive_file(url, user_id, semester):
    if url[-4:] != '.ics':
        return {'not_ics': True}
    return write_to_xlsx(url, user_id, semester)

def write_to_xlsx(url, user_id, semester):
    user_id = str(user_id)
    if not os.path.isfile(dir_path + '/spreadsheets/' + user_id + 'schedule.xlsx'):
        copyfile(dir_path + '/generic_sheet/generic_sheet.xlsx',
                 dir_path + '/spreadsheets/' + user_id + 'schedule.xlsx')

    c = Calendar(requests.get(url).text)
    workbook = openpyxl.load_workbook(filename=dir_path+'/spreadsheets/'+user_id+'schedule.xlsx')
    worksheet = workbook.active
    alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

    clear_alph = 'BCDEFGH'
    for key in EXCEL_KEYS[semester]:
        for row in EXCEL_KEYS[semester][key]:
            for col in clear_alph:
                xlformat = col + str(row+1)
                worksheet[xlformat] = ''

    for event in c.events:
        start = event.begin.datetime
        end = event.end.datetime

        while start < end:
            start_hour = start.hour
            start_minute = start.minute

            if start_minute < 30:
                start_minute = 0
            else:
                start_minute = 1

            col = start.weekday() + 1
            row = EXCEL_KEYS[semester][start_hour][start_minute] + 1
            xlformat = alphabet[col] + str(row)
            worksheet[xlformat] = 'busy'

            start = start + datetime.timedelta(minutes=30)
    workbook.save(dir_path + '/spreadsheets/' + user_id + 'schedule.xlsx')

    return {'submitted': True}


# Author: Jason Lu
# 购物车：
#     用户入口：
#         1。商品信息存在文件里
#         2。已购商品，余额记录。（下一次不需要输入工资）
#
#     商家入口：
#         1。可以天际商品，修改商品价格

import os, sys

str_filename = '/Users/jasonlu/Desktop/thefile.txt'

# 商品列表
list_products = {
                    'Iphone': 5800,
                    'Mac Pro': 12000,
                    'Starback Latte': 31,
                    'Alex Python': 81,
                    'Bike': 800
                 }

str_filename = "testFile"
# r只读，w可写，a追加
print("\n============判断文件是否存在============\n")
# 读取文件，首先判断文件是否存在
try:
    fsock = open(str_filename, "r")
except IOError:
    print("The file don't exist, Please double check!")
    # exit()

print("\n============读取文件的内容============\n")
fsock = open(str_filename, "r")
AllLines = fsock.readlines()
for EachLine in AllLines:
    print(EachLine)
fsock.close()

print("\n============覆盖文件内容============\n")
# 直接打开一个文件，如果文件不存在则创建文件
file_object = open(str_filename, 'w')
file_object.write("debug")
file_object.close()

print("\n============追加文件内容============\n")
fsock = open(str_filename, "a4")
fsock.write("""
#Line 1 Just for debug purpose
#Line 2 Just for debug purpose
#Line 3 Just for debug purpose""")
fsock.close()

print("\n============判断文件是否关闭============\n")
# 判断文件是否关闭
S1 = fsock.closed
if S1:
    print('the file is closed')
else:
    print('The file donot close')

fsock = open(str_filename, "w")
fsock.write(str(list_products))
fsock.close()
print("\n============读取文件的内容============\n")
fsock = open(str_filename, "r")
str_list = fsock.read()
fsock.close()

print(type(eval(str_list)))
print(eval(str_list)["Iphone"])

print("\n============其他============\n")

str_filename2 = '/Users/jasonlu/Desktop/Dev/GitHub/codehub/python/res/1.txt'
'''
# 直接读取文件内容
# data = open(str_filename2, encoding="utf-8").read()
# print(data)
'''
# f为文件句柄
'''
f = open(str_filename2, encoding="utf-8")
data = f.read()
data2 = f.read()
print(data)
print(data2)
f.close()
'''

# f = open("yesterday2", "a4", encoding="utf-8")
# f.write("\n我爱北京天安门........\n")
# f.write("天安门上太阳升....")
# f.close()

f2 = open("yesterday2", "r", encoding="utf-8")
print(f2.tell()) #打印当前位置
print(f2.readline())
print(f2.readline())
print(f2.readline())
print(f2.tell())
f2.seek(0)
print(f2.readline())
print(f2.name)

# 文件缓存机制
# 达到一定大小，一次性写入
# 场景：要求实时的一致性强，强制刷新
f2.flush()
f2.close()

f2 = open("yesterday2", "a4", encoding="utf-8")
f2.write("hello 1")

# 从文件开头截断
f2.truncate()
f2.close()

f2 = open("yesterday2", "w", encoding="utf-8")
# 从文件开头截断
f2.truncate()
f2.close()

print("\n============我是分隔符============\n")

'''
print("--------我是分割线--------")
# 一行一行读取，内存中只保存一行
# 效率高
count = 0
for line in f2:
    count += 1
    if count == 9:
        print("----------")
        continue

    print(line.strip())
'''

'''
# 全部读取，浪费内存，时间
for index, line in enumerate(f2.readlines()):
    if index == 9:
        print("----------")
        continue
    print(line.strip())
f2.close()
'''

'''
print("\n============修改文件的内容============\n")
# 读写 打开读写
f2 = open("yesterday2", "r+", encoding="utf-8")
print(f2.readline())
print(f2.readline())
print(f2.readline())
print(f2.tell()) # 打印光标
f2.write("----------kao-----------")
print(f2.readline())
f2.close()
'''

'''
# 写读
f2 = open("yesterday2", "w+", encoding="utf-8")
f2.write("----------kao-----------\n")
f2.write("----------kao-----------\n")
f2.write("----------kao-----------\n")
f2.write("----------kao-----------\n")

print(f2.tell()) # 打印光标
# f2.seek(10) # 没有办法定位修改 只能追加
print(f2.readline())
f2.write("should be at the begining of the second line.")
f2.close()
'''

'''
# 以二进制文件读 比如视频
# 使用场景:
#   网络传输（socket）
#   视频文件
f2 = open("yesterday2", "rb")
print(f2.readline())
print(f2.readline())
print(f2.readline())
f2.close()
'''

'''
# 以二进制文件写 比如视频
f2 = open("yesterday2", "ab")
f2.write(("hello binary\n").encode())
f2.close()
'''

# 文件操作with语句
with open('yesterday2', 'r', encoding='utf-8') as f:
    print(f.readline())

with open('yesterday2', 'r', encoding='utf-8') as f:
    for line in f:
        print(line)

# py2.7以后可以打开多个文件
with open("yesterday2", "r", encoding="utf-8") as f, \
     open("yesterday2", "r", encoding="utf-8") as f2:
    for line in f:
        print(line)

print("\n============文件操作内容：写入新文件============\n")
# 高效文件写方式
f = open('yesterday2', 'r', encoding='utf-8')
f_new = open('yesterday2.bak', 'w', encoding='utf-8')

# 打开文件(高效写文件)
for line in f:
    if 'xx' in line:
        line = line.replace('xx', 'bb')

    f_new.write(line)

f.close()
f_new.close()

# 改进版本
# 可以使用参数来进行替换
import sys

str_find = sys.argv[1]
str_replace = sys.argv[2]

print(str_find, str_replace)

f = open("yesterday2", "r", encoding="utf-8")
f_new = open("yesterday2.bak", "w", encoding="utf-8")

# 打开文件，修改完了，写到新文件中（效率高）
for line in f:
    # 循环查找字符串
    if str_find in line:
        line = line.replace(str_find, str_replace)

    # 每一行都要写入新文件
    f_new.write(line)

f.close()
f_new.close()


import sys
from pathlib import Path

DIR = Path(__file__).resolve().parent
sys.path.insert(0, str(DIR.parent.parent.parent.parent))
__package__ = DIR.name

import django

django.setup()
from BaseClass import *
from scrapy import signals

store_url = sys.argv[4]

class PrettylittlethingScrapper(Spider_BaseClass):
    @classmethod
    def from_crawler(cls, crawler, *args, **kwargs):
        spider = super(PrettylittlethingScrapper, cls).from_crawler(crawler, *args, **kwargs)
        crawler.signals.connect(spider.spider_closed, signal=signals.spider_closed)
        return spider

    def GetProductUrls(self, response):
        topCategoryNodes = response.xpath(
            "(//nav[@class='hidden']/ul/li/div[h3/a[contains(text(),'NEW') or contains(text(),'SALE')  or  contains("
            "text(),'SUMMER') or contains(text(),'FIGURE') or contains(text(),'CLOTHING') or contains(text(),"
            "'DRESSES') or contains(text(),'MOLLY')]])[1]")
        for top_category_node in topCategoryNodes:
            top_category_title = top_category_node.xpath("./h3/a/text()").get().strip()
            print("TOP CATEGORY  :", top_category_title)
            category_nodes = top_category_node.xpath("(./ul/li[h4/a[not(contains(text(),'SHOP')) and not(contains(text("
                                                     "),'Sizes')) and not(contains(text(),'MATERNITY')) and not("
                                                     "contains(text(),'SWIMWEAR')) and not(contains(text(),"
                                                     "'ACCESSORIES')) and not(contains(text(),'SHOES')) and not("
                                                     "contains(text(),'BEAUTY'))]])[1]")
            for category_node in category_nodes:
                category_title = category_node.xpath("./h4/a/text()").get().strip()
                print("category_title :", category_title)
                sub_category_nodes = category_node.xpath(
                    "(./ul/li/a[not(contains(text(),'All')) and  contains(text(),'Dresses') or contains(text(),"
                    "'Bodysuits') or contains(text(),'Jump') or contains(text(),'Loungewear') or contains(text(),"
                    "'Petite') or contains(text(),'Skirts')])[1]")
                for sub_category_node in sub_category_nodes:
                    sub_category_title = sub_category_node.xpath("./text()").get().strip()
                    sub_category_link = sub_category_node.xpath("./@href").get()
                    if not sub_category_link.startswith(store_url):
                        sub_category_link = store_url.rstrip('/') + sub_category_link
                    print(sub_category_title, " :", sub_category_link)
                    category = top_category_title + " " + category_title + " " + sub_category_title
                    self.listing(sub_category_link, category)
        return Spider_BaseClass.AllProductUrls

    def listing(self, subCategorylink, category):
        subCategoryLinkResponse = requests.get(subCategorylink)
        subCategoryLinkResponse = HtmlResponse(url=subCategorylink, body=subCategoryLinkResponse.text,
                                               encoding='utf-8')
        product_list = subCategoryLinkResponse.xpath(
            "(//a[contains(@class,'product-url')]/@href)[1]").extract()
        for productUrl in product_list:
            if not productUrl.startswith(store_url):
                productUrl = store_url.rstrip('/') + productUrl
            print('PRODUCT URL :', productUrl)
            Spider_BaseClass.AllProductUrls.append(productUrl)
            siteMapCategory = str(Spider_BaseClass.ProductUrlsAndCategory.get(productUrl)).replace('None', '')
            if siteMapCategory:
                Spider_BaseClass.ProductUrlsAndCategory[productUrl] = siteMapCategory + " " + category
            else:
                Spider_BaseClass.ProductUrlsAndCategory[productUrl] = category
        try:
            nextPageUrl = subCategoryLinkResponse.xpath("//a[@class='load-more-btn']/@href").get()
            if not nextPageUrl.startswith(store_url):
                nextPageUrl = store_url.rstrip('/') + nextPageUrl
                print("NEXT PAGE :", nextPageUrl)
            self.listing(nextPageUrl, category)
        except:
            pass
    def GetProducts(self, response):
        ignorProduct = self.IgnoreProduct(response)
        if ignorProduct == True:
            self.ProductIsOutofStock(GetterSetter.ProductUrl)
        categoryAndName = self.GetCategory(response) + " " + self.GetName(response)
        if (re.search('Sale', categoryAndName, re.IGNORECASE) or
            re.search('New', categoryAndName, re.IGNORECASE)) and not \
                re.search(r'\b((shirt(dress?)|jump(suit?)|dress|set|gown|suit|caftan)(s|es)?)\b', categoryAndName,
                          re.IGNORECASE):
            print('Skipping Non Dress Product')
            self.ProductIsOutofStock(GetterSetter.ProductUrl)
        else:
            self.GetProductInfo(response)

    def GetName(self, response):
        color = self.GetSelectedColor(response)
        name = str(response.xpath("//h1[@class='product-view-title']/text()").get()).strip()
        if not color == '' and not re.search(color, name, re.I):
            name = name + " - " + color
        print("name =", name)
        return name

    def GetSelectedColor(self, response):
        color = str(response.xpath("//div[@class='colour-option-label']/p/span[2]/text()").get()).strip()
        return color
    def GetPrice(self, response):
        orignalPrice = response.xpath(
            "//div[contains(@class,'price-target')]/p[contains(@class,'regular')]/span/text()").get()
        if orignalPrice != None:
            return float(str(orignalPrice).strip().replace('$', '').replace(',', '').replace('USD',''))
        else:
            regularPrice = response.xpath(
                "//div[contains(@class,'price-target')]/p[contains(@class,'old')]/span/text()").get()
            return float(str(regularPrice).strip().replace('$', '').replace(',', '').replace('USD',''))

    def GetSalePrice(self, response):
        salePrice = response.xpath(
            "//div[contains(@class,'price-target')]/p[contains(@class,'new')]/span[1]/text()").get()
        if salePrice is not None:
            return float(str(salePrice).strip().replace('$', '').replace(',', '').replace('USD',''))
        else:
            return 0
    def GetDescription(self, response):
        return ' '.join(response.xpath("//div[contains(@class,'description')]//p//text()").extract()).strip()

    def GetBrand(self, response):
        brand = str(response.text).split("brand':")[1].split(',')[0].replace('"',"")
        return brand
    def GetSizes(self, response):
        sizes = []
        sizeList = response.xpath(
            "//div[contains(@class,'size-in-stock')]")
        gender = ProductFilters.objects.get(ProductUrl=GetterSetter.ProductUrl).ParentCategory.split(',')[0]
        color = self.GetSelectedColor(response)
        for size in sizeList:
            sizename = size.xpath("./text()").get().strip()
            available = True
            fitType = GetFitType(gender, sizename)
            sizes.append((color, sizename, available, fitType, 0.0, 0.0))
        return sizes
    def GetImageUrl(self, response):
        imageUrls = []
        image_nodes = response.xpath(
            "//div[@itemprop='associatedMedia']/img")
        for image in image_nodes:
            umage_url = image.xpath("./@src").get().strip()
            imageUrls.append(umage_url)
        return imageUrls
    def GetCategory(self, response):
        siteMapCategory = str(Spider_BaseClass.ProductUrlsAndCategory.get(GetterSetter.ProductUrl)).replace('None', '')
        return "Women " + siteMapCategory +  "jeans "


from email.message import EmailMessage

import config
import validate_address
# ______________________________________________________________________________
# set mail server data

def BuildTable(info):
    '''
    Uses the information of a person to construct a table containing the
    payments the person has to do and the reason why they have to pay that.

    param info: information to a person
    return t: str table with the due pay ments
    '''
    t = '\n| Betrag  | Verwendungszweck'
    t += '\n----------------------------------------------------\n'
    i = 3
    while i < len(info)-1:
        value = str(info[i+1])
        if value == 'nan':
            value = 0
        elif float(value) == 0:
            value = 0
        else:
            t += '| {:6.2f}€ | {}\n'.format(float(value), info[i])
        i += 2
    return t+'\n'

def BildMail(info):
    '''Gets information of a specific person and builds the e-mail for this
    person. This then is put in a EmailMessage() which is defined in the
    package email.message. This contains all necessary propatys of the e-mail.

    param info: list of information to one person
    param ConfigFile: filename where the text that is ont changed is stored
    return message: final configured e-mail
    '''
    receiver = [info[2]]
    receiverName = info[1]  # only first name ist used
    # Seting up mail
    message = EmailMessage()
    message["From"] = config.settings['address']
    message["To"] = receiver

    if info[0] == -1:
        static = open(config.settings['static_mail_err']).read()
        static = static.split('#Cut\n')
        message["Subject"] = static[0]
        content = static[1] + ' unknown' + static[2] + '' + static[3]

    else:
        # Getting configured Text
        static = open(config.settings['static_mail']).read()
        static = static.split('#Cut\n')
        message["Subject"] = static[0]
        # gets table for mail
        table = BuildTable(info)
        # puts together all parts of the content
        content = static[1] + receiverName + static[2] + table + static[3]

    message.set_content(content, "utf-8")
    return message


from modeltranslation.translator import register, TranslationOptions
from . import models

@register(models.Organization)
class OrganizationTranslationOptions(TranslationOptions):
    fields = ('name', 'description', 'adress', )

@register(models.Statya)
class StatyaTranslationOptions(TranslationOptions):
    fields = ('name', )

@register(models.Author)
class AuthorTranslationOptions(TranslationOptions):
    fields = ('name', 'surname', 'family_name', 'description', 'work', )

@register(models.Jurnal)
class JurnalTranslationOptions(TranslationOptions):
    fields = ('name', 'description', 'keyword',)

@register(models.Subdivision)
class SubdivisionTranslationOptions(TranslationOptions):
    fields = ('name', 'description', 'adress', )

@register(models.Conference)
class ConferenceTranslationOptions(TranslationOptions):
    fields = ('name', 'description', 'adress', 'sponsor',)

@register(models.Seminar)
class SeminarTranslationOptions(TranslationOptions):
    fields = ('name', 'fio', 'description', 'linkbutton', 'sponsor',)

@register(models.News)
class NewsTranslationOptions(TranslationOptions):
    fields = ('title', 'description', )

@register(models.Faq)
class FaqTranslationOptions(TranslationOptions):
    fields = ('question', 'answer', )

@register(models.Banner)
class BannerTranslationOptions(TranslationOptions):
    fields = ('title', 'subtitle', 'button',)

@register(models.Webcontact)
class WebcontactTranslationOptions(TranslationOptions):
    fields = ('address', )

@register(models.Video)
class VideoTranslationOptions(TranslationOptions):
    fields = ('title', 'organization')

@register(models.Video_Gallery)
class VideoGalleryTranslationOptions(TranslationOptions):
    fields = ('title', )


import pandas as pd
from nltk.tokenize import RegexpTokenizer
import nltk as nltk
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer

nltk.download('stopwords')
nltk.download('punkt')

# federalist txt
authors = 'data/federalist.txt'

final_dataset = pd.DataFrame(columns=['author', 'body'])

f = open(authors)
full_text = f.read()
f.close

# Clean linebreaks and encodings
full_text_lower = full_text.replace(u'\ufeff', '')
full_text_lower = full_text.replace(u'\n', ' ')
full_text_lower = full_text.lower()

# Remove punctuation
tokenizer = RegexpTokenizer(r'\w+')
full_text = tokenizer.tokenize(full_text_lower)
preprocessed_text = ' '.join(full_text)

# exctact author, chapter title and text

startindex = []
endindex = []
authors = []
titles = []

for i in range(0, 85):  # Split into the 85 chapters
    search = 'federalist no ' + str(i + 1)
    startindex.append(preprocessed_text.find(search))  # Start point of chapter
    endindex.append(startindex[i] + len(search) + 1)  # End point of chapter

# find author of each chapter
for i in range(84):
    find_jay = preprocessed_text.find('jay', endindex[i], startindex[i + 1])
    find_hamilton = preprocessed_text.find('hamilton', endindex[i], startindex[i + 1])
    find_madison = preprocessed_text.find('madison', endindex[i], startindex[i + 1])
    find_HwM = preprocessed_text.find('madison with hamilton', endindex[i], startindex[i + 1])
    if find_jay != -1:
        df = {
            'author': 'jay',
            'body': preprocessed_text[find_jay + 4:startindex[i + 1]]
        }
    elif find_HwM != -1:
        df = {
            'author': 'madison with hamilton',
            'body': preprocessed_text[find_madison + 22:startindex[i + 1]]
        }
    elif find_hamilton != -1:
        df = {
            'author': 'hamilton',
            'body': preprocessed_text[find_hamilton + 9:startindex[i + 1]]
        }
    elif find_madison != -1:
        df = {
            'author': 'madison',
            'body': preprocessed_text[find_madison + 8:startindex[i + 1]]
        }
    final_dataset = final_dataset.append(df, ignore_index=True)

find_hamilton = preprocessed_text.find('hamilton', endindex[84])
df = {
    'author': 'hamilton',
    'body': preprocessed_text[find_hamilton + 9:1124005]
}
final_dataset = final_dataset.append(df, ignore_index=True)

# open each row in df and apply preproccessing

for i, text in enumerate(final_dataset['body']):
    # remove stop words
    words = nltk.word_tokenize(text)
    stop_words = set(stopwords.words('english'))
    filtered_output = [word for word in words if word not in stop_words]
    # # # stemming
    # stemmer = PorterStemmer()
    # stemmed_output = [stemmer.stem(word) for word in filtered_output]
    # # # Join the stemmed words back into a single string
    new_text = ' '.join(filtered_output)

    final_dataset.at[i, 'body'] = new_text
#
#     #
#     #
#     #
final_dataset.to_csv("data/text_stop.csv", index=False)


import numpy
import math
from gnuradio import gr

class ParteEntera(gr.sync_block):
    """
    docstring for block ParteEntera
    """
    def __init__(self, PARAM1, PARAM2):
        self.PARAM1 = PARAM1
        self.PARAM2 = PARAM2
        gr.sync_block.__init__(self,
            name="ParteEntera",
            in_sig=[numpy.float32],
            out_sig=[numpy.float32])

    def work(self, input_items, output_items):
        in0 = input_items[0]
        out = output_items[0]
        # <+signal processing here+>
        for i in range(len(in0)):
            if self.PARAM1:
                out[i]=math.floor(in0[i])
            else:
                out[i]=math.ceil(in0[i])
        return len(output_items[0])

Lab3 - Programacion en Python para GNURADIO/Lab3.1 - Creacion de Bloques en Python/Modulos_L1C/ParteEntera.py