"""
Created on 11/09/2023
@author jdh
"""

import jax.numpy as np
from jax import jit
import matplotlib.pyplot as plt

def normalise(data):

    return (data - np.min(data)) / (data.max() - data.min())

from .vae import VAE
from .classifier import Classifier
from .utils import plot_examples, load_stability_data

import orbax.checkpoint
import pickle
# X_train, X_test, y_train, y_test = load_stability_data()

def orbax_to_numpy_save(filename):

    orbax_checkpointer = orbax.checkpoint.PyTreeCheckpointer()
    raw_restored = orbax_checkpointer.restore(filename)

    raw_restored = dict(raw_restored)

    with open(filename + '/np_checkpoint.pickle', 'wb') as handle:
        pickle.dump(raw_restored, handle, protocol=pickle.HIGHEST_PROTOCOL)

    # d_latent = raw_restored.get('d_latent')
    # d_obs = raw_restored.get('d_obs')
    # vae_params = raw_restored.get('vae_params')
    # classifier_params = raw_restored.get('classifier_params')

def model_file_to_classifier_fn(filename):

    orbax_checkpointer = orbax.checkpoint.PyTreeCheckpointer()
    raw_restored = orbax_checkpointer.restore(filename)
    d_latent = raw_restored.get('d_latent')
    d_obs = raw_restored.get('d_obs')
    vae_params = raw_restored.get('vae_params')
    classifier_params = raw_restored.get('classifier_params')

    vae = VAE(d_obs, d_latent=d_latent)
    classifier = Classifier(d_latent=d_latent)

    encode_fn = lambda x: vae.encoder(vae_params[0], x)[0]
    reconstruct_fn = lambda x: vae._reconstruct(x, vae_params)

    @jit
    def classify(X):
        z = encode_fn(X)
        return np.argmax(classifier.predict(classifier_params, z))

    return classify, reconstruct_fn

def np_model_file_to_classifier_fn(filename):

    with open(filename, 'rb') as handle:
        raw_restored = pickle.load(handle)

    d_latent = raw_restored.get('d_latent')
    d_obs = raw_restored.get('d_obs')
    vae_params = raw_restored.get('vae_params')
    classifier_params = raw_restored.get('classifier_params')

    vae = VAE(d_obs, d_latent=d_latent)
    classifier = Classifier(d_latent=d_latent)

    encode_fn = lambda x: vae.encoder(vae_params[0], x)[0]

    @jit
    def classify(X):
        z = encode_fn(X)
        return np.argmax(classifier.predict(classifier_params, z))

    return classify

#
# example = lambda *args: plot_examples(X_test,
#               lambda x: np.argmax(classifier_trainer.classify(x, classifier_params)),
#               lambda x: vae._reconstruct(x, vae_params)
# )
#
# example()
#
# import sys
#
# sys.path.append('/home/jdh/PycharmProjects/qgor_qm')
# from qgor_simulation import Station
#
# station = Station()
#
#
# def plot(i, name='PCA_0'):
#
#     results = normalise(station.database.load(i).mm_r.get(name))
#
#     plt.figure()
#     plt.imshow(results)
#     plt.show()
#     print(np.argmax(classifier_trainer.classify(results.flatten(), classifier_params)),)


import os, datetime, logging, traceback
import apache_beam as beam
from apache_beam import pvalue
from apache_beam.options.pipeline_options import PipelineOptions
from apache_beam.options.pipeline_options import SetupOptions
from apache_beam.io import ReadFromText
from apache_beam.io import WriteToText

from apache_beam.io.gcp.internal.clients import bigquery

# DoFn to perform on each element in the input PCollection
class TransStateFn(beam.DoFn):
    def process(self, element):
        record = element
        event_id = record.get('event_id')
        state = record.get('state')
        begin_lat = record.get('begin_lat')
        begin_lon = record.get('begin_lon')

        us_state_abbrev = {
            'Alabama': 'AL',
            'Alaska': 'AK',
            'Arizona': 'AZ',
            'Arkansas': 'AR',
            'California': 'CA',
            'Colorado': 'CO',
            'Connecticut': 'CT',
            'Delaware': 'DE',
            'Florida': 'FL',
            'Georgia': 'GA',
            'Hawaii': 'HI',
            'Idaho': 'ID',
            'Illinois': 'IL',
            'Indiana': 'IN',
            'Iowa': 'IA',
            'Kansas': 'KS',
            'Kentucky': 'KY',
            'Louisiana': 'LA',
            'Maine': 'ME',
            'Maryland': 'MD',
            'Massachusetts': 'MA',
            'Michigan': 'MI',
            'Minnesota': 'MN',
            'Mississippi': 'MS',
            'Missouri': 'MO',
            'Montana': 'MT',
            'Nebraska': 'NE',
            'Nevada': 'NV',
            'New Hampshire': 'NH',
            'New Jersey': 'NJ',
            'New Mexico': 'NM',
            'New York': 'NY',
            'North Carolina': 'NC',
            'North Dakota': 'ND',
            'Ohio': 'OH',
            'Oklahoma': 'OK',
            'Oregon': 'OR',
            'Pennsylvania': 'PA',
            'Rhode Island': 'RI',
            'South Carolina': 'SC',
            'South Dakota': 'SD',
            'Tennessee': 'TN',
            'Texas': 'TX',
            'Utah': 'UT',
            'Vermont': 'VT',
            'Virginia': 'VA',
            'Washington': 'WA',
            'West Virginia': 'WV',
            'Wisconsin': 'WI',
            'Wyoming': 'WY',
        }

        if state.title() in list(us_state_abbrev.keys()):
            stateabb = us_state_abbrev[state.title()]
        else:
            stateabb = 'Not US state'

        return [(state, stateabb)]

class MakeRecordFn(beam.DoFn):
    def process(self,element):
        state, stateabb = element
        record = {'state': state, 'state_abbreviation':stateabb}
        return [record]

PROJECT_ID = os.environ['PROJECT_ID']

options = {
	'project': PROJECT_ID
}
opts = beam.pipeline.PipelineOptions(flags=[], **options)

# Create a Pipeline using a local runner for execution.
with beam.Pipeline('DirectRunner', options=opts) as p:

    query_result = p | 'Read from BigQuery' >> beam.io.Read(beam.io.BigQuerySource(query='SELECT * FROM dataset2.location'))

    # Write file
    query_result | 'Write to log 1' >> WriteToText('locationinput.txt')

    # Apply PCollection
    transfrom_pcol = query_result | 'Extract State' >> beam.ParDo(TransStateFn())

    # Write file
    transfrom_pcol | 'Write File' >> WriteToText('locationoutput.txt')

    # Make BQ records
    out_pcoll = transfrom_pcol | 'Make BQ Record' >> beam.ParDo(MakeRecordFn())

    qualified_table_name = PROJECT_ID + ':dataset2.state'
    table_schema = 'state:STRING, state_abbreviation:STRING'

    out_pcoll | 'Write to BigQuery' >> beam.io.Write(beam.io.BigQuerySink(qualified_table_name,
                                                                          schema=table_schema,
                                                                          create_disposition=beam.io.BigQueryDisposition.CREATE_IF_NEEDED,
                                                                          write_disposition=beam.io.BigQueryDisposition.WRITE_TRUNCATE))

Data Cleansing and Normalization/Transform/transform_state_single.py


# from hashlib import md5
#from urllib import urlencode
#from django.utils.http import urlencode

from django import template

register = template.Library()
# #
# #
# # @register.simple_tag
# # def get_gravatar(email, size=60, rating='g', default=None):
# #     """ Return url for a Gravatar. From Zinnia blog. """
# #     url = 'https://secure.gravatar.com/avatar/{0}.jpg'.format(
# #         md5(email.strip().lower()).hexdigest()
# #     )
# #     options = {'s': size, 'r': rating}
# #     if default:
# #         options['d'] = default
# #
# #     url = '%s?%s' % (url, urlencode(options))
# #     return url.replace('&', '&')
# #
# # # def _get_avatars(user):
# # #     # Default set. Needs to be sliced, but that's it. Keep the natural order.
# # #     avatars = user.avatar_set.all()
# # #
# # #     # Current avatar
# # #     primary_avatar = avatars.order_by('-primary')[:1]
# # #     if primary_avatar:
# # #         avatar = primary_avatar[0]
# # #     else:
# # #         avatar = None
# # #
# # #     if settings.AVATAR_MAX_AVATARS_PER_USER == 1:
# # #         avatars = primary_avatar
# # #     else:
# # #         # Slice the default set now that we used
# # #         # the queryset for the primary avatar
# # #         avatars = avatars[:settings.AVATAR_MAX_AVATARS_PER_USER]
# # #     return (avatar, avatars)
# #
@register.simple_tag
def page_query(request, page_num):
    qs = request.GET.copy()
    qs['page'] = page_num
    return qs.urlencode().replace('&', '&')


def solution(skill, skill_trees):
    answer = 0
    for s in skill_trees :
        check = True
        index =0
        for i in range(len(skill)):
            tempindex = s.find(skill[i])
            if  tempindex != -1 and index != -1 :
                if index > tempindex :
                    check = False
                    break
            elif tempindex != -1 and index == -1 :
                check = False
                break
            index = tempindex
        if check == True:
            answer +=1
    return answer
if __name__ == "__main__" :
    s = "CBD"
    st = ["BACDE", "CBADF", "AECB", "BDA"]
    a = solution(s,st)

프로그래머스/스킬트리/skill.py


def study_schedule(permanence_period, target_time):
    """ Faça o código aqui. """
    contador = 0
    try:
        for time in permanence_period:
            if target_time >= time[0] and target_time <= time[1]:
                contador += 1
    except TypeError:
        return None
    return contador


''''
问题：　在迭代操作或者其他操作时，怎么只保留最后有限
几个元素的历史记录
解决方案：
    使用　collections.deque
'''

from collections import deque

def search(lines, pattern, history=5):
    previous_lines = deque(maxlen=history)
    for line in lines:
        if pattern in line:
            yield line, previous_lines
        previous_lines.append(line)

if __name__ == '__main__':
    with open('test.txt') as f:
        f_line = []
        f_pre = None
        for line, prevlines in search(f, 'python', 5):
            f_line.append(line)
            f_pre = prevlines


import speech_recognition as sr
import datetime
import webbrowser
import time
import playsound
import os
import wikipedia
import random
from time import ctime
from gtts import gTTS
def wishME():
    hour = int (datetime.datetime.now().hour)
    if hour>= 0 and hour<12:
        joo_speak("good moring my dear")

    if hour>= 12 and hour<23:
        joo_speak("good evening my dear")
r = sr.Recognizer()

def record_audio(ask = False):
    with sr.Microphone() as source:
        if ask:
            joo_speak(ask)
        audio = r.listen(source)
        voice_data = ''

        try:
            voice_data = r.recognize_google(audio)
        except sr.UnknownValueError:
            joo_speak('Sorry, I did not get that,can you talk again')
        except sr.RequestError:
            joo_speak('sorry my speach service is down')
        return voice_data

def joo_speak(audio_string):
    tts = gTTS(text=audio_string, lang='en')
    r = random.randint(1, 1000000)
    audio_file = 'audio' +str(r) + '.mp3'
    tts.save(audio_file)
    playsound.playsound(audio_file)
    print(audio_string)
    os.remove(audio_file)

wishME()

def respond(voice_data):

    if 'what is your name' in voice_data:
        joo_speak('My name is joo')

    if 'nice name' in voice_data:
        joo_speak('how can i help you?')

    if 'what time is it' in voice_data:
        joo_speak(ctime())

    if 'YouTube' in voice_data:
        webbrowser.open('https://www.youtube.com/')

    if 'find location' in voice_data:
        location = record_audio('what is the location')
        url = 'https://google.nl/maps/place/' + location + '/&'
        webbrowser.get().open(url)
        joo_speak('here is the location of ' + location)

    if 'please search' in voice_data:
        joo_speak('Searching Wikipedia...')
        voice_data = record_audio('what do you want to search')
        voice_data = voice_data.replace("wikipedia", "")
        results = wikipedia.summary(voice_data, sentences = 3)
        joo_speak("According to Wikipedia")
        print(results)
        joo_speak(results)

    if 'thank you by' in voice_data:
        joo_speak('bye sir')
        exit()

time.sleep(1)
joo_speak('HELLO')
while 1:
    voice_data = record_audio()
    respond(voice_data)


from numpy import *
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from numpy import genfromtxt
import numpy as np

def pca(dataMat, k):
    average = np.mean(dataMat, axis=0) #按列求均值
    m, n = np.shape(dataMat)
    meanRemoved = dataMat - np.tile(average, (m,1)) #减去均值
    normData = meanRemoved / np.std(dataMat) #标准差归一化
    covMat = np.cov(normData.T)  #求协方差矩阵
    print( covMat)
    eigValue, eigVec = np.linalg.eig(covMat) #求协方差矩阵的特征值和特征向量
    eigValInd = np.argsort(-eigValue) #返回特征值由大到小排序的下标
    selectVec = np.matrix(eigVec.T[:k]) #因为[:k]表示前k行，因此之前需要转置处理（选择前k个大的特征值）
    finalData = normData * selectVec.T #再转置回来
    return finalData

#dataSet:聚类数据集
#k:指定的k个类（大佬）
def kmeans(dataSet, k):
    #得到数据样本的维度n
    sampleNum, col = dataSet.shape
     #初始化为一个(k,n)的矩阵=簇
    cluster = mat(zeros((sampleNum, 2)))
    #生成全零阵
    centroids = zeros((k, col))
    #选择质心
    for i in range(k):
        #索引为随机生成的int类型的且在0-sampleNum间的数
        index = int(random.uniform(0, sampleNum))
        centroids[i, :] = dataSet[index, :]
    #设置flag，查看聚类结果是否发生变化
    clusterChanged = True
     #只要聚类结果一直发生变化，就一直执行聚类算法，直至所有数据点聚类结果不变化
    while clusterChanged:
        #聚类结果变化布尔类型置为false
        clusterChanged = False
         #遍历数据集每一个样本向量
        for i in range(sampleNum):
            #使用sqrt函数（二分法）
            minDist = sqrt(sum(power(centroids[0, :] - dataSet[i, :], 2)))
            minIndex = 0
            #计算点到质心的距离
            for j in range(1,k):
                distance = sqrt(sum(power(centroids[j, :] - dataSet[i, :], 2)))
                #当前最小距离一定时，索引为J
                if distance < minDist:
                    minDist  = distance
                    minIndex = j

            # 当前聚类结果中第i个样本的聚类结果发生变化：布尔类型置为true，继续聚类算法
            if cluster[i, 0] != minIndex:
                clusterChanged = True
                #更新聚类结果和平方误差
                cluster[i, :] = minIndex, minDist**2
        #遍历每一个质心
        for j in range(k):
            #筛选出属于当前质心类的所有样本
            pointsInCluster = dataSet[nonzero(cluster[:, 0].A == j)[0]]
            #计算列的均值（使用axis=0：求列的均值）
            centroids[j, :] = mean(pointsInCluster, axis = 0)

    return centroids, cluster

#创建简单数据集以及进行可视化

f = open('space_dan_normalize_speaker.txt', 'r', encoding = 'utf-8')
dataSet = []
for line in f.readlines():
    lst = line.strip('\n').split('\t')
    lst = lst[1:]
    lst_int = []
    for i in range(len(lst)):
        num = float(lst[i])
        if num == 0:
            num = random.randint(0,1)
        else:
            num += 1

        '''
        if num <= 0.0025:
            num += 10
        elif 0.0025 < num <= 0.005:
            num += 20
        elif 0.005 < num <= 0.0075:
            num += 30
        elif 0.0075 < num <= 0.01:
            num += 40
        elif 0.01 < num <= 0.0125:
            num += 50
        elif 0.0125 < num <= 0.015:
            num += 60
        elif 0.015 < num <= 0.0175:
            num += 70
        elif num > 0.0175:
            num += 80
        '''
        lst_int.append(num)
    #print(lst_int)
    dataSet.append(lst_int)
#print(dataSet)

r = open('space_dan_normalize_speaker.csv', 'r', encoding = 'utf-8')
dataMat = genfromtxt(r, delimiter=',')
print(dataMat.shape)
print(np.isnan(dataMat).any())
dataMat = np.nan_to_num(dataMat)

s = open('space_dan_normalize_speaker_classification.txt', 'r', encoding = 'utf-8')
genders = []
for line in s.readlines():
    lst = line.strip('\n').split('\t')
    #gender = lst[2]+'/'+lst[3]+'/'+lst[4]+'/'+lst[5]
#    list = ['41','60','61','37','47','66','6','52','11','70','65','88','62','44','83']
    if lst[4] == 'F':
        gender = lst[4] + ' & ' + lst[14]
    else:
        gender = ' '
    genders.append(gender)

#print(dataMat)
k_value = [2,3]
for i in range(len(k_value)):
    finalData = pca(dataMat, k_value[i])
    print(finalData,shape)
    print(len(dataMat[:-1]))
    print(len(dataMat[1:]))
    #plt.scatter(dataMat.T[:-1],dataMat.T[1:], color='red',alpha=0.2, s=20)

    a = np.array(finalData.T[:-1])
    b = np.array(finalData.T[1:])
    plt.scatter(a,b, color='blue',alpha=0.1, s=30)
    plt.show()
    plt.close()

#dataSet = [[1.555,1,0,0,0,4],[0,6,0,4,0,0],[3,0,0,0,0,2],[8,0,0,1,1,0]]
#dataSet = [[1,1],[3,1],[1,4],[2,5],[11,12],[14,11],[13,12],[11,16],[17,12],[28,10],[26,15],[27,13],[28,11],[29,15]]

    dataSet = mat(finalData)
    k = 4
    centroids, cluster = kmeans(dataSet, k)
    sampleNum, col = dataSet.shape

    mark = ['ob', 'ok', 'oc', 'or', 'om', 'og']

    for i in range(sampleNum):
        markIndex = int(cluster[i, 0])
        plt.plot(dataSet[i, 0], dataSet[i, 1], mark[markIndex], alpha=0.6, markersize=6)

    name = genders
    for i in range(len(dataSet)):
        plt.text(dataSet[:, 0][i],dataSet[:, 1][i],name[i])

    mark = ['+b', '+k', '+c', '+r', '+m', '+g']
    for i in range(k):
        plt.plot(centroids[i, 0], centroids[i, 1], mark[i], markersize=12)

    plt.show()


'''
Max Sum Contiguous Subarray

Find the contiguous subarray within an array, A of length N which has the largest sum.

Constraints:
1 <= N <= 1e6
-1000 <= A[i] <= 1000

input: [1, 2, 3, 4, -10]
output: 10

input: [-2, 1, -3, 4, -1, 2, 1, -5, 4]
output: 6
'''

def maxSubArray(a):
    max_sum = curr_sum = a[0]
    # safety case
    if len(a) < 2:
        return max_sum
    # curr sum marks the beginning of our subarray
    # max sum marks the sum from the beginning to end of the sub array
    for i in range(1,len(a)):
        curr_sum = max(a[i], curr_sum + a[i])
        max_sum = max(curr_sum, max_sum)
    return max_sum


"""Helper functions and Classes for topographic maps during Lossless QC."""

# Authors: Christian O'Reilly <christian.oreilly@sc.edu>
#          Scott Huberty <seh33@uw.edu>
# License: MIT
from copy import copy
import warnings
from collections import OrderedDict

import plotly.graph_objects as go
from plotly.subplots import make_subplots
from dash import dcc, html
from dash.dependencies import Input, Output
import dash_bootstrap_components as dbc
import dash

import mne
import numpy as np
import pandas as pd

from mne import create_info
from mne.io import RawArray
from mne.utils.check import _check_sphere
from mne.viz.topomap import _get_pos_outlines
from mne.viz.topomap import _setup_interp, _check_extrapolate

from .css_defaults import CSS, STYLE
from . import ic_label_cmap

# thin lines in the background and numbers below
axis = {"showgrid": False, "visible": False}
yaxis = copy(axis)
yaxis.update({"scaleanchor": "x", "scaleratio": 1})

class TopoPlot:  # TODO: Fix/finish doc comments for this class.
    """Representation of a classic EEG topographic map as a plotly figure."""

    def __init__(
        self,
        montage="standard_1020",
        data=None,
        figure=None,
        color="black",
        row=None,
        col=None,
        res=64,
        width=None,
        height=None,
        cmap="RdBu_r",
        show_sensors=True,
        colorbar=False,
    ):
        """Initialize instance.

        Parameters
        ----------
        montage : mne.channels.DigMontage | str
            Montage for digitized electrode and headshape position data.
            See mne.channels.make_standard_montage(), and
            mne.channels.get_builtin_montages() for more information
            on making montage objects in MNE.
        data : OrderedDict | None
            The data to use for the topoplots.
        figure : plotly.graph_objects.Figure | None
            Figure to use (if not None) for plotting.
        color : str
            The color to use for the topoplot head outline. Must be a string
            of a rgba or hex code that is compatible with plotly's graphing
            library.
        row : int | None
            Row number of the topoplot, if embedded in a grid.
        col : int | None
            Column number for the topoplot, if embedded in a grid.
        res : int
            Resolution (res X res) for the heatmap.
        width : int
            The width of the dcc.graph object holding the topoplots
        height : int
            The height of the dcc.graph object holding the topoplots
        cmap : str
            The color to use for the topoplot heatmap. Must be a string of
            a rgba or hex code that is compatible with plotly's graphing
            library.
        show_sensors : bool
            Whether to show the sensors (as dots) on the topoplot. Defaults
            to True.
        colorbar : bool
            Whether to show the colorbar.
        """
        self.heatmap_traces = None
        self.colorbar = colorbar
        self.cmap = cmap
        self.title = None
        self.show_sensors = show_sensors
        self.info = None
        self.pos = None
        self.contours = None
        self.__data = None
        self.pos = None
        self.outlines = None
        self.color = color
        self.info = None
        self.col = col
        self.row = row
        self.res = res
        self.width = width
        self.height = height

        if isinstance(montage, str):
            self.montage = mne.channels.make_standard_montage(montage)
        else:
            self.montage = montage

        if figure is None:
            self.figure = go.Figure()
        else:
            self.figure = figure

        if data is None:
            return

        self.data = data
        self.plot_topo()

    @property
    def data(self):
        """Get accessor for the object containing the topomap data.

        Returns
        -------
        An OrderedDict with the channel names as keys, and the values
        to plot as values.
        """
        return self.__data

    @data.setter
    def data(self, data):
        """Setter accessor for the data of the topomap.

        Parameters
        ----------
        data : dict
            Dictionary of channel name (key) and corresponding values
            to be plotted.
        """
        self.set_data(data)

    def set_data(self, data):
        """Set the data used for plotting.

        Parameters
        ----------
        data : dict
            Dictionary of channel name (key) and corresponding values
            to be plotted.
        """
        if data is None:
            return
        self.__data = OrderedDict(data)
        names = list(self.__data.keys())
        self.info = create_info(names, sfreq=256, ch_types="eeg")
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            RawArray(
                np.zeros((len(names), 1)), self.info, copy=None, verbose=False
            ).set_montage(self.montage)
        self.set_head_pos_contours()

    # TODO: Finish/fix docstring
    def set_head_pos_contours(self, sphere=None, picks=None):
        """Manually set head position contours."""
        if not self.info:
            return
        sphere = _check_sphere(sphere, self.info)
        self.pos, self.outlines = _get_pos_outlines(
            self.info, picks, sphere, to_sphere=True
        )

    # TODO: Finish/fix docstring
    def get_head_scatters(self, color="back", show_sensors=True):
        """Build scatter plot from head position data."""
        outlines_scat = [
            go.Scatter(x=x, y=y, line=dict(color=color), mode="lines", showlegend=False)
            for key, (x, y) in self.outlines.items()
            if "clip" not in key and "mask" not in key
        ]
        if show_sensors:
            pos_scat = go.Scatter(
                x=self.pos.T[0],
                y=self.pos.T[1],
                line=dict(color=color),
                mode="markers",
                marker=dict(color=color, size=2, opacity=0.5),
                showlegend=False,
            )

            return outlines_scat + [pos_scat]

        return outlines_scat

    def get_heatmap_data(self, ch_type="eeg", extrapolate="auto"):
        """Get the data to use for the topo plots.

        Parameters
        ----------
        data : dict
            Dictionary with channel names as key and float as values.
        ch_type : str
            The data type. defaults to 'eeg'
        res : int
            The dpi resolution for the topoplots. Defaults to 64
        extrapolate : str
            Method to extrapoloate data

        Returns
        -------
        a dict of the data, with keys 'x', 'y', 'z'.
        """
        extrapolate = _check_extrapolate(extrapolate, ch_type)
        # find mask limits and setup interpolation
        _, Xi, Yi, interp = _setup_interp(
            self.pos,
            res=self.res,
            image_interp="cubic",
            extrapolate=extrapolate,
            outlines=self.outlines,
            border="mean",
        )
        interp.set_values(np.array(list(self.__data.values())))
        Zi = interp.set_locations(Xi, Yi)()

        # Clip to the outer circler
        x0, y0 = self.outlines["clip_origin"]
        x_rad, y_rad = self.outlines["clip_radius"]
        Zi[np.sqrt(((Xi - x0) / x_rad) ** 2 + ((Yi - y0) / y_rad) ** 2) > 1] = np.nan

        return {"x": Xi[0], "y": Yi[:, 0], "z": Zi}

    def _update_axes(self):
        self.figure.update_xaxes(
            {"showgrid": False, "visible": False}, row=self.row, col=self.col
        )

        scale_anchor = list(self.figure.select_yaxes(row=self.row, col=self.col))
        scale_anchor = scale_anchor[0]["anchor"]
        if not scale_anchor:
            scale_anchor = "x"
        self.figure.update_yaxes(
            {
                "showgrid": False,
                "visible": False,
                "scaleanchor": scale_anchor,
                "scaleratio": 1,
            },
            row=self.row,
            col=self.col,
        )

        self.figure.update_layout(
            autosize=False,
            width=self.width,
            height=self.height,
            plot_bgcolor="rgba(0,0,0,0)",
            paper_bgcolor="rgba(0,0,0,0)",
            margin=dict(l=0, r=0, b=0, t=20),
        )

    def plot_topo(self, **kwargs):
        """Plot the topomap.

        Parameters
        ----------
        **kwargs
            Arguments pass to plotly.graph_objects.Heatmap.

        Returns
        -------
            A plotly.graph_objects.Figure object.
        """
        if self.__data is None:
            return

        heatmap_trace = go.Heatmap(
            showscale=self.colorbar,
            colorscale=self.cmap,
            **self.get_heatmap_data(**kwargs)
        )

        for trace in self.get_head_scatters(color=self.color):
            self.figure.add_trace(trace, row=self.row, col=self.col)
        self.figure.add_trace(heatmap_trace, row=self.row, col=self.col)

        self._update_axes()

        return self.figure

def __check_shape__(rows, cols, data, fill=None):
    if not isinstance(data, (list, tuple, np.ndarray)):
        return np.array([[data] * cols] * rows)

    data = np.array(data)
    if data.shape == (rows, cols):
        return data

    if len(data.ravel()) < rows * cols:
        data = np.concatenate(
            (data.ravel(), [fill] * (rows * cols - len(data.ravel())))
        )
    return data.reshape((rows, cols))

class GridTopoPlot:
    """Representation of grid of topomaps as a plotly figure."""

    def __init__(
        self,
        rows=1,
        cols=1,
        montage="standard_1020",
        data=None,
        figure=None,
        color="black",
        subplots_kwargs=None,
        **kwargs
    ):
        """Initialize instance.

        Parameters
        ----------
        rows : int
            The number of rows to use for the topoplots. For example, using
            the default values, will show 5 rows of 4 topoplots each. A
            dash dcc.Slider is available to scroll if there are more topoplots
            than can be fit into one row x col view.
        cols : int
            The number of cols to use for the topoplots.
        montage : mne.channels.DigMontage
            Montage for digitized electrode and headshape position data.
            See mne.channels.make_standard_montage(), and
            mne.channels.get_builtin_montages() for more information
            on making montage objects in MNE.
        data : mne.preprocessing.ICA | None
            The data to use for the topoplots. Can be an instance of
            mne.preprocessing.ICA.
        figure : plotly.graph_objects.Figure | None
            Figure to use (if not None) for plotting.
        color : str
            The color to use for the topoplot head outline. Must be a string
            of a rgba or hex code that is compatible with plotly's graphing
            library.
        subplots_kwargs : dict
            Arguments to be passed to plotly.subplots.make_subplots.
        **kwargs:
            Additional arguments to be passed to TopoPlot.
        """
        montage = __check_shape__(rows, cols, montage)
        color = __check_shape__(rows, cols, color)

        subplots_kwargs_ = dict(horizontal_spacing=0.03, vertical_spacing=0.03)
        if subplots_kwargs:
            subplots_kwargs_.update(subplots_kwargs)
        self.rows = rows
        self.cols = cols
        self.color = color
        self.figure = None

        if data is None:
            self.__data = None
            return
        self.__data = __check_shape__(rows, cols, data)

        if figure is None:
            self.figure = make_subplots(rows=rows, cols=cols, **subplots_kwargs_)
        else:
            self.figure = figure

        self.topos = np.array(
            [
                [
                    TopoPlot(
                        montage=m,
                        data=d,
                        figure=self.figure,
                        col=col + 1,
                        row=row + 1,
                        color=color,
                        **kwargs
                    )
                    for col, (m, d, color) in enumerate(
                        zip(montage_row, data_row, color_row)
                    )
                ]
                for row, (montage_row, data_row, color_row) in enumerate(
                    zip(montage, self.__data, self.color)
                )
            ]
        )

    @property
    def nb_topo(self):
        """Return the number of topoplots."""
        return self.rows * self.cols

class TopoData:  # TODO: Fix/finish doc comments for this class.
    """Handler class for passing Topo Data."""

    def __init__(self, topo_values=()):
        """topo_values: list of dict."""
        self.topo_values = pd.DataFrame(topo_values)

    def add_topomap(self, topomap: dict, title=None):
        """topomap: dict."""
        if not title:
            title = str(len(self.topo_values))
        self.topo_values = pd.concat(
            [self.topo_values, pd.DataFrame(topomap, index=[title])]
        )

    @property
    def nb_topo(self):
        """topomap: shape."""
        return self.topo_values.shape[0]

class TopoViz:  # TODO: Fix/finish doc comments for this class.
    """Representation of a classic EEG topographic map."""

    def __init__(
        self,
        app=None,
        montage=None,
        data=None,
        rows=5,
        cols=4,
        width=400,
        height=600,
        margin_x=4 / 5,
        margin_y=2 / 5,
        res=64,
        head_contours_color="black",
        cmap="RdBu_r",
        show_sensors=True,
        mode=None,
        show_slider=True,
        refresh_inputs=None,
    ):
        """Initialize instance.

        Parameters
        ----------
        app : instance of Dash.app
            The dash app object to place the plot within.
        montage : mne.channels.DigMontage
            Montage for digitized electrode and headshape position data.
            See mne.channels.make_standard_montage(), and
            mne.channels.get_builtin_montages() for more information
            on making montage objects in MNE.
        data : mne.preprocessing.ICA
            The data to use for the topoplots. Can be an instance of
            mne.preprocessing.ICA.
        rows : int
            The number of rows to use for the topoplots. For example, using
            the default values, will show 5 rows of 4 topoplots each. A
            dash dcc.Slider is available to scroll if there are more topoplots
            than can be fit into one row x col view.
        cols : int
            The number of cols to use for the topoplots.
        width : int
            The width of the dcc.graph object holding the topoplots
        height : int
            The height of the dcc.graph object holding the topoplots
        margin_x : float
            Can be a float or for example 4/5.
        margin_y : float
            Can be a float or for example 4/5.
        res: int
            Resolution (res X res) of the heatmaps generated for the topomaps.
        head_contours_color : str
            The color to use for the topoplot head outline. Must be a string
            of a rgba or hex code that is compatible with plotly's graphing
            library.
        cmap : str
            The color to use for the topoplot heatmap. Must be a string of
            a rgba or hex code that is compatible with plotly's graphing
            library.
        show_sensors : bool
            Whether to show the sensors (as dots) on the topoplot. Defaults
            to True.
        mode : str
            Can take the value "standalone_jupyter" for an app within a
            Jupyter Notebook, "standalone" for a typical Dash app, or
            "embedded" for using an pre-existing app object.
        show_slider : bool
            Whether to show the dcc.Slider component that controls which
            topoplots are in view. Defaults to True.
        refresh_inputs : str | iterable
            The id of one or more dash components, that should trigger a
            refresh of the topoplots. For example this can be useful if
            one would like a dcc.dropdown component containing a list of
            file names to refresh the data when selected.
        """
        if refresh_inputs:
            if not isinstance(refresh_inputs, list):
                refresh_inputs = [refresh_inputs]
        else:
            refresh_inputs = []

        self.refresh_inputs = refresh_inputs
        self.app = app
        self.show_slider = show_slider
        self.data = None
        self.montage = montage
        self.offset = 0
        self.rows = rows
        self.cols = cols
        self.width = width
        self.height = height
        self.res = res
        self.colorbar = False
        self.cmap = cmap
        self.titles = None
        self.show_sensors = show_sensors
        self.margin_x = margin_x
        self.margin_y = margin_y
        self.head_contours_color = None
        self.container_plot = None

        if app is None:
            stylesheets = [dbc.themes.SLATE]
            if mode == "standalone_jupyter":
                from jupyter_dash import JupyterDash

                self.app = JupyterDash("TopoViz", external_stylesheets=stylesheets)
                self.mode = mode
            else:
                self.app = dash.Dash("TopoViz", external_stylesheets=stylesheets)
                self.mode = "standalone"
            self.app.layout = html.Div([])
        else:
            self.app = app
            self.mode = "embedded"

        self.graph = dcc.Graph(figure=None, id="topo-graph", className=CSS["topo-dcc"])
        self.graph_div = html.Div(
            children=[self.graph],
            id="topo-graph-div",
            className=CSS["topo-dcc-div"],
            style=STYLE["topo-dcc-div"],
        )

        self._init_slider()
        self.set_data(montage, data, head_contours_color)
        self._set_div()
        self.figure = None

        self._set_callback()

        if "standalone" in self.mode:
            self.app.layout.children.append(self.container_plot)

    @property
    def figure(self):
        """Return the go.Graph.figure object."""
        return self.graph.figure

    @figure.setter
    def figure(self, fig):
        """Set the value of the plotly figure object.

        Parameters
        ----------
        fig : plotly.graph_objects.Figure | None
            Figure object to be set or None if no figure should be plotted.
        """
        if fig:
            self.graph.figure = fig
        else:
            self.graph.figure = {}

    def set_data(self, montage=None, data=None, head_contours_color="black"):
        """Set the data used for plotting.

        Parameters
        ----------
        montage : mne.channels.DigMontage
            Montage for digitized electrode and headshape position data.
            See mne.channels.make_standard_montage(), and
            mne.channels.get_builtin_montages() for more information
            on making montage objects in MNE.
        data : TopoData
            Data to be plotted.
        head_contour_color : str
            The color to use for the topoplot head outline. Must be a string
            of a rgba or hex code that is compatible with plotly's graphing
            library.
        """
        if data is None:
            return
        self.data = data
        if montage is not None:
            self.montage = montage
        if isinstance(head_contours_color, str):
            head_contours_color = {
                title: head_contours_color for title in self.data.topo_values.index
            }
        if head_contours_color:
            self.head_contours_color = head_contours_color

        self.topo_slider.max = self.nb_topo - 1
        self.topo_slider.value = self.nb_topo - 1
        self.initialize_layout()

    def initialize_layout(self, slider_val=None, show_sensors=True):
        """Initialize the layout for the topoplot dcc.graph component."""
        if self.data is None:
            self.figure = None
            return

        if slider_val is not None:
            """
            For a total of N topomaps and a grid of M topomaps being displayed,
            the values for the slide varies from [M-1, N-1] with an initial
            value at N-1.
            """
            self.offset = slider_val - self.nb_sel_topo + 1

        titles = self.data.topo_values.index

        last_sel_topo = self.offset + self.nb_sel_topo
        titles = titles[::-1][self.offset : last_sel_topo][::-1]
        colors = [self.head_contours_color[title] for title in titles]

        # The indexing with ch_names is to ensure the order
        # of the channels are compatible between plot_data and the montage
        ch_names = [
            ch_name
            for ch_name in self.montage.ch_names
            if ch_name in self.data.topo_values.columns
        ]
        plot_data = self.data.topo_values.loc[titles, ch_names]
        plot_data = list(plot_data.T.to_dict().values())

        if len(plot_data) < self.nb_sel_topo:
            nb_missing_topo = self.nb_sel_topo - len(plot_data)
            plot_data = np.concatenate((plot_data, [None] * nb_missing_topo))

        self.figure = GridTopoPlot(
            rows=self.rows,
            cols=self.cols,
            montage=self.montage,
            data=plot_data,
            color=colors,
            res=self.res,
            height=self.height,
            width=self.width,
            show_sensors=show_sensors,
            subplots_kwargs=dict(
                horizontal_spacing=0.03,
                vertical_spacing=0.03,
                subplot_titles=titles,
            ),
        ).figure

    @property
    def nb_sel_topo(self):
        """Return the number of visible topoplots."""
        return self.rows * self.cols

    @property
    def nb_topo(self):
        """Return the total number of topoplots.

        Returns
        -------
           The total thumber of topomaps, which may be a faction of
           the number of visible topomaps at a givent time.
        """
        if self.data:
            return self.data.nb_topo
        return 0

    def _init_slider(self):
        """Initialize the dcc.Slider component for the topoplots."""
        self.topo_slider = dcc.Slider(
            id="topo-slider",
            min=self.nb_sel_topo - 1,
            max=self.nb_topo - 1,
            step=1,
            marks=None,
            value=self.nb_topo - 1,
            included=False,
            updatemode="mouseup",
            vertical=True,
            verticalHeight=400,
        )
        self.topo_slider_div = html.Div(
            self.topo_slider, className=CSS["topo-slider-div"], style={}
        )
        if not self.show_slider:
            self.topo_slider_div.style.update({"display": "none"})

    def _set_div(self):
        """Set the html.Div component for the topoplots."""
        # outer_div includes slider obj
        graph_components = [self.topo_slider_div, self.graph_div]
        self.container_plot = html.Div(
            children=graph_components,
            id="ica-topo-div",
            className=CSS["topo-container"],
            style={"display": "none"},
        )

    def _set_callback(self):
        """Create the callback for the dcc.graph component of the topoplots."""
        args = [Output("topo-graph", "figure")]
        args += [Input("topo-slider", "value")]
        if self.refresh_inputs:
            args += self.refresh_inputs

        @self.app.callback(*args, suppress_callback_exceptions=False)
        def callback(slider_val, *args):
            self.initialize_layout(
                slider_val=slider_val, show_sensors=self.show_sensors
            )
            if self.figure:
                return self.figure
            return dash.no_update

        @self.app.callback(
            Output("ica-topo-div", "style"),
            Input("topo-graph", "figure"),
        )
        def show_figure(figure):
            if figure:
                return {"display": "block"}
            return {"display": "none"}

class TopoVizICA(TopoViz):
    """Representation of a classic ICA topographic map."""

    def __init__(self, app, montage, ica, ic_labels=None, **kwargs):
        """Initialize instance.

        Parameters
        ----------
        app : instance of Dash.app
            The dash app object to place the plot within.
        montage : mne.channels.DigMontage
            Montage for digitized electrode and headshape position data.
            See mne.channels.make_standard_montage(), and
            mne.channels.get_builtin_montages() for more information
            on making montage objects in MNE.
        data : mne.preprocessing.ICA
            The data to use for the topoplots. Can be an instance of
            mne.preprocessing.ICA.
        ica : mne.preprocessing.ICA
            The data to use for the topoplots. Can be an instance of
            mne.preprocessing.ICA.
        ic_labels : mapping
            A mapping between the ICA names and their IClabels, which
            can be identified with mne-icalabel soon.
        rows : int
            The number of rows to use for the topoplots. For example, using
            the default values, will show 5 rows of 4 topoplots each. A
            dash dcc.Slider is available to scroll if there are more topoplots
            than can be fit into one row x col view.
        cols : int
            The number of cols to use for the topoplots.
        width : int
            The width of the dcc.graph object holding the topoplots
        height : int
            The height of the dcc.graph object holding the topoplots
        margin_x : float
            Can be a float or for example 4/5.
        margin_y : float
            Can be a float or for example 4/5.
        head_contours_color : str
            The color to use for the topoplot head outline. Must be a string
            of a rgba or hex code that is compatible with plotly's graphing
            library.
        cmap : str
            The color to use for the topoplot heatmap. Must be a string of
            a rgba or hex code that is compatible with plotly's graphing
            library.
        show_sensors : bool
            Whether to show the sensors (as dots) on the topoplot. Defaults
            to True.
        show_slider : bool
            Whether to show the dcc.Slider component that controls which
            topoplots are in view. Defaults to True.
        refresh_inputs : str | iterable
            The id of one or more dash components, that should trigger a
            refresh of the topoplots. For example this can be useful if
            one would like a dcc.dropdown component containing a list of
            file names to refresh the data when selected.
        """
        data = self.init_vars(montage, ica, ic_labels)
        super(TopoVizICA, self).__init__(app, montage, data, **kwargs)

    def init_vars(self, montage, ica, ic_labels):
        """Initialize the montage, ica, and ic_labels data."""
        if not montage or not ica:
            return None

        data = TopoData(
            [
                dict(zip(montage.ch_names, component))
                for component in ica.get_components().T
            ]
        )
        if ic_labels:
            self.head_contours_color = {
                comp: ic_label_cmap[label] for comp, label in ic_labels.items()
            }
            data.topo_values.index = list(ic_labels.keys())
        return data

    def load_recording(self, montage, ica, ic_labels):
        """Load the object to be plotted."""
        data = self.init_vars(montage, ica, ic_labels)
        super(TopoVizICA, self).set_data(montage, data, None)


#encoding:utf-8

from .models import Host
from datetime import datetime

class Validator(object):
    @classmethod
    def is_interger(cls,value):
        try:
            int(value)
            return True
        except BaseException as e:
            return False

class Host_Valid(Validator):   #这里都是view.py在调用的

    @classmethod
    def valid_update_asset(cls,params):
        is_valid = True
        errors = {}
        host = None
        try:
            host = Host.objects.get(pk=params.get('id','').strip())
        except BaseException as e:
            errors['id'] = '主机信息不存在'
            is_valid = False
            return is_valid, host, errors
        print(host.cpu)
        # return is_valid, host, errors
        name = params.get('name', '').strip()
        if not cls.valid_name_unique(name, host.id):
            errors['name'] = '主机名已存在'
            is_valid = False
        else:
            host.name = name

        ip = params.get('ip', '0').strip()
        host.ip = ip
        # if not ip.isdigit():
        #     errors['ip'] = 'IP格式错误'
        #     is_valid = False
        # else:
        #     host.ip = int(ip)
        host.mac = int(params.get('mac', '0'))  # w文件列表sex的值是整型，要不是整型，性别都为男
        host.os = params.get('os', '0')
        host.arch = params.get('arch', '0')
        host.mem = params.get('mem', '0')
        host.cpu = params.get('cpu', '0')
        host.disk = params.get('disk', '0')
        host.create_time = params.get('create_time', '0')
        host.last_time = params.get('last_time', '0')
        return is_valid, host, errors

    @classmethod
    def valid_name_unique(cls,name, uid):
        host = None
        try:
            host = Host.objects.get(name=name)
        except BaseException as e:
            pass
        if host is None:
            return True
        else:
            return str(host.id) == str(uid)  # 传进来是字符串类型，数据库是


from discord.ext.commands import has_permissions, MissingPermissions
from discord.ext import commands
import discord

import asyncio
import time
import json
import aiofiles

client = commands.Bot(command_prefix="!")
client.remove_command(name="help")

client.ticket_configs = {}

@client.event
async def on_ready():

    data = read_json("blacklist")
    client.blacklisted_users = data["blacklistedUsers"]

    for file in ["ticket_configs.txt"]:
        async with aiofiles.open(file, mode="a") as temp:
            pass

    async with aiofiles.open("ticket_configs.txt", mode="r") as file:
        lines = await file.readlines()
        for line in lines:
            data = line.split(" ")
            client.ticket_configs[int(data[0])] = [int(data[1]), int(data[2]), int(data[3])]

    print("Bot Is Ready.")

def read_json(filename):
    with open(f"{filename}.json","r") as file:
        data = json.load(file)
    return data

def write_json(data, filename):
    with open(f"{filename}.json", "w") as file:
        json.dump(data, file, indent=4)

@client.command()
async def help(ctx):
    embed=discord.Embed(title="Ticket Bot",description="Make sure the category has the permission `View channels` off.")
    embed.add_field(name="`!setup [message ID] [category ID]`",value="Setups the ticket system.",inline=False)
    embed.add_field(name="`!config`",value="Shows the ticket systems configuration.")
    embed.add_field(name="`!blacklist [@user]`",value="Blacklist mentioned user from creating a ticket.",inline=False)
    embed.add_field(name="`!unblacklist [@user]`",value="Unblacklist a blacklisted user.",inline=False)
    embed.set_footer(text="Made by ritz#8888")

    await ctx.send(embed=embed)

@client.command()
@commands.has_permissions(administrator=True)
async def config(ctx):
    try:
        msg_id, channel_id, category_id = client.ticket_configs[ctx.guild.id]

    except KeyError:
        embed=discord.Embed(title="Ticket Error",description="Ticket system has not been setup.",color=discord.Color.red())
        embed.set_footer(text="Made by ritz#8888")
        await ctx.send(embed=embed)

    else:
        embed=discord.Embed(title="Ticket System",description=f"**Message ID:** {msg_id}\n**Category ID:** {category_id}")
        embed.set_footer(text="Made by ritz#8888")
        await ctx.send(embed=embed)

@client.event
async def on_raw_reaction_add(payload):

    if payload.member.id in client.blacklisted_users:
        return

    if payload.member.id != client.user.id and str(payload.emoji) == u"\U0001F3AB":
        msg_id, channel_id, category_id = client.ticket_configs[payload.guild_id]

        if payload.message_id == msg_id:
            guild = client.get_guild(payload.guild_id)

            for category in guild.categories:
                if category.id == category_id:
                    break

            channel = guild.get_channel(channel_id)

            ticket_num = 1 if len(category.channels) == 0 else int(category.channels[-1].name.split("-")[-1]) + 1
            ticket_channel = await category.create_text_channel(f"ticket {ticket_num}", permission_synced=True)

            await ticket_channel.set_permissions(payload.member, read_messages=True, send_messages=True)

            message = await channel.fetch_message(msg_id)
            await message.remove_reaction(payload.emoji, payload.member)

            embed=discord.Embed(title="Ticket Opened",description=f"Support will be with you shortly. Use `!close` to close the ticket.",color=discord.Color.green())
            embed.set_footer(text="Made by ritz#8888")
            await ticket_channel.send(f"{payload.member.mention} Welcome", embed=embed)

            try:
                await client.wait_for("message", check=lambda m: m.channel == ticket_channel and m.content == "!close")

            except:
                pass

            else:
                time.sleep(.5)
                await ticket_channel.delete()

@client.command()
@commands.has_permissions(administrator=True)
async def setup(ctx,msg: discord.Message=None, category: discord.CategoryChannel=None):
    if msg is None or category is None:
        embed=discord.Embed(title="Ticket Error",description="Argument(s) was not given or was invalid.",color=discord.Color.red())
        embed.set_footer(text="Made by alter#6000")
        await ctx.channel.send(embed=embed)
        return

    client.ticket_configs[ctx.guild.id] = [msg.id, msg.channel.id, category.id]

    async with aiofiles.open("ticket_configs.txt", mode="r") as file:
        data = await file.readlines()

    async with aiofiles.open("ticket_configs.txt", mode="w") as file:
        await file.write(f"{ctx.guild.id} {msg.id} {msg.channel.id} {category.id}\n")

        for line in data:
            if int(line.split(" ")[0]) != ctx.guild.id:
                await file.write(line)

    await msg.add_reaction(u"\U0001F3AB")

    embed=discord.Embed(title="Ticket Success",description="Ticket system successfully setup.",color=discord.Color.green())
    embed.set_footer(text="Made by ritz#8888")
    await ctx.channel.send(embed=embed)

@client.command()
@commands.has_permissions(administrator=True)
async def blacklist(ctx, user: discord.Member):
    if user == ctx.message.author:
        embed=discord.Embed(title="Blacklist Error",description="You can't blacklist yourself.",color=discord.Color.red())
        await ctx.send(embed=embed)
    else:
        try:
            client.blacklisted_users.append(user.id)
            data = read_json("blacklist")
            data["blacklistedUsers"].append(user.id)
            write_json(data, "blacklist")
            embed=discord.Embed(title="User Blacklisted!",description=f"{user.mention} Has Been Blacklisted.",color=discord.Color.green())
            embed.set_footer(text="Made by ritz#8888")
            await ctx.send(embed=embed)
        except:
            embed=discord.Embed(title="Blacklist Error",description="Can't find mentioned user.",color=discord.Color.red())
            embed.set_footer(text="Made by ritz#8888")
            await ctx.send(embed=embed)

@client.command()
@commands.has_permissions(administrator=True)
async def unblacklist(ctx, user: discord.Member):
    try:
        client.blacklisted_users.remove(user.id)
        data = read_json("blacklist")
        data["blacklistedUsers"].remove(user.id)
        write_json(data, "blacklist")
        embed=discord.Embed(title="User Unblacklisted!",description=f"{user.mention} Has Been Unblacklisted.",color=discord.Color.green())
        embed.set_footer(text="Made by ritz#8888")
        await ctx.send(embed=embed)
    except:
        embed=discord.Embed(title="Unblacklist Error",description="Mentioned user is not blacklisted.",color=discord.Color.red())
        embed.set_footer(text="Made by ritz#8888")
        await ctx.send(embed=embed)

client.run("")


#coding:utf-8

'''
定义一个上报电瓶采样协议的类
'''

from lib.protocol.report.ProtocolBase import ProtocolBase

class VoltageDataReport_protocol(ProtocolBase):
    def __init__(self,WATER_CODE = "0002",DEV_ID = "M121501010001",sampleNums=1,sampleData=[{"sampleTime":"2020-04-09 16:20:22","voltage":12}]):
        super().__init__()
        self.WATER_CODE = int(WATER_CODE);                            # 设置默认消息流水号
        self.DEV_ID = DEV_ID                                          # 设置默认设备id

        self.sampleNums = sampleNums                                  #采样个数
        self.sampleData = sampleData                                  #采样数据

    #####################################################
    #               生成终端登录消息
    #####################################################
    def generateMsg(self):
        self.getProtocalHeader()
        info = ""
        HEADER = "4040"                                                        # 消息头
        WATER_CODE = self.getWaterCode(self.WATER_CODE)                        # 消息流水号
        DEV_ID = self.devid2hexString(self.DEV_ID)                             # 设备id
        FUN_ID = "000A"                                                        # 功能id(终端登录功能id)

        data = self.generateData()                                             # 数据段

        LENGTH = self.getMsgLength(int(len(WATER_CODE + DEV_ID + FUN_ID + data) / 2))   # 消息长度
        info += HEADER
        info += LENGTH
        info += WATER_CODE
        info += DEV_ID
        info += FUN_ID
        info += data
        CHECK_CODE = self.getCheckCode(info)                                   # 校验字段
        info += CHECK_CODE
        return info

    #####################################################
    #               创建终端登录数据段
    #####################################################
    def generateData(self):
        data = ""
        sampleNums = self.int2hexStringByBytes(self.sampleNums)
        data = data + sampleNums
        for i in range(0,self.sampleNums):
            sampleData = self.getUTCTimeHex(self.sampleData[i]["sampleTime"]) + self.int2hexStringByBytes(int(self.sampleData[i]["voltage"]),2)
            data = data + sampleData
        return data

if __name__ == "__main__":
    print(VoltageDataReport_protocol().generateMsg())


import math, os, arcade
from . import car_vis
from . import traffic_light_vis
from . import cross
from Simulator.simulator import Simulator

car_list = arcade.SpriteList(use_spatial_hash=False)
boundary_x, boundary_y = 1400, 1600

def setup(simulator):
	global s, light_list, offset_x, offset_y, zoom, cross_tex
	offset_x, offset_y, zoom = 0, 0, 1
	s = simulator
	light_list = arcade.SpriteList(use_spatial_hash=False)
	for dic in s.get_traffic_lights():
		light = traffic_light_vis.Traffic_light(dic['id'], (dic['coords'][0]*12),
					(dic['coords'][1]*12), dic['rotation'])
		light_list.append(light)
	cross.create_cross_png(s.get_roads())
	cross_tex = arcade.load_texture(os.path.dirname(os.path.abspath(__file__)) + "/sprites/cross.png")
	car_vis.setup_textures()

def update_resolution(width_scaling, height_scaling):
	global WIDTH, HEIGHT, offset_x, offset_y
	global light_list
	WIDTH = width_scaling
	HEIGHT = height_scaling

	car_vis.update_scaling(round(min(WIDTH,HEIGHT)*zoom, 2))
	traffic_light_vis.update_textures(WIDTH, HEIGHT, zoom)
	update_offset(0, 0)

	for light in light_list:
		light.center_x = WIDTH*(light.pos_x*zoom+790+offset_x)
		light.center_y = HEIGHT*(light.pos_y*zoom+360+offset_y)

def update_offset(dx, dy):
	global offset_x, offset_y
	offset_x += dx/WIDTH
	offset_y += dy/HEIGHT

	if offset_x > boundary_x*zoom:
		offset_x = boundary_x*zoom
	elif offset_x < -boundary_x*zoom:
		offset_x = -boundary_x*zoom
	if offset_y > boundary_y*zoom:
		offset_y = boundary_y*zoom
	elif offset_y < -boundary_y*zoom:
		offset_y = -boundary_y*zoom

	for light in light_list:
		light.center_x = WIDTH*(light.pos_x*zoom+790+offset_x)
		light.center_y = HEIGHT*(light.pos_y*zoom+360+offset_y)

def update_zoom(scroll_y):
	global zoom
	zoom += scroll_y/10
	zoom = max(0.1, min(zoom, 2))
	car_vis.update_scaling(round(min(WIDTH,HEIGHT)*zoom, 2))

	traffic_light_vis.update_textures(WIDTH, HEIGHT, zoom)
	for light in light_list:
		light.center_x = WIDTH*(light.pos_x*zoom+790+offset_x)
		light.center_y = HEIGHT*(light.pos_y*zoom+360+offset_y)

def draw_loop():
	try:
		cross_tex.draw(WIDTH*(790+offset_x), HEIGHT*(360+offset_y), WIDTH*zoom*3400, HEIGHT*zoom*3400)
		car_list.draw()
		light_list.draw()
	except:
		print("Texture too large")

	#debug function: displays debug messages at specified coordinates
	logs = s.get_debug_log()
	for log in logs:
		x = log[0][0]
		y = log[0][1]
		message = log[1]
		arcade.draw_text(f"{message}", WIDTH*(x*12+790+offset_x), HEIGHT*(y*12+360+offset_y), arcade.color.RED, 20)

def on_update(step_size):
	s.update(step_size)

	cars = s.get_cars()

	# Get IDs for each car from simulator
	dic_id = set(curr["id"] for curr in cars)

	# Remove cars no longer in the intersection
	for car in car_list:
		if car.id not in dic_id:
			car.kill()

	# Get IDs for each from visualiser
	car_id = set(car.id for car in car_list)

	# for dic in cars:
	# 	if dic["id"] not in car_id:
	# 		car_list.append(car_vis.Car(dic["id"]))

	id_to_car_vis = {car.id:car for car in car_list}

	# Update each car in car list, add new ones if they don't exist yet
	for dic in cars:

		# Add car if it has not been added
		dic_id = dic['id']
		if dic_id not in id_to_car_vis:
			new_car = car_vis.Car(dic_id)
			car_list.append(new_car)
			id_to_car_vis[dic_id] = new_car

		# Update cars
		id_to_car_vis[dic_id].update(
			WIDTH*(dic["coords"][0]*zoom*12+790+offset_x),
			HEIGHT*(dic["coords"][1]*zoom*12+360+offset_y),
			dic["rotation"],
			dic["braking"],
			dic["turn_signal"],
			dic["type"]
		)

	for dic in s.get_traffic_lights():
		for light in light_list:
			if light.id == dic['id']:
				light.update(dic['phase'])


import socket
import sys
import os
from lib.medoo import Medoo
from lib.switch import Switch
import math

def salvaInCronologia(expression, result):
    db.insert('cronologia', {"expression": expression, "result": result})  # Inserisci nella tabella cronologia del
    # database l'espressione e il suo risultato

def Risposta(r):
    risultato = r  # Inizializzazione risultato
    clear = False  # Inizializzazione variabile
    operators = ['×', '÷', '+', '-', '√']  # Lista degli operatori
    while not clear:  # Finchè l'espressione non è stata analizzata tutta, allora...
        for operator in operators:  # ... per ogni operatore della lista operators ...
            trovato = r.find(operator)  # trova l'operatore nella stringa
            if trovato != -1:  # Se l'operatore è stato trovato...
                l = r.split(operator)  # Dividi la stringa in base all'operatore
                if operator == "-" and not l[0]:  # Se l'operatore è il - e se l'elemento in prima posizione
                    # dell'espressione è vuoto (ad esempio: -2-1 --> l = ["", "2", "1"]
                    del l[0]  # elimina quell'elemento
                    l[0] = -float(l[0])  # trasforma il nuovo primo elemento in un float (numero decimale) negativo
                for p, e in enumerate(l):  # Per ogni elemento (e la sua posizione) nell'espressione:
                    if type(e) == str:  # se l'elemento attuale è una stringa ...
                        e = e.replace(",",
                                      ".")  # ... sostituisci tutte le virgole con dei punti (per la trasformazione in stringa)
                    l[p] = float(e)  # Trasforma l'elemento in float
                with Switch(operator) as case:  # Switch (controlla che l'operatore sia uguale a...
                    if case(operators[0]):  # Primo operatore nella lista (multiply) + calcolo
                        risultato = 1
                        for x in l:
                            risultato = risultato * x
                    elif case(operators[1]):  # Secondo operatore nella lista (divide) + calcolo
                        risultato = l[0]
                        for p, x in enumerate(l):
                            if p == 0:
                                continue
                            risultato = risultato / x
                    elif case(operators[2]):  # Terzo operatore nella lista (plus) + calcolo
                        risultato = sum(l)
                    elif case(operators[3]):  # Quarto operatore nella lista (minus) + calcolo
                        for p, e in enumerate(l):
                            if p != 0 and float(e) > 0:
                                l[p] = -float(e)
                        risultato = sum(l)
                    elif case(operators[4]):  # Quinto operatore nella lista (square root) + calcolo
                        risultato = math.sqrt(float(l[1]))
                clear = True  # Quando il ciclo è concluso, imposta la variabile clear a True
                # (l'espressione è stata analizzata)
    salvaInCronologia(r, risultato)  # Salva nella cronologia l'espressione e il risultato
    return risultato

# Apertura database (viene creato se non esiste già il file) e creazione tabelle se non esistono già
if not (os.path.exists(os.path.expanduser('~/Documents/RAMCalc'))):
    os.makedirs(os.path.expanduser('~/Documents/RAMCalc'))
    open(os.path.expanduser('~/Documents/RAMCalc/db.db'), "w").close()  # Creazione file database
db = Medoo('sqlite', database=os.path.expanduser('~/Documents/RAMCalc/db.db'))
query = open("tables.sql")
db.connection.executescript(query.read())
query.close()

s = socket.socket()
hostname = socket.gethostname()
ip = socket.gethostbyname(hostname)
try:
    if sys.argv[1] == "--localhost":
        ip = "127.0.0.1"
except IndexError:
    pass
# Check if a server already exists
try:
    s.bind((ip, 8888))
except OSError:  # otherwise
    exit()
print("L'indirizzo ip di questo server è: {}".format(ip))
s.listen(100)
conn, ip_client = s.accept()
while True:
    r = conn.recv(100)
    richiesta = r.decode()
    add = Risposta(richiesta)
    add = str(add)
    conn.send(add.encode())


from __future__ import print_function # python3 print function

__author__   = 'Joseph Cheng <indiejoseph@gmail.com>'
__version__  = '0.1'

import os
import pickle
from tabulate import tabulate
from data_prepare import YahooHistorical
from datetime import date, datetime
import numpy as np
from itertools import cycle
from sys import stdout
import matplotlib.pyplot as plt
from scipy import random
from scipy.signal import argrelextrema
from pybrain.supervised import RPropMinusTrainer, BackpropTrainer
from pybrain.datasets import SequentialDataSet
from pybrain.tools.shortcuts import buildNetwork
from pybrain.structure.modules import LSTMLayer, SigmoidLayer, LinearLayer, TanhLayer, SoftmaxLayer
from pybrain.tools.validation import testOnSequenceData
from pybrain.structure.modules.neuronlayer import NeuronLayer
from pybrain.tools.xml.networkwriter import NetworkWriter
from pybrain.tools.xml.networkreader import NetworkReader

random.seed(42)

def ir(p, i, data): # p-days, i=current day
  a = np.sum([n['adj_close'] for n in data[i:i+p]]) / p
  c = data[i]['adj_close']
  return ((a - c) / c)

# prepare date
symbol = '^HSI'
yahoo_data = YahooHistorical()
yahoo_data.open(os.path.join(os.path.dirname(__file__), 'data/' + symbol + '.csv'))
training_set = np.array([n for n in yahoo_data.data if n['date'] >= date(2007, 1, 1) and n['date'] <= date(2013, 12, 31)])
test_set = np.array([n for n in yahoo_data.data if n['date'] >= date(2014, 1, 1) and n['date'] <= date(2015, 12, 31)])
rsi = yahoo_data.relative_strength(n=14)
(sma13, sma7, macd) = yahoo_data.moving_average_convergence(7, 13) # 7 days and 13 days moving average and MACD
test_label = []
training_label = [n['date'] for n in training_set]
training_list = np.array([n['adj_close'] for n in training_set])
training_target = np.zeros(len(training_list))
test_list = np.array([n['adj_close'] for n in test_set])
test_target = np.zeros(len(test_list))
test_target[list(argrelextrema(test_list, np.greater)[0])] = 1
test_target[list(argrelextrema(test_list, np.less)[0])] = -1
training_target[list(argrelextrema(training_list, np.greater)[0])] = 1
training_target[list(argrelextrema(training_list, np.less)[0])] = -1
(tmax50, tmin50) = yahoo_data.trading_range_breakout(50)
(tmax100, tmin100) = yahoo_data.trading_range_breakout(100)
(tmax200, tmin200) = yahoo_data.trading_range_breakout(200)
(training_list, tmean, tstd) = normalize([[n['open'], n['high'], n['low'], n['adj_close']] for n in training_set])
(test_list, tmean, tstd) = normalize([[n['open'], n['high'], n['low'], n['adj_close']] for n in test_set], tmean, tstd)
(tmax50, tmean, tstd) = normalize(tmax50, tmean, tstd)
(tmin50, tmean, tstd) = normalize(tmin50, tmean, tstd)
(tmax100, tmean, tstd) = normalize(tmax100, tmean, tstd)
(tmin100, tmean, tstd) = normalize(tmin100, tmean, tstd)
(tmax200, tmean, tstd) = normalize(tmax200, tmean, tstd)
(tmin200, tmean, tstd) = normalize(tmin200, tmean, tstd)
(sma7, s20mean, s20std) = normalize(sma7, tmean, tstd)
(sma13, s100mean, s100std) = normalize(sma13, tmean, tstd)
(macd, macdmean, macdstd) = normalize(macd)
(rsi, rsimean, rsistd) = normalize(rsi)
dlen = len(training_list)

# plt.grid(True)
# plt.plot(training_label, [n[3] for n in training_list], color="blue", label=symbol)
# plt.plot(training_label, rsi[-dlen:], color=random.rand(3,1), label='RSI')
# plt.plot(training_label, macd[-dlen:], color=random.rand(3,1), label='MACD')
# plt.plot(training_label, rsi[-dlen:], color=random.rand(3,1), label='RSI')
# plt.plot(training_label, sma7[-dlen:], color=random.rand(3,1), label='EMA7')
# plt.plot(training_label, sma13[-dlen:], color=random.rand(3,1), label='EMA13')
# plt.plot(training_label, tmax50[-dlen:], color=random.rand(3,1), label='tmax50')
# plt.plot(training_label, tmin50[-dlen:], color=random.rand(3,1), label='tmin50')
# plt.plot(training_label, tmax100[-dlen:], color=random.rand(3,1), label='tmax100')
# plt.plot(training_label, tmin100[-dlen:], color=random.rand(3,1), label='tmin100')
# plt.plot(training_label, tmax200[-dlen:], color=random.rand(3,1), label='tmax200')
# plt.plot(training_label, tmin200[-dlen:], color=random.rand(3,1), label='tmin200')
# plt.legend()
# plt.show()

# build network
# net = buildNetwork(14, 54, 1, hiddenclass=LSTMLayer, outclass=TanhLayer, outputbias=False, recurrent=True)
net = NetworkReader.readFrom('target_weight.xml')

net.randomize()

# build sequential dataset
train_ds = SequentialDataSet(14, 1)

for n, r, m, m7, m13, tx50, tn50, tx100, tn100, tx200, tn200, target in zip(training_list, rsi[-dlen:], macd[-dlen:], sma7[-dlen:], sma13[-dlen:], tmax50[-dlen:], tmin50[-dlen:], tmax100[-dlen:], tmin100[-dlen:], tmax200[-dlen:], tmin200[-dlen:], training_target):
  i = np.append(n, [r, m, m7, m13, tx50, tn50, tx100, tn100, tx200, tn200])
  train_ds.addSample(i, target)

# train network
trainer = RPropMinusTrainer(net, dataset=train_ds)
# trainer = BackpropTrainer(net, dataset=train_ds)
train_errors = [] # save errors for plotting later
EPOCHS_PER_CYCLE = 100
CYCLES = 20

EPOCHS = EPOCHS_PER_CYCLE * CYCLES
for i in xrange(CYCLES):
  trainer.trainEpochs(EPOCHS_PER_CYCLE)
  train_errors.append(trainer.testOnData())
  epoch = (i+1) * EPOCHS_PER_CYCLE
  print("\r epoch {}/{}".format(epoch, EPOCHS), end="")
  stdout.flush()

# test output
sell_list = []
buy_list = []
sell_label = []
buy_label = []
actual_list = []
IRs = { 7: 0, 5: 0, 3: 0 }
IRb = { 7: 0, 5: 0, 3: 0 }
tlen = len(test_list)

for i, (n, r, m, m7, m13, tx50, tn50, tx100, tn100, tx200, tn200) in enumerate(zip(test_list, rsi[-tlen:], macd[-tlen:], sma7[-tlen:], sma13[-tlen:], tmax50[-tlen:], tmin50[-tlen:], tmax100[-tlen:], tmin100[-tlen:], tmax200[-tlen:], tmin200[-tlen:])):
  date = test_set[i]['date']
  o = net.activate([n[0], n[1], n[2], n[3], r, m, m7, m13, tx50, tn50, tx100, tn100, tx200, tn200])

  if o >= 0.99:
    sell_label.append(date)
    sell_list.append(n[3])
    for p in [7, 5, 3]:
      IRs[p] += ir(p, i, test_set)
  elif o <= -0.99:
    buy_label.append(date)
    buy_list.append(n[3])
    for p in [7, 5, 3]:
      IRb[p] += ir(p, i, test_set)

  test_label.append(date)
  actual_list.append(n[3])

IRba = ((IRb[7] + IRb[5] + IRb[3]) / 3) * 100
IRsa = ((IRs[7] + IRs[5] + IRs[3]) / 3) * 100

print("\r")
print(tabulate([
  ['IRb(%)', (IRb[7] * 100), (IRb[5] * 100), (IRb[3] * 100), IRba],
  ['IRs(%)', (IRs[7] * 100), (IRs[5] * 100), (IRs[3] * 100), IRsa],
  ['Gain(%)', IRba + IRsa, '', '', '']
], headers=['', 'P = 7', 'P = 5', 'P = 3', 'average']))

# export network
NetworkWriter.writeToFile(net, 'target_weight.xml')

# draw plot
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax1.plot(range(0, EPOCHS, EPOCHS_PER_CYCLE), train_errors)
ax1.set_title('Error')
ax2 = fig.add_subplot(212)
ax2.grid(True)
ax2.set_title('Predict')
ax2.plot(test_label, actual_list, color="blue", label="Acutal")
ax2.fill_between(test_label, actual_list, -1, color="blue", alpha=.15)
ax2.plot(test_label, sma7[-len(test_label):], color="cyan", label="EMA(20)")
ax2.plot(test_label, sma13[-len(test_label):], color="red", label="EMA(100)")
ax2.plot(test_label, macd[-len(test_label):], color="orange", label="MACD")
ax2.plot(test_label, rsi[-len(test_label):], color="pink", label="RSI")
ax2.plot(test_label, tmax50[-len(test_label):], color="tomato", label="TRBx50")
ax2.plot(test_label, tmin50[-len(test_label):], color="tan", label="TRBn50")
ax2.plot(test_label, tmax100[-len(test_label):], color="olive", label="TRBx100")
ax2.plot(test_label, tmin100[-len(test_label):], color="deeppink", label="TRBn100")
ax2.plot(test_label, tmax200[-len(test_label):], color="maroon", label="TRBx200")
ax2.plot(test_label, tmin200[-len(test_label):], color="skyblue", label="TRBn200")
plt.scatter(sell_label, sell_list, color="b", marker="o", label="Sell")
plt.scatter(buy_label, buy_list, color="r", marker="*", label="Buy")
ax2.legend()

plt.show()


# coding: utf-8
# !/usr/bin/env python
import os
from setuptools import setup, find_packages

__doc__ = """App for Django featuring improved form base classes."""

project_name = 'django-subscribe-form'
app_name = 'subscribe_form'

version = '0.0.5'

ROOT = os.path.dirname(__file__)

def read(fname):
    return open(os.path.join(ROOT, fname)).read()

try:
    import pypandoc

    long_description = pypandoc.convert('README.md', 'rst')
except ImportError:
    long_description = read('README.md')

packages = [package for package in find_packages() if package.startswith(app_name)]
setup(
    name=project_name,
    version=version,
    description=__doc__,
    long_description=long_description,
    url="https://github.com/Apkawa/django-subscribe-form",
    author="Apkawa",
    author_email='apkawa@gmail.com',
    packages=packages,
    install_requires=['six'],
    zip_safe=False,
    include_package_data=True,
    keywords=['django'],
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Framework :: Django',
        'Framework :: Django :: 1.8',
        'Framework :: Django :: 1.9',
        'Framework :: Django :: 1.10',
        'Framework :: Django :: 1.11',
        'Framework :: Django :: 2.0',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Topic :: Internet :: WWW/HTTP',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
    ],
)


from collections import defaultdict
class WordDictionary:
    def __init__(self):
        self.words = defaultdict(set)
    def addWord(self, word):
        self.words[len(word)].add(word)

    def search(self, word):
        for i in self.words[len(word)]:
            for x,c in enumerate(word):
                print(i[x])
                if c not in ['.',  i[x]]:
                    break
            # any_mismatch = any(word[x] != '.' and word[x] != i[x]  for x in range(len(word)))
                else:
                    return True
        return False

obj=WordDictionary()
obj.addWord("bad")
obj.addWord("dad")
obj.addWord("mad")
obj.addWord("hello")
print(obj.words)
print(obj.search("pad"))
print(obj.search("bad"))
print(obj.search(".ad"))
print(obj.search("b.."))


import requests
from datetime import datetime

PIXELA_ENDPOINT = "https://pixe.la/v1/users"
USERNAME = "kleber"
TOKEN = "TOKENpixela-12345"
GRAPH_ID = "graph1"

user_params = {
    "token": TOKEN,
    "username": USERNAME,
    "agreeTermsOfService": "yes",
    "notMinor": "yes"
}

# Create user
# response = requests.post(url=PIXELA_ENDPOINT, json=user_params)
# print(response.text)

GRAPH_ENDPOINT = f"{PIXELA_ENDPOINT}/{USERNAME}/graphs"

DELETE_ENDPOINT = f"{PIXELA_ENDPOINT}/{USERNAME}/graphs/{GRAPH_ID}"

graph_config = {
    "id": GRAPH_ID,
    "name": "Gym Graph",
    "unit": "times",
    "type": "int",
    "color": "ajisai"
}

headers = {
    "X-USER-TOKEN": TOKEN
}

# Delete graph
# response = requests.delete(url=DELETE_ENDPOINT, headers=headers)
# print(response.text)

# Create graph
# response = requests.post(url=GRAPH_ENDPOINT, json=graph_config, headers=headers)
# print(response.text)

PIXEL_CREATION_ENDPOINT = f"{PIXELA_ENDPOINT}/{USERNAME}/graphs/{GRAPH_ID}"

today = datetime.now()
pixel_data = {
    "date": today.strftime("%Y%m%d"),
    "quantity": "1"
}

response = requests.post(url=PIXEL_CREATION_ENDPOINT, json=pixel_data, headers=headers)
print(response.text)


from InferenceMethods import forwardChaining, backwardChaining
from KnowledgeBase import KnowledgeBase
from Literal import Literal
from HornClause import HornClause

#Wumpus-Test : we want to demonstrate that, in a 3x2 world,  (2,2) contains a pit:

P11 = Literal("P11")
P12 = Literal("P22")
P21 = Literal("P21")
B11 = Literal("B11")
B12 = Literal("B12")
B21 = Literal("B21")
P22 = Literal("P22")
B22 = Literal("B22")
P31 = Literal("P31")
B32 = Literal("B32")

clauseP22 = HornClause(P22, [B21,B12])
clauseP11 = HornClause(P11,[B12,B21])
clauseP12 = HornClause(P12, [B11,B22])
clauseP21 = HornClause(P21, [B11,B22])
clauseB21 = HornClause(B21)
clauseB12 = HornClause(B12)
clauseB32 = HornClause(B32, [P22])
clauseP31 = HornClause(P31,[B21, B32])

KB = KnowledgeBase()
KB.addClause(clauseP11)
KB.addClause(clauseP12)
KB.addClause(clauseP21)
KB.addClause(clauseB21)
KB.addClause(clauseB12)
KB.addClause(clauseP22)
KB.addClause(clauseP31)
KB.addClause(clauseB32)

KB.printKB()
graph = KB.getANDORGraph()
graph.plotGraph(KB, [], "plots/ToyTest/WumpusTheoremProvingBefore.png")

query = KB.getLiteral("P22")

FC_results = forwardChaining(KB,query)
print("ForwardChaining resulted in: " + str(FC_results[0]))
graph.plotGraph(KB,FC_results[1], "plots/ToyTest/WumpusTheoremProvingFC_Processed.png")
BC_results = backwardChaining(KB,graph,query)
print("BackwardChaining resulted in: " + str(BC_results[0]))
graph.plotGraph(KB,BC_results[1], "plots/ToyTest/WumpusTheoremProvingBC_Processed.png")
if(BC_results[0]):
    print("With path: ", end='')
    counter = len(BC_results[2])
    for step in BC_results[2]:
        print(step, end='')
        counter -= 1
        if(counter != 0):
            print(",", end='')
    print("")

print("Forward_Chaining executed in: " + str(FC_results[2]) + " seconds")
print("Backward_Chaining executed in: " + str(BC_results[3]) + " seconds")
print("-----------------------------------------------------------------")

#West-Criminal Test
print("__________________________")
print("Beginning Criminal Test :")

American = Literal("American")
Criminal = Literal("Criminal")
Weapon= Literal("Weapon")
Missile = Literal("Missile")
Sells= Literal ("Sells")
Owns= Literal("Owns")
Hostile= Literal("Hostile")
Enemy= Literal("Enemy")

AmericanClause=HornClause(American)
MissileClause= HornClause(Missile)
OwnsClause= HornClause(Owns)
CriminalClause = HornClause(Criminal, [American, Weapon, Sells, Hostile])
WeaponClause= HornClause(Weapon, [Missile])
SellsClause= HornClause(Sells, [Missile, Owns])
EnemyClause= HornClause(Enemy)
HostileClause = HornClause(Hostile, [Enemy])

KB= KnowledgeBase()
KB.addClause(MissileClause)
KB.addClause(OwnsClause)
KB.addClause(CriminalClause)
KB.addClause(AmericanClause)
KB.addClause(WeaponClause)
KB.addClause(SellsClause)
KB.addClause(EnemyClause)
KB.addClause(HostileClause)

graph = KB.getANDORGraph()
graph.plotGraph(KB,[], "plots/ToyTest/CriminalTheoremProvingBefore.png")
KB.printKB()
query = KB.getLiteral("Criminal")

FC_results = forwardChaining(KB,query)
print("ForwardChaining resulted in: " + str(FC_results[0]))
graph.plotGraph(KB,FC_results[1], "plots/ToyTest/CriminalTheoremProvingFC_Processed.png")
BC_results = backwardChaining(KB,graph,query)
print("BackwardChaining resulted in: " + str(BC_results[0]))
graph.plotGraph(KB,BC_results[1], "plots/ToyTest/CriminalTheoremProvingBC_Processed.png")
if(BC_results[0]):
    print("With path: ", end='')
    counter = len(BC_results[2])
    for step in BC_results[2]:
        print(step, end='')
        counter -= 1
        if(counter != 0):
            print(",", end='')
    print("")

print("Forward_Chaining executed in: " + str(FC_results[2]) + " seconds")
print("Backward_Chaining executed in: " + str(BC_results[3]) + " seconds")
print("-----------------------------------------------------------------")


#!/usr/bin python

from random import randint
import time
import drop
import bucket

class Emitter:
	def __init__(self, y):
		self.y = y
		self.interval = randint(1, 10)
		self.startTime = time.time()
		self.ellapsedTime = 0
		self.drops = []
		self.dropCount = 0
		self.collision = []
		self.collided = False

	def generateSystem(self):
		self.ellapsedTime = time.time() - self.startTime
		if (self.ellapsedTime > self.interval):
			self.startTime = time.time()
			self.drops.append(drop.Drop(self.y))
			self.dropCount += 1
			self.collision.append(False)

		for i in range(len(self.drops)):
			self.drops[i].update()
			self.collision[i] = self.drops[i].reachedBottom(self.y, self.dropCount)
			if self.collision[i]:
				self.collided = True
				self.drops.pop(i)
			else:
				self.collided = False
			return self.collided


from __future__ import absolute_import, print_function, division, unicode_literals

import os
import json
import datetime

from flask import Blueprint, request, g, jsonify
from flask_restful import Api, Resource
from ..models import Media

from .appuser import get_current_user

media_api = Api(Blueprint("media_api", __name__))

def format_status_date(media):
    status_date = None
    if media.status_date is not None:
        status_date = media.status_date.isoformat()

    return status_date

@media_api.resource("/media")
class MediaAPI(Resource):

    @staticmethod
    def get():
        from ..app import db

        current_user = get_current_user()

        try:
            o = int(request.args.get('offset', 0))
            l = int(request.args.get('limit', 100))
        except:
            res = jsonify({"error": "Limit and offset must be integers"})
            res.status_code = 400
            return res

        period = request.args.get('time_period', 'all')
        query = db.session.query(Media).filter(Media.appuser == current_user)

        last_date = None
        if period == "day":
            last_date = datetime.datetime.now() - datetime.timedelta(days=1)
        elif period == "week":
            last_date = datetime.datetime.now() - datetime.timedelta(days=7)
        elif period == "month":
            last_date = datetime.datetime.now() - datetime.timedelta(days=30)

        if last_date is not None:
            query = query.filter(Media.status_date > (last_date))

        return {
            "count": db.session.query(Media).filter(Media.appuser == current_user).count(),
            "media": [
                {
                    "id": media.id,
                    "path": media.path,
                    "media_type": media.media_type,
                    "mime": media.mime,
                    "file_reference": media.file_reference,
                    "props": json.loads(media.props),
                    "image_hash": media.image_hash,
                    "status": media.status,
                    "status_date": format_status_date(media),
                    "status_detail": media.status_detail
                } for media in query[o:o+l]
            ]
        }

    @staticmethod
    def post():
        from ..app import db

        if g.appuser is None:
            j = jsonify({"error": "Not Authorized"})
            j.status_code = 401
            return j

        b = request.get_json()

        media = Media()
        media.path = os.path.abspath(b["path"])
        media.file_reference = b["file_reference"]
        media.appuser = g.appuser

        if "media_type" in b:
            media.media_type = b["media_type"]

        if "mime" in b:
            media.mime = b["mime"]

        if "image_hash" in b:
            media.image_hash = b["image_hash"]

        db.session.add(media)
        db.session.commit()

        return {
            "id": media.id,
            "path": media.path,
            "media_type": media.media_type,
            "mime": media.mime,
            "file_reference": media.file_reference,
            "props": json.loads(media.props),
            "image_hash": media.image_hash,
            "status": media.status,
            "status_date": format_status_date(media),
            "status_detail": media.status_detail
        }

    @staticmethod
    def delete():
        from ..app import db
        current_user = get_current_user()

        b = request.get_json()

        period = b.get('time_period', 'all')
        status = b.get("status")
        query = db.session.query(Media).filter(Media.appuser == current_user).filter(Media.status == status)

        last_date = None
        if period == "day":
            last_date = datetime.datetime.now() - datetime.timedelta(days=1)
        elif period == "week":
            last_date = datetime.datetime.now() - datetime.timedelta(days=7)
        elif period == "month":
            last_date = datetime.datetime.now() - datetime.timedelta(days=30)

        if last_date is not None:
            query = query.filter(Media.status_date > (last_date))

        for m in query:
            db.session.delete(m)
        db.session.commit()

        return ('', 204)

@media_api.resource("/media/<int:media_id>")
class MediaItemAPI(Resource):

    @staticmethod
    def get(media_id):
        from ..app import db

        media = Media.query.get_or_404(media_id)

        return {
            "id": media.id,
            "path": media.path,
            "media_type": media.media_type,
            "mime": media.mime,
            "file_reference": media.file_reference,
            "props": json.loads(media.props),
            "image_hash": media.image_hash,
            "status": media.status,
            "status_date": format_status_date(media),
            "status_detail": media.status_detail
        }

@media_api.resource("/media/status")
class MediaStatusAPI(Resource):

    @staticmethod
    def get():
        from ..app import db

        current_user = get_current_user()

        statuses = db.session.query(db.func.count('*').label(
            "c"), Media.status).filter(Media.appuser == current_user).group_by(Media.status).all()

        resp_d = {
            "count": db.session.query(Media).filter(Media.appuser == current_user).count()
        }

        for m in statuses:
            if m.status is None:
                resp_d["pending"] = m.c
            else:
                resp_d[m.status] = m.c

        return resp_d


import pkgutil
import sys

def save_pickled_compatible(obj_to_pickle, file_name):
    '''
        Save an object to the specified file in a backward compatible
        way for Pybind objects. See:
        http://pybind11.readthedocs.io/en/stable/advanced/classes.html#pickling-support
        and https://github.com/pybind/pybind11/issues/271
    '''
    try:
        import cPickle as pickle  # Use cPickle on Python 2.7
    except ImportError:
        import pickle
    data = pickle.dumps(obj_to_pickle, 2)
    with open(file_name, "wb") as handle:
        handle.write(data)

def load_pickled_compatible(file_name):
    '''
        Loads a pickled object from the specified file
    '''
    try:
        import cPickle as pickle  # Use cPickle on Python 2.7
    except ImportError:
        import pickle

    with open(file_name, "rb") as handle:
        data = handle.read()
        if not is_python3():
            return pickle.loads(data)
        else:
            return pickle.loads(data, encoding="bytes")

def is_numpy_installed():
    '''
        Returns True if Numpy is installed otherwise False
    '''
    if pkgutil.find_loader("numpy"):
        return True
    else:
        return False

def is_python3():
    '''
        Returns True if using Python 3 or above, otherwise False
    '''
    return sys.version_info >= (3, 0)