from sys import argv, exit
from getopt import getopt, GetoptError
from os import path
from pickle import load
from itertools import islice

def init():
    inputFile = ""

    # Get the input arguments.
    try:
        opts, args = getopt(argv[1:],"hi:")
    # Unexpected arguments are provided.
    except GetoptError:
        print ('deserialize.py -i <inputfile>')
        exit(2)
    # For each provided argument:
    for opt, arg in opts:
        # Help argument.
        if opt == '-h':
            print ('deserialize.py -i <inputfile>')
            exit(2)
        # Input file argument.
        elif opt in ("-i"):
            inputFile = arg
            # Input file must exist.
            if not path.exists(inputFile):
                print('The input file does not exist.')
                exit(2)
            # Input file must also be a file.
            if not path.isfile(inputFile):
                print('The input is not a file.')
                exit(2)

    # Ensure that input file is not empty.
    if inputFile == "":
        print('Usage: deserialize.py -i <inputfile>')
        exit(2)

    return inputFile

def deserialize(inputFile):
    with open(inputFile, 'rb') as file:
        return load(file)

if __name__ == '__main__':
    # Get the input filename.
    inputFile = init()
    # Get the dict.
    deserializedDict = deserialize(inputFile)

    # Use the data, for instance print the first 10 n-grams:
    for key in islice(deserializedDict, 0, 10):
        print(key, "has", len(deserializedDict[key]), "occurrences.")


import json
import requests

from collections import OrderedDict
from SPARQLWrapper import SPARQLWrapper, JSON
from nltk.corpus import wordnet
from nltk.stem import SnowballStemmer
from nltk.tokenize import word_tokenize
import sys

# Takes in a word and stemms it
def stemm_word(word):
    stemmer = SnowballStemmer("english")
    word_token = word_tokenize(word)
    return stemmer.stem(word_token[0])

# Returns a list of synonyms of a word
def get_synonyms(word):
    synonyms = [word]
    for syn in wordnet.synsets(word):
        for lm in syn.lemmas():
            synonyms.append(lm.name())
    return list(OrderedDict.fromkeys(synonyms))

# Returns all possible stemmed strings
def get_stemm_combinations_rec(stemmed_string, word_list):
    if not word_list:
        return [stemmed_string]
    if stemmed_string == "":
        result_list = get_stemm_combinations_rec(word_list[0], word_list[1:])
        result_list.extend(get_stemm_combinations_rec(stemm_word(word_list[0]), word_list[1:]))
    else:
        result_list = get_stemm_combinations_rec(stemmed_string + " " + word_list[0], word_list[1:])
        result_list.extend(get_stemm_combinations_rec(stemmed_string + " " + stemm_word(word_list[0]), word_list[1:]))
    return result_list

def get_stemm_combinations(words):
    if (not words):
        return []
    word_list = words.split()
    return get_stemm_combinations_rec("", word_list)

# Returns all the existing matching properties of the entity uri
def get_prop_uri_list(uri, prop):
    sparql = SPARQLWrapper("https://dbpedia.org/sparql")
    query = """
            PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
            PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
            SELECT ?value
            WHERE {
                <""" + uri + """> ?value ?x .
                ?value a rdf:Property .
                ?value rdfs:label ?name .
                FILTER(bif:contains(?name, \'\"""" + prop + """\"\'))
            }
            """

    sparql.setQuery(query)
    sparql.setReturnFormat(JSON)
    global result
    result = list()
    a = sparql.query()
    results = a.convert()

    # parsing for dbpedia
    for data in results["results"]["bindings"]:
        result.append(data["value"]["value"])
    # removing redundant data from the result set, by using set function and then converting it to a list
    result = list(set(result))
    return result

# Returns all the entity URIs, who's labels match the entity name

def get_entity_uri_list(entity):
    sparql = SPARQLWrapper("https://dbpedia.org/sparql")
    # Right now relevance is decided by number of pages in other languages
    query = """
            PREFIX dbr: <http://dbpedia.org/resource/>
            PREFIX dbo: <http://dbpedia.org/ontology/>
            PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
            PREFIX owl: <http://www.w3.org/2002/07/owl#>
            SELECT DISTINCT ?value (COUNT(?s) as ?relevance)
            WHERE {
                {
                    ?temp rdfs:label ?name .
                    FILTER(bif:contains(?name, \"\'""" + entity + """\'\") && strstarts(str(?temp), "http://dbpedia.org/resource/"))
                    ?temp dbo:wikiPageDisambiguates ?value .
                    ?value owl:sameAs ?s
                } UNION {
                    ?temp rdfs:label ?name .
                    FILTER(bif:contains(?name, \"\'""" + entity + """\'\") && strstarts(str(?temp), "http://dbpedia.org/resource/"))
                    ?temp dbo:wikiPageRedirects ?value .
                    ?value owl:sameAs ?s
                } UNION {
                    ?value rdfs:label ?name .
                    FILTER(bif:contains(?name, \"\'""" + entity + """\'\") && strstarts(str(?value), "http://dbpedia.org/resource/")) .
                    FILTER NOT EXISTS{?value dbo:wikiPageDisambiguates ?x} .
                    FILTER NOT EXISTS{?value dbo:wikiPageRedirects ?y} .
                    ?value owl:sameAs ?s
                }
            } ORDER BY DESC(?relevance)
            """

    sparql.setQuery(query)
    sparql.setReturnFormat(JSON)
    global result
    result = list()
    a = sparql.query()
    results = a.convert()

    # parsing for dbpedia
    for data in results["results"]["bindings"]:
        result.append(data["value"]["value"])

    # removing redundant data from the result set, by using set function and then converting it to a list
    result = list(result)
    return result

# Fetches the data of given triplet
def SPARQL_data(uri, prop):
    sparql = SPARQLWrapper("https://dbpedia.org/sparql")
    query = """
            PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
            SELECT ?value WHERE
            {
                {
                    <""" + uri + """> <""" + prop + """> ?value .
                    FILTER ((LANG(?value) = "en") || !(datatype(?value) = xsd:string)) .
                } UNION {
                    <""" + uri + """> <""" + prop + """> ?temp .
                    ?temp rdfs:label ?value
                    FILTER (isURI(?temp)) .
                    FILTER ((LANG(?value) = "en")) .
                }
            }
            """

    sparql.setQuery(query)
    sparql.setReturnFormat(JSON)
    global result
    result = list()
    a = sparql.query()
    results = a.convert()

    # parsing for dbpedia
    for data in results["results"]["bindings"]:
        result.append(data["value"]["value"])

    # removing redundant data from the result set, by using set function and then converting it to a list
    result = list(set(result))
    return result

def get_answer_data(entity, prop = None):
    abstract = "http://dbpedia.org/ontology/abstract"
    entity_uri_list = None
    # Try to get the entity URIs
    for e in get_stemm_combinations(entity):
        if (not entity_uri_list):
            entity_uri_list = get_entity_uri_list(e)
    # Continue if you found some entities
    if (entity_uri_list):
        # If you've been given property, try to find it in all the found entities
        if (prop):
            prop_uri_list = None
            for e in entity_uri_list:
                for p in get_synonyms(prop):
                    if (not prop_uri_list):
                        prop_uri_list = get_prop_uri_list(e, p)
                        entity_uri = e
            # If you've found the property, fetch the data
            if (prop_uri_list):
                res = (SPARQL_data(entity_uri, prop_uri_list[0]))
            # Else fetch the abstract data of the most relevant entity
            else:
                entity_uri = entity_uri_list[0]
                res = SPARQL_data(entity_uri, abstract)
        # If you haven't been given property, fetch the abstract data of the most relevant entity
        else:
            entity_uri = entity_uri_list[0]
            res = SPARQL_data(entity_uri, abstract)
    # If you didn't find any entity URIs, return empty values
    else:
        entity_uri = ""
        res = []
    # Package the data and return it
    data = {'uri': entity_uri, 'result': res}
    json_data = json.dumps(data)
    return json_data


# Sentiment analysis for brand new iphone 13
"""
we have imported textblob library which inherits lexicon list of negative & positive words
like, positive- good,nice & negative words- bad ,adverse etc.
"""
from textblob import TextBlob
print("Enter your views about Iphone 13")
x = str(input())
feedback = TextBlob(x)
y = feedback.sentiment.polarity

# checking polarity & subjectivity of sentence with if else
if y < 0:
    print("Thanks for your feedback! We will improve our product according to your specifications & features")
elif y == 0:
    print("Thanks for your feedback!")
elif 0 < y <= 1:
    print("Thanks for your feedback! We are glad that you liked out product")


# Write a Python program to accept the user's first and last name and then getting them
# printed in the the reverse order with a space between first name and last name.

def get_string(prompt) :
  while True:
    val = input(prompt).strip()

    if val != "" :
      return val

def reverse_string(str):
  return str[-1::-1]

if __name__ == "__main__":
    # execute only if run as a script

    firstName = get_string("Please enter your First Name :")
    lastName  = get_string("Please enter your Last Name :")

    print("Reversed First and Last Names are : {} {}".format(reverse_string(firstName), reverse_string(lastName)))


#! /bin/python3

def check_rows(lst) :
    fun = False
    for ls in lst :
        if(all(x == ls[0] for x in ls)) :
            fun = True
            return (fun, ls[0])

def check_col(lst) :
    for i in range(3) :
        ls = []
        for j in range(3) :
            ls.append(lst[i][j])
        if(all(x == ls[0] for x in ls)) :
            return (True, ls[0])

def check_dia(lst) :
    pass

lst1 = list(input("Enter the first row elements: "))
lst2 = list(input("Enter the second row elements: "))
lst3 = list(input("Enter the third row elements: "))
lst = [lst1, lst2, lst3]
a, b = check_col(lst)
print (a, b)


import torch
import torchvision
import torchvision.transforms as transforms
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import matplotlib.pyplot as plt
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter

         # ================================================================== #
         #                      Discriminator Network                         #
         # ================================================================== #

class Disc(nn.Module):
    def __init__(self):
        super().__init__()
        #Convolution layers
        self.conv1 = nn.Conv2d(1, 6, 5)
        self.conv2 = nn.Conv2d(6, 12, 5)
        #Fletten (dense) layers
        self.fc1 = nn.Linear(12*4*4, 120)
        self.fc2 = nn.Linear(120, 60)
        self.out = nn.Linear(60, 1)
    def forward(self, x):
        # input layer
        x = x
        # hidden conv layer
        x = self.conv1(x)
        x = F.relu(x)
        x = F.max_pool2d(x, 2, 2)
        # hidden conv layer
        x = self.conv2(x)
        x = F.relu(x)
        x = F.max_pool2d(x, 2, 2)
        # hidden linear layer
        x = x.reshape(-1, 12*4*4)
        x = self.fc1(x)
        x = F.relu(x)
        # hidden linear layer
        x = self.fc2(x)
        x = F.relu(x)
        # output layer
        x = self.out(x)
        # Sigmoid function
        x = F.sigmoid(x)
        return x

         # ================================================================== #
         #                        Generator Network                           #
         # ================================================================== #

class Gen(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc1 = nn.Linear(64, 256)
        self.fc2 = nn.Linear(256, 512)
        self.out = nn.Linear(512, 784)
    def forward(self, x):
        #input layer
        x = x
        #hidden linear layer
        x = self.fc1(x)
        x = F.relu(x)
        #hidden linear layer
        x = self.fc2(x)
        x = F.relu(x)
        #hidden linear layer
        x = self.out(x)
        x = F.tanh(x)
        return x

         # ================================================================== #
         #                      Training Settings                             #
         # ================================================================== #

                        #=================================#
                        #          MNIST dataset          #
                        #=================================#

train_set = torchvision.datasets.MNIST(
    root = './train_dataset/MNIST', train = True,
    download = False, transform = transforms.Compose([
        transforms.ToTensor(),
        transforms.Normalize(mean = [0.5], std = [0.5])]))

                        #=================================#
                        #         Normlizing Data         #
                        #=================================#

# loader = DataLoader(train_set, batch_size=len(train_set), shuffle = False)

# loader_norm = DataLoader(train_set_norm, batch_size = len(train_set_norm), shuffle = False)

# data = next(iter(loader))

# data_norm = next(iter(loader_norm))

# m = data[0].mean()
# s = data[0].std()

# m_norm = data_norm[0].mean()
# s_norm = data_norm[0].std()

# print(m)
# print(s)

# print(m_norm)
# print(s_norm)

# plt.hist(data[0].flatten())
# plt.axvline(data[0].mean())
# plt.axvline(data[0].std())
# plt.xlabel('pixel value')
# plt.ylabel('number of pixels')

# plt.hist(data_norm[0].flatten())
# plt.axvline(data_norm[0].mean())
# plt.axvline(data_norm[0].std())
# plt.xlabel('pixel value')
# plt.ylabel('number of pixels')

                        #=================================#
                        #           Training Set          #
                        #=================================#

my_device = torch.device('cuda:0')

batch_size = 100

num_epochs = 200

train_loader = torch.utils.data.DataLoader(train_set, batch_size = batch_size, shuffle = True)

disc_network = Disc().to(my_device)

gen_network = Gen().to(my_device)

disc_optimizer = optim.Adam(disc_network.parameters(), lr = 0.0002)

gen_optimizer = optim.Adam(gen_network.parameters(), lr = 0.0002)

criterion = nn.BCELoss()

          # ================================================================== #
          #                      Adversarial Training                          #
          # ================================================================== #

tb_disc_graph = SummaryWriter()

tb_gen_graph = SummaryWriter()

tb_real_imgs = SummaryWriter()

tb_fake_imgs = SummaryWriter()

batch_num = len(train_loader) # Number of batches or Number of iterations

step_graph = 0

step_img = 0

for epoch in range(num_epochs):
    for i, (imgs, _) in enumerate(train_loader):
        imgs = imgs.to(my_device)
                        #=================================#
                        #      Discriminator Training     #
                        #=================================#

        real_labels = torch.ones(batch_size, 1).to(my_device)
        preds = disc_network(imgs)
        disc_loss_real = criterion(preds, real_labels).to(my_device)

        fake_labels = torch.zeros(batch_size, 1).to(my_device)
        z_noise_set = torch.randn(batch_size, 64).to(my_device)
        fake_imgs = gen_network(z_noise_set)
        fake_imgs = fake_imgs.reshape(batch_size, 1, 28, 28)
        fake_imgs = fake_imgs.to(my_device)
        preds = disc_network(fake_imgs)
        disc_loss_fake = criterion(preds, fake_labels)

        disc_loss = disc_loss_real + disc_loss_fake
        disc_optimizer.zero_grad()
        disc_loss.backward()
        disc_optimizer.step()

                        #=================================#
                        #         Generator Training      #
                        #=================================#

        z_noise_set = torch.randn(batch_size, 64).to(my_device)
        fake_imgs = gen_network(z_noise_set)
        fake_imgs = fake_imgs.reshape(batch_size, 1, 28, 28)
        fake_imgs = fake_imgs.to(my_device)
        preds = disc_network(fake_imgs)
        gen_loss = criterion(preds, real_labels)
        gen_optimizer.zero_grad()
        gen_loss.backward()
        gen_optimizer.step()

        tb_disc_graph.add_scalar('Discriminator Loss', disc_loss, global_step = step_graph)
        tb_gen_graph.add_scalar('Generator Loss', gen_loss, global_step = step_graph)
        step_graph = step_graph + 1
        if (i+1) % 100 == 0:
            print(f"Epoch num[{epoch}/{num_epochs}], Batch num [{i+1}/{batch_num}], Discriminator Loss: {disc_loss:.4f}, Generator Loss: {gen_loss:.4f}")
            img_grid_real = torchvision.utils.make_grid(imgs, normalize=True)
            img_grid_fake = torchvision.utils.make_grid(fake_imgs, normalize=True)
            tb_real_imgs.add_image("MNIST Real Images", img_grid_real, global_step = step_img)
            tb_fake_imgs.add_image("MNIST Fake Images", img_grid_fake, global_step = step_img)
            step_img = step_img + 1


import unittest, sys, tempfile, os
import testlib

try:
    from private.qrt.librsvg import PrivateLibrsvgTest
except ImportError:
    class PrivateLibrsvgTest(object):
        '''Empty class'''
    print >>sys.stdout, "Skipping private tests"

class LibrsvgTest(testlib.TestlibCase, PrivateLibrsvgTest):
    '''Test librsvg.'''

    def setUp(self):
        '''Set up prior to each test_* function'''
        self.fs_dir = os.path.abspath('.')
        os.chdir('librsvg')

    def tearDown(self):
        '''Clean up after each test_* function'''
        os.chdir(self.fs_dir)

    def _test_render(self, svg_filename):
        '''Convert to jpg to check for conversion warnings'''
        jpg_tmp = tempfile.NamedTemporaryFile(prefix='convert-',suffix='.jpg')
        jpg_filename = jpg_tmp.name

        self.assertFileType(svg_filename, 'SVG Scalable Vector Graphics image')
        self.assertShellExitEquals(0, ["eog", svg_filename])

        # Try a to-JPG conversion to catch rendering problems
        self.assertShellOutputEquals("",
                                     ["/usr/bin/convert",
                                      svg_filename,
                                      jpg_filename],
                                     expected=0)
        self.assertFileType(jpg_filename, 'JPEG image data.*')
        self.assertShellExitEquals(0, ["eog", jpg_filename])

    def test_complex_svg(self):
        '''normal SVG will render'''
        self._test_render("simple.svg")
        if self.lsb_release['Release'] > 10.04:
            self._test_render("complex.svg")

    def test_filters(self):
        '''misnamed filters do not run arbitrary code (CVE-2011-3146)'''
        self._test_render("good-filter.svg")
        self._test_render("bad-filter.svg")
        self._test_render("big-filter.svg")

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


"""
Calculates an exchange-flow oriented salt budget from TEF terms, and
explores dynamical scaling:

does Qe behave as expected relative to dSbar_dx and K?

"""

# imports
import matplotlib.pyplot as plt
import numpy as np
import pickle
import pandas as pd
from datetime import datetime, timedelta

import os; import sys
sys.path.append(os.path.abspath('../alpha'))
import Lfun
import zrfun
import zfun

import tef_fun
import flux_fun
from importlib import reload
reload(flux_fun)

from time import time

from warnings import filterwarnings
filterwarnings('ignore') # skip some warning messages
# associated with lines like QQp[QQ<=0] = np.nan

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-g', '--gridname', type=str, default='cas6')
parser.add_argument('-t', '--tag', type=str, default='v3')
parser.add_argument('-x', '--ex_name', type=str, default='lo8b')
parser.add_argument('-y', '--year', type=int, default=2017)
#parser.add_argument('-v', '--volume', type=str, default='Puget Sound')
args = parser.parse_args()
#which_vol = args.volume
year_str = str(args.year)

# Get Ldir
Ldir = Lfun.Lstart(args.gridname, args.tag)
gtagex = args.gridname + '_' + args.tag + '_' + args.ex_name

# select input/output location
run_name = gtagex+'_'+year_str+'.01.01_'+year_str+'.12.31'
indir00 = Ldir['LOo'] + 'tef/'
indir0 = indir00 + run_name + '/'
indir = indir0 + 'flux/'

outdir = indir00 + 'sill_dyn_plots/'
Lfun.make_dir(outdir)

# get section definitions
sect_df = tef_fun.get_sect_df()

# get volumes
voldir = indir00 + 'volumes_' + Ldir['gridname'] + '/'
v_df = pd.read_pickle(voldir + 'volumes.p')

plt.close('all')
#for which_vol in ['Salish Sea', 'Puget Sound', 'Hood Canal', 'South Sound', 'Strait of Georgia']:
for which_vol in ['Puget Sound']:

    # load low passed segment volume and net salt DataFrames
    v_lp_df = pd.read_pickle(indir + 'daily_segment_volume.p')
    sv_lp_df = pd.read_pickle(indir + 'daily_segment_net_salt.p')

    # Note that we trim off the first list item because we are doing our
    # dynamical calculations at something like the middle of a sill,
    # e.g. ai2 where we can sensibly calculate gradients like dSbar_dx.
    if which_vol == 'Salish Sea':
        seg_list = list(v_lp_df.columns)
        seg_list = seg_list[1:]
        sect_sign_dict = {'jdf2':1}
    elif which_vol == 'Puget Sound':
        seg_list = (flux_fun.ssA + flux_fun.ssM + flux_fun.ssT
            + flux_fun.ssS + flux_fun.ssW + flux_fun.ssH)
        # seg_list = seg_list[1:]
        # sect_sign_dict = {'ai2':1}
        seg_list = seg_list[3:]
        sect_sign_dict = {'ai4':1}
    elif which_vol == 'Hood Canal':
        seg_list = flux_fun.ssH
        seg_list = seg_list[1:]
        sect_sign_dict = {'hc2':1}
    elif which_vol == 'South Sound':
        seg_list = flux_fun.ssT + flux_fun.ssS
        seg_list = seg_list[1:]
        sect_sign_dict = {'tn2':1}
    elif which_vol == 'Strait of Georgia':
        seg_list = flux_fun.ssG
        seg_list = seg_list[1:]
        sect_sign_dict = {'sji2':1}

    v_lp_df = v_lp_df[seg_list]
    sv_lp_df = sv_lp_df[seg_list]

    river_list = []
    for seg_name in seg_list:
        seg = flux_fun.segs[seg_name]
        river_list = river_list + seg['R']
        riv_df = pd.read_pickle(Ldir['LOo'] + 'river/'
            + Ldir['gtag'] + '_'+year_str+'.01.01_'+year_str+'.12.31.p')
    riv_df.index += timedelta(days=0.5)
    riv_df = riv_df[river_list]

    tef_df_dict = {}
    for sn in sect_sign_dict.keys():
        in_sign = sect_sign_dict[sn]
        tef_df_dict[sn] = flux_fun.get_fluxes(indir0, sn, in_sign=in_sign)

    vol_df, salt_df, vol_rel_err, salt_rel_err, salt_rel_err_qe = flux_fun.get_budgets(
        sv_lp_df, v_lp_df, riv_df, tef_df_dict, seg_list)

    # getting gradients across the seaward section
    if which_vol == 'Salish Sea':
        sea_sect = 'jdf1'; land_sect = 'jdf3'
        sea_seg = 'J1'; land_seg = 'J2'
        sill_name = 'Western Strait of Juan de Fuca'

    elif which_vol == 'Puget Sound':
        # sea_sect = 'ai1'; land_sect = 'ai3'
        # sea_seg = 'A1'; land_seg = 'A2'
        sea_sect = 'ai3'; land_sect = 'mb1'
        sea_seg = 'A3'; land_seg = 'M1'
        sill_name = 'Admiralty Inlet South'

    elif which_vol == 'South Sound':
        sea_sect = 'tn1'; land_sect = 'tn3'
        sea_seg = 'T1'; land_seg = 'T2'
        sill_name = 'Tacoma Narrows'

    elif which_vol == 'Hood Canal':
        sea_sect = 'hc1'; land_sect = 'hc3'
        sea_seg = 'H1'; land_seg = 'H2'
        sill_name = 'Hood Canal'

    elif which_vol == 'Strait of Georgia':
        sea_sect = 'sji1'; land_sect = 'sog1'
        sea_seg = 'G1'; land_seg = 'G2'
        sill_name = 'San Juan Islands'

    df1 = flux_fun.get_fluxes(indir0, sea_sect)
    df3 = flux_fun.get_fluxes(indir0, land_sect)

    # get DX for dSbar_dx
    sea_lon = (sect_df.loc[sea_sect,'x0'] + sect_df.loc[sea_sect,'x1'])/2
    sea_lat = (sect_df.loc[sea_sect,'y0'] + sect_df.loc[sea_sect,'y1'])/2
    land_lon = (sect_df.loc[land_sect,'x0'] + sect_df.loc[land_sect,'x1'])/2
    land_lat = (sect_df.loc[land_sect,'y0'] + sect_df.loc[land_sect,'y1'])/2
    mean_lon = (sea_lon + land_lon)/2
    mean_lat = (sea_lat + land_lat)/2
    sea_x, sea_y = zfun.ll2xy(sea_lon, sea_lat, mean_lon, mean_lat)
    land_x, land_y = zfun.ll2xy(land_lon, land_lat, mean_lon, mean_lat)
    DX = np.sqrt((sea_x-land_x)**2 + (sea_y-land_y)**2)

    # various things for the dynamical scalings
    dSbar_dx = ((df1['Sin']+df1['Sout'])/2-(df3['Sin']+df3['Sout'])/2)/DX
    DF = df1['Ftide']-df3['Ftide'] # Net loss of tidal energy flux in region
    A0 = v_df.loc[sea_seg,'area m2'] + v_df.loc[land_seg,'area m2']
    V0 = v_df.loc[sea_seg,'volume m3'] + v_df.loc[land_seg,'volume m3']
    H0 = V0/A0 # average depth of surrounding segments
    B0 = V0/(H0*DX)

    # dynamical scalings
    a = 2.5 * 0.028 # the 2.5 is a fudge factor to get Qe to match Qe_pred
    Cd = 2.6e-3
    h = H0/2 # m
    rho = 1027 # kg m-3
    g = 9.8 # m2 s-1
    beta = 7.7e-4
    dyn_df = pd.DataFrame(index=salt_df.index)
    Km = (a**3 * Cd**2 * h**3 * DF / (rho*A0))**(1/3)
    Ks = Km/2.2
    dyn_df['Km'] = Km
    dyn_df['Ks'] = Ks
    dyn_df['dSbar_dx'] = dSbar_dx
    Ue = g * beta * dSbar_dx * H0**3 / (48 * Km)
    dyn_df['Ue'] = Ue
    dyn_df['Qe_pred'] = (Ue * B0 * H0 / 4)
    dyn_df['Qe'] = salt_df['Qe']
    dyn_df['DS_pred'] = H0**2 * dSbar_dx * Ue / (12 * Ks)
    dyn_df['DS'] = salt_df['DS']
    dyn_df['QeDS_pred'] = dyn_df['Qe_pred'] * dyn_df['DS_pred']
    dyn_df['QeDS'] = salt_df['QeDS']
    dyn_df['Qe_tide_pred'] = (vol_df['Qtide'])/7

    for cn in dyn_df.columns:
        dyn_df[cn] = pd.to_numeric(dyn_df[cn])
        if 'Q' in cn:
            # convert transports to 1000 m3/s
            dyn_df[cn] = dyn_df[cn]/1000

    fig = plt.figure(figsize=(12,12))

    lab_dict = {'Qe':'$Q_{E}\ (10^{3}\ m^{3}s^{-1})$',
                'Qe_pred':'$Predicted\ Q_{E}\ (10^{3}\ m^{3}s^{-1})$',
                'QeDS':'$Q_{E}\Delta S\ (10^{3}\ m^{3}s^{-1} g\ kg^{-1})$',
                'QeDS_pred':'$Predicted\ Q_{E}\Delta S\ (10^{3}\ m^{3}s^{-1} g\ kg^{-1})$',
                'Qe_tide_pred':'$Q_{Tide}/7\ (10^{3}\ m^{3}s^{-1})$',
                'DS':'$\Delta S (g\ kg^{-1})$',
                'DS_pred':'$Predicted\ \Delta S\ (g\ kg^{-1})$',
                }

    fs = 14
    axcount = 1
    for vtup in [('Qe','Qe_pred'),('DS','DS_pred'),('QeDS','QeDS_pred'),('Qe','Qe_tide_pred')]:
        ax = fig.add_subplot(2,2,axcount)
        v0 = dyn_df[vtup[0]].to_numpy()
        v1 = dyn_df[vtup[1]].to_numpy()
        r = np.corrcoef(v0, v1)[0,1]
        ax.plot(v0, v1, 'og', markersize=2)
        ax.grid(True)
        ax.axis('square')
        if 'Qe' in vtup[0]:
            axmax = 2*(dyn_df['Qe'].to_numpy()).mean()
        else:
            axmax = v0.mean() + 2*v0.std()
        ax.set_xlim(0,axmax)
        ax.set_ylim(0,axmax)
        ax.plot([0,axmax],[0,axmax],'-k')
        ax.set_xlabel(lab_dict[vtup[0]], size=fs)
        ax.set_ylabel(lab_dict[vtup[1]], size=fs)
        ax.text(.95, .1, '$r^{2}=%0.2f$' % (r*r), ha='right', transform = ax.transAxes, size=fs)
        axcount += 1
    fig.suptitle(sill_name + ' ' + year_str, size=fs+2)

    # a second figure aimed at time series
    fig2 = plt.figure(figsize=(15,15))

    vol_df['Qtide_scl'] = vol_df['Qtide']/7000
    vol_df['Qe_scl'] = salt_df['Qe']/1000
    vol_df['Qr_scl'] = vol_df['Qr']/1000
    vol_df['QeDS_scl'] = salt_df['QeDS']/1000
    vol_df['DS_scl'] = salt_df['DS'] * 30

    ax = fig2.add_subplot(411)
    vol_df[['QeDS_scl','Qtide_scl']].plot(ax=ax, grid=True, legend=False)
    ax.set_xlim(salt_df.index[0], salt_df.index[-1])
    legh = ax.legend(labels=['$Q_{E}\Delta S\ (g/kg\ 1000\ m^{3}s^{-1})$', '$Q_{Tide}\ (7000\ m^{3}s^{-1})$'])
    ax.set_xticklabels([])
    ax.set_title('%s TEF Terms vs. $Q_{Tide}$' % (sill_name))

    ax = fig2.add_subplot(412)
    vol_df[['Qe_scl','Qtide_scl']].plot(ax=ax, grid=True, legend=False)
    ax.set_xlim(salt_df.index[0], salt_df.index[-1])
    legh = ax.legend(labels=['$Q_{E}\ (1000\ m^{3}s^{-1})$', '$Q_{Tide}\ (7000\ m^{3}s^{-1})$'])
    ax.set_xticklabels([])

    ax = fig2.add_subplot(413)
    vol_df[['DS_scl','Qtide_scl']].plot(ax=ax, grid=True, legend=False)
    ax.set_xlim(salt_df.index[0], salt_df.index[-1])
    legh = ax.legend(labels=['$30\Delta S\ (g/kg)$', '$Q_{Tide}\ (7000\ m^{3}s^{-1})$'])
    ax.set_xticklabels([])

    ax = fig2.add_subplot(414)
    ax2 = ax.twinx()
    vol_df['Qr_scl'].plot(ax=ax, style='-g')
    salt_df['DS'].plot(ax=ax2, legend=False, style='-r')
    ax.set_ylabel('$Q_{R}\ (1000\ m^{3}s^{-1})$', color='g')
    ax2.set_ylabel('$\Delta S\ (g/kg)$', color='r')
    ax.set_xlim(salt_df.index[0], salt_df.index[-1])

    #plt.show()

    fig.savefig(outdir + sill_name.replace(' ','_') + '_' + year_str + '_' + 'scatter.png')
    fig2.savefig(outdir + sill_name.replace(' ','_') + '_' + year_str + '_' + 'series.png')


# -*- coding: utf-8 -*-
# Socket是网络编程的一个抽象概念。通常我们用一个Socket表示“打开了一个网络链接”，而打开一个Socket需要知道目标计算机的IP地址和端口号，再指定协议类型即可
import socket
# 创建一个socket:
# AF_INET指定使用IPv4协议，如果要用更先进的IPv6，就指定为AF_INET6。 SOCK_STREAM指定使用面向流的TCP协议
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 建立连接:
s.connect(('www.sina.com.cn', 80))

# 发送数据:
s.send(b'GET / HTTP/1.1\r\nHost: www.sina.com.cn\r\nConnection: close\r\n\r\n')

# TCP连接创建的是双向通道，双方都可以同时给对方发数据。但是谁先发谁后发，怎么协调，要根据具体的协议来决定。例如，HTTP协议规定客户端必须先发请求给服务器，服务器收到后才发数据给客户端。
# 接收数据:
buffer = []
while True:
    # 每次最多接收1k字节:
    d = s.recv(1024)
    if d:
        buffer.append(d)
    else:
        break
data = b''.join(buffer)
print(data)

# 关闭连接:
s.close()

# 接收到的数据包括HTTP头和网页本身，我们只需要把HTTP头和网页分离一下，把HTTP头打印出来，网页内容保存到文件
header, html = data.split(b'\r\n\r\n', 1)
print(header.decode('utf-8'))
# 把接收的数据写入文件:
with open('sina.html', 'wb') as f:
    f.write(html)

# 服务器会打开固定端口（比如80）监听，每来一个客户端连接，就创建该Socket连接。由于服务器会有大量来自客户端的连接，所以，服务器要能够区分一个Socket连接是和哪个客户端绑定的。一个Socket依赖4项：服务器地址、服务器端口、客户端地址、客户端端口来唯一确定一个Socket。
# 我们来编写一个简单的服务器程序，它接收客户端连接，把客户端发过来的字符串加上Hello再发回去
# 首先，创建一个基于IPv4和TCP协议的Socket：

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 监听端口:
s.bind(('127.0.0.1', 9999))

# 紧接着，调用listen()方法开始监听端口，传入的参数指定等待连接的最大数量：
s.listen(5)
print('Waiting for connection...')

# 接下来，服务器程序通过一个永久循环来接受来自客户端的连接，accept()会等待并返回一个客户端的连接:
while True:
    # 接受一个新连接:
    sock, addr = s.accept()
    # 创建新线程来处理TCP连接:
    t = threading.Thread(target=tcplink, args=(sock, addr))
    t.start()


import sys
n, m = map(int, sys.stdin.readline().split())
tree = list(map(int, sys.stdin.readline().split()))
left = 0
right = max(tree)
mid = (left + right)//2
while True:
    count = 0
    for i in range(n):
        if tree[i] > mid:
            count += tree[i]-mid
    if count >= m:
        if left == right:
            print(left)
            break
        else:
            left = mid + 1
            mid = (right + left) // 2
    else:
        if left == right:
            print(left - 1)
            break
        elif left == right - 1:
            print(left - 1)
            break
        else:
            right = mid - 1
            mid = (right + left) // 2


start, days = [int(n) for n in input().split()]
print("Sun Mon Tue Wed Thr Fri Sat")

calendar_spots = [""] * (start-1) + [n for n in range(1, days+1)]

for n in range(0, days+start-1, 7):
    week_str = ""
    for spot in calendar_spots[n:n+7]:
        week_str += "{:>3} ".format(spot)
    print(week_str[:-1])


"""
Creates database from converted OpenPose output files (should now be in .txt format) for use with RNN
for Human Activity Recognition - 2D Pose Input
"""

import json
from pprint import pprint
import glob, os
import numpy as np

test_file_X = "X_test.txt"
test_file_Y = "Y_test.txt"
train_file_X = "X_train.txt"
train_file_Y = "Y_train.txt"

data_path = "Data/MHAD/images"
activity_list =["jumping","jumping_jacks","boxing","waving_2hands","waving_1hand","clapping_hands"]
# Activity 3, bending, not to be included due to extreme pose distortion
cluster_nums=4
camera_nums=1
subject_nums=12
activity_nums=7
repetition_nums=5

# num_steps depends on rate of video and window_width to be used
# in this case camera was 22Hz and a window_width of 1.5s was wanted, giving 22*1.5 = 33
num_steps = 32
test_train_split = 0.8
overlap = 0.8125 # 0 = 0% overlap, 1 = 100%

# Read in all text files and create x_all and y_all files, with no splitting yet
# cut each frameset into 33 frame chunks (the input window width for out network)
# Note: No overlap has been performed yet!

for activity in range(0,len(activity_list)):
	os.chdir(os.path.join(data_path,activity_list[activity]))
	for file in sorted(glob.glob("*.txt")):
		# 1. Decide whether this entire frameset will be added to the test or train dataset (based on test_train_split)
		# 2. Have decided not to lop off any initial or end frames, eg as the subjects raise/lower hands whilst boxing.
		# 3. Determine how many chunks can be made from the frameset with required overlap and window width
		is_train = np.random.rand(1) < test_train_split
		print(is_train)
		data_file = open(file,'r')
		file_text = data_file.readlines()
		# Check how many framesets of length 33 we can get out of the total frames in this files
		num_frames = len(file_text)
		num_framesets = int((num_frames - num_steps)/(num_steps*(1-overlap)))+1
		data_file.close
		# Copy data to either test or train set dependent on is_train
		if is_train:
			output_file_X = train_file_X
			output_file_Y = train_file_Y
		else:
			output_file_X = test_file_X
			output_file_Y = test_file_Y
		x_file = open(os.path.join(data_path,output_file_X), 'a')
		for frameset in range(0, num_framesets):
			start = int(frameset*num_steps*(1-overlap))
			for line in range(start,(start+num_steps)):
				x_file.write(file_text[line])
		x_file.close()

		y_file = open(os.path.join(data_path,output_file_Y), 'a')
		for line in range(0,num_framesets):
			y_file.write(str(activity+1)+"\n")
		y_file.close()


class User:
    def __init__(self, name,):
        self.name = name
        self.account_balance = 0

    def make_deposit(self, amount):
        self.account_balance += amount

    def make_withdrawl(self, amount):
        self.account_balance -= amount

    def display_user_balance(self):
        print(f"User: {self.name}, Balance: ${self.account_balance}")

    def transfer_money(self,user,amount):
        self.account_balance -=amount
        user.account_balance += amount
        self.display_user_balance()
        user.display_user_balance()

xena = User("Xena B")
austin = User("Austin P")
bentley = User ("Bentley B")

#>>>>1st User
xena.make_deposit(150)
xena.make_deposit(200)
xena.make_deposit(30)
xena.make_withdrawl(144)
xena.display_user_balance()
#>>>>2nd User
austin.make_deposit(421)
austin.make_deposit(3200)
austin.make_withdrawl(1207)
austin.make_withdrawl(167)
austin.display_user_balance()
#>>>>3rd User
bentley.make_deposit(790)
bentley.make_withdrawl(320)
bentley.make_withdrawl(260)
bentley.make_withdrawl(413)
bentley.display_user_balance()

xena.transfer_money(bentley, 205)


# pylint: disable=wrong-import-position

APP_NAME = "fb"
OPERATION_NAME = "add_post_reaction"
REQUEST_METHOD = "post"
URL_SUFFIX = "post/{post_id}/react/"

from .test_case_01 import TestCase01AddPostReactionAPITestCase

__all__ = [
    "TestCase01AddPostReactionAPITestCase"
]


from tkinter import *
from  quize_brain import QuizeBrain
THEM_COLOR = "#375362"
class QuizInterface:
    def __init__(self,quiz: QuizeBrain):
        self.quiz = quiz
        self.window = Tk()
        self.window.title("Quizzler")
        self.window.config(padx=20,pady=20,bg=THEM_COLOR)

        self.label_score = Label(text="Score: 0",bg=THEM_COLOR,fg="white")
        self.label_score.grid(column=1, row=0)

        self.canvas = Canvas(width=300,height=250,)
        self.canvas.grid(column=0,row=1,columnspan=2,pady=50)
        self.text = self.canvas.create_text(150,125, font=("Arial",20,"italic"),fill=THEM_COLOR,text="somthing",width=280)

        self.right_path = PhotoImage(file="images/right.png")
        self.right_button = Button(image=self.right_path,command=self.true)
        self.right_button.grid(column=0,row=2)

        self.wrong_path = PhotoImage(file="images/wrong.png")
        self.wrong_button = Button(image=self.wrong_path,highlightthickness=0,command=self.false)
        self.wrong_button.grid(column=1, row=2)
        self.get_next_question()
        self.window.mainloop()

    def get_next_question(self):
        self.canvas.config(bg="white")
        if self.quiz.is_still_has_question():
            self.label_score.config(text=f"score: {self.quiz.secor}")
            q_text = self.quiz.next_question()
            self.canvas.itemconfig(self.text,text= q_text)
        else:
            self.canvas.itemconfig(self.text,text="End")
            self.right_button.config(state="disabled")
            self.wrong_button.config(state="disabled")

    def true(self):
        self.give_feedback(self.quiz.checking_answer("True"))
    def false(self):
        self.give_feedback(self.quiz.checking_answer("False"))

    def give_feedback(self,is_right):
        if is_right:
            self.canvas.config(bg="green")
        else:
            self.canvas.config(bg="red")

        self.window.after(1000,self.get_next_question)


# -*- coding: utf-8 -*-
"""
Created on Sat Jun 17 23:33:23 2023

@author: tarun
"""

import tensorflow as tf
from keras.preprocessing.image import ImageDataGenerator

##version of tensor flow
tf.__version__

##Prerocessing the training set
train_datagen = ImageDataGenerator(
                 rescale=1./255,
                 shear_range=0.2,
                 zoom_range=0.2,
                 horizontal_flip=True)  ##here an object is created for the purpose of data augumentation. Here the features will be changed that will add variablity in the trainingset and it will help
                                        ##the model from getting overfitted.
                                        ##filters used are rescale, shear_range, zoom_range,horizontal_flip

training_set = train_datagen.flow_from_directory(
                'dataset/training_set', #dataset for training
                target_size=(64,64),    ##output size of the image, larger size would take more time for triaining the data
                batch_size=32,          ##number of pcitures to be fed in a go
                class_mode='binary')
##now preprocess test set
##we will rescale it to 1./255 as the training set but we will not do any data augumentation since these images are new and will act like images in production in real world enviornment

test_datagen = ImageDataGenerator(rescale=1./255)
test_set = test_datagen.flow_from_directory('dataset/test_set',
                                            target_size=(64,64),
                                            batch_size=32,
                                            class_mode='binary')

##initialzing the CNN

cnn = tf.keras.models.Sequential()

##Step 1 convolution layer

cnn.add(tf.keras.layers.Conv2D(filters=32, kernel_size=3,activation='relu', input_shape = [64,64,3]))  ##Conv2d belongs to the same class layers and it is
                                                        #similiar to dense class that helps in creating layers. Filters
                                                        # will be number of filters requried, kernalz_size it shape of the matrix, so 3/3,
                                                        #activation is relu, imput shape shape should same as target size in training set.
                                                        #(64,64,3). Note 3 in the end is there because 3 means colored image. Had it been black and
                                                        #white it would be 1.

# Max pooling layer
cnn.add(tf.keras.layers.MaxPool2D(pool_size=2, strides=2)) ##pool size it size of the matrix for pooling, so 2/2.
                                                           ## and strides is movement, so 2 steps. Padding means
                                                           ##if during strides, it is not 2/2 in size....

##Add second convolution and pooling layer
cnn.add(tf.keras.layers.Conv2D(filters=32, kernel_size=3,activation='relu')) ##only change is that input_shape is removed because now we are at second layer and input is not
                                                                          ##coming from raw data that we have to resize or rescale it.
cnn.add(tf.keras.layers.MaxPool2D(pool_size=2, strides=2))

##Flattening, converting the data into one dimentional vector
cnn.add(tf.keras.layers.Flatten())

##add fully connected layer
cnn.add(tf.keras.layers.Dense(units = 128, activation='relu')) ##all layers and neuron are connected. we have choosen 128 neurons in the hidden layer

##output layer
cnn.add(tf.keras.layers.Dense(units = 1, activation='sigmoid')) ##since output will be one, so one neuron

##we will now train the model
cnn.compile(optimizer='adam', loss = 'binary_crossentropy', metrics = ['accuracy'])

##Training the CNN on the training set and evaluating it on the Test set
cnn.fit(x= training_set, validation_data= test_set, epochs= 25) ##training set will be validated on test set

##making a single  prediction
import numpy as np
from tensorflow.keras.preprocessing import image
test_image = image.load_img('single_prediction/cat_or_dog_1.jpg', target_size= (64,64)) ##we have uploaded a dogs image

##now we have to change it to PIL since predict method expects array as inputs.
test_image = image.img_to_array(test_image)

##we also have to define batach number since during training the data we did provide batch number
##so even though there is only one image, we still have to provide batch dimen so that algo recognizes it

test_image = np.expand_dims(test_image, axis=0) ##axis=0 meaning first dimenion added batch

result = cnn.predict(test_image/255.0)  ##by 255 I normalized the test image

training_set.class_indices
if result[0][0] > 0.5:  ##since result is in batch, with first 0, we are accessing 1st batch and within 1st batch, 0, we are accessing the first element
    prediction = 'dog'
else:
    prediction ='cat'

print(prediction)

##prediction is dog and it is correct


"""
Python dictionaries are incredibly powerful. They can handle getting just about any kind of data. This file will
walk you through how flexible 1.dictionaries can be and what they "look like"
"""

"""
Section 1
Creating dictionaries is pretty easy and there are two main ways to do it, they work just about the same. If you
want to learn more about the differences checkout
`Link <https://medium.com/@jodylecompte/dict-vs-in-python-whats-the-big-deal-anyway-73e251df8398>`
"""
print('Section 1')
dict_1 = dict()  # Explicitly create an empty dictionary
dict_2 = {}  # Another way to create an empty dictionary

print('dict_1', dict_1)
print('dict_2', dict_2)

"""
Section 2
Adding to dictionaries is pretty straight forward. Dictionaries contain "key-value" pairs that are used to represent
all data. This is similar to how classes work in Python. The example below shows how dictionaries and classes can
work in similar ways
"""
print('\nSection 2')

class ExampleClass:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __str__(self):
        return 'a: ' + str(self.a) + ' b: ' + str(self.b)

class_example = ExampleClass(8, 9)
dict_1['a'] = 8
dict_1['b'] = 9

print('class_example', class_example)
print('dict_1', dict_1)

"""
Section 3
The big difference is that dictionaries are not limited in the values they can hold. We can keep adding values to
dictionaries as we want
"""
print('\nSection 3')

dict_1['some'] = 'more'
dict_1['examples'] = 'are here'

print('dict_1', dict_1)

"""
Sections 4
Dictionaries can also hold multiple time at once, lists, ints, strings can all be possible values
"""
print('\nSection 4')

dict_1[9] = 'hey'
dict_1['there'] = 11
print('dict_1', dict_1)

"""
Section 5
One of the most powerful features is that dictionaries can also store dictionaries in them! Having nested dictionaries
means that we can store more complicated structures. Below we will make a Person which has a name and an age.
"""
name = dict()
person = dict()

name['first'] = 'Jimmothy'
name['last'] = 'Bob'

person['name'] = name
person['age'] = 19
print('person', person)

"""
That covers the very basics of dictionaries, there are a lot of other powerful features so will be covered in part2,
but play around with this file to make sure everything makes sense. Try updating the person dictionary to have
an address key with a dictionary to store information on the address something like below
person {'name': {'first': 'Jimmothy', 'last': 'Bob'}, 'age': 19, 'address': {'street': 'first', 'number': 13}}
"""


from django.urls import path

from . import views

"""
DEFAULT URL
/api/stories/
"""

app_name = 'api_stories'

urlpatterns = [
    path('comment/', views.comment_story, name='comment_story'),
    path('add/', views.add_story, name='add_story'),
    path('<str:user_id>/all/', views.get_user_stories, name='get_user_stories'),
]


# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

# 用小顶堆存储 链表中的值，及第几个链表， 每次都从小顶堆中取值，然后再往小顶堆加值（取出的值属于哪个链表，就把这个链表的下个值再存入，直到本次链表遍历完成）
class Solution:
    def mergeKLists(self, lists):
        import heapq
        dumpy = ListNode(0)
        p = dumpy
        head = []
        for i in range(len(lists)):
            if lists[i]:
                heapq.heappush(head, (lists[i].val, i))
                lists[i] = lists[i].next
        print(heapq)

        while head:
            val, idx = heapq.heappop(head)
            p.next = ListNode(val)
            p = p.next
            if lists[idx]:
                heapq.heappush(head, (lists[idx].val, idx))
                lists[idx] = lists[idx].next
        return dumpy.next

困难/23.合并K个升序链表.py

23.合并K个升序链表.py


# High Level Analyzer
# For more information and documentation, please go to https://support.saleae.com/extensions/high-level-analyzer-extensions

from saleae.analyzers import HighLevelAnalyzer, AnalyzerFrame, StringSetting, NumberSetting, ChoicesSetting
from binascii import hexlify

# High level analyzers must subclass the HighLevelAnalyzer class.
class Hla(HighLevelAnalyzer):
    # List of settings that a user can set for this High Level Analyzer.
    #my_string_setting = StringSetting()
    #my_number_setting = NumberSetting(min_value=0, max_value=100)
    my_choices_setting = ChoicesSetting(choices=('Show empty frames', 'Do not show empty frames'))

    # An optional list of types this analyzer produces, providing a way to customize the way frames are displayed in Logic 2.
    result_types = {
        'LINAK_frame_transaction': {
            'format': '{{data.parsed_command}} (Command: {{data.cmd}}, data: {{data.bytes}})'
        },
        'LINAK_frame_empty': {
            'format': '(Command: {{data.cmd}})'
        }
    }

    def PID_to_cmd(pid_byte):
        commands = {
            0: ["Ref1 Position and status", 0],
            1: ["Ref2 Position and status", 0],
            2: ["Ref3 Position and status", 0],
            3: ["Ref4 Position and status", 0],
            4: ["Ref5 Position and status", 0],
            5: ["Ref6 Position and status", 0],
            6: ["Ref7 Position and status", 0],
            7: ["Ref8 Position and status", 0],
            8: ["Master reference output", 0],
            9: ["Undefined", 0],
            10: ["Ref1 Input", 0],
            11: ["Ref2 Input", 0],
            12: ["Ref3 Input", 0],
            13: ["Ref4 Input", 0],
            14: ["Set compare serial #", 0],
            15: ["Get compare result", 0],
            16: ["Define slave #", 0],
            17: ["Enter boot load mode", 0],
            18: ["Slave 1 reference response", 0],
            19: ["Slave 2 reference response", 0],
            20: ["Slave 3 reference response", 0],
            21: ["Master bed reference outputs", 0],
            22: ["Slave 1 bed reference outputs", 0],
            23: ["Slave 2 bed reference outputs", 0],
            24: ["Slave 3 bed reference outputs", 0],
            25: ["Undefined", 0],
            26: ["Undefined", 0],
            27: ["Master serial", 0],
            28: ["Diagnostic message", 0],
            29: ["Twindrive slave 1 max speeds, status and positions", 0],
            30: ["Twindrive reference info", 0],
            31: ["Twindrive slave 0 max speeds", 0],
            32: ["Twindrave slave serial", 0],
            33: ["Undefined", 0],
            34: ["Undefined", 0],
            35: ["(backwards compatibilty)", 0],
            36: ["Request power", 0],
            37: ["Handset 1 command", 0],
            38: ["Handset 2 command", 0],
            39: ["Handset 1 safety sequence", 0],
            40: ["Handset 2 safety sequence", 0],
            41: ["Config request", 0],
            42: ["Config response", 0],
            43: ["Config take control", 0],
            44: ["--Unspecced--", 0],
        }

        return commands.get(pid_byte, ["invalid_command", 0])

    def translate_pid_data(pid_byte, data_bytes):
        if pid_byte <= 7:
            if len(data_bytes) != 6:
                return "Invalid length"
            ref_num = int(pid_byte) + 1
            current_position = int(data_bytes[1]) * 256 + int(data_bytes[0])
            return "Ref{} position: {}mm".format(ref_num, current_position / 10)
        elif pid_byte >= 10 and pid_byte <= 13:
            if len(data_bytes) != 3:
                return "Invalid length"
            ref_num = int(pid_byte) - 9
            command = int(data_bytes[1]) * 256 + int(data_bytes[0])
            if command == 0x7FFF:
                return "Ref{} move down".format(ref_num)
            elif command == 0x8000:
                return "Ref{} move up".format(ref_num)
            elif command == 0x8001:
                return "Ref{} do not move".format(ref_num)
            else:
                return "Ref{} move to position: {}mm".format(ref_num, command / 10)
        elif pid_byte == 36:
            if len(data_bytes) != 2:
                return "Invalid length"
            return "Power requested on"
        elif pid_byte == 37 or pid_byte == 38:
            handset_num = int(pid_byte) - 36
            return "Handset {} action {} flags 0x{}".format(handset_num, int(data_bytes[0]), hex(data_bytes[1]))
        elif pid_byte == 39 or pid_byte == 40:
            handset_num = int(pid_byte) - 38
            # Todo: say something if sequence is not expected?
            # 63 223 207 215 195 221 204 85 128
            return "Handset {} sequence {}".format(handset_num, int(data_bytes[0]))

        return ""

    def reset_state(self):
        # Static tracking variables
        self.current_starting_time = None
        self.last_end_time = None
        self.has_data = False
        self.has_checksum = False
        self.PID = None
        self.data = bytearray()

    def __init__(self):
        '''
        Initialize HLA.

        Settings can be accessed using the same name used above.
        '''
        self.reset_state()

        #print("Settings:", self.my_string_setting,
        #      self.my_number_setting, self.my_choices_setting)

    def decode(self, frame: AnalyzerFrame):
        '''
        Process a frame from the input analyzer, and optionally return a single `AnalyzerFrame` or a list of `AnalyzerFrame`s.

        The type and data values in `frame` will depend on the input analyzer.
        '''
        frames = []

        if frame.type == "header_break":
            if self.current_starting_time is not None and self.PID is not None:
                # Save last frame
                if len(self.data) > 0:
                    frames.append(AnalyzerFrame('LINAK_frame_transaction', self.current_starting_time, self.last_end_time,
                                    {
                                        'bytes': hexlify(self.data[:-1 if len(self.data) > 0 else 0]).decode('ascii'),
                                        'cmd': Hla.PID_to_cmd(self.PID)[0],
                                        'parsed_command': Hla.translate_pid_data(self.PID, self.data),
                                    }))
                else:
                    if self.my_choices_setting != "Do not show empty frames":
                        frames.append(AnalyzerFrame('LINAK_frame_empty', self.current_starting_time, self.last_end_time,
                                        {
                                            'cmd': Hla.PID_to_cmd(self.PID)[0],
                                        }))

            self.reset_state()
            self.current_starting_time = frame.start_time
        elif frame.type == "header_pid":
            self.PID = frame.data['protected_id']
        elif frame.type == "data" or frame.type == 'data_or_checksum':
            self.data += bytearray(frame.data['data'].to_bytes(1, 'big'))

        self.last_end_time = frame.end_time
        # Return the data frame itself
        return frames


from Pila import Pila
import numpy as np

class Manejador:
    __cantidad = None
    __cont = 0
    __pilas = None
    def __init__(self, cantidad):
        self.__cantidad = cantidad
        self.__cont = 0
        self.__pilas = np.empty(3, dtype=Pila)
    def __str__(self):
        texto = ''
        for i in range(len(self.__pilas)):
            texto += self.Grafico(self.__pilas[i], i)
            texto += '\n////////////////////////////////////////////////////'
        return texto
    def Escaneo(self):
        cont = self.__pilas[2].mostrar()
        self.__pilas[2] = self.reLoad(cont)
        return cont
    def Grafico(self, pila, posicion):
        text = '\n|'
        disco = '-----'
        torre = pila
        contenido = torre.mostrar()
        cont = 0
        if (len(contenido) > 0):
                for elemento in contenido:
                    text += '\n|'
                    text += '\n' + (disco * elemento)
        else:
                for i in range(self.__cantidad):
                    text += '\n|\n|'
        text += '\n|'
        self.__pilas[posicion] = self.reLoad(contenido)
        return text
    def reLoad(self, contenido):
        contenido.sort(reverse=True)
        pila = Pila(self.__cantidad)
        for cont in contenido:
            pila.insertar(cont)
        return pila
    def cargarPila(self, pila):
        if (self.__cont < self.__cantidad):
            self.__pilas[self.__cont] = pila
            self.__cont += 1
    def moverTope(self, inicio, final):
        tope = self.__pilas[inicio-1].suprimir()
        self.__pilas[final-1].insertar(tope)
    def getTope(self, pos):
        return self.__pilas[pos-1].getTope()
    def getDatoTope(self, pos):
        return self.__pilas[pos-1].getDatoTope()
    def getLen(self):
        return len(self.__pilas)


class BT:
    def __init__(self, value):
        self.val = value
        self.left = None
        self.right = None

def heightBST(root):
    if not root:
        return 0

    # get the hgiht of left and right sub tree
    leftTree_height = heightBST(root.left)
    rightTree_height = heightBST(root.right)

    # return height of tree
    # 1 : include the current node
    return 1 + max(leftTree_height , rightTree_height)

if __name__ == '__main__':
    root = BT(1)
    root.left = BT(2)
    root.right = BT(3)
    root.left.left = BT(4)
    root.left.right = BT(5)

    print(heightBST(root))


import logging
from flask_mail import Message

from aleph.core import get_config, mail

log = logging.getLogger(__name__)

def notify_role(role, subject, html):
    if role.email is None:
        log.error("Role does not have E-Mail: %r", role)
        return

    sender = '%s <%s>' % (get_config('APP_TITLE'),
                          get_config('MAIL_FROM'))
    subject = '[%s] %s' % (get_config('APP_TITLE'), subject)
    msg = Message(subject=subject,
                  sender=sender,
                  recipients=[role.email])
    msg.html = html
    mail.send(msg)


# Sofia Sackett
# Baconian Cipher

def main():
    alphabet = {'A':'aaaaa', 'B':'aaaab', 'C':'aaaba', 'D':'aaabb', 'E':'aabaa',
            'F':'aabab', 'G':'aabba', 'H':'aabbb', 'I':'abaaa', 'J':'abaab',
            'K':'ababa', 'L':'ababb', 'M':'abbaa', 'N':'abbab', 'O':'abbba',
            'P':'abbbb', 'Q':'baaaa', 'R':'baaab', 'S':'baaba', 'T':'baabb',
            'U':'babaa', 'V':'babab', 'W':'babba', 'X':'babbb', 'Y':'bbaaa', 'Z':'bbaab'}
    question = print("Enter 'e' to encipher or 'd' to decipher.")
    mode = input("Choose mode: ")

    if mode == 'e' or mode == 'E':
        text = input("Enter the text that you would like encrypted: ")
        text = text.upper()
        output = encipher(alphabet, text)
        print(output.lower())

    elif mode == 'd' or mode == 'D':
        text = input("Enter the text that you would like deciphered: ")
        text = text.lower()
        output = decipher(alphabet, text)
        print(output.lower())

    else:
        print("An error occured. Please enter 'e' to encipher or 'd' to decipher.")

def encipher(alphabet, plaintext):
    ciphertext = ""
    for letter in plaintext:
        if letter != " ":
            ciphertext += alphabet[letter]
        elif letter == " ":
            ciphertext += " "
        else:
            print("An error occured. Please only enter letters and spaces.")
    return ciphertext

def decipher(alphabet, ciphertext):
    plaintext = ""
    i = 0
    while True:
        if i < len(ciphertext)-4:
            section = ciphertext [i:i + 5]
            if section[0] != " ":
                plaintext += list(alphabet.keys())[list(alphabet.values()).index(section)]
                i += 5
            else:
                plaintext += " "
                i += 1
        else:
            break
    return plaintext

main()


from pathlib import Path
import numpy as np
from Bio.PDB import PDBParser
from rdkit import Chem
import torch
import matplotlib.pyplot as plt
import seaborn as sns

# Constants
ATOM_DICT = {"C": 0, "N": 1, "O": 2, "P": 3, "H": 4, "S": 5}  # Sample atom dictionary, can be expanded
RNA_RESIDUE_DICT = {"A": 0, "U": 1, "G": 2, "C": 3}  # RNA residues

def process_rna_and_ligand(pdbfile):
    pdb_struct = PDBParser(QUIET=True).get_structure('', pdbfile)

    # Process ligand (assuming HETATM denotes ligand atoms)
    lig_atoms = [atom for atom in pdb_struct.get_atoms() if atom.parent.id == "HETATM"]
    lig_coords = np.array([atom.coord for atom in lig_atoms])
    lig_one_hot = np.array([ATOM_DICT[atom.element] for atom in lig_atoms])

    # Process RNA pocket
    rna_residues = [res for res in pdb_struct[0].get_residues() if res.id[0] == " "]
    rna_coords = np.array([atom.coord for res in rna_residues for atom in res])
    rna_one_hot = np.array([ATOM_DICT[atom.element] for res in rna_residues for atom in res])

    return {
        'lig_coords': lig_coords,
        'lig_one_hot': lig_one_hot,
    }, {
        'rna_coords': rna_coords,
        'rna_one_hot': rna_one_hot,
    }
from rdkit.Chem import MolFromPDBBlock, MolToSmiles

def compute_smiles(pdbfile):
    """
    Compute the SMILES representation for the ligand in the given PDB file.
    """
    with open(pdbfile, 'r') as f:
        pdb_content = f.read()

    mol = MolFromPDBBlock(pdb_content)
    if mol:
        return MolToSmiles(mol)
    return None

def get_type_histograms(lig_one_hot, rna_one_hot):
    """
    Compute histograms for atom types in the ligand and residue types in the RNA.
    """
    atom_counts = {k: np.sum(lig_one_hot == v) for k, v in ATOM_DICT.items()}
    rna_residue_counts = {k: np.sum(rna_one_hot == v) for k, v in RNA_RESIDUE_DICT.items()}

    return atom_counts, rna_residue_counts

import os
from pathlib import Path
import argparse

def save_all(filename, pdb_ids, lig_coords, lig_one_hot, rna_coords, rna_one_hot):
    """
    Save the processed data to a numpy file.
    """
    np.savez(filename,
             names=pdb_ids,
             lig_coords=lig_coords,
             lig_one_hot=lig_one_hot,
             rna_coords=rna_coords,
             rna_one_hot=rna_one_hot
             )
    return True

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('basedir', type=Path, help="Base directory containing the PDB files.")
    parser.add_argument('--outdir', type=Path, default=None, help="Output directory for processed data.")
    args = parser.parse_args()

    # Define the directories
    data_dir = args.basedir

    # Create output directory if not specified
    if args.outdir is None:
        processed_dir = Path(data_dir, 'processed')
    else:
        processed_dir = args.outdir

    # Ensure the output directory exists
    processed_dir.mkdir(exist_ok=True, parents=True)

    lig_coords = []
    lig_one_hot = []
    rna_coords = []
    rna_one_hot = []
    pdb_ids = []

    # Iterate through all PDB files in the base directory
    for pdb_file in os.listdir(data_dir):
        if pdb_file.endswith(".pdb"):
            try:
                lig_data, rna_data = process_ligand_and_rna(os.path.join(data_dir, pdb_file))
                lig_coords.append(lig_data['lig_coords'])
                lig_one_hot.append(lig_data['lig_one_hot'])
                rna_coords.append(rna_data['rna_coords'])
                rna_one_hot.append(rna_data['rna_one_hot'])
                pdb_ids.append(pdb_file)
            except Exception as e:
                print(f"Failed processing {pdb_file} due to {str(e)}")

    # Convert lists to numpy arrays
    lig_coords = np.array(lig_coords)
    lig_one_hot = np.array(lig_one_hot)
    rna_coords = np.array(rna_coords)
    rna_one_hot = np.array(rna_one_hot)

    # Save the processed data
    save_all(processed_dir / 'processed_data.npz', pdb_ids, lig_coords, lig_one_hot, rna_coords, rna_one_hot)

    print("Processing completed!")
import warnings
from rdkit import Chem
from rdkit.Chem.rdForceFieldHelpers import UFFOptimizeMolecule, UFFHasAllMoleculeParams
import seaborn as sns
import matplotlib.pyplot as plt

def compute_smiles(positions, one_hot, ATOM_DICT):
    """
    Compute SMILES strings for ligands.
    """
    print("Computing SMILES ...")

    atom_types = [ATOM_DICT[idx] for idx in np.argmax(one_hot, axis=-1)]
    mol = Chem.MolFromXYZBlock(positions, atomTypes=atom_types)

    # Optimize molecule geometry
    try:
        UFFOptimizeMolecule(mol)
    except:
        print("UFF optimization failed. Skipping...")
        return None

    return Chem.MolToSmiles(mol)

def get_type_histograms(lig_one_hot, rna_one_hot, ATOM_DICT, nucleotide_dict):
    """
    Get histograms of ligand and RNA types.
    """
    atom_counts = {k: 0 for k in ATOM_DICT.keys()}
    for a in [ATOM_DICT[x] for x in lig_one_hot.argmax(1)]:
        atom_counts[a] += 1

    nuc_counts = {k: 0 for k in nucleotide_dict.keys()}
    for r in [nucleotide_dict[x] for x in rna_one_hot.argmax(1)]:
        nuc_counts[r] += 1

    return atom_counts, nuc_counts

def plot_histogram(data, title, save_path):
    """
    Plot and save a histogram.
    """
    sns.distplot(data)
    plt.title(title)
    plt.savefig(save_path)
    plt.clf()

# Compute statistics & additional information
if __name__ == "__main__":
    with np.load(processed_dir / 'processed_data.npz', allow_pickle=True) as data:
        lig_one_hot = data['lig_one_hot']
        rna_one_hot = data['rna_one_hot']

    # Compute SMILES for ligands
    lig_smiles = compute_smiles(lig_coords, lig_one_hot, ATOM_DICT)
    with open(processed_dir / 'ligand_smiles.txt', 'w') as f:
        for s in lig_smiles:
            f.write(s + "\n")

    # Histograms of ligand and RNA types
    atom_hist, nuc_hist = get_type_histograms(lig_one_hot, rna_one_hot, ATOM_DICT, nucleotide_dict)

    # Plot histograms
    plot_histogram(list(atom_hist.values()), "Ligand Atom Distribution", processed_dir / 'ligand_atom_distribution.png')
    plot_histogram(list(nuc_hist.values()), "RNA Nucleotide Distribution", processed_dir / 'rna_nucleotide_distribution.png')

    print("Summary statistics generated!")
import json

def save_processed_data(filename, ligand_data, rna_data):
    """
    Save the processed ligand and RNA data.
    """
    with open(filename, 'w') as f:
        json.dump({
            "ligand_data": ligand_data,
            "rna_data": rna_data
        }, f)

    print(f"Data saved to {filename}")

if __name__ == "__main__":
    # Assuming you've loaded and processed data into `ligand_data` and `rna_data` dictionaries
    save_processed_data(processed_dir / 'final_processed_data.json', ligand_data, rna_data)

    # Create summary string
    summary_string = '# SUMMARY\n\n'
    summary_string += 'Processed RNA-Ligand Data\n\n'
    summary_string += '# Ligand Data\n'
    for key, value in ligand_data.items():
        summary_string += f"{key}: {len(value)} entries\n"

    summary_string += '\n# RNA Data\n'
    for key, value in rna_data.items():
        summary_string += f"{key}: {len(value)} entries\n"

    # Save summary
    with open(processed_dir / 'summary.txt', 'w') as f:
        f.write(summary_string)

    # Print summary
    print(summary_string)


import cv2 as cv
import numpy as np
from funkcje import *

def generacja_sladu(img):
    cv.imshow('Zdjecie wejsciowe', img)
    # generacja pustego zdjecia o wymiarach zdjecia wejsciowego
    puste_zdjecie = np.zeros(img.shape[:2], dtype='uint8')
    kaskada = 'haar_face.xml'
    # kaskada = 'haarcascade_frontalface_alt.xml'
    # zmiana na odcienie szarosci do wykrycia twarzy przez kaskade
    gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
    haar_cascade = cv.CascadeClassifier(kaskada)
    wykryte_twarze = haar_cascade.detectMultiScale(gray, scaleFactor=1.05, minNeighbors=2)
    # wykryte_twarze = haar_cascade.detectMultiScale(gray, scaleFactor=1.05, minNeighbors=4)
    print("wykryto", len(wykryte_twarze), "twarz/twarze")
    # wykonanie extrakcji twarzy pod warunkiem wykrycia 1 twarzy
    if len(wykryte_twarze) == 2:
        # odjęcie falszywie wykrytej twarzy - najpierw utworzenie podział na pojedyncze wektory
        twarz_prostokat1 = np.delete(wykryte_twarze, 0, axis=0)
        twarz_prostokat2 = np.delete(wykryte_twarze, 1, axis=0)
        # wybor odrzuconego wykrycia
        wykryte_twarze = np.delete(wykryte_twarze, odrzucenie_wykrycia(twarz_prostokat1, twarz_prostokat2), axis=0)
        maska, zaznaczona_twarz = twarz_maska(img, wykryte_twarze)
        # usuniecie zimnego tla
        tlo = usuniecie_tla(img)
        po_maskowaniu = cv.bitwise_and(tlo, tlo, mask=maska)
        # zapis wyextractowanej twarzy
        # cv.imwrite('extracted_face.jpg', po_maskowaniu)
    elif len(wykryte_twarze) == 1:
        # wyznaczenie środka okręgu wykrytej twarzy
        maska, zaznaczona_twarz = twarz_maska(img, wykryte_twarze)
        # usuniecie zimnego tla
        tlo = usuniecie_tla(img)
        po_maskowaniu = cv.bitwise_and(tlo, tlo, mask=maska)
        cv.imwrite('extracted_face.jpg', po_maskowaniu)
    elif len(wykryte_twarze) == 0:
        raise ValueError('Nie wykryto twarzy, zmień zdjęcie!')
    else:
        # print('exception!!!!')
        raise ValueError('Wykryto więcej niż jedną twarz, zmień zdjęcie!')

    img = po_maskowaniu
    twoDimage = img.reshape((-1, 3))
    twoDimage = np.float32(twoDimage)
    # cv.imshow('twoDimage', twoDimage)
    kryteria = (cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_MAX_ITER, 10, 1.0)
    # liczba ekstraktowanych kolorow do segmentacji
    K = 4
    podejscia = 10
    segmentacja_maska = []

    ret, label, center = cv.kmeans(twoDimage, K, None, kryteria, podejscia, cv.KMEANS_PP_CENTERS)
    center = np.uint8(center)
    res = center[label.flatten()]
    image_segmentation = res.reshape(img.shape)

    # cv.imshow('Twarz po segmentacji', image_segmentation)
    n = 0
    for kolor in center:
        # print('kolor', kolor)
        segmentacja_maska.append(podzial_segmentacja(image_segmentation, kolor))

    for n in range(K):
        tekst = ('maska ') + str(n)
        # cv.imshow(tekst, segmentacja_maska[n])
        kernel_3 = np.ones((2, 2), 'uint8')
        closing_3 = cv.morphologyEx(segmentacja_maska[n], cv.MORPH_CLOSE, kernel_3)
        opening_3 = cv.morphologyEx(closing_3, cv.MORPH_OPEN, kernel_3)
        tekst_2 = tekst + 'po morfologi'
        # cv.imshow(tekst_2, opening_3)
    # wpisanie pustej maski do wyniku operacji szkieletonizacji
    result = cv.cvtColor(segmentacja_maska[0], cv.COLOR_BGR2GRAY)
    # cv.waitKey()
    # koza = [0, 2, 3]
    for n in range(1, K):
        # for n in koza:
        gray = cv.cvtColor(segmentacja_maska[n], cv.COLOR_BGR2GRAY)
        kernel_3 = np.ones((3, 3), 'uint8')
        closing_3 = cv.morphologyEx(gray, cv.MORPH_CLOSE, kernel_3)
        opening_3 = cv.morphologyEx(closing_3, cv.MORPH_OPEN, kernel_3)
        threshold, warstwa = cv.threshold(opening_3, 10, 255, cv.THRESH_BINARY)
        szkielet = cv.ximgproc.thinning(warstwa, thinningType=cv.ximgproc.THINNING_GUOHALL)
        result = cv.bitwise_or(result, szkielet)
    cv.imshow('Szkielet', result)
    cv.imwrite('test_systemu.jpg', result)
    cv.waitKey(0)
    return result


# -*- coding:utf-8 -*-
# pylint: disable=duplicate-code
'''

Some tool sets

'''
import time
import datetime
import shortuuid

def now():
    '''
    datetime
    '''
    return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))

def time_trans(utc_time: str):  # UTC时间转化本地时间
    if utc_time:
        utc_len = len(utc_time.split(':'))
        if utc_len == 2:
            UTC_FORMAT = "%Y-%m-%dT%H:%MZ"
        elif utc_len == 3:
            if len(utc_time.split('.')) == 2:
                UTC_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ"
            else:
                UTC_FORMAT = "%Y-%m-%dT%H:%M:%SZ"
        utcTime = datetime.datetime.strptime(utc_time, UTC_FORMAT)
        trans = utcTime + datetime.timedelta(hours=8)
        return str(trans)

def gen_shortuuid():
    uuid = shortuuid.ShortUUID().random(length=20)
    return uuid


#Brian Lee
#Version @8.20.21
#Working version @12.20.2021

#Load packages
import requests as req
import json
import numpy as np
import math
from hockey_rink import NHLRink
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
import pandas as pd
from PIL import Image
import matplotlib.lines as mlines
from matplotlib.patches import RegularPolygon
from PIL import Image
from matplotlib.colors import ListedColormap
from matplotlib.colors import LinearSegmentedColormap
import matplotlib.colors as mcolors

#########################################################
#Initialize dictionary, variables
games18 = 82 #82 games per season
id = 8471214 #Alex Ovechkin NHLID

leaguewide_stats = {}
leaguewide_stats['Shot'] = {}
leaguewide_stats['Shot']['x'] = []
leaguewide_stats['Shot']['y'] = []
leaguewide_stats['Shot']['time'] = []
leaguewide_stats['Goal'] = {}
leaguewide_stats['Goal']['x'] = []
leaguewide_stats['Goal']['y'] = []
leaguewide_stats['Goal']['time'] = []

player_stats = {}
player_stats['Shot'] = {}
player_stats['Shot']['x'] = []
player_stats['Shot']['y'] = []
player_stats['Shot']['time'] = []
player_stats['Goal'] = {}
player_stats['Goal']['x'] = []
player_stats['Goal']['y'] = []
player_stats['Goal']['time'] = []

#Master function of sorts that stores every play of every game for a player
# in a given year.
def store_year(year, until, searchid):
    end_year = int(year) + 1
    print("Appending data for year " + year + "-" + str(end_year)+ "...")

    for i in range(1, until):
        with open('./'+year+'Data'+'/'+
            year+'_g'+str(i)+'Capitals.json') as file:
            game = json.load(file)
            all_plays = game['liveData']['plays']['allPlays']
            fill_dict(all_plays, searchid)

#Fills the dictionary with all the right plays
def fill_dict(all_plays, searchid):
    for play in all_plays:
        if 'players' in play:
            j = 0

            #Differentiates if a the desired player is part of the play.
            player_list = play['players']
            for player in player_list:
                matchid = player_list[0]['player']['id']
                if searchid == matchid:
                    player_dict = player_stats
                    sort_event(play, player_dict)
                else:
                    player_dict = leaguewide_stats
                    sort_event(play, player_dict)
                j += 1

#Categorizes events based on type, i.e, shot, goal, etc.
def sort_event(play, dict):
    #Initialize for compactness purposes
    xs = dict['Shot']['x']
    ys = dict['Shot']['y']
    ts = dict['Shot']['time']
    xg = dict['Goal']['x']
    yg = dict['Goal']['y']
    tg = dict['Goal']['time']

    event = play["result"]['event'] #The name of type of event
    coordinates = play['coordinates'] #Necessary for special cases of
    #bad data where only one coordinate exists for the event

    if len(coordinates) == 2:
        if event == "Shot":
            xcoord = play['coordinates']['x']
            ycoord = play['coordinates']['y']
            time = play['about']['periodTime']
            xs.append(xcoord)
            ys.append(ycoord)
            ts.append(time)
        elif event == "Goal":
            xcoord = play['coordinates']['x']
            ycoord = play['coordinates']['y']
            time = play['about']['periodTime']
            xg.append(xcoord)
            yg.append(ycoord)
            tg.append(time)

#store_year('2010', 82, id)
#store_year('2011', 82, id)
#store_year('2012', 48, id)
#store_year('2013', 82, id)

store_year('2018', 82, id)
store_year('2019', 82, id)
store_year('2020', 56, id)

print("~~~~~~~~~~~~~~~~~~")

#################################################
#Initialize dataframes to use pandas data analysis
player_df = pd.DataFrame(player_stats)
league_df = pd.DataFrame(leaguewide_stats)

league_sog_x = league_df['Shot']['x'] + league_df['Goal']['x']
league_sog_y = league_df['Shot']['y'] + league_df['Goal']['y']
player_sog_x = player_df['Shot']['x'] + player_df['Goal']['x']
player_sog_y = player_df['Shot']['y'] + player_df['Goal']['y']

#Assumed that goals are added to where shots end. Create list to classify events.
def goalcheck(type_df):
    test = list()
    for i in range(len(type_df['Shot']['x'])):
        test.append(0)
    for i in range(len(type_df['Shot']['x']),
            len(type_df['Shot']['x'] + type_df['Goal']['x'])):
        test.append(1)
    return test
league_goalcheck = goalcheck(league_df)
player_goalcheck = goalcheck(player_df)
league_goalcheck = np.array(league_goalcheck)
player_goalcheck = np.array(player_goalcheck)

#Make new dataframes with a check if the shot is a goal or not
#League
league_sog_x = np.array(league_sog_x)
np.abs(league_sog_x, out=league_sog_x) #Normalize coordinates
league_sog_y = np.array(league_sog_y) #No normalization needed for y
league_g_x = np.abs(np.array(league_df['Goal']['x']))
league_g_y = np.array(league_df['Goal']['y'])

league_sog_df = pd.DataFrame()
league_sog_df['x'] = league_sog_x
league_sog_df['y'] = league_sog_y
league_sog_df['goalcheck'] = league_goalcheck

#Player
player_sog_x = np.array(player_sog_x)
np.abs(player_sog_x, out=player_sog_x)
player_sog_y = np.array(player_sog_y)
player_g_x = np.abs(np.array(player_df['Goal']['x']))
player_g_y = np.array(player_df['Goal']['y'])

player_sog_df = pd.DataFrame()
player_sog_df['x'] = player_sog_x
player_sog_df['y'] = player_sog_y
player_sog_df['goalcheck'] = player_goalcheck

#######################################################
#First figure, for preliminary visualization
fig, ax = plt.subplots(1, 2, figsize=(15, 8))
rink = NHLRink(rotation=90)
for i in range(2):
    rink.draw(ax=ax[i], display_range="ozone")

#Visualize raw shot-goal patterns
#rink.heatmap(league_sog_df.x, league_sog_df.y,
    #values=league_sog_df.goalcheck, cmap="magma", ax=ax[0], binsize=2)
#rink.heatmap(player_sog_df.x, player_sog_df.y,
    #values=player_sog_df.goalcheck, cmap="magma", ax=ax[1], binsize=2)

rink.contourf(league_sog_df.x, league_sog_df.y,
    values=league_sog_df.goalcheck, ax=ax[0], binsize=20, cmap="bwr", levels=100)
rink.contourf(player_sog_df.x, player_sog_df.y,
    values=player_sog_df.goalcheck, ax=ax[1], binsize=20, cmap="bwr", levels=100)

################################################
#Visualize relative efficiencies
bounds = [-100.0, 100.0, -100, 100]
grid = 30
cnt = 0
color_map = plt.cm.winter
positive_cm = ListedColormap([mcolors.ColorConverter().to_rgb('#e1e5e5'),
    mcolors.ColorConverter().to_rgb('#d63b36')])
negative_cm = ListedColormap([mcolors.ColorConverter().to_rgb('#e1e5e5'),
    mcolors.ColorConverter().to_rgb('#28aee4')])

width = 50
height= 50
scalex = width/100*1.25
scaley = height/100*1.8
scalehex = 4.4*scalex

###########################################################
league_sog_hex = plt.hexbin(league_sog_x, league_sog_y,
    gridsize=grid, extent=bounds, mincnt=cnt, alpha=0)
league_g_hex = plt.hexbin(league_g_x, league_g_y,
    gridsize=grid, extent=bounds, mincnt=cnt, alpha=0)

league_offsets = league_sog_hex.get_offsets()
league_sog_freq = league_sog_hex.get_array()
league_g_freq = league_g_hex.get_array()

fig2 = plt.figure(figsize=(8,8))
ax2 = fig2.add_subplot(111)
relrink = NHLRink()
rinkdraw = relrink.draw(display_range="ozone")

for i,j in enumerate(league_offsets):
    if league_sog_freq[i] < 25: continue
    league_sog_scale = league_sog_freq[i]/max(league_sog_freq)
    radius = scalehex * math.sqrt(league_sog_scale)

    hex = RegularPolygon((28+j[0]*scalex, (height/2)-j[1]*scaley-25), numVertices=6,
        radius=radius, orientation=np.radians(0), alpha=0.5)
    rinkdraw.add_patch(hex)

#########################################################
fig3 = plt.figure(figsize=(8,8))
ax3 = fig3.add_subplot(111)
rinkdraw2 = relrink.draw(display_range="ozone")

player_sog_hex = plt.hexbin(player_sog_x, player_sog_y,
    gridsize=grid, extent=bounds, mincnt=cnt, alpha=0)
player_g_hex = plt.hexbin(player_g_x, player_g_y,
    gridsize=grid, extent=bounds, mincnt=cnt, alpha=0)

player_offsets = player_sog_hex.get_offsets()
player_sog_freq = player_sog_hex.get_array()

player_g_offsets = player_g_hex.get_offsets()
player_g_freq = player_g_hex.get_array()

#Visualize where player takes shots
for i,j in enumerate(player_offsets):
    if player_sog_freq[i] < 20: continue
    player_sog_scale = player_sog_freq[i]/max(player_sog_freq)
    radius = scalehex * math.sqrt(player_sog_scale)

    hex = RegularPolygon((28+j[0]*scalex, (height/2)-j[1]*scaley-25), numVertices=6,
        radius=radius, orientation=np.radians(0), alpha=0.5)
    rinkdraw2.add_patch(hex)

#Visualize where player scores
for i, j in enumerate(player_g_offsets):
    if player_g_freq[i] < 5: continue
    player_g_scale = player_g_freq[i]/max(player_g_freq)
    radius2 = scalehex * math.sqrt(player_g_scale)

    hex2 = RegularPolygon((28+j[0]*scalex, (height/2)-j[1]*scaley-25), numVertices=6,
        radius=radius2, orientation=np.radians(0), alpha=1.0, facecolor="aquamarine")
    rinkdraw2.add_patch(hex2)
###############################################
league_eff = list()
player_eff = list()
comp_eff = list()

for i in range(0, len(league_sog_freq)):
    if league_sog_freq[i] < 5 or player_sog_freq[i] < 5: continue
    league_eff_local = league_g_freq[i]/league_sog_freq[i]
    player_eff_local = player_g_freq[i]/player_sog_freq[i]

    league_eff.append(league_eff_local)
    player_eff.append(player_eff_local)
    comp_eff.append(player_eff_local-league_eff_local)

for i, j in enumerate(player_offsets):
    if player_sog_freq[i] < 5: continue

    player_sog_scale = player_sog_freq[i]/max(player_sog_freq)
    radius3 = scalehex * math.sqrt(player_sog_scale)

    league_eff_local = league_g_freq[i]/league_sog_freq[i]
    player_eff_local = player_g_freq[i]/player_sog_freq[i]

    comp_eff_local = player_eff_local-league_eff_local

    if comp_eff_local > 0:
        colour = positive_cm(math.pow(comp_eff_local, 0.2))
    else:
        colour = negative_cm(math.pow(-comp_eff_local, 0.5))

    hex3 = RegularPolygon((28+j[0]*scalex, (height/2)-j[1]*scaley-25), numVertices=6,
        radius=radius3, orientation=np.radians(0), alpha=1.0, facecolor=colour)

    rinkdraw2.add_patch(hex3)

###############################################
plt.show()


import pygame

class Timer:
    def __init__(self, clock: pygame.time.Clock, timeLimit: int, timerStarts=0, oneTime=False):
        assert isinstance(timeLimit, int), "The timeLimit value must be an integer! (Its in milliseconds not seconds)."
        assert isinstance(oneTime, bool), "The oneTime value should be a boolean (true/false)!"

        self.once = oneTime
        self.limit = timeLimit
        self.timer = 0
        self.timerStarts = timerStarts
        self.clock = clock
        self.run = True

    # must be called each frame to ensure a working timer
    def tick(self):
        if self.run:
            self.timer += self.clock.get_time()
            if self.timer > self.limit:
                self.timer = self.timerStarts
                if self.once:
                    self.run = False
                return True  # meaning that the timer has reached the time limit
            else:
                return False  # meaning that the timer hasn't reached the time limit

    def reset(self):
        self.timer = 0
        self.run = True
        self.clock.tick()


import torch
import numpy as np

# gradients accumulate + apex mixed precision training step

# no gradients accumulate training step
def train(train_dataloader, model, criterion, optimizer, epoch, local_rank, args):
    total_loss, total_accuracy = 0, 0
    model.train()
    starttime = time.time()
    for step, batch in enumerate(train_dataloader):
        batch = [r.cuda(local_rank, non_blocking = True) for r in batch]
        sent_id, mask, labels = batch
        predictions = model(sent_id, mask)
        loss = criterion(predictions, labels)
        accuarcy = torch.mean((torch.argmax(predictions, axis=1) == labels).float())
        if step%100==0:
            print(f"On rank {local_rank}, loss is {loss:6.5f}, acc is {accuarcy:6.5f}")
        model.zero_grad()
        torch.distributed.barrier()
        reduced_loss = reduce_mean(loss, args['nprocs'])
        reduced_accuracy = reduce_mean(accuarcy, args['nprocs'])
        total_loss = total_loss + reduced_loss.item()
        total_accuracy = total_accuracy + reduced_accuracy.item()
        # compute gradient and do SGD backpropagation
        loss.backward()
        torch.nn.utils.clip_grad_norm_(model.parameters(), args['max_grad_norm'])
        optimizer.step()

# gradients accumulate + apex mixed precision training step
def grad_accu_train(train_dataloader, model, criterion, optimizer, epoch, local_rank, args):
    model.train()
    total_loss, total_accuracy = 0, 0
    total_preds = []
    for step, batch in enumerate(train_dataloader):
        split_size = args['train_batch_size'] / args['gradient_accumulation_steps']
        split_accum = zip(*[torch.split(x, int(split_size)) for x in batch])
        for j, batch_split in enumerate(split_accum):
            batch_split = [r.to(device) for r in batch_split]
            sent_id, mask, labels = batch_split
            model.zero_grad()
            # get model predictions for the current batch_split
            predictions = model(sent_id, mask)
            # compute the loss between actual and predicted values
            loss = criterion(predictions, labels)
            # normalize the loss
            if args['gradient_accumulation_steps'] > 1:
                loss = loss / args['gradient_accumulation_steps']
            # add on to the total loss
            total_loss = total_loss + loss.item()
            # apex.amp mixed precision
            if args['fp16']:
                with amp.scale_loss(loss, optimizer) as scaled_loss:
                    scaled_loss.backward()
                torch.nn.utils.clip_grad_norm_(amp.master_params(optimizer), args['max_grad_norm'])
            else:
                # backward pass to calculate the gradients
                loss.backward()
                # clip the the gradients to 1.0. It helps in preventing the exploding gradient problem
                torch.nn.utils.clip_grad_norm_(model.parameters(), args['max_grad_norm'])
            # accumulative gradients
            if (j + 1) % args['gradient_accumulation_steps'] == 0:
                # update parameters
                optimizer.step()
                # reset gradients tensors
                model.zero_grad()
            preds = predictions.detach().cpu().numpy()
            total_preds.append(preds)


from django.contrib import admin

from .models import Redirect, Statistic, TotalStats

class RedirectAdmin(admin.ModelAdmin):
    list_display = (
        "source",
        "destination",
        "extra_info",
        "referer_constraint",
        "is_logged",
        "is_active",
        "status_code",
    )
    list_filter = ("extra_info",)
    list_display_links = list_display
    list_per_page = 400

class TotalizerAdmin(admin.ModelAdmin):
    list_display = (
        "redir",
        "accesses",
        "last_access",
    )
    list_display_links = list_display
    list_per_page = 400

class StatsAdmin(admin.ModelAdmin):
    list_display = ("redir", "referrer", "ip_address", "accessed", "user_agent")
    list_display_links = list_display
    list_per_page = 500

admin.site.register(Redirect, RedirectAdmin)
admin.site.register(TotalStats, TotalizerAdmin)
admin.site.register(Statistic, StatsAdmin)


# -*- coding: utf-8 -*-
from somali.database.base import Base, TimestampMixin, fields

class Wedding(Base, TimestampMixin):
    user_1 = fields.ForeignKeyField("models.Cookie", related_name="user_1")
    user_2 = fields.ForeignKeyField("models.Cookie", related_name="user_2")
    divorced = fields.BooleanField(default=False)

    class Meta:
        table = "wedding"

    async def divorce(self):
        self.divorced = True
        await self.save()

    async def spouse(self, name: str):
        await self.fetch_related("user_1", "user_2")
        return self.user_1 if self.user_2.name == name else self.user_2

    @classmethod
    async def find(cls, id_1: int, id_2: int = None):
        if not id_2:
            return (
                await cls.filter(user_1_id=id_1, divorced=False).first()
                or await cls.filter(user_2_id=id_1, divorced=False).first()
            )
        return (
            await cls.filter(user_1_id=id_1, user_2_id=id_2, divorced=False).first()
            or await cls.filter(user_1_id=id_2, user_2_id=id_1, divorced=False).first()
        )

    @classmethod
    async def find_all(cls, id: int):
        return (
            await cls.filter(user_1_id=id, divorced=False).all()
            + await cls.filter(user_2_id=id, divorced=False).all()
        )


from Prac_06.person import Person

MENU = """
A - Add person
L - List people
Q - Quit
"""

def main():
    print(MENU)
    person1 = Person("Brandon", "Paull", 19)
    person2 = Person("Thanos", "The Mad Titan", 2000)
    people = [person1, person2]

    choice = input(">>> ").upper()
    while choice != "Q":
        if choice == "A":
            first_name = input("First name: ")
            last_name = input("Last name: ")
            age = int(input("Age: "))
            people.append(Person(first_name, last_name, age))
        elif choice == "L":
            print(people)
        else:
            print("Invalid menu choice")
        print(MENU)
        choice = input(">>> ").upper()
    print("Byeeee")

if __name__ == '__main__':
    main()


from traceback import format_exc
from time import sleep, time
from mmap import mmap
from os.path import getmtime
from pyACC import *
from psutil import pid_exists
import os, re
from setting_define import *
car_angle = {'alpine_a110_gt4':720,
 'aston_martin_v8_vantage_gt4':640,
 'amr_v8_vantage_gt4':640,
 'audi_r8_lms_gt4':720,
 'audi_r8_gt4':720,
 'bmw_m4_gt4':500,
 'bmw_m4_gt3':500,
 'chevrolet_camaro_gt4.r':720,
 'chevrolet_camaro_gt4r':720,
 'ginetta_g55_gt4':720,
 'ktm_xbow_gt4':580,
 'ktm_x_bow_gt4':580,
 'maserati_granturismo_mc_gt4':900,
 'maserati_mc_gt4':900,
 'mclaren_570s_gt4':480,
 'mercedes_amg_gt4':500,
 'porsche_718_cayman_gt4':800,
 'porsche_718_cayman_gt4_mr':800,
 'amr_v12_vantage_gt3':640,
 'audi_r8_lms':720,
 'bentley_continental_gt3_2015':640,
 'bentley_continental_gt3_2016':640,
 'bentley_continental_gt3_2018':640,
 'bmw_m6_gt3':565,
 'emil_frey_jaguar_gt3':720,
 'jaguar_g3':720,
 'ferrari_488_gt3':480,
 'honda_nsx_gt3':620,
 'lamborghini_huracan_gt3':620,
 'lamborghini_huracan_st':620,
 'lexus_rc_f_gt3':640,
 'mclaren_650s_gt3':480,
 'mercedes_amg_gt3':640,
 'nissan_gt_r_gt3_2015':640,
 'nissan_gt_r_gt3_2018':640,
 'nissan_gt_r_gt3_2017':640,
 'porsche_991_gt3_r':800,
 'porsche_991ii_gt3_cup':800,
 'reiter_engineering_r_ex_gt3':720,
 'aston_martin_racing_v8_vantage_gt3':640,
 'amr_v8_vantage_gt3':640,
 'audi_r8_lms_evo':720,
 'bentley_continental_gt3':640,
 'bmw_m6_gt3':565,
 'ferrari_488_gt3':480,
 'ferrari_488_gt3_evo':480,
 'honda_nsx_gt3_evo':620,
 'lamborghini_huracan_gt3':620,
 'lamborghini_huracan_gt3_evo':620,
 'lamborghini_gallardo_rex':620,
 'lexus_rc_f_gt3':640,
 'mclaren_720s_gt3':480,
 'mercedes_amg_gt3':640,
 'mercedes_amg_gt3_evo':640,
 'nissan_gt_r_gt3':640,
 'porsche_991ii_gt3_r':800}

class pyDashACC:

    def __init__(self, acc_pid, dash, game_data, enable):
        self.acc_pid = acc_pid
        self.game_data = game_data[0]
        self.game_data_slow = game_data[1]
        self.enable = enable
        self.dash = dash
        self.status = False
        try:
            accMapHandle['physics'] = mmap(fileno=0, length=(sizeof(accPhysics)), tagname=(accMapTag['physics']))
            accMapHandle['graphics'] = mmap(fileno=0, length=(sizeof(accGraphics)), tagname=(accMapTag['graphics']))
            accMapHandle['static'] = mmap(fileno=0, length=(sizeof(accStatic)), tagname=(accMapTag['static']))
            if pid_exists(self.acc_pid):
                self.status = True
                self.game_data.t_game_id = game_id['acc']
        except Exception as e:
            print('Unable to open shared memory map', e)

    def isRun(self):
        return self.status

    def __del__(self):
        pass

    def update(self):
        if pid_exists(self.acc_pid) and self.enable:
            try:
                accMapHandle['physics'].seek(0)
                accMapHandle['graphics'].seek(0)
                accMapHandle['static'].seek(0)
                physics_smm = accPhysics.from_buffer_copy(accMapHandle['physics'])
                graphics_smm = accGraphics.from_buffer_copy(accMapHandle['graphics'])
                static_smm = accStatic.from_buffer_copy(accMapHandle['static'])
                status = graphics_smm.AC_STATUS
                if status == 2:
                    self.game_data.t_speed = int(physics_smm.speedKmh + 0.5)
                    self.game_data.t_rpm = physics_smm.rpm
                    self.game_data_slow.t_max_rpm = static_smm.maxRpm
                    self.dash.slip = (physics_smm.wheelSlip[0] + physics_smm.wheelSlip[1]) / 2
                    self.dash.rear_slip = (physics_smm.wheelSlip[2] + physics_smm.wheelSlip[3]) / 2
                    ave_load = (physics_smm.wheelLoad[0] + physics_smm.wheelLoad[1]) / 2
                    sub_load = physics_smm.wheelLoad[0] - physics_smm.wheelLoad[1]
                    try:
                        self.dash.load_diff = physics_smm.accG[0]
                    except Exception as e:
                        self.dash.load_diff = 0
                        print('e', e)

                    doc_path = os.path.expanduser('~\\Documents') + '\\Assetto Corsa Competizione\\Config\\controls.json'
                    if os.path.exists(doc_path):
                        with open(doc_path, 'r', encoding='UTF-8') as (f):
                            for line in f.readlines():
                                if 'steerLock' in line:
                                    self.dash.max_steering_angle = int(re.sub('\\D', '', line))
                                    break

                    else:
                        self.dash.max_steering_angle = 900
                    self.game_data.t_car_num = static_smm.numCars
                    performanceM = physics_smm.performanceMeter
                    if performanceM >= 32.768:
                        performanceM = 32.768
                    else:
                        if performanceM <= -32.768:
                            performanceM = -32.768
                        self.game_data.t_performance = int(performanceM * 1000 + 32768)
                        current_time = graphics_smm.currentTime
                        if ':' in current_time:
                            if '-' not in current_time:
                                t_hour, t_min, t_sec = current_time.split(':')
                                self.game_data.t_current_time_hour = int(t_hour)
                                self.game_data.t_current_time_min = int(t_min)
                                self.game_data.t_current_time_sec = int(t_sec)
                        self.game_data.t_current_time_hour = 0
                        self.game_data.t_current_time_min = 0
                        self.game_data.t_current_time_sec = 0
                    last_time = graphics_smm.lastTime
                    if ':' in last_time:
                        if '-' not in last_time:
                            t_hour, t_min, t_sec = last_time.split(':')
                            self.game_data.t_last_time_hour = int(t_hour)
                            self.game_data.t_last_time_min = int(t_min)
                            self.game_data.t_last_time_sec = int(t_sec)
                    self.game_data.t_last_time_hour = 0
                    self.game_data.t_last_time_min = 0
                    self.game_data.t_last_time_sec = 0
                else:
                    best_time = graphics_smm.bestTime
                    if ':' in best_time:
                        if '-' not in best_time:
                            t_hour, t_min, t_sec = best_time.split(':')
                            self.game_data.t_best_time_hour = int(t_hour)
                            self.game_data.t_best_time_min = int(t_min)
                            self.game_data.t_best_time_sec = int(t_sec)
                        else:
                            self.game_data.t_best_time_hour = 0
                            self.game_data.t_best_time_min = 0
                            self.game_data.t_best_time_sec = 0
                        self.game_data.t_yellow_flag = graphics_smm.GlobalYellow
                        self.game_data.t_red_flag = graphics_smm.GlobalRed
                        self.game_data.t_white_flag = graphics_smm.GlobalWhite
                        self.game_data.t_finish_lap = graphics_smm.completedLaps + 1
                        self.game_data.t_lap_number = graphics_smm.numberOfLaps
                        self.game_data.t_pos = graphics_smm.position
                        self.game_data.t_gas = int(physics_smm.gas)
                        self.game_data.t_brake = int(physics_smm.brake)
                        self.game_data.t_clutch = int(physics_smm.clutch)
                        gear = physics_smm.gear
                        if gear == 0:
                            self.game_data.t_gear = 30
                        else:
                            if gear == 1:
                                self.game_data.t_gear = 31
                            else:
                                self.game_data.t_gear = int(gear - 1)
                            self.game_data.t_fuel = int(physics_smm.fuel)
                            self.game_data.t_tc_running = int(physics_smm.tc)
                            self.game_data.t_abs_running = int(physics_smm.abs)
                            self.game_data.t_has_drs = int(physics_smm.drs)
                            self.game_data.t_fl_tire_wear = int(physics_smm.tyreWear[0]) - 70
                            self.game_data.t_fr_tire_wear = int(physics_smm.tyreWear[1]) - 70
                            self.game_data.t_rl_tire_wear = int(physics_smm.tyreWear[2]) - 70
                            self.game_data.t_rr_tire_wear = int(physics_smm.tyreWear[3]) - 70
                            self.game_data.t_fl_tire_temp = int(physics_smm.tyreTemp[0])
                            self.game_data.t_fr_tire_temp = int(physics_smm.tyreTemp[1])
                            self.game_data.t_rl_tire_temp = int(physics_smm.tyreTemp[2])
                            self.game_data.t_rr_tire_temp = int(physics_smm.tyreTemp[3])
                            self.game_data.t_fl_brake_temp = int(physics_smm.brakeTemp[0])
                            self.game_data.t_fr_brake_temp = int(physics_smm.brakeTemp[1])
                            self.game_data.t_rl_brake_temp = int(physics_smm.brakeTemp[2])
                            self.game_data.t_rr_brake_temp = int(physics_smm.brakeTemp[3])
                            self.game_data.t_pit_limiter = physics_smm.pitLimiterOn
                            try:
                                self.dash.syna_steering_lock = car_angle[static_smm.carModel]
                            except Exception as e:
                                self.dash.max_steering_angle = 900
                                print('acc ', e)

                    else:
                        self.game_data.t_speed = 0
                    self.game_data.t_rpm = 0
                self.status = True
                return self.game_data
            except Exception as e:
                print('updata error', e)
                self.status = False

        else:
            self.status = False