import numpy as np

import pandas as pd

import matplotlib.pyplot as plt

import seaborn as sns

train_identity = pd.read_csv('/kaggle/input/ieee-fraud-detection/train_identity.csv', index_col='TransactionID')

train_transaction = pd.read_csv('/kaggle/input/ieee-fraud-detection/train_transaction.csv', index_col='TransactionID')

# merge the two dataframe in a single set

train = train_transaction.merge(train_identity, how='left', left_index=True, right_index=True)
# compile list of C columns

c_list = []

for i in range(1,15):

    c_list.append('C' + str(i))

# compile list of D columns

d_list = []

for i in range(1,16):

    d_list.append('D' + str(i))

# compile list of V columns

v_list = []

for i in range(1,340):

    v_list.append('V' + str(i))

# compile list of id columns

id_list = []

for i in range(1,12):

    ii = str(i).zfill(2)

    id_list.append('id_' + str(ii))

id_list.extend(['id_13','id_14','id_17','id_18','id_19','id_20','id_21',\

                'id_22','id_24','id_25','id_26','id_32'])

# create list of columns label for correlation check

colums_for_corr = ['isFraud','TransactionAmt','card1','card2','card3','card5','addr1','addr2','dist1','dist2']

colums_for_corr.extend(c_list)

colums_for_corr.extend(d_list)

colums_for_corr.extend(v_list)

colums_for_corr.extend(id_list)

corr_matrix = train[colums_for_corr].corr()
sns.set(rc={'figure.figsize':(20,20)})

sns.heatmap(corr_matrix, cmap="RdBu")
isFraud_corr = corr_matrix['isFraud']

columns_with_correlation = isFraud_corr.loc[isFraud_corr >= 0.2]

print(columns_with_correlation.sort_values(ascending=False))
def check_corr_fraud(df, col):

    fr1 = (df.loc[df['isFraud'] == 1][col].value_counts())

    fr0 = (df.loc[df['isFraud'] == 0][col].value_counts())

    fr = pd.merge(fr1, fr0, how = 'left',

                  left_on  = fr1.index,

                  right_on = fr0.index)

    fr = fr.rename(columns={'key_0': col,

                            f'{col}_x': 'Fraud',

                            f'{col}_y': 'Not Fraud'})

    fr['tot count'] = fr['Fraud'] + fr['Not Fraud']

    fr['% Fraud'] = 100 * np.divide(fr['Fraud'], fr['tot count'])

    fr['% Not Fraud'] = 100 * np.divide(fr['Not Fraud'], fr['tot count'])

    return fr
def plot_corr_fraud(df,col):

    a = check_corr_fraud(train,col)

    sns.set(rc={'figure.figsize':(11.7,8.27)})

    plt.bar(a[col], a['% Fraud'])

    plt.ylim([0,100])

    plt.ylabel('% Fraud',fontsize=12)

    plt.xlabel(col,fontsize=12)

    plt.xticks(rotation=90)

    plt.subplots_adjust(bottom=0.4)

    return

def plot_corr_fraud_large(df,col):

    a = check_corr_fraud(train,col)

    sns.set(rc={'figure.figsize':(101.7,8.27)})

    plt.bar(a[col], a['% Fraud'])

    plt.ylim([0,100])

    plt.ylabel('% Fraud',fontsize=12)

    plt.xlabel(col,fontsize=12)

    plt.xticks(rotation=90)

    plt.subplots_adjust(bottom=0.4)

    return
plot_corr_fraud(train,'P_emaildomain')
plot_corr_fraud(train,'R_emaildomain')
plot_corr_fraud_large(train,'id_31')
plot_corr_fraud_large(train,'DeviceInfo')


import socket
import time
import picamera

"""
First way:
- Run server first and then `vlc tcp/h264://127.0.0.1:8000/` on client
- Running into main input error: ES_OUT_SET_(GROUP_)PCR errors
- super jittery

An alternative way:
- server: $ raspivid -vf -n -w 640 -h 480 -t 60000 -o - | nc localhost 8000
- client: $ nc -l 8000 | vlc --demux h264 -
OR        $ nc -l localhost 8000 | vlc --demux h264 -
- There is a heavy delay

Alternatively:
- use mplayer, need cache (otherwise get `Cannot seek backward in linear streams!`)
  https://unix.stackexchange.com/questions/97046/how-to-get-mplayer-to-play-from-stdin
- $ nc -l 8000 | mplayer -fps 24 -cache 1024 -framedrop -
"""
with picamera.PiCamera() as camera:
    camera.resolution = (640, 480)
    camera.framerate = 30
    camera.vflip = True
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server_socket.bind(('localhost', 8000)) # 127.0.0.1
    print("Server Listening")
    server_socket.listen(0)

    # Accept a single connection and make a file-like object out of it
    connection = server_socket.accept()[0].makefile('wb')
    try:
        print('Starting recording')
        camera.start_recording(connection, format='h264')
        camera.wait_recording(10)
        print('Stopping recording')
        camera.stop_recording()
    finally:
        connection.close()
        server_socket.close()


import asyncio
import aiohttp
from django.shortcuts import render

import requests
import time

async def fetch(session, url):
    async with session.get(url) as response:
        assert response.status == 200
        return await response.json()

async def async_home_view(request):
    start_time = time.time()

    url_list = [
        ('people', 'https://swapi.dev/api/people/'),
        ('starships', 'https://swapi.dev/api/starships/'),
    ]

    async with aiohttp.ClientSession() as client:
        tasks = []

        for key, url in url_list:
            task = asyncio.ensure_future(fetch(client, url))
            tasks.append(task)

        results = await asyncio.gather(*tasks)

    total_time = time.time() - start_time

    context = {
        'people': results[0],
        'starships': results[1],
        'total_time': total_time,
    }

    return render(request, 'home.html', context)

def home_view(request):
    start_time = time.time()

    data = []

    url_list = [
        'https://swapi.dev/api/people/',
        'https://swapi.dev/api/starships/',
    ]

    for url in url_list:
        response = requests.get(url)
        results = response.json()
        data.append(results)

    total_time = time.time() - start_time

    context = {
        'people': data[0],
        'starships': data[1],
        'total_time': total_time,
    }

    return render(request, 'home.html', context)


import pandas as pd
import os
import warnings
from tqdm import tqdm
from config import *
from gen_html import gen_html
warnings.filterwarnings("ignore")

def deal_name_changes(name):
    if name=='天才呆黑魔魔':
        return '胡乱思维的猫'
    return name

def cal():
    # 出场次数	总得分	一位率	二位率	三位率	四位率  总局数  和牌率  放铳率  立直率  副露率  自摸率
    data=[[0,0,0,0,0,0,0,0,0,0,0,0] for i in range(34)]

    file_name = 'player.xlsx'
    frame=pd.read_excel(file_name)
    dic={}
    team_has_player=[[] for _ in range(10)]
    for i in range(len(frame['id'])):
        dic[str(frame['name'][i])]=frame['id'][i]
        team_has_player[int(frame['team_id'][i])].append(int(frame['id'][i]))

    data_filenames=None
    for root, dirs, files in os.walk('./data'):
        data_filenames=[root+'/'+f for f in files]
    #print(data_filenames)

    # 顺位马见config.add_score
    for path in tqdm(data_filenames):
        frame1=pd.read_excel(path)
        scores=[0,0,0,0]

        for i in range(4):
            playerid=dic[deal_name_changes(str(frame1['帐户名'][i]))]
            place=int(frame1['名次'][i])
            scores[i]=add_score[place-1]+(int(frame1['标准分之和'][i])-init_score)/1000
            data[playerid][0]+=1
            data[playerid][place+1]+=1
            data[playerid][6]+=frame1['局数'][i]
            data[playerid][7]+=frame1['和了数'][i]
            data[playerid][8]+=frame1['放銃数'][i]
            data[playerid][9]+=frame1['立直数'][i]
            data[playerid][10]+=frame1['副露数'][i]
            data[playerid][11]+=frame1['自摸数'][i]

        if has_tie:
            # 同分则平分点数
            for m in range(4):
                for n in range(m+1,4):
                    if int(frame1['标准分之和'][m])==int(frame1['标准分之和'][n]):
                        scores[m]=scores[n]=(scores[m]+scores[n])/2
        for i in range(4):
            playerid=dic[deal_name_changes(str(frame1['帐户名'][i]))]
            data[playerid][1]+=scores[i]

    for i in range(player_number):
        frame['出场次数'][i]=data[i][0]
        frame['总得分'][i]=data[i][1]
        frame['一位率'][i]=str(round(data[i][2]/data[i][0]*100,2))+'%' if data[i][0]!=0 else "0.0%"
        frame['二位率'][i]=str(round(data[i][3]/data[i][0]*100,2))+'%' if data[i][0]!=0 else "0.0%"
        frame['三位率'][i]=str(round(data[i][4]/data[i][0]*100,2))+'%' if data[i][0]!=0 else "0.0%"
        frame['四位率'][i]=str(round(data[i][5]/data[i][0]*100,2))+'%' if data[i][0]!=0 else "0.0%"
        frame['总局数'][i]=data[i][6]
        frame['自摸率'][i]=str(round(data[i][11]/data[i][7]*100,2))+'%' if data[i][7]!=0 else "0.0%"
        frame['和牌率'][i]=str(round(data[i][7]/data[i][6]*100,2))+'%' if data[i][6]!=0 else "0.0%"
        frame['放铳率'][i]=str(round(data[i][8]/data[i][6]*100,2))+'%' if data[i][6]!=0 else "0.0%"
        frame['立直率'][i]=str(round(data[i][9]/data[i][6]*100,2))+'%' if data[i][6]!=0 else "0.0%"
        frame['副露率'][i]=str(round(data[i][10]/data[i][6]*100,2))+'%' if data[i][6]!=0 else "0.0%"

    scores=team_init_score
    for i in range(player_number):
        for j in range(len(team_name)):
            if i in team_has_player[j]:
                scores[j]+=data[i][1]

    names=team_name
    df = pd.DataFrame([[names[i],scores[i]]for i in range(len(team_name))],index=[i for i in range(len(team_name))],columns=['team_name', 'score'])

    with pd.ExcelWriter('output.xlsx') as writer:
        frame.to_excel(writer,sheet_name='player')
        df.to_excel(writer , sheet_name='team')

    with pd.ExcelWriter('./koala/output.xlsx') as writer:
        frame.to_excel(writer,sheet_name='player')
        df.to_excel(writer , sheet_name='team')

if __name__=='__main__':
    cal()
    gen_html()


import matplotlib.pyplot as plt
import numpy as np

xp = np.linspace(0.1, 0.4, 100)
xs=0.5
mu=1
rop=xp/mu
ros=xs/mu
yp=1+(0.5/(1-rop))
ys=1+(0.5/((1-rop)*(1-rop-ros)))
plt.plot(xp, yp,label="Elsődleges felhasználó")
plt.plot(xp,ys,label="Kognitív felhasználó")
plt.legend(loc="upper right")
plt.title("CRN")
plt.ylim(ymin=0)
plt.xlim(xmin=0.1)
plt.xlim(xmax=0.4)
#plt.xticks([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7 ,0.8, 0.9, 1])
plt.xlabel("ELsődleges érkezési intenzitás")
plt.ylabel("Átlagos várakozási idő")
plt.show()


##########################
import math
import sys
# from random import randrange

try:
  from OpenGL.GLUT import *
  from OpenGL.GL import *
  from OpenGL.GLU import *
except:
  print ('''
ERROR: PyOpenGL not installed properly.
        ''')
  sys.exit()
###########################

###  32 Column 40 rows ###

# keylocx = randrange(10,160,15)
# keylocy = randrange(10,160,15)
keylocx = 40
keylocy = 25
print(keylocy)
print(keylocx)

ambil_kunci = False
levels = [""]
left = 0
right = 0
up = 0
down = 0

### MAZE ###
level_1 = [
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"XP        XXXXXXXXX                       XXXXXXXXXXXXX",
"X XX XXXX XXXXXXXXX                       XXXXXXXXXXXXX",
"X X     X XXXXXXXXX                       XXXXXXXXXXXXX",
"X XXXXX X XXXXXXXXX     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"X     X X XXXXXXXXX                       XXXXXXXXXXXXX",
"XX XX XXX XXXXXXXXX     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"X  X  XXXXXXXXXXXXX                     XXXXXXXXXXXXXXX",
"X                                         XXXXXXXXXXXXX",
"X     XXXXXXXXXXXXX                       XXXXXXXXXXXXX",
"X     XXXXXXXXXXXXX     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"X     XXXXXXXXXXXXX                       XXXXXXXXXXXXX",
"X     XXXXXXXXXXXXX     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"X                                             XXXXXXXXX",
"X     XXXXXXXXXXXXX                      XXXXXXXXXXXXXX",
"X     XXXXXXXXXXXXX     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"X     XXXXXXXXXXXXX                           XXXXXXXXX",
"X     XXXXXXXXXXXXX                        XXXXXXXXXXXX",
"X     XXXXXXXXXXXXX                       XXXXXXXXXXXXX",
"X                                         XXXXXXXXXXXXX",
"X                       XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"X     XXXXXXXXXXXXX     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"X     XXXXXXXXXXXXX                       XXXXXXXXXXXXX",
"X     XXXXXXXXXXXXX                       XXXXXXXXXXXXX",
"X     XXXXXXXXXXXXX     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"X     XXXXXXXXXXXXX     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"X     XXXXXXXXXXXXX                       XXXXXXXXXXXXX",
"X     XXXXXXXXXXXXX     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"X     XXXXXXXXXXXXX     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"X     XXXXXXXXXXXXX                       XXXXXXXXXXXXX",
"X     XXXXXXXXXXXXX     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"X     XXXXXXXXXXXXX                       XXXXXXXXXXXXX",
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
]

levels.append(level_1)

walls = []

class Draw():
    def dot(self,size,red,green,blue,x,y):
        self.size = size
        self.red = red
        self.green = green
        self.blue = blue
        self.x = x
        self.y = y
        glPointSize(size)
        glBegin(GL_POINTS)
        glColor3f(red,green,blue)
        glVertex2f(x,y)
        glEnd()

def setup_maze(level):
    global screen_x, screen_y, walls
    for y in range(len(level)):
        for x in range(len(level[y])):
            character = level[y][x]
            screen_x = 10 + (x*15)
            screen_y = 10 + (y*15)
            if character == "X":
              walls.append((screen_x,screen_y))
              draw.dot(15,255,0,0,screen_x,screen_y)

class Player():
    def playerk(self,x,y):
        global koorx,koory
        self.koorx = koorx = x
        self.koory = koory = y
        draw.dot(14,0,0,200,koorx+left+right,koory+up+down)

    def player_movement(key,x,y):
        global up, down, left, right
        # print(koorx+left+right, koory+up+down)
        if (koorx+left+right, koory+up+down+15) not in walls:
            if key == GLUT_KEY_UP:
                up += 15
        if (koorx+left+right, koory+up+down-15) not in walls:
            if key == GLUT_KEY_DOWN:
                down -= 15
        if (koorx+left+right+15, koory+up+down) not in walls:
            if key == GLUT_KEY_RIGHT:
                right += 15
        if (koorx+left+right-15, koory+up+down) not in walls:
            if key == GLUT_KEY_LEFT:
                left -= 15

        # if (koorx+(left-15)+(right+15), koory+(up+15)+(down-15)) == (keylocx,keylocy):
        #     exitkey.taken_by_player(keylocx,keylocy)
        #     print("kunci telah diambil")

        if (koorx+(left-15)+(right+15), koory+(up+15)+(down-15)) == (koorxg+(left-15)+(right+15), kooryg+(up+15)+(down-15)):
            print("kunci telah diambil")

    # def is_colliding_key(self,other):
    #     a = self.koorx - other[0]
    #     b = self.koory- other[1]
    #     distance = math.sqrt((a**2)+(b**2))
    #     if distance < 5:
    #         print("Taken")
    #         return True
    #     else:
    #         return False

# def check_col():
#     if player.is_colliding_key((keylocx,keylocy)):
#         (print("nice"))

class ExitKey():
    def exitkey(self,x,y):
        global keylocx,keylocy,ambil_kunci
        self.keylocx = keylocx = x
        self.keylocy = keylocy = y
        draw.dot(10,255,0,255,keylocx,keylocy)
        draw.dot(6,255,0,255,keylocx+8,keylocy)
        draw.dot(6,255,0,255,keylocx+14,keylocy)
        draw.dot(6,255,0,255,keylocx+20,keylocy)
        draw.dot(6,255,0,255,keylocx+20,keylocy-3)
        if (keylocx,keylocy) ==(koorx+(left-15)+(right+15), koory+(up+15)+(down-15)):
            ambil_kunci = True
            keylocx += 800
            keylocy += 300
            print(ambil_kunci,"kunci telah diambil")

    def taken_by_player(self,keylocx, keylocy):
        self.keylocx = keylocx + 500
        self.keylocy = keylocy + 500

class Ghost():
  def ghost(self,xg,yg):
    global koorxg,kooryg
    self.koorxg = koorxg = xg
    self.kooryg = kooryg = yg
    draw.dot(14,0,255,255,koorxg+left+right, kooryg+up+down)

### class instance ###
draw = Draw()
player = Player()
exitkey = ExitKey()
ghost1 = Ghost()

def iterate():
    glViewport(0, 0, 1000, 500)
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    glOrtho(0.0, 1000, 0.0, 500, 0.0, 1.0)
    glMatrixMode (GL_MODELVIEW)
    glEnable(GL_BLEND)
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
    glLoadIdentity()

def showScreen():
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    glLoadIdentity()
    iterate()
    glColor3f(1.0, 0.0, 3.0)
    setup_maze(levels[1])
    player.playerk(25,25)
    ghost1.ghost(40,40)
    exitkey.exitkey(keylocx,keylocy)
    glutSwapBuffers()

glutInit()
glutInitDisplayMode(GLUT_RGBA)
glutInitWindowSize(1000, 500)
glutInitWindowPosition(100, 50)
wind = glutCreateWindow("ini maze")
glutDisplayFunc(showScreen)
glutSpecialFunc(Player.player_movement)
glutIdleFunc(showScreen)
glutMainLoop()


import cv2
import tkinter as tk
from PIL import Image, ImageTk

root = tk.Tk()
root.title("Webcam App")

label = tk.Label(root)
label.pack()

cap = cv2.VideoCapture("http://192.168.1.6:8080/video")

def update():
    ret, frame = cap.read()
    if ret:
        img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        img = Image.fromarray(img)
        img = ImageTk.PhotoImage(img)
        label.imgtk = img
        label.config(image=img)
    label.after(10, update)

update()

root.mainloop()

cap.release()


from django.urls import path
from . import views

urlpatterns = [
    path('api-item/', views.Home.as_view()),
    path('api-item/<str:pk>/', views.Detail.as_view()),
    path('<str:pk>/add_to_cart/', views.add_to_cart),
    path('api-cart/', views.cart_view),
    path('<str:pk>/rmone_from_cart/', views.remove_one_item_from_cart),
    path('<str:pk>/rm_from_cart/', views.remove_from_cart),
    path('api-search/', views.PostSearch.as_view()),
    path('wish/', views.WishList().as_view()),
    path('<str:pk>/wish/', views.add_wish),
]


import os
import stripe
from datetime import datetime, timedelta
from assets.models import DataSource

stripe.api_key = os.environ.get("STRIPE_API_KEY", None)
stripe.api_version = "2020-08-27"

def query_subscription_data(api_key, data):
    """
    Query subscription data and populate the data dictionary
    """
    # initialize stripe client
    stripe.api_key = os.environ.get(api_key, None)
    stripe.api_version = "2020-08-27"

    # Retrieve the list of subscriptions
    subscriptions = stripe.Subscription.list(limit=100)

    mrr = total_revenue = 0

    # Iterate over each subscription
    for subscription in subscriptions.auto_paging_iter():
        created_timestamp = subscription.created
        created_date = datetime.fromtimestamp(created_timestamp)
        month_year = created_date.strftime("%Y-%m")

        total_revenue += subscription.plan.amount / 100

        if subscription.plan and subscription.plan.interval == "month":
            mrr += subscription.plan.amount / 100

        # Add the data points to the corresponding month
        if month_year not in data:
            data[month_year] = {
                "all subscription": 0,
                "active subscriptions": 0,
                "trial subscriptions": 0,
                "canceled subscriptions": 0,
                "monthly recurring revenue": 0,
                "total revenue": 0,
                "user churn": 0,
                "revenue churn": 0,
            }

        monthly_data = data[month_year]

        monthly_data["all subscription"] += 1

        monthly_data["monthly recurring revenue"] = mrr

        monthly_data["annual recurring revenue"] = mrr * 12

        monthly_data["total revenue"] = total_revenue

        monthly_data["timestamp"] = str(datetime.now())

        if subscription.status == "active":
            monthly_data["active subscription"] += 1
        elif subscription.status == "trialing":
            monthly_data["trial subscription"] += 1
        elif subscription.status == "canceled":
            monthly_data["canceled subscription"] += 1
            monthly_data["user churn"] += 1
            monthly_data["revenue churn"] += subscription.plan.amount

    return data

def query_customer_data(api_key, data):
    """
    Query customer data and populate the data dictionary
    """
    # Active Customers
    customers = stripe.Customer.list(limit=100)

    for customer in customers.auto_paging_iter():
        created_timestamp = customer.created
        created_date = datetime.fromtimestamp(created_timestamp)
        month_year = created_date.strftime("%Y-%m")

        if "active customers" not in data[month_year]:
            data[month_year]["active customers"] = 0
            data[month_year]["arpu"] = 0

        monthly_data = data[month_year]

        monthly_data["active customers"] += 1
        monthly_data["arpu"] = (
            monthly_data["total revenue"] / monthly_data["active customers"]
        )

        monthly_data["timestamp"] = str(datetime.now())

    return data

def fetch_data(datasource_id):
    """
    Fetch data associated with a given source
    {
        '2023-05':
            {
                'all subscription': 200,
                'active subscription': 200,
                'trial subscription': 0,
                'canceled subscription': 0,
                'monthly recurring revenue': 10372.760000000004,
                'total revenue': 10372.760000000004,
                'user churn': 0,
                'revenue churn': 0,
                'annual recurring revenue': 124473.12000000005,
                'total customers': 519,
                'arpu': 19.947615384615393,
                'active customers': 520,
                'timestamp': '2023-05-22 21:19:10.709702'
            },
        '2023-06':
            {
                'all subscription': 200,
                'active subscription': 200,
                'trial subscription': 0,
                'canceled subscription': 0,
                'monthly recurring revenue': 10372.760000000004,
                'total revenue': 10372.760000000004,
                'user churn': 0,
                'revenue churn': 0,
                'annual recurring revenue': 124473.12000000005,
                'total customers': 519,
                'arpu': 19.947615384615393,
                'active customers': 520,
                'timestamp': '2023-05-22 21:19:10.709702'
            },
    }
    """
    datasource = DataSource.objects.get(id=datasource_id)
    api_key = datasource.api_key

    # Create a dictionary to store subscriptions month-wise
    data = {}

    query_subscription_data(api_key, data)
    query_customer_data(api_key, data)

    return data


"""
가장 어려웠던 문제였고 다른 사람 풀이 참조해서 풀었음.
operand로 쓰이는 N의 개수를 1개부터 8개까지 test 해가면서 사칙연산한 값 중에서 target 값이 있다면,
해당 N의 개수를 반환
"""

def solution(N, number):
    arr = [set() for _ in range(8)]
    for idx, i in enumerate(arr):
        i.add(int(str(N) * (idx+1)))
    print(arr)
    for i in range(1, len(arr)):
        for j in range(i):
            for x in arr[j]:
                for y in arr[i-j-1]:
                    if y == 0:
                        arr[i].update([x + y, x - y, x * y])
                    else:
                        arr[i].update([x + y, x - y, x * y, x // y])
        if number in arr[i]:
            return i + 1
    return -1

print(solution(5,12))


from generalized_alphanpi.utils import import_dyn_class
from generalized_alphanpi.core.PolicyOnly import PolicyOnly

import numpy as np
import pandas as pd

from argparse import ArgumentParser
import yaml

import time
import os
from tqdm import tqdm

import torch

if __name__ == "__main__":

    parser = ArgumentParser()
    parser.add_argument("model", type=str, help="Path to the automa model we want to validate.")
    parser.add_argument("task", type=str, help="Task we want to execute")
    parser.add_argument("--config", type=str, help="Path to the file with the experiment configuration")
    parser.add_argument("--alpha", type=float, default=0.65, help="Percentage of successful rules satisfied")
    parser.add_argument("--single-core", default=True, action="store_false", help="Run everything with a single core.")
    parser.add_argument("--tree", default=False, action="store_true", help="Replace solver with decision tree")
    parser.add_argument("--save", default=False, action="store_true", help="Save result to file")
    parser.add_argument("--to-stdout", default=False, action="store_true", help="Print results to stdout")

    args = parser.parse_args()
    config = yaml.load(open(args.config), Loader=yaml.FullLoader)

    reward = 0
    results_file = None
    costs = None
    total_actions = None
    length_actions = None
    results_filename = None

    env = import_dyn_class(config.get("environment").get("name"))(
        **config.get("environment").get("configuration_parameters", {}),
        **config.get("validation").get("environment").get("configuration_parameters", {})
    )

    method = "agent_only"
    dataset = config.get("validation").get("dataset_name")

    num_programs = env.get_num_programs()
    num_non_primary_programs = env.get_num_non_primary_programs()
    observation_dim = env.get_obs_dimension()
    programs_library = env.programs_library

    idx_tasks = [prog['index'] for key, prog in env.programs_library.items() if prog['level'] > 0]

    # Set up the encoder needed for the environment
    encoder = import_dyn_class(config.get("environment").get("encoder").get("name"))(
        env.get_obs_dimension(),
        config.get("environment").get("encoder").get("configuration_parameters").get("encoding_dim")
    )

    indices_non_primary_programs = [p['index'] for _, p in programs_library.items() if p['level'] > 0]

    additional_arguments_from_env = env.get_additional_parameters()

    policy = import_dyn_class(config.get("policy").get("name"))(
        encoder,
        config.get("policy").get("hidden_size"),
        num_programs, num_non_primary_programs,
        config.get("policy").get("embedding_dim"),
        config.get("policy").get("encoding_dim"),
        indices_non_primary_programs,
        **additional_arguments_from_env
    )

    policy.load_state_dict(torch.load(args.model))

    idx = env.prog_to_idx[args.task]
    failures = 0

    ts = time.localtime(time.time())
    date_time = '-validation-static-{}_{}_{}-{}_{}_{}.csv'.format(ts[0], ts[1], ts[2], ts[3], ts[4], ts[5])

    if args.save:
        results_filename = config.get("validation").get("save_results_name") + date_time
        # results_file = open(
        #    os.path.join(config.get("validation").get("save_results"), results_filename), "w"
        # )

    # perform validation, not training
    env.validation = True

    reward = []
    costs = []
    total_actions = []
    length_actions = []

    iterations = min(int(config.get("validation").get("iterations")), len(env.data))

    for _ in tqdm(range(0, iterations), disable=args.to_stdout):

        idx = env.prog_to_idx[args.task]

        network_only = PolicyOnly(policy, env, env.max_depth_dict)
        netonly_reward, trace_used, cost = network_only.play(idx)

        reward.append(netonly_reward)
        if netonly_reward > 0:
            total_actions.append(trace_used)
            length_actions.append(len(trace_used))
            costs.append(sum(cost))

    # Create dataframe with the complete actions
    traces = []

    for k, trace in enumerate(total_actions):
        for p, a in trace:
            traces.append([
                k, p, a
            ])

    if len(traces) != 0:
        t = pd.DataFrame(traces, columns=["id", "program", "argument"])

    #print("Correct:", sum(reward))
    #print("Failures:", iterations-sum(reward))
    # print("Mean/std cost: ", sum(costs)/len(costs), np.std(costs))
    # print("Mean/std length actions: ", sum(length_actions) / len(length_actions), np.std(length_actions))

    # Fix if they are empty
    costs = costs if costs else [0]
    length_actions = length_actions if length_actions else [0]

    if args.to_stdout:
        print(
            f"{method},{dataset},{np.mean(reward)},{1 - np.mean(reward)},{np.mean(costs)},{np.std(costs)},{np.mean(length_actions)},{np.std(length_actions)},0.0,0.0")

        if traces:
            # Create a dataframe and save sequences to disk
            best_sequences = pd.DataFrame(traces, columns=["id", "program", "arguments"])
            best_sequences.to_csv(
                os.path.join(config.get("validation").get("save_results"),
                             f"traces-{method}-{dataset}-{results_filename}"),
                index=None)


from config.bd import app,bd,ma

class ProfesorPrograma(bd.Model):
    __tablename__ = 'tblProfesorPrograma'
    idProfesorPrograma = bd.Column(bd.Integer, primary_key=True)
    profesorId = bd.Column(bd.Integer, bd.ForeignKey("tblProfesor.codigoProfesor"))
    programaId = bd.Column(bd.Integer, bd.ForeignKey("tblPrograma.codigoPrograma"))

    def __init__(self, profesorId, programaId):
        self.profesorId = profesorId
        self.programaId = programaId

# Creación de la tabla
with app.app_context():
    bd.create_all()

# Descerialización
class GProfesorPrograma_Schema(ma.Schema):
    class Meta:
        fields = ("profesorId", "programaId")


# Uses python3
import sys

def fibonacci_sum_naive(n):
    if n <= 1:
        return n

    previous = 0
    current  = 1
    sum      = 1

    for _ in range(n - 1):
        previous, current = current, previous + current
        sum += current

    return sum % 10

def fibonacci_sum_fast(n):
    m = 10
    if n in [0, 1]:
        return n % m
    period = 60

    previous, current = 0, 1
    fib_mod_sum = 1

    fibs_range = (period if n % period == 0 else n % period) + 1
    for i in range(2, fibs_range):
        previous, current = current % m, (current + previous) % m
        fib_mod_sum += current
        fib_mod_sum = fib_mod_sum % m

    return fib_mod_sum

if __name__ == '__main__':
    input = sys.stdin.read()
    n = int(input)
    print(fibonacci_sum_fast(n))


from vectortween.NumberAnimation import NumberAnimation
from vectortween.SequentialAnimation import SequentialAnimation

from expremigen.io.constants import PhraseProperty as PP
from expremigen.io.pat2midi import Pat2Midi
from expremigen.io.phrase import Phrase
from expremigen.musicalmappings.durations import Durations as Dur
from expremigen.musicalmappings.dynamics import Dynamics as Dyn
from expremigen.musicalmappings.note2midi import Note2Midi
from expremigen.patterns.pconst import Pconst
from expremigen.patterns.pseq import Pseq
from expremigen.patterns.ptween import Ptween

outputfile = "output/rubato.mid"

def create_phrase():
    p = Pat2Midi()
    n = Note2Midi()

    # vary the lag to create the rubato feeling
    lag_inc = NumberAnimation(frm=0, to=0.3, tween=['easeOutQuad'])
    lag_dec = NumberAnimation(frm=0.3, to=0, tween=['easeInOutCubic'])
    lag = SequentialAnimation([lag_inc, lag_dec], [1, 3], 2)

    # vary the volume over time to keep it interesting
    vol_inc1 = NumberAnimation(frm=Dyn.f, to=Dyn.ff, tween=['linear'])
    vol_dec1 = NumberAnimation(frm=Dyn.ff, to=Dyn.mf, tween=['linear'])

    vol_inc2 = NumberAnimation(frm=Dyn.mf, to=Dyn.f, tween=['linear'])
    vol_dec2 = NumberAnimation(frm=Dyn.f, to=Dyn.mp, tween=['linear'])

    vol_inc3 = NumberAnimation(frm=Dyn.mp, to=Dyn.mf, tween=['linear'])
    vol_dec3 = NumberAnimation(frm=Dyn.mf, to=Dyn.pp, tween=['linear'])
    vol = SequentialAnimation([vol_inc1, vol_dec1, vol_inc2, vol_dec2, vol_inc3, vol_dec3])

    # and why not bounce a bit between legato and staccato while we're having fun?
    legato_to_staccato = NumberAnimation(frm=1, to=0.25, tween=['easeOutBounce'])
    staccato_to_legato = NumberAnimation(frm=0.1, to=1, tween=['easeOutBounce'])
    dur = SequentialAnimation([legato_to_staccato, staccato_to_legato])

    # animate the tempo
    tempo_slowdown = NumberAnimation(frm=120, to=80, tween=['easeOutQuad'])

    # play some random cadenza
    notes = n.convert2(
        "a5 b5 c6 a5 e5 d5 c5 d5 e5 c5 a4 g#4 a4 b4 c5 a4 e4 d4 c4 d4 e4 c4 a3 g#3 a3 b3 c4 d4 e4 g#4 a4".split(" "))
    notes2 = n.convert2(
        "d4 e4 f4 d4 a3 g3 f3 g3 a3 b3 c4 d4 c4 d4 e4 c4 g3 f3 e3 f3 g3 a3 b3 c4 a3 b3 c4 d4 e4 g#4 a4".split(" "))
    notes.extend(notes2)

    properties_plain = {
        PP.NOTE: Pseq(notes, 1),
        PP.VOL: Pconst(100),
        PP.PLAYEDDUR: Pconst(0.95),
        PP.DUR: Pseq([Pconst(Dur.sixteenth_triplet, len(notes2) - 1), Pconst(Dur.half, 1)], 2),
        PP.LAG: Pconst(0),
        PP.TEMPO: Pconst(120)
    }
    properties_rubato = {
        PP.NOTE: Pseq(notes, 1),
        PP.VOL: Ptween(vol, 0, 0, len(notes), len(notes), None),
        PP.PLAYEDDUR: Ptween(dur, 0, 0, len(notes), len(notes), None),
        PP.DUR: Pseq([Pconst(Dur.sixteenth_triplet, len(notes2) - 1), Pconst(Dur.half, 1)], 2),
        PP.LAG: Ptween(lag, 0, 0, len(notes), len(notes), None),
        PP.TEMPO: Ptween(tempo_slowdown, 0, 0, len(notes), len(notes), None)
    }

    ph = Phrase(properties_plain)
    ph2 = Phrase(properties_rubato)
    p.add_phrases([ph, ph2], 0, 0, 0)

    p.write(outputfile)

if __name__ == "__main__":
    create_phrase()


import gym
import numpy as np
from gym.envs.registration import register

def make(
    domain_name,
    task_name,
    noise,
    mult_factor,
    idx,
    seed=1,
    visualize_reward=True,
    from_pixels=False,
    height=84,
    width=84,
    camera_id=0,
    frame_skip=1,
    episode_length=1000,
    environment_kwargs=None
):
    env_id = 'dmc_%s_%s_factor%s-v1' % (domain_name, task_name, idx)

    if from_pixels:
        assert not visualize_reward, 'cannot use visualize reward when learning from pixels'

    # shorten episode length
    max_episode_steps = (episode_length + frame_skip - 1) // frame_skip

    if not env_id in gym.envs.registry.env_specs:
        register(
            id=env_id,
            entry_point='dmc2gym.wrappers:DMCWrapper',
            kwargs={
                'domain_name': domain_name,
                'task_name': task_name,
                'noise': noise,
                'mult_factor': mult_factor,
                'idx': idx,
                'task_kwargs': {
                    'random': seed
                },
                'environment_kwargs': environment_kwargs,
                'visualize_reward': visualize_reward,
                'from_pixels': from_pixels,
                'height': height,
                'width': width,
                'camera_id': camera_id,
                'frame_skip': frame_skip,
            },
            max_episode_steps=max_episode_steps
        )
    return gym.make(env_id)


## Assertion

# Here is a function that converts a temperature from degrees Kelvin to degrees Fahrenheit.
# Since zero degrees Kelvin is as cold as it gets, the function bails out if it sees a negative temperature:

def KelvinToFahrenheit(Temperature):
    assert (Temperature >= 0), "Colder than absolute zero"
    return((Temperature - 273) * 1.8) + 32

KelvinToFahrenheit(273)
KelvinToFahrenheit(505.78)
KelvinToFahrenheit(-5)

Basic Tutorial/Chapter 15 - Exceptions/script1.py


'''
Run-length encoding of a list.
    Use the result of problem P09 to implement the so-called run-length
	encoding data compression method. Consecutive duplicates of elements
	are encoded as lists (N E) where N is the number of duplicates of the
	element E.
'''

#taking input of list elements at a single time seperating by space and splitting each by split() method
demo_list = input("Enter elememts sep by space: ").split(' ')

#creating new lists
runLength_converted_list = list()
encoded_list = list()

previous_item = demo_list[0]         #assigning first element of demo_list to previous_item
temp_list = list()				     #creating new list as temp_list

for current_item in demo_list:               #iterating through all elements of demo_list
	if current_item == previous_item:        #checking if previously added element is same as current element of list, for checking repetative elements
		temp_list.append(current_item)		 #appending current element to temp_list. for creation of sublist
	else: 									 #if not repetative element
		runLength_converted_list.append(temp_list[:])		 #appending previously created sublist(temp_list) copy to new_list
		temp_list.clear()					 #clearing temp_list to create new sublist
		temp_list.append(current_item)		 #appending current_item to temp_list
		previous_item = current_item         #assigning current_item to previous_item
else:
	runLength_converted_list.append(temp_list[:])            #appending temp_list copy to new_list

for item in runLength_converted_list:            		#iterating through all elements of demo_list
	temp_list.clear()			 		#removing all elements from temp_list
	temp_list.append(len(item))  		#new_list contains sublist of repetative elements, so finding size of sublist and appending to temp_list.
	temp_list.append(item[0])    		#also appending element with its count present in sublist.
	encoded_list.append(temp_list[:])	#appending temp_list to encoded_list

#printing demo_list and encoded_list
print(f"old list: {demo_list}")
print(f"result list: {encoded_list}")


# Filename: compress.py
# Description: compress an ASCII file

def compress(line):
    while len(line) > 0:
        # while there's stuff to compress in the line
        if len(line) > 1:
            # only check for repetition of there's more than one character in the line
            if line[0] == line[1]:
                char = line[0]
                # assign the character first
                n = 0
                while len(line) > 1 and line[0] == char:
                    # take away first occurrence
                    n = n + 1
                    line = line[1:]
                print(char + str(n))
            else:
                print(line[0])
                line = line[1:]
        else:
            print(line)
            break

try:
    infile = open("flintstones.txt", 'r')

    lines = infile.readlines()
    for line in lines[:-1]:
        compress(line)
        print("---")
    compress(lines[-1])
    infile.close()
except IOError:
    print("Error reading from flintstones.txt.")


import json
import boto3

def lambda_handler(event, context):

    def handleGetActivities(id):
        dynamodb = boto3.resource('dynamodb')
        activitiesTable = dynamodb.Table('fbla_activities_table')
        response = activitiesTable.get_item(
            Key={
                'id': id
            }
        )
        return response

    bodyDict = json.loads(event['body'])
    id = bodyDict['id']
    action = bodyDict['action']

    if action == 'getActivities':
        response = handleGetActivities(id)
        statusCode = 200 if response['ResponseMetadata']['HTTPStatusCode'] == 200 and 'Item' in response else 400
        message = response['Item']['activities'] if statusCode == 200 else f'Failed to get activities for id {id}'
        print(message)
        return {
            "statusCode": statusCode,
            "body": json.dumps(message)
        }

    return {
        "statusCode": 400,
        "body": json.dumps({
            "message": f"Invalid activities action requested for id {id}",
        }),
    }


import string

def split(word):
    return [char for char in word]

def solve(data):
    R = int(data[0])
    S = data[1]
    result = ''
    for x in split(S):
        result += (x * R)
    print(result)

def main():
    T = int(input())
    for n in range(0, T):
        data = input().split()
        solve(data)

if __name__ == "__main__":
    main()


import subprocess
try:
    from termcolor import colored
except ModuleNotFoundError:
    def colored(string, *args, **kwargs):
        return string
from sys import argv

class TestFile:
    def __init__(self, filename, expected_code = 0, expected_output = "", expected_in_error = [], folder = "test_files/") -> None:
        self.folder = folder
        self.filename = filename
        self.timed_out = False
        self.expected_code = expected_code
        self.expected_in_error = ["ERROR"] + expected_in_error if expected_code != 0 else expected_in_error
        self.expected_output = expected_output
        self.actual = ""
        self.error_channel = ""
        self.exit_code = 0
        self.has_ran = False
        self.options = []

    def run(self):
        self.has_ran = True
        try:
            res = subprocess.run(["./glados", self.folder + self.filename ] + self.options, capture_output=True, timeout=10, stdin=subprocess.DEVNULL)
        except subprocess.TimeoutExpired as e:
            self.timed_out = True
            return
        self.actual = res.stdout.decode("utf-8")
        if len(self.actual) != 0 and (self.actual[-1] == '\n'):
            self.actual = self.actual[:-1]
        self.error_channel = res.stderr.decode("utf-8")
        if len(self.error_channel) != 0 and self.error_channel[-1] == '\n':
            self.error_channel = self.error_channel[:-1]
        self.exit_code = res.returncode

    def checkResult(self, skipGood: bool) -> bool:
        if (not self.has_ran):
            print(f"File {self.filename} has not been ran yet; skipping\n")
            return False
        if self.timed_out:
            print(colored(f"File {self.filename} has timed out\n", "light_red"))
            return False
        missing_in_error = [item for item in self.expected_in_error if item.lower() not in self.error_channel.lower()]
        if self.actual != self.expected_output or self.exit_code != self.expected_code or len(missing_in_error) != 0:
            s = f"File {self.filename}: KO"
            if self.exit_code != self.expected_code:
                s += f"\nExpected exit code {self.expected_code} but got {self.exit_code}"
            if self.actual != self.expected_output:
                s += f"\nExpected output:\n'{self.expected_output}'\nBut got:\n'{self.actual}'"
                if len(self.error_channel) != 0:
                    s += f"\nError channel was not empty: \n'{self.error_channel}'"
            if len(missing_in_error) != 0:
                s += f"\nKeywords {', '.join(missing_in_error)} in error message:\nBut got\n'{self.error_channel}'"
            print(colored(s + "\n", "light_red"))
            return False
        else:
            if not skipGood:
                print(colored(f"File {self.filename}: OK", "light_green"))
            return True

class TestLisp(TestFile):
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs, folder="test_files/lisp/")
        self.options = ["--lisp"]

lispFileList = [
    TestLisp("okay/sujet/lambda1.scm", expected_output="#<procedure>"),
    TestLisp("okay/sujet/lambda2.scm", expected_output="3"),
    TestLisp("okay/sujet/lambda3.scm", expected_output="7"),
    TestLisp("okay/sujet/function1.scm", expected_output="7"),
    TestLisp("okay/sujet/if1.scm", expected_output="1"),
    TestLisp("okay/sujet/if2.scm", expected_output="2"),
    TestLisp("okay/sujet/if3.scm", expected_output="21"),
    TestLisp("okay/sujet/builtins1.scm", expected_output="11"),
    TestLisp("okay/sujet/builtins2.scm", expected_output="#t"),
    TestLisp("okay/sujet/builtins3.scm", expected_output="#f"),
    TestLisp("okay/sujet/builtins2.scm", expected_output="#t"),
    TestLisp("okay/sujet/factorial.scm", expected_output="3628800"),

    TestLisp("okay/factorial.txt",          expected_output="120"),
    TestLisp("okay/negative.txt",           expected_output="-1"),
    TestLisp("okay/max_int.txt",            expected_output="9223372036854775807"),
    TestLisp("okay/min_int.txt",            expected_output="-9223372036854775808"),
    TestLisp("okay/foo.txt",                expected_output="42"),
    TestLisp("okay/lazy_vars.txt",          expected_output="1"),
    TestLisp("okay/var_attribution.txt",    expected_output=""),
    TestLisp("okay/sort_list.txt",          expected_output="[1,2,3,4]\n[1,2,3,4]\n[]\n[1,1,1,1]\n[2]"),

    TestLisp("okay/basic_operations/add.txt", expected_output="5"),
    TestLisp("okay/basic_operations/sub.txt", expected_output="-1"),
    TestLisp("okay/basic_operations/mul.txt", expected_output="6"),
    TestLisp("okay/basic_operations/div.txt", expected_output="0"),
    TestLisp("okay/basic_operations/mod.txt", expected_output="2"),
    TestLisp("okay/basic_operations/pow.txt", expected_output="8"),

    TestLisp("error/div-zero.txt", expected_code=84,        expected_in_error=["division","zero"]),
    TestLisp("error/mod-zero.txt", expected_code=84,        expected_in_error=["mod","zero"]),
    TestLisp("error/unknown_var.txt", expected_code=84,     expected_in_error=["foo"]),
    TestLisp("error/missing.txt", expected_code=84,         expected_in_error=[]),
    TestLisp("error/unmatched.txt", expected_code=84,       expected_in_error=["parenthesis"]),
]

def main():
    skipGood = "--skip-good" in argv
    success_count = 0
    for file in lispFileList:
        file.run()
        if (file.checkResult(skipGood)):
            success_count += 1
    if (success_count == len(lispFileList)):
        print(colored(f"{success_count}/{success_count} test passed", "light_green"))
        return 0
    else:
        print(colored(f"{success_count}/{len(lispFileList)} test passed", "light_red"))
        return 84

if __name__ == "__main__":
    exit(main())


elf = genMonster("Elf", (62, 6003), "an elf")
elf.setHealth(100, healthmax=100)
elf.bloodType("blood")
elf.setDefense(armor=7, fire=1, earth=1, energy=1, ice=1, holy=0.8, death=1.1, physical=1, drown=1)
elf.setExperience(42)
elf.setSpeed(220)
elf.setBehavior(summonable=320, hostile=1, illusionable=1, convinceable=320, pushable=1, pushItems=0, pushCreatures=0, targetDistance=1, runOnHealth=0)
elf.walkAround(energy=1, fire=1, poison=1)
elf.setImmunity(paralyze=0, invisible=0, lifedrain=0, drunk=0)
elf.voices("Death to the Defilers!", "You are not welcome here.", "Flee as long as you can.", "Bahaha aka!", "Ulathil beia Thratha!")
elf.regMelee(15)
elf.regDistance(25, ANIMATION_ARROW, chance(21))
elf.loot( ("arrow", 15.5, 3), ("plum", 33.5, 2), (2148, 100, 30), ("studded armor", 10.0), ("studded helmet", 16.0), ("plate shield", 8.75), ("leather boots", 11.5), ("longsword", 12.5), ("elvish talisman", 2.5), (5921, 1.0) )


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

class Solution(object):
    def getIntersectionNode(self, headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """
        if headA is None or headB is None:
            return None
        countA = 0
        tmpA = headA
        while tmpA is not None:
            tmpA = tmpA.next
            countA += 1
        countB = 0
        tmpB = headB
        while tmpB is not None:
            tmpB = tmpB.next
            countB += 1
        tmpA = headA
        tmpB = headB
        if countA > countB:
            for i in range(countA - countB):
                tmpA = tmpA.next
        else:
            for i in range(countB - countA):
                tmpB = tmpB.next
        while tmpA != tmpB and tmpA and tmpB:
            tmpA = tmpA.next
            tmpB = tmpB.next

        if tmpA == tmpB:
            return tmpA
        else:
            return None

if __name__ == '__main__':
    solution = Solution()
    head1 = ListNode(1)
    head2 = head1
    result = solution.getIntersectionNode(head1, head2)
    print(result)


from jupyter_ui_poll import ui_events
import ipywidgets as widgets
from jupyterMagicCommands.outputters.outputter import AbstractOutputterReadCB
from jupyterMagicCommands.outputters.outputter import AbstractOutputter, EmptyOutputterReadCB

from IPython.display import display

class InteractiveOutputter(AbstractOutputter):

    def __init__(self):
        self.ui = ui_events()
        self.poll = self.ui.__enter__()
        self.out = widgets.Output()
        self.text = widgets.Text(placeholder='input')
        self.sendEnterWidget = widgets.ToggleButtons(
            options=['Send Enter', "Don't send enter"],
            description='Send enter?:',
            disabled=False,
        )
        self.read_cb: AbstractOutputterReadCB = EmptyOutputterReadCB()
        display(widgets.VBox([self.out, self.text, self.sendEnterWidget]))

    def register_read_callback(self, cb) -> None:
        self.read_cb = cb
        def wrapped_cb(widget):
            if self.sendEnterWidget.value == 'Send Enter':
                cb(widget.value + '\n')
            else:
               cb(widget.value)
        self.text.on_submit(wrapped_cb)

    def write(self, s):
        self.out.append_stdout(s)

    def handle_read(self):
        self.poll(10000)


#flatten

liste = [[1,'a',['cat'],2],[[[3]],'dog'],4,5]

new_liste = []

def flatten(x):
    for i in x:
        if isinstance(i, list):
            flatten(i)
        else:
            new_liste.append(i)

flatten(liste)
print(new_liste)

#****************************************************

#reverse

def reverse_list(x):
    x.reverse()

    for i in x:
        if type(i) == list:
            reverse_list(i)
    return x

liste = [[1, 2], [3, 4], [5, 6, 7]]

print(reverse_list(liste))


'''
@package tfignite.parser
Customized parser for tfignite.
'''
import argparse

class ArgumentParser(argparse.ArgumentParser):
    def __init__(self, Model, Dataset, *args, **kwargs):
        self._Model = Model
        self._Dataset = Dataset
        argparse.ArgumentParser.__init__(self, *args, **kwargs)

    def parse_args(self, *args, **kwargs):
        model_parser = self.add_argument_group(self._Model.__name__)
        self._Model.add_parser(model_parser)

        dataset_parser = self.add_argument_group(self._Dataset.__name__)
        self._Dataset.add_parser(dataset_parser)

        return argparse.ArgumentParser.parse_args(self, *args, **kwargs)


"""
A CUSTOM HASHMAP IMPLEMENTATION IN PYTHON

This custom HashMap class handles collision by utilizing the open addressing strategy with a probe sequencing of 1

Note: Python has a built-in implementation of hash maps in forms of dictionaries with a more complex functionality
han the custom hash map below!
"""
import string

class HashMap:
    def __init__(self, array_size):
        self.array_size = array_size
        self.array = [None for _ in range(self.array_size)]

    def hash(self, key, collision_count):
        key_bytes = key.encode()
        hash_code = sum(key_bytes)

        return hash_code + collision_count

    def compressor(self, hash_code):
        return hash_code % self.array_size

    def get_index_and_value(self, key, collision_count=0):
        index = self.compressor(self.hash(key, collision_count))
        value = self.array[index]

        return index, value

    def retrieve_value_and_index(self, key, collision_count):
        current_index, current_value = self.get_index_and_value(key, collision_count)

        if collision_count > self.array_size or current_value is None:
            return None
        elif current_value[0] == key:
            return current_value[1], current_index
        else:
            return self.retrieve_value_and_index(key, collision_count + 1)

    def insert_value(self, key, collision_count):
        current_index, current_value = self.get_index_and_value(key, collision_count)

        if collision_count > self.array_size:
            return None
        elif current_value is None or current_value[0] == key:
            return current_index
        else:
            return self.insert_value(key, collision_count + 1)

    def set_value(self, key, value):
        current_index, current_value = self.get_index_and_value(key)

        if current_value is None or current_value[0] == key:
            self.array[current_index] = [key, value]
            return
        else:
            collision_count = 1
            new_index = self.insert_value(key, collision_count)
            if new_index is not None:
                self.array[new_index] = [key, value]
                return
            else:
                print("Could not insert - HashMap is full!")
            return

    def get_value(self, key):
        _, current_value = self.get_index_and_value(key)

        if current_value is None:
            return f"No value associated with: '{key}', was found in the HashMap!"
        elif current_value[0] == key:
            return current_value[1]
        else:
            collision_count = 1
            value = self.retrieve_value_and_index(key, collision_count)
            if value is None:
                return f"No value associated with: '{key}', was found in the HashMap!"
            else:
                return value[0]

    def delete_value(self, key):
        current_index, current_value = self.get_index_and_value(key)

        if not current_value:
            print(f"No key with the name: '{key}', was found in the HashMap!")
            return
        elif current_value[0] == key:
            self.array[current_index] = None
            return
        else:
            collision_count = 1
            current_value = self.retrieve_value_and_index(key, collision_count)
            if current_value:
                value, index = current_value
                self.array[index] = None
                return
            else:
                print(f"No key with the name: '{key}', was found in the HashMap!")
            return

if __name__ == "__main__":
    """The alphabet_hash_map maps each ascii lowercase character to its corresponding location in the alphabet
    following: character(key): location in alphabet(value)"""
    alphabet_count = [(letter, index) for index, letter in enumerate(string.ascii_lowercase, 1)]

    alphabet_hash_map = HashMap(len(alphabet_count))
    for element in alphabet_count:
        alphabet_hash_map.set_value(element[0], element[1])

    # UNCOMMENT TO SEE HASH MAP METHODS IN ACTION:

    # print(alphabet_hash_map.get_value("a"))
    # print(alphabet_hash_map.get_value("/"))
    # alphabet_hash_map.delete_value("a")
    # print(alphabet_hash_map.get_value("a"))

    """The languages_hash_map maps each programming language to its developer following:
    language(key): developer(value)"""

    languages = ["Python", "Java", "C", "C++", "C#", "PHP", "Ruby", "Swift"]
    developers = ["Guido van Rossum", "James Gosling", "Dennis Ritchie", "Bjarne Stroustrup", "Anders Hejlsberg",
                  "Rasmus Lerdorf", "Yukihiro Matsumoto", "Chris Lattner"]
    langs_and_devs = [(lang, dev) for lang, dev in zip(languages, developers)]

    languages_hash_map = HashMap(len(langs_and_devs) - 1)
    for element in langs_and_devs:
        languages_hash_map.set_value(element[0], element[1])

    # UNCOMMENT TO SEE HASH MAP METHODS IN ACTION:
    # print(languages_hash_map.get_value("Python"))
    # print(languages_hash_map.get_value("Ruby"))


class Solution(object):
    def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        for index, num in enumerate(nums):
            if nums[index] >= target: return index
        return len(nums)

# Better Solution
class Solution(object):
    def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        left, right = 0, len(nums)-1
        while right>=left:
            mid = (left+right)// 2
            if nums[mid] == target: return mid
            elif nums[mid] < target: left = mid+1
            else: right = mid-1
        return left

LeetCode/00035. Search Insert Position.py


# -*- coding: utf-8 -*-
"""
这个类负责所有和音乐有关的操作
"""
import wx
import pygame
import os

class MusicControl:
    MusicPath = ""
    musicList = []
    index = 0

    def __init__(self):
        pygame.mixer.init()
        # Music单独保存自己的路径，与工作相独立,存在默认播放路径
        self.MusicPath = "d:\\Music"
        self.musicList = \
            [self.MusicPath + '\\' + music for music in os.listdir(self.MusicPath) if music.endswith('.mp3')]

    def ChangeMusicFilePath(self):
        dlg = wx.DirDialog(None, u"更改音乐文件夹路径", style=wx.FD_CHANGE_DIR)
        if dlg.ShowModal() == wx.ID_OK:
            self.MusicPath = dlg.GetPath()
            self.musicList = \
                [self.MusicPath + '\\' + music for music in os.listdir(self.MusicPath) if music.endswith('.mp3')]
            self.index = 0
        dlg.Destroy()

    def PreviousMusic(self):
        self.index -= 1
        if self.index == -1:
            self.index = len(self.musicList)-1
        pygame.mixer.music.load(self.musicList[self.index])
        pygame.mixer.music.play()
        return self.musicList[self.index]

    def NextMusic(self):
        self.index += 1
        if self.index == len(self.musicList):
            self.index = 0
        pygame.mixer.music.load(self.musicList[self.index])
        pygame.mixer.music.play()
        return self.musicList[self.index]

    def StopMusic(self):
        pygame.mixer.music.stop()

    def PlayMusic(self):
        if not pygame.mixer.music.get_busy():
            pygame.mixer.music.load(self.musicList[self.index])
            pygame.mixer.music.play(loops=0)
            return self.musicList[self.index]
        else:
            pygame.mixer.music.unpause()
            return self.musicList[self.index]
        pass

    def PauseMusic(self):
            pygame.mixer.music.pause()
    pass

    def ChangeVolume(self,volume):
        pygame.mixer.music.set_volume(volume)

成果物/6. Translation Assistant/Translation assistant/MusicPanel.py


from math import pi, cos, sin, sqrt
from typing import Type

import bpy
from bpy.props import *
from bpy.types import NodeSocket
import mathutils

import arm.node_utils
import arm.utils

if arm.is_reload(__name__):
    arm.node_utils = arm.reload_module(arm.node_utils)
    arm.utils = arm.reload_module(arm.utils)
else:
    arm.enable_reload(__name__)

# See Blender sources: /source/blender/editors/space_node/drawnode.cc
# Permalink for 3.2.2: https://github.com/blender/blender/blob/bcfdb14560e77891d674c2701a5071a7c07baba3/source/blender/editors/space_node/drawnode.cc#L1152-L1167
socket_colors = {
    'ArmNodeSocketAction': (0.8, 0.3, 0.3, 1),
    'ArmNodeSocketAnimAction': (0.8, 0.8, 0.8, 1),
    'ArmRotationSocket': (0.68, 0.22, 0.62, 1),
    'ArmNodeSocketArray': (0.8, 0.4, 0.0, 1),
    'ArmBoolSocket': (0.80, 0.65, 0.84, 1.0),
    'ArmColorSocket': (0.78, 0.78, 0.16, 1.0),
    'ArmDynamicSocket': (0.39, 0.78, 0.39, 1.0),
    'ArmFloatSocket': (0.63, 0.63, 0.63, 1.0),
    'ArmIntSocket': (0.059, 0.522, 0.149, 1),
    'ArmNodeSocketObject': (0.15, 0.55, 0.75, 1),
    'ArmStringSocket': (0.44, 0.70, 1.00, 1.0),
    'ArmVectorSocket': (0.39, 0.39, 0.78, 1.0),
    'ArmAnySocket': (0.9, 0.9, 0.9, 1)
}

def _on_update_socket(self, context):
    self.node.on_socket_val_update(context, self)

class ArmCustomSocket(NodeSocket):
    """
    A custom socket that can be used to define more socket types for
    logic node packs. Do not use this type directly (it is not
    registered)!
    """

    bl_idname = 'ArmCustomSocket'
    bl_label = 'Custom Socket'
    # note: trying to use the `type` property will fail. All custom nodes will have "VALUE" as a type, because it is the default.
    arm_socket_type = 'NONE'
    # please also declare a property named "default_value_raw" of arm_socket_type isn't "NONE"

    def get_default_value(self):
        """Override this for values of unconnected input sockets."""
        return None

    def on_node_update(self):
        """Called when the update() method of the corresponding node is called."""
        pass

    def copy_defaults(self, socket):
        """Called when this socket default values are to be copied to the given socket"""
        pass

class ArmActionSocket(ArmCustomSocket):
    bl_idname = 'ArmNodeSocketAction'
    bl_label = 'Action Socket'
    arm_socket_type = 'NONE'

    def draw(self, context, layout, node, text):
        layout.label(text=self.name)

    def draw_color(self, context, node):
        return socket_colors[self.bl_idname]

class ArmAnimActionSocket(ArmCustomSocket):
    bl_idname = 'ArmNodeSocketAnimAction'
    bl_label = 'Action Socket'
    arm_socket_type = 'STRING'

    default_value_get: PointerProperty(name='Action', type=bpy.types.Action)  # legacy version of the line after this one
    default_value_raw: PointerProperty(name='Action', type=bpy.types.Action, update=_on_update_socket)

    def __init__(self):
        super().__init__()
        if self.default_value_get is not None:
            self.default_value_raw = self.default_value_get
            self.default_value_get = None

    def get_default_value(self):
        if self.default_value_raw is None:
            return ''
        if self.default_value_raw.name not in bpy.data.actions:
            return self.default_value_raw.name
        name = arm.utils.asset_name(bpy.data.actions[self.default_value_raw.name])
        return arm.utils.safestr(name)

    def draw(self, context, layout, node, text):
        if self.is_output:
            layout.label(text=self.name)
        elif self.is_linked:
            layout.label(text=self.name)
        else:
            layout.prop_search(self, 'default_value_raw', bpy.data, 'actions', icon='NONE', text='')

    def draw_color(self, context, node):
        return socket_colors[self.bl_idname]

    def copy_defaults(self, socket):
        if socket.bl_idname == self.bl_idname:
            socket.default_value_raw = self.default_value_raw

class ArmRotationSocket(ArmCustomSocket):
    bl_idname = 'ArmRotationSocket'
    bl_label = 'Rotation Socket'
    arm_socket_type = 'ROTATION'  # the internal representation is a quaternion, AKA a '4D vector' (using mathutils.Vector((x,y,z,w)))

    def get_default_value(self):
        if self.default_value_raw is None:
            return mathutils.Vector((0.0,0.0,0.0,1.0))
        else:
            return self.default_value_raw

    def on_unit_update(self, context):
        if self.default_value_unit == 'Rad':
            fac = pi/180  # deg->rad conversion
        else:
            fac = 180/pi  # rad->deg conversion
        if self.default_value_mode == 'AxisAngle':
            self.default_value_s3 *= fac
        elif self.default_value_mode == 'EulerAngles':
            self.default_value_s0 *= fac
            self.default_value_s1 *= fac
            self.default_value_s2 *= fac
        self.do_update_raw(context)

    def on_mode_update(self, context):
        if self.default_value_mode == 'Quaternion':
            summ = abs(self.default_value_s0)
            summ+= abs(self.default_value_s1)
            summ+= abs(self.default_value_s2)
            summ+= abs(self.default_value_s3)
            if summ<0.01:
                self.default_value_s3 = 1.0
        elif self.default_value_mode == 'AxisAngle':
            summ = abs(self.default_value_s0)
            summ+= abs(self.default_value_s1)
            summ+= abs(self.default_value_s2)
            if summ<1E-5:
                self.default_value_s3 = 0.0
        self.do_update_raw(context)

    @staticmethod
    def convert_to_quaternion(part1,part2,param1,param2,param3):
        """converts a representation of rotation into a quaternion.
        ``part1`` is a vector, ``part2`` is a scalar or None,
        ``param1`` is in ('Quaternion', 'EulerAngles', 'AxisAngle'),
        ``param2`` is in ('Rad','Deg') for both EulerAngles and AxisAngle,
        ``param3`` is a len-3 string like "XYZ", for EulerAngles """
        if param1=='Quaternion':
            qx, qy, qz = part1[0], part1[1], part1[2]
            qw = part2
            # need to normalize the quaternion for a rotation (having it be 0 is not an option)
            ql = sqrt(qx**2+qy**2+qz**2+qw**2)
            if abs(ql)<1E-5:
                qx, qy, qz, qw = 0.0,0.0,0.0,1.0
            else:
                qx /= ql
                qy /= ql
                qz /= ql
                qw /= ql
            return mathutils.Vector((qx,qy,qz,qw))

        elif param1 == 'AxisAngle':
            if param2 == 'Deg':
                angle = part2 * pi/180
            else:
                angle = part2
            cang, sang = cos(angle/2), sin(angle/2)
            x,y,z = part1[0], part1[1], part1[2]
            veclen = sqrt(x**2+y**2+z**2)
            if veclen<1E-5:
                return mathutils.Vector((0.0,0.0,0.0,1.0))
            else:
                return mathutils.Vector((
                    x/veclen * sang,
                    y/veclen * sang,
                    z/veclen * sang,
                    cang
                ))
        else:  # param1 == 'EulerAngles'
            x,y,z = part1[0], part1[1], part1[2]
            if param2 == 'Deg':
                x *= pi/180
                y *= pi/180
                z *= pi/180
            cx, sx = cos(x/2), sin(x/2)
            cy, sy = cos(y/2), sin(y/2)
            cz, sz = cos(z/2), sin(z/2)

            qw, qx, qy, qz  = 1.0,0.0,0.0,0.0
            for direction in param3[::-1]:
                qwi, qxi,qyi,qzi = {'X': (cx,sx,0,0), 'Y': (cy,0,sy,0), 'Z': (cz,0,0,sz)}[direction]

                qw = qw*qwi -qx*qxi -qy*qyi -qz*qzi
                qx = qx*qwi +qw*qxi +qy*qzi -qz*qyi
                qy = qy*qwi +qw*qyi +qz*qxi -qx*qzi
                qz = qz*qwi +qw*qzi +qx*qyi -qy*qxi
            return mathutils.Vector((qx,qy,qz,qw))

    def do_update_raw(self, context):
        part1 = mathutils.Vector((
            self.default_value_s0,
            self.default_value_s1,
            self.default_value_s2, 1
        ))
        part2 = self.default_value_s3

        self.default_value_raw = self.convert_to_quaternion(
            part1,
            self.default_value_s3,
            self.default_value_mode,
            self.default_value_unit,
            self.default_value_order
        )

    def draw(self, context, layout, node, text):
        if (self.is_output or self.is_linked):
            layout.label(text=self.name)
        else:
            coll1 = layout.column(align=True)
            coll1.label(text=self.name)
            bx=coll1.box()
            coll = bx.column(align=True)
            coll.prop(self, 'default_value_mode')
            if self.default_value_mode in ('EulerAngles', 'AxisAngle'):
                coll.prop(self, 'default_value_unit')

            if self.default_value_mode == 'EulerAngles':
                coll.prop(self, 'default_value_order')
                coll.prop(self, 'default_value_s0', text='X')
                coll.prop(self, 'default_value_s1', text='Y')
                coll.prop(self, 'default_value_s2', text='Z')
            elif self.default_value_mode == 'Quaternion':
                coll.prop(self, 'default_value_s0', text='X')
                coll.prop(self, 'default_value_s1', text='Y')
                coll.prop(self, 'default_value_s2', text='Z')
                coll.prop(self, 'default_value_s3', text='W')
            elif self.default_value_mode == 'AxisAngle':
                coll.prop(self, 'default_value_s0', text='X')
                coll.prop(self, 'default_value_s1', text='Y')
                coll.prop(self, 'default_value_s2', text='Z')
                coll.separator()
                coll.prop(self, 'default_value_s3', text='Angle')

    def draw_color(self, context, node):
        return socket_colors[self.bl_idname]

    default_value_mode: EnumProperty(
        items=[('EulerAngles', 'Euler Angles', 'Euler Angles'),
               ('AxisAngle', 'Axis/Angle', 'Axis/Angle'),
               ('Quaternion', 'Quaternion', 'Quaternion')],
        name='', default='EulerAngles',
        update=on_mode_update)

    default_value_unit: EnumProperty(
        items=[('Deg', 'Degrees', 'Degrees'),
               ('Rad', 'Radians', 'Radians')],
        name='', default='Rad',
        update=on_unit_update)
    default_value_order: EnumProperty(
        items=[('XYZ','XYZ','XYZ'),
               ('XZY','XZY (legacy Armory euler order)','XZY (legacy Armory euler order)'),
               ('YXZ','YXZ','YXZ'),
               ('YZX','YZX','YZX'),
               ('ZXY','ZXY','ZXY'),
               ('ZYX','ZYX','ZYX')],
        name='', default='XYZ'
    )

    default_value_s0: FloatProperty(update=do_update_raw)
    default_value_s1: FloatProperty(update=do_update_raw)
    default_value_s2: FloatProperty(update=do_update_raw)
    default_value_s3: FloatProperty(update=do_update_raw)

    default_value_raw: FloatVectorProperty(
        name='Value',
        description='Raw quaternion obtained for the default value of a ArmRotationSocket socket',
        size=4, default=(0,0,0,1),
        update = _on_update_socket
    )

    def copy_defaults(self, socket):
        if socket.bl_idname == self.bl_idname:
            socket.default_value_mode = self.default_value_mode
            socket.default_value_unit = self.default_value_unit
            socket.default_value_order = self.default_value_order
            socket.default_value_s0 = self.default_value_s0
            socket.default_value_s1 = self.default_value_s1
            socket.default_value_s2 = self.default_value_s2
            socket.default_value_s3 = self.default_value_s3
            socket.default_value_raw = self.default_value_raw

class ArmArraySocket(ArmCustomSocket):
    bl_idname = 'ArmNodeSocketArray'
    bl_label = 'Array Socket'
    arm_socket_type = 'NONE'

    def draw(self, context, layout, node, text):
        layout.label(text=self.name)

    def draw_color(self, context, node):
        return socket_colors[self.bl_idname]

class ArmBoolSocket(ArmCustomSocket):
    bl_idname = 'ArmBoolSocket'
    bl_label = 'Boolean Socket'
    arm_socket_type = 'BOOLEAN'

    default_value_raw: BoolProperty(
        name='Value',
        description='Input value used for unconnected socket',
        update=_on_update_socket
    )

    def draw(self, context, layout, node, text):
        draw_socket_layout(self, layout)

    def draw_color(self, context, node):
        return socket_colors[self.bl_idname]

    def get_default_value(self):
        return self.default_value_raw

    def copy_defaults(self, socket):
        if socket.bl_idname == self.bl_idname:
            socket.default_value_raw = self.default_value_raw

class ArmColorSocket(ArmCustomSocket):
    bl_idname = 'ArmColorSocket'
    bl_label = 'Color Socket'
    arm_socket_type = 'RGBA'

    default_value_raw: FloatVectorProperty(
        name='Value',
        size=4,
        subtype='COLOR',
        min=0.0,
        max=1.0,
        default=[0.0, 0.0, 0.0, 1.0],
        description='Input value used for unconnected socket',
        update=_on_update_socket
    )

    def draw(self, context, layout, node, text):
        draw_socket_layout_split(self, layout)

    def draw_color(self, context, node):
        return socket_colors[self.bl_idname]

    def get_default_value(self):
        return self.default_value_raw

    def copy_defaults(self, socket):
        if socket.bl_idname == self.bl_idname:
            socket.default_value_raw = self.default_value_raw

class ArmDynamicSocket(ArmCustomSocket):
    bl_idname = 'ArmDynamicSocket'
    bl_label = 'Dynamic Socket'
    arm_socket_type = 'NONE'

    def draw(self, context, layout, node, text):
        layout.label(text=self.name)

    def draw_color(self, context, node):
        return socket_colors[self.bl_idname]

class ArmAnySocket(ArmCustomSocket):
    bl_idname = 'ArmAnySocket'
    bl_label = 'Any Socket'
    arm_socket_type = 'NONE'

    # Callback function when socket label is changed
    def on_disp_label_update(self, context):
        node = self.node
        if node.bl_idname == 'LNGroupInputsNode' or node.bl_idname == 'LNGroupOutputsNode':
            if not node.invalid_link:
                node.socket_name_update(self)
                self.on_node_update()
                self.name = self.display_label

    display_label: StringProperty(
        name='display_label',
        description='Property to store socket display name',
        update=on_disp_label_update)

    display_color: FloatVectorProperty(
        name='Color',
        size=4,
        subtype='COLOR',
        min=0.0,
        max=1.0,
        default=socket_colors['ArmAnySocket']
    )

    def draw(self, context, layout, node, text):
        layout.label(text=self.display_label)

    def draw_color(self, context, node):
        return self.display_color

    def on_node_update(self):
        # Cache name and color of connected socket
        if self.is_output:
            c_node, c_socket = arm.node_utils.output_get_connected_node(self)
        else:
            c_node, c_socket = arm.node_utils.input_get_connected_node(self)

        if c_node is None:
            self.display_color = socket_colors[self.__class__.bl_idname]
        else:
            if self.display_label == '':
                self.display_label = c_socket.name
            self.display_color = c_socket.draw_color(bpy.context, c_node)

class ArmFloatSocket(ArmCustomSocket):
    bl_idname = 'ArmFloatSocket'
    bl_label = 'Float Socket'
    arm_socket_type = 'VALUE'

    default_value_raw: FloatProperty(
        name='Value',
        description='Input value used for unconnected socket',
        precision=3,
        update=_on_update_socket
    )

    def draw(self, context, layout, node, text):
        draw_socket_layout(self, layout)

    def draw_color(self, context, node):
        return socket_colors[self.bl_idname]

    def get_default_value(self):
        return self.default_value_raw

    def copy_defaults(self, socket):
        if socket.bl_idname == self.bl_idname:
            socket.default_value_raw = self.default_value_raw

class ArmIntSocket(ArmCustomSocket):
    bl_idname = 'ArmIntSocket'
    bl_label = 'Integer Socket'
    arm_socket_type = 'INT'

    default_value_raw: IntProperty(
        name='Value',
        description='Input value used for unconnected socket',
        update=_on_update_socket
    )

    def draw(self, context, layout, node, text):
        draw_socket_layout(self, layout)

    def draw_color(self, context, node):
        return socket_colors[self.bl_idname]

    def get_default_value(self):
        return self.default_value_raw

    def copy_defaults(self, socket):
        if socket.bl_idname == self.bl_idname:
            socket.default_value_raw = self.default_value_raw

class ArmObjectSocket(ArmCustomSocket):
    bl_idname = 'ArmNodeSocketObject'
    bl_label = 'Object Socket'
    arm_socket_type = 'OBJECT'

    default_value_get: PointerProperty(name='Object', type=bpy.types.Object)  # legacy version of the line after this one
    default_value_raw: PointerProperty(name='Object', type=bpy.types.Object, update=_on_update_socket)

    def __init__(self):
        super().__init__()
        if self.default_value_get is not None:
            self.default_value_raw = self.default_value_get
            self.default_value_get = None

    def get_default_value(self):
        if self.default_value_raw is None:
            return ''
        if self.default_value_raw.name not in bpy.data.objects:
            return self.default_value_raw.name
        return arm.utils.asset_name(bpy.data.objects[self.default_value_raw.name])

    def draw(self, context, layout, node, text):
        if self.is_output:
            layout.label(text=self.name)
        elif self.is_linked:
            layout.label(text=self.name)
        else:
            row = layout.row(align=True)
            row.prop_search(self, 'default_value_raw', context.scene, 'objects', icon='NONE', text=self.name)

    def draw_color(self, context, node):
        return socket_colors[self.bl_idname]

    def copy_defaults(self, socket):
        if socket.bl_idname == self.bl_idname:
            socket.default_value_raw = self.default_value_raw

class ArmStringSocket(ArmCustomSocket):
    bl_idname = 'ArmStringSocket'
    bl_label = 'String Socket'
    arm_socket_type = 'STRING'

    default_value_raw: StringProperty(
        name='Value',
        description='Input value used for unconnected socket',
        update=_on_update_socket
    )

    def draw(self, context, layout, node, text):
        draw_socket_layout_split(self, layout)

    def draw_color(self, context, node):
        return socket_colors[self.bl_idname]

    def get_default_value(self):
        return self.default_value_raw

    def copy_defaults(self, socket):
        if socket.bl_idname == self.bl_idname:
            socket.default_value_raw = self.default_value_raw

class ArmVectorSocket(ArmCustomSocket):
    bl_idname = 'ArmVectorSocket'
    bl_label = 'Vector Socket'
    arm_socket_type = 'VECTOR'

    default_value_raw: FloatVectorProperty(
        name='Value',
        size=3,
        precision=3,
        description='Input value used for unconnected socket',
        update=_on_update_socket
    )

    def draw(self, context, layout, node, text):
        if not self.is_output and not self.is_linked:
            col = layout.column(align=True)
            col.label(text=self.name + ":")
            col.prop(self, 'default_value_raw', text='')
        else:
            layout.label(text=self.name)

    def draw_color(self, context, node):
        return socket_colors[self.bl_idname]

    def get_default_value(self):
        return self.default_value_raw

    def copy_defaults(self, socket):
        if socket.bl_idname == self.bl_idname:
            socket.default_value_raw = self.default_value_raw

def draw_socket_layout(socket: bpy.types.NodeSocket, layout: bpy.types.UILayout, prop_name='default_value_raw'):
    if not socket.is_output and not socket.is_linked:
        layout.prop(socket, prop_name, text=socket.name)
    else:
        layout.label(text=socket.name)

def draw_socket_layout_split(socket: bpy.types.NodeSocket, layout: bpy.types.UILayout, prop_name='default_value_raw'):
    if not socket.is_output and not socket.is_linked:
        # Blender layouts use 0.4 splits
        layout = layout.split(factor=0.4, align=True)

    layout.label(text=socket.name)

    if not socket.is_output and not socket.is_linked:
        layout.prop(socket, prop_name, text='')

def _make_socket_interface(interface_name: str, bl_idname: str) -> Type[bpy.types.NodeSocketInterface]:
    """Create a socket interface class that is used by Blender for node
    groups. We currently don't use real node groups, but without these
    classes Blender will (incorrectly) draw the socket borders in light grey.
    """
    def draw(self, context, layout):
        pass

    def draw_color(self, context):
        # This would be used if we were using "real" node groups
        return 0, 0, 0, 1

    cls = type(
        interface_name,
        (bpy.types.NodeSocketInterface, ), {
            'bl_socket_idname': bl_idname,
            'draw': draw,
            'draw_color': draw_color,
        }
    )
    return cls

ArmActionSocketInterface = _make_socket_interface('ArmActionSocketInterface', 'ArmNodeSocketAction')
ArmAnimSocketInterface = _make_socket_interface('ArmAnimSocketInterface', 'ArmNodeSocketAnimAction')
ArmRotationSocketInterface = _make_socket_interface('ArmRotationSocketInterface', 'ArmRotationSocket')
ArmArraySocketInterface = _make_socket_interface('ArmArraySocketInterface', 'ArmNodeSocketArray')
ArmBoolSocketInterface = _make_socket_interface('ArmBoolSocketInterface', 'ArmBoolSocket')
ArmColorSocketInterface = _make_socket_interface('ArmColorSocketInterface', 'ArmColorSocket')
ArmDynamicSocketInterface = _make_socket_interface('ArmDynamicSocketInterface', 'ArmDynamicSocket')
ArmFloatSocketInterface = _make_socket_interface('ArmFloatSocketInterface', 'ArmFloatSocket')
ArmIntSocketInterface = _make_socket_interface('ArmIntSocketInterface', 'ArmIntSocket')
ArmObjectSocketInterface = _make_socket_interface('ArmObjectSocketInterface', 'ArmNodeSocketObject')
ArmStringSocketInterface = _make_socket_interface('ArmStringSocketInterface', 'ArmStringSocket')
ArmVectorSocketInterface = _make_socket_interface('ArmVectorSocketInterface', 'ArmVectorSocket')
ArmAnySocketInterface = _make_socket_interface('ArmAnySocketInterface', 'ArmAnySocket')

__REG_CLASSES = (
    ArmActionSocketInterface,
    ArmAnimSocketInterface,
    ArmRotationSocketInterface,
    ArmArraySocketInterface,
    ArmBoolSocketInterface,
    ArmColorSocketInterface,
    ArmDynamicSocketInterface,
    ArmFloatSocketInterface,
    ArmIntSocketInterface,
    ArmObjectSocketInterface,
    ArmStringSocketInterface,
    ArmVectorSocketInterface,
    ArmAnySocketInterface,

    ArmActionSocket,
    ArmAnimActionSocket,
    ArmRotationSocket,
    ArmArraySocket,
    ArmBoolSocket,
    ArmColorSocket,
    ArmDynamicSocket,
    ArmFloatSocket,
    ArmIntSocket,
    ArmObjectSocket,
    ArmStringSocket,
    ArmVectorSocket,
    ArmAnySocket,
)
register, unregister = bpy.utils.register_classes_factory(__REG_CLASSES)


from flask import Flask, render_template, request, redirect, url_for, send_file, flash
from youtube_downloader import VideoDownloader, PlaylistDownloader
from io import BytesIO
from zipfile import ZipFile

app = Flask(__name__)
app.config['SECRET_KEY'] = 'Powerful Secret Key'

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'GET':
        return render_template('index.html')

    if "VideoLinkInput" in request.form:
        if request.form["VideoLinkInput"] == '':
            flash("Enter the URL.")
            return render_template('index.html')
        elif str(request.form["VideoLinkInput"]).find('?v=') == -1:
            flash("Enter a valid URL.")
            return render_template('index.html')

        video_id = request.form["VideoLinkInput"].split('?v=')[1]
        return redirect(url_for('download_video',vid_id = video_id))

    if "PlaylistLinkInput" in request.form:
        if request.form["PlaylistLinkInput"] == '':
            flash("Enter the URL.")
            return render_template('index.html')
        elif str(request.form["PlaylistLinkInput"]).find('playlist?list=') == -1:
            flash("Enter a valid URL.")
            return render_template('index.html')

        playlist_id = request.form["PlaylistLinkInput"].split('playlist?list=')[1]
        return redirect(url_for('download_playlist',pl_id = playlist_id))

@app.route('/download/video/<string:vid_id>', methods=['GET', 'POST'])
def download_video(vid_id):
    try:
        video = VideoDownloader(f"""https://www.youtube.com/watch?v={vid_id}""")
    except:
        flash("Enter a valid URL.")
        return redirect(url_for('index'))
    if request.method == 'GET':
        return render_template('download_video.html', title = video.title, thumbnail = video.thumbnail_url,
                                resolutions = video.GetAvailableResolutions())

    if request.form['SelectedResolution'] == 'audio':
        return send_file(
            BytesIO(video.StreamToBuffer(request.form['SelectedResolution'])),
            as_attachment = True,
            download_name=f"""{video.title}.mp3""")

    return send_file(
        BytesIO(video.StreamToBuffer(request.form['SelectedResolution'])),
        as_attachment = True,
        download_name=f"""{video.title}.mp4""")

@app.route('/download/playlist/<string:pl_id>', methods=['GET', 'POST'])
def download_playlist(pl_id):
    try:
        playlist = PlaylistDownloader(f"""https://www.youtube.com/playlist?list={pl_id}""")
        videos = playlist.GetVideos()
    except:
        flash("Enter a valid URL.")
        return redirect(url_for('index'))

    if request.method == 'GET':
        return render_template('download_playlist.html', title = playlist.title, videos = videos)

    # Create a ZipFile object in memory
    in_memory = BytesIO()
    with ZipFile(in_memory, 'w') as zip:
        # Add multiple files to the zip file
        for file in videos:
            if request.form['SelectedResolution'] == 'audio':
                zip.writestr(f"""{file.title}.mp3""",file.StreamToBuffer(request.form['SelectedResolution']))
            else:
                zip.writestr(f"""{file.title}.mp4""",file.StreamToBuffer(request.form['SelectedResolution']))

    # Set the zip file as the response
    in_memory.seek(0)
    return send_file(in_memory, download_name=f"""{playlist.title}.zip""", as_attachment=True)


import bs4
import requests

import constants as keys
from services import convert_price

class WatsonsHelper:
    @staticmethod
    def get_category_urls(base_url):
        r = requests.get(base_url)
        soup = bs4.BeautifulSoup(r.content, features="lxml")
        urls = list()
        links = soup.findAll("a", {"class": "main-menu-link"})
        for link in links:
            href = link.get("href")
            url = base_url + href
            if "sayfa" not in url and url not in urls:
                urls.append(url)

        return urls

    @staticmethod
    def extract_product_info(product_div, base_url):

        brand = product_div.css(".productbox-name::text").extract_first().strip()
        name = (
            product_div.css(".product-box-zoom-image::attr(title)")
            .extract_first()
            .strip()
        )
        name = " ".join([brand, name])

        price = product_div.css(".product-box-price::text").extract_first()

        price = price.replace("₺", "").replace(".", "").replace(",", ".").strip()

        price = convert_price(price)
        if not price:
            return

        href = product_div.css(
            ".product-box-image-container a::attr(href)"
        ).extract_first()

        src = (
            product_div.css(".product-box-zoom-image::attr(src)")
            .extract_first()
            .strip()
        )

        product = {
            keys.LINK: base_url + href,
            keys.NAME: name,
            keys.PRICE: price,
            keys.MARKET: keys.WATSONS,
            keys.BRAND: brand,
            keys.OUT_OF_STOCK: False,
        }

        if "default" not in src:
            product[keys.SRC] = src

        if product_div.css(".product-box-has-no-stock"):
            product[keys.OUT_OF_STOCK] = True

        return product


from setuptools import setup

with open("README", "r") as fh:
    long_description = fh.read()

setup(
    name='placeandroute',
    version='0.0.0',
    packages=['placeandroute','placeandroute.routing',
              'placeandroute.tilebased'],
    install_requires=['networkx>=2.4,<3.0',
                      'dwave-networkx>=0.8.2',
                      'matplotlib',
                      ],
    extras_requires= {"cpp": "placeandroutecpp"},
    url='https://bitbucket.org/StefanoVt/placeandroute/',
    license='MIT',
    author='Stefano Varotti',
    author_email='stefano.varotti@unitn.it',
    description='graph placement and routing library',
    long_description=long_description,
    long_description_content_type="text/markdown",
    classifiers = [
                  "Programming Language :: Python :: 3",
                  "License :: OSI Approved :: MIT License",
                  "Operating System :: OS Independent",
              ],

)


import numpy as np
import cv2
import re
#  绘制画布
canvas = np.zeros((720,1280,3),dtype="uint8")

# 定义颜色
green = (0,255,0)
red = (0,0,255)
blue = (255,0,0)

f = open('xml.txt', 'r')

# 用于存储需要绘制直线的三个点坐标 因为点坐标为数字 所以必须用数组
x = [0, 0, 0]
y = [0, 0, 0]

# 一次性读取所有的内容 节省时间
line = f.readlines()
# print(line)
# print(line[0])

# 设置循环初始状态
i=0
n=0
m = len(line)
# print(m)

# 将行数设置为外循环条件
while(m > 0):
    # 设置每次读取三行后进行处理
    for i in range(n,n+3):
        # print(i)
        # print(n,n+3)
        r = re.split(' ',line[i])
        m -= 1
        print(i)
        print(r)
        r[0] = float(r[0])
        r[1] = float(r[1])
        r[2] = float(r[2])
        r[3] = float(r[3])
        # 因为x只包含3个数 所以下标需要对3取余才不会越界
        x[i%3] = int((r[0]+r[2])/2)
        y[i%3] = int((r[1]+r[3])/2)
        # print(x)
        # print(y)
    # 将n重新赋值从而可以继续循环
    n = i + 1
    # print(n)
    # print(i)
    # 绘制线段 因为i的值最后为累加后的 所以做减法运算
    cv2.line(canvas,(x[(i-2)%3],y[(i-2)%3]),(x[(i-1)%3],y[(i-1)%3]),green)
    cv2.line(canvas,(x[(i-1)%3],y[(i-1)%3]),(x[i%3],y[i%3]),green)
    cv2.imwrite("traffic_line.jpg", canvas)


#! /usr/bin/python3
"""Load a gumpy Genome object, and use pickle to save to disk.
Due to the security implications of the pickle module, USE AT YOUR OWN RISK.
It is recommended to avoid sending and recieving pickled objects.
"""
import argparse
import pickle
import os

import gumpy

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--genbank_file", required=True, help="Path to a single genbank file"
    )
    parser.add_argument("--path", required=True, help="Path to the output file")
    parser.add_argument(
        "--overwrite",
        required=False,
        default=False,
        action="store_true",
        help="Overwrite a file at the given path (if exists)",
    )
    options = parser.parse_args()

    # instantiate a gumpy Genome object using the provided Genbank file
    reference_genome = gumpy.Genome(options.genbank_file, show_progress_bar=True)

    if os.path.exists(options.path):
        if options.overwrite:
            print("File existed! Overwriting")
            pickle.dump(reference_genome, open(options.path, "wb"))
        else:
            print("File already exists! Use --overwrite to replace it")
    else:
        pickle.dump(reference_genome, open(options.path, "wb"))


import numpy as np
import matplotlib.pylab as plt
import os

def nucleoPropuestoPrimo(f0, nHarmonics, fs, N, decayP=0.5, amplitudeLimit=0.5):
    return getPrimeKernel(float(f0), nHarmonics, fs, N, decayP, amplitudeLimit)

def nucleoPropuestoNoPrimo(f0, nHarmonics, fs, N, decayP=0.5, amplitudeLimit=0.5):
    return getNonPrimeKernel(float(f0), nHarmonics, fs, N, decayP, amplitudeLimit)

def isPrime(x):
    xp = x + 0.0
    return 1.0 == xp or 2.0 == xp or 3.0 == xp or 5.0 == xp or 7.0 == xp or 11.0 == xp or 13.0 == xp

def getPrimeKernel(f0, A, fs, N, decayP, amplitudeLimit):
    # nucleo propuesto con armonicas PRIMAS

    k = np.zeros([N, 1])
    fmax = fs / 2.0
    for n in range(0, N):
        f = n * fmax / N
        fNorm = f / f0
        if (0.25 < fNorm and fNorm < 0.75) or (A + 0.25 < fNorm and fNorm < A + 0.75):
            k[n] = amplitudeLimit * np.cos(2 * np.pi * 1 / f0 * f)
        elif (0.75 < fNorm and fNorm < A + 0.25) and (isPrime(np.round(fNorm)) or 0.25 <= np.abs(round(fNorm) - fNorm)):
            k[n] = np.cos(2 * np.pi * 1 / f0 * f)

        # 0.9 para alcanzar un error de -0.013202 con 5 armonicas y
        # conservar el peso 0.5 en la primer subarmonica
        decaimiento = fNorm ** -decayP if 0 < fNorm else 1
        k[n] *= decaimiento

    return k

def getNonPrimeKernel(f0, A, fs, N, decayP, amplitudeLimit):
    # nucleo propuesto con todas las armonicas

    k = np.zeros([N, 1])
    fmax = fs / 2.0
    for n in range(0, N):
        f = n * fmax / N
        fNorm = f / f0
        if (0.25 < fNorm and fNorm < 0.75) or (A + 0.25 < fNorm and fNorm < A + 0.75):
            k[n] = amplitudeLimit * np.cos(2 * np.pi * 1 / f0 * f)
        elif (0.75 < fNorm and fNorm < A + 0.25):
            k[n] = np.cos(2 * np.pi * 1 / f0 * f)

        # 0.9 para alcanzar un error de -0.013202 con 5 armonicas y
        # conservar el peso 0.5 en la primer subarmonica
        decaimiento = fNorm ** -decayP if 0 < fNorm else 1
        k[n] *= decaimiento

    return k

def run(A=7, outImgFolderPath=None):
    # A: number of harmonics
    N = 256
    fs = 22050.0
    f0 = 1000.0
    f = np.linspace(0, fs / 2, N)

    bestDecaP = 0.5
    bestAmpLim = 0.5
    k1 = nucleoPropuestoPrimo(f0, A, fs, N, bestDecaP, bestAmpLim)
    k2 = nucleoPropuestoNoPrimo(f0, A, fs, N, bestDecaP, bestAmpLim)

    # plot kernel
    plt.figure()
    plt.subplot(211)
    plt.title('f0=%.1f kHz, A=%i, dec.=k^-%.1f, ampLim=%.1f, sum=%.2f vs. %.2f' % (
    f0 / 1000.0, A, bestDecaP, bestAmpLim, np.sum(k1), np.sum(k2)))
    plt.plot(f, k1)
    plt.xlim([0, A * f0 * 1.5])
    plt.ylabel('Amplitud')
    plt.subplot(212)
    plt.plot(f, k2)
    plt.ylabel('Amplitud')
    plt.xlabel('Frecuencia (Hz)')
    plt.xlim([0, A * f0 * 1.5])

    # guardar en archivo para graficar en formato vectorial
    hilera_k1 = "f, p"
    hilera_k2 = "f, p"
    for n in range(0, N):
        hilera_k1 = "%s\n%f, %f" % (hilera_k1, f[n], k1[n])
        hilera_k2 = "%s\n%f, %f" % (hilera_k2, f[n], k2[n])

    if outImgFolderPath is None:
        plt.show()
    else:
        outImgPath = '%s/proposedKernels_%iHarm.pdf' % (outImgFolderPath, A)
        text_file_k1 = open('%s/prime_%iHarmKernel.txt' % (outImgFolderPath, A), "w")
        text_file_k2 = open('%s/nonPrime_%iHarmKernel.txt' % (outImgFolderPath, A), "w")
        text_file_k1.write(hilera_k1)
        text_file_k2.write(hilera_k2)
        text_file_k1.close()
        text_file_k2.close()
        plt.savefig(outImgPath)

# testing
if __name__ == "__main__":
    # save current working directory and change to script's directory
    cwd = os.getcwd()
    os.chdir(os.path.dirname(os.path.realpath(__file__)))

    run()

    os.chdir(cwd)  # restore directory


import argparse
import os

from rinna_ure import get_ure_answers

from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Query URE for an answer.")
    parser.add_argument("query", type=str, help="The query to ask.")
    parser.add_argument("--knowledgeSetId", type=str, help="The knowledge set ID to use.")
    parser.add_argument("--l2ReturnNum", type=int, default=3, help="The number of L2 results to return. Defaults to 3.")
    parser.add_argument("--l3ReturnNum", type=int, default=1, help="The number of L3 results to return. Defaults to 1.")
    args = parser.parse_args()

    results = get_ure_answers(args.query, args.knowledgeSetId, args.l2ReturnNum, args.l3ReturnNum)
    print(results)


from turtle import Turtle, Screen
import random

screen = Screen()
screen_width = 600
screen_height = 400
screen.setup(width=screen_width, height=screen_height)
user_bet = screen.textinput(title='Make your bet!', prompt='Which turtle will win the race? Enter a color: ')
print(user_bet)

turtle_starting_x = -screen_width/2 + screen_width * 0.05

turtle_colors = ['red', 'blue', 'orange', 'green', 'purple']

tim = Turtle()
bob = Turtle()
joe = Turtle()
alex = Turtle()
phil = Turtle()

all_turtles = [tim, bob, joe, alex, phil]

def init_turtle(turtle, turtle_number, turtle_color):
    turtle_starting_y = -screen_height / 6 + (25 * turtle_number)
    turtle.color(turtle_color)
    turtle.shape('turtle')
    turtle.penup()
    turtle.setx(turtle_starting_x)
    turtle.sety(turtle_starting_y)

number_of_turtles = len(all_turtles)
for turtle_number in range(number_of_turtles):
    init_turtle(turtle=all_turtles[turtle_number], turtle_number=turtle_number, turtle_color=turtle_colors[turtle_number])

screen.exitonclick()