import os

from PIL import Image
from PyPDF2 import PdfFileWriter, PdfFileReader
from pdf2image import convert_from_path
from reportlab.lib.units import cm
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfgen import canvas

# pip3 install pdf2image
# https://github.com/Belval/pdf2image、
# 中文支持
# https://github.com/StellarCN/scp_zh/blob/master/fonts/SimSun.ttf
# D:\python\Lib\site-packages\reportlab\fonts

# 创建文字pdf
def create_watermark_content(content):
    pdfmetrics.registerFont(TTFont("SimSun", "SimSun.ttf"))
    # 默认大小为21cm*29.7cm
    c = canvas.Canvas("mark.pdf", pagesize=(30 * cm, 30 * cm))
    # 移动坐标原点(坐标系左下为(0,0))
    c.translate(10 * cm, 5 * cm)

    # 设置字体
    # c.setFont("Helvetica", 80)
    # 中文
    c.setFont("SimSun", 14)
    # 指定描边的颜色
    c.setStrokeColorRGB(0, 1, 0)
    # 指定填充颜色
    c.setFillColorRGB(0, 1, 0)
    # 画一个矩形
    c.rect(cm, cm, 7 * cm, 17 * cm, fill=1)
    # 旋转45度，坐标系被旋转
    c.rotate(45)
    # 指定填充颜色
    c.setFillColorRGB(0.6, 0, 0)
    # 设置透明度，1为不透明
    c.setFillAlpha(0.3)
    # 画几个文本，注意坐标系旋转的影响
    c.drawString(3 * cm, 0 * cm, content)
    c.setFillAlpha(0.6)
    c.drawString(6 * cm, 3 * cm, content)
    c.setFillAlpha(1)
    c.drawString(9 * cm, 6 * cm, content)

    # 关闭并保存pdf文件
    c.save()

# create_watermark('walker')

# 制作图片水印pdf
def create_watermark(f_jpg, f_pdf):
    w_pdf = 25 * cm
    h_pdf = 30 * cm

    c = canvas.Canvas(f_pdf, pagesize=(w_pdf, h_pdf))
    c.setFillAlpha(0.5)  # 设置透明度
    # 这里的单位是物理尺寸
    print(c.drawImage(f_jpg, 15.4 * cm, 23 * cm, 6 * cm, 6 * cm))
    c.save()

# 所有路径为绝对路径
def add_watermark(pdf_file_in, pdf_file_mark, pdf_file_out):
    pdf_output = PdfFileWriter()
    input = open(pdf_file_in, 'rb')
    pdf_input = PdfFileReader(input)
    # PDF文件被加密了
    if pdf_input.getIsEncrypted():
        print('该PDF文件被加密了.')
        # 尝试用空密码解密
        try:
            pdf_input.decrypt('')
        except Exception as e:
            print('尝试用空密码解密失败.')
            return False
        else:
            print('用空密码解密成功.')

    # 获取PDF文件的页数
    pageNum = pdf_input.getNumPages()
    # 读入水印pdf文件
    pdf_watermark = PdfFileReader(open(pdf_file_mark, 'rb'))
    # 给每一页打水印
    for i in range(pageNum):
        page = pdf_input.getPage(i)
        page.mergePage(pdf_watermark.getPage(0))
        page.compressContentStreams()  # 压缩内容
        pdf_output.addPage(page)
        print("第{}页".format(i))

    with open(pdf_file_out, 'wb') as out:
        pdf_output.write(out)
    input.close()

# pdf转png
def pdf_pic(fn):
    pages = convert_from_path(fn)
    file_name = fn.split('.')[0]
    for i in range(0, len(pages)):
        new_name = file_name + str((i + 1))
        pages[i].save(f"" + new_name + ".png", 'PNG')
        print("生成图片：{}".format(new_name))

# 文字水印
def creat_font_watermark(txt):
    pdfmetrics.registerFont(TTFont("SimSun", "SimSun.ttf"))
    # 默认大小为21cm*29.7cm
    c = canvas.Canvas("mark.pdf", pagesize=(50 * cm, 25 * cm))
    # 移动坐标原点(坐标系左下为(0,0))
    c.translate(11 * cm, 20 * cm)
    # 设置字体
    # c.setFont("Helvetica", 80)
    # 中文
    c.setFont("SimSun", 30)
    c.rotate(45)
    c.setFillAlpha(0.7)
    c.drawString(3 * cm, 0 * cm, txt)
    c.save()

# 图片添加水印
def pic_add_watermark(fn, watermark):
    file_name = fn.split('.')[0]
    list = os.listdir(os.getcwd())
    i = 0
    file_list = []
    # 寻找文件列表
    for file in list:
        if file_name in file and file.endswith(".png"):
            print(file)
            file_list.append(file)
            i = i + 1
    print(file_list)
    print(i)
    # 图片合成
    for file in file_list:
        background = Image.open(file)
        foreground = Image.open(watermark)
        background.paste(foreground, (background.size[0] - foreground.size[0] - 200, 150), foreground)
        background.save(file)

    im_list = []
    for each_image in range(i):
        try:
            img = Image.open(file_name + str((each_image + 2)) + ".png")
        except:
            continue
        if img.mode == "RGBA":
            img = img.convert('RGB')
            im_list.append(img)
        else:
            im_list.append(img)
    new_pdf = file_name + "_watermark.pdf"
    if not os.path.isfile(file_name + "_watermark.pdf"):  # 无文件时创建
        fd = open(new_pdf, mode="w", encoding="utf-8")
        fd.close()
    pdf = Image.open(file_list[0])
    # 保存pdf
    pdf.save(new_pdf, "PDF", resolution=100.0, save_all=True, append_images=im_list)
    # 删除图片
    for file in file_list:
        os.remove(file)
    return new_pdf

# 图片覆盖demo
def test():
    background = Image.open("XXXXXXXXX.png")
    foreground = Image.open("a.jpg")
    background.paste(foreground, (0, 0), foreground)
    background.show()

if __name__ == '__main__':
    # creat_font_watermark("XXXXXXXXX。")
    file_name = "XXXXXXXXX.pdf"
    pdf_pic(file_name)
    new_pdf = pic_add_watermark(file_name, "a.png")
    # 添加文字水印
    f_pdf = 'mark.pdf'
    add_watermark(new_pdf, f_pdf, file_name)
    os.remove(new_pdf)
    # f_pdf = "mark.pdf"
    # create_watermark('a.jpg', f_pdf)


import sys

R, D, L, U = 0, 1, 2, 3

class S:
    def init_mms(self):
        self.row_min = [-1] * self.R
        self.row_max = [-1] * self.R
        for row in range(self.R):
            for col in range(self.C):
                if self.grid[row][col] != ' ':
                    if self.row_min[row] == -1:
                        self.row_min[row] = col
                    self.row_max[row] = col

        self.col_min = [-1] * self.C
        self.col_max = [-1] * self.C
        for col in range(self.C):
            for row in range(self.R):
                if self.grid[row][col] != ' ':
                    if self.col_min[col] == -1:
                        self.col_min[col] = row
                    self.col_max[col] = row

    def __init__(self, grid, row, col, dir):
        self.grid = grid
        self.R = len(grid)
        self.C = len(grid[0])
        self.row = row
        self.col = col
        self.dir = dir
        self.moves = [(0, 1), (1, 0), (0, -1), (-1, 0)]
        self.init_mms()

    def p(self):
        d = ['>', 'v', '<', '^']
        self.grid[self.row][self.col] = d[self.dir]
        for row in self.grid:
            print(*row)
        print()
        self.grid[self.row][self.col] = '.'

def move(s, m):
    r, c = s.moves[s.dir]
    for _ in range(m):
        new_row = s.row + r
        new_col = s.col + c
        if r != 0 and new_row < s.col_min[new_col]:
            new_row = s.col_max[new_col]
        elif r != 0 and s.col_max[new_col] < new_row:
            new_row = s.col_min[new_col]
        elif c != 0 and new_col < s.row_min[new_row]:
            new_col = s.row_max[new_row]
        elif c != 0 and s.row_max[new_row] < new_col:
            new_col = s.row_min[new_row]

        if s.grid[new_row][new_col] == '#':
            return

        s.row = new_row
        s.col = new_col

def part1(grid, instrs):
    s = S(grid, 0, grid[0].index('.'), 0)
    for i, instr in enumerate(instrs):
        if i % 2:
            s.dir = (s.dir + instr) % 4
        else:
            move(s, instr)

    return 1000 * (s.row + 1) + 4 * (s.col + 1) + s.dir

def get_cube_transitions(s):
    transitions = {}
    f2r = s.row_max[0]
    f3r = s.row_max[50]
    f5r = s.row_max[100]
    f6r = s.row_max[150]
    f6d = s.col_max[0]
    f5d = s.col_max[50]
    f2d = s.col_max[100]
    f1l = s.row_min[0]
    f3l = s.row_min[50]
    f4l = s.row_min[100]
    f6l = s.row_min[150]
    f4u = s.col_min[0]
    f1u = s.col_min[50]
    f2u = s.col_min[100]

    for i in range(50):

        transitions[(i, f1l, L)] = (149 - i, f4l, R) # 1L -> 4L
        transitions[(i + 100, f4l, L)] = (49 - i, f1l, R) # 4L -> 1L

        transitions[(i + 50, f3l, L)] = (f4u, i, D) # 3L -> 4U
        transitions[(f4u, i, U)] = (i + 50, f3l, R) # 4U -> 3L

        transitions[(i + 150, f6l, L)] = (f1u, i + 50, D) # 6L -> 1U
        transitions[(f1u, i + 50, U)] = (i + 150, f6l, R) # 1U -> 6L

        transitions[(f6d, i, D)] = (f2u, i + 100, D) # 6D -> 2U
        transitions[(f2u, i + 100, U)] = (f6d, i, U) # 2U -> 6D

        transitions[(i + 150, f6r, R)] = (f5d, i + 50, U) # 6R -> 5D
        transitions[(f5d, i + 50, D)] = (i + 150, f6r, L) # 5D -> 6R

        transitions[(i + 100, f5r, R)] = (49 - i, f2r, L) # 5R -> 2R
        transitions[(i, f2r, R)] = (149 - i, f5r, L) # 2R -> 5R

        transitions[(i + 50, f3r, R)] = (f2d, i + 100, U) # 3R -> 2D
        transitions[(f2d, i + 100, D)] = (i + 50, f3r, L) # 2D -> 3R

    return transitions

def move2(s, m, transitions):
    for _ in range(m):
        r, c = s.moves[s.dir]
        new_row = new_col = new_dir = None
        if (s.row, s.col, s.dir) in transitions:
            new_row, new_col, new_dir = transitions[(s.row, s.col, s.dir)]
        else:
            new_row = s.row + r
            new_col = s.col + c
            new_dir = s.dir

        if s.grid[new_row][new_col] == '#':
            return

        s.row = new_row
        s.col = new_col
        s.dir = new_dir

def part2(grid, instrs):
    s = S(grid, 0, grid[0].index('.'), 0)
    transitions = get_cube_transitions(s)
    for i, instr in enumerate(instrs):
        if i % 2:
            s.dir = (s.dir + instr) % 4
        else:
            move2(s, instr, transitions)

    return 1000 * (s.row + 1) + 4 * (s.col + 1) + s.dir

if __name__ == "__main__":
    grid, instrs = [], []
    for line in sys.stdin:
        line = line.rstrip()
        if len(line) == 0:
            continue
        if line[0].isnumeric():
            num = ""
            for c in line:
                if c.isnumeric():
                    num += c
                else:
                    instrs.append(int(num))
                    instrs.append(1 if c == 'R' else -1)
                    num = ""
            instrs.append(int(num))
            break
        grid.append(list(line))

    C = max(len(row) for row in grid)
    for row in grid:
        row.extend([' '] * (C - len(row)))

    print(part1(grid, instrs))
    print(part2(grid, instrs))


import numpy as np

class PageRankApproximate:
    # CONSTRUCTOR
    def __init__(self, alpha=0.85, max_iteration=1000, tol=1e-6):
        # APPROXIMATE PAGE RANK PARAMETERS
        self.alpha     = alpha
        self.max_iter  = max_iteration
        self.tol       = tol
        # NODES INDEXING
        self.nodes_idx = {}
        self.idx_nodes = {}
        # PAGE RANKS ELEMENTS TO WORK
        self.adj_mat   = None
        self.deg_vet   = None
        self.page_rank = None

    # FUNCTION USED TO CREATE A INDEX MAP ON NETWORK NODES
    # IT WILL BE USED TO MAKE A FAST PAGE RANK
    def _nodes_index_creation(self, network):
        for node_idx, node_key in enumerate(network.nodes):
            self.nodes_idx[node_key] = node_idx
            self.idx_nodes[node_idx] = node_key

    # WEIGHTED ADJACENT MATRIX CONSTRUCTION
    def _adjacent_matrix_construction(self, network):
        nodes_number = len(self.nodes_idx)
        adjacent_mtx = np.zeros((nodes_number, nodes_number), dtype=float)
        for src, dsts_edges_id in network.adj_list.items():
            src_idx  = self.nodes_idx[src]
            for dst, edge_id in dsts_edges_id:
                dst_idx  = self.nodes_idx[dst]
                score    = network.edges[edge_id].weight
                adjacent_mtx[src_idx, dst_idx] = score
        self.deg_vet = np.sum(adjacent_mtx, axis=1)
        self.adj_mat = adjacent_mtx

    # PAGERANK INITIALIZATION
    def _init_pagerank(self, network, n):
        pagerank = np.zeros(n, dtype=float)
        for node_key, node_id in self.nodes_idx.items():
            pagerank[node_id] = network.nodes[node_key].size
        self.page_rank = pagerank

    def approximate_pagerank_computing(self, network):
        self._nodes_index_creation(network)
        self._adjacent_matrix_construction(network)
        n = self.adj_mat.shape[0]
        self._init_pagerank(network, n)

        for i in range(self.max_iter):
            prev_pagerank   = self.page_rank.copy()
            # multiply by the adjacency matrix and damping factor
            self.page_rank  = self.alpha * self.adj_mat.dot(self.page_rank)
            # add the teleportation probability
            self.page_rank += (1 - self.alpha) * np.ones(n) / n
                   # tutti 0 tranne un 1 che corrisponde al nodo dove vi stiamo centrando (nodo della query)
                   # 1/k se sono k nodi indicati nella query
            # normalize to ensure the sum is 1
            self.page_rank /= np.sum(self.page_rank)
            # check for convergence
            if np.linalg.norm(self.page_rank - prev_pagerank) < self.tol:
                break

        for node_idx, pagerank in enumerate(self.page_rank):
            network.nodes[self.idx_nodes[node_idx]].pagerank = pagerank

        # SORTING NODE
        network.nodes = {
            k: v for k, v in sorted(network.nodes.items(), key=lambda item: item[1].pagerank, reverse=True)
        }


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

# In[1]:

# importing packages
import numpy as np
import pandas as pd

# opening dataframe file from local computer
df1 = pd.read_csv(r'G:\Python projects\suicide rates\master.csv')

# cleaning up data removing columns
df1 = df1.drop(columns = ['country-year', 'HDI for year', 'gdp_per_capita ($)', 'generation'])

# sorting data frame
df1 = df1.sort_values(by=['sex', 'year', "country", "age"], ascending=True)

# resetting index
df1 = df1.reset_index(drop = True)

# dropping one column
df1 = df1.iloc[: , :-1]
df1

# In[ ]:


from quicksort import quicksort
import unittest

# arr1 = [4, 3, 1]
# quicksort(arr1)
#
# print(arr1)

class TestQuicksort(unittest.TestCase):

    def test_small_array(self):
        arr1 = [4, 3, 1]
        quicksort(arr1)
        self.assertEqual(arr1, [1, 3, 4])

    def test_sorted_array(self):
        arr1 = [1, 3, 4]
        quicksort(arr1)
        self.assertEqual(arr1, [1, 3, 4])

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


import unittest
from yaml_serializer import YamlSerializer

class TestYamlSerializer(unittest.TestCase):
    def test_dumps(self):
        obj = type('Example',(object,),{'five':5,'somedata':[123,321,222,111,333]})
        data = YamlSerializer().dumps(obj)
        res = 'type: "class"\nbody: \n  classname: "Example"\n  metaclasses: "(<class \'object\'>,)"\n  attributedict: \n    five: 5\n    somedata: \n      - 123\n      - 321\n      - 222\n      - 111\n      - 333'
        self.assertEqual(res,data)

    def test_dumps_instance(self):
        class Player:
            nickname = 'Player'
            team = 'Red'
            def about(self):
                return f"{self.nickname}#{self.team}"

        obj=Player()
        obj.nickname = 'FeedORfeed'
        obj.team = 'Green'

        YamlSerializer().dump(obj,open('player.yaml','w'))
        data = YamlSerializer().dumps(obj)
        res = YamlSerializer().loads(data)
        self.assertEqual(obj.nickname,res.nickname)
        self.assertEqual(obj.team,res.team)
        self.assertEqual(obj.about(),res.about())

    def test_loads(self):
        data = 'type: "class"\nbody: \n  classname: "Example"\n  metaclasses: "(<class \'object\'>,)"\n  attributedict: \n    five: 5\n    somedata: \n      - 123\n      - 321\n      - 222\n      - 111\n      - 333'
        obj = YamlSerializer().loads(data)
        self.assertEqual(obj.five,5)
        self.assertEqual(obj.somedata,[123,321,222,111,333])

    def test_load_func(self):
        obj = YamlSerializer().load(open('useglob.yml'))
        res = obj()
        from dump_test1 import pi
        self.assertEqual(res,pi)

    def test_load_class(self):
        obj = YamlSerializer().load(open('iitpclass.yml'))
        from dump_test1 import Iitp
        self.assertEqual(obj.Student.name,Iitp.Student.name)
        self.assertEqual(obj.Student.av_score,Iitp.Student.av_score)
        self.assertEqual(obj.expel.__code__,Iitp.expel.__code__)

    def test_class(self):
        class Testik:
            title = "test class named Testik"
            def about(self):
                return f"title:{self.title}"
        data = YamlSerializer().dumps(Testik)
        returned_class = YamlSerializer().loads(data)
        self.assertEqual(Testik().about(),returned_class().about())

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


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

import os
import sys
import time
import logging

log = logging.getLogger(__name__)

from RelayController import *
from TemperatureSensor import *

class Regulator:
    """Regulates the brewing process"""

    def __init__(self):
        self.rc = RelayController()
        self.ts = TemperatureSensor()
        self._heatingRelay = 1
        self._coolingRelay = 2
        self._marginOfError = 0.5 # Margin of 0.5 celsius

    def pid(self, targetTemp):
        currentTemp = self.ts.getFilteredTemperature()
        log.info('Current Temperature {}c, Target Temperature {}c, Margin {}c'.format(currentTemp, targetTemp, self._marginOfError))
        print('Current Temperature {}c, Target Temperature {}c, Margin {}c'.format(currentTemp, targetTemp, self._marginOfError))
        if currentTemp < targetTemp - self._marginOfError:
            #Turn on heating
            self.rc.setRelayOn(self._heatingRelay)
            self.rc.setRelayOff(self._coolingRelay)
            log.info('Too cold, turned on heating.')
            print('Too cold, turned on heating.')
        elif currentTemp > targetTemp + self._marginOfError:
            #Turn on cooling
            sleepTime = 5 #Minutes
            self.rc.setRelayOff(self._heatingRelay)
            self.rc.setRelayOn(self._coolingRelay)
            log.info('Too warm, turned on cooling. Sleeping for {}min.'.format(sleepTime))
            print('Too warm, turned on cooling. Sleeping for {}min.'.format(sleepTime))
            time.sleep(60*sleepTime)
        else:
            # Within margin, do nothing
            self.rc.setRelayOff(self._heatingRelay)
            self.rc.setRelayOff(self._coolingRelay)
            log.info('Temperature within margins, doing nothing.')
            print('Temperature within margins, doing nothing.')

    def selfTest(self):
        log.info('SelfTest started')
        self.rc.selfTest()
        self.ts.selfTest()

if __name__ == '__main__':
    try:
        logging.basicConfig(filename='/var/log/brewing_regulator.log', format='%(asctime)s %(levelname)-8s %(message)s', level=os.environ.get("LOGLEVEL", "INFO"))
        # Testing Relays
        regulator = Regulator()
        regulator.selfTest()
    except KeyboardInterrupt:
        log.error("Exiting application")
        sys.exit(0)


import sqlite3
import uuid
import random

def count_premia(time_worked_on_week):
    if time_worked_on_week > 40:
        return 800 * (time_worked_on_week - 40)

    if time_worked_on_week < 25:
        return 'уволен'
def count_formula(id):
    cum_time, time_worked_on_week, worked_days, worked_weeks, premia_nakapalo = list(
        cur.execute(f"SELECT * from worktime where id={id}").fetchall()[0][1:])
    exit_time = time_to_float(input("введите время ухода"))
    time_worked_on_week += exit_time - cum_time
    worked_days += 1
    if worked_days == 5:
        print("канец нидили")
        prem = count_premia(time_worked_on_week)
        if prem == "уволен":
            print("сотрудник увольняется! увольте вручную")
        else:
            premia_nakapalo += prem
            time_worked_on_week = 0

            worked_weeks += 1
            if worked_weeks == 4:
                print("выдайте премию и зарплату!")
                worked_weeks = 0
        worked_days = 0
    return ", ".join(list(map(str, [cum_time, time_worked_on_week, worked_days, worked_weeks, premia_nakapalo])))

import sqlite3

def add_employee(id, name, surname, age, phone_number,gender, salary):
    try:
        con = sqlite3.connect("maindb.db")
        cur = con.cursor()
        cur.execute("INSERT INTO main_sotrud (id, name, surname, age, phone_number, gender, salary) VALUES (?, ?, ?, ?, ?, ?, ?)", (id, name, surname, age, phone_number, gender, salary))
        con.commit()
        print("Сотрудник успешно добавлен в базу данных.")
        print(f"ID добавленного сотрудника: {id}")
    except sqlite3.Error as e:
        print(f"Ошибка базы данных: {e}")
    finally:
        con.close()

def time_to_float(time):
    time = time.split(":")
    return int(time[0]) + int(time[1]) / 60

con = sqlite3.connect("maindb.db")
cur = con.cursor()
for i in cur.execute("SELECT id, name, surname, salary from main_sotrud"):
    for j in i:
        print(j, end=" ")
    print()
while True:
    deyst = int(input("1 - сотрудник пришел, 2 - сотрудник ушел, 3 - добавить рабочего \n"))
    if deyst == 1:
        id = input("введите id сотрудника: ")
        if id.isdigit() == False:
            raise Exception("ID cant be text")
        if int(id) > 999999 or int(id) < 100000:
            raise Exception("ID не может быть больше 999999 и меньше 100000")

        try:
            needed_values = ", ".join(list(map(str, list(cur.execute(f"SELECT time_worked_on_week, worked_days, worked_weeks, premia_nakapalo from worktime where id={id}").fetchall()[0]))))
        except IndexError:
            needed_values = "0, 0, 0, 0"
        cur.execute(f"INSERT OR REPLACE into worktime (id, cum_time, time_worked_on_week, worked_days, worked_weeks, premia_nakapalo) VALUES ({id}, {str(time_to_float(input('введите время')))}, {needed_values})")
        con.commit()
    if deyst == 2:
        id = input("введите id: ")
        if id.isdigit() == False:
            raise ValueError("ID cant be text")
        if int(id) > 999999 or int(id) < 100000:
            raise Exception("ID не может быть больше 999999 и меньше 100000")
        cur.execute(f"INSERT OR REPLACE into worktime (id, cum_time, time_worked_on_week, worked_days, worked_weeks, premia_nakapalo) VALUES ({id}, {count_formula(id)})")
        con.commit()

    if deyst == 3:
        id = random.randint(100000, 999999)
        name = input("Имя: ")
        surname = input("Фамилия: ")
        age = input("Сколько лет: ")
        phone_number = input("Номер телефона: ")
        gender = input("Пол: Мужской, Женский \n")
        salary = input("Зарплата: ")
        if salary.isdigit() == False:
            raise Exception('Введите число')
        add_employee(id, name, surname, age, phone_number,gender, salary)


import sys

from dimod import ExactSolver
from docplex.mp.model import Model
from pandas import DataFrame

sys.path.append("/home/adam/Documents/omniqubo/")

from omniqubo import Omniqubo  # noqa: E402
from omniqubo.converters.converter import (  # noqa: E402
    ConverterAbs,
    can_convert,
    convert,
    interpret,
)
from omniqubo.models.sympyopt import SympyOpt  # noqa: E402
from omniqubo.sampleset import dimod_import  # noqa: E402

class MultiplyBy(ConverterAbs):
    def __init__(self, val: float) -> None:
        super().__init__()
        self.val = val

@convert.register
def convert_mul_by(model: SympyOpt, converter: MultiplyBy) -> SympyOpt:
    assert can_convert(model, converter)
    model.objective = converter.val * model.objective
    return model

@can_convert.register
def can_convert_mul_by(model: SympyOpt, converter: MultiplyBy) -> bool:
    return converter.val > 0

@interpret.register
def interpret_mul_by(samples: DataFrame, converter: MultiplyBy) -> bool:
    if "energy" in samples.columns:
        samples["energy"] /= converter.val
    return samples

# construct the model in language you like
mdl = Model("ILP")
x = mdl.integer_var(name="x", lb=-2, ub=2)
y = mdl.binary_var("y")
mdl.minimize((x + y) ** 2 + 3)

omniqubo = Omniqubo(mdl)
omniqubo.to_hobo(penalty=1)
omniqubo.convert(MultiplyBy(2.0))

# export the QUBO and solve it with third-party solver
bqm = omniqubo.export("bqm")
Q, offset = bqm.to_qubo()
df = ExactSolver().sample_qubo(Q)

# interpret the results
df = dimod_import(df)
df["energy"] += offset  # this needs to be done as solver ignores offset
print(df["energy"])
df = omniqubo.interpret(df)
print(df["energy"])


import random
from typing import Callable, Generic, TypeVar

import torch
from torch.distributions import Categorical

from models import NetV2, QNet

# A Policy takes a batch of observations and action masks and returns a batch of actions.
Policy = Callable[[torch.FloatTensor, torch.BoolTensor], torch.IntTensor]

P = TypeVar("P", bound=Policy)

class EpsilonGreedy(Generic[P]):
    """ϵ-greedy policy that wraps another policy."""

    def __init__(self, original_policy: P, num_actions: int, epsilon: float) -> None:
        self.original_policy = original_policy
        self.num_actions = num_actions
        self.epsilon = epsilon

    def __call__(self, obs: torch.FloatTensor, action_masks: torch.BoolTensor) -> torch.IntTensor:
        batch_size = obs.shape[0]

        with obs.device:
            # Sample uniformly-random valid actions.
            actions = [
                random.choice([i for i, valid in enumerate(action_mask) if valid])
                for action_mask in action_masks.cpu()
            ]
            actions = torch.tensor(actions)

            # Generate a mask that will determine which actions will be greedy.
            greedy_mask = torch.rand(batch_size) > self.epsilon

            # Replace the designated actions with actions from the wrapped policy.
            actions[greedy_mask] = self.original_policy(obs[greedy_mask], action_masks[greedy_mask])

            return actions

class MaxQPolicy:
    """
    A policy that selects the action with the highest Q(s, a) value, as predicted by a Q network.

    The Q network is expected to take a (batched) observation tensor and return a (batched) vector
    of Q values, with shape (batch_size, num_actions).
    """

    def __init__(self, q_net: QNet) -> None:
        self.q_net = q_net

    @torch.no_grad()
    def __call__(self, obs: torch.FloatTensor, action_masks: torch.BoolTensor) -> torch.IntTensor:
        action_values = self.q_net(obs)
        action_values[~action_masks] = -torch.inf
        return action_values.argmax(dim=1)

class PNetPolicy:
    """
    A policy that selects an action according to the categorical distribution predicted by a policy
    network.

    The policy network is expected to take a (batched) observation tensor and return a (batched) vector
    of action logits, with shape (batch_size, num_actions).
    """

    def __init__(self, policy_net: NetV2) -> None:
        self.policy_net = policy_net

    def __call__(self, obs: torch.FloatTensor, action_masks: torch.BoolTensor) -> torch.IntTensor:
        actions, _ = self.action_and_entropy(obs, action_masks)
        return actions

    @torch.no_grad()
    def action_and_entropy(
        self, obs: torch.FloatTensor, action_masks: torch.BoolTensor
    ) -> tuple[torch.IntTensor, torch.FloatTensor]:
        action_logits = self.policy_net(obs)
        action_logits[~action_masks] = -torch.inf
        action_dist = Categorical(logits=action_logits)
        return action_dist.sample(), action_dist.entropy()


## Entry widget and Checkbuttons

import tkinter as tk

root = tk.Tk()
root.geometry("300x300")
root.title("MY GUI")

label = tk.Label(text="Welcome to Python Class", font="comicsansms 13 bold", pady=10)
label.grid(row=0, column=3)

name = tk.Label(text="Name")
name.grid(row=1, column=1)

phone = tk.Label(text="Phone")
phone.grid(row=2, column=1)

gender = tk.Label(text="Gender")
gender.grid(row=3, column=1)

# i_agree = tk.Label(text="I agree")
# i_agree.grid(row=4, column=1)

name_value = tk.StringVar()
phone_value = tk.StringVar()
gender_value = tk.StringVar()
agreed_to_admit = tk.BooleanVar()

name_entry = tk.Entry(textvariable=name_value)
phone_entry = tk.Entry(textvariable=phone_value)
gender_entry = tk.Entry(textvariable=gender_value)
agree_check = tk.Checkbutton(text='I agree', textvariable=agreed_to_admit)

name_entry.grid(row=1, column=3)
phone_entry.grid(row=2, column=3)
gender_entry.grid(row=3, column=3)
agree_check.grid(row=4, column=3)

def get_val():
    print("This is done!")
    print(name_value.get())
    with open("detail.txt", mode='w') as file:
        file.write(f"{name_value.get()}\n{phone_value.get()}\n{gender_value.get()}\n{agreed_to_admit.get()}")

submit = tk.Button(text='Submit', padx=10, command=get_val)
submit.grid(row=5, column=3)

root.mainloop()


import json
import io
import os
import os.path
from myhttp import prepare, get, download, APP_SERVER, post
import shutil
from config import Config

def process_picture(folder, ccid, jo):
    id = jo['id']
    fnp = jo['fileName'].split('.')
    type = fnp[len(fnp) - 1]

    print("\tdownload picture %d-%d ..." % (ccid, id), end='')

    if True:
        try:
            jo1 = get('%s/class_circle_messages/%d/oss_resources/%d/origin_resource?platform=app' % (APP_SERVER, ccid, id))

            if Config().debug:
                with open(os.path.join(folder, '%d.json' % id), 'w') as fp:
                    json.dump(jo1, fp)

            download(jo1['ossResourceUrl'], os.path.join(folder, "%d.%s" % (id, type)))
        except:
            download(jo['url'], os.path.join(folder, "%d_normal.%s" % (id, type)))
    else:
        print("ccid=%d, pid=%d" % (ccid, id))

    print(' done')

def process_class_circle(folder, jo):
    id = jo['id']
    time = jo['createTime'].replace(' ', '_').replace(':', '-')
    name = "%d_%s" % (id, time)

    print('process class circle [%d] (%s)' % (id, time))

    datadir = os.path.join(folder, name)
    if os.access(datadir, os.F_OK):
        #TODO 是否会存在内容被zQWTY4
        print('already done')
        return False;
    else:
        tempdir = os.path.join(folder, str(id))
        if os.access(tempdir, os.F_OK):
            shutil.rmtree(tempdir)
            #os.rmdir(tempdir)

        os.mkdir(tempdir)

        # 下载图片
        for picture in jo['ossResources']:
            process_picture(tempdir, id, picture)

        # 下载文字
        with open(os.path.join(tempdir, 'content.txt'), 'w', encoding='utf8') as fp:
            text = jo['content']
            fp.write(text)

        os.rename(tempdir, datadir)

        print('class circle [%d] done' % id)

def praise_class_circle(jo):
    for comment in jo['comments']:
        if str(comment['createUserId']) == Config().get('userid'):
            return

    ccid = jo['id']
    print('praise class circle [%d] (%s) ...' % (ccid, jo['createTime']), end='')

    url = APP_SERVER + '/class_circle_messages/%d/comments?objJsonStr=#7B#22createUserId#22#3A%s#2c#22isPraised#22#3Atrue#7D&platform=app' % (ccid, Config().get('userid'))
    url = url.replace('#', '%')

    post(url, data='')
    #print(url)

    print(' done')

if __name__ == '__main__':
    items = []
#    login('13761240204', '123')
#    r = get(APP_SERVER + "/class_circle_messages/?currentPage=1&pageSize=1000&platform=app")
#    items = r['item']
    Config().load('config.ini')

    with open('test/banjiquan.json', 'r', encoding='utf8') as fp:
        j = json.load(fp)
        for item in j['data']['items']:
            #process_class_circle("test/", item)
            praise_class_circle(item)


import cv2 as cv
import numpy as np
from numpy import fft
import matplotlib.pyplot as plt
from scipy import ndimage
from scipy import signal
from scipy import fftpack

def create_histogram(img):
	size = img.shape[0]*img.shape[1]
	hist = np.zeros(8, dtype=np.float)
	for row in range(img.shape[0]):
		for col in range(img.shape[1]):
			hist[img[row][col]] += 1
	return hist/size

def create_sum_histogram(hist):
	sum_hist = np.zeros(8,dtype=np.float)
	sum_hist[0] = hist[0]
	for x in range(1,8):
		sum_hist[x] = sum_hist[x-1] + hist[x]
	return sum_hist

def dft(signal):
	N = len(signal)
	x = np.array(range(N))
	x = np.tile(x,(N,1))
	u = x.copy().T
	M = np.exp((-1j*2*np.pi*x*u)/N)
	return np.matmul(M,signal)

def show_dft_vector(N):
	x = np.array(range(N))
	x = np.tile(x,(N,1))
	u = x.copy().T
	M = np.exp((-1j*2*np.pi*x*u)/N)
	print(M)

def dct(signal):
	N = len(signal)
	x = np.array(range(N))
	x = np.tile(x,(N,1))
	u = x.copy().T
	M = np.cos((2*x+1)*u*np.pi/(2*N))
	a1 = [np.sqrt(1/N)]
	a2 = np.repeat(np.array([np.sqrt(2/N)]),N-1)
	a = np.concatenate((a1,a2),axis = 0)
	return np.matmul(M,signal)*a

def show_dct(N):
	x = np.array(range(N))
	x = np.tile(x,(N,1))
	u = x.copy().T
	M = np.cos((2*x+1)*u*np.pi/(2*N))
	a1 = [np.sqrt(1/N)]
	a2 = np.repeat(np.array([np.sqrt(2/N)]),N-1)
	a = np.concatenate((a1,a2),axis = 0)
	a = np.repeat(a,4)
	a = np.reshape(a,(4,4))
	return M*a

def bai1():
	I = np.array([[5,0,0,1,2],
				[2,1,5,1,2],
				[7,1,5,1,2],
				[7,4,5,4,3],
				[7,1,6,1,3]])
	Kx = np.array([[-1,0,1],
				[-2,0,2],
				[-1,0,1]])
	Ky = Kx.T
	Gx = ndimage.convolve(I,Kx,mode='reflect')
	Gy = ndimage.convolve(I,Ky,mode='reflect')
	print('Gradient vector at (0,0): (' + str(Gx[0,0]) + ',' + str(Gy[0,0]) +')')
	print('Gradient vector at (1,1): (' + str(Gx[1,1]) + ',' + str(Gy[1,1]) +')')
	print('Gradient vector at (0,3): (' + str(Gx[0,3]) + ',' + str(Gy[0,3]) +')')

	h = create_histogram(I)
	plt.plot(h,color = 'b')
	plt.xlim([0,7])
	plt.show()
	sumhist = create_sum_histogram(h)

	new_I = I.copy()
	for x in range(I.shape[0]):
		for y in range(I.shape[1]):
			new_I[x][y] = int(np.round(sumhist[I[x][y]]*7))
	new_h = create_histogram(new_I)
	new_h_sum = create_sum_histogram(new_h)
	plt.plot(sumhist,color = 'r')
	plt.plot(new_h_sum,color = 'b')
	plt.xlim([0,7])
	plt.show()

	print(new_I)

def bai2():
	# a)
	print('Cau 2a)')
	show_dft_vector(2)
	print(dft([1,3]))
	# b)
	print('Cau b)')
	fx = np.array([1,3])
	fu = dft(fx)
	print(fu)
	print('Chung minh truc giao chuan:')
	base_vector = show_dct(4)
	for v in base_vector:
		print(np.sum(v**2))
	for x in range(base_vector.shape[0]):
		for y in range(x,base_vector.shape[0]):
			if x == y:
				continue
			print(np.dot(base_vector[x],base_vector[y]))

	fx = np.array([1,0,1])
	fxx = np.array([1,0,1,0])
	print(dct(fxx))

def bai3():
	A = np.array([[1/np.sqrt(2),-1/np.sqrt(2),3],
				[1/np.sqrt(2),1/np.sqrt(2),-3*2**0.5+3],
				[0,0,1]])
	P1 = np.array([2,3,1])
	pixel = np.round(np.matmul(np.linalg.inv(A),P1))
	print(pixel)

bai1()
bai2()
bai3()


# 문자열 압축

# s 입력
s = input()

# 1,2,3'''만큼 자른 s를 저장할 split 리스트 선언
split = [[] for _ in range(int(len(s)/2) + 1)]
# size만큼 자르고 split[size]에 저장
for size in range(1, int(len(s)/2) + 1):
    for i in range(0, len(s), size):
        split[size].append(s[i:i+size])
# 압축한 문자열의 개수를 저장할 리스트
result = []

# 자를 크기를 변경하며 반복
for i in range(1, len(split)):
    # i단위로 문자열을 자른 리스트를 s에 넣음
    s = split[i]
    # 중간 값을 저장할 변수 선언
    temp_result = ""
    temp_cnt = 1
    # 첫 항을 prev에 넣음
    prev = s[0]
    # 두 번째항부터 prev와 비교하며 같다면 cnt + 1, 다르면 temp_result에 추가해줌
    for j in range(1, len(s)):
        if prev == s[j]:
            temp_cnt += 1
        else:
            if temp_cnt > 1:
                temp_result += str(temp_cnt)
                temp_cnt = 1
            temp_result += prev
        prev = s[j]
    # 마지막 항을 계산함
    if temp_cnt > 1:
        temp_result += str(temp_cnt)
        temp_cnt = 1
    temp_result += s[-1]

    # 압축된 문자열의 길이를 result에 추가함
    result.append(len(temp_result))
# 최소 출력
print(min(result))

# # 문자열을 이상하게 다룸. size만큼 1개면 1개씩 2개면 2개씩 저장해서 비교하는 게 편할 듯

# # s 입력
# s = list(input())

# # 잘린 결과를 저장할 배열
# result = [len(s)] * (int(len(s)/2)+1)

# # size 단위 만큼 자르며, N/2 만큼 반복
# for size in range(1, int(len(s)/2)+1):
#     # size로 자르며 중간 결과를 저장할 변수들
#     temp_result = ""
#     temp_str = ""
#     temp_cnt = 1
#     # s를 순차탐색한 size 단위로
#     for i in range(0, len(s)-size+1, size):
#         # 현재 문자열
#         cur = ""
#         for j in range(i, i+size):
#             cur += s[j]
#         # 다음 문자열
#         nex = ""
#         if i+size+size <= len(s):
#             for j in range(i+size, i+size+size):
#                 nex += s[j]
#         # 현재 값과 다음 값이 같다면 cnt + 1
#         if cur == nex:
#             temp_cnt += 1
#         # 다르다면 temp_str에 현재 문자열을 넣고
#         else:
#             temp_str = cur
#             # cnt가 1보다 크다면 temp_result에 추가, cnt 초기화
#             if temp_cnt > 1:
#                 temp_result += str(temp_cnt)
#                 temp_cnt = 1
#             # temp_str을 temp_result에 추가
#             temp_result += temp_str
#     print(temp_result)
#     result[size] = len(temp_result)
# print(result)


from collections import deque

n = int(input())
gmax = -1
arr = [list(map(int , input().split())) for i in range(n)]

def bfs ( a , b ) :
    global gmax
    dy = [ 1, -1 , 0, 0]
    dx = [0 , 0, 1, -1]

    q = deque()

    q.append( (a , b, 1))

    while q :
        y, x, count = q.popleft()
        for i in range(4) :
            ny = dy[i] +y
            nx = dx[i] +x
            if  0<=ny < n and 0<= nx < n and arr[ny][nx] > arr[y][x] :
                gmax = max( gmax , count+1)
                q.append( (ny , nx , count+1))

for y in range(n) :
    for x in range(n) :
        bfs( y, x)

print (gmax)

백준/풀이/백준_욕심쟁이 팬더 1937.py

백준_욕심쟁이 팬더 1937.py


from matplotlib import pyplot as plt
import numpy as np
from sklearn import datasets, model_selection

def plot_decision_boundary(data, predict):
    """ref: http://scikit-learn.org/stable/auto_examples/svm/plot_iris.html"""

    x_min, x_max = data[:, 0].min() - .5, data[:, 0].max() + .5
    y_min, y_max = data[:, 1].min() - .5, data[:, 1].max() + .5
    h = .02
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
                         np.arange(y_min, y_max, h))

    Z = predict(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)

    plt.contourf(xx, yy, Z, cmap=plt.cm.coolwarm, alpha=0.8)

def sigmoid(x):
    return 1 / (1 + np.exp(-x))

class NeuralNetwork:
    EPOCH = 3000

    def __init__(self, layers, rho=1e-1):
        self.W_list = [np.random.randn(layers[i], layers[i-1] + 1)
                       for i in range(1, len(layers))]
        self.rho = rho

    def train(self, data, label):
        for i in range(self.__class__.EPOCH):
            # shuffle
            perm = np.random.permutation(len(data))
            data, label = data[perm], label[perm]

            for x, y in zip(list(data), list(label)):
                g_list = self._predict(x)

                # back propagation
                new_W_list = [np.zeros(W.shape) for W in self.W_list]
                for i in reversed(range(len(self.W_list))):
                    _g = g_list[i + 1]
                    g = g_list[i]
                    W = self.W_list[i]

                    if i == len(self.W_list) - 1:
                        # output layer
                        e = (_g - y) * _g * (1 - _g)
                    else:
                        # hidden layer
                        _W = self.W_list[i + 1][:, :-1]
                        e = np.dot(_W.T, e) * _g * (1 - _g)

                    G = np.repeat(np.concatenate([g, [1]])[np.newaxis, :],
                                  W.shape[0],
                                  axis=0)
                    E = np.repeat(e[:, np.newaxis],
                                  W.shape[1],
                                  axis=1)
                    new_W_list[i] = W - self.rho * E * G

                self.W_list = new_W_list

    def _predict(self, x):
        g_list = [x]
        for W in self.W_list:
            x = np.concatenate([g_list[-1], [1]])
            g_list.append(sigmoid(np.dot(W, x)))

        return g_list

    def predict(self, x):
        return np.argmax(self._predict(x)[-1])

    def predict_array(self, X):
        return np.array([self.predict(x) for x in list(X)])

if __name__ == '__main__':
    # prepare dataset
    moons = datasets.make_moons(n_samples=500, noise=0.1)

    x_train, x_test, y_train, y_test = model_selection.train_test_split(
        moons[0], np.eye(2)[moons[1]], test_size=0.5, shuffle=True
    )

    # train
    nn = NeuralNetwork([2, 3, 2])
    nn.train(x_train, y_train)

    # test
    errors = [y[nn.predict(x)] != 1
              for x, y in zip(list(x_test), list(y_test))]
    error_rate = len(x_test[errors]) / len(x_test)
    print(f"error rate={error_rate}")

    # display
    plot_decision_boundary(x_test, lambda x: nn.predict_array(x))

    X_c0 = x_test[np.argmax(y_test, axis=1) == 0]
    X_c1 = x_test[np.argmax(y_test, axis=1) == 1]
    plt.scatter(X_c0[:, 0], X_c0[:, 1])
    plt.scatter(X_c1[:, 0], X_c1[:, 1])

    plt.show()


import filters

def main():
    file = "cube.jpg"

    myimage = filters.load_img(file)
    filters.show_img(myimage)

    #filtered = filters.obamicon(myimage)
    #filters.save_img(filtered, "filtered_" + file)

if __name__ == '__main__':
    main()


#Brandon Marcouiller
#U28887050
from LL1Parser import Parser
import sys
import re

if len(sys.argv) != 2:
    raise ValueError('Please provide a grammar file.')

def parseGrammar(file):
    start = None
    grammar = {}
    txt = ''
    for line in file:
        if line == '' or line == '\n':
            break
        match = re.search('([A-Z]) -> (.*)', line)
        var = match.group(1)
        if not start:
            start = var
        productions = set(re.findall('[^\\| ]*', match.group(2))) - {''}
        grammar[var] = productions
        txt += line
    return [grammar, start, txt]

out = parseGrammar((open(sys.argv[1],'r')))
grammar = out[0]
start = out[1]
txt = out [2]

parser = Parser(grammar, start)
while True:
    print('****************************')
    print('The given grammar is: \n{}'.format(txt))
    print('****************************')
    str = input('Enter a string to parse:').strip()
    print('The string accepted = {}'.format(parser.parse(str, start)))
    str = input('Would you like to parse another string. Enter Y for yes; anything else will terminate').strip()
    if str != 'Y':
        break

x = 0


#!/usr/bin/python3
"""
Test Class for BASE class
"""
import unittest
from models.base import Base

class TestBase:
    """
    The test case for BASE class
    Args:
        test__init__
    """

    def test_init(self):
        """
        Tests the class constructor
        """
        b1 = Base()
        self.assertEqual(b1.id, 1)
        b2 = Base()
        self.assertEqual(b2.id, 2)
        b3 = Base(10)
        self.assertEqual(b2.id, 10)


"""Find a Trevanion-type null cipher encoded with a specific number of letters after each punctuation mark."""

import sys
import string  # contains collections of constants like letters and punctuation marks

def load_text(file):
    """Load a text file as a string."""
    with open(file) as f:
        return f.read().strip()  # strip removes leading and trailing whitespace

def solve_null_cipher(message, lookahead):
    """ Solve a null cipher based on number of letters after punctuation mark.

    message = null cipher text as a string stripped of whitespace
    lookahead = end point of range of letters after punctuation mark to examine
    """
    for i in range(1, lookahead + 1):
        plaintext = ''
        count = 0
        found_first = False
        for char in message:
            if char in string.punctuation:
                count = 0
                found_first = True
            elif found_first is True:
                count += 1
            if count == i:
                plaintext += char
        print(f"Using offset of {i} after punctuation = {plaintext}")
        print()

def main():
    """Load text, solve null cipher."""
    # load & process message:
    filename = input("\nEnter full filename for message to translate: ")
    try:
        loaded_message = load_text(filename)
    except IOError as e:
        print("{}. Terminating program.".format(e), file=sys.stderr)
        sys.exit(1)
    print("\nORIGINAL MESSAGE = ")
    print(f"{loaded_message} \n")
    print(f"List of punctuation marks to check = {string.punctuation} \n")

    # remove whitespace
    message = ''.join(loaded_message.split())

    # get range of possible cipher keys from user:
    while True:
        lookahead = input("\nNumber of letters to check after punctuation mark: ")
        if lookahead.isdigit():
            lookahead = int(lookahead)
            break
        else:
            print("Please input a number.", file=sys.stderr)
        print()

    # run function to decode cipher
    solve_null_cipher(message, lookahead)

if __name__ == "__main__":
    main()

Ch05/Project 10 - The Trevanion Cipher/null_cipher_finder.py


import json, os
import tweepy
import time, csv
from config import config

ts = time.time()

auth = tweepy.OAuthHandler(config.CONSUMER_KEY, config.CONSUMER_SECRET)
auth.set_access_token(config.ACCESS_TOKEN, config.ACCESS_TOKEN_SECRET)

api = tweepy.API(auth)
data = []
public_tweets = api.home_timeline()

file_json = 'data-' + str(int(ts)) + '.txt'
file_csv = 'data' + str(int(ts)) + '.csv'

with open(os.path.join('/opt/datascience/tweepy/data', file_csv), 'w') as file_csv:
    data = csv.DictWriter(file_csv, ['id', 'tweet', 'datetime'])
    data.writeheader()
    for tweet in public_tweets:
        data.writerow({'id': tweet.id, 'tweet': tweet.text.encode('utf-8'), 'datetime': str(tweet.created_at)})


import pandas as pd
from ..features.feature_engineering import feature_engineering
from sklearn.preprocessing import StandardScaler
from sklearn.impute import SimpleImputer
from app import cos, init_cols

def make_dataset(data, model_info, cols_to_remove):

    """
        Function that performs data transformations.

        Args:
           data (List):  List with the new requested observation.
           model_info (dict):  Info from the model in production.

        Kwargs:

        Returns:
           DataFrame. Dataset to infere.
    """

    print('---> Getting data')
    print(data)
    data_df = get_raw_data_from_request(data)
    print('---> Transforming data and making Feature Engineering')
    data_df = transform_data(data_df, model_info, cols_to_remove)
    print('---> Inputing and Scaling')
    data_df = pre_train_data_prep(data_df, model_info)

    return data_df.copy()

def get_raw_data_from_request(data):

    """
        Function to obtain new observations

        Args:
           data (List):  List with the requested observation.

        Returns:
           DataFrame. Dataset with the input data.
    """
    return pd.DataFrame(data, columns=init_cols)

def transform_data(data_df, model_info, cols_to_remove):
    """
        Function that transforms the input data and makes feature engineering.

        Args:
            data_df (DataFrame):  Data input.
            model_info (dict):  Info. from the model in production.
            cols_to_remove (list): Cols to remove.

        Returns:
           DataFrame. Transformed data.
    """

    # Removing senseless data related to 'impossible' beam destinations
    print('------> Removing senseless data')
    data_df = remove_senseless(data_df)

    #Adding new predictors (Feature Engineering)
    print('------> Adding new predictors')
    data_df = add_predictors(data_df)

    #Removing rows with BM 'No beam'
    print('------> Removing data with BM=NoBeam')
    data_df = remove_rows_BM_zero(data_df)

    # Removing BM column
    print('------> Removing BM columns')
    data_df = remove_unwanted_columns(data_df, cols_to_remove)

    return data_df.copy()

def remove_senseless(df):
    """
        Function to remove imposible beam destinations

        Args:
           df (DataFrame):  Dataset.

        Returns:
           DataFrame. Dataset.
    """
    index_names_BD5 = df[ (df['BD_2'] == 1) & (df['BD_1'] == 0) & (df['BD_0'] == 1)].index
    index_names_BD6 = df[ (df['BD_2'] == 1) & (df['BD_1'] == 1) & (df['BD_0'] == 0)].index
    index_names_BD7 = df[ (df['BD_2'] == 1) & (df['BD_1'] == 1) & (df['BD_0'] == 1)].index
    df.drop(index_names_BD5, inplace = True)
    df.drop(index_names_BD6, inplace = True)
    df.drop(index_names_BD7, inplace = True)

    return (df)

def add_predictors(df):
    """
        Function to add new predictors (Feature Engineering)

        Args:
           df (DataFrame):  Dataset.

        Returns:
           DataFrame. Dataset.
    """
    df['Section_1'] = ((df['GV1'] == 1) & (df['GV2'] == 1) & (df['VBP1']==1) & (df['VBP2']==1)).astype(int)
    df['Section_2'] = ((df['GV3'] == 1) & (df['GV4'] == 1) & (df['VBP3']==1) & (df['VBP4']==1)).astype(int)
    df['Section_3'] = ((df['GV5'] == 1) & (df['VBP5']==1)).astype(int)
    df['Section_4'] = ((df['GV6'] == 1) & (df['GV7'] == 1) & (df['VBP6']==1) & (df['VBP7']==1)).astype(int)
    df['BtT'] = (df['Section_1'] & df['Section_2'] & df['Section_3'] & df['Section_4']).astype(int)
    return (df)

def remove_rows_BM_zero(df):
    """
        Function to remove data rows with BM zero

        Args:
           df (DataFrame):  Dataset.

        Returns:
           DataFrame. Dataset.
    """
    index_names = df[ (df['BM'] == 0) ].index
    df.drop(index_names, inplace = True)
    return (df)

def remove_unwanted_columns(df, cols_to_remove):
    """
        Function to remove unnneded columns

        Args:
           df (DataFrame):  Dataset.

        Returns:
           DataFrame. Dataset.
    """
    return df.drop(columns=cols_to_remove)

def pre_train_data_prep(data_df, model_info):
    """
        Function that makes the last transformations on the dataset NULL imputing and scaling
        Args:
           data_df (DataFrame):  dataset.

        Returns:
           DataFrame. transformed dataset.
    """

    # NULL imputing
    print('------> Getting imputer from cos')
    imputer_key = model_info['objects']['imputer']+'.pkl'
    data_df = input_missing_values(data_df, imputer_key)

    # Scaling
    print('------> Getting scaler from cos')
    scaler_key = model_info['objects']['scaler']+'.pkl'
    data_df = scale_data(data_df, scaler_key)

    return data_df.copy()

def input_missing_values(data_df, key):
    """
        Function for NULLs imputing
        Args:
           data_df (DataFrame):  dataset.

        Returns:
           DataFrame. transformed dataset.
    """

    print('------> Inputing missing values')
    # obtain the SimpleImputer object from  COS
    imputer = cos.get_object_in_cos(key)
    data_df = pd.DataFrame(imputer.transform(data_df), columns=data_df.columns)

    return data_df.copy()

def scale_data(data_df, key):
    """
        Function to scale variables
        Args:
           data_df (DataFrame):  dataset.
           Returns:
           DataFrame. dataset transformed.
    """

    print('------> Scaling values')
    # obtain the Scaled object from  COS
    scaler = cos.get_object_in_cos(key)
    data_df = pd.DataFrame(scaler.transform(data_df), columns=data_df.columns)

    return data_df.copy()


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

# # my 1st code in python
#

# In[14]:

## data types
(a,b,c,d)=(2,3.4,'hello','world')
print(type(a),type(b),type(c),type(d))
## TYPE is used to tell what is it
## PRINT used for printing or displayig the content inside it

# In[16]:

## list and tuple
A =[1,2,'hi']
B = (2,5,'friend')
print(type(A),type(B))
## [] is used to declare the nums or char & () is used to tuple

# In[ ]:


import subprocess
from pathlib import Path
from typing import Dict, Any, Sequence, Optional

from aislib.misc_utils import ensure_path_exists, get_logger

from eir_auto_gp.preprocess import gwas_pre_selection as gps

logger = get_logger(name=__name__)

def get_gwas_feature_selection_filter_config(
    genotype_data_path: str,
    data_config: Dict[str, Any],
    modelling_config: Dict[str, Any],
    feature_selection_config: Dict[str, Any],
) -> gps.GWASPreFilterConfig:
    target_names = (
        modelling_config["output_con_columns"] + modelling_config["output_cat_columns"]
    )
    covariate_names = (
        modelling_config["input_con_columns"] + modelling_config["input_cat_columns"]
    )

    fam_file_path = next(Path(genotype_data_path).glob("*.fam"))
    id_split_folder = _get_id_split_folder(
        pre_split_folder=data_config["pre_split_folder"],
        data_output_folder=data_config["data_output_folder"],
        fam_file=fam_file_path,
    )

    config = gps.GWASPreFilterConfig(
        genotype_data_path=genotype_data_path,
        label_file_path=data_config["label_file_path"],
        output_path=feature_selection_config["feature_selection_output_folder"],
        target_names=target_names,
        covariate_names=covariate_names,
        pre_split_folder=id_split_folder,
        only_gwas=True,
        p_value_threshold=feature_selection_config["gwas_p_value_threshold"],
    )

    return config

def _get_id_split_folder(
    pre_split_folder: Optional[str],
    data_output_folder: str,
    fam_file: Optional[Path] = None,
) -> str:
    if pre_split_folder is not None and Path(pre_split_folder).exists():
        return pre_split_folder

    ids_folder = Path(data_output_folder, "ids")
    if ids_folder.exists():
        gps.add_plink_format_train_test_files(fam_file=fam_file, ids_folder=ids_folder)
        return str(ids_folder)

    raise ValueError(f"Could not find ids folder in {data_output_folder}")

def run_gwas_feature_selection(
    genotype_data_path: str,
    data_config: Dict[str, Any],
    modelling_config: Dict[str, Any],
    feature_selection_config: Dict[str, Any],
) -> str | Path:
    filter_config = get_gwas_feature_selection_filter_config(
        genotype_data_path=genotype_data_path,
        data_config=data_config,
        modelling_config=modelling_config,
        feature_selection_config=feature_selection_config,
    )

    fam_file_path = next(Path(genotype_data_path).glob("*.fam"))

    gwas_label_path = Path(filter_config.output_path, "gwas_label_file.csv")
    ensure_path_exists(path=gwas_label_path)
    if not gwas_label_path.exists():
        gps.prepare_gwas_label_file(
            label_file_path=filter_config.label_file_path,
            fam_file_path=fam_file_path,
            output_path=gwas_label_path,
        )

    base_path = fam_file_path.with_suffix("")
    fs_output_folder = feature_selection_config["feature_selection_output_folder"]
    gwas_output_path = Path(fs_output_folder, "gwas_output")

    target_names = gps.parse_gwas_label_file_column_names(
        target_names=filter_config.target_names, gwas_label_file=gwas_label_path
    )

    train_ids_file = Path(filter_config.pre_split_folder, "train_ids_plink.txt")
    assert train_ids_file.exists(), f"Could not find train ids file at {train_ids_file}"

    command = gps.get_plink_gwas_command(
        base_path=base_path,
        label_file_path=gwas_label_path,
        target_names=target_names,
        covariate_names=filter_config.covariate_names,
        output_path=gwas_output_path,
        ids_file=train_ids_file,
    )

    if not all_gwas_already_finished(
        target_names=filter_config.target_names,
        gwas_output_folder=gwas_output_path,
    ):
        logger.info("Running GWAS with command: %s", " ".join(command))
        subprocess.run(command, check=True)
        gps.plot_gwas_results(
            gwas_output_path=gwas_output_path,
            p_value_line=filter_config.p_value_threshold,
        )
        gwas_label_path.unlink()

    snps_to_keep_path = gps.gather_all_snps_to_keep(
        gwas_output_folder=gwas_output_path,
        p_value_threshold=filter_config.p_value_threshold,
    )

    return snps_to_keep_path

def all_gwas_already_finished(
    target_names: Sequence[str], gwas_output_folder: str | Path
) -> bool:
    for target_name in target_names:
        gwas_file = tuple(
            i for i in Path(gwas_output_folder).glob(f"gwas.{target_name}*")
        )
        if not gwas_file:
            return False

    return True


import pygame, sys
from pygame.locals import *

# Define some colors
black    = (   0,   0,   0)
white    = ( 255, 255, 255)
green    = (   0, 255,   0)
red      = ( 255,   0,   0)

def keyPressed(inputKey):
	keysPressed = pygame.key.get_pressed()
	if keysPressed[inputKey]:
		return True
	else:
		return False

pygame.init()

# Set the height and width of the screen
size=[720,450]
screen=pygame.display.set_mode(size)
fullscreen=False

pygame.display.set_caption("Biopoiesis SOM")

#Loop until the user clicks the close button.
done=False

# Used to manage how fast the screen updates
clock=pygame.time.Clock()

# -------- Main Program Loop -----------
while done==False:
	for event in pygame.event.get(): # User did something
		if event.type == QUIT: # If user clicked close
			done=True # Flag that we are done so we exit this loop

	if keyPressed(K_ESCAPE):
		done = True
	elif keyPressed(K_f):
		if not fullscreen:
			screen = pygame.display.set_mode(size, pygame.FULLSCREEN)
			fullscreen = True
			pygame.mouse.set_visible(False)
		else:
			screen = pygame.display.set_mode(size)
			fullscreen = False
			pygame.mouse.set_visible(True)

    # Set the screen background
	screen.fill(black)

    # Limit to 20 frames per second
	clock.tick(20)

    # Go ahead and update the screen with what we've drawn.
	pygame.display.flip()

pygame.quit()
sys.exit()


'''Faça um algoritmo para ler um número indeterminado de dados, contendo cada um, a idade de um indivíduo. O último dado, que não entrará nos cálculos, contém o valor de idade negativa. Calcular e imprimir a idade média deste grupo de indivíduos.
Entrada
A entrada contém um número indeterminado de inteiros. A entrada será encerrada quando um valor negativo for lido.
Saída
A saída contém um valor correspondente à média de idade dos indivíduos.

'''
lista=[]
soma=0
num= int(input('Informe uma idade : ' ))

while num > 0 :
    if num > 0 :
        lista.append(num)
        soma+=num
        num= int(input('Informe uma idade : ' ))

media =soma/len(lista)
print(f" A quantidade de idades informadas foram {len(lista)}, a soma das idades é {soma}, e media das idades é {media} ")


import requests
import json
import os
from datetime import date, timedelta

CONST_CURRENCY = 'USD'
CONST_CLIENTID = os.getenv('CLIENTID')

def write_file(value):
    with open('out_rate', 'w') as output:
        output.write(str(value))

def read_file():
    with open('out_rate') as f:
        lines = f.readlines()
    return float(lines[0])

def get_yesterday():
    return (date.today() - timedelta(days=1)).strftime("%G-%m-%d")

def get_usdthb_raw():
    url = "https://apigw1.bot.or.th/bot/public/Stat-ExchangeRate/v2/DAILY_AVG_EXG_RATE/?start_period="+get_yesterday()+"&end_period="+get_yesterday()+"&currency="+CONST_CURRENCY
    response = requests.get(url,
                            headers={'Cache-Control': 'no-cache',
                                     'X-IBM-Client-Id': CONST_CLIENTID})

    try:
        data = json.loads(response.text)
        return data
    except requests.exceptions.Timeout:
        return 0
    except requests.exceptions.TooManyRedirects:
        return 0
    except requests.exceptions.RequestException as e:
        return 0

def get_usdthb():
    raw = get_usdthb_raw()
    if(not raw):
        return 0

    try:
        new_rate = float(raw['result']['data']['data_detail'][0]['mid_rate'])
        write_file(new_rate)
        return new_rate
    except:
        return read_file()

if __name__ == "__main__":
    print(get_yesterday())
    print(get_usdthb())


import json
import numpy as np
import pickle
from torch.utils.data import Dataset

NYU40CLASSES = ('void',
                'wall', 'floor', 'cabinet', 'bed', 'chair',
                'sofa', 'table', 'door', 'window', 'bookshelf',
                'picture', 'counter', 'blinds', 'desk', 'shelves',
                'curtain', 'dresser', 'pillow', 'mirror', 'floor_mat',
                'clothes', 'ceiling', 'books', 'refridgerator', 'television',
                'paper', 'towel', 'shower_curtain', 'box', 'whiteboard',
                'person', 'night_stand', 'toilet', 'sink', 'lamp',
                'bathtub', 'bag', 'otherstructure', 'otherfurniture', 'otherprop')

class SunDataset_2DBB(Dataset):
    def __init__(self, root_path='../', mode='train'):
        """
        self.root_path:    Get the data_path
        self.file_idx = []:    Get the file index, train: idx 5051 to 10335, test: idx 1 to 5050
        """
        self.root_path = root_path
        self.file_idx = []
        if mode == 'train':
            with open(self.root_path + '/data/sunrgbd/splits/train.json') as json_file:
                self.file_idx = json.load(json_file)
        elif mode == 'test':
            with open(self.root_path + '/data/sunrgbd/splits/test.json') as json_file:
                self.file_idx = json.load(json_file)

    def __len__(self):
        return len(self.file_idx)

    def __getitem__(self, idx):
        """
        Return: img, 2d bounding boxes, labels
        """
        data_pkl = pickle.load(open(self.root_path + self.file_idx[idx][1:], 'rb'))
        boxes = data_pkl['boxes']
        bbox = [[boxes['bdb2D_pos'][i][1], boxes['bdb2D_pos'][i][0], boxes['bdb2D_pos'][i][3], boxes['bdb2D_pos'][i][2]]
                for i in range(boxes['bdb2D_pos'].shape[0])]
        return np.float32(data_pkl['rgb_img'].transpose((2, 0, 1))), np.float32(bbox), boxes['size_cls']


from functools import partial
from torch import nn
from torch.optim import Optimizer
from typing import Generator
import torch
import logging
from src.helps import ConfigurationError
from torch.optim.lr_scheduler import ReduceLROnPlateau, StepLR, ExponentialLR

logger = logging.getLogger(__name__)

def build_gradient_clipper(train_cfg: dict):
    """
    Define the function for gradient clipping as specified in configuration.
    Current Options:
        clip_grad_val: clip the gradients if they exceed value
            torch.nn.utils.clip_grad_value_
        clip_grad_norm: clip the gradients if they norm exceeds this value
            torch.nn.utils.clip_grad_norm_
    """
    clip_grad_function = None
    if "clip_grad_val" in train_cfg.keys():
        clip_grad_function = partial(nn.utils.clip_grad_value_, clip_value=train_cfg["clip_grad_val"])
    elif "clip_grad_norm" in train_cfg.keys():
        clip_grad_function = partial(nn.utils.clip_grad_norm_, max_norm=train_cfg["clip_grad_norm"])
    return clip_grad_function

def build_optimizer(train_cfg:dict, parameters: Generator)  -> Optimizer:
    """
    Create an optimzer for the given parameters as specified in config.
    """
    optimizer_name = train_cfg.get("optimizer",'adam').lower()
    kwargs = {"lr": train_cfg.get("learning_rate", 3e-4), "weight_decay":train_cfg.get("weight_decay",0)}
    if optimizer_name == "adam":
        kwargs["betas"] = train_cfg.get("adam_betas", (0.9, 0.999))
        # kwargs: lr; weight_decay; betas
        optimizer = torch.optim.Adam(parameters, **kwargs)
    elif optimizer_name == "sgd":
        # kwargs: lr; momentum; dampening; weight_decay; nestrov
        optimizer = torch.optim.SGD(parameters, **kwargs)
    else:
        raise ConfigurationError("Invalid optimizer.")

    logger.info("%s(%s)", optimizer.__class__.__name__, ", ".join([f"{key}={value}" for key,value in kwargs.items()]))
    return optimizer

def build_scheduler(train_cfg:dict, optimizer:Optimizer):
    """
    Create a learning rate scheduler if specified in train config and determine
    when a scheduler step should be executed.
    return:
        - scheduler: scheduler object
        - scheduler_step_at: "validation", "epoch", "step" or "none"
    """
    scheduler, scheduler_step_at = None, None
    scheduler_name = train_cfg.get("scheduling", None)
    assert scheduler_name in ["StepLR", "ExponentialLR", "ReduceLROnPlateau"], "Invalid scheduling."

    if scheduler_name == "ReduceLROnPlateau":
        mode = train_cfg.get("mode", "max")
        factor = train_cfg.get("factor", 0.5)
        patience = train_cfg.get("patience", 5)
        scheduler = ReduceLROnPlateau(optimizer, mode=mode, factor=factor, patience=patience,
                        threshold=0.0001, threshold_mode='abs', eps=1e-8)
        scheduler_step_at = "validation"
    elif scheduler_name == "StepLR":
        step_size = train_cfg.get("step_size", 5)
        gamma = train_cfg.get("gamma", 0.1)
        scheduler = StepLR(optimizer, step_size=step_size, gamma=gamma)
        scheduler_step_at = "epoch"
    elif scheduler_name == "ExponentialLR":
        gamma  = train_cfg.get("gamma", 0.98)
        scheduler = ExponentialLR(optimizer, gamma=gamma)
        scheduler_step_at = "epoch"
    else:
        raise ConfigurationError("Invalid scheduling setting.")

    logger.info("Scheduler = %s", scheduler.__class__.__name__)
    return scheduler, scheduler_step_at


class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        result = ""
        for i in zip(*strs):
            tmp = set(i)
            if len(tmp) == 1:
                result += i[0]
            else:
                return result
        return result


#!/usr/bin/env python
# encoding: utf-8
# @author: qiaoxc
# @file: try_except_else.py
# @time: 2021/11/24 23:30
# @desc:
'''
    try:
        正常逻辑
    except  错误类型1:
        报错之后的处理逻辑
    except baseException:
        报错之后的处理逻辑
    else:
        如果没有出错，执行该代码体
    finally:
        无论是否报错，都执行该代码体

备注：except 与 else 只执行一个方法体
'''

'''
traceback打印异常：

'''
import traceback

# num2 = 10/0

try:
    print('------')
    num = 10/0
except:
    traceback.print_exc()  # 打印报错日志


#for i, j in enumerate()

import tensorflow as tf
from tensorflow.python import debug as tf_debug

a = tf.constant([1, 2, 3])
b = tf.constant([5, 6, 5, 4, 4])

a = tf.Print(a, [a, b], message="a, b ", first_n=3, summarize=5)

c = a + b
a = a + c

with tf.Session() as sess:
    sess = tf_debug.LocalCLIDebugWrapperSession(sess)
    sess.add_tensor_filter("has_inf_or_nan", tf_debug.has_inf_or_nan)

    for _ in range(10):
        result = sess.run(a)
    print(result)


import inspect
import logging
import os
import traceback
from functools import wraps
from subprocess import PIPE, run
from typing import List

from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt

from rcon.broadcast import get_votes_status
from rcon.cache_utils import RedisCached, get_redis_pool
from rcon.commands import CommandFailedError
from rcon.config import get_config
from rcon.discord import send_to_discord_audit
from rcon.extended_commands import MOD_ALLOWED_CMDS
from rcon.gtx import GTXFtp
from rcon.player_history import add_player_to_blacklist, remove_player_from_blacklist
from rcon.recorded_commands import RecordedRcon
from rcon.settings import SERVER_INFO
from rcon.user_config import (
    AutoBroadcasts,
    AutoVoteKickConfig,
    CameraConfig,
    DiscordHookConfig,
    InvalidConfigurationError,
    StandardMessages,
)
from rcon.utils import LONG_HUMAN_MAP_NAMES, MapsHistory, map_name
from rcon.watchlist import PlayerWatch
from rcon.workers import temporary_broadcast, temporary_welcome

from .audit_log import auto_record_audit, record_audit
from .auth import api_response, login_required
from .multi_servers import forward_command, forward_request
from .utils import _get_data

logger = logging.getLogger("rconweb")
ctl = RecordedRcon(SERVER_INFO)

def set_temp_msg(request, func, name):
    data = _get_data(request)
    failed = False
    error = None
    try:
        func(ctl, data["msg"], data["seconds"])
    except Exception as e:
        failed = True
        error = repr(e)

    return api_response(failed=failed, error=error, result=None, command=name)

@csrf_exempt
@login_required(True)
@record_audit
def set_name(request):
    data = _get_data(request)
    failed = False
    error = None
    try:
        gtx = GTXFtp.from_config()
        gtx.change_server_name(data["name"])
    except Exception as e:
        failed = True
        error = repr(e)
    return api_response(
        failed=failed, error=error, result=None, command="set_server_name"
    )

@csrf_exempt
@login_required(True)
@record_audit
def set_temp_broadcast(request):
    return set_temp_msg(request, temporary_broadcast, "set_temp_broadcast")

@csrf_exempt
@login_required(True)
@record_audit
def set_temp_welcome(request):
    return set_temp_msg(request, temporary_welcome, "set_temp_welcome")

@csrf_exempt
def get_version(request):
    res = run(["git", "describe", "--tags"], stdout=PIPE, stderr=PIPE)
    return api_response(res.stdout.decode(), failed=False, command="get_version")

@csrf_exempt
def public_info(request):
    gamestate = ctl.get_gamestate()
    curr_players, max_players = tuple(map(int, ctl.get_slots().split("/")))
    try:
        current_map_start = MapsHistory(max_len=1)[0]["start"]
    except IndexError:
        logger.error("Can't get current map time, map_recorder is probably offline")
        current_map_start = None

    def explode_map_info(game_map: str, start) -> dict:
        return dict(
            just_name=map_name(game_map),
            human_name=LONG_HUMAN_MAP_NAMES.get(game_map, game_map),
            name=game_map,
            start=start,
        )

    return api_response(
        result=dict(
            current_map=explode_map_info(gamestate["current_map"], current_map_start),
            next_map=explode_map_info(gamestate["next_map"], None),
            player_count=curr_players,
            max_player_count=max_players,
            players=dict(
                allied=gamestate["num_allied_players"],
                axis=gamestate["num_axis_players"],
            ),
            score=dict(allied=gamestate["allied_score"], axis=gamestate["axis_score"]),
            raw_time_remaining=gamestate["raw_time_remaining"],
            vote_status=get_votes_status(none_on_fail=True),
            name=ctl.get_name(),
            short_name=os.getenv("SERVER_SHORT_NAME", "HLL RCON"),
            public_stats_port=os.getenv("PUBLIC_STATS_PORT", "Not defined"),
            public_stats_port_https=os.getenv("PUBLIC_STATS_PORT_HTTPS", "Not defined"),
        ),
        failed=False,
        command="public_info",
    )

@csrf_exempt
@login_required(True)
def get_hooks(request):
    return api_response(
        result=DiscordHookConfig.get_all_hook_types(as_dict=True),
        command="get_hooks",
        failed=False,
    )

@csrf_exempt
@login_required(True)
@record_audit
def set_hooks(request):
    data = _get_data(request)

    hook_config = DiscordHookConfig(for_type=data["name"])
    hook_config.set_hooks(data["hooks"])

    audit("set_hooks", request, data)
    return api_response(
        result=DiscordHookConfig.get_all_hook_types(),
        command="get_hooks",
        failed=False,
    )

@csrf_exempt
@login_required(True)
def get_camera_config(request):
    config = CameraConfig()
    return api_response(
        result={
            "broadcast": config.is_broadcast(),
            "welcome": config.is_welcome(),
        },
        command="get_camera_config",
        failed=False,
    )

@csrf_exempt
@login_required(True)
def get_votekick_autotoggle_config(request):
    config = AutoVoteKickConfig()
    return api_response(
        result={
            "min_ingame_mods": config.get_min_ingame_mods(),
            "min_online_mods": config.get_min_online_mods(),
            "is_enabled": config.is_enabled(),
            "condition_type": config.get_condition_type(),
        },
        command="get_votekick_autotoggle_config",
        failed=False,
    )

@csrf_exempt
@login_required(True)
@record_audit
def set_votekick_autotoggle_config(request):
    config = AutoVoteKickConfig()
    data = _get_data(request)
    funcs = {
        "min_ingame_mods": config.set_min_ingame_mods,
        "min_online_mods": config.set_min_online_mods,
        "is_enabled": config.set_is_enabled,
        "condition_type": config.set_condition_type,
    }

    for k, v in data.items():
        try:
            funcs[k](v)
        except KeyError:
            return api_response(
                error="{} invalid key".format(k),
                command="set_votekick_autotoggle_config",
            )

        audit("set_votekick_autotoggle_config", request, {k: v})

    return api_response(
        command="set_votekick_autotoggle_config",
        failed=False,
    )

@csrf_exempt
@login_required(True)
@record_audit
def set_camera_config(request):
    config = CameraConfig()
    data = _get_data(request)

    funcs = {
        "broadcast": config.set_broadcast,
        "welcome": config.set_welcome,
    }

    for k, v in data.items():
        if not isinstance(v, bool):
            return api_response(
                error="Values must be boolean", command="set_camera_config"
            )
        try:
            funcs[k](v)
        except KeyError:
            return api_response(
                error="{} invalid key".format(k), command="set_camera_config"
            )

        audit("set_camera_config", request, {k: v})

    return api_response(
        result={
            "broadcast": config.is_broadcast(),
            "welcome": config.is_welcome(),
        },
        command="set_camera_config",
        failed=False,
    )

def _do_watch(request, add: bool):
    data = _get_data(request)
    error = None
    failed = True
    result = None

    try:
        watcher = PlayerWatch(data["steam_id_64"])
        if add:
            params = dict(
                reason=data["reason"],
                by=request.user.username,
                player_name=data.get("player_name"),
                steam_id_64=data.get("steam_id_64"),
            )
            # watch(self, reason: str, by: str, player_name: str = "")
            result = watcher.watch(
                reason=params["reason"],
                by=params["by"],
                player_name=params["player_name"],
            )
            audit("do_watch_player", request, params)
        else:
            result = watcher.unwatch()
            audit(
                "do_unwatch_player",
                request,
                dict(
                    player_name=data.get("player_name"), steam_id_64=data["steam_id_64"]
                ),
            )
        failed = False
    except KeyError as e:
        error = f"No {e.args} provided"
    except CommandFailedError as e:
        error = e.args[0]

    return api_response(
        result=result,
        arguments=data,
        error=error,
        command="do_watch_player",
        failed=failed,
    )

@csrf_exempt
@login_required()
@record_audit
def do_watch_player(request):
    return _do_watch(request, add=True)

@csrf_exempt
@login_required()
@record_audit
def do_unwatch_player(request):
    return _do_watch(request, add=False)

@csrf_exempt
@login_required()
@record_audit
def clear_cache(request):
    res = RedisCached.clear_all_caches(get_redis_pool())
    audit("clear_cache", request, {})
    return JsonResponse(
        {
            "result": res,
            "command": "clear_cache",
            "arguments": None,
            "failed": res is None,
        }
    )

@csrf_exempt
@login_required(True)
def get_auto_broadcasts_config(request):
    failed = False
    config = None

    try:
        broadcasts = AutoBroadcasts()
        config = {
            "messages": ["{} {}".format(m[0], m[1]) for m in broadcasts.get_messages()],
            "randomized": broadcasts.get_randomize(),
            "enabled": broadcasts.get_enabled(),
        }
    except:
        logger.exception("Error fetch broadcasts config")
        failed = True

    return JsonResponse(
        {
            "result": config,
            "command": "get_auto_broadcasts_config",
            "arguments": None,
            "failed": failed,
        }
    )

@csrf_exempt
@login_required(True)
@record_audit
def set_auto_broadcasts_config(request):
    failed = False
    res = None
    data = _get_data(request)
    broadcasts = AutoBroadcasts()
    config_keys = {
        "messages": broadcasts.set_messages,
        "randomized": broadcasts.set_randomize,
        "enabled": broadcasts.set_enabled,
    }
    try:
        for k, v in data.items():
            if k in config_keys:
                config_keys[k](v)
                audit(set_auto_broadcasts_config.__name__, request, {k: v})
    except InvalidConfigurationError as e:
        failed = True
        res = str(e)

    return JsonResponse(
        {
            "result": res,
            "command": "set_auto_broadcasts_config",
            "arguments": data,
            "failed": failed,
        }
    )

@csrf_exempt
def get_standard_messages(request):
    failed = False
    data = _get_data(request)

    try:
        msgs = StandardMessages()
        res = msgs.get_messages(data["message_type"])
    except CommandFailedError as e:
        failed = True
        res = repr(e)
    except:
        logger.exception("Error fetching standard messages config")
        failed = True
        res = "Error setting standard messages config"

    return JsonResponse(
        {
            "result": res,
            "command": "get_standard_messages",
            "arguments": data,
            "failed": failed,
        }
    )

@csrf_exempt
@login_required(True)
@record_audit
def set_standard_messages(request):
    failed = False
    data = _get_data(request)

    try:
        msgs = StandardMessages()
        res = msgs.set_messages(data["message_type"], data["messages"])
        send_to_discord_audit("set_standard_messages", request.user.username)
    except CommandFailedError as e:
        failed = True
        res = repr(e)
    except:
        logger.exception("Error setting standard messages config")
        failed = True
        res = "Error setting standard messages config"

    return JsonResponse(
        {
            "result": res,
            "command": "get_standard_messages",
            "arguments": data,
            "failed": failed,
        }
    )

@csrf_exempt
@login_required()
@record_audit
def blacklist_player(request):
    data = _get_data(request)
    res = {}
    try:
        name = data["name"] if "name" in data else None
        # Using the the perma ban by steamid actually sucks because the player won't see the reason for his ban
        # Also it could seem interesting to use it, so that if the player is on the server at the time of the
        # Blacklist he'd be banned immediately, however that's not the case, which is apparently a bug
        # ctl.do_perma_ban(
        #     steam_id_64=data["steam_id_64"], reason=data["reason"], by=name
        # )
        add_player_to_blacklist(
            data["steam_id_64"], data["reason"], name, request.user.username
        )
        audit("Blacklist", request, data)
        failed = False
    except:
        logger.exception("Unable to blacklist player")
        failed = True

    return JsonResponse(
        {
            "result": res,
            "command": "blacklist_player",
            "arguments": data,
            "failed": failed,
        }
    )

@csrf_exempt
@login_required()
@record_audit
def unblacklist_player(request):
    data = _get_data(request)
    res = {}

    potential_failed_unbans: List[str] = []
    try:
        remove_player_from_blacklist(data["steam_id_64"])
        audit("unblacklist", request, data)
        if get_config()["BANS"]["unblacklist_does_unban"]:
            # also remove bans
            potential_failed_unbans = ctl.do_unban(data["steam_id_64"])
            if get_config()["MULTI_SERVERS"]["broadcast_unbans"]:
                forward_command(
                    "/api/do_unban",
                    json=data,
                    sessionid=request.COOKIES.get("sessionid"),
                )

        failed = False

        if potential_failed_unbans:
            raise CommandFailedError(", ".join(potential_failed_unbans))
    except:
        logger.exception("Unable to unblacklist player")
        failed = True

    return JsonResponse(
        {
            "result": res,
            "command": "unblacklist_player",
            "arguments": data,
            "failed": failed,
            "error": ", ".join(potential_failed_unbans),
        }
    )

@csrf_exempt
@login_required()
@record_audit
def unban(request):
    data = _get_data(request)
    res = {}
    results = None

    potential_failed_unbans: List[str] = []
    try:
        # also remove bans
        potential_failed_unbans = ctl.do_unban(data["steam_id_64"])
        audit("unban", request, data)
        if get_config()["MULTI_SERVERS"]["broadcast_unbans"]:
            results = forward_command(
                "/api/do_unban", json=data, sessionid=request.COOKIES.get("sessionid")
            )
        if get_config()["BANS"]["unban_does_unblacklist"]:
            try:
                remove_player_from_blacklist(data["steam_id_64"])
            except CommandFailedError:
                logger.warning("Player %s was not on blacklist", data["steam_id_64"])
        failed = False

        if potential_failed_unbans:
            raise CommandFailedError(", ".join(potential_failed_unbans))

    except:
        logger.exception("Unable to unban player")
        failed = True

    return JsonResponse(
        {
            "result": res,
            "command": "unban_player",
            "arguments": data,
            "failed": failed,
            "error": ", ".join(potential_failed_unbans),
            "forward_results": results,
        }
    )

def audit(func_name, request, arguments):
    dont_audit = ["get_"]

    try:
        if any(func_name.startswith(s) for s in dont_audit):
            return
        args = dict(**arguments)
        try:
            del args["by"]
        except KeyError:
            pass
        arguments = " ".join([f"{k}: `{v}`" for k, v in args.items()])
        send_to_discord_audit(
            "`{}`: {}".format(func_name, arguments), request.user.username
        )
    except:
        logger.exception("Can't send audit log")

# This is were all the RCON commands are turned into HTTP endpoints
def wrap_method(func, parameters, command_name, require_perms=False):
    @csrf_exempt
    @login_required(require_perms)
    @auto_record_audit(command_name)
    @wraps(func)
    def wrapper(request):
        logger = logging.getLogger("rconweb")
        arguments = {}
        data = {}
        failure = False
        others = None
        error = ""
        data = _get_data(request)

        for pname, param in parameters.items():
            if pname == "by":
                arguments[pname] = request.user.username
            elif param.default != inspect._empty:
                arguments[pname] = data.get(pname, param.default)
            else:
                try:
                    arguments[pname] = data[pname]
                except KeyError:
                    # TODO raise 400
                    raise

        try:
            logger.debug("%s %s", func.__name__, arguments)
            res = func(**arguments)
            audit(func.__name__, request, arguments)
        except CommandFailedError as e:
            failure = True
            error = e.args[0] if e.args else None
            res = None

        response = JsonResponse(
            dict(
                result=res,
                command=func.__name__,
                arguments=data,
                failed=failure,
                error=error,
                forward_results=others,
            )
        )
        if data.get("forward"):
            if command_name == "do_temp_ban" and not get_config().get(
                "MULTI_SERVERS", {}
            ).get("broadcast_temp_bans", True):
                logger.debug("Not broadcasting temp ban due to settings")
                return response
            try:
                others = forward_request(request)
            except:
                logger.exception("Unexpected error while forwarding request")
        # logger.debug("%s %s -> %s", func.__name__, arguments, res)
        return response

    return wrapper

@login_required()
@csrf_exempt
def get_connection_info(request):
    return api_response(
        {
            "name": ctl.get_name(),
            "port": os.getenv("RCONWEB_PORT"),
            "link": os.getenv("RCONWEB_SERVER_URL"),
        },
        failed=False,
        command="get_connection_info",
    )

@csrf_exempt
@login_required(True)
def run_raw_command(request):
    data = _get_data(request)
    command = data.get("command")
    if not command:
        res = 'Parameter "command" must not be none'
    else:
        try:
            res = ctl._request(command, can_fail=True, log_info=True)
        except CommandFailedError:
            res = "Command returned FAIL"
        except:
            logging.exception("Internal error when executing raw command")
            res = "Internal error!\n\n" + traceback.format_exc()
    return HttpResponse(res, content_type="text/plain")

PREFIXES_TO_EXPOSE = ["get_", "set_", "do_"]

commands = [
    ("blacklist_player", blacklist_player),
    ("unblacklist_player", unblacklist_player),
    ("get_auto_broadcasts_config", get_auto_broadcasts_config),
    ("set_auto_broadcasts_config", set_auto_broadcasts_config),
    ("clear_cache", clear_cache),
    ("get_standard_messages", get_standard_messages),
    ("set_standard_messages", set_standard_messages),
    ("get_version", get_version),
    ("get_connection_info", get_connection_info),
    ("unban", unban),
    ("get_hooks", get_hooks),
    ("set_hooks", set_hooks),
    ("do_unwatch_player", do_unwatch_player),
    ("do_watch_player", do_watch_player),
    ("public_info", public_info),
    ("set_camera_config", set_camera_config),
    ("get_camera_config", get_camera_config),
    ("set_votekick_autotoggle_config", set_votekick_autotoggle_config),
    ("get_votekick_autotoggle_config", get_votekick_autotoggle_config),
    ("set_name", set_name),
    ("run_raw_command", run_raw_command),
]

logger.info("Initializing endpoint")

try:
    # Dynamically register all the methods from ServerCtl
    for name, func in inspect.getmembers(ctl):
        if not any(name.startswith(prefix) for prefix in PREFIXES_TO_EXPOSE):
            continue

        require_perms = name not in MOD_ALLOWED_CMDS

        commands.append(
            (
                name,
                wrap_method(
                    func,
                    inspect.signature(func).parameters,
                    name,
                    require_perms=require_perms,
                ),
            )
        )
    logger.info("Done Initializing endpoint")
except:
    logger.exception("Failed to initialized endpoints - Most likely bad configuration")
    raise

# Warm the cache as fetching steam profile 1 by 1 takes a while
if not os.getenv("DJANGO_DEBUG", None):
    try:
        logger.warning("Warming up the cache this may take minutes")
        ctl.get_players()
        logger.warning("Cache warm up done")
    except:
        logger.exception("Failed to warm the cache")


# sample period in seconds, controls how fast the game starts out
STARTING_SAMPLE_PERIOD = 0.3

# list of pins to use for the led strip, uses BCM numbering
LED_PINS = [26, 21, 20, 16, 12]

# pin to use for the button, uses BCM numbering
BUTTON_PIN = 13

# number of lives you start with when you start a new round
STARTING_NUM_LIVES = 3


from os import error
import serial
from serial.serialutil import EIGHTBITS, PARITY_NONE, STOPBITS_ONE
import threading

class Logic:
    port = serial.Serial()
    def __init__(self, debug_handler, out_handler) -> None:
        errors = 0
        port_interfaces = ('COM1', 'COM2')
        self.debug_handler, self.out_handler = debug_handler, out_handler
        for i in port_interfaces:
            try:
                self.port = serial.Serial(i)
                self.debug_handler("Port {} has opened\n".format(i))
                thread = threading.Thread(target=self.read)
                thread.start()
                return
            except IOError:
                errors += 1
                if error == len(port_interfaces):
                    self.debug_handler("[ERROR] Port's can't be opened!\n")

    def close(self):
        if self.port.isOpen() == True:
            self.port.close()

    def read(self):
        message = bytes()
        while True:
            reading_buffer = self.port.read(1)
            if len(reading_buffer) == 0:
                if self.port.isOpen() != True:
                    break
                continue
            if reading_buffer == b'\x00':
                self.out_handler(message)
                message = bytes()
            else:
                message += reading_buffer

    def write(self, string):
        if self.port.isOpen() == False:
            self.debug_handler("Data didn't send: port is closed\n")
            return False
        for c in string:
            self.port.write(c.encode('utf-8'))
        self.port.write('\0'.encode('utf-8'))
        return True

    def switch_baudrate(self, new_baudrate):
        if self.port.isOpen() == False:
            self.debug_handler("Can't switch baudrate: port is closed\n")
            return
        if self.port.baudrate == new_baudrate:
            return
        self.port.baudrate = new_baudrate
        self.debug_handler('New baudrate is {}\n'.format(self.port.baudrate))


# Bon Appetit: https://www.hackerrank.com/challenges/bon-appetit/problem

def bonAppetit(bill, didntEat, annaPay):
    realBill = (sum(bill) - bill[didntEat])//2
    if annaPay == realBill:
        return 'Bon Appetit'
    else:
        return abs(realBill - annaPay)

bill1 = [3, 10, 2, 9]
dE1 = 1
aP1 = 7

print(bonAppetit(bill1, dE1, aP1))


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 26 11:20:35 2018

@author: ycan
"""
import os
import warnings
import iofuncs as iof
import numpy as np
import matplotlib.pyplot as plt
import plotfuncs as plf

def allonoff(exp_name, stim_nrs):

    if isinstance(stim_nrs, int) or len(stim_nrs) <= 1:
        print('Multiple onoffsteps stimuli expected, '
              'allonoff analysis will be skipped.')
        return

    exp_dir = iof.exp_dir_fixer(exp_name)
    exp_name = os.path.split(exp_dir)[-1]

    for j, stim in enumerate(stim_nrs):
        data = iof.load(exp_name, stim)
        all_frs = data['all_frs']
        clusters = data['clusters']
        preframe_duration = data['preframe_duration']
        stim_duration = data['stim_duration']
        onoffbias = data['onoffbias']
        t = data['t']

        if j == 0:
            a = np.zeros((clusters.shape[0], t.shape[0], len(stim_nrs)))
            bias = np.zeros((clusters.shape[0], len(stim_nrs)))
        a[:, :, j] = np.array(all_frs)
        bias[:, j] = onoffbias

    plotpath = os.path.join(exp_dir, 'data_analysis', 'allonoff')
    clusterids = plf.clusters_to_ids(clusters)
    if not os.path.isdir(plotpath):
        os.makedirs(plotpath, exist_ok=True)

    for i in range(clusters.shape[0]):
        ax = plt.subplot(111)
        for j, stim in enumerate(stim_nrs):
            labeltxt = (iof.getstimname(exp_name,
                                        stim).replace('onoffsteps_', '')
                        + f' Bias: {bias[i, j]:4.2f}')
            plt.plot(t, a[i, :, j], alpha=.5,
                     label=labeltxt)
        plt.title(f'{exp_name}\n{clusterids[i]}')
        plt.legend()
        plf.spineless(ax)
        plf.drawonoff(ax, preframe_duration, stim_duration, h=.1)

        plt.savefig(os.path.join(plotpath, clusterids[i])+'.svg',
                    format='svg', dpi=300)
        plt.close()

    rows = len(stim_nrs)
    columns = 1
    _, axes = plt.subplots(rows, columns, sharex=True)
    colors = plt.get_cmap('tab10')

    for i, stim in enumerate(stim_nrs):
        ax = axes[i]
        with warnings.catch_warnings():
            warnings.filterwarnings('ignore', category=RuntimeWarning)
            ax.hist(bias[:, i], bins=20, color=colors(i),
                    range=[-1, 1], alpha=.5)

        ax.set_ylabel(iof.getstimname(exp_name,
                                      stim).replace('onoffsteps_', ''))
        plf.spineless(ax)
    plt.suptitle(f'Distribution of On-Off Indices for {exp_name}')
    plt.subplots_adjust(top=.95)
    plt.xlabel('On-Off index')
    plt.savefig(os.path.join(exp_dir, 'data_analysis', 'onoffindex_dist.svg'),
                format='svg', dpi=300)
    plt.close()


from datetime import datetime

import requests

def get_hour(time):
    return int(time.split("T")[1].split(":")[0])

LATITUDE = 51.507351
LONGITUDE = -0.127758
URL = "https://api.sunrise-sunset.org/json"

params = {
    "lat": LATITUDE,
    "lng": LONGITUDE,
    "formatted": 0
}
response = requests.get(URL, params=params)
response.raise_for_status()
data = response.json()
print(data)

sunrise = data['results']['sunrise']
sunset = data['results']['sunset']
print(sunrise, sunset)

sunrise = get_hour(data['results']['sunrise'])
sunset = get_hour(data['results']['sunset'])
print(sunrise, sunset)

now = datetime.now()


""" From "COMPUTATIONAL PHYSICS" & "COMPUTER PROBLEMS in PHYSICS"
    by RH Landau, MJ Paez, and CC Bordeianu (deceased)
    Copyright R Landau, Oregon State Unv, MJ Paez, Univ Antioquia,
    C Bordeianu, Univ Bucharest, 2017.
    Please respect copyright & acknowledge our work."""

# VectoField.py: Visualize dipole field, based on scipython example

import sys, numpy as np, matplotlib.pyplot as plt
from matplotlib.patches import Circle

def E(q, r0, x, y):
    """Return the electric field vector E=(Ex,Ey) due to charge q at r0."""
    den = ((x-r0[0])**2 + (y-r0[1])**2)**1.5
    return q * (x - r0[0]) / den, q * (y - r0[1]) / den

# Grid of x, y points
nx, ny = 64, 64
x = np.linspace(-2, 2, nx)
y = np.linspace(-2, 2, ny)
X, Y = np.meshgrid(x, y)

# Create a multipole with nq charges of alternating sign, equally spaced
# on the unit circle.
nq = 2
charges = []
for i in range(nq):
    q = i%2 * 2 - 1
    charges.append((q, (np.cos(2*np.pi*i/nq), np.sin(2*np.pi*i/nq))))

# Electric field vector, E=(Ex, Ey), as separate components
Ex, Ey = np.zeros((ny, nx)), np.zeros((ny, nx))
for charge in charges:
    ex, ey = E(*charge, x=X, y=Y)
    Ex += ex
    Ey += ey

fig = plt.figure()
ax = fig.add_subplot(111)

# Plot the streamlines with an appropriate colormap and arrow style
color = np.log(np.sqrt(Ex**2 + Ey**2))
ax.streamplot(x, y, Ex, Ey, color=color, linewidth=1, cmap=plt.cm.inferno,
              density=2, arrowstyle='->', arrowsize=1.5)

# Add filled circles for the charges themselves
charge_colors = {True: '#aa0000', False: '#0000aa'}
for q, pos in charges:
    ax.add_artist(Circle(pos, 0.05, color=charge_colors[q>0]))

ax.set_xlabel('$x$')
ax.set_ylabel('$y$')
ax.set_xlim(-2,2)
ax.set_ylim(-2,2)
ax.set_aspect('equal')
plt.show()