import sys
std_deduction = 50000
taxable_hra = 0
while True:
    print("\n T A X   C A L C U L A T O R \n")
    tax_option = int(input('''Enter the tax regime you would like to opt for:
            1 - FY 2019-20
            2 - FY 2020-21
            Your Choice :   '''))
    if tax_option > 2 or tax_option <= 0:
        print("Invalid Choice")
        break
    else:

        print("INCOME : ")
        print("--------------------------------------------------------------")
        ctc = float(input("\tEnter your CTC : "))
        print("\n")
        basic = 0.4 * ctc

        if tax_option == 1:
            print("HRA : ")
            print("--------------------------------------------------------------")
            hra_recieved = float(input("\tEnter HRA recieved per annum : "))
            rent = float(input("\tEnter Total Rent paid per annum : "))
            city = int(input('''\tAre you from Metropolitan City ? :
                                Press 1 for YES
                                Press 2 for NO
                                Your Choice : '''))
            print("\n")
            # HRA can be claimed in three ways
            # 1. Rent - 10% of basic
            # 2. Actual HRA
            # 3. 50% or 40% of basic
            # Select lowest one
            hra_1 = rent - 0.1 * basic
            hra_2 = hra_recieved
            if city == 1:
                hra_3 = 0.5 * basic
            else:
                hra_3 = 0.4 * basic
                min_hra = min(hra_1, hra_2, hra_3)
                if min_hra <= 0:
                    taxable_hra = hra_recieved
                else:
                    taxable_hra = min_hra

            print("DEDUCTIONS : ")
            print("--------------------------------------------------------------")
            # taking only EPF and Investments under 80C along with home loan
            EPF = float(input("\tEnter EPF : "))
            i80C = float(input("\tEnter Investments under 80C : "))
            i80D = float(input("\tEnter Investments under 80D : "))
            i80 = float(input("\tEnter Investments under sec 80 (other than C and D and E) : "))
            home_loan = float(input("\tEnter Home Loan: "))
            education_loan = float(input("\tEnter Education Loan Interest amount: "))
            print("\n")
            if EPF + i80C >= 150000:  # max allowance is 1.5 lakhs
                if home_loan >= 200000: #max allowance is 2 lakhs
                    if i80D >= 150000:
                        if i80 >= 100000:
                            deductions = 600000 + education_loan
                        else:
                            deductions = 500000 + i80 + education_loan
                    else:
                        if i80 >= 100000:
                            deductions = 450000 + i80D + education_loan
                        else:
                            deductions = 350000 + i80 + i80D + education_loan
                else:
                    if i80D >= 150000:
                        if i80 >= 100000:
                            deductions = 400000 + home_loan + education_loan
                        else:
                            deductions = 300000 + i80 + home_loan + education_loan
                    else:
                        if i80 >= 100000:
                            deductions = 250000 + home_loan + i80D + education_loan
                        else:
                            deductions = 150000 + home_loan + i80D + i80 + education_loan
            else:
                if home_loan >= 200000:
                    if i80D >= 150000:
                        if i80 >= 100000:
                            deductions = EPF + i80C + 450000 + education_loan
                        else:
                            deductions = EPF + i80C + 350000 + i80 + education_loan
                    else:
                        if i80 >= 100000:
                            deductions = EPF + i80C + i80D + 300000 + education_loan
                        else:
                            deductions = EPF + i80C + i80D + i80 + 200000 + education_loan
                else:
                    if i80D >= 150000:
                        if i80 >= 100000:
                            deductions = EPF + i80C + home_loan + 250000 + education_loan
                        else:
                            deductions = EPF + i80C + i80D + home_loan + i80 + 150000 + education_loan
                    else:
                        if i80 >= 100000:
                            deductions = EPF + i80C + i80D + home_loan + 100000 + education_loan
                        else:
                            deductions = EPF + i80C + i80D + home_loan + i80 + education_loan

            # gross salary = ctc - (EPF + gratuity)
            # there is no gratuity
            gross_salary = ctc - EPF
            # calculating total taxable income (also known as Gross Taxable income)
            # Taxable Income = Gross Salary – Section 80C deduction – Standard Deduction – HRA – Professional Tax
            # There is no professional tax
            taxable_income = gross_salary - std_deduction - taxable_hra - (deductions - EPF)
            # Calculating Tax
            # Tax Slab for fy 2019-20
            if taxable_income < 250000:
                final_tax = 0
            elif 250000 < taxable_income < 500000:
                tax = 0.05 * (taxable_income - 250000)
                final_tax = tax + (0.04 * tax)
            elif 500000 < taxable_income < 1000000:
                tax = 12500 + (0.2 * (taxable_income - 500000))
                final_tax = tax + (0.04 * tax)
            elif 1000000 < taxable_income < 5000000:
                tax = 112500 + (0.312 * (taxable_income - 1000000))
                final_tax = tax + (0.04 * tax)
            elif 5000000 < taxable_income < 10000000:
                tax = 112500 + (0.3432 * (taxable_income - 1000000))
                final_tax = tax + (0.04 * tax)

        if tax_option == 2:
            print("HRA : ")
            print("--------------------------------------------------------------")
            hra_recieved = 0.0
            rent = 0.0
            city = 0
            print("You will not get HRA or rent!!!")
            print("\n")
            taxable_hra = hra_recieved
            print("DEDUCTIONS : ")
            print("--------------------------------------------------------------")
            EPF = float(input("\tEnter EPF : "))
            i80C = float(input("\tEnter Investments under 80C : "))
            i80D = float(input("\tEnter Investments under 80D : "))
            home_loan = float(input("\tEnter Home Loan: "))
            print("There will be NO deductions on EPF, Ivestments under 80C or home loan!")
            print("\n")
            deductions = 0.0

            # gross salary = ctc - (EPF + gratuity)
            # there is no gratuity
            gross_salary = ctc - EPF
            # calculating total taxable income (also known as Gross Taxable income)
            # Taxable Income = Gross Salary – Section 80C deduction – Standard Deduction – HRA – Professional Tax
            # There is no professional tax
            taxable_income = gross_salary - taxable_hra
            # Calculating Tax
            # Tax slab for fy 2020-21
            if taxable_income < 250000:
                final_tax = 0
            elif 250000 < taxable_income < 500000:
                tax = 0.05 * (taxable_income - 250000)
                final_tax = tax + (0.04 * tax)
            elif 500000 < taxable_income < 750000:
                tax = 25000 + (0.104 * (taxable_income - 500000))
                final_tax = tax + (0.04 * tax)
            elif 750000 < taxable_income < 1000000:
                tax = 37500 + (0.156 * (taxable_income - 750000))
                final_tax = tax + (0.04 * tax)
            elif 1000000 < taxable_income < 1250000:
                tax = 62500 + (0.208 * (taxable_income - 1000000))
                final_tax = tax + (0.04 * tax)
            elif 1250000 < taxable_income < 1500000:
                tax = 75000 + (0.26 * (taxable_income - 1250000))
                final_tax = tax + (0.04 * tax)
            elif 1500000 < taxable_income < 5000000:
                tax = 75000 + (0.312 * (taxable_income - 1500000))
                final_tax = tax + (0.04 * tax)
            elif 5000000 < taxable_income < 10000000:
                tax = 85800 + (0.3432 * (taxable_income - 1500000))
                surcharge = 1.1 * tax
                final_tax = surcharge + (0.04 * tax)

        print("FINAL REPORT : ")
        print("--------------------------------------------------------------")
        print("\t\tBASIC INCOME : ", basic)
        print("\t\tGROSS SALARY:", gross_salary)
        print("\t\tHRA EXEMPTION : ", taxable_hra)
        print("\t\tTAXABLE INCOME : ", taxable_income)
        print("\t\tT A X : ", int(final_tax))
        # Take Home Salary = Gross Salary – (Income Tax + Professional Tax)
        print("\t\tTAKE-HOME SALARY : ", gross_salary - final_tax)
        print("\n")

        while True:
            choice = int(input('''Press 1 to Calculate again\nPress 2 to Exit '''))
            if choice == 1:
                break
            elif choice == 2:
                sys.exit()
            else:
                print("Invalid Choice")
                continue


from rsf.proj import *

Flow('spike',None,
     '''
     spike n1=129 n2=129 n3=129 d1=0.004 d2=0.008 d3=0.008
     nsp=3 k1=50,75,100 k2=50,75,100 k3=50,75,100 |
     bandpass flo=10 fhi=50
     ''')

Flow('fft3','spike','cosft sign2=1 sign3=1')

# Loop over interpolation lengths
for nf in [2,4,8]:
    stolt = 'stolt%d' % nf
    Flow(stolt,'fft3',
              'stolt2 nf=%d vel=2 | cosft sign2=-1 sign3=-1' % nf)
    Plot(stolt+'-depth',stolt,
              '''window n1=1 f1=30 |
              grey title="Stolt migration %d: Depth slice"
              screenratio=1 screenht=12''' % nf)
    Plot(stolt+'-line',stolt,
              '''window n2=1 f2=64 |
              grey title="Stolt migration %d: In-line slice"
              screenratio=0.5 screenht=6''' % nf)
    Plot(stolt,[stolt+'-line',stolt+'-depth'],'OverUnderAniso')

Result('stolt','stolt2 stolt8','SideBySideAniso')

End()


from hitchbuildpg.server import PostgresServer
from commandlib import Command
from path import Path
import hitchbuild

class PostgresDatafiles(hitchbuild.HitchBuild):
    def __init__(self, build_path, postgresapp, databuild):
        self.buildpath = Path(build_path).abspath()
        self._databuild = databuild
        self.fingerprint_path = self.buildpath / "fingerprint.txt"
        self.postgresapp = self.dependency(postgresapp)

    @property
    def workingpath(self):
        return self.buildpath / "working"

    @property
    def snapshotpath(self):
        return self.buildpath / "snapshot"

    @property
    def postgres(self):
        return self.postgresapp.build.bin.postgres.with_trailing_args(
            "-D",
            self.workingpath,
            "--unix_socket_directories={0}".format(self.workingpath),
            "--log_destination=stderr",
        )

    @property
    def psql(self):
        return self.postgresapp.build.bin.psql("--host", self.workingpath)

    def server(self):
        return PostgresServer(self)

    def build(self):
        if self.incomplete() or self.postgresapp.rebuilt:
            self.postgresapp.build.ensure_built()
            self.buildpath.rmtree(ignore_errors=True)
            self.buildpath.mkdir()
            self.workingpath.mkdir()
            self.snapshotpath.mkdir()
            self.postgresapp.build.bin.initdb(self.workingpath).run()
            self._databuild.from_datafiles(self).build()
            self._rsync(self.workingpath, self.snapshotpath)
            self.refingerprint()
        else:
            self._rsync(self.snapshotpath, self.workingpath)

    def _rsync(self, from_path, to_path):
        Command("rsync")(
            "--del",
            "-av",
            # Trailing slash so contents are moved not whole dir
            from_path + "/",
            to_path,
        ).run()

    def clean(self):
        if self.buildpath.exists():
            self.buildpath.rmtree()


import torch

config = {
    'PongNoFrameskip-v4'      : ('models/pong.pth'     , 10 ** 5),
    'FreewayNoFrameskip-v4'   : ('models/freeway.pth'  , 10 ** 5),
    'KrullNoFrameskip-v4'     : ('models/krull.pth'    , 4 * 10 ** 5),
    'AtlantisNoFrameskip-v4'  : ('models/atlantis.pth' , 4 * 10 ** 5),
    'TutankhamNoFrameskip-v4' : ('models/tutankham.pth', 10 ** 5)
}

def initial_state(screen):
    CHANNEL_NUM, height, width = 4, 84, 84
    state = torch.cat(tuple(torch.tensor(screen) for _ in range(CHANNEL_NUM)))
    return state.reshape(1, CHANNEL_NUM, height, width)

def get_next_state(state, screen):
    CHANNEL_NUM, height, width = 4, 84, 84
    next_state = torch.zeros(1, CHANNEL_NUM, height, width, dtype=torch.uint8)
    next_state[:, :CHANNEL_NUM-1, :, :] = state[:, 1:, :, :]
    next_state[0][CHANNEL_NUM-1] = torch.from_numpy(screen.reshape(height, width))
    return next_state

class Agent(object):
    def __init__(self, model_file):
        self.state = None
        self.policy_net = torch.load(model_file).to('cuda')

    def act(self, state):
        if self.state is None:
            self.state = initial_state(state)
        else:
            self.state = get_next_state(self.state, state)

        return self.policy_net(self.state.to('cuda')).max(1)[1].item()

def make_agent(env_id):
    model_file, frame_num = config[env_id]
    return Agent(model_file), frame_num


import json

from flask import jsonify, request, current_app
from flask.views import MethodView

from . import books
from .models import Publisher
from .serializers import pub_schema, pubs_schema
from books.app import db

# crud
##########
# Publishers
##########

# list
@books.route('/api/publishers', methods=['GET'])
def get_publishers():
    query = Publisher.query.all()
    result = pubs_schema.dump(query)
    return jsonify(result.data)
    # return query

@books.route('/api/publishers_uc', methods=['GET'])
def get_publishers_uc():
    query = Publisher.query.all()
    result = pubs_schema.dump(query)
    return jsonify(result.data)

# get
@books.route('/api/publishers/<int:id>', methods=['GET'])
def get_publisher(id):
    query = Publisher.query.filter_by(id=id).first()
    result = pub_schema.dump(query)
    return jsonify(result.data)
    # TODO add not found exception

# add
@books.route('/api/publishers/add', methods=['POST'])
def create_publisher(**kwargs):
    # TODO check for duplicate b4 adding to db
    name = request.json['name']
    # email = request.json['email']

    new_pub = Publisher(name, **kwargs)

    db.session.add(new_pub)
    db.session.commit()

    result = pub_schema.dump(new_pub).data
    return jsonify(result)

# update
@books.route('/api/publishers/edit/<int:id>', methods=['PUT'])
def update_publisher(id):
    pub = Publisher.query.filter_by(id=id).first()

    name = request.json['name']
    # email = request.json['email']

    pub.name = name

    db.session.commit()

    result = pub_schema.dump(pub).data
    return jsonify(result)

# delete
@books.route('/api/publishers/del/<int:id>', methods=('DELETE',))
# @jwt_required()
def delete_publisher(id):
    pub = Publisher.query.filter_by(id=id).first()
    db.session.delete(pub)
    db.session.commit()
    return 'Deleted', 200

##########
# Authors
##########

##########
# Books
##########


import json
import logging
import os
import time

from datalad.interface.base import Interface
from datalad.interface.base import build_doc
from datalad.interface.results import get_status_dict
from datalad.support.exceptions import (
    CapturedException,
    InvalidGitRepositoryError,
    MissingExternalDependency,
)

__docformat__ = "restructuredtext"

lgr = logging.getLogger("datalad.local.check_dates")

def _git_repos(paths):
    for path in paths:
        for root, dirs, _ in os.walk(path):
            if any(d == ".git" for d in dirs):
                yield root

def _parse_date(date):
    if date.startswith("@"):  # unix timestamp
        timestamp = int(date[1:])
    else:
        try:
            import dateutil.parser
        except ImportError:
            raise MissingExternalDependency(
                "python-dateutil",
                msg="This package is required to parse non-timestamp dates")

        from calendar import timegm
        # Note: datetime.timestamp isn't available in Python 2.
        try:
            timestamp = timegm(dateutil.parser.parse(date).utctimetuple())
        except TypeError as exc:
            # Make older dateutil versions return a consistent error for
            # invalid dates.
            raise ValueError(exc)
    return timestamp

@build_doc
class CheckDates(Interface):
    """Find repository dates that are more recent than a reference date.

    The main purpose of this tool is to find "leaked" real dates in
    repositories that are configured to use fake dates. It checks dates from
    three sources: (1) commit timestamps (author and committer dates), (2)
    timestamps within files of the "git-annex" branch, and (3) the timestamps
    of annotated tags.
    """
    from datalad.interface.base import eval_results
    import datalad.support.ansi_colors as ac
    from datalad.support.constraints import EnsureChoice, EnsureNone, EnsureStr
    from datalad.support.param import Parameter

    result_renderer = "tailored"

    @staticmethod
    def custom_result_renderer(res, **kwargs):
        """Like 'json_pp', but skip non-error results without flagged objects.
        """
        # FIXME: I think the proper way to do this is to use 'result_filter',
        # but I couldn't seem to get eval_results to detect the filter when I
        # used
        #
        #      result_renderer = "json_pp"
        #      result_filter = lambda x: ...
        #
        # Also, I want to keep the "message" key for errors.
        from datalad.ui import ui
        to_render = {}
        if res["status"] == "error":
            to_render = dict(res.items())
        elif "report" in res and res["report"]["objects"]:
            to_render = {k: v for k, v in res.items()
                         if k not in ["status", "message", "logger"]}
        if to_render:
            ui.message(json.dumps(to_render, sort_keys=True, indent=2,
                                  default=str)
                       )

    _params_ = dict(
        paths=Parameter(
            args=("paths",),
            metavar="PATH",
            nargs="*",
            doc="""Root directory in which to search for Git repositories. The
            current working directory will be used by default.""",
            constraints=EnsureStr() | EnsureNone()),
        reference_date=Parameter(
            args=("-D", "--reference-date"),
            metavar="DATE",
            doc="""Compare dates to this date. If dateutil is installed, this
            value can be any format that its parser recognizes. Otherwise, it
            should be a unix timestamp that starts with a "@". The default
            value corresponds to 01 Jan, 2018 00:00:00 -0000.""",
            constraints=EnsureStr()),
        revs=Parameter(
            args=("--rev",),
            dest="revs",
            action="append",
            metavar="REVISION",
            doc="""Search timestamps from commits that are reachable from [PY:
            these revisions PY][CMD: REVISION CMD]. Any revision specification
            supported by :command:`git log`, including flags like --all and
            --tags, can be used.[CMD:  This option can be given multiple times.
            CMD]"""),
        annex=Parameter(
            args=("--annex",),
            doc="""Mode for "git-annex" branch search. If 'all', all blobs
            within the branch are searched. 'tree' limits the search to blobs
            that are referenced by the tree at the tip of the branch. 'none'
            disables search of "git-annex" blobs.""",
            constraints=EnsureChoice("all", "tree", "none")),
        no_tags=Parameter(
            args=("--no-tags",),
            action="store_true",
            doc="""Don't check the dates of annotated tags."""),
        older=Parameter(
            args=("--older",),
            action="store_true",
            doc="""Find dates which are older than the reference date rather
            than newer."""),
    )

    @staticmethod
    @eval_results
    def __call__(paths,
                 *,
                 reference_date="@1514764800",
                 revs=None,
                 annex="all",
                 no_tags=False,
                 older=False):
        from datalad.support.repodates import check_dates

        which = "older" if older else "newer"

        try:
            ref_ts = _parse_date(reference_date)
        except ValueError as exc:
            lgr.error("Could not parse '%s' as a date", reference_date)
            ce = CapturedException(exc)
            yield get_status_dict("check_dates",
                                  status="error",
                                  message=str(ce),
                                  exception=ce)
            return

        lgr.info("Searching for dates %s than %s",
                 which,
                 time.strftime("%d %b %Y %H:%M:%S +0000", time.gmtime(ref_ts)))

        for repo in _git_repos(paths or ["."]):
            fullpath = os.path.abspath(repo)
            lgr.debug("Checking %s", fullpath)

            try:
                report = check_dates(repo,
                                     ref_ts,
                                     which=which,
                                     revs=revs or ["--all"],
                                     annex={"all": True,
                                            "none": False,
                                            "tree": "tree"}[annex],
                                     tags=not no_tags)
            except InvalidGitRepositoryError as exc:
                lgr.warning("Skipping invalid Git repo: %s", repo)
                continue

            yield get_status_dict(
                "check_dates",
                status="ok",
                path=fullpath,
                message=("Found {} dates" if report["objects"]
                         else "No {} dates found").format(which),
                report=report)


import tensorflow as tf

def train_step(args, model, optimizer, train_ds, epoch, loss_object, train_summary_writer, train_loss, train_accuracy):
    for step, (images, labels) in enumerate(train_ds):
        with tf.GradientTape() as tape:
            # training=True is only needed if there are layers with different
            # behavior during training versus inference (e.g. Dropout).
            predictions = model(images, training=True)
            loss = loss_object(labels, predictions)
            gradients = tape.gradient(loss, model.trainable_variables)
            optimizer.apply_gradients(zip(gradients, model.trainable_variables))
            train_loss(loss)
            train_accuracy(labels, predictions)
        if step % args.log_interval == 0:
            print("Epoch: {} \t\ntrain_loss={:.4f}\ntrain_accuracy={:.4f}\n".format(
                epoch + 1,
                train_loss.result(), train_accuracy.result() * 100)
            )
    with train_summary_writer.as_default():
        tf.summary.scalar('train_loss', train_loss.result(), step=epoch)
        tf.summary.scalar('train_accuracy', train_accuracy.result(), step=epoch)

def test_step(model, test_ds, epoch, loss_object, test_summary_writer, test_loss, test_accuracy):
    for (images, labels) in test_ds:
        # training=False is only needed if there are layers with different
        # behavior during training versus inference (e.g. Dropout).
        predictions = model(images, training=False)
        t_loss = loss_object(labels, predictions)
        test_loss(t_loss)
        test_accuracy(labels, predictions)
    with test_summary_writer.as_default():
        tf.summary.scalar('val_loss', test_loss.result(), step=epoch)
        tf.summary.scalar('val_accuracy', test_accuracy.result(), step=epoch)
    print("val_loss={:.4f}\nval_accuracy={:.4f}\n".format(
        test_loss.result(), test_accuracy.result() * 100)
    )


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

MAX_VAL = 1e4

class PointWiseFeedForward(nn.Module):
    def __init__(self, hidden_units, dropout_rate):

        super(PointWiseFeedForward, self).__init__()

        self.conv1 = nn.Conv1d(hidden_units, hidden_units, kernel_size=1)
        self.dropout1 = nn.Dropout(p=dropout_rate)
        self.relu = nn.ReLU()
        self.conv2 = nn.Conv1d(hidden_units, hidden_units, kernel_size=1)
        self.dropout2 = nn.Dropout(p=dropout_rate)

    def forward(self, inputs):
        outputs = self.dropout2(self.conv2(self.relu(self.dropout1(self.conv1(inputs.transpose(-1, -2))))))
        outputs = outputs.transpose(-1, -2) # as Conv1D requires (N, C, Length)
        outputs += inputs
        return outputs

class Attention(nn.Module):
    def __init__(self, max_len, head_size, args=None):
        super().__init__()

        self.args = args

        self.global_num = args.trm_num_heads
        self.local_num = args.local_num_heads

        if self.local_num > 0:

            self.abs_pos_emb_key = nn.Embedding(max_len, head_size * self.local_num)
            self.abs_pos_emb_query = nn.Embedding(max_len, head_size * self.local_num)
            self.rel_pos_emb = nn.Embedding(2 * max_len - 1, head_size * self.local_num)
            position_ids_l = torch.arange(max_len, dtype=torch.long).view(-1, 1)
            position_ids_r = torch.arange(max_len, dtype=torch.long).view(1, -1)
            self.distance = position_ids_r - position_ids_l + max_len - 1
            self.mlps = nn.ModuleList([nn.Linear(head_size, 1) for _ in range(self.local_num)])
            self.sigmoid = nn.Sigmoid()

    "Compute 'Scaled Dot Product Attention"
    def forward(self, query, key, value, mask=None, dropout=None):
        b, h, l, d_k = query.size()
        query_g, key_g, value_g = query[:, :self.global_num, ...], key[:, :self.global_num, ...], value[:, :self.global_num, ...]

        scores_g = torch.matmul(query_g, key_g.transpose(-2, -1)) / math.sqrt(query_g.size(-1))
        scores_g = scores_g.masked_fill(mask, -MAX_VAL)
        p_attn_g = dropout(F.softmax(scores_g, dim=-1))
        value_g = torch.matmul(p_attn_g, value_g)

        if self.local_num > 0:
            query_l, key_l, value_l = query[:, self.global_num:, ...], key[:, self.global_num:, ...], value[:, self.global_num:, ...]
            index = self.distance.to(query_l.device)[-1]
            query_l = query_l + self.abs_pos_emb_query(index).unsqueeze(0).unsqueeze(0).view(1,-1,l,d_k)
            key_l = key_l + self.abs_pos_emb_key(index).unsqueeze(0).unsqueeze(0).view(1,-1,l,d_k)

            scores_l = torch.matmul(query_l, key_l.transpose(-2, -1)) / math.sqrt(query_l.size(-1))

            rel_pos_embedding = self.rel_pos_emb(self.distance.to(scores_l.device)).view(l, -1, self.local_num, d_k).permute(2,0,1,3).unsqueeze(0)
            inputs = rel_pos_embedding.repeat(b,1,1,1,1) + value_l.unsqueeze(dim=-2) + value_l.unsqueeze(dim=-3)# + self.user_proj(users).view(b, l, -1, d_k).permute(0,2,1,3).unsqueeze(-2)

            reweight = torch.cat([self.mlps[i](inputs[:, i, ...]).squeeze(-1).unsqueeze(1) for i in range(self.local_num)], dim=1)
            scores_l = scores_l + reweight

            scores_l = scores_l.masked_fill(mask, -MAX_VAL)
            p_attn_l = dropout(F.softmax(scores_l, dim=-1))
            value_l = torch.matmul(p_attn_l, value_l)

            if self.global_num > 0:
                return torch.cat([value_g, value_l], dim=1), (p_attn_g, p_attn_l)
            else:
                return value_l, p_attn_l

        else:

            return value_g, p_attn_g

class MultiHeadedAttention(nn.Module):
    "Take in model size and number of heads."
    def __init__(self, args=None):
        super().__init__()

        hidden_dim = args.trm_hidden_dim
        num_heads = args.trm_num_heads + args.local_num_heads
        assert hidden_dim % num_heads == 0
        dropout = args.trm_att_dropout
        max_len = args.trm_max_len

        self.head_size = hidden_dim // num_heads
        self.num_heads = num_heads

        self.linear_layers = nn.ModuleList([nn.Linear(hidden_dim, hidden_dim) for _ in range(3)])
        self.output_linear = nn.Linear(hidden_dim, hidden_dim)
        self.attention = Attention(max_len=max_len, head_size=self.head_size, args=args)

        self.dropout = nn.Dropout(p=dropout)

    def forward(self, query, key, value, mask=None):

        '''
        query, key, value: [batch, seq_len, hidden]
        '''

        batch_size = query.size(0)

        # 1) Do all the linear projections in batch from d_model => h x d_k
        query, key, value = [l(x).view(batch_size, -1, self.num_heads, self.head_size).transpose(1, 2)
                             for l, x in zip(self.linear_layers, (query, key, value))]

        # 2) Apply attention on all the projected vectors in batch.
        x, attn = self.attention(query, key, value, mask=mask, dropout=self.dropout)

        # 3) "Concat" using a view and apply a final linear.
        x = x.transpose(1, 2).contiguous().view(batch_size, -1, self.num_heads * self.head_size)

        return self.output_linear(x)

class LocalSelfAttention(nn.Module):
    def __init__(self, args):
        super().__init__()
        self.attention_layernorms = nn.ModuleList()
        self.attention_layers = nn.ModuleList()
        self.forward_layernorms = nn.ModuleList()
        self.forward_layers = nn.ModuleList()

        self.last_layernorm = nn.LayerNorm(args.trm_hidden_dim, eps=1e-8)

        for _ in range(args.trm_num_blocks):
            new_attn_layernorm = nn.LayerNorm(args.trm_hidden_dim, eps=1e-8)
            self.attention_layernorms.append(new_attn_layernorm)

            new_attn_layer =  MultiHeadedAttention(args)
            self.attention_layers.append(new_attn_layer)

            new_fwd_layernorm = nn.LayerNorm(args.trm_hidden_dim, eps=1e-8)
            self.forward_layernorms.append(new_fwd_layernorm)

            new_fwd_layer = PointWiseFeedForward(args.trm_hidden_dim, args.trm_dropout)
            self.forward_layers.append(new_fwd_layer)

    def forward(self, seqs, timeline_mask):

        seqs *= ~timeline_mask.unsqueeze(-1) # broadcast in last dim

        tl = seqs.shape[1] # time dim len for enforce causality
        attention_mask = ~torch.tril(torch.ones((tl, tl), dtype=torch.bool, device=seqs.device))

        attn_output_weights = []

        for i in range(len(self.attention_layers)):

            Q = self.attention_layernorms[i](seqs)
            mha_outputs = self.attention_layers[i](Q, seqs, seqs, mask=attention_mask)

            seqs = Q + mha_outputs

            seqs = self.forward_layernorms[i](seqs)
            seqs = self.forward_layers[i](seqs)
            seqs *=  ~timeline_mask.unsqueeze(-1)

        log_feats = self.last_layernorm(seqs) # (U, T, C) -> (U, -1, C)

        return log_feats, attn_output_weights


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import time

import numpy as np

import tensorflow as tf

BASE_LEARNING_RATE = 0.1  # This matches Jing's version.
TRAIN_TOP_1 = 'training_accuracy_top_1'

class BatchTimestamp(object):
  """A structure to store batch time stamp."""

  def __init__(self, batch_index, timestamp):
    self.batch_index = batch_index
    self.timestamp = timestamp

class TimeHistory(tf.keras.callbacks.Callback):
  """Callback for Keras models."""

  def __init__(self, batch_size, log_steps):
    """Callback for logging performance (# image/second).

    Args:
      batch_size: Total batch size.

    """
    self.batch_size = batch_size
    super(TimeHistory, self).__init__()
    self.log_steps = log_steps

    # Logs start of step 0 then end of each step based on log_steps interval.
    self.timestamp_log = []

  def on_train_begin(self, logs=None):
    self.record_batch = True

  def on_train_end(self, logs=None):
    self.train_finish_time = time.time()

  def on_batch_begin(self, batch, logs=None):
    if self.record_batch:
      timestamp = time.time()
      self.start_time = timestamp
      self.record_batch = False
      if batch == 0:
        self.timestamp_log.append(BatchTimestamp(batch, timestamp))

  def on_batch_end(self, batch, logs=None):
    if batch % self.log_steps == 0:
      timestamp = time.time()
      elapsed_time = timestamp - self.start_time
      examples_per_second = (self.batch_size * self.log_steps) / elapsed_time
      if batch != 0:
        self.record_batch = True
        self.timestamp_log.append(BatchTimestamp(batch, timestamp))
        tf.logging.info("BenchmarkMetric: {'num_batches':%d, 'time_taken': %f,"
                        "'images_per_second': %f}" %
                        (batch, elapsed_time, examples_per_second))

from tensorflow.python.keras import backend as K
class LearningRateBatchScheduler(tf.keras.callbacks.Callback):
  """Callback to update learning rate on every batch (not epoch boundaries).

  N.B. Only support Keras optimizers, not TF optimizers.

  Args:
      schedule: a function that takes an epoch index and a batch index as input
          (both integer, indexed from 0) and returns a new learning rate as
          output (float).
  """

  def __init__(self, schedule, batch_size, num_images):
    super(LearningRateBatchScheduler, self).__init__()
    self.schedule = schedule
    self.batches_per_epoch = num_images / batch_size
    self.batch_size = batch_size
    self.epochs = -1
    self.prev_lr = -1

  def on_epoch_begin(self, epoch, logs=None):
    if not hasattr(self.model.optimizer, 'lr'):
      raise ValueError('Optimizer must have a "learning_rate" attribute.')
    self.epochs += 1

  def on_batch_begin(self, batch, logs=None):
    """Executes before step begins."""
    lr = self.schedule(self.epochs,
                       batch,
                       self.batches_per_epoch,
                       self.batch_size)
    if not isinstance(lr, (float, np.float32, np.float64)):
      raise ValueError('The output of the "schedule" function should be float.')
    if lr != self.prev_lr:
      self.model.optimizer.lr = K.variable(lr, name='lr')  # lr should be a float here
      self.prev_lr = lr
      tf.logging.debug('Epoch %05d Batch %05d: LearningRateBatchScheduler '
                       'change learning rate to %s.', self.epochs, batch, lr)

def build_stats(history, eval_output, time_callback):
  """Normalizes and returns dictionary of stats.

  Args:
    history: Results of the training step. Supports both categorical_accuracy
      and sparse_categorical_accuracy.
    eval_output: Output of the eval step. Assumes first value is eval_loss and
      second value is accuracy_top_1.
    time_callback: Time tracking callback likely used during keras.fit.

  Returns:
    Dictionary of normalized results.
  """
  stats = {}
  if eval_output:
    stats['accuracy_top_1'] = eval_output[1].item()
    stats['eval_loss'] = eval_output[0].item()

  if history and history.history:
    train_hist = history.history
    # Gets final loss from training.
    stats['loss'] = train_hist['loss'][-1].item()
    # Gets top_1 training accuracy.
    if 'categorical_accuracy' in train_hist:
      stats[TRAIN_TOP_1] = train_hist['categorical_accuracy'][-1].item()
    elif 'sparse_categorical_accuracy' in train_hist:
      stats[TRAIN_TOP_1] = train_hist['sparse_categorical_accuracy'][-1].item()

  if time_callback:
    timestamp_log = time_callback.timestamp_log
    stats['step_timestamp_log'] = timestamp_log
    stats['train_finish_time'] = time_callback.train_finish_time
    if len(timestamp_log) > 1:
      stats['avg_exp_per_second'] = (
          time_callback.batch_size * time_callback.log_steps *
          (len(time_callback.timestamp_log)-1) /
          (timestamp_log[-1].timestamp - timestamp_log[0].timestamp))

  return stats

class DummyContextManager(object):

  def __enter__(self):
    pass

  def __exit__(self, *args):
    pass


# coding=utf-8
# auther：Liul5
# date：2019/4/26 13:08
# tools：PyCharm
# Python：2.7.15
# https://py.checkio.org/en/mission/sendgrid-daily-spam/
# https://github.com/sendgrid/sendgrid-python/blob/master/USAGE.md#api-keys

import sendgrid
import json
from datetime import datetime
from datetime import timedelta

# need to register and get the key https://app.sendgrid.com
API_KEY = 'your api key'

sg = sendgrid.SendGridAPIClient(apikey=API_KEY)

def how_spammed(str_date):
    end_time = datetime.strptime(str_date, '%Y-%m-%d')
    start_time = end_time + timedelta(days=1)
    response = sg.client.suppression.spam_reports.get(query_params={
    'end_time':int(end_time.timestamp()),
    'start_time': int(start_time.timestamp())
    })
    data = json.loads(response.body)
    return len(data)


# touchweel0_demo0.py -- quick test of the "touchwheel0" board w/ a Neopixel ring
#  Uses a super dumb algorthim to calculate wheel position
# 2 Nov 2023 - @todbot / Tod Kurt
#

import time
import board
import touchio
import neopixel

num_leds = 12
leds = neopixel.NeoPixel(board.GP15, num_leds, brightness=0.1)
leds[0] = 0x005500  # quick blip to indicate which LED is "up"
time.sleep(0.5)
leds[0] = 0

touch_pins = (board.GP18, board.GP19, board.GP20)
touchins = []
for p in touch_pins:
    touchin = touchio.TouchIn(p)
    touchins.append(touchin)

def wheel_pos(a,b,c):
    """
    Given three touchio.TouchIn pads, compute wheel position 0-1
    or return None if wheel is not pressed
    """
    # compute raw percentages
    a_pct = (a.raw_value - a.threshold) / a.threshold
    b_pct = (b.raw_value - b.threshold) / b.threshold
    c_pct = (c.raw_value - c.threshold) / c.threshold
    #print( "%+1.2f  %+1.2f  %+1.2f" % (a_pct, b_pct, c_pct), end="\t")

    offset = -0.333/2  # physical design is rotated 1/2 a sector anti-clockwise

    pos = None
    # cases when finger is touching two pads
    if a_pct >= 0 and b_pct >= 0:  #
        pos = 0 + 0.333 * (b_pct / (a_pct + b_pct))
    elif b_pct >= 0 and c_pct >= 0:  #
        pos = 0.333 + 0.333 * (c_pct / (b_pct + c_pct))
    elif c_pct >= 0 and a_pct >= 0:  #
        pos = 0.666 + 0.333 * (a_pct / (c_pct + a_pct))
    # special cases when finger is just on a single pad.
    # these shouldn't be needed and create "deadzones" at these points
    # so surely there's a better solution
    elif a_pct > 0 and b_pct <= 0 and c_pct <= 0:
        pos = 0
    elif a_pct <= 0 and b_pct > 0 and c_pct <= 0:
        pos = 0.333
    elif a_pct <= 0 and b_pct <= 0 and c_pct > 0:
        pos = 0.666
    # wrap pos around the 0-1 circle if offset puts it outside that range
    return (pos + offset) % 1 if pos is not None else None

dim_by = 20

while True:
    leds[:] = [[max(i-dim_by,0) for i in l] for l in leds]  # fade leds

    pos = wheel_pos(*touchins)
    if pos is not None:
        print("pos:%.2f" % pos)
        n = int(pos * num_leds)
        leds[n] = 0xff00ff
    else:
        print("no touch")

    time.sleep(0.01)


"""Restaurant rating lister."""

def read_ratings(file_path):

    restaurant_details = open(file_path)

    restaurants = {}

    for line in restaurant_details:

        line = line.rstrip()
        details = line.split(":")
        restaurant_name, restaurant_rating = details

        restaurants[restaurant_name] = restaurant_rating

    #ask user for input = name
    name = input("What restaurant do you want to add? ")
    name = name.title()
    #ask user for input = score
    rating = input("What is the rating? ")
    #take input and add into dict
    restaurants[name] = rating
    #print in alphabetical order

    #list = sorted(dict)
    alpha_rests = sorted(restaurants)
    #loop through list
    for restaurant in alpha_rests:
        print(f"{restaurant} is rated at {restaurants[restaurant]}.")
    # print rname and dict[rname]=rating

    restaurant_details.close()

read_ratings("scores.txt")


import snscrape.modules.twitter as sntwitter
import pandas as pd
import text2emotion as te
import threading

def get_tweets(user):
    print("User: " + user)
    query = f"(from:{user}) since:2018-7-1 until:2022-11-30"

    # Creating list to append tweet data to
    tweets_list = []
    print("grabbing tweets")
    i = 0
    for tweet in sntwitter.TwitterSearchScraper(query).get_items():
        # print(tweet.json())
        tweets_list.append(
            [tweet.date, tweet.id, tweet.content, tweet.retweetCount, tweet.replyCount, tweet.likeCount, tweet.user.username])
        i += 1
        print(user, i)

    # Creating a dataframe from the tweets list above
    tweets_df = pd.DataFrame(tweets_list, columns=[
        'Datetime', 'Tweet Id', 'Text', 'Retweets', 'Replies', 'Likes', 'Username'])
    print(
        f"tweets grabbed, saving to csv, please wait, 'tweets{user}.csv' will be created")
    # export to csv
    tweets_df.to_csv(f'tweets{user}.csv', index=False)

list_of_users = ["GiuseppeConteIT"]
for user in list_of_users:
    t = threading.Thread(target=get_tweets, args=(user,))
    t.start()


T = int(input())

def cmp_min(a, b):
    for c1, c2 in zip(a, b):
        if c1 == c2:
            continue
        if int(c1) < int(c2):
            return a
        else:
            return b
    return a

def eval_pos(N, mid, rest):
    pref = N[:mid]
    #print(f'evaluating N = {N}, mid = {mid}, pref = {pref}, rest = {rest}')
    return any(int(c)>rest for c in pref)

def gen_best_pos(N, rest):
    lo = 0
    hi = len(N)+1
    while lo < hi:
        mid = (lo + hi)//2
        if mid <= lo:
            break
        #print(f'lo = {lo}, high = {hi}, mid = {mid}')
        if eval_pos(N, mid, rest):
             hi = mid-1
        else:
            lo = mid

    return N[:lo] + str(rest) + N[lo:]

def gen_sol(N):
    sum_N = sum([ int(c) for c in N])
    if sum_N % 9 > 0:
        rest = 9 - (sum_N % 9)
    else:
        rest = 0
        return N[:1] + '0' + N[1:]

    sol =gen_best_pos(N, rest)
    return sol

for n in range(T):
    N = input()
    sol = gen_sol(N)
    print(f'Case #{n+1}: {sol}')


import logging
import pandas as pd
import json
import pickle
import sklearn

LOGGER = logging.getLogger(__name__)

def execute(data: dict):
    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)
    logger.info('event parameter: {}'.format(data))
    # print("Received event: " + json.dumps(event, indent=2))
    body = data
    print("Received body:  " + str(body))
    try:
        return score(body)
    except Exception as e:
        logger.error(e)
        print(json.dumps({'error': str(e)}))
        return {
            'statusCode': 500,
            'body': json.dumps({'error': str(e)})
        }

def score(data):
    LOGGER.info("Hello World")
    feat_dict = data
    pid = feat_dict["applicant_id"]
    feat_dict.pop("applicant_id", None)
    feat_dict["credit_score"] = feat_dict["credit_score"] / 1000
    feat_dict["age"] = feat_dict["age"] / 85
    mod = pd.DataFrame([feat_dict])
    model = pickle.load(open("src/data_applicant_scoring/tenant_score_ml_model", 'rb'))
    ans = model.predict(mod)[0]
    print("tenant scoring: ")
    if ans > 1:
        fans = 100
    elif ans < 0:
        fans = 20
    elif 0.85 > ans:
        fans = ans * 100 + 7
    else:
        fans = ans * 100
    if fans < 25:
        level = 1
    elif fans < 45:
        level = 2
    elif fans < 60:
        level = 3
    elif fans < 80:
        level = 4
    else:
        level = 5
    return {
        'statusCode': 200,
        'body': json.dumps(dict({'applicant_id': str(pid), 'level': level, 'score': fans}))}

# score({"applicant_id": "BC5T2A09-ELE2-4HG0-AE74-4E2DF78A3E1D",
#         "credit_score": 678,
#         "eviction": 2,
#         "criminal": 1,
#         "age": 28})


'''
@File  : find-two-non-overlapping-sub-arrays-each-with-target-sum.py
@Author: Swift
@Date  : 2020/12/14 22:06
@Link  : https://leetcode-cn.com/problems/find-two-non-overlapping-sub-arrays-each-with-target-sum/
@Desc  : 1477. 找两个和为目标值且不重叠的子数组
@Method:
'''

class Solution:
    def minSumOfLengths(self, arr, target):
        length = len(arr)
        dp = [2 * length] * (length + 1)
        res = 2 * length
        l, r, s = 0, 0, 0
        while r < length:
            dp[r + 1] = dp[r]
            s += arr[r]
            while s > target:
                s -= arr[l]
                l += 1

            if s == target:
                dp[r + 1] = min(dp[r], r - l + 1)
                res = min(res, dp[l] + r - l + 1)
            r += 1
        res = -1 if res == 2 * length else res
        return res

if __name__ == '__main__':
    obj = Solution()
    arr = [3, 3]
    target = 3
    res = obj.minSumOfLengths(arr, target)
    print(res)


# MOVE INTO src/video_embedder DIR TO TEST

from vid_embed import VideoEmbedder
import cv2
import numpy as np

if __name__ == '__main__':
    cap = cv2.VideoCapture(0)                               # camera
    model = cv2.imread('model.png')                         # model image
    carousel = [cv2.VideoCapture('video.mp4'), cv2.VideoCapture('video2.mp4')]                # overlay video(s)

    vidEmbedder = VideoEmbedder(cap, model, carousel)
    vidEmbedder.run()

    cap.release()
    cv2.destroyAllWindows()


destinos = ["Paris, Francia", "Shanghai, China", "Los Angeles, USA", "São Paulo, Brazil", "Cairo, Egipto"]

def obtenerIndiceDestino(destino):
    try:
        indiceDestino = destinos.index(destino)
    except ValueError:
        print("Ese destino no existe")
        indiceDestino = None
    return indiceDestino

def locacionViajero(viajero):
    destinoViaje = test_traveler[1]
    indiceDestinoViajero = obtenerIndiceDestino(destinoViaje)
    return indiceDestinoViajero

def añadirAtraccion(destino, atraccion):
    indiceDestino = obtenerIndiceDestino(destino)
    if indiceDestino == None:
        return
    atracciones[indiceDestino].append(atraccion)
    return

def encontrarAtracciones(destino, interes):
    indiceDestino = obtenerIndiceDestino(destino)
    if indiceDestino == None:
        return
    atraccionesCiudad = atracciones[indiceDestino]
    atraccionesInteres = []

    for i in atraccionesCiudad:
        etiquetas = i[1]
        for j in interes:
            if j in etiquetas:
                atraccionesInteres.append(i[0])

    return atraccionesInteres

def atraccionesParaViajeros(viajero):
    destino = viajero[1]
    intereses = viajero[2]

    atraccionesViajero = encontrarAtracciones(destino, intereses)
    string = """
    Hola, {nombre}, creemos que te gustaran estos lugares alrededor de {lugar}:
    """.format(nombre = viajero[0], lugar = destino)
    for i in atraccionesViajero:
        string += i + ", "
    return string

test_traveler = ['Erin Wilkes', 'Shanghai, China', ['historical site', 'art']]

atracciones = [[] for i in destinos]

añadirAtraccion("Los Angeles, USA", ['Venice Beach', ['beach']])
añadirAtraccion("Paris, Francia", ["the Louvre", ["art", "museum"]])
añadirAtraccion("Paris, Francia", ["Arc de Triomphe", ["historical site", "monument"]])
añadirAtraccion("Shanghai, China", ["Yu Garden", ["garden", "historcical site"]])
añadirAtraccion("Shanghai, China", ["Yuz Museum", ["art", "museum"]])
añadirAtraccion("Shanghai, China", ["Oriental Pearl Tower", ["skyscraper", "viewing deck"]])
añadirAtraccion("Los Angeles, USA", ["LACMA", ["art", "museum"]])
añadirAtraccion("São Paulo, Brazil", ["São Paulo Zoo", ["zoo"]])
añadirAtraccion("São Paulo, Brazil", ["Pátio do Colégio", ["historical site"]])
añadirAtraccion("Cairo, Egipto", ["Pyramids of Giza", ["monument", "historical site"]])
añadirAtraccion("Cairo, Egipto", ["Egyptian Museum", ["museum"]])

smills = atraccionesParaViajeros(['Dereck Smill', 'Paris, Francia', ['monument']])
print(smills)


import math
from opentrons.types import Point

# metadata
metadata = {
    'protocolName': 'Lexogen QuantSeq 3`mRNA FWD NGS Library Prep',
    'author': 'Nick <protocols@opentrons.com>',
    'source': 'Custom Protocol Request',
    'apiLevel': '2.12'
}

def run(ctx):

    [p20_single_mount, p300_multi_mount, magdeck_gen, tempdeck_gen,
     num_samples] = get_values(  # noqa: F821
        'p20_single_mount', 'p300_multi_mount', 'magdeck_gen', 'tempdeck_gen',
        'num_samples')

    # checks
    if num_samples > 96 or num_samples < 1:
        raise Exception('Invalid number of samples (must be 1-96).')

    # load labware
    outputplate = ctx.load_labware(
        'nest_96_wellplate_100ul_pcr_full_skirt',
        '1',
        'final output plate (load empty)'
    )
    tuberack = ctx.load_labware(
        'opentrons_24_tuberack_nest_1.5ml_snapcap',
        '2',
        'reagent tuberack with 1.5ml snapcap tubes'
    )
    reservoir = ctx.load_labware(
        'nest_12_reservoir_15ml', '3', 'reagent reservoir')
    magdeck = ctx.load_module(magdeck_gen, '4')
    magplate = magdeck.load_labware('nest_96_wellplate_100ul_pcr_full_skirt')
    sp2 = ctx.load_labware(
        'nest_96_wellplate_100ul_pcr_full_skirt', '5', 'SP2 (load empty)')
    tips20 = [
        ctx.load_labware('opentrons_96_tiprack_20ul', slot)
        for slot in ['6', '9']
    ]
    tempdeck = ctx.load_module(tempdeck_gen, '7')
    tubeblock = tempdeck.load_labware(
        'opentrons_24_aluminumblock_nest_1.5ml_snapcap')
    indexplate = ctx.load_labware(
        'nest_96_wellplate_100ul_pcr_full_skirt', '8', 'index plate')
    tips300 = [
        ctx.load_labware('opentrons_96_tiprack_300ul', slot)
        for slot in ['10', '11']
    ]

    # reagents and samples
    fs1, fs2e1, pb, eb, ps, pcre3 = tubeblock.rows()[0]
    rs, ss1, ss2 = tuberack.rows()[0][:3]
    num_etoh_chan = 2 if num_samples <= 48 else 3
    etoh = reservoir.wells()[:num_etoh_chan]
    waste = reservoir.wells()[-1].top()
    num_cols = math.ceil(num_samples/8)
    magsamples_s = magplate.wells()[:num_samples]
    magsamples_m = magplate.rows()[0][:num_cols]
    samples2_s = sp2.wells()[:num_samples]
    indexes = indexplate.wells()[:num_samples]
    output = outputplate.wells()[:num_samples]

    # pipettes
    p20 = ctx.load_instrument(
        'p20_single_gen2', p20_single_mount, tip_racks=tips20)
    m300 = ctx.load_instrument(
        'p300_multi_gen2', p300_multi_mount, tip_racks=tips300)

    # tip track
    tipcount20 = 0
    tipmax20 = 96*len(tips20)
    tipcount300 = 0
    tipmax300 = 12*len(tips300)

    def pickup(pip):
        nonlocal tipcount20
        nonlocal tipcount300
        if pip == p20:
            if tipcount20 == tipmax20:
                ctx.pause('Refill 20µl tipracks in slots 6 and 9 before \
resuming.')
                p20.reset_tipracks()
                tipcount20 = 0
            p20.pick_up_tip()
            tipcount20 += 1
        else:
            if tipcount300 == tipmax300:
                ctx.pause('Refill 200µl tipracks in slots 8, 10, and 11 \
before resuming.')
                m300.reset_tipracks()
                tipcount300 = 0
            m300.pick_up_tip()
            tipcount300 += 1

    def init_transfers(vol, reagent):
        for s in magsamples_s:
            pickup(p20)
            p20.transfer(vol, reagent, s, mix_after=(3, 10), new_tip='never')
            p20.blow_out(s.top())
            p20.drop_tip()

    # transfer FS1
    init_transfers(5, fs1)
    ctx.pause('Place sample plate in cycler at 85C for 3 minutes, then cool \
down to 42C. Return sample plate to OT-2 when finished.')

    # transfer FS2/E1
    init_transfers(10, fs2e1)
    ctx.pause('Place sample plate in cycler at 42C for 15 minutes. Return \
sample plate to OT-2 when finished.')

    # transfer RS
    init_transfers(5, rs)
    ctx.pause('Place sample plate in cycler at 95C for 10 minutes. Return \
sample plate to OT-2 when finished.')

    # transfer SS1
    init_transfers(10, ss1)
    ctx.pause('Place sample plate in cycler at 98C for 1 minute. Return \
sample plate to OT-2 when finished.')

    # transfer SS2
    init_transfers(5, ss2)
    ctx.pause('Place sample plate in cycler at 25C for 15 minutes. Return \
sample plate to OT-2 when finished.')

    # transfer PB
    init_transfers(16, pb)

    magdeck.engage()
    ctx.delay(minutes=5, msg='Incubating on magnet for 5 minutes.')

    # remove supernatant
    for m in magsamples_m:
        pickup(m300)
        m300.transfer(60, m.bottom(0.5), waste, new_tip='never')
        m300.drop_tip()

    # add 80% EtOH
    for m in magsamples_m:
        pickup(m300)
        m300.transfer(120, etoh[0], waste, new_tip='never')
        m300.drop_tip()

    ctx.delay(seconds=30, msg='Incubating on magnet for 30 seconds.')

    # remove supernatant
    for m in magsamples_m:
        pickup(m300)
        m300.transfer(130, m.bottom(0.5), waste, new_tip='never')
        m300.drop_tip()

    ctx.delay(minutes=10, msg='Drying beads for 10 minutes.')

    magdeck.disengage()

    # elute beads in EB
    for i, s in enumerate(magsamples_s):
        side = 1 if (i//8) % 2 == 0 else -1
        mix_loc = s.bottom().move(Point(x=side*s.diameter/2*0.9, y=0, z=2))
        pickup(p20)
        p20.transfer(20, eb, s.top(), new_tip='never')
        p20.aspirate(20, eb)
        p20.move_to(s.center())
        p20.dispense(20, mix_loc)
        p20.mix(5, 10, mix_loc)
        p20.blow_out(s.top(-2))
        p20.drop_tip()

    # transfer PS
    for s in magsamples_s:
        pickup(p20)
        p20.transfer(56, ps, s.top(), new_tip='never')
        p20.mix(3, 10, s)
        p20.blow_out(s.top(-2))
        p20.drop_tip()

    ctx.delay(minutes=5, msg='Incubating off magnet for 5 minutes.')
    magdeck.engage()
    ctx.delay(minutes=5, msg='Incubating on magnet for 5 minutes.')

    # transfer supernatant to SP2
    for s, d in zip(magsamples_s, samples2_s):
        pickup(p20)
        p20.transfer(17, s.bottom(0.5), d, new_tip='never')
        p20.drop_tip()

    # transfer pcre3
    pickup(p20)
    for s in samples2_s:
        p20.transfer(8, pcre3, s.top(), new_tip='never')
        p20.blow_out(s.top())

    # transfer corresponding indices
    for index, s in zip(indexes, samples2_s):
        if not p20.hw_pipette['has_tip']:
            pickup(p20)
        p20.transfer(5, index, s, mix_after=(3, 10), new_tip='never')
        p20.blow_out(s.top())
        p20.drop_tip()

    ctx.pause('Perform PCR cycling reaction, then place SP2 on the magnetic \
deck.')

    # transfer PB
    for s in magsamples_s:
        pickup(p20)
        p20.transfer(30, pb, s.top(), new_tip='never')
        p20.mix(3, 10, s)
        p20.blow_out(s.top())
        p20.drop_tip()

    ctx.delay(minutes=5, msg='Incubating off magnet for 5 minutes.')
    magdeck.engage()
    ctx.delay(minutes=5, msg='Incubating on magnet for 5 minutes.')

    # remove supernatant
    for m in magsamples_m:
        pickup(m300)
        m300.transfer(65, m.bottom(0.5), waste, new_tip='never')
        m300.drop_tip()

    magdeck.disengage()

    # elute beads in EB
    for i, s in enumerate(magsamples_s):
        side = 1 if (i//8) % 2 == 0 else -1
        mix_loc = s.bottom().move(Point(x=side*s.diameter/2*0.9, y=0, z=2))
        pickup(p20)
        p20.transfer(20, eb, s.top(), new_tip='never')
        p20.aspirate(10, eb)
        p20.move_to(s.center())
        p20.dispense(10, mix_loc)
        p20.mix(5, 10, mix_loc)
        p20.blow_out(s.top(-2))
        p20.drop_tip()

    # transfer PS
    for s in magsamples_s:
        pickup(p20)
        p20.transfer(30, ps, s.top(), new_tip='never')
        p20.mix(3, 10, s)
        p20.blow_out(s.top(-2))
        p20.drop_tip()

    ctx.delay(minutes=5, msg='Incubating off magnet for 5 minutes.')
    magdeck.engage()
    ctx.delay(minutes=5, msg='Incubating on magnet for 5 minutes.')

    # remove supernatant
    for m in magsamples_m:
        pickup(m300)
        m300.transfer(65, m.bottom(0.5), waste, new_tip='never')
        m300.drop_tip()

    # 2x EtOH washes
    for wash in range(2):
        # add 80% EtOH
        chan = 1 if wash == 0 else -1
        for m in magsamples_m:
            pickup(m300)
            m300.transfer(120, etoh[chan], waste, new_tip='never')
            m300.drop_tip()

        ctx.delay(seconds=30, msg='Incubating on magnet for 30 seconds.')

        # remove supernatant
        for m in magsamples_m:
            pickup(m300)
            m300.transfer(130, m.bottom(0.5), waste, new_tip='never')
            m300.drop_tip()

        ctx.delay(minutes=10, msg='Drying beads for 10 minutes.')

    magdeck.disengage()

    # elute beads in EB
    for i, s in enumerate(magsamples_s):
        side = 1 if (i//8) % 2 == 0 else -1
        mix_loc = s.bottom().move(Point(x=side*s.diameter/2*0.9, y=0, z=2))
        pickup(p20)
        p20.aspirate(20, eb)
        p20.move_to(s.center())
        p20.dispense(20, mix_loc)
        p20.mix(5, 10, mix_loc)
        p20.blow_out(s.top(-2))
        p20.drop_tip()

    magdeck.engage()
    ctx.delay(minutes=5, msg='Incubating on magnet for 5 minutes.')

    # transfer supernatant to output plate
    for s, o in zip(magsamples_m, output):
        pickup(p20)
        p20.transfer(15, s, o, new_tip='never')
        p20.drop_tip()


import os
import sys
import os.path as op
import random
import string

def create_random_file(size, ext):
    for i in range(size):
        body = ''.join(random.choices(string.ascii_letters +string.digits, k=6))
        if len(ext) > 0:
            filename = body + '.' + ext
        else:
            filename = body
        open(filename, 'a').close()
        print(filename)

def create_files(download_dir):
    if not op.isdir(download_dir):
        os.mkdir(download_dir)
    os.chdir(download_dir)
    exts = [
        'exe', 'msi',
        'txt', 'pdf', 'docs', 'xlsx',
        'zip', 'rar', '7z',
        'avi', 'mp4',
        'mp3',
    ]
    count = 0
    count_no_ext = 4
    for ext in exts:
        size_list = random.choices(range(1,4))
        size = size_list[0]
        create_random_file(size, ext)
        count = count + size
    create_random_file(count_no_ext, '')
    count += count_no_ext
    print("Create {} files".format(count))

if __name__ == '__main__':
    download_dir = input("Input download dir path:")
    create_files(download_dir)
    sys.exit(0)


# The Nature of Code
# Daniel Shiffman
# http://natureofcode.com

import pygame
import random as rnd

width = 640
height = 360
window = pygame.display.set_mode((width,height))

def setup():
    global width
    global height

def draw():
    global width
    global height
    global window

    # Get a gaussian random number w/ mean of 0 and standard deviation of 1.0
    xloc = rnd.gauss(0, 1.0)

    sd = 60.0                       # Define a standard deviation
    mean = width/2                  # Define a mean value (middle of the screen along the x-axis)
    xloc = (xloc * sd) + mean       # Scale the gaussian random number by standard deviation and mean

    pygame.draw.ellipse(window, pygame.Color('white'), (xloc, height/2, 16, 16))  # Draw an ellipse at our "normal" random position
    pygame.display.update()
    pygame.time.delay(10)

setup()
while(True):
  draw()


from tkinter import EXCEPTION
from django.shortcuts import render
import requests
from .models import City
from .forms import CityForm
import os

apiId = os.environ['weatherapp_api_key']

def index(request):
    url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=imperial&appid=%s' %apiId
    cities = City.objects.all()

    error_msg = ''
    message = ''
    message_class = ''
    if request.method == 'POST':
        form = CityForm(request.POST)
        # form.save()

        if form.is_valid():
            new_city = form.cleaned_data['name']
            existing_city_count = City.objects.filter(name=new_city).count()

            if existing_city_count == 0:
                r = requests.get(url.format(new_city)).json()

                if r['cod'] == 200:
                    form.save()
                else:
                    error_msg = 'City doesnot exists.'
            else:
                error_msg = 'City already exists in the database!'

        if error_msg:
            message = error_msg
            message_class = 'is-danger'
        else:
            message = 'City added successfully'
            message_class= 'is-success'

    # if request.method == 'POST':
    #     form = CityForm(request.POST)
    #     form.save() #It will both validate and save the new city name to the databaseat hte same time

    form = CityForm()

    weather_list = []
    try:
        for city in cities:

            r = requests.get(url.format(city)).json()

            weather = {
                'city': city.name, # city or city.name, city print the object that contains city name, and city.name directly print the city name.
                'temperature': r['main']['temp'],
                'pressure': r['main']['pressure'],
                'humidity': r['main']['humidity'],
                'wind': r['wind']['speed'],
                'description': r['weather'][0]['description'], # 0 means first item in the list 'weather'
                'icon': r['weather'][0]['icon']
            }

            weather_list.append(weather)
    except KeyError:
        pass
    except EXCEPTION as e:
        pass
    print(weather_list)

    context = {'weather_list': weather_list,
                'form': form,
                 'message': message,
                 'message_class':message_class}
    return render(request, 'design/index.html', context)


from plone.app.portlets.portlets import base
from plone.portlets.interfaces import IPortletDataProvider
from Products.CMFCore.utils import getToolByName
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from zope.i18n import translate
from zope.interface import implements

from intranett.policy import IntranettMessageFactory as _
from intranett.policy.utils import get_user_profile_url

class IProjectRoomInfo(IPortletDataProvider):
    pass

class Assignment(base.Assignment):

    implements(IProjectRoomInfo)
    title = _("Project Info")

class Renderer(base.Renderer):

    render = ViewPageTemplateFile('projectroominfo.pt')
    portletTitle = _("Project Info")

    @property
    def available(self):
        return (getattr(self.context, 'getProjectRoom', None) is not None and
                'portal_factory' not in self.request.URL)

    def update(self):
        if not self.available:
            return
        context = self.context
        mtool = getToolByName(context, 'portal_membership')
        gtool = getToolByName(context, 'portal_groups')
        room = self.context.getProjectRoom()
        self.state = room.getProjectRoomState()
        self.title = room.Title()
        self.project_url = room.absolute_url()
        result = []
        for name in room.participants:
            title = name
            url = None
            if name == 'AuthenticatedUsers':
                title = translate(u'Authenticated Users (Virtual Group)',
                    domain='plone', context=self.request)
                result.append(dict(name=name, title=title, url=None))
                continue
            member = mtool.getMemberById(name)
            if member is not None:
                title = member.getProperty("fullname") or name
                url = get_user_profile_url(context, name)
            else:
                group = gtool.getGroupById(name)
                if group is not None:
                    title = group.getProperty('title') or name
            result.append(dict(name=name, title=title, url=url))
        self.participants = result

class AddForm(base.NullAddForm):

    def create(self):
        return Assignment()


import json
import logging
import os
import uuid

import mz2geohash
import requests
from django.conf import settings
from django.template.loader import render_to_string
from xhtml2pdf import pisa

from gis_app.exceptions import ExternalServiceError
from gis_app.models import (UserPosition, UserPositionExport, Vehicle,
                            VehicleExport)

def get_distance_from_openrouteservice(start, end):
    api_url = "https://api.openrouteservice.org/v2/directions/driving-car"
    params = {
        "api_key": settings.OPENROUTESERVICE_API_KEY,
        "start": f"{start[0]},{start[1]}",
        "end": f"{end[0]},{end[1]}"
    }
    response = requests.get(api_url, params=params)
    obj = json.loads(response.content)
    try:
        distance = obj['features'][0]['properties']['summary']['distance']
    except KeyError:
        raise ExternalServiceError("Error fetching data from openrouteservice API")
    return distance

def get_hash_for_coords(start, end):
    geo_hash = f"{mz2geohash.encode(start)}-{mz2geohash.encode(end)}"
    return geo_hash

class PdfExport:
    def __init__(self, queryset, fields, template):
        self.fields = fields
        self.template = template
        self.queryset = queryset

    def export_to_string(self):
        values = self.queryset.values(*self.fields)
        return render_to_string(self.template, {"objects": list(values)})

    def export_to_file(self, file_name):
        with open(file_name, "w+b") as dest_pdf:
            pisa.CreatePDF(self.export_to_string(), dest=dest_pdf)

    def get_extension(self):
        return ".pdf"

class UserPositionPdfExport(PdfExport):
    def __init__(self):
        self.fields = ['id', 'user__username', 'position__lat', 'position__lon', 'fetch_time']
        self.template = "vehicle_export.html"
        self.queryset = UserPosition.objects.all()

class VehiclePdfExport(PdfExport):
    def __init__(self):
        self.fields = ['id', 'name', 'users__username']
        self.template = "vehicle_export.html"
        self.queryset = Vehicle.objects.all()

class ReportMaker:
    def __init__(self, export_model, exporter):
        self.export_model = export_model
        self.exporter = exporter

    def _get_instance(self, export_id):
        try:
            instance = self.export_model.objects.get(id=export_id)
        except self.export_model.DoesNotExist:
            logging.warning(f"Trying to get non existing {self.export_model.__name__} export '{export_id}'")
        else:
            return instance

    def make_file_path(self):
        return os.path.join(settings.PDF_EXPORTS_DIR, f"{uuid.uuid4()}.{self.exporter.get_extension()}")

    def make_report(self, export_id):
        export_instance = self._get_instance(export_id)
        export_instance.set_status("creating")
        if not export_instance.file_path:
            export_instance.file_path = self.make_file_path()
        self.exporter.export_to_file(file_name=export_instance.file_path)
        export_instance.set_status("done")

class VehicleReportMaker(ReportMaker):
    def __init__(self):
        self.export_model = VehicleExport
        self.exporter = VehiclePdfExport()

class UserPositionReportMaker(ReportMaker):
    def __init__(self):
        self.export_model = UserPositionExport
        self.exporter = UserPositionPdfExport()


import random
from flask import Flask, render_template, request, redirect, url_for

app = Flask(__name__)

# Define the grid size
GRID_SIZE = 20

# Initialize the Snake game
class SnakeGame:
    def __init__(self):
        self.snake = [(GRID_SIZE // 2, GRID_SIZE // 2)]
        self.food = self.generate_food()
        self.direction = (0, 1)
        self.game_over = False

    def generate_food(self):
        while True:
            food = (random.randint(0, GRID_SIZE - 1), random.randint(0, GRID_SIZE - 1))
            if food not in self.snake:
                return food

    def move(self):
        if self.game_over:
            return

        head = self.snake[0]
        new_head = (head[0] + self.direction[0], head[1] + self.direction[1])

        if (
            new_head in self.snake
            or new_head[0] < 0
            or new_head[0] >= GRID_SIZE
            or new_head[1] < 0
            or new_head[1] >= GRID_SIZE
        ):
            self.game_over = True
            return

        self.snake.insert(0, new_head)

        if self.snake[0] == self.food:
            self.food = self.generate_food()
        else:
            self.snake.pop()

# Create a new Snake game instance
game = SnakeGame()

@app.route("/")
def index():
    return render_template("index.html", GRID_SIZE=GRID_SIZE)

@app.route("/move/<direction>")
def move(direction):
    if direction == "up":
        game.direction = (-1, 0)
    elif direction == "down":
        game.direction = (1, 0)
    elif direction == "left":
        game.direction = (0, -1)
    elif direction == "right":
        game.direction = (0, 1)
    game.move()
    return redirect(url_for("index"))

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000)


import requests
from aip import AipSpeech
import speech_recognition as sr
# pip install azure-cognitiveservices-speech
import azure.cognitiveservices.speech as speechsdk

class BaiduASR:
    def __init__(self, APP_ID, API_KEY, SECRET_KEY):
        self.APP_ID = APP_ID
        self.API_KEY = API_KEY
        self.SECRET_KEY = SECRET_KEY
        self.client = AipSpeech(self.APP_ID, self.API_KEY, self.SECRET_KEY)
        self.r = sr.Recognizer()

    # 从麦克风收集音频并写入文件
    def _record(self, if_cmu: bool = False, rate=16000):
        with sr.Microphone(sample_rate=rate) as source:
            # 校准环境噪声水平的energy threshold
            # duration:用于指定计算环境噪声的持续时间（秒）。默认值为1秒。函数将等待指定时间来计算环境噪声水平，并相应地调整麦克风增益，以提高语音识别的准确性。如果噪声水平很高，则可以增加此值以获得更准确的噪声估计。
            # self.r.adjust_for_ambient_noise(source, duration=1)
            print('您可以开始说话了')
            # timeout 用于指定等待语音输入的最长时间（秒），如果没有检测到语音输入，则函数将返回None。默认值为 None，表示等待无限长的时间。如果指定了超时时间，则函数将在等待指定时间后自动返回。
            # phrase_time_limit：用于指定允许单次语音输入的最长时间（秒），如果超过这个时间，函数将自动停止录制，并返回None.默认值为 None，表示允许单次语音输入的时间没有限制。
            audio = self.r.listen(source, timeout=20, phrase_time_limit=4)

        file_name = "./speech.wav"
        with open(file_name, "wb") as f:
            f.write(audio.get_wav_data())

        if if_cmu:
            return audio
        else:
            return self._get_file_content(file_name)

    # 从本地文件中加载音频 作为后续百度语音服务的输入
    def _get_file_content(self, file_name):
        with open(file_name, 'rb') as f:
            audio_data = f.read()
        return audio_data

    def speech_to_text(self, audio_path: str = "test.wav", if_microphone: bool = True):
        # 麦克风输入 采样频率必须为8的倍数 我们使用16000和上面保持一致
        if if_microphone:
            result = self.client.asr(self._record(), 'wav', 16000, {
                'dev_pid': 1537  # 识别中文普通话
            })
        # 从文件中读取
        else:
            result = self.client.asr(self._get_file_content(audio_path), 'wav', 16000, {
                'dev_pid': 1537  # 识别中文普通话
            })
        if result["err_msg"] != "success.":
            return "语音识别失败：" + result["err_msg"]
        else:
            return result['result'][0]

class OpenaiASR:
    def __init__(self, API_KEY):
        self.API_KEY = API_KEY
        self.r = sr.Recognizer()

    # 从麦克风收集音频并写入文件
    def _record(self, if_cmu: bool = False, rate=16000):
        with sr.Microphone(sample_rate=rate) as source:
            print('您可以开始说话了')
            audio = self.r.listen(source, timeout=20, phrase_time_limit=5)

        file_name = "./speech.wav"
        with open(file_name, "wb") as f:
            f.write(audio.get_wav_data())

        if if_cmu:
            return audio
        else:
            return self._get_file_content(file_name)

    # 从本地文件中加载音频 作为后续百度语音服务的输入
    def _get_file_content(self, file_name):
        with open(file_name, 'rb') as f:
            audio_data = f.read()
        return audio_data

    def _get_speech_text(self, audio_file):
        print('调用用语音识别')
        url = 'https://api.openai.com/v1/audio/transcriptions'
        headers = {
            'Authorization': 'Bearer ' + self.API_KEY
        }
        files = {
            'file': ('./speech.wav', audio_file),
        }
        data = {
            'model': 'whisper-1',
        }
        response = requests.post(url, headers=headers, data=data, files=files)
        result = response.json()['text']
        # print(result)
        return result

    def speech_to_text(self, audio_path: str = "test.wav", if_microphone: bool = True):
        if if_microphone:
            result = self._get_speech_text(self._record())
        else:
            result = self._get_speech_text(audio_path)
        return result

class AzureASR:
    def __init__(self, AZURE_API_KEY, AZURE_REGION):
        self.AZURE_API_KEY = AZURE_API_KEY
        self.AZURE_REGION = AZURE_REGION
        self.speech_config = speechsdk.SpeechConfig(subscription=AZURE_API_KEY, region=AZURE_REGION)

    def speech_to_text(self, audio_path: str = "test.wav", if_microphone: bool = True):
        self.speech_config.speech_recognition_language = "zh-CN"
        audio_config = speechsdk.audio.AudioConfig(use_default_microphone=True)
        speech_recognizer = speechsdk.SpeechRecognizer(speech_config=self.speech_config, audio_config=audio_config)
        print("Speak into your microphone.")
        speech_recognition_result = speech_recognizer.recognize_once_async().get()

        if speech_recognition_result.reason == speechsdk.ResultReason.RecognizedSpeech:
            print("Recognized:{}".format(speech_recognition_result.text))
            return speech_recognition_result.text
        elif speech_recognition_result.reason == speechsdk.ResultReason.NoMatch:
            print("No speech could be recognized :{}".format(speech_recognition_result.no_match_details))
        elif speech_recognition_result.reason == speechsdk.ResultReason.Canceled:
            cancellation_details = speech_recognition_result.cancellation_details
            print("Speech Recognition canceled:{}".format(cancellation_details.reason))
            if cancellation_details.reason == speechsdk.CancellationReason.Error:
                print("Error details:{}".format(cancellation_details.error_details))
                print("Did you set the speech resource key and region values?")
        return None

if __name__ == '__main__':
    # APP_ID = ''
    # API_KEY = ''
    # SECRET_KEY = ''
    # baiduasr = BaiduASR(APP_ID, API_KEY, SECRET_KEY)
    # result = baiduasr.speech_to_text()
    # print(result)
    # AZURE_API_KEY = ""
    # AZURE_REGION = ""
    # azureasr = AzureASR(AZURE_API_KEY, AZURE_REGION)
    # azureasr.speech_to_text()
    openai_api_key = ""
    openaiasr = OpenaiASR(openai_api_key)
    print(openaiasr.speech_to_text())


# pyright: reportGeneralTypeIssues=false

from dataclasses import dataclass
from typing import Any

from litestar import (
    Controller,
    get,  # pylint: disable=unused-import
)
from litestar.exceptions import NotFoundException
from litestar.params import Dependency
from livekit import AccessToken, RoomServiceClient, VideoGrant, models

from app.domain.accounts.guards import requires_active_user
from app.domain.accounts.schemas import User
from app.lib.settings import server

__all__ = ["ApiController"]

validation_skip: Any = Dependency(skip_validation=True)

@dataclass
class Token:
    room: str
    token: str

class ApiController(Controller):
    path = "/api/live/rooms"
    tags = ["Livekit Room API"]
    room_open_route = "open/{room_id:str}/{user_id:str}"
    room_list_route = "list/{room_id:str}"
    guards = [requires_active_user]

    @get(room_list_route, sync_to_thread=True)
    async def retrieve(self, room_id: str) -> models.Room:
        """Get a list of Models."""
        rooms: list[models.Room] = RoomServiceClient(
            server.LIVE_API_URL, server.LIVE_API_KEY, server.LIVE_API_SECRET
        ).list_rooms()
        for room in rooms:
            if room.sid == room_id:
                return room
        raise NotFoundException()

    @get(sync_to_thread=True)
    async def list_all(self) -> list[models.Room]:
        """Get a list of Models."""
        rooms: list[models.Room] = RoomServiceClient(
            server.LIVE_API_URL, server.LIVE_API_KEY, server.LIVE_API_SECRET
        ).list_rooms()
        return rooms

    @get(room_open_route, sync_to_thread=True)
    async def token(self, room_id: str, user_id: str, current_user: User) -> Token:
        grant = VideoGrant(
            room_join=True,
            room=room_id,
            can_publish=True,
            can_subscribe=True,
            can_publish_data=True,
            room_create=True,
            room_list=True,
            room_admin=True,
        )

        access_token = AccessToken(
            server.LIVE_API_KEY,
            server.LIVE_API_SECRET,
            grant=grant,
            identity=user_id,
            name=user_id,
        )

        return Token(room=room_id, token=access_token.to_jwt())