#Name: Anooshka Bajaj

#1
import pandas as pd
df=pd.read_csv(r'E:\landslide_dataset.csv')
pd.set_option('display.max_columns',50)        #to display all the columns
print(df.describe())                  #gives statistical values of the data
print(df[df.columns[2:]].mode())      #for finding out mode

#2

#2(a)
import matplotlib.pyplot as plt
attributes1=['temperature','humidity','pressure','lightavgw/o0','lightmax','moisture']
fig,axs=plt.subplots(nrows=3,ncols=2,figsize=(11,16))

r=0;c=0
for i in attributes1:
    x = df['rain']
    y=df[i]
    axs[r][c].scatter(x,y,color='red',marker='*')
    axs[r][c].set_title(i +' vs rain')
    axs[r][c].set_xlabel('rain')
    axs[r][c].set_ylabel(i)
    c+=1
    if c==2:
        r+=1;c=0

plt.show()

#2(b)
attributes2=['humidity','pressure','rain','lightavgw/o0','lightmax','moisture']
fig,axs=plt.subplots(nrows=3,ncols=2,figsize=(11,16))

r=0;c=0
for i in attributes2:
    x = df['temperature']
    y=df[i]
    axs[r][c].scatter(x,y,color='red',marker='*')
    axs[r][c].set_title(i +' vs temperature')
    axs[r][c].set_xlabel('temperature')
    axs[r][c].set_ylabel(i)
    c+=1
    if c==2:
        r+=1;c=0

plt.show()

#3

#3(a)
c1=df.corrwith(df['rain'])       #finding correlation coefficient with rain
print('Correlation Coeffecient of rain with:')
print(c1)

#3(b)
c2=df.corrwith(df['temperature'])   #finding correlation coefficient with temperature
print('Correlation Coefficient of temperature with:')
print(c2)

#4
plt.hist(df['rain'],label='rain')     #plotting histogram with rain
plt.xlabel('rain')
plt.ylabel('frequency')
plt.legend()
plt.show()

plt.hist(df['moisture'],label='moisture')     #plotting histogram with moisture
plt.xlabel('moisture')
plt.ylabel('frequency')
plt.legend()
plt.show()

#5
g=df.groupby('stationid')
fig,axs=plt.subplots(nrows=5,ncols=2,figsize=(11,30))
r=0;c=0
for i in g['rain']:
    axs[r][c].hist(i[1],label='rain')
    axs[r][c].set_title(i[0])
    axs[r][c].set_xlabel('Rain')
    axs[r][c].set_ylabel('Frequency')
    axs[r][c].legend()
    c+=1
    if c==2:
        r+=1;c=0

plt.show()

#6
df.boxplot(column=['rain'], figsize=(8,8))    #boxplot for rain
plt.ylabel('Amount of rainfall in ml')
plt.show()

df.boxplot(column=['moisture'], figsize=(8,8))     #boxplot for moisture
plt.ylabel('Moisture content in percentage')
plt.show()


######################################################
# Connectivity between 2 neurons
######################################################

from __future__ import division

from brian2 import *
import matplotlib.pylab as plt
import json

import os, sys
mod_path = os.path.abspath(os.path.join('..','0. Model'))
sys.path.append(mod_path)

from oo_Parameters import *
from oo_equations_AMPAplast import *
from oo_initScripts import set_init_nrn, set_init_syn
from MakeNeuron_AMPAplast import *
from MorphologyData import *

for zzz in range(1):
    start_scope()
    namestr = '30'
    print('>> filename will be '+namestr)

    ######################################################
    ## Load Morpho
    ######################################################
    #morph = '../0. Model/Branco2010_Morpho.swc'
    #morph_data = BrancoData
    #
    #dc = distal_compartments_Branco_eff
    #pc = proximal_compartments_Branco

    morph = '../0. Model/Acker2008.swc'
    morph_data = AckerData

    dc = distal_compartments_Acker_eff
    pc = proximal_compartments_Acker

    Theta_low = morph_data['thetalow']*mV

    #####################################################
    loc1 = 'all'           # synaptic location: choose prox (proximal), dist (distal), branch (one basal branch) or all (all basals)
    syn_arrange1 = 'distrib'  # synaptic arrangement: choose clust (clustered) or distrib (distributed)
    loc2 = 'all'           # synaptic location: choose prox (proximal), dist (distal), branch (one basal branch) or all (all basals)
    syn_arrange2 = 'distrib'  # synaptic arrangement: choose clust (clustered) or distrib (distributed)
    #####################################################

    t_max = 5*second

    init_weight = .5

    NrSyn = 15
    ampa_cond = 1000.*1e-12*siemens  # AMPA maximal conductance
    nmda_cond = 2000.*1e-12*siemens  # NMDA maximal conductance

    if loc1 == 'prox':
        compv1 = pc
    elif loc1 == 'dist':
        compv1 = dc
    elif loc1 == 'branch':
        ii = 0
        b = dc[int(np.random.rand(1)*len(dc))]
        compv1 = []
        while b-ii not in pc:
            compv1 = compv1 + [b-ii]
            ii = ii+1
    elif loc1 == 'all':
        compv1 = list(morph_data['basal'])
    else:
        print('ERROR: synaptic location key error')

    if syn_arrange1 == 'clust':
        syn_loc1 = np.array([int(np.random.rand(1)*len(compv1))]*NrSyn)
        saveloc1 = str(syn_loc1[0])
    elif syn_arrange1 == 'distrib':
        syn_loc1 = np.floor((np.random.rand(NrSyn)*len(compv1)))
        saveloc1 = str(int(syn_loc1[0]))
    else:
        print('ERROR: synaptic arrangement key error')

    if loc2 == 'prox':
        compv2 = pc
    elif loc2 == 'dist':
        compv2 = dc
    elif loc1 == 'branch':
        ii = 0
        b = dc[int(np.random.rand(1)*len(dc))]
        compv2 = []
        while b-ii not in pc:
            compv2 = compv2 + [b-ii]
            ii = ii+1
    elif loc2 == 'all':
        compv2 = list(morph_data['basal'])
    else:
        print('ERROR: synaptic location key error')

    if syn_arrange2 == 'clust':
        syn_loc2 = np.array([int(np.random.rand(1)*len(compv2))]*NrSyn)
        saveloc2 = str(syn_loc2[0])
    elif syn_arrange2 == 'distrib':
        syn_loc2 = np.floor((np.random.rand(NrSyn)*len(compv2)))
        saveloc2 = str(int(syn_loc2[0]))
    else:
        print('ERROR: synaptic arrangement key error')

    print('Start: '+loc1+'/'+syn_arrange1+saveloc1+' - '+loc2+'/'+syn_arrange2+saveloc2)

    ratesv = np.arange(0,20,2)
    storew = np.zeros((len(ratesv),len(ratesv),2*NrSyn))

    for rr1 in range(len(ratesv)):
        for rr2 in range(rr1,len(ratesv)):

            start_scope()
            print('scope')

            rate_1 = ratesv[rr1]
            rate_2 = ratesv[rr2]

            #####################################################
            # Create neuron
            #####################################################

            test_model = BRIANModel(morph)

            neuron = test_model.makeNeuron_Ca(morph_data)
            neuron.run_regularly('Mgblock = 1./(1.+ exp(-0.062*vu2)/3.57)',dt=defaultclock.dt)

            neuron2 = test_model.makeNeuron_Ca(morph_data)
            neuron2.run_regularly('Mgblock = 1./(1.+ exp(-0.062*vu2)/3.57)',dt=defaultclock.dt)

            print('Neurons created...')

            ######################################################
            ## create Synapses
            ######################################################
            #
            Syn_1 = Synapses(neuron,neuron2,
                            model= eq_1_plastAMPA,
                            on_pre = eq_2_plastAMPA,
                            method='heun'
                            )
            #
            #
            Syn_4 = Synapses(neuron2,neuron,
                            model= eq_1_plastAMPA,
                            on_pre = eq_2_plastAMPA,
                            method='heun'
                            )
            #
            for rr in range(NrSyn):
                    Syn_1.connect(i=0,j=neuron2[compv1[int(syn_loc1[rr])]:compv1[int(syn_loc1[rr])]+1])
            set_init_syn(Syn_1,init_weight)
            #
            #
            for rr in range(NrSyn):
                    Syn_4.connect(i=0,j=neuron[compv2[int(syn_loc2[rr])]:compv2[int(syn_loc2[rr])]+1])
            set_init_syn(Syn_4,init_weight)
            #
            print('Synapses created...')
            #

            #####################################################
            # Monitors
            #####################################################
            #M_soma = StateMonitor(neuron.main, ['v'], record=True)#, dt = 25*defaultclock.dt)
            #M_soma2 = StateMonitor(neuron2.main, ['v'], record=True)#, dt = 25*defaultclock.dt)

            ##M_in = StateMonitor(N_input, ['v'], record=True)#, dt = 25*defaultclock.dt)
            #
            #M_dend = StateMonitor(neuron[compv[0]:compv[0]+1], ['v'], record=True)
            #M_dend2 = StateMonitor(neuron2[compv[0]:compv[0]+1], ['v'], record=True)#, dt = 25*defaultclock.dt)

            #M_weights = StateMonitor(Syn_1,['wampa'],record=True, dt = 400*defaultclock.dt)
            #M_weights2 = StateMonitor(Syn_4,['wampa'],record=True, dt = 400*defaultclock.dt)

            #####################################################
            # Run
            #####################################################
            neuron.main.rate_v = 0*Hz
            neuron2.main.rate_v = 0*Hz
            run(500*ms)

            neuron.main.rate_v = rate_1*Hz
            neuron2.main.rate_v = rate_2*Hz
            print('Simulating...'+str(rr1)+' '+str(rr2))
            run(t_max)

            print('Simulation finished!')

            storew[rr1,rr2,:NrSyn] = Syn_1.wampa[:]
            storew[rr1,rr2,NrSyn:] = Syn_4.wampa[:]

            fname = loc1+'_'+syn_arrange1+'_'+namestr # 'testfile' #loc1+'_'+syn_arrange1+'_'+saveloc1+saveloc2+str(zzz)

#            data12 = open('ConnectData/AMPA_axonH2_'+str(NrSyn)+'_'+fname+'_LoHi.txt','w')
#            p1 = storew[:,:,:NrSyn]
#            json.dump(p1.tolist(),data12)
#            data12.close()
#
#            data1 = open('ConnectData/AMPA_axonH2_'+str(NrSyn)+'_'+fname+'_HiLo.txt','w')
#            p2 = storew[:,:,NrSyn:]
#            json.dump(p2.tolist(),data1)
#            data1.close()
#
#            data13 = open('ConnectData/AMPA_axonH2_'+str(NrSyn)+'_'+fname+'_loc1.txt','w')
#            p3 = syn_loc1
#            json.dump(p3.tolist(),data13)
#            data13.close()
#
#            data14 = open('ConnectData/AMPA_axonH2_'+str(NrSyn)+'_'+fname+'_loc2.txt','w')
#            p4 = syn_loc2
#            json.dump(p4.tolist(),data14)
#            data14.close()

    #####################################################
    # Plot
    #####################################################

    #plt.figure()
    #plt.pcolor(storew[:,:,0])
    #plt.colorbar()
    #plt.xticks(np.arange(0.5,len(ratesv),1),ratesv)
    #plt.yticks(np.arange(0.5,len(ratesv),1),ratesv)
    #plt.ylabel('pre (low)')
    #plt.xlabel('post (high)')
    #plt.title('low-high '+str(compv[0]))
    #
    #plt.figure()
    #plt.pcolor(storew[:,:,1])
    #plt.colorbar()
    #plt.xticks(np.arange(0.5,len(ratesv),1),ratesv)
    #plt.yticks(np.arange(0.5,len(ratesv),1),ratesv)
    #plt.ylabel('post (low)')
    #plt.xlabel('pre (high)')
    #plt.title('high-low '+str(compv[0]))
    #
    #plt.figure()
    #plt.pcolor(1*(storew[:,:,1]>.5)+2*(storew[:,:,0]>.5))
    #plt.colorbar()
    #plt.xticks(np.arange(0.5,len(ratesv),1),ratesv)
    #plt.yticks(np.arange(0.5,len(ratesv),1),ratesv)
    #plt.title('uni vs bidirectional '+str(compv[0]))

    #np.savetxt('ConnectData/AckerCONN'+str(NrSyn)+'_'+fname+'_LoHi.dat',storew[:,:,:NrSyn])
    #np.savetxt('ConnectData/AckerCONN'+str(NrSyn)+'_'+fname+'_HiLo.dat',storew[:,:,NrSyn:])

    #Mdend_max = np.amax(M_dend.v/mV,axis=0)

    #figure(figsize=(10, 4))
    ##plot(M_soma.t/ms, M_soma.v[0]/mV)
    #plot(M_dend.t/ms, M_dend.v[0]/mV)
    #plot(M_soma2.t/ms, M_soma2.v[0]/mV)
    #plot(M_dend2.t/ms, M_dend2.v[0]/mV)

    #figure(figsize=(10, 4))
    #plot(M_weights.t/ms, M_weights.wampa[0], linewidth=2)
    #plot(M_weights2.t/ms, M_weights2.wampa[0], linewidth=2)


import sys
sys.path.append('.')
sys.path.append('utils')
sys.path.append('../posenetpython')
import tensorflow
import multiprocessing
from custom_queue import Queue
import numpy as np, cv2
import time
import human_detector_pose_est as human_detector
import posenet, posenet_helper
import video_channels

# The idea is to only measure the timing for the pose estimation, which is done on the GPU
maxNumWorkers = 2
completionTime = np.zeros(maxNumWorkers)
numImsInTest = 100
myChannels = [ video_channels.channel('oxford','cache')]
cap = cv2.VideoCapture(myChannels[0].CapturePath)
frameCounter = 0

numFrames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))

if __name__ == "__main__":

    input_det_q = [Queue()]
    output_det_q = [Queue()]

    for numWorkers in range(1,maxNumWorkers+1):
        print('Testing with {:d} workers'.format(numWorkers))
        det_pool = multiprocessing.Pool(numWorkers, human_detector.GPU_worker, (input_det_q,output_det_q))
        # instead of an init we need to process the first image, before we can kick everything loose...
        input_image, _ = human_detector.scale_image_for_pose_model(np.zeros(myChannels[0].imSize,np.uint8))
        jobInfo = {"dummy":0}
        input_det_q[0].put((jobInfo, np.expand_dims(input_image,axis=0)))
        #input_det_q.put((0, int(0),0.0) + posenet_helper.scale_image_for_pose_model(np.zeros(myChannels[0].imSize,np.uint8)))
        while (output_det_q[0].empty()):
            time.sleep(0.01)
        output_det_q[0].get() # flush that first image

        # ready to start the test now
        jobsSent = 0
        jobsCompleted = 0
        startTime = time.time()
        while jobsCompleted < numImsInTest:
            while jobsSent < numImsInTest and input_det_q[0].qsize() < 5:
                   # add another job
                   r, img = cap.read()
                   timestamp = time.time()
                   input_image, _ = human_detector.scale_image_for_pose_model(img)
                   input_det_q[0].put((jobInfo, np.expand_dims(input_image,axis=0)))
                   frameCounter = (frameCounter + 1) % numFrames
                   if frameCounter == 0:
                       cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
                   jobsSent += 1
            # check the output queue now
            while not output_det_q[0].empty():
                output_det_q[0].get()
                jobsCompleted += 1
                if jobsCompleted % 10 == 0:
                    print('{:d} of {:d} jobs completed.'.format(jobsCompleted,numImsInTest))
            time.sleep(0.001)
        completionTime[numWorkers-1] = time.time() - startTime
        det_pool.terminate()

    cap.release()

    print('Test results for {:d} images:'.format(maxNumWorkers))
    for numWorkers in range(maxNumWorkers):
        print('With {:d} workers pose detection took {:.2f} seconds, {:.3f} seconds per frame.'.format(numWorkers+1,completionTime[numWorkers], completionTime[numWorkers] / numImsInTest))


import logging
import requests
import json

import candlepin as env

__author__ = "tcoufal"

def activate_pool(username, org_id, regnum, start_date):
    """
    Attach a SKU registration number to an account

    Runs a request to the Candlepin REST API in order to hook the account
    specified by the 'username' and the 'org_id' with the activation
    key 'regnum'.

    :param username: Account's username
    :param org_id: Organization identifier for the given account
    :param regnum: The subscription pool's identifier
    :param start_data: A date by which the entitlement should be effective
    """
    logging.debug("Started to activate Registration number {0}".format(regnum))

    activation_info = {
        "activationKey": regnum,
        "vendor": "REDHAT",
        "startDate": str(start_date),
        "userName": username,
        "webCustomerId": org_id,
        "systemName": "genie"
    }

    for attempt in range(env.RETRY):
        try:
            r = requests.post('{0}/activate'.format(env.REST_ACTIVATION),
                              headers={'content-type': 'application/json'},
                              data=json.dumps(activation_info))
            r.raise_for_status()
        except (requests.ConnectionError, requests.HTTPError) as e:
            logging.error("[Activate reg. number] Failed to active no. {0}:"
                          " {1}".format(regnum, e))
            continue

        if "Reg number product not active for SKU" in r.content:
            logging.error("[Activate reg. number] Failed to active no. {0}"
                          "".format(regnum))
            raise RuntimeError("Failed to active pool no. {0}".format(regnum))
        break
    else:
        logging.error("[Activate reg. number] out of retries")
        raise RuntimeError("Failed to active pool no. {0}".format(regnum))

    logging.info("[Activate reg. number] successful for no. {0}"
                 "".format(regnum))
    return True


from deprotocol.app.setup.setup import SetupABC
from deprotocol.app.logger import Logger
from deprotocol.network.peer_networking.node import Node

class P2PNodeSetup(SetupABC):
    def __init__(self, deprotocol, node_host, node_port):
        self.deprotocol = deprotocol
        self.node = None
        self.node_host = node_host
        self.node_port = node_port

    def setup(self):
        # Start Node
        self.node = Node(self.deprotocol, self.node_host, self.node_port)
        self.node.start()
        Logger.get_logger().info(f"Node started correctly! Host:Port -> {self.node_host}:{self.node_port}")


import matplotlib.pyplot as plt
import numpy as np
from icecream import ic

# Fixing random state for reproducibility
np.random.seed(19680801)

fig, axs = plt.subplots(2, 2)
cmaps = ['hot_r','RdBu_r', 'viridis'] # 代表两种颜色
ic(np.random.random((5, 5)))
for col in range(2):
    for row in range(2):
        ic(col,row)
        ax = axs[row, col]
        pcm = ax.pcolormesh([[0.5,0.25],[0,20]],
                            cmap=cmaps[col])
        fig.colorbar(pcm, ax=ax)

plt.show()
plt.savefig('plot_test.png')


# import dependencies
import numpy as np

#===============================================================================
# Split
#===============================================================================

def check_for_imbalanced_data(DF, **kwargs):
    """Checks the array is imbalanced. Returns a dictionary with keys, ['imbalanced', 'bincount', 'unique']; its values are whether the data set is imbalanced and the bincount and unique arrays, which are both sorted by bincount."""

    # options
    threshold = kwargs['threshold'] if 'threshold' in kwargs else 0.2
    verbose = kwargs['verbose'] if 'verbose' in kwargs else False
    column = kwargs['column'] if 'column' in kwargs else 'target'

    # check input
    assert column in DF, f"{column} is not a column in the given DataFrame, try using: column = <desired column>"
    y = DF.target.to_numpy(np.int32)
    assert y.shape[0] == y.size, "to bincounts, input array must be 1D"

    bincount = np.bincount(y) # how many observations for each unique value
    unique = np.unique(y) # find all the unique values
    N = y.shape[0] # total number of observations

    for i,v in enumerate(unique):
        assert y[y==v].size == bincount[i], "for some reason, the unique values and the bincounts don't match"

    imbalanced = np.any(bincount/N < threshold) # find out if the data is imbalanced
    if verbose:
        print("\nchecking if data is imbalanced...")
        if imbalanced:
            print(f"data is imbalanced (threshold = {threshold})")
        else:
            print(f"data is not imbalanced (threshold = {threshold})")

        print("unique values line up with bincounts")

    # sort bincount and uniques
    idx = bincount.argsort() # find the indicies to sort bincount

    return {'imbalanced':imbalanced, 'bincount':bincount[idx], 'unique':unique[idx]}

def split_stratify(DF, **kwargs):
    """Stratifies the given DataFrame based on the specified column (default: column = 'target') and returns a dictionary of np.int32 index arrays with keys ['train', 'validate', 'test']."""

    # options
    train_size = kwargs['train_size'] if 'train_size' in kwargs else 0.6
    validate_size = kwargs['validate_size'] if 'validate_size' in kwargs else 0.2
    shuffle = kwargs['shuffle'] if 'shuffle' in kwargs else True
    seed = kwargs['seed'] if 'seed' in kwargs else 0
    verbose = kwargs['verbose'] if 'verbose' in kwargs else False

    if verbose: print("\nStratifying observations...")

    check = check_for_imbalanced_data(DF, **kwargs)

    # set up empty containers for indices
    idx = np.arange(DF.shape[0])
    indices = {
        'train'    : np.array([], dtype=np.int32),
        'validate' : np.array([], dtype=np.int32),
        'test'     : np.array([], dtype=np.int32)
    }

    for i,(value,count) in enumerate(zip(check['unique'],check['bincount'])):
        idx1 = idx[ y == value ]
        N = idx1.size
        assert N == count, "For some reason, the counts don't line up."
        N_train = int(N*train_size)
        N_validate = int(N*validate_size)
        indices['train'] = np.hstack(( indices['train'], idx1[:N_train] ))
        indices['validate'] = np.hstack(( indices['validate'], idx1[N_train:N_train+N_validate]))
        indices['test'] = np.hstack(( indices['test'], idx1[N_train+N_validate:]))

    if shuffle:
        if verbose: print("shuffling stratified observations...")
        for key in ['train', 'validate', 'test']:
            np.random.RandomState(seed=seed).shuffle(indices[key])

    return indices

def split_straight(DF, **kwargs):
    """Splits the given DataFrame (w\\o stratifing) based on the specified column (default: column = 'target') and returns a dictionary of np.int32 index arrays with keys ['train', 'validate', 'test']."""

    # options
    train_size = kwargs['train_size'] if 'train_size' in kwargs else 0.6
    validate_size = kwargs['validate_size'] if 'validate_size' in kwargs else 0.2
    shuffle = kwargs['shuffle'] if 'shuffle' in kwargs else True
    seed = kwargs['seed'] if 'seed' in kwargs else 0
    verbose = kwargs['verbose'] if 'verbose' in kwargs else False

    # find number of observations for each dataset
    N = DF.shape[0]
    N_train = int(N*train_size)
    N_validate = int(N*validate_size)

    if shuffle:
        if verbose: print("shuffling observations...")
        idx = np.random.RandomState(seed=seed).permutation(N)
    else:
        idx = np.arange(N)

    if verbose: print("splitting observations w/o stratifying...")
    indices = {
        'train'    : idx[ : N_train ],
        'validate' : idx[ N_train : N_train + N_validate ],
        'test'     : idx[ N_train + N_validate : ]
    }

    return indices

def train_test_split_indices(DF, **kwargs):
    """Returns the indicies for the train, validate, and test sets as a dictionary with keys: 'train', 'validate', and 'test', with int32 numpy arrays as their values."""

    # options
    stratify = kwargs['stratify'] if 'stratify' in kwargs else False

    if stratify:
        return split_stratify(DF, **kwargs)
    else:
        return split_straight(DF, **kwargs)

def kfolds_indices(DF, **kwargs):
    """Splits the DataFrame k-fold, returns a dictionary with int keys from 0 to k; the values are the index dictionaries for eack of the k folds. The index dictionaries are np.int32 arrays with keys ['train', 'validate', 'test']."""

    # options
    k = kwargs['k'] if 'k' in kwargs else 10
    stratify = kwargs['stratify'] if 'stratify' in kwargs else False
    column = kwargs['column'] if 'column' in kwargs else 'target'
    shuffle = kwargs['shuffle'] if 'shuffle' in kwargs else True

    # get an array of indices
    N = DF.shape[0]
    Nk = N//k
    if shuffle:
        idx = np.random.RandomState(seed=seed).permutation(N)
    else:
        idx = np.arange(N)

    indices = {}
    for i in range(k):
        idx1 = idx[ i*N1 : (i+1)*N1 ]
        DF1 = DF.iloc[idx1]
        if stratify:
            indices[i] = split_stratify(DF1, **kwargs)
        else:
            indices[i] = split_straight(DF1, **kwargs)

#===============================================================================
# Model Selection
#===============================================================================


import cv2
import numpy as np

img = cv2.imread("Photos/self.jpg")
cv2.imshow('Img', img)

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow('gray', gray)

threshold, thresh = cv2.threshold(gray, 125, 256, cv2.THRESH_BINARY)
cv2.imshow('thresh', thresh)

threshold, thresh_inv = cv2.threshold(gray, 125, 256, cv2.THRESH_BINARY_INV)
cv2.imshow('thresh inv', thresh_inv)

adaptive_thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 11, 9)
cv2.imshow('Adaptive thresh', adaptive_thresh)

cv2.waitKey(0)


from django.conf import settings
from django.shortcuts import render_to_response, get_object_or_404
from django import forms
from django.template import RequestContext
from django.views.generic import list_detail
from django.http import Http404, HttpResponseRedirect
from colddirt.dirty.models import *
from colddirt.forms import *
import datetime, colddirt.captcha

def live_update(request):
    from django.http import HttpResponse
    from django.core import serializers
    # To get my designed feature set, plus not kill the load
    # on my server, this is all a bit hackery.  If you see
    # a better way to handle it, *especially* the JS, let
    # me know!
    if request.method == 'GET':
        new_pk = request.GET.get('pk')
        if new_pk:
            data = serializers.serialize("json", Dirt.objects.filter(pk__gte=new_pk).order_by('-publish_date')[:10])
    return HttpResponse(data, mimetype='application/json')

def dirt_count(request):
    from django.http import HttpResponse
    countd = str(Dirt.objects.all().count())
    return HttpResponse(countd, mimetype='text/plain')

def live(request):
    dirt_form = DirtyForm()
    html_captcha = colddirt.captcha.displayhtml(settings.RECAPTCHA_PUB_KEY)
    return render_to_response("dirty/live_dirt.html", {
                                "form": dirt_form.as_ul(),
                                'html_captcha': html_captcha})

def index(request):
    import re
    from django.template.defaultfilters import slugify
    # I display the form on every page, so I don't need an if/else here.  However, You would normall put the below two lines after an else:
    dirt_form = DirtyForm()
    html_captcha = colddirt.captcha.displayhtml(settings.RECAPTCHA_PUB_KEY)
    if request.method == 'POST':
        check_captcha = colddirt.captcha.submit(request.POST['recaptcha_challenge_field'], request.POST['recaptcha_response_field'], settings.RECAPTCHA_PRIVATE_KEY, request.META['REMOTE_ADDR'])
        if check_captcha.is_valid is False:
            # Captcha is wrong show a error ...
            return render_to_response('dirty/dirt_list.html',
                                      { 'form': dirt_form.as_ul(),
                                       'html_captcha': html_captcha,
                                       'errorlist_captcha': True},
                                      context_instance=RequestContext(request))
        dirt_form = DirtyForm(request.POST)
        if dirt_form.is_valid():
            # I opted not to create an m2m relationship for several
            # reasons. Note: the latest_word is some random word.
            latest_word = Word.objects.filter(is_taken__exact=False).order_by('?')[:1]
            latest_word[0].is_taken=True
            latest_word[0].save()
            new_dirt = Dirt(description=dirt_form.cleaned_data['description'],
                            dirtword=latest_word[0].dirtyword)
            new_dirt.save()
            # Credit for the tag parsing goes to Ubernostrum (James B)
            # from the Cab (great for learning!) project
            # I opted to not store tag_list in each entry
            # Splitting to get the new tag list is tricky, because people
            # will stick commas and other whitespace in the darndest places.
            new_tag_list = [t for t in re.split('[\s,]+', dirt_form.cleaned_data['tag_list']) if t]
            # Now add the tags
            for tag_name in new_tag_list:
                tag, created = Tagling.objects.get_or_create(name=slugify(tag_name), slug=slugify(tag_name))
                new_dirt.tags.add(tag)
            return HttpResponseRedirect(new_dirt.get_absolute_url())
    return list_detail.object_list(
           request,
           queryset = Dirt.objects.order_by('?')[:100],
           template_name = "dirty/dirt_list.html",
           template_object_name = "dirty",
           paginate_by = 10,
           extra_context = {'form': dirt_form.as_ul(),
                            'html_captcha': html_captcha},
        )

def submit(request):
    import re
    from django.template.defaultfilters import slugify
    dirt_form = DirtyForm()
    html_captcha = colddirt.captcha.displayhtml(settings.RECAPTCHA_PUB_KEY)
    if request.method == 'POST':
        check_captcha = colddirt.captcha.submit(request.POST['recaptcha_challenge_field'], request.POST['recaptcha_response_field'], settings.RECAPTCHA_PRIVATE_KEY, request.META['REMOTE_ADDR'])
        if check_captcha.is_valid is False:
            # Captcha is wrong show a error ...
            return render_to_response('dirty/dirt_list.html',
                                      { 'form': dirt_form.as_ul(),
                                       'html_captcha': html_captcha,
                                       'errorlist_captcha': True},
                                      context_instance=RequestContext(request))
        dirt_form = DirtyForm(request.POST)
        if dirt_form.is_valid():
            # I opted not to create an m2m relationship for several
            # reasons. Note: the latest_word is some random word.
            latest_word = Word.objects.filter(is_taken__exact=False).order_by('?')[:1]
            latest_word[0].is_taken=True
            #latest_word[0].save()
            new_dirt = Dirt(description=dirt_form.cleaned_data['description'],
                            dirtword=latest_word[0].dirtyword)
            new_dirt.save()
            # Credit for the tag parsing goes to Ubernostrum (James B)
            # from the Cab (great for learning!) project
            # I opted to not store tag_list in each entry
            # Splitting to get the new tag list is tricky, because people
            # will stick commas and other whitespace in the darndest places.
            new_tag_list = [t for t in re.split('[\s,]+', dirt_form.cleaned_data['tag_list']) if t]
            # Now add the tags
            for tag_name in new_tag_list:
                tag, created = Tagling.objects.get_or_create(name=slugify(tag_name), slug=slugify(tag_name))
                new_dirt.tags.add(tag)
            return HttpResponseRedirect(new_dirt.get_absolute_url())
    return render_to_response('dirty/dirt_list.html',
                              { 'form': dirt_form.as_ul(),
                               'html_captcha': html_captcha},
                              context_instance=RequestContext(request))

def tag_list(request, slug):
    dirts = Dirt.objects.filter(tags__slug__iexact=slug)
    html_captcha = colddirt.captcha.displayhtml(settings.RECAPTCHA_PUB_KEY)
    return list_detail.object_list(
           request,
           queryset = dirts,
           template_name = "dirty/dirt_list.html",
           template_object_name = "dirty",
           paginate_by = 25,
           extra_context = {'form': DirtyForm().as_ul(),
                            'html_captcha': html_captcha,
                            'tag_search': slug }
        )

def search(request):
    from django.db.models import Q
    q = request.GET.get("q", "")
    if q and len(q) >= 3:
        clause = Q(dirtword__icontains=q)               \
               | Q(description__icontains=q)       \
               | Q(tags__name__icontains=q)
        site_search = Dirt.objects.filter(clause).distinct()
    else:
        site_search = Dirt.objects.order_by('?')[:100]
    return list_detail.object_list(
        request              = request,
        queryset             = site_search,
        template_name        = "dirty/search.html",
        template_object_name = "dirty",
        paginate_by          = 20,
        extra_context        = {"q" : q},
    )

def tag_cloud(request):
    #make tag cloud
    populartags = Tagling.objects.popular_tags()
    maxtags = []
    for tag in populartags:
        maxtags.append(tag.tagcount)
    #we need max count for the tagcloud
    maxtagcount = max(maxtags)
    html_captcha = colddirt.captcha.displayhtml(settings.RECAPTCHA_PUB_KEY)
    return render_to_response("dirty/tag_cloud.html", {
                                "populartags" : populartags,
                                "maxtagcount" : maxtagcount,
                                'html_captcha': html_captcha,
                                'form': DirtyForm().as_ul()})

def huh(request, template="dirty/huh.html",redirect_to="/"):
    from django.core.mail import send_mail
    contact_form = ContactForm()
    user = request.user
    description = ''
    status = ''
    subject = ''
    from_email = ''
    if request.method == 'POST':
        contact_form = ContactForm(request.POST)
        if contact_form.is_valid():
            description = contact_form.cleaned_data['description']
            status = contact_form.cleaned_data['status']
            subject = contact_form.cleaned_data['subject']
            from_email = contact_form.cleaned_data['from_email']
            send_mail('Cold Dirt ' + subject,
                      'Type: ' + status + description,
                      from_email,
                      ['kelvin@kelvinism.com'], fail_silently=True)
    return render_to_response(template, {'contact_form':contact_form.as_ul(),
                                      'description': description,
                                      'status': status,
                                      'subject': subject,
                                      'from_email': from_email,
                                      'user': user})

def report(request, report_id):
    # This is super ghetto, but works for now
    new_report = Report(item=report_id)
    new_report.save()
    return HttpResponseRedirect("/reported/success/")


# -*- coding: utf-8 -*-
# !/usr/bin/env python3
"""
"""

__author__ = "Hans Bering"
__copyright__ = "Copyright 2017"
__credits__ = ["Hans Bering"]
__license__ = "MIT License"
__maintainer__ = "Hans Bering"
__email__ = "hansi.b.github@mgail.moc"
__status__ = "Development"

import unittest

from rewrapped import ReWrap, matched

class AnInt(ReWrap):
    matchOn = "Number ([0-9]+)"
    no = matched.g1.asInt

class TestAsInt(unittest.TestCase):

    def testSearch(self):
        res = AnInt.search("Number 11 came up")

        self.assertEqual(11, res.no)

    def testSearchNoMatch(self):
        res = AnInt.search("Number x came up")
        self.assertIsNone(res)

class Floater(ReWrap):
    matchOn = "beyond ([+-]?[0-9]+\.[0-9]+)"
    limit = matched.g1.asFloat

class TestAsFloat(unittest.TestCase):

    def testSearch(self):
        res = Floater.search("beyond 11.01")

        self.assertEqual(11.01, res.limit)

    def testSearchNoMatch(self):
        res = Floater.search("beyond 23")
        self.assertIsNone(res)

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


from absl import logging

from common import api_utils
from data_models import translation_frame as translation_frame_lib

TRANSLATE_API_BASE_URL = 'https://translate.googleapis.com'

TRANSLATE_TEXT_ENDPOINT = (
    TRANSLATE_API_BASE_URL
    + '/v{api_version}/projects/{gcp_project_name}:translateText'
)

_API_VERSION = '3'

_CREDENTIAL_REQUIRED_KEYS = (
    'client_id',
    'client_secret',
    'refresh_token',
)

# Max batch size for the Cloud Translation API V3 is 5000 code points.
# Setting the batch too high could result in long response times, and some chars
# may be represented by 3 code points, so 1500 keeps response times short in the
# average case, and stops us exceeding limits in the worst case of all chars
# being represented by multiple code points.
_DEFAULT_BATCH_CHAR_LIMIT = 1500

class CloudTranslationClient:
  """A client for translating data via the Google Cloud Translation API.

  The credentials need to be provided as a dictionary see details below:

  Sample usage:
    credentials = {
      'client_id': <client_id>,
      'client_secret': <client_secret>,
      'refresh_token': <refresh_token>,
    }

    cloud_translation_client = CloudTranslationClient(credentials, 'my_project')
    cloud_translation_client.translate(
        translation_frame=<TranslationFrame>,
        source_language_code='EN',
        target_language_code='DE',
        )

    The TranslationFrame object will be mutated to add translations in-place.
  """

  def __init__(
      self,
      credentials: dict[str, str],
      gcp_project_name: str,
      api_version: str = _API_VERSION,
      batch_char_limit: int = _DEFAULT_BATCH_CHAR_LIMIT,
  ) -> None:
    """Instantiates the Clound Translation client.

    Args:
      credentials: The Cloud API credentials as dict. Should contain client_id,
        client_secret, and refresh_token keys.
      gcp_project_name: The name or ID of the Google Cloud Project associated
        with the credentials.
      api_version: The Cloud Translate API API Version.
      batch_char_limit: The size of content batches to send to the translation
        API, in chars.
    """
    self.api_version = api_version
    self.batch_char_limit = batch_char_limit
    self.credentials = credentials
    self.gcp_project_name = gcp_project_name
    # The access_token be lazily loaded and cached when the API is called to
    # ensure token is fresh and won't be retrieved repeatedly.
    self.access_token = None
    api_utils.validate_credentials(self.credentials, _CREDENTIAL_REQUIRED_KEYS)
    logging.info('Successfully initialized CloudTranslationClient.')

  def translate(
      self,
      translation_frame: translation_frame_lib.TranslationFrame,
      source_language_code: str,
      target_language_code: str) -> None:
    """Translates the terms in a translation frame in place.

    The translations will be added to the 'target_terms' column of the
    translation_frame.

    Args:
      translation_frame: The terms to translate.
      source_language_code: The language to translate from.
      target_language_code: The language to translate to.
    """
    logging.info('Starting translation for %d terms.', translation_frame.size())

    batch_start = 0
    parent = f'projects/{self.gcp_project_name}'

    while batch_start < translation_frame.size():

      batch, next_batch_index = translation_frame.get_term_batch(
          batch_start, self.batch_char_limit)

      params = {
          'contents': batch,
          'mimeType': 'text/plain',
          'parent': parent,
          'source_language_code': source_language_code,
          'target_language_code': target_language_code,
      }

      url = TRANSLATE_TEXT_ENDPOINT.format(
          api_version=self.api_version, gcp_project_name=self.gcp_project_name)

      response = api_utils.send_api_request(
          url, params, self._get_http_header())

      logging.info('Got responses for terms %d-%d of %d',
                   batch_start,
                   batch_start + len(batch) - 1, translation_frame.size())

      translations = [t['translatedText'] for t in response['translations']]

      translation_frame.add_translations(
          start_index=batch_start,
          target_language_code=target_language_code,
          translations=translations,
      )

      batch_start = next_batch_index

    logging.info(
        'Completed translation for %d terms.', translation_frame.size())

  def _get_http_header(self) -> dict[str, str]:
    """Get the Authorization HTTP header.

    Returns:
      The authorization HTTP header.
    """
    if not self.access_token:
      self.access_token = api_utils.refresh_access_token(self.credentials)
    return {
        'Authorization': f'Bearer {self.access_token}',
        'Content-Type': 'application/json',
    }


"""
Non-embedded helpers, mainly for the command interpreter
"""
from __future__ import annotations

import hashlib

from .path import APath, copytree

def githash(data):
    h = hashlib.sha1()
    h.update(f"blob {len(data)}\0".encode("utf-8"))
    h.update(data)
    return h.digest()

async def rd(f):
    async with await f.open("rb") as fd:
        return await fd.read()

async def run_update(dest: MoatPath, release:str|None = None, check=None, cross=None):
    """
    Update a remote file system.

    The satellite knows which git version its frozen library is built for.
    Thus if the source of that frozen file is identical to what we have
    now, the remote shouldn't have that file (or its .mpy derivative) in
    its file system. It might be there as a left-over artefact from a
    previous update. Thus we delete it.
    """
    import git

    src = APath(__file__).parent / "_embed"
    root = APath(__file__).parent.parent.parent

    try:
        r = git.Repo(str(root))
    except git.exc.InvalidGitRepositoryError:
        if release:
            raise RuntimeError("release version found but no git")
        async def drop(dst):
            return False
    else:
        if not release:
            # raise RuntimeError("git but no release version found")
            pass
        root_r = await root.resolve()
        emb_r = await src.resolve()
        if release:
            t = r.commit(release).tree
        else:
            t = r.head.commit.tree
        t = t[str(emb_r.relative_to(root_r))]

        async def drop(dst):
            """
            delete files on the satellite that didn't change between the
            version in their firmware and our current version.
            """
            # rp = dst.relative_to(emb_r)
            # assume dst is relative
            sp = src/dst
            # XXX we might want to ask git which files differ,
            # it's supposed to have a cache for that
            if await sp.is_symlink():
                return None  # ignore completely
            try:
                return t[str(dst)].binsha == githash(await rd(sp))
            except KeyError:
                # not yet in git
                return False

        # otherwise sync as normal

    await copytree(src, dest, check=check, drop=drop, cross=cross)


import sys, os
if hasattr(sys.modules['__main__'], 'DC') and 'standalone' in sys.modules['__main__'].DC.options.optional:
    sys.path.append(os.getcwd())
    sys.path.append(os.path.dirname(os.getcwd()))

from inductive_valuation import NonFinalInductiveValuation

from sage.misc.cachefunc import cached_method
from sage.structure.unique_representation import UniqueRepresentation
from sage.structure.factory import UniqueFactory

class GaussValuationFactory(UniqueFactory):
    r"""
    Create a Gauss valuation on ``domain``.

    INPUT:

    - ``domain`` -- a univariate polynomial ring

    - ``v`` -- a valuation on the base ring of ``domain``, the underlying
      valuation on the constants of the polynomial ring (if unspecified take
      the natural valuation on the valued ring ``domain``.)

    EXAMPLES:

    The Gauss valuation is the minimum of the valuation of the coefficients::

        sage: from mac_lane import * # optional: standalone
        sage: v = pAdicValuation(QQ, 2)
        sage: R.<x> = QQ[]
        sage: w = GaussValuation(R, v)
        sage: w(2)
        1
        sage: w(x)
        0
        sage: w(x + 2)
        0

    """
    def create_key(self, domain, v = None):
        r"""
        Normalize and check the parameters to create a Gauss valuation.

        TESTS::

            sage: from mac_lane import * # optional: standalone
            sage: v = pAdicValuation(QQ, 2)
            sage: R.<x> = ZZ[]
            sage: GaussValuation.create_key(R, v)
            Traceback (most recent call last):
            ...
            ValueError: the domain of v must be the base ring of domain but 2-adic valuation is not defined over Integer Ring but over Rational Field

        """
        from sage.rings.polynomial.polynomial_ring import is_PolynomialRing
        if not is_PolynomialRing(domain):
            raise TypeError("GaussValuations can only be created over polynomial rings but %r is not a polynomial ring"%(domain,))
        if not domain.ngens() == 1:
            raise NotImplementedError("domain must be univariate but %r is not univariate"%(domain,))

        if v is None:
            v = domain.base_ring().valuation()

        if not v.domain() is domain.base_ring():
            raise ValueError("the domain of v must be the base ring of domain but %r is not defined over %r but over %r"%(v, domain.base_ring(), v.domain()))
        if not v.is_discrete_valuation():
            raise ValueError("v must be a discrete valuation but %r is not"%(v,))

        return (domain, v)

    def create_object(self, version, key, **extra_args):
        r"""
        Create a Gauss valuation from normalized parameters.

        TESTS::

            sage: from mac_lane import * # optional: standalone
            sage: v = pAdicValuation(QQ, 2)
            sage: R.<x> = QQ[]
            sage: GaussValuation.create_object(0, (R, v))
            Gauss valuation induced by 2-adic valuation

        """
        domain, v = key
        from sage.rings.valuation.valuation_space import DiscretePseudoValuationSpace
        parent = DiscretePseudoValuationSpace(domain)
        return parent.__make_element_class__(GaussValuation_generic)(parent, v)

GaussValuation = GaussValuationFactory("GaussValuation")

class GaussValuation_generic(NonFinalInductiveValuation):
    """
    A Gauss valuation on a polynomial ring ``domain``.

    INPUT:

    - ``domain`` -- a univariate polynomial ring over a valued ring `R`

    - ``v`` -- a discrete valuation on `R`

    EXAMPLES::

        sage: from mac_lane import * # optional: standalone
        sage: R = Zp(3,5)
        sage: S.<x> = R[]
        sage: v0 = pAdicValuation(R)
        sage: v = GaussValuation(S, v0); v
        Gauss valuation induced by 3-adic valuation

        sage: S.<x> = QQ[]
        sage: v = GaussValuation(S, pAdicValuation(QQ, 5)); v
        Gauss valuation induced by 5-adic valuation

    TESTS::

        sage: TestSuite(v).run() # long time

    """
    def __init__(self, parent, v):
        """
        TESTS::

            sage: from mac_lane import * # optional: standalone
            sage: from mac_lane.gauss_valuation import GaussValuation_generic # optional: standalone
            sage: S.<x> = QQ[]
            sage: v = GaussValuation(S, pAdicValuation(QQ, 5))
            sage: isinstance(v, GaussValuation_generic)
            True

        """
        NonFinalInductiveValuation.__init__(self, parent, parent.domain().gen())

        self._base_valuation = v

    def value_group(self):
        """
        Return the value group of this valuation.

        EXAMPLES::

            sage: from mac_lane import * # optional: standalone
            sage: S.<x> = QQ[]
            sage: v = GaussValuation(S, pAdicValuation(QQ, 5))
            sage: v.value_group()
            Additive Abelian Group generated by 1

        """
        return self._base_valuation.value_group()

    def _repr_(self):
        """
        Return a printable representation of this valuation.

        EXAMPLES::

            sage: from mac_lane import * # optional: standalone
            sage: S.<x> = QQ[]
            sage: v = GaussValuation(S, pAdicValuation(QQ, 5))
            sage: v # indirect doctest
            Gauss valuation induced by 5-adic valuation

        """
        return "Gauss valuation induced by %r"%self._base_valuation

    @cached_method
    def uniformizer(self):
        """
        Return a uniformizer of this valuation, i.e., a uniformizer of the
        valuation of the base ring.

        EXAMPLES::

            sage: from mac_lane import * # optional: standalone
            sage: S.<x> = QQ[]
            sage: v = GaussValuation(S, pAdicValuation(QQ, 5))
            sage: v.uniformizer()
            5
            sage: v.uniformizer().parent() is S
            True

        """
        return self.domain()(self._base_valuation.uniformizer())

    def shift(self, f, s):
        """
        Multiply ``f`` by a power of the uniformizer which has valuation ``s``.

        INPUT:

        - ``f`` -- a polynomial in the domain of this valuation

        - ``s`` -- an element of the :meth:`value_group`

        EXAMPLES::

            sage: from mac_lane import * # optional: standalone
            sage: S.<x> = QQ[]
            sage: v = GaussValuation(S, pAdicValuation(QQ, 5))
            sage: v.shift(x, -2)
            1/25*x

        It is an error to perform a shift if the result is not in the domain of
        the valuation anymore::

            sage: S.<x> = Zp(2,5)[]
            sage: v = GaussValuation(S)
            sage: f = v.shift(x, 2); f
            (2^2 + O(2^7))*x
            sage: f.parent() is S
            True
            sage: f = v.shift(x, -2)
            Traceback (most recent call last):
            ...
            ValueError: since 2-adic Ring with capped relative precision 5 is not a field, -s must not exceed the valuation of f but 2 does exceed 0

        Of course, the above example works over a field::

            sage: S.<x> = Qp(2,5)[]
            sage: v = GaussValuation(S)
            sage: f = v.shift(x, -2); f
            (2^-2 + O(2^3))*x

        """
        f = self.domain().coerce(f)
        s = self.value_group()(s)

        if s == 0:
            return f

        from sage.categories.fields import Fields
        if -s > self(f) and self.domain().base_ring() not in Fields():
            raise ValueError("since %r is not a field, -s must not exceed the valuation of f but %r does exceed %r"%(self.domain().base_ring(), -s, self(f)))

        if f == 0:
            raise ValueError("can not shift zero")

        return f.map_coefficients(lambda c:self._base_valuation.shift(c, s))

    def valuations(self, f):
        """
        Return the valuations of the `f_i\phi^i` in the expansion `f=\sum f_i\phi^i`.

        INPUT:

        - ``f`` -- a polynomial in the domain of this valuation

        OUTPUT:

        A list, each entry a rational numbers or infinity, the valuations of `f_0, f_1\phi, \dots`

        EXAMPLES::

            sage: from mac_lane import * # optional: standalone
            sage: R = ZZ
            sage: S.<x> = R[]
            sage: v = GaussValuation(S, pAdicValuation(R, 2))
            sage: f = x^2 + 2*x + 16
            sage: list(v.valuations(f))
            [4, 1, 0]

        """
        f = self.domain().coerce(f)

        for c in self.coefficients(f):
            yield self._base_valuation(self.domain().base_ring()(c))

    @cached_method
    def residue_ring(self):
        """
        Return the residue ring of this valuation, i.e., the elements of
        valuation zero module the elements of positive valuation.

        EXAMPLES::

            sage: from mac_lane import * # optional: standalone
            sage: S.<x> = Qp(2,5)[]
            sage: v = GaussValuation(S)
            sage: v.residue_ring()
            Univariate Polynomial Ring in x over Finite Field of size 2 (using NTL)

        """
        return self.domain().change_ring(self._base_valuation.residue_ring())

    def reduce(self, f):
        """
        Return the reduction of ``f`` modulo this valuation.

        INPUT:

        - ``f`` -- an integral element of the domain of this valuation

        OUTPUT:

        A polynomial in the :meth:`residue_ring` of this valuation.

        EXAMPLES::

            sage: from mac_lane import * # optional: standalone
            sage: S.<x> = Qp(2,5)[]
            sage: v = GaussValuation(S)
            sage: f = x^2 + 2*x + 16
            sage: v.reduce(f)
            x^2
            sage: v.reduce(f).parent() is v.residue_ring()
            True

        The reduction is only defined for integral elements::

            sage: f = x^2/2
            sage: v.reduce(f)
            Traceback (most recent call last):
            ...
            ValueError: reduction not defined for non-integral elements and (2^-1 + O(2^4))*x^2 is not integral over Gauss valuation induced by 2-adic valuation

        .. SEEALSO::

            :meth: `lift`

        """
        f = self.domain().coerce(f)
        if not all([v>=0 for v in self.valuations(f)]):
            raise ValueError("reduction not defined for non-integral elements and %r is not integral over %r"%(f, self))

        return f.map_coefficients(lambda c:self._base_valuation.reduce(c), self.restriction(self.domain().base_ring()).residue_field())

    def lift(self, F):
        """
        Return a lift of ``F``.

        INPUT::

        - ``F`` -- a polynomial over the :meth:`residue_ring` of this valuation

        OUTPUT:

        a (possibly non-monic) polynomial in the domain of this valuation which
        reduces to ``F``

        EXAMPLES::

            sage: from mac_lane import * # optional: standalone
            sage: S.<x> = Qp(3,5)[]
            sage: v = GaussValuation(S)
            sage: f = x^2 + 2*x + 16
            sage: F = v.reduce(f); F
            x^2 + 2*x + 1
            sage: g = v.lift(F); g
            (1 + O(3^5))*x^2 + (2 + O(3^5))*x + (1 + O(3^5))
            sage: v.is_equivalent(f,g)
            True
            sage: g.parent() is v.domain()
            True

        .. SEEALSO::

            :meth:`reduce`

        """
        F = self.residue_ring().coerce(F)

        return F.map_coefficients(lambda c:self._base_valuation.lift(c), self._base_valuation.domain())

    def lift_to_key(self, F):
        """
        Lift the irreducible polynomial ``F`` from the :meth:`residue_ring` to
        a key polynomial over this valuation.

        INPUT:

        - ``F`` -- an irreducible non-constant monic polynomial in
          :meth:`residue_ring` of this valuation

        OUTPUT:

        A polynomial `f` in the domain of this valuation which is a key
        polynomial for this valuation and which, for a suitable equivalence
        unit `R`, satifies that the reduction of `Rf` is ``F``

        EXAMPLES::

            sage: from mac_lane import * # optional: standalone
            sage: R.<u> = QQ
            sage: S.<x> = R[]
            sage: v = GaussValuation(S, pAdicValuation(QQ, 2))
            sage: y = v.residue_ring().gen()
            sage: f = v.lift_to_key(y^2 + y + 1); f
            x^2 + x + 1

        """
        F = self.residue_ring().coerce(F)

        if F.is_constant():
            raise ValueError("F must not be constant but %r is constant"%(F,))
        if not F.is_monic():
            raise ValueError("F must be monic but %r is not monic"%(F,))
        if not F.is_irreducible():
            raise ValueError("F must be irreducible but %r factors"%(F,))

        return self.lift(F)

    def equivalence_unit(self, s):
        """
        Return an equivalence unit of valuation ``s``.

        INPUT:

        - ``s`` -- an element of the :meth:`value_group`

        EXAMPLES::

            sage: from mac_lane import * # optional: standalone
            sage: S.<x> = Qp(3,5)[]
            sage: v = GaussValuation(S)
            sage: v.equivalence_unit(2)
            (3^2 + O(3^7))
            sage: v.equivalence_unit(-2)
            (3^-2 + O(3^3))

        """
        one = self._base_valuation.domain().one()
        ret = self._base_valuation.shift(one, s)
        return self.domain()(ret)

    def element_with_valuation(self, s):
        r"""
        Return a polynomial of minimal degree with valuation ``s``.

        EXAMPLES::

            sage: from mac_lane import * # optional: standalone
            sage: R.<x> = QQ[]
            sage: v = GaussValuation(R, pAdicValuation(QQ, 2))
            sage: v.element_with_valuation(-2)
            1/4

        """
        return self.equivalence_unit(s)

    def E(self):
        """
        Return the ramification index of this valuation over its underlying
        Gauss valuation, i.e., 1.

        EXAMPLES::

            sage: from mac_lane import * # optional: standalone
            sage: R.<u> = Qq(4,5)
            sage: S.<x> = R[]
            sage: v = GaussValuation(S)
            sage: v.E()
            1

        """
        from sage.rings.all import ZZ
        return ZZ.one()

    def F(self):
        """
        Return the degree of the residue field extension of this valuation
        over the Gauss valuation, i.e., 1.

        EXAMPLES::

            sage: from mac_lane import * # optional: standalone
            sage: R.<u> = Qq(4,5)
            sage: S.<x> = R[]
            sage: v = GaussValuation(S)
            sage: v.F()
            1

        """
        from sage.rings.all import ZZ
        return ZZ.one()

    def change_domain(self, ring):
        r"""
        Return this valuation as a valuation over ``ring``.

        EXAMPLES::

            sage: from mac_lane import * # optional: standalone
            sage: v = pAdicValuation(ZZ, 2)
            sage: R.<x> = ZZ[]
            sage: w = GaussValuation(R, v)
            sage: w.change_domain(QQ['x'])
            Gauss valuation induced by 2-adic valuation

        """
        from sage.rings.polynomial.polynomial_ring import is_PolynomialRing
        if is_PolynomialRing(ring) and ring.ngens() == 1:
            base_valuation = self._base_valuation.change_domain(ring.base_ring())
            return GaussValuation(self.domain().change_ring(ring.base_ring()), base_valuation)
        return super(GaussValuation_generic, self).change_domain(ring)

    def extensions(self, ring):
        r"""
        Return the extensions of this valuation to ``ring``.

        EXAMPLES::

            sage: from mac_lane import * # optional: standalone
            sage: v = pAdicValuation(ZZ, 2)
            sage: R.<x> = ZZ[]
            sage: w = GaussValuation(R, v)
            sage: w.extensions(GaussianIntegers()['x'])
            [Gauss valuation induced by 2-adic valuation]

        """
        from sage.rings.polynomial.polynomial_ring import is_PolynomialRing
        if is_PolynomialRing(ring) and ring.ngens() == 1:
            if self.domain().is_subring(ring):
                return [GaussValuation(ring, w) for w in self._base_valuation.extensions(ring.base_ring())]
        return super(GaussValuation_generic, self).extensions(ring)

    def restriction(self, ring):
        r"""
        Return the restriction of this valuation to ``ring``.

        EXAMPLES::

            sage: from mac_lane import * # optional: standalone
            sage: v = pAdicValuation(ZZ, 2)
            sage: R.<x> = ZZ[]
            sage: w = GaussValuation(R, v)
            sage: w.restriction(ZZ)
            2-adic valuation

        """
        if ring.is_subring(self.domain().base_ring()):
            return self._base_valuation.restriction(ring)
        from sage.rings.polynomial.polynomial_ring import is_PolynomialRing
        if is_PolynomialRing(ring) and ring.ngens() == 1:
            if ring.base().is_subring(self.domain().base()):
                return GaussValuation(ring, self._base_valuation.restriction(ring.base()))
        return super(GaussValuation_generic, self).restriction(ring)

    def is_gauss_valuation(self):
        r"""
        Return whether this valuation is a Gauss valuation.

        EXAMPLES::

            sage: from mac_lane import * # optional: standalone
            sage: R.<u> = Qq(4,5)
            sage: S.<x> = R[]
            sage: v = GaussValuation(S)
            sage: v.is_gauss_valuation()
            True

        """
        return True

    def augmentation_chain(self):
        r"""
        Return a list with the chain of augmentations down to the underlying
        :class:`GaussValuation`.

        EXAMPLES::

            sage: from mac_lane import * # optional: standalone
            sage: R.<u> = Qq(4,5)
            sage: S.<x> = R[]
            sage: v = GaussValuation(S)
            sage: v.augmentation_chain()
            [Gauss valuation induced by 2-adic valuation]

        """
        return [self]

    def is_trivial(self):
        r"""
        Return whether this is a trivial valuation (sending everything but zero
        to zero.)

        EXAMPLES::

            sage: from mac_lane import * # optional: standalone
            sage: R.<x> = QQ[]
            sage: v = GaussValuation(R, TrivialValuation(QQ))
            sage: v.is_trivial()
            True

        """
        return self._base_valuation.is_trivial()

    def monic_integral_model(self, G):
        r"""
        Return a monic integral irreducible polynomial which defines the same
        extension of the base ring of the domain as the irreducible polynomial
        ``G`` together with maps between the old and the new polynomial.

        EXAMPLES::

            sage: from mac_lane import * # optional: standalone
            sage: R.<x> = Qp(2, 5)[]
            sage: v = GaussValuation(R)
            sage: v.monic_integral_model(5*x^2 + 1/2*x + 1/4)
            (Ring endomorphism of Univariate Polynomial Ring in x over 2-adic Field with capped relative precision 5
               Defn: (1 + O(2^5))*x |--> (2^-1 + O(2^4))*x,
             Ring endomorphism of Univariate Polynomial Ring in x over 2-adic Field with capped relative precision 5
               Defn: (1 + O(2^5))*x |--> (2 + O(2^6))*x,
            (1 + O(2^5))*x^2 + (1 + 2^2 + 2^3 + O(2^5))*x + (1 + 2^2 + 2^3 + O(2^5)))

        """
        if not G.is_monic():
            # this might fail if the base ring is not a field
            G = G / G.leading_coefficient()

        x = G.parent().gen()
        u = self._base_valuation.uniformizer()

        factor = 1
        substitution = x
        H = G
        while self(H) < 0:
            # this might fail if the base ring is not a field
            factor *= u
            substitution = x/factor
            H = G(substitution) * (factor ** G.degree())

        assert H.is_monic()
        return H.parent().hom(substitution, G.parent()), G.parent().hom(x / substitution[1], H.parent()), H

    def _ge_(self, other):
        r"""
        Return whether this valuation is greater than or equal to ``other``
        everywhere.

        EXAMPLES::

            sage: from mac_lane import * # optional: standalone
            sage: R.<x> = QQ[]
            sage: v = GaussValuation(R, pAdicValuation(QQ, 2))
            sage: w = GaussValuation(R, pAdicValuation(QQ, 3))
            sage: v >= w
            False
            sage: w >= v
            False

        """
        if isinstance(other, GaussValuation_generic):
            return self._base_valuation >= other._base_valuation
        from augmented_valuation import AugmentedValuation_base
        if isinstance(other, AugmentedValuation_base):
            return False
        if other.is_trivial():
            return other.is_discrete_valuation()
        return super(GaussValuation_generic, self)._ge_(other)

    def scale(self, scalar):
        r"""
        Return this valuation scaled by ``scalar``.

        EXAMPLES::

            sage: from mac_lane import * # optional: standalone
            sage: R.<x> = QQ[]
            sage: v = GaussValuation(R, pAdicValuation(QQ, 2))
            sage: 3*v # indirect doctest
            Gauss valuation induced by 3 * 2-adic valuation

        """
        from sage.rings.all import QQ
        if scalar in QQ and scalar > 0 and scalar != 1:
            return GaussValuation(self.domain(), self._base_valuation.scale(scalar))
        return super(GaussValuation_generic, self).scale(scalar)


#!/usr/bin/env python

import matplotlib
matplotlib.use("Agg")

def plot_stability_region(code, parallel=None, scale_factor=None, **kwargs):
    from leap.stability import find_stability_region
    points = find_stability_region(code, parallel=parallel,
            prec=1e-2, n_angles=100, origin=-.3)

    if scale_factor is not None:
        points = points * scale_factor

    from matplotlib.pyplot import fill
    fill(points.real, points.imag, **kwargs)

def main(save_pdfs=True):
    import matplotlib.pyplot as pt
    pt.rc("font", size=20)
    #title("Stability Region")
    pt.xlabel(r"Re $\lambda$ / RHS calls")
    pt.ylabel(r"Im $\lambda$ / RHS calls")
    pt.grid()

    import leap.rk as rk
    import leap.multistep as multistep

    for label, method, factor in [
            #("ode23", rk.ODE23MethodBuilder("y", use_high_order=True), 1),
            #("ab2", multistep.AdamsBashforthMethodBuilder("y", 2), 1),
            ("ab3", multistep.AdamsBashforthMethodBuilder("y", 3), 1),
            #("ab4", multistep.AdamsBashforthMethodBuilder("y", 4), 1),
            ("lserk", rk.LSRK4MethodBuilder("y"), 1/5),
            ("rk4", rk.RK4MethodBuilder("y"), 1/4),
            ]:

        code = method.generate()
        plot_stability_region(code, label=label, alpha=0.3, scale_factor=factor,
                parallel=True)

    pt.legend(labelspacing=0.1, borderpad=0.3, loc="best")
    if save_pdfs:
        pt.savefig("stab-regions.pdf")
        xmin, xmax = pt.xlim()
        xsize = xmax-xmin

        pt.gca().set_aspect("equal")
        pt.ylim([-xsize/2*0.75, xsize/2*0.75])
        pt.savefig("stab-regions-eq-aspect.pdf")

        print("Output written to stab-regions.pdf and stab-regions-eq-aspect.pdf")
    else:
        pt.show()

if __name__ == "__main__":
    main()


# -*- coding: gb18030 -*-
#
# $Id: EspialWindow.py Exp $

from guis import *
from LabelGather import labelGather
from guis.common.Window import Window
from guis.common.PyGUI import PyGUI
from guis.controls.Control import Control
from guis.controls.Button import Button
from guis.controls.StaticText import StaticText
from guis.controls.ProgressBar import HProgressBar
from guis.tooluis.CSRichText import CSRichText
from guis.controls.ButtonEx import HButtonEx
from guis.controls.ODPagesPanel import ODPagesPanel
from guis.controls.RichText import RichText
from guis.tooluis.richtext_plugins.PL_Image import PL_Image
from guis.tooluis.richtext_plugins.PL_Font import PL_Font
from guis.tooluis.richtext_plugins.PL_NewLine import PL_NewLine
from RobotRender import RobotRender
from RobotInfosLoader import robotInfosLoader
from guis.general.petswindow.vehiclepanel.VehiclePanel import GuardAttr as RobotAttr
from NPCModelLoader import NPCModelLoader
g_npcmodel = NPCModelLoader.instance()
import csdefine
import csconst
import GUIFacade

class RobotProperty( Window ):
	"""
	机器人属性界面
	"""
	_cc_items_rows = ( 3, 2 )

	def __init__( self ):
		wnd = GUI.load( "guis/general/lolpvp/prownd.gui" )
		uiFixer.firstLoadFix( wnd )
		Window.__init__( self, wnd )
		self.posZSegment = ZSegs.L4
		self.activable_ = True
		self.escHide_ 		 = True

		self.__triggers = {}
		self.__registerTriggers()
		self.__turnModelCBID = 0
		self.__trapID = 0
		self.__allModels = {}
		self.__teamNumber = 0
		self.__modifyIndex = -1
		self.__initialize( wnd )

	def __initialize( self, wnd ):
		self.__pyLifeBar = HProgressBar( wnd.lifeBar )
		self.__pyLifeBar.clipMode = "RIGHT"
		self.__pyLifeBar.value = 0.0

		self.__pyStLifeRatio = StaticText( wnd.stLifeRatio )
		self.__pyStLifeRatio.text = ""

		self.__pyStRobotName = StaticText( wnd.stGuardName ) #骑宠名称
		self.__pyStRobotName.text= ""

		self.__pyBtnLeft = Button( wnd.btnLeft ) #向左转动模型
		self.__pyBtnLeft.setStatesMapping( UIState.MODE_R2C2 )
		self.__pyBtnLeft.onLMouseDown.bind( self.__onTurnLeft )

		self.__pyBtnRight = Button( wnd.btnRight ) #向右转动模型
		self.__pyBtnRight.setStatesMapping( UIState.MODE_R2C2 )
		self.__pyBtnRight.onLMouseDown.bind( self.__onTurnRight )

		self.__pyRobotsPage = ODPagesPanel( wnd.guardsPanel, wnd.pgIdxBar )
		self.__pyRobotsPage.onViewItemInitialized.bind( self.__initListItem )
		self.__pyRobotsPage.onDrawItem.bind( self.__drawListItem )
		self.__pyRobotsPage.selectable = True
		self.__pyRobotsPage.onItemSelectChanged.bind( self.__onRobotSelChange )
		self.__pyRobotsPage.viewSize = self._cc_items_rows

		self.__pyBtnOk = HButtonEx( wnd.btnOk )
		self.__pyBtnOk.setExStatesMapping( UIState.MODE_R3C1 )
		self.__pyBtnOk.onLClick.bind( self.__onOK ) #
		labelGather.setPyBgLabel( self.__pyBtnOk, "LolPVP:RobotProperty", "btnOk" )

		self.__pyBtnCancel = HButtonEx( wnd.btnCancel )
		self.__pyBtnCancel.setExStatesMapping( UIState.MODE_R3C1 )
		self.__pyBtnCancel.onLClick.bind( self.__onCandel ) #
		labelGather.setPyBgLabel( self.__pyBtnCancel, "LolPVP:RobotProperty", "btnCancel" )

		self.__pyRtIntro = CSRichText( wnd.introBg.rtIntro )
		self.__pyRtIntro.text = ""

		self.__pyRobotRender = RobotRender( wnd.guardRender )

		self.__pyRobotAttrs = {}									#守护的属性
		for name, item in wnd.children:
			if "attr_" not in name:continue
			tag = name.split( "_" )[1]
			pyVehicleAttr = RobotAttr( item )
			pyVehicleAttr.title = labelGather.getText( "LolPVP:RobotProperty", tag )
			pyVehicleAttr.text = ""
			self.__pyRobotAttrs[tag] = pyVehicleAttr
		labelGather.setPyLabel( self.pyLbTitle_, "LolPVP:RobotProperty", "lbTitle" )
		labelGather.setLabel( wnd.nameText, "LolPVP:RobotProperty", "nameText" )
		labelGather.setLabel( wnd.expText, "LolPVP:RobotProperty", "lifeText" )
		labelGather.setLabel( wnd.listBg.bgTitle.stTitle, "LolPVP:RobotProperty", "robotList")
		labelGather.setLabel( wnd.attrsBg.bgTitle.stTitle, "LolPVP:RobotProperty", "robotAttrs")
		labelGather.setLabel( wnd.introBg.bgTitle.stTitle, "LolPVP:RobotProperty", "robotIntro")

	# ----------------------------------------------------------
	# private
	# ----------------------------------------------------------
	def __registerTriggers( self ):
#		self.__triggers["EVT_ON_PVE_ADD_ROBOT"] = self.__onAddRobot
#		self.__triggers["EVT_ON_PVE_REMOVE_ROBOT"] = self.__onRemovRobot
#		self.__triggers["EVT_ON_PVE_UPDATE_ROBOT"] = self.__onUpateRobot
		self.__triggers["EVT_ON_ROBOT_SELECTED"] = self.__onRobotSelected
		for key in self.__triggers :
			ECenter.registerEvent( key, self )

	def __deregisterTriggers( self ) :
		"""
		deregister all events
		"""
		for key in self.__triggers.iterkeys() :
			ECenter.registerEvent( key, self )
	# ----------------------------------------------------------------------
	def __initListItem( self, pyViewItem ):
		"""
		初始化添加的商品列表项
		"""
		pyRobot = RobotItem()
		pyViewItem.pyRobot = pyRobot
		pyViewItem.addPyChild( pyRobot )
		pyViewItem.dragFocus = False
		pyViewItem.focus = False
		pyRobot.left = 0
		pyRobot.top = 0

	def __drawListItem( self, pyViewItem ) :
		"""
		重画商品列表项
		"""
		robotInfo = pyViewItem.pageItem
		pyRobot = pyViewItem.pyRobot
		pyRobot.selected = pyViewItem.selected
		pyRobot.update( robotInfo )
		pyViewItem.focus = robotInfo is not None

	def __onAddRobot( self, robot ):
		"""
		增加机器人
		"""
		if robot is None:return
		objectID = robot.objectID
		if not objectID in [item.objectID for item in self.__pyRobotsPage.items]:
			self.__pyRobotsPage.addItem( robot )

	def __onRemovRobot( self, objectID ):
		"""
		删除机器人
		"""
		for robot in self.__pyRobotsPage.items:
			if robot.objectID == objectID:
				self.__pyRobotsPage.removeItem( robot )

	def __onUpateRobot( self, oldIndex, newRobot ):
		"""
		更新机器人
		"""
		pass

	def __onRobotSelChange( self, selIndex ):
		"""
		选择某个机器人
		"""
		if selIndex < 0:return
		player = BigWorld.player()
		robotInfo = self.__pyRobotsPage.selItem
		# 刷新模型
		modelNum = robotInfo.modelNum
		className = robotInfo.className
		robotInfos = player.baoZangRobotInfos
		if not className in robotInfos:return
		robotInfo = robotInfos[className]
		uiRbtInfo = robotInfosLoader.getRobotInfo( className )
		if uiRbtInfo is None:return
		level = robotInfo["level"]
		raceclass = robotInfo["robotClass"]
		soulCoin = robotInfo["accumPoint"]
		life = int( robotInfo["hp_max"] )
		force = robotInfo["damage"]
		self.__setModel( className, modelNum )
		self.__pyStRobotName.text = robotInfo["robotName"]
		self.__onAttrUpdate( "soulCoin", soulCoin )
		self.__onAttrUpdate( "life", life )
		self.__onAttrUpdate( "force", force )
		robotInfosLoader.setRbtExtraInfo( className, level, raceclass, soulCoin, life, 0, force )
		self.__pyRtIntro.text = uiRbtInfo.dsp
		self.__pyLifeBar.value = 1.0
		self.__pyStLifeRatio.text = "%d/%d"%( int( life ), int( life ) )

	def __onRobotSelected( self, className ):
		"""
		选择某个机器人
		"""
		for pyViewItem in self.__pyRobotsPage.pyViewItems:
			robotInfo = pyViewItem.pageItem
			pyRobot = pyViewItem.pyRobot
			if robotInfo is None:continue
			pyRobot.selected = robotInfo.className == className
			if robotInfo.className == className:
				self.__pyRobotsPage.selItem = robotInfo

	def __onLastKeyUpEvent( self, key, mods ) :
		if key != KEY_LEFTMOUSE : return
		BigWorld.cancelCallback( self.__turnModelCBID )
		LastKeyUpEvent.detach( self.__onLastKeyUpEvent )

	def __onTurnLeft( self ):
		BigWorld.cancelCallback( self.__turnModelCBID )
		self.__turnModel( False )
		LastKeyUpEvent.attach( self.__onLastKeyUpEvent )
		return True

	def __onTurnRight( self ):
		BigWorld.cancelCallback( self.__turnModelCBID )
		self.__turnModel( True )
		LastKeyUpEvent.attach( self.__onLastKeyUpEvent )
		return True

	def __turnModel( self, isRTurn ) :
		"""
		turning model on the mirror
		"""
		self.__pyRobotRender.yaw += ( isRTurn and -0.1 or 0.1 )
		if BigWorld.isKeyDown( KEY_LEFTMOUSE ) :
			self.__turnModelCBID = BigWorld.callback( 0.1, Functor( self.__turnModel, isRTurn ) )

	def __setModel( self, className, modelNum ):
		"""
		设置DBID的模型
		"""
		player = BigWorld.player()
		if player is None: return

		if className in self.__allModels:
			model = self.__allModels[className]
			self.__pyRobotRender.update( className, model )
		else:
			rds.npcModel.createDynamicModelBG( modelNum, Functor( self.__onModelCreated, className, modelNum ) )

	def __onModelCreated( self, className, modelNum, model ):
		"""
		模型后线程加载完回调
		"""
		self.__allModels[className] = model
		selRobotInfo = self.__pyRobotsPage.selItem
		if selRobotInfo is None:return
		if className == selRobotInfo.className:
			self.__pyRobotRender.update( className, model )

	def __onAttrUpdate( self, attrTag, value ):
		"""
		更新守护属性
		"""
		if self.__pyRobotAttrs.has_key( attrTag ):
			pyStAttr = self.__pyRobotAttrs[attrTag]
			pyStAttr.text = str( value )

	def __clearAttrs( self ):
		for tag, pyStAttr in self.__pyRobotAttrs.iteritems():
			pyStAttr.text = ""

	def __onOK( self ):
		"""
		确定选择
		"""
		selRobotInfo = self.__pyRobotsPage.selItem
		if selRobotInfo is None:return
		if self.__modifyIndex >= 0:
			ECenter.fireEvent( "EVT_ON_UPDATE_PVE_ROBOT", self.__teamNumber, self.__modifyIndex, selRobotInfo )
		else:
			ECenter.fireEvent( "EVT_ON_ADD_PVE_ROBOT", self.__teamNumber, selRobotInfo )

	def __onCandel( self ):
		"""
		取消选择
		"""
		self.hide()

	# ----------------------------------------------------------
	#public
	# ---------------------------------------------------------
	def onEvent( self, eventMacro, *args ) :
		"""
		respond base triggering
		"""
		self.__triggers[eventMacro]( *args )

	def onLeaveWorld( self ):
		self.hide()

	def show( self, teamNumber = 0, modifyIndex = -1, pyBinder = None ):
		self.__pyRobotsPage.clearItems()
		self.__teamNumber = teamNumber
		self.__modifyIndex = modifyIndex
		classNames = []
		if teamNumber == 0:
			classNames = csconst.YXLM_ROBOT_1
		else:
			classNames = csconst.YXLM_ROBOT_2
		for className in classNames:
			robotInfo = robotInfosLoader.getRobotInfo( className )
			if robotInfo is None:continue
			self.__pyRobotsPage.addItem( robotInfo )
		BigWorld.player().baoZangReqRobotInfos()
		self.__pyRobotRender.enableDrawModel()
		self.__pyRobotsPage.selIndex = 0
		Window.show( self, pyBinder )

	def hide( self ):
		Window.hide( self )
		self.__pyRobotRender.disableDrawModel()

# ------------------------------------------------------------------------------------------------

class RobotItem( Control ):
	def __init__( self ):
		vcItem = GUI.load( "guis/general/petswindow/vehicleitem.gui")
		uiFixer.firstLoadFix( vcItem )
		Control.__init__( self, vcItem )
		self.crossFocus = False
		self.dragFocus = False
		self.focus = False
		self.__pyCover = None
		self.__pyVehicleBg = PyGUI( vcItem.petBg )
		self.infoBg = vcItem.infoBg
		self.__pyItem = Item( vcItem.item, self )
		self.__pyRtInfo = CSRichText( vcItem.rtInfo )
		self.__pyRtInfo.top = 15.0
		self.__pyRtInfo.maxWidth = 100.0
		self.__pyRtInfo.align = "C"
		self.__pyRtInfo.lineFlat = "M"
		self.__pyRtInfo.fontSize = 14.0
		self.robotInfo = None
		self.__panelState = ( 1, 1 )
		if hasattr( vcItem, "cover" ) :
			self.__pyCover = PyGUI( vcItem.cover )
			self.__pyCover.visible = False

	# -------------------------------------------------------------
	# public
	# -------------------------------------------------------------
	def update( self, robotInfo ):
		name = ""
		if robotInfo:
			name = robotInfo.name
			nameText = PL_Font.getSource( "%s"%name, fc = ( 0, 255, 255, 255 ) )
			self.__pyRtInfo.text = nameText
			self.__pyItem.crossFocus = True
			util.setGuiState( self.__pyVehicleBg.getGui(), ( 1,2 ),( 1, 1 ) )
		else:
			self.__pyRtInfo.text = ""
			self.__pyItem.crossFocus = False
			util.setGuiState( self.__pyVehicleBg.getGui(), ( 1,2 ),( 1, 2 ) )
		self.robotInfo = robotInfo
		self.__pyItem.update( robotInfo )

	def __select( self ):
		self.panelState = ( 3, 1 )
		if self.__pyCover:
			self.__pyCover.visible = True

	def __deselect( self ):
		self.panelState = ( 1, 1 )
		if self.__pyCover:
			self.__pyCover.visible = False

	def revertVehicleName( self, baseItem ):
		"""
		还原骑宠类物品名字
		骑宠蛋(XXX) -> XXX
		"""
		name = baseItem.name()
		return name.split("(")[-1].split(")")[0]

	# ----------------------------------------------------------------
	# property methods
	# ----------------------------------------------------------------
	def getObjectItem( self ):
		return self.__pyItem

	def _getPanelState( self ):
		return self.__panelState

	def _setPanelState( self, state ):
		self.__panelState = state
		elements = self.infoBg.elements
		for ename, element in elements.items():
			element.mapping = util.getStateMapping( element.size, UIState.MODE_R3C1, state )
			if ename in ["frm_rt", "frm_r", "frm_rb"]:
				element.mapping = util.hflipMapping( element.mapping )

	def _getSelected( self ):
		return self.__selected

	def _setSelected( self, selected ):
		if selected:
			self.__select()
		else:
			self.__deselect()
		self.__selected = selected
	# -------------------------------------------------
	panelState = property( _getPanelState, _setPanelState )
	selected = property( _getSelected, _setSelected )

# ----------------------------------------------------------------------
import event.EventCenter as ECenter
from guis.controls.Item import Item as BOItem
from guis import *
import BigWorld

class Item( BOItem ):
	def __init__( self, item, pyBinder = None ):
		BOItem.__init__( self, item, pyBinder )
		self.focus = True
		self.crossFocus = True
		self.dragFocus = False
		self.selectable = True
		self.description = ""
		self.index = 0
		self.__initialize( item )

	def subclass( self, item ) :
		BOItem.subclass( self, item )
		self.__initialize( item )
		return True

	def __initialize( self, item ) :
		if item is None : return

	def onMouseEnter_( self ):
		#BOItem.onMouseEnter_( self )
		toolbox.itemCover.highlightItem( self )
		if self.pyBinder.robotInfo is None:return
		if self.pyBinder.selected:return
		self.pyBinder.panelState = ( 2, 1 )
		return True

	def onMouseLeave_( self ):
		BOItem.onMouseLeave_( self )
		if self.pyBinder.robotInfo is None:return
		if self.pyBinder.selected:return
		self.pyBinder.panelState = ( 1, 1 )
		return True

	def onRClick_( self,mods ):
		BOItem.onRClick_( self, mods )
		return True

	def onLClick_( self, mods ):
		if self.pyBinder.robotInfo is None:return
		BOItem.onLClick_( self, mods )
		robotInfo = self.pyBinder.robotInfo
		ECenter.fireEvent( "EVT_ON_ROBOT_SELECTED", robotInfo.className )
		return True

	# -------------------------------------------------
	def onDragStart_( self, pyDragged ) :
		BOItem.onDragStart_( self, pyDragged )
		if BigWorld.isKeyDown( KEY_LCONTROL ) :
			rds.ruisMgr.dragObj.attach = KEY_LCONTROL
		if self.itemInfo is None:return
		rds.ruisMgr.hideBar.enterShow()
		return True

	def onDragStop_( self, pyDragged ) :
		if self.pyBinder.robotInfo is None:return
		rds.ruisMgr.hideBar.leaveShow()
	# -----------------------------------------------
	# public
	# -----------------------------------------------
	def update( self, robotInfo ):
		"""
		update item
		"""
		headTexture = ""
		if robotInfo:
			modelNum = robotInfo.modelNum
			headTexture = g_npcmodel.getHeadTexture( modelNum )
		self.texture = headTexture
#		BOItem.update( self, robotInfo )


import numpy as np
import Interpolation as interpolation

class linedg:
    def __init__(self, mesh, params, equations):
        self.params = params
        self.__dim   = 1
        self.__neqs  = params.neqs()
        self.__order = params.order()
        self.__nnodes = self.__order+1
        self.__nels  = params.nels()
        self.__nquads = params.nquads()
        self.ip = interpolation.Interpolation(self.__nnodes, self.__nquads)
        self.mesh  = mesh
        self.mass = np.matmul(np.transpose(self.ip.B()), np.matmul(self.ip.W(), self.ip.B()) )
        self.invMass = np.linalg.inv(self.mass)
        self.__q = np.zeros([self.__nels,self.__nnodes,self.__neqs])
        self.equations = equations
        self.__leftBC = np.zeros([self.__neqs])
        self.__rightBC = np.zeros([self.__neqs])

    def order(self) -> int:
        return self.__order

    def q(self) -> np.array:
        return self.__q

    def Flux(self, u: np.array) -> np.array:
        F = self.equations.Flux(u)
        return F*self.mesh.J()*self.mesh.invJ()

    def SetBC(self):
        if (self.params.BoundaryConditions() == "periodic"):
            self.__leftBC = self.u[self.__nels-1, self.__nnodes-1,:]
            self.__rightBC = self.u[0,0,:]
        elif (self.params.BoundaryConditions() == "outflow"):
            self.__leftBC = self.params.LeftBC()
            self.__rightBC = self.params.RightBC()
        # elif (self.params.BoundaryConditions() == "outflow"):

    def AssembleElement(self, u: np.array) -> np.array:
        self.u = u
        self.SetBC()
        q = np.zeros([self.__nnodes,self.__neqs])
        U = np.zeros([self.__nels, self.__nquads, self.__neqs])
        fstar = np.zeros([2,self.__neqs])
        for iel in range(self.__nels):
            # Compute u at quadrature points
            for ieq in range(self.__neqs):
                U[iel,:,ieq] = np.matmul(self.ip.B(),self.u[iel,:,ieq])

            # Compute flux at quadrature points
            F = np.zeros(U.shape)
            for iq in range(self.__nquads):
                # print(U[iel,iq,:])
                F[iel,iq,:] = self.Flux(U[iel,iq,:])

            for ieq in range(self.__neqs):
                #Compute volume term
                q[:,ieq] = -np.matmul( np.transpose(self.ip.D()), np.matmul(self.ip.W(), F[iel,:,ieq]) )
                # Compute numerical flux
                if (iel == 0):
                    leftBC = self.equations.Prim2Cons(self.__leftBC)
                    temp = self.RiemannSolver(leftBC,self.u[iel,0,:])
                    fstar[0,ieq] = temp[ieq]
                    # fstar[0,ieq] = self.RiemannSolver(self.__leftBC[ieq],self.u[iel,0,ieq])

                    temp = self.RiemannSolver(self.u[iel,-1,:], self.u[iel+1,0,:])
                    fstar[-1,ieq] = temp[ieq]
                    # fstar[-1,ieq] = self.RiemannSolver(self.u[iel,-1,ieq], self.u[iel+1,0,ieq])
                elif (iel == self.__nels-1):
                    temp = self.RiemannSolver(self.u[iel-1,-1,:], self.u[iel,0,:])
                    fstar[0,ieq] = temp[ieq]

                    rightBC = self.equations.Prim2Cons(self.__rightBC)
                    temp =self.RiemannSolver(self.u[iel,-1,:], rightBC)
                    fstar[-1,ieq] = temp[ieq]
                else:
                    temp = self.RiemannSolver(self.u[iel-1,-1,:], self.u[iel,0,:])
                    fstar[0,ieq] = temp[ieq]

                    temp = self.RiemannSolver(self.u[iel,-1,:], self.u[iel+1,0,:])
                    fstar[-1,ieq] = temp[ieq]

                q[0,ieq] -= fstar[0,ieq]
                q[-1,ieq] += fstar[1,ieq]
                self.__q[iel,:,ieq] = np.matmul(self.invMass, q[:,ieq])
        return -self.__q/self.mesh.detJ()

    ######################################################
    #
    # Riemann Solver Functions
    #
    #######################################################

    def RiemannSolver(self, uleft: np.array, uright: np.array) -> np.array:
        rs = self.params.RiemannSolver()
        if (rs == "upwind"):
            c = np.max(self.u)
            fhat = self.Upwind(c,uleft,uright)
        elif (rs == "godunov"):
            fhat = self.Godunov(uleft,uright)
        elif (rs == "lf"):
            fhat = self.LF(uleft,uright)
        elif (rs == "llf"):
            fhat = self.LLF(uleft,uright)
        return fhat

    def Upwind(self, c, uleft: np.array, uright: np.array) -> np.array:
        if (c >= 0 ):
            ustar = uleft
        elif (c < 0):
            ustar = uright
        fstar = self.Flux(ustar)
        return fstar

    def Godunov(self, uleft: np.array, uright: np.array) -> np.array:
        s = 0.5*(uleft + uright)
        if (uleft >= uright):
            if (s >= 0):
                ustar = uleft
            else:
                ustar = uright
        elif (uleft < uright):
            if (uleft >= 0):
                ustar = uleft
            elif (uright <= 0):
                ustar = uright
            elif (uleft < 0 and uright > 0):
                ustar = 0
        Fstar = self.Flux(ustar)
        return Fstar

    def LF(self, uleft: np.array, uright: np.array) -> np.array:
        Cmax = np.amax(self.equations.Dflux(self.u))
        FL = self.Flux(uleft)
        FR = self.Flux(uright)
        avgState = 0.5*(FL + FR)
        jump     = uright - uleft
        Fstar    = avgState - 0.5*Cmax*jump
        return Fstar

    def LLF(self, uleft: np.array, uright: np.array) -> np.array:

        assert(self.equations.IsStatePhysical(uleft))
        assert(self.equations.IsStatePhysical(uright))

        Cmax = np.amax([self.equations.Dflux(uleft),self.equations.Dflux(uright)])
        FL = self.Flux(uleft)
        FR = self.Flux(uright)
        avgState = 0.5*(FL + FR)
        jump     = uright - uleft
        Fstar    = avgState - 0.5*Cmax*jump
        return Fstar