#!/usr/bin/env python
# a script for live monitoring CPU usage, network conn, volume, VPN conn, installed packages.
# required: psutil, netifaces, sockets, subprocess

import socket
import netifaces
from os import popen
import subprocess
import psutil  # For Cpu and ram usage, and storage
import distro  # Check distro name to Know How to count the installed packages
import time

# TODO: Pesentage option and number option for swap and memory
# WARNING: The ram function is giving unaccurate numbers !

# Network
def ping():  # checks if there is a connection
    try:
        socket.setdefaulttimeout(1)
        socket_obj = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        host = "1.1.1.1"
        port = 80
        server_addr = (host, port)
        socket_obj.connect(server_addr)
    except OSError as Err:
        return False
    else:
        socket_obj.close()
        return True

# Set network devices
Ethernet_device = "enp2s0"
Wifi_device = "wlp3s0"

def interface(eth=Ethernet_device, wifi=Wifi_device):  # returns the type of connection
    gateways = netifaces.gateways()
    if gateways["default"][2][1] == eth:
        return "Ethernet"
    elif gateways["default"][2][1] == wifi:
        return "Wifi"
    else:
        return None

def connection():  # combines the previous two functions
    if ping() is True:
        if interface() == "Ethernet":
            return "Ethernet: CONNECTED"
        elif interface() == "Wifi":
            return "Wi-fi: CONNECTED"
    elif ping() is False or interface() is None:
        return "NO CONNECTION !"

# VPN
def vpn_connection():
    r = popen("ip a | grep tun0 | grep inet | wc -l").readline()
    if r == 1:
        return "on"
    else:
        return "off"

# CPU
def cpu():
    return psutil.cpu_percent(interval=0.5)

# Ram and swap
def ram():
    return psutil.virtual_memory()[2]

def swap():
    return psutil.swap_memory()[3]

# Battery
def battery():
    if psutil.sensors_battery() is not None:
        return int(psutil.sensors_battery()[0])
    else:
        return "This Device Don't have a Battery"

# VOLUME
def check_vol():
    cmd = "amixer get Master | awk -F'[][]' 'END{ print $2}'"
    process = subprocess.run(cmd, stdout=subprocess.PIPE, shell=True)
    return process.stdout.strip().decode("ascii")

# count installed packages
# Check distro name :
def count_pkg():  # rpm -qa for fedora  # dpkg -l for Debian # pacman -Q
    if distro.id() in ['fedora', 'rhel', 'centos', 'opensuse']:
        default_cmd = "rpm -qa"
    elif distro.id() in ['ubuntu', 'debian']:
        default_cmd = "dpkg -l"
    elif distro.id() in ['arch']:
        default_cmd = "pacman -Q"
    else:
        return "Unknown"
    return str(len(popen(default_cmd).readlines()))

def main():
    # can be used in a while loop to live monitor data.
    print(
        " CPU: {}%".format(cpu()),
        "|",
        " RAM: {}%".format(ram()),
        "|",
        "易SWAP: {}%".format(swap()),
        "|",
        " Packages: {}".format(count_pkg()),
        "|",
        "嬨VPN: {}".format(vpn_connection()),
        "|",
        "墳VOL: {}".format(check_vol()),
        "|",
        "  " + connection(),
        "|",
        " BAT: {}%".format(battery()),
        # flush=True,
        # end="",
    )
    time.sleep(0.3)

if __name__ == "__main__":
    main()


import json
import os
import shutil
import sys
import time
import pytz
import importlib
import requests as req

from dotenv import load_dotenv
from random import randint
from bs4 import BeautifulSoup as bs
from datetime import datetime

if getattr(sys, 'frozen', False):
    if '_PYIBoot_SPLASH' in os.environ and importlib.util.find_spec("pyi_splash"):
        import pyi_splash

def local_work(type_id):

    if type_id == 'datadir':

        extDataDir = os.getcwd()

        if getattr(sys, 'frozen', False):
            extDataDir = f"{sys._MEIPASS}"

        return extDataDir

    elif type_id == 'appdata_path':

        appdata_path = f"{os.getenv('APPDATA')}/VibesBot/web/src"

        return appdata_path

    elif type_id == 'tempdir':

        appdata_path = os.getenv('APPDATA')

        return appdata_path

load_dotenv(dotenv_path=os.path.join(local_work('datadir'), '.env'))

def error_log(ex):

    now = datetime.now()
    time_error = now.strftime("%d/%m/%Y %H:%M:%S")

    trace = []
    error_type = "Unknown"
    error_message = ""

    if isinstance(ex, BaseException):  # Verifica se ex é uma exceção
        tb = ex.__traceback__

        while tb is not None:
            trace.append({
                "filename": tb.tb_frame.f_code.co_filename,
                "name": tb.tb_frame.f_code.co_name,
                "lineno": tb.tb_lineno
            })
            tb = tb.tb_next

        error_type = type(ex).__name__
        error_message = str(ex)
    else:
        error_message = ex

    error = str(f'Erro = type: {error_type} | message: {error_message} | trace: {trace} | time: {time_error} \n\n')

    with open(f"{local_work('appdata_path')}/error_log.txt", "a+", encoding='utf-8') as log_file_r:
        log_file_r.write(error)

class DictDot:
    def __init__(self, data):
        self.data = data

    def __getattr__(self, key):
        if key in self.data:
            return self.data[key]

def manipulate_json(custom_path, type_id, data=None):

    try:

        if type_id == 'load':

            with open(custom_path, 'r',encoding='utf-8') as file:
                loaded_data = json.load(file)
            return loaded_data
        elif type_id == 'save':

            with open(custom_path, 'w',encoding='utf-8') as file:
                json.dump(data, file, indent=4, ensure_ascii=False)

    except FileNotFoundError:
        print(f'The file {custom_path} was not found.')

    except Exception as e:
        error_log(custom_path)
        error_log(e)

def send_message(data):

    try:

        status_commands_data = manipulate_json(f"{local_work('appdata_path')}/config/commands_config.json", "load")

        type_message = data['type']
        message = data['message']

        status_error_time = status_commands_data['STATUS_ERROR_TIME']
        status_error_user = status_commands_data['STATUS_ERROR_USER']
        status_tts = status_commands_data['STATUS_TTS']
        status_music = status_commands_data['STATUS_MUSIC']
        status_music_error = status_commands_data['STATUS_MUSIC_ERROR']
        status_music_confirm = status_commands_data['STATUS_MUSIC_CONFIRM']

        if type_message == 'CHAT':
            return True

        elif type_message == 'ERROR_TIME':

            if status_error_time == 1:
                return True

        elif type_message == 'ERROR_USER':

            if status_error_user == 1:
                return True

        elif type_message == 'STATUS_TTS':

            if status_tts == 1:
                return True

        elif type_message == 'STATUS_MUSIC':

            if status_music == 1:
                return True

        elif type_message == 'STATUS_MUSIC_CONFIRM':

            if status_music_confirm == 1:
                return True

        elif type_message == 'STATUS_MUSIC_ERROR':

            if status_music_error == 1:
                return True

    except Exception as e:
        error_log(e)

def splash_close():
    pyi_splash.close()

def find_between(s, first, last):

    try:
        start = s.index(first) + len(first)
        end = s.index(last, start)
        return s[start:end]

    except ValueError:

        return False

def calculate_time(started):

    try:

        utc_now = datetime.utcnow().replace(tzinfo=pytz.utc)
        utc_date = datetime.fromisoformat(started).replace(tzinfo=pytz.utc)

        gmt_minus_3_now = utc_now.astimezone(pytz.timezone("Etc/GMT+3"))
        gmt_minus_3_date = utc_date.astimezone(pytz.timezone("Etc/GMT+3"))

        difference = gmt_minus_3_now - gmt_minus_3_date

        days = difference.days
        hours = difference.seconds//3600
        minutes = (difference.seconds//60) % 60
        sec = difference.seconds % 60

        time_in_live = {
            'days': str(days),
            'hours': str(hours),
            'minutes': str(minutes),
            'sec': str(sec)
        }

        return time_in_live

    except Exception as e:

        error_log(e)

        return 'none'

def check_delay(delay_command, last_use):

    with open(f"{local_work('appdata_path')}/messages/messages_file.json", "r", encoding='utf-8') as messages_file:
        messages_data = json.load(messages_file)

    message_error = messages_data['response_delay_error']

    last_command_time = last_use
    delay_compare = int(delay_command)

    current_time = int(time.time())

    if current_time >= last_command_time + delay_compare:

        message = 'OK'
        value = True

        return message, value, current_time

    else:

        remaining_time = last_command_time + delay_compare - current_time

        message = message_error.replace('{seconds}', str(remaining_time))
        value = False
        current_time = ''

        return message, value, current_time

def copy_file(source, dest):
    copy = 0

    try:

        shutil.copy2(source, dest)

    except Exception as e:

        error_log(e)
        copy = 1
        return copy

    copy = 1
    return copy

def check_image(image):

    try:
        respon = req.get(image, stream=True)

        if respon.status_code == 200:
            return True
        else:
            return False

    except req.exceptions.RequestException as e:

        return False

def update_ranks(data):

    ranks_config = manipulate_json(f"{local_work('appdata_path')}/config/rank.json", "load")

    type_id = data["type_id"]
    info = data["info"]

    if type_id == "likes":

        bg = ranks_config['likes_bg']
        op = ranks_config['likes_op']

        with open(f"{local_work('appdata_path')}/html/ranks/likes/likes.html", 'r', encoding='utf-8') as file:
            content_html = file.read()

            soup = bs(content_html, 'html.parser')

            div = soup.find("div", {"class": f"event_block"})

        for user, userdata in info:

            if check_image(userdata['profile_pic']):
                image = userdata['profile_pic']
            else:
                image = "icon.ico"

            new_block = bs(f'''

{userdata['display_name']}

{userdata['likes']} Curtidas

            ''', 'html.parser')

            div.append(new_block)

        return str(soup)

    elif type_id == "shares":

        bg = ranks_config['shares_bg']
        op = ranks_config['shares_op']

        with open(f"{local_work('appdata_path')}/html/ranks/shares/shares.html", 'r', encoding='utf-8') as file:
            content_html = file.read()

            soup = bs(content_html, 'html.parser')

            div = soup.find("div", {"class": f"event_block"})

        for user, userdata in info:

            if check_image(userdata['profile_pic']):
                image = userdata['profile_pic']
            else:
                image = "icon.ico"

            new_block = bs(f'''

{userdata['display_name']}

{userdata['shares']} Compartilhamentos

            ''', 'html.parser')

            div.append(new_block)

        return str(soup)

    elif type_id == "gifts":

        bg = ranks_config['gifts_bg']
        op = ranks_config['gifts_op']

        with open(f"{local_work('appdata_path')}/html/ranks/gifts/gifts.html", 'r', encoding='utf-8') as file:
            content_html = file.read()

            soup = bs(content_html, 'html.parser')

            div = soup.find("div", {"class": f"event_block"})

        for user, userdata in info:

            if check_image(userdata['profile_pic']):
                image = userdata['profile_pic']
            else:
                image = "icon.ico"

            new_block = bs(f'''

{userdata['display_name']}

{userdata['gifts']} Presentes

            ''', 'html.parser')

            div.append(new_block)

        return str(soup)

    elif type_id == "points":

        bg = ranks_config['points_bg']
        op = ranks_config['points_op']

        with open(f"{local_work('appdata_path')}/html/ranks/points/points.html", 'r', encoding='utf-8') as file:
            content_html = file.read()

            soup = bs(content_html, 'html.parser')

            div = soup.find("div", {"class": f"event_block"})

        for user, userdata in info:

            if check_image(userdata['profile_pic']):
                image = userdata['profile_pic']
            else:
                image = "icon.ico"

            new_block = bs(f'''

{userdata['display_name']}

{userdata['points']} Pontos

            ''', 'html.parser')

            div.append(new_block)

        return str(soup)

def update_alert(data):

    notifc_config_Data = manipulate_json(f"{local_work('appdata_path')}/config/notfic.json", "load")
    alert_config_data = manipulate_json(f"{local_work('appdata_path')}/config/alerts.json", "load")

    duration = notifc_config_Data['HTML_ALERT_TIME']

    message = data['message']
    img = data['img']

    image_size = alert_config_data['image_size']
    font_size = alert_config_data['font_size']
    background_color = alert_config_data['background_color']

    html_file = f"{local_work('appdata_path')}/html/alerts/alerts.html"

    try:

        with open(html_file, "r") as html:
            soup = bs(html, 'html.parser')

        main_div = soup.find("div", {"class": f"enter"})
        main_div['style'] = f'animation-duration: {duration}s'

        event_block = soup.find("div", {"class": f"event_block"})
        event_block['style'] = f'background-color: {background_color}'

        img_tag = soup.find("img", {"class": "img"})
        img_tag['src'] = img
        img_tag['width'] = image_size

        messsage_tag = soup.find("span", {"class": "message"})
        messsage_tag.string = message
        messsage_tag['style'] = f"font-size:{font_size};"

        return str(soup)

    except Exception as e:

        error_log(e)
        return True

def update_notif(data):

    notifc_config_Data = manipulate_json(f"{local_work('appdata_path')}/config/notfic.json", "load")

    duration = notifc_config_Data['HTML_REDEEM_TIME']

    message = data['message']

    html_file = f"{local_work('appdata_path')}/html/events/events.html"

    try:

        with open(html_file, "r") as html:
            soup = bs(html, 'html.parser')

        main_div = soup.find("div", {"class": f"enter"})
        main_div['style'] = f"animation-duration: {duration}s;"

        messsage_tag = soup.find("span", {"class": "message"})

        messsage_tag.string = message

        return str(soup)

    except Exception as e:

        error_log(e)
        return True

def update_music(data):

    notifc_config_Data = manipulate_json(f"{local_work('appdata_path')}/config/notfic.json", "load")

    duration = notifc_config_Data['HTML_MUSIC_TIME']

    user = data['redeem_user']
    artist = data['artist']
    music = data['music']

    html_file = f"{local_work('appdata_path')}/html/music/music.html"

    try:

        with open(html_file, "r") as html:
            soup = bs(html, 'html.parser')

        album_src = f"../../player/images/album.png?noCache={randint(0, 100000)}"

        main_div = soup.find("div", {"class": f"player"})
        main_div['style'] = f'animation-duration: {duration}s'

        music_name_tag = soup.find("span", {"class": "music_name"})
        artist_name_tag = soup.find("span", {"class": "artist_name"})
        user_name_tag = soup.find("span", {"class": "user_name"})

        music_name_tag.string = music
        artist_name_tag.string = artist
        user_name_tag.string = user

        artwork_tag = soup.find("div", {'class':'artwork'})

        if artwork_tag:

            artwork_tag['style'] = f"background: url(https://i.imgur.com/3idGgyU.png), url({album_src}) center no-repeat;"

        return str(soup)

    except Exception as e:

        error_log(e)
        return True

def update_goal(data):

    goal_data = manipulate_json(f"{local_work('appdata_path')}/config/goal.json", "load")

    try:

        if data['type_id'] == 'get_html':

            type_goal = data['type_goal']

            data = {
                'title_text_value' : goal_data[type_goal]['goal_text'],
                'outer_bar' : goal_data[type_goal]['outer_bar'],
                'title_text' : goal_data[type_goal]['title_text'],
                'progress_bar' : goal_data[type_goal]['progress_bar'],
                'progress_bar_background' : goal_data[type_goal]['progress_bar_background'],
            }

            return data

        elif data['type_id'] == 'save_html':

            type_goal = data['type_goal']

            path = normpath_simple(f"{local_work('appdata_path')}/html/goal/{type_goal}/goal.html")

            with open(path, "r") as html:
                soup = bs(html, 'html.parser')

            outer_bar = soup.find("div", {"class": "progress-outer"})
            title_text = soup.find("h3", {"class": "progress-title"})
            goal_text = soup.find("span", {"id": "progress-title"})
            progress_bar = soup.find("div", {"class": "progress-bar"})
            progress_bar_bg = soup.find("div", {"class": "progress"})

            goal_text.string = data['text_value']
            outer_bar['style'] = f"background-color: {data['outer_color']}"
            title_text['style'] = f"color: {data['text_color']}"
            progress_bar['style'] = f"background-color: {data['bar_color']}"
            progress_bar_bg['style'] = f"background-color: {data['background_bar_color']}"

            goal_data[type_goal]['goal_text'] = data['text_value']
            goal_data[type_goal]['outer_bar'] = data['outer_color']
            goal_data[type_goal]['title_text'] = data['text_color']
            goal_data[type_goal]['progress_bar'] = data['bar_color']
            goal_data[type_goal]['progress_bar_background'] = data['background_bar_color']

            manipulate_json(f"{local_work('appdata_path')}/config/goal.json", "save", goal_data)

            with open(path, "w", encoding="utf-8") as html_w:
                html_w.write(str(soup))

            return str(soup)

        elif data['type_id'] == 'update_goal':

            type_goal = data['type_goal']

            path = normpath_simple(f"{local_work('appdata_path')}/html/goal/{type_goal}/goal.html")

            with open(path, "r") as html:
                soup = bs(html, 'html.parser')

            data = {
                'text_value' : goal_data[type_goal]['goal_text'],
                'outer_color' : goal_data[type_goal]['outer_bar'],
                'text_color' : goal_data[type_goal]['title_text'],
                'bar_color' : goal_data[type_goal]['progress_bar'],
                'background_bar_color' : goal_data[type_goal]['progress_bar_background'],
            }

            outer_bar = soup.find("div", {"class": "progress-outer"})
            title_text = soup.find("h3", {"class": "progress-title"})
            goal_text = soup.find("span", {"id": "progress-title"})
            progress_bar = soup.find("div", {"class": "progress-bar"})
            progress_bar_bg = soup.find("div", {"class": "progress"})

            goal_text.string = data['text_value']
            outer_bar['style'] = f"background-color: {data['outer_color']}"
            title_text['style'] = f"color: {data['text_color']}"
            progress_bar['style'] = f"background-color: {data['bar_color']}"
            progress_bar_bg['style'] = f"background-color: {data['background_bar_color']}"

            with open(path, "r") as html:
                soup = bs(html, 'html.parser')

            return str(soup)

    except Exception as e:

        error_log(e)

        return True

def replace_all(text, dic_res):

    try:
        for i, j in dic_res.items():
            text = text.replace(str(i), str(j))

        return text

    except Exception as e:
        error_log(e)

        return ''

def messages_file_load(key):

    with open(f"{local_work('appdata_path')}/messages/messages_file.json", "r", encoding='utf-8') as messages_file:
        messages_data = json.load(messages_file)

    message = messages_data[key]

    return message

def compare_and_insert_keys():

    source_directory = f"{local_work('datadir')}/web/src"
    destination_directory = f"{local_work('appdata_path')}"

    if not os.path.exists(destination_directory):

        shutil.copytree(source_directory, destination_directory)

    def update_dict_recursive(dest_dict, source_dict):
        for key, value in source_dict.items():
            if key in dest_dict:
                if isinstance(value, dict) and isinstance(dest_dict[key], dict):
                    update_dict_recursive(dest_dict[key], value)
            else:
                dest_dict[key] = value
                error_log(f"Chave '{key}' atualizada: {value}")

    for root_directory, _, files in os.walk(source_directory):

        for file in files:

            if file.endswith('.json') and not file.endswith('gifts.json'):

                source_file_path = os.path.join(root_directory, file)
                destination_file_path = source_file_path.replace(source_directory, destination_directory)

                if not os.path.exists(destination_file_path):
                    error_log(f"File missing in the destination directory: {destination_file_path}")
                    shutil.copy2(source_file_path, destination_file_path)

                try:
                    with open(source_file_path, 'r', encoding='utf-8') as src_file, open(destination_file_path, 'r+', encoding='utf-8') as dest_file:
                        data1 = json.load(src_file)
                        data2 = json.load(dest_file)

                        if isinstance(data1, dict) and isinstance(data2, dict):
                            update_dict_recursive(data2, data1)
                            dest_file.seek(0)
                            json.dump(data2, dest_file, indent=4, ensure_ascii=False)
                            dest_file.truncate()

                except json.JSONDecodeError as e:
                    error_log(f"Error decoding the source JSON file: {source_file_path}")

    for root_directory, dirs, files in os.walk(destination_directory):

        for d in dirs:

            destination_path = os.path.join(root_directory, d)
            source_path = destination_path.replace(destination_directory, source_directory)

            if not os.path.exists(source_path):
                if os.path.isdir(destination_path):
                    error_log(f"File or directory in the destination directory that is not in the source directory: {destination_path}")
                    shutil.rmtree(destination_path)

        for file in files:

            destination_path = os.path.join(root_directory, file)
            source_path = destination_path.replace(destination_directory, source_directory)

            if not os.path.exists(source_path):
                if os.path.isfile(destination_path):
                    error_log(f"File in the destination directory that is not in the source directory: {destination_path}")
                    os.remove(destination_path)

    return True

def normpath_simple(path):

    path_norm = os.path.normpath(path)

    path_norm_simple = path_norm.replace('\\', '/')

    return path_norm_simple

def update_dict_gifts(dict_b):

    dict_a_load = manipulate_json(f"{local_work('appdata_path')}/config/gifts.json","load")
    dict_a = dict_a_load["gifts"]

    if not dict_a:
        dict_a.update(dict_b)
    else:
        for id_, item_a in dict_a.items():

            if id_ in dict_b:
                item_b = dict_b[id_]

                if item_a['name'] != item_b['name']:
                    print(f"Atualizado 'name' para {id_}")
                    dict_a[id_]['name'] = item_b['name']

                if item_a['value'] != item_b['value']:
                    print(f"Atualizado 'value' para {id_}")
                    dict_a[id_]['value'] = item_b['value']

                if item_a['icon'] != item_b['icon']:
                    print(f"Atualizado 'value' para {id_}")
                    dict_a[id_]['icon'] = item_b['icon']

            else:
                print(f"Removendo item para {id_}")
                del dict_a[id_]

    manipulate_json(f"{local_work('appdata_path')}/config/gifts.json","save",dict_a_load)

def check_file(file):

    try:

        with open(file, 'r', encoding='utf-8') as file_r:
            json.load(file_r)

        return True

    except Exception as e:
        return False


import datetime
from celery import Celery
from ..models.declarative_base import Base, engine, session
from ..models.models import *
import random

celery_app = Celery('health', broker='redis://localhost:6379/0')

celery_app.conf.task_queues = {
    'team': {
        'exchange': 'team',
        'exchange_type': 'direct',
        'routing_key': 'team',
    },
}

@celery_app.task(name='tasks.health_check', queue='team')
def check(message):

    random_number = random.random()

    if random_number <= 0.9:
        celery_app.send_task('tasks.health_response', args=['team', message], queue='monitor')
    else:
        failure = ServiceRegistration(requestId = message, timestamp=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), serviceName='team')
        session.add(failure)
        session.commit()
        session.close()


import json
import traceback

import boto3
from botocore.exceptions import ClientError

SSM_PARAM_TYPES = ['String', 'SecureString', 'StringList']
MISSING_TYPE_ERROR_MESSAGE = f""""Type" parameter, the type of key in the SSM
parameter store, is required, and must be one of {SSM_PARAM_TYPES}"""
MISSING_NAME_ERROR_MESSAGE = """"Name" parameter (name of key in SSM parameter
store) is required"""

def get_ssm_client():
  return boto3.client('ssm')

def handle_transform(parameters):
    if 'Type' not in parameters or parameters['Type'] not in SSM_PARAM_TYPES:
      raise ValueError(MISSING_TYPE_ERROR_MESSAGE)
    if 'Name' not in parameters:
      raise ValueError(MISSING_NAME_ERROR_MESSAGE)

    decrypt = True if parameters['Type'] == SSM_PARAM_TYPES[1] else False

    client = get_ssm_client()

    try:
      response = client.get_parameter(
        Name=parameters['Name'],
        WithDecryption=decrypt)
      fragment = response['Parameter']['Value']
      return fragment
    except ClientError as e:

      raise e

def handler(event, context):
    status = 'success'
    response = {
      'requestId': event['requestId'],
      'status': 'success'
    }

    try:
      response['fragment'] = handle_transform(event['params'])
    except Exception as e:
      traceback.print_exc()
      response['status'] = 'failure'
      response['errorMessage'] = str(e)

    return response


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

import os, json, datetime, re, urllib, time, argparse

import requests

from lxml import html

class ParserData():

    def __init__(self, **values):
        self.__values = values
        self.__values['type'] = self.type
        for attr in values:
            setattr(self, attr, values[attr])

    def __setattr__(self, attr, value):
        if not attr.startswith('_'):
            self.__values[attr] = value
        super().__setattr__(attr, value)

    def tojson(self):
        return json.dumps(self.__values, sort_keys=True)

    def __str__(self):
        return str(self.__values)

class CountryData(ParserData):
    type = 'countrydata'

class DetailData(ParserData):
    type = 'detaildata'

class PopulationData(ParserData):
    type = 'populationdata'

class WOMParser():

    def __init__(self, url):
        self.url = url

    def parsenumber(self, text):
        if text is None:
            return text
        try:
            return int(text.replace(',',''))
        except ValueError:
            return text

    def parsecountries(self):
        r = requests.get(self.url)
        r.raise_for_status()
        page = html.fromstring(r.content)

        #table = page.xpath('//*[@id="main_table_countries_today"]/tbody[1]')[0]
        table = page.xpath('//*[@id="main_table_countries_yesterday"]/tbody[1]')[0]
        #country_element = table.xpath("//td[contains(., 'USA')]")[0]
        #print(html.tostring(country_element))
        #row = country_element.xpath("./..")[0]
        for row in table.xpath("tr"):
            #print(html.tostring(row))
            if row.attrib.get("class") in ["total_row_world row_continent", "total_row_world"]:
                continue
            links = row.xpath("td/a")
            if not links:
                continue
            country = links[0].text

            data = [self.parsenumber(td.text) for td in row.xpath("td")]

            baseidx = 1

            total_cases = data[baseidx+1]
            new_cases = data[baseidx+2]
            total_deaths = data[baseidx+3]
            new_deaths = data[baseidx+4]
            total_recovered = data[baseidx+5]
            active_cases = data[baseidx+6]
            new_recovered = data[baseidx+7]
            serious_critical = data[baseidx+8]
            total_per_1m = data[baseidx+9]
            total_deaths_per_1m = data[baseidx+10]
            total_tests = data[baseidx+11]
            total_tests_per_1m = data[baseidx+12]
            continent = data[baseidx+14]

            if len(links) > 1:
                population = self.parsenumber(links[1].text)
            else:
                population = data[baseidx+13]

            if False:
                print("Country: ", country)
                print("Total cases: ", total_cases)
                print("New cases: ", new_cases)
                print("Total deaths: ", total_deaths)
                print("New deaths: ", new_deaths)
                print("Active cases: ", active_cases)
                print("Total recovered: ", total_recovered)
                print("Serious, critical cases: ", serious_critical)

            countrydata = CountryData(
                country=country,
                total_cases = total_cases,
                new_cases = new_cases,
                total_deaths = total_deaths,
                new_deaths = new_deaths,
                active_cases = active_cases,
                total_recovered = total_recovered,
                #new_recovered = new_recovered,
                serious_critical = serious_critical,
                total_per_1m = total_per_1m,
                total_deaths_per_1m = total_deaths_per_1m,
                total_tests = total_tests,
                total_tests_per_1m = total_tests_per_1m,
                date = str(datetime.date.today()-datetime.timedelta(days=1)),
                continent = continent,
                population = population,
                #data = str(data),
            )
            yield countrydata

    def parsepopulation(self):
        r = requests.get(self.url)
        r.raise_for_status()
        page = html.fromstring(r.content)

        table = page.xpath('//*[@id="example2"]/tbody[1]')[0]
        for row in table.xpath("tr"):
            #print(html.tostring(row))
            if row.attrib.get("class") in ["total_row_world row_continent", "total_row_world"]:
                continue
            country_elem = row.xpath("td/a")
            if not country_elem:
                continue
            country = country_elem[0].text

            data = [self.parsenumber(td.text) for td in row.xpath("td")]

            population = data[2]

            if False:
                print("Country: ", country)
                print("Population: ", population)

            popdata = PopulationData(
                country=country,
                population=data[2]
            )
            yield popdata

    def parsedetails(self):
        r = requests.get(self.url)
        r.raise_for_status()
        page = html.fromstring(r.content)

        table = page.xpath('//*[@id="main_table_countries_yesterday"]/tbody[1]')[0]

        for row in table.xpath("tr"):
            if row.attrib.get("class") in ["total_row_world row_continent", "total_row_world"]:
                continue
            country_elem = row.xpath("td/a")
            if not country_elem:
                continue

            country = country_elem[0].text
            url = country_elem[0].attrib.get('href')
            (cases, deaths, active) = self.parsecountry(country, url)
            detaildata = DetailData(
                country=country,
                cases = cases,
                deaths = deaths,
                active = active,
            )

            yield detaildata

    def parsecountry(self, country, url):
        r = requests.get(urllib.parse.urljoin(self.url, url))
        page = html.fromstring(r.content)

        if False:
            script = page.xpath('//div[@id="graph-cases-daily"]/following-sibling::script[1]')
            if script:
                cases = self.parsescript(script[0], "Daily Cases")
            else:
                cases = []

            script = page.xpath('//div[@id="graph-deaths-daily"]/following-sibling::script[1]')
            if script:
                deaths = self.parsescript(script[0], "Daily Deaths")
            else:
                deaths = []
        else:
            script = page.xpath('//div[@class="tabbable-panel-cases"]/following-sibling::script[1]')
            if script:
                cases = self.parsescript(script[0], "Cases")
            else:
                cases = []

            script = page.xpath('//div[@class="tabbable-panel-deaths"]/following-sibling::script[1]')
            if script:
                deaths = self.parsescript(script[0], "Deaths")
            else:
                deaths = []

        script = page.xpath('//div[@id="graph-active-cases-total"]/following-sibling::script[1]')
        if script:
            active = self.parsescript(script[0], "Currently Infected")
        else:
            active = []

        return cases, deaths, active

    def parsescript(self, elem, attribute):
        lines = elem.text.split('\n')

        try:
            xaxis = lines.index('        xAxis: {')
        except ValueError:
            xaxis = lines.index('            xAxis: {')
        datevalues = self.parsevalues(lines[xaxis+1])
        dates = self.parsedates(datevalues)
        try:
            vidx = lines.index("            name: '%s'," % attribute)
        except ValueError:
            vidx = lines.index("                name: '%s'," % attribute)

        values = self.parsevalues(lines[vidx+3])
        #print(dates)
        #print(values)
        return list(zip(dates, values))

    def parsevalues(self, line):
        r = re.compile(r".*(\[.*?\]).*")
        v = r.match(line)
        parsed = json.loads(v.group(1))
        return parsed

    def parsedates(self, datevalues):
        dates = []

        baseyear = 2020
        prevd = None

        for text in datevalues:
            ts = time.strptime(text, '%b %d')
            d = datetime.date(baseyear, ts.tm_mon, ts.tm_mday)
            if prevd and prevd > d:
                baseyear += 1
                d = datetime.date(baseyear, ts.tm_mon, ts.tm_mday)
            prevd = d
            dates.append(d.strftime('%Y-%m-%d'))
        return dates

def main():
    p = argparse.ArgumentParser()
    p.add_argument(
        "-s",
        "--stdout",
        action="store_true",
        dest="write_stdout",
        default=False,
        help="output to stdout",
    )
    p.add_argument(
        "-C", "--csv", action="store_true", dest="csv", default=False, help="csv mode"
    )
    p.add_argument(
        "-f",
        "--outputfile",
        action="store",
        dest="outputfile",
        default=None,
        help="outputfile name",
    )
    p.add_argument(
        "-o",
        "--overwrite",
        action="store_true",
        dest="overwrite",
        default=False,
        help="overwrite existing outputfile",
    )
    p.add_argument("dataset", choices=['countries', 'details', 'population'])

    options = p.parse_args()
    dataset = options.dataset

    cov_url = 'https://www.worldometers.info/coronavirus/'
    pop_url = 'https://www.worldometers.info/world-population/population-by-country/'

    if options.outputfile:
        outputfile = options.outputfile
    else:
        datestr = datetime.date.today().strftime("%Y%m%d")
        outputfile = "%s-%s.json" % (dataset, datestr)

    if dataset == 'countries':
        parser = WOMParser(cov_url)
        parsermethod = parser.parsecountries

    elif dataset == 'details':
        parser = WOMParser(cov_url)
        parsermethod = parser.parsedetails

    elif dataset == 'population':
        parser = WOMParser(pop_url)
        parsermethod = parser.parsepopulation

    else:
        usage()
        return

    if parsermethod:
        if options.write_stdout:
            for event in parsermethod():
                print(event.tojson())

        else:
            if os.path.exists(outputfile) and os.path.getsize(outputfile) > 0 and not options.overwrite:
                print("%s exists" % outputfile)
                return

            with open(outputfile, 'w') as fp:
                for event in parsermethod():
                    print(event.tojson(), file=fp)

if __name__ == "__main__":
    main()


import re
from django import template
from decimal import Decimal

register = template.Library()

@register.filter
def match(value, regex):
    """
    Tests a regular expression against the start of a value.

    Especially useful in if statements::

        {% if value|match:"regex" %}

Some text

        {% endif %}
    """
    return re.match(regex, value)

@register.filter
def subtract(value, arg):
  return value - arg


"""
    Advent of Code 2021
    Day 02: Dive!
"""

import pytest

def parse_input(file_name):
    with open(file_name, "r", encoding="ascii") as data_file:
        data = []
        for line in data_file.readlines():
            command, value = line.split()
            data.append((command, int(value)))
        return data

def day02_part1(data):
    hpos = 0
    depth = 0
    for cmd, val in data:
        if cmd == "forward":
            hpos += val
        else:
            depth += val if cmd == "down" else -val
    return hpos * depth

def day02_part2(data):
    hpos = 0
    depth = 0
    aim = 0
    for cmd, val in data:
        if cmd == "forward":
            hpos += val
            depth += aim * val
        else:
            aim += val if cmd == "down" else -val
    return hpos * depth

@pytest.fixture(autouse=True, name="test_data")
def fixture_test_data():
    return parse_input("data/day02_test.txt")

def test_day02_part1(test_data):
    assert day02_part1(test_data) == 150

def test_day02_part2(test_data):
    assert day02_part2(test_data) == 900

if __name__ == "__main__":
    input_data = parse_input("data/day02.txt")

    print("Day 02 Part 1:")
    print(day02_part1(input_data))  # Correct answer is 1451208

    print("Day 02 Part 2:")
    print(day02_part2(input_data))  # Correct answer is 1620141160


from __future__ import absolute_import, print_function, division
from __future__ import unicode_literals

import math
import os
import time

import tensorflow as tf

from utils.utils import deco_print, log_summaries_from_dict, get_results_for_epoch

class PrintSampleHook(tf.train.SessionRunHook):

    def __init__(self, every_steps, model):
        super(PrintSampleHook).__init__()
        self._timer = tf.train.SecondOrStepTimer(every_steps = every_steps)
        self._iter_count = 0
        self._global_step = None
        self._model = model

        # Using only the 1st GPU
        output_tensors = model.get_output_tensors(0)
        self._fetches = [model.get_data_layer(0).input_tensors, output_tensors]

    def begin(self):
        self._iter_count = 0
        self._global_step = tf.train.get_global_step()

    def before_run(self, run_context):
        if self._timer.should_trigger_for_step(self._iter_count):
            return tf.train.SessionRunArgs([self._fetches, self._global_step])
        return tf.train.SessionRunArgs([[], self._global_step])

    def after_run(self, run_context, run_values):
        results, step = run_values.results
        self._iter_count = step

        if not results:
            return
        self._timer.update_last_triggered_step(self._iter_count - 1)

        input_values, output_values = results
        dict_to_log = self._model.maybe_print_logs(input_values, output_values, step)

        if self._model.params["save_summaries_steps"] and dict_to_log:
            log_summaries_from_dict(
                    dict_to_log,
                    self._model.params["logdir"],
                    step)

class PrintLossAndTimeHook(tf.train.SessionRunHook):

    def __init__(self, every_steps, model):
        super(PrintLossAndTimeHook).__init__()
        self._timer = tf.train.SecondOrStepTimer(every_steps = every_steps)
        self._every_steps = every_steps
        self._iter_count = 0
        self._global_step = None
        self._model = model
        self._fetches = [model.loss]
        self._last_time = time.time()

    def begin(self):
        self._iter_count = 0
        self._global_step = tf.train.get_global_step()

    def before_run(self, run_context):
        if self._timer.should_trigger_for_step(self._iter_count):
            return tf.train.SessionRunArgs([self._fetches, self._global_step])
        return tf.train.SessionRunArgs([[], self._global_step])

    def after_run(self, run_context, run_values):
        results, step = run_values.results
        self._iter_count = step

        if not results:
            return

        self._timer.update_last_triggered_step(self._iter_count - 1)

        if self._model.steps_in_epoch is None:
            deco_print("Global step {}:".format(step), end = " ")
        else:
            deco_print("Epoch {}, global step {}:".format(step // self._model.steps_in_epoch, step), end = " ")

        loss = results[0]

        deco_print("Train loss: {:.4f}".format(loss), offset = 4)

        tm = (time.time() - self._last_time) / self._every_steps
        m, s = divmod(tm, 60)
        h, m = divmod(m ,60)

        deco_print("time per step = {}:{:02}:{:.3f}".format(int(h), int(m), s), start = " ")

        self._last_time = time.time()


import asyncio
from typing import TypeVar, Awaitable, Callable

T = TypeVar('T')

class RateLimitExceedException(Exception):
    pass

# Internal design:
# All requests are put in a common queue,
# a middleware consumer runs at the specified rate and, at each tick, removes one item
# from the common queue and puts it in the rate-limited queue.
# multiple final consumers (number = to the max concurrent tasks available) pop a task from the
# rate limited queue and execute it

class RateLimiter:
    """
    Rate-limits async queries and implements retrial mechanisms appropriate for a robust scraping system

    Lots of APIs have rate limits on the number of queries that can be executed that are hard to maintain in
    asynchronous contexts, this class implements a limiting valve that, given multiple queries, executes them
    at the specified rate (with a specified maximum number. of concurrent queries).
    Another useful aspect is query re-execution, if the query surpassed rate limits the task can throw
    RateLimitExceedException, it will automatically be re-tried after some time (using exponential back-off).
    """

    def __init__(self, tasks_per_seconds: int, max_tasks_at_once: int):
        self._tasks_per_second = tasks_per_seconds
        self._queue = asyncio.Queue()
        self._rate_limited_queue = asyncio.Queue(1)
        self._consumers = [asyncio.create_task(self._consumer()) for _ in range(max_tasks_at_once)]
        self._producer_task = asyncio.create_task(self._producer())

    async def _producer(self):
        while True:
            x = await self._queue.get()
            await self._rate_limited_queue.put(x)
            await asyncio.sleep(1 / self._tasks_per_second)

            self._queue.task_done()

    async def _consumer(self):
        while True:
            x = await self._rate_limited_queue.get()
            await x
            self._rate_limited_queue.task_done()

    async def execute(self, x: Callable[[], Awaitable[T]]) -> T:
        """
        Inserts a task in the system, it will be executed at the specified rate

        Since the task can be restarted if a RateLimitExceedException is thrown the argument is not an awaitable
        but a task factory, that should produce a task each time it's called.

        :param x: A task factory
        :return: The returned result (once completed)
        """
        future = asyncio.Future()

        async def wrapper():
            retry = 0
            while True:
                try:
                    future.set_result(await x())
                    break
                except RateLimitExceedException:
                    retry += 1
                    # Exponential backoff
                    wait_time = 2+2**retry
                    print(f"Rate limit exceed, waiting {wait_time}s")
                    await asyncio.sleep(wait_time)
                    # Don't break: repeat
                except Exception as e:
                    future.set_exception(e)
                    break

        await self._queue.put(wrapper())
        return await future

    async def stop(self) -> None:
        """
        Waits for the execution of all queried tasks and returns, freeing allocated resources
        """
        await self._queue.join()
        self._producer_task.cancel()
        await self._rate_limited_queue.join()

        for c in self._consumers:
            c.cancel()

    async def __aenter__(self):
        return self

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        await self.stop()


import cv2 as cv
import numpy as np
from scipy.signal import argrelextrema
import matplotlib.pyplot as plt
import time

cap = cv.VideoCapture(0)
time.sleep(1)
ret, base = cap.read()
step=1
while True:
    step=step+1
    ret, frame = cap.read()

    # フレームを表示
    # cv.imshow('Flame', frame)
    # if cv.waitKey(1) & 0xFF == ord('q'):
    #     break
    # cv.imwrite('basetest5.jpg', frame)

    # ret, frame = cap.read()
    # 差分抽出
    # frame1=base_frame
    frame_diff=((base>frame)*(base-frame)+(base<frame)*(frame-base))
    frame_diff=(frame_diff>=10)*(frame_diff-0)
    # plt.imshow(frame_diff)
    diff_sum=np.sum(frame_diff, axis=2)
    # plt.imshow(diff_sum)

    median = cv.medianBlur(frame_diff,31)
    # median = cv.medianBlur(frame_diff,1)

    # x,y方向それぞれ畳み込む
    median=np.sum(median, axis=2)
    diff_sum_x=np.sum(median, axis=0)
    diff_sum_y=np.sum(median, axis=1)

    # 画素の濃淡で重み付けして重心を計算
    diff_sum_all=np.sum(median)
    if(diff_sum_all==0):
        diff_sum_all=1
    # print(diff_sum_all)
    axis_x=np.arange(diff_sum_x.size)
    axis_y=np.arange(diff_sum_y.size)
    ave_x=np.sum(diff_sum_x*axis_x)/diff_sum_all
    ave_y=np.sum(diff_sum_y*axis_y)/diff_sum_all
    if(step%10==0):
        print(step,ave_x,ave_y)
    # print(ave_x,ave_y)

    # 重心を中心とする円を描画
    cv.circle(frame, (int(ave_x),int(ave_y)), 100, (255, 0, 0), thickness=5)
    cv.imshow('Flame', frame)
    if cv.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv.destroyAllWindows()


from entities.game_console import Game
from entities.round_console import Round, Subround
from entities.tournament_console import Tournament
from utils.template_data import EXAMPLE_PLAYERS, EXAMPLE_WORDS
from typing import List, Optional
from collections import Counter
from typing import Counter as CounterT

VERSION_INTERFACE: str = "0.0.3"
HELP: str = """
Доступные команды:
quit, exit
version
help
add word
delete word
add players
delete players
template fill (broken)
add round
add subround
checkout round
checkout subround
checkout game
set game results
split to games
conclude subround result
conclude round result
get k best
"""

if __name__ == "__main__":
    current_tournament: Tournament = Tournament(0)
    current_round: Optional[Round] = None
    current_subround: Optional[Subround] = None
    current_game: Optional[Game] = None
    print("Система организации турниров по шляпе, локальный командный интерфейс")

    while True:
        command: str = input(">>> ")
        if command == "quit" or command == "exit":
            break
        elif command == "version":
            print(f"Версия интерфейса: {VERSION_INTERFACE}")
            print(f"Версия класса: {current_tournament.VERSION}")
        elif command == "help":
            print(HELP)
        elif command == "add word":
            word: str = input("Введите слово:\n")
            difficulty: int = int(input("Введите сложность:\n"))
            result, word_id = current_tournament.add_word(
                word, difficulty
            )  # FIXME: No type annotation
            if result:
                print(f"Слово добавлено, его uid: {word_id}")
            else:
                print(f"Слово уже есть в базе")
        elif command == "delete word":
            word: str = input("Введите слово:\n")
            result: bool = current_tournament.delete_word(word)
            if result:
                print(f"Слово удалено")
            else:
                print(f"Слова нет в базе")
        elif command == "add players":
            first_player: str = input("Введите имя и фамилию первого игрока:\n")
            second_player: str = input("Введите имя и фамилию второго игрока:\n")
            result: bool = current_tournament.add_play_pair(first_player, second_player)
            if result:
                print("Пара игроков успешно добавлена")
            else:
                print("Пара игроков уже участвует")
        elif command == "delete players":
            first_player: str = input("Введите имя и фамилию первого игрока:\n")
            second_player: str = input("Введите имя и фамилию второго игрока:\n")
            result: bool = current_tournament.delete_play_pair(
                first_player, second_player
            )
            if result:
                print("Пара игроков успешно удалена")
            else:
                print("Пары игроков нет в списке участников")
        elif command == "template fill":
            for word, diff in EXAMPLE_WORDS:
                current_tournament.add_word(word, diff)
            for play_1, play_2 in EXAMPLE_PLAYERS:
                current_tournament.add_play_pair(play_1, play_2)
            print("Добавлены слова и игроки для примера")
        elif command == "add round":
            players_uid: List[int] = list(
                map(int, input("Введите uid пар участников нового раунда:\n").split())
            )
            difficulty: int = int(input("Введите ожидаемую сложность раунда:\n"))
            name: str = input("Введите название раунда:\n")
            current_tournament.create_round(players_uid, difficulty, name)
            print("Раунд создан")
        elif command == "checkout round":
            round_id: int = int(input("Введите номер раунда:\n"))
            if round_id >= len(current_tournament.rounds):
                print("Нет раунда с таким номером")
            else:
                current_round = current_tournament.rounds[round_id]
                print("Раунд успешно выбран")
        elif command == "add subround":
            if current_round is None:
                print("Сначала выберите раунд")
                continue
            players_uid: List[int] = list(
                map(
                    int, input("Введите uid пар участников нового подраунда:\n").split()
                )
            )
            words_amount: int = int(input("Укажите, сколько слов из банка взять:\n"))
            result: bool = current_round.add_subround(players_uid, words_amount)
            if result:
                print("Подраунд успешно создан")
            else:
                print("Что-то пошло не так")
        elif command == "checkout subround":
            if current_round is None:
                print("Сначала выберите раунд")
                continue
            subround_id: int = int(input("Введите номер подраунда:\n"))
            if subround_id >= len(current_round.subrounds):
                print("Нет подраунда с таким номером")
            else:
                current_subround = current_round.subrounds[subround_id]
                print("Подраунд успешно выбран")
        elif command == "split to games":
            if current_subround is None:
                print("Сначала выберите подраунд")
                continue
            games_amount: int = int(
                input("Укажите, на сколько игр разбить подраунд:\n")
            )
            result: bool = current_subround.split_players_to_games(games_amount)
            if result:
                print("Подраунд успешно разбит на игры")
            else:
                print("Что-то пошло не так")
        elif command == "checkout game":
            if current_subround is None:
                print("Сначала выберите подраунд")
                continue
            game_id: int = int(input("Введите номер игры:\n"))
            if game_id >= len(current_subround.games):
                print("Нет игры с таким номером")
            else:
                current_game = current_subround.games[game_id]
                print("Игра успешно выбрана")
        elif command == "set game results":
            if current_game is None:
                print("Сначала выберите игру")
                continue
            game_results: CounterT[int] = Counter(current_game.participants_uid)
            for player_uid in current_game.participants_uid:
                game_results[player_uid] = int(
                    input(
                        f"Enter result for pair {current_tournament.uid_to_play_pair[player_uid]}:\n"
                    )
                )

            result: bool = current_game.conclude_result(game_results)
            if result:
                print("Итоги успешно подведены")
            else:
                print("Произошла какая-то ошибка при подведении итогов")
        elif command == "conclude subround result":
            result: bool = current_subround.conclude_results()
            if result:
                print("Итоги подраунда успешно подведены")
            else:
                print("Подведение итогов не прошло успешно")
        elif command == "conclude round result":
            result: bool = current_round.conclude_results()
            if result:
                print("Итоги раунда успешно подведены")
            else:
                print("Подведение итогов не прошло успешно")
        elif command == "get k best":
            k: int = int(input("Укажите число для взятия:\n"))
            result: Optional[List[int]] = current_round.get_top_n(k)
            if result:
                for uid in result:
                    print(current_tournament.uid_to_play_pair[uid])
            else:
                print("Что-то пошло не так")


from datetime import datetime

from django.http import JsonResponse
from django.shortcuts import redirect, get_object_or_404
from django.urls import reverse
from django.db.models import Q
from django.contrib.auth.mixins import PermissionRequiredMixin, LoginRequiredMixin
from django.utils.http import urlencode
from django.views.generic import ListView, CreateView, DetailView, DeleteView, UpdateView

from advert.models import Advert
from advert.forms import AdvertForm, SearchForm

class AdvertListView(ListView):
    model = Advert
    template_name = 'adverts/list.html'
    context_object_name = 'ads'
    paginate_related_by = 4
    paginate_related_orphans = 0

    def get(self, request, **kwargs):
        self.form = SearchForm(request.GET)
        self.search_data = self.get_search_data()
        return super(AdvertListView, self).get(request, **kwargs)

    def get_queryset(self):
        queryset = super().get_queryset()

        if self.search_data:
            queryset = queryset.filter(
                Q(title__icontains=self.search_data)
            )
        return queryset.filter(moderated=True).order_by('-post_date')

    def get_search_data(self):
        if self.form.is_valid():
            return self.form.cleaned_data['search_value']
        return None

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['adverts'] = Advert.objects.all().filter(moderated=True).order_by('-post_date')
        context['search_form'] = self.form

        if self.search_data:
            context['query'] = urlencode({'search_value': self.search_data})
        return context

class AdvertCreateView(LoginRequiredMixin, CreateView):
    model = Advert
    template_name = 'adverts/create.html'
    form_class = AdvertForm

    def form_valid(self, form):
        ad = form.save(commit=False)
        ad.author = self.request.user
        ad.save()
        return redirect('advert_list')

class ApprovalListView(PermissionRequiredMixin, ListView):
    model = Advert
    template_name = 'adverts/approval.html'
    context_object_name = 'ads'
    paginate_related_by = 4
    paginate_related_orphans = 0
    permission_required = 'advert.approve'

    def get(self, request, **kwargs):
        self.form = SearchForm(request.GET)
        self.search_data = self.get_search_data()
        return super(ApprovalListView, self).get(request, **kwargs)

    def get_queryset(self):
        queryset = super().get_queryset()

        if self.search_data:
            queryset = queryset.filter(
                Q(title__icontains=self.search_data)
            )
        return queryset.filter(moderated=False).order_by('created_date')

    def get_search_data(self):
        if self.form.is_valid():
            return self.form.cleaned_data['search_value']
        return None

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['adverts'] = Advert.objects.all().filter(moderated=False).order_by('created_date')
        context['search_form'] = self.form

        if self.search_data:
            context['query'] = urlencode({'search_value': self.search_data})
        return context

    def has_permission(self):
        return super().has_permission()

class AdvertDetailView(DetailView):
    model = Advert
    template_name = 'adverts/detail.html'
    context_object_name = 'ad'

class AdvertUpdateView(PermissionRequiredMixin, UpdateView):
    model = Advert
    template_name = 'adverts/update.html'
    form_class = AdvertForm
    context_object_name = 'ad'

    def form_valid(self, form):
        ad = form.save(commit=False)
        ad.author = self.request.user
        ad.moderated = False
        ad.save()
        return redirect('advert_list')

    def has_permission(self):
        return self.get_object().author == self.request.user

class AdvertDeleteView(PermissionRequiredMixin, DeleteView):
    model = Advert
    template_name = 'adverts/delete.html'

    def get_success_url(self):
        return reverse('advert_list')

    def has_permission(self):
        return self.get_object().author == self.request.user

class ApprovalAdvertDetailView(PermissionRequiredMixin, DetailView):
    model = Advert
    template_name = 'adverts/approval_detail.html'
    context_object_name = 'ad'
    permission_required = 'advert.approve'

    def has_permission(self):
        return super().has_permission()

def approve(request, *args, **kwargs):
    if request.is_ajax and request.method == "POST":
        ad = get_object_or_404(Advert, pk=list(dict(request.POST).keys())[0])
        ad.moderated = True
        ad.published_at = datetime.now()
        ad.save()
        return JsonResponse({'message': 'Success!'}, status=200)
    return JsonResponse({"error": ""}, status=400, safe=False)

def reject(request, *args, **kwargs):
    if request.is_ajax and request.method == "POST":
        ad = get_object_or_404(Advert, pk=list(dict(request.POST).keys())[0])
        ad.rejected = True
        ad.save()
        return JsonResponse({'message': 'Rejected'}, status=200)
    return JsonResponse({"error": ""}, status=400, safe=False)


# -*- coding: utf-8 -*-
import maya.cmds as cmds
import platform
import random
from functools import partial
from tracker import before_tracking, after_tracking, send

_VERSION = "0.0.1"
_WINDOW_NAME = "GATrackingWindow"
GA_BASE_PARAMS = {'ul': str(cmds.about(uil=True)),
                  'an': 'ga_plugin_example',
                  'aid': 'ga_plugin_example_id',
                  'av': _VERSION,
                  'aiid': str(cmds.about(iv=True)),
                  'cd': _WINDOW_NAME,
                  'cd1': str(platform.platform())}

class GATrackingWindow(object):
    def __init__(self):
        self.windowName = _WINDOW_NAME
        self.windowTitle = self.windowName + "(v{0})".format(_VERSION)

    @classmethod
    def main(cls, *args):
        cls().create_gui()

    @before_tracking("screenview", GA_BASE_PARAMS)
    def create_gui(self):

        if cmds.window(self.windowName, exists=True):
            cmds.deleteUI(self.windowName)

        self.window = cmds.window(self.windowName,
                                  title=self.windowTitle,
                                  topLeftCorner=[200, 200],
                                  width=280, sizeable=True,
                                  maximizeButton=False, minimizeButton=False)

        cmds.frameLayout(label=u"GA Tracking",
                         marginWidth=6,
                         marginHeight=6,
                         borderStyle="etchedIn")

        cmds.button(label=u"Button1",
                    c=partial(self.button_command1, "button1"))
        cmds.button(label=u"Button2",
                    c=partial(self.button_command2, "button2"))

        cmds.setParent('..')

        cmds.showWindow(self.window)

    @after_tracking("event", GA_BASE_PARAMS, {'ec': "ToolAction",
                                              'ea': "ButtonPressed",
                                              'el': "button1"})
    def button_command1(self, arg, *args, **kwargs):
        print("pressed.", arg)

    @after_tracking("event", GA_BASE_PARAMS, {'ec': "ToolAction",
                                              'ea': "ButtonPressed",
                                              'el': "button2"})
    def button_command2(self, arg, *args, **kwargs):
        num = random.randint(0, 1)
        if num == 0:
            raise Exception("dancing with hard luck.")
            return
        print("pressed.", arg)


#!/usr/bin/python2.7

from __future__ import print_function
from subprocess import *
import curses
import os
import sys
from time import sleep, strftime, time
import re

USER = os.environ['USER']

re_state = re.compile(' ([CHERW]) ')

def get_qstat(user=USER):
  #p1 = Popen(['qstat', '-u', user], shell=FALSE, stdout=PIPE)
  output = check_output(['qstat', '-u', user], shell=False)
  output = output.split('\n')[2:]
  output = '\n'.join(output)
  return output

def print_qstat_head(stdscr, qstat, y=3, x_offset=1):
  stdscr.addstr(y, x_offset, qstat[0])
  y += 1
  stdscr.addstr(y, x_offset, qstat[1])
  y += 1
  stdscr.addstr(y, x_offset, qstat[2])
  y += 1

def print_qstat_jobs(stdscr, qstat, y=6, x_offset=1):
  for l in qstat:
    # goto state:
    state = re_state.search(l, pos=80, endpos=93)
    try:
      stdscr.addstr(y, x_offset, l)
    except curses.error:
      pass

    if state is not None:
      start = state.start(1)
      end   = state.span(1)[1]
      state = state.groups()[0]

      state_att = curses.A_NORMAL
      line_att = curses.A_NORMAL

      if state == 'E' or state == 'C':
        state_att = curses.A_BLINK
      if state == 'W':
        state_att = curses.A_DIM
        line_att = curses.A_DIM
      try:
        if line_att != curses.A_NORMAL:
          stdscr.addstr(y, x_offset, l, line_att)
        if state_att != curses.A_NORMAL:
          stdscr.addstr(y, x_offset+start, state, state_att)
      except curses.error:
        pass
    y += 1
  stdscr.refresh()

def print_time(stdscr, y=2, x=1):
  stdscr.addstr(y, x, strftime('%Y-%m-%d %H:%M:%S  '))
  stdscr.refresh()

def print_right_time(stdscr, y=3):
  time_length = 20
  x = stdscr.getmaxyx()[1] - time_length
  print_time(stdscr, y, x)

def main(stdscr):
  #print('Qstat for user', USER)
  #print('Hello world!')
  #print(get_qstat())
  curses.curs_set(0)
  stdscr.move(5,5)
  stdscr.addstr(1,1, 'qstat for user ')
  stdscr.addstr(USER, curses.A_BOLD)
  print_right_time(stdscr, y=1)
  qstat = [l.rstrip() for l in get_qstat().split('\n')]
  print_qstat_head(stdscr, qstat)
  if len(qstat) > 3:
    print_qstat_jobs(stdscr, qstat[3:])

  #print_qstat(stdscr)
  #stdscr.refresh()

  #qstat_win = curses.newwin(8, 94, 3, 1)
  qstat_lines = 0

  stdscr.nodelay(1)  # getch is non-blocking
  start = time()
  wait = time()
  while True:
    print_right_time(stdscr, y=1)
    c = stdscr.getch()
    if c == ord('q') or c == ord('Q'):
      break
    if time() >= wait + 30:
      qstat = [l.rstrip() for l in get_qstat().split('\n')]
      if len(qstat) != qstat_lines:
        stdscr.clear()
        print_qstat_head(stdscr, qstat)
        qstat_lines = len(qstat)
      if len(qstat) > 3:
        print_qstat_jobs(stdscr, qstat[3:])
      wait = time()
    #if time() >= start + 30:
    #  break
    sleep(1)
  #stdscr.addstr(3,1, get_qstat())
  #stdscr.refresh()
  #sleep(2)

#main()

curses.wrapper(main)

#print(get_qstat())

#print(USER)
#print(get_qstat())

#stdscr = curses.initscr()
#curses.noecho()  ## disables echoing of keys to the screen
#curses.cbreak()  ## react to keys instantly (i.e. do not wait for Enter)
#stdscr.keypad(1) ## enable use of special keys (Page Up, Home, etc.)

## When exiting:
#curses.nocbreak(); stdscr.keypad(0); curses.echo()
#curses.endwin()


import spotipy
from spotipy.oauth2 import SpotifyClientCredentials

sp = spotipy.Spotify(auth_manager=SpotifyClientCredentials(client_id="",
                                                           client_secret=""))

print("***** Welcome to the Music Grading System V3.0 *****")
print("***** Created by Ahmed Alami, GitHub: A71as *****")

# Get the album name and artist name from the user
artist_name = input("Enter the artist name: ")
album_name = input("Enter the album name: ")

# Search for the album using the album name and artist name
results = sp.search(q='album:{} artist:{}'.format(album_name, artist_name), type='album', limit=1)
albums = results['albums']['items']

# Get the album ID
album_id = None
if len(albums) > 0:
    album = albums[0]
    album_id = album['id']

if album_id:
    results = sp.album_tracks(album_id)
    tracks = results['items']
    tracklist = []

    for track in tracks:
        song_name = track['name']
        while True:
            user_input = int(input("On a scale from 1 to 10, rate the song '{}': ".format(song_name)))
            try:
                user_int = int(user_input)
                if user_int > 10 or user_int < 1:
                    print("Invalid input, please enter a number between 1 and 10")
                else:
                    tracklist.append([song_name, user_int])
                    break
            except ValueError:
                print("Invalid input, please enter a number between 1 and 10")
    k = int(input("How would you grade this album as a whole? (1-10) "))/2

else:
    print("No album was found with the given name and artist.")

def mgs(tllength):
    num = k
    for i in range(len(tracklist)):
        for j in range(len(tracklist[i])):
            num = num + int(tracklist[i][1])/2

    den = (10 * len(tracklist))
    score = num / den * 100
    score = min(100, round(score, 2))

    if score >= 95:
        return "'" + album_name + "', by " + artist_name + ", scored " + str(score) + "%, which is an A+. That's a Classic Album!"
    elif score >= 90:
        return "'" + album_name + "', by " + artist_name + ", scored " + str(
            score) + "%, which is an A. Not quite a Classic but an Honorable Mention!"
    elif score >= 85:
        return "'" + album_name + "', by " + artist_name + ", scored " + str(score) + "%, which is an A-. You Loved this album."
    elif score >= 80:
        return "'" + album_name + "', by " + artist_name + ", scored " + str(score) + "%, which is a B+. This is a Great album."
    elif score >= 76:
        return "'" + album_name + "', by " + artist_name + ", scored " + str(score) + "%, which is a B. This is a Good album."
    elif score >= 70:
        return "'" + album_name + "', by " + artist_name + ", scored " + str(score) + "%, which is a B-. You Liked this Album."
    elif score >= 65:
        return "'" + album_name + "', by " + artist_name + ", scored " + str(score) + "%, which is a C. This album is average."
    elif score >= 61:
        return "'" + album_name + "', by " + artist_name + ", scored " + str(
            score) + "%, which is a C-. This album is below Average"
    elif score >= 60:
        return "'" + album_name + "', by " + artist_name + ", scored " + str(score) + "%, which is a D. This album is not good."
    else:
        return "'" + album_name + "', by " + artist_name + ", scored " + str(score) + "%, or an F. This album is bad."

print(mgs(tracklist))

allgrades = open('albumgrades.txt', 'a+')
allgrades.write(mgs(tracklist) + '\n')
allgrades.close()

allgrades = open('albumgrades.txt', 'r')
ls = []
for l in allgrades.readlines():
    ls.append(l)
allgrades.close()

ls.sort()
allgrades = open('albumgrades.txt', 'w')
for i in ls:
    if '100' in i[:3]:
        allgrades.write(i)
ls.reverse()
for i in ls:
    if '100' not in i[:3]:
        allgrades.write(i)

allgrades.close()


import pygame
import random

WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
ORANGE = (255, 165, 0)
DEEPPINK = (255, 20, 147)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
DEEPSKYBLUE = (0, 191, 255)

pygame.init()

game_display = pygame.display.set_mode((800, 600))
pygame.display.set_caption('Snake Game')
clock = pygame.time.Clock()
key_type1 = [pygame.K_LEFT, pygame.K_RIGHT, pygame.K_UP, pygame.K_DOWN, pygame.K_RSHIFT]
key_type2 = [pygame.K_a, pygame.K_d, pygame.K_w, pygame.K_s, pygame.K_LSHIFT]

class Player:
    def __init__(self, display, color_head, color_body, keytype):
        self.display = display
        self.color_head = color_head
        self.color_body = color_body
        self.x = random.randint(0, 79) * 10
        self.y = random.randint(0, 59) * 10
        self.bef_x = -10
        self.bef_y = -10
        self.dx = 0
        self.dy = 0
        self.snake = []
        self.snake_len = 1
        self.key_type = keytype
        self.food_check = []

    def handle_event(self, event):
        if (event.type == pygame.KEYDOWN):
            if (event.key == self.key_type[0]):
                self.dx -= 10
                self.dy = 0
            elif (event.key == self.key_type[1]):
                self.dx += 10
                self.dy = 0
            elif (event.key == self.key_type[2]):
                self.dy -= 10
                self.dx = 0
            elif (event.key == self.key_type[3]):
                self.dy += 10
                self.dx = 0

    def handle_tick(self): # 실질적인 이동 함수
        self.bef_x = self.x
        self.bef_y = self.y
        self.x += self.dx
        self.y += self.dy
        self.snake_head = []
        self.snake_head.append(self.x)
        self.snake_head.append(self.y)
        self.snake.append(self.snake_head)
        if (len(self.snake) > self.snake_len):
            del self.snake[0]

    def draw(self):
        for x in self.snake:
            if (x == self.snake_head):
                pygame.draw.rect(self.display, self.color_head, [x[0], x[1], 10, 10])
            else:
                pygame.draw.rect(self.display, self.color_body, [x[0], x[1], 10, 10])

class Food:
    def __init__(self, display, color):
        self.x = random.randint(0, 79) * 10
        self.y = random.randint(0, 59) * 10
        self.active = True
        self.display = display
        self.color = color

    def draw(self):
        pygame.draw.rect(self.display, self.color, [self.x, self.y, 10, 10])

game_over = False

p1 = Player(game_display, DEEPPINK, ORANGE, key_type1)
p2 = Player(game_display, DEEPSKYBLUE, BLUE, key_type2)
foods = [Food(game_display, GREEN) for _ in range(20)]

while not game_over:
    game_display.fill(BLACK)

    for event in pygame.event.get():
        if (event.type == pygame.QUIT):
            game_over = True
            break
        p1.handle_event(event)
        p2.handle_event(event)

    if (p1.x < 0 or p1.x >= 800 or p1.y < 0 or p1.y >= 600):
        game_over = True
        break

    if (p2.x < 0 or p2.x >= 800 or p2.y < 0 or p2.y >= 600):
        game_over = True
        break

    for x in p1.snake[:-1]:
        if (x == p1.snake_head):
            game_over = True

    for x in p2.snake[:-1]:
        if (x == p2.snake_head):
            game_over = True

    for x in p1.snake:
        if (p2.snake_head == x):
            game_over = True

    for x in p2.snake:
        if (p1.snake_head == x):
            game_over = True

    p1.handle_tick()
    p2.handle_tick()
    p1.draw()
    p2.draw()

    pressed = pygame.key.get_pressed()
    if pressed[pygame.K_RSHIFT]:
        p1.handle_tick()
        p1.draw()

    elif pressed[pygame.K_LSHIFT]:
        p2.handle_tick()
        p2.draw()

    num = 0

    for food in foods:
        if food.active:
            food.draw()
            num += 1

    for food in foods:
        if p1.x == food.x and p1.y == food.y and food.active == True:
            food.active = False
            p1.snake_len += 1

            if (num <= 20):
                foods.append(Food(game_display, GREEN))

        elif p1.bef_x == food.x and p1.bef_y == food.y and food.active == True:
            food.active = False
            p1.snake_len += 1

            if (num <= 20):
                foods.append(Food(game_display, GREEN))

        elif p2.x == food.x and p2.y == food.y and food.active == True:
            food.active = False
            p2.snake_len += 1
            if (num <= 20):
                foods.append(Food(game_display, GREEN))

        elif p2.bef_x == food.x and p2.bef_y == food.y and food.active == True:
            food.active = False
            p2.snake_len += 1

            if (num <= 20):
                foods.append(Food(game_display, GREEN))

    if (num != 20):
        game_over = True

    pygame.display.update()
    clock.tick(10)


#!/usr/bin/env python

from skimage.metrics import structural_similarity as ssim
import numpy as np
import cv2
import argparse

def options():
 parser = argparse.ArgumentParser(description="Read image metadata")
 parser.add_argument("-o", "--first", help="Input image file.", required=True)
 parser.add_argument("-c", "--second", help="Input image file.", required=True)
 args = parser.parse_args()
 return args

def mse(imageA, imageB):
 # the 'Mean Squared Error' between the two images is the sum of the squared difference between the two images
 mse_error = np.sum((imageA.astype("float") - imageB.astype("float")) ** 2)
 mse_error /= float(imageA.shape[0] * imageA.shape[1])

 # return the MSE. The lower the error, the more "similar" the two images are.
 return mse_error

def compare(imageA, imageB):
 # Calculate the MSE and SSIM
 m = mse(imageA, imageB)
 s = ssim(imageA, imageB)

 # Return the SSIM. The higher the value, the more "similar" the two images are.
 return s

def main():

 # Get options
 args = options()

 # Import images
 image1 = cv2.imread(args.first)
 image2 = cv2.imread(args.second, 1)

 # Convert the images to grayscale
 gray1 = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)
 gray2 = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)

 # Check for same size and ratio and report accordingly
 ho, wo, _ = image1.shape
 hc, wc, _ = image2.shape
 ratio_orig = ho/wo
 ratio_comp = hc/wc
 dim = (wc, hc)

 if round(ratio_orig, 2) != round(ratio_comp, 2):
  print("\nImages not of the same dimension. Check input.")
  exit()

 # Resize first image if the second image is smaller
 elif ho > hc and wo > wc:
  print("\nResizing original image for analysis...")
  gray1 = cv2.resize(gray1, dim)

 elif ho < hc and wo < wc:
  print("\nCompressed image has a larger dimension than the original. Check input.")
  exit()

 if round(ratio_orig, 2) == round(ratio_comp, 2):
  mse_value = mse(gray1, gray2)
  ssim_value = compare(gray1, gray2)
  print("MSE:", mse_value)
  print("SSIM:", ssim_value)

if __name__ == '__main__':
    main()


from django.contrib.auth.models import User
from rest_framework import generics
from rest_framework.permissions import AllowAny
from .serializers import RegisterSerializer, UserSerializer
from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework.response import Response
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse, JsonResponse
from PIL import Image
from io import BytesIO
from rest_framework_simplejwt.views import TokenObtainPairView

class RegisterView(generics.CreateAPIView):
    """
    Lớp xử lý yêu cầu đăng ký người dùng mới.

    Tham số:
    - generics.CreateAPIView: Lớp cho phép tạo đối tượng mới.

    Thuộc tính:
    - queryset: Queryset của tất cả các đối tượng User trong cơ sở dữ liệu.
    - permission_classes: Danh sách các lớp cho phép xác định ai được phép truy cập API. Ở đây, tất cả các người dùng đều được phép truy cập.
    - serializer_class: Lớp Serializer để sử dụng cho yêu cầu đăng ký mới.

    Trả về:
    - Trả về một đối tượng User mới được tạo ra dưới dạng đối tượng JSON được mã hóa bởi RegisterSerializer và mã trạng thái HTTP 201 nếu thành công.

    Cách sử dụng:
    - Sử dụng lớp RegisterSerializer để phân tích cú pháp yêu cầu đăng ký và tạo một đối tượng User mới.
    - Trả về một đối tượng JsonResponse chứa đối tượng User mới nếu thành công.
    """
    queryset = User.objects.all()
    permission_classes = [AllowAny]
    serializer_class = RegisterSerializer

class AdminTokenObtainPairView(TokenObtainPairView):
    """
    Lớp xử lý yêu cầu truy xuất mã thông báo truy cập (access token và refresh token) cho người dùng quản trị.

    Tham số:
    - TokenObtainPairView: Lớp xử lý yêu cầu truy xuất mã thông báo truy cập.

    Phương thức:
    - post: Phương thức xử lý yêu cầu POST để truy xuất mã thông báo truy cập.

    Trả về:
    - Trả về một đối tượng Response với mã trạng thái HTTP 403 nếu người dùng không có quyền truy cập tài nguyên.
    - Trả về một đối tượng Response với mã trạng thái HTTP và thông tin mã thông báo truy cập.

    Cách sử dụng:
    - Lấy mã thông báo truy cập được trả về bởi phương thức POST.
    - Sử dụng mã thông báo truy cập để xác thực người dùng và trả về thông tin về mã thông báo truy cập.
    - Kiểm tra xem người dùng có quyền truy cập tài nguyên hay không. Nếu không có, trả về một đối tượng Response với mã trạng thái HTTP 403.
    """
    def post(self, request, *args, **kwargs):
        response = super().post(request, *args, **kwargs)
        token = response.data.get('access')
        if token:
            username = request.data.get('username')
            user = User.objects.get(username=username)
            response.data['role'] = 1
            if not user.is_superuser:
                return Response({'detail': 'You do not have permission to access this resource.'}, status=403)
        return response

class UserTokenObtainPairView(TokenObtainPairView):
    """
    Lớp xử lý yêu cầu truy xuất mã thông báo truy cập cho người dùng.

    Tham số:
    - TokenObtainPairView: Lớp xử lý yêu cầu truy xuất mã thông báo truy cập.

    Phương thức:
    - post: Phương thức xử lý yêu cầu POST để truy xuất mã thông báo truy cập.

    Trả về:
    - Trả về một đối tượng Response với mã trạng thái HTTP 403 nếu tài khoản của người dùng bị khóa hoặc người dùng không phải là khách hàng.
    - Trả về một đối tượng Response với mã trạng thái HTTP và thông tin mã thông báo truy cập.

    Cách sử dụng:
    - Lấy mã thông báo truy cập được trả về bởi phương thức POST.
    - Sử dụng mã thông báo truy cập để xác thực người dùng và trả về thông tin về mã thông báo truy cập.
    - Kiểm tra xem tài khoản của người dùng có bị khóa hay không hoặc người dùng có phải là khách hàng hay không. Nếu không phải, trả về một đối tượng Response với mã trạng thái HTTP 403.
    """
    def post(self, request, *args, **kwargs):
        response = super().post(request, *args, **kwargs)
        token = response.data.get('access')
        if token:
            username = request.data.get('username')
            user = User.objects.get(username=username)
            response.data['role'] = 0
            if not user.is_active:
                return Response({'detail': 'Your account has locked.'}, status=403)
            if user.is_superuser:
                return Response({'detail': 'Your account is not access as customer.'}, status=403)
        return response

class UserInfoView(APIView):
    """
    Lớp xử lý yêu cầu để lấy thông tin người dùng và cập nhật thông tin người dùng.

    Thuộc tính:
    - permission_classes: Danh sách các lớp cho phép xác định ai được phép truy cập API. Ở đây, chỉ người dùng đã xác thực mới được phép truy cập.
    - authentication_classes: Danh sách các lớp xác thực được sử dụng để xác thực yêu cầu. Ở đây, chúng tôi sử dụng JWTAuthentication để xác thực mã thông báo truy cập.

    Phương thức:
    - get: Phương thức xử lý yêu cầu GET để lấy thông tin người dùng.
    - post: Phương thức xử lý yêu cầu POST để cập nhật thông tin người dùng.

    Trả về:
    - Trả về một đối tượng JsonResponse chứa thông tin người dùng hoặc thông tin lỗi nếu yêu cầu không hợp lệ.

    Cách sử dụng:
    - Lấy thông tin người dùng bằng cách sử dụng đối tượng HttpRequest và trả về một đối tượng JsonResponse chứa thông tin người dùng.
    - Cập nhật thông tin người dùng bằng cách sử dụng đối tượng HttpRequest và serializer, sau đó trả về một đối tượng JsonResponse chứa thông tin người dùng mới nếu thành công hoặc một đối tượng JsonResponse chứa thông tin lỗi nếu yêu cầu không hợp lệ.
    """
    permission_classes = [IsAuthenticated]
    authentication_classes = [JWTAuthentication]

    def get(self, request):
        user = request.user
        info = User.objects.get(pk=user.id)
        serializer = RegisterSerializer(info)

        return JsonResponse(
            serializer.data, safe=False
        )
    def post(self, request):
        user = request.user
        info = User.objects.get(pk=user.id)
        serializer = UserSerializer(info, data=request.data, partial=True)

        if serializer.is_valid():
            image_data = request.FILES.get('avatar')
            if image_data:
                info.avatar_url.save(image_data.name, image_data)

            serializer.save()

            return JsonResponse(
                serializer.data, safe=False, status=200
            )
        else:
            return JsonResponse(
                serializer.errors, status=400)


from typing import List, Type

import numpy as np
from pyrep.const import RenderMode
from pyrep.errors import ConfigurationPathError, IKError
from pyrep.objects import Dummy, VisionSensor
from rlbench import ObservationConfig
from rlbench.action_modes.action_mode import MoveArmThenGripper
from rlbench.action_modes.arm_action_modes import JointPosition, JointVelocity
from rlbench.action_modes.gripper_action_modes import Discrete
from rlbench.backend.exceptions import InvalidActionError
from rlbench.backend.observation import Observation
from rlbench.backend.task import Task
from rlbench.backend.utils import task_file_to_task_class
from yarr.agents.agent import ActResult, VideoSummary
from yarr.envs.rlbench_env import RLBenchEnv
from yarr.utils.observation_type import ObservationElement
from yarr.utils.transition import Transition

RECORD_EVERY = 20

class KeypointEnvironment(RLBenchEnv):
    def __init__(
        self,
        task_class,
        action_mode,
        obs_config,
        headless,
    ):
        super(KeypointEnvironment, self).__init__(
            task_class=task_class,
            observation_config=obs_config,
            action_mode=action_mode,
            headless=headless,
            channels_last=True,
        )
        self._previous_obs_dict = None

    @property
    def observation_elements(self) -> List[ObservationElement]:
        obs_elems = super(KeypointEnvironment, self).observation_elements
        for oe in obs_elems:
            if oe.name == "low_dim_state":
                oe.shape = (
                    oe.shape[0] - 7 * 2,
                )  # remove pose and joint velocities as they will not be included
                self.low_dim_state_len = oe.shape[0]
        obs_elems.append(ObservationElement("gripper_pose", (7,), np.float32))
        # obs_elems.append(
        #     ObservationElement("gripper_joint_positions", (2,), np.float32)
        # )
        # obs_elems.append(ObservationElement("joint_velocities", (7,), np.float32))
        # obs_elems.append(ObservationElement("joint_positions", (7,), np.float32))
        return obs_elems

    def extract_obs(self, obs: Observation):
        joint_vel = obs.joint_velocities
        obs.joint_velocities = None
        grip_mat = obs.gripper_matrix
        grip_pose = obs.gripper_pose
        joint_pos = obs.joint_positions
        obs.gripper_matrix = None
        obs.wrist_camera_matrix = None
        obs.joint_positions = None
        if obs.gripper_joint_positions is not None:
            obs.gripper_joint_positions = np.clip(
                obs.gripper_joint_positions, 0.0, 0.04
            )

        obs_dict = super(KeypointEnvironment, self).extract_obs(obs)

        obs.gripper_matrix = grip_mat
        obs.joint_positions = joint_pos

        obs_dict["gripper_joint_positions"] = obs.gripper_joint_positions
        obs_dict["gripper_pose"] = grip_pose
        obs_dict["joint_velocities"] = joint_vel
        obs_dict["joint_positions"] = joint_pos
        return obs_dict

    def launch(self):
        super(KeypointEnvironment, self).launch()

    def reset(self):
        self._previous_obs_dict = super(KeypointEnvironment, self).reset()
        return self._previous_obs_dict

    def register_callback(self, func):
        self._task._scene.register_step_callback(func)

    def step(self, action):
        success = False
        obs = self._previous_obs_dict  # in case action fails.

        try:
            obs, reward, terminal = self._task.step(action)
            if reward >= 1:
                success = True
            else:
                reward = 0.0
            obs = self.extract_obs(obs)
            self._previous_obs_dict = obs
        except (IKError, ConfigurationPathError, InvalidActionError) as e:
            terminal = True
            reward = 0.0

        return obs, reward, terminal, success

if __name__ == "__main__":
    task = task_file_to_task_class("reach_target")
    env = KeypointEnvironment(
        task, MoveArmThenGripper(JointPosition(), Discrete()), ObservationConfig(), True
    )
    env.launch()
    env._task.set_variation(0)
    obs = env.reset()


from typing import Dict, List, Optional, Union, Tuple

import aiohttp

from omni.services.browser.asset import BaseAssetStore, AssetModel, SearchCriteria, ProviderModel
from .constants import SETTING_STORE_ENABLE
from pathlib import Path

CURRENT_PATH = Path(__file__).parent
DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("data")

# The name of your company
PROVIDER_ID = "PROVIDER_NAME"
# The URL location of your API
STORE_URL = "https://www.your_store_url.com"

class TemplateAssetProvider(BaseAssetStore):
    """
        Asset provider implementation.
    """

    def __init__(self, ov_app="Kit", ov_version="na") -> None:
        super().__init__(PROVIDER_ID)
        self._ov_app = ov_app
        self._ov_version = ov_version

    async def _search(self, search_criteria: SearchCriteria) -> Tuple[List[AssetModel], bool]:
        """ Searches the asset store.

            This function needs to be implemented as part of an implementation of the BaseAssetStore.
            This function is called by the public `search` function that will wrap this function in a timeout.
        """
        params = {}

        # Setting for filter search criteria
        if search_criteria.filter.categories:
            # No category search, also use keywords instead
            categories = search_criteria.filter.categories
            for category in categories:
                if category.startswith("/"):
                    category = category[1:]
                category_keywords = category.split("/")
                params["filter[categories]"] = ",".join(category_keywords).lower()

        # Setting for keywords search criteria
        if search_criteria.keywords:
            params["keywords"] = ",".join(search_criteria.keywords)

        # Setting for page number search criteria
        if search_criteria.page.number:
            params["page"] = search_criteria.page.number

        # Setting for max number of items per page
        if search_criteria.page.size:
            params["page_size"] = search_criteria.page.size

        items = []

        # TODO: Uncomment once valid Store URL has been provided
        # async with aiohttp.ClientSession() as session:
        #     async with session.get(f"{STORE_URL}", params=params) as resp:
        #         result = await resp.read()
        #         result = await resp.json()
        #         items = result

        assets: List[AssetModel] = []

        # Create AssetModel based off of JSON data
        for item in items:
            assets.append(
                AssetModel(
                    identifier="",
                    name="",
                    published_at="",
                    categories=[],
                    tags=[],
                    vendor=PROVIDER_ID,
                    product_url="",
                    download_url="",
                    price=0.0,
                    thumbnail="",
                )
            )

        # Are there more assets that we can load?
        more = True
        if search_criteria.page.size and len(assets) < search_criteria.page.size:
            more = False

        return (assets, more)

    def provider(self) -> ProviderModel:
        """Return provider info"""
        return ProviderModel(
            name=PROVIDER_ID, icon=f"{DATA_PATH}/logo_placeholder.png", enable_setting=SETTING_STORE_ENABLE
        )


import astropy.io.fits as fits
import astropy.io.votable.treeFits as vo
import glob
import os
import numpy as np

def str_max(string, length):
  len_str = len(string)
  if len_str > length:
    return len_str
  else:
    return length

def hdu_unpack(hdu_header):
  hdu_dict = dict( hdu_header )
  hdu_keys = list( set(hdu_dict.keys()) )
  hdu_keys.remove('')
  hdu_keys.remove('HISTORY')
  hdu_keys.remove('COMMENT')
  hdu_keys.sort()
  # table.create_arrays( len(hdu_keys) )
  hdu_list = []

  key_len = 0
  val_len = 0
  com_len = 0

  for i in range( len(hdu_keys) ):
    k = hdu_keys[i]
    v = hdu_header[k]
    v_type = type(v).__name__
    com = hdu_header.comments[k]
    # if com:
    #   com='None'

    key_len = str_max(str(k), key_len)
    com_len = str_max( str(com), com_len )

    if (v_type=='int') or (v_type=='float'):
      hdu_list.append([k, str(v), '', com])
    else:
      hdu_list.append([k, '', str(v), com])
      val_len = str_max( str(v), val_len)

  return hdu_list, str(key_len)+'*', str(val_len)+'*', str(com_len)+'*'

fitsList = glob.glob('./TWHYA_BAND7/*.fits')
fits0 = fitsList[0]
fits_nm = fits0.rsplit('/',1)[-1]
fits_pre = fits_nm.rsplit('.',1)[-2]
# print(fits_pre)

hdu = fits.open(fits0)[0]

votable = vo.VOTableFile(version='1.2')

resource = vo.Resource()

votable.resources.append(resource)

table = vo.Table(votable)
resource.tables.append(table)
table.description = fits_pre

# h0 = hdu[0]
# hdu_dict = dict(hdu.header)

hdu_list, klen, vlen, clen = hdu_unpack(hdu.header)
# print(klen, vlen, clen)

field0 = vo.Field(votable, name='key', datatype='char', arraysize=klen)
field1 = vo.Field(votable, name='value_float', datatype='double')
field2 = vo.Field(votable, name='value_str', datatype='char', arraysize=vlen)#str(vlen)+'*')
field3 = vo.Field(votable, name='comments', datatype='char', arraysize=clen)#str(clen)+'*')
table.fields.append(field0)
table.fields.append(field1)
table.fields.append(field2)
table.fields.append(field3)

# table.array = hdu_arr
# hdu_arr = hdu_arr.copy(order='C')
table.para_array = hdu_list
# print(hdu_arr)
# row = hdu_arr.shape[0]
# table.create_arrays(row)
# for i in range(row):
  # table.array[i] = hdu_arr[i]

# print(table.array)

table.format = 'fits'

if( os.path.exists(fits0)):
  table.set_href('file://' + os.path.abspath(fits0))

votable.to_xml(fits_pre+'4.xml')