import mne
import numpy as np
from scipy.signal import detrend

class JointDecorrelation:

    """
    Implementation of Joint Decorrelation from de Cheveigné & Parra [2014] to
    1) Find components (linear combinations of sensors that maximize either evoked
    activity or the difference between two experimental conditions and
    2) Reproject a subset of components onto the sensor space to filter the data
    """

    def __init__(self, kind="evoked"):
        if kind not in ["evoked", "difference"]:
            raise ValueError("kind must be either 'evoked' or 'difference'!")
        self.kind = kind
        self.mixing = None
        self.unmixing = None

    def fit(self, epochs, keep1=None, keep2=None, keep3=None,
            condition1=None, condition2=None, detrending=True):

        if keep1 is None:
            keep1 = epochs.info["nchan"]
        if keep2 is None:
            keep2 = keep1
        if keep3 is None and self.kind == "difference":
            keep3 = keep2
        if condition1 is None and condition2 is None and self.kind == "difference":
            if len(list(epochs.event_id.keys())) != 2:
                raise ValueError("If conditions are not specified, "
                                 "epochs must contain exactly two types of events!")
            else:
                condition1, condition2 = list(epochs.event_id.keys())
        n_epochs, n_channels, n_times = epochs._data.shape
        if self.kind == "evoked":
            X = epochs._data
        elif self.kind == "difference":  # sort by condition
            X = np.concatenate([epochs[condition1]._data, epochs[condition1]._data])
        if detrending:
            X = detrend(X, axis=-1, type="linear")
            print("detrending data...")
        X = np.transpose(epochs._data, (1, 0, 2))
        X = X.reshape(n_channels, n_epochs * n_times).T
        L = np.tile(np.identity(n_times), n_epochs)
        P, N, Q = JointDecorrelation._transform(X, L, keep1, keep2)
        self.unmixing = P @ N @ Q
        self.mixing = Q.T @ np.diag(1/np.diag(N)) @ P.T
        if self.kind == "difference":
            L = np.concatenate([np.tile(np.identity(n_times), epochs[condition1]._data.shape[0]),
                                np.tile(np.identity(n_times), epochs[condition2]._data.shape[0])
                                * -1], axis=1)
            Y = X @ self.unmixing
            P, N, Q = JointDecorrelation._transform(Y, L, keep2, keep3)
            self.unmixing = self.unmixing @ P @ N @ Q
            self.mixing = Q.T @ np.diag(1/np.diag(N)) @ P.T @ self.mixing

    def get_components(self, epochs):
        n_epochs, n_channels, n_times = epochs._data.shape
        X = np.transpose(epochs._data, (1, 0, 2))
        X = X.reshape(n_channels, n_epochs * n_times).T
        Y = X @ self.unmixing
        Y = np.reshape(Y.T, [-1, n_epochs, n_times]).transpose([1, 0, 2])
        info = mne.create_info(Y.shape[1], epochs.info["sfreq"], ch_types="eeg")
        return mne.EpochsArray(Y, info, epochs.events, epochs.tmin)

    def reproject_components(self, epochs):
        n_epochs, n_channels, n_times = epochs._data.shape
        X = np.transpose(epochs._data, (1, 0, 2))
        X = X.reshape(n_channels, n_epochs * n_times).T
        Y = X @ self.unmixing
        X = Y @ self.mixing
        X = np.reshape(X.T, [-1, n_epochs, n_times]).transpose([1, 0, 2])
        return mne.EpochsArray(X, epochs.info, epochs.events, epochs.tmin)

    def sort_epochs(epochs, condition1, condition2):

        X = np.concatenate([epochs[condition1]._data, epochs[condition1]._data])
        events = np.concatenate([epochs.events[epochs.events[:, 2] == epochs.event_id[condition1]],
                                 epochs.events[epochs.events[:, 2] == epochs.event_id[condition2]]])
        # Do we need to chage the event time  in column 0 as well?
        return X, events

    def _transform(X, L, keep1, keep2):

        C0 = X.T @ X  # Data covariance Matrix
        D, P = np.linalg.eig(C0)  # eigendecomposition of C0
        idx = np.argsort(D)[::-1][0:keep1]  # sort array by descending magnitude
        D = D[idx]
        P = P[:, idx]
        # STEP2: Normalize to "sphere" the signal
        N = np.diag(np.sqrt(1. / D))  # diagonal whitening matrix
        Z = X @ P @ N  # sphered signal
        # STEP3: apply bias filter to the sphered data
        Zbar = L @ Z  # bias filter data
        # STEP4: Do a PCA on the bias filtered data
        C1 = Zbar.T @ Zbar  # Covariance of filtered data
        Dz, Q = np.linalg.eig(C1)  # eigendecomposition of bias filtered covariance matrix
        idx = np.argsort(Dz)[::-1][0:keep2]
        Dz = Dz[idx]
        Q = Q[:, idx]
        return P, N, Q

def surrogate_data(epochs, kind="shuffle"):

    n_epochs, n_channels, n_times = epochs._data.shape
    data = np.concatenate(epochs._data, axis=0)
    data = np.transpose(epochs._data, (1, 0, 2))
    data = data.reshape(n_channels, n_epochs * n_times).T

    if kind == "shuffle":
        [np.random.shuffle(data[:, i]) for i in range(n_channels)]

    data = np.reshape(data.T, [-1, n_epochs, n_times]).transpose([1, 0, 2])
    return mne.EpochsArray(data, epochs.info, epochs.events, epochs.tmin)

def bootstrap_components(epochs, n_bootstrap=1000, keep1=40, keep2=15, ci=0.95, invert=True):
    # pre allocate data matrix for bootstrap runs
    # TODO: implement for kind=="difference"
    ci = (((1 - ci) / 2) * 100, ((1 - ((1 - ci) / 2))) * 100)
    n_epochs, n_channels, n_times = epochs._data.shape
    data = np.zeros([n_bootstrap, keep2, n_times])
    jd = JointDecorrelation(kind="evoked")
    jd.fit(epochs, keep1=keep1, keep2=keep2)
    for i in range(n_bootstrap):
        indices = np.random.choice(np.arange(n_epochs, dtype=int), n_epochs, replace=True)
        permutated_epochs = epochs.copy()
        permutated_epochs._data = permutated_epochs._data[indices, :, :]
        jd_i = JointDecorrelation(kind="evoked")
        jd_i.fit(permutated_epochs, keep1=keep1, keep2=keep2)
        components_i = jd.get_components(permutated_epochs).average().data
        if invert:  # check if dot product of vectors is negative, if so invert
            for nc in range(components_i.shape[0]):
                if(np.dot(jd.mixing[nc, :], jd_i.mixing[nc, :])) < -1e-05:
                    components_i[nc, :] = components_i[nc, :]*-1
        data[i, :, :] = components_i
        ci_low, ci_up = np.percentile(data, ci, axis=0)

    return ci_low, ci_up

if __name__ == "__main":
    from matplotlib import pyplot as plt
    data_path = mne.datasets.sample.data_path()
    raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
    event_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'
    raw = mne.io.read_raw_fif(raw_fname, preload=True)
    events = mne.read_events(event_fname)
    tmin, tmax = -0.2, 0.5
    reject = None
    # reject = dict(eeg=80e-6)
    epochs = mne.Epochs(raw, events, tmin=-0.2, tmax=0.5, picks=('eeg'),
                        baseline=None, reject=reject, preload=True)
    epochs._data = detrend(epochs._data, axis=-1)
    con1, con2 = "1", "2"  # the conditions to compare
    epochs = epochs[[con1, con2]]  # only use auditory events
    jd = JointDecorrelation(kind="evoked")
    jd.fit(epochs, keep1=40, keep2=5)

    components = jd.get_components(epochs).average().data
    ci_low, ci_up = bootstrap_components(
        epochs, n_bootstrap=100, keep1=40, keep2=15, ci=0.95, invert=True)

    plt.plot(epochs.times, components[0, :])
    plt.fill_between(epochs.times, ci_low[0, :], ci_up[0, :], alpha=.5)

    jd = JointDecorrelation(kind="difference")
    jd.fit(epochs, keep1=40, keep2=10, keep3=5)
    components = jd.get_components(epochs).average()
    components.plot()
    reprojected = jd.reproject_components(epochs)
    reprojected.average().plot()

    # test bootstrap:
    n_bootstrap, keep2, keep1, invert = 10, 40, 1, True
    ci = (((1 - .95) / 2) * 100, ((1 - ((1 - .95) / 2))) * 100)
    n_epochs, n_channels, n_times = epochs._data.shape
    data = np.zeros([n_bootstrap, keep2, n_times])
    jd = JointDecorrelation(kind="evoked")
    jd.fit(epochs, keep1=keep1, keep2=keep2)
    components = jd.get_components(epochs).average().data
    for i in range(n_bootstrap):
        indices = np.random.choice(np.arange(n_epochs, dtype=int), n_epochs, replace=True)
        permutated_epochs = epochs.copy()
        permutated_epochs._data = permutated_epochs._data[indices, :, :]
        jd_i = JointDecorrelation(kind="evoked")
        jd_i.fit(permutated_epochs, keep1=keep1, keep2=keep2)
        components_i = jd.get_components(permutated_epochs).average().data
        if invert:  # check if dot product of vectors is negative, if so invert
            for nc in range(components_i.shape[0]):
                dotproduct = np.dot(jd_i.mixing[nc, :], jd.mixing[nc, :])
                if dotproduct < 0:
                    fig, ax = plt.subplots()
                    textstr = '\n'.join((
                        r'$|m|=%.5f$' % (np.linalg.norm(jd.mixing[:, nc]), ),
                        r'$|m_i|=%.5f$' % (np.linalg.norm(jd_i.mixing[:, nc], )),
                        r'$m x m_i=%.5f$' % (dotproduct, )))
                    ax.plot(epochs.times, components_i[nc, :], label="bootstrap component")
                    ax.plot(epochs.times, components[nc, :], label="original component")
                    props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)
                    ax.text(0.05, 0.95, textstr, transform=ax.transAxes, fontsize=14,
                            verticalalignment='top', bbox=props)
                    ax.legend()
                    plt.show()

                    components_i[nc, :] = components_i[nc, :]*-1


#coding:utf-8
import os
import shutil

main_path = r'E:\train4\neg_n16w'

a = ["2019 _ 副本.jpg"]
print(a[0][-6:-4])
print(a[0][:-9]+a[0][-4:])
if u"副本" in a[0]:
    print("1111111111111111")

res_path="E:\\cut_pic\\quick_detect_pic\\quick_pos"

for picname in os.listdir(main_path):
    # if
    if u"副本"==picname[-7:-5]:
    # if picname[:3] == 'neg':
        pic_path = os.path.join(main_path,picname)
        # dst_path =os.path.join(res_path,picname)
        # shutil.move(pic_path,dst_path)
        os.remove(pic_path)
        # add_pic_path = os.path.join(main_path,picname[:-9]+"tsts"+picname[-4:])
        # add_pic_path = os.path.join(main_path,picname[:-9]+"tsts"+picname[-4:])
        # shutil.move(add_pic_path, res_path+"\\"+picname[:-9]+picname[-4:])
        # os.remove(add_pic_path)
        # os.rename(pic_path,add_pic_path)


from fastapi import HTTPException
from sqlalchemy import Column, Integer, String, Table, ForeignKey
from sqlalchemy.orm import relationship
from db import Base
from models.subject import Subject
import json

category_subject_association = Table(
    'category_subject', Base.metadata,
    Column('category_id', Integer, ForeignKey("categories.id")),
    Column('subject_id', Integer, ForeignKey('subjects.id'))
)

class Category(Base):
    __tablename__ = 'categories'
    id = Column('id', Integer, primary_key=True)
    parent_id = Column(Integer, ForeignKey('categories.id'))
    parent = relationship('Category', remote_side=[id],backref="sub_categories")
    name = Column('name', String(32))
    subjects = relationship("Subject", secondary=category_subject_association)

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

    def get_children(self):
        return self.subjects if len(self.subjects) > 0 else self.sub_categories

    def append_child(self, children):
        if type(children) == Category:
            if len(self.subjects) > 1:
                raise HTTPException(status_code=400, detail="Invalid Child type[Category] for this category")
            else:
                self.sub_categories.append(children)
        elif type(children) == Subject:
            if len(self.sub_categories) > 1:
                raise HTTPException(status_code=400, detail="Invalid Child type[Subject] for this category")
            else:
                self.subjects.append(children)
        else:
            raise HTTPException(status_code=400, detail="Invalid Child type for exam")

    def json(self):
        child_json = "[ "
        if self.get_children() is not None:
            for child in self.get_children():
                child_json += json.dumps(child.json()) + ","
        child_json = child_json[:-1] + "]"
        return {
            "id": self.id,
            "name": self.name,
            ("subjects" if len(self.subjects) > 0 else "categories"): json.loads(child_json)
        }


import logging
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import tensorflow as tf
tf.get_logger().setLevel(logging.ERROR)
tf.keras.utils.disable_interactive_logging()

physical_devices = tf.config.experimental.list_physical_devices('GPU')
assert len(physical_devices) > 0, "Not enough GPU hardware devices available"
config = tf.config.experimental.set_memory_growth(physical_devices[0], True)
config = tf.config.experimental.set_memory_growth(physical_devices[1], True)

from apache_beam.io.textio import WriteToText
from sklearn.mixture import GaussianMixture
from sklearn.model_selection import LeaveOneOut
import pyarrow as pa
import numpy as np
import itertools as ite
from functools import reduce
from mtsa import (
    MFCCMix,
    Hitachi,
    FEATURES,
    files_train_test_split,
    calculate_aucroc,
    get_tsne_results,
    files_train_test_split_combined
)
import os
import glob
from functools import partial
from mtsa.metrics import calculate_aucroc
from mtsa.common import elapsed_time
from mtsa.utils import files_train_test_split
from apache_beam.io import WriteToText
from apache_beam.pipeline import PipelineOptions
import apache_beam as beam
import argparse

from mtsa import get_tsne_results

class IndividualCreateKeyFn(beam.DoFn):
    def __init__(self, *args, **kwargs) -> None:
        beam.DoFn.__init__(self)
        self.__dict__.update(kwargs)

    def process(self, args):
        model_name, model = args
        all_paths = glob.glob(os.path.join(self.path, f'*{os.sep}' * self.level))
        for path in all_paths:
            X_train, X_test, y_train, y_test = files_train_test_split(path)
            metrics = []
            yield (path, model_name, model, X_train, X_test, y_train, y_test, metrics)

class CombinedCreateKeyFn(beam.DoFn):
    def __init__(self, *args, **kwargs) -> None:
        beam.DoFn.__init__(self)
        self.__dict__.update(kwargs)

    def process(self, args):
        model_name, model = args
        all_paths = glob.glob(os.path.join(self.path, f'*{os.sep}' * (self.level - 1)))
        for path in all_paths:
            paths = np.array(glob.glob(os.path.join(path, f'*{os.sep}')))
            loo = LeaveOneOut()
            splits = loo.split(paths)
            for split in splits:
                path_train = paths[split[0]]
                path_test = paths[split[1]]
                train_X_train, train_X_test, train_y_train, train_y_test = files_train_test_split_combined(path_train)
                test_X_train, test_X_test, test_y_train, test_y_test = files_train_test_split_combined(path_test)
                metrics = []
                yield (path_test[0], model_name, model, train_X_train, test_X_test, train_y_train, test_y_test, metrics)

class FitFn(beam.DoFn):
    def __init__(self, *args, **kwargs) -> None:
        beam.DoFn.__init__(self)
        self.__dict__.update(kwargs)

    def process(self, element):
        path, model_name, model, X_train, X_test, y_train, y_test, metrics = element
        result_fit = elapsed_time(model.fit, X_train, y_train)
        metrics.append({
            "name": "fit_time",
            "value": result_fit.time_elapsed
        }
        )
        yield (path, model_name, model, X_train, X_test, y_train, y_test, metrics)

class RocFn(beam.DoFn):
    def __init__(self, *args, **kwargs) -> None:
        beam.DoFn.__init__(self)
        self.__dict__.update(kwargs)

    def process(self, element):
        path, model_name, model, X_train, X_test, y_train, y_test, metrics = element
        result_roc = elapsed_time(
            calculate_aucroc, model, X_test, y_test)
        metrics.append({
            "name": "roc_time",
            "value": result_roc.time_elapsed
        },)
        metrics.append({
            "name": "roc_value",
            "value": result_roc.fun_return
        },)
        yield (path, model_name, model, X_train, X_test, y_train, y_test, metrics)

class TSNEFn(beam.DoFn):
    def __init__(self, *args, **kwargs) -> None:
        beam.DoFn.__init__(self)
        self.__dict__.update(kwargs)

    def process(self, element):
        path, model_name, model, X_train, X_test, y_train, y_test, metrics = element
        x, y, hue = get_tsne_results(model, X_test, y_test)
        tsne = {
            'x': list(x),
            'y': list(y),
            'hue': list(hue)
        }
        yield (path, model_name, model, X_train, X_test, y_train, y_test, metrics, tsne)

class TransformFn(beam.DoFn):
    def __init__(self, *args, **kwargs) -> None:
        beam.DoFn.__init__(self)
        self.__dict__.update(kwargs)

    def process(self, element):
        path, model_name, model, X_train, X_test, y_train, y_test, metrics, tsnes = element

        yield {
            "path": path,
            "model": model_name,
            "metrics": metrics,
            "tsnes": tsnes
        }

def get_models_mfccmix(n_components):
    def get_features():
        number_features = np.arange(1, len(FEATURES)+1)
        def combinations(r): return ite.combinations(FEATURES, r)
        all_combinations = map(combinations, number_features)
        features = reduce(lambda x, y: ite.chain(x, y), all_combinations)
        return features

    def build_mfccmix_by_features(features):
        mfccmix = MFCCMix(
            features=list(features),
            final_model=GaussianMixture(n_components=n_components)
        )
        return "MFCCMix " + "+".join([f[0] for f in features]), mfccmix

    features = get_features()
    mfcc_models = map(build_mfccmix_by_features, features)
    return mfcc_models

def get_models(n_components):
    models_hitachi = [("Hitachi", Hitachi())]
    # models_mfccmix = get_models_mfccmix(n_components)
    models_mfccmix = []
    all_models = reduce(lambda x, y: ite.chain(
        x, y), (models_hitachi, models_mfccmix))
    return list(all_models)

def run_pipeline(known_args):

    if known_args.script == 'individual':
        create_key_fn = IndividualCreateKeyFn
    elif known_args.script == 'combined':
        create_key_fn = CombinedCreateKeyFn

    with beam.Pipeline() as pipeline:

        models = pipeline | "models" >> beam.Create(known_args.runs * get_models(known_args.n_components))

        keys = models | "keys" >> beam.ParDo(create_key_fn(path=known_args.path, level=known_args.level))

        fits = keys | "train" >> beam.ParDo(FitFn())

        rocs = fits | "test" >> beam.ParDo(RocFn())

        tsnes = rocs | "tsne" >> beam.ParDo(TSNEFn())

        transform = tsnes | beam.ParDo(TransformFn(path=known_args.path))

        write = transform | WriteToText(
            f"{known_args.output}{known_args.script}.text")

def main(argv=None):

    parser = argparse.ArgumentParser()
    parser.add_argument('--script', choices=['individual', 'combined'], required=True)
    parser.add_argument('--path', type=str, required=True)
    parser.add_argument('--level', type=int, required=True)
    parser.add_argument('--output', type=str, required=True)
    parser.add_argument('--runs', type=int, required=True)
    parser.add_argument('--n_components', type=int, required=True)
    parser.add_argument('--sampling_rate', type=int)
    # parser.add_argument('--perplexity', type=int)

    known_args, pipeline_args = parser.parse_known_args(argv)

    beam_options = PipelineOptions()

    run_pipeline(known_args)

if __name__ == "__main__":
    main()


#
# PySNMP MIB module PYSNMP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PYSNMP-MIB
# Produced by pysmi-0.3.4 at Wed May  1 14:43:00 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, ValueRangeConstraint, ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueRangeConstraint", "ConstraintsUnion", "ValueSizeConstraint", "SingleValueConstraint")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
MibScalar, MibTable, MibTableRow, MibTableColumn, Gauge32, Bits, NotificationType, enterprises, IpAddress, Counter64, MibIdentifier, ObjectIdentity, ModuleIdentity, Counter32, iso, TimeTicks, Unsigned32, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Gauge32", "Bits", "NotificationType", "enterprises", "IpAddress", "Counter64", "MibIdentifier", "ObjectIdentity", "ModuleIdentity", "Counter32", "iso", "TimeTicks", "Unsigned32", "Integer32")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
pysnmp = ModuleIdentity((1, 3, 6, 1, 4, 1, 20408))
pysnmp.setRevisions(('2017-04-14 00:00', '2005-05-14 00:00',))

if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
    if mibBuilder.loadTexts: pysnmp.setRevisionsDescriptions(('Updated addresses', 'Initial revision',))
if mibBuilder.loadTexts: pysnmp.setLastUpdated('201704140000Z')
if mibBuilder.loadTexts: pysnmp.setOrganization('The PySNMP Project')
if mibBuilder.loadTexts: pysnmp.setContactInfo('E-mail: Ilya Etingof <etingof@gmail.com> GitHub: https://github.com/etingof/pysnmp')
if mibBuilder.loadTexts: pysnmp.setDescription('PySNMP top-level MIB tree infrastructure')
pysnmpObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 1))
pysnmpExamples = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 2))
pysnmpEnumerations = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3))
pysnmpModuleIDs = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3, 1))
pysnmpAgentOIDs = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3, 2))
pysnmpDomains = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3, 3))
pysnmpExperimental = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 9999))
pysnmpNotificationPrefix = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 4))
pysnmpNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 4, 0))
pysnmpNotificationObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 4, 1))
pysnmpConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 5))
pysnmpCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 5, 1))
pysnmpGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 5, 2))
mibBuilder.exportSymbols("PYSNMP-MIB", pysnmpNotifications=pysnmpNotifications, pysnmpObjects=pysnmpObjects, pysnmpGroups=pysnmpGroups, pysnmp=pysnmp, pysnmpNotificationObjects=pysnmpNotificationObjects, pysnmpExamples=pysnmpExamples, pysnmpCompliances=pysnmpCompliances, PYSNMP_MODULE_ID=pysnmp, pysnmpNotificationPrefix=pysnmpNotificationPrefix, pysnmpEnumerations=pysnmpEnumerations, pysnmpModuleIDs=pysnmpModuleIDs, pysnmpAgentOIDs=pysnmpAgentOIDs, pysnmpConformance=pysnmpConformance, pysnmpExperimental=pysnmpExperimental, pysnmpDomains=pysnmpDomains)


import tkinter
from tkinter import messagebox

# Gjenstand klassen består av 4 inputs/verdier:

# navn: hva heter gjenstander/ hva er gjenstanden

# fra_aar og til_aar: hvilken tid er gjenstanden fra? Hvis vi ikke vet eksakt,
#  hvilke årstall befinner gjenstanden seg mellom?

# sted: hvor er gjenstanden fra? F.eks: Rogaland, Sandnes...

#GUI til gjenstand lager et vindu hvor man kan skrive inn for de 4 inputtene/verdiene
# i klassen Gjenstand

# Det lages en liste som lagrer gjenstandene, og disse printes når vinduet lukkes.

class Gjenstand:
    def __init__(self, navn, fra_aar, til_aar, sted):
        self.navn = navn
        self.fra_aar = fra_aar
        self.til_aar = til_aar
        self.sted = sted

    def __str__(self):
        if self.fra_aar == self.til_aar:
            return f"{self.navn} fra år {self.fra_aar} fra {self.sted}"
        return f"{self.navn} fra tidsperiode (år {self.fra_aar}-{self.til_aar}) fra {self.sted}"

class GjenstandGUI:
    def __init__(self):
        self.gjenstander = []

        self.hovedvindu = tkinter.Tk()

        self.navn = tkinter.Label(self.hovedvindu, text="Navn på gjenstanden:")
        self.navn.grid(column=0, row=0)
        self.navn_felt = tkinter.Entry(self.hovedvindu, width=10)
        self.navn_felt.grid(column=1, row=0)

        self.tidligste_aar = tkinter.Label(self.hovedvindu, text="Tidligste år:")
        self.tidligste_aar.grid(column=0, row=1)
        self.tidlig_aar_felt = tkinter.Entry(self.hovedvindu, width=10)
        self.tidlig_aar_felt.grid(column=1, row=1)

        self.seneste_aar = tkinter.Label(self.hovedvindu, text="Seneste år:")
        self.seneste_aar.grid(column=0, row=2)
        self.senest_aar_felt = tkinter.Entry(self.hovedvindu, width=10)
        self.senest_aar_felt.grid(column=1, row=2)

        self.gjenstand_fra = tkinter.Label(self.hovedvindu, text="Hvor er gjenstanden fra:")
        self.gjenstand_fra.grid(column=0, row=3)
        self.gjenstand_fra_felt = tkinter.Entry(self.hovedvindu, width=10)
        self.gjenstand_fra_felt.grid(column=1, row=3)

        self.fjern_knapp = tkinter.Button(self.hovedvindu, text="Fjern innhold", command=self.fjern_innhold_metode)
        self.fjern_knapp.grid(column=0, row=4)
        self.lagre_knapp = tkinter.Button(self.hovedvindu, text="Lagre gjenstand", command=self.registrer_gjenstand)
        self.lagre_knapp.grid(column=1, row=4)

        tkinter.mainloop()

    def fjern_innhold_metode(self):
        self.navn_felt.delete(0, tkinter.END)
        self.tidlig_aar_felt.delete(0, tkinter.END)
        self.senest_aar_felt.delete(0, tkinter.END)
        self.gjenstand_fra_felt.delete(0, tkinter.END)

    def registrer_gjenstand(self):
        try:
            tidlig_aar = int(self.tidlig_aar_felt.get())
        except ValueError:
            messagebox.showerror("Må være et tall!")
            return
        try:
            senest_aar = int(self.senest_aar_felt.get())
        except ValueError:
            messagebox.showerror("Må være et tall!")
            return
        gjenstander = Gjenstand(self.navn_felt.get(), tidlig_aar, senest_aar, self.gjenstand_fra_felt.get())
        self.gjenstander.append(gjenstander)
        self.fjern_innhold_metode()

if __name__ == "__main__":
    gui = GjenstandGUI()
    for gjenstand in gui.gjenstander:
        print(gjenstand)


import random
import pylab

# Global Variables
MAXRABBITPOP = 1000
CURRENTRABBITPOP = 500
CURRENTFOXPOP = 30

def rabbitGrowth():
    """
    rabbitGrowth is called once at the beginning of each time step.

    It makes use of the global variables: CURRENTRABBITPOP and MAXRABBITPOP.

    The global variable CURRENTRABBITPOP is modified by this procedure.

    For each rabbit, based on the probabilities in the problem set write-up,
      a new rabbit may be born.
    Nothing is returned.
    """
    # you need this line for modifying global variables
    global CURRENTRABBITPOP

    # TO DO
    for anzahl in range(CURRENTRABBITPOP):
        if random.random() <= (1 - (CURRENTRABBITPOP / MAXRABBITPOP)):
            CURRENTRABBITPOP += 1

    return()

def foxGrowth():
    """
    foxGrowth is called once at the end of each time step.

    It makes use of the global variables: CURRENTFOXPOP and CURRENTRABBITPOP,
        and both may be modified by this procedure.

    Each fox, based on the probabilities in the problem statement, may eat
      one rabbit (but only if there are more than 10 rabbits).

    If it eats a rabbit, then with a 1/3 prob it gives birth to a new fox.

    If it does not eat a rabbit, then with a 1/10 prob it dies.

    Nothing is returned.
    """
    # you need these lines for modifying global variables
    global CURRENTRABBITPOP
    global CURRENTFOXPOP

    # TO DO
    for anzahl in range(CURRENTFOXPOP):
        if CURRENTRABBITPOP > 10:
            if random.random() <= (CURRENTRABBITPOP / MAXRABBITPOP):
                CURRENTRABBITPOP -= 1
                if random.random() <= ( 1 / 3 ):
                    CURRENTFOXPOP += 1
        else:
            if random.random() <= 0.1:
                CURRENTFOXPOP -= 1
    return()

def runSimulation(numSteps):
    """
    Runs the simulation for `numSteps` time steps.

    Returns a tuple of two lists: (rabbit_populations, fox_populations)
      where rabbit_populations is a record of the rabbit population at the
      END of each time step, and fox_populations is a record of the fox population
      at the END of each time step.

    Both lists should be `numSteps` items long.
    """

    # TO DO
    kaninchen = []; fuechse = []

    for n in range(numSteps):
        rabbitGrowth()
        foxGrowth()
        kaninchen.append(CURRENTRABBITPOP)
        fuechse.append(CURRENTFOXPOP)

    return (kaninchen, fuechse)

fuechse   = list(runSimulation(200)[:2])
kaninchen = list(runSimulation(200)[:1])
xVals = []
for i in range(0,200):
    xVals.append(i)
#print(xVals)

#print(kaninchen)
print(fuechse)

#pylab.plot(xVals, yVals, 'bo', label = 'Measured displacements')
#pylab.title('Measured Displacement of Spring')
#pylab.xlabel('Force (Newtons)')
#pylab.ylabel('Distance (meters)')

coeff = polyfit(range(len(rabbitPopulationOverTime)), rabbitPopulationOverTime, 2)

plot(polyval(coeff, range(len(rabbitPopulationOverTime))))


#
# FILE TESTS
#

import testfw
import os

def addIntegrationTests(env, parent_dir, testProgram, serverProgram):
    #
    # FILE TESTS (CONCURRENT CLIENTS)
    #

    env.addIntegrationTest(testfw.integration_test.IntegrationTest(
        name = 'CFSFile:TestCreateOpenConcurrent',
        init_script = os.path.join(parent_dir, 'test/integration/cfs/init.sh'),
        testfw = testProgram, server = serverProgram,
        clients = {
            'C1': ( testProgram, [('T1', 'CFSFile:TestCreate')]),
            'C2': ( testProgram, [('T1', 'CFSFile:TestOpen')])
        },
        rendezvous = [('C1:T1:E2:block', 'C2:T1:E1:block'),
                      ('C1:T1:E3:block', 'C2:T1:E3:block')]
    ))


from settings import SIZE_X, SIZE_Y
from vector import Vec2D

class Wall:
    def __init__(self, coords):
        self.coords = coords

    def __eq__(self, other):
        return self.coords == other.coords

class Bullet:
    ttl = 100

    def __init__(self, coords, direction, angle, owner):
        self.pos = coords
        self.direction = direction
        self.angle = angle
        self.owner = owner

    def flight(self, world, alpha):
        move = self.pos + self.direction
        if move[0] >= 0 and move[0] < SIZE_X and \
           move[1] >= 0 and move[1] < SIZE_Y:
            self.pos = move
            self.ttl -= 10


import time

time_start = time.time_ns()/1000

for i in range(2,10001):
	prime_list = []
	tok = False
	for j in range(2,i):
		if i%j == 0:
			tok = True
			break
	if not tok:
		prime_list.append(i)

time_stop = time.time_ns()/1000
print("Python Time difference =", time_stop - time_start, "[us]")


import h5py
from PIL import Image
import random
import numpy as np
import os
import glob
import yaml

# Load config file
# ! Specify base_dir
with open('/workspaces/ps_project/config.yaml') as file:
    config = yaml.safe_load(file)

# Class encapsulating the data preparation functionality
class SamplePrepare(object):

    # @param src_path: path to raw images
    # @param dest_path: path to store
    # @param size: patch_size of images
    def __init__(self, src_path, dest_path, size):
        self.src_path = src_path
        self.dest_path = dest_path
        self.size = size

    # Stores the ip and op image in h5 file using self
    def __crop_store(self, op_present = False):
        for ip_file in glob.glob(self.current_path + '*.bmp'):
            file_name = (ip_file.split('/')[-1])[:-4]

            # input image
            ip_image = np.array(Image.open(ip_file))
            img_size = ip_image.shape[0]
            border = 16
            pieces = img_size // (self.size - border)
            pieces -= 1

            start_i = 0
            end_i = 32

            for i in range(0, pieces):
                start_j = 0
                end_j = 32
                for j in range(0, pieces):

                    name = file_name + '_' + str(i).zfill(2) + '_' + str(j).zfill(2)
                    a = ip_image[start_j:  end_j, start_i: end_i]
                    self.ip.create_dataset(name, data = a)
                    start_j += 16
                    end_j = start_j + 32

                start_i += 16
                end_i = start_i + 32

            b = np.zeros(shape = (img_size, img_size, config["wavelengths"]), dtype = np.uint16)

            start_i = 0
            end_i = 32

            for i in range(0, pieces):
                start_j = 0
                end_j = 32
                for j in range(0, pieces):

                    name = file_name + '_' + str(i).zfill(2) + '_' + str(j).zfill(2)
                    a = b[start_j:  end_j, start_i: end_i, :]
                    self.op.create_dataset(name, data = a)
                    start_j += 16
                    end_j = start_j + 32

                start_i += 16
                end_i = start_i + 32

    def prepare_sample(self):
        print("Creating image dataset...")
        self.file = h5py.File(self.dest_path + 'sample.h5', 'w')
        self.ip = self.file.create_group('ip')
        self.op = self.file.create_group('op')

        print(f"Output path: {self.dest_path}")
        self.current_path = self.src_path + '/'
        self.__crop_store()


# Example 1
def sum_two_num(num_a, num_b):
    total = num_a + num_b
    print(total)

sum_two_num(2, 4)

"""
>>> sum_two_num(2, 4)
6

-`2` and `4` are the argument passed into the function `sum_two_num`. The parameters are `num_a` and `num_b`
"""

# Example 2
sum_two_num(2, 4)  # Values as arguments

a = 5
b = 10
sum_two_num(a, b)  # Variable as arguments

sum_two_num(3 + 5, 6 + b)  # Expression as arguments

"""
>>> sum_two_num(2, 4)
6

>>> a = 5
>>> b = 10
>>> sum_two_num(a, b)
15

>>> sum_two_num(3 + 5, 6 + b)
24
"""

# Example 3
def sum_two_num_local():
    num_a = 4
    num_b = 2

print(num_a)
"""
NameError: name 'num_a' is not defined

-`num_a` is a local variable defined within `sum_two_num_local`, hence it raise a NameError when used outside the function.
"""

# Example 4
def sum_two_num_parameter(num_a, num_b):
    total = num_a + num_b
    print(total)

print(num_a + num_b)
"""
NameError: name 'num_a' is not defined

-`num_a` and `num_b` are local variables within `sum_two_num_parameter`, hence it raise a NameError when used outside the function.
"""

# Example 5
num_x = 100  # Global
def sum_two_num_global_local_1():
    num_x = 10  # Local
    total = num_x + 2
    print(total)

sum_two_num_global_local_1()

num_y = 100  # Global
def sum_two_num_global_local_2():
    total = num_y + 2
    print(total)

sum_two_num_global_local_2()

"""
>>> sum_two_num_global_local_1()
12
>>> sum_two_num_global_local_2()
102

- The function will first search within the local scope for the variable. If it finds the variable within the local scope, it will use it.
If it cannot find the variable within the local scope, it will then look for it in the global scope.
For `sum_two_num_global_local_1`, since the variable `num_x` is already found within the local scope (10), thus it did not use the `num_x` define in the global scope (100), thus the total will be equal to 12 (10 + 2)
For `sum_two_num_global_local_2`, since it cannot find the variable `num_y` locally, it looked for it in the global scope, thus total will be equal to 102 (100 + 2)
"""

# References:
# No resources are consulted to solve the given problems


import logging
import tensorflow as tf
import collections
from vocab import Vocab
import os
import pickle
import json

"""
用这个程序替代官方run.py里的prepare方法。
准备vocab文件，保存预训练的词向量
"""

class Param(collections.namedtuple("param",
                                   ["train_files","dev_files", "test_files",
                                    "vocab_dir", "model_dir", "result_dir", "summary_dir",
                                    "max_p_num", "max_p_len", "max_q_len",
                                    "embed_size", "use_embd"])):
    pass

# override /DuReader/tensorflow/dataset.BRCDataset._load_dataset + word_iter
def load_dataset(paths, param, train=False):
    for path in paths:
        for data_path in tf.gfile.Glob(path):
            print(data_path)
            with open(data_path, "r", encoding="utf-8") as fin:
                for lidx, line in enumerate(fin):
                    sample = json.loads(line.strip())
                    yield sample

# override /DuReader/tensorflow/run.prepare
def prepare(args):
    """
    checks data, creates the directories, prepare the vocabulary and embeddings
    """
    logger = logging.getLogger("brc")
    logger.info('Checking the data files...')
    for data_path in tf.gfile.Glob(args.train_files + args.dev_files + args.test_files):
        assert tf.gfile.Exists(data_path), '{} file does not exist.'.format(data_path)

    logger.info('Preparing the directories...')
    for dir_path in [args.vocab_dir]:
        if not os.path.exists(dir_path):
            os.makedirs(dir_path)

    logger.info('Building vocabulary...')
    brc_data = load_dataset([args.train_files, args.dev_files, args.test_files], args, train=True)
    vocab = Vocab(lower=True)
    for sample in brc_data:
        for token in sample['segmented_question']:
            vocab.add(token)
        for doc in sample['documents']:
            for p in doc['segmented_paragraphs']:
                for token in p:
                    vocab.add(token)

    unfiltered_vocab_size = vocab.size()
    vocab.filter_tokens_by_cnt(min_cnt=10)
    filtered_num = unfiltered_vocab_size - vocab.size()
    logger.info('After filter {} tokens, the final vocab size is {}'.format(filtered_num,
                                                                            vocab.size()))

    logger.info('Assigning embeddings...')
    if args.use_embd:
        vocab.load_pretrained_embeddings("w2v_pe.txt")
    else:
        vocab.randomly_init_embeddings(args.embed_size)

    logging.info(vocab)
    logger.info('Saving vocab...')
    with open(os.path.join(args.vocab_dir, 'vocab.data'), 'wb') as fout:
        pickle.dump(vocab, fout)

    logger.info('Done with preparing!')

if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger("brc")

    working_dir = "./"
    # param = Param(["../data/train_preprocessed/trainset/*.json_pe"],
    #               dev_files=["../data/dev_preprocessed/devset/*.json_pe"],
    #               test_files=["../data/test1_preprocessed/test1set/*.json_pe"],
    #               vocab_dir=working_dir+"vocab/",
    #               model_dir=working_dir+"models/",
    #               result_dir=working_dir+"results/",
    #               summary_dir=working_dir+"summary/",
    #               max_p_num=5,
    #               max_p_len=800,
    #               max_q_len=60,
    #               embed_size=100,
    #               use_embd=True)
    #
    # prepare(param)

    with open("resource/vocab/vocab.data", "rb") as f:
        vocab = pickle.load(f)
    pass


''' a = 2
b = 1

if a < b:
    print("a es menor que b")
else:
    print("a es mayor que b")

 '''
    #Nesse exemplo vemos que nao precisamos colocar function
    # como no JS, e vemos que if e o primeiro e chamamos de
    # else de se nao ou se nao for if e else
    #--------------------------------------------------------
'''
a = True

if a:
    print("A es verdadero")
else:
    print("A es falso")

    #Nesse exemplo vemos que a e verdadeito pois definimos ele como boeleanas  '''
'''
a = False

if type(a) is bool:
    print("A es booleano")
else:
    print("A es otyo tipo de dato")

     '''

a = 10
b = 5
c = 10

if a>b and b>c: #Aqui escrevemos que se a e maior que b e b e maior que c a condicao sera verdadeira
    print("Las dos condiciones son verdaderas")


from scipy.stats import lognorm
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import random
import math

#max number of calls handled
n = 41

#values for random call generation
maxValue = 3600
skewness = 0.5
average_no_calls=99
std_deviation = 27

graph_x2=[]
graph_y2=[]

#generate random varibales for simulation
def create_random_variables():
    #generate random # of calls from normal distribution
    no_calls = int(random.normalvariate(average_no_calls,std_deviation))
    #if no_calls invalid set to standard avergae # calls not in busy hour
    if no_calls <= 0:
        no_calls = 67

    #get random length of calls
    #random_call_length2 = lognorm.rvs(s =skewness,loc=average_no_calls, size=no_calls)
    random_call_length2 = np.random.random_sample(size = no_calls)
    c = 0
    while c < len(random_call_length2):
        x = 1 - random_call_length2[c]
        random_call_length2[c] = math.log(x)/ -(1/900)
        c+=1
    #checks to make sure call lenght is ok
    if (len(random_call_length2) == 0):
        random_call_length2 = [0.1,0.2,0.3]
    for call in random_call_length2:
        if call < 0 or np.isnan(call):
            random_call_length2[call] = 0.1

    np.seterr(all='raise')
    #normalise data between 0-3600 seconds
    # try:
    #     random_call_length2 = random_call_length2 - min(random_call_length2)
    #     random_call_length2 = random_call_length2 / max(random_call_length2)
    #     random_call_length2 = random_call_length2 * maxValue
    # except FloatingPointError:
    #     print("Invalid value caught and programme continues")

    #put random call lengths into a list parsed into ints
    random_call_lengths_int = []
    for value in random_call_length2:
        if math.isnan(value):
            random_call_lengths_int.append(900)
            continue
        random_call_lengths_int.append(int(value))

    p = 0
    time_between_calls = int(maxValue/no_calls)
    time=0
    call_dict = {}

    #assign call length to call start time
    while p < no_calls:
        time += time_between_calls
        call_dict.update({time:random_call_lengths_int[p]})
        p+=1

    return call_dict

#carry out Monte Carlo Simulation
def simulate_calls(call_dict):
    time = 0
    simultaneous_calls=0
    skip_because_dropped=[]
    queued_calls = {}
    completed_queued_calls = []
    call_index=0
    end_q_length=0

    while time < maxValue:
        q = 0
        #attempt to add queued calls first due to FIFO
        while q < len(queued_calls):
            #If time = queued call start time, add it to simultaneous cal count, given there is room
            #Otherwise incrament its start time value in the queued by 1
            if queued_calls[q][0] == time:
                if simultaneous_calls < n:
                    simultaneous_calls +=1
                    completed_queued_calls.append(queued_calls[q][0])
                else:
                    queued_calls[q][0]+=1
            #If queued call end time = time, take it off simultaneous call count
            if (queued_calls[q][0] + queued_calls[q][1]) == time:
                simultaneous_calls -=1
            q+=1

        for call in call_dict.items():
            #If time = call start time, add it to simultaneous calls count
            #otherwise queue and add it to queued_calls list
            if call[0] == time:
                if simultaneous_calls < n:
                    simultaneous_calls +=1
                else:
                    queued_calls[call_index] = list()
                    queued_calls[call_index].extend((call[0]+1,call[1]+1))
                    call_index +=1
                    skip_because_dropped.append(call[0])
            #If call end time = time, take it off simultaneous call count
            #Check to make sure that call has not been queued
            if (call[1] + call[0]) == time:
                if call[0] in skip_because_dropped:
                    continue
                simultaneous_calls -=1
        time +=1
    #number of calls left on the queue at the end of the hour
    end_q_length = len(queued_calls) - len(completed_queued_calls)

    #get params to calculate GOS manually
    avg_call_duration = sum(call_dict.values())/len(call_dict.values())
    avg_offered_traffic = (avg_call_duration/maxValue)*len(call_dict.values())
    avg_GOS_from_queued=100*len(queued_calls)/len(call_dict)

    return(avg_call_duration,len(call_dict),avg_offered_traffic,avg_GOS_from_queued,end_q_length)

def calculate_erlangc(bottom_range,top_range):
    global graph_x2
    global graph_y2
    np.seterr(all='raise')
    all_data= []
    iterator = bottom_range
    while iterator <= top_range:
        Ao = iterator
        i = 1
        n_factorial = 1
        factorial_list=[]
        numerator = 0
        #calculate factorial
        while i <= n:
            n_factorial= n_factorial * i
            factorial_list.append(n_factorial)
            i +=1
        #calculate numerator
        try:
            a_add_on = n/(n-Ao)
        except ZeroDivisionError:
            a_add_on = 0
        numerator = ((Ao**n)/factorial_list[n-1]) * a_add_on
        denominator=0
        j = 1
        #calculate denominator
        while j < len(factorial_list):
            denominator +=(Ao**j)/factorial_list[j-1]
            j+=1
        denominator +=1
        denominator += (((Ao ** n)/factorial_list[n-1])* a_add_on)
        #calculate GOS
        E1 = numerator/denominator
        #print("Offered traffic %s Erlang   GOS %s "%(iterator, E1*100))
        iterator +=1
        all_data.append([Ao,E1*100])
        graph_x2.append([Ao])
        graph_y2.append([E1*100])

if __name__ == "__main__":
    simulation_list = []
    graph_x=[]
    graph_y=[]
    print("Please wait a moment while the programme executes...")
    k=0
    while k < 500:
        call_dictionary = create_random_variables()
        call_dur,calls,offered_traffic,GOS,unasnwered_calls =simulate_calls(call_dictionary)
        graph_x.append(offered_traffic)
        graph_y.append(GOS)
        simulation_list.append([call_dur,calls,offered_traffic,GOS,unasnwered_calls])
        k+=1

    print("\nResults from Monte deCarlo simulation. Offered traffic varied with random number of calls and varied call length.\nConstant channels = 41")
    results_df = pd.DataFrame.from_records(simulation_list, columns=['Avg Call Duration',
                                                           'Avg No Calls',
                                                           'Avg Offered Traffic',
                                                           'Avg GOS',
                                                           'Avg No Unanswered Calls'])
    print(results_df.describe())

    xs, ys = zip(*sorted(zip(graph_x, graph_y)))

    calculate_erlangc(results_df['Avg Offered Traffic'].min(),results_df['Avg Offered Traffic'].max())
    plt.plot(xs,ys)
    plt.plot(graph_x2,graph_y2)
    plt.xlabel("Ao")
    plt.ylabel("GOS")
    plt.title("Erlang C formula Vs Simulation with Decaying Exponential")
    plt.show()


import random
from DeepRTS import Engine
from DeepRTS.python import scenario
from DeepRTS.python import Config
from DeepRTS.python import Game

episodes = 100
steps = 100

MAP="32.json"

gui_config = Config(
            render=True,
            view=True,
            inputs=False,
            caption=False,
            unit_health=True,
            unit_outline=True,
            unit_animation=True,
            audio=False,
            audio_volume=50
        )

engine_config = Engine.Config.defaults()

game = Game(
            MAP,
            n_players = 1,
            engine_config = engine_config,
            gui_config = gui_config,
            terminal_signal = False
        )
game.set_max_fps(1000000)
game.set_max_ups(1000000)

for ep in range(episodes):
    print("Episode " + str(ep + 1))
    game.start()
    game.reset()

    for step in range(steps):
        print("Step " + str(step + 1))
        player = game.players[0]
        action = random.randint(0, 15)
        player.do_action(action + 1)

        game.update()
        state = game.get_state()

        game.render()
        game.view()

        print("Current state: ")
        print(state)
        print("FPS: " + str(game.get_fps()))


import os
import warnings
from typing import List, Optional

from .. import exceptions, utils
from . import base

__all__ = ("Babel",)

class Babel(base.BaseCompiler):
    name = "babel"
    input_extension = "es6"
    output_extension = "js"

    def __init__(
        self,
        executable: str = "babel",
        sourcemap_enabled: bool = False,
        modules: Optional[str] = None,
        plugins: Optional[str] = None,
        presets: Optional[str] = None,
    ):
        self.executable = executable
        self.is_sourcemap_enabled = sourcemap_enabled
        if modules:
            warnings.warn(
                "'modules' option is removed in Babel 6.0. Use `plugins` instead.", DeprecationWarning, stacklevel=2
            )
        self.modules = modules
        self.plugins = plugins
        self.presets = presets
        super().__init__()

    def get_extra_args(self) -> List[str]:
        args = []

        if self.modules is not None:
            args += ["--modules", self.modules]

        if self.plugins is not None:
            args += ["--plugins", self.plugins]

        if self.presets is not None:
            args += ["--presets", self.presets]

        return args

    def compile_file(self, source_path: str) -> str:
        args = [self.executable, *self.get_extra_args()]

        if self.is_sourcemap_enabled:
            args.append("-s")

        full_output_path = self.get_full_output_path(source_path)

        full_output_dirname = os.path.dirname(full_output_path)
        if not os.path.exists(full_output_dirname):
            os.makedirs(full_output_dirname)

        args.extend(["-o", full_output_path])
        args.append(self.get_full_source_path(source_path))

        return_code, out, errors = utils.run_command(args)
        if return_code:
            raise exceptions.StaticCompilationError(errors)

        if self.is_sourcemap_enabled:
            utils.fix_sourcemap(full_output_path + ".map", source_path, full_output_path)

        return self.get_output_path(source_path)

    def compile_source(self, source: str) -> str:
        args = [self.executable, *self.get_extra_args()]

        return_code, out, errors = utils.run_command(args, input=source)
        if return_code:
            raise exceptions.StaticCompilationError(errors)

        return out


#d=decimal
#b=binary
#h=hexadecimal
#o=octal
#We will be defining to general functions r2d(radix to decimal)
# & d2r ( decimal to radix) & then implementing them according to requirements.
def r2d(number,radix):
    p=list(number)[::-1]
    dict={'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'A':10,'B':11,'C':12,'D':13,'E':14,'F':15,'G':16,'H':17,'I':18,'J':19,'K':20,'L':21,'M':22,'N':23,'O':24,'P':25,'Q':26,'R':27,'S':28,'T':29,'U':30,'V':31,'W':32,'X':33,'Y':34,'Z':35}
    for j in p:
        if j in dict.keys() and dict[j]<radix:
            k=p.index(j)
            p[k]=dict[j]
        else:
            print("")
            return
    l=[]
    for i in p:
        k=p.index(i)
        a=(i*(radix**k))
        l.append(a)
    d=sum(l)
    return d

def d2r(number,radix):
    st=''
    dict={10:'A',11:'B',12:'C',13:'D',14:'E',15:'F',16:'G',17:'H',18:'I',19:'J',20:'K',21:'L',22:'M',23:'N',24:'O',25:'P',26:'Q',27:'R',28:'S',29:'T',30:'U',31:'V',32:'W',33:'X',34:'Y',35:'Z'}
    while int(number)>0:
        remainder=int(number)%radix
        if remainder>=10:
            a=dict[remainder]
        else:
            a=str(remainder)
        st+=(a)
        number=int(number)//radix
    final=st[::-1]
    return final

while True:
    print ('''Choose a function among the following:
    1. Convert decimal to binary
    2. Convert binary to decimal
    3. Convert decimal to hexadecimal
    4. Convert hexadecimal to decimal
    5. Convert decimal to octal
    6. Convert octal to decimal
    7. Convert binary to hexadecimal
    8. Convert hexadecimal to binary
    9. Convert binary to octal
    10. Convert octal to binary
    11. Convert hexadecimal to octal
    12. Convert octal to hexadecimal
    13. Convert  radix A to radix B
    14. exit ''')
    a=int(input())
    b=str(input('Enter the number to be converted:'))
    if a==1:
        print (d2r(b,2))
    elif a==2:
        print (r2d(b,2))
    elif a==3:
        print (d2r(b,16))
    elif a==4:
        print (r2d(b,16))
    elif a==5:
        print (d2r(b,8))
    elif a==6:
        print (r2d(b,8))
    elif a==7:
        m=r2d(b,2)
        n=d2r(m,16)
        print (n)
    elif a==8:
        m=r2d(b,16)
        n=d2r(m,2)
        print (n)
    elif a==9:
        m=r2d(b,2)
        n=d2r(m,8)
        print (n)
    elif a==10:
        m=r2d(b,8)
        n=d2r(m,2)
        print (n)
    elif a==11:
        m=r2d(b,16)
        n=d2r(m,8)
        print (n)
    elif a==12:
        m=r2d(b,8)
        n=d2r(m,16)
    elif a==13:
        x=int(input('Enter radix A:'))
        m=r2d(b,x)
        y=int(input('Enter radix B:'))
        n=d2r(m,y)
        print (n)
    elif a==14:
        break


__author__ = '祥祥'

from DiningServer.models import TblUser

from DiningServer.common.time_format_util import SERVER_DATA_FORMAT
import time

SEX = {
    # 从数据库得到数值 从下面得到对应的性别
    1 : '男',
    2 : '女',

    # web端传过来 男女，从下面获取对应的数值
    '男' : 1,
    '女' : 2,
}

# 获取用户详细信息
def getMyDetailInfo(user_id):
    user = TblUser.objects.filter(id=user_id)
    for item in user:
        detail_info =  {
            'id' : item.id,
            'username' : item.username,
            'sex' : item.sex,      # html显示的是选项 所以使用int值判断
            'birthday' : item.birthday.strftime(SERVER_DATA_FORMAT),
            'phone' : item.phone,
            'email' : item.email,
            'location' : item.user_location
        }
        return detail_info
    return {}

# 更改用户详细信息
def modifyMyDetailInfo(user_id, user_name, sex, birthday, phone, email, location):
    user = TblUser()
    user.id = user_id
    user.username = user_name
    user.sex = SEX.get(sex, 0)
    user.birthday = birthday       # 存入数据库的时间 使用string即可
    user.phone = phone
    user.email = email
    user.user_location = location
    user.save()


from tkinter import *
class frame(Frame):
	def __init__(self, master = None, width = 300, heigth = 300):
		super().__init__(master)
		self.var = IntVar()
		self.master.title('program one')
		self.master.minsize(width, heigth)
	def hello(self):
		print('hello')
fr = frame()
fred = Button(fr.master, text = 'hello', activeforeground = 'red', fg = 'black', bg = 'white', command = fr.hello)
fred.pack()
fred.place(x = 100, y = 100)
fred1 = Button(fr.master, text = 'exit', activeforeground = 'red', fg = 'black', bg = 'white', command = fr.quit)
fred1.pack(side = 'right')
fred1.place(x = 150, y = 100)
cb = Checkbutton(fr.master, text = 'check', variable =  fr.var, onvalue = 1, offvalue = 0, command = fr.hello)
cb.pack()
cb.place(x = 180, y = 100)
fr.mainloop()


import networkx as nx
import os

from simtk.openmm import app

def nmols_in_file(box_file):
    """return how many molecules are in the pdb file."""
    pdb = app.PDBFile(box_file)
    n_molecules = pdb.topology.getNumResidues()

    return n_molecules

def create_box(pdb_name, nmol=500):

    resn = 'MOL'        # Enter new molecule description code to rename UNK

    with open(pdb_name, 'rt') as f_in, open(f'{resn}.pdb', 'wt') as f_out:
        for line in f_in:
            f_out.write(line.replace('UNK', resn))

    x = y = z = 4       # Initial liquid box dimensions
    n_molecules = 0
    while n_molecules < nmol:
        os.system(f'gmx insert-molecules -ci  {resn}.pdb -box {x} {y} {z} -nmol {nmol} -o box.pdb')
        n_molecules = nmols_in_file('box.pdb')
        x += 0.2
        y += 0.2
        z += 0.2

def generate_connections(single_pdb, all_pdb, n_molecules):

    os.system(f'head -n -2 {all_pdb} > temp.pdb ; mv temp.pdb new.pdb')

    with open(single_pdb, 'r') as s_pdb, open('new.pdb', 'a+') as new_pdb:

        lines = s_pdb.readlines()

        topology = nx.Graph()

        for line in lines:
            if 'CONECT' in line:
                topology.add_node(int(line.split()[1]))
                for i in range(2, len(line.split())):
                    if int(line.split()[i]) != 0:
                        topology.add_node(int(line.split()[i]))
                        topology.add_edge(int(line.split()[1]), int(line.split()[i]))

        n_atoms = len(list(topology.nodes))

        for mol in range(n_molecules):
            for node in topology.nodes:
                bonded = sorted(list(nx.neighbors(topology, node)))
                if len(bonded) > 1:
                    new_pdb.write(f'CONECT{node + (mol * n_atoms):5}{"".join(f"{x + (mol * n_atoms):5}" for x in bonded)}\n')

        new_pdb.write('END\n')


import nltk
from nltk.util import ngrams
from nltk.corpus import gutenberg
from collections import Counter

#testVar = raw_input("Give path")
#print testVar
#fo = open(testVar, "wb")
count = 0
testStr = ""
testWord = ""
dictWords = []
wordsFornGram = []
with open("rural.txt", 'r') as f:
     for line in f :
        i = 0
        #print line
        while i < len(line) :
            if line[i] != '.' and line[i] != '!' and line[i] != '?':
                testStr = testStr + line[i]
                if line[i]==' ' or line[i]=='\n':
                    if testWord != "" :
                        wordsFornGram.append(testWord.lower())
                    if testWord in dictWords:
                        if count == 0 :
                            print ("hii")
                    else :
                        if count == 0 :
                            print ("%s"%testWord)
                        dictWords.append(testWord.lower())
                    testWord = ""
                else:
                    testWord = testWord + line[i]
                i=i+1
            elif line[i]=='!' or line[i]=='?':
                if testWord != "" :
                    wordsFornGram.append(testWord.lower())
                if testWord in dictWords:
                    if count == 0 :
                        print ("hii")
                else :
                    if count == 0 :
                        print ("%s\n"%testWord)
                    dictWords.append(testWord.lower())
                testWord = ""
                if i+1 < len( line ) and line[i+1].isupper :
                #   print count
                #   print testStr
                    testStr=""
                    count=count+1
                else :
                    testStr = testStr + line[i]
                i=i+1
            elif line[i]=='.' :
                if testWord != "" :
                    wordsFornGram.append(testWord.lower())
                if line[i-2:i-1]!="Dr" or line[i-2:i-1]!="Mr" or line[i-2:i-1]!="vs" or line[i-3:i-1]!="Mrs" or line[i-3:i-1]!="etc" :
                #   print count
                #   print testStr
                    testStr=""
                    count=count+1
                    print ("%d \n"%count)
                else :
                    testStr = testStr + line[i]
                if testWord in dictWords:
                    if count == 1 :
                        print ("hii")
                else :
                    if count == 1 :
                        print ("%s\n"%testWord)
                    dictWords.append(testWord.lower())
                testWord = ""

                i=i+1
f.close()
n=1
try:
   f1 = open("uni.txt","w")
except IOError:
   print ("Err uni")
try:
   f2 = open("bi.txt","w")
except IOError:
   print ("Err bi")
try:
   f3 = open("tri.txt","w")
except IOError:
   print ("Err tri")

unigrams = ngrams(wordsFornGram, n)
#print (len(unigrams))
unigrams_freq = Counter(unigrams)
unigrams_sorted =  unigrams_freq.most_common()
for x in unigrams_sorted:
   f1.write("%s\n"%(x,))
n=2
bigrams = ngrams(wordsFornGram, n)
#print (len(bigrams))
bigrams_freq = Counter(bigrams)
bigrams_sorted =  bigrams_freq.most_common()
for x in bigrams_sorted:
   f2.write("%s\n"%(x,))
n=3
trigrams = ngrams(wordsFornGram, n)
#print (len(trigrams))
trigrams_freq = Counter(trigrams)
trigrams_sorted =  trigrams_freq.most_common()
for x in trigrams_sorted:
   f3.write("%s\n"%(x,))
f1.close()
f2.close()
f3.close()


import time
from os.path import exists, expanduser

from adapt.intent import IntentBuilder
from mycroft.skills.core import MycroftSkill, intent_file_handler
from mycroft.skills.core import intent_handler
from mycroft.skills.intent_service_interface import IntentQueryApi
from ovos_workshop.skills import OVOSSkill
from ovos_workshop.skills.decorators import layer_intent, enables_layer, \
    disables_layer, resets_layers
from .adventure import load_advent_dat
from .adventure.game import Game

class ColossalCaveAdventureSkill(OVOSSkill):

    def __init__(self):
        super().__init__()
        self.playing = False
        self.game = None
        self.last_interaction = time.time()
        # TODO xdg path
        self.save_file = expanduser("~/cave_adventure.save")

    def initialize(self):
        # start skill in "not_playing" layer
        self.intent_layers.disable()
        self.intent_layers.activate_layer("not_playing")

    def will_trigger(self, utterance, lang):
        # will an intent from this skill trigger ?
        skill_id = IntentQueryApi(self.bus).get_skill(utterance, lang)
        if skill_id and skill_id == self.skill_id:
            return True
        return False

    @enables_layer("playing")
    def start_game(self):
        self.playing = True
        self.game = Game()
        load_advent_dat(self.game)
        self.last_interaction = time.time()
        self.game.start()
        self.speak_output(self.game.output)

    def speak_output(self, line):
        # dont speak parts of the intro
        # replace type with say because its voice game
        # re join words split across lines
        # reformat \n and separate by sentence
        line = line.lower().replace("type", "say").replace("-\n", "")
        line = line.replace(
            '  i should warn\nyou that i look at only the first five letters of each word, so you\'ll\nhave to enter "northeast" as "ne" to distinguish it from "north".',
            "")
        line = line.replace(
            "- - this program was originally developed by willie crowther.  most of the\nfeatures of the current program were added by don woods (don @ su-ai).\ncontact don if you have any questions, comments, etc.",
            "")
        line = line.replace("\n", " ").replace("(", "").replace(")",
                                                                "").replace(
            "etc.", "etc")

        # TODO nice background picture
        self.gui["text"] = line
        self.gui.show_page("text.qml")

        lines = line.split(".")
        for line in lines:
            if line.strip():
                self.speak(line.strip())
        self.last_interaction = time.time()
        self.maybe_end_game()
        # HACK this is a workaround for a core bug, skill is only booted
        # to top of converse list after next intent interaction
        self.make_active()

    @layer_intent("play.intent", layer_name="not_playing")
    def handle_play(self, message=None):
        self.start_game()

    @layer_intent("restart_game.intent", layer_name="playing")
    def handle_restart(self, message=None):
        # shorter intent that doesnt require game name in utt
        self.start_game()

    @layer_intent("save.intent", layer_name="playing")
    def handle_save(self, message=None):
        if not self.playing:
            self.speak_dialog("save.not.found")
        else:
            with open(self.save_file, "wb") as f:
                self.game.t_suspend("save", f)
                self.speak_dialog("game.saved")

    @layer_intent("resume_game_short.intent", layer_name="playing")
    def handle_resume(self, message=None):
        # shorter intent that doesnt require game name in utt
        self.handle_restore(message)

    @intent_file_handler("restore.intent")
    def handle_restore(self, message):
        if exists(self.save_file):
            self.playing = True
            self.game = Game.resume(self.save_file)
            self.speak_dialog("restore.game")
        else:
            self.speak_dialog("save.not.found")
            new_game = self.ask_yesno("new.game")
            if new_game:
                self.start_game()

    @resets_layers()
    def game_over(self):
        self.disable_intent("Save")
        self.playing = False
        self.game = Game()
        load_advent_dat(self.game)

    def maybe_end_game(self):
        # end game if no interaction for 10 mins
        if self.playing:
            timed_out = time.time() - self.last_interaction > 10 * 3600
            # disable save and gameplay
            if self.game.is_finished or timed_out:
                self.game_over()
            # save game to allow restoring if timedout
            if timed_out:
                self.handle_save()

    def converse(self, utterances, lang="en-us"):
        """ Handle conversation.

        This method gets a peek at utterances before the normal intent
        handling process after a skill has been invoked once.

        To use, override the converse() method and return True to
        indicate that the utterance has been handled.

        Args:
            utterances (list): The utterances from the user
            lang:       language the utterance is in

        Returns:
            bool: True if an utterance was handled, otherwise False
        """
        # check if game was abandoned midconversation and we should clean it up
        self.maybe_end_game()
        if self.playing:
            ut = utterances[0]
            # if self will trigger do nothing and let intents handle it
            if self.will_trigger(ut, lang):
                # save / restore will trigger
                return False
            # capture speech and pipe to the game
            words = ut.split(" ")
            self.speak_output(self.game.do_command(words))
            self.make_active()
            return True
        return False

def create_skill():
    return ColossalCaveAdventureSkill()


# a script for plotting
import matplotlib.pyplot as plt
import numpy as np
import os
def plot_breast_scatter(x, y):
    plt.figure()
    plt.scatter(x[:,0],x[:,2],s=40,c=y,cmap=plt.cm.Spectral)
    plt.xlabel('Mean radius',fontweight='bold')
    plt.ylabel('Mean perimeter',fontweight='bold')
    plt.show()

    plt.figure()
    plt.scatter(x[:,5],x[:,6],s=40,c=y, cmap=plt.cm.Spectral)
    plt.xlabel('Mean compactness',fontweight='bold')
    plt.ylabel('Mean concavity',fontweight='bold')
    plt.show()

    plt.figure()
    plt.scatter(x[:,0],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)
    plt.xlabel('Mean radius',fontweight='bold')
    plt.ylabel('Mean texture',fontweight='bold')
    plt.show()

    plt.figure()
    plt.scatter(x[:,2],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)
    plt.xlabel('Mean perimeter',fontweight='bold')
    plt.ylabel('Mean compactness',fontweight='bold')
    plt.show()

def plot_heatmap(x,y,data,show = True, title=None, store = True, type_axis = 'float', store_dir = None,
                 xlabel = None, ylabel = None, cbar_label = None, vmin=0, vmax = 1):

    # plot results
    fontsize=16

    fig = plt.figure()
    ax = fig.add_subplot(111)
    cax = ax.matshow(data, interpolation='nearest', vmin=vmin, vmax=vmax)

    cbar=fig.colorbar(cax)
    if cbar_label is None:
        cbar.ax.set_ylabel('accuracy (%)',rotation=90,fontsize=fontsize)
    else:
        cbar.ax.set_ylabel(cbar_label,rotation=90,fontsize=fontsize)
    #cbar.set_ticks([0,.2,.4,0.6,0.8,1.0])
    #cbar.set_ticklabels(['0%','20%','40%','60%','80%','100%'])

    # put text on matrix elements
    for i, x_val in enumerate(np.arange(len(x))):
        for j, y_val in enumerate(np.arange(len(y))):
            c = "${0:.2f}$".format( data[j,i])
            ax.text(x_val, y_val, c, va='center', ha='center')

    # convert axis vaues to to string labels
    if type_axis == 'log':
        x=["1e{0:.2}".format(np.log10(i)) for i in x]
        y=["1e{0:.2}".format(np.log10(i)) for i in y]
    if type_axis == 'int':
        x=["%i"%(i) for i in x]
        y=["%i"%(i) for i in y]
    if type_axis == 'float':
        x=["{0:.2}".format(i) for i in x]
        y=["{0:.2}".format(i) for i in y]
    ax.set_xticklabels(['']+x)
    ax.set_yticklabels(['']+y)
    if xlabel is None:
        ax.set_xlabel('$\\mathrm{learning\\ rate}$',fontsize=fontsize)
    else:
        ax.set_xlabel(xlabel, fontsize=fontsize)
    if ylabel is None:
        ax.set_ylabel('$\\mathrm{hidden\\ neurons}$',fontsize=fontsize)
    else:
        ax.set_ylabel(ylabel, fontsize=fontsize)
    if title is not None:
        ax.set_title(title)

    plt.tight_layout()
    plt.show()
    if store:
        if store_dir is None:
            fig.savefig(os.getcwd() + "/plots/neurons_eta_heatmap_breast_" + title + ".png", dpi=150)
        else:
            fig.savefig(store_dir + title + ".png", dpi=150)

def plot_norm_gradient(norms_gradient, fig, ax, label, ylabel, xlabel='Epoch', store = False, store_dir = None):
    ax.plot(np.arange(norms_gradient) + 1, norms_gradient, label = label)
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    ax.legend()
    if store:
        fig.savefig(store_dir + ".png", dpi=150)

def plot_activation_functions(af, x, fig, ax):
    if af == 'sigmoid':
        y = 1/(1 + np.exp(-x))
    if af == 'tanh':
        y = np.tanh(x)
    if af == 'leaky_relu':
        y = .5*( (1 - np.sign(x))*1e-2*x + (1 + np.sign(x))*x)
    if af == 'relu':
        y = np.maximum(x, 0)
    ax.plot(x, y, label=af)
    return fig, ax


from collections import deque
import time
from copy import deepcopy

class Computer:

    def __init__(self, prog=None):
        self.prog = prog
        self.ip = 0
        self.base = 0

    def __deepcopy__(self, memo):
        c = Computer()
        c.prog = deepcopy(self.prog)
        c.ip = self.ip
        c.base = self.base
        return c

    def parse_instruction(self, i):
        i = str(i)
        opcode = int(i[-1])
        mode1 = int(i[-3]) if len(i) > 2 else 0
        mode2 = int(i[-4]) if len(i) > 3 else 0
        mode3 = int(i[-5]) if len(i) > 4 else 0

        return opcode, mode1, mode2, mode3

    def read_value(self, op, mode):
        if mode == 0:
            return self.prog[op]
        elif mode == 1:
            return op
        elif mode == 2:
            return self.prog[self.base + op]

    def read_write_address(self, op, mode):
        if mode == 2:
            return op + self.base
        else:
            return op

    def is_halt(self):
        return self.prog[self.ip] == 99

    def run_step(self, inp):
        while self.prog[self.ip] != 99:
            opcode, mode1, mode2, mode3 = self.parse_instruction(self.prog[self.ip])

            if opcode == 1:
                op1, op2, op3 = self.prog[self.ip+1], self.prog[self.ip+2], self.prog[self.ip+3]
                self.prog[self.read_write_address(op3, mode3)] = self.read_value(op1, mode1) + self.read_value(op2, mode2)
                self.ip += 4

            elif opcode == 2:
                op1, op2, op3 = self.prog[self.ip+1], self.prog[self.ip+2], self.prog[self.ip+3]
                self.prog[self.read_write_address(op3, mode3)] = self.read_value(op1, mode1) * self.read_value(op2, mode2)
                self.ip += 4

            elif opcode == 3:
                op1 = self.prog[self.ip+1]
                self.prog[self.read_write_address(op1, mode1)] = inp

                self.ip += 2

            elif opcode == 4:
                op1 = self.read_value(self.prog[self.ip+1], mode1)
                self.ip += 2
                return op1

            elif opcode == 5:
                op1, op2 = self.prog[self.ip+1], self.prog[self.ip+2]
                if self.read_value(op1, mode1) != 0:
                    self.ip = self.read_value(op2, mode2)
                else:
                    self.ip += 3

            elif opcode == 6:
                op1, op2 = self.prog[self.ip+1], self.prog[self.ip+2]
                if self.read_value(op1, mode1) == 0:
                    self.ip = self.read_value(op2, mode2)
                else:
                    self.ip += 3

            elif opcode == 7:
                op1, op2, op3 = self.prog[self.ip+1], self.prog[self.ip+2], self.prog[self.ip+3]
                if self.read_value(op1, mode1) < self.read_value(op2, mode2):
                    self.prog[self.read_write_address(op3, mode3)] = 1
                else:
                    self.prog[self.read_write_address(op3, mode3)] = 0
                self.ip += 4

            elif opcode == 8:
                op1, op2, op3 = self.prog[self.ip+1], self.prog[self.ip+2], self.prog[self.ip+3]
                if self.read_value(op1, mode1) == self.read_value(op2, mode2):
                    self.prog[self.read_write_address(op3, mode3)] = 1
                else:
                    self.prog[self.read_write_address(op3, mode3)] = 0
                self.ip += 4

            elif opcode == 9:
                op1 = self.read_value(self.prog[self.ip+1], mode1)
                self.base += op1
                self.ip += 2

def bfs1(queue, grid):
    d = {1: (0,1), 2: (0,-1), 3: (-1,0), 4: (1,0)}
    while len(queue) > 0:
        x, y, computer, dist = queue.pop(0)
        grid[(x,y)] = '.'
        print(x,y)

        for i in [1,2,3,4]:
            newx = x + d[i][0]
            newy = y + d[i][1]
            if (newx, newy) in grid:
                continue
            c = deepcopy(computer)
            output = c.run_step(i)
            if output == 0:
                grid[(newx, newy)] = '#'
            elif output == 1:
                queue.append((newx, newy, c, dist+1))
            elif output == 2:
                grid[(newx, newy)] = 'O'
                ox_x = newx
                ox_y = newy
                dist_to_oxygen = dist + 1

    return dist_to_oxygen, ox_x, ox_y

def bfs2(queue, grid):
    d = {1: (0,1), 2: (0,-1), 3: (-1,0), 4: (1,0)}
    max_dist = 0
    while len(queue) > 0:
        x, y, dist = queue.pop(0)
        max_dist = max(max_dist, dist)
        grid[(x,y)] = 'O'

        for i in [1,2,3,4]:
            newx = x + d[i][0]
            newy = y + d[i][1]
            if (newx, newy) not in grid:
                continue
            if grid[(newx, newy)] == '#' or grid[(newx, newy)] == 'O':
                continue
            else:
                queue.append((newx, newy, dist+1))

    return max_dist

def print_grid(grid):
    maze = [[' ' for i in range(50)] for j in range(50)]
    for x, y in grid.keys():
        maze[y+25][x+25] = grid[(x,y)]
    for i in range(50):
        print(''.join(maze[i]))

if __name__ == '__main__':

    with open('day15.txt') as f:
        prog_input = [int(x) for x in f.read().split(',')] + [0 for i in range(100000)]

    computer = Computer(prog_input)
    grid = dict()
    dist, ox_x, ox_y = bfs1([(0, 0, computer, 0)], grid)
    print('Distance:', dist)

    print_grid(grid)

    dist = bfs2([(ox_x, ox_y, 0)], grid)
    print('Distance:', dist)

    print_grid(grid)


import datetime

from fastapi import status
import httpx
import pytest
import requests
import responses
import respx

from app.internal.astronomy import ASTRONOMY_URL
from app.internal.astronomy import get_astronomical_data

RESPONSE_FROM_MOCK = {
    "location": {
        "name": "Tel Aviv-Yafo",
        "region": "Tel Aviv",
        "country": "Israel",
        "lat": 32.07,
        "lon": 34.76,
        "tz_id": "Asia/Jerusalem",
        "localtime_epoch": 1611399607,
        "localtime": "2021-01-23 13:00",
    },
    "astronomy": {
        "astro": {
            "sunrise": "05:25 AM",
            "sunset": "06:03 PM",
            "moonrise": "01:56 PM",
            "moonset": "03:04 AM",
            "moon_phase": "Waxing Gibbous",
            "moon_illumination": "79",
        }
    }
}

ERROR_RESPONSE_FROM_MOCK = {
    "error": {
        "message": "Error Text",
    }
}

@pytest.mark.asyncio
async def test_get_astronomical_data(httpx_mock):
    requested_date = datetime.datetime(day=4, month=4, year=2020)
    httpx_mock.add_response(method="GET", json=RESPONSE_FROM_MOCK)
    output = await get_astronomical_data(requested_date, "tel aviv")
    assert output['success']

@respx.mock
@pytest.mark.asyncio
async def test_astronomical_data_error_from_api():
    requested_date = datetime.datetime(day=4, month=4, year=2021)
    route = respx.get(ASTRONOMY_URL)
    route.return_value = httpx.Response(
        status.HTTP_200_OK,
        json=ERROR_RESPONSE_FROM_MOCK,
    )
    output = await get_astronomical_data(requested_date, "123")
    assert not output['success']

@respx.mock
@pytest.mark.asyncio
async def test_astronomical_exception_from_api(httpx_mock):
    requested_date = datetime.datetime.now() + datetime.timedelta(days=3)
    respx.get(ASTRONOMY_URL).mock(
        return_value=httpx.Response(status.HTTP_500_INTERNAL_SERVER_ERROR))
    output = await get_astronomical_data(requested_date, "456")
    assert not output['success']

@responses.activate
@pytest.mark.asyncio
async def test_astronomical_no_response_from_api():
    requested_date = datetime.datetime(day=11, month=1, year=2020)
    responses.add(
        responses.GET,
        ASTRONOMY_URL,
        status=status.HTTP_500_INTERNAL_SERVER_ERROR,
    )
    requests.get(ASTRONOMY_URL)
    output = await get_astronomical_data(requested_date, "789")
    assert not output['success']


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

x_pi = 3.14159265358979324 * 3000.0 / 180.0
pi = 3.1415926535897932384626  # π
a = 6378245.0  # 长半轴
ee = 0.00669342162296594323  # 扁率
def gcj02_to_bd09(lng, lat):
    """
    火星坐标系(GCJ-02)转百度坐标系(BD-09)
    谷歌、高德——>百度
    :param lng:火星坐标经度
    :param lat:火星坐标纬度
    :return:
    """
    if out_of_china(lng, lat):  # 判断是否在国内
        return lng, lat
    z = math.sqrt(lng * lng + lat * lat) + 0.00002 * math.sin(lat * x_pi)
    theta = math.atan2(lat, lng) + 0.000003 * math.cos(lng * x_pi)
    bd_lng = z * math.cos(theta) + 0.0065
    bd_lat = z * math.sin(theta) + 0.006
    return [bd_lng, bd_lat]

def bd09_to_gcj02(bd_lon, bd_lat):
    """
    百度坐标系(BD-09)转火星坐标系(GCJ-02)
    百度——>谷歌、高德
    :param bd_lat:百度坐标纬度
    :param bd_lon:百度坐标经度
    :return:转换后的坐标列表形式
    """
    if out_of_china(bd_lon, bd_lat):  # 判断是否在国内
        return bd_lon, bd_lat
    x = bd_lon - 0.0065
    y = bd_lat - 0.006
    z = math.sqrt(x * x + y * y) - 0.00002 * math.sin(y * x_pi)
    theta = math.atan2(y, x) - 0.000003 * math.cos(x * x_pi)
    gg_lng = z * math.cos(theta)
    gg_lat = z * math.sin(theta)
    return [gg_lng, gg_lat]

def wgs84_to_gcj02(lng, lat):
    """
    WGS84转GCJ02(火星坐标系)
    :param lng:WGS84坐标系的经度
    :param lat:WGS84坐标系的纬度
    :return:
    """
    if out_of_china(lng, lat):  # 判断是否在国内
        return lng, lat
    dlat = _transformlat(lng - 105.0, lat - 35.0)
    dlng = _transformlng(lng - 105.0, lat - 35.0)
    radlat = lat / 180.0 * pi
    magic = math.sin(radlat)
    magic = 1 - ee * magic * magic
    sqrtmagic = math.sqrt(magic)
    dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * pi)
    dlng = (dlng * 180.0) / (a / sqrtmagic * math.cos(radlat) * pi)
    mglat = lat + dlat
    mglng = lng + dlng
    return [mglng, mglat]

def gcj02_to_wgs84(lng, lat):
    """
    GCJ02(火星坐标系)转GPS84
    :param lng:火星坐标系的经度
    :param lat:火星坐标系纬度
    :return:
    """
    if out_of_china(lng, lat):
        return lng, lat
    dlat = _transformlat(lng - 105.0, lat - 35.0)
    dlng = _transformlng(lng - 105.0, lat - 35.0)
    radlat = lat / 180.0 * pi
    magic = math.sin(radlat)
    magic = 1 - ee * magic * magic
    sqrtmagic = math.sqrt(magic)
    dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * pi)
    dlng = (dlng * 180.0) / (a / sqrtmagic * math.cos(radlat) * pi)
    mglat = lat + dlat
    mglng = lng + dlng
    return [lng * 2 - mglng, lat * 2 - mglat]

def gcj02_to_wgs84_exact(gcjLng, gcjLat):#
    # if out_of_china(gcjLng, gcjLng):
    #     return lng, lat
    initDelta = 0.01
    threshold = 0.000001
    dLat = dLng = initDelta
    mLat = gcjLat - dLat
    mLng = gcjLng - dLng
    pLat = gcjLat + dLat
    pLng = gcjLng + dLng
    wgsLat = 0.0
    wgsLng = 0.0
    n=0
    for i in range(30):
        n+=1
        wgsLat = (mLat + pLat) / 2.0
        wgsLng = (mLng + pLng) / 2.0
        tmplng,tmplat=wgs84_to_gcj02(wgsLng,wgsLat)
        dLat = tmplat - gcjLat
        dLng = tmplng - gcjLng
        if abs(dLat) < threshold and abs(dLng) < threshold:
            return wgsLng,wgsLat
        if dLat > 0:
            pLat = wgsLat
        else:
            mLat = wgsLat
        if dLng > 0:
            pLng = wgsLng
        else:
            mLng = wgsLng
    return wgsLng, wgsLat

def bd09_to_wgs84(bd_lon, bd_lat):
    lon, lat = bd09_to_gcj02(bd_lon, bd_lat)
    return gcj02_to_wgs84(lon, lat)

def bd09_to_wgs84_exact(bd_lon, bd_lat):
    lon, lat = bd09_to_gcj02(bd_lon, bd_lat)
    return gcj02_to_wgs84_exact(lon, lat)

def wgs84_to_bd09(lon, lat):
    lon, lat = wgs84_to_gcj02(lon, lat)
    return gcj02_to_bd09(lon, lat)

def _transformlat(lng, lat):
    ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + \
          0.1 * lng * lat + 0.2 * math.sqrt(math.fabs(lng))
    ret += (20.0 * math.sin(6.0 * lng * pi) + 20.0 *
            math.sin(2.0 * lng * pi)) * 2.0 / 3.0
    ret += (20.0 * math.sin(lat * pi) + 40.0 *
            math.sin(lat / 3.0 * pi)) * 2.0 / 3.0
    ret += (160.0 * math.sin(lat / 12.0 * pi) + 320 *
            math.sin(lat * pi / 30.0)) * 2.0 / 3.0
    return ret

def _transformlng(lng, lat):
    ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + \
          0.1 * lng * lat + 0.1 * math.sqrt(math.fabs(lng))
    ret += (20.0 * math.sin(6.0 * lng * pi) + 20.0 *
            math.sin(2.0 * lng * pi)) * 2.0 / 3.0
    ret += (20.0 * math.sin(lng * pi) + 40.0 *
            math.sin(lng / 3.0 * pi)) * 2.0 / 3.0
    ret += (150.0 * math.sin(lng / 12.0 * pi) + 300.0 *
            math.sin(lng / 30.0 * pi)) * 2.0 / 3.0
    return ret

def out_of_china(lng, lat):
    """
    判断是否在国内，不在国内不做偏移
    :param lng:
    :param lat:
    :return:
    """
    return not (lng > 73.66 and lng < 135.05 and lat > 3.86 and lat < 53.55)
import csv
def change_latlon(fileName,fileSave,latindex,lonindex,toto):
    with open(fileName) as fileR,open(fileSave,'w') as fileW:
        lines = csv.reader(fileR)
        fileW.write(','.join(next(lines))+',changelat,changelon\n')
        error_num = 0
        ss_num = 0
        for line in lines:
            try:
                lat = float(line[latindex])
                lon = float(line[lonindex])
                changelon,changelat = toto(lon,lat)
                line.append(str(changelat))
                line.append(str(changelon))
                fileW.write(','.join(line)+'\n')
                ss_num+=1
            except:
                error_num+=1
        print(u'文件共',ss_num+error_num,u'条',u'成功',ss_num,'条','不成功',error_num,'条')
        print('转换结束！！')

if __name__ == '__main__':
    fileName = u'.\\'
    fileSave = u'.\\'
    latindex = 1
    lonindex = 2
    toto = wgs84_to_gcj02
    change_latlon(fileName, fileSave, latindex, lonindex, toto)


print('Welcome to data configurator!')
a, b, c, d=input('Please input 4 data seperated by space to configure(1 2 3 4): ').split(',')
x = [a, b, c, d]
y = (a, b, c, d)
print(x)
print(y)
ctr=0
while True:
    z=input('Do you want to input another data to the list?(Yes or No): ')
    if z=='Yes':
        n=input('Please Input a data: ')
        x.append(n)
        print(x)
        print(y)
    else:
        print('Thankyou for using our service!')
        break

1st Semester/Sir Jude's Exercise 5/No. 1.py


#!/usr/bin/python

from sm_brokerBase import sm_brokerBase

class sm_Mx( sm_brokerBase ):

    def __init__( self, option = None, CommandAndControl = None ):

        super( sm_Mx, self ).__init__(
            CommandAndControl = CommandAndControl,
            botList           = 'mxBrokers',
            menuName          = 'Mx Broker',
        )


def main():

    # Copying images to training, validation, and test directories
    import os
    import shutil
    import pathlib
    original_dir = pathlib.Path("train")
    base_dir = pathlib.Path("cats_vs_dogs_small")

    # Instantiating a small convnet for dogs vs. cats classification
    from tensorflow import keras
    from tensorflow.keras import layers

    # # Using image_dataset_from_directory to read images
    from tensorflow.keras.utils import image_dataset_from_directory
    train_dataset = image_dataset_from_directory(
        base_dir / "train",
        image_size=(180, 180),
        batch_size=32)
    validation_dataset = image_dataset_from_directory(
        base_dir / "validation",
        image_size=(180, 180),
        batch_size=32)
    test_dataset = image_dataset_from_directory(
        base_dir / "test",
        image_size=(180, 180),
        batch_size=32)

    # FEATURE EXTRACTION TOGETHER WITH DATA AUGMENTATIO
    # Instantiating and freezing the VGG16 convolutional base
    conv_base = keras.applications.vgg16.VGG16(
        weights="imagenet",
        include_top=False)
    conv_base.trainable = False
    print(conv_base.summary())

    #  Adding a data augmentation stage and a classifier to the convolutional base
    data_augmentation = keras.Sequential(
        [
            layers.RandomFlip("horizontal"),
            layers.RandomRotation(0.1),
            layers.RandomZoom(0.2),
        ]
    )
    inputs = keras.Input(shape=(180, 180, 3))
    x = data_augmentation(inputs)
    x = keras.applications.vgg16.preprocess_input(x)
    x = conv_base(x)
    x = layers.Flatten()(x)
    x = layers.Dense(256)(x)
    x = layers.Dropout(0.5)(x)
    outputs = layers.Dense(1, activation="sigmoid")(x)
    model = keras.Model(inputs, outputs)
    model.compile(loss="binary_crossentropy",
                  optimizer="rmsprop",
                  metrics=["accuracy"])

    # Evaluating the model on the test set

    # Fine-tuning a pretrained model
    # Freezing all layers until the fourth from the last
    conv_base.trainable = True
    for layer in conv_base.layers[:-4]:
        layer.trainable = False

    # Fine-tuning the model
    model.compile(loss="binary_crossentropy",
                  optimizer=keras.optimizers.RMSprop(learning_rate=1e-5),
                  metrics=["accuracy"])
    callbacks = [
        keras.callbacks.ModelCheckpoint(
            filepath="fine_tuning.keras",
            save_best_only=True,
            monitor="val_loss")
    ]
    history = model.fit(
        train_dataset,
        epochs=30,
        validation_data=validation_dataset,
        callbacks=callbacks)

    #  evaluate this model on the test data
    model = keras.models.load_model("fine_tuning.keras")
    test_loss, test_acc = model.evaluate(test_dataset)
    print(f"Test accuracy: {test_acc:.3f}")

if __name__ == '__main__':
    main()


from django import template
from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe

register = template.Library()

@register.filter(needs_autoescape=True)
def goallist(s, autoescape=True):
    result = []
    for line in (l.strip() for l in s.split('\n')):
        if line:
            if autoescape:
                line = conditional_escape(line)
            result.append('<li>%s</li>' % line)

    return mark_safe('\n'.join(result))


## Rauf's and Pasha's bot

from flask import Flask, request
import vk_api
import json
import random
from settings import *

vk_session = vk_api.VkApi(token=API_TOKEN)
api = vk_session.get_api()
app = Flask(__name__)

def message_handler(n_type, uid):
    rand_id = random.randint(0, 10000000)
    if n_type in answers.keys():
        for i, answer in enumerate(answers[n_type], start=1):
            api.messages.send(
                peer_id=uid,
                random_id=rand_id + i,
                attachment=answer
            )
    elif n_type == 'secret-message':
        api.messages.send(
            peer_id=uid,
            random_id=rand_id,
            attachment='photo534733700_457242449'
        )
    else:
        api.messages.send(
            peer_id=uid,
            random_id=rand_id,
            message='hoola hoola get a doolar'
        )

@app.route('/')
def hello():
    return 'Hello, World!'

@app.route('/', methods=["POST"])
def handling_post():
    data = json.loads(request.data)
    if 'type' not in data.keys():
        return 'not vk request'
    if data['type'] == 'confirmation':
        return CONFIRMATION_TOKEN
    elif data['type'] == 'message_new':
        message_handler(data['object']['body'], data['object']['user_id'])
        return 'ok'

if __name__ == '__main__':
    app.run()


from ultralytics import YOLO
import cv2
from sort import *

# cap = cv2.VideoCapture(0)
# cap.set(3, 1280)
# cap.set(4, 720)

cap = cv2.VideoCapture("../Videos/people.mp4")

model = YOLO("../yolo_weights/yolov8n.pt")
mask = cv2.imread('mask.png')
tracker = Sort(max_age=20)

classNames = ["person", "bicycle", "car", "motorbike", "aeroplane", "bus", "train", "truck", "boat",
              "traffic light", "fire hydrant", "stop sign", "parking meter", "bench", "bird", "cat",
              "dog", "horse", "sheep", "cow", "elephant", "bear", "zebra", "giraffe", "backpack", "umbrella",
              "handbag", "tie", "suitcase", "frisbee", "skis", "snowboard", "sports ball", "kite", "baseball bat",
              "baseball glove", "skateboard", "surfboard", "tennis racket", "bottle", "wine glass", "cup",
              "fork", "knife", "spoon", "bowl", "banana", "apple", "sandwich", "orange", "broccoli",
              "carrot", "hot dog", "pizza", "donut", "cake", "chair", "sofa", "pottedplant", "bed",
              "diningtable", "toilet", "tvmonitor", "laptop", "mouse", "remote", "keyboard", "cell phone",
              "microwave", "oven", "toaster", "sink", "refrigerator", "book", "clock", "vase", "scissors",
              "teddy bear", "hair drier", "toothbrush"
              ]

limits1 = [580, 608, 850, 608] # for down
limits2 = [93, 142, 317, 142] # for up
total_humans_up = []
total_humans_down = []

while True:
    sucess, img = cap.read()
    imgregion = cv2.bitwise_and(img, mask)
    result = model(imgregion, stream=True)
    detections = np.empty((0,5)) # for tracker
    for r in result:
        box = r.boxes
        for b in box:
            x1,y1,x2,y2 = b.xyxy[0]
            x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)

            conf = round(b.conf[0].item(), 2)
            cls = b.cls[0]
            # print(int(cls))
            curClass = classNames[int(cls)]
            if curClass  == "person":

                # detection rectangle
                # cv2.rectangle(img, (x1,y1), (x2,y2), (0,0,255), 2)

                # # rect info
                # h,w = cv2.getTextSize(f'{conf} {curClass }', cv2.FONT_HERSHEY_PLAIN, 2, 2)[0]
                # cv2.rectangle(img, (max(0,x1), max(0,y1)), (x1+h, y1-w), (0,0,0), cv2.FILLED)
                # cv2.putText(img, f'{conf} {classNames[int(cls)]}', (max(0,x1), max(0,y1)), cv2.FONT_HERSHEY_PLAIN, 2, (0,0,255), 2)

                currArray = np.array([[x1,y1,x2,y2,conf]])
                detections = np.vstack((detections, currArray))

    result_Tracker = tracker.update(detections)

    cv2.line(img, (limits1[0], limits1[1]), (limits1[2], limits1[3]), (0, 0, 255), 5)
    cv2.line(img, (limits2[0], limits2[1]), (limits2[2], limits2[3]), (0, 0, 255), 5)

    for res in result_Tracker:
        x1, y1, x2, y2, id = res
        x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
        # print(res, x1, y1, x2, y2)
        cw, ch = x2 - x1, y2 - y1

        cv2.rectangle(img, (x1,y1), (x2,y2), (255,0,255), 1)

        h,w = cv2.getTextSize(f'{id}', cv2.FONT_HERSHEY_PLAIN, 2, 2)[0]
        cv2.rectangle(img, (max(0,x1), max(0,y1)), (x1+h, y1-w), (0,0,0), cv2.FILLED)
        cv2.putText(img, f'{id}', (max(0,x1), max(0,y1)), cv2.FONT_HERSHEY_PLAIN, 2, (0,0,255), 2)

        cx, cy = x1+cw//2, y1+ch//2
        cv2.circle(img, (cx,cy), 5, (0,255,0), cv2.FILLED)

        if limits1[0]<cx<limits1[2] and limits1[1]-20<cy<limits1[3]+20:
            print("up")
            if id not in total_humans_up:
                total_humans_up.append(id)
                cv2.line(img, (limits1[0], limits1[1]), (limits1[2], limits1[3]), (0, 255, 0), 5)

        if limits2[0]<cx<limits2[2] and limits2[1]-20<cy<limits2[3]+20:
            print("down")
            if id not in total_humans_down:
                total_humans_down.append(id)
                cv2.line(img, (limits2[0], limits2[1]), (limits2[2], limits2[3]), (0, 255, 0), 5)

        # print(total_humans_up, total_humans_down)

    # top counter 1
    x1, y1 = 10,50
    h,w = cv2.getTextSize(f'Total Humans down: {len(total_humans_up)}', cv2.FONT_HERSHEY_PLAIN, 2, 2)[0]
    cv2.rectangle(img, (max(0,x1), max(0,y1)), (x1+h, y1-w), (0,0,0), cv2.FILLED)
    cv2.putText(img, f'Total Humans down: {len(total_humans_up)}', (x1,y1), cv2.FONT_HERSHEY_PLAIN, 2, (0,0,255), 2)

    # top counter 2
    x1, y1 = 10,80
    h,w = cv2.getTextSize(f'Total Humans up: {len(total_humans_down)}', cv2.FONT_HERSHEY_PLAIN, 2, 2)[0]
    cv2.rectangle(img, (max(0,x1), max(0,y1)), (x1+h, y1-w), (0,0,0), cv2.FILLED)
    cv2.putText(img, f'Total Humans up: {len(total_humans_down)}', (x1,y1), cv2.FONT_HERSHEY_PLAIN, 2, (0,0,255), 2)

    cv2.imshow("Image", img)
    # cv2.imshow("Image Region", imgregion) #mask
    cv2.waitKey(1)


import numpy as np
from matplotlib import pyplot as plt

from YOLO import YOLO, ImageResult
from datasets.YoloTransforms import *
from datasets.YoloDataset import YoloDataset
from yolov5.utils import LOGGER
from yolov5.utils.box import Boxes, squeeze_with_indices
from yolov5.utils.image import Image
from yolov5.utils.train import Assigner

class DatasetEvaluator:
    def __init__(self, model: YOLO, dataset: YoloDataset, batch_size=1):
        self.model = model
        self.dataloader = dataset.get_dataloader(batch_size)
        if self.model.names is not None and self.model.names != dataset.names:
            LOGGER.Error("names must be equal")

    def get_iter(self, cutoff=None):
        size = cutoff if cutoff else len(self.dataloader)
        for i, data in enumerate(self.dataloader):
            if i == cutoff:
                break
            print(f"\r dataloader {i + 1}/{size}", end="")
            yield data

    def show(self, cutoff=None):
        i = 0
        for imgs, targets in self.get_iter(cutoff):
            for img, target in zip(imgs, targets):
                i += 1
                fig = plt.imshow(img.data)
                target.plot(fig.axes, self.model.names, ["r"] * len(self.model.names))
                plt.show()

    def detect(self, cutoff=None):
        self.model.eval_mode()
        for imgs, targets in self.get_iter(cutoff):
            preds = self.model(imgs)
            for img, target, pred in zip(imgs, targets, preds):
                fig = pred.plot(show=False)
                target.plot(fig.axes, self.model.names, ["r"] * len(self.model.names))
                plt.show()

    def show_assignment_layer(self, img: Image, matched_targets, pred, stride):
        fig = img.letterbox(self.model.imgsz).plot(False)
        fig.axes.grid()
        fig.axes.set_xticks(np.arange(0, self.model.imgsz, int(stride)))
        fig.axes.set_yticks(np.arange(0, self.model.imgsz, int(stride)))

        if matched_targets is None:
            plt.show()
            return

        targets, bi, ai, xi, yi = matched_targets.split([5, 1, 1, 1, 1], dim=-1)
        targets = Boxes(targets, has_conf=False)
        xi, yi = xi.clamp(0, pred.shape[3] - 1), yi.clamp(0, pred.shape[2] - 1)

        names = self.model.names
        targets.plot(fig.axes, names, ["r"] * len(names))

        pred = Boxes(pred[bi, ai, yi, xi, :5].view(-1, 5), is_xywh=True)
        pred[:, 4] = pred.conf.sigmoid()

        pred.plot(fig.axes, names, ["g"] * len(names))

        plt.show()

    def show_assignment(self, cutoff=30):
        self.model.train_mode()
        assigner = Assigner()
        strides = self.model.get_strides()
        anchors = self.model.get_anchors()
        for imgs, targets in self.get_iter(cutoff):
            with torch.no_grad():
                preds, targets = self.model.train_process(imgs, targets)

            for layer_idx, pred in enumerate(preds):
                stride = strides[layer_idx]
                matched_targets = assigner(targets, stride, anchors[layer_idx])
                for bi, img in enumerate(imgs):
                    t = matched_targets[matched_targets[..., 5] == bi] if matched_targets is not None else None
                    self.show_assignment_layer(img, t, pred, stride)

if __name__ == '__main__':
    mosaic = 0.0
    mixup = 1.0

    transforms = None
    # transforms = Transforms(RandomHorizontalFlip(), RandomHSV(), RandomRotate(10))
    # transforms = Transforms(RandomHorizontalFlip(), RandomHSV(), RandomCutImage(), proportions=[1.0, 0.2, 1.0])

    dataset = YoloDataset(path="datasets/train_fire.txt", input_size=640, augments=transforms, mosaic_prob=mosaic,
                          mixup_prob=mixup)

    model = YOLO("models/train/best.pt", ["fire", "smoke"], device_id=-1)
    # model.reset_num_classes()
    # model.init_weights()

    evaluator = DatasetEvaluator(model, dataset, 1)
    # evaluator.show(30)
    evaluator.detect(30)
    # evaluator.show_assignment(5)