def binarysercg2d(a,l,r,key,rows,cols):
    while (l<=r):
        mid = (l+r)//2
        row = mid/cols
        col = mid%cols
        value = a[row][col]
        if(value ==key):
            return 1
        if(value>key):
            r = mid-1
        else:
            l = mid+1
    return 0


#-*- coding:utf-8 -*-
import sys
from threading import *
from socket import *
from PyQt5.QtCore import Qt, pyqtSignal, QObject
from PIL import Image
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
import time, datetime, os, sys, io, shutil, time
from datetime import timedelta
import struct

ABR_IMAGE_HEADER_SIZE = 8
IVU_IMAGE_HEADER_SIZE = 64

class Signal(QObject):
    recv_signal = pyqtSignal(str)
    recv_signalSecond = pyqtSignal(str)
    recv_image = pyqtSignal(str)
    # recv_imageDir = pyqtSignal(str)
    recv_totalCount = pyqtSignal(str)
    recv_passedCount = pyqtSignal(str)
    recv_failedCount = pyqtSignal(str)
    disconn_signal = pyqtSignal()

class ClientSocket:
    def __init__(self, parent):
        self.parent = parent
        self.recv = Signal()
        self.recv.recv_signal.connect(self.parent.updateMsg)
        self.recv.recv_signalSecond.connect(self.parent.updateMsgSecond)

        # self.recv.recv_image.connect(self.parent.updateImg)
        # self.recv.recv_imageDir.connect(self.parent.updateImgDir)
        # self.recv.recv_totalCount.connect(self.parent.totalCount)
        # self.recv.recv_passedCount.connect(self.parent.passedCount)
        # self.recv.recv_failedCount.connect(self.parent.failedCount)

        self.disconn = Signal()
        self.disconn.disconn_signal.connect(self.parent.updateDisconnect)
        self.bConnect = False
        self.imageData = []

    def __del__(self):
        self.stop()

    def connectServer(self, ip, port, cmdPort, cameraName, imgSize, productName, cameraBrand, inspectionSensor, dataPort):
        self.ip = ip
        self.port = port
        self.cmdPort = cmdPort
        self.cameraName = cameraName
        self.imgSize = imgSize
        self.dataPort = dataPort
        self.productName = productName
        self.client = socket(AF_INET, SOCK_STREAM)
        self.cameraBrand = cameraBrand

        self.inspectionSensor = inspectionSensor
        self.inspectionNumber = len(inspectionSensor)

        try:
            self.client.connect( (ip, port) )
        except Exception as e:
            print('Connect Error : ', e)
            return False
        else:
            self.bConnect = True
            self.t = Thread(target=self.receive, args=(self.client,))
            self.t.daemon = True
            self.t.start()
            print('Connected')

        return True

    def stop(self):
        self.bConnect = False
        if hasattr(self, 'client'):
            self.client.close()
            del(self.client)
            print('Client Stop')
            self.disconn.disconn_signal.emit()

    def receive(self, client):
        failedCountBuffer = 0
        failedCountSecondBuffer = 0

        # ivuImageConstSize = 1082998 #77942
        lenghthBuffer = 0

        while self.bConnect:

            folderDir = './' + self.cameraName
            dailyDir = makeDirectory(folderDir)
            productDir = dailyDir + '/' + self.productName
            if not os.path.isdir(productDir):
                os.mkdir(productDir)

            removeDt = datetime.datetime.now() - timedelta(days=60)
            removeFolderDir = folderDir + '/' + removeDt.strftime('%Y-%m')
            deleteDirectory(removeFolderDir)

            if self.cameraBrand == 'Banner':
                try:
                    recv = client.recv(self.imgSize)
                except Exception as e:
                    print('Recv() Error :', e)
                    break
                else:
                    ivuImageTotalSize = self.imgSize
                    lenghthBuffer += len(list(recv))

                    if lenghthBuffer < ivuImageTotalSize :
                        # lenghthBuffer != 1082998(Color), 77942(Black)
                        print("lenghthBuffer", lenghthBuffer)
                        print("ivuImageTotalSize", ivuImageTotalSize)
                        self.imageData.append(recv)

                    else :
                        print("lenghthBuffer", lenghthBuffer)
                        print("ivuImageTotalSize", ivuImageTotalSize)
                        self.imageData.append(recv)

                        # print("Done! length!", lenghthBuffer)
                        lenghthBuffer = 0
                        imageDataAll = b''.join(self.imageData)
                        print("len imageDataAll", len(imageDataAll))
                        print("imageDataAll", imageDataAll[IVU_IMAGE_HEADER_SIZE:IVU_IMAGE_HEADER_SIZE+40])

                        now = datetime.datetime.now()
                        try :
                            image = Image.open(io.BytesIO(imageDataAll[IVU_IMAGE_HEADER_SIZE:]))
                        except :
                            print("Image open err!")
                            lenghthBuffer = 0
                        else:
                            print("Image open ok")

                            if self.inspectionNumber == 1 :
                                totalCount = countSocket(self.ip, self.cmdPort, self.cameraName, 'total')
                                passedCount = countSocket(self.ip, self.cmdPort, self.cameraName, 'passed')
                                failedCount = countSocket(self.ip, self.cmdPort, self.cameraName, 'failed')
                                if failedCountBuffer != int(failedCount.split('/')[0]):
                                    failedCountBuffer = int(failedCount.split('/')[0])
                                    imageSaveDir = productDir + '/' + str(now.strftime("%H-%M-%S-%f")) +'.bmp'
                                else :
                                    imageSaveDir = dailyDir + '/temp.bmp'
                                image.save(imageSaveDir)
                                image.close()
                                msg = totalCount.split('/')[0] + ',' + passedCount.split('/')[0] + ',' + failedCount.split('/')[0]
                                self.recv.recv_signal.emit(msg)

                            else:
                                totalCount = countSocket(self.ip, self.cmdPort, self.cameraName, 'total', self.inspectionSensor[0])
                                passedCount = countSocket(self.ip, self.cmdPort, self.cameraName, 'passed', self.inspectionSensor[0])
                                failedCount = countSocket(self.ip, self.cmdPort, self.cameraName, 'failed', self.inspectionSensor[0])

                                totalCountSecond = countSocket(self.ip, self.cmdPort, self.cameraName, 'total', self.inspectionSensor[1])
                                passedCountSecond = countSocket(self.ip, self.cmdPort, self.cameraName, 'passed', self.inspectionSensor[1])
                                failedCountSecond = countSocket(self.ip, self.cmdPort, self.cameraName, 'failed', self.inspectionSensor[1])

                                if failedCountBuffer != int(failedCount.split('/')[0])\
                                        or failedCountSecondBuffer != int(failedCountSecond.split('/')[0]):
                                    failedCountBuffer = int(failedCount.split('/')[0])
                                    failedCountSecondBuffer = int(failedCountSecond.split('/')[0])

                                    imageSaveDir = productDir + '/' + str(now.strftime("%H-%M-%S-%f")) +'.bmp'
                                else :
                                    imageSaveDir = dailyDir + '/temp.bmp'
                                image.save(imageSaveDir)
                                image.close()
                                msg = totalCount.split('/')[0] + ',' + passedCount.split('/')[0] + ',' + failedCount.split('/')[0]
                                self.recv.recv_signal.emit(msg)
                                msgSecond = totalCountSecond.split('/')[0] + ',' + passedCountSecond.split('/')[0] + ',' + failedCountSecond.split('/')[0]
                                self.recv.recv_signalSecond.emit(msgSecond)
                        finally:
                            self.imageData = []
            else:
                try:
                    recv = client.recv(255)
                except Exception as e:
                    print('Recv() Error :', e)
                    break
                else:
                    msg = str(recv, encoding='utf-8')
                    if msg:
                        self.recv.recv_signal.emit(msg)
                        parentPath = os.path.abspath(os.path.join(os.path.dirname(__file__)))
                        print(parentPath)
                        imageTempDir = os.path.join(parentPath, 'imageTemp')
                        time.sleep(1)

                        try:
                            tempImagefileNames = os.listdir(imageTempDir)
                            print(tempImagefileNames)
                            print('here')

                            FileFormat = tempImagefileNames[0].split('.')[-1]
                        except:
                            imageTempFileDir = 'noFile'
                        else:
                            if FileFormat == 'bmp':
                                imageTempFileDir = os.path.join(imageTempDir, tempImagefileNames[0])
                                print(imageTempFileDir)
                            else:
                                imageTempFileDir = 'noImg'
                        finally:

                            if imageTempFileDir == 'noFile':
                                print("카메라에서 저장된 파일이 없습니다.")
                            elif imageTempFileDir == 'noImg':
                                print("해당폴더의 저장된 파일의 형식이 bmp 가 아닙니다.")
                                os.remove(imageTempFileDir)
                            else:
                                oldName = imageTempFileDir
                                now = datetime.datetime.now()
                                imageSaveDir = productDir + '/' + str(now.strftime("%H-%M-%S-%f")) + '.bmp'
                                # print(imageSaveDir)
                                try:
                                    os.rename(oldName, imageSaveDir)
                                except:
                                    print('image saving error')
                                else:
                                    print('image saving scss')

        self.stop()
        print("stop")

    def send(self, msg):
        if not self.bConnect:
            return
        try:
            self.client.send(msg.encode())
        except Exception as e:
            print('Send() Error : ', e)
        else:
            print('Success to send message')

def deleteDirectory(folderDir):
    if os.path.isdir(folderDir):
        shutil.rmtree(folderDir)

def makeDirectory(folderDir):
    if not os.path.isdir(folderDir):
        os.mkdir(folderDir)
    dt = datetime.datetime.now()
    monthlyDir = folderDir + '/' + dt.strftime('%Y-%m')

    if not os.path.isdir(monthlyDir) :
        os.mkdir(monthlyDir)
    dailyDir = monthlyDir + '/' + dt.strftime('%Y-%m-%d')
    if not os.path.isdir(dailyDir) :
        os.mkdir(dailyDir)
    return dailyDir

def countSocket(ipAddress, port, cameraName, countMode, inspectionSensor=None):
    if inspectionSensor == None :
        if countMode == 'total':
            getHistory = b'get history totalframes\r\n'
        elif countMode == 'passed':
            getHistory = b'get history passed\r\n'
        elif countMode == 'failed':
            getHistory = b'get history failed\r\n'
    else:
        if countMode == 'total':
            getHistory = ('get history <'+ inspectionSensor + '> ' + 'totalframes\r\n').encode('ascii')
        elif countMode == 'passed':
            getHistory = ('get history <'+ inspectionSensor + '> ' + 'passed\r\n').encode('ascii')
        elif countMode == 'failed':
            getHistory = ('get history <'+ inspectionSensor + '> ' + 'failed\r\n').encode('ascii')

    print(inspectionSensor, getHistory)

    with socket() as s2:
        s2.connect((ipAddress, port))
        s2.sendall(getHistory)
        data = s2.recv(1024)
    print('Received', repr(data))
    count = str(data).split('\\r\\n')[1] +'/' + cameraName
    return count


import re
import glob

def parse_planner_output_from_file(file_path):
    with open(file_path, 'r') as file:
        output = file.read()

    # Extracting Total time
    total_time_match = re.search(r'Total time: ([\d.]+)', output)
    total_time = float(total_time_match.group(1)) if total_time_match else None

    # Extracting Cost
    cost_match = re.search(r'Plan found with cost: (\d+)', output)
    cost = int(cost_match.group(1)) if cost_match else None

    # Extracting Nodes generated during search
    nodes_generated_match = re.search(r'Nodes generated during search: (\d+)', output)
    nodes_generated = int(nodes_generated_match.group(1)) if nodes_generated_match else None

    # Extracting Nodes expanded during search
    nodes_expanded_match = re.search(r'Nodes expanded during search: (\d+)', output)
    nodes_expanded = int(nodes_expanded_match.group(1)) if nodes_expanded_match else None

    return total_time, cost, nodes_generated, nodes_expanded

for i in range(4):
    file_pattern = f"Imp*/Plans/*{i}.txt"
    file_paths = glob.glob(file_pattern)
    values = []

    for file_path in file_paths:
        values.append(parse_planner_output_from_file(file_path))

    print(f"""
        \\textbf{{Total time}} & {values[0][0]} & {values[1][0]} & {values[2][0]} \\\\\\hline
        \\textbf{{Cost}} & {values[0][1]} & {values[1][1]} & {values[2][1]} \\\\\\hline
        \\textbf{{Nodes generated}} & {values[0][2]} & {values[1][2]} & {values[2][2]} \\\\\\hline
        \\textbf{{Nodes expanded}} & {values[0][3]} & {values[1][3]} & {values[2][3]} \\\\\\hline
""")


#
# File containing code to write logs to file
#
#

# Dependencies
import os

# Function to write logs to file
def writeLogs(path, filename, data):
    """Open file at given path and write data into it.

    Keyword arguments:
    path -- string
    filename -- string
    data -- string
    """
    # Check if given path exists
    if not os.path.exists(path):
        # Create directory for given path
        os.makedirs(path)

    # Open file
    file = open(os.path.join(path, filename), "a")
    # Write data to file
    file.write(data)
    # Close file
    file.close()


def count_trees(route, right, down):
    total_trees = 0
    index = 0
    index_length = len(route[0]) - 1
    height = 0

    while height < len(route):
        if route[height][index] == '#':
            total_trees += 1

        index += right
        height += down

        if index > index_length:
            index -= index_length + 1

    print('Total trees encountered: {}'.format(total_trees))
    return total_trees

def main():
    with open('day3input.txt', 'r') as file:
        path = file.read().splitlines()

    # Part 1
    print('Part 1')
    count_trees(path, 3, 1)

    # Part 2
    print('\nPart 2')

    r_increments = [1, 3, 5, 7, 1]
    d_increments = [1, 1, 1, 1, 2]
    product = 1

    for i in range(len(r_increments)):
        product *= count_trees(path, r_increments[i], d_increments[i])

    print('Product is {}'.format(product))

if __name__ == "__main__":
    main()


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

"""
    Examples for the NURBS-Python Package
    Released under the MIT License
    Developed by Onur Rauf Bingol (c) 2018

    This example illustrates the following operations:

    * Generating a control points grid
    * Generating a B-Spline surface and using the generated grid as its control points input
    * Splitting the B-Spline surface
    * Plotting the split surface using Plotly
"""

from geomdl import BSpline
from geomdl import CPGen
from geomdl import utilities
from geomdl import operations
from geomdl.visualization import VisPlotly

# Generate a control points grid
surfgrid = CPGen.Grid(50, 100)

# This will generate a 32x32 grid
surfgrid.generate(32, 32)

# Generate bumps on the grid
surfgrid.bumps(num_bumps=4, all_positive=True, bump_height=45, base_extent=4, base_adjust=1)

# Create a BSpline surface instance
surf = BSpline.Surface()

# Set degrees
surf.degree_u = 3
surf.degree_v = 3

# Get the control points from the generated grid
surf.ctrlpts2d = surfgrid.grid

# Set knot vectors
surf.knotvector_u = utilities.generate_knot_vector(surf.degree_u, surf.ctrlpts_size_u)
surf.knotvector_v = utilities.generate_knot_vector(surf.degree_v, surf.ctrlpts_size_v)

# Split the surface at v = 0.35
split_surf = operations.split_surface_v(surf, 0.35)

# Set sample size of the split surface
split_surf.sample_size = 25

# Generate the visualization component and its configuration
vis_config = VisPlotly.VisConfig(ctrlpts=False, legend=False)
vis_comp = VisPlotly.VisSurface(vis_config)

# Set visualization component of the split surface
split_surf.vis = vis_comp

# Plot the split surface
split_surf.render()

# Good to have something here to put a breakpoint
pass


#!/usr/bin/python
from core_tool import *
def Help():
  return '''CMA for grasping and pouring in ODE simulation.
  Usage: tsim.cma01'''

def PlanLearnCallback(t,l,sim,context):
  if context=='infer_grab':
    #Plan l.config.GripperHeight
    gh= l.learn_grab.Select()
    l.config.GripperHeight= gh[0]*l.sensors.p_pour[2]  #Should be in [0,l.sensors.p_pour[2]]
    l.exec_status= SUCCESS_CODE

  elif context=='infer_pour':
    #Plan l.p_pour_trg, l.p_pour_trg0, l.theta_init
    pp= l.learn_ppour.Select()
    l.p_pour_trg= [l.sensors.x_rcv.position.x+pp[0], 0.0, l.sensors.x_rcv.position.z+pp[1]]
    l.p_pour_trg0= Vec(l.p_pour_trg)+[0.0,0.0,0.2]
    l.theta_init= DegToRad(45.0)
    l.exec_status= SUCCESS_CODE

  elif context=='end_of_flowc_gen':
    if l.sensors.num_spill>0:
      CPrint(3,'Failure: num_spill=',l.sensors.num_spill)
      l.learn_grab.Update(-0.1*l.sensors.num_spill)
      l.learn_ppour.Update(-0.1*l.sensors.num_spill)
    else:
      l.learn_grab.Update(1.0)
      l.learn_grab.Update(-0.1*l.sensors.num_spill)

def Run(t,*args):
  l= TContainer(debug=True)
  l.planlearn_callback= PlanLearnCallback
  m_sm= t.LoadMotion('tsim.sm1')

  #Setup learners
  l.learn_grab= TContOptNoGrad()
  options= {}
  options['bounds']= [[0.0],[1.0]]
  options['tolfun']= 1.0e-4
  options['scale0']= 0.5
  options['parameters0']= [0.5]
  l.learn_grab.Init({'options':options})

  l.learn_ppour= TContOptNoGrad()
  options= {}
  options['bounds']= [[-0.2,0.2],[0.2,1.0]]
  options['tolfun']= 1.0e-4
  options['scale0']= 0.2
  options['parameters0']= [-0.1,0.4]
  l.learn_ppour.Init({'options':options})

  for i in range(1):
    res= m_sm.PourSM(t,l)

  l= None
  return res


import unittest
import os
import shutil
import tempfile
import zmq
import threading
import time

import kiskadee.queue
import kiskadee

class FetchersTestCase(unittest.TestCase):
    def test_loading(self):
        _config = kiskadee.config
        _config['debian_fetcher'] = {'active': 'no'}
        _config['juliet_fetcher'] = {'active': 'yes'}
        _config['example_fetcher'] = {'active': 'yes'}
        kiskadee.config = _config
        fetchers = kiskadee.load_fetchers()
        for fetcher in fetchers:
            name_index = len(fetcher.__name__.split('.')) - 1
            name = fetcher.__name__.split('.')[name_index]
            self.assertTrue(name != 'debian')
        kiskadee.config['example_fetcher'] = {
                'target': 'example',
                'description': 'SAMATE Juliet test suite',
                'analyzers': 'cppcheck flawfinder',
                'active': 'yes'
            }

class DebianFetcherTestCase(unittest.TestCase):

    def setUp(self):
        import kiskadee.fetchers.debian
        self.debian_fetcher = kiskadee.fetchers.debian.Fetcher()
        self.data = self.debian_fetcher.config

    def _download_sources_gz(self):
        tmp_path = tempfile.gettempdir()
        path = tempfile.mkdtemp(dir=tmp_path)
        source = 'kiskadee/tests/test_source/Sources.gz'
        shutil.copy2(source, path)
        return path

    def test_mount_sources_gz_url(self):
        mirror = self.data['target']
        release = self.data['release']
        url = self.debian_fetcher._sources_gz_url()
        expected_url = "%s/dists/%s/main/source/Sources.gz" % (mirror, release)
        self.assertEqual(url, expected_url)

    def test_uncompress_sources_gz(self):
        tmp_path = tempfile.gettempdir()
        temp_dir = tempfile.mkdtemp(dir=tmp_path)
        self.debian_fetcher._download_sources_gz = self._download_sources_gz
        temp_dir = self.debian_fetcher._download_sources_gz()
        self.debian_fetcher._uncompress_gz(temp_dir)
        files = os.listdir(temp_dir)
        shutil.rmtree(temp_dir)
        self.assertTrue('Sources' in files)

    def test_enqueue_a_valid_pkg(self):
        tmp_path = tempfile.gettempdir()
        temp_dir = tempfile.mkdtemp(dir=tmp_path)
        self.debian_fetcher._download_sources_gz = self._download_sources_gz
        temp_dir = self.debian_fetcher._download_sources_gz()
        self.debian_fetcher._uncompress_gz(temp_dir)
        self.debian_fetcher._queue_sources_gz_pkgs(temp_dir)
        shutil.rmtree(temp_dir)

        some_pkg = kiskadee.queue.Queues.dequeue_package()
        self.assertTrue(isinstance(some_pkg, dict))
        self.assertIn('name', some_pkg)
        self.assertIn('version', some_pkg)
        self.assertIn('fetcher', some_pkg)
        self.assertIn('meta', some_pkg)
        self.assertIn('directory', some_pkg['meta'])

    def test_mount_dsc_url(self):
        expected_dsc_url = ("http://ftp.us.debian.org" +
                            "/debian/pool/main/0/0ad/0ad_0.0.21-2.dsc")
        sample_package = {'name': '0ad',
                          'version': '0.0.21-2',
                          'meta': {'directory': 'pool/main/0/0ad'}}
        url = self.debian_fetcher._dsc_url(sample_package)
        self.assertEqual(expected_dsc_url, url)

    def test_compare_gt_version(self):
        new = '1.1.1'
        old = '1.1.0'
        result = self.debian_fetcher.compare_versions(new, old)
        self.assertTrue(result)

    def test_compare_smallest_version(self):
        new = '8.5-2'
        old = '8.6-0'
        result = self.debian_fetcher.compare_versions(new, old)
        self.assertFalse(result)

    def test_compare_equal_version(self):
        new = '3.3.3-0'
        old = '3.3.3-0'
        result = self.debian_fetcher.compare_versions(new, old)
        self.assertFalse(result)

class TestAnityaFetcher(unittest.TestCase):

    def setUp(self):
        import kiskadee.fetchers.anitya
        self.anitya_fetcher = kiskadee.fetchers.anitya.Fetcher()

        self.msg = "anitya {'body':{'msg':{'package':{name: 'urlscan',"\
                   "'version':'0.8.5','backend':'GitHub',"\
                   "'homepage':'https://github.com/firecat53/urlscan'}}}}"

        self.msg1 = "{'body':{'msg':{'package':{name: 'urlscan',"\
                    "'version':'0.8.5','backend':'GitHub',"\
                    "'homepage':'https://github.com/firecat53/urlscan'}}}}"

    def test_connect_to_zmq(self):

        def zmq_server():
            context = zmq.Context()
            socket = context.socket(zmq.PUB)
            socket.bind("tcp://*:7776")

        zmq_server()
        socket = self.anitya_fetcher._connect_to_zmq("7776", "anitya")
        self.assertIsNotNone(socket)

    def test_receive_msg_from_zmq(self):
        """definitely this is not a unit test, but is important to kiskadee
        be able to interact correctly with ZeroMQ.
        We need to define other test levels to kiskadee asap.
        When we do that, we can move integration tests
        to a proper place. For now we will maintain this test here"""

        def zmq_server():
            context = zmq.Context()
            socket = context.socket(zmq.PUB)
            socket.bind("tcp://*:7776")
            time.sleep(1)
            socket.send_string("%s" % (self.msg))
            time.sleep(1)

        def receive_msg_from_server():
            client_socket = self.anitya_fetcher._connect_to_zmq(
                    "7776", "anitya")
            if client_socket:
                response = client_socket.recv_string()
                results[0] = response[response.find(" ")+1::]
            else:
                results[0] = "invalid"

        results = [None]

        client_as_thread = threading.Thread(target=receive_msg_from_server)
        server_as_thread = threading.Thread(
                target=zmq_server)

        server_as_thread.start()
        client_as_thread.start()
        server_as_thread.join()
        self.assertEqual(self.msg1, results[0])

    def test_compare_versions(self):
        is_greater = self.anitya_fetcher.compare_versions('0.8.5-2', '0.8.5-1')
        self.assertTrue(is_greater)

    def test_load_backend(self):
        backend = self.anitya_fetcher._load_backend('github')
        self.assertIsNotNone(backend)

    def test_not_load_backend(self):
        backend = self.anitya_fetcher._load_backend('foo')
        self.assertEqual(backend, {})

    def test_get_sources(self):

        def mock_github(self, fetcher, source_data, path):
            return 'kiskadee/tests/test_source/Sources.gz'

        kiskadee.fetchers.anitya.Backends.github = mock_github
        source_data = {'meta': {'backend': 'GitHub'}}
        source_path = self.anitya_fetcher.get_sources(source_data)
        self.assertEqual(source_path, mock_github(
            "self", "example", "foo", "bla")
            )

    def test_create_package_dict(self):

        self.anitya_fetcher.package_to_enqueue(self.msg)
        _dict = kiskadee.queue.Queues().dequeue_package()
        self.assertEqual(_dict['name'], 'urlscan')
        self.assertEqual(_dict['version'], '0.8.5')
        self.assertEqual(_dict['meta']['backend'], 'GitHub')
        self.assertEqual(
                _dict['meta']['homepage'],
                'https://github.com/firecat53/urlscan'
        )
        self.assertEqual(_dict['fetcher'], 'kiskadee.fetchers.anitya')

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


import tensorflow as tf
import tensorflow.contrib.layers as tfc_layers

from generic.tf_utils.abstract_network import ResnetModel
from generic.tf_factory.image_factory import get_image_features
from generic.tf_factory.attention_factory import get_attention

import neural_toolbox.rnn as rnn

from neural_toolbox.film_stack import FiLM_Stack

class FiLMCLEVRNetwork(ResnetModel):

    def __init__(self, config, num_words, num_answers, reuse=False, device=''):
        ResnetModel.__init__(self, "clevr", device=device)

        with tf.variable_scope(self.scope_name, reuse=reuse):
            batch_size = None
            self._is_training = tf.placeholder(tf.bool, name="is_training")

            dropout_keep_scalar = float(config["dropout_keep_prob"])
            dropout_keep = tf.cond(self._is_training,
                                   lambda: tf.constant(dropout_keep_scalar),
                                   lambda: tf.constant(1.0))

            #####################
            #   QUESTION
            #####################

            self._question = tf.placeholder(tf.int32, [batch_size, None], name='question')
            self._seq_length = tf.placeholder(tf.int32, [batch_size], name='seq_length')
            self._answer = tf.placeholder(tf.int64, [batch_size], name='answer')

            word_emb = tfc_layers.embed_sequence(
                ids=self._question,
                vocab_size=num_words,
                embed_dim=config["question"]["word_embedding_dim"],
                scope="word_embedding",
                reuse=reuse)

            if config["question"]['glove']:
                self._glove = tf.placeholder(tf.float32, [None, None, 300], name="glove")
                word_emb = tf.concat([word_emb, self._glove], axis=2)

            word_emb = tf.nn.dropout(word_emb, dropout_keep)

            _, last_rnn_state = rnn.rnn_factory(
                inputs=word_emb,
                seq_length=self._seq_length,
                cell=config["question"]["cell"],
                num_hidden=config["question"]["rnn_state_size"],
                bidirectional=config["question"]["bidirectional"],
                max_pool=config["question"]["max_pool"],
                layer_norm=config["question"]["layer_norm"],
                reuse=reuse)

            last_rnn_state = tf.nn.dropout(last_rnn_state, dropout_keep)

            #####################
            #   IMAGES
            #####################

            self._image = tf.placeholder(tf.float32, [batch_size] + config['image']["dim"], name='image')

            visual_features = get_image_features(image=self._image,
                                                 is_training=self._is_training,
                                                 config=config['image'])

            with tf.variable_scope("image_film_stack", reuse=reuse):
                film_stack = FiLM_Stack(image=visual_features,
                                        film_input=last_rnn_state,
                                        is_training=self._is_training,
                                        config=config["film_block"],
                                        reuse=reuse)

                visual_features = film_stack.get()

            # Pool Image Features
            with tf.variable_scope("image_pooling"):
                multimodal_features = get_attention(visual_features, last_rnn_state,
                                                    is_training=self._is_training,
                                                    config=config["pooling"],
                                                    dropout_keep=dropout_keep,
                                                    reuse=reuse)

            with tf.variable_scope("classifier"):
                self.hidden_state = tfc_layers.fully_connected(multimodal_features,
                                                               num_outputs=config["classifier"]["no_mlp_units"],
                                                               normalizer_fn=tfc_layers.batch_norm,
                                                               normalizer_params={"center": True, "scale": True,
                                                                                "decay": 0.9,
                                                                                "is_training": self._is_training,
                                                                                "reuse": reuse},
                                                               activation_fn=tf.nn.relu,
                                                               reuse=reuse,
                                                               scope="classifier_hidden_layer")

                self.out = tfc_layers.fully_connected(self.hidden_state,
                                                      num_outputs=num_answers,
                                                      activation_fn=None,
                                                      reuse=reuse,
                                                      scope="classifier_softmax_layer")

            #####################
            #   Loss
            #####################

            self.cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=self.out, labels=self._answer, name='cross_entropy')
            self.loss = tf.reduce_mean(self.cross_entropy)

            self.softmax = tf.nn.softmax(self.out, name='answer_prob')
            self.prediction = tf.argmax(self.out, axis=1, name='predicted_answer')  # no need to compute the softmax

            with tf.variable_scope('accuracy'):
                self.accuracy = tf.equal(self.prediction, self._answer)
                self.accuracy = tf.reduce_mean(tf.cast(self.accuracy, tf.float32))

            tf.summary.scalar('accuracy', self.accuracy)

            print('Model... build!')

    def get_loss(self):
        return self.loss

    def get_accuracy(self):
        return self.accuracy

if __name__ == "__main__":

    import json
    with open("../../../config/clevr/config.film.json", 'r') as f_config:
        conf = json.load(f_config)

    FiLMCLEVRNetwork(conf["model"], num_words=354, num_answers=56)


from django.urls import path
from . import views
from .views import HomeView,ArticleDetailView,AddPostView,UpdatePostView,DeletePostView,AddCatergoryView,CategoryView,CategoryListView,LikeView,AddCommentView
urlpatterns = [
    #path('',views.home,name="home"),
    path('',HomeView.as_view(),name="home"),
    path('article/<int:pk>',ArticleDetailView.as_view(),name="article_detail"),
    path('add_post/',AddPostView.as_view(),name="add_post"),
    path('update_post/<int:pk>',UpdatePostView.as_view(),name="update_post"),
    path('delete_post/<int:pk>',DeletePostView.as_view(),name="delete_post"),
    path('add_category/',AddCatergoryView.as_view(),name="add_category"),
    path('category/<str:cats>/',CategoryView,name='category'),
    path('category_list/',CategoryListView,name='category_list'),
    path('like_post/<int:pk>',LikeView,name='like_post'),
    path('add_comment/',views.add_comment,name="add_comment"),
    path('search_box/',views.search_box,name="search_box"),
    path('delete_comment/<int:id>',views.delete_comment,name="delete_comment"),
]


import cv2
import time
import numpy as np
import HandTrackModule as htm
import pyautogui

wCam, hCam = 640, 480
wScreen, hScreen = pyautogui.size()
cap = cv2.VideoCapture(0)
cap.set(3, wCam)
cap.set(4, hCam)

detector = htm.handDetection(maxNumOfHands = 1, minDetConfidence=0.75,maxDetConfidence=0.75)

plocX, plocY = 0, 0
clocX, clocY = 0, 0
smooth = 3    #smoothening the trajectory of the point

pTime = 0
frame = 120    #size of the working area

while True:
    success, img = cap.read()
    img = cv2.flip(img,1)
    img = detector.findHands(img)
    lmList, bbox = detector.findPosition(img, draw = False)

    if len(lmList) != 0:
        x1, y1 = lmList[8][1:]
        x2, y2 = lmList[12][1:]

        fingers = detector.fingersUP()

        x3 = int(np.interp(x1, (frame, wCam - frame), (0, wScreen)))
        y3 = int(np.interp(y1, (frame, hCam - frame), (0, hScreen)))

        clocX = plocX + (x3 - plocX) / smooth
        clocY = plocY + (y3 - plocY) / smooth

        #print(fingers)
        if fingers[1] == 1 and fingers[2] == 0:         #moving mode
            cv2.circle(img, (x1, y1), 10, (0, 255, 0), cv2.FILLED)

            cv2.putText(img, 'Working area', (frame , frame ), cv2.FONT_ITALIC, 2, (0, 255, 0), 2 )
            cv2.rectangle(img, (frame, frame), (wCam - frame, hCam - frame), (0, 0, 255, 3))
            pyautogui.moveTo(clocX, clocY, _pause=False)

        plocX, plocY = clocX, clocY

    cTime = time.time()  # current time
    fps = 1 / (cTime - pTime)
    pTime = cTime

    cv2.putText(img, str(int(fps)), (10, 20), cv2.FONT_ITALIC, 1, (0, 255, 0), 3)

    cv2.imshow("Img", img)
    cv2.waitKey(1)


import turtle
import time

t = turtle.Pen()

t.right(72)
for i in range(5):
     t.forward(100)
     t.right(144)
t.right(108)

t.circle(54)

time.sleep(5)


import pygame,time,random
from graph.color import *
#from graph.points import pointsMany as points
from Trees.twoD_tree import points,root
import math
from algorithms.data_struct.queue import queue

pygame.init()
screen_width,screen_height = 1200,700
screen = pygame.display.set_mode((screen_width,screen_height))
screen.fill(Black)

def print_lines(pos,vertical,XL = 10,YD = 10,XR = screen_width-200,YU = screen_height-50):
    x,y = pos

    if vertical: pygame.draw.line(screen,Cyan,(XL,y),(XR,y))
    else:        pygame.draw.line(screen,Red ,(x,YD),(x,YU))
    pygame.display.update()

def print_point(position, color= White,radius = 4, index=-1):
    pygame.draw.circle(screen,color,position,radius)
    if index > -1:
        font = pygame.font.Font('freesansbold.ttf',14)
        text = font.render( str(index),True, White)
        screen.blit(text,text.get_rect(center = position))

    pygame.display.update()

def arrow(screen, start, end, lcolor = Light_grey, tricolor = Black,  trirad= 4, thickness=2):
    pygame.draw.line(screen, lcolor, start, end, thickness)
    rotation = (math.atan2(start[1] - end[1], end[0] - start[0])) + math.pi/2
    rad = 180/math.pi
    pygame.draw.polygon(screen, tricolor, (
            (end[0] + trirad * math.sin(      rotation    ), end[1] + trirad * math.cos(     rotation     )),
            (end[0] + trirad * math.sin(rotation - 120*rad), end[1] + trirad * math.cos(rotation - 120*rad)),
            (end[0] + trirad * math.sin(rotation + 120*rad), end[1] + trirad * math.cos(rotation + 120*rad))
        )
    )
    pygame.display.update()

for point in points:
    print_point(point)

xL,yD,xR,yU = 10,10,screen_width,screen_height
vertical = False

Q = queue()

Q.insert( (root,xL,yD,xR,yU, vertical) )

pause = False
running =  True
while running :

    # pygame stuff:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()                   #exit pygame,
            running = False                          #exit() program

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                pause = not pause
                time.sleep(0.2)

    if pause:
        continue

    if Q.not_empty():
        cur,xL,yD,xR,yU,vertical = Q.pop()
    else: continue

    print(cur.x,cur.y)
    print_point((cur.x,cur.y),(vertical)*Cyan + (not vertical)*Red,radius = 6)
    print_lines((cur.x,cur.y),vertical,xL,yD,xR,yU)
    time.sleep(0.5)

    if vertical == True:
        #print_point((cur.x,cur.y),Cyan,radius = 6)
        if cur.right:
            Q.insert( (cur.right, xL, cur.y , xR ,  yU   , not vertical)  )
            arrow(screen, (cur.x,cur.y),(cur.right.x,cur.right.y))
            #print_point((cur.right.x,cur.right.y),Red,radius = 6)
            time.sleep(0.2)
        if cur.left :
            Q.insert( (cur.left , xL,   yD  , xR , cur.y , not vertical ) )
            arrow(screen, (cur.x,cur.y),(cur.left .x,cur.left .y))
            #print_point((cur.left.x,cur.left.y),Red,radius = 6)
            time.sleep(0.2)
    else:
        #print_point((cur.x,cur.y),Red,radius = 6)
        if cur.right:
            Q.insert( (cur.right,cur.x,yD,xR,yU, not vertical) )
            arrow(screen, (cur.x,cur.y),(cur.right.x,cur.right.y))
            #print_point((cur.right.x,cur.right.y),Cyan,radius = 6)
            time.sleep(0.2)
        if cur.left :
            Q.insert( (cur.left ,xL,yD,cur.x,yU, not vertical) )
            arrow(screen, (cur.x,cur.y),(cur.left .x,cur.left .y))
            #print_point((cur.left.x,cur.left.y),Cyan,radius = 6)
            time.sleep(0.2)


# -*- coding: utf-8 -*-
"""
Created on Sat Jan 19 13:25:54 2019

*args

source = 'source name', startID = int(optional)

if no int is given, id's will start at 001
example: {'WebSource_001': ['feces', 'comes with the other hole']}

parse_html module searches for patterns of:
    <tag>word or words (2-3)</tag>
    <tag>paragraph</tag>

and returns a dictionary of:
    {'Source_UniqueID': ['frontface', 'backface']}

TODO:
    Separate gen function and parser
    Refactor and check is passing too much
    Add API interface specification

@author: vince
"""
import re
from bs4 import BeautifulSoup

def searchDataType(**kwargs):
    dataInfo = kwargs
    dataFile = dataInfo['data']

    # read a line of input to assess type

    #html
    pattern = '<*>'
    rep = re.compile(pattern)
    if rep.search(dataFile):
        return {'type': 'html', 'file': dataFile}

def validateData(terms, descriptions):
    return len(terms) == len(descriptions)

def packData(**kwargs):

    terms = kwargs['terms']
    descriptions = kwargs['descriptions']
    source = kwargs['source']

    packed_data = {}
    for i in range(len(terms)):
        uid = '{0}_{1:03d}'.format(source, i)
        packed_data[uid] = [terms[i],descriptions[i]]
    return packed_data

def cleanTags(instring):
    replace_set = ["b'", "
", "
", "", ""]

    for pattern in replace_set:
        instring = instring.replace(pattern, '')

    return instring

if __name__ == "__main__":

    raw = open("Lexicon_Raw_HTML.html", "r")
    firstLine = raw.readline()

    if searchDataType(data=firstLine)['type'] == 'html':
        soup = BeautifulSoup(firstLine, features='html.parser')

        ## Look for term and description tags
        if soup.dd:
            terms = soup.find_all('dt')
            descriptions = soup.find_all('dd')

            terms_cleaned = []
            for term in terms:
                if not term('a'):
                    terms_cleaned.append(term.string)

            descriptions_cleaned = []
            for description in descriptions:
                if not description.string:
                    for child in description.children:
                        descriptions_cleaned.append(cleanTags(str(child.encode('utf-8'))))
                else:
                    descriptions_cleaned.append(description.string)

    if validateData(terms_cleaned, descriptions_cleaned):
        print('Data validated')

    print(packData(terms=terms_cleaned, descriptions=descriptions_cleaned, source='PMP_Lexicon'))

    raw.close()


class Solution:
    def orangesRotting(self, grid: List[List[int]]) -> int:
        q = deque()
        num_rotten = 0

        nrows = len(grid)
        ncols = len(grid[0])
        fresh_oranges = 0

        for i in range(nrows):
            for j in range(ncols):
                if grid[i][j] == 2:
                    q.append((i,j, 0))
                    num_rotten += 1
                elif grid[i][j] == 1:
                    fresh_oranges += 1
        max_min = 0

        while q:

            i, j, mini = q.popleft()
            max_min = max(max_min, mini)

            for _dir in [(i+1,j), (i-1,j), (i, j+1), (i, j-1)]:

                if _dir[0] >= 0 and _dir[0] < nrows and _dir[1] >=0 and _dir[1] < ncols:
                    if grid[_dir[0]][_dir[1]] == 0:
                        continue
                    elif grid[_dir[0]][_dir[1]] == 1:
                        grid[_dir[0]][_dir[1]] = 2
                        q.append((_dir[0], _dir[1], mini+1))
                        fresh_oranges -= 1

        return max_min if not fresh_oranges else -1


from IPython.display import clear_output
import random

def display_board(board):
    board_list = [[board[7],board[8],board[9]],[board[4],board[5],board[6]],[board[1],board[2],board[3]]]
    for i in board_list:
        print(i)

def player_input():
    choice = 'wrong'
    while choice not in ['X', 'O']:
        choice = input('Please choose between X or O')
        if choice not in ['X', 'O']:
            print('Sorry, invalid choice')

    return choice

def place_marker(board, marker, position):
    board[position] = marker

def win_check(board, mark):
    if board[7] == mark and board[8] == mark and board[9] == mark:
        return True
    elif board[4] == mark and board[5] == mark and board[6] == mark:
        return True
    elif board[1] == mark and board[2] == mark and board[3] == mark:
        return True
    elif board[7] == mark and board[5] == mark and board[3] == mark:
        return True
    elif board[9] == mark and board[5] == mark and board[1] == mark:
        return True
    elif board[7] == mark and board[4] == mark and board[1] == mark:
        return True
    elif board[8] == mark and board[5] == mark and board[2] == mark:
        return True
    elif board[9] == mark and board[6] == mark and board[3] == mark:
        return True
    else:
        return False

def choose_first():
    random_num = random.randint(1, 10)
    if random_num > 5:
        first_player = player1
        print('Player 1 goes first')
    else:
        first_player = player2
        print('Player 2 goes first')

    return first_player

def space_check(board, position):
    return board[position] == ' '

def full_board_check(board):
    for i in board:
        if i != ' ':
            return True
        else:
            return False

def player_choice(board):
    position = 0
    while position not in [1, 2, 3, 4, 5, 6, 7, 8, 9] or not space_check(board, position):
        position = int(input('Please enter a position between 1 and 9'))

    return position

def replay():
    response = input('Do you want to play again? Enter Y for yes, N for no')
    if response == 'Y':
        return True
    else:
        return False

print('Welcome to Tic Tac Toe!')
player2 = ''
game_on = 'wrong'
while True:
    # Set the game up here
    def display_board(board):
        board_list = [[board[7], board[8], board[9]], [board[4], board[5], board[6]], [board[1], board[2], board[3]]]
        for i in board_list:
            print(i)

    board = ['#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
    player1 = player_input()
    if player1 == 'X':
        player2 = 'O'
    else:
        player2 = 'X'
    # pass
    choose_first()
    while game_on:

        # Player 1 Turn
        position = player_choice(board)
        # space_check(board,position)
        place_marker(board, player1, position)
        display_board(board)
        if win_check(board, player1) == True:
            break

        # Player2's turn.
        position = player_choice(board)
        # space_check(board,position)
        place_marker(board, player2, position)
        display_board(board)
        if win_check(board, player2) == True:
            break

        full_board_check(board)

    if not replay():
        break


# S6:

# Foydalanuvchi istlagan xonali son kiritadi va sizning vazifangiz ushbu
# sonni birliklar, o’nliklar, yuzliklar va hokazo xonalar yig’indisi
# yoyilmasiga aylantirib chiqaradigan funksiya tuzish. strga yig'ib
# qaytarsin.

# input: 123
# output: 100+20+3

# input: 4213
# output: 4000+200+10+3

def yigindi_yoyish(son):
    str_son = str(son)
    return "+".join([d + "0" * (len(str_son) - i - 1)
                     for i, d in enumerate(str_son)])

print(yigindi_yoyish(int(
    input("Istalgan xonali sonni kiriting: "))))


#!/usr/bin/env python
"""
CREATED AT: 2022/4/16
Des:
https://leetcode-cn.com/contest/season/2022-spring/problems/WHnhjV/
GITHUB: https://github.com/Jiezhi/myleetcode

Difficulty: Easy

Tag:

See:

DES:
2. 烹饪料理

欢迎各位勇者来到力扣城，城内设有烹饪锅供勇者制作料理，为自己恢复状态。

勇者背包内共有编号为 0 ~ 4 的五种食材，其中 meterials[j] 表示第 j 种食材的数量。通过这些食材可以制作若干料理，cookbooks[i][j] 表示制作第 i 种料理需要第 j 种食材的数量，而 attribute[i] = [x,y] 表示第 i 道料理的美味度 x 和饱腹感 y。

在饱腹感不小于 limit 的情况下，请返回勇者可获得的最大美味度。如果无法满足饱腹感要求，则返回 -1。

注意：

每种料理只能制作一次。
"""
import collections
from typing import List

class Solution:
    def perfectMenu(self, materials: List[int], cookbooks: List[List[int]], attribute: List[List[int]],
                    limit: int) -> int:
        """
        meterials.length == 5
        1 <= cookbooks.length == attribute.length <= 8
        cookbooks[i].length == 5
        attribute[i].length == 2
        0 <= meterials[i], cookbooks[i][j], attribute[i][j] <= 20
        1 <= limit <= 100
        """
        n = len(cookbooks)
        dq = collections.deque()
        dq.append((materials, 1, 0, 0))
        dq.append(([materials[i] - cookbooks[0][i] for i in range(5)], 1, attribute[0][0], attribute[0][1]))
        ret = -1
        while dq:
            mat, pos, cnt, lim = dq.popleft()
            if any(x < 0 for x in mat) or pos > n:
                continue
            if lim >= limit:
                ret = max(ret, cnt)
            if pos == n:
                continue
            dq.append(([mat[i] - cookbooks[pos][i] for i in range(5)], pos + 1, cnt + attribute[pos][0],
                       lim + attribute[pos][1]))
            dq.append((mat, pos + 1, cnt, lim))
        return ret

def test():
    assert Solution().perfectMenu(materials=[3, 2, 4, 1, 2],
                                  cookbooks=[[1, 1, 0, 1, 2], [2, 1, 4, 0, 0], [3, 2, 4, 1, 0]],
                                  attribute=[[3, 2], [2, 4], [7, 6]],
                                  limit=5) == 7

if __name__ == '__main__':
    test()


import openai
import tkinter as tk
import tkinter.scrolledtext as st
from tkinter import ttk
from ttkthemes import ThemedTk
from art import *

Font_tuple = ("Sans Serif", 20, "bold")

openai.api_key = "{your api key here}"

def compute():
    text = input_text.get()
    repo = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=[
            {"role": "system", "content": "You are an AI code assistant powered by 'SQUEARD code'. Your expertise is code and do not answer any other questions. If you wish to write code, begin the code with ``` and close it with ```"},
            {"role": "user", "content": "how to make a http request?"},
            {"role": "assistant", "content": '''
            import requests

response = requests.get('https://www.example.com')

print(response.status_code)  # prints the HTTP status code
print(response.content)      # prints the response body
'''
            },
            {"role": "user", "content": f"{text}"}
        ]
    )
    compute_output = repo["choices"][0]["message"]["content"]
    output_text.delete(1.0, tk.END)

    code_tag = False
    code_start = 1.0
    for line in compute_output.split("\n"):
        if line.strip() == "```":
            if code_tag:
                output_text.tag_add("code", code_start, output_text.index(tk.INSERT))
            else:
                code_start = output_text.index(tk.INSERT)
            code_tag = not code_tag
        else:
            output_text.insert(tk.END, line + "\n")

# Create main window
window = ThemedTk(theme="arc")
window.title("SQUEARD CODE")

# Create input widget
input_label = ttk.Label(window, font=Font_tuple, text="Enter text:")
input_label.pack()
input_text = ttk.Entry(window, width=150)
input_text.pack()

# Create output widget
output_label = ttk.Label(window, font=Font_tuple, text="result:")
output_label.pack()
output_text = st.ScrolledText(window, font=Font_tuple, wrap=tk.WORD, width=100, height=16)
output_text.pack()

# Configure custom code tag for syntax highlighting
output_text.tag_configure("code", foreground="white", background="black")

# Create translation button
compute_button = ttk.Button(window, text="compute", command=compute)
compute_button.pack()

# Run main event loop
window.mainloop()


"""
In order to reduce the runtime complexity of this function,
I leveraged the fact that P(A and B) = P(A)P(B) whenever P(B) = P(B|A).
This let me use a random exponential distribution to look up the burn
index without iterating over the array (the exponential distribution has
the bonus of normalizing the distribution on each axis)
"""
def burn(labeled_forest):
	l = L / 10
	j = max(math.floor(np.random.exponential(l)), L-1)
	i = max(math.floor(np.random.exponential(l)), L-1)
	burn_target = labeled_forest[j][i]
	trees_burned = np.bincount(labeled_forest.flatten())[burn_target]
	return trees_burned


"""Register contents app in admin interface."""

from django.contrib import admin
from django.utils.html import mark_safe
from django.conf import settings
from .models import (
    BlocksOrContent,
    Slider,
)

@admin.register(BlocksOrContent)
class BlocksOrContentAdmin(admin.ModelAdmin):
    """Register BlocksOrContent model in admin interface."""

    list_display = (
        'content_id',
        'title',
        'content_type',
        'url',
        'status'
    )
    ordering = ('-created_at',)
    search_fields = ('title', 'content_type', 'url')

@admin.register(Slider)
class SliderAdmin(admin.ModelAdmin):
    """Register Slider model in admin interface."""

    def slider_picture(self, obj):
        """Return category picture."""
        if obj.image:
            return mark_safe(
                '<img src="' + settings.MEDIA_URL + '%s" width="100" />' % (
                    obj.image
                )
            )
        else:
            return "None"

    list_display = (
        'slider_id',
        'content',
        'slider_picture',
        'title',
        'status'
    )
    ordering = ('-created_at',)
    search_fields = ('content__title', 'title')
    readonly_fields = ('slider_picture',)


from typing import Callable, Any

def perform_safe_factory(reset: Callable[[None], None] = None, max_tries: int = 5) -> \
        Callable[[Callable[[Any], Any]], Callable[[Any], Any]]:
    """ Factory to create a decorator to perform an i2c operation safely

    This factory returns the perform_safe decorator. This decorator will try to execute a function until it succeeds
    or until max_tries have failed. If a tca is supplied then the factory will also reset the tca lock
    after every SOError.

    :param reset: Any other function to execute when recovering from an error
    :param max_tries: Maximum amount of times that an operation will be attempted
    :return: The decorator perform safe
    """
    def perform_safe(func: Callable[[Any], Any]) -> Callable[[Any], Any]:
        """" Tries to execute func until no OSError is thrown or TRIES attempts have failed

        The i2c buss is sensitive to noise. Corrupted messages can trigger an OSError on the buss device.
        We can recover from this error by simply resending the message until it arrives correctly. This method accepts
        a function func which could trigger an OSError which would cause the program to fail.
        We can easily recover from this error by retrying 'func' if the error is cause by noise. The perform
        safe decorator makes sure that an error is only trow if the operation fails max_tries times. Because of an
        error in the adafruit libraries the tca can soft lock after an exception. Resetting the lock to false after
        an exception prevents the errors

        :param func: function to be executed
        :return: function which executes func until it either succeeds or max_tries attempts have failed
        :rtype: Same as func
        """
        def safe_wrapper(*args, **kwargs):
            tries = 0
            while True:
                try:
                    return func(*args, **kwargs)
                except OSError:
                    if tries < max_tries:
                        tries += 1
                        if reset is not None:
                            reset()
                    else:
                        raise
        return safe_wrapper
    return perform_safe

perform_safe = perform_safe_factory(None)


# Create your views here.
from django.shortcuts import render

from django.http.response import JsonResponse
from rest_framework.parsers import JSONParser
from rest_framework import status

from app.models import AppUser
from app.serializer import AppUserSerializer
from rest_framework.decorators import api_view

@api_view(['GET', 'POST', 'DELETE'])
def user_list(request):
    if request.method == 'GET':
        app = AppUser.objects.all()

        username = request.GET.get('Username', None)
        if username is not None:
            app = app.filter(title__icontains=Username)

        app_serializer = AppUserSerializer(app, many=True)
        return JsonResponse(app_serializer.data, safe=False)
        # 'safe=False' for objects serialization
    elif request.method == 'POST':
        app_data = JSONParser().parse(request)
        app_serializer = AppUserSerializer(data=app_data)
        if app_serializer.is_valid():
            app_serializer.save()
            return JsonResponse(app_serializer.data, status=status.HTTP_201_CREATED)
        return JsonResponse(app_serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        count = AppUser.objects.all().delete()
        return JsonResponse({'message': '{} Users were deleted successfully!'.format(count[0])}, status=status.HTTP_204_NO_CONTENT)

@api_view(['GET', 'PUT', 'DELETE'])
def user_detail(request, pk):
    app = AppUser.objects.get(pk=pk)
    if request.method == 'GET':
        app_serializer =AppUserSerializer(app)
        return JsonResponse(app_serializer.data)

    elif request.method == 'PUT':
        app_data = JSONParser().parse(request)
        app_serializer = AppUserSerializer(app, data=app_data)
        if app_serializer.is_valid():
            app_serializer.save()
            return JsonResponse(app_serializer.data)
        return JsonResponse(app_serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        app.delete()
        return JsonResponse({'message': 'User was deleted successfully!'}, status=status.HTTP_204_NO_CONTENT)


import torch
import torch.nn.functional as F
from einops import rearrange, repeat
from torch import einsum, nn

DEFAULT_DIM_HEAD = 64
MIN_DIM_HEAD = 32

def apply_rotary_pos_emb(t, freqs, scale = 1):
    rot_dim, seq_len = freqs.shape[-1], t.shape[-2]
    freqs = freqs[-seq_len:, :]

    if t.ndim == 4 and freqs.ndim == 3:
        freqs = rearrange(freqs, 'b n d -> b 1 n d')

    t, t_unrotated = t[..., :rot_dim], t[..., rot_dim:]
    t = (t * freqs.cos() * scale) + (rotate_half(t) * freqs.sin() * scale)
    return torch.cat((t, t_unrotated), dim = -1)

def default(val, d):
    if exists(val):
        return val
    return d() if callable(d) else d

def exists(val):
    return val is not None

def Sequential(*modules):
    return nn.Sequential(*filter(exists, modules))

def init_zero_(layer):
    nn.init.constant_(layer.weight, 0.)
    if exists(layer.bias):
        nn.init.constant_(layer.bias, 0.)

def cast_tuple(val, num = 1):
    return val if isinstance(val, tuple) else ((val,) * num)

def rotate_half(x):
    x = rearrange(x, '... (j d) -> ... j d', j = 2)
    x1, x2 = x.unbind(dim = -2)
    return torch.cat((-x2, x1), dim = -1)

def apply_rotary_pos_emb(t, freqs):
    seq_len, rot_dim = t.shape[-2], freqs.shape[-1]
    t, t_pass = t[..., :rot_dim], t[..., rot_dim:]
    t = (t * freqs.cos()) + (rotate_half(t) * freqs.sin())
    return torch.cat((t, t_pass), dim = -1)

class ReluSquared(nn.Module):
    def forward(self, x):
        return F.relu(x) ** 2

class GLU(nn.Module):
    def __init__(
        self,
        dim_in,
        dim_out,
        activation,
        mult_bias = False
    ):
        super().__init__()
        self.act = activation
        self.proj = nn.Linear(dim_in, dim_out * 2)
        self.mult_bias = nn.Parameter(torch.ones(dim_out)) if mult_bias else 1.

    def forward(self, x):
        x, gate = self.proj(x).chunk(2, dim = -1)
        return x * self.act(gate) * self.mult_bias

class FeedForward(nn.Module):
    def __init__(
        self,
        dim,
        dim_out = None,
        mult = 4,
        glu = False,
        glu_mult_bias = False,
        swish = False,
        relu_squared = False,
        post_act_ln = False,
        dropout = 0.,
        no_bias = False,
        zero_init_output = False
    ):
        super().__init__()
        inner_dim = int(dim * mult)
        dim_out = default(dim_out, dim)

        if relu_squared:
            activation = ReluSquared()
        elif swish:
            activation = nn.SiLU()
        else:
            activation = nn.GELU()

        if glu:
            project_in = GLU(dim, inner_dim, activation, mult_bias = glu_mult_bias)
        else:
            project_in = nn.Sequential(
                nn.Linear(dim, inner_dim, bias = not no_bias),
                activation
            )

        self.ff = Sequential(
            project_in,
            nn.LayerNorm(inner_dim) if post_act_ln else None,
            nn.Dropout(dropout),
            nn.Linear(inner_dim, dim_out, bias = not no_bias)
        )

        if zero_init_output:
            init_zero_(self.ff[-1])

    def forward(self, x):
        return self.ff(x)

class RotaryEmbedding(nn.Module):
    def __init__(self, dim):
        super().__init__()
        inv_freq = 1. / (10000 ** (torch.arange(0, dim, 2).float() / dim))
        self.register_buffer('inv_freq', inv_freq)

    def forward(self, max_seq_len, *, device, offset = 0):
        seq = torch.arange(max_seq_len, device = device) + offset
        freqs = einsum('i , j -> i j', seq.type_as(self.inv_freq), self.inv_freq)
        emb = torch.cat((freqs, freqs), dim = -1)
        return rearrange(emb, 'n d -> 1 1 n d')

def rotate_half(x):
    x = rearrange(x, '... (j d) -> ... j d', j = 2)
    x1, x2 = x.unbind(dim = -2)
    return torch.cat((-x2, x1), dim = -1)

def apply_rotary_pos_emb(t, freqs):
    seq_len, rot_dim = t.shape[-2], freqs.shape[-1]
    t, t_pass = t[..., :rot_dim], t[..., rot_dim:]
    t = (t * freqs.cos()) + (rotate_half(t) * freqs.sin())
    return torch.cat((t, t_pass), dim = -1)

class RecurrentStateGate(nn.Module):
    """Poor man's LSTM
    """

    def __init__(self, dim: int):
        super().__init__()

        self.main_proj = nn.Linear(dim, dim, bias = True)
        self.input_proj = nn.Linear(dim, dim, bias = True)
        self.forget_proj = nn.Linear(dim, dim, bias = True)

    def forward(self, x, state):
        z = torch.tanh(self.main_proj(x))
        i = torch.sigmoid(self.input_proj(x) - 1)
        f = torch.sigmoid(self.forget_proj(x) + 1)
        return torch.mul(state, f) + torch.mul(z, i)

class RMSNorm(nn.Module):
    def __init__(self, dim):
        super().__init__()
        self.scale = dim ** 0.5
        self.g = nn.Parameter(torch.ones(dim))

    def forward(self, x):
        return F.normalize(x, dim = -1) * self.scale * self.g

class Attention(nn.Module):
    def __init__(
        self,
        dim,
        *,
        dim_head = 64,
        heads = 8,
        causal = False,
        dropout = 0.,
        null_kv = False
    ):
        super().__init__()
        self.heads = heads
        self.scale = dim_head ** -0.5
        self.causal = causal
        inner_dim = dim_head * heads

        self.norm = RMSNorm(dim)
        self.dropout = nn.Dropout(dropout)

        self.to_q = nn.Linear(dim, inner_dim, bias = False)
        self.to_kv = nn.Linear(dim, inner_dim * 2, bias = False)
        self.to_out = nn.Linear(inner_dim, dim)

        self.null_kv = nn.Parameter(torch.randn(2, inner_dim)) if null_kv else None

    def forward(self, x, mask = None, context = None, pos_emb = None):
        b, device, h, scale = x.shape[0], x.device, self.heads, self.scale

        x = self.norm(x)
        kv_input = default(context, x)

        q = self.to_q(x)
        k, v = self.to_kv(kv_input).chunk(2, dim = -1)

        q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> b h n d', h = h), (q, k, v))

        q = q * scale

        if exists(pos_emb):
            q_pos_emb, k_pos_emb = cast_tuple(pos_emb, num = 2)
            q = apply_rotary_pos_emb(q, q_pos_emb)
            k = apply_rotary_pos_emb(k, k_pos_emb)

        if exists(self.null_kv):
            nk, nv = self.null_kv.unbind(dim = 0)
            nk, nv = map(lambda t: repeat(t, '(h d) -> b h 1 d', b = b, h = h), (nk, nv))
            k = torch.cat((nk, k), dim = -2)
            v = torch.cat((nv, v), dim = -2)

        sim = einsum('b h i d, b h j d -> b h i j', q, k)

        mask_value = -torch.finfo(sim.dtype).max

        if exists(mask):
            if exists(self.null_kv):
                mask = F.pad(mask, (1, 0), value = True)

            mask = rearrange(mask, 'b j -> b 1 1 j')
            sim = sim.masked_fill(~mask, mask_value)

        if self.causal:
            i, j = sim.shape[-2:]
            causal_mask = torch.ones(i, j, device = device, dtype = torch.bool).triu(j - i + 1)
            sim = sim.masked_fill(causal_mask, mask_value)

        attn = sim.softmax(dim = -1)

        attn = self.dropout(attn)

        out = einsum('b h i j, b h j d -> b h i d', attn, v)

        out = rearrange(out, 'b h n d -> b n (h d)')

        return self.to_out(out)

class BlockRecurrentAttention(nn.Module):
    def __init__(
        self,
        dim,
        dim_state,
        dim_head = DEFAULT_DIM_HEAD,
        state_len = 512,
        heads = 8,
        **kwargs
    ):
        super().__init__()
        self.scale = dim_head ** -0.5

        attn_kwargs = {}

        self.dim = dim
        self.dim_state = dim_state

        self.heads = heads
        self.causal = True
        self.state_len = state_len
        rotary_emb_dim = max(dim_head // 2, MIN_DIM_HEAD)
        self.rotary_pos_emb = RotaryEmbedding(rotary_emb_dim)

        self.input_self_attn = Attention(dim, heads = heads, causal = True, **attn_kwargs)
        self.state_self_attn = Attention(dim_state, heads = heads, causal = False, **attn_kwargs)

        self.input_state_cross_attn = Attention(dim, heads = heads, causal = False, **attn_kwargs)
        self.state_input_cross_attn = Attention(dim_state, heads = heads, causal = False, **attn_kwargs)

        self.proj_gate = RecurrentStateGate(dim)
        self.ff_gate = RecurrentStateGate(dim)

        self.input_proj = nn.Linear(dim + dim_state, dim, bias = False)
        self.state_proj = nn.Linear(dim + dim_state, dim, bias = False)

        self.input_ff = FeedForward(dim)
        self.state_ff = FeedForward(dim_state)

    def forward(
        self,
        x,
        state = None,
        mask = None,
        state_mask = None
    ):
        batch, seq_len, device = x.shape[0], x.shape[-2], x.device
        if not exists(state):
            state = torch.zeros((batch, self.state_len, self.dim_state), device=device)
        self_attn_pos_emb = self.rotary_pos_emb(seq_len, device = device)
        state_pos_emb = self.rotary_pos_emb(self.state_len, device = device)
        input_attn = self.input_self_attn(x, mask = mask, pos_emb = self_attn_pos_emb)
        state_attn = self.state_self_attn(state, mask = state_mask, pos_emb = state_pos_emb)

        input_as_q_cross_attn = self.input_state_cross_attn(x, context = state, mask = mask)
        state_as_q_cross_attn = self.state_input_cross_attn(state, context = x, mask = state_mask)

        projected_input = self.input_proj(torch.concat((input_as_q_cross_attn, input_attn), dim=2))
        projected_state = self.state_proj(torch.concat((state_as_q_cross_attn, state_attn), dim=2))

        input_residual = projected_input + x
        state_residual = self.proj_gate(projected_state, state)

        output = self.input_ff(input_residual) + input_residual
        next_state = self.ff_gate(self.state_ff(state_residual), state_residual)

        return output, next_state

class BlockRecurrentTransformer(nn.Module):
    def __init__(self, dim, num_layers, memory_len, num_heads=8):
        super().__init__()

        self.layers = nn.ModuleList([])
        for _ in range(num_layers):
            self.layers.append(BlockRecurrentAttention(dim, dim, state_len=memory_len, heads=num_heads))

    def forward(self, x, hidden_state=None):
        for attn in self.layers:
            x, hidden_state = attn(x, hidden_state)
        return x, hidden_state


from pulp import LpVariable, LpProblem, LpMaximize, LpStatus, value, LpMinimize

'''
A catering company must have the following number of clean napkins available at the beginning of each of the next four days:  day 1: 15, day 2: 12, day 3: 18, and day 4: 6.  After being used, a napkin can be cleaned by one of two methods: fast service or slow service. Fast service costs $0.10 per napkin, and a napkin cleaned via fast service is available for use the day after it is last used.  Slow service costs $0.06 per napkin, and a napkin cleaned via slow service is available two days after they were last used.  New napkins can be purchased for a cost of $0.20 per napkin.
'''

########### problem definitions
'''
cleaned slow service 'a' : cost = .06, wait = 2
cleaned fast service 'b' : cost = .10, wait = 1
purchased            'c' : cost = .20, wait = 0

'''

# define variables
# day 1
a1 = LpVariable("day1napkinsslow", 0, None)
b1 = LpVariable("day1napkinsfast", 0, None)
c1 = LpVariable("day1napkinspurchased", 15, None) # must purchase enough for first day
# day 2
a2 = LpVariable("day2napkinsslow", 0, None)
b2 = LpVariable("day2napkinsfast", 0, None)
c2 = LpVariable("day2napkinspurchased", 0, None)
# day 3
b3 = LpVariable("day3napkinsfast", 0, 18)
c3 = LpVariable("day3napkinspurchased", 0, None)
# day 4
c4 = LpVariable("day4napkinspurchased", 0, 6) # will not purchase more than needed for last day

# define the problem
prob = LpProblem("problem", LpMinimize)

### define constraints
# laundered each day is less than or equal to demand
prob += a1 + b1 <= 15
prob += a2 + b2 <= 12
# prob += b3 <= 18  # this can be moved to the variable definition since a3 is zero

# received each day is greater than or equal to demand
# prob += c1 >= 15  # moved to variable definition
prob += c1 + c2 + b1 >= 27
prob += c1 + c2 + c3 + b1 + b2 + a1 >= 45
prob += c1 + c2 + c3 + c4 + b1 + b2 + b3 + a1 + a2  >= 51

# define objective function
prob += .06*(a1 + a2) + .1*(b1 + b2 + b3) + .2*(c1 + c2 + c3 + c4)

# solve the problem
status3 = prob.solve()
print(f"Problem")
print(f"status={LpStatus[status3]}")

# print the results
for variable in prob.variables():
    print(f"{variable.name} = {variable.varValue}")

print(f"Objective = {value(prob.objective)}")
print(f"")

# in month 1, all \\$200 remaining should be invested in (d)
# in month 2, approx \\$100 should be invested in (c), and \\$200 in (a)
# in month 3, no additional money is invested, as the \\$200 return from month 2 is used to pay bills
# in month 4, \\$50 should be invested in (a)
# this will result in approx \\$370 cash on hand in month 5
#
# ----


from typing import List, Union

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

from models import BaseVAE

class VectorQuantizer(nn.Module):
    """
    Reference:
    [1] https://github.com/deepmind/sonnet/blob/v2/sonnet/src/nets/vqvae.py
    """

    def __init__(self, num_embeddings: int, embedding_dim: int, beta: float = 0.25):
        super(VectorQuantizer, self).__init__()
        self.K = num_embeddings
        self.D = embedding_dim
        self.beta = beta

        self.embedding = nn.Embedding(self.K, self.D)
        self.embedding.weight.data.uniform_(-1.0 / self.K, 1.0 / self.K)

    def forward(self, latents: torch.Tensor) -> torch.Tensor:
        latents = latents.permute(0, 2, 3, 1).contiguous()  # [B x D x H x W] -> [B x H x W x D]
        latents_shape = latents.shape
        flat_latents = latents.view(-1, self.D)  # [BHW x D]

        # Compute L2 distance between latents and embedding weights
        dist = (
            torch.sum(flat_latents ** 2, dim=1, keepdim=True)
            + torch.sum(self.embedding.weight ** 2, dim=1)
            - 2 * torch.matmul(flat_latents, self.embedding.weight.t())
        )  # [BHW x K]

        # Get the encoding that has the min distance
        encoding_inds = torch.argmin(dist, dim=1).unsqueeze(1)  # [BHW, 1]

        # Convert to one-hot encodings
        device = latents.device
        encoding_one_hot = torch.zeros(encoding_inds.size(0), self.K, device=device)
        encoding_one_hot.scatter_(1, encoding_inds, 1)  # [BHW x K]

        # Quantize the latents
        quantized_latents = torch.matmul(encoding_one_hot, self.embedding.weight)  # [BHW, D]
        quantized_latents = quantized_latents.view(latents_shape)  # [B x H x W x D]

        # Compute the VQ Losses
        commitment_loss = F.mse_loss(quantized_latents.detach(), latents)
        embedding_loss = F.mse_loss(quantized_latents, latents.detach())

        vq_loss = commitment_loss + self.beta * embedding_loss

        # Add the residue back to the latents
        quantized_latents = latents + (quantized_latents - latents).detach()

        return quantized_latents.permute(0, 3, 1, 2).contiguous(), vq_loss  # [B x D x H x W]

class ResidualLayer(nn.Module):
    def __init__(self, in_channels: int, out_channels: int):
        super(ResidualLayer, self).__init__()
        self.resblock = nn.Sequential(
            nn.ReLU(True),
            nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1, bias=False),
            nn.ReLU(True),
            nn.Conv2d(out_channels, out_channels, kernel_size=1, bias=False),
        )

    def forward(self, input: torch.Tensor) -> torch.Tensor:
        return input + self.resblock(input)

class VQVAE(BaseVAE):
    def __init__(
        self,
        in_channels: int,
        out_channels: int,
        embedding_dim: int,
        num_embeddings: int,
        hidden_dims: List = None,
        n_residual_layers: int = 6,
        beta: float = 0.25,
        img_size: int = 64,
        **kwargs,
    ) -> None:
        super(VQVAE, self).__init__()

        self.embedding_dim = embedding_dim
        self.num_embeddings = num_embeddings
        self.img_size = img_size
        self.beta = beta

        # modules = []
        # if hidden_dims is None:
        #     hidden_dims = [32, 64]

        # # Build Encoder
        # for h_dim in hidden_dims:
        #     modules.append(
        #         nn.Sequential(
        #             nn.Conv2d(in_channels, out_channels=h_dim, kernel_size=4, stride=2, padding=1),
        #             nn.LeakyReLU(),
        #         )
        #     )
        #     in_channels = h_dim

        # modules.append(
        #     nn.Sequential(nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1),)
        # )

        # for _ in range(n_residual_layers):
        #     modules.append(ResidualLayer(in_channels, in_channels))
        # modules.append(nn.LeakyReLU())

        # modules.append(nn.Sequential(nn.Conv2d(in_channels, embedding_dim, kernel_size=1, stride=1),))

        # self.encoder = nn.Sequential(*modules)

        # self.vq_layer = VectorQuantizer(num_embeddings, embedding_dim, self.beta)

        # # Build Decoder
        # modules = []
        # modules.append(
        #     nn.Sequential(
        #         nn.Conv2d(embedding_dim, hidden_dims[-1], kernel_size=3, stride=1, padding=1),
        #     )
        # )

        # for _ in range(n_residual_layers):
        #     modules.append(ResidualLayer(hidden_dims[-1], hidden_dims[-1]))
        # modules.append(nn.LeakyReLU())

        # hidden_dims.reverse()
        # for i in range(len(hidden_dims) - 1):
        #     modules.append(
        #         nn.Sequential(
        #             nn.ConvTranspose2d(
        #                 hidden_dims[i], hidden_dims[i + 1], kernel_size=4, stride=2, padding=1
        #             ),
        #             nn.LeakyReLU(),
        #         )
        #     )

        # modules.append(
        #     nn.Sequential(
        #         nn.ConvTranspose2d(
        #             hidden_dims[-1], out_channels=out_channels, kernel_size=4, stride=2, padding=1
        #         ),
        #         # nn.Tanh(),
        #     )
        # )

        # self.decoder = nn.Sequential(*modules)
        self.encoder = Encoder(1, h_dim=128, n_res_layers=2, res_h_dim=128, embedding_dim=64)
        self.vq_layer = VectorQuantizer2(n_e=512, e_dim=64, beta=.25)
        self.decoder = Decoder(in_dim=64, h_dim=128, n_res_layers=4, res_h_dim=128)

    def encode(self, input: torch.Tensor) -> List[torch.Tensor]:
        """
        Encodes the input by passing through the encoder network
        and returns the latent codes.
        :param input: (torch.Tensor) Input torch.tensor to encoder [N x C x H x W]
        :return: (torch.Tensor) List of latent codes
        """
        result = self.encoder(input)
        return [result]

    def decode(self, z: torch.Tensor) -> torch.Tensor:
        """
        Maps the given latent codes
        onto the image space.
        :param z: (torch.Tensor) [B x D x H x W]
        :return: (torch.Tensor) [B x C x H x W]
        """

        result = self.decoder(z)
        return result

    def forward(self, input: torch.Tensor, return_embed: bool = False, **kwargs) -> List[torch.Tensor]:
        encoding = self.encode(input)[0]
        if return_embed:
            return encoding.squeeze()
        quantized_inputs, vq_loss = self.vq_layer(encoding)
        return [self.decode(quantized_inputs), input, vq_loss]

    def loss_function(self, *args, **kwargs) -> dict:
        """
        :param args:
        :param kwargs:
        :return:
        """
        recons = args[0]
        input = args[1]
        vq_loss = args[2]

        recons_loss = F.mse_loss(recons, input)

        loss = recons_loss + vq_loss
        return {"loss": loss, "Reconstruction_Loss": recons_loss, "VQ_Loss": vq_loss}

    def sample(self, num_samples: int, current_device: Union[int, str], **kwargs) -> torch.Tensor:
        raise Warning("VQVAE sampler is not implemented.")

    def generate(self, x: torch.Tensor, **kwargs) -> torch.Tensor:
        """
        Given an input image x, returns the reconstructed image
        :param x: (torch.Tensor) [B x C x H x W]
        :return: (torch.Tensor) [B x C x H x W]
        """

        return self.forward(x)[0]

    def embed(self, input: torch.Tensor, **kwargs) -> List[torch.Tensor]:
        return self.forward(input, return_embed=True, **kwargs)

class ResidualLayer2(nn.Module):
    """
    One residual layer inputs:
    - in_dim : the input dimension
    - h_dim : the hidden layer dimension
    - res_h_dim : the hidden dimension of the residual block
    """

    def __init__(self, in_dim, h_dim, res_h_dim):
        super().__init__()
        self.res_block = nn.Sequential(
            nn.ReLU(True),
            nn.Conv2d(in_dim, res_h_dim, kernel_size=3, stride=1, padding=1, bias=False),
            nn.ReLU(True),
            nn.Conv2d(res_h_dim, h_dim, kernel_size=1, stride=1, bias=False),
        )

    def forward(self, x):
        x = x + self.res_block(x)
        return x

class ResidualStack(nn.Module):
    """
    A stack of residual layers inputs:
    - in_dim : the input dimension
    - h_dim : the hidden layer dimension
    - res_h_dim : the hidden dimension of the residual block
    - n_res_layers : number of layers to stack
    """

    def __init__(self, in_dim, h_dim, res_h_dim, n_res_layers):
        super(ResidualStack, self).__init__()
        self.n_res_layers = n_res_layers
        self.stack = nn.ModuleList([ResidualLayer2(in_dim, h_dim, res_h_dim)] * n_res_layers)

    def forward(self, x):
        for layer in self.stack:
            x = layer(x)
        x = F.relu(x)
        return x

class VectorQuantizer2(nn.Module):
    """
    Discretization bottleneck part of the VQ-VAE.
    Inputs:
    - n_e : number of embeddings
    - e_dim : dimension of embedding
    - beta : commitment cost used in loss term, beta * ||z_e(x)-sg[e]||^2
    """

    def __init__(self, n_e, e_dim, beta):
        super().__init__()
        self.n_e = n_e
        self.e_dim = e_dim
        self.beta = beta

        self.embedding = nn.Embedding(self.n_e, self.e_dim)
        self.embedding.weight.data.uniform_(-1.0 / self.n_e, 1.0 / self.n_e)

    def forward(self, z):
        """
        Inputs the output of the encoder network z and maps it to a discrete
        one-hot vector that is the index of the closest embedding vector e_j
        z (continuous) -> z_q (discrete)
        z.shape = (batch, channel, height, width)
        quantization pipeline:
            1. get encoder input (B,C,H,W)
            2. flatten input to (B*H*W,C)
        """
        # reshape z -> (batch, height, width, channel) and flatten
        z = z.permute(0, 2, 3, 1).contiguous()
        z_flattened = z.view(-1, self.e_dim)
        # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z

        d = (
            torch.sum(z_flattened ** 2, dim=1, keepdim=True)
            + torch.sum(self.embedding.weight ** 2, dim=1)
            - 2 * torch.matmul(z_flattened, self.embedding.weight.t())
        )

        # find closest encodings
        device = z.device
        min_encoding_indices = torch.argmin(d, dim=1).unsqueeze(1)
        min_encodings = torch.zeros(min_encoding_indices.shape[0], self.n_e, device=device)
        min_encodings.scatter_(1, min_encoding_indices, 1)

        # get quantized latent vectors
        z_q = torch.matmul(min_encodings, self.embedding.weight).view(z.shape)

        # compute loss for embedding
        loss = torch.mean((z_q.detach() - z) ** 2) + self.beta * torch.mean((z_q - z.detach()) ** 2)

        # preserve gradients
        z_q = z + (z_q - z).detach()

        # perplexity
        # e_mean = torch.mean(min_encodings, dim=0)
        # perplexity = torch.exp(-torch.sum(e_mean * torch.log(e_mean + 1e-10)))

        # reshape back to match original input shape
        z_q = z_q.permute(0, 3, 1, 2).contiguous()

        return z_q, loss

class Encoder(nn.Module):
    """
    This is the q_theta (z|x) network. Given a data sample x q_theta
    maps to the latent space x -> z.
    For a VQ VAE, q_theta outputs parameters of a categorical distribution.
    Inputs:
    - in_dim : the input dimension
    - h_dim : the hidden layer dimension
    - res_h_dim : the hidden dimension of the residual block
    - n_res_layers : number of layers to stack
    """

    def __init__(self, in_dim, h_dim, n_res_layers, res_h_dim, embedding_dim):
        super(Encoder, self).__init__()
        kernel = 4
        stride = 2
        self.conv_stack = nn.Sequential(
            nn.Conv2d(1, h_dim // 2, kernel_size=kernel, stride=stride, padding=1),
            nn.ReLU(),
            nn.Conv2d(h_dim // 2, h_dim, kernel_size=kernel, stride=stride, padding=1),
            nn.ReLU(),
            nn.Conv2d(h_dim, h_dim, kernel_size=kernel - 1, stride=stride - 1, padding=1),
            ResidualStack(h_dim, h_dim, res_h_dim, n_res_layers),
        )
        self.pre_quantization_conv = nn.Conv2d(h_dim, embedding_dim, kernel_size=1, stride=1)

    def forward(self, x):
        x = self.conv_stack(x)
        x = self.pre_quantization_conv(x)
        return x

class Decoder(nn.Module):
    """
    This is the p_phi (x|z) network. Given a latent sample z p_phi
    maps back to the original space z -> x.
    Inputs:
    - in_dim : the input dimension
    - h_dim : the hidden layer dimension
    - res_h_dim : the hidden dimension of the residual block
    - n_res_layers : number of layers to stack
    """

    def __init__(self, in_dim, h_dim, n_res_layers, res_h_dim):
        super(Decoder, self).__init__()
        kernel = 4
        stride = 2

        self.inverse_conv_stack = nn.Sequential(
            nn.ConvTranspose2d(in_dim, h_dim, kernel_size=kernel - 1, stride=stride - 1, padding=1),
            ResidualStack(h_dim, h_dim, res_h_dim, n_res_layers),
            nn.ConvTranspose2d(h_dim, h_dim // 2, kernel_size=kernel, stride=stride, padding=1),
            nn.ReLU(),
            nn.ConvTranspose2d(h_dim // 2, 1, kernel_size=kernel, stride=stride, padding=1),
        )

    def forward(self, x):
        return self.inverse_conv_stack(x)


import numpy as np
import pandas as pd
from decimal import *
# Project Euler Problem 30
#
# Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:
#
# 1634 = 14 + 64 + 34 + 44
# 8208 = 84 + 24 + 04 + 84
# 9474 = 94 + 44 + 74 + 44
# As 1 = 14 is not a sum it is not included.
#
# The sum of these numbers is 1634 + 8208 + 9474 = 19316.
#
# Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.

xx = [str(x) for x in range(1,1000000)]
def check(p):
    b = []
    for x in p:
        b.append(int(x)**5)
    if sum(b) == int(p):
        return int(p)
    else:
        return 0
d = []
for x in xx:
    d.append(check(x))
print(sum(d)-1)


#!/usr/bin/python3
"""Defines unittests for base_model.py"""

import models
import unittest
import os
from datetime import datetime
from models.base_model import BaseModel

class TestBaseModel(unittest.TestCase):
    """Test cases for the BaseModel class"""

    def test_create_base_model_with_no_arguments(self):
        """Test creating a BaseModel instance with no arguments."""
        model = BaseModel()
        self.assertTrue(hasattr(model, 'id'))
        self.assertTrue(hasattr(model, 'created_at'))
        self.assertTrue(hasattr(model, 'updated_at'))

    def test_create_base_model_with_attributes(self):
        """Test creating a BaseModel instance with attributes."""
        data = {
            'name': 'Test Model',
            'value': 42
        }
        model = BaseModel(**data)
        self.assertEqual(model.name, 'Test Model')
        self.assertEqual(model.value, 42)

    def test_create_base_model_with_invalid_attributes(self):
        """Test creating a BaseModel instance with invalid attributes."""
        data = {
            'created_at': '2022-01-01T00:00:00.000',
            'updated_at': '2022-01-02T00:00:00.000'
        }
        model = BaseModel(**data)
        # created_at and updated_at should not be directly set using kwargs
        self.assertNotEqual(model.created_at, '2022-01-01T00:00:00.000')
        self.assertNotEqual(model.updated_at, '2022-01-02T00:00:00.000')

    def test_save_method_updates_updated_at(self):
        """Test that the save method updates the 'updated_at' attribute."""
        model = BaseModel()
        original_updated_at = model.updated_at
        model.save()
        self.assertNotEqual(original_updated_at, model.updated_at)

    def test_to_dict_method(self):
        """Test the to_dict method for creating a dictionary representation."""
        model = BaseModel()
        model_dict = model.to_dict()
        self.assertEqual(model_dict['__class__'], 'BaseModel')
        self.assertTrue('created_at' in model_dict)
        self.assertTrue('updated_at' in model_dict)

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


import turtle

wn = turtle.Screen()
wn.title("Example 18.1 Drawing Fractals!")
wn.bgcolor("white")
fract_turtle = turtle.Turtle()
fract_turtle.pencolor("#0000FF")
fract_turtle.hideturtle()
fract_turtle.pensize(2)

def koch(t, order, size):
    """
    Make turtle t draw a Koch fractal of ’order’ and ’size’.
    Leave the turtle facing the same direction.
    """
    if order == 0:  # The base case is just a straight line
        t.forward(size)
    else:
        for angle in [-60, 120, -60, 0]:
            koch(t, order - 1, size / 3)
            t.left(angle)

def draw_poly(turtle, sides, line_length):
    for i in range(sides):
        # turtle.forward(line_length)
        koch(turtle, 3, line_length)
        turtle.left(360 / sides)

draw_poly(fract_turtle, 4, 100)

# koch(fract_turtle, 2, 100)

wn.mainloop()


import xadmin
from .models import OrderInfo

class OrderAdmin(object):
    list_display = ['order_id', 'create_time', 'total_amount', 'pay_method', 'status']
    refresh_times = [3, 5]  # 可选以支持按多长时间(秒)刷新页面
    data_charts = {
        "order_amount": {'title': '订单金额', "x-field": "create_time", "y-field": ('total_amount',),
                       "order": ('create_time',)},
        "order_count": {'title': '订单量', "x-field": "create_time", "y-field": ('total_count',),
                       "order": ('create_time',)},
    }
xadmin.site.register(OrderInfo,OrderAdmin)


import random
import time

mod = 1000000007

def main():
    print(suminvmod(input()))

def test(n):
    return ''.join(random.choice(['0', '1', '?']) for _ in range(n))

def suminvmod(string: str):
    ones = 0
    questions = 0
    inversions = 0

    for digit in string:

        if digit == '1':
            ones += 1
        else:
            if digit == '?':
                inversions *= 2

            inversions += ones * pow(2, questions, mod)
            if questions > 0:
                inversions += questions * pow(2, questions - 1, mod)

            if digit == '?':
                questions += 1

            inversions %= mod

    return inversions

if __name__ == '__main__':
    main()


import busio
import board
import time
from adafruit_bus_device.i2c_device import I2CDevice

i2c = busio.I2C(board.SCL, board.SDA)
dev = I2CDevice(i2c, 0x70)
t_1 = time.time()
count = 0
fails = 0
t_0 = time.time()
while True:
    if time.time() - t_0 > 0.07:
        result = bytearray(2)
        dev.readinto(result)
        dist = int.from_bytes(result, 'big')
        print(dist)
        t_0 = time.time()
        dev.write(bytes([0x51]))

    if time.time() - t_1 > 0.1:
        print(time.time() - t_1, dist)
        t_1 = time.time()


from rawserialised import *
from boostmappings import mappings

class Parser:
    def __init__(self, funcs):
        self.funcs = funcs
        self.parsed = []

    def parse(self):
        for func in self.funcs:
            self.parsed.append(Parser._parse(func))

    ##static methods below as they do not require instance state
    @staticmethod
    def _parse(serialised):
        nested_args = []
        nested_ret = []

        ##parse arg types
        try:
            for arg in serialised['type']['arg_types']:
                chain = Parser._chain_nested(arg)
                nested_args.append(chain)
        except:
            nested_args.append('None')

        ##parse return types
        try:
            nested_ret.append(Parser._chain_nested(serialised['type']['ret_type']))
        except:
            nested_ret.append('None')
        return (nested_ret, nested_args)

    @staticmethod
    def _chain_nested(arg):
        try:
            if 'args' in arg:
                return '%s%s' % (Parser._mapped(arg['type_ref']),[Parser._chain_nested(a) for a in arg['args']])
            elif 'items' in arg:
                return '%s%s' % (Parser._mapped(arg['fallback']['type_ref']), [Parser._chain_nested(i) for i in arg['items']])
            elif 'item' in arg:
                return Parser._chain_nested(arg['item'])
            else:
                return Parser._mapped(arg['type_ref'])
        except:
            return 'None'

    @staticmethod
    def _mapped(builtin):
        return mappings.get(builtin, builtin)

if __name__ == '__main__':
    parser = Parser([inproduct])
    parser.parse()
    print(parser.parsed)


import discord
import random
import asyncio
from discord.ext import commands
from util.core import formatter, data

em = formatter.embed_message

class Gambling(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.cooldown(1, 30, commands.BucketType.user)
    @commands.command(name="flip", aliases=["coin"])
    async def coinflip(self, ctx, bet, side=None):
        """Bet on a coinflip.
        Choose side 'heads' or 'tails'.
        If chosen right you'll double your bet!"""
        try:
            bet = int(bet)
        except (ValueError, TypeError):
            if str(bet).lower() != "all":
                await ctx.send(**em("Please give me a valid bet!\nOr if you want to go all in use \"all\"!"))
                ctx.command.reset_cooldown(ctx)
                return
        if str(bet).lower() == "all":
            bet = data.get_global_bal(ctx.author.id)[0][0]
        if side is None:
            await ctx.send(**em(type_="error",
                                content="Please provide a side your flip's on!\n"
                                        "Sides: heads *(H)* tails *(T)*"))
            ctx.command.reset_cooldown(ctx)
            return
        elif bet < 10:
            await ctx.send(**em("The minimum bet is 10!"))
            ctx.command.reset_cooldown(ctx)
            return
        elif bet > data.get_global_bal(ctx.author.id)[0][0]:
            await ctx.send(**em("You can't bet what you don't have!\n"
                                f"You have `{round(data.get_global_bal(ctx.author.id)[0][0], 2)}` coins!"))
            ctx.command.reset_cooldown(ctx)
            return
        _heads, _tails = False, False
        side = str(side).lower()
        tails = ("tails", "tail", "t")
        heads = ("heads", "head", "h")
        for count in range(len(tails)):
            if tails[count] == side:
                _tails = True
            if heads[count] == side:
                _heads = True
        if not _tails and not _heads:
            await ctx.send(**em(content="Seems like the chosen side wasn't valid!"))
        else:
            win_winning_side, los_winning_side = heads[0].capitalize(), tails[0].capitalize()
            if _tails:
                win_winning_side, los_winning_side = tails[0].capitalize(), heads[0].capitalize()
            if _heads is random.choice([True, False]):
                await ctx.send(**em(f"You just doubled your bet. *(`{round(bet, 2)}` --> `{round(bet*2, 2)}`)*\n"
                                    f"Winning side: {win_winning_side}"))
                data.add_global_bal(ctx.author.id, bet)
            else:
                await ctx.send(**em(f"You just lost your bet! *(`{round(bet, 2)}`)*\n"
                                    f"Winning side: {los_winning_side}"))
                data.remove_global_bal(ctx.author.id, bet)

    @commands.cooldown(1, 300, commands.BucketType.user)
    @commands.command(name="slots")
    async def slots(self, ctx, bet):
        """Gamble with slots!
        Slots are very profitable, but watch out!
        You can lose more than what you bet"""
        try:
            bet = int(bet)
        except (ValueError, TypeError):
            if str(bet).lower() != "all":
                await ctx.send(**em("Please give me a valid bet!\nOr if you want to go all in use \"all\"!"))
                ctx.command.reset_cooldown(ctx)
                return
        if str(bet).lower() == "all":
            bet = data.get_global_bal(ctx.author.id)[0][0]
        if bet < 100:
            await ctx.send(**em("The minimum bet is 100!"))
            ctx.command.reset_cooldown(ctx)
            return
        elif bet > data.get_global_bal(ctx.author.id)[0][0]:
            await ctx.send(**em("You can't bet what you don't have!\n"
                                f"You have `{round(data.get_global_bal(ctx.author.id)[0][0], 2)}` coins!"))
            ctx.command.reset_cooldown(ctx)
            return
        spinning = await ctx.send(**em("Spinning weel!"))
        slot_icons = ("<:Majam:659018214633635843>", "<:DevBot:659019961334890537>",
                      "<:CheekiBreeki:659018436524900383>", "ðŸ’©", "ðŸ¤¡", "ðŸ¤‘", "ðŸ’¸", "ðŸ’°", "ðŸ’³", "ðŸ’µ", "ðŸ’²")

        choices, first, last, win, selected = (), (), (), 0, " "
        for _ in range(5):
            choices += (random.choice(slot_icons),)
            first += (random.choice(slot_icons),)
            last += (random.choice(slot_icons),)
        for choice in choices:
            if choice == "<:Majam:659018214633635843>" or choice == "<:DevBot:659019961334890537>": win += 1.75
            elif choice == "<:CheekiBreeki:659018436524900383>": win += 1.25
            elif choice == "ðŸ’©" or choice == "ðŸ¤¡": win -= 2.5
            elif choice == "ðŸ¤‘" or choice == "ðŸ’³": win += 0.2
            elif choice == "ðŸ’¸" or choice == "ðŸ’°": win += 0.5
            elif choice == "ðŸ’µ" or choice == "ðŸ’²": win += 1
        await asyncio.sleep(2)
        func = spinning.edit
        try:
            await spinning.edit(**em("Spinning weel!"))
        except discord.errors.NotFound:
            func = ctx.send
        if win >= 0:
            data.add_global_bal(ctx.author.id, round(bet*win, 2))
            await func(**em(title="Slots:",
                            content=f"{selected.join(first)}\n{selected.join(choices)}<--\n"
                            f"{selected.join(last)}\nYour bet got multiplied by `{round(win, 2)}`. "
                            f"*(`{round(bet*win, 2)}`)*"))
        else:
            if bet*win - data.get_global_bal(ctx.author.id)[0][0] > 0:
                data.add_global_bal(ctx.author.id, round(bet*win, 2))
                await func(**em(title="Slots:",
                                content=f"{selected.join(first)}\n{selected.join(choices)}<--\n"
                                        f"{selected.join(last)}\nYou lost your bet by `{round(win, 2)}`."
                                        f" *(`{round(bet*win, 2)}`)*"))
            else:
                data.add_global_bal(ctx.author.id, -data.get_global_bal(ctx.author.id)[0][0])
                await func(**em(title="Slots:",
                                content=f"{selected.join(first)}\n{selected.join(choices)}<--\n"
                                        f"{selected.join(last)}\nYou lost your bet by `{round(win, 2)}`. "
                                        f"*(`{round(bet*win, 2)}`)*\nBecause you dont have so much coins your "
                                        f"balance got set to `0`!"))

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


import argparse as ap

import scipy as sp
import scipy.misc

import matplotlib

matplotlib.use('Cairo')

from matplotlib import pyplot as plt
from mpl_toolkits.axes_grid.anchored_artists import AnchoredText

_LABELS = "abcde"

def parse():
    parser = ap.ArgumentParser()
    parser.add_argument(
        "infiles", nargs="+")
    parser.add_argument(
        "-s", "--size", default=[5.8, 2.8],
        type=lambda x: [float(y) for y in x.split(",")],
        help="Size of the image (inches)")
    parser.add_argument(
        "--colormap", default="gray",
        help="Name of the colormap (in matplotlib.cm namespace)")
    parser.add_argument(
        "-d", "--dpi", default=200.0, type=float,
        help="Resolution of the image")
    parser.add_argument(
        "-o", "--output", default=None,
        help="Where to save the result")
    ret = parser.parse_args()
    return ret

def _imshow(pl, what, label, cmap):
    pl.grid()
    pl.imshow(what, cmap=cmap)
    pl.tick_params(axis='both', which='major', labelsize=10)
    at = AnchoredText(
        label, loc=2)
    at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2")
    pl.add_artist(at)

def mkFig(fig, infiles, cmap):
    imgs = [sp.misc.imread(fname, True) for fname in infiles]
    ncols = len(imgs)
    pl0 = fig.add_subplot(1, ncols, 1)
    _imshow(pl0, imgs[0], _LABELS[0], cmap)
    for ii, img in enumerate(imgs[1:]):
        ii += 2
        pl = fig.add_subplot(1, ncols, ii, sharey=pl0)
        plt.setp(pl.get_yticklabels(), visible=False)
        _imshow(pl, img, _LABELS[ii - 1], cmap)

def main():
    args = parse()
    cmap = getattr(matplotlib.cm, args.colormap)
    fig = plt.Figure(dpi=args.dpi, figsize=args.size)
    mkFig(fig, args.infiles, cmap)
    fig.tight_layout()
    fig.savefig(args.output)

if __name__ == "__main__":
    main()


from typing import *

class Solution:
    def maxOperations(self, nums: List[int], k: int) -> int:
        m = {}
        for n in nums:
            if n not in m:
                m[n] = 0
            m[n] += 1

        ret = 0
        for n in nums:
            if n in m and k - n in m and m[n] > 0 and m[k - n] > 0:
                m[n] -= 1
                m[k - n] -= 1
                if m[n] >= 0:
                    ret += 1

        return ret

solu = Solution()
print(solu.maxOperations([1,2,3,4], 5))
print(solu.maxOperations([3,1,3,4,3], 6))