import random
from gcolor import Gcolor
import gtime
from perspective import Perspective
from cardinal import Cardinal
from celestial_cluster import CelestialCluster
from syscomm import SysComm

import os
import math
from graficos import grafico

'''
equaçoes de colisão(2D):
Vf * cos{angulo final} *(m1 + m2) = m1 * v1 + m2 * v2 * cos{angulo entre obj1 e obj2}
Vf * sin{angulo final} *(m1 + m2) = m2 * v2 *sin{angulo entre obj1 e obj2}

Algebra:
Vf  = m1 * v1 + m2 * v2 * cos{angulo entre obj1 e obj2} / (cos{angulo final} *(m1 + m2))

sin{angulo final} = m2 * v2 *sin{angulo entre obj1 e obj2} / (m1 * v1 + m2 * v2 * cos{angulo entre obj1 e obj2} / (cos{angulo final} *(m1 + m2)) *(m1 + m2))

'''
def colisão_2D_a(orbi_1,orbi_2):

    m1 = orbi_1.mass
    v1 =(orbi_1.speed.x**2 + orbi_1.speed.y**2) **(1/2)
    v1 = math.fabs(v1)

    m2 = orbi_2.mass
    v2 =(orbi_2.speed.x**2 + orbi_2.speed.y**2) **(1/2)
    v2 = math.fabs(v2)

    angulo = (((orbi_1.speed.x * orbi_2.speed.x) + (orbi_1.speed.y * orbi_2.speed.y)) / (math.sqrt((orbi_1.speed.x ** 2) * (orbi_1.speed.y ** 2)) * (math.sqrt((orbi_1.speed.y ** 2) * (orbi_1.speed.y ** 2)))))
    angulo = math.cos(angulo)

    angulo_final_SemSin = m2 * v2 * math.sin(angulo)/ ((m1 * v1 + m2 * v2 * math.cos(angulo))/ (math.cos(angulo) * (m1 + m2)) *(m1 + m2))
    angulo_final = math.sin(angulo_final_SemSin)

    Vf = m1 * v1 + m2 * v2 * math.cos(angulo) / (math.cos(angulo_final) *(m1 + m2))

    return Vf,angulo_final

def distancia(orbi_a,orbi_b):
    dist = math.sqrt(((orbi_a.position.x - orbi_b.position.x)**2) + ((orbi_a.position.y - orbi_b.position.y) **2))
    return math.fabs(dist)

def distancia_2_planetas(cluster,orbi_1,orbi_2):
    try:
        for planet in cluster:
            if planet.color == orbi_1:
                planeta_1 = planet
#                print(planeta_1)

            if planet.color == orbi_2:
                planeta_2 = planet
#                print(planeta_2)

        return distancia(planeta_1,planeta_2)
    except:
        print('planeta não encontrado')

class StarDome():

    def __init__(self):
        #generate stars
        starnum= 30000
        self.star= []

        for num in range(starnum):
            self.star.append( [(random.randint(0, MainFrame.HEIGTH-1), random.randint(0, MainFrame.WIDTH-1)), random.randint(3, 8) ])

    def draw(self):
        canvas.fill(Gcolor.WHITE)
        for stup in self.star:
            draw.circle(MainFrame.CANVAS, Gcolor.BLACK, stup[0], stup[1])

    def update(self):
        pass

def summon_asteroid():

    speed= None
    mass= None
    RADIUS= None
    #asteroid= OrbitalBody(position, speed, mass, RADIUS)

CelestialCluster.init()

distancia_corpos = []

from display import Display
os.environ['SDL_VIDEO_WINDOW_POS'] = "0, 0"
#--MAIN LOOP--

while not SysComm.quit:
    current_time= gtime.current()

    #update system interface
    SysComm.update()

    #update things
    CelestialCluster.update()
    Perspective.update()

    #draw things
    Display.update()

    gtime.update()
    elapsed_time= gtime.current()-current_time
    if elapsed_time < 16:
        gtime.sleep( 16 - elapsed_time)

    #print(distancia_corpos)
    #grafico(ticks,distancia_corpos,gtime.RESOLUTION)
    #distancia_corpos.append(distancia_2_planetas(celestial_cluster.cluster,color.EARTH,color.SUN))


#!/usr/bin/env python
# coding: utf-8

# In[1]:

# Implement by Zhe Chu, Jun 17,2021
# This python script file implement the THz Channel model introduced by
#A. Saeed, O. Gurbuz, A. O. Bicen and M. A. Akkas,
#"Variable-Bandwidth Model and Capacity Analysis for Aerial Communications in the Terahertz Band,"
#in IEEE Journal on Selected Areas in Communications, vol. 39, no. 6, pp. 1768-1784, June 2021, doi: 10.1109/JSAC.2021.3071831.

# In[2]:

import matplotlib.pyplot as plt

import numpy as np

import math
from matplotlib.pyplot import figure
import matplotlib.pylab as pylab

# In[3]:

# Our model focusing on altitude between 10km to 16km. US standard 1976 is our atmospheric model.
# Antenna transmission power = 37 dBm, gain = 80 dBi.
# band (0.75-10THz) in the paper; however, we only take 10% of the whole band.

# In[4]:

# band (0.75-10THz)
# 10km alitutde model
altitude = 10 #km

transmission_distance = [1,2,3,4,5,6,7,8,9,10] #km

capacity =[11.53, 3.5, 1.5, 1, 0.5, 0.3, 0.2, 0.1, 0.1, 0] #Tbps

zenith_angle = [0,30,60,90,120,150,180]

zenith_capacity = [14.1, 14, 13.5, 11.53, 10, 8.5, 8.1] # with distance = 1km

# In[5]:

# I divided it by 10 right here, sice the real bandwidth can be use is much smaller

capacity_copy = [element * 0.027 for element in capacity]

zenith_capacity_copy = [element * 0.027 for element in zenith_capacity]

capacity = capacity_copy

zenith_capacity = zenith_capacity_copy

# In[6]:

def estimate_data_at_0_distance(transmission_distance,capacity):

    if(transmission_distance[0]!=0):

        slop = (capacity[1] - capacity[0])/(transmission_distance[1]-transmission_distance[0])

        value_at_zero = capacity[0]-slop*transmission_distance[0]

        #print(slop,value_at_zero)

        transmission_distance.insert(0,0)

        capacity.insert(0,value_at_zero)

    return([transmission_distance,capacity])

# In[7]:

[transmission_distance,capacity] = estimate_data_at_0_distance(transmission_distance,capacity)

#print(transmission_distance)
#print(capacity)

# In[8]:

def plot_channel_capacity(altitude, transmission_distance,capacity,zenith_angle=[],zenith_capacity=[] ):

    params = {'legend.fontsize': 'x-large',
              'figure.figsize': (10, 5),
              'axes.labelsize': 'x-large',
              'axes.titlesize':'x-large',
              'xtick.labelsize':'x-large',
              'ytick.labelsize':'x-large'}
    pylab.rcParams.update(params)

    plt.rcParams.update({'font.size': 11})

    # =========channel capacity vs distance=========
    plot1 = plt.figure(1)

    plt.plot(transmission_distance, capacity)
    # naming the x axis
    plt.xlabel('Transmission Distance (km)')
    # naming the y axis
    plt.ylabel('Capacity(Tbps)')
    # giving a title to my graph
    title_name = 'Capacity(Tbps) vs Distance at Altitude '+str(altitude)+ ' km'

    plt.title(title_name)

    plt.ylim(0,)
    plt.xlim(1,)
    plt.grid()

    for a,b in zip(transmission_distance,capacity):
        plt.text(a, b, str(b))

    plt.xticks(np.arange(min(transmission_distance), max(transmission_distance)+1, 1.0))

    # =========channel capacity vs zenith angle===========
    if(len(zenith_capacity)!=0 and len(zenith_angle)!=0):

        plot1 = plt.figure(2)

        plt.plot(zenith_angle, zenith_capacity)
        # naming the x axis
        plt.xlabel('Zenith Angle (degrees)')
        # naming the y axis
        plt.ylabel('Capacity(Tbps)')
        # giving a title to my graph
        title_name = 'Capacity(Tbps) vs Zenith Angle (degrees) at Altitude '+str(altitude)+ ' km'

        plt.title(title_name)

        plt.ylim(zenith_capacity[-1]*0.9,zenith_capacity[0]*1.1)
        plt.xlim(0,180)
        plt.grid()

        for a,b in zip(zenith_angle, zenith_capacity):
            plt.text(a, b, str(b))

        plt.xticks(np.arange(min(zenith_angle), max(zenith_angle)+1,30))

        plt.show()

#plot_channel_capacity(altitude, transmission_distance,capacity,zenith_angle,zenith_capacity)

# In[9]:

def Reverse(lst):
    return [ele for ele in reversed(lst)]

# In[10]:

class channels:

    def __init__(self, transmission_distance, capacity, zenith_angle, zenith_capacity, altitude):

        self.transmission_distance = transmission_distance

        self.capacity = capacity

        self.zenith_angle = zenith_angle

        self.zenith_capacity = zenith_capacity

        self.altitude = altitude

# In[11]:

jet_channel =  channels(transmission_distance, capacity, zenith_angle, zenith_capacity, altitude)

# In[12]:

# 16km alitutde model
# UAV altitude data

# In[13]:

# 33.6 dBm, 80 dBi #ignor the minor changes in antenna dBm
# band (0.75-10THz)

altitude = 16 #km

transmission_distance = [1,2,3,4,5,6,7,8,9,10] #km

capacity =[34.65, 15, 7.5, 4, 3.5, 2, 1.5, 1, 0.5, 0] #Tbps

zenith_angle = [0,30,60,90,120,150,180]

zenith_capacity = [36.3, 36.2, 35.5, 34.65,33.4, 32.5, 32.18] # with distance = 1km

# In[14]:

# I divided it by 10 right here, sice the real bandwidth can be use is much smaller

capacity_copy = [element * 0.027 for element in capacity]

zenith_capacity_copy = [element * 0.027 for element in zenith_capacity]

capacity = capacity_copy

zenith_capacity = zenith_capacity_copy

# In[15]:

[transmission_distance,capacity] = estimate_data_at_0_distance(transmission_distance,capacity)

# In[16]:

#plot_channel_capacity(altitude, transmission_distance,capacity,zenith_angle,zenith_capacity)

# In[17]:

UAV_channel =  channels(transmission_distance, capacity, zenith_angle, zenith_capacity, altitude)

# In[18]:

#print(UAV_channel.zenith_capacity)
#print(jet_channel.zenith_capacity)

# In[19]:

# Accroding to fig 6 in paper, channel capacity is almost linearly increasing vs altitude increasing
# Hence, channel capacitance at each specific altitude can be estimated
# However, what we want to have is the channel capacitance for two nodes at different altitude.
# Capacitance vs Zenith Angle graphy provide us the vertical(altitude) direction information
# We want to estimate Capacitance vs Zenith Angle at each altitude

# In[20]:

def cap_vs_zenith_at_target_altitude(target_altitude,                                     low_altitude_channel_model = jet_channel,                                     high_altitude_channel_model = UAV_channel ):

    angles = low_altitude_channel_model.zenith_angle

    start_altitude = low_altitude_channel_model.altitude

    end_altitude = high_altitude_channel_model.altitude

    start_cap_vs_znith_curve = low_altitude_channel_model.zenith_capacity

    end_cap_vs_znith_curve   = high_altitude_channel_model.zenith_capacity

    target_altitude = target_altitude

    cap_vs_zenith_at_target_altitude = []

    for i in range(len(start_cap_vs_znith_curve)):

        bot_val = start_cap_vs_znith_curve[i]

        up_val = end_cap_vs_znith_curve[i]

        slope = (up_val-bot_val)/(end_altitude-start_altitude)

        #print(slope)

        new_val = bot_val + slope* (target_altitude - start_altitude)

        new_val = max(0,new_val)

        cap_vs_zenith_at_target_altitude.append(new_val)

    return(cap_vs_zenith_at_target_altitude)

# In[21]:

#test_cap_vs_zenith = cap_vs_zenith_at_target_altitude(14)

#print(test_cap_vs_zenith)

# In[22]:

#plot
'''
for test_altitude in range(jet_channel.altitude - 1, UAV_channel.altitude + 1):

    params = {'legend.fontsize': 'x-large',
              'figure.figsize': (30, 20),
              'axes.labelsize': 'x-large',
              'axes.titlesize':'x-large',
              'xtick.labelsize':'x-large',
              'ytick.labelsize':'x-large'}
    pylab.rcParams.update(params)

    plt.rcParams.update({'font.size': 22})

    plot1 = plt.figure(1)

    test_cap_vs_zenith = cap_vs_zenith_at_target_altitude(test_altitude)

    label = "Altitude = "+str(test_altitude)+"km"

    plt.plot(zenith_angle, test_cap_vs_zenith, label=label)

    for e in range(len(test_cap_vs_zenith)):

        test_cap_vs_zenith[e] = round(test_cap_vs_zenith[e],2)

    for a,b in zip(zenith_angle, test_cap_vs_zenith):
        plt.text(a, b, str(b))

    #print(test_cap_vs_zenith[0] - test_cap_vs_zenith[-1])

plt.grid()

plt.xticks(np.arange(min(zenith_angle), max(zenith_angle)+70,30))

plt.legend()

plt.show()
'''

# In[23]:

def find_channel_cap_vs_dsitance_at_specific_altitude(altitude,                                                      low_altitude_channel_model= jet_channel,                                                      high_altitude_channel_model = UAV_channel):

    bottom_cureve = low_altitude_channel_model.capacity

    upper_cureve  = high_altitude_channel_model.capacity

    start_altitude = low_altitude_channel_model.altitude

    end_altitude = high_altitude_channel_model.altitude

    alt_dif = end_altitude - start_altitude

    cureve_at_traget_altitude = []

    for i in range(len(bottom_cureve)):

        bottom_cap = bottom_cureve[i]

        upper_cap = upper_cureve[i]

        slop = (upper_cap - bottom_cap)/alt_dif

        estimate_cap = bottom_cap + slop*(altitude - start_altitude)

        cureve_at_traget_altitude.append(estimate_cap)

    return cureve_at_traget_altitude

# In[24]:

#test_curve = (find_channel_cap_vs_dsitance_at_specific_altitude(13))

#plot_channel_capacity(13 , transmission_distance,test_curve)

# In[25]:

# given X,Y data points, try to find y value when given a x

def estimate_value_by_cureve_slop(x_vals,y_vals,target_x):

    if(target_x<x_vals[0]):

        slop = (y_vals[1] - y_vals[0])/(x_vals[1] - x_vals[0])

        result = y_vals[0]-slop*(x_vals[0]-target_x)

        return result

    elif(target_x>x_vals[-1]):

        slop = (y_vals[-1] - y_vals[-2])/(x_vals[-1] - x_vals[-2])

        result = y_vals[-1]+slop*(target_x-x_vals[-1])

        return result

    i=0

    while(x_vals[i]<target_x):

        i+=1

    i-=1

    x1 = x_vals[i]
    x2 = x_vals[i+1]
    y1 = y_vals[i]
    y2 = y_vals[i+1]

    slop = (y2-y1)/(x2-x1)

    result = y1+slop*(target_x-x1)

    return result

# In[26]:

#test = estimate_value_by_cureve_slop(x_vals = transmission_distance,y_vals = test_curve,target_x = 11)

#print(test)

# In[27]:

# intput: node1/2 psoition = [x,y,z] or [x,y], the z will be set =10 for default
#output: channel capacitance in unit Tbps

def find_channel_capacity(node1_position,node2_position,                          low_altitude_channel_model= jet_channel,                          high_altitude_channel_model = UAV_channel):

    global zenith_angle

    global transmission_distance

    # set up default altitude if altitude information are not given
    default_altitude = 10

    if(len(node1_position) <3):
        node1_position.append(default_altitude)

    if(len(node2_position) <3):
        node2_position.append(default_altitude)

    # node 2 altitude must > node 1

    if(node2_position[2]<node1_position[2]):
        return find_channel_capacity(node2_position,node1_position,                                     low_altitude_channel_model,                                     high_altitude_channel_model)

    x_dif = node2_position[0] - node1_position[0]

    y_dif = node2_position[1] - node1_position[1]

    z_dif = node2_position[2] - node1_position[2]

    distance = (x_dif**2 + y_dif**2 + z_dif**2)**(1/2)

    #xy_plan_d = (x_dif**2 + y_dif**2)**(1/2)

    if(distance ==0):
        zenith_angle_between_nodes = 90
    else:
        zenith_angle_between_nodes = math.acos(z_dif/distance)/math.pi*180

    #print('distance between nodes: ',distance)
    #print('zenith angle between nodes: ',zenith_angle_between_nodes,'degree')

    #find lower altitude channel modle
    base_model_altitude = node1_position[2]

    lower_altitude_base_capacity_vs_distance_model = find_channel_cap_vs_dsitance_at_specific_altitude(base_model_altitude)

    base_capacitance = estimate_value_by_cureve_slop(x_vals = transmission_distance,y_vals = lower_altitude_base_capacity_vs_distance_model,target_x = distance)

    base_capacitance =max(base_capacitance,0)

    #print('without zenith angle, the capacitance is ',base_capacitance)

    # due to zenith angle, the acutal cureve will be shifted(up wards)
    cap_vs_zenith = cap_vs_zenith_at_target_altitude(base_model_altitude)

    zero_angle_val = estimate_value_by_cureve_slop(x_vals = zenith_angle,y_vals = cap_vs_zenith,target_x = 90)

    with_angle_val = estimate_value_by_cureve_slop(x_vals = zenith_angle,y_vals = cap_vs_zenith,target_x = zenith_angle_between_nodes)

    #print('when d=1km, without zenith, cap = ',zero_angle_val)
    #print('when d=1km, with zenith,  cap = ',with_angle_val)

    percentage_change = (with_angle_val-zero_angle_val)/zero_angle_val

    final_result = (1+percentage_change)*base_capacitance

    return final_result

# In[28]:

'''
node1_position = [0,0,16] #[0, 0, 0+10]

node2_position = [0,0,16] #[10, 1,3**(1/2)+10]

capacitance = find_channel_capacity(node1_position,node2_position)

print('channel capacitance is ',capacitance,'Tbps')
'''

# In[ ]:

# In[ ]:

# In[ ]:


import sys
import random

random.seed(None)

letters = [chr(x) for x in range(ord('A'), ord('z'))]
#print(letters)

with open(sys.argv[1], 'w') as f:
    for x in range(int(sys.argv[2])):
        word_len = random.randint(1,20)
        f.write(''.join(random.sample(letters, word_len)) + '\n')


# Test Cases
# 123
# 12345
# 2147483647
# 1234567891
# 0
# 20
# 10
# 100
# 1000

class Solution:
    def numberToWords(self, num: int) -> str:
        return self.ans1(num)

    def ans1(self, num: int) -> str:

        if num == 0:
            return 'Zero'

        n = num
        ans = []
        nums = []
        titles = [' Billion' ,' Million',' Thousand' ,'']

        while n > 0:
            p = n%1000
            nums.insert(0, p)
            n = n // 1000

        for i in range(len(nums)-1, -1, -1):
            number = nums[i]
            eng = self.three(number)
            if eng != '':
                ans.insert(0, self.three(number) + titles.pop())
            else:
                titles.pop()

        # print(ans)
        return ' '.join(ans)

    def three(self, n: int):

        one_d = {1:'One', 2:'Two', 3:'Three', 4:'Four', 5:'Five', 6:'Six', 7:'Seven', 8:'Eight', 9:'Nine'}
        two_d = {1:'One', 2:'Twenty', 3:'Thirty', 4:'Forty', 5:'Fifty', 6:'Sixty', 7:'Seventy', 8:'Eighty', 9:'Ninety'}
        ele_d = {10: 'Ten', 11:'Eleven', 12:'Twelve', 13:'Thirteen', 14:'Fourteen', 15:'Fifteen', 16:'Sixteen', 17:'Seventeen', 18:'Eighteen', 19:'Nineteen'}

        st = []
        nums = []
        n2 = n

        while n>0:
            p = n%10
            nums.append(p)
            n = n//10

        # print(nums)

        i = 1

        while i<=len(nums):

            if i == 2 and nums[1] == 1:
                if st:
                    st.pop()
                st.insert(0, ele_d[n2%100])
            elif i == 2 and nums[i-1] != 0:
                st.insert(0, two_d[nums[i-1]])
            elif i == 1 and nums[i-1] != 0:
                st.insert(0, one_d[nums[i-1]])
            elif i == 3 and nums[i-1] != 0:
                st.insert(0, one_d[nums[i-1]] + ' Hundred')

            i+=1

        # print('three')
        # print(st)

        return ' '.join(st)


import numpy as np

s = 10

DiaSum = np.zeros([256,1])
M = np.zeros([256,256])
Mx = np.zeros([254,1,8])
AbsorbingStates = np.zeros([2,1,8])
#My = np.zeros([254,1,8])
Input = np.zeros([4,2])
Input[1,1],Input[2,0],Input[3,0],Input[3,1] = 1,1,1,1

k = 0
for i in range(256):
    if i == 105 or i == 150:
        continue
    k += 1
    binary = "{0:08b}".format(i)
    x = 0
    #Mx[k-1,1,0] = i
    for j in binary:
        Mx[k-1,0,x] = int(j)
        x += 1

y = 0
for i in (105,150):
    binary = "{0:08b}".format(i)
    x = 0
    #Mx[k-1,1,0] = i
    for j in binary:
        AbsorbingStates[y,0,x] = int(j)
        x += 1
    y += 1

Mx = np.vstack((AbsorbingStates,Mx))
My = Mx

def CalculateClasueOutputs(TADecisions, Input):
    TADecisions = np.reshape(TADecisions, (2, 4), order='F')

    Clause1 = 1
    if (TADecisions[0,0] == 1 and Input[0] == 0) or (TADecisions[1,0] == 1 and Input[0] == 1) or (TADecisions[0,1] == 1 and Input[1] == 0) or (TADecisions[1,1] == 1 and Input[1] == 1):
        Clause1 = 0

    Clause2 = 1
    if (TADecisions[0,2] == 1 and Input[0] == 0) or (TADecisions[1,2] == 1 and Input[0] == 1) or (TADecisions[0,3] == 1 and Input[1] == 0) or (TADecisions[1,3] == 1 and Input[1] == 1):
        Clause2 = 0

    return Clause1, Clause2

def ActivationProbability(FeedbackType, v):
    if FeedbackType == 2:
        if v == 0:
            ActProbability = 0.5
        else:
            ActProbability = 1
    else:
        if v == 0:
            ActProbability = 0.5
        else:
            ActProbability = 0.0

    return ActProbability

def getLiteral(index, Input):
    if index % 2 == 0:
        literalType = 1
    else:
        literalType = 0

    if index % 4 < 2:
        INx = 0
    else:
        INx = 1

    if literalType == 1:
        literal = Input[INx]
    else:
        literal = int(not Input[INx])

    return literal

def FeedbackProbability(FeedbackType, ClauseOutput, Literal, taDecision, change):
    #print('FeedbackType', FeedbackType, 'ClauseOutput', ClauseOutput, 'Literal', Literal, 'taDecision', taDecision, 'change', change)
    FeedProb = 0.0
    Feedrew = 0.0
    Feedinact = 0.0
    if change == 1:
        if FeedbackType == 1:
            if ClauseOutput == 1:
                if Literal == 1:
                    if taDecision == 0:
                        FeedProb = (s-1)/s

            else:
                if Literal == 1:
                    if taDecision == 1:
                        FeedProb = 1/s

                else:
                    if taDecision == 1:
                        FeedProb = 1/s

        else:
            if ClauseOutput == 1:
                if Literal == 0:
                    if taDecision == 0:
                        FeedProb = 1
    else:
        if FeedbackType == 1:
            if ClauseOutput == 1:
                if Literal == 1:
                    if taDecision == 1:
                        Feedrew = (s-1)/s
                        Feedinact = 1/s
                    else:
                        Feedinact = 1/s
                else:
                    if taDecision == 0:
                        Feedrew = 1/s
                        Feedinact = (s-1)/s
            else:
                if taDecision == 1:
                    Feedinact = (s-1)/s
                else:
                    Feedrew = 1/s
                    Feedinact = (s-1)/s
        else:
            if ClauseOutput == 1:
                if Literal == 1:
                    Feedinact = 1.0
            else:
                Feedinact = 1.0

    if change == 1:
        FeedProb = FeedProb
    else:
        FeedProb = Feedrew + Feedinact
        #print(FeedProb)
    return FeedProb

for xaxis in range(len(Mx)):
    for yaxis in range(len(My)):
        p = 0
        for case in range(4): # different Inputs
            if case == 0 or case == 3:
                FeedbackType = 2
            else:
                FeedbackType = 1

            Clause1, Clause2 = CalculateClasueOutputs(Mx[xaxis,:,:],Input[case,:])
            Clause1Prime, Clause2Prime = CalculateClasueOutputs(My[yaxis,:,:],Input[case,:])
            ActProb = ActivationProbability(FeedbackType, Clause1+Clause2)

            if np.array_equal(Mx[xaxis,:,0:4], My[yaxis,:,0:4]):#clause1, no change case
                FeedProb = 1
                for index in range(4):
                    literal = getLiteral(index, Input[case,:])
                    change = 0
                    FeedProb = FeedProb * FeedbackProbability(FeedbackType, Clause1, literal, Mx[xaxis,:,index], change)

                Pc1 = (ActProb * FeedProb) + (1 - ActProb)

            else:# clause1, change case
                FeedProb = 1
                for index in range(4):
                    literal = getLiteral(index, Input[case,:])
                    if Mx[xaxis,:,index] == My[yaxis,:,index]:
                        change = 0
                    else:
                        change = 1

                    FeedProb = FeedProb * FeedbackProbability(FeedbackType, Clause1, literal, Mx[xaxis,:,index], change)

                Pc1 = ActProb * FeedProb

            if np.array_equal(Mx[xaxis,:,4:8], My[yaxis,:,4:8]):#clause2, no change case
                FeedProb = 1
                for kk in range(4):
                    index = kk+4
                    literal = getLiteral(index, Input[case,:])
                    change = 0
                    FeedProb = FeedProb * FeedbackProbability(FeedbackType, Clause2, literal, Mx[xaxis,:,index], change)

                Pc2 = (ActProb * FeedProb) + (1 - ActProb)

            else:#clause2, change case
                FeedProb = 1
                for kk in range(4):
                    index = kk+4
                    literal = getLiteral(index, Input[case,:])
                    if Mx[xaxis,:,index] == My[yaxis,:,index]:
                        change = 0
                    else:
                        change = 1

                    FeedProb = FeedProb * FeedbackProbability(FeedbackType, Clause2, literal, Mx[xaxis,:,index], change)

                Pc2 = ActProb * FeedProb

            p += 0.25 * Pc1 * Pc2
            #print(Pc1, Pc2)

        M[yaxis, xaxis] = p

MM = M.transpose()

for j in range(256):
    DiaSum[j,0] = sum(MM[j,:]) # sum of all row

np.savetxt('transitionmatrixstandard.csv', MM)

mm=np.linalg.matrix_power(MM, 1000000)


# The Computer Language Benchmarks Game
# http://benchmarksgame.alioth.debian.org/

# contributed by Dieter Weber

import numpy as np
import sys
import os
import multiprocessing
import ctypes

# set HALF=True to get twice the speed
HALF = False

# We knowingly produce overflows, therefore
# ignore warning
np.seterr(all='ignore')

size = int(sys.argv[1])
if HALF:
    # we only calculate the upper half, but calculated area is always asymmetric
    # by one line, so always one more line necessary
    calcsize = size // 2 + 1
else:
    calcsize = size
# boundaries of the calculated area
remin = -1.5
remax = 0.5
# if we break the symmetry here, we have to fix the "calculate half" aspect
# of the code!
imin = -1.
imax = -imin

# there are apparently a few differences in handling strings and byte arrays...
V3 = sys.version_info >= (3, )

# maximum number of points calculated in parallel to avoid
# excessive memory use
# this seems to be the optimum on my machine, fairly low value imho
maxchunk = 1<<14

# fixed to match reference output
# iterations = 49

# List of iteration steps, supplied by hand as number of iterations is fixed
# optimized for speed, ignoring overflows
# this is apparently a good tradeoff between the cost of making a new array
# and the cost of calculating more points
iteration_steps = [9] + [10]*4

# distance between points in real direction
restep = (remax - remin)/size
# distance between points in imaginary direction
imstep = (imax - imin)/size

# number of bits
# remainder of experiments with long long int for bit shifting,
# but no advantage, therefore byte boundary of lines not implemented for
# other types than unsigned byte
(bits, calctype) = (8, 'u1')
bytesize = 8

# precalculate real part of one line  and reuse later
reline = np.linspace(remin, remax - restep, size)
# precalculate imaginary parts and reuse later
if HALF:
    imline = 1j*np.linspace(imin, 0 - imstep*(size%2)*0.5, calcsize)
else:
    imline = 1j*np.linspace(imin, imax - imstep, calcsize)

# padding to start new line at byte boundary following pbm format
# size in [1,8] -> 1 byte per line ; size in [9,16]-> 2 bytes per line etc.
linesize = (size - 1)//bytesize + 1

# PBM header, important to calculate buffer size
header = "P4\n{0} {0}\n".format(size)
if V3:
    header = bytes(header, 'ascii')
header_offset = len(header)

bufferlen = len(header) + linesize * size

# creates ctypes array in shared memory
# REMARK: mmap.mmap can do almost the same here, but by the benchmark's specs
# we have to write to stdout anyway.
# if there are memory size issues, we can
# mmap a temporary file here and also adjust maxchunk above,
# but 16000x16000 only uses approx. 32 MB, no problem on todays machines
# if we wanted bigger than about 50000x50000, or minimize memory usage, it could
# however be a good idea to implement the mmap version.
sharedbitmap = multiprocessing.Array(ctypes.c_char, bufferlen, lock=False)
sharedbitmap[0:len(header)] = header

# not more to avoid task switching overhead and surplus memory usage
# one process already puts one core to 100%, no waiting, locking etc. :-)
# may not be portable, but no worries on standard Linux
workers = multiprocessing.cpu_count()

# calculate line package size, either divide fairly per cpu or limit
# by memory use
maxlines = maxchunk // size
# make sure we calculate at least one line per package

# we only calculate the upper half of the set and exploit it's symmetry!
lines_per_chunk = max(1, min(calcsize//workers,  maxlines))

# number of tasks, only upper half of the set!
packages = max(1, calcsize // lines_per_chunk)
# hehe, we could have many processors...
if workers <= calcsize:
# make sure it's dividable by number of processors to have all working
# There's a small imbalance at the very end of the program run because
# different chunks have different calculation time
    packages += packages%workers
else:
    # one line per package
    packages = calcsize
# To make sure we can calculate very small sets on machines with lots of
# processors: max(1, ...)
lines_per_chunk = max(1, calcsize // packages)

tasks = []
for i in range(packages):
    tasks.append((i*lines_per_chunk, lines_per_chunk))

# see what lines are not covered yet, distribute them among the tasks
(last_offset, last_lines) = tasks[-1]
missing_lines = calcsize - (last_offset+last_lines)
for i in range(missing_lines):
    index = -(missing_lines-i)
    (offset, lines) = tasks[index]
    tasks[index] = (offset + i, lines + 1)

# modifies z! call by reference!
# iterate z according to formula, set all elements
# in the set to 0
def mandeliterations(z):
    # calculate subsequently shorter lists and keep track of indices
    indexlist = []
    calcc = z.copy()
    calcz = z
    # filtering the list is expensive,
    # calculate several iterations before filtering
    for iterations in iteration_steps:
        for i in range(iterations):
            calcz **= 2
            calcz += calcc
        indices = np.nonzero(abs(calcz) < 2)
        # I guess that continuous arrays are better for fast iterating,
        # therefore create new arrays
        calcz = calcz[indices]
        calcc = calcc[indices]
        indexlist.append(indices)
    # "collapes" the index list from the bottom to get the elements
    # remaining in the set
    mandelbrot = indexlist.pop()
    # a bit messy because of the index format that numpy uses
    for indices in reversed(indexlist[1:]):
        mandelbrot = indices[0][mandelbrot]
    mandelbrot = (indexlist[0][0][mandelbrot], indexlist[0][1][mandelbrot])
    # finally, set everything in the set = 0
    # maybe the index list could be used to set bitmap directly?
    # But this seems cleaner in terms of code structure: only floats here,
    # keep bitmap business in pbmline()
    z[mandelbrot] = 0

# generate/allocate block of complex numbers for subsequent iteration
def mandelblock(line_offset, lines):
    # maybe numpy.mgrid or another method would be faster, but not tried yet...
    (re, im) = np.meshgrid(reline, imline[line_offset:line_offset+lines])
    # reuse memory
    im += re
    return im

# convert data array into "compressed" bitmap to be written to binary pbm file
def pbmline(points, lines):
    # each point is in [0, 1] now, 8 bit unsigned int
    bitmap = np.zeros((lines, linesize*bits), dtype=calctype)
    # respect  the "padding" bits at the end of
    # the line to get byte boundaries
    bitmap[:,:size] = points==0
    # make blocks with 8 bits
    bitmap = bitmap.reshape((linesize*lines, bits))
    # shift bits, accumulate in highest bit
    for bit in range(0,bits-1):
        # fix bit order here
        bitmap[:,bit] <<= (bits-bit-1)
        bitmap[:,bits-1] += bitmap[:,bit]
    # return accumulator
    result = bitmap[:,bits-1]
    return result

if V3:
    def tobytes(a):
        return bytes(iter(a))
else:
    def tobytes(a):
        return a.tostring()

if HALF:
    # move bitmap fragments to output
    # eventually modifies bitmap in the process!
    # But we're done after :-)
    def copybits(line_offset, bitmap, lines):
        # make sure that array is "flat"
        bitmap.reshape(-1)
        # use this for number of bytes, reshaping influences len(bitmap)
        len_bitmap = len(bitmap)
        startbyte = header_offset + line_offset * linesize
        # program works with 8/8 now, less headache
        # but keep this for explicity
        copybytes = len_bitmap*bits//bytesize
        # didn't get ctypes.memcopy to work,
        # this does it although it may be a bit slower
        # bitmap HAS to be flat
        sharedbitmap[startbyte:startbyte+len_bitmap] = tobytes(bitmap)
        # now reshape to lines x lines in order to reverse and exploit symmetry
        bitmap = bitmap.reshape((lines, linesize))
        # reverse the lines
        bitmap = bitmap[::-1, :]
        startbyte = bufferlen - line_offset * linesize - len_bitmap + linesize
        stopbyte = startbyte + len_bitmap
        # the calculated area is not symmetric, we have overlap
        # therefore clip overhang
        if startbyte < (bufferlen - header_offset) // 2:
            bitmap = bitmap[1:,:]
            startbyte += linesize
        if stopbyte > bufferlen:
            bitmap = bitmap[:-1,:]
            stopbyte -= linesize
        # flat again for output
        bitmap = bitmap.reshape(-1)
        sharedbitmap[startbyte:startbyte+len_bitmap] = tobytes(bitmap)
else:
    # move bitmap fragments to output
    # eventually modifies bitmap in the process!
    # But we're done after :-)
    def copybits(line_offset, bitmap, lines):
        # make sure that array is "flat"
        bitmap.reshape(-1)
        # use this for number of bytes, reshaping influences len(bitmap)
        len_bitmap = len(bitmap)
        startbyte = header_offset + line_offset * linesize
        # program works with 8/8 now, less headache
        # but keep this for explicity
        copybytes = len_bitmap*bits//bytesize
        # didn't get ctypes.memcopy to work,
        # this does it although it may be a bit slower
        # bitmap HAS to be flat
        sharedbitmap[startbyte:startbyte+len_bitmap] = tobytes(bitmap)

# function to be called with element of the task array,
# suitable for mapping (no output, only modifies shared buffer)
def work(tup):
    (line_offset, lines) = tup
    block = mandelblock(line_offset, lines)
    mandelbrot = mandeliterations(block)
    bitmap = pbmline(block, lines)
    copybits(line_offset, bitmap, lines)

pool = multiprocessing.Pool(workers)
# for debugging: just use map(...) instead of pool.map(...)
# to get the exceptions + trace
# global variables etc. are shared between processes! :-)
pool.map(work, tasks)
#for tup in tasks:
    #work(tup)

# dump it!
if V3:
    sys.stdout.buffer.write(sharedbitmap)
else:
    sys.stdout.write(sharedbitmap.raw)


import unittest
from selenium import webdriver
from src.page.login_page import ShowAll_page
from time import sleep
from src.common import excel_data
from src.common.mylog import mylog
from src.common.page_url import url

class TestSaasShowAll(unittest.TestCase):
    def setUp(self):
        self.mylog = mylog()
        self.driver = webdriver.Chrome()
        self.url = url.login_page
        self.ShowAll_page = ShowAll_page(self.driver, self.url, 'SaaS Web')
        self.ShowAll_page.login_success()

    def test_selected(self):
        '''验证登录后默认选中'''
        try:
            status = self.driver.find_element_by_xpath(self.ShowAll_page.tab_loc).get_attribute("aria-current")
            self.assertEqual(status, 'true')
        except Exception as e:
                self.mylog.error('error_log ')
                self.ShowAll_page.img_screenshot('error_img')
                raise e

    def test_skipToSetting(self):
        '''验证hover并打开账号设置页面'''
        try:
            self.ShowAll_page.hover_it()
            self.ShowAll_page.click_setting()
            sleep(1)
            self.assertEqual(self.driver.current_url, url.setting_page)
        except Exception as e:
                self.mylog.error('error_log ')
                self.ShowAll_page.img_screenshot('error_img')
                raise e

    def test_skipToDetail(self):
        '''验证跳转点击查看button'''
        try:
            self.ShowAll_page.click_detail()
            sleep(1)
            self.assertIn(url.detail_page, self.driver.current_url)
        except Exception as e:
            self.mylog.error('error_log ')
            self.ShowAll_page.img_screenshot('error_img')
            raise e

    def test_logout(self):
        '''验证hover并退出登录'''
        try:
            self.ShowAll_page.hover_it()
            self.ShowAll_page.click_logout()
            sleep(1)
            self.driver.switch_to_alert().dismiss()
            self.assertEqual(self.driver.current_url, url.showAll_page)
        except Exception as e:
                self.mylog.error('error_log ')
                self.ShowAll_page.img_screenshot('error_img')
                raise e
        sleep(1)
        try:
            self.ShowAll_page.hover_it()
            self.ShowAll_page.click_logout()
            sleep(1)
            self.driver.switch_to_alert().accept()
            self.assertEqual(self.driver.current_url, url.login_page)
        except Exception as e:
                self.mylog.error('error_log ')
                self.ShowAll_page.img_screenshot('error_img')
                raise e

    def tearDown(self):
        self.driver.close()

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


import logging

from archinfo import ArchSoot

from .base import SimSootExpr
from ..values.thisref import SimSootValue_ThisRef

l = logging.getLogger("angr.engines.soot.expressions.cast")

class SimSootExpr_Cast(SimSootExpr):
    def _execute(self):
        # get value
        local = self._translate_value(self.expr.value)
        value_uncasted = self.state.memory.load(local)
        # cast value
        if self.expr.cast_type in ArchSoot.primitive_types:
            javavm_simos = self.state.project.simos
            self.expr = javavm_simos.cast_primitive(self.state, value_uncasted, to_type=self.expr.cast_type)
        else:
            self.expr = SimSootValue_ThisRef(heap_alloc_id=value_uncasted.heap_alloc_id, type_=self.expr.cast_type)


import requests
from fastapi import Depends, HTTPException
from jose.backends import RSAKey
from jose.jwt import decode, get_unverified_header

from app.config import settings

def get_keycloak_jwks():
    keycloak_well_known_url = settings.OIDC_CONFIG_URL
    response = requests.get(keycloak_well_known_url)
    well_known_config = response.json()
    jwks_url = well_known_config["jwks_uri"]
    jwks_response = requests.get(jwks_url)
    jwks = jwks_response.json()
    return jwks["keys"]

def validate_jwt(token: str = Depends(get_keycloak_jwks)):
    header = get_unverified_header(token)
    jwks = get_keycloak_jwks()

    # Find the RSA key with the matching kid in the JWKS
    rsa_key = None
    for key in jwks:
        if key["kid"] == header["kid"]:
            rsa_key = RSAKey(
                key=key["n"], alg=key["alg"], use=key["use"], kid=key["kid"]
            )
            break

    if rsa_key is None:
        raise HTTPException(status_code=401, detail="RSA Key not found in JWKS")

    try:
        payload = decode(token, rsa_key, algorithms=[header["alg"]])
    except Exception:
        raise HTTPException(status_code=401, detail="Invalid JWT token") from Exception

    return payload


import torch
import os
import re
from pathlib import Path
from functools import partial
import esm
from torch.nn.utils.rnn import pad_sequence
from transformers import AlbertTokenizer, AutoModelForMaskedLM, logging
from tf_bind_transformer.cache_utils import cache_fn, run_once, md5_hash_fn

def exists(val):
    return val is not None

def map_values(fn, dictionary):
    return {k: fn(v) for k, v in dictionary.items()}

def to_device(t, *, device):
    return t.to(device)

def cast_tuple(t):
    return (t,) if not isinstance(t, tuple) else t

PROTEIN_EMBED_USE_CPU = os.getenv('PROTEIN_EMBED_USE_CPU', None) is not None

if PROTEIN_EMBED_USE_CPU:
    print('calculating protein embed only on cpu')

# global variables

GLOBAL_VARIABLES = {
    'model': None,
    'tokenizer': None
}

# general helper functions

def calc_protein_representations_with_subunits(proteins, get_repr_fn, *, device):
    representations = []

    for subunits in proteins:
        subunits = cast_tuple(subunits)
        subunits_representations = list(map(get_repr_fn, subunits))
        subunits_representations = list(map(partial(to_device, device = device), subunits_representations))
        subunits_representations = torch.cat(subunits_representations, dim = 0)
        representations.append(subunits_representations)

    lengths = [seq_repr.shape[0] for seq_repr in representations]
    masks = torch.arange(max(lengths), device = device)[None, :] <  torch.tensor(lengths, device = device)[:, None]
    padded_representations = pad_sequence(representations, batch_first = True)

    return padded_representations.to(device), masks.to(device)

# esm related functions

ESM_MAX_LENGTH = 1024
ESM_EMBED_DIM = 1280

INT_TO_AA_STR_MAP = {
    0: 'A',
    1: 'C',
    2: 'D',
    3: 'E',
    4: 'F',
    5: 'G',
    6: 'H',
    7: 'I',
    8: 'K',
    9: 'L',
    10: 'M',
    11: 'N',
    12: 'P',
    13: 'Q',
    14: 'R',
    15: 'S',
    16: 'T',
    17: 'V',
    18: 'W',
    19: 'Y',
    20: '_'
}

def tensor_to_aa_str(t):
    str_seqs = []
    for int_seq in t.unbind(dim = 0):
        str_seq = list(map(lambda t: INT_TO_AA_STR_MAP[t] if t != 20 else '', int_seq.tolist()))
        str_seqs.append(''.join(str_seq))
    return str_seqs

@run_once('init_esm')
def init_esm():
    model, alphabet = esm.pretrained.esm1b_t33_650M_UR50S()
    batch_converter = alphabet.get_batch_converter()

    if not PROTEIN_EMBED_USE_CPU:
        model = model.cuda()

    GLOBAL_VARIABLES['model'] = (model, batch_converter)

def get_single_esm_repr(protein_str):
    init_esm()
    model, batch_converter = GLOBAL_VARIABLES['model']

    data = [('protein', protein_str)]
    batch_labels, batch_strs, batch_tokens = batch_converter(data)

    if batch_tokens.shape[1] > ESM_MAX_LENGTH:
        print(f'warning max length protein esm: {protein_str}')

    batch_tokens = batch_tokens[:, :ESM_MAX_LENGTH]

    if not PROTEIN_EMBED_USE_CPU:
        batch_tokens = batch_tokens.cuda()

    with torch.no_grad():
        results = model(batch_tokens, repr_layers=[33])

    token_representations = results['representations'][33]
    representation = token_representations[0][1 : len(protein_str) + 1]
    return representation

def get_esm_repr(proteins, device):
    if isinstance(proteins, torch.Tensor):
        proteins = tensor_to_aa_str(proteins)

    get_protein_repr_fn = cache_fn(get_single_esm_repr, path = 'esm/proteins')

    return calc_protein_representations_with_subunits(proteins, get_protein_repr_fn, device = device)

# prot-albert 2048 context length

PROT_ALBERT_PATH = 'Rostlab/prot_albert'
PROT_ALBERT_DIM = 4096
PROT_ALBERT_MAX_LENGTH = 2048

def protein_str_with_spaces(protein_str):
    protein_str = re.sub(r"[UZOB]", 'X', protein_str)
    return ' '.join([*protein_str])

@run_once('init_prot_albert')
def init_prot_albert():
    GLOBAL_VARIABLES['tokenizer'] = AlbertTokenizer.from_pretrained(PROT_ALBERT_PATH, do_lower_case = False)
    model = AutoModelForMaskedLM.from_pretrained(PROT_ALBERT_PATH)

    if not PROTEIN_EMBED_USE_CPU:
        model = model.cuda()

    GLOBAL_VARIABLES['model'] = model

def get_single_prot_albert_repr(
    protein_str,
    max_length = PROT_ALBERT_MAX_LENGTH,
    hidden_state_index = -1
):
    init_prot_albert()
    model = GLOBAL_VARIABLES['model']
    tokenizer = GLOBAL_VARIABLES['tokenizer']

    encoding = tokenizer.batch_encode_plus(
        [protein_str_with_spaces(protein_str)],
        add_special_tokens = True,
        padding = True,
        truncation = True,
        max_length = max_length,
        return_attention_mask = True,
        return_tensors = 'pt'
    )

    if not PROTEIN_EMBED_USE_CPU:
        encoding = map_values(lambda t: t.cuda(), encoding)

    model.eval()
    with torch.no_grad():
        outputs = model(**encoding, output_hidden_states = True)

    hidden_state = outputs.hidden_states[hidden_state_index][0]
    return hidden_state

def get_prot_albert_repr(
    proteins,
    device,
    max_length = PROT_ALBERT_MAX_LENGTH,
    hidden_state_index = -1
):
    if isinstance(proteins, str):
        proteins = [proteins]

    if isinstance(proteins, torch.Tensor):
        proteins = tensor_to_aa_str(proteins)

    get_protein_repr_fn = cache_fn(get_single_prot_albert_repr, path = f'proteins/prot_albert')

    return calc_protein_representations_with_subunits(proteins, get_protein_repr_fn, device = device)

# alphafold2 functions

AF2_MAX_LENGTH = 2500
AF2_EMBEDDING_DIM = 384

AF2_DIRECTORY = os.getenv('TF_BIND_AF2_DIRECTORY', os.path.expanduser('~/.cache.tf.bind.transformer/.af2_embeddings'))
AF2_DIRECTORY_PATH = Path(AF2_DIRECTORY)

def get_single_alphafold2_repr(
    protein_str,
    max_length = AF2_MAX_LENGTH,
):
    md5 = md5_hash_fn(protein_str)
    embedding_path = AF2_DIRECTORY_PATH / f'{md5}.pt'
    assert embedding_path.exists(), f'af2 embedding not found for {protein_str}'

    tensor = torch.load(str(embedding_path))
    return tensor[:max_length]

def get_alphafold2_repr(
    proteins,
    device,
    max_length = AF2_MAX_LENGTH,
    **kwargs
):
    representations = []

    for subunits in proteins:
        subunits = cast_tuple(subunits)
        subunits = list(map(lambda t: get_single_alphafold2_repr(t, max_length = max_length), subunits))
        subunits = torch.cat(subunits, dim = 0)
        representations.append(subunits)

    lengths = [seq_repr.shape[0] for seq_repr in representations]
    masks = torch.arange(max(lengths), device = device)[None, :] <  torch.tensor(lengths, device = device)[:, None]
    padded_representations = pad_sequence(representations, batch_first = True)

    return padded_representations.to(device), masks.to(device)

# factory functions

PROTEIN_REPR_CONFIG = {
    'esm': {
        'dim': ESM_EMBED_DIM,
        'fn': get_esm_repr
    },
    'protalbert': {
        'dim': PROT_ALBERT_DIM,
        'fn': get_prot_albert_repr
    },
    'alphafold2': {
        'dim': AF2_EMBEDDING_DIM,
        'fn': get_alphafold2_repr
    }
}

def get_protein_embedder(name):
    allowed_protein_embedders = list(PROTEIN_REPR_CONFIG.keys())
    assert name in allowed_protein_embedders, f"must be one of {', '.join(allowed_protein_embedders)}"

    config = PROTEIN_REPR_CONFIG[name]
    return config


from django.urls import path, include
from django.views.decorators.cache import cache_page, never_cache

from catalog.apps import CatalogConfig
from catalog.views import contacts, category,\
    ProductListView, ProductCreateView, ProductDetailView, ProductUpdateView, ProductDeleteView

app_name = CatalogConfig.name

urlpatterns = [
    path('create/', never_cache(ProductCreateView.as_view()), name='create'),
    path('', cache_page(60)(ProductListView.as_view()), name='index'),
    path('view/<int:pk>/', cache_page(60)(ProductDetailView.as_view()), name='view'),
    path('edit/<int:pk>/', never_cache(ProductUpdateView.as_view()), name='edit'),
    path('delete/<int:pk>/', never_cache(ProductDeleteView.as_view()), name='delete'),
    path('contacts/', contacts, name='contacts'),
    path('category/', category, name='category'),
    path("__debug__/", include("debug_toolbar.urls")),
]


import falcon
from falcon_cors import CORS

from api import resources

cors = CORS(
    allow_all_origins=True,
    allow_all_headers=True,
    allow_all_methods=True,
    )
routes = falcon.API(middleware=[cors.middleware])

inch_worm = resources.InchWorm()
routes.add_route('/inchworm', inch_worm)


import os
from flask import Flask
from flask import request
from flask import render_template
import urllib
import time
from datetime import datetime
import threading
import random

r_time_str = ''
num_threads = 5
thread_delay = 3
loadtest = 0

class InitiateLoad (threading.Thread):
 def run (self):
     global loadtest
     global num_threads
     global thread_delay
     loadtest = 1
     while (loadtest):
      for x in xrange ( num_threads ):
       MyThread().start()
      time.sleep(thread_delay)

class MyThread ( threading.Thread ):
 def run (self):
     global r_time_str
     global thread_delay
     url = 'http://helloflask25.cfapps.io/fast'
     time.sleep (random.random()*thread_delay)
     start = datetime.now()
     nf = urllib.urlopen(url)
     page = nf.read()
     end = datetime.now()
     r_time_str += str(start)[:-4] + ',' + str(page) + ',' + (str(end - start)[:-4])[5:] + '<br>'
     nf.close()

app = Flask(__name__)

@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):
    return render_template('hello.html', name=name)

@app.route('/monitor/')
def monitor():
    return render_template('flot/ajax/index.html')

@app.route('/mon/')
def mon():
    return render_template('index.html')
@app.route('/data/')
def data():
    url = 'http://monitor25.cfapps.io/static/flot/examples/ajax/data-usa-gdp-growth.json'
    nf = urllib.urlopen(url)
    page = nf.read()
    nf.close()
    return page


import sys
sys.path.insert(0, '../common_python')
import tools
import pytest
import os, sys

def test_unit_lbann2_reload(cluster, exe, dirname):
    lbann2  = exe + '2'
    model_path = '{../../model_zoo/models/lenet_mnist/model_lenet_mnist.prototext,../../model_zoo/tests/model_lenet_mnist_lbann2ckpt.prototext}'
    command = tools.get_command(
        cluster=cluster, executable=lbann2, data_reader_name='mnist',
        data_filedir_ray='/p/gscratchr/brainusr/datasets/MNIST',
        dir_name=dirname,
        model_path=model_path,
        optimizer_name='sgd',
        num_epochs=2)
    return_code = os.system(command)
    if return_code != 0:
        sys.stderr.write('LBANN2 LeNet execution failed, exiting with error')
        sys.exit(1)

    os.system('mv lbann2_ckpt lbann2_nockpt')

    command = tools.get_command(
        cluster=cluster, executable=exe, num_nodes=1, num_processes=1,
        dir_name=dirname,
        data_filedir_ray='/p/gscratchr/brainusr/datasets/MNIST',
        data_reader_name='mnist', model_folder='tests',
        model_name='lenet_mnist_ckpt', num_epochs=2, optimizer_name='sgd')
    return_code_ckpt_1 = os.system(command)
    if return_code_ckpt_1 != 0:
        sys.stderr.write('LeNet (checkpoint) execution failed, exiting with error')
        sys.exit(1)

    command = tools.get_command(
        cluster=cluster, executable=lbann2, num_nodes=1, num_processes=1,
        dir_name=dirname,
        data_filedir_ray='/p/gscratchr/brainusr/datasets/MNIST',
        data_reader_name='mnist',
        model_path='../../model_zoo/tests/model_lenet_mnist_lbann2ckpt.prototext', num_epochs=2, optimizer_name='sgd', ckpt_dir='ckpt/')
    return_code_ckpt_2 = os.system(command)
    if return_code_ckpt_2 != 0:
        sys.stderr.write('LBANN2 LeNet weight reload failed, exiting with error')
        sys.exit(1)
    os.system('rm lbann2_ckpt/model0-epoch*')
    os.system('rm lbann2_nockpt/model0-epoch*')
    diff_test = os.system('diff -rq lbann2_ckpt/ lbann2_nockpt/')
    os.system('rm -rf ckpt')
    os.system('rm -rf lbann2_*')
    assert diff_test == 0


from PyQt5.QtCore import QSize
from ..ekmap_common import *
from ..ekmap_converter import eKConverter
from ..qgslayer_parser.symbol_layer_factory import SymbolLayerFactory
import json, hashlib, os.path

class SymbologyParser():

    # This is abstract method
    def parse(self, renderer, exporter):
        raise NotImplementedError("Please Implement this method")

    def _wrapSymbolLayer(self, symbol, exporter):
        styleLayers = []
        for symbolLayer in symbol.symbolLayers():
            styleParser = SymbolLayerFactory.getLayerParser(symbolLayer, exporter)
            if styleParser is not None:
                styles = styleParser.parse()
                # Case POINT
                if symbolLayer.type() == 0:
                    key = json.dumps(styles)
                    key = hashlib.md5(key.encode()).hexdigest()
                    sizeUnit = eKConverter.convertRenderUnitValueToName(symbol.sizeUnit())
                    size = eKConverter.convertUnitToPixel(symbol.size(), sizeUnit)
                    exportImagePath = TEMP_LOCATION + '/' + key + '.png'
                    symbol.exportImage(exportImagePath, 'png', QSize(size, size))
                    if os.path.isfile(exportImagePath):
                        exporter.externalGraphics.append(exportImagePath)
                        styleLayers.append({
                            'type': 'symbol',
                            'layout': {
                                'icon-image': key
                            }
                        })
                # Case LINE or POLYGON
                else:
                    styleLayers.extend(styleParser.parse())

        return styleLayers


import unittest
from dependencies.python.fmlaas.model import JobBuilder
from dependencies.python.fmlaas.model import JobConfiguration
from dependencies.python.fmlaas.model import ExperimentBuilder
from dependencies.python.fmlaas.model import ProjectBuilder

class AbstractModelTestCase(unittest.TestCase):

    def _build_default_experiment(self):
        experiment = self._build_parameterized_experiment(1)

        experiment_json = {
            "ID" : "123dafasdf34sdfsdf_1",
            "jobs" : [],
            "current_job" : "NONE",
            "start_model" : {},
            "current_model" : {},
            "hyperparameters" : {},
            "is_active" : False
        }

        return experiment, experiment_json

    def _build_parameterized_experiment(self, id):
        builder = ExperimentBuilder()
        builder.id = "123dafasdf34sdfsdf_{}".format(id)

        return builder.build()

    def _build_job(self, id):
        builder = JobBuilder()
        builder.set_id("test_id_{}".format(id))
        builder.set_experiment_id("123dafasdf34sdfsdf")
        builder.set_project_id("fl_group_1232234")
        builder.set_devices(["123", "234"])
        configuration = JobConfiguration(2, 0, "RANDOM", [])
        builder.set_configuration(configuration.to_json())

        return builder.build()

    def _build_simple_project(self, id):
        builder = ProjectBuilder()
        builder.set_id("id_{}".format(id))
        builder.set_name("my_name")

        return builder.build()

    def _get_simple_project_json(self, id):
        return {
            'name': 'my_name',
            'ID': 'id_{}'.format(id),
            'devices': {},
            "experiments": {},
            "members": {},
            "billing": {}}


from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.future import select
from sqlalchemy.orm import join

from .models import Item, Comment
from .schemas import ItemCreate, CommentCreate

async def get_items_db(db: AsyncSession, skip: int = 0, limit: int = 100):
    result = await db.execute(select(Item).offset(skip).limit(limit))

    return result.scalars().all()

async def get_item_db(db: AsyncSession, item_id: int):
    result = await db.execute(select(Item).filter(Item.id == item_id))
    return result.scalars().first()

async def create_user_item(db: AsyncSession, item: ItemCreate, user_id: int):
    db_item = Item(**item.dict(), owner_id=user_id)
    db.add(db_item)
    try:
        await db.commit()
        await db.refresh(db_item)
    except IntegrityError as ex:
        await db.rollback()
    else:
        return db_item

async def create_comment_item(
        db: AsyncSession,
        comment: CommentCreate,
        user_id: int,
        item_id: int
):
    db_comment = Comment(**comment.dict(), owner_id=user_id, item_id=item_id)
    db.add(db_comment)
    try:
        await db.commit()
        await db.refresh(db_comment)
    except IntegrityError as ex:
        await db.rollback()
    else:
        return db_comment

async def get_comments_db(db: AsyncSession, item_id: int, skip: int = 0, limit: int = 100):
    result = await db.execute(select(Comment).filter(
        Comment.item_id == item_id
    ).offset(skip).limit(limit))

    return result.scalars().all()


import pandas as pd

# Example DataFrame
data = pd.DataFrame({'year_built': [1990, 2000, 2010, 2020]})

# Using domain knowledge to create a new feature
current_year = pd.Timestamp.now().year
data['age'] = current_year - data['year_built']

print(data)


#try:
#	f=open('demo1.txt')
#	x =y
#except FileNotFoundError:
#	print('Sorry,This file does not exist')
#except Exception:
#	print('Sorry,Something went Wrong')

try:
	f=open('demo1.txt')
	#x =y
except FileNotFoundError as e:
	print(e)
except Exception as e:
	print(e)
else:
	print(f.read())
	f.close()
finally:
	print("Executed finally...")

Python Training by Mukesh/Python Programs Practice/Exception handling.py


import requests

from loguru import logger

host = "http://localhost:9999"

r = requests.get(f"{host}/train")
logger.info(r.text)

payload = [
    {"Age": 85, "Sex": "male", "Embarked": "S"},
    {"Age": 24, "Sex": "female", "Embarked": "C"},
    {"Age": 3, "Sex": "male", "Embarked": "C"},
    {"Age": 21, "Sex": "male", "Embarked": "S"},
]

r = requests.post(f"{host}/predict", json=payload)
logger.info(r.text)

#if you dont want to remove the model.comment the following code
r = requests.get(f"{host}/wipe")
logger.info(r.text)

"""
from urllib.parse import urlparse
import http.client as ht
def getStatus(ourl):
    try:
        url = urlparse(ourl)
        conn = ht.HTTPConnection(url.netloc)
        conn.request("HEAD", url.path)
        res = conn.getresponse()
        return res.status, ourl
    except:
        return "error", ourl
getStatus(ourl="http://127.0.0.1:5000/train")
"""


class Solution:
    def findAnagrams(self, s: str, p: str) -> List[int]:
        res = []
        if len(s) < len(p):
            return res
        hs, hf = 0, 0
        for i in range(len(p)):
            hs += hash(s[i])
            hf += hash(p[i])
        if hs == hf:
            res.append(0)
        for r in range(len(p),len(s)):
            hs += hash(s[r]) - hash(s[r-len(p)])
            if hs == hf:
                res.append(r - len(p) + 1)
        return res


from flask import Flask, render_template, request
import pandas as pd
import numpy as np
import joblib

housing_df = pd.read_excel('C://Users//anike//Zep Analytics//Real Estate Analysis//MagicBricks Cleaned (Excel).xlsx')
cities_list = list(np.sort(housing_df['City'].unique()))
states_list = list(np.sort(housing_df['State/Territory'].unique()))
tiers_list = list(np.sort(housing_df['Tier'].unique()))
transaction_list = list(np.sort(housing_df['Transaction'].unique()))
furnishing_list = list(np.sort(housing_df['Furnishing'].unique()))
status_list = list(np.sort(housing_df['Status'].unique()))

app = Flask(__name__)

@app.route('/')
def home_page():
    prediction = "₹ 0.00"
    return render_template("index.html",
                           price=prediction,
                           cities=cities_list,
                           states=states_list,
                           tiers=tiers_list,
                           trans=transaction_list,
                           furnish=furnishing_list,
                           status=status_list)

@app.route('/predict', methods=["GET", "POST"])
def predict():
    if request.method == 'POST':
        input_df = pd.DataFrame(index=[0])
        input_df['Bedrooms'] = int(request.form.get('Bedrooms'))
        input_df['Bathroom'] = int(request.form.get('Bathrooms'))
        input_df['Area(sqft)'] = float(request.form.get('Area'))
        input_df['Latitude'] = float(request.form.get('Latitude'))
        input_df['Longitude'] = float(request.form.get('Longitude'))
        input_df['Price per sqft'] = float(request.form.get('Price per sqft'))
        for t in tiers_list:
            if t == request.form.get('Tier'):
                input_df['Tier_' + t] = 1
            else:
                input_df['Tier_' + t] = 0
        for s in states_list:
            if s == request.form.get('State/Territory'):
                input_df['State/Territory_' + s] = 1
            else:
                input_df['State/Territory_' + s] = 0
        for t in transaction_list:
            if t == request.form.get('Transaction'):
                input_df['Transaction_' + t] = 1
            else:
                input_df['Transaction_' + t] = 0
        for f in furnishing_list:
            if f == request.form.get('Furnishing'):
                input_df['Furnishing_' + f] = 1
            else:
                input_df['Furnishing_' + f] = 0
        for s in status_list:
            if s == request.form.get('Status'):
                input_df['Status_' + s] = 1
            else:
                input_df['Status_' + s] = 0

        #input_df.to_csv('Input_df.csv', index=False)
        model = joblib.load('GradientBoosting (Price Predictor).joblib')
        pred = np.round(model.predict(input_df)[0], 2)
        if pred > 100:
            prediction = '₹ ' + str(round(pred / 100, 2)) + ' Cr'
        else:
            prediction = '₹ ' + str(pred) + ' Lacs'

    return render_template("index.html",
                           price=prediction,
                           cities=cities_list,
                           states=states_list,
                           tiers=tiers_list,
                           trans=transaction_list,
                           furnish=furnishing_list,
                           status=status_list)

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


import os
import json
import re
from string import digits

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        pass
    try:
        import unicodedata
        unicodedata.numeric(s)
        return True
    except (TypeError, ValueError):
        pass
    return False

def lower(text):
	"""delete the words in text"""
	if isinstance(text,list):
		texts=[]
		for t in text:
			t=lower(t)
			if t:
				texts.append(t)
		return texts
	elif isinstance(text,str):
		text=text.lower()
		return text.strip()
	else:
		print('lower error')

def prestring(string):
	string=string.replace('|',' ')
	string=string.replace('(',' ')
	string=string.replace(')',' ')
	string=string.replace(',',' ')
	string=string.replace('"',' ')
	string=string.replace('\'',' ')
	string=string.replace('\n',' ')
	string=string.replace('\t',' ')
	if string[-4:]=='#aba':
		string=string[:-4]
	while '  ' in string:
		string=string.replace('  ',' ')
	return string

def ismodelword(w):
	if len(w)<4:
		return False
	if w in ['3m','3d','720p','1080p','2711p','rs-232','ohc24','2xhdmi']:
		return False
	for word in ['1024','1920','1080']:
		if word in w:
			return False
	if w.count('.')>1:
		return False

	endwords=['.com','.ca','slr','cm','mm','ms','mp','megapixel','display','in','inch','hz','bit','cd','cc','year','years']
	for word in endwords:
		partlen=0-len(word)
		if w[partlen:]==word and (len(w)-len(word)<5 or is_number(w[:partlen])):
			return False
	#startwords=['lcd-','ctr-','led-','tft-','megapixel','ohc','rs','win']
	startwords=['lcd','ctr','led','tft','megapixel','ohc','rs','win','lcd-','ctr-','led-','tft-','ohc-','rs-','win-']
	for word in startwords:
		partlen=len(word)
		if w[:partlen]==word and (len(w)-len(word)<5 or is_number(w[partlen:])):
			return False
	#get brands
	brands={}
	with open('../brands.json') as f:
		brands=json.load(f)
	if w in brands:
		return False

	numpattern = re.compile('[0-9]+')
	w=w.replace('-','')
	w=w.replace(':','')
	numpattern = re.compile('[0-9]+')
	if len("".join(filter(str.isdigit, w)))>0 and len(w.translate(str.maketrans('', '', digits)))>0:
		match_string=re.search(numpattern, w)
		if match_string:
			if bool(re.search('[^\d]',w.replace('.',''))) and bool(re.search('[^\d]',w.replace(',',''))) and bool(re.search('[^\d]',w.replace('×',''))):
				return True

	return False

def getMWSynonymsDictFromSignalProfile(dataset_path):
	"""
		input:	dataset_path: a string : directory of saving the test dataset(contains the profile of products)
		output: a dict : {'w1':[w2,w3,...],'w2':[w1,w3,...],'w3':[w1,w2,...],...}
	"""
	result={}
	products={}
	mpnmw_list=[]
	#get all the mpn
	for source in os.listdir(dataset_path)[:]:
		for specification in os.listdir(os.path.join(dataset_path, source))[:]:
			specification_number = specification.replace('.json', '')
			specification_id = '{}//{}'.format(source, specification_number)
			with open(dataset_path+'/'+source+'/'+specification,encoding='utf-8') as specification_file:
				product=json.load(specification_file)
				for k,v in product.items():
					product[k]=lower(v)
				for k,v in product.items():
					k=k.lower()
					if 'mpn' in k or 'upc' in k:
						mpn_list=[]
						#split value to mpn_list
						if not isinstance(v,list) and  not '/' in v:
							v.strip(':')
							v=[v]
						elif '/' in v:
							v.strip(':')
							v=v.split('/')

						for vi in v:
							vi.strip()
							vi=prestring(vi)
							if ':' in vi:
								continue
							elif ' ' in vi:
								vi=vi.split(' ')
								mpn_list.extend(vi)
							else:
								mpn_list.append(vi)
						#get all the model words in mpnmw_list
						for vi in mpn_list:
							if ismodelword(vi):
								mpnmw_list.append(vi)
	#get all the profile in dataset
	for source in os.listdir(dataset_path)[:]:
		for specification in os.listdir(os.path.join(dataset_path, source))[:]:
			specification_number = specification.replace('.json', '')
			specification_id = '{}//{}'.format(source, specification_number)
			with open(dataset_path+'/'+source+'/'+specification,encoding='utf-8') as specification_file:
				product=json.load(specification_file)
				title=product['<page title>'].lower()
				syns='-,;"\'、!@#$%^()[]+~*|&/\\'
				for syn in list(syns):
					title=title.replace(syn,' ')
				del product['<page title>']
				for k,v in product.items():
					product[k]=lower(v)
				product['<page title>']=title
				if product:
					products[specification_id]=product
				#operate one product profile
				for k,v in product.items():
					k=k.lower()
					if 'model' in k or k in ['mfr part number','part','part number','manufacturer']:
						v_list=[]
						#split value to v_list
						if not isinstance(v,list) and  not '/' in v:
							v.strip(':')
							v=[v]
						elif '/' in v:
							v.strip(':')
							v=v.split('/')
						for vi in v:
							vi.strip()
							vi=prestring(vi)
							if ':' in vi:
								continue
							elif ' ' in vi:
								vi=vi.split(' ')
								v_list.extend(vi)
							else:
								v_list.append(vi)
						#spliting title save into v_list
						t_list=title.split(' ')
						for vi in t_list:
							if ismodelword(vi):
								v_list.append(vi)
								break
						#get all the model words in v_list
						vmw_list=[]
						for vi in v_list:
							if ismodelword(vi) and vi not in mpnmw_list:
								vmw_list.append(vi)
						#save into result
						for token in vmw_list:
							if token in result:
								result[token].extend(vmw_list)
							else:
								result[token]=vmw_list
							ret=list(set(result[token]))
							while token in ret:
								ret.remove(token)
							if len(ret)>0:
								result[token]=ret
							if len(ret)==0 and token in result:
								del result[token]
								continue
							#result[token].append(token)
							result[token]=list(set(result[token]))
	return result

def getMWSynoDictFromData(dataset_path):
	result = getMWSynonymsDictFromSignalProfile(dataset_path)
	resultjs = json.dumps(result)
	f=open('./MWSynonymsDict_s.json','w',encoding='utf-8')
	f.write(resultjs)
	f.close()
	##print result
	#for kk,vv in result.items():
	#	print(kk,vv)
	#print(len(result))

if __name__ == '__main__':
	dataset_path='../../DI2KG_Datasets/X-monitor_specs/2013_monitor_specs'
	getMWSynoDictFromData(dataset_path)

	print("\nThe model word synonym dictionary was successfully obtained from the data set!")
	print("The synonym dictionary was written into MWSynonymsDict_s.json")


from pathlib import Path
import shutil
import os
from tqdm import tqdm

def prepare_images_by_age( path_dataset="../datasets/ffhq_mini/images/", age_min=20, age_max=70):
    dataset_name = "age_"+str(age_min)+"_to_"+str(age_max)
    print(f'[INFO] Dataset name: {dataset_name}.')

    new_path = Path(path_dataset) / dataset_name
    try :
        new_path.mkdir(parents=True, exist_ok=False)
    except FileExistsError:
        print(f'[INFO] Dataset already created.')
    else:
        print(f'[INFO] Dataset is being created...')

    for filename in tqdm(os.listdir(path_dataset)):

        if filename.split('_')[0] != 'age':

            in_age_min = int(filename.split('_')[0]) >= age_min
            in_age_max = int(filename.split('_')[0]) <= age_max

            if  in_age_min and in_age_max :
                shutil.move(path_dataset+"/"+filename, str(new_path)+"/"+filename)

if __name__ == "__main__":
    prepare_images_by_age()


'''
🍊75 · 寻找峰值(二分法)
中等  https://www.lintcode.com/problem/75
给定一个整数数组(size为n)，其具有以下特点：
	• 相邻位置的数字是不同的
	• A[0] < A[1] 并且 A[n - 2] > A[n - 1]
假定P是峰值的位置则满足A[P] > A[P-1]且A[P] > A[P+1]，返回数组中任意一个峰值的位置。
	• 数组保证至少存在一个峰
	• 如果数组存在多个峰，返回其中任意一个就行
	• 数组至少包含 3 个数

样例 1：
输入：A = [1, 2, 1, 3, 4, 5, 7, 6]
输出：1
解释：返回任意一个峰顶元素的下标，6也同样正确。

样例 2：
输入：A = [1,2,3,4,1]
输出：3
解释：返回峰顶元素的下标。
挑战
时间复杂度O (logN)O(logN)
'''

class Solution:
    """
    @param A: An integers array.
    @return: return any of peek positions.
    """
    def findPeak(self, A):
        n = len(A)
        l, r = 0, n - 1
        while l < r:
            m = l + ((r - l) >> 1)
            left, mid, right = A[m - 1], A[m], A[m + 1]
            if left < mid and right < mid:
                return m
            elif left > mid and right > mid:
                l = m + 1
            elif left < mid < right:
                l = m
            elif left > mid > right:
                r = m
        return l

75.寻找峰值-二分法.py


import collections
import json
from unittest import mock

import pytest
from py_zipkin.storage import get_default_tracer
from py_zipkin.storage import Stack

from pyramid_zipkin import tween
from tests.acceptance.test_helper import MockTransport

DummyRequestContext = collections.namedtuple(
    'RequestContext',
    ['zipkin_context'],
)

@pytest.mark.parametrize('is_tracing', [True, False])
@mock.patch.object(get_default_tracer(), 'zipkin_span', autospec=True)
def test_zipkin_tween_sampling(
    mock_span,
    dummy_request,
    dummy_response,
    is_tracing,
):
    """
    We should enter py_zipkin context manager and
    generate a trace id regardless of whether we are sampling
    """
    dummy_request.registry.settings = {
        'zipkin.is_tracing': lambda _: is_tracing,
        'zipkin.transport_handler': MockTransport(),
    }
    handler = mock.Mock()
    handler.return_value = dummy_response

    assert tween.zipkin_tween(handler, None)(dummy_request) == dummy_response
    assert handler.call_count == 1
    assert mock_span.call_count == 1

@pytest.mark.parametrize(['set_callback', 'called'], [(False, 0), (True, 1)])
@pytest.mark.parametrize('is_tracing', [True, False])
@mock.patch.object(get_default_tracer(), 'zipkin_span', autospec=True)
def test_zipkin_tween_post_handler_hook(
    mock_span,
    dummy_request,
    dummy_response,
    is_tracing,
    set_callback,
    called,
):
    """
    We should invoke the post processor callback regardless of trace id
    or sampling
    """
    mock_post_handler_hook = mock.Mock()

    dummy_request.registry.settings = {
        'zipkin.is_tracing': lambda _: is_tracing,
        'zipkin.transport_handler': MockTransport(),
    }
    if set_callback:
        dummy_request.registry.settings['zipkin.post_handler_hook'] = \
            mock_post_handler_hook

    handler = mock.Mock()
    handler.return_value = dummy_response

    assert tween.zipkin_tween(handler, None)(dummy_request) == dummy_response
    assert handler.call_count == 1
    assert mock_span.call_count == 1
    assert mock_post_handler_hook.call_count == called
    if set_callback:
        mock_post_handler_hook.assert_called_once_with(
            dummy_request,
            dummy_response,
            mock_span.return_value.__enter__.return_value,
        )

@pytest.mark.parametrize(['set_callback', 'called'], [(False, 0), (True, 1)])
@pytest.mark.parametrize('is_tracing', [True])
def test_zipkin_tween_exception(
    get_request,
    dummy_response,
    is_tracing,
    set_callback,
    called,
):
    """
    If request processing has an exception set response_status_code to 500
    """

    mock_post_handler_hook = mock.Mock()
    transport = MockTransport()

    get_request.registry.settings = {
        'zipkin.is_tracing': lambda _: is_tracing,
        'zipkin.transport_handler': transport,
    }
    if set_callback:
        get_request.registry.settings['zipkin.post_handler_hook'] = \
            mock_post_handler_hook

    handler = mock.Mock(side_effect=Exception)

    try:
        tween.zipkin_tween(handler, dummy_response)(get_request)
        pytest.fail('exception was expected to be thrown!')
    except Exception:
        pass

    spans = transport.get_payloads()
    assert len(spans) == 1
    span = json.loads(spans[0])[0]
    span['tags']['response_status_code'] = '500'
    span['tags']['error.type'] = 'Exception'

    assert handler.call_count == 1
    assert mock_post_handler_hook.call_count == called

@pytest.mark.parametrize(['set_callback', 'called'], [(False, 0), (True, 1)])
@pytest.mark.parametrize('is_tracing', [True])
def test_zipkin_tween_no_exception(
    get_request,
    dummy_response,
    is_tracing,
    set_callback,
    called,
):
    mock_post_handler_hook = mock.Mock()
    transport = MockTransport()

    get_request.registry.settings = {
        'zipkin.is_tracing': lambda _: is_tracing,
        'zipkin.transport_handler': transport,
    }
    if set_callback:
        get_request.registry.settings['zipkin.post_handler_hook'] = \
            mock_post_handler_hook

    handler = mock.Mock()
    tween.zipkin_tween(handler, dummy_response)(get_request)

    spans = transport.get_payloads()
    assert len(spans) == 1
    span = json.loads(spans[0])[0]
    span['tags']['response_status_code'] = '200'

    assert handler.call_count == 1
    assert mock_post_handler_hook.call_count == called

def test_zipkin_tween_context_stack(
    dummy_request,
    dummy_response,
):
    old_context_stack = get_default_tracer()._context_stack
    dummy_request.registry.settings = {
        'zipkin.is_tracing': lambda _: False,
        'zipkin.transport_handler': MockTransport(),
        'zipkin.request_context': 'rctxstorage.zipkin_context',
    }

    context_stack = mock.Mock(spec=Stack)
    dummy_request.rctxstorage = DummyRequestContext(
        zipkin_context=context_stack,
    )

    handler = mock.Mock(return_value=dummy_response)
    response = tween.zipkin_tween(handler, None)(dummy_request)
    get_default_tracer()._context_stack = old_context_stack

    assert response == dummy_response

    assert context_stack.push.call_count == 1
    assert context_stack.pop.call_count == 1

def test_getattr_path():
    request_context = DummyRequestContext(zipkin_context=object())
    assert tween._getattr_path(request_context, 'zipkin_context.__class__')

    # missing attribute
    tween._getattr_path(request_context, 'zipkin_context.missing') is None

    # attribute is None
    mock_object = mock.Mock(nil=None)
    assert tween._getattr_path(mock_object, 'nil') is None

def test_logs_warning_if_using_function_as_transport(
    dummy_request,
    dummy_response,
):
    dummy_request.registry.settings = {
        'zipkin.is_tracing': lambda _: False,
        'zipkin.transport_handler': lambda x: None,
        'request_context': 'rctxstorage',
    }

    handler = mock.Mock(return_value=dummy_response)
    with pytest.deprecated_call():
        tween.zipkin_tween(handler, None)(dummy_request)


n = input()
m = input()
m = m.split(' ')
moves = 0
m = [int(num, base = 10) for num in m]
y = m[0]
for x in m:
    if x < y:
        z = y-x
        y = x + z
        moves = z + moves
    else:
        y = x
print(moves)


"""
Functions for working with SDKs
"""
import maya.cmds as cmds
import maya.api.OpenMayaAnim as oma

import rigamajig2.shared.common as common
import rigamajig2.maya.attr as attr
import rigamajig2.maya.openMayaUtils as omu

SDKNODETYPES = ['animCurveUU', 'animCurveUA', 'animCurveUL', 'animCurveUT']
DEFAULT_SDK_TYPE = 'animCurveUU'

TANGENT_TYPE_DICT = {"linear": oma.MFnAnimCurve.kTangentLinear,
                     "auto": oma.MFnAnimCurve.kTangentAuto,
                     "fast": oma.MFnAnimCurve.kTangentFast,
                     "slow": oma.MFnAnimCurve.kTangentSlow,
                     "step": oma.MFnAnimCurve.kTangentStep,
                     "clamp": oma.MFnAnimCurve.kTangentClamped}

def getSdkNode(driver, driven, type=None):
    """
    Get all SDK nodes between the driver and driven node.
    This is useful especially for things like rotations where the conncection may be fed through
    a UnitConversion node before going to the driven node.

    :param str driver: sdk driver node
    :param str driven: sdk driven node
    :param type: Optional - specifiy a type of animCurve to return.
    :return: list of sdk nodes between a driver and driven.
    """
    if type is None:
        type = SDKNODETYPES
    else:
        type = common.toList(type)

    driver = common.getFirstIndex(driver)
    driven = common.getFirstIndex(driven)
    sdkSet = set()
    for obj in [driver, driven]:
        if not cmds.objExists(obj):
            raise RuntimeError("{} does not exist".format(obj))
        connList = cmds.ls(cmds.listConnections(obj, scn=True), type=type)
        for each in connList:
            connList.extend(cmds.ls(cmds.listConnections(each, scn=True), type=type))
            sdkSet.update(set(connList))
    return list(sdkSet)

def getSdkDriver(sdk):
    """
    get the driver of an sdk node

    :param str sdk: name of an SDK node
    :return: driver of an SDK node
    :rtype: str
    """
    if not cmds.ls(sdk, type=SDKNODETYPES):
        cmds.error('{} is not an SDK node'.format(sdk))
        return
    connList = cmds.listConnections(sdk, s=True, d=False, p=True, scn=True)
    if connList:
        return common.getFirstIndex(connList)
    else:
        return None

def getSdkDriven(sdk):
    """
    Get the nodes driven by a set driven key (anim curve) node

    :param sdk: Set driven key animation curve node. must be a valid rigamaig sdk curve type.
    :return: nodes driven by the sdk
    :rtype: str
    """
    if not cmds.ls(sdk, type=SDKNODETYPES):
        cmds.error('{} is not an SDK node'.format(sdk))
        return
    connList = cmds.listConnections(sdk, s=False, d=True, p=True, scn=True)

    if cmds.nodeType(connList[0]) == 'blendWeighted':
        connList = cmds.listConnections(connList[0].split('.', 1)[0], s=False, d=True, p=True, scn=True)

    if connList:
        return connList[0]
    else:
        return None

# TODO:
def createSdk(driverPlug, drivenPlug, values, preInfinity=False, postInfinity=False, tangent='linear'):
    """
    Create an SDK connection

    :param str driverPlug: driver plug
    :param str drivenPlug: driven plug
    :param list tupple values: list of values as tuples. in the format of: [(driver, driven), ...]
    :param bool preInfinity: If true set the tanget to PreInfitity to linear
    :param bool postInfinity:If true set the tanget to postInfinity to linear
    :param str tangent: type of tangent for the curve.
                        Valid values are: "spline", "linear" "fast", "slow", "flat", "step", "clamped".
    :return: the name of the SDK node created
    :rtype: str
    """
    driverNode, driverAttr = driverPlug.split(".")
    drivenNode, drivenAttr = drivenPlug.split(".")

    animCurveName = '{}_{}_{}_{}_animCurve'.format(driverNode, driverAttr, drivenNode, drivenAttr)
    animCurveNode = cmds.createNode(DEFAULT_SDK_TYPE, n=animCurveName)

    mObject = omu.getMObject(animCurveNode)
    mfnAnimCurve = oma.MFnAnimCurve(mObject)

    # connect the driver into the animCurveNode
    cmds.connectAttr(driverPlug, "{}.input".format(animCurveNode))

    # set the pre infinity behavior
    if preInfinity:
        mfnAnimCurve.setPreInfinityType(oma.MFnAnimCurve.kCycleRelative)
    else:
        mfnAnimCurve.setPreInfinityType(TANGENT_TYPE_DICT[tangent])

    # set the post infitiy behavior
    if postInfinity:
        mfnAnimCurve.setPostInfinityType(oma.MFnAnimCurve.kCycleRelative)
    else:
        mfnAnimCurve.setPostInfinityType(TANGENT_TYPE_DICT[tangent])

    for i, point in enumerate(values):
        inn = point[0]
        out = point[-1]
        mfnAnimCurve.addKey(inn, out)
        # set the in and out tangets based on the input
        mfnAnimCurve.setInTangentType(i, TANGENT_TYPE_DICT[tangent])
        mfnAnimCurve.setOutTangentType(i, TANGENT_TYPE_DICT[tangent])

    connected = cmds.listConnections(drivenPlug, source=True, destination=False, skipConversionNodes=True)
    if connected:
        nodeType = cmds.nodeType(connected[0])

        # if the input is a set driven key then created a blendweighted node to add the values together
        if nodeType in SDKNODETYPES:
            blendWeightedNode = createBlendWeightedNode(drivenPlug)
            nextInput = attr.getNextAvailableElement("{}.input".format(blendWeightedNode))
            cmds.connectAttr("{}.output".format(animCurveNode), nextInput)

        # if a blend weighted node is connected then connect the animCurve into the next available input
        elif nodeType == 'blendWeighted':
            blendWeightedNode = connected[0]
            nextInput = attr.getNextAvailableElement("{}.input".format(blendWeightedNode))
            cmds.connectAttr("{}.output".format(animCurveNode), nextInput)

        # if the connected plug is not a animCurve or a blendWeighted node then throw an error.
        else:
            raise Exception("{} is already connected to {}".format(drivenPlug, connected[0]))

    # if nothing is connected we can connect directly to the driver plug
    else:
        cmds.connectAttr("{}.output".format(animCurveNode), drivenPlug, f=True)

    # return the anim curve created
    return animCurveNode

def createBlendWeightedNode(drivenPlug):
    """
    create a blend weighted node on the driven plug

    :param drivenPlug: plug to add the blend weighted node to
    :return: blend weighted node created
    :rtype: str
    """
    drivenNode, drivenAttr = drivenPlug.split(".")
    # get the connected node. dont skip the conversion nodes in the case of connection to a rotation.
    # also get a unit conversion node. later we will check if the first node is a unit conversion and if it is delete it.
    connected = cmds.listConnections(drivenPlug, source=True, destination=False, plugs=True, skipConversionNodes=True)
    unitConvert = cmds.listConnections(drivenPlug, source=True, destination=False, plugs=True, skipConversionNodes=False)

    blendWeightedNode = cmds.createNode("blendWeighted", n="{}_{}_blendWeighted".format(drivenNode, drivenAttr))

    # if the drivenPlug has an incoming connection connect it to the blendWeightedNode
    if connected:
        nextPlug = attr.getNextAvailableElement("{}.input".format(blendWeightedNode))
        # a node can only have one given input so we can get the first index of the connected list
        cmds.connectAttr(connected[0], nextPlug, f=True)

    if cmds.nodeType(unitConvert[0]) == 'unitConversion':
        cmds.delete(unitConvert)

    # connect the blendWeighted to the drivenPlug
    cmds.connectAttr("{}.output".format(blendWeightedNode), drivenPlug, f=True)

    return blendWeightedNode


import airshare
import requests
import socket
import webbrowser

SERVER_ADDR = 'http://172.30.1.48:32456'

CODE = 'brad-macbook-pro'
PORT = 23456

local_ip_addr = socket.inet_ntoa(airshare.utils.get_local_ip_address())

data = {
    'code': CODE,
    'ip_addr': local_ip_addr,
    'port': PORT,
}

r = requests.post('%s/register' % (SERVER_ADDR,), data)

print(r.json())

try:
    webbrowser.open('%s/browse' % SERVER_ADDR)
except:
    print('%s/browse' % SERVER_ADDR)

airshare.receiver.receive_server(code=CODE, port=PORT)


def main():

    table = []
    for i in range(8):
        table.append([0,0,0,0,0,0,0,0])

    table[0][0] = 1

    steps = [[1,2], [2,1], [-1,2], [2,-1]]

    points = [[0,0]]

    sw = True
    start = 0

    while sw:

        if [7,7] in points:
            sw = True
            break

        l = []
        for p in points:
            for step in steps:
                i = p[0] + step[0]
                j = p[1] + step[1]
                if (i <= 7 and i >= 0) and (j <= 7 and j >= 0) and table[i][j] == 0:
                    table[i][j] = 1
                    l.append([i, j])
        points = l

    for t in table:
        print(t)

    revers_table = []
    for _ in range(8):
        revers_table.append([0,0,0,0,0,0,0,0])

    print()
    for i in range(8):
        for j in range(8):
            revers_table[7 - i][7 - j] = table[i][j]

    for t in revers_table:
        print(t)

    last = []
    for _ in range(8):
        last.append([0,0,0,0,0,0,0,0])

    for i in range(8):
        for j in range(8):
            last[i][j] = table[i][j] and revers_table[i][j]

    print()

    for t in last:
        print(t)

main()


# do not forget to run the coupon project !!
import requests # need to install in settings
import json
import pytest

class RestObject:
    def __init__(self, d):
        self.__dict__ = d
    def __str__(self):
        result = ""
        for k, v in self.__dict__.items():
            result += k
            result += " : "
            result += str(v)
            result += '\n'
        return result

def test_rest_api_get_todos():
    resp = requests.get("https://jsonplaceholder.typicode.com/todos/1")
    d = json.loads(resp.content)
    t = RestObject(d)
    assert t.id == 1
    assert t.userId == 1
    assert t.title == 'delectus aut autem'
    assert t.completed == False

def test_rest_api_get_coupon():
    resp = requests.get("http://localhost:8080/coupon/1")
    d = json.loads(resp.content)
    t = RestObject(d)
    assert t.id == 1
    assert t.title == 'Caffe'
    # [{"title":"Caffe","id":1},{"title":"Movie VIP","id":2},{"title":"Sky jump","id":3}]


# -*- coding: utf-8 -*-
"""
Created on Thu May  7 11:55:28 2020

@author: Prabhanshu Aggarwal
"""

def pair_sum(arr , k):
    seen =set()
    output =set()

    for num in arr:
        target = k-num
        if target not in seen:
            seen.add(num)
        else:
            output.add(((min(num, target)), max(num, target)))
    print((output))
    print(list(output))
    return '\n'.join(map(str, list(output)))


# !/usr/bin/env python
# -*-coding:utf-8-*-
from sqlite import sqlite_get_first, sqlite_first, sqlite_update
from web3 import Web3
from web3.middleware import geth_poa_middleware
from config import config
import sys
import os
from datetime import datetime

network = sys.argv[1]
w3 = Web3(Web3.WebsocketProvider(config('NODE', network + config('NODE', 'CHAIN')).format(config('MORALIS', "FIND_BLOCK")), websocket_timeout=900, websocket_kwargs={'max_size': 999999999}))
w3.middleware_onion.inject(geth_poa_middleware, layer=0)
while True:
    try:
        latestBlock = w3.eth.getBlock('latest').number
        checkLastBlock = sqlite_first("bots", "WHERE network='{0}' AND status=1 ORDER BY block DESC".format(network))
        if checkLastBlock is None:
            blockNum = latestBlock
        else:
            blockNum = int(checkLastBlock['block']) + 1
        if latestBlock >= blockNum:
            checkFreeBot = sqlite_get_first("bots", "block", None)
            if checkFreeBot is not None:
                sqlite_update("bots", "block = {0}, network = '{1}', updated_at='{2}'".format(blockNum, network, datetime.now().strftime("%d/%m/%Y %H:%M:%S")), "bot", checkFreeBot['bot'])
    except Exception as e:
        exc_type, exc_obj, exc_tb = sys.exc_info()
        fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
        print("error----------", e, exc_type, fname, exc_tb.tb_lineno)


from fastapi import APIRouter

from app.api import RouterTags

router = APIRouter(
    tags = [RouterTags.File],
    responses = { 404: { "detail": "not found" } }
)

####################################
# file serve request
# /home/foo/var.txt -> /files//home/foo/var.txt
####################################
@router.get("/files/{filepath:path}")
async def serve_file(filepath: str):
    return { filepath: filepath }


'''
    ControlSurface_Calibration.py

    Description: Library containing the control surface calibration
                 for servo limiting.

    Revision History
    15 Feb 2017 - Created and debugged

    Author: Lars Soltmann

    References: None

    Calls: None

    Notes:
    - Written for Python3

    Inputs: d_a - aileron deflection (deg)
            d_e - elevator deflection (deg)
            d_r - rudder deflection (deg)

    Outputs: d_a_pwm - PWM command for aileron servo (u_sec)
             d_e_pwm - PWM command for elevator servo (u_sec)
             d_r_pwm - PWM command for rudder servo (u_sec)
             d_T_pwm - PWM command for throttle (u_sec)

    OPEN ITEMS:
    1.

    '''

class CS_cal:
    def __init__(self):
        #Calibration functions are measured and will generally follow the form
        # slope=((pwm_1-pwm_2)/(deflection_1-deflection_2))
        # intercept=center

        #Zero position PWM (u_sec) of each control surface
        self.da_center=1504
        self.de_center=1488
        self.dr_center=1523
        self.dT_off=900

        #Slope of calibration function
        self.da_slope=-23.328
        self.de_slope=17.316
        self.dr_slope=19.786
        self.dT_slope=(2100-900)/(100)

    def delta_to_pwm(self,d_a,d_e,d_r,d_T):
        ##Apply control surface calibrations
        #Aileron
        d_a_pwm=round(self.da_slope*d_a+self.da_center)

        #Elevator
        d_e_pwm=round(self.de_slope*d_e+self.de_center)

        #Rudder
        d_r_pwm=round(self.dr_slope*d_r+self.dr_center)

        #Throttle
        d_T_pwm=round(self.dT_slope*d_T+self.dT_off)

        return d_a_pwm,d_e_pwm,d_r_pwm,d_T_pwm

    def pwm_to_delta(self,d_a_pwm,d_e_pwm,d_r_pwm,d_T_pwm):
        ##Apply inverse of control surface calibration
        #Aileron
        d_a=-(self.da_center-d_a_pwm)/self.da_slope

        #Elevator
        d_e=-(self.de_center-d_e_pwm)/self.de_slope

        #Rudder
        d_r=-(self.dr_center-d_r_pwm)/self.dr_slope

        #Throttle
        d_T=-(self.dT_off-d_T_pwm)/self.dT_slope

        return d_a,d_e,d_r,d_T


"""
Serves any global constants (e.g., strings, ints, enums) relative
to this code base. Avoid importing the entire module (e.g., import constants)

Typical usage example:
    from core.constants import bar
    foo = bar
"""

JS_CSP_SCRIPTS = [
    "'self'",
    "https://*.jsdelivr.net",
    "https://*.jquery.com",
    "https://*.rawgit.com",
    "https://*.usefathom.com",
]

CSP_SCRIPT_EXCLUSION_HEADERS = " ".join(JS_CSP_SCRIPTS)


import argparse

def config_setting():
    ############################
    #    hyper parameters      #
    ############################
    cfg = argparse.ArgumentParser(description='PyTorch MNIST Capsnet Example')

    cfg.add_argument('--m_plus', type=float, default=0.9, help='the parameter of m plus')
    cfg.add_argument('--m_minus', type=float, default=0.1, help='the parameter of m minus')
    cfg.add_argument('--lambda_val', type=float, default=0.5, help='down weight of the loss for absent digit classes')

    # for training
    cfg.add_argument('--epoch', type=int, default=50000, help='epoch')
    cfg.add_argument('--num_routing', type=int, default=3, help='number of iterations in routing algorithm')
    cfg.add_argument('--num_primary_caps', type=int, default=32, help='number of primary caps')
    boolean_flag(cfg, 'leaky', default=True, help='if use leaky routing')
    cfg.add_argument('--learning_rate', type=float, default=0.001, help='initial learning rate')
    cfg.add_argument('--decay_rate', type=float, default=0.96, help='learning rate decay')
    cfg.add_argument('--decay_steps', type=int, default=2000, help='decay steps')
    boolean_flag(cfg, 'use_cuda', default=True, help='use cuda')

    cfg.add_argument('--dataset', type=str, default='mnist', help='dataset name')
    cfg.add_argument('--path', type=str, default='../../data/mnist/', help='the path for dataset')
    cfg.add_argument('--batch_size', type=int, default=100, help='batch size')
    cfg.add_argument('--balance_factor', type=float, default=0.0005, help='classification loss + balance_factor*reconstruciton loss')
    boolean_flag(cfg, 'constrained', default=False, help='Use constrained capsules')
    args = cfg.parse_args()
    return args

def boolean_flag(cfg, name, default=False, help=None):
    dest = name.replace('-', '_')
    cfg.add_argument("--" + name, action="store_true", default=default, dest=dest, help=help)
    cfg.add_argument("--no-" + name, action="store_false", dest=dest)