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

import os
import sys
import string
from Constants import *
from PIL import Image, ImageDraw, ImageFont

emojiTextFile = open(EMOJIS_TXT, 'r')
lines = emojiTextFile.readlines()
EMOJIS = [line[:-1].split(',') for line in lines]
MAX_EMOJI_COUNT = len(lines)

class DynamicColour:
    def __init__(self, dark, light):
        self.dark = dark
        self.light = light

    def fill(self):
        return self.dark if isDark() else self.light

def clamp(minVal, val, maxVal):
    return max(minVal, min(val, maxVal))

def getEmojiCode(index):
    return EMOJIS[index][1]

def getEmojiName(index):
    return EMOJIS[index][2]

def getEmojiFileName(index):
    return "%s/%s.png" % (EMOJIS_DIR, getEmojiCode(index))

def getMergedFileName(first, second):
    return "%s/%s_%s.png" % (MERGED_DIR, getEmojiCode(first), getEmojiCode(second))

def main(argc, argv):
    print("Preparing poster file...")

    textColour = DynamicColour(dark = WHITE_FILL, light = BLACK_FILL)
    niceColour = DynamicColour(dark = RED_FILL, light = RED_FILL)

    font = ImageFont.truetype(FONT_TYPE, int(FONT_SIZE / 2))
    rows = MAX_EMOJI_COUNT
    columns = MAX_EMOJI_COUNT

    startRow = 0
    startColumn = 0

    if argc in [1, 3, 5]:
        setModes(str(argv[-1]).lower())

    if argc in [2, 3]:
        columns, rows = [clamp(1, int(i), MAX_EMOJI_COUNT) if i.isnumeric() else MAX_EMOJI_COUNT for i in argv[:2]]

    if argc in [4, 5]:
        startColumn, startRow = [clamp(0, int(argv[i * 2]) - 1, MAX_EMOJI_COUNT) if argv[i * 2] else MAX_EMOJI_COUNT for i in range(2)]
        columns, rows = [clamp(1, int(argv[i * 2 + 1]), MAX_EMOJI_COUNT) if argv[i * 2 + 1] else MAX_EMOJI_COUNT for i in range(2)]

    background = Image.open(getDynamicBackground()).convert("RGBA")
    finalW, finalH = (SPRITE_WIDTH * (columns + 1), SPRITE_HEIGHT * (rows + 1) + BOTTOM_DELTA)
    final = Image.new("RGBA", (finalW, finalH))
    draw = ImageDraw.Draw(final)

    if not os.path.exists(POSTER_DIR):
        os.makedirs(POSTER_DIR)

    # Draw background first
    print("Adding background...")

    origin = Image.open(getDynamicOrigin()).convert("RGBA")
    final.paste(origin, (0, 0, SPRITE_WIDTH, SPRITE_HEIGHT))

    for i in range(columns + 1):
        for j in range(rows + 1):
            x, y = (i * SPRITE_WIDTH, j * SPRITE_HEIGHT)
            final.paste(background, (x, y, x + SPRITE_WIDTH, y + SPRITE_HEIGHT))

    cellWidth = background.size[0]
    croppedCell = background.crop((0, 0, cellWidth, BOTTOM_DELTA))

    for i in range(columns + 1):
        x, y = (SPRITE_WIDTH * i, SPRITE_HEIGHT * (rows + 1))
        final.paste(croppedCell, (x, y, x + cellWidth, y + BOTTOM_DELTA))

    # Plop origin cell down

    origin = Image.open(getDynamicOrigin()).convert("RGBA")
    final.paste(origin, (0, 0, SPRITE_WIDTH, SPRITE_HEIGHT))

    # Draw sprites and text

    for i in range(startColumn, min(startColumn + columns, MAX_EMOJI_COUNT) + 1):
        for j in range(startRow, min(startRow + rows, MAX_EMOJI_COUNT) + 1):
            if not (i == startColumn and j == startRow):
                emojiName = ""
                fileName = ""
                first = 0
                second = 0
                colour = textColour

                if i == startColumn or j == startRow:
                    colour = niceColour
                    index = (j if i == startColumn else i) - 1
                    text = emojiName = getEmojiName(index)
                    fileName = getEmojiFileName(index)
                else:
                    iIndex = i - 1
                    jIndex = j - 1

                    if not os.path.isfile(getMergedFileName(iIndex, jIndex)):
                        if not os.path.isfile(getMergedFileName(jIndex, iIndex)):
                            continue

                        first = jIndex
                        second = iIndex
                    else:
                        first = iIndex
                        second = jIndex

                    text = emojiName = "%s + %s" % (getEmojiName(first), getEmojiName(second))
                    fileName = getMergedFileName(first, second)

                text = string.capwords(text)
                emojiName = string.capwords(emojiName)

                if i == j:
                    colour = niceColour
                    text = emojiName = "%s x 2" % string.capwords(getEmojiName(first))

                print("Adding Sprite (%03d, %03d): %s" % (first, second, emojiName))

                current = Image.open(fileName).convert("RGBA")

                x, y = (SPRITE_WIDTH * (i - startColumn), SPRITE_HEIGHT * (j - startRow))
                width, height = current.size
                deltaX, deltaY = (round((SPRITE_WIDTH - width) / 2), round((SPRITE_HEIGHT - height) / 2))

                final.paste(current, (x + deltaX, y + deltaY, x + deltaX + width, y + deltaY + height), current)

                for index, name in enumerate(text.split("+")):
                    w, h = draw.textsize(name, font=font)
                    draw.text((x + (SPRITE_WIDTH - w) / 2, y + (SPRITE_HEIGHT - 33) + (h * index)), name, fill=colour.fill(), font=font)

    # Finally, draw credits

    credits = "「EmojiKitchenPoster 2021 | Alex Mueller」"
    f = ImageFont.truetype(FONT_TYPE, int(FONT_SIZE * 2 / 5))
    w, h = draw.textsize(credits, font=f)
    delta = (BOTTOM_DELTA - h) / 2
    x, y = ((finalW - w) / 2, finalH - h - delta)
    draw.text((x, y), credits, fill=GRAY_FILL, font=f)

    print("Saving...", flush=True)
    final.save('%s/EmojiKitchenPoster(%ix%i)[rowStart=%s, columnStart=%s]_%s.png' % (POSTER_DIR, columns, rows, startRow, startColumn, getModeFolder()))
    print("Finished!")

if __name__ == '__main__':
   main(len(sys.argv) - 1, sys.argv[1:])


# zendesk_application.py

'''This file contains the logic application function.'''

# Import statements
from database import create_data_base
from search_engine import search_by_user, search_by_organization, search_by_tickets, searchable_fields

# Main run function.

def run_application():
    # Messages
    welcome = '\n\nWelcome to Zendesk Search'
    information_text_1 = 'Type "quit" to exit at any time, Press "Enter" to continue\n'
    information_text_2 = '\t\tSelect search options:\n\t\t* Press 1 to search\n\t\t* Press 2 to view a list of ' \
                         'searchable field\n\t\t* Type "quit" to exit\n '
    information_text_3 = '\t\tSelect table:\n\t\t* Select 1 users\n\t\t* Select 2 organizations\n\t\t* Select 3 ' \
                         'tickets\n '

    # Data base initialization
    json_files = ["users.json", "organizations.json", "tickets.json"]
    connection = create_data_base(json_files)

    # Start our application
    print(f'{welcome}')

    command = input(information_text_1)
    # Exit any time
    while not command == 'quit':
        # Client press "Enter"
        if command == '':
            # Exit any time
            while not command == 'quit':
                # Display options
                command = input(information_text_2)
                # Selected Search option
                if command == '1':
                    # Exit any time
                    while not command == 'quit':
                        # Display table options
                        command = input(information_text_3)
                        # Selected users table
                        if command == '1':
                            # Enter search column
                            search_attr = input('Enter search term\n')
                            # Enter search value
                            search_value = input('Enter search value\n')
                            # Searching
                            search_by_user(connection, search_attr, search_value)
                        # Selected organizations table
                        elif command == '2':
                            # Enter search column
                            search_attr = input('Enter search term\n')
                            # Enter search value
                            search_value = input('Enter search value\n')
                            # Searching
                            search_by_organization(connection, search_attr, search_value)
                        # Selected tickets table
                        elif command == '3':
                            # Enter search column
                            search_attr = input('Enter search term\n')
                            # Enter search value
                            search_value = input('Enter search value\n')
                            # Searching
                            search_by_tickets(connection, search_attr, search_value)
                # Selected Searchable  field list option
                elif command == '2':
                    searchable_fields(connection)
        else:
            command = input(information_text_1)

    # Close connection and free up the memory
    connection.close()

    print('Good Bye')

# Run the application
if __name__ == '__main__':
    run_application()


import pygame, DailyDoubleSetter, EventHandler, Question, Button

class Board:
    def __init__(self, players, screen):
        self.screen = screen
        self.box = []
        self.players = players
        self.done_image = "done.png"
        #self.background = 'background.mid'
        #self.buzzer = 'TIMESUP.WAV'
        self.boardFill = 'boardFill2.wav'
        #do we need font here?
        self.font = pygame.font.SysFont(None, 48)
        self.ignorePlayers = []
        self.doubleJeopardy = False
        self.beginRound = True
        self.isItOverYet = 0
        self.wagered = False
        self.dd1 = 0
        self.dd2 = 0
        self.dd3 = 0
        #these coords may not be needed anymore
        self.xCoord = int(self.screen.get_rect().width * .85)
        self.yCoord = int(self.screen.get_rect().height / 10)
        self.event = EventHandler.EventHandler()
        self.question = Question.Question(screen, players)
        self.button = Button.Button(players, screen)
        self.dd = False

    """showBoard controls the main game loop - it draws the board, and calls ask when a button is clicked on.  It checks the beginRound boolean to see whether it
should form randomly."""
    def showBoard(self, box, gSetup):
        for i in xrange(36):
            self.box.append(box[i])
        if self.dd1 == 0:
            dds = DailyDoubleSetter.DailyDoubleSetter(self.box)
            self.dd1 = dds.setDailyDoubles()
            print(self.box[self.dd1].getQuestion(self.doubleJeopardy))
            self.dd2 = dds.setDailyDoubles()
            print(self.box[self.dd2].getQuestion(self.doubleJeopardy))
            self.dd3 = dds.setDailyDoubles()
            print(self.box[self.dd3].getQuestion(self.doubleJeopardy))

        if self.isItOverYet == 30:
            self.doubleJeopardy = True
            self.beginRound = True
            self.isItOverYet = 0
            for i in xrange(36):
                self.box[i].setBeenClicked()
        self.screen.fill((14,27,121))
        pygame.display.update()
        #if self.doubleJeopardy == True and  self.is_it_over_yet == 30:
            #self.final_jeopardy()
        if self.beginRound == True:
            pygame.mixer.music.load(self.boardFill)
            pygame.mixer.music.play()
            pygame.time.delay(225)
            if len(self.players) == 3:
                self.ignorePlayers = [-1, -1]
            else:
                self.ignorePlayers = [-1]
            for i in xrange(36):
                coords = self.box[i].getCoords()
                image = pygame.image.load(self.box[i].getImage(self.doubleJeopardy))
                frame = pygame.Rect(coords, (125, 95))
                self.box[i].setFrame(frame)
                self.screen.blit(image, frame)
                pygame.time.delay(60)
                pygame.display.flip()

            self.beginRound = False
        else:
            if len(self.players) == 3:
                self.ignorePlayers = [-1, -1]
            else:
                self.ignorePlayers = [-1]
            for i in xrange(36):
                coords = self.box[i].getCoords()
                if self.box[i].getBeenClicked() == True:
                    image = pygame.image.load(self.box[i].getImage(self.doubleJeopardy))
                else:
                    image = pygame.image.load(self.box[i].getImage(self.doubleJeopardy))
                frame = pygame.Rect(coords, (125, 95))
                self.box[i].setFrame(frame)
                self.screen.blit(image, frame)

            pygame.display.flip()

        #mainClock = pygame.time.Clock()
        gameLoop = True
        self.dd = False
        while gameLoop:
            temp = self.event.handleBoardEvents()
            boxNum = self.isMenuClicked(temp[0], temp[1])
            if boxNum >= 0 and self.box[boxNum].getBeenClicked() == False and self.box[boxNum].getQuestion(boxNum) != "placeholder":
                    if boxNum == self.dd2 and self.doubleJeopardy or boxNum == self.dd3 and self.doubleJeopardy:
                        self.dd = True
                        gameLoop = False
                        self.isItOverYet += 1
                        self.question.ddCheck(self.question, self.box[boxNum], self.doubleJeopardy, self.ignorePlayers, gSetup, self.dd)
                    elif boxNum == self.dd1:
                        self.dd = True
                        gameLoop = False
                        self.isItOverYet += 1
                        self.question.ddCheck(self.question, self.box[boxNum], self.doubleJeopardy, self.ignorePlayers, gSetup, self.dd)

                    else:
                        gameLoop = False
                        self.isItOverYet += 1
                        self.question.ddCheck(self.question, self.box[boxNum], self.doubleJeopardy, self.ignorePlayers, gSetup, self.dd)

    """This method checks if a question box was clicked by iterating through the box array. Items is a
    list containing the 4 edges of the button in the order, left, right, top, bottom. If a box was clicked
    on, returns the index number of theteamButtons = self.makePlayerBoxes() box. Else returns -1"""
    def isMenuClicked(self, x, y):
        for i in self.box:
            frame = i.getFrame()
            if (x > frame.left) and (x < frame.right) and (y > frame.top) and (y < frame.bottom):
                return self.box.index(i)
        return -1

    def setIsItOverYet(self, num):
        self.isItOverYet += 1

    def getIsItOverYet(self):
        return self.isItOverYet

    def resetIsItOverYet(self):
        self.isItOverYet = 0

    def getDoubleJeopardy(self):
        return self.doubleJeopardy

    def setDoubleJeopardy(self, state):
        self.doubleJeopardy = state

    def getBox(self):
        return self.box


import serial
import sys

s = serial.Serial(sys.argv[1], 9600, timeout = 1)

def m(v):
    if v >= 65 and v <= 122:
        return chr(v)
    else:
        return int(v)

s.reset_input_buffer()
while True:
    b = s.read(6)
    if len(b) == 0:
        continue;
    elif len(b) != 6:
        print("TRUNC")
    l = map(m, b)
    print(list(l))


from pathvalidate import sanitize_filename
import numpy as np
import re
import redis
from datetime import timedelta

def safe_filenames(label_1, label_2):
    """ Return safe and distinct filenames from the labels provided for the uploaded datasets"""

    sf_1 = sanitize_filename(label_1)
    sf_2 = sanitize_filename(label_2)
    if sf_1 == sf_2:
        return f'{sf_1}_1', f'{sf_1}_2'
    else:
        return sf_1, sf_2

def cache_key(session_id, file_type):
    """ Generate a cache key in a consistent way from session id and file type"""
    return '_'.join([session_id, file_type])

def df_to_data(df):
    """ Extract the data from a Pandas dataframe, dropping metadata columns"""
    return np.array(df.drop(columns=['cluster', 'ttype']))

def short_ephys_labels(label: str) -> str:
    """Given an excessively verbose ephysiology label, return an abbreviated one"""
    updates = dict([
              ('_', ' '),
              ('upstroke', 'up'),
              ('downstroke', 'down'),
              ('square', 'sq'),
              ('ratio', 'rat'),
              ('resistance', 'resist'),
              ('polarization', 'polar'),
              ('amplitude', 'amp'),
              ('number', 'num'),
              ('frequency', 'freq'),
              ('adaptation', 'adapt'),
              ('potential', 'pot'),
              ('..', ' '),
              ('.', ' ')
    ])
    for k, v in updates.items():
        label = re.sub(r'(?i)'+re.escape(k), v, label)  # case-insensitive matching
    return label

def short_morph_labels(label: str) -> str:
    """Shorten morphology feature labels"""
    updates = dict([
        ('axon', 'ax'),
        ('dendrite', 'dend'),
        ('number', 'num'),
        ('angle', 'ang'),
        ('"apical"', 'ap'),
        ('bifurcation', 'bifurc'),
        ('fraction', 'frac'),
        ('tortuosity', 'tort'),
        ('distance', 'dist'),
    ])
    for k, v in updates.items():
        label = re.sub(r'(?i)'+re.escape(k), v, label)  # case-insensitive matching
    return label

def unique_visitors():
    """Report the number of "unique" visitors to the site"""

    # check if log has been accessed today
    r = redis.Redis(host='localhost', port=6379, decode_responses=True)
    if r.exists('unique_visitors'):
        return r.get('unique_visitors')

    # for testing
    access_log = r'/var/log/nginx/access.log'

    regex = r'^(?P<ip>\S+)\s+(\S+)\s+(\S+)\s+\[((?P<date>[^:]+)[^\]]+)\]\s+"([A-Z]+)([^"]+)?HTTP/[0-9.]+"\s+([0-9]{3})\s+([0-9]+|-)\s+"([^"]*)"\s+"(?P<agent>[^"]*)"\s+"([^"]*)"'
    log_parser = re.compile(regex)
    u = set()
    first = True
    try:
        with open(access_log, 'r') as f:
            for line in f:
                if first:
                    try:
                        match = log_parser.match(line)
                        startdate = match.groupdict()['date']
                        first = False
                    except:
                        pass
                if '_dash-update-component' in line:
                    # store date, ip, browser string
                    match = log_parser.match(line)
                    if match:
                        mg = match.groupdict()
                        u.add((mg['ip'], mg['date'], mg['agent']))
    except FileNotFoundError:
        return ''

    response = f'{len(u)} visitors since {startdate} (updated daily)'
    r.setex('unique_visitors', timedelta(days=1), response)
    return response


# -*- coding: utf-8 -*-
# @Time    : 2022/11/14 14:09
# @Author  : Carlos
import time

from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select

# 导入模块
from selenium import webdriver

# 浏览器启动配置
def option_use(url):

    # ChromeOptions是chromedriver支持的浏览器启动选项。
    opt = webdriver.ChromeOptions()

    # 启动参数：
    # # 1.获取浏览器cookies储存的路径 浏览器搜索 ”Edge//version/ “  C:\Users\carlos\AppData\Local\Microsoft\Edge\User Data\Default
    # # 我们去掉后面的 \Default，然后在路径前加上“–user-data-dir=”就拼接出我们要的路径了。
    # profile_directory = r'--user-data-dir=C:\Users\carlos\AppData\Local\Microsoft\Edge\User Data'
    profile_directory = (r" user-data-dir=C:\Users\carlos\AppData\Local\Google\Chrome\User Data")  # 把数据传入程序
    opt.add_argument(profile_directory)

    # 设置为 headless 模式 无头浏览器
    # opt.add_argument('--headless')

    # 隐身模式(无痕模式)
    # opt.add_argument('incognito')

    # 禁用GPU
    opt.add_argument('--disable-gpu')

    # 设置窗口大小
    opt.add_argument("window-size=1024,768")

    # 彻底停用沙箱。
    opt.add_argument("--no-sandbox")

    # 防止网站发现我们使用模拟器 规避检测
    opt.add_experimental_option('excludeSwitches', ['enable-automation'])

    # 创建浏览器对象
    driver = webdriver.Chrome(chrome_options=opt)

    driver.get(url)

    time.sleep(1)

    return driver

# 选择框操作
def select_ues(wb):

    # 获取元素
    element1 = wb.find_element(By.XPATH, '//*[@id="OptionDate"]')  # select框对象

    # 获取文本值
    text = element1.text

    # 生成下拉框的实例对象  Select(元素)
    from selenium.webdriver.support.select import Select

    # 生成选择框对象
    select_obj=Select(element1)

    # 返回所有下拉框对象
    select_all=select_obj.options

    #通过索引选择
    select_obj.select_by_index(2)
    time.sleep(2)

    # 通过value选择
    select_obj.select_by_value("2021")
    time.sleep(2)

    #通过text文本选择
    select_obj.select_by_visible_text("2012年")
    time.sleep(2)

# 窗口操作
def handle_ues(wb):

    # 打开一个新的窗口
    wb.execute_script('window.open("https://www.endata.com.cn/BoxOffice/BO/Year/index.html")')

    # 切换窗口 索引切换
    wb.switch_to.window(wb.window_handles[-1])
    time.sleep(2)

    # 执行选择框操作
    select_ues(wb)

    #回退
    wb.back()
    time.sleep(2)

    # 前进
    wb.forward()
    time.sleep(2)

    # 刷新当前页面
    wb.refresh()
    time.sleep(1)

    wb.set_window_size(1000, 800)
    time.sleep(2)

    # 关闭当前窗口页面
    wb.close()

# 获取页面页面信息
def get_page_infomation(wb):

    # 切换到最后一页
    wb.switch_to.window(wb.window_handles[-1])

    # 获取页面标题
    title = wb.title

    # 生成当前页面快照并保存
    picture = wb.save_screenshot("页面快照.png")

    # 打印网页渲染后的源代码
    source_code = wb.page_source

    # 获取当前页面Cookie
    cookie = wb.get_cookies()

    # 获取当前url
    url = wb.current_url

    #打印
    print('页面信息获取成功')

def login(wb):

    # 点击登录
    wb.find_element(By.XPATH,'//section/section[2]/button/span').click()
    time.sleep(0.5)

    # 点击切换密码登录
    wb.find_element(By.XPATH,'//section/ul/li[2]').click()
    time.sleep(0.5)

    # 输入用户名密码
    wb.find_element(By.XPATH,'//section/form/div[1]/div/div/input').send_keys('13142392973')

    wb.find_element(By.XPATH,'//section/section/form/div[2]/div/div/input').send_keys('whm51921')

    # 点击登录
    wb.find_element(By.XPATH,'//section/section/div[2]/button').click()

    time.sleep(2)

# 基础用法
def basic_ues():
    url='https://ys.endata.cn/DataMarket/Index'

    # 调用配置函数
    wb=option_use(url)

    #页面最小化
    wb.minimize_window()
    time.sleep(1)
    #页面最大化
    wb.maximize_window()

    # 登录
    login(wb)

    # input 文本呢输入
    wb.find_element(By.XPATH,'//*[@id="app"]/header/section/section/section[1]/div/input').send_keys("独行月球66666")
    time.sleep(2)

    # 清空文本
    wb.find_element(By.XPATH, '//*[@id="app"]/header/section/section/section[1]/div/input').clear()
    wb.find_element(By.XPATH, '//*[@id="app"]/header/section/section/section[1]/div/input').send_keys("独行月球")

    # .click 元素点击 暂时搞不了，建议打断点，手动登录后
    # wb.find_element(By.XPATH,'//*[@id="app"]/header/section/section/section[1]/div/span/span/label/svg/use').click()
    time.sleep(0.5)
    wb.find_element(By.XPATH,'//span/span/label').click()
    time.sleep(3)

    wb.find_element(By.XPATH,'//section/section/ul/li/a/span').click()
    time.sleep(2)

    from selenium.webdriver import Keys
    # Keys.RETURN操作
    # wb.find_element(By.XPATH,'/html/body/section/section/main/div/div[1]/div/section/section[2]/section/div/label[2]/span').send_keys(Keys.RETURN)

    # 获取页面信息
    get_page_infomation(wb)

    # 窗口操作
    handle_ues(wb)

    print('运行成功')

    time.sleep(5)

    wb.quit()

    return wb

# 跳过验证码登录
def login_tomtoc():
    url='https://www.tomtoc.cn/'

    # 调用配置函数
    wb=option_use(url)

    #页面最小化
    wb.minimize_window()
    time.sleep(1)
    #页面最大化
    wb.maximize_window()
    time.sleep(5)

    # 关闭浏览器
    wb.quit()

# 切换 alert 窗口（弹窗）
def alert_handle():
    url='https://www.w3school.com.cn/tiy/t.asp?f=hdom_prompt'

    # 调用配置函数
    driver = option_use(url)

    # 切换进iframe
    driver.switch_to.frame("iframeResult")
    time.sleep(0.5)

    # 要让alert出现
    driver.find_element(By.XPATH,'//input[@type="button"]').click()

    # 切换到alert
    alert = driver.switch_to.alert

    # 在弹出框当中输入文本内容 还有问题
    # alert.send_keys("hello selenium")
    # time.sleep(2)

    # 获取当前弹框的文本内容
    text=alert.text
    print(text)

    # 切换到主文档

    # driver.switch_to.default_content()
    # print(driver.page_source)

    # 关闭浏览器
    driver.quit()

    # 切换到 confirm确认框
    # 与警告框不同，确认框还有取消按钮

    # 调用配置函数
    url = 'https://www.w3school.com.cn/tiy/t.asp?f=hdom_confirm'
    driver = option_use(url)

    time.sleep(1)

    # 切换进iframe
    driver.switch_to.frame("iframeResult")
    time.sleep(0.5)

    # 要让alert出现
    driver.find_element(By.XPATH,'//input[@type="button"]').click()

    # 切换到alert
    alert = driver.switch_to.alert

    # 获取当前弹框的文本内容
    text = alert.text
    print(text)

    #取消
    alert.dismiss()
    time.sleep(1)

    # 要让alert出现
    driver.find_element(By.XPATH,'//input[@type="button"]').click()

    # 获取当前弹框的文本内容
    text = alert.text
    print(text)

    # 确认
    alert.accept()
    time.sleep(1)

    time.sleep(10)
    driver.quit()

# 运行文件
# basic_ues()

# 验证跳过验证码登录
# login_tomtoc()

'''页面的弹出框2种：
1）右键元素定位
2）js弹框 – 由页面操作触发的。
WebDriver提供了一个API，用于处理JavaScript提供的三种类型的原生弹窗消息'''
# 切换 alert 窗口（弹窗）
# alert_handle()
wb=webdriver.Edge()

wb.get("https://www.baidu.com")

wb.get("https://www.csdn.net")

wb.execute_script("window.open('https://www.baidu.com')")


#!/usr/bin/env python3
import io, sys, re
from urllib import parse

from lxml import html
import requests

html_ = requests.get(f'https://en.wikipedia.org/wiki/{sys.argv[-1]}').content.decode('utf8')

doc = html.parse(io.StringIO(html_))
root = doc.getroot()

def walk_tree(root):
  yield root
  for child in root:

    # ignore everything but the main part of the article
    if child.tag == 'table':
      continue
    if child.tag == 'h2':
      if child.text == 'Navigation menu':
        return
    if child.classes and 'hatnote' in child.get('class'):
      continue
    if child.classes and 'thumb' in child.get('class'):
      continue

    for grandchild in walk_tree(child):
      yield grandchild

headers = []
for child in walk_tree(root):

  # Stop when we hit the end of the main part of the article
  if child.tag == 'h2':
    headline = child.find('span[@class="mw-headline"]')
    if headline is not None and headline.text in (
      'External links',
      'Further reading',
      'References',
      'Notes',
      'See also',
    ):
      break

  if child.tag in ('h1', 'h2', 'h3', 'h4'):
    while headers and child.tag <= headers[-1].tag:
      headers.pop()
    headers.append(child)

  # headlines
  elif(
    child.tag == 'span' and child.classes and 'mw-headline' in child.get('class')
  ):
    print(f'{"  " * len(headers)}{child.text_content()}')

  # links
  elif(
    child.tag == 'a' and headers and child.text and len(child.text) > 2 and
    not re.match(r'\[[0-9]+\]', child.text)
  ):
    if child.text.startswith('Jump to ') or child.text == 'edit':
      continue
    if child.text.startswith('Wikipedia articles with'):
      break
    # print(f'{"  " * (len(headers) + 1)}[[{child.text}]]')
    if '/wiki/' not in child.attrib['href']:
      continue
    article_name = child.attrib["href"].split('/wiki/')[1]
    article_name = re.sub('_', ' ', article_name)
    article_name = parse.unquote(article_name)
    print(f'{"  " * (len(headers) + 1)}[[{article_name}]]')


import os
import sys
import re

direct = sys.argv[1]
print(sys.version)
list = os.listdir(direct)
for x in list:
    task1 = re.match('file_', x)
    if (task1):
    	print(x)

    task2 = re.match('[a-z]', x)
    if (task2):
    	print(x)

    task3 = re.search('[0-9][0-9][0-9]$', x)
    if (task3):
    	print(x)

    task4 = re.match('^[^_]+$', x)
    if (task4):
    	print(x)


"""
Merge sort sử dụng chiến lược chia để trị
Merge sort là thuật toán sắp xếp đệ quy, liên tục chia đôi danh sách.
    - nếu danh sách rỗng hoặc có 1 phần tử, nó đã được sắp xếp
    - nếu danh sách có nhiều hơn 1 phần tử, chúng ta chia đôi danh sách và gọi đệ quy
        merge sort trên 2 nửa
    - Khi 2 nửa đã được sắp xếp thì thực hiện merge 2 nửa đó thành 1 danh sách đã
        được sắp xếp, tiến trình merge lấy 2 danh sách con đã được sắp xếp và kết hợp
        đồng thời sắp xếp chúng thành 1 danh sách đơn

"""

def merge_sort(unsorted_list):

    if len(unsorted_list) <= 1:
        return unsorted_list
    # Find the middle point and devide it
    middle = len(unsorted_list) // 2
    left_list = unsorted_list[:middle]
    right_list = unsorted_list[middle:]

    left_list = merge_sort(left_list)
    right_list = merge_sort(right_list)
    return list(merge(left_list, right_list))

# Merge the sorted halves

def merge(left_half, right_half):

    res = []
    while len(left_half) != 0 and len(right_half) != 0:
        if left_half[0] < right_half[0]:
            res.append(left_half[0])
            left_half.remove(left_half[0])
        else:
            res.append(right_half[0])
            right_half.remove(right_half[0])
    if len(left_half) == 0:
        res = res + right_half
    else:
        res = res + left_half
    return res

unsorted_list = [3, 4, 2, 1, 8, 6, 9, 0, 5, 7]

print(merge_sort(unsorted_list))


def survey(ori_path):
    f = open('%s\poll.txt'%ori_path, 'a', encoding='UTF-8')
    answer = ''
    name = ''

    while True:
        answer = input("프로그래밍이 왜 좋으세요?(종료 입력시 프로그램 종료): ")
        if answer == '종료':
            return
        name = input("이름을 입력하세요: ")

        f.write('[%s] %s\n' % (name, answer))
        print("설문에 응답해 주셔서 감사합니다.")
        print('[%s] %s\n' % (name, answer))

if __name__ == '__main__':
        survey('.')


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# license removed for brevity

import sys
import rospy
from std_msgs.msg import String
from geometry_msgs.msg import Twist
from trajectory_msgs.msg import JointTrajectory, JointTrajectoryPoint
#import tf2_ros

from hsr_image_collector.msg import TakePictureRequestMsg
from image_saver import ImageSaver
from handyman.msg import HandymanMsg as HandyManMsg

class Msg(object):

    def __init__(self):
        self.msg_are_you_ready      = "Are_you_ready?";
        self.msg_setting_completed  = "Setting_completed";
        self.msg_score_received     = "Score";
        self.msg_stop               = "Stop_process";

        self.msg_i_am_ready         = "I_am_ready";
        self.msg_images_captured    = "Images_captured";
        self.msg_object_placed      = "Object_placed"
        self.msg_score_saved        = "Score_saved";
        self.msg_stopped            = "Process_stopped";

class PlacingDataCollection(object):

    def __init__(self):

        self.furniture_type = "lower"

        # def step
        self.step = 0
        self.score = 0
        self.camera_height = 0
        self.num_dir = 1
        self.dir_name = "ponNet%s" % self.num_dir
        self.strategy  = 0
        self.max_vel = 0

        #def max number of images per directory
        self.max_images_dir = 100
        self.img_in_dir = 0

        # def arm joint trajectory
        self.arm_joint_trajectory = JointTrajectory()
        self.arm_joint_names = [ 'arm_lift_joint', 'arm_flex_joint', 'arm_roll_joint', 'wrist_flex_joint', 'wrist_roll_joint' ]
        self.arm_joint_point = JointTrajectoryPoint()
        self.arm_joint_trajectory.joint_names = self.arm_joint_names
        self.arm_joint_trajectory.points.append(self.arm_joint_point)

        # def head joint trajectory
        self.head_joint_trajectory = JointTrajectory()
        self.head_joint_names = [ 'head_tilt_joint', 'head_pan_joint']
        self.head_joint_point = JointTrajectoryPoint()
        self.head_joint_trajectory.joint_names = self.head_joint_names
        self.head_joint_trajectory.points.append(self.head_joint_point)

        # def gripper joint trajectory
        self.gripper_joint_trajectory = JointTrajectory()
        self.gripper_joint_names = ['hand_l_proximal_joint', 'hand_r_proximal_joint']
        self.gripper_joint_point = JointTrajectoryPoint()
        self.gripper_joint_trajectory.joint_names = self.gripper_joint_names
        self.gripper_joint_trajectory.points.append(self.gripper_joint_point)

        # def status flags
        self.start = None
        self.finished = None
        self.failed = None

        # def msgs
        self.msg = Msg()

        # def topic names
        self.sub_msg_to_robot_topic_name = "/handyman/message/to_robot"
        self.pub_msg_to_moderator_topic_name = "/handyman/message/to_moderator"
        self.pub_arm_trajectory_topic_name = "/hsrb/arm_trajectory_controller/command"
        self.pub_gripper_trajectory_topic_name = "/hsrb/gripper_trajectory_controller/command"
        self.pub_head_trajectory_topic_name = "/hsrb/head_trajectory_controller/command"
        self.pub_base_twist_topic_name = "/hsrb/opt_command_velocity"

        # def subscriber
        self.msg_robot_subscriber = rospy.Subscriber(self.sub_msg_to_robot_topic_name, HandyManMsg, self.msg_to_robot_callback)

        # def publisher
        self.msg_publisher = rospy.Publisher(
            self.pub_msg_to_moderator_topic_name, HandyManMsg, queue_size=10)

        self.arm_trj_publisher = rospy.Publisher(
            self.pub_arm_trajectory_topic_name, JointTrajectory, queue_size=10)

        self.gripper_trj_publisher = rospy.Publisher(
            self.pub_gripper_trajectory_topic_name, JointTrajectory, queue_size=10)

        self.head_trj_publisher = rospy.Publisher(
            self.pub_head_trajectory_topic_name, JointTrajectory, queue_size=10)

        self.base_twist_publisher = rospy.Publisher(
            self.pub_base_twist_topic_name, Twist, queue_size=10)

        self.image_saver = ImageSaver()

        self.output_dir = self.image_saver.set_directory(self.dir_name)

        self.reset()

    def reset(self):
        self.start = False
        self.finished = False
        self.failed = False

        head_pos = [ 0.0, 0.0 ]
        self.head_joint_trajectory.points[0].positions = head_pos

        gripper_pos = [ 0.0, 0.0 ]
        self.gripper_joint_trajectory.points[0].positions = gripper_pos

################ RECEIVE MESSAGE ##################
    def msg_to_robot_callback(self, ros_data):
        # parse ros_data
        message = ros_data.message
        detail = ros_data.detail
        if message == self.msg.msg_are_you_ready:
            if self.step == 0:
                rospy.loginfo('ARE YOU READY?')
                self.start = True
                self.step += 1

        if message == self.msg.msg_setting_completed:
            if self.step == 2:
                meta = detail.split("-")
                if meta[0] == "L":
                    self.furniture_type = "lower"
                else :
                    self.furniture_type = "upper"
                self.camera_height = meta[1]
                self.strategy = int(meta[2])
                rospy.loginfo('SETTING COMPLETED')
                rospy.loginfo('CAMERA HEIGHT RECEIVED: %s' % self.camera_height)
                rospy.loginfo("STRATEGY RECEIVED %s" % self.strategy)
                self.step += 1

        if message == self.msg.msg_score_received:
            if self.step == 7:
                #rospy.loginfo(detail)
                sc = detail.split("-")
                self.score = sc[0]
                self.max_vel = sc[1]
                self.target = sc[2]
                rospy.loginfo('SCORE RECEIVED: %s' % self.score)
                rospy.loginfo('Target RECEIVED: %s' % self.target)
                rospy.loginfo('MAX Velocity RECEIVED: %s' % self.max_vel)
                self.step += 1

        if message == self.msg.msg_stop:
            rospy.loginfo('STOPPING')
            self.step = 9

################ SEND MESSAGE ##################
    def send_message(self, msg):
         #rospy.loginfo('Send message: %s' % msg)
         handyman_msg = HandyManMsg()
         handyman_msg.message = msg
         self.msg_publisher.publish(handyman_msg)

############### ROBOT CONTROL ###################                           OK

    def move_arm(self, positions, duration):
        #rospy.loginfo('call move_arm')
        try:
            self.arm_joint_trajectory.points[0].positions = positions
            self.arm_joint_trajectory.points[0].time_from_start = duration
            self.arm_trj_publisher.publish(self.arm_joint_trajectory)
        except Exception as e:
            rospy.logerr('failed to moving arm')
            rospy.logerr(e)
            rospy.logerr(type(e))

    def move_head(self, positions, duration):
        #rospy.loginfo('call move_head')
        try:
            self.head_joint_trajectory.points[0].positions = positions
            self.head_joint_trajectory.points[0].time_from_start = duration
            self.head_trj_publisher.publish(self.head_joint_trajectory)
        except Exception as e:
            rospy.logerr('failed to moving head')
            rospy.logerr(e)
            rospy.logerr(type(e))

    def move_base(self, l_x, l_y, l_z, a_x, a_y, a_z):
        #rospy.loginfo('call move_base')
        try:
            twist = Twist()
            twist.linear.x = l_x
            twist.linear.y = l_y
            twist.linear.z = l_z
            twist.angular.x = a_x
            twist.angular.y = a_y
            twist.angular.z = a_z
            self.base_twist_publisher.publish(twist)
        except Exception as e:
            rospy.logerr(e)
            rospy.logerr(type(e))

    def stop_base(self):
        #rospy.loginfo('call stop_base')
        self.move_base(0, 0, 0, 0, 0, 0)

    def goto_strategy(self):
        #For strategies 1-4 (2 is default position)
        #rospy.loginfo("GOTO %s " % self.strategy)
        if self.strategy == 1 :
            self.move_base(0.0, 1.0, 0.0, 0, 0, 0)
            rospy.sleep(rospy.Duration(1.2))
        elif self.strategy == 2:
            return

        elif self.strategy == 3 :
            self.move_base(0.0, -1.0, 0.0, 0, 0, 0)
            rospy.sleep(rospy.Duration(0.8))

        elif self.strategy == 4 :
            self.move_base(0.0, -1.0, 0.0, 0, 0, 0)
            rospy.sleep(rospy.Duration(1.8))
        self.stop_base()

    def close_hand(self):
        """
        closing hand
        """

        rospy.loginfo('call close_hand')
        try:
            duration = rospy.Duration()
            duration.secs = 1
            gripper_pos = [-0.01, 0.01]
            self.gripper_joint_trajectory.points[0].positions = gripper_pos
            self.gripper_joint_trajectory.points[0].time_from_start = duration
            self.gripper_trj_publisher.publish(self.gripper_joint_trajectory)
            rospy.sleep(rospy.Duration(1.5))
        except Exception as error:
            rospy.logerr(error)
            rospy.logerr(type(error))

    def open_hand(self):

        rospy.loginfo('call open_hand')
        try:
            duration = rospy.Duration()
            duration.secs = 1
            gripper_pos = [0.611, -0.611]
            self.gripper_joint_trajectory.points[0].positions = gripper_pos
            self.gripper_joint_trajectory.points[0].time_from_start = duration
            self.gripper_trj_publisher.publish(self.gripper_joint_trajectory)
            rospy.sleep(rospy.Duration(0.5))
        except Exception as error:
            rospy.logerr('failed to open hand')
            rospy.logerr(error)
            rospy.logerr(type(error))

    def set_arm_position(self, position):
        if position == "default":
            self.move_arm([0, 0, 0, -1.57, 0], rospy.Duration(1))

        elif position == "capturing_lower":
            self.move_arm([0, 0, 1.57, -1.57, 0], rospy.Duration(1))

        elif position == "grasping_lower":
            #self.close_hand()
            self.move_arm([0.155, -1.57, 0, 0, 0], rospy.Duration(1))
            rospy.sleep(rospy.Duration(2))
            self.open_hand()
            self.move_arm([0.25, -1.57,  0, 0, 0], rospy.Duration(1))

        elif position == "capturing_upper":
            self.move_arm([0.25, 0, 1.57, -1.57, 0], rospy.Duration(1))

        elif position == "grasping_upper":
            #self.close_hand()
            self.move_arm([0.42, -1.57, 0, 0, 0], rospy.Duration(1))
            rospy.sleep(rospy.Duration(2))
            self.open_hand()
            self.move_arm([0.5, -1.57, 0, 0, 0], rospy.Duration(1))

        rospy.sleep(rospy.Duration(2))
        self.ready_for_capture = True

    def set_head_position(self, position):
        if position == "default":
            self.move_head([0, 0], rospy.Duration(1))
        elif position == "capturing_lower":
            self.move_head([-0.55, 0.0], rospy.Duration(1))
        elif position == "capturing_upper":
            self.move_head([-0.35, 0.0], rospy.Duration(1))
        self.set_arm_position(position)

    def set_capturing_position(self):
        self.open_hand()
        if self.furniture_type == "lower":
            self.set_head_position("capturing_lower")
        else:
            self.set_head_position("capturing_upper")

    ###############################################################################

    def capturing(self):
        if self.ready_for_capture:
            if(self.img_in_dir >= self.max_images_dir):
                self.num_dir += 1
                self.dir_name = "ponNet%s" % self.num_dir
                self.output_dir = self.image_saver.set_directory(self.dir_name)
                self.img_in_dir = 0

            self.image_saver.save_img('rgb')
            self.image_saver.save_img('depth')
            self.score_file = open('%s/y-%s.txt' % (self.output_dir, self.num_dir), "a")
            self.metadata_file = open('%s/meta-%s.txt' % (self.output_dir, self.num_dir), "a")
            #self.img_in_dir += 1
            rospy.sleep(rospy.Duration(1))
            self.step += 1

    def save_score(self):
        self.score_file.write(self.score + "\n")
        self.score_file.close()
        self.save_metadata()

    def save_metadata(self):
        rospy.loginfo("Saving metadata...")
        self.metadata_file.write(self.camera_height + ":" + self.target + ":" + self.score + ":" + self.max_vel + ":" + str(self.strategy) +"\n")
        self.metadata_file.close()

    def capture_end(self):
        self.image_saver.save_img('rgb-final')
        self.image_saver.save_img('depth-final')
        self.img_in_dir += 1

    def run(self):
        rospy.init_node('PlacingDataCollection', anonymous=True)
        rospy.loginfo('Placing Data Collection start!')
        r = rospy.Rate(10) # 10hz

        while not rospy.is_shutdown():
            if self.failed:
                rospy.loginfo('Process Failed')
                self.step =0

            # Initialize
            rospy.sleep(1.)
            if self.step == 0:
                print("Waiting to start")

            # Ready
            elif self.step == 1:
                rospy.loginfo('I am ready')
                self.open_hand()
                self.send_message(self.msg.msg_i_am_ready)
                self.step += 1

            # WaitForCompleted
            elif self.step == 2:
                rospy.loginfo("Waiting for setting completed")

            # GoToPosition
            elif self.step == 3:
                self.ready_for_capture = False
                self.set_capturing_position()
                self.step += 1

            # CaptureImages
            elif self.step == 4:
                rospy.loginfo("Capturing images")
                self.capturing()

            # FinishCapturing
            elif self.step == 5:
                rospy.loginfo('Finished capturing images')
                self.send_message(self.msg.msg_images_captured)
                self.close_hand()
                self.goto_strategy()
                self.step += 1

            #Moving to place object
            elif self.step == 6:
                if self.furniture_type == "lower":
                    self.set_arm_position("grasping_lower")  #For lower furniture
                else:
                    self.set_arm_position("grasping_upper")  #For upper furniture
                self.set_capturing_position()
                self.send_message(self.msg.msg_object_placed)
                self.step += 1

            # WaitForScore
            elif self.step == 7:
                rospy.loginfo("Waiting for score")

            # ScoreSaved
            elif self.step == 8:
                rospy.loginfo("SAVING FINAL IMAGE")
                self.capture_end()
                self.save_score()
                rospy.loginfo('Score saved')
                self.send_message(self.msg.msg_score_saved)
                self.step = 0

            # StopProcess
            elif self.step == 9:
                rospy.loginfo('Stopped')
                self.send_message(self.msg.msg_stopped)
                self.step += 1

            # ProcessFinished
            elif self.step == 10:
                #if self.finished:
                rospy.loginfo('Process Finished')
                self.step = 0

if __name__ == '__main__':
    try:
        placing = PlacingDataCollection()
        placing.run()
    except rospy.ROSInterruptException: pass


from lms.models import StudentCourse

import os
from django.conf import settings
import csv

delete_record_ids = []
with open(os.path.join(settings.BASE_DIR, "scripts/new/lms/student_course_duplicates.csv"), 'r') as file:
    csv_data = csv.reader(file)

    for row in csv_data:
        # id,student,student_name,courses_id,course,count
        try:
            student_id = row[1]
            course_id = row[3]
            print(student_id, course_id)
            if StudentCourse.objects.filter(student_id=student_id, course_id=course_id).count() > 1:
                get_non_subscribe_record = StudentCourse.objects.filter(student_id=student_id, course_id=course_id, subscription_on=None)
                for record in get_non_subscribe_record:
                    delete_record_ids.append(record.id)
                    record.delete()
        except Exception as e:
            print(row, e)
print(len(delete_record_ids))
#print(delete_record_ids)


#!/usr/bin/python3
""" Holds class Review """
from models.base_model import BaseModel, Base
from os import getenv
from sqlalchemy import Column, String, ForeignKey
from sqlalchemy.orm import relationship

class Review(BaseModel, Base):
    """ Representation of Review """
    if getenv('HBNB_TYPE_STORAGE') == 'db':
        __tablename__ = 'reviews'
        text = Column(String(1024))
        place_id = Column(String(60), ForeignKey('places.id'))
        user_id = Column(String(60), ForeignKey('users.id'))
    else:
        text = ""
        place_id = ""
        user_id = ""

    def __init__(self, *args, **kwargs):
        """ Initializes Review """
        super().__init__(*args, **kwargs)


import RobotsTools as rt

outputFile = f"{rt.dataLocation}/output.txt"
varFile = f"{rt.dataLocation}/var.ini"
rt.logFile(outputFile)
rt.setLogSettings(False)
rt.createConfigFile(varFile)

#
#      Function
#

class Function:
    def __init__(self, textSplit):
        if textSplit[0] == "print":
            Function.fprint(textSplit)
        elif textSplit[0] == "add":
            Function.fadd(textSplit)
        elif textSplit[0] == "sub":
            Function.fsub(textSplit)
        elif textSplit[0] == "var":
            Function.fvar(textSplit)

    def fprint(textSplit):
        print(" ".join(textSplit[1:]))
        rt.log(" ".join(textSplit[1:]))

    def fadd(textSplit):
        if textSplit[2] == "and":
            print(eval(f"{int(textSplit[1])} + {int(textSplit[3])}"))
            rt.log(eval(f"{int(textSplit[1])} + {int(textSplit[3])}"))
        else:
            print("""missing the "and" after add""")

    def fsub(textSplit):
        if textSplit[2] == "and":
            print(eval(f"{int(textSplit[1])} - {int(textSplit[3])}"))
            rt.log(eval(f"{int(textSplit[1])} - {int(textSplit[3])}"))
        else:
            print("""missing the "and" after sub""")

    def fvar(textSplit):
        rt.addToConfigFile(varFile, " ".join(textSplit[1:]), textSplit[1])

###################################
#               RUN
###################################

def run(text, Line):
    Lexer(text, Line)

###################################
#               TokenTypes
###################################

keywords = ["input", "for", "print"]
#with open("keywords.txt", 'r') as keywordsfile:
#    keylines = keywordsfile.readlines()
#
#keyline = "".join(keylines)
#keywords = keyline.split("|")

operators = ["+", "-", "*", "/", "="]
varlist = ["int", "str", "bool"]

###################################
#               Operators
###################################

operatorsx = ["+", "-", "*", "/", "//", "**", "<", ">", "%", "=", "+=", "-=", "%=", "*=", "/=", "//=", "**/", "&=", "|=", "^=", ">>=", "<<=", "==", "!=", "<=", ">="]
parenthesis = ["(", ")"]

class Operators:
    def __init__(self, textTokens, textSplit, Line):
        pass

###################################
#               Lexer
###################################

class Lexer:
    def __init__(self, text, Line):
        self.text = text
        self.textSplit = text.split()

        Function(self.textSplit)
        rt.log(self.textSplit)

def runShell():
    Line = 0

    rt.truncateLogFile(outputFile)

    while True:
            text = input('shell > ')
            run(text, Line)
            Line = Line + 1


# TASK 6
# 1. Declare two numbers with any values
# 2. Check if the first number is greater than 50 and check if the second number is less than 100,
#    if True print out "Evaluation is True"
# 3. Add an else block that prints "Evaluation is False"
# 4. Declare a string with value "python"
# 5. Check if the first string is equal to "testify" or "python", if True prints out "Yay!!
#    The string is a Testify Python".

# Note: Use the logical and to check if the first number is greater than 50 and the second number is less than 100

# 1.
score1 = 65
score2 = 135

# 2. and 3.
if score1 > 50:
    print("Evaluation is True")
else:
    print("Evaluation is False")

if score2 < 100:
    print("Evaluation is True")
else:
    print("Evaluation is False")

# 4.
string1 = "python"
string2 = "testify"

if string1 == string2:
    print("Yay!! The string is a Testify Python")
else:
    print("No!! The string is not a Testify Python")


import asyncio
import socket
import json
import pathlib
import os
import platform
import cv2 as cv
from google_images_download import google_images_download
from pdd_prep_data import Prep_Class
import xml_to_csv

CWD = '/home/furoki_sama/projects/machinevision-server/'

class Obj():
    def __init__(self, name, info_data):
        self.info_data = info_data
        self.name = str(name)

    def save(self, dir):
        if not pathlib.Path('{}'.format(dir)).exists():
            os.makedirs(str(dir))
        with open('{}/{}.json'.format(dir, self.name), 'w+') as outfile:
            json.dump(self.info_data, outfile)
            pass

def readNparseObject(id):
    if not pathlib.Path(CWD+'artifact_objects').exists():
        return """No atrifact_objects dir , can't read Object """
    if not pathlib.Path(CWD+'artifact_objects/{id}.json'.format(id=id)).exists():
        return """No such file , can't read Object """
    with open(CWD+'artifact_objects/{id}.json'.format(id=id)) as f:
        object_Data = json.load(f)
    return object_Data

def dwn_web_img(request, count_urls, offset):
    response = google_images_download.googleimagesdownload()

    arguments = {
        "keywords": str(request), "limit": count_urls, "print_urls": False, "offset": offset,
        'no_download': True, "extract_metadata": True
    }
    if platform.system() != 'Windows':
        arguments['chromedriver'] = '/usr/lib/chromium-browser/chromedriver'

    response.download(arguments)

def get_my_ipv4():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(('8.8.8.8', 80))
    res = s.getsockname()[0]
    s.close()
    return res

async def handle_echo(reader, writer):

    databytes = bytearray()
    while True:
        buffData = await reader.read(100)
        if not buffData:
            break
        databytes += buffData

    data = databytes.decode('utf-8')

    if data != '':
        print('[SERVER] Received data from client' + ':\n\t' + data)
    if data is not None:
        try:
            recvdata = json.loads(data)
        except:
            recvdata = {'reqimg': None, 'query': None, 'rtcount': None, 'offset': None}
    else:
        recvdata = []
    try:
        request = recvdata['request_code']
    except Exception:
        request = 'None'

    if request == 'reqimg':
        print('Waiting....')
        # time.sleep(5)
        try:
            offset = int(recvdata['offset'])
        except KeyError:
            offset = 0
        print('\tquery:{}\trtcount:{}'.format(recvdata['query'], recvdata['rtcount']))
        dwn_web_img(recvdata['query'], int(recvdata['rtcount']) + offset, offset + 1)
        with open('logs/{}.json'.format(recvdata['query'])) as f:
            meta_json = json.loads(f.read())
        response = {
            "response_code": "query_metadata",
            "metadata": meta_json
        }
        response = json.dumps(response)
        print('[SERVER] Sending:\n\t{}'.format(response))
        writer.write(bytes(response, 'utf-8'))
        await writer.drain()
        print('[SERVER] Success')

    elif request == 'list_objects':
        obj_list = []
        path_to_artobj = CWD+'artifact_objects'
        path_check = os.path.exists(path_to_artobj)
        if not path_check:
            print('[SERVER]no such dir')
        else:
            for filename in os.listdir(path_to_artobj+'/'):
                # obj_list.append(filename)
                with open(path_to_artobj+'/{}'.format(filename), 'r') as file_json:
                    obj_list.append(json.load(file_json))
                    file_json.close()
        response = {
            'answer_code': 'list_objects',
            'objects': obj_list
        }
        writer.write(bytes(json.dumps(response), 'utf-8'))
        await writer.drain()

    elif request == 'new_object':
        new_obj = Obj(name=recvdata['artifact_object']['id'], info_data=recvdata['artifact_object'])
        new_obj.save('artifact_objects')
        writer.write(b'success')
        await writer.drain()

    elif request == 'delete_object':
        try:
            os.remove('/home/furoki_sama/projects/machinevision-server/artifact_objects/{}.json'.format(recvdata['id']))
            writer.write(b'success')
            await writer.drain()
        except:
            pass

    elif request == 'train_model':
        obj_data = readNparseObject(recvdata['object_id'])
        name = obj_data['title']
        id = recvdata['object_id']
        # repr(obj_data)
        print(obj_data)
        # obj_data['status'] = 1
        Obj(recvdata['object_id'], obj_data).save('artifact_objects')
        print(id)
        prep_data = Prep_Class(name, id)
        prep_data.init_dirs()
        prep_data.img_from_link('new')
        prep_data.separate_img()
        prep_data.gen_labelmap_file()
        # prep_data.making_xmls('train')
        # prep_data.making_xmls('test')
        xml_to_csv.do_this(name)
        train = '--csv_input=prep_data/{a}/data/train_labels.csv --image_dir=prep_data/{a}/models/model/train --output_path=prep_data/{a}/data/train.record'.format(a=name)
        eval = '--csv_input=prep_data/{a}/data/test_labels.csv --image_dir=prep_data/{a}/models/model/test --output_path=prep_data/{a}/data/test.record'.format(a=name)
        os.system('python3 generate_tfrecords.py '+train)
        os.system('python3 generate_tfrecords.py '+eval)
        prep_data.gen_pipeline()
        print('[SERVER] Data is ready')
        print('[RUN BASH]')
        # obj_data['status'] = 2
        # obj_data['lastActType'] = 2
        # obj_data['lastAct'] = int(round(time.time() * 1000))
        Obj(recvdata['object_id'], obj_data).save('artifact_objects')
        writer.write(b'success')
        await writer.drain()
        # task = asyncio.ensure_future(prep_data.gen_train_run_bash_and_run())
    else:
        pass
    # print("Send: %r" % message)
    # writer.write(data)
    # await writer.drain()

    # print("Close the client socket")
    writer.close()

loop = asyncio.get_event_loop()
coro = asyncio.start_server(handle_echo,get_my_ipv4(), 1337, loop=loop)
server = loop.run_until_complete(coro)

# Serve requests until Ctrl+C is pressed
print('Serving on {}'.format(server.sockets[0].getsockname()))
try:
    loop.run_forever()
except KeyboardInterrupt:
    pass

# Close the server
server.close()
loop.run_until_complete(server.wait_closed())
loop.close()


try:
    import pymongo

    client=pymongo.MongoClient("mongodb://127.0.0.1:27017")
    mydb=client["b9"]

    student=mydb["KIT_student"]

    data={'id':31,'name':'sovankoko','age':22}

    student.insert_one(data)
    print('completed')
except Exception as e:
    print('error',e)


NBAurls = []
MLBurls = []
finalImageList = []
MLBImageList = []
NBAImageList = []
NHLImageList = []
NHLurls = []

from bs4 import BeautifulSoup
import requests

NFLURL = "https://www.nfl.com/news/all-news"

page = requests.get(NFLURL)
soup = BeautifulSoup(page.content, "html.parser")
images = soup.find_all('img')
imageList = []

section = soup.find_all('a')

co = 0
unfilteredNFLURLDict = {}
for link in section:
  try:
     fig = link.find('figure')
     pic = fig.find('picture')
     img = pic.find('img')
     image = img.get('src')
     image = image.replace("/t_lazy","")
     unfilteredNFLURLDict['https://www.nfl.com' + link.get('href')] = image

  except:
     co = co + 1

NFLurls = list(unfilteredNFLURLDict.keys())

finalImageList = list(unfilteredNFLURLDict.values())

#print(NFLurls)
#print('\n')
NBAURL = 'https://www.nba.com/news/category/top-stories'
page2 = requests.get(NBAURL)
soup2 = BeautifulSoup(page2.content, "html.parser")

divTag = soup2.find('div', {'class': 'lg:pr-3 lg:w-3/4'})
uList = divTag.find('ul')
list = uList.find_all('li')
for li in list:
  div = li.find('div')
  article = div.find('article')
  aTag = article.find('a')
  NBAurls.append('https://www.nba.com' + aTag.get('href'))
  div2 = aTag.find('div')
  fig = div2.find('figure')
  img = fig.find('img')
  NBAImageList.append(img.get('src'))
#print(NBAurls)

unfilteredMLB = {}
MLBURL = "https://www.cbssports.com/mlb/"
page3 = requests.get(MLBURL)
soup3 = BeautifulSoup(page3.content, "html.parser")
ul = soup3.find('ul',{'tournament-latest-news load-more-content-wrapper'})
divTag = ul.find('div',{'data-component':'loadMore'})
rows = divTag.find_all('ul',{'class':'row article-list-pack-row'})

for row in rows:
   l = row.find_all(['li'])
   for li in l:
      div = li.find('div',{'class','article-list-pack-image'})
      aTag = div.find('a')

      theUrl = 'https://www.cbssports.com' + aTag.get('href')

      fig = aTag.find('figure',{'class':'img'})
      image = fig.find('img')
      src = image.get('data-lazy')
      MLBImageList.append(src)
      MLBurls.append(theUrl)

unfilteredNHL = {}
NHLurl = 'https://www.cbssports.com/nhl/'
page4 = requests.get(NHLurl)
soup4 = BeautifulSoup(page4.content, "html.parser")
ul = soup4.find('ul',{'arena-pack-list-wrapper load-more-content-wrapper'})
divTag = ul.find('div',{'data-component':'loadMore'})
rows = divTag.find_all('ul',{'class':'row article-list-pack-row'})

for row in rows:
   l = row.find_all(['li'])
   for li in l:
      try:
         div = li.find('div',{'class','article-list-pack-image'})
         aTag = div.find('a')

         theUrl = 'https://www.cbssports.com' + aTag.get('href')

         fig = aTag.find('figure',{'class':'img'})
         image = fig.find('img')
         src = image.get('data-lazy')
         NHLImageList.append(src)
         NHLurls.append(theUrl)

      except AttributeError:
         x = 5


import cv2
import sys
import scipy.misc

FACE_CASCADE_PATH = "../resources/haarcascade_frontalface_default.xml"
FACE_PROFILE_CASCADE_PATH = '../resources/haarcascade_profileface.xml'
EYE_CASCADE_PATH = cv2.CascadeClassifier("../resources/haarcascade_eye.xml")

faceCascade = cv2.CascadeClassifier(FACE_CASCADE_PATH)
profileFaceCascade = cv2.CascadeClassifier(FACE_PROFILE_CASCADE_PATH)
video_capture = cv2.VideoCapture(0)

div = 0.25

while True:
    # Capture frame-by-frame
    ret, fullFrame = video_capture.read()
    frame = fullFrame
    #frame = cv2.resize(fullFrame, (fullFrame.shape[1]/div, fullFrame.shape[0]/div))

    frame = cv2.resize(fullFrame,None,fx=div, fy=div, interpolation = cv2.INTER_LINEAR)

    print("Full: " + str(fullFrame.shape))
    print("Small: " + str(frame.shape))

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    faces = faceCascade.detectMultiScale(
        gray,
        scaleFactor=1.1,
        minNeighbors=5,
        minSize=(25, 25),
        flags=cv2.cv.CV_HAAR_SCALE_IMAGE
    )

    facesProfiles = profileFaceCascade.detectMultiScale(
        gray,
        scaleFactor=1.1,
        minNeighbors=5,
        minSize=(25, 25),
        flags=cv2.cv.CV_HAAR_SCALE_IMAGE
    )

    # Draw a rectangle around the faces
    for (x, y, w, h) in faces:
        print("Face: " + str((x, y, w, h)))
        cv2.rectangle(fullFrame, (int(x/div), int(y/div)), (int(x/div+w/div), int(y/div+h/div)), (0, 255, 0), 4)

        roi_gray = gray[y:y+h, x:x+w]
        roi_color = fullFrame[int(y/div):int(y/div+h/div), int(x/div):int(x/div+w/div)]

        eyes = eye_cascade.detectMultiScale(roi_gray,
            scaleFactor=1.1,
            minNeighbors=2,
            minSize=(w/6, h/6),
            flags=cv2.cv.CV_HAAR_SCALE_IMAGE
        )

        for (ex,ey,ew,eh) in eyes:
            cv2.rectangle(roi_color,(int(ex/div),int(ey/div)),(int(ex/div+ew/div),int(ey/div+eh/div)),(255,0,0),4)

    # Display the resulting frame
    cv2.imshow('Video', fullFrame)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()


import os
import sys
import math

try:
    path = sys.argv[1]
    output_file=sys.argv[2]
except:
    print ('path not correct Resetting path to cwd')
    path= os.getcwd()
    output_file='per_output.txt'

print (path)

class avg_perModel:
    def __init__(self):
        self.weights = {}
        self.bias = 0
        self.output={}

    def readModelData(self):
        print('reading file')
        with open("avg_per_model.txt", "r", encoding="latin1") as file:
        #with open('avg_permodel.txt','r') as file:
            data=file.read()
            lines=data.split('\n')

            count=0
            for line in lines:
                parts= line.split('=$#$')
                if count <1:
                    self.__dict__[str(parts[0])]=float(parts[1])
                    print (parts[0],'\t :: \t',parts[1])
                else:
                    self.__dict__[str(parts[0])]=eval(parts[1])
                    #print parts[0],'\t :: \t',parts[1],'\n'
                count = count + 1
            print (len(avg_per.weights))

def outputLabel(dir_path,avg_per):
    try:
        outStream = open(output_file, 'w',encoding="latin1")
        #outStream = open('avg_peroutput.txt', 'w')
        #print (avg_per.output)
        for k,v in avg_per.output.items():
            outStream.write(avg_per.output[k]+' '+k+'\n')
        outStream.close()
        return 'check to avg_peroutput.txt'
    except:
        return '[ERROR] Output to avg_peroutput.txt',sys.exc_info()

def predictTrainingLabels(dir_path):
    #read test directory
    output={}
    num=0
    for dirpath, sdirs, files in os.walk(dir_path):
        for filename in files:
            file_path = os.path.join(dirpath, filename)
            #print file_path,
            if filename.endswith('.txt'):
                #print flag,filename
                spl_char = '!%^_`{|}~"#$&\'()*+,-./:;<=>@[\\]\n'
                # with open(file_path,"r",encoding="latin1") as f:
                with open(file_path,"r") as f:
                    #tokens= map(lambda w: w.strip(spl_char), f.read().split())
                    tokens= map(lambda w: w, f.read().split())
                    alpha = 0
                    # print y,x_d

                word_list={}
                for word in tokens:
                    if word not in word_list:
                        word_list[word] = 1
                    else:
                        word_list[word]=word_list[word]+1
                    if word not in avg_per.weights:
                        avg_per.weights[word] = 0
                #print (len(tokens),len(word_list),len(avg_per.weights))
                for word in word_list:
                    alpha = alpha + (avg_per.weights[word] * word_list[word])
                alpha = alpha + avg_per.bias

                if alpha > 0:
                    label = 'SPAM'
                else:
                    label = 'HAM'
                f_name = os.path.join(dirpath, filename)
                avg_per.output[f_name] = label
                #print avg_per.output

                '''
                    if a_flag.upavg_per()!=label:
                        print 'actual:',a_flag,'predicted:',label,'\tspam',p_spam_msg,'ham',p_ham_msg,'\t',f_name
                '''

print ('Running avg_per_classify')
avg_per=avg_perModel()
avg_per.readModelData()
print ('test data')
predictTrainingLabels(path)
print ('over')
cwd=os.getcwd()
print (outputLabel(cwd,avg_per))


import os
from typing import Callable

directory_to_scan = "./FATURALAR"
file_name_extre = "ekstre.txt"

def read_file(file_name_extre):
    with open(file_name_extre,"r",encoding="cp1254") as f:
        print("dosya okunuyor")
        icerik=f.read()
        print(icerik)
        print("dosya içeriği okundu")
        liste1=icerik.split(",")
        print(liste1)

def parse_invoice(raw_text):
    return "okunmuş:" + raw_text

def read_invoice_file(file_name_invoice ,invoice_parser):
    with open(file_name_invoice,"r",encoding="cp1254") as f:
        print("fatura dosyası okunuyor")
        icerik=f.read()
        print(icerik)
        print("fatura içeriği okundu")
        if isinstance(invoice_parser,Callable):
            liste1=invoice_parser(icerik)
            print(liste1)
        else:
            print(f"parser function değil: {invoice_parser}")

def read_folder(directory_to_scan):
     with os.scandir(directory_to_scan) as tarama:
         for belge in tarama:
             if belge.is_file():
                 read_invoice_file(belge.path,parse_invoice)

if __name__ == "__main__":
    read_file(file_name_extre)
    read_folder(directory_to_scan)


# 1071. Greatest Common Divisor of Strings (leetcode)
class Solution:
    def gcdOfStrings(self, str1: str, str2: str) -> str:
        if len(str2) > len(str1):
            str1, str2 = str2, str1

        l = []
        for i in range(len(str2)):
            for j in range(i + 1, len(str2) + 1):
                a = str2[i:j]
                l.append(a)
        l.sort(key=len)
        l = l[::-1]
        # print(l)
        x = ""
        for i in l:
            if i in str1:
                a = str1.count(i)
                b = str2.count(i)
                if len(str1) == (len(i) * a) and (len(str2) == (len(i) * b)):
                    x = i
                    break
        return x


import logging
import os
import subprocess
from concurrent.futures.thread import ThreadPoolExecutor

import cyvcf2
from django.conf import settings
from django.core.cache import cache

from library.genomics.vcf_utils import vcf_get_ref_alt_end
from library.utils.file_utils import name_from_filename, mk_path
from snpdb import variant_collection
from snpdb.models import VariantCoordinate
from snpdb.variant_pk_lookup import VariantPKLookup
from upload.models import UploadStep, UploadStepTaskType, VCFPipelineStage
from upload.tasks.vcf.import_vcf_step_task import ImportVCFStepTask
from upload.vcf import sql_copy_files
from variantgrid.celery import app

USE_THREADS = True

def handle_unknown_variants(upload_pipeline, unknown_variants, unknown_variants_filename):
    sql_copy_files.write_sql_copy_csv(unknown_variants, unknown_variants_filename)

    name = UploadStep.CREATE_UNKNOWN_LOCI_AND_VARIANTS_TASK_NAME
    sort_order = upload_pipeline.get_max_step_sort_order() + 1
    upload_step = UploadStep.objects.create(upload_pipeline=upload_pipeline,
                                            name=name,
                                            sort_order=sort_order,
                                            task_type=UploadStepTaskType.CELERY,
                                            pipeline_stage=VCFPipelineStage.INSERT_UNKNOWN_VARIANTS,
                                            input_filename=unknown_variants_filename,
                                            items_to_process=len(unknown_variants))
    upload_step.launch_task(InsertUnknownVariantsTask)

class BulkUnknownVariantInserter:

    def __init__(self, upload_step):
        self.upload_step = upload_step
        self.unknown_dir = upload_step.upload_pipeline.get_pipeline_processing_subdir("vcf_unknown")
        self.rows_processed = 0
        self.unknown_variants_batch_id = 0
        self.executor = ThreadPoolExecutor(max_workers=1)
        self.child_futures = []
        self.variant_pk_lookup = VariantPKLookup(upload_step.genome_build)

    def process_vcf_record(self, variant):
        # Pre-processed by vcf_filter_unknown_contigs so only recognised contigs present
        # This has been decomposed (only be 1 alt per line)
        ref, alt, end = vcf_get_ref_alt_end(variant)
        variant_coordinate = VariantCoordinate(chrom=variant.CHROM, start=variant.POS, end=end, ref=ref, alt=alt)
        self.variant_pk_lookup.add(variant_coordinate)
        self.batch_process_check()

    def finish(self):
        self.batch_process_check(insert_all=True)

        # Make sure all child threads returned ok
        for f in self.child_futures:
            f.result()

    def batch_process_check(self, insert_all=False):
        if insert_all:
            minimum_size = 0
        else:
            minimum_size = settings.SQL_BATCH_INSERT_SIZE

        self.variant_pk_lookup.batch_check(minimum_size)

        # Unknown variants
        num_unknown_variants = len(self.variant_pk_lookup.unknown_variant_coordinates)
        if num_unknown_variants and num_unknown_variants >= minimum_size:
            uv_basename = f"unknown_variants_step_{self.upload_step.pk}_batch_{self.unknown_variants_batch_id}.csv"
            unknown_variants_filename = os.path.join(self.unknown_dir, uv_basename)
            huv_args = (self.upload_step.upload_pipeline, self.variant_pk_lookup.unknown_variant_coordinates,
                        unknown_variants_filename)

            if USE_THREADS:
                future = self.executor.submit(handle_unknown_variants, *huv_args)
                self.child_futures.append(future)
            else:
                handle_unknown_variants(*huv_args)

            self.variant_pk_lookup.clear()
            self.unknown_variants_batch_id += 1

class SeparateUnknownVariantsTask(ImportVCFStepTask):
    """ This is run on split VCF file.
        If it finds unknown, it writes files and launches InsertUnknownVariantsTask on them """

    def process_items(self, upload_step):
        bulk_inserter = BulkUnknownVariantInserter(upload_step)

        vcf_reader = cyvcf2.VCF(upload_step.input_filename)
        for v in vcf_reader:
            bulk_inserter.process_vcf_record(v)

        bulk_inserter.finish()  # Any leftovers
        variant_collection.count = bulk_inserter.rows_processed
        return bulk_inserter.rows_processed

class AnnotateImportedVCFTask(ImportVCFStepTask):
    """ Indexes then annotates the VCF """
    def process_items(self, upload_step):
        cmd_index = ['bcftools', 'index', upload_step.input_filename]
        subprocess.run(cmd_index, capture_output=True, check=True)

        common_settings = settings.VCF_IMPORT_COMMON_FILTERS.get(upload_step.genome_build.name)
        gnomad_af_filename = common_settings["gnomad_af_filename"]
        if not gnomad_af_filename.startswith("/"):
            gnomad_af_filename = os.path.join(settings.ANNOTATION_VEP_BASE_DIR, gnomad_af_filename)
        cmd_annotate = [
            "bcftools", "annotate", "-force",
            "--annotations", gnomad_af_filename, "--columns", "AF",
            "--output-type", "z", "--output", upload_step.output_filename,
            upload_step.input_filename
        ]
        subprocess.run(cmd_annotate, capture_output=True, check=True)
        return 1

class InsertUnknownVariantsTask(ImportVCFStepTask):
    """ Loci/Variants may have been inserted since the unknown variants were written, so we need to check
        in this process (which runs under a lock and in variant_id_single_workers so will avoid race conditions """

    def process_items(self, upload_step):
        LOCK_EXPIRE = 60 * 5  # 5 minutes
        LOCK_ID = "insert-unknown-variants-lock"

        if not settings.UPLOAD_ENABLED:
            raise ValueError(f"Uploads disabled, this should not have been called!")

        if cache.add(LOCK_ID, "true", LOCK_EXPIRE):  # fails if already exists
            try:
                return InsertUnknownVariantsTask.process_items_in_lock(upload_step)
            finally:
                logging.info("Releasing %s", LOCK_ID)
                cache.delete(LOCK_ID)
        else:
            logging.info("Someone else is doing the import")

    @staticmethod
    def process_items_in_lock(upload_step):
        logging.info("InsertUnknownVariantsTask.process_items() - %s", upload_step)

        # TODO: Fix this, bit of a hack at the moment....
        input_filename = upload_step.input_filename
        logging.info("file: %s", input_filename)

        pipeline_processing_dir = upload_step.upload_pipeline.get_pipeline_processing_dir()
        working_dir = os.path.join(pipeline_processing_dir, "unknown_variants", name_from_filename(input_filename))
        mk_path(working_dir)

        variant_pk_lookup = VariantPKLookup(upload_step.genome_build, working_dir=working_dir)

        with open(input_filename) as f:
            items_processed = 0
            # Python CSV reader dies with extremely long lines, so we just do by hand (not quoted or anything)
            for line in f:
                chrom, start, end, ref, alt = line.strip().split(",")  # Not quoted, exactly 5 columns
                variant_coordinate = VariantCoordinate(chrom=chrom, start=int(start), end=int(end), ref=ref, alt=alt)
                variant_pk_lookup.add(variant_coordinate)
                variant_pk_lookup.batch_check(settings.SQL_BATCH_INSERT_SIZE, insert_unknown=True)
                items_processed += 1
            # Any remaining
            variant_pk_lookup.batch_check(insert_unknown=True)
        return items_processed

SeparateUnknownVariantsTask = app.register_task(SeparateUnknownVariantsTask())
AnnotateImportedVCFTask = app.register_task(AnnotateImportedVCFTask())
InsertUnknownVariantsTask = app.register_task(InsertUnknownVariantsTask())


#Vowel and Consonants
vowel=0
cons=0
def check(a):
    n=len(a)
    global vowel
    global cons
    for char in a:
        char=char.lower()
        if char in 'aeiou':
            vowel+=1
            print(f"Letter {char} is vowel")
        elif char >= 'a' and char<= 'z'  :
            cons+=1
            print(f"Letter {char} is consonant")

def main():
    s=input("Enter the string:")
    s.lower()
    check(s)
    print(f"Vowels:{vowel}  \nConsonants{cons}")
main()


from sqlalchemy import Index, MetaData, Table

def upgrade(migrate_engine):
    meta = MetaData()
    meta.bind = migrate_engine

    # Based on migration_get_by_instance_and_status
    # from: nova/db/sqlalchemy/api.py
    t = Table('migrations', meta, autoload=True)
    i = Index('migrations_instance_uuid_and_status_idx', t.c.deleted,
            t.c.instance_uuid, t.c.status)
    i.create(migrate_engine)

def downgrade(migrate_engine):
    meta = MetaData()
    meta.bind = migrate_engine

    t = Table('migrations', meta, autoload=True)
    i = Index('migrations_instance_uuid_and_status_idx', t.c.deleted,
            t.c.instance_uuid, t.c.status)
    i.drop(migrate_engine)


# -*- coding: utf-8 -*-
# @Time    : 2020/5/12 15:06
# @Author  : 张开
# File      : 5. 文件操作.py

import time

from selenium import webdriver

driver = webdriver.Chrome()

driver.get('http://127.0.0.1:8022/upload/1')

time.sleep(1)
driver.find_element_by_id('ajaxFile').send_keys(r'D:\video\s28-testing-day17-接口自动化平台-实现-4\note\dengxin\data\接口测试示例-2.xlsx')
time.sleep(1)
driver.find_element_by_id('ajaxBtn').click()

time.sleep(5)
driver.quit()

选修进阶/python自动化测试/自动化/day18/note/5. 文件操作.py


"""
Fácil Fruit count
Operaciones entre tipos de datos distintos.
===
Proponga una corrección para que el siguiente código se ejecute sin errores e imprima
`Hay 12 frutas en total.`
"""
peras = 5
manzanas = 7
frutas = peras + manzanas
print('Hay', frutas, 'frutas en total.')
"""
Placeholder:
peras = 5
manzanas = '7'
frutas = peras + manzanas
print('Hay', frutas, 'frutas en total.')
"""


import time
from datetime import datetime
import os
import re

###############################################################################
# redText
# Adds flags to print given text in red color in console.
# - text: the text to be colored
# - return: the text with red color/standard color flags
def redText(text):
	return "\x1b[31m" + str(text) + "\x1b[0m"

###############################################################################
# cyanText
# Adds flags to print given text in cyan color in console.
# - text: the text to be colored
# - return: the text with cyan color/standard color flags
def cyanText(text):
	return "\x1b[36m" + str(text) + "\x1b[0m"

###############################################################################
# getTimestamp
# Returns a previously determined timestamp, or the timestamp of the current point in time
# - refresh [optional]: if True, forcibly retrieves a new timestamp; else, only returns a new timestamp if no previous one is known
# - return: timestamp in the format YY-MM-DD_HH-MM-SS
def getTimestamp(refresh = False):
	global timestamp_var # make this variable static

	try:
		if timestamp_var and refresh == True:
			timestamp_var = datetime.now() # forcibly refresh timestamp
	except NameError:
		timestamp_var = datetime.now() # get timestamp for the first time

	return timestamp_var.strftime("%y-%m-%d_%H-%M-%S")

###############################################################################
# getFormattedTime
# Returns a string indicating the hours, minutes, and seconds of a time given in seconds
# - time_el: time in seconds
# - return: formatted time string
def getFormattedTime(time_el):
	if time_el < 1:
		time_el_str = "<1 s"
	elif time_el < 60:
		time_el_str = f"{time_el} s"
	elif time_el < 3600:
		time_el_str = f"{time_el // 60} m {time_el % 60} s"
	else:
		time_el_str = f"{time_el // 3600} h {(time_el % 3600) // 60} m {(time_el % 3600) % 60} s"

	return time_el_str

###############################################################################
# getTimeDiff
# Returns current timepoint and the time that has passed since a given timepoint
# - t_ref [optional]: reference timepoint
# - return: current timepoint, time difference
def getTimeDiff(t_ref = 0):
	t_cur = time.time()

	return t_cur, t_cur - t_ref

###############################################################################
# setDataPathPrefix
# Sets prefix for the path names used by getDataPath()
# - prefix [optional]: prefix string
def setDataPathPrefix(prefix = ""):
	global data_path_prefix

	data_path_prefix = prefix

###############################################################################
# getDataPath
# Consumes a general description for the simulation and a file description, and returns
# a path to a timestamped file in the output directory;  if no file description is provided,
# returns the path to the output directory
# - sim_description: general description for the simulation
# - file_description [optional]: specific name and extension for the file
# - refresh [optional]: if True, enforces the retrieval of a new timestamp
# - return: path to a file in the output directory
def getDataPath(sim_description, file_description = "", refresh = False):
	global data_path_prefix

	timestamp = getTimestamp(refresh)
	out_path = data_path_prefix + timestamp

	if sim_description != "":
			out_path = out_path + " " + sim_description

	if file_description == "":
		return out_path

	return os.path.join(out_path, timestamp + "_" + file_description)

###############################################################################
# initLog
# Initializes the global log file
# - desc: description in the data path
def initLog(desc):
	global logf

	logf = open(getDataPath(desc, "log.txt"), "w")

###############################################################################
# writeLog
# Writes string(s) to the global log file and prints to the console
# - ostrs: the string(s) to be written/printed
# - prnt [optional]: specifies whether to print to console or not
def writeLog(*ostrs, prnt = True):
	global logf

	for i in range(len(ostrs)):
		ostr = str(ostrs[i])
		ostr = re.sub(r'\x1b\[[0-9]*m', '', ostr) # remove console formatting
		if i == 0:
			logf.write(ostr)
		else:
			logf.write(" " + ostr)
	logf.write("\n")

	if prnt:
		print(*ostrs)

###############################################################################
# writeAddLog
# Writes string(s) to global log file (without printing to the console)
# - ostrs: the string(s) to be written
def writeAddLog(*ostrs):

	writeLog(*ostrs, prnt = False)

###############################################################################
# closeLog
# Close the global log file
def closeLog():
	global logf

	logf.close()

###############################################################################
# getSynapseId
# If provided, returns the synapse identifier for the corresponding neuron identifier in 'sample_gid_list',
# otherwise, returns the generic identifier
# - sample_syn_list: the list of synapse indices (or value -1 to disbale reading)
# - index: pointing at the list element to be considered
# - return: the synapse identifier
def getSynapseId(sample_syn_list, index):

		# get synapse id provided for corresponding neuron in 'sample_gid_list'
		if len(sample_syn_list) > 1:
			sample_syn = sample_syn_list[index]

		# get generic synapse id that has been provided
		else:
			sample_syn = sample_syn_list[0]

		return sample_syn


import os
from pathlib import Path

from dotenv import load_dotenv

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
load_dotenv()

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get("SECRET_KEY")

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ["*"]

CSRF_TRUSTED_ORIGINS = [
    "https://join.istenith.com",
    "http://join.istenith.com",
    "http://0.0.0.0:8081",
]

INSTALLED_APPS = [
    "forms",
    "solo",
    "results",
    "phonenumber_field",
    "adminactions",
    "jazzmin",
    "widget_tweaks",
    "import_export",
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
]

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
]

ROOT_URLCONF = "main.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [
            os.path.join(BASE_DIR, "templates"),
            os.path.join(BASE_DIR, "templates", "jazzmin"),
        ],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
            ],
        },
    },
]

WSGI_APPLICATION = "main.wsgi.application"

# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.sqlite3",
        "NAME": BASE_DIR / "db.sqlite3",
    }
}

# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
    },
]

# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/

LANGUAGE_CODE = "en-us"

TIME_ZONE = "UTC"

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = "/static/"
STATIC_ROOT = os.path.join(BASE_DIR, "static_root")
MEDIA_ROOT = BASE_DIR / "media"
MEDIA_URL = "/media/"

STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),)

JAZZMIN_UI_TWEAKS = {
    "theme": "flatly",
    "navbar": "navbar-dark",
    "dark_mode_theme": "darkly",
}
JAZZMIN_SETTINGS = {
    # title of the window (Will default to current_admin_site.site_title)
    "site_title": "ISTE-NITH",
    # Title on the login screen (19 chars max) (will default to current_admin_site.site_header)
    "site_header": "join.istenith.com",
    # Title on the brand (19 chars max) (will default to current_admin_site.site_header)
    "site_brand": "ISTE-NITH'22",
    "welcome_sign": "Welcome to the admin dashboard. Login to take incharge.",
    # Copyright on the footer
    "copyright": "ISTE-NITH",
    "changeform_format": "horizontal_tabs",
    "site_logo": "images/iste.png",
    "site_logo_classes": "img-circle",
    "topmenu_links": [
        {"name": "Home", "url": "/", "new_window": True},
    ],
}

CRISPY_TEMPLATE_PACK = "bootstrap4"

# SMTP setup
# EMAIL_HOST= 'smtp.gmail.com'
# EMAIL_PORT= 587
# EMAIL_HOST_USER= ''  #email id to be filled
# EMAIL_HOST_PASSWORD= '' # password for same email id!
# EMAIL_USE_TLS= True


from dataclasses import dataclass
from typing import List

from dataclasses_json import dataclass_json

@dataclass_json
@dataclass
class Bar:
    chords: List[str] = None
    beats: int = 4
    division: int = 4
    short: bool = False

    def add_chord(self, chord: str):
        if not self.chords:
            self.chords = list()
        self.chords.append(chord)

    def set_signature(self, beats, division):
        self.beats = beats
        self.division = division

@dataclass_json
@dataclass
class Part:
    bars: List[Bar] = None
    note: str = ""

    def add_bar(self, bar: Bar):
        if not self.bars:
            self.bars = list()

        self.bars.append(bar)

@dataclass_json
@dataclass
class Element:
    name: str
    parts: List[Part] = None
    note: str = ""

    def add_part(self, part: Part):
        if not self.parts:
            self.parts = list()

        self.parts.append(part)

@dataclass_json
@dataclass
class Song:
    title: str
    key: str
    elements: List[Element] = None
    beats: int = 4
    division: int = 4

    def add_element(self, element: Element):
        if not self.elements:
            self.elements = list()

        self.elements.append(element)

    def set_signature(self, beats, division):
        self.beats = beats
        self.division = division


from PIL import Image
from pylab import *

# This plots an image and waits for the user to click three times in the image region of
# the figure window. The coordinates [x, y] of the clicks are saved in a list x.
im = array(Image.open('empire.jpeg'))
imshow(im)
print('Please click 3 points')
x = ginput(3)
print('you clicked:',x)
show()


def min_window_containing_all_chars(s, p):
    char_count = {}
    for char in p:
        char_count[char] = char_count.get(char, 0) + 1

    required_chars = len(char_count)
    formed_chars = 0
    left = right = 0
    min_length = float('inf')
    result_start = 0

    while right < len(s):
        char = s[right]
        if char in char_count:
            char_count[char] -= 1
            if char_count[char] == 0:
                formed_chars += 1

        while formed_chars == required_chars and left <= right:
            if right - left + 1 < min_length:
                min_length = right - left + 1
                result_start = left

            if s[left] in char_count:
                char_count[s[left]] += 1
                if char_count[s[left]] > 0:
                    formed_chars -= 1

            left += 1

        right += 1

    if min_length == float('inf'):
        return "-1"
    return s[result_start:result_start + min_length]

# Example usage
s = "timetopractice"
p = "toc"
result = min_window_containing_all_chars(s, p)
print("Smallest window:", result)  # Output: "toprac"


import pygame
import pygame as pg
import numpy as np
from pygame.locals import *
from escenario import *

class Cartel(pygame.sprite.Sprite):
    #_________________________________________________inicializador
    def __init__(self, x, y, width, height,fuente,numero_de_fotogramas,tasa_fotogramas,instante_de_partida):
        self.letra=""
        #tamaño
        self.x = x
        self.y = y
        #posicion
        self.width = width
        self.height = height
        self.fuente = fuente
        self.numero_de_fotogramas = numero_de_fotogramas
        self.tasa_fotogramas = tasa_fotogramas
        self.instante_de_partida = instante_de_partida
        pygame.font.init()
        temp = pygame.font.Font(None,45)
        self.texto = temp.render(self.letra,0,(0,0,0))
        self.textooriginal=None
        self.textoArmado=None
    #_________________________________________________Cambiar iamgen de boton
    def update_image(self, ui):
        img = pygame.image.load(ui)
        self.image1 = img
        img2 = pg.transform.scale(self.image1, (self.width, self.height))
        self.image2 = img2
    #_________________________________________________Ajustar tamaño de boton
    def update_size(self, width, height):
        self.width = width
        self.height = height
        img2 = pg.transform.scale(self.image1, (self.width, self.height))
        self.image2 = img2
    #_________________________________________________Dibujar Boton
    def draw(self,buff):
        buff.blit(self.image2, (self.x, self.y))
        buff.blit(self.texto,(self.x+50,self.y+50))

    def iniciar_contador(self,screen):
        segundos_totales = self.instante_de_partida - (self.numero_de_fotogramas // self.tasa_fotogramas)
        if segundos_totales < 0:
            segundos_totales = 0
        minutos = segundos_totales // 60
        segundos = segundos_totales % 60
        texto_de_salida = "Tiempo: {0:02}:{1:02}".format(minutos, segundos)
        texto = self.fuente.render(texto_de_salida, True, (0, 0, 0))
        screen.blit(texto, [self.x+60, self.y+20])
        self.numero_de_fotogramas += 1
    def aumentar_palabra(self,temp):
        self.letra+=temp
        pygame.font.init()
        temp = pygame.font.Font(None,30)
        self.texto = temp.render(self.letra,0,(0,0,0))


#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
'''
编写一个程序，打开文件夹中所有的.txt文件，查找匹配用户提供的正则表达式
的所有行。结果应该打印到屏幕上。
'''
import re,os,sys
cwd = os.getcwd()
txtDirList = []

regex1 = re.compile(r'\.txt$')
for sdir in os.listdir(cwd):
	if regex1.search(sdir):
		txtDirList.append(sdir)
print(txtDirList)

print('{} {}'.format(sys.argv[0],sys.argv[1]))
regex2 = re.compile(sys.argv[1])
txtLineList = []

for sdir in txtDirList:
	with open(sdir,'r',encoding='UTF-8') as txtFile:
		txtLineList = txtFile.readlines()
		for l in txtLineList:
			if regex2.search(l):
				print(l)


#
# @lc app=leetcode.cn id=2 lang=python3
#
# [2] 两数相加
#

# @lc code=start
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        dummy = tail = ListNode(0)
        carry = 0
        while l1 or l2 or carry:
            carry += (l1.val if l1 else 0) + (l2.val if l2 else 0)
            dummy.next = ListNode(carry % 10)
            dummy = dummy.next
            carry = carry // 10 # 是否进位
            l1 = l1.next if l1 else None
            l2 = l2.next if l2 else None
        return tail.next
# @lc code=end


import os
import tempfile

from avocado import Test
from avocado.utils import archive
from avocado.utils import process
from avocado.utils import build, distro
from avocado.utils.software_manager.manager import SoftwareManager

class Lmbench(Test):

    """
    lmbench is a series of micro benchmarks intended to measure basic
    operating system and hardware system metrics. The benchmarks fall
    into three general classes: bandwidth, latency, and ``other''.
    """

    def setUp(self):
        '''
        Build lmbench
        Source:
        http://www.bitmover.com/lmbench/lmbench3.tar.gz
        '''
        fsdir = self.params.get('fsdir', default=None)
        temp_file = self.params.get('temp_file', default=None)
        memory_size_mb = self.params.get('MB', default=125)
        self.tmpdir = tempfile.mkdtemp(prefix='avocado_' + __name__)
        smm = SoftwareManager()
        detected_distro = distro.detect()
        packages = ['gcc', 'make', 'patch']
        if detected_distro.name in ['SuSE', 'rhel', 'centos', 'fedora']:
            packages.extend(['libtirpc-devel'])
        elif detected_distro.name == "Ubuntu":
            packages.extend(['libtirpc-dev'])
        for package in packages:
            if not smm.check_installed(package) and not smm.install(package):
                self.cancel("%s is needed for the test to be run" % package)
        tarball = self.fetch_asset('http://www.bitmover.com'
                                   '/lmbench/lmbench3.tar.gz')
        archive.extract(tarball, self.workdir)
        version = os.path.basename(tarball.split('.tar.')[0])
        self.sourcedir = os.path.join(self.workdir, version)

        # Patch for lmbench

        os.chdir(self.sourcedir)

        makefile_patch = 'patch -p1 < %s' % self.get_data('makefile.patch')
        build_patch = 'patch -p1 < %s' % self.get_data(
            '0001-Fix-build-issues-with-lmbench.patch')
        lmbench_fix_patch = 'patch -p1 < %s' % self.get_data(
            '0002-Changing-shebangs-on-lmbench-scripts.patch')
        ostype_fix_patch = 'patch -p1 < %s' % self.get_data(
            'fix_add_os_type.patch')
        lsleek_fix_patch = 'patch -p1 < %s' % self.get_data(
            'fix_lseek.patch')

        process.run(makefile_patch, shell=True)
        process.run(build_patch, shell=True)
        process.run(lmbench_fix_patch, shell=True)
        process.run(ostype_fix_patch, shell=True)
        process.run(lsleek_fix_patch, shell=True)

        build.make(self.sourcedir, extra_args='LDFLAGS=-ltirpc')

        # configure lmbench
        os.chdir(self.sourcedir)

        process.system('yes "" | make config', shell=True, ignore_status=True)

        # find the lmbench config file
        output = os.popen('ls -1 bin/*/CONFIG*').read()
        config_files = output.splitlines()
        if len(config_files) != 1:
            self.error('Config not found : % s' % config_files)
        config_file = config_files[0]
        if not fsdir:
            fsdir = self.tmpdir
        if not temp_file:
            temp_file = os.path.join(self.tmpdir, 'XXX')

        # patch the resulted config to use the proper temporary directory and
        # file locations
        with open(config_file, "r+") as cfg_file:
            lines = cfg_file.readlines()
            cfg_file.seek(0)
            cfg_file.truncate()
            for line in lines:
                if line.startswith("FSDIR="):
                    cfg_file.write("FSDIR=%s\n" % fsdir)
                elif line.startswith("FILE="):
                    cfg_file.write("FILE=%s\n" % temp_file)
                elif line.startswith("MB="):
                    cfg_file.write("MB=%s\n" % memory_size_mb)
                else:
                    cfg_file.write(line)
            # Printing the config file
            cfg_file.seek(0)
            for line in cfg_file.readlines():
                print(line)

    def test(self):

        os.chdir(self.sourcedir)
        build.make(self.sourcedir, extra_args='rerun')
        build.make(self.sourcedir, extra_args='rerun')
        build.make(self.sourcedir, extra_args='see')


# Write a Python program to check a dictionary is empty or not.
dic1 = {}
spam = {'rahul': 25, 'vipin': 21, 'prince': 29, 'kas': 17}

if len(dic1.keys()) == 0:
    print("dic is empty")
else:
    print("dic is not empty")

#dic is empty


import os
import tempfile
from os.path import join as pjoin

import dask
import distributed
import structlog
from distributed import SpecCluster

log = structlog.get_logger()

def default_cluster(large=False) -> SpecCluster:
    """Create a default Dask cluster for scheduling.

    Args:
        large: Whether workers have 12Gb of mem or 6Gb.

    Notes:
        1. We start workers as non-daemon as we need to spawn workers in the workers.
        2. If one wants to make their own cluster please see:
            https://docs.dask.org/en/latest/how-to/deploy-dask-clusters.html

    Returns:
        A LocalCluster with 2 workers.
    """
    dask_envs = {
        "DASK_DISTRIBUTED__WORKER__DAEMON": "False",
        "DASK_DISTRIBUTED__WORKER__MULTIPROCESSING_METHOD": "fork",
    }
    os.environ.update(dask_envs)

    # Start the cluster locally
    memory_limit = "12GB" if large else "6GB"
    log.info(f"Starting cluster with 2 workers of {memory_limit} of memory!")
    tmp_file = pjoin(str(tempfile.mkdtemp()), "dask-worker-space")
    with dask.config.set({"distributed.worker.daemon": False}):
        cluster = distributed.LocalCluster(
            n_workers=2,
            local_directory=tmp_file,
            threads_per_worker=1,
            memory_limit=memory_limit,  # "auto" doesnt work well.
        )
    return cluster


from project.services.base_service import BaseService

class MainService(BaseService):
    CAPACITY = 30

    def __init__(self, name: str):
        super().__init__(name, MainService.CAPACITY)

    def details(self):
        final = [f"{self.name} Main Service:"]

        if self.robots:
            final.append(f"Robots: {' '.join(r.name for r in self.robots)}")
        else:
            final.append(f"Robots: none")

        return '\n'.join(final)

3. Python Advanced/Python OOP - Exams/Python OOP Exam - 8 April 2023/01. Structure and 02. Functionality/project/services/main_service.py