import numpy as np
import common
import os

##################################

# Constants
GyrToYr = 1e9
Zsun = 0.0127
XH = 0.72
PI = 3.141592654
MpcToKpc = 1e3
c_light = 299792458.0 #m/s

# Mass function initialization

mlow = 0
mupp = 30
dm = 0.5
mbins = np.arange(mlow,mupp,dm)
xlf   = mbins + dm/2.0

mlow2 = -2
mupp2 = 2
dm2 = 0.15
mbins2 = np.arange(mlow2,mupp2,dm2)
xlf2   = mbins2 + dm2/2.0

zlow = 0
zupp = 6
dz = 0.2
zbins = np.arange(zlow,zupp,dz)
xz   = zbins + dz/2.0

dzobs = 0.5
zbinsobs = np.arange(zlow,zupp,dzobs)
xzobs   = zbinsobs + dzobs/2.0

def plot_redshift(plt, outdir, obsdir):
    file = 'zDistribution-Deep-Optical-eagle-rr14-steep.data'
    data_eagle_rr14_steep = np.loadtxt(file)
    file = 'zDistribution-Deep-Optical-eagle-rr14.data'
    data_eagle_rr14 = np.loadtxt(file)
    file = 'zDistribution-Deep-Optical-eagle-const.data'
    data_eagle_const = np.loadtxt(file)
    file = 'zDistribution-Deep-Optical-CF00.data'
    data_cf00 = np.loadtxt(file)

    xtit="$\\rm redshift$"
    ytit="$\\rm N(S_{\\rm 850 \\mu m}>5 mJy)/dz/area [deg^{-2}]$"

    xmin, xmax, ymin, ymax = 0, 6, 0, 200
    xleg = xmin + 0.2 * (xmax-xmin)
    yleg = ymax - 0.1 * (ymax-ymin)

    fig = plt.figure(figsize=(5,4))
    ax = fig.add_subplot(111)
    common.prepare_ax(ax, xmin, xmax, ymin, ymax, xtit, ytit, locators=(1, 1, 20, 20))
    plt.subplots_adjust(left=0.2, bottom=0.15)
    #file = obsdir+'/lf/numbercounts/ncts870_Dudzeviciute19.data'
    #zd19,nd19,nd19errdn,nd19errup = np.loadtxt(file,usecols=[0,1,2,3],unpack=True)

    file = obsdir+'/lf/numbercounts/SMG_z_LESS_wardlow2011_table.data'
    sw11,sw11err,zw11 = np.loadtxt(file,usecols=[1,2,4],unpack=True)
    ind = np.where(sw11 >= 5)
    zdistw11 = np.zeros(shape = (2,len(zbinsobs)))

    H, bins_edges = np.histogram(zw11[ind],bins=np.append(zbinsobs,zupp))
    zdistw11[0,:] = zdistw11[0,:] + H
    zdistw11[1,:] = np.sqrt(zdistw11[0,:])
    areaobs = 0.5*0.5
    yobs = zdistw11[0,:]/areaobs/dzobs
    yup  = (zdistw11[0,:]+zdistw11[1,:])/areaobs/dzobs
    ydn  = (zdistw11[0,:]-zdistw11[1,:])/areaobs/dzobs
    ind = np.where(yobs > 0)
    ax.errorbar(xzobs[ind],yobs[ind],yerr=[yobs[ind]-ydn[ind],yup[ind]-yobs[ind]], ls='None', mfc='None', ecolor = 'grey', mec='grey',marker='D',label='Wardlow+11')
    #ax.errorbar(zd19,nd19,yerr=[nd19-nd19errdn,nd19errup-nd19], ls='None', mfc='None', ecolor = 'grey', mec='grey',marker='s',label='Dudzeviciute+19')

    ax.plot(data_eagle_rr14_steep[:,0],data_eagle_rr14_steep[:,1],'Indigo', linewidth=4, alpha=0.5)
    ax.plot(data_eagle_rr14[:,0],data_eagle_rr14[:,1],'Indigo', linewidth=4, linestyle='dotted')
    ax.plot(data_eagle_const[:,0],data_eagle_const[:,1],'Indigo', linestyle='dashed', linewidth=4, alpha=0.4)
    ax.plot(data_cf00[:,0],data_cf00[:,1],'Indigo', linestyle='dashdot', linewidth=4, alpha=0.3)

    common.prepare_legend(ax, ['grey','grey'], loc="upper left")

    common.savefig(outdir, fig, "zdistribution-850microns-5mJy.pdf")

def plot_numbercounts(plt, outdir, obsdir):

    file = 'NumberCounts-Deep-Optical-eagle-rr14-steep.data'
    datam = np.loadtxt(file)
    lm_eagle_rr14_steep = datam[:,0]
    num_eagle_rr14_steep = datam[:,1:10]

    file = 'NumberCounts-Deep-Optical-eagle-rr14.data'
    datam = np.loadtxt(file)
    lm_eagle_rr14 = datam[:,0]
    num_eagle_rr14 = datam[:,1:10]

    file = 'NumberCounts-Deep-Optical-eagle-const.data'
    datam = np.loadtxt(file)
    lm_eagle_const = datam[:,0]
    num_eagle_const = datam[:,1:10]

    file = 'NumberCounts-Deep-Optical-CF00.dat'
    datam = np.loadtxt(file)
    lm_cf00 = datam[:,0]
    num_cf00 = datam[:,1:10]

    xtit="$\\rm app\, mag (AB)$"
    ytit="$\\rm log_{10}(N/{\\rm 0.5 mag}^{-1}/A\, deg^2)$"

    xmin, xmax, ymin, ymax = 8, 30, -2 , 5.5
    xmin2, xmax2 = 8, 24
    xleg = xmin + 0.2 * (xmax-xmin)
    yleg = ymax - 0.1 * (ymax-ymin)

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

    subplots = (331, 332, 333, 334, 335, 336, 337, 338, 339)#, 5510, 5511, 5512, 5513, 5514, 5515, 5516, 5517, 5518, 5519, 5520, 5521, 5522, 5523, 5524, 5525)
    idx = (0, 1, 2, 3, 4, 5, 6, 7, 8)#, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24)

    labels= ('GALEX NUV', 'SDSS r', 'VISTA Y', 'IRAC 3.6', 'IRAC 8', 'P70', 'P100', 'S500', 'JCTM850')
    bands = (1, 4, 7, 12, 16, 19, 20, 25, 26)
    obs_start = (32, 272, 656, 1031, 1106, 1232, 1273, 1472)
    obs_end   = (98, 387, 756, 1061, 1129, 1273, 1336, 1496)

    file = obsdir+'/lf/numbercounts/Driver16_numbercounts.data'
    lm,p,dp = np.loadtxt(file,usecols=[2,3,4],unpack=True)
    yobs = np.log10(p)
    ydn  = np.log10(p-dp)
    yup  = np.log10(p+dp)

    for subplot, idx, b in zip(subplots, idx, bands):

        ax = fig.add_subplot(subplot)
        if (idx == 0 or idx == 3 or idx == 6):
            ytitplot = ytit
        else:
            ytitplot = ' '
        if (idx >= 6):
            xtitplot = xtit
        else:
            xtitplot = ' '
        if(idx <= 5):
            xminin, xmaxin= xmin, xmax
        else:
            xminin, xmaxin= xmin2, xmax2

        common.prepare_ax(ax, xminin, xmaxin, ymin, ymax, xtitplot, ytitplot, locators=(2, 2, 1, 1))
        ax.text(xleg,yleg, labels[idx])

        if(idx <= 7):
           ax.errorbar(lm[obs_start[idx]:obs_end[idx]], yobs[obs_start[idx]:obs_end[idx]], yerr=[yobs[obs_start[idx]:obs_end[idx]]-ydn[obs_start[idx]:obs_end[idx]],yup[obs_start[idx]:obs_end[idx]]-yobs[obs_start[idx]:obs_end[idx]]], ls='None', mfc='None', ecolor = 'grey', mec='grey',marker='o')
        else:
            file = obsdir+'/lf/numbercounts/ncts850_Geach2017.data'
            lmg17,pg17,dpg17 = np.loadtxt(file,usecols=[0,1,4],unpack=True)
            bing17  = 1.0 #mJy
            xobsg17 = -2.5 * np.log10(lmg17*1e-3) + 8.9 #in AB mag
            yobsg17 = np.zeros(shape = (3,len(xobsg17)))
            for o in range(0,len(xobsg17)):
                dmo = abs(-2.5 * np.log10((lmg17[o]-bing17/2.0)*1e-3) + 2.5 * np.log10((lmg17[o]+bing17/2.0)*1e-3))
                yobsg17[0,o] = np.log10(pg17[o]*bing17 / dmo)
                yobsg17[1,o] = np.log10((pg17[o]-dpg17[o])*bing17 / dmo)
                yobsg17[2,o] = np.log10((pg17[o]+dpg17[o])*bing17 / dmo)
            ax.errorbar(xobsg17,yobsg17[0,:] + np.log10(0.5),yerr=[yobsg17[0,:]-yobsg17[1,:],yobsg17[2,:]-yobsg17[0,:]], ls='None', mfc='None', ecolor = 'grey', mec='grey',marker='*')

        #Predicted LF
        if(idx < 5):
           x = lm_eagle_rr14_steep[240:305]
           y = num_eagle_rr14_steep[240:305,idx]
           ind = np.where(y != 0)
           ax.plot(x[ind],y[ind],'Indigo', linewidth=1)

        x = lm_eagle_rr14_steep[0:60]
        y = num_eagle_rr14_steep[0:60,idx]
        ind = np.where(y != 0)
        ax.plot(x[ind],y[ind],'Indigo', linewidth=4, alpha=0.5)

        x = lm_eagle_rr14_steep[60:120]
        y = num_eagle_rr14_steep[60:120,idx]
        ind = np.where(y != 0)
        ax.plot(x[ind],y[ind],'blue', linewidth=2, linestyle='dotted', label='disks')
        x = lm_eagle_rr14_steep[120:180]
        y = num_eagle_rr14_steep[120:180,idx]
        ind = np.where(y != 0)
        ax.plot(x[ind],y[ind],'LightSalmon', linewidth=2, linestyle='dashdot', label='SBs diskins')
        x = lm_eagle_rr14_steep[180:240]
        y = num_eagle_rr14_steep[180:240,idx]
        ind = np.where(y != 0)
        ax.plot(x[ind],y[ind],'red', linewidth=2, linestyle='dashed', label='SBs mergers')

        x = lm_eagle_rr14
        y = num_eagle_rr14[:,idx]
        ind = np.where(y != 0)
        ax.plot(x[ind],y[ind],'Indigo', linewidth=4, linestyle='dotted')
        x = lm_eagle_const
        y = num_eagle_const[:,idx]
        ind = np.where(y != 0)
        ax.plot(x[ind],y[ind],'Indigo', linewidth=4, alpha=0.4, linestyle='dashed')
        x = lm_cf00
        y = num_cf00[:,idx]
        ind = np.where(y != 0)
        ax.plot(x[ind],y[ind],'Indigo', linewidth=4, alpha=0.3, linestyle='dashdot')

#        ind = np.where(LFs_dust2[z,4,band,:] < 0.)
#        y = LFs_dust2[z,4,band,ind]+volcorr-np.log10(dm)
#        ax.plot(xlf_obs[ind],y[0],'Indigo', linewidth=3, linestyle='dotted',label='$\\rm EAGLE-\\tau\, RR14$')
#        ind = np.where(LFs_dust3[z,4,band,:] < 0.)
#        y = LFs_dust3[z,4,band,ind]+volcorr-np.log10(dm)
#        ax.plot(xlf_obs[ind],y[0],'Indigo', linewidth=3, alpha=0.4, linestyle='dashed', label='$\\rm EAGLE-\\tau\,f_{\\rm dust}\, const$')
#        ind = np.where(LFs_dust4[z,4,band,:] < 0.)
#        y = LFs_dust4[z,4,band,ind]+volcorr-np.log10(dm)
#        ax.plot(xlf_obs[ind],y[0],'Indigo', linewidth=3, alpha=0.3, linestyle='dashdot', label='CF00')

        if (idx == 5):
            common.prepare_legend(ax, ['b','LightSalmon','red'], loc='lower right')
    common.savefig(outdir, fig, "number-counts-deep-lightcone-selected.pdf")

def main():

    outdir= '/group/pawsey0119/clagos/Stingray/output/medi-SURFS/Shark-TreeFixed-ReincPSO-kappa0p002/deep-optical/Plots/'
    #'/mnt/su3ctm/clagos/Stingray/output/medi-SURFS/Shark-Lagos18-final/deep-optical/'
    obsdir= '/home/clagos/shark/data/'

    outdir = os.path.join(outdir, 'allmodels')

    plt = common.load_matplotlib()

    plot_numbercounts(plt, outdir, obsdir)
    plot_redshift(plt, outdir, obsdir)

if __name__ == '__main__':
    main()


from .CoordinateConfig import CoordinateReconConfig
from Trainer.CoordinateContrastiveTrainer import CoordinateContrastiveTrainer
import math
import torch
import torchaudio

def noise_aug(args, waveform):
    torch.manual_seed(waveform.shape[1])
    noise = (torch.rand_like(waveform) - 0.5) * 2
    aug_wave = waveform + noise * torch.rand(1).item() * 0.4
    return aug_wave

def freq_aug(args, waveform):
    base_freq = args.sample_rate
    target_freq = 1
    while math.gcd(base_freq, target_freq) < 8:         # 公因数越大重采样越快
        target_freq = int(base_freq * (0.95 + 0.1 * torch.rand(1).item()))  # 95%-105%
    aug_wave = torchaudio.transforms.Resample(base_freq, target_freq).cuda()(waveform)
    return aug_wave

def mask_aug(args, waveform):
    waveform = torch.split(waveform, args.sample_rate * 5, dim=1)  # 5s a chunk
    waveform = [w for w in waveform if torch.rand(1).item() < 0.90]  # 10% mask
    waveform = torch.cat(waveform, dim=1)
    return waveform

def mix_aug(args, waveform):
    return noise_aug(args, mask_aug(args, waveform))

class CoordinateAugConfig(CoordinateReconConfig):
    Trainer = CoordinateContrastiveTrainer

    epoch = 5
    model_name = "CoordinateContrastiveModel"
    aug_func = [noise_aug, freq_aug, mask_aug]
    contrastive_weight = 500


import numpy as np
import sklearn as sk
from sklearn.neural_network import MLPClassifier
from sklearn.model_selection import train_test_split
from sklearn.model_selection import ShuffleSplit
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
import matplotlib.pyplot as plt
import cv2
import os
import tensorflow as tf
from tensorflow.keras import datasets, layers, models, losses
from tensorflow.keras.datasets import mnist
from keras.utils import np_utils
import matplotlib.pyplot as plt

#Reading in data
(x_train, y_train), (x_test, y_test) = mnist.load_data()

#Saving data
y_test1 = y_test

#Flattening each image
x_train = x_train.reshape(x_train.shape[0],x_train.shape[1]*x_train.shape[2])
x_test = x_test.reshape(x_test.shape[0],x_test.shape[1]*x_test.shape[2])

#Regularizing images
x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.

#Using one-hot encoding
y_train = np_utils.to_categorical(y_train,10)
y_test = np_utils.to_categorical(y_test,10)

#constructing the model
model = models.Sequential()
model.add(layers.Dense(100, input_dim=784,activation='relu'))
model.add(layers.Dense(50, activation='relu'))
model.add(layers.Dense(10, activation='softmax'))

#compiling the model
model.compile(optimizer='adam', loss=losses.CategoricalCrossentropy(), metrics=['accuracy'])

history = model.fit(x_train, y_train,
                epochs=100,
                shuffle=True,
                validation_data=(x_test, y_test))

model.summary()

first_layer_weights = model.layers[0].get_weights()[0]
np.savetxt('firstwts.csv', first_layer_weights, delimiter=',')

second_layer_weights = model.layers[1].get_weights()[0]
np.savetxt('secondwts.csv', second_layer_weights, delimiter=',')

third_layer_weights = model.layers[2].get_weights()[0]
np.savetxt('thirdwts.csv', third_layer_weights, delimiter=',')

yp_test = model.predict(x_test)
yp_test = np.argmax(yp_test, axis=1)
cm_test = confusion_matrix(y_test1, yp_test)
t3 = ConfusionMatrixDisplay(cm_test)
t3.plot()
plt.show()
plt.clf()

plt.plot(history.history['accuracy'], label='accuracy')
plt.plot(history.history['val_accuracy'], label='val_accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.ylim([0.75, 1])
plt.legend(loc='lower right')
plt.show()

plt.plot(history.history['val_loss'], label='val_loss')
plt.xlabel('Epoch')
plt.ylabel('Accuracy and loss')
plt.ylim([min(history.history['val_loss']), max(history.history['val_loss'])])
plt.legend(loc='lower right')
plt.show()


class Solution(object):
    def intToRoman(self, num):
        """
        :type num: int
        :rtype: str
        """

        nums = {
            "I":1,   "II":2,   "III":3,   "IV":4,   "V":5,   "IX":9,
            "X":10,  "XX":20,  "XXX":30,  "XL":40,  "L":50,  "XC":90,
            "C":100, "CC":200, "CCC":300, "CD":400, "D":500, "CM":900,
            "M":1000,"MM":2000,"MMM":3000
        }

        s = ""
        while num > 0:
            picked = None

            for letters, weight in nums.items():
                if weight <= num:
                    if picked is None:
                        picked = letters
                    elif weight > nums[picked]:
                        picked = letters

            num -= nums[picked]
            s += picked

        return s


class Node:
    def __init__(self, data=None, next=None):
        self.data = data
        self.next = next

class LinkedList:
    def __init__(self):
        self.head = None

    def add(self, data):
        newNode = Node(data)
        if (self.head):
            current = self.head
            while current.next:
                current = current.next
            current.next = newNode
        else:
            self.head = newNode

    def print(self):
        if self.head:
            curr = self.head
            print(curr.data)
            while curr.next:
                curr = curr.next
                print(curr.data)
        else:
            print("The linked list does not have a head yet")

    # returns number of nodes in a linked list
    def count(self):
        if self.head == None:
            raise TypeError("The linked list does not have a head yet")
        counter = 1
        curr = self.head
        while curr.next:
            counter += 1
            curr = curr.next
        return counter

    # returns a node at a specified index
    def access(self, index):
        if self.head == None:
            raise TypeError("The linked list does not have a head yet")

        if type(index) != int:
            raise TypeError("Expected an integer in second argument")

        if index < 0:
            raise TypeError("Index cannot be negative")

        lenOfLL = self.count()

        if index >= lenOfLL:
            raise TypeError("Index out of range")

        curr = self.head
        for i in range(index+1):
            if i == index:
                return curr
            else:
                curr = curr.next

    # replaces a node at a specified index with another node
    def replace(self, index, newNode):
        if not(isinstance(newNode, Node)):
            raise TypeError("Expected type Node in third argument")

        oldNode = self.access(index)
        if index == 0:
            oldNode.data = newNode.data
        else:
            prevNode = self.access(index-1)
            prevNode.next = newNode
            newNode.next = oldNode.next

    # insert a new node at a given index
    def insert(self, index, newNode):
        if not(isinstance(newNode, Node)):
            raise TypeError("Expected type Node in third argument")

        if type(index) != int:
            raise TypeError("Expected an integer in second argument")

        if index < 0:
            raise TypeError("Index cannot be negative")

        lenOfLL = self.count()

        if index > lenOfLL:
            raise TypeError("Index out of range")

        if index == 0:
            newNode.next = self.head
            self.head = newNode
        elif index == lenOfLL:
            lastNode = self.access(index-1)
            lastNode.next = newNode
        else:
            prevNode = self.access(index-1)
            currNode = self.access(index)
            prevNode.next = newNode
            newNode.next = currNode

    # deletes a node at a given index in a linked list
    def delete(self, index):
        if type(index) != int:
            raise TypeError("Expected an integer in second argument")

        if index < 0:
            raise TypeError("Index cannot be negative")

        lenOfLL = self.count()

        if index > lenOfLL:
            raise TypeError("Index out of range")

        if index == 0:
            self.head = self.head.next
        elif index == lenOfLL - 1:
            prevNode = self.access(index-1)
            prevNode.next = None
        else:
            prevNode = self.access(index-1)
            nextNode = self.access(index+1)
            prevNode.next = nextNode

    # returns a new sub linked list of a bigger linked list when given an index range
    def subLL(self, startIndex, endIndex):
        if type(startIndex) != int or type(endIndex) != int:
            raise TypeError("Expected an integer in second and third arguments")

        if startIndex >= endIndex:
            raise TypeError("Use a valid index range")

        if startIndex < 0:
            raise TypeError("Integer in second argument cannot be negative")

        lenOfLL = self.count()

        if endIndex >= lenOfLL:
            raise TypeError("Index is out of range")

        newLL = LinkedList()
        newLL.add(self.access(startIndex).data)

        for i in range(startIndex+1, endIndex+1):
            curr = self.access(i)
            newLL.add(curr.data)

        return newLL

# creates a linked list from a list and returns it
def createLL(normList):
    ll = LinkedList()
    if not(type(normList) == list):
        raise TypeError("Expected argument of type list")

    for i in range(len(normList)):
        ll.add(normList[i])

    return ll


#!/usr/bin/env python

import numpy as np

def get_max_amp(trace,tmark,pre=0.25,post=0.25):

    ttime = trace.stats.sac[tmark]
    delta = trace.stats.delta

    t1 = trace.stats.sac.b
    tloc = int((ttime - t1)/delta + 1)

    #tloc = int(ttime/delta + 1)

    b = int(tloc - pre/delta)
    e = int(tloc + post/delta)
    seg = trace.data[b:e]
    seg = np.abs(seg)
    ind = seg.argmax()

    mind = b + ind

    return mind

def sum_traces(stream):
    '''
    Sum all the traces in the stream, start time of each trace should
    be the same.
    '''
    tr_num = len(stream)

    delta = stream[0].stats.delta
    b = stream[0].stats.sac.b
    npts = stream[0].stats.npts
    tr_sum = np.zeros_like(stream[0].data)
    t = np.arange(npts)*delta + b

    for tr in stream:
        tr_sum += tr.data

    tr_sum = tr_sum/tr_num

    return tr_sum,t

if __name__ == '__main__':

    print("this should not be appear.")


class TreeNode(object):
	def __init__(self, x):
		self.val = x
		self.left = None
		self.right = None

t = TreeNode(1)

tl = TreeNode(2)
tr = TreeNode(2)

tll = None
tlr = TreeNode(3)
trl = None
trr = TreeNode(3)

t.left = tl
t.right = tr

t.left.left = tll
t.left.right = tlr

t.right.left = trl
t.right.right = trr

		 #    1
		 #  2   2
		 # n 3 n 3
def preorder(tree):

	if tree == None:
		return [None]

	if tree.left == None and tree.right == None:
		return [tree.val]

	vals = [tree.val]

	vals += preorder(tree.left)
	vals += preorder(tree.right)

	return vals

def postorder(tree):

	if tree == None:
		return [None]

	if tree.left == None and tree.right == None:
		return [tree.val]

	vals = [tree.val]

	vals += postorder(tree.right)
	vals += postorder(tree.left)

	return vals

# class Solution(object):
#     def isSymmetric(self, root):
#         if root == None or root.left == None and root.right == None:
#             return True
#         pre = preorder(root)
#         post = postorder(root)
#         print(pre)
#         print(post)
#         return pre == post

# r = Solution().isSymmetric(t)

post = postorder(t)
print(post)


#!/usr/bin/env python3

import requests, pprint, sys, getopt

# Test query for https://anilist.co/graphiql
# {
#   MediaListCollection(userName: "nathan", type: ANIME) {
#     lists {
#       entries {
#         id
#         status
#         score(format: POINT_10)
#         progress
#         notes
#         repeat
#         media {
#           chapters
#           volumes
#           idMal
#           episodes
#           title { romaji }
#         }
#       }
#       name
#       isCustomList
#       isSplitCompletedList
#       status
#     }
#   }
# }

# What kind of output do we want
outputFile = 'xml'
outputTxt = ''''''
silent = False
showProgress = False
name = 'anilist-export'
listName = ''
complete = True
# Define our query variables and values that will be used in the query request
variables = {
  'username': '',
  'type': 'ANIME'
}

url = 'https://graphql.anilist.co'

def main(argv):
#   print('''
#                   ┏━━━━━━━━━━━━━━━━━━┓
#                   ┃  AniList to MAL  ┃
#                   ┗━━━━━━━━━━━━━━━━━━┛

# An export tool for Anilist to import to MyAnimeList.
# Enter your username, and this will generate a MyAnimeList
# compatible XML file to import at https://myanimelist.net/import.php

# Made by Nathan Wentworth (https://nathanwentworth.co)

# Report any problems to me on twitter! https://twitter.com/nathanwentworth
# ''')

  global outputFile, silent, name, showProgress, listName, complete

  for index, arg in enumerate(argv):
    if arg == "-f" or arg == "--file":
      outputFile = argv[index + 1]
    elif arg == "-u":
      variables['username'] = argv[index + 1]
    elif arg == "-t":
      variables['type'] = argv[index + 1].upper()
    elif arg == "-s":
      silent = True
    elif arg == "-n":
      name = argv[index + 1]
    elif arg == "-p":
      showProgress = True
    elif arg == "-l":
      listName = argv[index + 1]

  if not silent:
    print('''
  ┏━━ AniList to MAL ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
  ┃ An export tool for Anilist to import to MyAnimeList.          ┃
  ┃ Enter your username, and this will generate an XML file       ┃
  ┃ to import here: https://myanimelist.net/import.php            ┃
  ┃ Made by Nathan Wentworth (https://nathanwentworth.co)         ┃
  ┃ Report any problems here: https://twitter.com/nathanwentworth ┃
  ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
''')

  if (listName != ''):
    complete = False

  if variables['username'] == '':
    getUserData()
  elif variables['type'] == '':
    getListType()
  else:
    getAnilistData()

def getUserData():
  variables['username'] = input("→ Anilist username: ")

  if variables['username'] == '':
    print('Please enter a valid username!')
    getUserData()
  elif variables['type'] == '':
    getListType()
  else:
    getAnilistData()

def getListType():
  variables['type'] = input("→ List type (ANIME or MANGA): ").upper()

  if variables['type'] != 'ANIME' and variables['type'] != 'MANGA':
    print('Please enter either ANIME or MANGA')
    getListType()
  else:
    getAnilistData()

def getAnilistData():
  # Make the HTTP Api request
  query = '''
  query ($username: String, $type: MediaType) {
    MediaListCollection(userName: $username, type: $type) {
      lists {
        name
        entries {
          id
          status
          score(format: POINT_10)
          progress
          notes
          repeat
          media {
            chapters
            volumes
            idMal
            episodes
            title { romaji }
          }
        }
        name
        isCustomList
        isSplitCompletedList
        status
      }
    }
  }
  '''

  response = requests.post(url, json={'query': query, 'variables': variables})
  jsonData = response.json()

  if ('errors' in jsonData):
    for error in jsonData['errors']:
      print(error['message'])
    print('Your username may be incorrect, or Anilist might be down.')
    return

  statusLists = jsonData['data']['MediaListCollection']['lists']
  if len(statusLists) < 1:
    print('No items found in this list!\nDid you enter the wrong username?')
    return;
  if silent == False:
    convertAnilistDataToTxt(statusLists)
  if outputFile == 'xml':
    convertAnilistDataToXML(statusLists)
  elif outputFile == 'txt':
    if silent == True:
      convertAnilistDataToTxt(statusLists)
    writeToFile(outputTxt)

def convertAnilistDataToTxt(data):
  listOrder = ['current', 'completed', 'paused', 'planning', 'dropped']

  global outputTxt
  if variables['type'] == 'ANIME':
    outputTxt = "# Anime List\n"
  else:
    outputTxt = "# Manga List\n"

  for listStatus in listOrder:
    if listStatus in data:
      outputTxt += '\n## ' + listStatus.capitalize() + '\n'
      data[listStatus].sort(key=lambda show: show['score'], reverse=True)
      for item in data[listStatus]:
        outputTxt += '- '

        progress = '{0: >3}'.format(str(item['progress'])) + '/'
        progress += '{0: <3}'.format(str(item['media']['episodes']) if item['media']['episodes'] is not None else '??')
        if showProgress and listStatus == 'current' or listStatus == 'paused' or listStatus == 'dropped':
          outputTxt += progress + ' '
        else:
          outputTxt += '        ' # 8 characters, same as progress block

        title = str(item['media']['title']['romaji'])
        outputTxt += title

        if item['score'] > 0:
          outputTxt += '\tScore: ' + str(item['score']) + '/10'
        outputTxt += '\n'

  if not silent:
    print(outputTxt)

def convertAnilistDataToXML(data):
  output = ''''''
  user_total_anime = 0
  user_total_watching = 0
  user_total_completed = 0
  user_total_onhold = 0
  user_total_dropped = 0
  user_total_plantowatch = 0

  for x in range(0, len(data)):
    if (data[x]['name'] == listName or complete):
      for item in data[x]['entries']:
        s = str(item['status'])
        # print(s)
        if s == "PLANNING":
          if variables['type'] == 'ANIME':
            s = "Plan to Watch"
          else:
            s = "Plan to Read"
          user_total_plantowatch += 1
        elif s == "DROPPED":
          s = "Dropped"
          user_total_dropped += 1
        elif s == "CURRENT":
          if variables['type'] == 'ANIME':
            s = "Watching"
          else:
            s = "Reading"
          user_total_watching += 1
        elif s == "PAUSED":
          s = "On-Hold"
          user_total_onhold += 1
        elif "completed" in s.lower():
          s = "Completed"
          user_total_completed += 1

        animeItem = ''
        animeItem += '        <anime>\n'
        animeItem += '          <series_animedb_id>' + str(item['media']['idMal']) + '</series_animedb_id>\n'
        animeItem += '          <series_episodes>' + str(item['media']['episodes']) + '</series_episodes>\n'
        animeItem += '          <my_watched_episodes>' + str(item['progress']) + '</my_watched_episodes>\n'
        animeItem += '          <my_score>' + str(item['score']) + '</my_score>\n'
        animeItem += '          <my_status>' + s + '</my_status>\n'
        animeItem += '          <my_times_watched>' + str(item['repeat']) + '</my_times_watched>\n'

        animeItem += '          <update_on_import>1</update_on_import>\n'
        animeItem += '        </anime>\n\n'

        output += animeItem
        user_total_anime += 1

  outputStart = '''<?xml version="1.0" encoding="UTF-8" ?>
    <!--
     Created by XML Export feature at MyAnimeList.net
     Programmed by Xinil
     Last updated 5/27/2008
    -->

    <myanimelist>

      <myinfo>
        <user_id>123456</user_id>
        <user_name>''' + variables['username'] + '''</user_name>
        <user_export_type>1</user_export_type>
        <user_total_anime>''' + str(user_total_anime) + '''</user_total_anime>
        <user_total_watching>''' + str(user_total_watching) + '''</user_total_watching>
        <user_total_completed>''' + str(user_total_completed) + '''</user_total_completed>
        <user_total_onhold>''' + str(user_total_onhold) + '''</user_total_onhold>
        <user_total_dropped>''' + str(user_total_dropped) + '''</user_total_dropped>
        <user_total_plantowatch>''' + str(user_total_plantowatch) + '''</user_total_plantowatch>
      </myinfo>

'''
  output = outputStart + output + '      </myanimelist>'

  writeToFile(output)

  if not silent:
    print('✔ Successfully exported!')
    print('\nGo to https://myanimelist.net/import.php and select "MyAnimeList Import" under import type.\n')

def writeToFile(output):
  f = open(name + variables['type'] + '.' + outputFile, 'w')
  f.write(output)
  f.close()

if __name__ == '__main__':
  main(sys.argv)


# Напишите программу, которая принимает на вход вещественное число и показывает сумму его цифр.
# Пример: - 6782 -> 23; - 0,56 -> 11

a = input("Введите число: ")

def func(arr):
    summ = 0
    for i in arr:
        if(i.isdigit()):  #пытается преобразует строку в число
            summ += int(i)
    return summ

print(func(a))


import random
from glob import glob
from datasets import load_dataset

random.seed(42)

dataset = {
    "MNBVC_news": "../data/pretrain_data/MNBVC_news/*.jsonl.zst",
    "MNBVC_qa": "../data/pretrain_data/MNBVC_qa/*.jsonl.zst",
    "MNBVC_wiki": "../data/pretrain_data/MNBVC_wiki/*.jsonl.zst",
}

paths = []
for _, pat in dataset.items():
    files = glob(pat)
    sample_num = min(len(files), 10)
    paths.extend(random.sample(files, sample_num))

dataset = load_dataset(
    "json",
    data_files=paths,
    split="train",
    streaming=True
)
dataset = dataset.shuffle(seed=42)

def transform(dataset):
    for line in dataset:
        if "title" in line and "content" in line:
            yield line["title"] + "\n" + line["content"]
        else:
            yield line["text"]

data_iter = transform(dataset)

import io
import sentencepiece as spm

# Loads model from URL as iterator and stores the model to BytesIO.
model = io.BytesIO()
spm.SentencePieceTrainer.train(
    sentence_iterator=data_iter,
    model_writer=model,
    shuffle_input_sentence=False,
    train_extremely_large_corpus=True,
    # hyperparameters of tokenizer
    max_sentence_length=16384,
    pad_id=3,
    model_type="BPE",
    vocab_size=10000,
    # split digits and fallback to byte same as Llama.
    # set split_by_unicode_script to True to avoid grouping punctuation and characters together.
    split_digits=True,
    split_by_unicode_script=True,
    byte_fallback=True,
    # reserve whitespace and \n and \t etc. for code generation
    allow_whitespace_only_pieces=True,
    remove_extra_whitespaces=False,
    # Llama use identity instead of nfkc
    normalization_rule_name="nfkc",
)

# Serialize the model as file.
with open("./test_tokenizer.model", "wb") as f:
    f.write(model.getvalue())

# Directly load the model from serialized model.
sp = spm.SentencePieceProcessor(model_proto=model.getvalue())
print(sp.decode(sp.encode("只因你太美🤗▃     \n  1")))


"""
Enter your Description of your Contract here
"""
display_name = 'Enter Contract Display Name Here'
api = '3.0.0'  # This is a V3 Smart Contract
version = '0.0.1'  # Use semantic versioning, this is explained in the overview document
summary = 'Enter one line summary of contract here'
tside = Tside.LIABILITY

parameters = [
    Parameter(
        name='denomination',
        shape=DenominationShape,
        level=Level.TEMPLATE,
        description='Default denomination.',
        display_name='Default denomination for the contract.',
    ),
    Parameter(
        name='overdraft_limit',
        shape=NumberShape(
            kind=NumberKind.MONEY,
            min_value=0,
            max_value=10000,
            step=0.01
        ),
        level=Level.TEMPLATE,
        description='Overdraft limit',
        display_name='Maximum overdraft permitted for this account',
    ),
    Parameter(
        name='overdraft_fee',
        shape=NumberShape(
            kind=NumberKind.MONEY,
            min_value=0,
            max_value=1,
            step=0.01
        ),
        level=Level.TEMPLATE,
        description='Overdraft fee',
        display_name='Fee charged on balances over overdraft limit',
    ),
]
internal_account = '1'

@requires(parameters=True)
def pre_posting_code(postings, effective_date):
    denomination = vault.get_parameter_timeseries(name='denomination').latest()
    if any(post.denomination != denomination for post in postings):
        raise Rejected(
            'Cannot make transactions in given denomination; '
            'transactions must be in {}'.format(denomination),
            reason_code=RejectedReason.WRONG_DENOMINATION,
        )

@requires(parameters=True, balances='latest')
def post_posting_code(postings, effective_date):
    denomination = vault.get_parameter_timeseries(name='denomination').latest()
    overdraft_limit = vault.get_parameter_timeseries(name='overdraft_limit').latest()
    balances = vault.get_balance_timeseries().latest()
    committed_balance = balances[(DEFAULT_ADDRESS, DEFAULT_ASSET, denomination, Phase.COMMITTED)].net
    # We ignore authorised (PENDING_OUT) transactions and only look at settled ones (COMMITTED)
    if committed_balance <= -overdraft_limit:
        # Charge the fee
        _charge_overdraft_fee(vault, effective_date + timedelta(minutes=1))

    committed_balance = balances[(DEFAULT_ADDRESS, DEFAULT_ASSET, denomination, Phase.COMMITTED)].net

def _charge_overdraft_fee(vault, effective_date):
    denomination = vault.get_parameter_timeseries(name='denomination').latest()
    overdraft_fee = vault.get_parameter_timeseries(name='overdraft_fee').latest()
    instructions = vault.make_internal_transfer_instructions(
        amount=overdraft_fee,
        denomination=denomination,
        from_account_id=vault.account_id,
        from_account_address=DEFAULT_ADDRESS,
        to_account_id=internal_account,
        to_account_address=DEFAULT_ADDRESS,
        asset=DEFAULT_ASSET,
        client_transaction_id='{}_OVERDRAFT_FEE'.format(
            vault.get_hook_execution_id()
        ),
        instruction_details={
            'description':
                'Overdraft fee charged'
        },
        pics=[]
    )
    vault.instruct_posting_batch(
        posting_instructions=instructions,
        effective_date=effective_date,
        client_batch_id='BATCH_{}_OVERDRAFT_FEE'.format(
            vault.get_hook_execution_id()
        )
    )


from dataset import AneurysmDataset
from torch.utils.data import DataLoader
import torch
import os
import pickle

def get_loaders(train_path, val_path, num_workers, batch_size, pin_memory):
    train_dataset = AneurysmDataset(train_path, crop=None)
    val_dataset = AneurysmDataset(val_path, crop=None)

    train_loader = DataLoader(train_dataset,
                              batch_size=batch_size,
                              num_workers=num_workers,
                              shuffle=True,
                              pin_memory=pin_memory)

    val_loader = DataLoader(val_dataset,
                            batch_size=batch_size,
                            num_workers=num_workers,
                            shuffle=False,
                            pin_memory=pin_memory)

    return train_loader, val_loader

def save_checkpoint(model, optimizer, path):
    torch.save(model.state_dict(), os.path.join(path, 'model_checkpoint.pth'))
    torch.save(optimizer.state_dict(), os.path.join(path, 'optimizer_checkpoint.pth'))

def load_checkpoint(model, optimizer, path):
    model_state_dict = torch.load(os.path.join(path, 'model_checkpoint.pth'))
    optim_state_dict = torch.load(os.path.join(path, 'optimizer_checkpoint.pth'))

    model.load_state_dict(model_state_dict)
    optimizer.load_state_dict(optim_state_dict)

def save_histories(hist_dict, path):
    with open(path, 'wb') as f:
        pickle.dump(hist_dict, f)

def load_histories(path):
    with open(path, 'rb') as f:
        hist_dict = pickle.load(f)

    return hist_dict


import pygame
import sys
import time
from .. import constants as C
from .. import setup
from ..components import button, info

class GameOver:
    def start(self, game_info):
        self.game_info = game_info
        self.finished = False
        self.next = "main_menu"
        self.background = setup.GRAPHICS["background"]

        # 用于阻止重复打开记录文件
        self.recorded = False

        # 游戏结束画面
        self.gameover_font = pygame.font.Font(C.FONT, 48)
        self.again_image = setup.GRAPHICS["again"]
        self.again_rect = self.again_image.get_rect()
        self.gameover_image = setup.GRAPHICS["gameover"]
        self.gameover_rect = self.gameover_image.get_rect()

        if not self.recorded:
            self.recorded = True
            # 读取历史最高得分
            with open(C.RECORD, "r") as f:
                self.record_score = int(f.read())

            # 如果玩家得分高于历史最高得分，则存档
            if self.game_info["score"] > self.record_score:
                with open(C.RECORD, "w") as f:
                    f.write(str(self.game_info["score"]))

            with open(C.HISTORY, "a") as f:
                f.write(
                    str(
                        time.asctime(time.localtime(time.time()))
                        + "    "
                        + str(self.game_info["score"])
                        + "\n"
                    )
                )

    def update(self, surface, mouse):
        if mouse[0]:
            # 如果用户点击 “重新开始”
            if self.again_rect.collidepoint(mouse[1]):
                # 调用main函数，重新开始游戏
                self.finished = True
            # 如果用户点击 “结束游戏”
            elif self.gameover_rect.collidepoint(mouse[1]):
                # 退出游戏
                pygame.quit()
                sys.exit()

        self.draw(surface)

    def draw(self, surface):
        surface.blit(self.background, (0, 0))
        # 绘制结束界面
        record_score_text = self.gameover_font.render(
            "Best : %d" % self.record_score, True, C.BLACK
        )
        surface.blit(record_score_text, (50, 50))

        gameover_text1 = self.gameover_font.render("Your Score", True, C.BLACK)
        gameover_text1_rect = gameover_text1.get_rect()
        gameover_text1_rect.left, gameover_text1_rect.top = (
            C.SCREEN_W - gameover_text1_rect.width
        ) // 2, C.SCREEN_H // 3
        surface.blit(gameover_text1, gameover_text1_rect)

        gameover_text2 = self.gameover_font.render(
            str(self.game_info["score"]), True, C.BLACK
        )
        gameover_text2_rect = gameover_text2.get_rect()
        gameover_text2_rect.left, gameover_text2_rect.top = (
            C.SCREEN_W - gameover_text2_rect.width
        ) // 2, gameover_text1_rect.bottom + 10
        surface.blit(gameover_text2, gameover_text2_rect)

        self.again_rect.left, self.again_rect.top = (
            C.SCREEN_W - self.again_rect.width
        ) // 2, gameover_text2_rect.bottom + 50
        surface.blit(self.again_image, self.again_rect)

        self.gameover_rect.left, self.gameover_rect.top = (
            C.SCREEN_W - self.again_rect.width
        ) // 2, self.again_rect.bottom + 10
        surface.blit(self.gameover_image, self.gameover_rect)


"""
Plot LFPs in the time domain.

"""
__date__ = "August 2021 - April 2023"

from matplotlib.colors import TABLEAU_COLORS
from matplotlib.patches import Rectangle
import matplotlib.pyplot as plt
import numpy as np
from scipy.signal import hilbert
from scipy.stats import zscore

import lpne

def plot_lfps(
    lfps,
    rois=None,
    t1=0.0,
    t2=None,
    fs=1000,
    y_space=4.0,
    alpha=0.85,
    lw=1.0,
    colors=None,
    highlight_bands=[],
    highlight_colors=None,
    highlight_threshold=2.0,
    highlight_alpha=0.4,
    window_duration=None,
    show_windows=True,
    fn="temp.pdf",
):
    """
    Plot the LFPs in the specified time range.

    Optionally highlight times and channels where there is high power in particular
    frequency bands.

    Parameters
    ----------
    lfps : dict
        Maps ROI names to LFPs.
    rois : None or list of str
        Which ROIs to plot. If `None`, all the ROIs are plotted.
    t1 : float
        Start time, in seconds.
    t2 : None or float, optional
        End time, in seconds. If `None`, this is taken to be the end
        of the LFP.
    fs : int
        Samplerate, in Hz.
    y_space : float, optional
        Vertical spacing between LFPs.
    alpha : float, optional
        Passed to `pyplot.plot`.
    lw : float, optional
        Passed to `pyplot.plot`.
    colors : None or list of str, optional
        Colors to plot
    highlight_bands : list of tuples, optional
        Determines which frequency bands to highlight. Each tuple should contain two
        floats, the lowcut and highcut bandpass filter parameters.
    highlight_colors : None or list of str, optional
        Colors of the frequency band highlights
    highlight_threshold : float, optional
        Highlight when the norm of the analytic bandpassed signal is above this many
        standard deviations from the mean.
    highlight_alpha : float, optional
        Transparency of the highlights
    window_duration : None or float
        Window duration, in seconds. If `None`, no window markers are plotted.
    show_windows : bool, optional
        Whether to plot vertical lines separating the windows
    fn : str
        Image filename
    """
    # Figure out ROIs.
    if rois is None:
        rois = sorted([i for i in lfps.keys() if i not in lpne.MATLAB_IGNORED_KEYS])
    assert len(rois) > 0
    if colors is None:
        colors = list(TABLEAU_COLORS)
    if highlight_colors is None:
        highlight_colors = list(TABLEAU_COLORS)
    # Figure out times.
    i1 = int(fs * t1)
    if t2 is None:
        i2 = len(lfps[list(lfps.keys())[0]])
    else:
        i2 = min(int(fs * t2), len(lfps[rois[0]]))
    t2 = i2 / fs
    t_vals = np.linspace(t1, t2, i2 - i1)
    # Plot.
    ax = plt.gca()
    nan_bar = None
    for i, roi in enumerate(rois):
        # Plot the single channel.
        trace = _zscore(lfps[roi][i1:i2])
        c = colors[i % len(colors)]
        plt.plot(t_vals, i * y_space + trace, lw=lw, alpha=alpha, c=c)

        # Plot the channel's outliers (NaNs) on top of that channel.
        if nan_bar is None:
            nan_bar = np.zeros(len(trace), dtype=int)
        nan_trace = np.isnan(trace)
        nan_bar += nan_trace
        idx = np.argwhere(nan_trace > 0).flatten()
        if len(idx) > 0:
            y_vals = [i * y_space] * len(idx)
            plt.scatter(t_vals[idx], y_vals, c="k", s=4.0)

        # Plot the frequency band highlights.
        for j, (f1, f2) in enumerate(highlight_bands):
            temp_lfp = lfps[roi][:]
            temp_lfp[np.isnan(temp_lfp)] = 0.0
            lfp_filt = lpne.filter_signal(lfps[roi][:], fs, lowcut=f1, highcut=f2)
            lfp_filt = zscore(np.abs(hilbert(lfp_filt)))
            lfp_filt = lfp_filt[i1:i2]
            idx = np.argwhere(lfp_filt >= highlight_threshold).flatten()
            onsets, offsets = _indices_to_onsets_offsets(idx)
            y1, y2 = (i - 0.5) * y_space, (i + 0.5) * y_space
            for onset, offset in zip(onsets, offsets):
                x1, x2 = t1 + onset / fs, t1 + offset / fs
                patch = Rectangle(
                    (x1, y1),
                    x2 - x1,
                    y2 - y1,
                    alpha=highlight_alpha,
                    fc=highlight_colors[j % len(highlight_colors)],
                )
                ax.add_patch(patch)

    # Plot the overall outliers.
    idx = np.argwhere(nan_bar > 0).flatten()
    if len(idx) > 0:
        if window_duration is None:
            # Plot as scatters if we don't have window information.
            plt.scatter(t_vals[idx], [-2 * y_space] * len(idx), c="k")
        else:
            # Otherwise mark out entire windows at a time.
            i = i1
            window_samp = int(fs * window_duration)
            temp_y = [-2 * y_space] * 2
            while i + window_samp <= i2:
                if nan_bar[i - i1 : i - i1 + window_samp].sum() > 0:
                    plt.plot(
                        [t_vals[i - i1], t_vals[i - i1 + window_samp]],
                        temp_y,
                        c="k",
                        solid_capstyle="butt",
                        lw=2,
                    )
                i += window_samp
    pretty_rois = [roi.replace("_", " ") for roi in rois]
    plt.yticks(
        y_space * np.arange(len(rois)),
        pretty_rois,
        size="xx-small",
        rotation=30,
    )
    ax = plt.gca()
    for dir in ["top", "left", "right"]:
        ax.spines[dir].set_visible(False)
    if show_windows and window_duration is not None:
        i1 = int(np.ceil(t1 / window_duration))
        i2 = 1 + int(np.floor(t2 / window_duration))
        window_ts = [window_duration * i for i in range(i1, i2)]
        for window_t in window_ts:
            plt.axvline(x=window_t, c="k", lw=1.0, ls="--")
    plt.xlabel("Time (s)")
    plt.savefig(fn)
    plt.close("all")

def _zscore(trace):
    """Z-score with NaN handling"""
    temp = np.copy(trace)
    nan_mask = np.argwhere(np.isnan(temp) > 0).flatten()
    temp[nan_mask] = 0.0
    temp = zscore(temp)
    temp[nan_mask] = np.nan
    return temp

def _indices_to_onsets_offsets(idx):
    if len(idx) == 0:
        return [], []
    arr = np.zeros(idx[-1] + 3, dtype=int)
    arr[idx + 1] = 1
    diff_arr = np.diff(arr)
    onsets = np.argwhere(diff_arr > 0).flatten()
    offsets = np.argwhere(diff_arr < 0).flatten()
    return onsets, offsets

if __name__ == "__main__":
    pass

###


from zooAnimales.animal import Animal

class Mamifero(Animal):
    listado = []
    caballos = 0
    leones = 0

    def __init__(self, n, e, hab, g, pel, pat):
        super().__init__(n, e, hab, g)
        self.pelaje = pel
        self.patas = pat
        Mamifero.listado.append(self)

    @classmethod
    def cantidadMamiferos(self):
        return len(Mamifero.listado)

    @classmethod
    def crearCaballo(
        self,
        n,
        e,
        g,
    ):
        nuevo = Mamifero(n, e, "pradera", g, True, 4)
        Mamifero.caballos += 1
        return nuevo

    @classmethod
    def crearLeon(
        self,
        n,
        e,
        g,
    ):
        nuevo = Mamifero(n, e, "selva", g, True, 4)
        Mamifero.leones += 1
        return nuevo

    def isPelaje(self):
        return self.pelaje

    def getPatas(self):
        return self.patas


from scipy.cluster.hierarchy import dendrogram, linkage, cophenet
from scipy.spatial.distance import pdist
import matplotlib.pyplot as plt
import sys
import random
import math
import numpy as np
from numpy import array
import scipy.spatial.distance as ssd

points_array = [[21.16935483870968, 22.721774193548384, 78.60887096774192, 40.685483870967744],
                [87.74285714285716, 17.323214285714293, 36.76964285714287, 16.144642857142863]]

matrix = []

def fill_cell(row, column, arr, matr):
    # row = 1
    # column = 0
    matr[row][column] = math.sqrt(
        (arr[0][column] - arr[0][row + 1]) ** 2 + (arr[1][column] - arr[1][row + 1]) ** 2
    )
    return matr[row][column]

def build_matrix(coord_array, mtx):
    mtx_depth = len(coord_array[0]) - 1
    for i in range(0, mtx_depth):
        mtx.append([0])
        for j in range(0, i):
            mtx[i].append(0)
    # print(mtx[1][0])
    row_length = 1
    for item in range(0, mtx_depth):
        for i in range(0, row_length):
            mtx[item][i] = fill_cell(item, i, coord_array, mtx)
        row_length += 1
    print(mtx)
    return mtx

"""

test_matrix = [[0, 12.3214, 64.2314],
               [12.3214, 0, 11.21],
               [64.2314, 11.21, 0]]
test_matrix_a = array(test_matrix)
dist_matrix = ssd.squareform(test_matrix_a)
print(dist_matrix)
"""

to_vector = [[3], [97, 96], [96, 98, 97], [96, 98, 97, 95], [98, 98, 97, 95, 98]]
one_list = []
for i in range(0, len(to_vector)):
    for j in range(0, len(to_vector[i])):
        one_list.append(to_vector[i][j])
a = np.array(one_list)
print(a)

Z = linkage(a, 'single')
plt.figure(figsize=(25, 10))
plt.title('Hierachical Clustering Dendrogram')
plt.xlabel('sample matrix')
plt.ylabel('distance')
dendrogram(Z,
           truncate_mode='lastp',
           p=12,
           show_leaf_counts=True,
           leaf_rotation=90.,
           leaf_font_size=8,
           show_contracted=True, )
plt.show()
#print(Z)

#build_matrix(points_array, matrix)


from django.db import IntegrityError

from invoker.core.phone.search import Search

class Controller:
    __MOBILE_NUMBER__ = None
    __ALLOW_PUBLIC__ = None

    def __init__(self, mobile_number, allow_public):
        self.__MOBILE_NUMBER__ = mobile_number
        self.__ALLOW_PUBLIC__ = allow_public

    def __check_record__(self):
        from invoker.models import SearchedPhoneNumberModel
        try:
            record = SearchedPhoneNumberModel.objects.filter(
                phone_number=self.__MOBILE_NUMBER__
            )
            if record:
                return True
            else:
                return False
        except SearchedPhoneNumberModel.DoesNotExist:
            return False

    def __add_phone_number__(self):
        from invoker.models import SearchedPhoneNumberModel

        try:
            SearchedPhoneNumberModel.objects.create(
                phone_number=self.__MOBILE_NUMBER__,
                is_public_allowed=self.__ALLOW_PUBLIC__,
            )
        except:
            print("Failed to add phone number in database.")

    def __start_search__(self):
        from invoker.models import SearchedPhoneNumberModel, NumberDetailModel, CnicNumbersModel, \
            NetworkInformationModel, \
            LocationGenderModel

        if self.__check_record__():
            print("Record already exists into database")
            return
        # Phone number added into database
        self.__add_phone_number__()

        search_object = Search(self.__MOBILE_NUMBER__)
        status_code, content = search_object.get_report()
        if not status_code:
            SearchedPhoneNumberModel.objects.filter(
                phone_number=self.__MOBILE_NUMBER__
            ).update(
                is_search_completed=True
            )
            print("Failed to scrap results from web")
            return
        try:
            ref_phone_record = SearchedPhoneNumberModel.objects.get(
                phone_number=self.__MOBILE_NUMBER__
            )
            pak_data = content["pak_data"]
            sim_info = content["sim_info"]
            cnic_info = content["cnic_info"]
            if "cnic" in pak_data:
                try:
                    ref_cnic_record = CnicNumbersModel.objects.create(
                        cnic_number=pak_data["cnic"]
                    )
                except IntegrityError:
                    ref_cnic_record = CnicNumbersModel.objects.get(
                        cnic_number=pak_data["cnic"]
                    )
                NumberDetailModel.objects.create(
                    phone_number=ref_phone_record,
                    cnic=ref_cnic_record,
                    date=pak_data["date"],
                    name=pak_data["name"],
                    address=pak_data["address"],
                    address1=pak_data["address1"],
                    address2=pak_data["address2"],
                    city=pak_data["city"],
                    other_phone=pak_data["other_phone"],
                    first_name=pak_data["first_name"],
                    last_name=pak_data["last_name"],

                )
                SearchedPhoneNumberModel.objects.filter(
                    phone_number=self.__MOBILE_NUMBER__
                ).update(
                    details_found=True
                )
                if cnic_info:
                    LocationGenderModel.objects.create(
                        cnic=ref_cnic_record,
                        tehsil=cnic_info["tehsil"],
                        division=cnic_info["division"],
                        province=cnic_info["province"],
                        gander=cnic_info["gander"],
                    )

            if sim_info:
                NetworkInformationModel.objects.create(
                    phone_number=ref_phone_record,
                    network=sim_info["network"],
                    city=sim_info["city"],
                    status=sim_info["status"],
                )
            SearchedPhoneNumberModel.objects.filter(
                phone_number=self.__MOBILE_NUMBER__
            ).update(
                is_search_completed=True,
            )

        except SearchedPhoneNumberModel.DoesNotExist:
            pass
        print("ALL GOOD!")

    def start(self):
        self.__start_search__()

def controller(mobile_number, allow_public):
    controller_object = Controller(mobile_number, allow_public)
    controller_object.start()


from requests_html import HTML
from requests_futures.sessions import FuturesSession

BASE = 'http://theremin.music.uiowa.edu/'

# Downloaded from `MISPiano.html`
with open('mispiano.html') as f:
    root = HTML(html=f.read())

mfs = [h for h in root.links if 'Piano.ff' in h]
nmfs = len(mfs)
print(f'total: {nmfs} files')

session = FuturesSession(max_workers=10)

ars = [session.request('get', BASE + h) for h in mfs]
for i, ar in enumerate(ars):
    r = ar.result()
    fname = r.url.split('/')[-1]

    if r.status_code != 200:
        print(f'Failed to download {fname}')
        continue

    with open(fname, 'wb') as f:
        f.write(r.content)

    print(f'[{i+1}/{nmfs}] {fname} done')


"""
Student: elon hadad
Assignment no. 1
Program: intersection.py
"""
from math import *
from random import *
import sys

def newton_raphson(f, epsilon=10 ** (-10), n=100, h=0.000001):
    """
    Newton Rapson's method for finding the 0 point of a function
    """
    deriv = lambda x: (f(x + h) - f(x)) / h
    x0 = uniform(0.1, 10)
    while abs(deriv(x0)) < epsilon:
        x0 = uniform(0.1, 10)
    x = x0
    y = f(x)
    count = 1

    while abs(y) > epsilon and count <= n:
        count += 1
        y = f(x)
        x = x - y/deriv(x)

    if count > n:
        return None
    return x

def func_diff(f, g):
    """
    The function receives two functions `g` and `f`.
    :return: Difference between The first function to the second function.
    """
    return lambda x: f(x) - g(x)

def main():
    try:
        lst = []
        file = open("input.txt", "r")
        for val in file.readlines():
            lst.append(val)
        file.close()

        my_range = lst[2].split()
        f = eval(f"lambda x: {lst[0]}")
        g = eval(f"lambda x: {lst[1]}")

        flag = True
        for i in range(50):
            try:
                for j in range(50):
                    root = newton_raphson(func_diff(f, g))
                    if float(my_range[0]) < root < float(my_range[1]):
                        print(f"intersection: ({root:.4f} ,{f(root):.4f})")
                        sys.exit()
                flag = False
            except ValueError:
                continue
        if flag:
            print("no intersection")
    except FileNotFoundError:
        print("File not found")

if __name__ == "__main__":
    main()


from math import log
from collections import Counter

class Ranker(object):

    def __init__(self):
        self.k1 = 1.2
        self.b = 0.75
        self.total_docs = 16195639
        self.avg_doc_len = 5600
        self.min_doc_size = 3000
        self.max_doc_size = 18000

        self.max_file_lines = 1 * (10 ** 4)
        self.reset()
        self.results = []
        self.doc_size = []

        self.limit = 10

    def reset(self):
        self.idf_scores = {}
        self.word_count = {}
        self.all_word_posting = {}
        self.final_score = {}
        self.doc_counter = Counter()

    def calculate_scores(self):
        self.idf_scores = {k: self.get_idf(v) for k, v in self.word_count.items()}
        [self.final_score.update(
            {d_id: self.get_score(w, d_id, ct) + self.final_score.get(d_id, 0)})
            for w, d in self.all_word_posting.items() for ct, d_id in d]
        self.results = sorted([(self.doc_counter[k], v, k) for k, v in self.final_score.items()],
                              reverse=True)[:self.limit]
        self.results = [x[2] for x in self.results]

    def get_score(self, word, doc_id, word_freq):
        d_size = max(self.min_doc_size, min(self.max_doc_size, self.doc_size[doc_id]))
        return self.idf_scores[word] * word_freq * (self.k1 + 1) / (word_freq + (
                self.k1 * (1 - self.b + (self.b * d_size / self.avg_doc_len))))

    def get_idf(self, val):
        return log(1 + ((self.total_docs - val + 0.5) / (val + 0.5)))


from collections import deque
import sys

sys.stdin = open("input.txt")
input = sys.stdin.readline # 리스트 만들때는 split() 처럼 strip()을 까먹지 않고 써줘야함

N = int(input())

#그래프 만들기 두개 다 기억해두기 // 언제든지 기억 나는걸로 바로 쓰기 위해
graph = [list(map(int, input().strip())) for _ in range(N)]
# graph = []
# for i in range(N):
#     graph.append(list(map(int, input().strip())))
visited = [[-1] * N for _ in range(N)]
visited[0][0] = 0

dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
que = deque([])
que.append((0, 0))
def bfs():
    while que:
        x, y = que.popleft()
        if x == N-1 and y == N-1:
            return visited[x][y]
        for k in range(4):
            nx = x + dx[k]
            ny = y + dy[k]
            if 0 <= nx < N and 0 <= ny < N and visited[nx][ny] == -1:
                if graph[nx][ny] == 1:
                    que.appendleft((nx, ny))
                    visited[nx][ny] = visited[x][y]
                else:
                    que.append((nx, ny))
                    visited[nx][ny] = visited[x][y] + 1
print(bfs())


"Run all tests"

__author__ = "Johan Hake (hake.dev@gmail.com)"
__date__ = "2012-08-15 -- 2012-08-15"
__copyright__ = "Copyright (C) 2012 " + __author__
__license__ = "GNU LGPL version 3.0"

from modelparameters.commands import get_status_output

import re, sys, os

failed = []

num_tests = 0
timing = 0.0

python3 = sys.version.startswith("3")

# Run tests
for dirpath, dirnames, filenames in os.walk("modelparameters"):
    if ".tox" in dirpath:
        continue

    if os.path.basename(dirpath) == "tests":

        print("")
        print(f"Running tests in: {dirpath}")
        print("----------------------------------------------------------------------")
        for test in filenames:
            if "test_" not in test:
                continue
            fail, output = get_status_output(f"python {os.path.join(dirpath, test)}")
            if python3:
                output = output.decode()
            if output == "":
                continue

            num_tests += int(re.findall("Ran (\d+) tests", output)[0])
            timing += float(re.findall("tests in ([\d\.]+)s", output)[0])
            if fail:
                failed.append(output)

print()
print("----------------------------------------------------------------------")
print("Ran %d tests in %.3fs" % (num_tests, timing))
if failed:
    for output in failed:
        print(output)

sys.exit(len(failed))


name1_list=[]
name2_list=[]
flames=['f','l','a','m','e','s']
relationship={'f':"Friend",'l':"Love",'a':"Admirer",'m':"Marry",'e':"Enemy",'s':"Sibling"}
def common_char(name1_list,name2_list):
    for i in name1_list:
        if i in name2_list:
            name1_list.remove(i)
            name2_list.remove(i)
            common_char(name1_list,name2_list)

def iterate(flames,length_concat):
    a=0
    while(len(flames) != 1):
        a+=(length_concat-(len(flames)))
        a=a%(len(flames))
        flames.pop(a)

def display(relationship,b,name1,name2):
    print("the relationship between",'"',name1,'"'," and ",'"',name2,'"'," is derived as ",'"',relationship[b],'"'," by the “FLAMES” game.")

A=input("enter the first name : ")
B=input("enter the second name : ")
name1=A.lower()
name2=B.lower()
for i in name1:
    name1_list.append(i)
for j in name2:
    name2_list.append(j)

common_char(name1_list,name2_list)
concat_list=name1_list+name2_list
x=''
for i in concat_list:
    x+=i
print("the resultant string is : ",x)
length_concat=len(concat_list)-1
print("the length of the concated string is : ",length_concat+1)
iterate(flames,length_concat)
b=flames[0]
display(relationship,b,name1,name2)


from lib389._constants import INSTALL_LATEST_CONFIG
from lib389.configurations import get_sample_entries

def initialise(inst, basedn, log, args):
    sample_entries = get_sample_entries(args.version)
    assert basedn is not None
    s_ent = sample_entries(inst, basedn)
    s_ent.apply()

def create_parser(subparsers):
    initialise_parser = subparsers.add_parser('initialise', aliases=['init'], help="Initialise a backend with domain information and sample entries")
    initialise_parser.set_defaults(func=initialise)
    initialise_parser.add_argument('--version', help="The version of entries to create.", default=INSTALL_LATEST_CONFIG)


#

import requests
#request lib to read the URI in Json
def SegersjoMotTumba():
    r = requests.get("http://api.sl.se/api2/realtimedeparturesV4.json?key="-youre-api-key-here-"&siteid=7263&timewindow=60")
    j = r.json()
    print(r.status_code) #mostly for debugging
    buses = j['ResponseData']['Buses']
    for bus in buses:
        if bus['JourneyDirection'] == 2:  #journey direction is either 1 or 2 depending on which way the buss travels.
            print(bus['Destination'] + " : " + bus['DisplayTime']) #print out the buss destination from the bus stop as defined in the siteid in he URI above


# coding: utf-8

__author__ = 'Frederick NEY'

import logging

def request(api, uri, method='GET'):
    """
    Execute the http request to the given api
    :param api: object describing web service
    :param uri: endpoint
    :param method: http method
    :return: requests.models.Response
    """

    def inject(func):
        """
        Call the referenced function
        :param func:
        :return:
        """
        def run(*args, **kwargs):
            """
            Run the referenced function
            :param args: function arguments to send through the api
            :param kwargs: function known arguments to send through the api
            :return:
            """
            import requests
            import logging
            params = kwargs.get('uri_parameters', None)
            kwargs = func(*args, **kwargs)
            kwargs.setdefault('method', method)
            kwargs.setdefault('url', "{}/{}".format(api.base_url, uri.format(*params) if params else uri))
            logging.debug(kwargs)
            rsp = requests.request(**kwargs)
            try:
                return rsp.status_code, rsp.json()
            except Exception as e:
                logging.warning(e)
                return rsp.status_code, None

        return run

    return inject


#!/bin/python3

import os

# Complete the countArray function below.
def countArray(n, k, x):
    # Return the number of ways to fill in the array.
    mod = 10 ** 9 + 7
    a = [0] * n
    b = [0] * n
    if x == 1:
        a[0] = 1
        b[0] = 0
    else:
        a[0] = 0
        b[0] = 1
    for i in range(1, n):
        a[i] = b[i - 1]
        b[i] = (a[i - 1] * (k - 1) + b[i - 1] * (k - 2)) % mod
    return a[-1]

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    nkx = input().split()

    n = int(nkx[0])

    k = int(nkx[1])

    x = int(nkx[2])

    answer = countArray(n, k, x)

    fptr.write(str(answer) + '\n')

    fptr.close()


#!/usr/bin/env python3

"""Determine cost of previously scheduled bigquery-etl queries."""

from argparse import ArgumentParser
from pathlib import Path

from google.cloud import bigquery

DEFAULT_PROJECTS = [
    "moz-fx-data-shared-prod",
    "moz-fx-data-experiments",
    "mozdata"
]

parser = ArgumentParser(description=__doc__)
parser.add_argument("--date", required=True)  # expect string with format yyyy-mm-dd
parser.add_argument("--project", default="moz-fx-data-shared-prod")
# projects queries were run from that access table
parser.add_argument("--source_projects", nargs="+", default=DEFAULT_PROJECTS)
parser.add_argument("--destination_dataset", default="monitoring_derived")
parser.add_argument(
    "--destination_table", default="bigquery_etl_scheduled_query_usage_v1"
)
parser.add_argument("--sql_dir", default="sql/")

def create_query(query_paths, date, project):
    datasets = ['"' + path.parent.parent.name + '"' for path in query_paths]
    tables = [path.parent.name + "*" for path in query_paths]

    return f"""
      WITH logs AS (
        SELECT
            DATE('{date}') AS submission_date,
            project_id,
            referenced_tables,
          FROM `region-us`.INFORMATION_SCHEMA.JOBS_BY_PROJECT
          WHERE
            statement_type = "SELECT" AND
            DATE(creation_time) = '{date}'
        )
        SELECT
          submission_date,
          logs.project_id,
          CONCAT(referenced_table.project_id, ".", referenced_table.dataset_id, ".", referenced_table.table_id) as table,
          COUNT(*) AS number_of_accesses
        FROM logs
        CROSS JOIN UNNEST(logs.referenced_tables) AS referenced_table
        WHERE
          referenced_table.dataset_id IN ({",".join(datasets)})
          AND REGEXP_CONTAINS(referenced_table.table_id, "({"|".join(tables)})")
        GROUP BY submission_date, project_id, table
    """

def main():
    args = parser.parse_args()

    sql_queries = list(Path(args.sql_dir).rglob("query.sql"))
    python_queries = list(Path(args.sql_dir).rglob("query.py"))
    multipart_queries = list(Path(args.sql_dir).rglob("part1.sql"))
    query_paths = sql_queries + python_queries + multipart_queries
    partition = args.date.replace("-", "")
    destination_table = f"{args.project}.{args.destination_dataset}.{args.destination_table}${partition}"

    # remove old partition in case of re-run
    client = bigquery.Client(args.project)
    client.delete_table(destination_table, not_found_ok=True)

    for project in args.source_projects:
        client = bigquery.Client(project)
        query = create_query(query_paths, args.date, project)
        job_config = bigquery.QueryJobConfig(
            destination=destination_table, write_disposition="WRITE_APPEND"
        )
        client.query(query, job_config=job_config).result()

if __name__ == "__main__":
    main()


# Soru 1 : Seçtiniz Bir Kelimeyi İstediğiniz Defa Ekrana Yazdırın.
from typing import List, Any

def yazdir(a,b):
    print( a * b)

yazdir('Merhaba\n',5)

# Soru 2 : Kendine Gönderilen Sınırsız Sayıdaki Parametreyi Listeye Çeviren Bir Fonksiyon Yazın.

def  listeyeCevir(*params):
    liste = []

    for i in params:
        liste.append(i)

    return liste

result = listeyeCevir(10,20,30,40,50,'Salam')
print(result)

# Soru 3 : Gönderilen 2 Sayı Arasındaki Tüm Asal Sayıları Bul

def AsalSayıBulma(a,b):
    for sayi in range(a,b+1):
        if  sayi > 1:
            for i in range(2,sayi):
                if (sayi % i == 0):
                    break
                    print('bitti')
            else:
                print(i)

sayi1 = int(input('1. Sayınız : '))
sayi2 = int(input('2. Sayınız : '))
AsalSayıBulma(sayi1,sayi2)

# Soru 4 : Kendisine Gönderilen Sayının Tam Bölenleri Ayırıp Bir Liste Yapacak Fonksiyon Yaz

def SayıBul(a):

    for i in range(2,a):
        if a % i  == 0:
            tamBolen.append(i)
    return tamBolen

tamBolen = []
deneme = int(input('Sayı : '))
SayıBul(deneme)
print(tamBolen)


# -*- coding: utf-8 -*-
"""
Created on Fri Jan 12 14:35:14 2018

@author: Administrator
"""

from turtle import *
from random import *

def ground():
    hideturtle()
    speed(100)
    for i in range(400):
        pensize(randint(35, 50))
        x = randint(-400, 350)
        y = randint(-280, -1)
        r = -y / 280
        g = -y / 280
        b = -y / 280
        pencolor(r, g, b)
        penup()
        goto(x, y)
        pendown()
        forward(randint(40, 100))

def snow():
    hideturtle()
    speed(0)
    pensize(2)
    for i in range(1000):
        r = random()
        g = random()
        b = random()
        pencolor(r, g, b)
        penup()
        setx(randint(-350, 350))
        sety(randint(-270, 270))
        pendown()
        dens = randint(8, 12)
        snowsize = randint(5, 24)
        for j in range(dens):
            forward(snowsize)
            backward(snowsize)
            right(360 / dens)

def draw():
    setup(800, 600, 0, 0)
    tracer(False)
    bgcolor("black")

    snow()
    ground()

if __name__ == "__main__":
    draw()
    mainloop()


import random
import json
import pika
from paho.mqtt import client as mqtt_client
from gpiozero import PWMLED
from time import sleep
from types import SimpleNamespace

class Temp:
    def __init__(self, temp, hum, id):
        self.temp = temp
        self.hum = hum
        self.id = id

broker = 'mqtt.flespi.io'
port = 1883
weather = "easv/weather"
gas = "easv/gas"
light = "easv/light"

#led = PWMLED(25)

routing_key = "WeatherEvent"
exchange = "weather_exchange"
queue = "easv/WeatherEvent"

routing_key_gas = "GasEvent"
exchange_gas = "gas_exchange"
queue_gas = "easv/GasEvent"

# generate client ID with pub prefix randomly
client_id = f'python-mqtt-{random.randint(0, 100)}'
client_id_gas = f'python-mqtt-{random.randint(0, 100)}'
username = '30Zeg20AopbivFfYG0I7klFHoZDm8GS1uF3AvR1H60PruSf0IMVTVqq9fTlbn10F'
password = ''

params = pika.URLParameters('amqps://mhomznpp:jdDTdT3rqFFEsNtgL6XefLF8mlaTYIo8@goose.rmq2.cloudamqp.com/mhomznpp')
connection = pika.BlockingConnection(params)

channel = connection.channel()  # start a channel
channel.exchange_declare(exchange)
channel.queue_bind(queue, exchange, routing_key)
channel.queue_declare(queue=queue)

channelgas = connection.channel()  # start a gas channel
channelgas.exchange_declare(exchange_gas)
channelgas.queue_declare(queue=queue_gas)
channelgas.queue_bind(queue_gas, exchange_gas, routing_key_gas)

def connect_mqtt() -> mqtt_client:
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            print("Connected to MQTT Broker!")
        else:
            print("Failed to connect, return code %d\n", rc)

    client = mqtt_client.Client(client_id)
    client.username_pw_set(username, password)
    client.on_connect = on_connect
    client.connect(broker, port)
    return client

def subscribe(client: mqtt_client):
    def on_message(client, userdata, msg):
        datajson = msg.payload.decode()
        print(datajson)
        if "temp" in datajson:
            channel.basic_publish(
                body=datajson,
                exchange=exchange,
                routing_key=routing_key
                )
        if "gasN" in datajson:
            channel.basic_publish(
                body=datajson,
                exchange=exchange_gas,
                routing_key=routing_key_gas
            )
        if "light_level" in datajson:
            x = json.loads(datajson, object_hook=lambda d: SimpleNamespace(**d))
            print(x.light_level)
            if x.light_level > 5:
                led.value = 0
            if x.light_level < 5:
                led.value = 1

    client.subscribe(weather)
    client.subscribe(light)
    client.subscribe(gas)
    client.on_message = on_message

def run():
    client = connect_mqtt()
    subscribe(client)
    client.loop_forever()

if __name__ == '__main__':
    run()


import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import LSTM, Dense, Activation
scaler_minmax = MinMaxScaler()
def load_data(file_name1):
    df1 = pd.read_csv(file_name1, sep=',',header=None)

    # data1 = scaler_minmax.fit_transform(df1[0])
    data1 = np.array(df1[0]).astype(int)
    data2 = np.array(df1[1]).astype(int)
    data1to1 = scaler_minmax.fit_transform(data1.reshape(-1,1))
    data2to1 = scaler_minmax.fit_transform(data2.reshape(-1,1))

    train_x = data1to1[: 990]
    test_x = data1to1[990:1190]
    train_y = data2to1[: 990]
    test_y = data2[990:1190]

    return train_x, train_y, test_x, test_y

def build_model():
    # input_dim是输入的train_x的最后一个维度，train_x的维度为(n_samples, time_steps, input_dim)
    model = Sequential()
    model.add(LSTM(input_shape=(None, 1) ,units=96, return_sequences=True))
    model.add(LSTM(96, return_sequences=False))
    print(model.layers)
    model.add(Dense(units=1))

    model.add(Activation('linear'))

    model.compile(loss='mse', optimizer='adam')

    return model

def train_model(train_x, train_y, test_x, test_y):
    model = build_model()

    try:
        model.fit(train_x, train_y, batch_size=32, epochs=100, validation_data=(test_x, test_y))
        # predict = model.predict(test_x)
        predict = scaler_minmax.inverse_transform(model.predict(test_x))
    except KeyboardInterrupt:
        print(predict)
        print(test_y)
    print("predict={},test_y={}".format(predict,test_y))

    # inverse_transform获得归一化前的原始数据
    plt.plot(test_y, label='true data')
    plt.plot(predict, 'r:', label='predict')
    plt.legend()
    plt.show()
    # print(test_y)

    return predict, test_y

if __name__ == '__main__':

    train_x, train_y, test_x, test_y = load_data("../../resources/train_data/test_train.csv")
    train_x = np.reshape(train_x, (990, 1, 1))
    test_x = np.reshape(test_x, (200, 1, 1))
    print("train_x.shape={},test_x.shape={}".format(train_x.shape, test_x.shape))
    predict_y, test_y = train_model(train_x, train_y, test_x, test_y)


import logging
from datetime import datetime
from datetime import timezone
from typing import Dict
from typing import List
from typing import Optional
from typing import Union

from sqlalchemy import JSON
from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import Numeric
from sqlalchemy import String
from sqlalchemy import and_
from sqlalchemy.orm.attributes import flag_modified

from src.code.const import SLACK_DATETIME_FMT
from src.code.db import db
from src.code.model.schemas import ChannelProperties
from src.code.model.schemas import channel_properties_schema

logger = logging.getLogger(__name__)

class ControlPanel(db.Model):
    __tablename__ = "control_panels"

    id = Column(Integer, primary_key=True)
    slack_channel_name = Column(String(80), nullable=False)
    slack_channel_id = Column(String(64), nullable=False)
    channel_properties = Column(JSON)
    label_questions = Column(String(1000))
    form_questions = Column(JSON)
    creation_ts = Column(Numeric(16, 6), nullable=False)
    deactivation_ts = Column(Numeric(16, 6))

    def get_channel_properties_by_channel_id(self, channel_id: str) -> ChannelProperties:
        channel = self._get_control_panel_by_channel_id_or_throw_exception(channel_id)
        return channel_properties_schema.load(data=channel.channel_properties)

    def get_channel_name(self, channel_id: str) -> str:
        control_panel = self._get_control_panel_by_channel_id_or_throw_exception(channel_id)
        return control_panel.slack_channel_name

    def get_channel_id_by_channel_name(self, channel_name: str) -> str:
        control_panel = (
            db.session.query(ControlPanel).filter(ControlPanel.slack_channel_name.like(f"%{channel_name}")).first()
        )
        if control_panel is None:
            raise ValueError(f"Channel for {channel_name} not found")
        return control_panel.slack_channel_id

    def _get_control_panel_by_channel_id_or_throw_exception(self, channel_id: Optional[str]) -> "ControlPanel":
        control_panel = db.session.query(ControlPanel).filter_by(slack_channel_id=channel_id).first()
        if control_panel is None:
            raise ValueError(f"Property for {channel_id} not found")
        return control_panel

    # api
    def get_all_active_control_panels(self) -> List["ControlPanel"]:
        return db.session.query(ControlPanel).filter(ControlPanel.deactivation_ts == None).all()  # noqa: E711

    def get_control_panel_by_channel_id(self, channel_id: Optional[str]) -> "ControlPanel":
        return db.session.query(ControlPanel).filter_by(slack_channel_id=channel_id).first()

    def activate_control_panel(self, control_panel: "ControlPanel") -> None:
        control_panel.deactivation_ts = None
        db.session.commit()

    def add_control_panel(self, channel_id: str, channel_name: str) -> None:
        db.session.add(
            ControlPanel(
                slack_channel_name=channel_name,
                slack_channel_id=channel_id,
                creation_ts=datetime.now(timezone.utc).timestamp(),
                channel_properties=channel_properties_schema.dump(channel_properties_schema.load({})),
            )
        )
        db.session.commit()

    def get_active_control_panel_details(self, channel_id: str) -> Optional["ControlPanel"]:
        channel = (
            db.session.query(ControlPanel)
            .filter(
                and_(ControlPanel.slack_channel_id == channel_id, ControlPanel.deactivation_ts == None)  # noqa: E711
            )
            .first()
        )
        if not channel:
            return None
        return channel

    def soft_delete_control_panel(self, control_panel: "ControlPanel") -> None:
        control_panel.deactivation_ts = datetime.now(timezone.utc).timestamp()
        db.session.commit()

    def update_channel_property(self, channel_id: str, property: str, feature_properties: Union[Dict, List]):
        cp = self._get_control_panel_by_channel_id_or_throw_exception(channel_id)
        cp.channel_properties = channel_properties_schema.dump(
            channel_properties_schema.load(data=cp.channel_properties)
        )
        cp.channel_properties[property] = feature_properties
        flag_modified(cp, "channel_properties")
        db.session.commit()

    def toggle_feature(self, channel_id: str, feature: str, toggle: bool) -> None:
        cp = self._get_control_panel_by_channel_id_or_throw_exception(channel_id)
        cp.channel_properties = channel_properties_schema.dump(
            channel_properties_schema.load(data=cp.channel_properties)
        )
        cp.channel_properties["features"][feature]["enabled"] = toggle
        flag_modified(cp, "channel_properties")
        db.session.commit()

    def modify_daily_report(self, schedules: List[str], time_zone: str, output_channel_name: str) -> None:
        channel_properties: ChannelProperties = channel_properties_schema.load(self.channel_properties)
        if channel_properties.features.daily_report.enabled:
            channel_properties.daily_report.output_channel_name = output_channel_name
            channel_properties.daily_report.time_zone = time_zone
            channel_properties.daily_report.schedules = [
                {"local_time": x, "last_report_datetime_utc": ""} for x in schedules
            ]
            self.channel_properties = channel_properties_schema.dump(channel_properties)
            flag_modified(self, "channel_properties")
            db.session.commit()

    def update_last_report_datetime_utc_field(self, index: int, channel_id: str, utc_now: datetime):
        control_panel: ControlPanel = self._get_control_panel_by_channel_id_or_throw_exception(channel_id)
        channel_properties: ChannelProperties = channel_properties_schema.load(control_panel.channel_properties)
        if channel_properties.features.daily_report.enabled and len(channel_properties.daily_report.schedules) > 0:
            channel_properties.daily_report.schedules[index].last_report_datetime_utc = utc_now.strftime(
                SLACK_DATETIME_FMT
            )
            control_panel.channel_properties = channel_properties_schema.dump(channel_properties)
            flag_modified(control_panel, "channel_properties")
            db.session.commit()
        else:
            raise ValueError(f"Last report data for {channel_id} not updated properly")


import torch
import torchaudio
import numpy as np

from dataset import AudioMNISTDataset
from model import AudioMNISTModel
from sklearn.metrics import classification_report

def predict(model, input, target):
    model.eval()
    with torch.no_grad():
        predictions = model(input)
        predicted = predictions[0].argmax(0)
        expected = target
    return predicted, expected

def accuracy(y_pred, y_true):
    correct = np.sum(np.array(y_pred) == np.array(y_true))
    acc = (correct / len(y_pred)) * 100
    return acc

if __name__ == "__main__":

    class_mapping = ["zero", "one", "two", "three",
                     "four", "five", "six", "seven", "eight", "nine"]
    SAMPLE_RATE = 48000
    NUM_SAMPLES = 48000
    device = "cpu"
    AUDIO_DIR_PATH = "/home/armak/Python_projects_WSL/Audio_MNIST_classification/data"

    # load back the model
    audio_classifier = AudioMNISTModel()
    state_dict = torch.load(
        "/home/armak/Python_projects_WSL/Audio_MNIST_classification/AudioMNISTModel.pth")
    audio_classifier.load_state_dict(state_dict)

    # load audio mnist dataset
    mel_spectrogram_transformation = torchaudio.transforms.MelSpectrogram(
        sample_rate=SAMPLE_RATE,
        n_fft=1024,
        hop_length=512,
        n_mels=64
    )

    audio_mnist_dataset_test = AudioMNISTDataset(AUDIO_DIR_PATH,
                                                 mel_spectrogram_transformation,
                                                 NUM_SAMPLES,
                                                 device,
                                                 train_set=False)

    # get a sample from the audio mnist dataset for inference
    y_pred = []
    y_true = []
    for i in range(len(audio_mnist_dataset_test)):
        predicted, expected = predict(audio_classifier,
                                      audio_mnist_dataset_test[i][0].unsqueeze_(
                                          0),
                                      audio_mnist_dataset_test[i][1])
        y_pred.append(predicted)
        y_true.append(expected)
        # print(f"Predicted: '{predicted}', expected: '{expected}'")

    # calculate accuracy
    acc = accuracy(y_pred, y_true)
    print(f"Accuracy: {acc:.2f} %")

    # print classification report
    print(classification_report(y_true, y_pred, target_names=class_mapping))


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov  2 15:31:43 2020

@author: afo
"""

import pandas as pd
import os
from os import listdir
from os.path import abspath, isfile, join
from inspect import getsourcefile
import numpy as np

p = abspath(getsourcefile(lambda:0))
p = p.rsplit('/', 1)[0]
os.chdir(p)
print('Working Directory is: %s' % os.getcwd())

# Function calculates mean ratios accross all companies of interest. This to be used as a soft benchmark
def get_means():

    # list of each file with financials
    files = [f for f in listdir(p + '/annual_financials_tech') if isfile(join(p + '/annual_financials_tech', f))]
    try :
        files.remove('.DS_Store')
    except ValueError:
        print()

    # lists for each of the ratios
    eps = []
    epsGr = []
    pe = []
    pb = []
    ps = []
    divPyr = []
    divYield = []
    roe = []
    roa = []
    opIncR = []
    opIncGr = []
    netPrMar = []
    cashR = []
    currentR = []
    de = []
    da = []
    intCov = []
    asTurn = []
    payTurn = []
    asGr = []
    fcfGr = []
    peg = []

    i = 0

    # Main loop for going through each file and exctracting ratios
    for i in range(0, len(files)):

        xls = pd.ExcelFile( p + '/annual_financials_tech/' + files[i])
        #xls = pd.ExcelFile( p + '/annual_financials_tech/MSFT.xlsx')

        balance_sheet = pd.read_excel(xls, 'BS', index_col=0)
        income_statement = pd.read_excel(xls, 'IS', index_col=0)
        cash_flow = pd.read_excel(xls, 'CF', index_col=0)
        key_metrics = pd.read_excel(xls, 'Key Metrics', index_col=0)
        financial_ratios = pd.read_excel(xls, 'Ratios', index_col=0)
        growth_ratios = pd.read_excel(xls, 'Growth', index_col=0)
        dcf = pd.read_excel(xls, 'DCF', index_col=0)

        # If it is the very first file, than it creates the list, otherwise appends
        if i == 0:

            # Each part is wrapped in its own try/catch block based on the table, where this ratio is found
            # KeyError means there is no such element, then it just skipped
            try:
                eps = [income_statement.loc['eps'].to_list()]
                opIncR = [income_statement.loc['operatingIncomeRatio'].to_list()]
            except KeyError:
                continue

            try:
                epsGr = [growth_ratios.loc['epsgrowth'].to_list()]
                opIncGr = [growth_ratios.loc['operatingIncomeGrowth'].to_list()]
                asGr = [growth_ratios.loc['assetGrowth'].to_list()]
                fcfGr = [growth_ratios.loc['freeCashFlowGrowth'].to_list()]
            except KeyError:
                continue

            try:
                pe = [key_metrics.loc['peRatio'].to_list()]
                pb = [key_metrics.loc['pbRatio'].to_list()]
                ps = [key_metrics.loc['priceToSalesRatio'].to_list()]
                divYield = [key_metrics.loc['dividendYield'].to_list()]
                roe = [key_metrics.loc['roe'].to_list()]
                de = [key_metrics.loc['debtToEquity'].to_list()]
                da = [key_metrics.loc['debtToAssets'].to_list()]
                intCov = [key_metrics.loc['interestCoverage'].to_list()]

            except KeyError:
                continue

            try:
                divPyr = [financial_ratios.loc['dividendPayoutRatio'].to_list()]
                roa = [financial_ratios.loc['returnOnAssets'].to_list()]
                netPrMar = [financial_ratios.loc['netProfitMargin'].to_list()]
                cashR = [financial_ratios.loc['cashRatio'].to_list()]
                currentR = [financial_ratios.loc['currentRatio'].to_list()]
                asTurn = [financial_ratios.loc['assetTurnover'].to_list()]
                payTurn = [financial_ratios.loc['payablesTurnover'].to_list()]
            except KeyError:
                continue

        # Append to list, if it is not the first element
        else:

            try:
                eps.append(income_statement.loc['eps'].to_list())
                opIncR.append(income_statement.loc['operatingIncomeRatio'].to_list())
            except KeyError:
                continue

            try:
                epsGr.append(growth_ratios.loc['epsgrowth'].to_list())
                opIncGr.append(growth_ratios.loc['operatingIncomeGrowth'].to_list())
                asGr.append(growth_ratios.loc['assetGrowth'].to_list())
                fcfGr.append(growth_ratios.loc['freeCashFlowGrowth'].to_list())
            except KeyError:
                continue

            try:
                pe.append(key_metrics.loc['peRatio'].to_list())
                pb.append(key_metrics.loc['pbRatio'].to_list())
                ps.append(key_metrics.loc['priceToSalesRatio'].to_list())
                divYield.append(key_metrics.loc['dividendYield'].to_list())
                roe.append(key_metrics.loc['roe'].to_list())
                de.append(key_metrics.loc['debtToEquity'].to_list())
                da.append(key_metrics.loc['debtToAssets'].to_list())
                intCov.append(key_metrics.loc['interestCoverage'].to_list())
            except KeyError:
                continue

            try:
                divPyr.append(financial_ratios.loc['dividendPayoutRatio'].to_list())
                roa.append(financial_ratios.loc['returnOnAssets'].to_list())
                netPrMar.append(financial_ratios.loc['netProfitMargin'].to_list())
                cashR.append(financial_ratios.loc['cashRatio'].to_list())
                currentR.append(financial_ratios.loc['currentRatio'].to_list())
                asTurn.append(financial_ratios.loc['assetTurnover'].to_list())
                payTurn.append(financial_ratios.loc['payablesTurnover'].to_list())
            except KeyError:
                continue

    # Conver lists into the dataframes. years sometimes might be wrong (e.g. if some companies are not yet published their financials)
    # but that does not matter, as what matters is the last available value to be taken into the considerationg
    all_eps = pd.DataFrame(eps, columns = ['2020', '2019', '2018', '2017', '2016'])
    all_epsGr =  pd.DataFrame(epsGr, columns = ['2020', '2019', '2018', '2017', '2016'])
    all_pe = pd.DataFrame(pe, columns = ['2020', '2019', '2018', '2017', '2016'])
    all_pb = pd.DataFrame(pb, columns = ['2020', '2019', '2018', '2017', '2016'])
    all_ps = pd.DataFrame(ps, columns = ['2020', '2019', '2018', '2017', '2016'])
    all_divPyr = pd.DataFrame(divPyr, columns = ['2020', '2019', '2018', '2017', '2016'])
    all_divYield = pd.DataFrame(divYield, columns = ['2020', '2019', '2018', '2017', '2016'])
    all_roe = pd.DataFrame(roe, columns = ['2020', '2019', '2018', '2017', '2016'])
    all_roa = pd.DataFrame(roa, columns = ['2020', '2019', '2018', '2017', '2016'])
    all_opIncR = pd.DataFrame(opIncR, columns = ['2020', '2019', '2018', '2017', '2016'])
    all_opIncGr = pd.DataFrame(opIncGr, columns = ['2020', '2019', '2018', '2017', '2016'])
    all_netPrMar = pd.DataFrame(netPrMar, columns = ['2020', '2019', '2018', '2017', '2016'])
    all_cashR = pd.DataFrame(cashR, columns = ['2020', '2019', '2018', '2017', '2016'])
    all_currentR = pd.DataFrame(currentR, columns = ['2020', '2019', '2018', '2017', '2016'])
    all_de = pd.DataFrame(de, columns = ['2020', '2019', '2018', '2017', '2016'])
    all_da = pd.DataFrame(da, columns = ['2020', '2019', '2018', '2017', '2016'])
    all_intCov = pd.DataFrame(intCov, columns = ['2020', '2019', '2018', '2017', '2016'])
    all_asTurn = pd.DataFrame(asTurn, columns = ['2020', '2019', '2018', '2017', '2016'])
    all_payTurn = pd.DataFrame(payTurn, columns = ['2020', '2019', '2018', '2017', '2016'])
    all_asGr = pd.DataFrame(asGr, columns = ['2020', '2019', '2018', '2017', '2016'])
    all_fcfGr = pd.DataFrame(fcfGr, columns = ['2020', '2019', '2018', '2017', '2016'])

    all_peg = all_pe.divide(all_epsGr.replace(np.inf, 0))

    # List of means for last available value
    l = [all_eps['2020'].mean(),
    all_epsGr['2020'].mean(),
    all_pe['2020'].mean(),
    all_pb['2020'].mean(),
    all_ps['2020'].mean(),
    all_divPyr['2020'].mean(),
    all_divYield['2020'].mean(),
    all_roe['2020'].mean(),
    all_roa['2020'].mean(),
    all_opIncR['2020'].mean(),
    all_opIncGr['2020'].mean(),
    all_netPrMar['2020'].mean(),
    all_cashR['2020'].mean(),
    all_currentR['2020'].mean(),
    all_de['2020'].mean(),
    all_da['2020'].mean(),
    all_intCov['2020'].mean(),
    all_asTurn['2020'].mean(),
    all_payTurn['2020'].mean(),
    all_asGr['2020'].mean(),
    all_fcfGr['2020'].mean(),
    all_peg['2020'].mean()]

    # List of ratio names
    ind = ['eps',
    'epsGr',
    'pe',
    'pb',
    'ps',
    'divPyr',
    'divYield',
    'roe',
    'roa',
    'opIncR',
    'opIncGr',
    'netPrMar',
    'cashR',
    'currentR',
    'de',
    'da',
    'intCov',
    'asTurn',
    'payTurn',
    'asGr',
    'fcfGr',
    'peg']

    # Combine values and names into df
    df = pd.DataFrame(l, columns=['2020'])
    df.index = ind

    return df


from sqlalchemy.ext.associationproxy import _AssociationList
import datetime
import json

"""
    Decorator class that adds a to_dict() function to the decorated
    class
"""
class Jsonable:
    def __init__(self, *args):
        self.fields = args

    def __call__(self, cls):
        cls._jsonFields = self.fields

        def to_dict(self):
            dict_representation = {}

            for attribute in self.__class__._jsonFields:
                value = getattr(self, attribute)

                if isinstance(value, list) or isinstance(value, _AssociationList):
                    dict_representation[attribute] = []
                    for i in value:
                        if hasattr(i.__class__, '_jsonFields'):
                            dict_representation[attribute].append(i.to_dict())
                        else:
                            dict_representation[attribute].append(i)
                    continue

                if type(value) is datetime.date:
                    dict_representation[attribute] = str(value)
                elif type(value) is datetime.datetime:
                    dict_representation[attribute] = value.strftime("%Y-%m-%d")
                elif hasattr(value.__class__, '_jsonFields'):
                    dict_representation[attribute] = value.to_dict()
                else:
                    dict_representation[attribute] = value

            return dict_representation

        cls.to_dict = to_dict
        return cls

"""
    This function accepts a jsonable value (list or single element)
    and calls to_dict() to transform the value into a python dictionary.

    Useful for passing lists resulting from a query
"""
def make_jsonable(value):
	if isinstance(value, list):
		jsonable_data = []
		for element in value:
			jsonable_data.append(element.to_dict())
	else:
		jsonable_data = value.to_dict()

	return jsonable_data


#!/usr/bin/python3
# Datei wassermelder.py
import time, sys
import RPi.GPIO as GPIO
from pushbullet.pushbullet import PushBullet

GPIO.setmode(GPIO.BOARD)
GPIO.setup(16, GPIO.IN, pull_up_down=GPIO.PUD_UP)

api_key = "Ihr API-Key"
pb = PushBullet(api_key)

def melder(pin):
    zeit= time.strftime("%d.%m.%Y %H:%M:%S")
    devices = pb.getDevices()
    pb.pushNote(devices[0]["iden"], 'Wasser im Keller!', zeit)
    return

GPIO.add_event_detect(16, GPIO.FALLING, bouncetime=1000)
GPIO.add_event_callback(16, melder)

# mit minimaler CPU-Auslastung auf das Programmende durch
# Strg+C warten
try:
  while True:
    time.sleep(0.5)
except KeyboardInterrupt:
  GPIO.cleanup()
  sys.exit()


# simple neural network to classify handwritten digits from MNIST dataset

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

"""Data Preparation"""
mnist = input_data.read_data_sets('MNIST_data/', one_hot = True) # use the TF helper function to pull down the data from the MNIST data

# x: placeholder for the 28 x 28 image data
x = tf.placeholder(tf.float32, shape = [None, 784]) # None means we know the dimension exists, but not how many items will be there
y_ = tf.placeholder(tf.float32, [None, 10]) # y_: 10 element vector containing the predicted prob of each digit.  must sum to 1

W = tf.Variable(tf.zeros([784, 10])) # define weights
b = tf.Variable(tf.zeros([10])) # define zbiases

"""Prediction"""
y = tf.nn.softmax(tf.matmul(x, W) + b) # softmax is good for the output layer of a NN that determines which class you have

"""Define Loss Function - Cross Entropy"""
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels = y_, logits = y))

"""Optimize to minimize loss"""
train_step = tf.train.GradientDescentOptimizer(.5).minimize(cross_entropy) # each training step in GD we want to minimize the CE

"""Initialize"""
init = tf.global_variables_initializer()

sess = tf.Session()
sess.run(init) # perform the initiailization which is only the initialization of all global variables

for i in range(1000):
    batch_xs, batch_ys = mnist.train.next_batch(100) # get 100 random data points from the data. batch_xs = image, batch_ys = digit class
    sess.run(train_step, feed_dict = {x: batch_xs, y_: batch_ys}) #optimize with this data

correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
test_accuracy = sess.run(accuracy, feed_dict = {x: mnist.test.images, y_: mnist.test.labels})
print("Test Accuracy: {0}".format(test_accuracy * 100.0))

sess.close()