import sqlite3
from zipfile import ZipFile
from tempfile import TemporaryDirectory
import json
from tqdm import tqdm
import os
import re
import logging

from .config import config
from .util import MediaType
from . import db

def init(database, **kwargs):
    db.database.init(database, **kwargs)
    if not os.path.exists(database):
        db.create_all_tables()

def update_config(markdown=False, srs=None):
    config.update(markdown=markdown, srs=srs)
    if db.Settings.get_or_none() is None:
        db.Settings().save()
    else:
        config.update(db.Settings.to_dict())

def import_apkg(src_apkg, skip_media=False):
    """

    :param src_apkg:
    :param bool|list skip_media:
    :return:
    """
    info = dict()

    with TemporaryDirectory() as temp_dir:
        with db.database.atomic():
            with ZipFile(src_apkg) as zf:
                zf.extractall(temp_dir)

            conn = sqlite3.connect(os.path.join(temp_dir, 'collection.anki2'))
            conn.row_factory = sqlite3.Row

            try:
                d = dict(conn.execute('''SELECT * FROM col LIMIT 1''').fetchone())
                for model in tqdm(tuple(json.loads(d['models']).values()), desc='models'):
                    db.Model.create(
                        id=model['id'],
                        name=model['name'],
                        css=model['css']
                    )

                    info.setdefault('model', dict())[int(model['id'])] = model
                    for media_name in re.findall(r'url\([\'\"]((?!.*//)[^\'\"]+)[\'\"]\)', model['css']):
                        info.setdefault('media', dict())\
                            .setdefault(MediaType.font, dict())\
                            .setdefault(media_name, [])\
                            .append(model['id'])

                    for template in model['tmpls']:
                        db_template = db.Template.get_or_create(
                            model_id=model['id'],
                            name=template['name'],
                            question=template['qfmt'],
                            answer=template['afmt'],
                        )[0]

                        info.setdefault('template', dict())[db_template.id] = template

                for deck in tqdm(tuple(json.loads(d['decks']).values()), desc='decks'):
                    db.Deck.create(
                        id=deck['id'],
                        name=deck['name']
                    )

                c = conn.execute('''SELECT * FROM notes''')
                for note in tqdm(c.fetchall(), desc='notes'):
                    info_model = info['model'][note['mid']]
                    header = [field['name'] for field in info_model['flds']]

                    db_note = db.Note.create(
                        id=note['id'],
                        model_id=note['mid'],
                        data=dict(zip(header, note['flds'].split('\u001f')))
                    )

                    for tag in set(t for t in note['tags'].split(' ') if t):
                        db_tag = db.Tag.get_or_create(
                            name=tag
                        )[0]

                        db_tag.notes.add(db_note)

                    info.setdefault('note', dict())[note['id']] = dict(note)

                    for media_name in re.findall(r'src=[\'\"]((?!.*//)[^\'\"]+)[\'\"]', note['flds']):
                        info.setdefault('media', dict())\
                            .setdefault(MediaType.image, dict())\
                            .setdefault(media_name, [])\
                            .append(note['id'])

                    for media_name in re.findall(r'\[sound:[^\]]+\]', note['flds']):
                        info.setdefault('media', dict()) \
                            .setdefault(MediaType.audio, dict()) \
                            .setdefault(media_name, []) \
                            .append(note['id'])

                c = conn.execute('''SELECT * FROM cards''')
                for card in tqdm(c.fetchall(), desc='cards'):
                    info_note = info['note'][card['nid']]
                    info_model = info['model'][info_note['mid']]
                    db_model = db.Model.get(id=info_model['id'])
                    db_template = db_model.templates[0]

                    if '{{cloze:' not in db_template.question:
                        db_template = db_model.templates[card['ord']]
                        db.Card.create(
                            id=card['id'],
                            note_id=card['nid'],
                            deck_id=card['did'],
                            template_id=db_template.id
                        )
                    else:
                        for db_template_n in db_model.templates:
                            db.Card.create(
                                id=card['id'],
                                note_id=card['nid'],
                                deck_id=card['did'],
                                cloze_order=card['ord'] + 1,
                                template_id=db_template_n.id
                            )

                for db_deck in db.Deck.select():
                    if not db_deck.cards:
                        db_deck.delete_instance()
            finally:
                conn.close()

            if not skip_media:
                if skip_media is False:
                    skip_media = []

                with open(os.path.join(temp_dir, 'media')) as f:
                    info_media = info.get('media', dict())
                    for media_id, media_name in tqdm(json.load(f).items(), desc='media'):
                        with open(os.path.join(temp_dir, media_id), 'rb') as image_f:
                            db_media = db.Media.create(
                                id=int(media_id),
                                name=media_name,
                                data=image_f.read()
                            )

                            if MediaType.image not in skip_media:
                                for note_id in info_media.get(MediaType.image, dict()).get(media_name, []):
                                    db_media.notes.add(db.Note.get(id=note_id))

                            if MediaType.audio not in skip_media:
                                for note_id in info_media.get(MediaType.audio, dict()).get(media_name, []):
                                    db_media.notes.add(db.Note.get(id=note_id))

                            if MediaType.font not in skip_media:
                                for model_id in info_media.get(MediaType.font, dict()).get(media_name, []):
                                    db_media.models.add(db.Model.get(id=model_id))

                            if not db_media.notes and db_media.models:
                                logging.error('%s not connected to Notes or Models. Deleting...', media_name)
                                db_media.delete_instance()


from collections import deque
n, m, v = map(int, input().split())

data = [[] for x in range(n+1)]
# DFS 전용 체크 visited
visited = [False] * (n+1)
# BFS 전용 체크 visited1
visited2 = [False] * (n+1)

for i in range(m):
    a, b = map(int, input().split())
    data[a].append(b)
    data[b].append(a)

for i in range(len(data)):
    data[i].sort()

def dfs(graph, v, visited):
    visited[v] = True
    print(v, end=' ')
    for i in graph[v]:
        if not visited[i]:
            dfs(graph, i, visited)

def bfs(graph, v, visited):
    queue = deque([v])
    visited[v] = True
    while queue:
        v = queue.popleft()
        print(v, end=' ')
        for i in graph[v]:
            if not visited[i]:
                queue.append(i)
                visited[i] = True

dfs(data, v, visited)
print()
bfs(data, v, visited2)


from math import ceil, floor
from random import choice

from .ball import Ball
from .ball_colors import BallColors
from .point import Point

class Field:
    """Реализует логику игры."""

    def __init__(self, field_size: int):
        # некорректно рассчитывается счёт
        # Минимальная линия -- вверх n/2 + eps
        # выгоднее уничтожить 5 линий по 6, чем 6 линий по 5
        # выгоднее уничтожать подряд
        self.buffer = []
        self.len_buffer = []    # длины всех найденных линий и прямоугольников
        self.size = field_size
        self.min_line_size = ceil(field_size / 2 + 1e-6)
        self.field_objects = [[None] * field_size for _ in range(field_size)]
        self.game_over = False
        self.score = 0
        self.generate_balls(self.min_line_size + 1)

    def restart(self):
        """Вызывается в случае перезапуска игры, обнуляет все показатели."""
        self.buffer = []
        self.len_buffer = []
        self.field_objects = [[None] * self.size for _ in range(self.size)]
        self.game_over = False
        self.score = 0
        self.generate_balls(self.min_line_size + 1)

    def mouse_click(self, x, y):
        """Обрабатывает нажатие клавиши."""
        if not self.buffer:
            if self.field_objects[x][y]:
                self.buffer.append((x, y))
        else:
            if (x, y) == self.buffer[0]:
                self.buffer = []
            elif not self.field_objects[x][y]:
                self.buffer.append((x, y))
                self.swap()
            else:
                self.buffer[0] = (x, y)

    def get_balls(self):
        """Возвращает шарики, находящиеся на поле."""
        return (self.field_objects[x][y] for x in range(self.size) for y in
                range(self.size) if self.field_objects[x][y])

    def get_empty_cells(self):
        """Возвращает пустые клетки поля."""
        return ((x, y) for x in range(self.size) for y in range(self.size)
                if not self.field_objects[x][y])

    def swap(self):
        """Реализует перемещение шариков по полю."""
        (x1, y1), (x2, y2) = self.buffer
        if (x2, y2) in self.get_component(x1, y1):
            self.field_objects[x2][y2] = self.field_objects[x1][y1]
            self.field_objects[x1][y1] = None
            self.field_objects[x2][y2].position = Point(x2, y2)
            self.buffer = []

            if not self.remove_lines_and_rectangles():
                self.generate_balls(ceil(self.min_line_size / 2 + 1e-6))
                self.remove_lines_and_rectangles()
            if not list(self.get_empty_cells()):
                self.game_over = True
        else:
            self.buffer.pop()

    def get_component(self, x, y):
        """Возвращает вершины компоненты связности."""
        res = []
        stack = [(x, y)]
        while stack:
            x, y = stack.pop()
            res.append((x, y))
            yield x, y
            for _x in range(-1, 2):
                for _y in range(-1, 2):
                    if (abs(_x), abs(_y)) == (1, 1):
                        continue
                    n_x, n_y = x + _x, y + _y
                    if 0 <= n_x < self.size and 0 <= n_y < self.size and \
                            not self.field_objects[n_x][n_y] and (n_x, n_y) \
                            not in res:
                        stack.append((n_x, n_y))

    def find_lines_and_rectangles(self):
        """Ищет линии и прямоугольники."""
        ball_positions = set(map(lambda p: (p.position.x, p.position.y),
                                 self.get_balls()))
        result = set()
        colors_corresponding_balls = {}
        for color in BallColors:
            colors_corresponding_balls[color] = {(x, y)
                                                 for x, y in ball_positions
                                                 if self.field_objects[x][y].
                                                 color is color}
        for color_positions in colors_corresponding_balls.values():
            for x1, y1 in color_positions:
                for x2, y2 in color_positions - {(x1, y1)}:
                    r_x, r_y = abs(x1 - x2) + 1, abs(y1 - y2) + 1
                    min_x, min_y = min(x1, x2), min(y1, y2)
                    rect = {(min_x + x, min_y + y)
                            for x in range(r_x) for y in range(r_y)}
                    if rect.issubset(color_positions) and \
                       len(rect) >= self.min_line_size:
                        result.update(rect)
                    if r_x == r_y:
                        r_x = range(x1, x2 + 1) if x1 < x2 else \
                            range(x1, x2 - 1, -1)
                        r_y = range(y1, y2 + 1) if y1 < y2 else \
                            range(y1, y2 - 1, -1)
                        diagonal = {(x, y) for x, y in zip(r_x, r_y)}
                        if diagonal.issubset(color_positions) and \
                           len(diagonal) >= self.min_line_size:
                            result.update(diagonal)
        return result

    def generate_balls(self, n):
        """Генерирует шарики на поле."""
        # проверить, чтобы выгоднее было уничтожать подряд
        if self.len_buffer and len(self.len_buffer) != 1:
            first = sum(self.len_buffer) / len(self.len_buffer)
            second = len(self.len_buffer)
            self.score += floor(first) + second
            if first - 1 == second:
                self.score += self.min_line_size // 2
        empty_cells = list(self.get_empty_cells())
        cells = set()
        if not empty_cells:
            self.game_over = True
        while len(cells) < min(n, len(empty_cells)):
            cells.add(choice(empty_cells))
        for x, y in cells:
            colors = [c for c in BallColors]
            color = choice(colors)
            self.field_objects[x][y] = Ball(color, Point(x, y))
        self.len_buffer = []

    def remove_lines_and_rectangles(self):
        """Удаляет линии и прямоугольники с поля."""
        lines_and_rectangles = self.find_lines_and_rectangles()
        for x, y in lines_and_rectangles:
            self.field_objects[x][y] = None
        if lines_and_rectangles:
            self.len_buffer.append(len(lines_and_rectangles))
            self.score += len(lines_and_rectangles) * 2
        return lines_and_rectangles


import sys

if __name__ == '__main__':

    OBS = {}
    TIMEOUT = 600

    filename = sys.argv[1]
    with open(filename) as f:
        for line in f:
            if not line.startswith("OW"): continue
            pawsid, ip, ts = map(lambda l: l.strip(), line.strip().split("|"))

            ts = float(ts)

            if pawsid not in OBS: OBS[pawsid] = [ts, ts]
            ob = OBS[pawsid]

            gap = ts - ob[1]
            if gap > TIMEOUT:
                print("%s, %0.0f, %0.0f" % (pawsid, ob[0], ob[1]-ob[0]))
                del OBS[pawsid]
            else:
                ob[1] = ts
                if ob[1] - ob[0] < 0:
                    print("ERR: "+line)
                    BARF


def solution(my_string):
    answer = ''
    flag = True #같은 문자가 있다면 False 없다면 True

    for i in range(len(my_string)):
        for j in range(len(answer)):
            if my_string[i] == answer[j]: #같은 문자가 있다면 break
                flag = False
                break
        if flag == True: #같은 문자가 없다면 문자 삽입
            answer += my_string[i]

        flag = True #변수 초기화

    return answer

[경남대학교] Python 코딩테스트 대비 특강/중복된 문자 제거.py

중복된 문자 제거.py


from tkinter import *
from tkinter.ttk import Combobox
import sqlite3
import math
import Languages as LG
import Number_format as Nf

class Sheet_SummaryMenu():
    def __init__(self, Multiple_Page, Invcal):
        self.Pagina_Multiple = Multiple_Page
        self.Invcal = Invcal

        self.Page = Frame(Multiple_Page)
        self.start = 0

        self.dict_actual = LG.create_language(language=LG.language_actual())
        self.dict_main = LG.create_language()

        self.Text1_Filter = Label(self.Page, text=LG.translate(self.dict_main, self.dict_actual,"text_54"))
        self.Text2_Filter = Label(self.Page, text=LG.translate(self.dict_main, self.dict_actual,"text_55"))

        self.Text1_Filter.place(x=130, y=35, anchor=E)
        self.Text2_Filter.place(x=130, y=70, anchor=E)

        self.List1_Filter_var = StringVar()
        self.List1_Filter = Combobox(self.Page,values= [LG.translate(self.dict_main, self.dict_actual,"type_domain_1"), LG.translate(self.dict_main, self.dict_actual,"type_domain_2")], textvariable=self.List1_Filter_var, state="readonly", width=15)
        self.List1_Filter.bind("<<ComboboxSelected>>", self.Update_List_Button)
        self.List1_Filter_var.set("-")
        self.List2_Filter_var = StringVar()
        self.List2_Filter = Combobox(self.Page,values= [LG.translate(self.dict_main, self.dict_actual,"status_1"), LG.translate(self.dict_main, self.dict_actual,"status_2")], textvariable=self.List2_Filter_var, state="readonly", width=15)
        self.List2_Filter.bind("<<ComboboxSelected>>", self.Update_List_Button)
        self.List2_Filter_var.set("-")

        self.List1_Filter.place(x=140, y=35, anchor=W)
        self.List2_Filter.place(x=140, y=70, anchor=W)

        self.Marco1a = Label(self.Page)
        self.Marco1a.config(relief="groove", width=36, height=10)
        self.Marco1a.place(x=430, y=20, anchor=N)

        self.Marco1b = Label(self.Page)
        self.Marco1b.config(relief="groove", width=36, height=10)
        self.Marco1b.place(x=713, y=20, anchor=N)

        self.Text1_Marco1a = Label(self.Page, text=LG.translate(self.dict_main, self.dict_actual,"text_57"))
        self.Text1_Marco1b = Label(self.Page, text=LG.translate(self.dict_main, self.dict_actual,"text_56"))

        self.Text1_Marco1a.place(x=430, y=30, anchor=N)
        self.Text1_Marco1b.place(x=713, y=30, anchor=N)

        self.Text_Image1_Marco1a_var = IntVar()
        self.Text_Image1_Marco1a = Label(self.Page, textvariable=self.Text_Image1_Marco1a_var)
        self.Text_Image1_Marco1a.place(x=360, y=85, anchor=N)
        self.Text_Image2_Marco1a_var = IntVar()
        self.Text_Image2_Marco1a = Label(self.Page, textvariable=self.Text_Image2_Marco1a_var)
        self.Text_Image2_Marco1a.place(x=430, y=85, anchor=N)
        self.Text_Image3_Marco1a_var = IntVar()
        self.Text_Image3_Marco1a = Label(self.Page, textvariable=self.Text_Image3_Marco1a_var)
        self.Text_Image3_Marco1a.place(x=500, y=85, anchor=N)
        self.Text_Image4_Marco1a_var = IntVar()
        self.Text_Image4_Marco1a = Label(self.Page, textvariable=self.Text_Image4_Marco1a_var)
        self.Text_Image4_Marco1a.place(x=360, y=140, anchor=N)
        self.Text_Image5_Marco1a_var = IntVar()
        self.Text_Image5_Marco1a = Label(self.Page, textvariable=self.Text_Image5_Marco1a_var)
        self.Text_Image5_Marco1a.place(x=430, y=140, anchor=N)
        self.Text_Image6_Marco1a_var = IntVar()
        self.Text_Image6_Marco1a = Label(self.Page, textvariable=self.Text_Image6_Marco1a_var)
        self.Text_Image6_Marco1a.place(x=500, y=140, anchor=N)

        self.Text_Image1_Marco1b_var = IntVar()
        self.Text_Image1_Marco1b = Label(self.Page, textvariable=self.Text_Image1_Marco1b_var)
        self.Text_Image1_Marco1b.place(x=643, y=85, anchor=N)
        self.Text_Image2_Marco1b_var = IntVar()
        self.Text_Image2_Marco1b = Label(self.Page, textvariable=self.Text_Image2_Marco1b_var)
        self.Text_Image2_Marco1b.place(x=713, y=85, anchor=N)
        self.Text_Image3_Marco1b_var = IntVar()
        self.Text_Image3_Marco1b = Label(self.Page, textvariable=self.Text_Image3_Marco1b_var)
        self.Text_Image3_Marco1b.place(x=783, y=85, anchor=N)
        self.Text_Image4_Marco1b_var = IntVar()
        self.Text_Image4_Marco1b = Label(self.Page, textvariable=self.Text_Image4_Marco1b_var)
        self.Text_Image4_Marco1b.place(x=643, y=140, anchor=N)
        self.Text_Image5_Marco1b_var = IntVar()
        self.Text_Image5_Marco1b = Label(self.Page, textvariable=self.Text_Image5_Marco1b_var)
        self.Text_Image5_Marco1b.place(x=713, y=140, anchor=N)
        self.Text_Image6_Marco1b_var = IntVar()
        self.Text_Image6_Marco1b = Label(self.Page, textvariable=self.Text_Image6_Marco1b_var)
        self.Text_Image6_Marco1b.place(x=783, y=140, anchor=N)

        self.Marco2 = Label(self.Page)
        self.Marco3 = Label(self.Page)
        self.Marco4 = Label(self.Page)

        self.Text1_Marco2 = Label(self.Page)
        self.Text1_Marco3 = Label(self.Page)
        self.Text1_Marco4 = Label(self.Page)

        self.Text1_Marco2.place(x=27, y=210, anchor=W)
        self.Text1_Marco3.place(x=310, y=210, anchor=W)
        self.Text1_Marco4.place(x=593, y=210, anchor=W)

        self.Text2_Marco2_var = StringVar()
        self.Text2_Marco2 = Label(self.Page, textvariable=self.Text2_Marco2_var, justify=LEFT)
        self.Text2_Marco3_var = StringVar()
        self.Text2_Marco3 = Label(self.Page, textvariable=self.Text2_Marco3_var, justify=LEFT)
        self.Text2_Marco4_var = StringVar()
        self.Text2_Marco4 = Label(self.Page, textvariable=self.Text2_Marco4_var, justify=LEFT)

        self.Text3_Marco2_var = StringVar()
        self.Text3_Marco2 = Label(self.Page, textvariable=self.Text3_Marco2_var)
        self.Text3_Marco3_var = StringVar()
        self.Text3_Marco3 = Label(self.Page, textvariable=self.Text3_Marco3_var)
        self.Text3_Marco4_var = StringVar()
        self.Text3_Marco4 = Label(self.Page, textvariable=self.Text3_Marco4_var)

        self.Text4_Marco2_var = StringVar()
        self.Text4_Marco2 = Label(self.Page, textvariable=self.Text4_Marco2_var)
        self.Text4_Marco3_var = StringVar()
        self.Text4_Marco3 = Label(self.Page, textvariable=self.Text4_Marco3_var)
        self.Text4_Marco4_var = StringVar()
        self.Text4_Marco4 = Label(self.Page, textvariable=self.Text4_Marco4_var)

        self.Text5_Marco2_var = StringVar()
        self.Text5_Marco2 = Label(self.Page, textvariable=self.Text5_Marco2_var)
        self.Text5_Marco3_var = StringVar()
        self.Text5_Marco3 = Label(self.Page, textvariable=self.Text5_Marco3_var)
        self.Text5_Marco4_var = StringVar()
        self.Text5_Marco4 = Label(self.Page, textvariable=self.Text5_Marco4_var)

        self.Load_Images()

        self.Image1_Marco2 = Label(self.Page, image=self.Image_Resin_var)
        self.Image2_Marco2 = Label(self.Page, image=self.Image_Resin_var)
        self.Image3_Marco2 = Label(self.Page, image=self.Image_Resin_var)
        self.Image4_Marco2 = Label(self.Page, image=self.Image_Mora_var)
        self.Image5_Marco2 = Label(self.Page, image=self.Image_Character_var)
        self.Image6_Marco2 = Label(self.Page, image=self.Image_Book_var)

        self.Image1_Marco3 = Label(self.Page, image=self.Image_Resin_var)
        self.Image2_Marco3 = Label(self.Page, image=self.Image_Resin_var)
        self.Image3_Marco3 = Label(self.Page, image=self.Image_Resin_var)
        self.Image4_Marco3 = Label(self.Page, image=self.Image_Mora_var)
        self.Image5_Marco3 = Label(self.Page, image=self.Image_Character_var)
        self.Image6_Marco3 = Label(self.Page, image=self.Image_Book_var)

        self.Image1_Marco4 = Label(self.Page, image=self.Image_Resin_var)
        self.Image2_Marco4 = Label(self.Page, image=self.Image_Resin_var)
        self.Image3_Marco4 = Label(self.Page, image=self.Image_Resin_var)
        self.Image4_Marco4 = Label(self.Page, image=self.Image_Mora_var)
        self.Image5_Marco4 = Label(self.Page, image=self.Image_Character_var)
        self.Image6_Marco4 = Label(self.Page, image=self.Image_Book_var)

        self.Summary_All()

    def Load_Images(self):

        self.Image_Card_var = LG.fastimport_imagech("card_character", "others", 3)
        self.Image_Resin_var = LG.fastimport_imagech("condensed_resin", "others", 3)
        self.Image_Mora_var = LG.fastimport_imagech("mora", "others", 3)
        self.Image_Character_var = LG.fastimport_imagech("xp_character", "others", 3)
        self.Image_Weapon_var = LG.fastimport_imagech("xp_weapon", "others", 3)
        self.Image_Mat_var = LG.fastimport_imagech("mat_domain_weapon_04", "weapon_asc", 3)
        self.Image_Book_var = LG.fastimport_imagech("mat_domain_book_01", "talent", 3)

        self.Image1_Marco1a = Label(self.Page, image=self.Image_Mora_var)
        self.Image2_Marco1a = Label(self.Page, image=self.Image_Character_var)
        self.Image3_Marco1a = Label(self.Page, text=LG.translate(self.dict_main, self.dict_actual,"text_58"))
        self.Image4_Marco1a = Label(self.Page, image=self.Image_Resin_var)
        self.Image5_Marco1a = Label(self.Page, image=self.Image_Resin_var)
        self.Image6_Marco1a = Label(self.Page, image=self.Image_Weapon_var)

        self.Image1_Marco1b = Label(self.Page, image=self.Image_Mora_var)
        self.Image2_Marco1b = Label(self.Page, image=self.Image_Character_var)
        self.Image3_Marco1b = Label(self.Page, text=LG.translate(self.dict_main, self.dict_actual,"text_58"))
        self.Image4_Marco1b = Label(self.Page, image=self.Image_Resin_var)
        self.Image5_Marco1b = Label(self.Page, image=self.Image_Resin_var)
        self.Image6_Marco1b = Label(self.Page, image=self.Image_Weapon_var)

        self.Image1_Marco1a.place(x=360,y=50, anchor=N)
        self.Image2_Marco1a.place(x=430,y=50, anchor=N)
        self.Image3_Marco1a.place(x=500,y=57, anchor=N)

        self.Image4_Marco1a.place(x=360,y=105, anchor=N)
        self.Image5_Marco1a.place(x=430,y=105, anchor=N)
        self.Image6_Marco1a.place(x=500,y=105, anchor=N)

        self.Image1_Marco1b.place(x=643,y=50, anchor=N)
        self.Image2_Marco1b.place(x=713,y=50, anchor=N)
        self.Image3_Marco1b.place(x=783,y=57, anchor=N)

        self.Image4_Marco1b.place(x=643,y=105, anchor=N)
        self.Image5_Marco1b.place(x=713,y=105, anchor=N)
        self.Image6_Marco1b.place(x=783,y=105, anchor=N)

    def Load_Images_Dynamic(self):

        self.Image1_Marco2.place(x=162,y=200)
        self.Image2_Marco2.place(x=197,y=200)
        self.Image3_Marco2.place(x=232,y=200)
        self.Image4_Marco2.place(x=162,y=230)
        self.Image5_Marco2.place(x=197,y=230)
        self.Image6_Marco2.place(x=232,y=230)

        self.Image1_Marco3.place(x=445,y=200)
        self.Image2_Marco3.place(x=480,y=200)
        self.Image3_Marco3.place(x=515,y=200)
        self.Image4_Marco3.place(x=445,y=230)
        self.Image5_Marco3.place(x=480,y=230)
        self.Image6_Marco3.place(x=515,y=230)

        self.Image1_Marco4.place(x=728,y=200)
        self.Image2_Marco4.place(x=763,y=200)
        self.Image3_Marco4.place(x=798,y=200)
        self.Image4_Marco4.place(x=728,y=230)
        self.Image5_Marco4.place(x=763,y=230)
        self.Image6_Marco4.place(x=798,y=230)

    def Summary_All(self):

        conexion1 = sqlite3.connect("DB SQL/genshin_db.db")
        query1 = conexion1.execute("select Build, sum(XP_Character), sum(XP_Weapon), sum(Mora_Ascension + Mora_Talent + Mora_Weapon_Ascension + XP_Character*0.2 + XP_Weapon*0.1) as Mora from user group by Build")
        conexion1.commit()

        query1_values = query1.fetchall()

        try:
            var1a=query1_values[0][3] + query1_values[1][3]
        except:
            try:
                var1a=query1_values[0][3]
            except:
                var1a=0

        try:
            var2a=query1_values[0][1] + query1_values[1][1]
        except:
            try:
                var2a=query1_values[0][1]
            except:
                var2a=0

        try:
            var3a=query1_values[0][2] + query1_values[1][2]
        except:
            try:
                var3a=query1_values[0][2]
            except:
                var3a=0

        try:
            var1b=query1_values[1][3]
        except:
            var1b=0

        try:
            var1b=query1_values[1][3]
        except:
            var1b=0

        try:
            var2b=query1_values[1][1]
        except:
            var2b=0

        try:
            var3b=query1_values[1][2]
        except:
            var3b=0

        # var2a=query1_values[0][1] + query1_values[1][1]
        # var3a=query1_values[0][2] + query1_values[1][2]

        # var1b=query1_values[1][3]
        # var2b=query1_values[1][1]
        # var3b=query1_values[1][2]

        self.Text_Image1_Marco1a_var.set(Nf.format_point(var1a))
        self.Text_Image2_Marco1a_var.set(Nf.format_point(var2a))
        self.Text_Image3_Marco1a_var.set(Nf.format_point(var3a))

        self.Text_Image4_Marco1a_var.set(Nf.format_point(math.ceil(var1a/120000)))
        self.Text_Image5_Marco1a_var.set(Nf.format_point(math.ceil(var2a/245000)))
        self.Text_Image6_Marco1a_var.set(Nf.format_point(math.ceil(var3a/10000)))

        self.Text_Image1_Marco1b_var.set(Nf.format_point(var1b))
        self.Text_Image2_Marco1b_var.set(Nf.format_point(var2b))
        self.Text_Image3_Marco1b_var.set(Nf.format_point(var3b))

        self.Text_Image4_Marco1b_var.set(Nf.format_point(math.ceil(var1b/120000)))
        self.Text_Image5_Marco1b_var.set(Nf.format_point(math.ceil(var2b/245000)))
        self.Text_Image6_Marco1b_var.set(Nf.format_point(math.ceil(var3b/10000)))

    def Load_Marco(self):

        self.Marco2.config(width=36, height=24, relief="groove")
        self.Marco3.config(width=36, height=24, relief="groove")
        self.Marco4.config(width=36, height=24, relief="groove")

        self.Marco2.place(x=147, y=190, anchor=N)
        self.Marco3.place(x=430, y=190, anchor=N)
        self.Marco4.place(x=713, y=190, anchor=N)

        self.Text1_Marco2.config(text=LG.translate(self.dict_main, self.dict_actual,"day_1"))
        self.Text1_Marco3.config(text=LG.translate(self.dict_main, self.dict_actual,"day_2"))
        self.Text1_Marco4.config(text=LG.translate(self.dict_main, self.dict_actual,"day_3"))

        self.Text2_Marco2.place(x=27, y=270)
        self.Text2_Marco3.place(x=310, y=270)
        self.Text2_Marco4.place(x=593, y=270)

        self.Text3_Marco2.place(x=152, y=270)
        self.Text3_Marco3.place(x=435, y=270)
        self.Text3_Marco4.place(x=718, y=270)

        self.Text4_Marco2.place(x=187, y=270)
        self.Text4_Marco3.place(x=470, y=270)
        self.Text4_Marco4.place(x=753, y=270)

        self.Text5_Marco2.place(x=222, y=270)
        self.Text5_Marco3.place(x=505, y=270)
        self.Text5_Marco4.place(x=788, y=270)

    def Summary_day(self):

        #Query Total
        build = "status_1"

        list_day1 = []
        list_day2 = []
        list_day3 = []

        list_unic_day1 = set()
        list_unic_day2 = set()
        list_unic_day3 = set()

        if LG.translate_inv(self.List2_Filter_var.get()) == "status_2":
            build= "status_2"

        var_book = 1

        for elem in self.query2_values:
            if build == "status_1":
                if elem[3] == 1:

                    list_day1.append([self.dict_actual[elem[0]], self.dict_actual[elem[2]], math.ceil(self.Invcal.Calculate_Value([elem[4], elem[5], elem[6]])/var_book), math.ceil(elem[7]/120000), math.ceil(elem[8]/245000)])
                    list_unic_day1.add(self.dict_actual[elem[2]])
                elif elem[3] == 2:
                    list_day2.append([self.dict_actual[elem[0]], self.dict_actual[elem[2]], math.ceil(self.Invcal.Calculate_Value([elem[4], elem[5], elem[6]])/var_book), math.ceil(elem[7]/120000), math.ceil(elem[8]/245000)])
                    list_unic_day2.add(self.dict_actual[elem[2]])
                elif elem[3] == 3:
                    list_day3.append([self.dict_actual[elem[0]], self.dict_actual[elem[2]], math.ceil(self.Invcal.Calculate_Value([elem[4], elem[5], elem[6]])/var_book), math.ceil(elem[7]/120000), math.ceil(elem[8]/245000)])
                    list_unic_day3.add(self.dict_actual[elem[2]])
            elif build == "status_2":
                if elem[3] == 1 and elem[1] == build:
                    list_day1.append([self.dict_actual[elem[0]], self.dict_actual[elem[2]], math.ceil(self.Invcal.Calculate_Value([elem[4], elem[5], elem[6]])/var_book), math.ceil(elem[7]/120000), math.ceil(elem[8]/245000)])
                    list_unic_day1.add(self.dict_actual[elem[2]])
                elif elem[3] == 2 and elem[1] == build:
                    list_day2.append([self.dict_actual[elem[0]], self.dict_actual[elem[2]], math.ceil(self.Invcal.Calculate_Value([elem[4], elem[5], elem[6]])/var_book), math.ceil(elem[7]/120000), math.ceil(elem[8]/245000)])
                    list_unic_day2.add(self.dict_actual[elem[2]])
                elif elem[3] == 3 and elem[1] == build:
                    list_day3.append([self.dict_actual[elem[0]], self.dict_actual[elem[2]], math.ceil(self.Invcal.Calculate_Value([elem[4], elem[5], elem[6]])/var_book), math.ceil(elem[7]/120000), math.ceil(elem[8]/245000)])
                    list_unic_day3.add(self.dict_actual[elem[2]])

        list_day1.sort(key=lambda x: x[1])
        list_day2.sort(key=lambda x: x[1])
        list_day3.sort(key=lambda x: x[1])

        list_unic_day1 = sorted(list_unic_day1)
        list_unic_day2 = sorted(list_unic_day2)
        list_unic_day3 = sorted(list_unic_day3)

        self.Text2_Marco2_var.set(self.List_Text(list_unic_day1, list_day1, "text", 0))
        self.Text2_Marco3_var.set(self.List_Text(list_unic_day2, list_day2, "text", 0))
        self.Text2_Marco4_var.set(self.List_Text(list_unic_day3, list_day3, "text", 0))

        self.Text3_Marco2_var.set(self.List_Text(list_unic_day1, list_day1, "number", 3))
        self.Text3_Marco3_var.set(self.List_Text(list_unic_day2, list_day2, "number", 3))
        self.Text3_Marco4_var.set(self.List_Text(list_unic_day3, list_day3, "number", 3))

        self.Text4_Marco2_var.set(self.List_Text(list_unic_day1, list_day1, "number", 4))
        self.Text4_Marco3_var.set(self.List_Text(list_unic_day2, list_day2, "number", 4))
        self.Text4_Marco4_var.set(self.List_Text(list_unic_day3, list_day3, "number", 4))

        self.Text5_Marco2_var.set(self.List_Text(list_unic_day1, list_day1, "number", 2))
        self.Text5_Marco3_var.set(self.List_Text(list_unic_day2, list_day2, "number", 2))
        self.Text5_Marco4_var.set(self.List_Text(list_unic_day3, list_day3, "number", 2))

    def List_Text(self, list1, list2, type_value, elem_list):
        text_day = ""
        for elem1 in list1:
            if type_value == "text":
                text_day += elem1 + "\n"
            elif type_value == "number":
                text_day += "\n"
            for elem2 in list2:
                if elem1 == elem2[1]:
                    text_day += f"      {elem2[elem_list]}\n"
        return text_day

    def Update_List_Button(self, event):
        self.Update_List(self.List1_Filter_var, self.List2_Filter_var)

    def Update_List(self, list1_var, list2_var):

        if list1_var.get() != "-" and list2_var.get() != "-":
            self.start = 1

            if LG.translate_inv(list1_var.get()) == "type_domain_1": #talent
                conexion2 = sqlite3.connect("DB SQL/genshin_db.db")
                query2 = conexion2.execute("""select v.Character, u.Build, v.n1, o.order2, sum(v.t2), sum(v.t3), sum(v.t4), (u.Mora_Ascension + u.Mora_Weapon_Ascension + u.Mora_Talent + u.XP_Character*0.2 + u.XP_Weapon*0.1) as mora, (u.XP_Character) as xp_ch from
                                            (select u.Character, b.tal_1_book_1 as n1, u.Tal1_B1_T2 as t2, u.Tal1_B1_T3 as t3, u.Tal1_B1_T4 as t4 from user as u join db_base as b on u.Character = b.id
                                            union all
                                            select u.Character, b.tal_1_book_2 as n1, u.Tal1_B2_T2 as t2, u.Tal1_B2_T3 as t3, u.Tal1_B2_T4 as t4 from user as u join db_base as b on u.Character = b.id
                                            union all
                                            select u.Character, b.tal_1_book_3 as n1, u.Tal1_B3_T2 as t2, u.Tal1_B3_T3 as t3, u.Tal1_B3_T4 as t4 from user as u join db_base as b on u.Character = b.id
                                            union all
                                            select u.Character, b.tal_2_book_1 as n1, u.Tal2_B1_T2 as t2, u.Tal2_B1_T3 as t3, u.Tal2_B1_T4 as t4 from user as u join db_base as b on u.Character = b.id
                                            union all
                                            select u.Character, b.tal_2_book_2 as n1, u.Tal2_B2_T2 as t2, u.Tal2_B2_T3 as t3, u.Tal2_B2_T4 as t4 from user as u join db_base as b on u.Character = b.id
                                            union all
                                            select u.Character, b.tal_2_book_3 as n1, u.Tal2_B3_T2 as t2, u.Tal2_B3_T3 as t3, u.Tal2_B3_T4 as t4 from user as u join db_base as b on u.Character = b.id
                                            union all
                                            select u.Character, b.tal_3_book_1 as n1, u.Tal3_B1_T2 as t2, u.Tal3_B1_T3 as t3, u.Tal3_B1_T4 as t4 from user as u join db_base as b on u.Character = b.id
                                            union all
                                            select u.Character, b.tal_3_book_2 as n1, u.Tal3_B2_T2 as t2, u.Tal3_B2_T3 as t3, u.Tal3_B2_T4 as t4 from user as u join db_base as b on u.Character = b.id
                                            union all
                                            select u.Character, b.tal_3_book_3 as n1, u.Tal3_B3_T2 as t2, u.Tal3_B3_T3 as t3, u.Tal3_B3_T4 as t4 from user as u join db_base as b on u.Character = b.id
                                            ) as v join user as u on v.Character = u.Character join db_order as o on o.id = v.n1
											where (v.t2 + v.t3 + v.t4) != 0
											group by v.Character, v.n1""")
                conexion2.commit()
            elif LG.translate_inv(list1_var.get()) == "type_domain_2": #mat_weapon
                conexion2 = sqlite3.connect("DB SQL/genshin_db.db")
                query2 = conexion2.execute("select u.Character, u.Build, w.mat_domain_weapon, o.order2, sum(u.Weapon_Material_Domain_Tier2) as matt2, sum(u.Weapon_Material_Domain_Tier3) as matt3, sum(u.Weapon_Material_Domain_Tier4) as matt4, sum(u.Weapon_Material_Domain_Tier5) as matt5, (u.Mora_Ascension + u.Mora_Weapon_Ascension + u.Mora_Talent + u.XP_Character*0.2 + u.XP_Weapon*0.1) as mora, (u.XP_Character) as XP_Character from user as u join db_weapon as w on u.weapon = w.id join db_order as o on o.id = w.mat_domain_weapon group by u.Character, u.Build, w.mat_domain_weapon, o.order2 HAVING (matt2 + matt3 + matt4 + matt5) != 0")
                conexion2.commit()

            self.query2_values = query2.fetchall()

            self.Summary_day()

        if self.start == 1:
            self.Load_Marco()
            self.Load_Images_Dynamic()


import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np

class Qnet(torch.nn.Module):
    ''' 只有一层隐藏层的Q网络 '''
    def __init__(self, state_dim, hidden_dim, action_dim):
        super(Qnet, self).__init__()
        self.fc1 = torch.nn.Linear(state_dim, hidden_dim)
        self.fc2 = torch.nn.Linear(hidden_dim, action_dim)

    def forward(self, x):
        x = F.relu(self.fc1(x))  # 隐藏层使用ReLU激活函数
        return self.fc2(x)
class VDN:
    def __init__(self, agents_num, state_dim, hidden_dim, action_dim, learning_rate, gamma,
                  epsilon, target_update, device):

        # 智能体数量
        self.agents_num = agents_num
        # 状态维度
        self.state_dim = state_dim
        # 隐藏层维度
        self.hidden_dim = hidden_dim
        # 动作维度
        self.action_dim = action_dim
        # 学习率
        self.learning_rate = learning_rate
        # 折扣因子
        self.gamma = gamma
        # epsilon-贪婪策略
        self.epsilon = epsilon
        # 目标网络更新频率
        self.target_update = target_update
        # 设备
        self.device = device
        self.count = 0  # 计数器,记录更新次数

        Qnet_input_dim = state_dim * self.agents_num

        # 神经网络
        # 所有智能体共用一个决策q网络，但是每个智能体有一个独立的target_q网络
        self.eval_qnet = Qnet(Qnet_input_dim, hidden_dim,
                          self.action_dim).to(device)   # 每个agent选动作的网络
        self.target_qnet = []
        for i in range(self.agents_num):
            self.target_qnet.append(Qnet(Qnet_input_dim, hidden_dim,
                          self.action_dim).to(device))  # 每个agent选动作的网络

        # 让target_net和eval_net的网络参数相同
        for i in range(self.agents_num):
            self.target_qnet[i].load_state_dict(self.eval_qnet.state_dict())

        self.optimizer = torch.optim.Adam(self.eval_qnet.parameters(), lr=self.learning_rate)

        print('Init alg VDN')

    def update(self, transition_dict):
        """更新Q网络参数"""
        states = torch.tensor(transition_dict['states'],
                              dtype=torch.float).to(self.device)
        actions1 = torch.tensor(transition_dict['actions1']).view(-1, 1).to(
            self.device)
        actions2 = torch.tensor(transition_dict['actions2']).view(-1, 1).to(
            self.device)
        rewards = torch.tensor(transition_dict['rewards'],
                               dtype=torch.float).view(-1, 1).to(self.device)
        next_states = torch.tensor(transition_dict['next_states'],
                                   dtype=torch.float).to(self.device)
        dones = torch.tensor(transition_dict['dones'],
                             dtype=torch.float).view(-1, 1).to(self.device)

        # 计算loss
        q_values_1 = self.eval_qnet(states)
        q_values_2 = self.eval_qnet(states)
        # 分别计算每个智能体的target_q值并加起来
        for i in range(self.agents_num):
            next_q_value= self.target_qnet[i](next_states)
            if i == 0:
                next_q_values = next_q_value
            else:
                next_q_values = next_q_values + next_q_value

        with torch.no_grad():
            max_next_q_values = next_q_values.max(dim=1)[0].unsqueeze(1)
            target_q_values = rewards + (self.gamma * max_next_q_values * (1 - dones))
        # # detach()函数将target_q_values从计算图中分离出来，防止梯度传播
        # target_q_values = target_q_values.detach()
        # 获取对应的q值
        q_values1 = q_values_1.gather(1, actions1)
        q_values2 = q_values_2.gather(1, actions2)
        q_values = q_values1 + q_values2
        loss = nn.functional.mse_loss(q_values, target_q_values)

        # 反向传播更新参数
        self.optimizer.zero_grad()
        loss.backward()
        self.optimizer.step()

        # 更新target网络
        if self.count % self.target_update == 0:
            for i in range(self.agents_num):
                self.target_qnet[i].load_state_dict(self.eval_qnet.state_dict())
        self.count += 1

    def take_action(self, state):  # epsilon-贪婪策略采取动作
        if np.random.random() < self.epsilon:
            action = np.random.randint(self.action_dim)

        else:
            state = torch.tensor([state], dtype=torch.float).to(self.device)
            action = self.eval_qnet(state).argmax().item()

        return action


import sys

octopuses = [[int(x) for x in l.rstrip()] for l in sys.stdin]
deltas = [-1, 0, 1]
flashed = 0
first_synchronized_flash = None
iteration = 0
while True:
    to_visit = set()
    for i in range(10):
        for j in range(10):
            octopuses[i][j] += 1
            if octopuses[i][j] == 10:
                to_visit.add((i, j))

    seen = set()
    while to_visit:
        point = to_visit.pop()
        seen.add(point)
        i, j = point
        for d1 in deltas:
            for d2 in deltas:
                new_point = (i + d1, j + d2)
                k, l = new_point
                if 0 <= k <= 9 and 0 <= l <= 9:
                    octopuses[k][l] += 1
                    if octopuses[k][l] == 10 and new_point not in seen:
                        to_visit.add((k, l))

    for i, j in seen:
        octopuses[i][j] = 0

    if iteration < 100:
        flashed += len(seen)
    iteration += 1
    if len(seen) == 100:
        first_synchronized_flash = iteration
        break

print(flashed)
print(first_synchronized_flash)


"""
common used functions
"""

from functools import reduce
from numpy import trapz
import numpy as np
from astropy.time import Time
from astropy.modeling import models
from astropy.modeling.fitting import LevMarLSQFitter

class Experiment:
    """
     Experiment class
    """

    def __init__(self, **entries):
        self.flag = None
        self.modifiedJulianDays = None
        self.Iteration_number = None
        self.polarizationAVG = None
        self.polarizationU9 = None
        self.polarizationU1 = None
        self.location = None
        self.Date = None
        self.specie = None
        self.type = None
        self.__dict__.update(entries)

def file_len(file_name):
    """

    :param file_name: file name
    :return: rows of file
    """
    i = 0
    with open(file_name) as file:
        for i, _ in enumerate(file):
            pass
    return i + 1

def get_iteration_from_output_file(file):
    return int(file.split(".")[1].split("_")[-1])

def indexies(array, value):
    """

    :param array: nupmy array
    :param value: value to search
    :return: indexes in array for value
    """
    indexes = list()
    for i in range(0, len(array) - 1):
        if array[i] == value:
            indexes.append(i)
    return indexes

def find_nearest_index(array, value):
    """

    :param array: array
    :param value: value to search
    :return: nearest index of value for array
    """
    array = np.asarray(array)
    index = (np.abs(array - value)).argmin()
    return index

def correct_numpy_read_data(data):
    """

    :param data: numpy array
    :return: corrected numpy array
    """
    corrected_data = list()
    for dd_ in data:
        corrected_data.append(dd_[0])
    return np.array(corrected_data)

def convert_datetime_object_to_mjd(time):
    """

    :param time: datetime object
    :return: MJD
    """
    time = time.isoformat()
    tt_ = Time(time, format='isot')
    return tt_.mjd

def compute_gauss(xarray, avg_y_not_smooht_data, gauss_lines):
    """

    :param xarray: xarray
    :param avg_y_not_smooht_data:
    :param gauss_lines: gauss_lines
    :return: area under signal from spectre
    """
    ampvid = avg_y_not_smooht_data
    velocity = xarray
    indexs = [(np.abs(velocity - float(line))).argmin() for line in gauss_lines]
    mons = [max(ampvid[index - 5:index + 5]) for index in indexs]
    gaussian = [models.Gaussian1D(mons[index], gauss_lines[index],
                                  0.05, bounds={'stddev': (None, 0.15)})
                for index in range(0, len(mons))]

    gg_init = reduce(lambda a, b : a + b, gaussian)
    fit = LevMarLSQFitter()
    gg_fit = fit(gg_init, velocity, ampvid)
    if len(gauss_lines) > 1:
        sts = [models.Gaussian1D(gg_fit[index].amplitude,
                                 gg_fit[index].mean,
                                 gg_fit[index].stddev) for index in range(0, len(gauss_lines))]
        gaussian_areas = []
        gaussiana_amplitudes = [str(gg_fit[index].amplitude).split("=")[-1].replace(")", "")
                                for index in range(0, len(gauss_lines))]
        gaussiana_mean = [str(gg_fit[index].mean).split("=")[-1].replace(")", "")
                          for index in range(0, len(gauss_lines))]
        gaussiana_std = [str(gg_fit[index].stddev).split(",")[1].split("=")[-1]
                         for index in range(0, len(gauss_lines))]

        for st_ in sts:
            gaussian_areas.append(trapz(st_(velocity), velocity))

        return (gaussian_areas, sts, gg_fit, velocity, ampvid, gauss_lines,
                gaussiana_amplitudes, gaussiana_mean, gaussiana_std)

    else:
        sts = models.Gaussian1D(gg_fit.amplitude, gg_fit.mean, gg_fit.stddev)
        gaussian_areas = []
        gaussiana_amplitudes = str(gg_fit.amplitude).split("=")[-1].replace(")", "")
        gaussiana_mean = str(gg_fit.mean).split("=")[-1].replace(")", "")
        gaussiana_std = str(gg_fit.stddev).split(",")[1].split("=")[-1]

        gaussian_areas.append(trapz(sts(velocity), velocity))

        return (gaussian_areas, sts, gg_fit, velocity, ampvid,
                gauss_lines, gaussiana_amplitudes, gaussiana_mean, gaussiana_std)


import cv2
import io
import numpy as np
from django.core.files.uploadedfile import InMemoryUploadedFile

#convert memory image to numpy array that can be used by opencv
def convert_to_numpy(image):
    image_bytes = image.read()
    image = np.frombuffer(image_bytes, np.uint8)
    image = cv2.imdecode(image, cv2.IMREAD_COLOR)
    return image
def convert_to_memory(image):
    _, image = cv2.imencode(".png", image)
    image = io.BytesIO(image)
    image = InMemoryUploadedFile(image, None, "image.png", "image/png", image.tell(), None)
    return image
#rotate

#mirror
def mirror(image):
    image = convert_to_numpy(image)
    mirroredImage = cv2.flip(image, 1)
    image = convert_to_memory(mirroredImage)
    return image
#resize
def resize(image, width, height):
    image = convert_to_numpy(image)
    resizedImage = cv2.resize(image, (width, height))
    image = convert_to_memory(resizedImage)
    return image

def rotate(image, angle):
    image = convert_to_numpy(image)

    rotatedImage = cv2.getRotationMatrix2D((image.shape[1] / 2, image.shape[0] / 2), -angle, 1)
    rotatedImage = cv2.warpAffine(image, rotatedImage, (image.shape[1], image.shape[0]))

    image = convert_to_memory(rotatedImage)
    return image

#crop
def crop(image, top_coordinate,left_coordinate,bottom_coordinate,right_coordinate):
    image = convert_to_numpy(image)
    croppedImage = image[top_coordinate:bottom_coordinate, left_coordinate:right_coordinate]
    image = convert_to_memory(croppedImage)
    return image

def mirror_v(image):
    #vertical mirror
    image = convert_to_numpy(image)
    mirroredImage = cv2.flip(image, 0)
    image = convert_to_memory(mirroredImage)
    return image


"""
Procuret Python
Customer Payment Module
author: hugh@blinkybeach.com
"""
from procuret.data.codable import Codable, CodingDefinition as CD
from procuret.time.time import ProcuretTime
from decimal import Decimal
from procuret.human.headline import HumanHeadline
from procuret.data.disposition import Disposition
from procuret.payment_method.headline import PaymentMethodHeadline
from procuret.money.currency import Currency
from typing import Optional

class CustomerPayment(Codable):

    coding_map = {
        'public_id': CD(str),
        'executor': CD(HumanHeadline),
        'created': CD(ProcuretTime),
        'executed': CD(ProcuretTime),
        'magnitude': CD(Decimal),
        'disposition': CD(Disposition),
        'active': CD(bool),
        'payment_method': CD(PaymentMethodHeadline, optional=True),
        'commitment_id': CD(str),
        'denomination': CD(Currency)
    }

    def __init__(
        self,
        public_id: str,
        executor: HumanHeadline,
        created: ProcuretTime,
        executed: ProcuretTime,
        magnitude: Decimal,
        disposition: Disposition,
        active: bool,
        payment_method: Optional[PaymentMethodHeadline],
        commitment_id: str,
        denomination: Currency
    ) -> None:

        self._public_id = public_id
        self._executor = executor
        self._created = created
        self._executed = executed
        self._disposition = disposition
        self._magnitude = magnitude
        self._active = active
        self._payment_method = payment_method
        self._commitment_id = commitment_id
        self._denomination = denomination

        return

    public_id: str = property(lambda s: s._public_id)
    executor: HumanHeadline = property(lambda s: s._executor)
    created: ProcuretTime = property(lambda s: s._created)
    executed: ProcuretTime = property(lambda s: s._executed)
    magnitude: Decimal = property(lambda s: s._magnitude)
    disposition: Disposition = property(lambda s: s._disposition)
    active: bool = property(lambda s: s._active)
    payment_method: Optional[PaymentMethodHeadline] = property(
        lambda s: s._payment_method
    )
    commitment_id: str = property(lambda s: s._commitment_id)
    denomination: Currency = property(lambda s: s._denomination)


import logging
import re

from SpiffWorkflow.exceptions import SpiffWorkflowException
from SpiffWorkflow.bpmn.exceptions import WorkflowTaskException

from ..specs.model import HitPolicy

logger = logging.getLogger('spiff.dmn')

class DMNEngine:
    """
    Handles the processing of a decision table.
    """

    def __init__(self, decision_table):
        self.decision_table = decision_table

    def decide(self, task):
        rules = []
        for rule in self.decision_table.rules:
            if self.__check_rule(rule, task):
                rules.append(rule)
                if self.decision_table.hit_policy == HitPolicy.UNIQUE.value:
                    return rules
        return rules

    def result(self, task):
        """Returns the results of running this decision table against
        a given task."""
        result = {}
        matched_rules = self.decide(task)
        if self.decision_table.hit_policy == HitPolicy.COLLECT.value:
            # each output will be an array of values, all outputs will
            # be placed in a dict, which we will then merge.
            for rule in matched_rules:
                rule_output = rule.output_as_dict(task)
                for key in rule_output.keys():
                    if key not in result:
                        result[key] = []
                    result[key].append(rule_output[key])
        elif len(matched_rules) > 0:
            result = matched_rules[0].output_as_dict(task)
        return result

    def __check_rule(self, rule, task):
        for input_entry in rule.inputEntries:
            for lhs in input_entry.lhs:
                if lhs is not None:
                    input_val = DMNEngine.__get_input_val(input_entry, task.data)
                else:
                    input_val = None
                try:
                    if not self.evaluate(input_val, lhs, task):
                        return False
                except SpiffWorkflowException as se:
                    se.add_note(f"Rule failed on row {rule.row_number}")
                    raise se
                except Exception as e:
                    error = WorkflowTaskException(str(e), task=task, exception=e)
                    error.add_note(f"Failed to execute DMN Rule on row {rule.row_number}")
                    raise error
                else:
                    # Empty means ignore decision value
                    continue  # Check the other operators/columns
        return True

    def needs_eq(self, script_engine, text):
        try:
            # this should work if we can just do a straight equality
            script_engine.validate(text)
            return True
        except SyntaxError:
            # if we have problems parsing, then we introduce a variable on the left hand side
            # and try that and see if that parses. If so, then we know that we do not need to
            # introduce an equality operator later in the dmn
            script_engine.validate(f'v {text}')
            return False

    def evaluate(self, input_expr, match_expr, task):
        """
        Here we need to handle a few things such as if it is an equality or if
        the equality has already been taken care of. For now, we just assume
         it is equality.

         An optional task can be included if this is being executed in the
         context of a BPMN task.
        """
        if match_expr is None:
            return True

        script_engine = task.workflow.script_engine
        # NB - the question mark allows us to do a double ended test - for
        # example - our input expr is 5 and the match expr is 4 < ? < 6  -
        # this should evaluate as 4  < 5 < 6 and it should evaluate as 'True'
        # NOTE:  It should only do this replacement outside of quotes.
        # for example, provided "This thing?"  in quotes, it should not
        # do the replacement.
        match_expr = re.sub(r'(\?)(?=(?:[^\'"]|[\'"][^\'"]*[\'"])*$)', 'dmninputexpr', match_expr)
        if 'dmninputexpr' in match_expr:
            external_context = {
                'dmninputexpr': script_engine.evaluate(task, input_expr)
            }
            return script_engine.evaluate(task, match_expr,
                                          external_context=external_context)

        # The input expression just has to be something that can be parsed as is by the engine.
        script_engine.validate(input_expr)

        # If we get here, we need to check whether the match expression includes
        # an operator or if can use '=='
        needs_eq = self.needs_eq(script_engine, match_expr)
        # Disambiguate cases like a == 0 == True when we add '=='
        expr = f'({input_expr}) == ({match_expr})' if needs_eq else input_expr + match_expr
        return script_engine.evaluate(task, expr)

    @staticmethod
    def __get_input_val(input_entry, context):
        """
        The input of the decision method should be an expression,  but will
        fallback to the likely very bad idea of trying to use the label.

        :param inputEntry:
        :param context:  # A dictionary that provides some context/local vars.
        :return:
        """
        if input_entry.input.expression:
            return input_entry.input.expression
        else:
            # Backwards compatibility
            return "%r" % context[input_entry.input.label]


import struct
import ecdsa

import trezor_pb2 as proto
import tools

def raw_tx_header(inputs_count):
    s = ''
    s += '\x01\x00\x00\x00'  # version
    s += tools.var_int(inputs_count)  # number of inputs
    return s

def raw_tx_input(inp, script_sig):
    s = ''
    s += inp.prev_hash[::-1]  # prev hash
    s += struct.pack('<L', inp.prev_index)  # prev index
    if script_sig != '':
        s += tools.var_int(len(script_sig))  # script length
        s += script_sig  # script sig
    s += "\xff\xff\xff\xff"  # sequence
    return s

def raw_tx_middle(outputs_count):
    s = ''
    s += tools.var_int(outputs_count)  # number of outputs
    return s

def raw_tx_output(out):
    s = ''
    s += struct.pack('<Q', out.amount)  # amount

    if out.script_type == proto.PAYTOADDRESS:
        script = '\x76\xa9'  # op_dup, op_hash_160
        script += '\x14'  # push 0x14 bytes
        script += tools.bc_address_to_hash_160(out.address)
        script += '\x88\xac'  # op_equalverify, op_checksig

    elif out.script_type == proto.PAYTOSCRIPTHASH:
        raise Exception("P2SH not implemented yet!")

    else:
        raise Exception("Unknown script type!")

    s += tools.var_int(len(script))  # script length
    s += script  # script
    return s

def raw_tx_footer(for_sign):
    s = ''
    s += '\x00\x00\x00\x00'  # lock time
    if for_sign:
        s += '\x01\x00\x00\x00'  # hash type
    return s

'''
# https://en.bitcoin.it/wiki/Protocol_specification#Variable_length_integer
def raw_tx(inputs, outputs, for_sig):
    s = ''
    s += raw_tx_header(len(inputs))

    for i in range(len(inputs)):
        inp = inputs[i]

        if for_sig == i:
            script_sig = inp.script_sig
        else:
            script_sig = ''

        s += raw_tx_input(inp, script_sig)

    s += raw_tx_middle(len(outputs))

    for output in outputs:
        s += raw_tx_output(output)

    s += raw_tx_footer()
    return s
'''

def sign_input(algo, secexp, addr_n, tx_hash):
    pk = algo.get_private_key(secexp, addr_n)
    private_key = ecdsa.SigningKey.from_string(pk, curve=tools.SECP256k1)
    sig = private_key.sign_digest(tx_hash, sigencode=ecdsa.util.sigencode_der)
    public_key = private_key.get_verifying_key()
    pubkey = public_key.to_string()
    return (pubkey, sig)

'''
def sign_inputs(algo, secexp, inputs, outputs):
    # This is reworked but backward compatible (non-streaming) method from Electrum
    signatures = []
    for i in range(len(inputs)):
        addr_n = inputs[i].address_n
        print addr_n

        tx = raw_tx(inputs, outputs, for_sig=i)
        tx_hash = tools.Hash(tx)
        signatures.append(sign_input(algo, secexp, addr_n, tx_hash))
    return signatures
'''


#compares ints and prints out which is larger
def compare(num_1: int, num_2:int):
    if num_1 > num_2:
        print(f"Luku {num_1} on suurempi kuin luku {num_2}.")
    elif num_1 < num_2:
        print(f"Luku {num_2} on suurempi kuin luku {num_1}.")
    else:
        print(f"Syötetyt luvut {num_2} ja {num_1} ovat samansuuruiset.")

if __name__ == '__main__':
    #ask for two integers, then compare them printing out the result
    num_1 = int(input("Syötä ensimmäinen luku: "))
    print()
    num_2 = int(input("Syötä toinen luku: "))
    print()
    compare(num_1, num_2)


import sys

sys.stdin = open("input.txt", "r")

T = int(input())

for tc in range(T):
    data = input()

    l = len(data)
    cards = {'S': '', 'D': '', 'H': '', 'C': ''}
    for i in cards:
        cards[i] = [0 for _ in range(14)]

    num_cards = {'S': 13, 'D': 13, 'H': 13, 'C': 13}
    isError = False

    for i in range(0, l, 3):
        type = data[i]
        num = int(data[i+1:i+3])

        if not cards[type][num]:
            cards[type][num] = 1
            num_cards[type] -= 1
        else:
            isError = True
            break

    print('#{}'.format(tc+1), end=' ')
    if isError:
        print('ERROR')
    else:
        for c in num_cards.values():
            print(c, end=' ')
        print()


#reading cascade files

import pandas as pd
import csv

pd.set_option('display.max_columns', 500)

types = {'0128':'time t only','0313':'time t and t-1'}

times = {1:0,2:3,3:6,4:9,5:12,6:24}

dfs = {'time t only':pd.DataFrame(index=times.values(),columns=['top 101:','top 111:',
                                                                'top 011:','past 001:',
                                                                'mid 111:','mid 101-111-011:',
                                                                'mid 101-011','bot 001',
                                                                'past 001->001','unexplained'],
                                  dtype=object),
       'time t and t-1':pd.DataFrame(index=times.values(),columns=['top 101:','top 111:',
                                                                'top 011:','past 001:',
                                                                'mid 111:','mid 101-111-011:',
                                                                'mid 101-011','bot 001',
                                                                'past 001->001','unexplained'],
                                  dtype=object)}

for date in ['0128','0313']:
    print(types[date])
    df = dfs[types[date]]
    for time in list(range(1,7)):
        print(times[time])
        with open('20170313_mcf7_transcriptional_cascade_layers/cascade_layer_'+
                  str(time)+'_2017'+date+'.txt','r') as file:
            file = csv.reader(file,delimiter=' ')
            file= list(file)
            for line in file:
                line = [i for i in line if i != '']
                if line[0] in ['top','past','mid','bot',]:
                    if len(line)>2:
                        if line[2]=='->':
                            df.ix[times[time],line[0]+' '+line[1]+line[2]+line[3]] = line[4:]
                        else:
                            df.ix[times[time],line[0]+' '+line[1]] = line[2:]
                    else:
                        df.ix[times[time],line[0]+' '+line[1]] = line[2:]
                else:
                    df.ix[times[time],line[0]] = line[1:]

diff = pd.DataFrame(index=times.values(),columns=['top 101:','top 111:',
                                                                'top 011:','past 001:',
                                                                'mid 111:','mid 101-111-011:',
                                                                'mid 101-011','bot 001',
                                                                'past 001->001','unexplained'],
                    dtype=object)
diffr = diff.copy()

for row in diff.index:
    for col in diff.columns:
            diff.ix[row,col] = set(dfs['time t and t-1'].ix[row,col]).difference(dfs['time t only'].ix[
                row,col])
print('****ADDED WHEN INCLUDING PREVIOUS TIME****')
print(diff)

for row in diffr.index:
    for col in diffr.columns:
            diffr.ix[row,col] = set(dfs['time t only'].ix[row,col]).difference(dfs['time t and t-1'].ix[
                row,col])
print('****ADDED WHEN EXCLUDING PREVIOUS TIME****')
print(diffr)

dfs['N time t and t-1'] = dfs['time t and t-1'].applymap(len)
dfs['N time t only'] = dfs['time t only'].applymap(len)

for frame in ['N time t and t-1','N time t only']:
    df = dfs[frame]
    df['explained']=df[['mid 111:','mid 101-111-011:','mid 101-011','bot 001','past 001->001']].sum(axis=1)
    df['total'] = df[['explained','unexplained']].sum(axis=1)
    df['percent explained'] = 100*df['explained']/df['total']
    dfs[frame] = df

print('****NUMBERS****')
print(pd.concat([dfs['N time t only'],dfs['N time t and t-1']],axis=1,keys=['N time t only','N time t and t-1']))

Ndiff = dfs['N time t and t-1']-dfs['N time t only']

print('****DIFFERENCE****')
print(Ndiff)


"""
Database class
"""
import os
from ase.db import connect

def make_entry_from_CSD(code):
    """
    make entry dictionary from CSD codes

    Args:
        code: a list of CSD codes
    """
    from pyxtal.msg import CSDError
    from pyxtal import pyxtal
    from rdkit.Chem.Descriptors import ExactMolWt
    from rdkit.Chem.rdMolDescriptors import CalcMolFormula
    from rdkit import Chem

    url0 = "https://www.ccdc.cam.ac.uk/structures/Search?Ccdcid="
    xtal = pyxtal(molecular=True)
    try:
        xtal.from_CSD(code)
    except CSDError as e:
        print("CSDError", code, e.message)
    if xtal.valid:
        m = Chem.MolFromSmiles(xtal.tag['smiles'])
        mol_wt = ExactMolWt(m)
        mol_formula = CalcMolFormula(m)
        kvp = {
                "csd_code": xtal.tag['csd_code'],
                "mol_smi": xtal.tag['smiles'],
                "ccdc_number": xtal.tag['ccdc_number'],
                "space_group": xtal.group.symbol,
                "spg_num": xtal.group.number,
                "Z": sum(xtal.numMols),
                "Zprime": xtal.get_zprime()[0],
                "url": url0 + str(xtal.tag['ccdc_number']),
                "mol_formula": mol_formula,
                "mol_weight": mol_wt,
                "mol_name": xtal.tag['csd_code'],
                "l_type": xtal.lattice.ltype,
              }
        entry = (xtal.to_ase(), kvp, None)
        return entry
    else:
        return None

def make_db_from_CSD(dbname, codes):
    """
    make database from CSD codes

    Args:
        dbname: db file name
        codes: a list of CSD codes
    """
    # open
    db = database(dbname)

    # add structure
    for i, code in enumerate(codes):
        entry = make_entry_from_CSD(code)
        if entry is not None:
            db.add(entry)
            print(i, code)

class database():
    """
    This is a database class to process crystal data

    Args:
        db_name: *.db format from ase database
    """

    def __init__(self, db_name):
        self.db_name = db_name
        #if not os.path.exists(db_name):
        #    raise ValueError(db_name, 'doesnot exist')

        self.db = connect(db_name)
        self.get_all_codes()
        self.keys = ['csd_code', 'space_group', 'spg_num',
                     'Z', 'Zprime', 'url', 'mol_name',
                     'mol_smi', 'mol_formula', 'mol_weight',
                     'l_type',
                    ]
        self.calculators = ['charmm',
                            'gulp',
                            'ani',
                            'dftb_D3',
                            'dftb_TS',
                           ]

    def vacuum(self):
        self.db.vacuum()

    def get_all_codes(self):
        codes = []
        for row in self.db.select():
            if row.csd_code not in codes:
                codes.append(row.csd_code)
            else:
                print('find duplicate! remove', row.csd_code)
                self.db.delete(row.id)
        self.codes = codes

    def add(self, entry):
        (atom, kvp, data) = entry
        if kvp['csd_code'] not in self.codes:
            kvp0 = self.process_kvp(kvp)
            self.db.write(atom, key_value_pairs=kvp0, data=data)
            self.codes.append(kvp['csd_code'])

    def add_from_code(self, code):
        entry = make_entry_from_CSD(code)
        if entry is not None:
            self.add(entry)
        else:
            print("{:s} is not a valid entry".format(code))

    def process_kvp(self, kvp):
        kvp0 = {}
        for key in self.keys:
            if key in kvp:
                kvp0[key] = kvp[key]
            else:
                print('Error, cannot find ', key, ' from the input')
                return
        return kvp0

    def check_status(self, show=False):
        """
        Check the current status of each entry
        """
        ids = []
        for row in self.db.select():
            if len(row.data.keys())==len(self.calculators):
                ids.append(row.id)
                if show:
                    row_info = self.get_row_info(id=row.id)
                    self.view(row_info)
            else:
                print(row.csd_code) #, row.data['charmm_info']['prm'])
        return ids

    def copy(self, db_name, csd_codes):
        """
        copy the entries to another db

        Args:
            db_name: db file name
            csd_codes: list of codes
        """
        if db_name == self.db_name:
            raise RuntimeError('Cannot use the same db file for copy')
        with connect(db_name) as db:
            for csd_code in csd_codes:
                row_info = self.get_row_info(code=csd_code)
                (atom, kvp, data) = row_info
                db.write(atom, key_value_pairs=kvp, data=data)

    def view(self, row_info):
        """
        print the summary of benchmark results

        Args:
            row: row object
        """
        from pyxtal import pyxtal
        from pyxtal.util import ase2pymatgen
        from pyxtal.representation import representation
        from pyxtal.msg import ReadSeedError

        (atom, kvp, data) = row_info

        #Reference
        xtal = self.get_pyxtal(kvp['csd_code'])
        rep = xtal.get_1D_representation()
        print('\n', kvp['csd_code'], kvp['mol_smi'], xtal.lattice.volume)
        print(rep.to_string() + ' reference')

        #calcs
        for key in data.keys():
            calc = key[:-5]
            time = data[key]['time']

            rep = data[key]['rep']
            if type(rep[0]) is not list: rep = [rep]
            rep = representation(rep, kvp['mol_smi']).to_string()

            (dv, msd1, msd2) = data[key]['diff']
            strs = "{:s} {:8s} {:6.2f} {:6.3f}".format(rep, calc, time/60, dv)
            if msd1 is not None:
                strs += "{:6.3f}{:6.3f}".format(msd1, msd2)
            print(strs)

    def get_row_info(self, id=None, code=None):
        match = False
        if id is not None:
            for row in self.db.select(id=id):
                match = True
                break
        elif code is not None:
            for row in self.db.select(csd_code=code):
                match = True
                break
        if match:

            kvp = {}
            for key in self.keys:
                kvp[key] = row.key_value_pairs[key]

            data0 = {}
            for calc in self.calculators:
                key = calc + '_info'
                if key in row.data.keys():
                    data0[key] = row.data[key]

            atom = self.db.get_atoms(id=row.id)
            return (atom, kvp, data0)
        else:
            msg = 'cannot find the entry from ' + id + code
            raise RuntimeError(msg)

    def get_row(self, code):
        for row in self.db.select(csd_code=code):
            return row
        msg = 'cannot find the entry from ' + code
        raise RuntimeError(msg)

    def get_pyxtal(self, code):
        from pyxtal import pyxtal
        from pyxtal.util import ase2pymatgen
        from pyxtal.msg import ReadSeedError

        row = self.get_row(code)
        atom = self.db.get_atoms(id=row.id)
        #Reference
        pmg = ase2pymatgen(atom)
        smi = row.mol_smi
        smiles = smi.split('.')
        molecules = [smile+'.smi' for smile in smiles]

        xtal = pyxtal(molecular=True)
        try:
            xtal.from_seed(pmg, molecules=molecules)
        except ReadSeedError:
            xtal.from_seed(pmg, molecules=molecules, add_H=True)

        return xtal

    def compute(self, row, work_dir, skf_dir):
        if len(row.data.keys())<len(self.calculators):
            #not label information, run antechamber
            atom = self.db.get_atoms(id=row.id)
            if 'gulp_info' not in row.data.keys():
                pmg, c_info, g_info = get_parameters(row, atom)
                row.data = {'charmm_info': c_info,
                            'gulp_info': g_info
                           }
            else:
                pmg = ase2pymatgen(atom)

            data = compute(row, pmg, work_dir, skf_dir)
            self.db.update(row.id, data=data)
            print('updated the data for', row.csd_code)

if __name__ == "__main__":
    # open
    db = database('test.db')
    print("Total number of entries", len(db.codes))

    # view structure
    c = db.get_pyxtal('HXMTAM')
    print(c)


import Matrices

"""
Input file format:
first line is the number of branches in the circuit
following that is an empty line
following that are the J R E values written as 3 space
	seperated digits
following that is an empty line
following that is the incidence matrix.
	The digits can be seperated by any number of spaces
	Newlines seperate the rows.

Example network file between dashed lines:
-----------------------------
5

0 2 -5
0 3 0
0 4 0
0 3 0
0 1 0

-1 1 0 0 0
0 -1 1 0 1
0 -1 1 0 1
0 0 -1 0 1
-----------------------------
"""

class NetworkSolver():

	def __init__(self, inputFile):
		network = inputFile.read().split('\n')
		network = [line for line in network if line != '\n']
		self.numBranches = int(network[0].strip())
		self.physicalValues = [[float(x) for x in line.split()] for line in network[2:self.numBranches+2]]
		mtrx = [[float(x) for x in line.split()] for line in network[self.numBranches+3:] if line !='']
		self.incidenceMtrx = Matrices.Matrix(len(mtrx), self.numBranches, mtrx)

	def computeLeftSide(self):
		# cool trick for making matrix
		conductanceMtrx = Matrices.Matrix(self.numBranches, self.numBranches, \
		                    [[(i == j) * 1/self.physicalValues[j][1] \
		                    for i in range(self.numBranches)] \
							for j in range(self.numBranches)])
		scaledIncidence = self.incidenceMtrx.multiplyByMatrix(conductanceMtrx)
		result = scaledIncidence.multiplyByMatrix(self.incidenceMtrx.getTranspose())
		result = result.getRawDataRef() # just want raw data
		# it's now positive definite so we have to upgrade it
		return Matrices.BehavingMatrix(len(result), len(result), result)

	def computeRightSide(self):
		# we'll just return the 1D vector
		# branchValues == J - Y*E
		branchValues = [[J - E/R] for [J, R, E] in self.physicalValues]
		# change it to matrix
		branchValues = Matrices.Matrix(self.numBranches, 1, branchValues)
		return self.incidenceMtrx.multiplyByMatrix(branchValues).getTranspose().getRawDataRef()[0]

	def solveSystemCholesky(self):
		return self.computeLeftSide().solveSystem(self.computeRightSide())

class SparseNetworkSolver(NetworkSolver):
	def computeLeftSide(self):
		# cool trick for making matrix
		conductanceMtrx = Matrices.Matrix(self.numBranches, self.numBranches, \
		                    [[(i == j) * 1/self.physicalValues[j][1] \
		                    for i in range(self.numBranches)] \
							for j in range(self.numBranches)])
		scaledIncidence = self.incidenceMtrx.multiplyByMatrix(conductanceMtrx)
		result = scaledIncidence.multiplyByMatrix(self.incidenceMtrx.getTranspose())
		result = result.getRawDataRef() # just want raw data
		# it's now positive definite so we have to upgrade it
		return Matrices.BehavingSparseMatrix(len(result), len(result), result)


#  program to check the number is palindrome or not

num  = int(input("Enter a number"))
temp = num
rev =  0

while num > 0:
    dig = num % 10
    rev = rev*10+dig
    num = num // 10

if temp == rev:
    print("palindrome")
else:
    print("not palindrome")

# revese the string using list
# my_str = input("Enter a string:")

# my_str = my_str.casefold()

# re_str = list(reversed(my_str))
# for i in re_str:
#     print(i,end=" ")

# print()
# print(re_str,"\n")


from db.run_sql import run_sql
from models.member import Member
from models.upcoming_session import UpcomingSession

import repositories.member_repository as member_repository
import repositories.upcoming_sessions_repository as upcoming_sessions_repository

def save(upcoming_sessions_member):
    sql = "INSERT INTO upcoming_sessions_members(upcoming_session_id, member_id) VALUES (%s, %s) RETURNING *"
    values = [upcoming_sessions_member.upcoming_session.id, upcoming_sessions_member.member.id]

    # Check is there is space in the upcoming session
    upcoming_session = upcoming_sessions_member.upcoming_session
    print(upcoming_session.remaining_capacity)
    if upcoming_session.remaining_capacity > 0:
        results = run_sql(sql, values)
        upcoming_sessions_member.id = results[0]['id']
        upcoming_sessions_repository.update_capacity(upcoming_session)
    else:
        print("Upcoming Session Full")

def select_all_booked_members(id):
    all_booked_member_ids = []
    results = run_sql("SELECT * FROM upcoming_sessions_members")
    for row in results:
        if int(row['upcoming_session_id']) == int(id):
            all_booked_member_ids.append(row['member_id'])
    all_booked_members = []
    for member_id in all_booked_member_ids:
        found_member = member_repository.select(member_id)
        all_booked_members.append(found_member)
    return all_booked_members


"""Creates database table with a defined schema if it does not already exist."""
import argparse
import os
import sys
import sqlite3

def get_schema(path):
    """read schema and strip \n, returning a single line string"""
    with open(path, "r") as schema:
        schema_text = schema.read()
    return schema_text.replace("\n", " ")

# Setup parser

parser = argparse.ArgumentParser(
    description="Create database table if it does not already exist."
)
parser.add_argument("-db", help="full path to a valid database")
parser.add_argument("-schema", help="full path to a schema file")

# script

args = parser.parse_args()

if not os.path.exists(args.schema):
    sys.exit(f"Schema file {args.schema} does not exist.")

schema = get_schema(args.schema)
con = sqlite3.connect(args.db)
try:
    con.execute(schema)
except Exception as e:
    print(f"Something went wrong. Exception:\n {e}")

sys.exit("Table created")


import re

__author__ = 'Daeyun Shin'

vim = None

class PythonVimUtils(object):
    comment_pattern = re.compile(r"(^(?:(?<![\.\w\)\}\]])'[^']*'|[^%]*?)*)(%.*|$)")
    cell_header_pattern = re.compile(
        r'(?:^%%(?:[^%]|$)|^[ \t]*?(?<!%)[ \t]*?(?:function|classdef)\s+)')
    ellipsis_pattern = re.compile(r'^(.*[^\s])\s*\.\.\.\s*$')
    variable_pattern = re.compile(r"\b((?:[a-zA-Z_]\w*)*\.?[a-zA-Z_]*\w*)")
    function_block_pattern = re.compile(
        r'(?:^|\n[ \t]*)(?<!%)[ \t]*(?:function|classdef)(?:.*?)[^\w]([a-zA-Z]\w*) *(?:\(|(?:%|\n|\.\.\.|$))[\s\S]*?(?=(?:\n)(?<!%)[ \t]*(?:function[^a-zA-Z]|classdef[^a-zA-Z])|$)')
    option_line_pattern = re.compile(r'%%! *vim-matlab: *(\w+) *\(([^\(]+)\)')

    @staticmethod
    def get_current_file_path():
        return vim.eval("expand('%:p')")

    @staticmethod
    def save_current_buffer():
        vim.command("w")

    @staticmethod
    def edit_file(path):
        vim.command("silent e! {}".format(path))

    @staticmethod
    def get_cursor():
        """
        :return: 1-indexed current cursor position
        """
        row, col = vim.current.window.cursor
        return row, col + 1

    @staticmethod
    def set_cursor(row_col):
        vim.current.window.cursor = (row_col[0], row_col[1] - 1)

    @staticmethod
    def get_selection(ignore_matlab_comments=True):
        buf = vim.current.buffer
        row1, col1 = buf.mark('<')
        row2, col2 = buf.mark('>')
        lines = buf[row1 - 1:row2]
        if len(lines) == 1:
            lines[0] = lines[0][col1:col2 + 1]
        else:
            lines[0] = lines[0][col1:]
            lines[-1] = lines[-1][:col2 + 1]

        if ignore_matlab_comments:
            return PythonVimUtils.trim_matlab_code(lines)
        return lines

    @staticmethod
    def get_lines():
        buf = vim.current.buffer
        return buf

    @staticmethod
    def get_text_selection():
        pass

    @staticmethod
    def is_current_buffer_modified():
        return vim.eval('&modified') == 1

    @staticmethod
    def echo_text(string):
        vim.command("echo '{}'".format(string.replace("'", r"''")))

    @staticmethod
    def get_current_matlab_cell_lines(ignore_matlab_comments=True):
        lines = PythonVimUtils.get_lines()
        crow, _ = PythonVimUtils.get_cursor()

        cell_start = crow - 1
        while cell_start > 0:
            if PythonVimUtils.cell_header_pattern.match(lines[cell_start]):
                cell_start += 1
                break
            cell_start -= 1

        cell_end = crow - 1
        while cell_end < len(lines) - 1:
            cell_end += 1
            if PythonVimUtils.cell_header_pattern.match(lines[cell_end]):
                cell_end -= 1
                break

        lines = lines[cell_start:cell_end + 1]
        if ignore_matlab_comments:
            return PythonVimUtils.trim_matlab_code(lines)
        return lines

    @staticmethod
    def trim_matlab_code(lines):
        new_lines = []

        ellipsis = PythonVimUtils.ellipsis_pattern

        is_continuation = False

        for line in lines:
            line = PythonVimUtils.comment_pattern.sub(r"\1", line).strip()
            if line in ('', '...'):
                continue

            has_ellipsis_suffix = ellipsis.match(line)
            if has_ellipsis_suffix:
                line = ellipsis.sub(r"\1", line)

            if is_continuation and new_lines:
                new_lines[-1] += line
            else:
                new_lines.append(line)

            is_continuation = has_ellipsis_suffix

        return new_lines

    @staticmethod
    def get_variable_under_cursor():
        line = PythonVimUtils.get_current_line()
        if not line:
            return None
        _, col = PythonVimUtils.get_cursor()

        for m in PythonVimUtils.variable_pattern.finditer(line):
            if m.start() < col <= m.end():
                return m.group(0)

    @staticmethod
    def get_current_line():
        row, col = PythonVimUtils.get_cursor()
        lines = PythonVimUtils.get_lines()
        if len(lines) < row:
            return None
        return lines[row - 1]

    @staticmethod
    def get_current_matlab_line():
        row, col = PythonVimUtils.get_cursor()
        lines = PythonVimUtils.get_lines()
        if len(lines) < row:
            return None

        cur = row - 1

        cont = PythonVimUtils.ellipsis_pattern

        off = 0
        while cur + 1 < len(lines) and cont.match(lines[cur + off]):
            off += 1

        line = lines[cur + off]

        while cur + off > 0 and cont.match(lines[cur + off - 1]):
            line = cont.sub(r"\1", lines[cur + off - 1]) + line
            off -= 1

        return line

    @staticmethod
    def get_options():
        lines = vim.current.buffer[:20]
        options = {}
        for line in lines:
            m = PythonVimUtils.option_line_pattern.match(line)
            if m is None:
                break
            options[m.group(1)] = [s.strip() for s in m.group(2).split(',')]
        return options

    @staticmethod
    def get_function_blocks():
        lines = vim.current.buffer
        content = '\n'.join(lines)
        function_blocks = {}
        for m in PythonVimUtils.function_block_pattern.finditer(content):
            function_blocks[m.group(1)] = m.group(0).strip()

        return function_blocks


#!/bin/python
# -*- coding: UTF-8 -*-

import torch
import torch.nn as nn
from torch.distributions.categorical import Categorical
from torch.optim import Adam
import numpy as np
import gym
from gym.spaces import Discrete, Box
import sys
import json
import pdb
import os
import gym_arc
import time
sys.path.append('./gym_arc/envs/')
from config import LR, EPOCHS, batch_size, RENDER, MODEL, INPUT_FILE, STEPS_LIMIT, DECAY, FILE_ID, device, action_model

# soft-ac, ppo
# 怎样优化重复动作，无意义动作
# 找最核心特征
# 适配所有题目，看是否泛化

def generate_model(feature_num, action_num):
    hidden_size = 82

    net = nn.Sequential(
        nn.Linear(feature_num, hidden_size),
        nn.Dropout(0.3),
        nn.ReLU(),
        nn.Linear(hidden_size, hidden_size),
        nn.Dropout(0.3),
        nn.ReLU(),
        nn.Linear(hidden_size, hidden_size),
        nn.Dropout(0.3),
        nn.ReLU(),
        nn.Linear(hidden_size, action_num),
        nn.Softmax()
    )

    for layer in net:
        if isinstance(layer, nn.Linear):
            nn.init.xavier_uniform(layer.weight)

    return net

def get_categorical(model, obs):
    model.eval()
    probs = model(obs)
    return Categorical(probs=probs)

def get_action(model, obs):
    return get_categorical(model, obs).sample().item()

def compute_loss(model, obs, action, weights):
    logp = get_categorical(model, obs).log_prob(action)
    return -(logp * weights).mean()

def train():
    with open(INPUT_FILE, 'r') as f:
        puzzle = json.load(f)

    envs = []
    env_idx = 0

    for i in range(len(puzzle['train'])):
        p = puzzle['train'][i]
        e = gym.make('arc-v0', input=p['input'], output=p['output'], need_ui=RENDER, action_mode='single')
        envs.append(e)

    #envs = envs[:1]
    #pdb.set_trace()

    test_input = puzzle['test'][0]['input']
    test_output = puzzle['test'][0]['output']
    env_test = gym.make('arc-v0', input=test_input, output=test_output, need_ui=RENDER, action_mode='single')

    n_feature = env_test.observation_space.shape[0]
    n_acts = env_test.action_space.n
    print('feature(%d) actions(%d)' % (n_feature, n_acts))

    #
    if (MODEL == ''):
        net = generate_model(n_feature, n_acts)
        net.train()
    else:
        net = torch.load(MODEL)
        envs.append(env_test)
        print(envs)
        net.eval()

    net.to(device)

    optimizer = Adam(net.parameters(), lr=LR)

    for epoch_idx in range(EPOCHS):
        batch_obs = []
        batch_acts = []
        batch_weights = []
        rewards = []

        env = envs[0]
        obs = env.reset()
        steps = 0

        while True:
            steps += 1

            if RENDER: env.render()

            act = get_action(net, torch.as_tensor(obs, dtype = torch.float32).to(device))
            next_obs, r, done, info = env.step(act)

            if (steps >= STEPS_LIMIT):
                done = True

            batch_acts.append(act)
            batch_obs.append(obs)
            rewards.append(r)

            obs = next_obs

            #time.sleep(5)

            if done:
                print('epoch_idx:%4d %100s     ----> %2.1f\t env:%2d' % (epoch_idx, info['steps'][:20], info['total_reward'], env_idx))

                if (len(envs) > 1):
                    env_idx = (env_idx + 1) % len(envs)
                    env = envs[env_idx]

                returns = [0] * len(rewards)
                acc_rewards = 0
                for i in reversed(range(len(rewards))):
                    acc_rewards = rewards[i] + DECAY * acc_rewards
                    returns[i] = acc_rewards
                batch_weights += returns

                obs, done, rewards, steps = env.reset(), False, [], 0

                if len(batch_obs) > batch_size:
                    break

        if (MODEL == ''):
            net.train()
            optimizer.zero_grad()
            print('----------------------------- learning --------------------------')
            loss = compute_loss(net,
                                    torch.as_tensor(batch_obs, dtype = torch.float32).to(device),
                                    torch.as_tensor(batch_acts, dtype = torch.int32).to(device),
                                    torch.as_tensor(batch_weights, dtype = torch.float32).to(device)
                                    )

            loss.backward()
            optimizer.step()

            if (epoch_idx % 20 == 0):
                torch.save(net, ('./result/%s_%4d.model' % (FILE_ID, epoch_idx)))

if __name__ == '__main__':
    train()


"""
Funções (def): *args, **kwargs

Não obrigatoriamente precisa ser colocado "args" ou "kwargs" isso é mais um padrão,
porém só é necessario os astéricos.
"""

"""
def func(*args):
    for v in args:
        print(args)
    print(args[0])
    print(len(args))

func(1, 2, 3, 4, 5)

# Args é uma tuple possuindo comandos que usamos na lista e podem virar listas
lista = [1, 2, 3, 4, 5]
n1, n2, *n = lista  # Desempacotou 2 valores e "guardou o resto"
print(n1, n2, n)

lista = [6, 7, 8, 9]
print(*lista, sep='-')
"""

"""
def func1(*args, **kwargs):
    print(args)
    print(kwargs)  # Mostra os argumentos com valores determinados (args não mostra)

lista1 = [1, 2, 3, 4, 5]
lista2 = [10, 20, 30, 40, 50]
func1(*lista1, *lista2, nome='Gabriel', sobrenome="Belo")
# As listas foram desempacotadas formando uma tuple
"""

# Melhor forma de se usar "kwargs", para não apresentar erros no código, quando não se tem
# certeza sobre os argumentos do código

def func2(**kwargs):

    idade = kwargs.get('idade')

    if idade is not None:
        print(f'Sua idade é {idade} anos')

    altura = kwargs.get('altura')

    if altura is not None:
        print(altura)

    else:
        print('Não foi enviado os dados de altura')

func2(idade=14)

Python Intermediário/Aula 30 a 39/Aula 31/Aula 31 - Funções (def) Part3.py


from math import sin, cos, radians, acos

class CalculationPosition:
	def __init__(self, Length, Width, Angle, StepX = 0, StepY = 0):
		self.Length = Length
		self.Width = Width
		self.Angle = Angle
		self.StepX = StepX
		self.StepY = StepY

	def define_сoordinates_contour(self):
		self.Diagonal = (((self.Width/2)**2 + (self.Length/2)**2)**0.5)*2
		if -self.Angle != 0:
			AngleDiagonal = (radians(-self.Angle) -
						acos((self.Length/2)/(self.Diagonal/2)))
			self.x1 = sin(AngleDiagonal)*(self.Diagonal/2) + self.StepX
			self.y1 = cos(AngleDiagonal)*(self.Diagonal/2) + self.StepY
			self.x2 = cos(AngleDiagonal)*(self.Diagonal/2) + self.StepX
			self.y2 = sin(AngleDiagonal)*(self.Diagonal/2) + self.StepY
			self.x3 = -sin(AngleDiagonal)*(self.Diagonal/2) + self.StepX
			self.y3 = -cos(AngleDiagonal)*(self.Diagonal/2) + self.StepY
			self.x4 = -cos(AngleDiagonal)*(self.Diagonal/2) + self.StepX
			self.y4 = -sin(AngleDiagonal)*(self.Diagonal/2) + self.StepY
		else:
			self.x1 = -self.Length/2 + self.StepX
			self.y1 = self.Width/2 + self.StepY
			self.x2 = self.Length/2 + self.StepX
			self.y2 = self.Width/2 + self.StepY
			self.x3 = self.Length/2 + self.StepX
			self.y3 = -self.Width/2 + self.StepY
			self.x4 = -self.Length/2 + self.StepX
			self.y4 = -self.Width/2 + self.StepY
		self.point1 = (self.x1, self.y1)
		self.point2 = (self.x2, self.y2)
		self.point3 = (self.x3, self.y3)
		self.point4 = (self.x4, self.y4)
		self.Coordinates = [self.point1, self.point2, self.point3, self.point4]
		return self.Coordinates

	def get_text_metrics(self, Size):
		if self.Length >= Size:
			self.SizeText = Size
		else:
			self.SizeText = self.Length
		# tk_root = Tkinter.Tk()
		# font = tkFont.Font(family = 'GOST type A (plotter)', size = self.SizeText, slant = "italic")
		self.WithText = 50 #(font.measure(self.TextKompas))

		return (self.SizeText, self.WithText)

	def define_сoordinates_text(self):
		if self.Angle < 0:
			self.xText = -sin(radians(-self.Angle)) * self.SizeText/2 - sin(radians(-self.Angle)) * self.WithText/2 + self.StepX
			self.yText = -cos(radians(-self.Angle)) * self.SizeText/2 + cos(radians(-self.Angle)) * self.WithText/2 + self.StepY
		elif self.Angle > 0:
			self.xText = cos(radians(-self.Angle)) * self.SizeText/2 + sin(radians(-self.Angle)) * self.WithText/2 + self.StepX
			self.yText = -cos(radians(-self.Angle)) * self.SizeText/2 - cos(radians(-self.Angle)) * self.WithText/2 + self.StepY
		else:
			self.xText = +self.SizeText/2 + self.StepX
			self.yText = -self.WithText/2 + self.StepY
		self.CoordinatesText = (self.xText, self.yText)
		return self.CoordinatesText

	def direction_text(self, Top = 0, Down = 0, Left = 0, Right = 0):
		if self.Angle > 0:
			if Top != 0:
				self.xdText += sin(radians(-self.Angle)) * Top
				self.ydText += cos(radians(-self.Angle)) * Top
			if Down != 0:
				self.xdText += -sin(radians(-self.Angle)) * Down
				self.ydText += -cos(radians(-self.Angle)) * Down
			if Left != 0:
				self.xdText += sin(radians(-self.Angle)) * Left
				self.ydText += -cos(radians(-self.Angle)) * Left
			if Right != 0:
				self.xdText += -sin(radians(-self.Angle)) * Right
				self.ydText += cos(radians(-self.Angle)) * Right
		elif self.Angle < 0:
			if Top != 0:
				self.xdText += sin(radians(-self.Angle)) * Top
				self.ydText += cos(radians(-self.Angle)) * Top
			if Down != 0:
				self.xdText += -sin(radians(-self.Angle)) * Down
				self.ydText += -cos(radians(-self.Angle)) * Down
			if Left != 0:
				self.xdText += -sin(radians(-self.Angle)) * Left
				self.ydText += cos(radians(-self.Angle)) * Left
			if Right != 0:
				self.xdText += sin(radians(-self.Angle)) * Right
				self.ydText += -cos(radians(-self.Angle)) * Right
		else:
			if Top != 0:
				self.xdText += Top
			if Down != 0:
				self.xdText += -Down
			if Left != 0:
				self.ydText += -Left
			if Right != 0:
				self.ydText += Right
		return (self.xdText, self.ydText)


import argparse
import gzip
import hashlib
import json
import logging
from pathlib import Path
from tqdm import tqdm

logging_fmt="%(asctime)s %(levelname)s: %(message)s"
logging.basicConfig(format=logging_fmt)
logger=logging.getLogger(__name__)
logger.setLevel(level=logging.INFO)

def get_md5_hash(text:str)->str:
    return hashlib.md5(text.encode()).hexdigest()

def main(args):
    logger.info(args)

    wikipedia_data_filepath:str=args.wikipedia_data_filepath
    extract_root_dirname:str=args.extract_root_dirname

    extract_root_dir=Path(extract_root_dirname)
    extract_root_dir.mkdir(parents=True,exist_ok=True)

    logger.info("Wikipediaデータの行数を数えています...")

    num_wiki_data_lines=0
    with gzip.open(wikipedia_data_filepath,"r") as r:
        for line in r:
            num_wiki_data_lines+=1

    logger.info("行数: {}".format(num_wiki_data_lines))

    with gzip.open(wikipedia_data_filepath,"r") as r:
        for line in tqdm(r,total=num_wiki_data_lines):
            data=json.loads(line)

            title=data["title"]
            text=data["text"]

            title_hash=get_md5_hash(title)

            wiki_save_dir=extract_root_dir.joinpath(title_hash)
            wiki_save_dir.mkdir(exist_ok=True)

            title_file=wiki_save_dir.joinpath("title.txt")
            with title_file.open("w") as w:
                w.write(title)

            text_file=wiki_save_dir.joinpath("text.txt")
            with text_file.open("w") as w:
                w.write(text)

    logger.info("処理が完了しました")

if __name__=="__main__":
    parser=argparse.ArgumentParser()
    parser.add_argument("--wikipedia_data_filepath",type=str,default="../Data/all_entities.json.gz")
    parser.add_argument("--extract_root_dirname",type=str,default="../Data/Wikipedia")
    args=parser.parse_args()

    main(args)


#!/usr/bin/env python3

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

class ComboBox(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self)
        self.set_title("ComboBox")
        self.set_default_size(150, -1)
        self.connect("destroy", Gtk.main_quit)

        liststore = Gtk.ListStore(str)

        for item in ["Debian", "Fedora", "Tiny Core", "Linux Mint", "Mageia"]:
            liststore.append([item])

        combobox = Gtk.ComboBox()
        combobox.set_model(liststore)
        combobox.set_active(0)
        combobox.connect("changed", self.on_combobox_changed)
        self.add(combobox)

        cellrenderertext = Gtk.CellRendererText()
        combobox.pack_start(cellrenderertext, True)
        combobox.add_attribute(cellrenderertext, "text", 0)

    def on_combobox_changed(self, combobox):
        treeiter = combobox.get_active_iter()
        model = combobox.get_model()

        print("ComboBox selected item: %s" % (model[treeiter][0]))

window = ComboBox()
window.show_all()

Gtk.main()


"""Unittest suit cases for TFRecord IO
"""

__author__ = "Liyan Chen"
__copyright__ = "Copyright (c) 2017 Malmactor"
__license__ = "MIT"

import unittest

import numpy as np

class TestTFRecordIO(unittest.TestCase):
    def test_IO(self):
        batch = np.random.rand(32, 60, 60, 4)

        # Write numpy batch into TFRecord

        # Read it out from TFRecord again

        # Compare them
        self.assertTrue(np.allclose(batch, batch))

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