import sys

n = int(input())
lst = []

for i in range(n):
    s = sys.stdin.readline().split()
    if s[0] == 'push_front':
        lst.insert(0, int(s[1]))

    elif s[0] == 'push_back':
        lst.append(int(s[1]))

    elif  s[0] == 'pop_front':
        if lst:
            print(lst[0])
            del lst[0]
        else:
            print(-1)

    elif s[0] == 'pop_back':
        if lst:
            print(lst[-1])
            lst.pop()
        else:
            print(-1)

    elif s[0] == 'size':
        print(len(lst))

    elif s[0] == 'empty':
        if lst:
            print(0)
        else:
            print(1)

    elif s[0] == 'front':
        if lst:
            print(lst[0])
        else:
            print(-1)

    elif s[0] == 'back':
        if lst:
            print(lst[-1])
        else:
            print(-1)


rock=1
paper=2
scissors=3
lost=0
draw=3
won=6
points=0

with open ("day2.txt") as file:
    for i in file:
        columns=i.strip().split(" ")
        elf=columns[0]
        me=columns[1]
        if elf=="A":
            if me=="X":
                points+=(lost+scissors)
            elif me=="Y":
                points+=(draw+rock)
            else:
                points+=(won+paper)

        elif elf=="B":
            if me=="X":
                points+=(lost+rock)
            elif me=="Y":
                points+=(draw+paper)
            else:
                points+=(won+scissors)

        elif elf=="C":
            if me=="X":
                points+=(lost+paper)
            elif me=="Y":
                points+=(draw+scissors)
            else:
                points+=(won+rock)
print(points)


# -*- coding: utf-8 -*-
"""
Created on Wed Dec 22 21:32:13 2021

@author: Marius
"""

import torch
import torch.nn as nn
import numpy as np
from functools import reduce
import operator

def krons(psi):
    if psi.shape[0] == 2:
        return torch.kron(psi[0], psi[1])
    elif psi.shape[0] > 2:
        return torch.kron(psi[0], krons(psi[1:]))
    elif psi.shape[0] == 1:
        return psi[0]
    else:
        return print("Invalid input")

class Rx_layer(nn.Module):
    "A layer applying the Rx gate"
    def __init__(self, n_blocks: int, n_qubits: int, weights = None, weights_spread = [-np.pi/2,np.pi/2]):
        """
        weights: a tensor of rotation angles, if given from input data
        """

        super().__init__()

        self.n_blocks = n_blocks
        self.n_qubits = n_qubits
        self.weights_spread = weights_spread

        if weights is None:
            self.weights = nn.Parameter(torch.Tensor(1, self.n_blocks,1,self.n_qubits,1,1))
            nn.init.uniform_(self.weights, self.weights_spread[0], self.weights_spread[1])
            self.weights.cfloat()
        else:
            self.weights = weights
            if self.weights.shape[1] == n_blocks*n_qubits:
                self.weights = self.weights.view(-1, n_blocks, 1, n_qubits, 1, 1)
            else:
                shape = weights.shape
                self.weights = weights.view(shape[0], shape[1], 1, shape[2], 1, 1)
            if self.weights.shape[1] == 1 and self.n_blocks > 1:
                self.weights = self.weights.repeat(1,self.n_blocks,1, 1, 1, 1)
            if self.weights.shape[3] == 1 and self.n_qubits > 1:
                self.weights = self.weights.repeat(1,1,1, self.n_qubits, 1, 1)

            assert self.weights.shape[1] * self.weights.shape[3] == n_blocks*n_qubits, "Dimensions of weight tensor are incompatable. Check the input has the right batch size, block and qubit count"

    def Rx(self, data=None):
        identity = torch.eye(2)
        off_identity = torch.Tensor([[0,1],[1,0]])
        if data == None:
            a = (self.weights/2).cos()
            b = (self.weights/2).sin()
        else:
            assert data.shape[1] == self.weights.nelement(), "Dimension of data incompatible"
            data = data.view((-1, *self.weights.shape[1:]))
            a = (self.weights*data/2).cos()
            b = (self.weights*data/2).sin()

        return a*identity - 1j*b*off_identity

    def forward(self, state, data=None):
        """
        Take state to be a tensor with dimension batch x blocks x d&c x n-qubit state (2**n x 1)
        """
        Rxs = self.Rx(data).cfloat()
        U = torch.zeros(*Rxs.shape[:3], 2**self.n_qubits, 2**self.n_qubits).cfloat()
        for batch_idx in range(U.shape[0]):
            for block_idx in range(self.n_blocks):
                U[batch_idx, block_idx, :] = krons(Rxs[batch_idx, block_idx, 0])

        state = torch.matmul(U, state)

        return state

class Ry_layer(nn.Module):
    "A layer applying the Ry gate"
    def __init__(self, n_blocks: int, n_qubits: int, weights = None, weights_spread = [-np.pi/2,np.pi/2]):
        """
        weights: a tensor of rotation angles, if given from input data
        """

        super().__init__()

        self.n_blocks = n_blocks
        self.n_qubits = n_qubits
        self.weights_spread = weights_spread

        if weights is None:
            self.weights = nn.Parameter(torch.Tensor(1, self.n_blocks,1,self.n_qubits,1,1))
            nn.init.uniform_(self.weights, self.weights_spread[0], self.weights_spread[1])
            self.weights.cfloat()
        else:
            self.weights = weights
            if self.weights.shape[1] == n_blocks*n_qubits:
                self.weights = self.weights.view(-1, n_blocks, 1, n_qubits, 1, 1)
            else:
                shape = weights.shape
                self.weights = weights.view(shape[0], shape[1], 1, shape[2], 1, 1)
            if self.weights.shape[1] == 1 and self.n_blocks > 1:
                self.weights = self.weights.repeat(1,self.n_blocks,1, 1, 1, 1)
            if self.weights.shape[3] == 1 and self.n_qubits > 1:
                self.weights = self.weights.repeat(1,1,1, self.n_qubits, 1, 1)

            assert self.weights.shape[1] * self.weights.shape[3] == n_blocks*n_qubits, "Dimensions of weight tensor are incompatable. Check the input has the right batch size, block and qubit count"

    def Ry(self, data=None):
        identity = torch.eye(2)
        off_identity = torch.Tensor([[0,-1],[1,0]])
        if data == None:
            a = (self.weights/2).cos()
            b = (self.weights/2).sin()
        else:
            assert data.shape[1] == self.weights.nelement(), "Dimension of data incompatible"
            data = data.view((-1, *self.weights.shape[1:]))
            a = (self.weights*data/2).cos()
            b = (self.weights*data/2).sin()
        return a*identity + b*off_identity

    def forward(self, state, data=None):
        """
        Take state to be a tensor with dimension batch x blocks x d&c x n-qubit state (2**n x 1)
        """

        Rys = self.Ry(data).cfloat()
        U = torch.zeros(*Rys.shape[:3], 2**self.n_qubits, 2**self.n_qubits).cfloat()
        for batch_idx in range(U.shape[0]):
            for block_idx in range(self.n_blocks):
                U[batch_idx, block_idx, :] = krons(Rys[batch_idx, block_idx, 0])

        state = torch.matmul(U, state)

        return state

    ### Consider how to include nograd if weights is given. This might be already incorporated?

class Rz_layer(nn.Module):
    "A layer applying the Rz gate"
    def __init__(self, n_blocks: int, n_qubits: int, weights = None, weights_spread = [-np.pi/2,np.pi/2]):
        """
        weights: a tensor of rotation angles, if given from input data
        """

        super().__init__()

        self.n_blocks = n_blocks
        self.n_qubits = n_qubits
        self.weights_spread = weights_spread

        if weights is None:
            self.weights = nn.Parameter(torch.Tensor(1, self.n_blocks,1,self.n_qubits,1))
            nn.init.uniform_(self.weights, self.weights_spread[0], self.weights_spread[1])
            self.weights.cfloat()
        else:
            self.weights = weights
            if self.weights.shape[1] == n_blocks*n_qubits:
                self.weights = self.weights.view(-1, n_blocks, 1, n_qubits, 1)
            else:
                shape = weights.shape
                self.weights = weights.view(shape[0], shape[1], 1, shape[2], 1)
            if self.weights.shape[1] == 1 and self.n_blocks > 1:
                self.weights = self.weights.repeat(1,self.n_blocks,1, 1, 1)
            if self.weights.shape[3] == 1 and self.n_qubits > 1:
                self.weights = self.weights.repeat(1,1,1, self.n_qubits, 1)

            assert self.weights.shape[1] * self.weights.shape[3] == n_blocks*n_qubits, "Dimensions of weight tensor are incompatable. Check the input has the right batch size, block and qubit count"

    def Rz(self):
        a = -1j*(self.weights/2)
        Z = torch.Tensor([[1, -1]])
        return (a*Z).exp()

    def forward(self, state):
        """
        Take state to be a tensor with dimension batch x blocks x d&c x n_qubit state (2**n_qubits_perblock x 1)
        """
        Rzs = self.Rz().cfloat()
        U = torch.zeros(*Rzs.shape[:3], 2**self.n_qubits, 1).cfloat()
        for batch_idx in range(U.shape[0]):
            for block_idx in range(self.n_blocks):
                U[batch_idx, block_idx, :] = krons(Rzs[batch_idx, block_idx, 0]).reshape(-1,1) #Reshape because using flattend matrix

        state = U*state

        return state

class Hadamard_layer(nn.Module):
    def __init__(self, n_blocks: int, n_qubits: int):
        super().__init__()

        self.H = torch.Tensor([[1, 1], [1, -1]]).reshape(1,2,2)/(2**0.5)
        self.H = krons(self.H.repeat(n_qubits,1,1)).cfloat()

    def forward(self, state):
        return torch.matmul(self.H, state)

class CNOT_layer(nn.Module):
    def __init__(self, n_blocks: int, block_size: int, qubit_pairs: list):
        super().__init__()

        self.n_blocks = n_blocks
        self.block_size = block_size
        self.pairs = qubit_pairs

    def gen_CNOT(self, pair):
        if pair[0] > pair[1]:
            U = torch.zeros((2**self.block_size, 2**self.block_size))
            I = torch.eye(2**(self.block_size-1)).flatten()
            stride = 2**(self.block_size-pair[0]-1)
            unstride = 2**(pair[0])
            mask = torch.Tensor([[1,0],[0,0]]).bool()
            mask = mask.repeat_interleave(stride, dim=0).repeat_interleave(stride, dim=1)
            mask = mask.repeat(unstride, unstride)
            U[mask] = I

            I = torch.eye(2**(self.block_size-2)).flatten()
            outer_mask_1 = torch.Tensor([[0,0], [1,0]]).bool()
            outer_mask_2 = torch.Tensor([[0,1], [0,0]]).bool()
            inner_mask = torch.Tensor([[0,0],[0,1]]).bool()
            inner_mask = inner_mask.repeat_interleave(stride, dim=0).repeat_interleave(stride, dim=1)
            inner_mask = inner_mask.repeat(unstride//2, unstride//2)
            mask = torch.kron(outer_mask_1, inner_mask)
            U[mask] = I
            mask = torch.kron(outer_mask_2, inner_mask)
            U[mask] = I

        elif pair[0] < pair[1]:
            X = torch.Tensor([[0,1],[1,0]])
            I1 = torch.eye(2**(pair[1] - pair[0] - 1))
            I2 = torch.eye(2**(self.block_size - pair[1] - 1))
            M = torch.kron(I1, torch.kron(X, I2))
            U = torch.eye(M.shape[0]*2)
            U[U.shape[0]//2:, U.shape[0]//2:] = M
            pre_I = torch.eye(2**pair[0])
            U = torch.kron(pre_I, U)

        else:
            raise RuntimeError("Invalid qubit pair given")

        return U

    def forward(self, state):
        for pair in self.pairs:
            CNOT = self.gen_CNOT(pair).cfloat()
            state = torch.matmul(CNOT, state)

        return state

class Entangle_layer(nn.Module):
    """A layer applying the CNOT gate to given pairs of qubits in different blocks"""
    def __init__(self, coordinates, n_qubits):
        """
        qubit_pairs: a list of tuples containing pairs of qubits to be entangled in a single layer
        """

        super().__init__()

        self.n_qubits = n_qubits
        self.coordinates = coordinates
        # qubit pairs should be a list of tuples of the form ((block_idx1, qubit_idx1), (block_idx2, qubit_idx2))
        # the first tuple contains the control qubit coordinate, and the second tuple the target qubit coordinate

        self.I = torch.eye(2).cfloat()
        self.H = torch.Tensor([[1, 1], [1, -1]])/(2**0.5)
        self.H = self.H.cfloat()
        self.Z = torch.Tensor([[1,0],[0,-1]]).cfloat()
        self.S = torch.Tensor([[1,0],[0,1]]).cfloat()
        self.S[1,1] = -1j #This is actually S_conj just to save an unneccesary .conj() operation

    # Change this to feed in the explicit form of the matrix rather than calculating
    def control_U(self, Pauli):
        return torch.mm(self.S, Pauli)

    def target_U(self, Pauli):
        return torch.mm(self.H, torch.mm(self.S, torch.mm(Pauli, self.H)))

    def embed(self, q_idx: int, control_or_target):
        U = control_or_target
        if q_idx > 0 and q_idx < self.n_qubits - 1:
            pre_I = torch.eye(2**(q_idx))
            post_I = torch.eye(2**(self.n_qubits-q_idx-1))
            return torch.kron(pre_I, torch.kron(U, post_I))
        elif q_idx == 0:
            post_I = torch.eye(2**(self.n_qubits-1))
            return torch.kron(U, post_I)
        elif q_idx == self.n_qubits - 1 or q_idx == -1:
            pre_I = torch.eye(2**(self.n_qubits - 1))
            return torch.kron(pre_I, U)
        else:
            raise ValueError("Invalid qubit index given")

    def forward(self, state):
        """
        state is a batch_size x n_blocks x d&c x 2**n_qubits x 1
        ent_pairs is a list of lists containing pairs of idxs of entangled blocks"""
        for gate in self.coordinates:
            state = state.repeat(1,1,2,1,1)

            for j, (block_idx, qubit_idx) in enumerate(gate):

                reps = state.shape[2] // 2
                if j == 0:
                    state[:, block_idx, :reps] = torch.matmul(self.embed(qubit_idx, self.control_U(self.I)),
                                                              state[:, block_idx, :reps])
                    state[:, block_idx, reps:] = torch.matmul(self.embed(qubit_idx, self.control_U(self.Z)),
                                                              state[:, block_idx, reps:])
                if j == 1:
                    state[:, block_idx, :reps] = torch.matmul(self.embed(qubit_idx, self.target_U(self.I)),
                                                              state[:, block_idx, :reps])
                    state[:, block_idx, reps:] = torch.matmul(self.embed(qubit_idx, self.target_U(self.Z)),
                                                              state[:, block_idx, reps:])

        return state


import string
import docker
import tempfile
import json
import time
from redis_om import NotFoundError
from src.utils import wait_for_container
from src.core.config import settings
from src.schema.redis import ProjectModel, ResearchModel

class Biogpt():
	image_name: str = settings.biogpt_image
	network_name: str = 'duri_api'
	redis_hosturl: str = 'redis:6379'
	workdir: str = None
	project: str = None

	def __init__(self):
		pass

	def set_workdir(self) -> dict:
		if self.workdir:
			return self.workdir
		self.workdir = tempfile.mkdtemp(dir=settings.biogpt_workdir)
		return self.workdir

	def get_project(self, objective) -> dict:
		""" get a project from redis  """
		objective = objective.strip()
		try:
			project = ProjectModel.find(ProjectModel.objective == objective).first()
			if not project:
				return None
			print('project.workdir: ', project.workdir)
			if project.workdir:
				self.workdir = project.workdir
			else:
				project.workdir = self.set_workdir()
				project.save()
			#print(project)
			project.name = project.name.strip().replace("\\n", "").replace('\"', "").strip(string.punctuation).strip()
			project.save()
			self.project = project
			return project
		except NotFoundError as e:
			#print(e)
			return None
		except Exception:
			#print(e)
			return None

	def get_research(self, objective) -> dict:
		""" get a research obj from redis  """
		objective = objective.strip()
		try:
			research = ResearchModel.find(ResearchModel.objective == objective).first()
			if not research:
				return None
			print('research.workdir: ', research.workdir)
			if research.workdir:
				self.workdir = research.workdir
			else:
				research.workdir = self.set_workdir()
				research.save()
			#print(project)
			if research.name:
				research.name = research.name.strip().replace("\\n", "").replace('\"', "").strip(string.punctuation).strip()
				research.save()
			self.research = research
			return research
		except NotFoundError:
			return None

	def init(self, objective, name:str=None) -> ProjectModel:
		""" get or starts an ai project. returns a unique id of that project objective provided """
		project = self.get_project(objective)
		if project and project.name and project.name != 'None':
			return project
		self.workdir = self.set_workdir()
		cmds = [ "init", "-o", objective]
		container = self.call(cmds, wait=True)
		#print(response)
		#resp_dict = json.loads(response).get("project_id", None)
		#project_id = resp_dict.get("project_id", None)
		while True:
			time.sleep(1)
			project = self.get_project(objective)
			if project and project.assistants:
				break
		project = self.get_project(objective)
		#print(project)
		if name:
			project.name = name
			project.save()
		self.project = project
		return project

	def run(self, objective, max_count=50) -> dict:
		project = self.get_project(objective)
		if not project:
			raise NotFoundError()
		cmds = [ "run", "-o", str(objective), '-c', str(max_count)]
		container = self.call(cmds, wait=False, auto_remove=True)
		return container

	def init_research(self, project_id:str, objective, name:str=None) -> ResearchModel:
		""" get or starts an ai research. returns the research object """
		research = self.get_research(objective)
		if research and research.name:
			return research
		self.workdir = self.set_workdir()
		cmds = [ "research", "-p", str(project_id),  "-o", objective]
		if name:
			cmds = cmds + ["-n", name]
		container = self.call(cmds, wait=True)
		while True:
			time.sleep(1)
			research = self.get_research(objective)
			if research and research.goals:
				break
		research = self.get_research(objective)
		self.research = research
		return research

	def run_research(self, project_id:str, objective, max_count=50) -> dict:
		research = self.get_research(objective)
		if not research:
			raise ValueError('research not found')
		cmds = [ "research", "-p", str(project_id), "-r", "-o", objective, '-c', str(max_count)]
		container = self.call(cmds, wait=False, auto_remove=True)
		return container

	def call(self, cmd, wait=False, auto_remove=True, app_dir: str = "/app/outputs") -> dict:
		client = docker.from_env()
		assert self.workdir
		workdir = self.workdir
		envs = self.get_env()
		container = client.containers.run(
			image=self.image_name,
			detach=True,
			#privileged=True, ## for headless browser
			auto_remove=auto_remove,
			environment=envs,
			network=self.network_name,
			volumes={
				f'{workdir}/outputs': {
					"bind": app_dir,
					"mode": "rw"
				}
			},
			command=cmd
		)
		print(container)
		if wait:
			while wait_for_container(container) == 'running':
				time.sleep(1)
		print(container)
		#status = container.status
		#container_id = str(container.id)[:12]
		#container_id = container.shortid
		return container

	def get_env(cls):
		return {
			"OPENAI_API_KEY": settings.openai_key,
			"SERPER_API_KEY": settings.serper_key,
			"WEAVIATE_URL": settings.weaviate_url,
			"REDIS_HOST": settings.redis_host,
		}


dx, dy = [0,0,1,-1], [1,-1,0,0]

def sol(r, c):
    if 0 <= r < n and 0 <= c < n:
        if arr[r][c] == 1:
            cnt = 1
            arr[r][c] = 0
            for i in range(4):
                cnt += sol(r+dx[i], c+dy[i])
            return cnt
    return 0

n = int(input())
arr = [list(map(int, input())) for _ in range(n)]
ans = []

for r in range(n):
    for c in range(n):
        if arr[r][c] == 1:
            ans.append(sol(r, c))
print(len(ans), *sorted(ans), sep='\n')

백준/Silver/2667. 단지번호붙이기/단지번호붙이기.py


from wsgiref.simple_server import make_server
from pyramid.config import Configurator

import views

import os

from db import Session as DBSession

def manageSession(request):
  session = DBSession()
  def closeSession(request):
    session.close()
  request.add_finished_callback(closeSession)
  return session

if __name__ == '__main__':

  import logconfig
  logconfig.setup()

  here = os.path.dirname(os.path.abspath(__file__))

  settings = {}
  settings['reload_all'] = True
  settings['debug_all'] = True
  settings['mako.directories'] = os.path.join(here, 'templates')

  config = Configurator(settings=settings)

  config.add_request_method(manageSession, "session", reify=True)

  config.include('pyramid_mako')

  config.add_static_view("static", "static", cache_max_age = 0)

  #also show sample page. this is for testing and not part of the project itself.
  config.add_static_view("samplepage", "samplepage", cache_max_age = 0)

  views.addToConfig(config)

  app = config.make_wsgi_app()
  server = make_server('0.0.0.0', 8080, app)

  server.serve_forever()

  #import cProfile
  #cProfile.run("server.serve_forever()", "profile.rs")


#---==IMPORTS==---
from discord.ext import commands

#---==COMMANDS==---
class member(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_member_join(self, member):
        """Welcomes a new member."""
        channel = member.guild.system_channel
        if channel is not None:
            await channel.send('Welcome {0.mention}.'.format(member))

    # @commands.command()
    # async def joined(self, ctx, member : discord.Member):
    #     """Says when a member joined."""
    #     if member:
    #         await self.bot.say('{0.name} joined in {0.joined_at}'.format(member))
    #     else:
    #         await self.bot.say('Member not found.')


from rest_framework.response import Response
from rest_framework import status
from rest_framework.views import APIView

from management.serializers.NotificationSerializer import NotificationSerializer, NotificationPageSerializer
from pms.models import Notification
from pmsDoctor.models.APIObject import APIObject

class NotificationApi(APIView):

    def post(self, request, format=None):
        serializer = NotificationSerializer(data=request.data, context={'request': request})

        if serializer.is_valid():
            serializer.save()
            return Response({"message": "notification is created"}, status=status.HTTP_200_OK)
        else:
            errors = dict()
            for key, value in serializer.errors.items():
                if key == 'title':
                    errors['Baslik'] = value
                elif key == 'Image':
                    errors['fotograf'] = value
                elif key == 'body':
                    errors['Aciklama'] = value
                elif key == 'link':
                    errors['Link'] = value

            return Response(errors, status=status.HTTP_400_BAD_REQUEST)

    def get(self, request, format=None):
        active_page = 1
        count = 0
        if request.GET.get('activePage') is not None:
            active_page = int(request.GET.get('activePage'))
        lim_start = 10 * (int(active_page) - 1)
        lim_end = lim_start + 10
        notifications = Notification.objects.all().order_by('-id')[
                        lim_start:lim_end]
        count = Notification.objects.all().count()
        arr = []
        for notification in notifications:
            api_object = dict()
            api_object['uuid'] = notification.uuid
            api_object['title'] = notification.title
            api_object['body'] = notification.body
            api_object['image'] = notification.image
            api_object['link'] = notification.link
            arr.append(api_object)
        api_object = APIObject()
        api_object.data = arr
        api_object.recordsFiltered = notifications.count()
        api_object.recordsTotal = count
        if count % 10 == 0:
            api_object.activePage = count / 10
        else:
            api_object.activePage = (count / 10) + 1
        serializer = NotificationPageSerializer(api_object, context={'request': request})
        return Response(serializer.data, status.HTTP_200_OK)


'''
原型：filter（发你，lsd）
参数1为函数
参数2为序列

功能：用于过滤序列
白话文：把传入的函数依次作用于序列的每个元素，根据返回的是True还是False决定是否保留该元素
'''

list1 = [1,2,3,4,5,6,7,8,9]
#偶数保留，奇数剔除
def func(num):
    if num%2 == 0:
        return True
    return False
l = filter(func,list1)
print(list(l))


# coding=utf-8
import networkx as nx
from semantic_similarity_network import *
from candidate_words import *

class BetweenCentrality:

    def __init__(self):
        self.G = nx.Graph()
        self.bcdict = {}
        self.nword = {}

    def codes_betweeness_centarlity(self, string_sentence):
        """
        function: 计算词语的居间度
        :param: string_sentence :  待分析的短句
        :return: self.bcdict : 词语居间度
        """
        candidate_words_dict, nwword = CandidateWords().get_candidate_list(string_sentence)
        nwword_words = nwword.values()
        length = len(nwword_words)
        for i in range(length):
            self.G.add_node(i)
        E = SemanticSimilarity().similarity_network_edges(string_sentence)
        self.G.add_edges_from(E)
        vd = nx.betweenness_centrality(self.G, k=None, normalized=True, weight=None, endpoints=False, seed=None)
        for i in range(length):
            self.bcdict[nwword_words[i]] = vd[i]
        for i in range(length):
            self.nword[i] = nwword_words[i]
        return self.bcdict


fruit = ["Apple", "Orange", "Pear"]
print(fruit)

fruit.append("Banana")
fruit.append("Peach")
print(fruit)

a = fruit.pop()
b = fruit.pop()

print(a, b, fruit)

double_fruit = fruit + fruit
print(double_fruit)

print("Apple" in double_fruit)

len(double_fruit)

colors = ["purple", "orange", "green"]
guess = input("what is the color? (input):")
if guess in colors:
    print("Correct!")
else:
    print("Incorrect! Try again!")


# -*- coding: utf-8 -*-
"""
Created on Wed Sep 29 14:47:57 2021

@author: 张文浩
"""

#导入相关库
import sys
import math
from collections import defaultdict
from functools import reduce
from textblob import TextBlob        #导入文本处理工具
from textblob import Word
import json

Wt_d = defaultdict(dict) #记录Wt,d
doc_score = defaultdict(dict) #记录每个doc的最终得分
doc_tot = 0#总共有多少个文件
doc_num=defaultdict(int)#文档
Wt_q=defaultdict(int)#词数
df0 = defaultdict(dict)
smart=""

#为提前获得df而先读一遍文件的函数
def get_df():
    global doc_tot
    f = open(r"E:\datamining\exp1\tweets.txt")
    lines = f.readlines()
    uselessword = [",","'","‘","“","’","-","”","——"]
    #一行一行处理
    for line in lines:
        doc_tot += 1
        #大写转小写
        line = line.lower()
        line = json.loads(line)
        #处理当前行得到tweetidid和text文本
        tweetid = Word(line['tweetid'])
        text = TextBlob(line['text']+" "+line['username']).words.singularize()
        texts = []
        for word in text:
            if word in uselessword:
                continue
            temp = Word(word)
            temp = temp.lemmatize("v") #词形还原
            texts.append(temp)

        unique_terms=set(texts)
        for term in unique_terms:
            df0[term][tweetid]=1

def compute_Wt_d():
    global Wt_d
    #读入数据
    f = open(r"E:\datamining\exp1\tweets.txt")
    lines = f.readlines()
    uselessword = [",","'","‘","“","’","-","”","——"]
    #一行一行处理
    for line in lines:
        #大写转小写
        line = line.lower()
        line = json.loads(line)
        #处理当前行得到tweetidid和text文本
        tweetid = Word(line['tweetid'])
        text = TextBlob(line['text']+" "+line['username']).words.singularize()
        texts = []
        for word in text:
            if word in uselessword:
                continue
            temp = Word(word)
            temp = temp.lemmatize("v") #词形还原
            texts.append(temp)
        doc_num={} #记录这个词出现的次数
        for term in texts:
            if term in doc_num.keys():
                doc_num[term]+=1
            else:
                doc_num[term]=1
        #n/l/a/b/L
        if(smart[0]=='n'):
            pass
        if(smart[0]=='l'):
            for term in doc_num.keys():
                doc_num[term]=math.log(doc_num[term])+1
        if(smart[0]=='a'):
            maxx=0
            for term in doc_num.keys():
                if maxx<doc_num[term]:
                    maxx=doc_num[term]
            for term in doc_num.keys():
                doc_num[term]=0.5+(0.5*doc_num[term])/maxx
        if(smart[0]=='b'):
            for term in doc_num.keys():
                doc_num[term]=1
        if(smart[0]=='L'):
            ave=0;
            for term in doc_num.keys():
                ave+=doc_num[term]
            ave/=len(doc_num)
            for term in doc_num.keys():
                doc_num[term]=(1+math.log(doc_num[term]))/(1+math.log(ave))

        #n/t/p
        if(smart[1]=='n'):
            pass
        if(smart[1]=='t'):
            for term in doc_num.keys():
                doc_num[term]*=math.log(doc_tot/len(df0[term]))
        if(smart[1]=='p'):
            for term in doc_num.keys():
                doc_num[term]*=max(0,math.log((doc_tot-len(df0[term]))/len(df0[term])))

        #归一化
        #n/c
        if(smart[2]=='n'):
            pass
        if(smart[2]=='c'):
            sum=0
            for term in doc_num.keys():
                sum=sum+doc_num[term]*doc_num[term]
            sum=1.0/math.sqrt(sum)
            for term in doc_num.keys():
                doc_num[term]=doc_num[term]*sum

        unique_terms=set(texts)
        for term in unique_terms:
            Wt_d[term][tweetid]=doc_num[term]

def compute_score(query):
    global doc_score,Wt_q
    doc_score={}
    Wt_q={}
    for term in query:
        if term in Wt_q:
            Wt_q[term]+=1
        else:
            Wt_q[term]=1

    #n/l/a/b/L
    if(smart[4]=='n'):
        pass
    if(smart[4]=='l'):
        for term in Wt_q.keys():
            Wt_q[term]=math.log(Wt_q[term])+1
    if(smart[4]=='a'):
        maxx=0
        for term in Wt_q.keys():
            if maxx<Wt_q[term]:
                maxx=Wt_q[term]
        for term in Wt_q.keys():
            Wt_q[term]=0.5+(0.5*Wt_q[term])/maxx
    if(smart[4]=='b'):
        for term in Wt_q.keys():
            Wt_q[term]=1
    if(smart[4]=='L'):
        ave=0;
        for term in Wt_q.keys():
            ave+=Wt_q[term]
        ave/=len(Wt_q)
        for term in Wt_q.keys():
            Wt_q[term]=(1+math.log(Wt_q[term]))/(1+math.log(ave))

    #n/t/p
    if(smart[5]=='n'):
        pass
    if(smart[5]=='t'):
        for term in Wt_q.keys():
            Wt_q[term]*=math.log(doc_tot/len(df0[term]))
    if(smart[5]=='p'):
        for term in Wt_q.keys():
            Wt_q[term]*=max(0,math.log((doc_tot-len(df0[term]))/len(df0[term])))

    #归一化
    #n/c
    if(smart[6]=='n'):
        pass
    if(smart[6]=='c'):
        sum=0
        for term in Wt_q.keys():
            sum=sum+Wt_q[term]*Wt_q[term]
        sum=1.0/math.sqrt(sum)
        for term in Wt_q.keys():
            Wt_q[term]=Wt_q[term]*sum

#    for term in Wt_q.keys():
#        if term in Wt_d:
#            df=len(Wt_d[term])
#        else:
#            df=doc_tot
#        Wt_q[term]=(math.log(Wt_q[term])+1)*math.log(doc_tot/df)

    for term in query:
        if term in Wt_d:
            for doc in Wt_d[term]:
                if doc in doc_score.keys():
                    doc_score[doc]+=Wt_d[term][doc]*Wt_q[term]
                else:
                    doc_score[doc]=Wt_d[term][doc]*Wt_q[term]
    doc_score_sorted=sorted(doc_score.items(),key=lambda x:x[1],reverse=True)
    return doc_score_sorted

def myinput(doc):
    #处理手动输入的数据，方便与terms中的存好的term进行匹配
    doc = doc.lower()
    terms = TextBlob(doc).words.singularize()
    res = []
    for term in terms:
        term = Word(term)
        term = term.lemmatize("v") #词形还原
        res.append(term)
    return res

#取并集函数
def Union(sets):
    return reduce(set.union, [s for s in sets])

def search():       #查询
    n=int(input("请输入想得到的最相关的doc的数量：  "))
    if (n==0):
        sys.exit()
    query = myinput(input("请输入要查询词,退出请键入exit： "))
    ans = []
    if len(query)==0:
        sys.exit()
    ans_num = Union([set(Wt_d[term].keys()) for term in query])
    print("一共有"+str(len(ans_num))+"条相关doc")
    print("与输入相关性最大的"+str(n)+"个doc的score及其tweetid分别是:")#调用sorted函数对score进行排序
    scores=compute_score(query)
    i = 1
    for (id, score) in scores:
        if i<=n:#返回前n条查询到的信息
            ans.append(id)
            print(str(score) + ": " + id)
            i = i + 1
        else:
            break

def main():
    global smart
    get_df()
    smart=input("请输入计算机制，格式请标准如：lnc.ltn: ")
    compute_Wt_d()
    while 1:
        search()

if __name__ == "__main__":
    main()


# -*- coding: utf-8 -*-
import subprocess

class call:
    """アメダス[観測地点] : アメダスでの現在の情報を表示"""
    def __init__(self, payload):
        item = payload['data']
        text = item['text']
        rtmclient = payload['rtm_client']
        webclient = payload['web_client']
        channel = item['channel']
        thread_ts = item.get('thread_ts')

        prefix = 'アメダス'
        if text.startswith(prefix) and item.get('bot_id') is None:
            loc = text.replace(prefix, '')
            amedas = subprocess.check_output(['amedas', loc]).decode('utf8').strip()
            webclient.chat_postMessage(
                username=prefix,
                icon_emoji=rtmclient.icon_emoji,
                channel=channel,
                text=amedas,
                thread_ts=thread_ts,
            )


from itertools import product
import sys

sys.setrecursionlimit(10**6)

input = sys.stdin.readline

def func1( S : str) -> str:
    return (S+"A")

def func2(S : str) -> str:
    return (S+"B")[::-1]

def checkf(li):
    global S

    tmp_s = S
    for i in li:
        tmp_s = func1(tmp_s) if i == 0 else func2(tmp_s)
    return tmp_s

def dfs(idx, level):

    global S
    global T
    global check

    if idx == level:
        if checkf(result) == T:
            print(1)
            sys.exit()

        return

    for i in range(2):
        result[idx] = elem[i]
        checked[i] = True
        dfs(idx+1, level)
        checked[i]= False

elem = [0,1]

S = input().split()[0]
T =  input().split()[0]

check = False
length = len(T) - len(S)
result = [0]*length
checked =[False]*2

dfs(0, length)

print(0)


import pandas as pd
donnees = pd.read_excel("ProjetDATASCIENCE.xlsx")
moyenneEcole = donnees["Moyenne"].sum()/(len(donnees))
pourcentageFille = (len(donnees[donnees["Sexe"]=="F"])/len(donnees))*100
pourcentageGarcon = (len(donnees[donnees["Sexe"]=="M"])/len(donnees))*100
regionPlusforte = donnees[donnees["Moyenne"]==donnees["Moyenne"].max()]
regionPlusforteM = regionPlusforte["Region"]
data=[[moyenneEcole,pourcentageFille,pourcentageGarcon,regionPlusforteM]]
statistics = pd.DataFrame(data,columns=["moyenneEcole","pourcentageFille","pourcentageGarcon","regionPlusforte"])
statistics.to_excel("statistics.xlsx")


# -*- coding: utf-8 -*-

if __name__ == "__main__":
    n = int(input())
    a_list = [int(v) for v in input().split()]
    b_list = [int(v) for v in input().split()]
    c_list = [int(v) for v in input().split()]

    # 予め Ai と Bcj の値として考えられるものを全て列挙し、カウントする。（バケット法）
    a_cnt_list = [0] * (n+1)
    b_cnt_list = [0] * (n+1)
    for i in range(n):
        a_i = a_list[i]
        a_cnt_list[a_i] += 1

        c_i = c_list[i] - 1
        b_ci = b_list[c_i]
        b_cnt_list[b_ci] += 1

    ans_cnt = 0
    # 値が一致する A と B だけを調べる。
    for a_cnt, b_cnt in zip(a_cnt_list, b_cnt_list):
        if a_cnt * b_cnt:
            ans_cnt += a_cnt * b_cnt

    print(ans_cnt)


import argparse
import sys

from collections import OrderedDict

ignoreEvn = ['PATH']

serviceOrder = [
    'image',
    'container_name',
    'restart',
    'command',
    'networks',
    'labels',
    'logging',
    'ports',
    'environment',
    'volumes',
]

def customOrder(data: dict, items: list):

    new_data = OrderedDict()

    for i in items:
        try:
            new_data[i] = data[i]
        except:
            pass

    for j in data.keys():
        if j not in items:
            new_data[j] = data[j]

    return new_data

def find(source: dict, path: str):

    splited_path = path.split('.')

    d = source.copy()

    for key in splited_path:
        try:
            d = d[key]
        except:
            return None

    return d if d else None

def find_and_set(source: dict, source_path: str, dest: dict, dest_path: str):

    splited_dest_path = dest_path.split('.')

    found = find(source, source_path)

    if found == None:
        return False

    counter = 1
    for key in splited_dest_path:

        if counter == len(splited_dest_path):
            dest[key] = found
        else:
            dest[key] = {}
            dest = dest[key]

        counter += 1

    return True


import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
import sys
from netCDF4 import Dataset
import netCDF4 as nc

#---------------------------------------------------------------
#combine MODIS Monthly mean Dust AOD over ocean (Dr. Yu) and over land (Paul)
#Over Ocean 2000-2017; Over land 2003-2016
#Global product 2013-2016
#---------------------------------------------------------------
def global_mn_aod(iy):
    #read MODIS ocean product from Dr.Yu
    ocean_dir ='/home/cd11735/zzbatmos_common/Data/Global_dust_from_HongbinYu/Hongbin_Ocean_monthly/'
    ocean_fname = ocean_dir+ 'AquaMODISAODComponentsmonthly20002017.nc'
    ocean_dataset = Dataset(ocean_fname)
    ocean_year    = ocean_dataset.variables['year'][:]
    ocean_lat     = ocean_dataset.variables['lat'][:]
    ocean_lon     = ocean_dataset.variables['lon'][:]
    ocean_dod     = ocean_dataset.variables['daod'][:] #((18year, 12mon, 180lat, 360lon))
    ocean_taod    = ocean_dataset.variables['taod'][:] #((18year, 12mon, 180lat, 360lon))
    ocean_year_list = ocean_year.tolist()
    iy_ocean = ocean_year_list.index(year[iy])
    #read MODIS land product from Paul
    land_dir  ='/home/cd11735/zzbatmos_common/Data/Global_dust_from_HongbinYu/Paul_Land/aqua/'
    land_fname  = land_dir +'fod_sod_dod_av_mth_{:4d}_1x1_mth.nc'.format(year[iy])
    land_dataset = Dataset(land_fname)
    land_lat  = land_dataset.variables['lat'][:]
    land_lon  = land_dataset.variables['lon'][:]
    land_dod  = land_dataset.variables['dod_flag3_av_mth'][:]#(12time, 180lat, 360lon)
    land_fod  = land_dataset.variables['fod_flag3_av_mth'][:]#(12time, 180lat, 360lon)
    land_sod  = land_dataset.variables['sod_flag3_av_mth'][:]#(12time, 180lat, 360lon)
    #the following three variables are for total aod (taod) calculation (summation = taod)
    land_dod_for_taod = land_dataset.variables['dod_flag3_av_mth'][:]#(12time, 180lat, 360lon)
    land_fod_for_taod = land_dataset.variables['fod_flag3_av_mth'][:]#(12time, 180lat, 360lon)
    land_sod_for_taod  = land_dataset.variables['sod_flag3_av_mth'][:]#(12time, 180lat, 360lon)

    land_fill_value = land_dataset.variables['dod_flag3_av_mth']._FillValue
    ocean_fill_value = -9.9
    print(land_fill_value,ocean_fill_value)

    #replace filled_value with np.nan
    ocean_dod[ocean_dod<=ocean_fill_value]   = np.nan
    ocean_taod[ocean_taod<=ocean_fill_value] = np.nan
    land_dod[land_dod <= land_fill_value]    = np.nan
    land_dod_for_taod[land_dod_for_taod<=land_fill_value] = 0.0
    land_fod_for_taod[land_fod_for_taod<=land_fill_value] = 0.0
    land_sod_for_taod[land_sod_for_taod<=land_fill_value] = 0.0

    #This part combine MODIS ocean and land together
    global_mon_dod = np.zeros((12,180,360)) #12month,180lat,360lon
    global_mon_taod = np.zeros((12,180,360))
    bm = Basemap()
    for im in np.arange(0,12):
        for ilat in range(180):
            for ilon in range(360):
                if not(bm.is_land(ocean_lon[ilon],ocean_lat[ilat])): # check whether the location is over ocean
                    global_mon_dod[im,ilat,ilon]=ocean_dod[iy_ocean,im,ilat,ilon]
                    global_mon_taod[im,ilat,ilon]=ocean_taod[iy_ocean,im,ilat,ilon]
                else:
                    global_mon_dod[im,ilat,ilon]=land_dod[im,ilat,ilon]
                    global_mon_taod[im,ilat,ilon]=land_dod_for_taod[im,ilat,ilon]+land_fod_for_taod[im,ilat,ilon]+land_sod_for_taod[im,ilat,ilon]
    #convert to 5lonx2lat, in order to be consistent with CALIOP dust product
    global_mon_dod_5x2deg=np.zeros((12,90,72))#12month,90lat,72lon
    global_mon_taod_5x2deg=np.zeros((12,90,72))#12month,90lat,72lon
    lon_ct = np.arange(-179.5,180,1)
    lat_ct = np.arange(89.5,-90,-1)
    lon_ct_new=np.arange(177.5,-180,-5)
    lat_ct_new=np.arange(-89,90,2)
    for im in range(12):
        for ilat in range(90):
            for ilon in range(72):
                lon_mask=((lon_ct>=lon_ct_new[ilon]-2.5))&(lon_ct<(lon_ct_new[ilon]+2.5))
                lat_mask=((lat_ct>=lat_ct_new[ilat]-1))&(lat_ct<(lat_ct_new[ilat]+1))
                global_mon_dod_5x2deg[im,ilat,ilon]=np.nanmean(global_mon_dod[im,:,:][lat_mask,:][:,lon_mask])
                global_mon_taod_5x2deg[im,ilat,ilon]=np.nanmean(global_mon_taod[im,:,:][lat_mask,:][:,lon_mask])
    return(global_mon_dod_5x2deg,global_mon_taod_5x2deg)

if __name__ == '__main__':
    year  = np.array([2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016])
    ny    = len(year)
    nm    = 12
    nlat  = 90
    nlon  = 72
    global_mon_dod_20032016  = np.zeros((ny,nm,nlat,nlon))
    global_mon_taod_20032016 = np.zeros((ny,nm,nlat,nlon))
    for iy in range(ny):
        global_mon_dod_20032016[iy,:,:,:]  = global_mn_aod(iy)[0]
        global_mon_taod_20032016[iy,:,:,:] = global_mn_aod(iy)[1]
    #-----------------
    #write netCDF file
    #-----------------
    #write to netcdf file
    lonS  = np.arange(177.5,-180,-5)
    latS  = np.arange(-89,90,2)
    yearS = year
    monS  = range(12)
    nlon  = len(lonS)
    nlat  = len(latS)
    ny    = len(yearS)
    nm    = len(monS)

    da=nc.Dataset('ModisGlobalMonthlyGlobalAOD20032016.nc','w',format='NETCDF4')
    da.createDimension('lons',nlon) #create x coordinate
    da.createDimension('lats',nlat) #create y coordinate
    da.createDimension('year',ny)
    da.createDimension('month',nm)
    da.createVariable("lon",'f',("lons")) #'f' 数据类型，不可或缺
    da.createVariable("lat",'f',("lats"))
    da.createVariable("year",'f',("year"))
    da.createVariable("month",'f',("month"))
    da.createVariable('daod','f',('year','month','lats','lons'))
    da.createVariable('taod','f',('year','month','lats','lons'))
    da.variables['lat'][:]   = latS     #填充数据
    da.variables['lon'][:]   = lonS     #填充数据
    da.variables['year'][:]  = yearS
    da.variables['month'][:] = monS
    da.variables['daod'][:]  = global_mon_dod_20032016
    da.variables['taod'][:]  = global_mon_taod_20032016
    da.close()


from django.shortcuts import get_object_or_404
from django.http import HttpResponse
from django.template import loader
from .models import *

def index(request):
    template = loader.get_template('posts/index.html')
    post_list = Posts.objects.all()
    user_list = User.objects.all()
    context = {
        'post_list': post_list,
        'user_list': user_list,
    }
    return HttpResponse(template.render(context, request))

def post_view(request):
    post_id = request.GET.get('id')
    post = get_object_or_404(Posts, id=post_id)
    comments = Comments.objects.all()
    template = loader.get_template('posts/post.html')
    context = {
        'object': post,
        'comments': comments,
    }
    return HttpResponse(template.render(context, request))

# Get parameter
def get_parameter(request):
    age = request.GET.get('age', 0)
    name = request.GET.get('name', 'Undefined')
    return HttpResponse(f'
Name: {name} Age: {age}
')


import itertools as it
import random
import numpy as np
import slith
import copy

EMPTY = -1
OUT_OF_BOARD = -2
UP = 1
DOWN = 2
RIGHT = 3
LEFT = 4

ALL_DIRS = [
    [-1, 0],
    [1,  0],
    [0, -1],
    [0,  1]
]

OFFSET_TO_DIR = {
    (-1, 0): UP,
    (1,  0): DOWN,
    (0,  1): RIGHT,
    (0, -1): LEFT
}

class Board:
    def __init__(self, n, m):
        self.nums_height = n + 2
        self.nums_width = m + 2
        self.nums = [[EMPTY] * self.nums_width]
        for i in range(n):
            self.nums += [[EMPTY] + [EMPTY for x in range(m)] +
                          [EMPTY]]
        self.nums += [[EMPTY] * self.nums_width]

        self.dots_height = self.nums_height + 1
        self.dots_width = self.nums_width + 1
        self.dots = [[OUT_OF_BOARD] * self.dots_width]
        for i in range(1, self.dots_height - 1):
            self.dots += [[OUT_OF_BOARD] + [EMPTY] * (self.dots_width - 2) +
                          [OUT_OF_BOARD]]
        self.dots += [[OUT_OF_BOARD] * self.dots_width]

        self.edges_taken = 0
        self.solutions = 0

def global_check(board, edges_taken, final=False):
    for i, j in it.product(range(board.nums_height), range(board.nums_width)):
        amount_taken = 0
        for edge in slith.face_to_edges(i, j):
            if edge in edges_taken:
                amount_taken += 1
    x = board.dots[board.dots_height - 1]
    if amount_taken > 3 or x.count(-1) == len(x):
        return False
    if len(edges_taken) < 2 * board.nums_height + board.nums_width:
        return False

    board.edges_taken = len(edges_taken)
    return True

def is_drawn(board, dot1, dot2):
    i, j = dot1
    x, y = dot2

    if x == i and y == j + 1:   # top / bottom of the cell
        if board.dots[i][j] == 3 or board.dots[x][y] == 4:
            return True
    if x == i + 1 and y == j:   # left / right hand side of the cell
        if board.dots[i][j] == 2 or board.dots[x][y] == 1:
            return True
    return False

def count_edges(board):
    for i, j in it.product(range(1, board.nums_height - 1),
                           range(1, board.nums_width - 1)):
        amount_taken = 0
        edges = slith.face_to_edges(i, j)
        for edge in edges:
            if is_drawn(board, edge[0], edge[1]):
                amount_taken += 1
        board.nums[i][j] = amount_taken

def fast_check(board, edges_taken, face):
    i, j = face
    amount_taken = 0
    for edge in slith.face_to_edges(i, j):
        if edge in edges_taken:
            amount_taken += 1
    if amount_taken > 3:
        return False
    return True

def delete_clues(board, nums, how_many):
    clues = set()

    while len(clues) < how_many:
        x = np.random.randint(1, board.nums_height)
        y = np.random.randint(1, board.nums_width)
        if board.nums[x][y] != 0 and board.nums[x][y] != EMPTY:
            clues.add((x, y))
    for clue in clues:
        nums[clue[0]][clue[1]] = EMPTY
    return nums

def create_puzzle(board, nums):
    with open("slither.txt", 'w') as puzzle:
        puzzle.write(str(board.nums_height - 2) + ' ' +
                     str(board.nums_height - 2) + '\n')
        for row in nums[1:-1]:
            puzzle.write(' '.join(map(str, row[1:-1])) + '\n')

def generate(board, edges_taken=None, i=1, j=1, begin_i=1, begin_j=1):
    if not edges_taken:  # edges are represented by an ORDERED pair of pairs
        edges_taken = set()
    if abs(begin_i - i) + abs(begin_j - j) == 1 and len(edges_taken) > 1:
        last_edge = tuple(sorted([(begin_i, begin_j), (i, j)]))
        board.dots[i][j] = OFFSET_TO_DIR[(begin_i - i, begin_j - j)]
        edges_taken.add(last_edge)
        if global_check(board, edges_taken, final=True):
            return True
        board.dots[i][j] = EMPTY
        edges_taken.remove(last_edge)

    for _ in range(4):
        offset = random.choice(list(OFFSET_TO_DIR.keys()))
        dir_to_next = OFFSET_TO_DIR[offset]
        next_i, next_j = i + offset[0], j + offset[1]
        if board.dots[next_i][next_j] == EMPTY:
            board.dots[i][j] = dir_to_next
            edge_being_added = tuple(sorted([(i, j), (next_i, next_j)]))
            edges_taken.add(edge_being_added)
            face_A, face_B = slith.edge_to_faces(edge_being_added)
            if fast_check(board, edges_taken, face_A) and \
            fast_check(board, edges_taken, face_B):
                ret_val = generate(board, edges_taken, next_i,
                                   next_j, begin_i, begin_j)
                if ret_val:
                    return True
            board.dots[i][j] = EMPTY
            edges_taken.remove(edge_being_added)
    return False

if __name__ == "__main__":
    B = Board(5, 5)

    found = False
    if generate(B, edges_taken=None, i=1, j=1, begin_i=1, begin_j=1):
        found = True
    if found:
        print(str(B.dots_height) + " " + str(B.dots_width))
        for dots_row in B.dots:
            print(' | '.join(map(str, dots_row)))
        print()
    else:
        print("No solution")

    count_edges(B)

    for row in B.nums:
        print(' '.join(map(str, row)))  # good, no mistakes in counting edges
    print()

    original = B.nums
    nums = copy.deepcopy(original)
    print('nums')
    print(nums)

    # now we have generated the solved board
    # and we're going to create a puzzle
    # for that we need to delete some of the excessive numbers in cells

    many = B.edges_taken
    nums = delete_clues(B, nums, 5)
    print('nums')
    print(nums)
    create_puzzle(B, nums)
    for row in nums:
        print(' '.join(map(str, row[1:-1])) + '\n')

    # is it solvable? it should be, but it is worth checking anyway
    C = slith.Board()
    C.read('slither.txt')

    biggest_tile, biggest_tile_val = slith.find_biggest_tile(C)

    # dangerous assumption that there is a tile with val >= 1
    # ... and all the tiles are <= 3

    found_solution = False
    for begining_offsets in ALL_DIRS:
        begin_i = biggest_tile[0] + begining_offsets[0]
        begin_j = biggest_tile[1] + begining_offsets[1]
        if slith.backtrack(C, edges_taken=None, i=begin_i, j=begin_j,
                           begin_i=begin_i, begin_j=begin_j):
            found_solution = True
            break

    if found_solution:
        for dots_row in C.dots:
            print(' | '.join(map(str, dots_row)))
        print()
    else:
        print("No solution")

    # the main prroblem is - is the solution unique
    D = slith.Board()
    D.read('slither.txt')

    biggest_tile, biggest_tile_val = slith.find_biggest_tile(D)
    found_solution = False
    for begining_offsets in ALL_DIRS:
        begin_i = biggest_tile[0] + begining_offsets[0]
        begin_j = biggest_tile[1] + begining_offsets[1]
        slith.backtrack(D, edges_taken=None, i=begin_i, j=begin_j,
                        begin_i=begin_i, begin_j=begin_j, end_if_found=False)
        if D.solutions != 0:
            break
    print(D.solutions)
    if D.solutions > 2:
        print("The solution is not unique")
    else:
        print("unique")

    # there are two edges coming out of a vertex, so there are two
    # possible directions to follow the path

    while D.solutions > 2:
        many = B.edges_taken
        nums = delete_clues(B, nums, 5)
        print('nums')
        print(nums)
        create_puzzle(B, nums)
        for row in nums:
            print(' '.join(map(str, row[1:-1])) + '\n')

        C = slith.Board()
        C.read('slither.txt')

        biggest_tile, biggest_tile_val = slith.find_biggest_tile(C)

        # dangerous assumption that there is a tile with val >= 1
        # ... and all the tiles are <= 3

        found_solution = False
        for begining_offsets in ALL_DIRS:

            begin_i = biggest_tile[0] + begining_offsets[0]
            begin_j = biggest_tile[1] + begining_offsets[1]
            if slith.backtrack(C, edges_taken=None, i=begin_i, j=begin_j,
                               begin_i=begin_i, begin_j=begin_j):
                found_solution = True
                break

        if found_solution:
            # print(str(B.dots_height) + " " + str(B.dots_width))
            for dots_row in C.dots:
                print(' | '.join(map(str, dots_row)))
            print()
        else:
            print("No solution")

        D = slith.Board()
        D.read('slither.txt')

        biggest_tile, biggest_tile_val = slith.find_biggest_tile(D)
        found_solution = False
        for begining_offsets in ALL_DIRS:
            begin_i = biggest_tile[0] + begining_offsets[0]
            begin_j = biggest_tile[1] + begining_offsets[1]
            slith.backtrack(D, edges_taken=None, i=begin_i, j=begin_j,
                            begin_i=begin_i, begin_j=begin_j,
                            end_if_found=False)
            if D.solutions != 0:
                break
        print(D.solutions)

    if D.solutions > 2:
        print("The solution is not unique")
    else:
        print("unique")


def load_file(filepath):

    annotations = {}

    for line in open(filepath):
        record, string, entity = line.strip().split('\t', 2)
        annotations[(record, string)] = entity

    return annotations

def get_performance (gold_file,pred_file):

    gold = {}
    for line in open(gold_file):
        record, string, entity = line.strip().split('\t', 2)
        gold[(string)] = entity

    pred = {}
    for line in open(pred_file):
        record, string, entity = line.strip().split('\t', 2)
        pred[(string)] = entity

    n_gold = len(gold)
    n_predicted = len(pred)
    print('gold: %s' % n_gold)
    print('predicted: %s' % n_predicted)

    # Evaluate predictions
    n_correct = sum( int(pred[i]==gold[i]) for i in set(gold) & set(pred) )
    print('correct: %s' % n_correct)

    # Calculate scores
    precision = float(n_correct) / float(n_predicted)
    print('precision: %s' % precision )
    recall = float(n_correct) / float(n_gold)
    print('recall: %s' % recall )
    f1 = 2 * ( (precision * recall) / (precision + recall) )
    print('f1: %s' % f1 )

# get_performance('data/sample_annotations.tsv', 'data/sample-labels-cheat.txt')
get_performance('data/sample_annotations.tsv', 'results/annotations_sample_entities_lesk')


import sys
from time import sleep

# Check if file was given in arguments
if len(sys.argv) <= 2: sys.exit("Please provide a type of agent and file to read the map from as an argument. Example: python ./maze.py random ./maps/map1.json")
type_of_agent = sys.argv[1]
map_name = sys.argv[2]
# Create export Module
from export import create_export_module
export_module = create_export_module(type_of_agent, map_name)

# Ursina import
from ursina import *
app = Ursina()
# Import util : load_json
from utils import load_map_from_json_file
# Import environment
from environment.setup import setup_window, setup_camera, setup_panel_control, setup_panel_messages
from environment.World import World
from environment.Panels import InfoPanel, MessagePanel
# Import agent
from agent.agent import *

# Load map
map_info = load_map_from_json_file(type_of_agent, './maps/'+map_name+'.json' )

# Setup window, camera and window panel
setup_window(borderless = False)
setup_camera(position = Vec3(-50,50,-50), look_at = map_info["center"])

world = map_info['world']
agents = map_info['agents'].values()

info_panel = InfoPanel()
message_panel = MessagePanel()
min_tick_time, tick_time, max_tick_time, step = 0.02, 0.5, 1.0, 0.005
setup_panel_control(info_panel, min_tick_time, tick_time, max_tick_time, step, map_info['agents'].keys())
setup_panel_messages(message_panel)

max_time = 20000
t = 0
def update():
    global t, tick_time
    t += time.dt
    if t > tick_time:
        t = 0
        export_module.print_and_write_to_txt('')
        export_module.print_and_write_to_txt('------------ ' + str(world.metrics.time) + ' ------------')
        tick_time = info_panel.get_time_tick()
        agents_in_goal = 0
        agents_decisions = []
        for agent in agents:
            agent.set_animation_duration(.8 * tick_time)
            a = agent.decision(world, agents_decisions)
            agents_decisions.append(a)

            if agent.position - Vec3(0, 1, 0) == world.get_agent_goal_position(agent.name):
                agents_in_goal += 1

        if agents_in_goal == len(agents):
            print()
            print()
            print('   ==========================')
            print(' //                          \\\\')
            print(' |  The Agents won the game!  |')
            print(' \\\\                          //')
            print('   ==========================')
            print()
            print()
            print(world.metrics.time)
            exit()

        world.update()
        world.export_metrics_content(info_panel)
        world.export_messages_content(message_panel)

        export_module.save_current_state()

        if world.metrics.time == max_time:
            print()
            print()
            print('   ==========================')
            print(' //                          \\\\')
            print(' |     Solution not found!    |')
            print(' \\\\                          //')
            print('   ==========================')
            print()
            print()
            exit()

app.run()


import aiofiles
import ffmpeg
import asyncio
import os
import shutil
import psutil
import subprocess
import requests
import aiohttp
import yt_dlp
import aiohttp
import random
import shutil
import re
import subprocess
import os
import sys

from git import Repo
from pyrogram.types import Message
from Codexun.utils.filters import command
from pyrogram import Client, filters
from os import system, execle, environ
from git.exc import InvalidGitRepositoryError
from Codexun.utils.decorators import sudo_users_only
from Codexun.config import UPSTREAM_REPO, BOT_USERNAME, SUDO_USERS, BOT_NAME

from os import path
from typing import Union
from asyncio import QueueEmpty
from PIL import Image, ImageFont, ImageDraw, ImageFilter
from PIL import ImageGrab
from typing import Callable

from pytgcalls import StreamType
from pytgcalls.types.input_stream import InputStream
from pytgcalls.types.input_stream import InputAudioStream

from youtube_search import YoutubeSearch

from pyrogram import Client, filters
from pyrogram.types import (
    Message,
    Voice,
    InlineKeyboardButton,
    InlineKeyboardMarkup,
    CallbackQuery,
)
from pyrogram.errors import UserAlreadyParticipant, UserNotParticipant
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, Message
from pyrogram.errors import ChatAdminRequired, UserNotParticipant, ChatWriteForbidden
from Codexun.database.functions import start_restart_stage
from Codexun.utils.decorators import errors
from Codexun.tgcalls import calls, queues
from Codexun.tgcalls.youtube import download
from Codexun.tgcalls import convert as cconvert
from Codexun.tgcalls.calls import client as ASS_ACC
from Codexun.database.queue import (
    get_active_chats,
    is_active_chat,
    add_active_chat,
    remove_active_chat,
    music_on,
    is_music_playing,
    music_off,
)

from Codexun import BOT_NAME, BOT_USERNAME, OWNER
from Codexun import app
import Codexun.tgcalls
from Codexun.tgcalls import youtube
from Codexun.config import (
    DURATION_LIMIT,
    que,
    SUDO_USERS,
    BOT_ID,
    ASSNAME,
    ASSUSERNAME,
    ASSID,
    START_IMG,
    SUPPORT,
    UPDATE,
    BOT_NAME,
    BOT_USERNAME,
)
from Codexun.utils.filters import command
from Codexun.utils.decorators import errors, sudo_users_only
from Codexun.utils.administrator import adminsOnly
from Codexun.utils.errors import DurationLimitError
from Codexun.utils.gets import get_url, get_file_name
from Codexun.modules.admins import member_permissions

def gen_chlog(repo, diff):
    upstream_repo_url = Repo().remotes[0].config_reader.get("url").replace(".git", "")
    ac_br = repo.active_branch.name
    ch_log = tldr_log = ""
    ch = f"updates for [{ac_br}]:"
    ch_tl = f"updates for {ac_br}:"
    d_form = "%d/%m/%y || %H:%M"
    for c in repo.iter_commits(diff):
        ch_log += (
            f"\n\n💬 {c.count()} 🗓 [{c.committed_datetime.strftime(d_form)}]\n"
            f"[{c.summary}] 👨💻 {c.author}"
        )
        tldr_log += f"\n\n💬 {c.count()} 🗓 [{c.committed_datetime.strftime(d_form)}]\n[{c.summary}] 👨💻 {c.author}"
    if ch_log:
        return str(ch + ch_log), str(ch_tl + tldr_log)
    return ch_log, tldr_log

def updater():
    try:
        repo = Repo()
    except InvalidGitRepositoryError:
        repo = Repo.init()
        origin = repo.create_remote("upstream", UPSTREAM_REPO)
        origin.fetch()
        repo.create_head("main", origin.refs.main)
        repo.heads.main.set_tracking_branch(origin.refs.main)
        repo.heads.main.checkout(True)
    ac_br = repo.active_branch.name
    if "upstream" in repo.remotes:
        ups_rem = repo.remote("upstream")
    else:
        ups_rem = repo.create_remote("upstream", UPSTREAM_REPO)
    ups_rem.fetch(ac_br)
    changelog, tl_chnglog = gen_chlog(repo, f"HEAD..upstream/{ac_br}")
    return bool(changelog)

def others_markup(videoid, user_id):
    buttons = [
        [
            InlineKeyboardButton(text="▷", callback_data=f"resumevc"),
            InlineKeyboardButton(text="II", callback_data=f"pausevc"),
            InlineKeyboardButton(text="‣‣I", callback_data=f"skipvc"),
            InlineKeyboardButton(text="▢", callback_data=f"stopvc"),
        ],[
            InlineKeyboardButton(text="Manage", callback_data=f"cls"),
        ],

    ]
    return buttons

fifth_keyboard = InlineKeyboardMarkup(
    [
        [

            InlineKeyboardButton("20%", callback_data="first"),
            InlineKeyboardButton("50%", callback_data="second"),

        ],[

            InlineKeyboardButton("100%", callback_data="third"),
            InlineKeyboardButton("150%", callback_data="fourth"),

        ],[

            InlineKeyboardButton("200% 🔊", callback_data="fifth"),

        ],[
            InlineKeyboardButton(text="⬅ Back", callback_data=f"cbmenu"),
        ],
    ]
)

fourth_keyboard = InlineKeyboardMarkup(
    [
        [

            InlineKeyboardButton("20%", callback_data="first"),
            InlineKeyboardButton("50%", callback_data="second"),

        ],[

            InlineKeyboardButton("100%", callback_data="third"),
            InlineKeyboardButton("150% 🔊", callback_data="fourth"),

        ],[

            InlineKeyboardButton("200%", callback_data="fifth"),

        ],[
            InlineKeyboardButton(text="⬅ Back", callback_data=f"cbmenu"),
        ],
    ]
)

third_keyboard = InlineKeyboardMarkup(
    [
        [

            InlineKeyboardButton("20%", callback_data="first"),
            InlineKeyboardButton("50%", callback_data="second"),

        ],[

            InlineKeyboardButton("100% 🔊", callback_data="third"),
            InlineKeyboardButton("150%", callback_data="fourth"),

        ],[

            InlineKeyboardButton("200%", callback_data="fifth"),

        ],[
            InlineKeyboardButton(text="⬅ Back", callback_data=f"cbmenu"),
        ],
    ]
)
update_keyboard = InlineKeyboardMarkup(
    [
        [

            InlineKeyboardButton("Check Update ➡", callback_data="cheupdate"),

        ],
        [
            InlineKeyboardButton(text="Close 🗑", callback_data=f"cls"),
        ],
    ]
)

already = InlineKeyboardMarkup(
    [

        [
            InlineKeyboardButton(text="Close 🗑", callback_data=f"cls"),
        ],
    ]
)
confirm = InlineKeyboardMarkup(
    [
        [

            InlineKeyboardButton("Update Now ♻", callback_data="confm_update"),

        ],
        [
            InlineKeyboardButton(text="Cancel it 🚫", callback_data=f"cls"),
        ],
        [
            InlineKeyboardButton(text="Close 🗑", callback_data=f"cls"),
        ],
    ]
)
second_keyboard = InlineKeyboardMarkup(
    [
        [

            InlineKeyboardButton("20%", callback_data="first"),
            InlineKeyboardButton("50% 🔊", callback_data="second"),

        ],[

            InlineKeyboardButton("100%", callback_data="third"),
            InlineKeyboardButton("150%", callback_data="fourth"),

        ],[

            InlineKeyboardButton("200%", callback_data="fifth"),

        ],[
            InlineKeyboardButton(text="⬅ Back", callback_data=f"cbmenu"),
        ],
    ]
)

first_keyboard = InlineKeyboardMarkup(
    [
        [

            InlineKeyboardButton("20% 🔊", callback_data="first"),
            InlineKeyboardButton("50%", callback_data="second"),

        ],[

            InlineKeyboardButton("100%", callback_data="third"),
            InlineKeyboardButton("150%", callback_data="fourth"),

        ],[

            InlineKeyboardButton("200%", callback_data="fifth"),

        ],[
            InlineKeyboardButton(text="⬅ Back", callback_data=f"cbmenu"),
        ],
    ]
)
highquality_keyboard = InlineKeyboardMarkup(
    [
        [

            InlineKeyboardButton("Low Quality", callback_data="low"),],
         [   InlineKeyboardButton("Medium Quality", callback_data="medium"),

        ],[   InlineKeyboardButton("High Quality ✅", callback_data="high"),

        ],[
            InlineKeyboardButton(text="⬅ Back", callback_data=f"cbmenu"),
            InlineKeyboardButton(text="Close 🗑", callback_data=f"cls"),
        ],
    ]
)
lowquality_keyboard = InlineKeyboardMarkup(
    [
        [

            InlineKeyboardButton("Low Quality ✅", callback_data="low"),],
         [   InlineKeyboardButton("Medium Quality", callback_data="medium"),

        ],[   InlineKeyboardButton("High Quality", callback_data="high"),

        ],[
            InlineKeyboardButton(text="⬅ Back", callback_data=f"cbmenu"),
            InlineKeyboardButton(text="Close 🗑", callback_data=f"cls"),
        ],
    ]
)
mediumquality_keyboard = InlineKeyboardMarkup(
    [
        [

            InlineKeyboardButton("Low Quality", callback_data="low"),],
         [   InlineKeyboardButton("Medium Quality ✅", callback_data="medium"),

        ],[   InlineKeyboardButton("High Quality", callback_data="high"),

        ],[
            InlineKeyboardButton(text="⬅ Back", callback_data=f"cbmenu"),
            InlineKeyboardButton(text="Close 🗑", callback_data=f"cls"),
        ],
    ]
)

dbclean_keyboard = InlineKeyboardMarkup(
    [
        [

            InlineKeyboardButton("Yes, Proceed !", callback_data="cleandb"),],
        [    InlineKeyboardButton("Nope, Cancel !", callback_data="cbmenu"),

        ],[
            InlineKeyboardButton(text="⬅ Back", callback_data=f"cbmenu"),
        ],
    ]
)
menu_keyboard = InlineKeyboardMarkup(
    [
        [

            InlineKeyboardButton("▷", callback_data="resumevc"),
            InlineKeyboardButton("II", callback_data="pausevc"),
            InlineKeyboardButton("‣‣I", callback_data="skipvc"),
            InlineKeyboardButton("▢", callback_data="stopvc"),

        ],[
            InlineKeyboardButton(text="Volume", callback_data=f"fifth"),
             InlineKeyboardButton(text="Quality", callback_data=f"high"),
        ],[
            InlineKeyboardButton(text="CleanDB", callback_data=f"dbconfirm"),
             InlineKeyboardButton(text="About", callback_data=f"nonabout"),
        ],[
             InlineKeyboardButton(text="🗑 Close Menu", callback_data=f"cls"),
        ],
    ]
)

@Client.on_message(command(["update"]) & filters.group & ~filters.edited)
async def update(client: Client, message: Message):
    await message.reply_photo(
        photo=f"{START_IMG}",
        caption=f"""**Hey {message.from_user.mention()}** 👋
Kindly first check for available updates below.""",
    reply_markup=update_keyboard
    )
@Client.on_callback_query(filters.regex("cheupdate"))
async def cheupdate(_, CallbackQuery):
    chat_id = CallbackQuery.message.chat.id
    msg = await CallbackQuery.answer("checking for updates..")
    update_avail = updater()
    if update_avail:
        await CallbackQuery.edit_message_text("Update available 🚀\n\nClick on the button given below if you want to update your bot with latest one!", reply_markup=confirm)
        system("git pull -f && pip3 install -r requirements.txt")
        execle(sys.executable, sys.executable, "main.py", environ)
        return
    await CallbackQuery.edit_message_text("Bot is already in up-to-date with **[main version](https://github.com/PavanMagar/CodexunMusicBot)**", disable_web_page_preview=True, reply_markup=already)

@Client.on_callback_query(filters.regex("confm_update"))
@errors
async def confm_update(_, CallbackQuery):
    m = subprocess.check_output(["git", "pull"]).decode("UTF-8")
    if str(m[0]) != "A":
        x = await CallbackQuery.answer("Update Found, updating...")
        await start_restart_stage(x.chat.id, x.message_id)
        os.execvp("python3", ["python3", "-m", "Codexun"])
    else:
        await CallbackQuery.answer("it's already up-to-date")

async def aexec(code, client, message):
    exec(
        "async def __aexec(client, message): "
        + "".join(f"\n {a}" for a in code.split("\n"))
    )
    return await locals()["__aexec"](client, message)

async def edit_or_reply(msg: Message, **kwargs):
    func = msg.edit_text if msg.from_user.is_self else msg.reply
    spec = getfullargspec(func.__wrapped__).args
    await func(**{k: v for k, v in kwargs.items() if k in spec})

@Client.on_callback_query(filters.regex("skipvc"))
async def skipvc(_, CallbackQuery):
    a = await app.get_chat_member(
        CallbackQuery.message.chat.id, CallbackQuery.from_user.id
    )
    if not a.can_manage_voice_chats:
        return await CallbackQuery.answer(
            """
Only admin with manage voice chat permission can do this.
""",
            show_alert=True,
        )
    CallbackQuery.from_user.first_name
    chat_id = CallbackQuery.message.chat.id
    chat_title = CallbackQuery.message.chat.title
    if await is_active_chat(chat_id):
            user_id = CallbackQuery.from_user.id
            await remove_active_chat(chat_id)
            user_name = CallbackQuery.from_user.first_name
            rpk = "[" + user_name + "](tg://user?id=" + str(user_id) + ")"
            await CallbackQuery.answer()
            await CallbackQuery.message.reply(
                f"""
**Skip Button Used By** {rpk}
• No more songs in Queue
`Leaving Voice Chat..`
"""
            )
            await calls.pytgcalls.leave_group_call(chat_id)
            return
            await CallbackQuery.answer("Voice Chat Skip.!", show_alert=True)

@Client.on_callback_query(filters.regex("pausevc"))
async def pausevc(_, CallbackQuery):
    a = await app.get_chat_member(
        CallbackQuery.message.chat.id, CallbackQuery.from_user.id
    )
    if not a.can_manage_voice_chats:
        return await CallbackQuery.answer(
            "Only admin with manage voice chat permission can do this.",
            show_alert=True,
        )
    CallbackQuery.from_user.first_name
    chat_id = CallbackQuery.message.chat.id
    if await is_active_chat(chat_id):
        if await is_music_playing(chat_id):
            await music_off(chat_id)
            await calls.pytgcalls.pause_stream(chat_id)
            await CallbackQuery.answer("Music Paused Successfully.", show_alert=True)

        else:
            await CallbackQuery.answer(f"Nothing is playing on voice chat!", show_alert=True)
            return
    else:
        await CallbackQuery.answer(f"Nothing is playing in on voice chat!", show_alert=True)

@Client.on_callback_query(filters.regex("resumevc"))
async def resumevc(_, CallbackQuery):
    a = await app.get_chat_member(
        CallbackQuery.message.chat.id, CallbackQuery.from_user.id
    )
    if not a.can_manage_voice_chats:
        return await CallbackQuery.answer(
            """
Only admin with manage voice chat permission can do this.
""",
            show_alert=True,
        )
    CallbackQuery.from_user.first_name
    chat_id = CallbackQuery.message.chat.id
    if await is_active_chat(chat_id):
        if await is_music_playing(chat_id):
            await CallbackQuery.answer(
                "Nothing is paused in the voice chat.",
                show_alert=True,
            )
            return
        else:
            await music_on(chat_id)
            await calls.pytgcalls.resume_stream(chat_id)
            await CallbackQuery.answer("Music resumed successfully.", show_alert=True)

    else:
        await CallbackQuery.answer(f"Nothing is playing.", show_alert=True)

@Client.on_callback_query(filters.regex("stopvc"))
async def stopvc(_, CallbackQuery):
    a = await app.get_chat_member(
        CallbackQuery.message.chat.id, CallbackQuery.from_user.id
    )
    if not a.can_manage_voice_chats:
        return await CallbackQuery.answer(
            "Only admin with manage voice chat permission can do this.",
            show_alert=True,
        )
    CallbackQuery.from_user.first_name
    chat_id = CallbackQuery.message.chat.id
    if await is_active_chat(chat_id):

        try:
            await calls.pytgcalls.leave_group_call(chat_id)
        except Exception:
            pass
        await remove_active_chat(chat_id)
        await CallbackQuery.answer("Music stream ended.", show_alert=True)
        user_id = CallbackQuery.from_user.id
        user_name = CallbackQuery.from_user.first_name
        rpk = "[" + user_name + "](tg://user?id=" + str(user_id) + ")"
        await CallbackQuery.message.reply(f"**• Music successfully stopped by {rpk}.**")
    else:
        await CallbackQuery.answer(f"Nothing is playing on voice chat.", show_alert=True)

@Client.on_callback_query(filters.regex("cleandb"))
async def cleandb(_, CallbackQuery):
    a = await app.get_chat_member(
        CallbackQuery.message.chat.id, CallbackQuery.from_user.id
    )
    if not a.can_manage_voice_chats:
        return await CallbackQuery.answer(
            "Only admin with manage voice chat permission can do this.",
            show_alert=True,
        )
    CallbackQuery.from_user.first_name
    chat_id = CallbackQuery.message.chat.id
    if await is_active_chat(chat_id):

        try:
            await calls.pytgcalls.leave_group_call(chat_id)
        except Exception:
            pass
        await remove_active_chat(chat_id)
        await CallbackQuery.answer("Db cleaned successfully!", show_alert=True)
        user_id = CallbackQuery.from_user.id
        user_name = CallbackQuery.from_user.first_name
        rpk = "[" + user_name + "](tg://user?id=" + str(user_id) + ")"
        await CallbackQuery.edit_message_text(
        f"✅ __Erased queues successfully__\n│\n╰ Database cleaned by {rpk}",
        reply_markup=InlineKeyboardMarkup(
            [
            [InlineKeyboardButton("Close 🗑", callback_data="cls")]])

    )
    else:
        await CallbackQuery.answer(f"Nothing is playing on voice chat.", show_alert=True)

@Client.on_callback_query(filters.regex("cbcmnds"))
async def cbcmnds(_, query: CallbackQuery):
    await query.edit_message_text(
        f"""**{BOT_NAME} Bot Commands 💡**

• /play (song name)
- For playing music

• /pause
- For pausing music

• /resume
- For resuming music

• /skip
- For skipping current song

• /search (song name)
- For searching music

• /song
- For download music

Powered by **@{UPDATE}** !""",
        reply_markup=InlineKeyboardMarkup(
            [
              [
                    InlineKeyboardButton(
                        "Menu", callback_data="cbstgs"),
                    InlineKeyboardButton(
                        "Sudo/Owner", callback_data="cbowncmnds")
                ],
              [InlineKeyboardButton("🔙  Back Home", callback_data="cbhome")]]
        ),
    )
@Client.on_callback_query(filters.regex("cbowncmnds"))
async def cbowncmnds(_, query: CallbackQuery):
    await query.edit_message_text(
        f"""**Owner & Sudo Commands 💡**

• /broadcast (massage)
- Broadcast msg through bot

• /gcast (massage)
- Broadcast msg with pin

• /restart
- Restart bot from server

• /exec
- Execute any code

• /stats
- Get all statistics

• /ping
- Pinging uptime

• /update
- Update bot with latest version

• /gban or /ungban
- Global Ban system

• /leaveall
- leaving assistant from all chats

Powered by **@{UPDATE}** !""",
        reply_markup=InlineKeyboardMarkup(
            [

              [InlineKeyboardButton("🔙  Back Home", callback_data="cbcmnds")]]
        ),
    )

@Client.on_callback_query(filters.regex("cbabout"))
async def cbabout(_, query: CallbackQuery):
    await query.edit_message_text(
        f"""**About {BOT_NAME} Bot 💡**

**[{BOT_NAME}](https://t.me/{BOT_USERNAME})** Music Bot is the bot designed by **@{UPDATE}** for playing a high quality and unbreakable music in your groups voice chat.

This bot helps you to play music, to search music from youtube and to download music from youtube server and many more features related to telegram voice chat feature.

**Assistant :- @{ASSUSERNAME}**""",
        reply_markup=InlineKeyboardMarkup(
            [
              [
                    InlineKeyboardButton("Support 🚶", url=f"https://t.me/{SUPPORT}"),
                    InlineKeyboardButton("Updates 🤖", url=f"https://t.me/{UPDATE}")
                ],
            [InlineKeyboardButton("Make Your Own Bot", callback_data="cbtuto")],
            [InlineKeyboardButton("🔙  Back Home", callback_data="cbhome")]]
        ),
    )

@Client.on_callback_query(filters.regex("cbstgs"))
async def cbstgs(_, query: CallbackQuery):
    await query.edit_message_text(
        f"""**About Menu Buttons 💡**

After you played your song some menu buttons will be comes to manage your music playing on voice chat. They are as follows :

• ▷
- Resume Music
• II
- Pause Music
• ▢
- End Music
• ‣‣
- Skip Music

You can also open this menu through /menu and /settings command.

**Only admins can use this buttons 📍**""",
        reply_markup=InlineKeyboardMarkup(
            [
            [InlineKeyboardButton("🔙  Back Home", callback_data="cbcmnds")]]
        ),
    )

@Client.on_callback_query(filters.regex("cbguide"))
async def cbguide(_, query: CallbackQuery):
    await query.edit_message_text(
        f"""**Read Basic Guide Carefully 💡**

• First add this bot in your group

• Make a bot admin

• Give needed admin permission

• Type /reload in your group

• Start your groups voice chat

• Now play your song and enjoy !""",
        reply_markup=InlineKeyboardMarkup(
            [[
              InlineKeyboardButton("Common Error", callback_data="cberror")],
              [InlineKeyboardButton("🔙  Back Home", callback_data="cbhome")]]
        ),
    )

@Client.on_callback_query(filters.regex("cberror"))
async def cberror(_, query: CallbackQuery):
    await query.edit_message_text(
        f"""**Mostly Faced Errors 💡**

mostly, there wiil be the main error about to music assistant. If you are facing any type of error in your group then that time first make sure @{ASSUSERNAME} is available in your group. If not then add it manually and before that make sure also it is not banned in ur chat.\n\n**Assistant :- @{ASSUSERNAME}**\n\n**Thanks !**""",
        reply_markup=InlineKeyboardMarkup(
            [
            [
                    InlineKeyboardButton("Assistant 🙋🏻♂", url=f"https://t.me/{ASSUSERNAME}")
                ],
              [InlineKeyboardButton("🔙  Back Home", callback_data="cbguide")]]
        ),
    )

@Client.on_callback_query(filters.regex("cbtuto"))
async def cbtuto(_, query: CallbackQuery):
    await query.edit_message_text(
        f"""**Make Your Own Bot Like this💡**

Good news! Now you can allow to make your own music bot like to this one. You will be get repo link below just click on it and follow steps!

If you didn't know how to make your own bot then contact us at @TeamCodexun and get help from us.

**🔗 Repo Link : https://github.com/PavanMagar/CodexunMusicBot**

**Thanks !""",
       reply_markup=InlineKeyboardMarkup(
            [[
                    InlineKeyboardButton("Get Repo 📦", url=f"https://github.com/PavanMagar/CodexunMusicBot")
                ],
              [InlineKeyboardButton("🔙  Back Home", callback_data="cbabout")]]
        ),
    )

@Client.on_callback_query(filters.regex("cbhome"))
async def cbhome(_, query: CallbackQuery):
    await query.edit_message_text(
        f"""**Welcome [{query.message.chat.first_name}](tg://user?id={query.message.chat.id})** 👋

This is the **[{BOT_NAME}](https://t.me/{BOT_USERNAME}) bot,** a bot for playing high quality and unbreakable music in your groups voice chat.

Just add me to your group & make as a admin with needed admin permissions to perform a right actions, now let's enjoy your music!

Use the given buttons for more 📍""",
        reply_markup=InlineKeyboardMarkup(
            [
                [
                    InlineKeyboardButton(
                        "Commands", callback_data="cbcmnds"),
                    InlineKeyboardButton(
                        "About", callback_data="cbabout")
                ],
                [
                    InlineKeyboardButton(
                        "Basic Guide", callback_data="cbguide")
                ],
                [
                    InlineKeyboardButton(
                        "✚ Add Bot in Your Group ✚", url=f"https://t.me/{BOT_USERNAME}?startgroup=true")
                ]

           ]
        ),
    )

@Client.on_callback_query(filters.regex(pattern=r"^(cls)$"))
async def closed(_, query: CallbackQuery):
    from_user = query.from_user
    permissions = await member_permissions(query.message.chat.id, from_user.id)
    permission = "can_restrict_members"
    if permission not in permissions:
        return await query.answer(
            "You don't have enough permissions to perform this action.",
            show_alert=True,
        )
    await query.message.delete()

@Client.on_callback_query(filters.regex("cbmenu"))
async def cbmenu(_, query: CallbackQuery):
    if query.message.sender_chat:
        return await query.answer("you're an Anonymous Admin !\n\n» revert back to user account from admin rights.")
    a = await _.get_chat_member(query.message.chat.id, query.from_user.id)
    if not a.can_manage_voice_chats:
        return await query.answer("Only admins cam use this..!", show_alert=True)
    chat_id = query.message.chat.id
    if is_music_playing(chat_id):
          await query.edit_message_text(
              f"**⚙ {BOT_NAME} Bot Settings**\n\n📮 Group : {query.message.chat.title}.\n📖 Grp ID : {query.message.chat.id}\n\n**Manage Your Groups Music System By Pressing Buttons Given Below 💡**",

              reply_markup=menu_keyboard
         )
    else:
        await query.answer("nothing is currently streaming", show_alert=True)

@Client.on_callback_query(filters.regex("high"))
async def high(_, CallbackQuery):
    a = await app.get_chat_member(
        CallbackQuery.message.chat.id, CallbackQuery.from_user.id
    )
    if not a.can_manage_voice_chats:
        return await CallbackQuery.answer(
            "Only admin with manage voice chat permission can do this.",
            show_alert=True,
        )
    CallbackQuery.from_user.first_name
    chat_id = CallbackQuery.message.chat.id
    if await is_active_chat(chat_id):

        await CallbackQuery.answer("Now streaming in high quality!", show_alert=True)
        await CallbackQuery.edit_message_text(
        f"**Manage Audio Quality 🔊**\n\nChoose your option from given below to manage audio quality.",
        reply_markup=highquality_keyboard
    )
    else:
        await CallbackQuery.answer(f"Nothing is playing on voice chat.", show_alert=True)

@Client.on_callback_query(filters.regex("low"))
async def low(_, CallbackQuery):
    a = await app.get_chat_member(
        CallbackQuery.message.chat.id, CallbackQuery.from_user.id
    )
    if not a.can_manage_voice_chats:
        return await CallbackQuery.answer(
            "Only admin with manage voice chat permission can do this.",
            show_alert=True,
        )
    CallbackQuery.from_user.first_name
    chat_id = CallbackQuery.message.chat.id
    if await is_active_chat(chat_id):

        await CallbackQuery.answer("Now streaming in low quality!", show_alert=True)
        await CallbackQuery.edit_message_text(
        f"**Manage Audio Quality 🔊**\n\nChoose your option from given below to manage audio quality.",
        reply_markup=lowquality_keyboard
    )
    else:
        await CallbackQuery.answer(f"Nothing is playing on voice chat.", show_alert=True)

@Client.on_callback_query(filters.regex("medium"))
async def medium(_, CallbackQuery):
    a = await app.get_chat_member(
        CallbackQuery.message.chat.id, CallbackQuery.from_user.id
    )
    if not a.can_manage_voice_chats:
        return await CallbackQuery.answer(
            "Only admin with manage voice chat permission can do this.",
            show_alert=True,
        )
    CallbackQuery.from_user.first_name
    chat_id = CallbackQuery.message.chat.id
    if await is_active_chat(chat_id):

        await CallbackQuery.answer("Now streaming in medium quality!", show_alert=True)
        await CallbackQuery.edit_message_text(
        f"**Manage Audio Quality 🔊**\n\nChoose your option from given below to manage audio quality.",
        reply_markup=mediumquality_keyboard
    )
    else:
        await CallbackQuery.answer(f"Nothing is playing on voice chat.", show_alert=True)

@Client.on_callback_query(filters.regex("fifth"))
async def fifth(_, CallbackQuery):
    a = await app.get_chat_member(
        CallbackQuery.message.chat.id, CallbackQuery.from_user.id
    )
    if not a.can_manage_voice_chats:
        return await CallbackQuery.answer(
            "Only admin with manage voice chat permission can do this.",
            show_alert=True,
        )
    CallbackQuery.from_user.first_name
    chat_id = CallbackQuery.message.chat.id
    if await is_active_chat(chat_id):

        await CallbackQuery.answer("Now streaming in 200% volume!", show_alert=True)
        await CallbackQuery.edit_message_text(
        f"**Manage Audio Volume 🔊**\n\nIf you want to manage volume through buttons then make a assistant Admin first.",
        reply_markup=fifth_keyboard
    )
    else:
        await CallbackQuery.answer(f"Nothing is playing on voice chat.", show_alert=True)

@Client.on_callback_query(filters.regex("fourth"))
async def fourth(_, CallbackQuery):
    a = await app.get_chat_member(
        CallbackQuery.message.chat.id, CallbackQuery.from_user.id
    )
    if not a.can_manage_voice_chats:
        return await CallbackQuery.answer(
            "Only admin with manage voice chat permission can do this.",
            show_alert=True,
        )
    CallbackQuery.from_user.first_name
    chat_id = CallbackQuery.message.chat.id
    if await is_active_chat(chat_id):

        await CallbackQuery.answer("Now streaming 150 volume!", show_alert=True)
        await CallbackQuery.edit_message_text(
        f"**Manage Audio Volume 🔊**\n\nIf you want to manage volume through buttons then make a assistant Admin first.",
        reply_markup=fourth_keyboard
    )
    else:
        await CallbackQuery.answer(f"Nothing is playing on voice chat.", show_alert=True)

@Client.on_callback_query(filters.regex("third"))
async def third(_, CallbackQuery):
    a = await app.get_chat_member(
        CallbackQuery.message.chat.id, CallbackQuery.from_user.id
    )
    if not a.can_manage_voice_chats:
        return await CallbackQuery.answer(
            "Only admin with manage voice chat permission can do this.",
            show_alert=True,
        )
    CallbackQuery.from_user.first_name
    chat_id = CallbackQuery.message.chat.id
    if await is_active_chat(chat_id):

        await CallbackQuery.answer("Now streaming in 100% volume!", show_alert=True)
        await CallbackQuery.edit_message_text(
        f"**Manage Audio Volume 🔊**\n\nIf you want to manage volume through buttons then make a assistant Admin first.",
        reply_markup=third_keyboard
    )
    else:
        await CallbackQuery.answer(f"Nothing is playing on voice chat.", show_alert=True)

@Client.on_callback_query(filters.regex("second"))
async def second(_, CallbackQuery):
    a = await app.get_chat_member(
        CallbackQuery.message.chat.id, CallbackQuery.from_user.id
    )
    if not a.can_manage_voice_chats:
        return await CallbackQuery.answer(
            "Only admin with manage voice chat permission can do this.",
            show_alert=True,
        )
    CallbackQuery.from_user.first_name
    chat_id = CallbackQuery.message.chat.id
    if await is_active_chat(chat_id):

        await CallbackQuery.answer("Now streaming in 50% volume!", show_alert=True)
        await CallbackQuery.edit_message_text(
        f"**Manage Audio Volume 🔊**\n\nIf you want to manage volume through buttons then make a assistant Admin first.",
        reply_markup=second_keyboard
    )
    else:
        await CallbackQuery.answer(f"Nothing is playing on voice chat.", show_alert=True)

@Client.on_callback_query(filters.regex("first"))
async def first(_, CallbackQuery):
    a = await app.get_chat_member(
        CallbackQuery.message.chat.id, CallbackQuery.from_user.id
    )
    if not a.can_manage_voice_chats:
        return await CallbackQuery.answer(
            "Only admin with manage voice chat permission can do this.",
            show_alert=True,
        )
    CallbackQuery.from_user.first_name
    chat_id = CallbackQuery.message.chat.id
    if await is_active_chat(chat_id):

        await CallbackQuery.answer("Now streaming in 20% volume!", show_alert=True)
        await CallbackQuery.edit_message_text(
        f"**Manage Audio Volume 🔊**\n\nIf you want to manage volume through buttons then make a assistant Admin first.",
        reply_markup=first_keyboard
    )
    else:
        await CallbackQuery.answer(f"Nothing is playing on voice chat.", show_alert=True)

@Client.on_callback_query(filters.regex("nonabout"))
async def nonabout(_, query: CallbackQuery):
    await query.edit_message_text(
        f"""**Here is the some basic information about to {BOT_NAME},From here you can simply contact us and can join us!**""",
        reply_markup=InlineKeyboardMarkup(
            [
              [
                    InlineKeyboardButton("Support 🚶", url=f"https://t.me/{SUPPORT}"),
                    InlineKeyboardButton("Updates 🤖", url=f"https://t.me/{UPDATE}")
                ],
              [InlineKeyboardButton("🔙  Back Menu", callback_data="cbmenu")]]
        ),
    )

@Client.on_callback_query(filters.regex("dbconfirm"))
async def dbconfirm(_, query: CallbackQuery):
    if query.message.sender_chat:
        return await query.answer("you're an Anonymous Admin !\n\n» revert back to user account from admin rights.")
    a = await _.get_chat_member(query.message.chat.id, query.from_user.id)
    if not a.can_manage_voice_chats:
        return await query.answer("Only admins cam use this..!", show_alert=True)
    chat_id = query.message.chat.id
    if is_music_playing(chat_id):
          await query.edit_message_text(
              f"**Confirmation ⚠**\n\nAre you sure want to end stream in {query.message.chat.title} and clean all Queued songs in db ?**",

              reply_markup=dbclean_keyboard
         )
    else:
        await query.answer("nothing is currently streaming", show_alert=True)


# sample data from the backend

# Please, test your code in assignments.ipynb
investments= [{'investment': 'Tesla', 'revenue': 24000, 'cost': 8000},
                        {'investment': 'Google', 'revenue': 20000, 'cost': 6400},
                        {'investment': 'Microsoft', 'revenue': 19600, 'cost': 5800},
                        {'investment': 'Applee', 'revenue': 21300, 'cost': 8120},
                        {'investment': 'IBM', 'revenue': 17400, 'cost': 9180}]

available = 20000

# best_investment_choice helps determine the best investment given a set of competing investments?
def best_investment_choice(investments = [], available=0):
    """
        Given a list of investments and the total available funding, returns the single investment that yields the most profit(revenue - cost)
    """
    best_investment = None
    best_worth = 0

    #Loop through investments

        # for each investment, check if its revenue - cost is greater than current best_worth,
        # if its cost is less than or equal to available, and if it is not already in best_investments:

            # if this is the case
             # -> set best_investment = this investment

            # -> set best_worth to its revenue - cost

    # Outside the for loop, return the best_investment
    return best_investment

# Given investments and available, complete the function optimize_investments such that it returns a list of best investment to maximize profit from a set of investments
def optimize_investments(investments=[], available=0):
    """
        uses a greedy approach to determine the best investments to make based on a list of available investments and available capital.
        Returns a dictionary containing the best investments(bests_investment) and the remaining_balance(available_balance)
    """

    best_investments = []

    # call best_investment to determine current best investment.
    best_investment =  best_investment_choice(investments, available)

    while best_investment is not None:
        # Given that best_investment returns a value

        # Get index of the best_investment

        #add best_investment to best_investments

        # Reduce available by cost of this particular investment

        best_investment =  best_investment_choice(investments, available)

    return {"best_investments": best_investments, "available_balance": available}

## Expected result from sample data
{'best_investments': [{'investment': 'Tesla', 'revenue': 24000, 'cost': 8000},
  {'investment': 'Microsoft', 'revenue': 19600, 'cost': 5800}],
 'available_balance': 6200}