####################
# NECESSARY IMPORTS#
####################

# core app function mechanics
import pandas as pd
import numpy as np
import cv2
from PIL import Image
import pickle

# importing custom functions
from softcopyOCR import decode_predictions, get_image_text, clean_string, clean_tesseract_output, display_ocr
from softcopy_textmatch import best_match
from softcopy_recommender import get_recommends_list, get_recommends, get_book_details

# app building
import streamlit as st
import time
import urllib.request
import io

# surpress streamlit warning
st.set_option('deprecation.showfileUploaderEncoding', False)
st.beta_set_page_config(page_title='SOFTCOPY',
                        page_icon=None,
                        layout='centered',
                        initial_sidebar_state='auto')

# loading data
with open('data/all_books_clean.pkl', 'rb') as f:
    books_all = pickle.load(f)

ISBNs = pd.read_csv('data/ISBNs.csv')

with open('data/vt_800.pkl', 'rb') as f:
    VT = pickle.load(f)

def show_book_images(recs):
    '''
    Displays images of recommendation ocr_results
    recs: list, ISBNs, of book recommendations
    '''
    # iterate through book recommendations
    for book in recs:
        try:
            # get url of large image for each recommended book
            rec_dict = get_book_details(book, books_all)
            url = rec_dict['image_l']
            with urllib.request.urlopen(url) as url:
                with open('temp.jpg', 'wb') as f:
                    f.write(url.read())

            # load and display image
            test_img = Image.open('temp.jpg')
            st.image(test_img)

        # error handling for image display error (rare)
        except OSError:
            pass

    # done!
    st.balloons()

def get_recs(matched_isbns, num_recs):
    '''
    Gets recommendations from matched ISBN_list
    Returns list of ISBNs for recommended books based on books in matched_isbns
    matched_isbns: list, book ISBNs matched from ORC output, produced by match_title
    '''

    st.header('**Step 3: Recommend books based on the ones on your bookshelf**')
    st.markdown('Getting recommendations...')

    # animates quick loading bar
    rec_loading_bar = st.progress(0)
    for percent_complete in range(100):
        time.sleep(0.02)
        rec_loading_bar.progress(percent_complete + 1)

    # gets recommendations
    global VT, ISBNs, books_all
    recs, basis = get_recommends_list(matched_isbns, VT, ISBNs, n=num_recs)

    # prints recommendation basis
    st.subheader('Based off of these books that you own : ')
    for book in basis:
        rec_dict = get_book_details(book, books_all)
        st.markdown("* {} by {} ({}, {})".format(rec_dict['title'],
                                                rec_dict['author'],
                                                rec_dict['publisher'],
                                                rec_dict['year']))

    # prints recommendations
    st.subheader('Your recommended reading includes: ')
    for book in recs:
        rec_dict = get_book_details(book, books_all)
        st.markdown("* {} by {} ({}, {})".format(rec_dict['title'],
                                                rec_dict['author'],
                                                rec_dict['publisher'],
                                                rec_dict['year']))

    # passing recs on to book cover displaying function
    show_book_images(recs)

def match_title(final_ocr, num_recs, confidence):
    '''
    Matches OCR text with book ISBNs
    Returns list of ISBNs of books that match OCR text above the confidence threshold
    final_ocr: list, strings for each grouping of text generated by OCR process
    '''

    st.header('**Step 2: Match OCR results to books in our database**')
    st.write("Matching titles...")
    match_loading_bar = st.progress(0)
    st.subheader('Text matching results:')

    matched_isbns = []
    global books_all

    # finding best match for each string detected by OCR
    for idx, title in enumerate(final_ocr):
        match_loading_bar.progress((idx+1)/len(final_ocr)) # increments loading bar
        match = best_match(title, books_all, min_confidence=confidence)
        matched_isbns.append(match)

    # w.i.p.: buttons to deselect books from rec process
    buttons = [get_book_details(i, books_all)['title'] for i in matched_isbns if get_book_details(i, books_all)]
    match_select = st.sidebar.multiselect('Recommendation basis: ', buttons, buttons)

    # passing matched titles on to recommendation engine
    get_recs(matched_isbns, num_recs)

def run_ocr(new_img, num_recs, confidence, verbose):
    '''
    Performs optical character recognition on specified image
    Returns list of strings
    new_img: image, supplied by main
    '''

    # parameters for OpenVC
    args = {'east': 'frozen_east_text_detection.pb',
            'min_confidence': 0.9,
            'width': 320,
            'height': 320,
            'padding': 0.2}

    st.header('**Step 1: Scan your image for text with OCR**')
    st.write('Scanning image...')

    # images preprocessing, text detection w/ open cv, and text recognition
    # with pytesseract
    ocr_results = get_image_text(args, new_img)

    # show boundary boxes during scan if sidebar box checked
    if verbose:
        display_ocr(ocr_results, new_img)

    # cleans up strings
    final_ocr = clean_tesseract_output(ocr_results, 100)

    # prints results
    st.subheader("Optical character recognition results: ")
    st.write(pd.DataFrame(final_ocr, columns = ['']))

    # passes final ocr results to text matching
    match_title(final_ocr, num_recs, confidence)

def main():
    '''
    Main app function. Features page selector and image upload.
    Press button once image uploaded to start matching/recommendation pipeline
    '''
    st.title('SoftCopy')
    activities = ['Home', 'About']

    # main site nav
    choice = st.sidebar.selectbox("", activities)

    st.sidebar.write('App parameters')

    # recs/text match for get_recs / get_recommends_list fcns
    num_recs = st.sidebar.slider("Recommendations per match", 1, 10, 4) #

    # text match confidence threshold for match_title / best_match fcns
    confidence = st.sidebar.slider('Text matching confidence % threshold',
    0, 100, 75)

    # toggle to show text detection/recognition images during OCR
    verbose = st.sidebar.checkbox('Show OCR Preprocessing', value=False)

    # main site nav choice
    if choice == 'Home':

        # image uploader
        st.header('**Upload an image of your books.**')
        st.header('**Get customized book recommendations.**')

        uploaded_file = st.file_uploader("Choose a image file")

        # displaying uploaded image
        if uploaded_file is not None:
            image_ = Image.open(uploaded_file) # reads image file
            st.image(image_, caption='Uploaded image', use_column_width=True) # displays on app
            new_img = np.array(image_.convert('RGB')) # makes it compatible with OpenCV

            # click to run program (pass image on to OCR)
            if st.button("Let's get started!"):
                run_ocr(new_img, num_recs, confidence, verbose)

    # main site nav choice
    elif choice == 'About':
        about()

def about():
    '''
    Helper function for the about page
    '''
    # overview
    st.subheader('About SoftCopy')
    st.markdown(
                '''
                SoftCopy uses an image of your bookshelf to recommend books for you to read.
                All you need to do is import a photo and the app does the rest!

                The app has three main phases:

                1. Optical character recognition (OCR)
                2. Text matching
                3. Recommendation
    	''')

    # select which phase to view details
    about_options = st.select_slider(
        label='Select a phase to learn more about how it works',
        options=['OCR', 'Text Matching', 'Recommendation'], )

    # OCR phase details
    if about_options == 'OCR':

        st.subheader('Optical character recognition')

        st.markdown('''SoftCopy uses Python, OpenCV and Pytesseract to detect and recognize text in your image.
        OpenCV is used to process images to prepare them for OCR''')

        st.image("https://nanonets.com/blog/content/images/2019/12/Tesseract.gif", width=500)

        st.markdown('''
        Step 1) Preprocessing
        * Image scaling, red/blue swap (for Pytesseract compatability)
        * Mean image subtraction (for clearer signal)

        Step 2) Text detection
        * Bounding box detection using EAST text detection model
        * Non-maxima suppression to eliminate weak, overlapping bounding boxes

        Step 3) Text recognition
        * Pytesseract - pretrained LSTM Neural Network model
        ''')

        # OCR example image
        st.image('Text detection pics/Text Detection_screenshot_09.09.2020 - 2.png', width=500, caption='OCR in action!')

    # text matching phase details
    if about_options == 'Text Matching':

        st.subheader('Text matching')

        st.markdown('''
        Next, SoftCopy takes the text that was detected during the OCR step and performs
        a **token set fuzzy match** the title and author against a list of **266,664 books**
        pulled from the [Book Crossing dataset](http://www2.informatik.uni-freiburg.de/~cziegler/BX/).
        ''')

        # books crossing logo
        st.image('images/bookcrossing.jpg')

        st.markdown('''
        Matching process:

        1. Combine title and author strings

        2. Tokenize into list of unigrams

        3. Sort tokens alphabetically

        4. Remove duplicate tokens

        5. Compare too each book in data set and assigne confidence scores

        Pairs with over 75% confidence are considered a match, but you can toggle
        this percentage in the sidebar to suit the needs of your image.

        Examples:
        * No match for "sil lack a sian sos oo tian m e a r ii lom aimles ba al".
        (Closest match was "smile like a plastic daisy sonia levitin" with 56% confidence.)

        * Closest match for "my ea t diaz junot d":
        **Drown** by **Junot Diaz** with 77% confidence.''')

        # publication year distribution viz
        st.image('viz/pub_year_dist.png')

        st.markdown('''It is important to note that book in this dataset were mostly published between 1980-2000,
        so the likelihood of matching goes up significantly for books from this time period.''')

    # recommendation phase details
    if about_options == 'Recommendation':

        st.subheader('Getting recommendations')

        st.markdown('''SoftCopy uses **collaborative filtering** to recommend books
        based off how your selections compare to other users book preferences.
        SoftCopy's recommendation matrix
        is comprised of:''')

        st.markdown('''
        * 134,299 ratings

        * 10,077 books

        * 12,854 unique reviewers
        ''')

        st.image(['viz/user_age_dist.png', 'viz/rating_dist.png'], width=325)

        st.markdown('''Under the hood, SoftCopy uses **singular value decomposition (SVD)**
        to generate 800 abstract features for each book in the Book Crossing data
        based off of how they have been rated by various users. This effectively groups
        the books into categories that can be throught of as something like *genres*.
        ''')

        st.markdown('Illustration of how SVD works:')

        st.image('images/svd.png', width=500)

        st.markdown('''
        The recommendation engine then uses these 800 properties to **compare the cosine similarity** each of your
        books to each book in the database and rank them in order of highest similarity.

        This process does not use any content-level data about your book such as language,
        length, or author to make a recommendation. **Your recommendations are strictly
        generated by collaborative filtering based on user ratings and SVD features!**
        ''')

# starts app
if __name__ == "__main__":
    main()


from data import *

def encrypt(sentence,key):
    sentence = sentence.lower()
    output=''
    for char in sentence:
        if char == ' ':
            output+=char
        if char in char_to_no.keys():
            pos = char_to_no[char] + key
            if pos in no_to_char.keys():
                output += no_to_char[pos]
            elif pos > len(no_to_char):
                pos = pos - 26
                output+=no_to_char[pos]
    print('Your Encrypted Message is: ')
    print(output)

def decrypt(sentence,key):
    sentence = sentence.lower()
    output = ''
    for char in sentence:
        if char == ' ':
            output+=char
        if char in char_to_no.keys():
            pos = char_to_no[char] - key
            if pos > 0:
                output += no_to_char[pos]
            if pos < 0:
                pos = len(no_to_char) + pos
                output += no_to_char[pos]
    print('Your Decrypted Message is :')
    print(output)

def valid_key():
    while True:
        try:
            key = int(input("Enter Key(1-26) : "))
            if key > 26 or key < 1:
                print('Keys are allowed only bet (1-26)')
            else:
                return key

        except ValueError:
            print('Invalid input. Please enter a valid integer.')

def main():
    print("---------** Casear Cipher **-----------")
    mode = input('Do you Want to (e)ncrypt or (d)ecrypt msg?: ')
    if mode.lower() == 'e':
        key = valid_key()
        message = input('Enter Message to Encrypt: ')
        encrypt(message,key)

    if mode.lower() == 'd':
        key = int(input('Enter Key(1-26): '))
        message = input('Enter Message to Decrypt: ')
        decrypt(message,key)

if __name__ == '__main__':
    main()


from nonebot import on_regex
from nonebot.typing import T_State
from nonebot.adapters.onebot.v11 import GroupMessageEvent,Bot,Message

class Msg:
    def __init__(self):
        self.msg = 0
        self.key = 0
    def get_msg(self,msg):
        self.msg = msg

    def get_key(self,key):
        self.key = key
msg = Msg()
message = on_regex(pattern = r''+msg.get_key()+'^$')

@message.handle()
async def send(bot: Bot, event: GroupMessageEvent, state: T_State):
    await message.send(Message(msg.get_msg()))


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Aug  5 15:08:49 2022

@author: chaithanya
"""
import numpy as np
import sys

class molecule:
    def __init__(self, name):
        self.name          = name
        self.timestep_prod = 0
        self.mol_id        = 0
        self.atom_id       = []


import logging
from common.myconfig import conf
import os
from common.contants import LOG_DIR
#读取配置文件中的数据
level=conf.get("logging","level")
f_level=conf.get("logging","f_level")
s_level=conf.get("logging","s_level")
filename=conf.get("logging","filename")
class Mylogger(object):
    @staticmethod
    def getLogger():
        # 一.创建一个名为：testcaseLog的日志收集器
        my_log=logging.getLogger("testcaseLog")
        # 二.设置日志收集器的等级
        my_log.setLevel(level)
        # 三.添加输出渠道
        # 1.创建一个输出控制台的输出渠道
        sh=logging.StreamHandler()
         # 2.设置输出等级
        sh.setLevel(s_level)
        # 3.将输出渠道绑定到日志收集器上去
        my_log.addHandler(sh)
        #四.添加输出渠道（输出到文件）
        fh=logging.FileHandler((os.path.join(LOG_DIR,filename)),encoding="utf8")
        fh.setLevel(f_level)
        #五.设置日志输出格式
        #创建一个日志输出格式
        my_log.addHandler(fh)
        formatter=logging.Formatter("'%(asctime)s - [%(filename)s-->line:%(lineno)d] - %(levelname)s: %(message)s'")
        #将输出格式和输出渠道进行绑定
        sh.setFormatter(formatter)
        fh.setFormatter(formatter)
        return my_log
#调用类的静态方法，创建一个日志收集器
my_log=Mylogger.getLogger()


import sys
import numpy as np
import yaml
import time
import unicodedata
import tensorflow as tf
from tensorflow.python.saved_model import tag_constants

# For Reproducible
# tf.set_random_seed(1234)
# Global Variables
byte_per_float32 = 4

with open('LPN_100Style25B_BLL.yml') as f:
    config = yaml.load(f, Loader=yaml.FullLoader)

# with open('LPN_FiLM_Finetuning.yml') as f:
#     config = yaml.load(f, Loader=yaml.FullLoader)

Xdim = config["Xdim"]
Ydim = config["Ydim"]
stats_path = config["stats_path"]
model_path = config["ft_model_path"]
styles_list = config["styles_list"]
styles_list.sort()

name_ep_input_tensor = "LPN/test_frame_ph:0"
name_gt_input_tensor = "Gating/test_gating_ph:0"
name_batch_size_tensor = "batch_size_ph:0"
name_mode_tensor = "mode_ph:0"
# name_test_style_tensor = "test_style_ph:0"
name_clip_seed = "clip_seed_ph:0"
name_frame_seed = "frame_seed_ph:0"
name_clip_handle = "Clips/clip_handle_ph:0"
name_frame_handle = "Frames/frame_handle_ph:0"
name_train_flag_0 = "FiLM_Generator/train_flag_ph:0"
name_train_flag_1 = "LPN/train_flag_ph:0"
name_train_flag_2 = "Gating/train_flag_ph:0"
name_film_flag = "FiLM_Generator/film_flag_ph:0"
name_film_params = "FiLM_Generator/film_params_ph:0"
# name_output_tensor = "PFNN/Output:0"
# name_output_tensor = "Square:0"
name_output_tensor = "Mean:0"
name_bll_output_tensor = "truediv:0"  # want to include division by num bones

with tf.Session() as sess:

    tf.saved_model.loader.load(sess, [tag_constants.SERVING], model_path)
    graph = tf.get_default_graph()
    print("Tensorflow graph loaded")

    nn_ep_input_frame = graph.get_tensor_by_name(name_ep_input_tensor)
    nn_gt_input_frame = graph.get_tensor_by_name(name_gt_input_tensor)
    nn_batch_size = graph.get_tensor_by_name(name_batch_size_tensor)
    nn_mode = graph.get_tensor_by_name(name_mode_tensor)

    clip_init_iterators = [graph.get_operation_by_name("Clips/" + style + "/MakeIterator") for style in styles_list]
    frame_init_iterators = [graph.get_operation_by_name("Frames/" + style + "/MakeIterator") for style in styles_list]
    clip_handle_phs = [graph.get_tensor_by_name("Clips/" + style + "/IteratorToStringHandle:0") for style in styles_list]
    frame_handle_phs = [graph.get_tensor_by_name("Frames/" + style + "/IteratorToStringHandle:0") for style in styles_list]

    nn_clip_seed = graph.get_tensor_by_name(name_clip_seed)
    nn_frame_seed = graph.get_tensor_by_name(name_frame_seed)
    nn_clip_handle = graph.get_tensor_by_name(name_clip_handle)
    nn_frame_handle = graph.get_tensor_by_name(name_frame_handle)
    nn_train_flag_0 = graph.get_tensor_by_name(name_train_flag_0)
    nn_train_flag_1 = graph.get_tensor_by_name(name_train_flag_1)
    nn_train_flag_2 = graph.get_tensor_by_name(name_train_flag_2)
    nn_film_flag = graph.get_tensor_by_name(name_film_flag)
    nn_film_params = graph.get_tensor_by_name(name_film_params)

    # test_clips = graph.get_tensor_by_name("Clips/IteratorGetNext:0")
    test_frames = graph.get_tensor_by_name("Frames/IteratorGetNext:0")

    # Initializing datasets
    clip_handles = [sess.run(handle_ph) for handle_ph in clip_handle_phs]
    frame_handles = [sess.run(handle_ph) for handle_ph in frame_handle_phs]

    for i, style in enumerate(styles_list):
        # reinitialize to start of dataset
        sess.run(clip_init_iterators[i], feed_dict={nn_batch_size: 1000, nn_mode: "Test", nn_clip_seed: 12345})
        sess.run(frame_init_iterators[i], feed_dict={nn_batch_size: 1000, nn_mode: "Test", nn_frame_seed: 12345})

        # Creating output tensor
        output_tensor = graph.get_tensor_by_name(name_output_tensor)
        bll_output_tensor = graph.get_tensor_by_name(name_bll_output_tensor)

        tensor_out = sess.run([output_tensor, bll_output_tensor], feed_dict={nn_frame_handle: frame_handles[i], nn_clip_handle: clip_handles[i], nn_train_flag_0: False,
                                                        nn_train_flag_1: True, nn_train_flag_2: True, nn_film_flag: True, nn_film_params: np.ones((1,512*4)),
                                                        nn_ep_input_frame: np.zeros([1000, 348]), nn_gt_input_frame: np.zeros([1000, 8])})

        # tally the square errors
        if i == 0:
            sq_err = tensor_out[0]
            bll_err = tensor_out[1]
        else:
            sq_err = np.vstack((sq_err,tensor_out[0]))
            bll_err = np.vstack((bll_err,tensor_out[1]))

        print("{}/{}".format(i, len(styles_list)), end="\r")
        print(style)
        print(np.mean(sq_err))  # so far
        print(np.mean(bll_err))  # so far
        print("==========")
    print("Test error:")
    print(sq_err.shape)
    print(np.mean(sq_err))
    print("BLL error:")
    print(bll_err.shape)
    print(np.mean(bll_err))


import heapq
from typing import List

class DinnerPlates:

    def __init__(self, capacity: int):
        self.capacity = capacity
        self.stacks: List[List] = []
        self.non_full_heap: List[int] = []

    def push(self, val: int) -> None:
        # 如果没有不满的index，则在最后添加新stack，并把index添加到不满的堆里
        if not len(self.non_full_heap):
            self.stacks.append([val])
            heapq.heappush(self.non_full_heap, len(self.stacks) - 1)
            return

        # 添加到第一个不满stack里
        smallest = self.non_full_heap[0]
        self.stacks[smallest].append(val)

        # 添加完满了，则把index从堆里去掉
        if len(self.stacks[smallest]) == self.capacity:
            heapq.heappop(self.non_full_heap)

    def pop(self) -> int:
        # 找到最后一个非空stack
        while self.stacks and not self.stacks[-1]:
            self.stacks.pop()
        return self.popAtStack(len(self.stacks) - 1)

    def popAtStack(self, index: int) -> int:
        # index有效 且 对应的stack非空
        if 0 <= index < len(self.stacks) and self.stacks[index]:
            # 如果stack是从满的到少一个，则要加到不满的堆里
            if len(self.stacks[index])==self.capacity:
                heapq.heappush(self.non_full_heap, index)
            return self.stacks[index].pop()
        return -1

# Your DinnerPlates object will be instantiated and called as such:
# obj = DinnerPlates(capacity)
# obj.push(val)
# param_2 = obj.pop()
# param_3 = obj.popAtStack(index)

if __name__ == '__main__':
    D = DinnerPlates(2)
    D.push(1)
    D.push(2)
    D.push(3)
    D.push(4)
    D.push(5)
    assert D.popAtStack(0) == 2
    D.push(20)
    D.push(21)
    assert D.popAtStack(0) == 20
    assert D.popAtStack(2) == 21
    assert D.pop() == 5
    assert D.pop() == 4
    assert D.pop() == 3
    assert D.pop() == 1
    assert D.pop() == -1

LeetCode-Algorithm/1172. Dinner Plate Stacks/1172.py


#! /usr/bin/env python3

# -------------
# status_bar.py
# -------------
# Author:      Daniel Sim (foxhead128)
# License:     See LICENSE.md for more details.
# Description: This is a browser status bar class.

from common import blank_toolbar, pyqt4
import custom_widgets
if not pyqt4:
    from PyQt5.QtCore import Qt, QSize
    from PyQt5.QtWidgets import QToolBar, QStatusBar, QFrame, QMainWindow, QLineEdit, QProgressBar, QSizeGrip
else:
    try:
        from PyQt4.QtCore import Qt, QSize
        from PyQt4.QtGui import QToolBar, QStatusBar, QFrame, QMainWindow, QLineEdit, QProgressBar, QSizeGrip
    except:
        from PySide.QtCore import Qt, QSize
        from PySide.QtGui import QToolBar, QStatusBar, QFrame, QMainWindow, QLineEdit, QProgressBar, QSizeGrip

class StatusBar(QToolBar):
    def __init__(self, parent=None):
        super(StatusBar, self).__init__(parent)
        if self.layoutDirection() == Qt.LeftToRight:
        	self.setLayoutDirection(Qt.RightToLeft)
        else:
        	self.setLayoutDirection(Qt.LeftToRight)
        self.setMovable(False)
        self.fullStatusBar = custom_widgets.Column(self)
        self.fullStatusBar.layout().setSpacing(0)
        self.addWidget(self.fullStatusBar)
        self.downloadsBar = QMainWindow(self)
        self.downloadsBar.setLayoutDirection(self.parent().layoutDirection())
        self.fullStatusBar.addWidget(self.downloadsBar)
        self.statusBar = QStatusBar(self)
        self.statusBar.setSizeGripEnabled(False)
        self.fullStatusBar.addWidget(self.statusBar)
        self.setStyleSheet(blank_toolbar + " QMainWindow { background: transparent; border: 0; }")
        self.progressBar = QProgressBar(self.statusBar)
        self.progressBar.setLayoutDirection(self.parent().layoutDirection())
        self.progressBar.hide()
        self.progressBar.setStyleSheet("min-height: 1em; max-height: 1em; min-width: 200px; max-width: 200px;")
        self.statusBar.addPermanentWidget(self.progressBar)
        self.widgetToolBar = QToolBar(self.statusBar)
        #self.widgetToolBar.setMaximumHeight(16)
        #self.widgetToolBar.setIconSize(QSize(16, 16))
        self.widgetToolBar.setMovable(False)
        self.widgetToolBar.setLayoutDirection(self.parent().layoutDirection())
        self.widgetToolBar.setContextMenuPolicy(Qt.CustomContextMenu)
        self.widgetToolBar.setStyleSheet("QToolBar { border: 0; background: transparent; } QToolButton { padding: 0; }")
        self.statusBar.addPermanentWidget(self.widgetToolBar)
    def addToolBar(self, toolbar):
        self.downloadsBar.addToolBar(toolbar)
    def setValue(self, value=0):
        if value in (0, 100):
            self.progressBar.hide()
        else:
            self.progressBar.show()
        self.progressBar.setValue(value)
    def statusBarMessage(self):
        return self.statusBar.currentMessage()
    def setStatusBarMessage(self, text=""):
        self.statusBar.showMessage(text)
    def addToolBar(self, toolbar):
        self.downloadsBar.addToolBar(toolbar)


import re
import packet_decoder

COLOURS = '(?:(\xa7.{1})+)'

class Plugin_Chat:
	def __init__(self, session):
		self.interestedPackets = [0x03]
		self.interestedMessages = []
		self.detect_bukkit_wrap = True
		self.wrap_moar = False
		self.subscribers = []
		self.packet_buffer = []

		triplet = "\((?P<%s>[0-9\.\-]+),\s?(?P<%s>[0-9\.\-]+),\s?(?P<%s>[0-9\.\-]+)\)"
		username = "(?:\xa7[0-9A-Za-z]{1})*(?P<%s>[0-9A-Za-z_]{1,16})(?:\xa7[0-9A-Za-z]{1})*"

		self.handlers = [
			#Basics
			('chat',                {'regex': '^\<'+username % 'player' +'\> (?P<message>.*)$'}),
			('action',              {'regex': '^\* '+username % 'player' +' (?P<action>.*)$'}),
			('player_join',         {'regex': '^\xa7e'+username % 'player' +' joined the game\.$'}),
			('player_quit', 	{'regex': '^\xa7e'+username % 'player' +' left the game\.$'}),
			('server_message',      {'regex': '^\xa7d\[Server\] (?P<message>.*)'}),
			('afk',                 {'regex': '^\xa77'+username % 'player' +' is now AFK$',
			                         'extra': {'enabled': True}}),
			('afk',                 {'regex': '^\xa77'+ username % 'player' +' is no longer AFK$',
			                         'extra': {'enabled': False}}),

			#Mail
			('mail_count',          {'regex': '^\xa7cYou have (?P<count>\d+) messages!\xa7f Type \xa77/mail read\xa7f to view your mail\.$',
			                         'num'  : ['count']}),
			('mail_count',          {'regex': '^\xa77You have no new mail\.$',
				                 'extra': {'count': 0}}),
			#PVP
			('player_kill',         {'regex': '^\xa74' + username % 'killer' +' (?:killed|executed|took down) '+ username % 'victim' +' using a\(n\) (?P<weapon>.*)\.$'}),
			('player_kill',         {'regex': '^\xa74' + username % 'killer' +' showed '+ username % 'victim' +' the (?:wrong|business) end of a\(n\) (?P<weapon>.*)\.$'}),
			('player_kill_streak',  {'regex': '^\xa72\['+ username % 'player' +'\] (?P<kill_streak>.*)!$'}),

			#Mod tools
			('mod_broadcast',       {'regex': '^\xa7f\[\xa7cMod broadcast\xa7f - \xa7c'+ username % 'player' +'\] \xa7a(?P<message>.*)$'}),
			('modmode',             {'regex': '^\xa7cYou are now in mod mode\.$',
				                 'extra': {'enabled': True}}),
			('vanish',              {'regex': '^\xa7cPoof!$',
				                 'extra': {'enabled': True}}),
			('vanish',              {'regex': '^\xa7cYou have reappeared!$',
			                         'extra': {'enabled': False}}),
			('pickup',              {'regex': '^\xa7cEnabling Picking Up of Items$',
			                         'extra': {'enabled': True}}),
			('pickup',              {'regex': '^\xa7cDisabling Picking Up of Items$',
			                         'extra': {'enabled': False}}),
			('godmode',             {'regex': '^\xa7eGod mode enabled! Use /ungod to disable.$',
			                         'extra': {'enabled': True}}),
			('teleport',            {'regex': '^\xa77Teleporting\.\.\.$'}),
			('kit',                 {'regex': '^\xa77Giving kit (?P<kit>.*)\.$'}),

			#WorldGuard
			('banned_item',         {'regex': '^\xa77WG: \xa7d'+ username % 'player' + '\xa76 \((?P<action>\w+)\) \xa7f(?P<block>.+) \(#(?P<block_id>\d+)\)\.$'}),

			#MCCondom
			('grief_warning',       {'regex': '^\xa7c'+ username % 'player' + ' \| Time on:(?P<time_on>\d+)mins \| Logins:(?P<logins>[0-9\-]+) \| Warns:(?P<warns>\d+)$',
			                         'num'  : ['time_on', 'logins', 'warns']}),
			('reach_warning',       {'regex': '^\xa7d'+ username % 'player' + ' broke a block at a distance of (?P<distance>[0-9\.]+)$',
			                         'num'  : ['distance']}),

			#MCBouncer
			('notes',               {'regex': '^\xa7a'+ username % 'player' + ' has (?P<count>\d+) notes?\.$',
			                         'num'  : ['count']}),

			#ModTRS
			('modtrs',              {'regex': '^\xa7aThere are (?P<count>\d+) open mod requests\. Type /check to see them\.$',
					         'extra': {'type': 'count'},
					         'num'  : ['count']}),
			('modtrs',              {'regex': '^\xa7aNew mod request filed; use /check for more\.$',
				                 'extra': {'type': 'new'}}),
			('modtrs',              {'regex': '^\xa76Request #(?P<req_id>[0-9,]+) has been completed\.$',
				                 'extra': {'type': 'done'},
				                 'num'  : ['req_id']}),
			#Nocheat
			('nocheat',             {'regex': '^\[(?:[A-Z]+)\] NC: Moving violation: '+ username % 'player' + ' from (?P<world>\w+) distance ' + triplet % ('x', 'y', 'z') + '$',
			                         'extra': {'type': 'moving_violation'},
			                         'num'  : ['x','y','z']}),
			('nocheat',             {'regex': '^\[(?:[A-Z]+)\] NC: Moving violation: '+ username % 'player' + ' from (?P<world>\w+) ' + triplet % ('x_from', 'y_from', 'z_from') + ' to ' + triplet % ('x_to', 'y_to', 'z_to') + ' distance ' + triplet % ('x_distance', 'y_distance', 'z_distance') + '$',
			                         'extra': {'type': 'moving_violation'},
			                         'num'  : ['x_from','y_from','z_from', 'x_to', 'y_to', 'z_to', 'x_distance', 'y_distance', 'z_distance']}),
			('nocheat',             {'regex': '^\[(?:[A-Z]+)\] NC: Moving summary of last ~(?P<time>\d+) seconds: '+ username % 'player' + ' total Violations: ' + triplet % ('x','y','z') + '$',
			                         'extra': {'type': 'moving_summary'},
			                         'num':   ['time','x','y','z']}),
			('nocheat',             {'regex': '^\[(?:[A-Z]+)\] NC: '+ username % 'player' + ' sent (?P<total_events>\d+) move events, but only (?P<allowed_events>\d+) were allowed\. Speedhack\?$',
			                         'extra': {'type': 'speedhack'},
			                         'num':   ['total_events', 'allowed_events']}),
			('nocheat',             {'regex': '^\[(?:[A-Z]+)\] NC: Nuke: '+ username % 'player' + ' tried to nuke the world$',
			                         'extra': {'type': 'nuke'}}),
			#Useless shit
			('null',                {'regex': '^\xa75\xa76\xa74\xa75$'}),
			('null',                {'regex': '^\xa7cWelcome, [0-9A-Za-z_]{1,16}\xa7c! $'}),
			('null',                {'regex': '^\xa7fType \xa7c/help\xa7f for a list of commands\. $'}),
			('null',                {'regex': '^Visit nerd\.nu for information on other servers\. $'}),
			('null',                {'regex': '^-$'}),
			('null',                {'regex': '^\xa7b[0-9A-Za-z_]{1,16}, craft a sword or something\.$'}),
			('null',                {'regex': '^\xa7b[0-9A-Za-z_]{1,16} is getting killed out there\.$'}),
			('null',                {'regex': '^\xa77You are now marked as away\.$'}),
			('null',                {'regex': '^\xa77You are no longer marked as away\.$'}),

			#Slime death
			('player_death',        {'regex': '^\xa74A rare slime found '+ username % 'player' + '\.  They didn\'t win\.$',
			                         'extra': {'cause': 'slime'}})
		]
		deaths = {
			'cactus':        ['got a little too close to a cactus', 'tried to hug a cactus'],
			'creeper':       ['hugged a creeper', 'was creeper bombed'],
			'fall':          ['has fallen to their death', 'leaped before looking'],
			'fire':          ['burned to death', 'just got burned', 'has been set on fire'],
			'lava':          ['became obsidian', 'tried to swim in a pool of lava'],
			'slime':         ['was slimed'],
			'spider':        ['was overtaken by the spiders'],
			'water':         ['needs swimming lessons', 'forgot to come up for air', 'has drowned'],
			'zombie pigman': ['lost the fight against a zombie pig'],
			'zombie':        ['was punched to death by zombies', 'was left 4 dead'],
			'unknown':       ['died from unknown causes'],
			'suffocation':   ['was buried alive', 'suffocated']
		}
		for cause, strings in deaths.items():
			for s in strings:
				self.handlers.append(('player_death', {'regex': '^\xa74'+ username % 'player' + ' %s\.$' % s, 'extra': {'cause': cause}}))

		self.handlers.append(('unknown', {'regex': '^(?P<text>.*)$'}))
		for h in self.handlers:
			h[1]['regex'] = re.compile(h[1]['regex'])
		self.session = session

	def detect_wrap(self, *args):
		chat_length = 119
		chat_width = 320
		characters = u' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_\'abcdefghijklmnopqrstuvwxyz{|}~\xe2\x8c\x82\xc3\x87\xc3\xbc\xc3\xa9\xc3\xa2\xc3\xa4\xc3\xa0\xc3\xa5\xc3\xa7\xc3\xaa\xc3\xab\xc3\xa8\xc3\xaf\xc3\xae\xc3\xac\xc3\x84\xc3\x85\xc3\x89\xc3\xa6\xc3\x86\xc3\xb4\xc3\xb6\xc3\xb2\xc3\xbb\xc3\xb9\xc3\xbf\xc3\x96\xc3\x9c\xc3\xb8\xc2\xa3\xc3\x98\xc3\x97\xc6\x92\xc3\xa1\xc3\xad\xc3\xb3\xc3\xba\xc3\xb1\xc3\x91\xc2\xaa\xc2\xba\xc2\xbf\xc2\xae\xc2\xac\xc2\xbd\xc2\xbc\xc2\xa1\xc2\xab\xc2\xbb#'
		character_widths = [
			1, 9, 9, 8, 8, 8, 8, 7, 9, 8, 9, 9, 8, 9, 9, 9,
			8, 8, 8, 8, 9, 9, 8, 9, 8, 8, 8, 8, 8, 9, 9, 9,
			4, 2, 5, 6, 6, 6, 6, 3, 5, 5, 5, 6, 2, 6, 2, 6,
			6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 2, 2, 5, 6, 5, 6,
			7, 6, 6, 6, 6, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6, 6,
			6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 4, 6, 4, 6, 6,
			3, 6, 6, 6, 6, 6, 5, 6, 6, 2, 6, 5, 3, 6, 6, 6,
			6, 6, 6, 6, 4, 6, 6, 6, 6, 6, 6, 5, 2, 5, 7, 6,
			6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 4, 6, 3, 6, 6,
			6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 4, 6,
			6, 3, 6, 6, 6, 6, 6, 6, 6, 7, 6, 6, 6, 2, 6, 6,
			8, 9, 9, 6, 6, 6, 8, 8, 6, 8, 8, 8, 8, 8, 6, 6,
			9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
			9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 9, 9, 9, 5, 9, 9,
			8, 7, 7, 8, 7, 8, 8, 8, 7, 8, 8, 7, 9, 9, 6, 7,
			7, 7, 7, 7, 9, 6, 7, 8, 7, 6, 6, 9, 7, 6, 7, 1]

		#PART ONE: examine the first part to see if it wraps
		more = False
		text = args[-1]
		text +="@"
		if len(text) > chat_length:
			more = True
		else:
			width = 0
			i = 0
			while i < len(text):
				if text[i] == u'\xa7':
					i+=2
					continue
				index = characters.find(text[i])
				width += character_widths[index+32]
				if width >= chat_width:
					more = True
					break
				i+=1

		#PART 2: examine the second part (if present) to see if it fits
		if len(args) == 1:
			return more
		else:
			#print "LINE 1: " + args[0]
			#print "LINE 2: " + args[1]

			pos = args[0].rfind(u'\xa7')
			if pos != -1: colour = args[0][pos+1]
			else:         colour = 'f'

			#print "colour: "+colour
			if colour.lower() == 'f':
				return args[1][0] != u'\xa7', more
			else:
				return args[1][1] ==  colour, more

	def merge(self, lines):
		out = ''
		colour = 'f'
		first_line = True
		#print "MERGING:"
		#print lines
		for l in lines:
			if not first_line and colour != 'f':
				assert l[:2] == u'\xa7%s' % colour
				out += l[2:]
			else:	out += l
			first_line = False
			pos = l.rfind(u'\xa7')
			if pos != -1:
				colour = l[pos+1]
		return out
	def to_num(self, text):
		text = text.replace(',', '')
		if '.' in text: return float(text)
		else:           return int(text)
	def read_packet(self, packet):
		if packet.direction != packet_decoder.TO_CLIENT: return
		if self.detect_bukkit_wrap:
			if self.packet_buffer:   ok, more = self.detect_wrap(self.packet_buffer[-1].data['text'], packet.data['text'])
			else:                    ok, more = True, self.detect_wrap(packet.data['text'])

			#print "BUFF LEN: ", len(self.packet_buffer)
			#print "OK", ok
			#print "MORE", more
			if not ok:
				self.process()

			self.packet_buffer.append(packet)

			if not more:
				self.process()
		else:
			self.packet_buffer.append(packet)
			self.process()

		packet.transmit = False

	def process(self):
		text = self.merge([i.data['text'] for i in self.packet_buffer])
		for handler in self.handlers:
			m = re.match(handler[1]['regex'], text)
			if m:
				ident = handler[0]
				data = m.groupdict()
				if 'extra' in handler[1]:
					data = dict(data, **handler[1]['extra'])
				if 'num' in handler[1]:
					for f in handler[1]['num']:
						data[f] = self.to_num(data[f])

				for s in self.subscribers:
					if s(ident, data) == False:
						#print "Not transmitting!"
						self.packet_buffer = []
						return
				break
		if self.wrap_moar:
			self.session.gen(0x03, packet_decoder.TO_CLIENT, {'text': text})
		else:
			for p in self.packet_buffer:
				p.transmit = True
				self.session.packet_queue.put(p)
			self.session.flush()

		self.packet_buffer = []

	def subscribe(self, callback):
		self.subscribers.append(callback)

	def unsubscribe(self, callback):
		self.subscribers.remove(callback)


import pdb

with open('input.txt', 'r') as tf:
    pol_pw = [(l.strip().split(':')[0], l.strip().split(':')[1]) for l in tf.readlines()]

valid = 0
for policy, pw_w in pol_pw:
    occurences, ch = policy.split(' ')

    # use pw_w w/ whitespace to shortcut the non-zero index situation
    pos1, pos2 = map(int, occurences.split('-'))

    if pw_w[pos1] != pw_w[pos2] and (pw_w[pos1] == ch or pw_w[pos2] == ch):
        valid += 1

print('---')
print(f'Total valid: {valid}/{len(pol_pw)}')


"""A class for ingesting data from `.csv` files.
This is a concrete implementation of the ingestor_interface class.
"""
from typing import List
import pandas
from .ingestor_interface import IngestorInterface
from .QuoteModel import QuoteModel

class CSVIngestor(IngestorInterface):
    """A class parsing quotes from .csv formats.
    This class extracts quotes and authors and
    constructs the Quote object.
    """

    allowed_extension = ['csv']

    @classmethod
    def parse(cls, path: str) -> List[QuoteModel]:
        """Checks that file extension is correct and extracts data.

        Each parsed Quote object is added into a list and
        returned.
        """
        if not cls.can_ingest(path):
            raise Exception("Oh no!.. Sorry, that seems a little melodramatic... I mean: that didn't work, I'm afraid.")

        quotes = []

        csv_read = pandas.read_csv(path, header = 0)

        for row in csv_read.iterrows():
            quote, author = row
            quotes.append(QuoteModel(quote, author))

        return quotes


# 6083.
"""
빨강(r), 초록(g), 파랑(b) 각 빛의 가짓수가 주어질 때,
주어진 rgb 빛들을 섞어 만들 수 있는 모든 경우의 조합(r g b)과
만들 수 있는 색의 가짓 수를 계산

# 입력
빨녹파(r, g, b) 각 빛의 가짓수가 공백을 두고 입력된다.
예를 들어, 3 3 3 은 빨녹파 빛에 대해서
각각 0~2까지 3가지 색이 있음을 의미한다.
0 <= r,g,b <= 127

# 출력
만들 수 있는 rgb 색의 정보를 오름차순
(계단을 올라가는 순, 12345... abcde..., 가나다라마...)으로
줄을 바꿔 모두 출력하고,
마지막에 그 개수를 출력한다.

"""

a, b, c = map(int, input().split())
for i in range(a):
    for j in range(b):
        for k in range(c):
            print(str(i) + " " + str(j) + " " + str(k))
            # print(i, j, k)
print(a*b*c)


import pickle
vocab = open("vocab","rb")
vocab = pickle.load(vocab)
d_vocab = {vocab["d_vocab"][i]:i for i in vocab["d_vocab"]}
num_layers = vocab["num_layers"]
import torch

def get_word(x):
	v,i=torch.max(x,0)
	return d_vocab[i.item()+1]

def get_tensor(x):
	return torch.LongTensor([vocab["d_vocab"][x]])

class Attention(torch.nn.Module):
	def __init__(self,embedding):
		super(Attention,self).__init__()
		self.embedding	= embedding
		self.emb1	= torch.nn.Embedding(len(vocab["e_vocab"])+1 , self.embedding)
		self.lstm1	= torch.nn.LSTM(num_layers = num_layers,input_size=self.embedding,hidden_size=self.embedding,batch_first=True)
		self.lin1	= torch.nn.Linear(vocab["e_max_len"],vocab["e_max_len"])
		self.soft	= torch.nn.Softmax(dim=1)

		self.emb2	= torch.nn.Embedding(len(vocab["d_vocab"])+1,self.embedding,padding_idx=0)
		self.lin2	= torch.nn.Linear(vocab["e_max_len"]+self.embedding,self.embedding)
		self.lstm2	= torch.nn.LSTM(num_layers = num_layers,input_size=self.embedding,hidden_size=self.embedding,batch_first=True)
		self.lin3	= torch.nn.Linear(self.embedding,len(vocab["d_vocab"]))

	def forward(self,e,d):
		pe=torch.nn.utils.rnn.pack_padded_sequence(e,[len(e[0])],batch_first=True)
		e = self.emb1(pe[0])
		#print(e)
		pe=torch.nn.utils.rnn.PackedSequence(e,pe[1])
		epo,(last_hid,last_state) = self.lstm1(pe)

		upo = torch.nn.utils.rnn.pad_packed_sequence(epo,batch_first=True,total_length=vocab["e_max_len"])[0]
		#print(upo)
		#print(last_hid)
		word = ""
		#++
		#d = d[:,None]
		#++
		#de = self.emb2(d)
		while word!="</s>":
		#------------------------------------------------------------------------------------------#
			#modified hidden for multi_layer purpose+++++++++
			last_hid_last = last_hid[-1][None]
			#last_hid_last = last_hid

			c = (last_hid_last[-1,:,None]*upo).sum(dim=2)
			c = self.lin1(c)
			#print(c)
			c = self.soft(c)
			#print(c)
			c = (c[:,:,None]*upo).sum(dim=2)
			#print(c)
			#--
			d = d[:,None]
			#print(d)
			#print(l)
			#--
			de = self.emb2(d)
			#print(de)
			c = c[:,None]
			de = torch.cat([c,de],dim=2)
			#print(de)
			de = self.lin2(de)
			#print(de)
			dout,(last_hid,last_state) = self.lstm2(de,(last_hid,last_state))
			#print(dout)
			#print(last_hid)
			#break
			if len(dout)>0:
				dout = self.lin3(dout)
				dout = dout[:,-1,:]
				word = get_word(dout[0])
				print(word)
				d    = get_tensor(word)
				#++d     = last_hid
		return
		#no problem-----------------------------------------------------------------------------------#

model = Attention(vocab["embedding"])
model.load_state_dict(torch.load('attention.pt'),strict=False)

sentence = "life </s>"
indexing = torch.LongTensor([[vocab["e_vocab"][s] for s in sentence.split()]])
d = model(indexing,get_tensor("<s>"))


import sys
sys.stdin = open('1.txt')

def find(x):
    if x == parent[x]:
        return x
    else:
        return find(parent[x])

def union(a, b):
    parent[find(a)] = find(b)

t = int(input())
for tc in range(1,t+1):
    n, m = map(int, input().split())
    parent = [i for i in range(n+1)]

    mlst = list(map(int, input().split()))

    for i in range(m):
        union(mlst[i*2+1], mlst[i*2])

    result = []
    for i in range(1, n+1):
        result.append(find(i))

    print(len(set(result)))


t=int(input())
for j in range(t):
    n=int(input())
    mnt=[int(k) for k in input().split()][:n]
    mnt.sort(reverse=True)
    count=mnt[0]
    sub=mnt[0]-mnt[1]
    for i in range(2,len(mnt),2):
        bur2=mnt[i]-sub
        if (i+1)<len(mnt):
            if mnt[i+1]>=mnt[i]:
                count+=mnt[i+1]
                sub=mnt[i+1]-bur2
            else:
                count+=bur2
                sub=bur2-mnt[i+1]
        else:
            count+=bur2
    print(count)


import dill as pickle
from datetime import datetime
import os
from constants import FUGENELEMENTE_FREQUENCY_ORDER

print(f'pid: {os.getpid()}')

def load_year(year):
    t1 = datetime.now()
    ycs = pickle.load(open(f'dumps/unfuge_candidates_added/{year}ycs', 'rb'))
    t2 = datetime.now()
    print(f'time to load {year}: {t2 - t1}')
    return ycs

years = {}

for year in range(1995, 2023):
    print(f'counting year: {year}')
    years[year] = {}
    ycs = load_year(year)

    for yc in ycs:
        matches = yc.lemma_matches
        for match in matches:
            for key in match.keys():
                if key not in years[year].keys():
                    years[year][key] = 0
                years[year][key] += 1

# for year, matchdict in years.items():
#     print(f'results for year: {year}')
#     for key, count in matchdict.items():
#         print(f'{key}: {count}')
#     print('\n')

# add the top row
table = [['year']]
for op in FUGENELEMENTE_FREQUENCY_ORDER:
    table[0].append(op)

for year, matchdict in years.items():
    entry = [year]
    for op in FUGENELEMENTE_FREQUENCY_ORDER:
        if op not in matchdict.keys():
            entry.append(0)
        else:
            entry.append(matchdict[op])
    table.append(entry)

csv_string = ''
for entry in table:
    csv_string += ','.join(str(s) for s in entry) + '\n'

outfile = open('lemma_strat_counts.csv', 'w')
outfile.write(csv_string)


class Solution:
    def addBinary2(self, a, b):

        return bin(int(a,2)+int(b,2))[2:]

    def addBinary(self, a, b, i):

            i += 1

            print("round: ",i)
            print("a: ",a)
            print("b: ",b)

            if len(a)==0:
                return b
            if len(b)==0:
                return a
            if a[-1] == '1' and b[-1] == '1':
                return self.addBinary(self.addBinary(a[0:-1],b[0:-1], i),'1', i)+'0'
            if a[-1] == '0' and b[-1] == '0':
                return self.addBinary(a[0:-1],b[0:-1], i)+'0'
            else:
                return self.addBinary(a[0:-1],b[0:-1], i)+'1'

def main():
    pass

if __name__ == '__main__':
    main()

    test1 = Solution()
    num1 = "1010"
    num2 = "1011"
    i = 0
    #print(test1.addBinary2(num1, num2))
    print(test1.addBinary(num1, num2, i))


import json
import os

as_files = 'C:/Users/Bobby/AppData/Local/UnrealEngine/Common/DerivedDataCache'
out_path = 'F:/DRG Modding/DRGPacker/JSON/Blender/DerivedDataCache'

def main():
    for root, _, files in os.walk(as_files):
        for file in files:
            if file.startswith('ANIMSEQ_'):
                out_file = os.path.join(out_path, os.path.relpath(root, as_files), file)
                os.makedirs(os.path.dirname(out_file), exist_ok=True)
                with open(os.path.join(root, file), 'rb') as f:
                    with open(out_file, 'wb') as f2:
                        f2.write(f.read())
                print(f'{out_file}')

if __name__ == '__main__':
    main()

Asset Generator/copy animseq shader cache.py


import os
import re
from glob import glob
import yaml
from typing import Dict, Tuple

from WNTRWrapper import WNTRWrapper
from ModificationStrategy import Strategy

def parse_line_time(line: str):
    timestamp = line.strip().split(" ")[0]
    time_seconds = int(timestamp.split(":")[0]) * 60 * 60 + int(timestamp.split(":")[1]) * 60 + int(
        timestamp.split(":")[2])
    return time_seconds

def create_epanet_file(length: float, diameter: float = 300, pressure: float = 20, roughness: float = 100,
                       height: float = 10, template_prefix: str = 'flat_template.inp') -> str:
    """
    Populates the template at the prefix with the following values

    :param length: m
    :param diameter: mm
    :param pressure: m
    :param roughness: something
    :param height: m
    :param template_prefix: str
    :return: the modified template file as a str
    """
    template_filepath = os.path.join(os.getcwd(), 'test_files', template_prefix)
    if not os.path.isfile(template_filepath):
        raise ValueError('Make sure that flat_template.inp is in the test_files folder')

    # create epanet file
    with open(template_filepath, 'r') as f:
        template = f.read()

    # replace length tag with actual length
    epanet_file = re.sub(r"<length>", str(length), template)
    epanet_file = re.sub(r"<diameter>", str(diameter * 1000), epanet_file)
    epanet_file = re.sub(r"<pressure>", str(pressure), epanet_file)
    epanet_file = re.sub(r"<roughness>", str(roughness), epanet_file)
    epanet_file = re.sub(f"<height>", str(height), epanet_file)

    return epanet_file

def save_epanet_file_yaml(epanet_file: str, yaml_file: str, template_prefix: str) -> str:
    # create reports folder if not exists
    if not os.path.exists('reports'):
        os.makedirs('reports')

    # save file
    epanet_file_path = os.path.join(os.getcwd(), 'reports', f"{template_prefix[:-4]}_{yaml_file[:-4]}.inp")
    with open(epanet_file_path, 'w') as f:
        f.write(epanet_file)

    return epanet_file_path

def save_epanet_file(epanet_file: str, length: float, diameter: float, pressure: float,
                     roughness: float, height: float, template_prefix: str) -> str:
    # create reports folder if not exists
    if not os.path.exists('reports'):
        os.makedirs('reports')

    # save file
    epanet_file_path = os.path.join(os.getcwd(), 'reports',
                                    f"{template_prefix[:-4]}_{length}_{diameter}_{pressure}_{roughness}_{height}.inp")
    with open(epanet_file_path, 'w') as f:
        f.write(epanet_file)

    return epanet_file_path

def create_and_run_epanet_simulation(length: float, diameter: float = 300, pressure: float = 20,
                                     roughness: float = 100, height: float = 10, template_prefix: str = 'flat_template.inp',
                                     strategy=Strategy.SINGLE_TANK_CV, tank_height_multiplier: float = 1,
                                     cf: float = 1, search_string: str = "Pipe 7 changed from closed to open") -> float:
    """
    Creates an epanet file based on flat_template.inp
    :param length: pipe length
    :return: tau, time it takes for the pipe to fill
    """
    epanet_file = create_epanet_file(length, diameter, pressure, roughness, height, template_prefix)

    epanet_file_path = save_epanet_file(epanet_file, length, diameter, pressure, roughness, height, template_prefix)

    # run simulations
    wrapper = WNTRWrapper(epanet_file_path, is_iwn=True, strategy=strategy,
                          tank_height_multiplier=tank_height_multiplier,
                          cf=cf)
    simulation_output_path = os.path.join(os.getcwd(), 'reports', epanet_file_path[:-4])
    wrapper.run_sim(simulation_output_path)

    # parse report (only way to get good timestep)
    with open(simulation_output_path + ".rpt", 'r') as f:
        simulation_report = f.read()

    # cleanup
    for file in glob(os.path.join(os.getcwd(), 'reports', "*")):
        os.remove(file)

    # parse the report to find when the pipe opens (e.g. has filled)
    for line in simulation_report.splitlines():
        if search_string in line:
            return parse_line_time(line)
    # should never get this but need a fallback if the flat pipe never fills
    return -1

def populate_final_template(template_path: str, config_path: str) -> Tuple[str, any]:
    with open(config_path, 'r') as f:
        config = yaml.safe_load(f)

    with open(template_path, 'r') as f:
        template = f.read()

    # populate junctions
    for i in range(1, 12):
        template = re.sub(rf"<e{i}>", str(config["pipes"]["elevation"][i - 1]), template)

    # update reservoir elevations
    template = re.sub(r"<e0>", str(config["reservoirs"]["elevation"][0]), template)
    template = re.sub(r"<e12>", str(config["reservoirs"]["elevation"][1]), template)

    # populate pipes
    for i in range(12):
        template = re.sub(rf"<l{i}>", str(config["pipes"]["length"][i]), template)
        template = re.sub(rf"<d{i}>", str(config["pipes"]["diameter"][i]), template)

    return template, config

def create_and_run_final_simulation(template_prefix: str = "results_template.inp", config_prefix: str = "uphill.yaml") -> Dict[int, int]:
    # update filepaths
    template_filepath = os.path.join(os.getcwd(), 'test_files', template_prefix)
    config_filepath = os.path.join(os.getcwd(), 'test_files', config_prefix)

    epanet_file, config = populate_final_template(template_filepath, config_filepath)
    epanet_file_path = save_epanet_file_yaml(epanet_file, config_prefix, template_prefix)

    # run simulations
    wrapper = WNTRWrapper(epanet_file_path, is_iwn=True)
    simulation_output_path = os.path.join(os.getcwd(), 'reports', epanet_file_path[:-4])
    wrapper.run_sim(simulation_output_path)

    # parse report (only way to get good timestep)
    with open(simulation_output_path + ".rpt", 'r') as f:
        simulation_report = f.read()

    # cleanup
    for file in glob(os.path.join(os.getcwd(), 'reports', "*")):
        os.remove(file)

    # parse the report to find when each rule is completed (breaks if pipe never fills :()
    filling_front_times = {}
    # calculate the location of the filling front
    pipe_distances = [sum(config["pipes"]["length"][:i + 1]) for i in range(len(config["pipes"]["length"]))]
    for line in simulation_report.splitlines():
        for i in range(1, 11):
            if pipe_distances[i] not in filling_front_times.keys() and f"rule {i}" in line:
                filling_front_times[pipe_distances[i]] = parse_line_time(line)

    return filling_front_times

if __name__ == "__main__":
    times = create_and_run_final_simulation()
    print(times)


# cook your dish here
t=int(input())
for _ in range(t):
    a,b,c,d,e,f=map(int,input().split())
    l=[a,b]
    if (c in l) and (d in l):
        print("1")
    elif (e in l) and (f in l):
        print("2")
    else:
        print("0")


#!/usr/bin/env python3
import sys, math ,heapq, bisect
from collections import deque
sys.setrecursionlimit(10**6)
def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))
def yes(): print("Yes")
def no(): print("No")
MOD = 1000000007
INF = 10**18

from collections import defaultdict

class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return
        if self.parents[x] > self.parents[y]:
            x, y = y, x
        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

def solve_uf():
    n = I()
    X = LI()
    for i in range(n):
        X[i] -= 1
    C = LI()
    uf = UnionFind(n)
    ans = 0
    for i,x in enumerate(X):
        if uf.find(i) != uf.find(x):
            uf.union(i,x)
        else:
            min_cost = C[i]
            to = X[i]
            while to != i:
                min_cost = min(min_cost, C[to])
                to = X[to]
            ans += min_cost
    print(ans)

# 強連結成分分解(SCC): グラフGに対するSCCを行う
# 入力: <N>: 頂点サイズ, <G>: 順方向の有向グラフ, <RG>: 逆方向の有向グラフ
# 出力: (<ラベル数>, <各頂点のラベル番号>)
def scc(N, G, RG):
    order = []
    used = [0]*N
    group = [None]*N
    def dfs(s):
        used[s] = 1
        for t in G[s]:
            if not used[t]:
                dfs(t)
        order.append(s)
    def rdfs(s, col):
        group[s] = col
        used[s] = 1
        for t in RG[s]:
            if not used[t]:
                rdfs(t, col)
    for i in range(N):
        if not used[i]:
            dfs(i)
    used = [0]*N
    label = 0
    for s in reversed(order):
        if not used[s]:
            rdfs(s, label)
            label += 1
    return label, group

def solve_scc():
    n = I()
    X = LI()
    C = LI()
    graph = [[] for _ in range(n)]
    rgraph = [[] for _ in range(n)]
    for i in range(n):
        graph[i].append(X[i]-1)
        rgraph[X[i]-1].append(i)  # 有向グラフなら消す
    num, label = scc(n,graph, rgraph)
    group = [[] for _ in range(num)]
    for i in range(n):
        group[label[i]].append(i)
    ans = 0
    for nodes in group:
        if len(nodes) <= 1:
            continue
        minc = INF
        for node in nodes:
            minc = min(minc, C[node])
        ans += minc
    print(ans)

solve_scc()


#!/usr/bin/env python
from __future__ import print_function

import simulator.OfflineLogConverter as ConverterModule

def convert_log(class_name, result_file, output_path):

    Converter = getattr(ConverterModule, class_name)

    converter = Converter(result_file)

    with open(output_path, 'w') as output_file:
        for line in converter:
            print(line, file=output_file)

if __name__ == "__main__":
    import argparse
    import sys

    parser = argparse.ArgumentParser(description="Result Converter", add_help=True)
    parser.add_argument("name", type=str, help="The name of the converter clss")
    parser.add_argument("-in", "--result-file", type=str, required=True, help="The location of the result file.")
    parser.add_argument("-out", "--output-file", type=str, required=True, help="The location of the converted result file.")

    args = parser.parse_args(sys.argv[1:])

    convert_log(args.name, args.result_file, args.output_file)


import pandas as pd
import os

"""
    This is the module for converting files to the correct json format
    the functions here must take two path, input file and output file
    the output will always be json and must be in the format:
    Submission Date: YYYY-MM-DD HH:MM:SS
    Email: String
    Preference: String with the name of the film
    Position: Int rank of film
    Points: Float rank of film normalized between 1 and 0 (1 if in first position 0 if last
"""

def analyze_jot(input_path, output_path=None, preference=None):
    """
    decodes csv from the horrible jotform format
    :param input_path: string path of the file
    :param output_path: string path of new file in json format, if None left
    the name of the input is used
    :param preference: string name in the header of the column that contains the vote
    :return: graph object
    """
    if output_path is None:
        output_path = os.path.splitext(input_path)[0] + '.json'
    if preference is None:
        preference = 'Ordina i film in base alle tue preferenze'

    data = pd.read_csv(input_path)
    data = data.rename(columns={preference: 'Preference'})
    data['Preference'] = data['Preference'].map(lambda s: s.split('\r\n'))
    data = data.explode(column='Preference')
    data['Position'] = data['Preference'].map(lambda s: s.split(':')[0]).astype('int64')
    data['Preference'] = data['Preference'].map(lambda s: s.split(': ')[1])
    m = data['Position'].max()
    data['Points'] = data['Position'].map(lambda n: (m - n) / (m - 1))
    data = data.reset_index().drop(columns='index')
    data.to_json(output_path)
    return


from __future__ import division
import tensorflow as tf
from utils import *

class branch_network():
	def __init__(self, image, target, num_class, name):
		self.image = image
		self.target = target
		self.num_class = num_class
		self.name = name
		self.keep_prob=tf.placeholder_with_default([1.0,1.0],shape=[2])
		self.train_mode = tf.placeholder_with_default(False, shape=())
		print(self.keep_prob)
		print(self.train_mode)

	def conv_bn(self, feature, filters, kernel):
		conv = tf.layers.conv2d(feature, filters, kernel, padding='same')
		bn = tf.layers.batch_normalization(conv, training=self.train_mode)
		return tf.nn.relu(bn)

	def net_structure(self):
		with tf.variable_scope(self.name):
			conv1 = self.conv_bn(self.image, 32, 5)
			pool1 = tf.layers.max_pooling2d(conv1, pool_size=2, strides=2)
			dropout1 = tf.layers.dropout(pool1, rate=self.keep_prob[0])
			conv2 = self.conv_bn(dropout1, 64, 5)
			pool2 = tf.layers.max_pooling2d(conv2, pool_size=2, strides=2)
			dropout2 = tf.layers.dropout(pool2,rate=self.keep_prob[0])

			conv3 = self.conv_bn(dropout2, 64, 3)
			pool3 = tf.layers.average_pooling2d(conv3, pool_size=2, strides=2)

			pool3_dropout = tf.layers.dropout(pool3, rate=self.keep_prob[0])
			fc1 = tf.layers.flatten(pool3_dropout)
			# print(fc1)
			fc2 = tf.layers.dense(fc1, 128, activation=tf.nn.relu)
			fc2_dropout = tf.layers.dropout(fc2, rate=self.keep_prob[1])
			print(fc2_dropout)
		fc3 = tf.layers.dense(fc2_dropout, self.num_class)
		return fc3

	def train(self):
		logits = self.net_structure()

		cross_entropy = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(
			labels=self.target, logits=logits))
		update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
		with tf.control_dependencies(update_ops):
			optimizer = tf.train.AdamOptimizer().minimize(cross_entropy)
		correct = tf.equal(tf.argmax(tf.nn.softmax(logits),1), self.target)
		accuracy = tf.reduce_mean(tf.cast(correct, tf.float32))
		var_list = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES,scope=self.name)
		g_list = tf.global_variables()
		bn_moving_vars = [g for g in g_list if 'moving_mean' in g.name]
		bn_moving_vars += [g for g in g_list if 'moving_variance' in g.name]
		var_list += bn_moving_vars
		# saver = tf.train.Saver(var_list)
		with tf.Session() as sess:
			sess.run(tf.global_variables_initializer())
			dataset=data_process()
			for epoch in range(30):
				x_batch,y_batch=dataset.fine_tune_next_batch(128,[3,5,7,2,4,6])
				for step in range(len(x_batch)):
					loss,_,acc=sess.run([cross_entropy,optimizer,accuracy],
										feed_dict={self.image:x_batch[step],self.target:y_batch[step],
												   self.keep_prob:[0.25,0.5],self.train_mode:True})
					if step%10==9:
						# saver.save(sess,self.name+'_initial_variables/branch.module',global_step=epoch*len(x_batch)+step)
						print("number epoch %d,number step %d,cross entropy is %f"%(epoch,step,loss))
						print("number epoch %d,number step %d,accuracy is %f"%(epoch,step,acc))
				test_accuracy=0
				x_batch,y_batch=dataset.fine_tune_next_batch(128,[3,5,7,2,4,6],mode='test')
				for step in range(len(x_batch)):
					test_acc=sess.run(accuracy,feed_dict={self.image:x_batch[step],self.target:y_batch[step]})
					test_accuracy+=test_acc
				print("test accuray is %f"%(test_accuracy/len(x_batch)))

# image=tf.placeholder(tf.float32,[None,32,32,3])
# target=tf.placeholder(tf.int64,[None])
# # num_class=6
# name='branch'
# net=branch_network(image,target,6,name)
# net.train()
# net.net_structure()
# print(net)


import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BOARD)

#resetarea pinilor
GPIO.cleanup()

#setarea pinului ce imi va da viteza motorului
motor_speed_pin = 8
#setarea pinilor de directie
DIRA = 10
DIRB = 22

#setarea pinilor de output
GPIO.setup(motor_speed_pin, GPIO.OUT)
GPIO.setup(DIRA, GPIO.OUT)
GPIO.setup(DIRB, GPIO.OUT)

#stingerea ledului rosu
GPIO.setup(3,GPIO.OUT)
GPIO.output(3,1)

#aprinderea ledului verde
GPIO.setup(5,GPIO.OUT)
GPIO.output(5,0)

pwmPin = GPIO.PWM(motor_speed_pin, 80)

GPIO.output(DIRA, GPIO.LOW)
GPIO.output(DIRB, GPIO.LOW)

#oprirea motorului
pwmPin.stop()


import numpy as np
import tensorflow as tf
from PIL import Image

def anlysis(path):
    labels = open('labels.txt', "r").readlines()

    # Load the TFLite model
    interpreter = tf.lite.Interpreter(model_path=r"model1.tflite")
    interpreter.allocate_tensors()

    # Get input and output tensors
    input_details = interpreter.get_input_details()
    output_details = interpreter.get_output_details()

    # Load the image
    image = Image.open(r'%s'%path).convert("RGB")
    image = image.resize((input_details[0]['shape'][1], input_details[0]['shape'][2]))

    # Prepare input data
    input_data = np.expand_dims(image, axis=0)
    input_data = input_data.astype(np.float32)

    # Set the input tensor
    interpreter.set_tensor(input_details[0]['index'], input_data)

    # Run inference
    interpreter.invoke()

    # Get the output tensor
    output_data = interpreter.get_tensor(output_details[0]['index'])

    # Process the output
    prediction = np.argmax(output_data[0])
    return labels[prediction-1]


import math
import math

def is_prime(n):
    if n == 2:
        return True
    if n % 2 == 0 or n <= 1:
        return False

    sqr = int(math.sqrt(n)) + 1

    for divisor in range(3, sqr, 2):
        if n % divisor == 0:
            return False
    return True

with open('Python/input.txt') as file:
    data = file.readlines()
    nums = [int(num.strip()) for num in data]
    nums = nums[1:]

for num in nums:
    if is_prime(num):
        print('Prime')
    else:
        print('Not prime')


from elasticsearch import Elasticsearch
from time import sleep
from bs4 import BeautifulSoup
import re, requests
class DataCollector:
    def __init__(self, name, host="192.168.1.3:9200"):
        self.es = Elasticsearch(hosts=host)
        self.name = name
        self.urls = []
        self.lasturl = ""
    def check_index(self, opt=True):
        if not opt and self.es.indices.exists(self.name):
            print("# 해당 인덱스 초기화를 위한 삭제")
            self.es.indices.delete(self.name)
        if not self.es.indices.exists(self.name):
            print("# 해당 인덱스 미존재")
            settings = {
                "index": {
                "analysis": {
                    "tokenizer": {
                    "nori_tokenizer_mixed": {
                        "type": "nori_tokenizer",
                        "decompound_mode": "mixed"
                    }
                    },
                    "analyzer": {
                    "korean": {
                        "type": "custom",
                        "tokenizer": "nori_tokenizer_mixed",
                        "filter": [
                        "nori_readingform",
                        "lowercase",
                        "nori_part_of_speech_basic"
                        ]
                    }
                    },
                    "filter": {
                    "nori_part_of_speech_basic": {
                        "type": "nori_part_of_speech",
                        "stoptags": ["E", "IC", "J",
                                    "MAG", "MAJ", "MM",
                                    "SP", "SSC", "SSO", "SC", "SE",
                                    "XPN", "XSA", "XSN", "XSV",
                                    "UNA", "NA", "VSV"]
                    }
                    }
                }
                }
            }
            body = {
            "settings": settings,
            "mappings" : {"properties" :
                            {"title" : {"type" : "text", "analyzer" : "korean"},
                                "body" : {"type" : "text", "analyzer" : "korean"},
                                "date" : {"type": "date", "format": "yyyy-MM-dd"}
                            }}
            }
            self.es.indices.create(index=self.name, body=body)#인덱스 생성
            print("# 해당 인덱스 생성 완료")
    def scrape_urls(self, url, pages=10):#page는 디폴트로 10
        print("# URL 수집 시작")
        self.lastnum = self.es.count(index=self.name, body={"query" : {"match_all" : {}}})['count']
        if not self.lastnum == 0:
            self.lasturl = self.es.get(index=self.name, id=self.lastnum)['_source']['url']
            print(self.lasturl)
        for i in range(1, pages+1):
            print("Page", i)
            sleep(0.1)
            for soup in BeautifulSoup(requests.get(url, params={"p" : i}).text, "lxml").select(".tr a"):
                url = re.search(r'\S+/\d+/\d+', soup['href']).group()
                if url == self.lasturl:
                    print("# 이미 수집된 URL => 종료")
                    return
                self.urls.append(url)
        print("# URL 수집 완료")
    def scrape_bodies(self):
        if len(self.urls) == 0 :
            print("# 우선 URL 수집을 진행해주세요!")
            return
        bulk_body = []
        for i, el in enumerate(reversed(self.urls)):
            print(i, el)
            sleep(0.1)
            bulk_body.append({"create" : {"_index" : self.name, "_id" : self.lastnum + i + 1}})
            soup = BeautifulSoup(requests.get(el).text, "lxml")
            bulk_body.append({"url" : el,
                        "community" : re.search(r'(.+) \:', soup.select_one("title").text.strip()).group(1),
                        "title" : soup.select_one(".articleTitle").text.strip(),
                        "date" : re.search(r'\d{4}-\d{2}-\d{2}', soup.select_one(".articleDate").text.strip()).group(),
                        "body" : re.sub(r'\xa0', "", soup.select_one("#powerbbsContent").text.strip()),
                        "hits" : int(re.search(r'[0-9,]+', soup.select_one(".articleHit").text).group().replace(",", "")),
                        "commments" : int(re.search(r'[0-9,]+', soup.select_one(".articleBottomMenu").text).group().replace(",", "")),
                        "recommand" : int(re.search(r'[0-9,]+', soup.select_one(".reqnum").text).group().replace(",", ""))
                        })
            if (i + 1) % 100 == 0:
                self.es.bulk(index=self.name, body=bulk_body)
                self.es.indices.refresh(index=self.name)
                print("# 중간 저장")
                bulk_body.clear()
        if len(bulk_body) != 0:
            self.es.bulk(index=self.name, body=bulk_body)
            self.es.indices.refresh(index=self.name)
        print("# 최종 저장")

collector = DataCollector(name="community_data")
collector.check_index(opt=False)
collector.scrape_urls("http://www.inven.co.kr/board/lineagem/5019", pages=60)
collector.scrape_bodies()


from collections import deque
def solution(cacheSize, cities):
    answer = 0
    queue=deque([])
    new_city=[]
    for i in cities:
        new_city.append(i.lower())

    for i in range(len(new_city)):
        if cacheSize==0:
            return len(new_city)*5

        if cacheSize==len(queue):
            if new_city[i] in queue:
                answer+=1
                temp=new_city[i]
                queue.remove(temp)
                queue.append(temp)
            else:
                answer+=5
                queue.popleft()
                queue.append(new_city[i])
        else:
            if new_city[i] in queue:
                answer+=1
                temp=new_city[i]
                queue.remove(temp)
                queue.append(temp)
            else:
                answer+=5
                queue.append(new_city[i])
    return answer

#모범풀이 deque의 maxlen을 지정해버리면 초과시 자동으로 맨 앞에꺼 삭제함
def solution(cacheSize, cities):
    cache = deque(maxlen=cacheSize)
    time = 0
    for i in cities:
        s = i.lower()
        if s in cache:
            cache.remove(s)
            cache.append(s)
            time += 1
        else:
            cache.append(s)
            time += 5
    return time


from authapp.forms import UserRegisterForm, UserProfileForm
from authapp.models import User

class UserAdminRegisterForm(UserRegisterForm):
    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'avatar', 'username', 'email', 'avatar')

    def __init__(self, *args, **kwargs):
        super(UserAdminRegisterForm, self).__init__(*args, **kwargs)
        self.fields['avatar'].widget.attrs['class'] = 'custom-file-input'

class UserAdminProfileForm(UserProfileForm):
    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'avatar', 'username', 'email', 'avatar')

    def __init__(self, *args, **kwargs):
        super(UserProfileForm, self).__init__(*args, **kwargs)
        for field_name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control py-4'
        self.fields['username'].widget.attrs['readonly'] = False
        self.fields['email'].widget.attrs['readonly'] = False
        self.fields['avatar'].widget.attrs['class'] = 'custom-file-input'


## Exercício 55 do livro Python 3 - Conceitos e Aplicações - Uma Abordagem Didática

""" Escreva uma função que receba como parâmetro de entrada dois números reais Min e Max. Essa função deve ler do teclado
um número real e retorná-lo caso esteja dentro do intervalo fechado [Min, Max]. Caso contrário, a função deve exibir uma
mensagem de erro e ler um novo valor. """

def MinMax(Num1, Num2):
    if Num1 > Num2:
        Maximo = Num1
        Minimo = Num2
    else:
        Maximo = Num2
        Minimo = Num1

    print("\n")
    print("==*"*18)
    print("O menor valor digitado foi {} e o maior foi {}".format(Minimo, Maximo))
    print("==*"*18)

    continua = 's'

    while continua == 's':
        X = float(input("\nDigite um valor real p/ saber se está dentro do range min / max: "))

        if X >= Minimo and X <= Maximo:
            print("O número {} está dentro do range min / max!\nPrograma encerrado.".format(X))
            continua = 'n'
        else:
            print("O número {} não está dentro do range min / max!".format(X))

MinMax(Num1 = float(input("Digite um valor real: ")), Num2 = float(input("Digite outro valor real: ")))


import logging

import gevent

from volttron.platform.agent.known_identities import PLATFORM_ALERTER
from volttron.platform.agent import utils
from volttron.platform.messaging.health import Status, STATUS_BAD
from volttron.platform.vip.agent import Agent, Core, RPC

utils.setup_logging()
_log = logging.getLogger(__name__)

__version__ = '0.4'

class AlertAgent(Agent):
    def __init__(self, config_path, **kwargs):
        super(AlertAgent, self).__init__(**kwargs)
        self.config = utils.load_config(config_path)
        self.group_agent = {}

    @Core.receiver('onstart')
    def onstart(self, sender, **kwargs):
        for group_name, config in self.config.items():
            event = gevent.event.Event()
            group = AlertGroup(group_name, config,
                               address=self.core.address,
                               enable_store=False)
            gevent.spawn(group.core.run, event)
            event.wait()

            self.group_agent[group_name] = group

    @RPC.export
    def watch_topic(self, group, topic, timeout):
        """RPC method

        Listen for a topic to be published within a given
        number of seconds or send alerts.

        :pararm group: Group that should watch the topic.
        :type group: str
        :param topic: Topic expected to be published.
        :type topic: str
        :param timeout: Seconds before an alert is sent.
        :type timeout: int
        """
        group = self.group_agent[group]
        group.watch_topic(topic, timeout)

    @RPC.export
    def watch_device(self, group, topic, timeout, points):
        """RPC method

        Watch a device's ALL topic and expect points. This
        method calls the watch topic method so both methods
        don't need to be called.

        :pararm group: Group that should watch the device.
        :type group: str
        :param topic: Topic expected to be published.
        :type topic: str
        :param timeout: Seconds before an alert is sent.
        :type timeout: int
        :param points: Points to expect in the publish message.
        :type points: [str]
        """
        group = self.group_agent[group]
        group.watch_device(topic, timeout, points)

    @RPC.export
    def ignore_topic(self, group, topic):
        """RPC method

        Remove a topic from agent's watch list. Alerts will no
        longer be sent if a topic stops being published.

        :param group: Group that should ignore the topic.
        :type group: str
        :param topic: Topic to remove from the watch list.
        :type topic: str
        """
        group = self.group_agent[group]
        group.ignore_topic(topic)

class AlertGroup(Agent):
    def __init__(self, group_name, config, **kwargs):
        super(AlertGroup, self).__init__(**kwargs)
        self.group_name = group_name
        self.config = config
        self.wait_time = {}
        self.topic_ttl = {}
        self.point_ttl = {}

    @Core.receiver('onstart')
    def onstart(self, sender, **kwargs):
        _log.info("Listening for alert group {}".format(self.group_name))
        config = self.config
        for topic in config.iterkeys():

            # Optional config option with a list of points that
            # might not be published.
            if type(config[topic]) is dict:
                point_config = config[topic]
                self.watch_device(topic,
                                  point_config["seconds"],
                                  point_config["points"])

            # Default config option
            else:
                timeout = config[topic]
                self.watch_topic(topic, timeout)

    def watch_topic(self, topic, timeout):
        """Listen for a topic to be published within a given
        number of seconds or send alerts.

        :param topic: Topic expected to be published.
        :type topic: str
        :param timeout: Seconds before an alert is sent.
        :type timeout: int
        """
        self.wait_time[topic] = timeout
        self.topic_ttl[topic] = timeout
        self.vip.pubsub.subscribe(peer='pubsub',
                                  prefix=topic,
                                  callback=self.reset_time)
        _log.info("Expecting {} every {} seconds"
                   .format(topic, timeout))

    def watch_device(self, topic, timeout, points):
        """Watch a device's ALL topic and expect points. This
        method calls the watch topic method so both methods
        don't need to be called.

        :param topic: Topic expected to be published.
        :type topic: str
        :param timeout: Seconds before an alert is sent.
        :type timeout: int
        :param points: Points to expect in the publish message.
        :type points: [str]
        """
        self.point_ttl[topic] = {}

        for p in points:
            self.point_ttl[topic][p] = timeout

        self.watch_topic(topic, timeout)

    def ignore_topic(self, topic):
        """Remove a topic from the group watchlist

        :param topic: Topic to remove from the watch list.
        :type topic: str
        """
        _log.info("Removing topic {} from watchlist".format(topic))

        self.vip.pubsub.unsubscribe(peer='pubsub',
                                    prefix=topic,
                                    callback=self.reset_time)
        self.point_ttl.pop(topic, None)
        self.topic_ttl.pop(topic, None)
        self.wait_time.pop(topic, None)

    def reset_time(self, peer, sender, bus, topic, headers, message):
        """Callback for topic subscriptions

        Resets the timeout for topics and devices when publishes are received.
        """
        if topic not in self.wait_time:
            found = False
            # if topic isn't in wait time we need to figure out the
            # prefix topic so that we can determine the wait time
            for x in self.wait_time:
                # TODO: order the wait_time topics so furthest down the tree wins.
                if topic.startswith(x):
                    topic = x
                    found = True
                    break
            if not found:
                _log.debug("No configured topic prefix for topic {}".format(
                    topic)
                )
                return

        _log.debug("Resetting timeout for {}".format(topic))

        # Reset the standard topic timeout
        self.topic_ttl[topic] = self.wait_time[topic]

        # Reset timeouts on volatile points
        if topic in self.point_ttl:
            received_points = set(message[0].keys())
            expected_points = self.point_ttl[topic].keys()
            for point in expected_points:
                if point in received_points:
                    self.point_ttl[topic][point] = self.wait_time[topic]

    @Core.periodic(1)
    def decrement_ttl(self):
        """Periodic call

        Used to maintain the time since each topic's last publish.
        Sends an alert if any topics are missing.
        """
        unseen_topics = set()
        for topic in self.wait_time.iterkeys():

            # Send an alert if a topic hasn't been seen
            self.topic_ttl[topic] -= 1
            if self.topic_ttl[topic] <= 0:
                unseen_topics.add(topic)
                self.topic_ttl[topic] = self.wait_time[topic]

            # Send an alert if a point hasn't been seen
            try:
                points = self.point_ttl[topic].keys()
                for p in points:
                    self.point_ttl[topic][p] -= 1
                    if self.point_ttl[topic][p] <= 0:
                        unseen_topics.add((topic, p))
                        self.point_ttl[topic][p] = self.wait_time[topic]
            except KeyError:
                pass

        if unseen_topics:
            self.send_alert(list(unseen_topics))

    def send_alert(self, unseen_topics):
        """Send an alert for the group, summarizing missing topics.

        :param unseen_topics: List of topics that were expected but not received
        :type unseen_topics: list
        """
        alert_key = "AlertAgent Timeout for group {}".format(self.group_name)
        context = "Topic(s) not published within time limit: {}".format(
            sorted(unseen_topics))

        status = Status.build(STATUS_BAD, context=context)
        self.vip.health.send_alert(alert_key, status)

def main():
    utils.vip_main(AlertAgent, identity=PLATFORM_ALERTER, version=__version__)

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        pass


import math
import os
import pandas as pd
import random

class Vector(object):

    def __init__(self):
        self.data = {}
        self.contents = set([])
        self.total_words = 0
        self.matches = 0

    def initialize(self, filename1, filename2):
        file1 = open(filename1,'r')
        for line in file1:
            self.data[line[:-1]] = 0
            self.contents.add(line[:-1])
        file2 = open(filename2,'r')
        for line in file2:
            self.data[line[:-1]] = 0
            self.contents.add(line[:-1])

    def add_word(self, word):
        self.total_words += 1
        if word.upper() in self.contents:
            self.data[word.upper()] += 1
            self.matches += 1

    def get_adjusted(self):
        vec_copy = {}
        for key, value in self.data.items():
            if self.total_words != 0:
                vec_copy[key] = value / self.total_words
            else:
                vec_copy[key] = 0

        return vec_copy

    def get_angle(self, secondary_vec):
        adj_1 = self.get_adjusted()
        adj_2 = secondary_vec.get_adjusted()
        dot_product = 0
        magnitude_1 = 0
        magnitude_2 = 0
        for key in adj_1.keys():
            dot_product += adj_1[key] * adj_2[key]
            magnitude_1 += adj_1[key] ** 2
            magnitude_2 += adj_2[key] ** 2

        magnitude_1 = math.sqrt(magnitude_1)
        magnitude_2 = math.sqrt(magnitude_2)

        if magnitude_2 * magnitude_1 == 0:
            print('Error: one or both vectors are empty')
            return 1000
        else:

            return math.acos(dot_product /(magnitude_1 * magnitude_2))

def read_file(filename):
    with open(filename, 'r') as file:
        data = file.read().replace('\n', ' ')

    return data

def test(learn_proportion=0.6):
    price_data = pd.read_csv('spy_historical.csv')
    price_data['gain'] = (price_data['Close'] - price_data['Open']) / price_data['Open']
    price_data = price_data[['Date', 'gain']]
    price_data['date_copy'] = price_data['Date']
    price_data_dates = list(price_data['Date'])
    price_data.set_index('date_copy', inplace=True)
    learn_data = []
    test_data = []
    for i, date in enumerate(price_data_dates):
        if random.random() <= learn_proportion:
            learn_data.append(i)
        else:
            test_data.append(i)

    positive_vec = Vector()
    negative_vec = Vector()
    positive_vec.initialize('McDonaldWords/positive.txt','McDonaldWords/negative.txt')
    negative_vec.initialize('McDonaldWords/positive.txt','McDonaldWords/negative.txt')
    counter = 0
    num_learn = len(learn_data)
    for i in learn_data:
        if i <= 1:
            continue
        date = price_data.iloc[i - 1]['Date']
        counter += 1
        if counter % 100 == 0:
            print(round (100 * (counter/ num_learn)),'percent done learning')
        year, month, day = date.split('-')
        filename = 'newspaperdata/{}/{}_{}/nyt_business.txt'.format(year, month, day)
        days_text = read_file(filename)
        if price_data.iloc[i]['gain'] >= 0:
            positive = True
        else:
            positive = False
        for word in days_text.split():
            if positive:
                positive_vec.add_word(word)
            else:
                negative_vec.add_word(word)

    correct_days = 0
    total_days = 0
    total_matches = 0
    for i in test_data:
        if i <= 1:
            continue
        date = price_data.iloc[i - 1]['Date']
        total_days += 1
        year, month, day = date.split('-')

        filename = 'newspaperdata/{}/{}_{}/nyt_business.txt'.format(year, month, day)
        days_text = read_file(filename)
        day_vec = Vector()
        day_vec.initialize('McDonaldWords/positive.txt','McDonaldWords/negative.txt')
        for word in days_text.split():
            day_vec.add_word(word)
        neg_angle = day_vec.get_angle(negative_vec)
        pos_angle = day_vec.get_angle(positive_vec)
        if pos_angle < neg_angle:
            predicted_gain = True
        else:
            predicted_gain = False
        if price_data.iloc[i]['gain'] >= 0:
            actual_gain = True
        else:
            actual_gain = False
        if predicted_gain == actual_gain:
            correct_days += 1
        total_matches += day_vec.matches
    print('avg word hits per day: ',total_matches/total_days)
    print('correctly predicted direction on {} percent of days'.format(100 * (correct_days / total_days)))
    return correct_days / total_days


# starting number initialize 0 for nice range
# count for the sequence of inputs
total = 0
average = 0
count = 0

user_input = int(input("enter a number (-1 to exit)"))

# loop for the repeating number inputs
while user_input != -1 :
    total += user_input
    count += 1
# how to calculate mean average
    average = total / count
    user_input = int(input("enter a number (-1 to exit)"))

# outputs for when the loop is to be stopped
    if user_input == -1:
        print("total:", total)
        print("The average:, ", average)
        break


import logging

def get_logger(name):
    '''Sets logger format and level'''
    console_format = logging.Formatter(
        '%(asctime)s~%(levelname)s: %(message)s')
    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.DEBUG)
    console_handler.setFormatter(console_format)

    logger = logging.getLogger(name)
    logger.addHandler(console_handler)
    logger.setLevel(logging.DEBUG)
    return logger


from typing import Text

from appyratus.test import (
    BaseTests,
    mark,
)
from appyratus.utils import PathUtils

@mark.unit
class TestPathUtils(BaseTests):

    @property
    def klass(self):
        return PathUtils

    @mark.params(
        'path, file_name', [
            ('/too/l33t', 'l33t'),
            ('/too/l33t.3p0', 'l33t.3p0'),
            ('/path/to/.l33t', '.l33t'),
            ('/l33t.tar.gz', 'l33t.tar.gz'),
        ]
    )
    def test_get_file_name(self, path: Text, file_name: Text):
        assert file_name == self.klass.get_file_name(path)

    @mark.params(
        'path, name', [
            ('/path/to/l33t', 'l33t'),
            ('/path/to/l33t.3p0', 'l33t'),
            ('/path/to/.l33t', '.l33t'),
            ('/l33t.tar.gz', 'l33t.tar'),
        ]
    )
    def test_get_name(self, path: Text, name: Text):
        assert name == self.klass.get_name(path)

    @mark.params(
        'path, extension', [
            ('/l33t', ''),
            ('/l33t.3p0', '3p0'),
            ('/.3p0', ''),
            ('r00.de.m00', 'm00'),
        ]
    )
    def test_get_extension(self, path: Text, extension: Text):
        assert extension == self.klass.get_extension(path)

    @mark.params(
        'path, dir_name', [
            ('/path/to/l33t', 'to'),
            ('/path/to/l33t/', 'l33t'),
        ]
    )
    def test_get_dir_name(self, path: Text, dir_name: Text):
        assert dir_name == self.klass.get_dir_name(path)

    @mark.params(
        'path, dir_path', [
            ('/my/l33t/path', '/my/l33t'),
            ('/my/l33t/path/', '/my/l33t/path'),
        ]
    )
    def test_get_dir_path(self, path: Text, dir_path: Text):
        assert dir_path == self.klass.get_dir_path(path)

    @mark.params(
        'path, extension, new_path', [
            ('/my/l33t.txt', 'jpg', '/my/l33t.jpg'),
            ('/l33t.txt', 'rar', '/l33t.rar'),
            ('r33t.bmp', 'tar.gz', 'r33t.tar.gz'),
            ('b33p.tar.bzip2', 'zip', 'b33p.tar.zip'),
        ]
    )
    def test_replace_extension(self, path: Text, extension: Text, new_path: Text):
        assert new_path == self.klass.replace_extension(path, extension)

    @mark.skip('need fs')
    @mark.params('path, exists', [
        ('', ''),
    ])
    def test_exists(self, path: Text, exists: bool):
        pass

    @mark.params(
        'path, paths, join_path', [
            ('/r00t', 't00t', '/r00t/t00t'),
            ('b00t', 'sc00t', 'b00t/sc00t'),
            ('/b00p', '/m00t', '/m00t'),
            ('/p00t', './d00t', '/p00t/./d00t'),
        ]
    )
    def test_join(self, path: Text, paths, join_path: Text):
        assert join_path == self.klass.join(path, paths)

    @mark.params(
        'path, split_path, separator', [
            ('/r00t/d0g', ['r00t', 'd0g'], None),
            ('/r00t/d0g/j34h', ['r00t', 'd0g', 'j34h'], None),
            ('r00t/d0g', ['r00t', 'd0g'], None),
            (':r00t:d0g:', ['r00t', 'd0g', ''], ':'),
            (':r00t:d0g:', [':r00t:d0g:'], '-'),
        ]
    )
    def test_split(self, path: Text, split_path: Text, separator):
        assert split_path == self.klass.split(path, separator)

    @mark.skip('need fs')
    @mark.params('path, depth, file_ext', [
        ('', '', ''),
    ])
    def test_get_nodes(self, path: Text, depth: int, file_ext: Text):
        pass


from src.load_data import load_data
from src.models.cnn import model_1
from keras.callbacks import ModelCheckpoint
import os
import pickle

continue_training = True

# Drive
drive_data_path = '/content/drive/My Drive/abdou/emotion_detection/fer2013.csv'

# Local
local_data_path = '../data/fer2013/fer2013.csv'
local_data_path2 = 'data/fer2013/fer2013.csv'

data_path_r = None
if os.path.isfile(local_data_path2):
    data_path_r = local_data_path2
elif os.path.isfile(local_data_path):
    data_path_r = local_data_path
else:
    data_path_r = drive_data_path

img_size = (48, 48)

x_train, y_train, x_val, y_val, x_test, y_test = load_data(data_path_r)

model = model_1()
model.summary()
save_path = 'save_model.ckpt'
save_model_callback = ModelCheckpoint(filepath=save_path, verbose=1)
if continue_training and os.path.isfile(save_path):
    model.load_weights(save_path)

history = model.fit(x_train, y_train, validation_data=(x_test, y_test), epochs=50,
                    batch_size=100, callbacks=[save_model_callback])

pickle.dump(history, open("history.bin", "wb"))

save_path_2 = "save_model_2.ckpt"
model.save(save_path_2)