import Tkinter as tk
from Tkinter import LabelFrame
import ast
import logging

from braviz.interaction.tk_tooltip import ToolTip

class subjects_list(LabelFrame):

    """A subjects list  tkMegaWidget. It gets the available subjects from a braviz reader and calls a function when changed
    The get method can be used to query the currently selected subject
    The listVariable method returns a tuple conaining the available items in the list"""

    def __init__(self, reader, function, master, **kw):
        """the reader should be a braviz reader which is used to populate the list of available subjects
        the function is called whenever the selection changes
        master is the parent tk_widget
        Additional keyword parameters are directly passed to the tk_widget frame constructor"""
        if not kw.has_key('text'):
            kw['text'] = 'Subject'
        if not kw.has_key('padx'):
            kw['padx'] = 10
        if not kw.has_key('pady'):
            kw['pady'] = 5
        LabelFrame.__init__(self, master, **kw)
        list_and_bar = tk.Frame(self)
        list_and_bar.pack(side='top', fill='both', expand=1)
        scrollbar = tk.Scrollbar(list_and_bar, orient=tk.VERTICAL)
        self.tk_listvariable = tk_listvariable = tk.StringVar()
        subjects_list_box = tk.Listbox(
            list_and_bar, selectmode=tk.BROWSE, yscrollcommand=scrollbar.set, exportselection=0, listvariable=tk_listvariable)
        scrollbar.config(command=subjects_list_box.yview)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        subjects_list_box.pack(side="left", fill='both', expand=1)
        subjects = reader.get('ids')
        self.list = subjects
        self.subjects_list = subjects_list_box
        tk_listvariable.set(tuple(subjects))
        subjects_list_box.select_set(0, 0)
        subjects_list_box.bind('<<ListboxSelect>>', function)
        subjects_list_box.bind('<Double-Button-1>', function)
        master.bind('<Return>', function)
        subjects_list_box.bind('<Key>', function)
        self.itemconfigure = subjects_list_box.itemconfigure

    def get(self):
        """Gets the currently selected subject"""
        select_idx = self.subjects_list.curselection()
        # print select_idx
        subj = self.subjects_list.get(select_idx)
        return subj

    def config(self, **kw):
        """Intercepts state option and passes it to the listbox widget, other options are passed directly to the tkFrame"""
        if kw.has_key('state'):
            new_state = kw.pop('state')
            self.subjects_list.config(state=new_state)
        LabelFrame.config(self, **kw)

    def configure(self, **kw):
        """Alias to config"""
        self.config(**kw)

    def listVariable(self):
        """Returns a tuple containing the subjects in the list"""
        return ast.literal_eval(self.tk_listvariable.get())

    def setSelection(self, index):
        """YOYIS: Sets the current selection to the given index"""
        # print self.subjects_list.size()
        self.subjects_list.selection_clear(0, tk.END)
        self.subjects_list.selection_set(index, index)
        self.subjects_list.see(index)

    def getSelectionIndex(self, value):
        """YOYIS: Returns the index of the given value in the patients list"""
        return self.list.index(value)

class structureList(LabelFrame):

    """A tkMegaWidget for listing freesurfer segmentation models.
    By default the list allows multiple selections.
    It maintains an internal list of structures directly chosen by the user.
    When a change in the selection is made the command function is called,
    with 'add' or 'remove' as the first argument, and the changed model name as the second argument
    The changeSubj method can be used to change the subject to which the list of structures match
    Not all subjects have the same structures, the list of directly chosen structures is not changed
    when the subject changes, but the command function is called in order to do the corresponding changes
    (See mriMultSlicer application for an example)
    The listVariable method returns a tuple with the models currently in the list
    The get method can be used to retrieve a list of currently selected models"""

    def __init__(self, reader, initial_subj, command, parent, initial_models=None, **kw):
        """the reader should be a braviz reader which is used to populate the list of available structures
        initial_subj is the subject initially used to populate the list
        command is called whenever the selection changes, with 'add' or 'remove' as first argument and the changed model name as second argument
        parent is the parent tk_widget
        Additional keyword parameters are directly passed to the tk_widget frame constructor"""
        if not kw.has_key('text'):
            kw['text'] = 'Models'
        if not kw.has_key('padx'):
            kw['padx'] = 10
        if not kw.has_key('pady'):
            kw['pady'] = 5
        LabelFrame.__init__(self, parent, **kw)
        model_list_and_bar = tk.Frame(self)
        model_list_and_bar.pack(side='top', fill='both', expand=1)
        model_scrollbar = tk.Scrollbar(model_list_and_bar, orient=tk.VERTICAL)
        self.tk_listvariable = tk.StringVar()
        model_list = tk.Listbox(model_list_and_bar, selectmode=tk.MULTIPLE,
                                yscrollcommand=model_scrollbar.set, exportselection=0, listvariable=self.tk_listvariable)
        model_scrollbar.config(command=model_list.yview)
        model_scrollbar.pack(side=tk.RIGHT, fill=tk.Y, expand=1)
        model_list.pack(side="left", fill='both', expand=1)
        model_list.bind('<<ListboxSelect>>', self.__update)

        availableModels = reader.get('model', initial_subj, index='t')
        self.tk_listvariable.set(tuple(sorted(availableModels)))

        if initial_models is not None:
            self.chosen_models = set(initial_models)
        else:
            self.chosen_models = {
                'CC_Anterior', 'CC_Central', 'CC_Mid_Anterior', 'CC_Mid_Posterior', 'CC_Posterior'}
        for m in self.chosen_models:
            try:
                index = self.listVariable().index(m)
            except ValueError:
                pass
            else:
                model_list.selection_set(index)
                if command is not None:
                    command('add', m)

        self.previous_selection = set(model_list.curselection())
        self.command = command
        self.model_list = model_list
        self.reader = reader
        self.model_list = model_list

        # Replicate list Interface
        self.see = model_list.see
        self.itemconfigure = model_list.itemconfigure
        self.itemconfig = model_list.itemconfig
        self.tool_tip = ToolTip(
            model_list, msgFunc=self.__get_tooltip, follow=1, delay=0.5)
        from braviz.readAndFilter.link_with_rdf import cached_get_free_surfer_dict
        self.cool_names = cached_get_free_surfer_dict(reader)
        parent.focus()

    def __update(self, *args):
        """Internally handles changes in subject selection and calls 'command' if necessary"""
        model_idx = set(self.model_list.curselection())
        chosen_models = self.chosen_models
        # find if a model was added
        new_set = model_idx - self.previous_selection
        log = logging.getLogger(__name__)
        if new_set:
            if len(new_set) > 1:
                log = logging.getLogger(__name__)
                log.warning(
                    "WARNING: this shouldn't happen, model_idx changed by more than one")
            new_name = self.model_list.get(new_set.pop())
            chosen_models.add(new_name)
            if self.command is not None:
                self.command('add', new_name)
            # print "%s added"%(new_name)
        # find if a model was removed
        removed_set = self.previous_selection - model_idx
        if removed_set:
            if len(removed_set) > 1:
                log.warning(
                    "WARNING: this shouldn't happen, model_idx changed by more than one")
            remove_name = self.model_list.get(removed_set.pop())
            chosen_models.remove(remove_name)
            if self.command is not None:
                self.command('remove', remove_name)
            # print "%s removed"%(remove_name)
        self.previous_selection = set(self.model_list.curselection())

    def changeSubj(self, newSubj):
        """Change the subject to which the structures list makes reference"""
        new_models = set(self.reader.get('model', newSubj, index='t'))
        unavailable_models = self.chosen_models - new_models
        available_models = self.chosen_models.intersection(new_models)
        if self.command is not None:
            for m in unavailable_models:
                self.command('remove', m)
            for m in available_models:
                self.command('add', m)
        self.model_list.select_clear(0, tk.END)
        self.tk_listvariable.set(tuple(sorted(new_models)))
        for m in available_models:
            index = self.listVariable().index(m)
            self.model_list.selection_set(index)
        self.previous_selection = set(self.model_list.curselection())

    def config(self, **kw):
        """Intercepts state kw and passes it to the listbox widget, other argument are passed directly to the tkFrame"""
        if kw.has_key('state'):
            new_state = kw.pop('state')
            self.model_list.config(state=new_state)
        LabelFrame.config(self, **kw)

    def configure(self, **kw):
        """Alias to config"""
        self.config(**kw)

    def listVariable(self):
        """Gets a tuple representation of the items in the list"""
        return ast.literal_eval(self.tk_listvariable.get())

    def get(self):
        """Get a list of currently selected items"""
        select_idx = self.model_list.curselection()
        return [self.model_list.get(i) for i in select_idx]

    def __get_tooltip(self, event=None):
        """returns a string containing the name under the event, and the cool name if available"""
        # print dir(event)
        y_coord = event.y
        index = self.model_list.nearest(y_coord)
        name = self.model_list.get(index)
        cool_name = self.cool_names.get(name, '')
        return "%s : %s " % (name, cool_name)

def hierarchy_dict_to_tree(tree_view, hierarchy_dict, root='', tags=tuple(), tooltip_dict=None, tooltip_source=None, default_message=''):
    """
    Reads from a hierarchy dictionary and adds the hierarchy to a tk tree view

    the id of the different nodes will contain the prefix root,
    a list of tags can also be added to the nodes
    if a tooltip_dict is provided, it will be used to associate tootips to the nodes looking in tooltip_source
    This is, the resulting message for the tooltip will be tooltip_source[tooltip_dict[key]] where key is the element in
    the hierarchy_dict. If tooltip_source does not contain dict, the default message will be used instead
    """

    for name, childs in sorted(hierarchy_dict.items(), key=lambda x: x[0]):
        tags2 = tags[:]
        if len(childs) > 0:
            tags2.append('parent')
        else:
            tags2.append('leaf')
        iid = ':'.join((root, name))
        iid = iid.replace(' ', '_')
        tree_view.insert(root, 'end', iid, text=name, tags=tags2)
        if tooltip_dict is not None:
            tooltip_dict[iid] = tooltip_source.get(name, default_message)
        if len(childs) > 0:
            if tooltip_source is None:
                hierarchy_dict_to_tree(
                    tree_view, childs, iid, tags, tooltip_dict, tooltip_source, '')
            else:
                hierarchy_dict_to_tree(
                    tree_view, childs, iid, tags, tooltip_dict, tooltip_source, tooltip_source.get(name, ''))


import sublime, sublime_plugin

class SelectToBookmarkCommand(sublime_plugin.TextCommand):
    def run(self, edit, **args):
        """Get initial position"""
        initialPoint = self.view.sel()[0].begin()

        """Clear selected things (if any)"""
        self.view.sel().clear()

        """Move to next bookmark or previous bookmark"""
        forward = args.get('forward','true')
        if forward is True:
            self.view.run_command("next_bookmark")
        else:
            self.view.run_command("prev_bookmark")

        """Get current position (position of the bookmark)"""
        finalPoint = self.view.sel()[0].begin()

        """Clear selected things (if any)"""
        self.view.sel().clear()

        """Region to select"""
        regionToSelect = sublime.Region(initialPoint, finalPoint)

        """Add the region to the selection"""
        self.view.sel().add(regionToSelect)


from models import db
from models import Ad, Campaign, Impression, Interaction

db.create_all()

# Inserting campaigns
a = Campaign('Oi Rio Pro')
b = Campaign('Hurley Lower Trestles')
db.session.add(a)
db.session.add(b)
db.session.commit()

# Inserting ads
c = Ad('ORP jerseys', a)
d = Ad('ORP tourism', a)
e = Ad('ORP hotels', a)
f = Ad('HLT San Clemente Tourism Offices', b)
db.session.add(c)
db.session.add(d)
db.session.add(e)
db.session.add(f)
db.session.commit()

# Inserting impressions
# 1 month ago
imps = [Impression(c, 12345, 1504247734), Impression(c, 12346, 1504255934), Impression(c, 12346, 1504254934), Impression(d, 12345, 1504337734)]
# # last week
imps += [Impression(c, 12345, 1505909046), Impression(c, 12346, 1505909046), Impression(c, 12346, 1505909046), Impression(d, 12345, 1505909046)]
# current week (25th sept +)
imps += [Impression(c, 12345, 1506427386), Impression(c, 12346, 1506427446), Impression(c, 12346, 1504254934), Impression(d, 12345, 1506513846)]
for i in imps:
    db.session.add(i)
db.session.commit()

# Inserting interactions
interactions = [Interaction(imps[11], 'click', 1505912646), Interaction(imps[10], 'swipe', 1505912546)]
for i in imps:
    db.session.add(i)
db.session.commit()


from telegram import ReplyKeyboardMarkup
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, RegexHandler, ConversationHandler

import logging

# logeamos
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
logger = logging.getLogger(__name__)

CHOOSING, TYPING_REPLY, TYPING_CHOICE = range(3)

reply_keyboard = [['Event\'s name', 'Date'], ['Priority', 'Something else...'], ['Done']]
markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard = True)

def facts_to_str(user_data):
    '''
    :param user_data: data from the user
    :return: espace + data [list-shape] + espace + espace
    '''

    facts = list()

    for key, value in user_data.items():
        facts.append('%s - %s' % (key, value))

    return "\n".join(facts).join(['\n', '\n'])

def start(bot, update):
    '''
    Shows a message and shows the markup keyboard
    :param bot: bot
    :param update: update
    :return: CHOOSING
    '''
    update.message.reply_text(
        "Hi! My name is ReminderHackUPC bot. I will remember importats facts for you :). ",
        reply_markup = markup)

    return CHOOSING

def regular_choice(bot, update, user_data):
    text = update.message.text
    user_data['choice'] = text
    update.message.reply_text('%s' % text.lower())

    return TYPING_REPLY

def custom_choice(bot, update):
    update.message.reply_text('Alright!!, something different', reply_markup = markup)

    return TYPING_CHOICE

def received_information(bot, update, user_data):
    text = update.message.text
    category = user_data['choice']
    user_data[category] = text
    del user_data['choice']

    update.message.reply_text("Neat! Just so you know, this is what you told me:"
                              "%s"
                              "You can tell me more, or change your opinion on something."
                              % facts_to_str(user_data),
                              reply_markup = markup)

    return CHOOSING

def done(bot, update, user_data):
    '''
    :param bot: bot
    :param update: update
    :param user_data: we use 'facts_to_str' to give them shape
    :return: nothing. Finish the conversation and erase the data
    '''

    if 'choice' in user_data:
        del user_data['choice']

    update.message.reply_text("The event consists of:"
                              "%s"
                              "Don\'t forgot it!" % facts_to_str(user_data))
    almacenar(facts_to_str(user_data))     # almaceno los datos
    user_data.clear()
    return ConversationHandler.END

def error(bot, update, error):
    logger.warn('Update "%s" caused error "%s"' % (update, error))

## ===========================================================

def listado(bot, update):
    update.message.reply_text("The next events are:")
    #chat_id = bot.get_updates()['id'].message.chat_id
    #bot.send_document(chat_id = chat_id, document = open('Datos.txt', 'rb'))
    file = open("Datos.txt", "r")
    cadena = ''
    for line in file.readlines():
        cadena += line
        cadena += '\n'
    update.message.reply_text("%s" % cadena)
    file.close()

def almacenar(data):
    file = open("Datos.txt", "a")
    file.write(data)
    file.write('----------')
    file.close()

## ===========================================================

def main():
    TOKEN = ''
    updater = Updater(TOKEN)

    # Obtenemos el  dispatcher para registrar los handlers
    dp = updater.dispatcher

    # Añadimos un Conversation handler con los estados GENDER, PHOTO, LOCATION y BIO
    conv_handler = ConversationHandler(
        entry_points=[CommandHandler('start', start)],

        states={
            CHOOSING: [RegexHandler('^(Event\'s name|Date|Priority)$',
                                    regular_choice,
                                    pass_user_data = True),
                       RegexHandler('^Something else...$',
                                    custom_choice),
                       ],

            TYPING_CHOICE: [MessageHandler(Filters.text,
                                           regular_choice,
                                           pass_user_data = True),
                            ],

            TYPING_REPLY: [MessageHandler(Filters.text,
                                          received_information,
                                          pass_user_data = True),
                           ],
        },

        fallbacks = [ RegexHandler('^Done$', done, pass_user_data = True) ]
    )

    dp.add_handler(conv_handler)

    ## ===========================================================

    dp.add_handler(CommandHandler("listado", listado))
    ## ===========================================================

    # logeamos los errores
    dp.add_error_handler(error)

    # Empezamos con el bot
    updater.start_polling()

    # Run the bot until you press Ctrl-C or the process receives SIGINT,
    # SIGTERM or SIGABRT. This should be used most of the time, since
    # start_polling() is non-blocking and will stop the bot gracefully.
    updater.idle()

if __name__ == '__main__':
    main()


# -*- coding: utf-8 -*-
"""
Created on Thu Feb  9 14:43:24 2023

@author: SCAN
"""
import socket
import time
from .Read_txt import *
import re

def SendCmdThenWaitRSP(sock, cmd, user_delay):
    BUF_SIZE = 1024
    try:
        sock.sendall(cmd.encode('utf-8'))
        recv_data = sock.recv(BUF_SIZE)
        time.sleep(user_delay)
        return recv_data
    except socket.error as msg:
        print('[SendCmdThenWaitRSP]Exception : % s' % (msg))
        return None

if __name__ == '__main__':
    RECV_TIMEOUT = 15
    IP = "192.168.100.111"
    PORT = 5025
    filename = 'Antenna_control_phase_steps_1deg_resolution.txt'
    somme, difference = Read_txt(filename)
    try:
        TCPsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        TCPsocket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        TCPsocket.settimeout(RECV_TIMEOUT)
        TCPsocket.connect((IP, PORT))
        SendCmdThenWaitRSP(TCPsocket,"INIT 0 \n\r",0)
        SendCmdThenWaitRSP(TCPsocket,"TDD 2 \n\r",0) # TDD 1 in TX, 2 in RX
        SendCmdThenWaitRSP(TCPsocket,"TC_MODULE_CTRL_ 1,0,8,6,2,11 \n\r",0)
        for ps_step in range(64):
            SendCmdThenWaitRSP(TCPsocket,"MODULE_CTRL_ 1,2,0,0,0,0,0,0,0,"+str(ps_step)+",0,0,0,0,0,0 \n\r",0)
    except socket.error as msg:
                    print('[Init_TCP_client]Exception : %s' % (msg))


import os

class Grafo:
    def __init__(self):
        pass

    def graficarArbol(self, raiz):
        acumuladores = ["digraph G{\nnode [shape=circle];\n", ""]

        if raiz != None:
            self.recorrerArbol(raiz,acumuladores)

        acumuladores[0] += acumuladores[1] + "\n}"

        f = open('grafo.dot', 'w')
        try:
            f.write(acumuladores[0])
        finally:
            f.close()

        prog = "dot -Tsvg  grafo.dot -o grafo.svg"
        os.system(prog)

    def recorrerArbol(self, raiz,acum):

        if raiz:
            acum[1] += '"{}"[label="{}"];\n'.format(str(hash(raiz)),str(raiz.id))

            if raiz.izq.raiz != None:
                acum[1] += '"{}" -> "{}";\n'.format(str(hash(raiz)),str(hash(raiz.izq.raiz)))
            if raiz.der.raiz != None:
                acum[1] += '"{}" -> "{}";\n'.format(str(hash(raiz)), str(hash(raiz.der.raiz)))

            self.recorrerArbol(raiz.izq.raiz, acum)
            self.recorrerArbol(raiz.der.raiz, acum)


def solution(m, musicinfos):
    answer = '(None)'
    longest_time = 0

    cnt = len(musicinfos)
    infos = []
    # 입력값 조정 (시간 분 단위로 변환)
    for i in musicinfos:
        start, end, name, codes = i.split(",")
        s_h, s_m = map(int, start.split(":"))
        e_h, e_m = map(int, end.split(":"))
        infos.append([s_h * 60 + s_m, e_h * 60 + e_m, name, codes])

    # '#'붙은 코드 한글자로 바꾸기
    change_code = {"A#": "Z", "C#": "Y", "D#": "X", "F#": "W", "G#": "V"}
    for old_code, new_code in change_code.items():
        m = m.replace(old_code, new_code)
        for i in range(cnt):
            infos[i][3] = infos[i][3].replace(old_code, new_code)

    listen_time = len(m)

    for start, end, name, code in infos:
        play_time = end - start
        # 재생 시간이 짧아서 일단 얘는 아님
        if play_time < listen_time:
            continue

        # 재생시간에 맞춰 악보를 만들어보자.
        code_len = len(code)
        repeats = play_time // code_len
        codes = code * repeats
        if play_time > repeats * code_len:
            codes += code[:play_time - repeats * code_len]

        # 포함하는가?
        if m in codes and play_time > longest_time:
            answer = name
            longest_time = play_time

    return answer


"""
1707. Maximum XOR With an Element From Array
Hard

Share
You are given an array nums consisting of non-negative integers. You are also given a queries array, where queries[i] = [xi, mi].

The answer to the ith query is the maximum bitwise XOR value of xi and any element of nums that does not exceed mi. In other words, the answer is max(nums[j] XOR xi) for all j such that nums[j] <= mi. If all elements in nums are larger than mi, then the answer is -1.

Return an integer array answer where answer.length == queries.length and answer[i] is the answer to the ith query.

Example 1:

Input: nums = [0,1,2,3,4], queries = [[3,1],[1,3],[5,6]]
Output: [3,3,7]
Explanation:
1) 0 and 1 are the only two integers not greater than 1. 0 XOR 3 = 3 and 1 XOR 3 = 2. The larger of the two is 3.
2) 1 XOR 2 = 3.
3) 5 XOR 2 = 7.
Example 2:

Input: nums = [5,2,4,6,6,3], queries = [[12,4],[8,1],[6,3]]
Output: [15,-1,5]

Constraints:

1 <= nums.length, queries.length <= 105
queries[i].length == 2
0 <= nums[j], xi, mi <= 109
"""

"""
The solution is we build a trie, and each node means a bit. so the trie's height is like 32 (it depends on the max value in the nums, but does not matter, 32 is Accept).

we put all elements in nums into this trie, the time cost is 32 * N. and space cost is N * ln N.
we got a trie that contains all emelemt in the nums, one important point is we put the minValue of each sub trie in the node. the minValue will be used later.
we iter all queries, and for each x we try out best to pick up a leaf from the tree. we use the minValue to exclude those invalid route (only pick up leaf from those minValue <= m subtree).
try out best means if we can choose one from left or from right, we pick up the right substree.
"""
from typing import List
class Trie:
    def __init__(self):
        self.root = {}

    def insert(self, num):
        p = self.root
        for i in range(31, -1, -1):
            cur = (num >> i) & 1
            if cur not in p:
                p[cur] = {}
            p = p[cur]

    def query(self, num):
        if not self.root:
            return -1
        p, ans = self.root, 0
        for i in range(31, -1, -1):
            cur = (num >> i) & 1
            if 1 - cur in p:
                p = p[1 - cur]
                ans |= (1 << i)
            else:
                p = p[cur]
        return ans

class Solution:
    def maximizeXor(self, nums: List[int], queries: List[List[int]]) -> List[int]:
        nums.sort()
        queries = sorted(enumerate(queries), key=lambda x: x[1][1])
        trie = Trie()
        ans = [-1] * len(queries)
        j = 0
        for i, (x, m) in queries:
            while j < len(nums) and nums[j] <= m:
                trie.insert(nums[j])
                j += 1
            ans[i] = trie.query(x)
        return ans

if __name__ == "__main__":
    print(Solution().maximizeXor(nums = [0,1,2,3,4], queries = [[3,1],[1,3],[5,6]]))


import sys
import PySide6.QtWidgets as QtW
import PySide6.QtCore as QtC
import PySide6.QtGui as QtG
from datetime import datetime

import resources.styling as styling
import resources.constants as const

from Note import Note
from NotebookGUI import NotebookGUI
import NotebookDB

class NotebookApp(NotebookGUI):
    def __init__(self):
        super().__init__()
        self.note: Note
        self.note_selected: bool = False
        self.note_count = 0

        self.connect_signals()
        self.theme_button.toggle()

        NotebookDB.load_notes(self)

    def connect_signals(self):
        self.tray_restore.triggered.connect(self.show)
        self.tray_quit.triggered.connect(self.quit)
        self.tray_icon.activated.connect(self.tray_icon_activated)

        self.search_edit.textChanged.connect(self.search_notes)
        self.add_button.clicked.connect(self.add_note)
        self.delete_button.clicked.connect(self.delete_note)
        self.quit_button.clicked.connect(self.quit)

        self.scheduled_button.toggled.connect(self.toggle_scheduled)
        self.theme_button.toggled.connect(self.toggle_theme)
        self.discard_button.clicked.connect(self.update_note_editor)
        self.save_button.clicked.connect(self.edit_note)

        self.notebook.itemSelectionChanged.connect(self.update_note_editor)
        self.notebook.dropEvent = self.dropEvent

    def closeEvent(self, event: QtG.QCloseEvent):
        event.ignore()
        self.hide()

    def dropEvent(self, event: QtG.QDropEvent):
        super(QtW.QListWidget, self.notebook).dropEvent(event)
        self.notebook.relocate(self.note)
        NotebookDB.save_notes(self)

    def tray_icon_activated(self, reason: QtW.QSystemTrayIcon.ActivationReason):
        if reason == QtW.QSystemTrayIcon.ActivationReason.DoubleClick:
            self.show()
            self.activateWindow()

    def quit(self):
        NotebookDB.save_notes(self)
        QtC.QCoreApplication.instance().quit()

    @QtC.Slot(str)
    def search_notes(self, query: str):
        query = query.strip().lower()
        for note in self.notebook:
            to_show = query in note.title.lower() or query in note.content.lower()
            in_tags = False
            for tag in note.tags:
                if query in tag.lower():
                    in_tags = True
                    break
            note.setHidden(not to_show and not in_tags)

    def add_note(self):
        self.note_count += 1
        self.note = self.notebook.add(
            title=f"New Note {self.note_count}",
            scheduled_at=datetime.now(),
            created_at=datetime.now(),
        )
        self.notebook.addItem(self.note)
        self.notebook.setCurrentItem(self.note)

    def delete_note(self):
        self.notebook.remove(self.notebook.currentRow())

    def update_note_editor(self):
        self.note = self.notebook.currentItem()
        if self.note is None:
            self.title_edit.clear()
            self.scheduled_button.setChecked(False)
            self.scheduled_edit_date.setDate(const.DEFAULT_INITIAL_DATE)
            self.scheduled_edit_time.setTime(const.DEFAULT_INITIAL_TIME)
            self.content_edit.clear()
            self.tags_edit.clear()
            self.created_at_edit.setDateTime(const.DEFAULT_INITIAL_DATETIME)
            self.update_interactability()
            return
        self.title_edit.setText(self.note.title)
        self.scheduled_button.setChecked(self.note.scheduled)
        self.scheduled_edit_date.setDate(
            QtC.QDate.fromString(
                self.note.scheduled_at.strftime(const.DEFAULT_DATE_FORMAT),
                const.DEFAULT_DATE_EDIT_CONVERSION_FORMAT,
            )
        )
        self.scheduled_edit_time.setTime(
            QtC.QTime.fromString(
                self.note.scheduled_at.strftime(const.DEFAULT_TIME_FORMAT),
                const.DEFAULT_TIME_EDIT_CONVERSION_FORMAT,
            )
        )
        self.content_edit.setText(self.note.content)
        self.tags_edit.setText(", ".join(self.note.tags))
        self.created_at_edit.setDateTime(
            QtC.QDateTime.fromString(
                self.note.created_at.strftime(const.DEFAULT_DATETIME_FORMAT),
                const.DEFAULT_DATETIME_CONVERSION_FORMAT,
            )
        )
        self.update_interactability()

    def update_interactability(self):
        note_selected = self.note is not None
        if self.note_selected == note_selected:
            return
        self.note_selected = note_selected
        self.delete_button.setEnabled(note_selected)
        self.title_label.setEnabled(note_selected)
        self.title_edit.setEnabled(note_selected)
        self.scheduled_button.setEnabled(note_selected)
        self.content_label.setEnabled(note_selected)
        self.content_edit.setEnabled(note_selected)
        self.tags_label.setEnabled(note_selected)
        self.tags_edit.setEnabled(note_selected)
        self.created_at_label.setEnabled(note_selected)
        self.created_at_edit.setEnabled(note_selected)
        self.discard_button.setEnabled(note_selected)
        self.save_button.setEnabled(note_selected)

    def edit_note(self):
        title = self.title_edit.text()
        scheduled = self.scheduled_button.isChecked()
        scheduled_at = datetime.combine(
            self.scheduled_edit_date.date().toPython(),
            self.scheduled_edit_time.time().toPython(),
        )
        content = self.content_edit.toPlainText()
        tags = self.tags_edit.text().split(", ")
        self.note.update(
            title=title,
            scheduled=scheduled,
            scheduled_at=scheduled_at,
            content=content,
            tags=tags,
        )
        NotebookDB.save_notes(self)

    def toggle_scheduled(self, checked: bool):
        self.scheduled_edit_date.setEnabled(checked)
        self.scheduled_edit_time.setEnabled(checked)

    def toggle_theme(self, checked: bool):
        if checked:
            app.setPalette(styling.DARK_PALETTE)
        else:
            app.setPalette(styling.LIGHT_PALETTE)

def main():
    global app
    app = QtW.QApplication(sys.argv)
    app.setStyle(styling.STYLE)
    app.setFont(const.DEFAULT_APP_FONT)
    notebook_app = NotebookApp()
    notebook_app.show()
    sys.exit(app.exec())

if __name__ == "__main__":
    main()


import logging, time, threading, socket

class pyropi:
    # General variable declaration
    GPIO_map = [14,15,18,23,24,25,8,7, 2,3,4,17,27,22,10,9]
    box_id_pins = [12,16,20,21]
    box_id_output = [5,6,13,19]
    ready_pin = 26
    button_pin = 11
    button_state = 1
    keep_watching = True
    imported = True
    ready = False
    box_id = 0
    port = None

    def __init__(self, port):
        # Set up logging
        logging.basicConfig(format='%(asctime)s %(levelname)s: %(name)s: %(message)s', level=logging.INFO, datefmt='%m/%d/%Y %I:%M:%S %p')
        self.log = logging.getLogger('pyropi')

        # Set up the port
        self.port = port

        # Try to import the RPi GPIO library
        try:
            global GPIO
            import RPi.GPIO as GPIO
        except:
            self.log.info('Failed to import RPi.GPIO')
            self.imported = False

        threading.Thread(target=self.setup).start()

    def setup(self):
        """The setup function (used for threading)"""
        # Set up the pins
        self.log.info("Setting up pins")
        self.setup_pins()

        # Start the button watching script
        threading.Thread(target=self.watch_button).start()

        # Get the box id
        self.log.info("Getting box ID")
        self.get_box_id()
        self.log.info("Box ID " + str(self.box_id))

    def setup_pins(self):
        """"Set up the output and input pins and set their default values"""
        # Exit if there is no RPi library
        if not self.imported:
            return 0

        # Set the mode
        GPIO.setmode(GPIO.BCM)
        GPIO.setwarnings(False)

        # Set up the ready LED
        GPIO.setup(self.ready_pin, GPIO.OUT)
        GPIO.output(self.ready_pin, GPIO.LOW)

        # Set up the push button
        GPIO.setup(self.button_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)

        # Set up the box id input pins
        for pin in self.box_id_pins:
            GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)

        # Set up the box id output pins
        for pin in self.box_id_output:
            GPIO.setup(pin, GPIO.OUT)
            GPIO.output(pin, GPIO.LOW)

        # Set all of the firing pins
        for pin in self.GPIO_map:
            # Set up the pin for output
            GPIO.setup(pin, GPIO.OUT)
            GPIO.output(pin, GPIO.HIGH)

    def watch_button(self):
        """Watches the button for pushes"""
        # Check for GPIO library
        if not self.imported:
            return 0

        # Watch the button
        start_time = time.time()
        while self.keep_watching:
            # Get the buttons current state
            current_state = GPIO.input(self.button_pin)
            if current_state != self.button_state and current_state == 0:
                # The button is pressed and wasn't last loop
                start_time = time.time()
            elif current_state != self.button_state and time.time() - start_time >= 1:
                # The button was released and was held for longer than 1 second
                # Shut down the server
                sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                sock.settimeout(0.5)
                sock.connect(("127.0.0.1",self.port))
                sock.send("exit")
            elif current_state != self.button_state:
                # The button was released and was help for less than 1 second
                # Fire all of the cues in 1 second intervals
                threading.Thread(target=self.fire_all_pins).start()

            # Save the (possibly) new button state
            self.button_state = current_state

    def fire_all_pins(self):
        """Fire all the pins in 1 second increment"""
        for pin in self.GPIO_map:
            time.sleep(1)
            threading.Thread(target=self._fire_pin, args=[pin]).start()

    def get_box_id(self):
        """Return the ID of the box based on switch positions"""
        # Default to box id 0
        if not self.imported:
            return 0

        # Get the actual box ID based on switches
        index = 0
        box_id = 0
        while ( index < len(self.box_id_pins)):
            # Read the state of the pin
            pin_state = 1 - GPIO.input(self.box_id_pins[index])
            self.log.info('Pin ' + str(index) + ' (' + str(self.box_id_pins[index]) + '): ' + str(pin_state))

            # Set the corresponding output pin
            GPIO.output(self.box_id_output[index], GPIO.HIGH if pin_state else GPIO.LOW)

            # Add to the box ID
            box_id = box_id + (pin_state * (2 ** index))

            # Increment index
            index = index + 1

        self.box_id = box_id

    def fire_pin(self, box, cue):
        """Start a threaded function that fires the cue if needed"""
        # Check for the box id
        if int(box) != self.box_id:
            return 0

        # Get the pin to use
        try:
            pin = self.GPIO_map[int(cue) - 1]
        except:
            self.log.info("Error Finding cue " + str(cue))
            return false

        # Log that the pin is being fired
        self.log.info("Fire " + str(box) + "-" + str(cue) + " (pin " + str(pin) + ")")

        # Start the thread
        threading.Thread(target=self._fire_pin, args=[pin]).start()

    def _fire_pin(self, pin):
        """Fire a certain pin"""
        # Exit if GPIO is not imported
        if not self.imported:
            return 0

        # Fire the pin
        self.log.debug("Turning on " + str(pin))
        GPIO.output(pin, GPIO.LOW)
        time.sleep(0.1)
        self.log.debug("Turning off " + str(pin))
        GPIO.output(pin, GPIO.HIGH)

    def ready(self):
        """Turn on the ready light"""
        if not self.imported:
            return False

        GPIO.output(self.ready_pin, GPIO.HIGH)
        self.ready = True

    def blink_ready(self, times):
        """Blink the ready light a certain number of times"""
        if not self.imported:
            return False

        index = 0;
        while index < times:
            index = index + 1
            GPIO.output(self.ready_pin, GPIO.LOW)
            time.sleep(0.5)
            GPIO.output(self.ready_pin, GPIO.HIGH)
            time.sleep(0.5)

        if not self.ready:
            GPIO.output(self.ready_pin, GPIO.LOW)


from django.core.validators import RegexValidator
from django.db import models

from groups.models import Group

phone_validation_message = "Phone number must be entered in the format: '+999999999'. \
                            Up to 15 digits allowed."

class Student(models.Model):
    first_name = models.CharField(max_length=24)
    last_name = models.CharField(max_length=24)
    age = models.IntegerField(default=0)
    phone = models.CharField(
        validators=[
            RegexValidator(
                regex=r'^\+?1?\d{12,15}$',
                message=phone_validation_message,
                code='invalid'
            )
        ],
        default='+00000000000000',
        max_length=15,
        blank=True
    )
    group_id = models.ForeignKey(
        Group,
        blank=True,
        default=None,
        on_delete=models.CASCADE)

    # def group_id(self):
    #     pass

    def __str__(self):
        return f'{self.id} \
                    {self.first_name} \
                    {self.last_name} \
                    {self.age} \
                    {self.phone} \
                    {self.group_id}'

# {self.Group.objects.filter(id=self.group_id)}

class Logger(models.Model):
    method = models.CharField(max_length=12)
    path = models.CharField(max_length=50)
    execution_time = models.FloatField(null=False)
    created = models.DateTimeField(auto_now_add=True)


from typing import Optional
from djfapi.security.jwt import JWTToken
from ..utils import get_connection

class JWTTokenRedis(JWTToken):
    def __init__(self, *args, redis_url: Optional[str] = None, **kwargs):
        super().__init__(*args, **kwargs)
        self.redis = get_connection(redis_url, use_async=True)

    async def _create_access(self, token):
        access = await super()._create_access(token)
        scopes = await self.redis.smembers(f'access:token:{access.jti}:scopes')
        access.token.aud = [str(scope, 'utf-8') for scope in scopes]
        return access


import os, time, spidev
import RPi.GPIO as GPIO

# Constants
BUTTON_DRDY0 = 36
BUTTON_DRDY1 = 37

POWER_CTL = 0x2D
calib = 1.0/52428.8

#Setup Board
GPIO.setmode(GPIO.BOARD)

# Interrupt Setup
GPIO.setup(BUTTON_DRDY0, GPIO.IN, pull_up_down = GPIO.PUD_UP)
GPIO.setup(BUTTON_DRDY1, GPIO.IN, pull_up_down = GPIO.PUD_UP)

#Setup SPI
spi0 = spidev.SpiDev()
spi0.open(0,0)
spi0.max_speed_hz = 1000000
spi0.mode = 0b00

#Setup SPI
spi1 = spidev.SpiDev()
spi1.open(0,1)
spi1.max_speed_hz = 9760000
spi1.mode = 0b00

def activate0():
	spi0.xfer([POWER_CTL<<1, 0])
	spi1.xfer([POWER_CTL<<1, 0])

def writeBytes(addr, data):
	spi0.xfer3([addr<<1] + data)

def writeBytes(addr, data):
	spi0.xfer3([addr<<1] + data)

def readByte(addr, count):
	data = spi0.xfer3([(addr<<1)|1]+([0]*count))
	return data[1:]

def readByte(addr, count):
	data = spi0.xfer3([(addr<<1)|1]+([0]*count))
	return data[1:]

def readFIFO(i):
	ADDR = [(0x11<<1)|1, 0,0,0, 0,0,0, 0,0,0]

	if i == 0: data = spi0.xfer3(ADDR)
	else: data = spi0.xfer3(ADDR)

	x = (data[1]<<12)|(data[2]<<4)|(data[3]>>4);
	if(data[1]&0x80): x = x - (1<<20)
	y = (data[4]<<12)|(data[5]<<4)|(data[6]>>4);
	if(data[4]&0x80): y = y - (1<<20)
	z = (data[7]<<12)|(data[8]<<4)|(data[9]>>4);
	if(data[7]&0x80): z = z - (1<<20)

	return (x*calib,y*calib,z*calib)

def cleanupp():
	spi0.close()
	spi1.close()
	GPIO.cleanup()

def intt():
	i = 0
	while True:
		# ~ GPIO.wait_for_edge(BUTTON_DRDY0, GPIO.FALLING)
		# ~ i = i + 1
		# ~ print(i)
		print(readFIFO(0))
		print(hex(readByte(0x04,1)[0]))

if __name__ == "__main__":
	activate0()
	# ~ intt()
	# ~ print(readFIFO(0))
	# ~ writeBytes(0x2D,[0])
	intt()
	print(hex(readByte(0x2,1)[0]))
	cleanupp()


from pydub import AudioSegment
from math import ceil
import ctypes
from glob import glob
from pathlib import Path

def clamp(n, minn, maxn):
    return max(min(maxn, n), minn)

def cleanup(filepath, file):
    cleanedup = "songs_converted/" + filepath.replace("songs\\", "").replace(".mp3", "").replace(".flac", "").replace(".wav", "").replace(".ogg", "").replace(".", "").replace(",", "").replace("_", "").replace("'", "") + " _" + str(ceil((len(file) / 1000.0))).zfill(3) # GMOD can't open some files if they have some forbidden characters. Some workshop uploads tools don't like them too. So I've did this awfulness. Oh and I need to make it fit for SBM.
    return cleanedup

def edit(file):
    loadedsong = AudioSegment.from_file(file)
    fadetime = ceil(clamp((len(loadedsong)) * 0.02, 0, 7000))
    editedsong = loadedsong.fade_in(fadetime).fade_out(fadetime).set_frame_rate(44100)
    return editedsong

def main():
    print("SBM Auto Converter: convert lots of songs automatically to the type SBM accepts! Made by John aka downline.")
    convertedfilesnumber = 0
    if not Path(str(Path.cwd()) + "/songs").is_dir() or not Path(str(Path.cwd()) + "/songs_converted").is_dir():
        Path(str(Path.cwd()) + "/songs").mkdir(parents=True, exist_ok=True)
        Path(str(Path.cwd()) + "/songs_converted").mkdir(parents=True, exist_ok=True)
        print("Created the previously missing directories for songs.")
        print("Drop your songs in there and restart the script! " + str(Path.cwd()) + "\songs")
    else:
        if len(glob('songs/*')) == 0:
            print("No songs found. Drop them into the songs folder! " + str(Path.cwd()) + "\songs")
        else:
            for i in glob("songs/*"):
                try:
                    print("Working...")
                    initializedfile = edit(i)
                    savepath = cleanup(i, initializedfile)
                    initializedfile.export(savepath + ".ogg", format="ogg")
                    print("Saved: " + savepath)
                    convertedfilesnumber += 1
                except Exception as e:
                    print("Unexpected error. ", e)
                    continue
            if convertedfilesnumber == len(glob('songs/*')):
                print("Ran out of files.")
                ctypes.windll.user32.FlashWindow(ctypes.windll.kernel32.GetConsoleWindow(), True )
    return input()

main()


import time
import random
import ff_eurofunctions as eurof

#Introduction
print("Ta ta-tarara ta taaa taa (imagine the music of Charpentier's 'Te Deum' right now)...\n")
time.sleep(3)
print("Welcome to mucbib Eurovision-Data, a web scraper which lets you download and save data from the Eurovision Song Contest.\n")
print("This program is licensed under MIT. See https://github.com/mucbib/Eurovision-Data for more information.\n")
time.sleep(5)
cities = ['Turin', 'Tel Aviv', 'Rotterdam', 'Lisbon', 'Kyiv', 'Stockholm', 'Vienna', 'Dublin', 'Copenhagen', 'Belgrade', 'Baku', 'Liverpool']
randomcity = random.choice(cities)
print(f"Okay, {randomcity}, are you ready ?\n")
time.sleep(2)
#User interaction: definition of what to scrape
print("Do you want to download all data from all contests from 1956 until today, including semi-finals ? (enter 'yes')")
print("Or do you want to set your own preferences (years and shows) ? (in that case enter 'no' or your favourite song by Carola).")
answer = input("yes/no: ").strip().lower()

#if yes: scrape everything
if answer == 'yes' or answer == 'y':
	eurof.scrapingwikifinal(True)
	time.sleep(1)
	eurof.scrapingwikisemi(True)
	time.sleep(1)
	eurof.merging()
else:
	#if no: customized scraping
	print("Set your preferences. Step 1:")
	print("Do you want to get data for contests between 1956 and 2003 and/or the finals after 2004 ? (enter 'yes')")
	both = 0
	answerfinal = input("yes/no: ").strip().lower()
	if answerfinal == 'yes' or answerfinal == 'y':
		eurof.scrapingwikifinal(False)
		both = both + 1

	time.sleep(1)

	print("Step 2: Do you want to get data for semi-finals ? (enter 'yes')")
	answersemi = input("yes/no: ").strip().lower()
	if answersemi == 'yes' or answersemi == 'y':
		eurof.scrapingwikisemi(False)
		both = both + 1
	time.sleep(1)

	#if the user has chosen to scrape both data from semi-finals and finals, ask if the two tables should be merged
	if both == 2:
		print("Do you want to merge the results from semi-finals and finals in one table ?")
		answermerge = input("yes/no: ").strip().lower()
		if answermerge == 'yes' or answermerge == 'y':
			eurof.merging()

print("End of program. Good night Europe !")


from sqlalchemy import ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.exc import IntegrityError
from src.database.db import db
from collections import OrderedDict

class Cart(db.Model):
    __tablename__ = 'carts'
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, ForeignKey('users.id'), unique=True)
    users = relationship('User', back_populates='carts')
    products = relationship('Product', secondary='cart_items', back_populates='carts')

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

    @staticmethod
    def create(user_id):
        try:
            new_cart = Cart(user_id)
            db.session.add(new_cart)
            db.session.commit()
            return OrderedDict(error=None, status_code=201)
        except IntegrityError:
            db.session.rollback()
            return OrderedDict(error='Cart already exists', status_code=400)
        except Exception as e:
            return OrderedDict(error=str(e), status_code=500)

    @staticmethod
    def get_all():
        try:
            carts = Cart.query.all()
            return OrderedDict(found_carts=carts, error=None, status_code=200)
        except Exception as e:
            return OrderedDict(found_carts=None, error=str(e), status_code=500)

    @staticmethod
    def get_one(cart_id):
        try:
            cart = Cart.query.get(cart_id)
            if not cart:
                return OrderedDict(found_cart=None, error='Cart not found', status_code=404)

            return OrderedDict(found_cart=cart, error=None, status_code=200)
        except Exception as e:
            return OrderedDict(found_cart=None, error=str(e), status_code=500)

    @staticmethod
    def get_by_user(user_id):
        try:
            cart = Cart.query.filter_by(user_id=user_id).first()
            if not cart:
                return OrderedDict(found_cart=None, error='Cart not found', status_code=404)
            return OrderedDict(found_cart=cart, error=None, status_code=200)
        except Exception as e:
            return OrderedDict(found_cart=None, error=str(e), status_code=500)

    @staticmethod
    def get_items_by_user(user_id):
        try:
            query = "SELECT cart_items.id as cart_item_id, carts.user_id, carts.id as cart_id, " \
                    "products.id as product_id, products.name as product_name, " \
                    "products.code as product_code, products.price as product_price FROM carts " \
                    "cross join products right join cart_items on cart_items.cart_id = carts.id " \
                    "and cart_items.product_id = products.id where carts.user_id = " + str(user_id) + ";"

            cart = db.session.execute(query).fetchall()
            if not cart:
                return OrderedDict(found_cart=None, error='No items found', status_code=404)
            return OrderedDict(found_cart=cart, error=None, status_code=200)
        except Exception as e:
            return OrderedDict(found_cart=None, error=str(e), status_code=500)


import sys, io
from PySide2.QtWidgets import QApplication
import queue
from pyGuiComms.utilities import cli, logger
from pyGuiComms.ui import uiBase
from pyGuiComms.comms import commsClient, remoteLogClient
import json

class UiExecute:
  def __init__(self, ui_file_path, settings_file_path, widgets_file_path, protocol_file_path):
    with open(settings_file_path, "r") as settings_file:
      settings = json.load(settings_file)

    with open(widgets_file_path, "r") as widgets_file:
      widget_settings = json.load(widgets_file)

    args = cli.get_args(settings["default"])
    log_port = None
    LogSocket = None

    if args.no_connect == True:
      from pyGuiComms.sockets import socketFake
      ClientSocket = socketFake.SocketFake
      serverAddress = ''
      port = 0
    elif args.tcp != None:
      from pyGuiComms.sockets import socketTcp
      ClientSocket = socketTcp.SocketTcp
      serverAddress = args.tcp[0]
      port = int(args.tcp[1])
      if (args.tcp_remote_log != None):
        log_port = int(args.tcp_remote_log)
        LogSocket = socketTcp.SocketTcp
    else:
      from pyGuiComms.sockets import socketBt
      ClientSocket = socketBt.SocketBt
      serverAddress = args.bluetooth[0]
      port = args.bluetooth[1]

    if args.data_logging != None:
      log_entries = logger.LogEntries()
    else:
      log_entries = None
      log_file = None
      log = None

    app = QApplication(sys.argv)

    window = uiBase.load_from_file(ui_file_path)

    command_queue = queue.Queue()
    client_socket = ClientSocket(serverAddress, port)
    comms = commsClient.CommsClient(protocol_file_path, client_socket, command_queue)
    window.add_upkeep(20, comms.upkeep)
    window.set_command_queue(command_queue)
    data_map = window.get_data_map()

    if LogSocket != None:
      log_socket = LogSocket(serverAddress, log_port)
      remote_logger = remoteLogClient.RemoteLogClient(log_socket, data_map)
      window.add_upkeep(250, remote_logger.upkeep)

    window.load(comms, widget_settings)

    if log_entries != None:
      log_file = open(args.data_logging, "w+")
      log = logger.Logger(log_file, log_entries)
      window.add_upkeep(100, log.publish)

    sys.exit(app.exec_())

    log_file.close()


#coding=utf-8
'''
Created on 2017��6��12��

@author: Administrator
'''

import sqlite3
def createDB():
# test.db is a file in the working directory.
    conn = sqlite3.connect("user.db")

#     c = conn.cursor()
    # create tables
    conn.execute('''CREATE TABLE IF NOT EXISTS users
         (uid INTEGER PRIMARY KEY, account text,location text,psw text,sex int,img text,phone text,name text,age int,token text)''')
    return conn
def selectDB(conn,account):
    c = conn.cursor()
    c.execute('SELECT * FROM users WHERE  account = '+account+' ORDER BY id')
    rows = c.fetchall()
    #遍历数据也不变（比上一个更直接一点）
    for row in rows:
        user={}
        user["location"]=(not row[2] )and row[2] or ''
        user["sex"]=(not row[4] )and row[4] or 0
        user["img"]=(not row[5] )and row[5] or ''
        user["phone"]=(not row[6] )and row[6] or ''
        user["name"]=(not row[7] )and row[7] or ''
        user["age"]=(not row[8] )and row[8] or 0
        user["token"]=(not row[9] )and row[9] or ''
        user["account"]=(not row[1] )and row[1] or ''
        user["uid"]=(not row[0] )and row[0] or 0
        return user
        break
    return None

def addDB(conn,account,psw,img):
    conn.execute('INSERT INTO users(account,psw,img)values('+account+','+psw+','+img+')')
    conn.commit()
def updatetokenDB(conn,account,token):
    conn.execute("UPDATE users SET token = '"+token+"' WHERE account = "+account)
    conn.commit()


import Crossfire
import os

whoami = Crossfire.WhoAmI()
whoisother = Crossfire.WhoIsOther()
parms = Crossfire.WhatIsMessage()

if parms=="give":
    Crossfire.Log(Crossfire.LogDebug, "Object given: %s" %(whoisother.Name))
    key = whoisother.ReadKey("mad_mage_marker")
    Crossfire.Log(Crossfire.LogDebug, "Object key  : %s" %(key))
    if key:
        mypath = os.path.join(Crossfire.DataDirectory(), Crossfire.MapDirectory(), 'python/maps/scorn/towers/mad_mage',key)
        Crossfire.Log(Crossfire.LogDebug, "Object path : %s" %(mypath))
        file = open(mypath, "r")
        for line in file:
            whoami.Say(line)
        file.close()
        if (key == 'brewery_letter'):
            whoisother.Name = "Milking machine blueprints"
            whoisother.WriteKey("mad_mage_marker", "milking_blueprints")
    else:
        whoami.Say("Yes?")


# ----------------------------------------------------------------------------------------------------------------------
#
# This scripts creates the MNE database and associated json file
#
# Authors: Andrea Brovelli <andrea.brovelli@univ-amu.fr>
#          Ruggero Basanisi <ruggero.basanisi@gmail.com>
#
# ----------------------------------------------------------------------------------------------------------------------

# Imports
from bv2mne.config.config import setup_db_info
from bv2mne.directories import create_sbj_db_mne

# Jobs
create_json_file = True
create_db_mne = True

# Directories and params of the project
db = '/hpc/bagamore/brainets/data/'
project = 'meg_te'
json_path = db + 'db_mne/' + project
subjects = ['subject_01', 'subject_04', 'subject_05', 'subject_06', 'subject_07', 'subject_09', 'subject_10',
            'subject_11', 'subject_12', 'subject_13']

# Create json file containing databases directories as a json file. One json file per project
if create_json_file:
    json_fname = setup_db_info(db, project, json_path=json_path, overwrite=True)
else:
    json_fname = json_path + '/db_info.json'

# Create MNE database with all directories and adds necessary files from BrainVISA and Freesurfer
if create_db_mne:
    for sbj in subjects:
        create_sbj_db_mne(sbj, json_fname=json_fname)

# Manual intervention: copy and paste adapted referential.txt and MarsAtlas files into /referential and /marsatlas


#Recursive program to find out if the given string is palindrome or not.
def isPalindrome(str):
    if len(str) == 0:
        return True
    if str[0] != str[len(str)-1]:
        return False
    return isPalindrome(str[1:-1])

print(isPalindrome('madam'))
print(isPalindrome('awesome'))


#!/usr/bin/env python-devops
# -*- coding: utf-8 -*-
# @Time    : 2019-04-18 10:44
# @Author  : Anthony.long
# @Site    :
# @File    : tornado-demo.py
# @Software: PyCharm

import requests
import time

def requestId(id):
    # 测试环境
    url = 'https://***.***.cn/actionService/gateway?sn=BatchQuartz&mn=createNewBookPackClass&packageId='

    # 生产环境
    # url = 'https://***.***.cn/actionService/gateway?sn=BatchQuartz&mn=createNewBookPackClass&packageId='

    response = requests.get('%s%s' % (url, id))
    localTimes = time.strftime('%Y.%m.%d %H:%m:%s', time.localtime(time.time()))

    if response.status_code == 200:
        print(response.text)
    else:
        with open('./requestId.log', 'a+', encoding="utf-8") as file:
            file.writelines('%s,%s%s,%s\n' % (localTimes, url, id, response.text))

if __name__ == '__main__':

    # 生产环境
    # idList = [3250, 3251, 3252, 3253, 3254, 3255, 3288, 3289, 3290, 3291, 3292, 3293, 3294, 3295, 3296, 3297, 3298,3299, 3344, 3345, 3346, 3347, 3348, 3349, 3455, 3456, 3457, 3458, 3495, 3496, 3497, 3498, 3499, 3500]

    # 测试环境
    idList = [4113, 4256, 4130]

    for i in idList:
        requestId(i)


def sequence_buttons(string):
    dict = {
        '1':'.,?!:',
        '2':'ABC',
        '3':'DEF',
        '4':'GHI',
        '5':'JKL',
        '6':'MNO',
        '7':'PQRS',
        '8':'TUV',
        '9':'WXYZ',
        '0': ' '}
    string = string.upper()
    result = ''
    for i in string:
        for j in dict.values():
            if i in j:
                count = j.index(i)+1
                for k, v in dict.items():
                    if v == j:
                        result += k*count
    return result


import json
import subprocess

from brownie import network, accounts, CompoundToNotionalV2

CONFIG = {
  "kovan": {
      "cETH": "0x40575f9Eb401f63f66F4c434248ad83D3441bf61"
  },
  "mainnet": {
      "cETH": "0x4ddc2d193948926d02f9b1fe9e1daa0718270ed5"
  }
}
def main():
  addresses = None
  network_name = network.show_active()
  config = CONFIG[network_name]
  private_key_name = network.show_active().upper() + "_DEPLOYER"
  output_file = "v2.{}.json".format(network_name)
  with open(output_file, "r") as f:
      addresses = json.load(f)

  # Load account from private key
  deployer = accounts.load(private_key_name)
  compound_to_notional = CompoundToNotionalV2.deploy(
    addresses["notional"],
    addresses["governor"],
    config["cETH"],
    {"from": deployer}
  )

  verify(
      compound_to_notional.address,
    [
        addresses["notional"],
        addresses["governor"],
        config["cETH"]
    ]
  )

def verify(address, args):
    proc = subprocess.run(
        ["npx", "hardhat", "verify", "--network",
         network.show_active(), address] + args,
        capture_output=True,
        encoding="utf8",
    )

    print(proc.stdout)
    print(proc.stderr)


import numpy as np
import pandas as pd
from sklearn import linear_model
from scipy.signal import argrelextrema

class ScanLine:
  def __init__(self, data, filename, ystep = 0.02):
    try:
      self.ypos = float(filename[:8])
    except:
      self.ypos = ystep * int(filename[filename.rfind('-') + 1: filename.find('.')])

    self.filename = filename
    self.data = data.to_numpy()
    self.slope_correction()
    self.smooth_width = 100
    self.smooth()

  def slope_correction(self):
    x = self.data[:, 0].reshape(-1, 1)
    y = self.data[:, 1].reshape(-1, 1)

    lr = linear_model.LinearRegression()
    lr.fit(x, y.ravel())
    regression = lr.predict(x)
    self.regression = regression

    self.slope = lr.coef_[0]
    self.intercept = lr.intercept_

    self.data_corrected = np.copy(self.data)
    self.data_corrected[:, 1] -= regression

  def smooth(self):
    smoothed = np.convolve(self.data_corrected[:, 1], np.ones((self.smooth_width,)) / self.smooth_width, mode='same')
    double_smoothed = np.convolve(smoothed, np.ones((self.smooth_width,)) / self.smooth_width, mode='same')
    triple_smoothed = np.convolve(double_smoothed, np.ones((self.smooth_width,)) / self.smooth_width, mode='same')
    self.data_corrected_smooth = np.copy(self.data_corrected)
    self.data_corrected_smooth[:, 1] = triple_smoothed

    self.maxima_xpos = argrelextrema(self.data_corrected_smooth[:, 1], np.greater)
    self.maxima = [self.data_corrected_smooth[xpos] for xpos in self.maxima_xpos]
    self.minima_xpos = argrelextrema(self.data_corrected_smooth[:, 1], np.less)
    self.minima = [self.data_corrected_smooth[xpos] for xpos in self.minima_xpos]

  def update_regression(self, slope, intercept):
    self.slope = slope
    self.intercept = intercept
    self.regression = (slope * self.data[:, 0] + intercept).reshape(len(self.data), -1)
    self.data_corrected[:, 1] = self.data[:, 1] - self.regression.ravel()
    self.smooth()

  def set_ypos(self, ypos):
    self.ypos = ypos


# https://www.codewars.com/kata/585d8c8a28bc7403ea0000c3

from itertools import combinations

def find_uniq(arr):
    # arr[:3] contains at least two similar character entries and at most 1 different. Thus two entries are guaranteed
    # to have similar characters (Pigeonhole Principle). Here we check each combination of two entries until we find
    # that match.
    for charset1, charset2 in combinations((set(entry.lower()) for entry in arr[:3]), 2):
        if charset1 == charset2:
            similar = charset1
            break

    for entry in arr:
        if set(entry.lower()) != similar:
            return entry

print(find_uniq(['Aa', 'aaa', 'aaaaa', 'BbBb', 'Aaaa', 'AaAaAa', 'a']))


import argparse
from daxpy import daxpy
from mxm import mxm
from mxm_tiled import mxm_tiled
import time

def get_ram_size(dim, alg):
    if alg == "mxm_blocked" or alg == "mxm":
        return dim * dim * 24
    else:
        return dim * 24

def main():
    parser = argparse.ArgumentParser(description='CPU Emulator')
    parser.add_argument('-c', '--cache', help='Size of cache')
    parser.add_argument('-b', '--block', help='Size of block')
    parser.add_argument('-n', '--associativity', help='associativity of the cache')
    parser.add_argument('-r', '--replacement', help='replacement policy of the cache')
    parser.add_argument('-a', '--algorithm', help='algorithm to simulate')
    parser.add_argument('-d', '--dimension', help='dimension of matrix/vector')
    parser.add_argument('-p', '--print', help='Print', action='store_true')
    parser.add_argument('-f', '--blocking', help='Blocking factor')

    args = parser.parse_args()

    cache = 65536
    block_size = 64
    n = 1024
    r = "LRU"
    a = "mxm_blocked"
    d = 320
    f = 32
    p = False

    if args.cache:
        cache = int(args.cache)
    if args.block:
        block_size = int(args.block)
    if args.associativity:
        n = int(args.associativity)
    if args.replacement:
        r = args.replacement
    if args.algorithm:
        a = args.algorithm
    if args.dimension:
        d = int(args.dimension)
    if args.print:
        p = args.print
    if args.blocking:
        f = int(args.blocking)

    ram = get_ram_size(dim=d, alg=a)
    cache_blocks = cache//block_size
    sets = cache_blocks // n

    print("INPUTS====================================")
    print("Ram Size =               ", ram , "bytes")
    print("Cache Size =             ", cache , "bytes")
    print("Block size =             ", block_size, "bytes")
    print("Total blocks in cache =  ", cache_blocks)
    print("Associativity =          ", n)
    print("Number of sets =         ", sets)
    print("Replacement policy =     ", r)
    print("Algorithm =              ", a)
    print("MXM Blocking Factor =    ", f)
    print("Matrix/Vector dimension =", d)

    start = time.time()
    # daxpy(block_size, n, cache, ram, r, d)
    # mxm(block_size, n, cache, ram, r, d)
    mxm_tiled(block_size, n, cache, ram, r, d, 1)

    print(f"Elapsed time: {time.time() - start:.6f} seconds")
if __name__ == "__main__":
    main()


from flask import Flask, render_template, request
from flask_debugtoolbar import DebugToolbarExtension

from stories import stories_list

app = Flask(__name__)
app.config['SECRET_KEY'] = "secret"

debug = DebugToolbarExtension(app)

@app.route("/")
def create_homepage():
    """ returns homepage html with a question form"""
    titles = [story.title for story in stories_list]
    return render_template("story-select.html", story_titles=titles)

@app.route("/questions")
def generate_questions():
    """ Gets user selected story and returns html with that story's prompts"""
    """TO-DO: Just loop through instead of doing comprehension
    or could also create a class method on Story class to find story by title"""
    story = [story for story in stories_list
            if story.title == request.args["story-selection"]]
    prompts = story[0].prompts
    title = story[0].title

    return render_template("questions.html", prompts=prompts, title=title)

@app.route("/story")
def generate_story():
    """ generate a story from form data upon form submission '"""
    answers = request.args
    story = [story for story in stories_list
        if story.title == request.args["title"]]
    story_text = story[0].generate(answers)

    return render_template("story.html", story=story_text)


# THIS PROGRAM WILL REMOVE PUNCTUATIONS ('''!()-[]{};:'"\,<>./?@#$%^&*~''') FROM ENTERED STRING
from run import *
PUNCTUATIONS = '''!()-[]{};:'"\,<>./?@#$%^&*~'''
STRING = input("\nENTER THE STRING THAT YOU WANT TO REMOVE PUNCTUATIONS :\n")
#STRING = STRING.casefold() # MAKE THE ENTERED STRING SUITABLE FOR CASELESS COMPARISON
# REMOVING PUNCTUATIONS FROM THE ENTERED STRING
NO_PUNCTUATIONS = ""
for char in STRING:
   if char not in PUNCTUATIONS:
       NO_PUNCTUATIONS = NO_PUNCTUATIONS + char

# DISPLAYING THE NON PUNCTUATED STRING
print("\nNON PUNCTUATED VERSION OF ENTERED STRING IS: ", NO_PUNCTUATIONS)
run("PUNCTUATION_REMOVER.py")


import catdog_input, catdog_model
import tensorflow as tf
import numpy as np
import time

from datetime import datetime

FLAGS = tf.app.flags.FLAGS

tf.app.flags.DEFINE_string('tfrecords_name', 'train', """filename of tfrecords""")
tf.app.flags.DEFINE_string('max_step', 1000000, """max step of training""")

LEARNING_RATE = 0.001
IMAGE_WIDTH = catdog_input.IMAGE_WIDTH
IMAGE_HEIGHT = catdog_input.IMAGE_HEIGHT
IMAGE_CHANNEL = catdog_input.IMAGE_CHANNEL
NUM_CLASS = catdog_input.NUM_CLASS

NUM_EXAPLME_PER_EPOCH_FOR_TRAIN = catdog_input.NUM_EXAPLME_PER_EPOCH_FOR_TRAIN
NUM_EXAPLME_PER_EPOCH_FOR_TEST = catdog_input.NUM_EXAPLME_PER_EPOCH_FOR_TEST

BATCH_SIZE = catdog_input.BATCH_SIZE

def train():

    # global step is necessary for "StopAtStepHook"
    global_step = tf.train.get_or_create_global_step()

    with tf.device('/cpu:0'):
        images, labels = catdog_input.distorted_input(FLAGS.tfrecords_name, BATCH_SIZE)

    logits = catdog_model.inference(images)
    loss = catdog_model.loss(logits, labels)
    accuracy = catdog_model.accuracy(logits, labels)

    train_op = catdog_model.train(loss)

    class _LoggerHook(tf.train.SessionRunHook):
        """log"""

        def begin(self):
            self._step = -1
            self._start_time = time.time()

        def before_run(self, run_context):
            self._step += 1
            # here return what you want to display when training
            # using run_values.result() to get the values
            return tf.train.SessionRunArgs([loss, accuracy])

        def after_run(self, run_context, run_values):

            # steps for displaying
            display_step = 1
            if self._step % display_step == 0:
                current_time = time.time()
                duration = current_time - self._start_time
                self._start_time = current_time
                loss, accuracy = run_values.results

                # examples used per seconds
                examples_per_sec = display_step * BATCH_SIZE / duration
                # the number of seconds for every batch
                sec_per_batch = float(duration / display_step)
                format_str = ('%s: step %d, loss = %.2f (%.1f examples/sec; %.3f '
                              'sec/batch)')
                print(format_str % (datetime.now(), self._step, loss,
                                    examples_per_sec, sec_per_batch))

    # need to look up the documentation
    with tf.train.MonitoredTrainingSession(
            hooks=[tf.train.StopAtStepHook(last_step=FLAGS.max_step),
                   tf.train.NanTensorHook(loss),
                   _LoggerHook()],
            config=tf.ConfigProto(
                log_device_placement=False)) as sess:

        coord = tf.train.Coordinator()
        # open the image read queue
        threads = tf.train.start_queue_runners(sess=sess, coord=coord)

        while not sess.should_stop():
            sess.run(train_op)

        coord.request_stop()
        coord.join(threads)

if __name__ == '__main__':
    train()


from tkinter import *
import gspread
from oauth2client.service_account import ServiceAccountCredentials

#### Access data spreadsheet ####
scope = ['https://spreadsheets.google.com/feeds']
credentials = ServiceAccountCredentials.from_json_keyfile_name('HKN Barcode Scanner-068aaeb7d73b.json', scope)
gc = gspread.authorize(credentials)
sh = gc.open_by_key('1NZJc2oPN9o_qWQq6CV7yCYGrmGwujlqfhEnhTBHTNKo')
users = sh.get_worksheet(0)
food = sh.get_worksheet(1)

foodData = food.get_all_values()

#### Controller for the app ####
class App(Tk):

        def __init__(self):
                Tk.__init__(self)

                container = Frame(self)
                container.pack(side="top", fill="both", expand=True)
                container.grid_rowconfigure(0, weight=1)
                container.grid_columnconfigure(0, weight=1)

                self.frames = {}
                for f in (ScanID, Balance, Decline, ItemSelect,
                	VerifyItem, ThankYou, AddCredit, VerifyAmt):
                        page_name = f.__name__
                        frame = f(parent=container, controller=self)
                        self.frames[page_name] = frame

                        frame.grid(row=0,column=0)

                self.show_frame("ScanID")

        def show_frame(self, page_name):
                for frame in self.frames.values():
                        frame.grid_remove()
                frame = self.frames[page_name]
                frame.grid()

        def accessID(self, id):
        	self.user = users.find(id)
        	self.userData = users.row_values(self.user.row)[:3]

        	b = self.frames["Balance"]
        	b.labelBalance.config(text=("$" + \
        		str.format('{0:.2f}', float(self.userData[2]))))

        	if (float(self.userData[2]) > 20.0):
        	    self.show_frame("Decline")
        	else:
        		self.show_frame("Balance")

        def accessFood(self, id):

        	self.foodItem = foodData[id[0]]

        	i = self.frames["ItemSelect"]
        	v = self.frames["VerifyItem"]
        	v.labelItem.config(text=i.listbox.get(id))

        	self.show_frame("VerifyItem")

        def updateID(self, amt):
        	print (self.userData[2])
        	print (amt)
        	newAmt = str(float(self.userData[2]) + float(amt))
        	users.update_cell(self.user.row, self.user.col + 2, newAmt)

        	self.show_frame("ThankYou")

#### User ID scanning screen ####
class ScanID(Frame):

	def __init__(self, parent, controller):
		Frame.__init__(self, parent)
		self.controller = controller

		labelScan = Label(self, text="Please scan ID:")
		entryID = Entry(self, show="*")
		entryID.focus()
		buttonClear = Button(self, text="CLEAR",
			command=lambda: entryID.delete(0, END))
		buttonOk1 = Button(self, text="OK", bg="green", fg="white",
			command=lambda: controller.accessID(entryID.get()))

		labelScan.grid(row=0, columnspan=2)
		entryID.grid(row=1, columnspan=2)
		buttonClear.grid(row=2,column=0)
		buttonOk1.grid(row=2,column=1)

#### User money balance screen ####
class Balance(Frame):

	def __init__(self, parent, controller):
		Frame.__init__(self, parent)
		self.controller = controller

		labelText = Label(self, text="Your balance:")
		self.labelBalance = Label(self)
		buttonCredit1 = Button(self, text="Add Credit",
			command=lambda: controller.show_frame("AddCredit"))
		buttonFood = Button(self, text="Buy Food",
			command=lambda: controller.show_frame("ItemSelect"))
		buttonBack1 = Button(self, text="BACK", bg="red", fg="white",
			command=lambda: controller.show_frame("ScanID"))

		labelText.grid(row=0, columnspan=3)
		self.labelBalance.grid(row=1, columnspan=3)
		buttonCredit1.grid(row=2,column=0)
		buttonFood.grid(row=2,column=1)
		buttonBack1.grid(row=2,column=2)

#### Large debt error screen ####
class Decline(Frame):

	def __init__(self, parent, controller):
		Frame.__init__(self, parent)
		self.controller = controller

		labelDecline = Label(self, text=("You currently owe too much money." + \
			" Please add funds"))
		buttonCredit2 = Button(self, text="Add Credit",
			command=lambda: controller.show_frame("AddCredit"))
		buttonBack2 = Button(self, text="BACK", bg="red", fg="white",
			command=lambda: controller.show_frame("ScanID"))

		labelDecline.grid(columnspan=2)
		buttonCredit2.grid(row=1,column=0)
		buttonBack2.grid(row=1,column=1)

#### Quick item purchase screen ####
class ItemSelect(Frame):

	def __init__(self, parent, controller):
		Frame.__init__(self, parent)
		self.controller = controller

		labelItem = Label(self, text="Please select item:")
		self.listbox = Listbox(self, selectmode=EXTENDED)
		buttonOk2 = Button(self, text="OK", bg="green", fg="white",
			command=lambda: controller.accessFood(self.listbox.curselection()))
		buttonBack3 = Button(self, text="BACK", bg="red", fg="white",
			command=lambda: controller.show_frame("Balance"))

		for item in foodData:
			self.listbox.insert(END, item[0] + " - $" + \
				str.format('{0:.2f}',float(item[1])))

		labelItem.grid(columnspan=2)
		self.listbox.grid(row=1, columnspan=2)
		buttonOk2.grid(row=2,column=0)
		buttonBack3.grid(row=2,column=1)

#### Item selection verification screen ####
class VerifyItem(Frame):

	def __init__(self, parent, controller):
		Frame.__init__(self, parent)
		self.controller = controller

		labelCorrect = Label(self, text="Is this correct?")
		self.labelItem = Label(self)
		buttonOk3 = Button(self, text="OK", bg="green", fg="white",
			command=lambda: controller.updateID("-" + controller.foodItem[1]))
		buttonBack4 = Button(self, text="BACK", bg="red", fg="white",
			command=lambda: controller.show_frame("ItemSelect"))

		labelCorrect.grid(columnspan=2)
		self.labelItem.grid(row=1, columnspan=2)
		buttonOk3.grid(row=2,column=0)
		buttonBack4.grid(row=2,column=1)

#### Finishing "Thank you" screen ####
class ThankYou(Frame):

	def __init__(self, parent, controller):
		Frame.__init__(self, parent)
		self.controller = controller

		labelThankYou = Label(self, text="Thank you!")
		buttonOk4 = Button(self, text="OK", bg="green", fg="white",
			command=lambda: controller.show_frame("ScanID"))

		labelThankYou.grid()
		buttonOk4.grid(row=1,column=0)

#### Adding funds screen ####
class AddCredit(Frame):

	def __init__(self, parent, controller):
		Frame.__init__(self, parent)
		self.controller = controller

		labelAmount = Label(self, text="Please enter amount:")
		buttonOk5 = Button(self, text="OK", bg="green", fg="white",
			command=lambda: controller.show_frame("VerifyAmt"))
		buttonBack5 = Button(self, text="BACK", bg="red", fg="white",
			command=lambda: controller.show_frame("Balance"))

		labelAmount.grid(columnspan=2)
		buttonOk5.grid(row=1,column=0)
		buttonBack5.grid(row=1,column=1)

#### Additional funds verification screen ####
class VerifyAmt(Frame):

	def __init__(self, parent, controller):
		Frame.__init__(self, parent)
		self.controller = controller

		labelCorrect = Label(self, text="Is this correct?")
		buttonOk6 = Button(self, text="OK", bg="green", fg="white",
			command=lambda: controller.show_frame("ThankYou"))
		buttonBack6 = Button(self, text="BACK", bg="red", fg="white",
			command=lambda: controller.show_frame("AddCredit"))

		labelCorrect.grid(columnspan=2)
		buttonOk6.grid(row=1,column=0)
		buttonBack6.grid(row=1,column=1)

#### Running the application ####
app = App()
app.title("HKN Food Scanner")
app.minsize(width=300, height=300)
app.maxsize(width=300, height=300)
app.mainloop()


from tabulate import tabulate
import sys
import csv

def main():
    if argv() == True:
        try:
            with open(sys.argv[1]) as file:
                reader = csv.DictReader(file)
                print(tabulate(reader, headers='keys', tablefmt='grid'))
        except FileNotFoundError:
            sys.exit('File not found !')

def argv():
    if len(sys.argv) == 2 and '.csv' in sys.argv[1]:
        return True
    elif len(sys.argv) > 2:
        sys.exit('Too few command-line arguments')
    elif len(sys.argv) < 2:
        sys.exit('Too many command-line arguments')
    else:
        sys.exit('not a csv file')

if __name__ == "__main__":
    main()


#!/usr/bin/env python3
""" Setup for Keymonger """
from setuptools import setup
__version__ = "0.0.2"

with open('requirements.txt') as f:
    required = f.read().splitlines()

setup(
	name='Keymonger',
	version=__version__,
	author="Robert Rice",
	author_email="h4110w33n@gmail.com",
	url='https://github.com/h4110w33n',
	description='A key management utility.',
	long_description='A key management utility.',
	keywords=['keys'],
	classifiers=[
		'Environment :: Console'
	],
	requires=required,
	install_requires=required,
	provides=['keymonger'],
	entry_points={
		'console_scripts': ['keymonger=keymonger:main'],
	},
	platforms='linux',
	license='GNU General Public License v3 (GPLv3)',
	packages=['keymonger'],
)


import numpy as np

from flip.flip import compute_flip
from flip.utils import *

# Set viewing conditions
monitor_distance = 0.7
monitor_width = 0.7
monitor_resolution_x = 3840

# Compute number of pixels per degree of visual angle
pixels_per_degree = monitor_distance * (monitor_resolution_x / monitor_width) * (np.pi / 180)

comparison_images = ["image1","image2","etc"]

for comparison_image in comparison_images:
	# Load sRGB images
	reference = load_image_array('path_to_reference_image.png')
	test = load_image_array('path_to_compared_image/{}.png'.format(comparison_image))

	# Compute FLIP map
	deltaE = compute_flip(reference, test, pixels_per_degree)

	# Save error map
	index_map = np.floor(255.0 * deltaE.squeeze(0))

	use_color_map = True
	if use_color_map:
		result = CHWtoHWC(index2color(index_map, get_magma_map()))
	else:
		result = index_map / 255.0
	save_image("path_to_flip_output/flip_{}.png".format(comparison_image), result)
	print("{} Done".format(comparison_image))


### 4195
### 친구 네트워크

# 친구 관계가 생길 때마다, 두 사람의 친구 네트워크에 몇 명이 있는지 구하는 프로그램
# 친구 네트워크란 친구 관계만으로 이동할 수 있는 사이
# 첫째 줄에 테스트 케이스
# 테스트 케이스 첫째 줄 친구 관계 수 F, 100,000 넘지 않음
# 둘째 줄은 두 사용자 이름

# HINT
# union-find 합집합으로 해결
# find : 연결 관계의 부모(첫번째 연결)를 찾음
# union : 집합을 합침, 각 집합의 개수를 더하면 연결관계의 수

# find : 재귀형태로 원소의 부모 찾아 반환
def find(x):
    if x == parent[x]:
        return x
    else:
        p = find(parent[x])
        parent[x] = p
        return p

# union : 집합의 부모로 연결, 합집합 시 y에 x를 붙이는 형태(x가 기준), 연결관계 수도 합침
def union(x, y):
    x = find(x)
    y = find(y)

    if x !=y:
        parent[y] = x
        number[x] += number[y]

test_case = int(input())
result = []

for _ in range(test_case):
    parent = dict() # 부모 정보를 갖도록 key, value 형태인 dict 사용
    number = dict()

    f = int(input())

    for _ in range(f): # 한 줄씩 처리
        x, y = input().split(' ')

        # parent에 처음 입력 시에는 연결관계 수 1
        if x not in parent:
            parent[x] = x
            number[x] = 1

        if y not in parent:
            parent[y] = y
            number[y] = 1

        union(x, y) # x, y의 부모를 찾아 x로 연결, 연결관계 수도 합침
        result.append(number[find(x)]) # 최종 부모의 연결관계 수

print('\n'.join(list(map(str, result))))
# print(parent)
# {'Fred': 'Fred', 'Barney': 'Fred', 'Betty': 'Fred', 'Wilma': 'Betty'}

# 2
# 3
# Fred Barney
# Barney Betty
# Betty Wilma

# 1
# 4
# Fred Barney
# Betty Wilma
# Betty2 Wilma
# Barney Betty

# 2
# 2
# 3
# 5


"""
Autor: Fco Javier Yagüe Izquierdo
Año: 2021
Versión: 1.0
Descripción:
Aplicación Web en Flask que junto con Detectron 2 y el modelo entrenado para el mismo, procesa y aplica una detección
sobre una imagen facilitada por el usuario.

"""

import io
import os
import csv
import cv2
import requests
import urllib.request
import datetime
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from detector import Detector
from PIL import Image
from werkzeug.utils import secure_filename
from skimage import data, filters, measure, morphology
from skimage.measure import label, regionprops
from collections import Counter
from io import BytesIO
import base64
from werkzeug.wsgi import FileWrapper
import matplotlib.pyplot as plt
from github import Github
import urllib
import json
import gdown
import re
import wget

from flask import Flask, flash, redirect, url_for, render_template, session, request, after_this_request, flash, send_file, jsonify

# Inicializacion de la web y carpeta de contenido estatico
app = Flask(__name__, static_folder='static')
app.secret_key = 'random secret key'

root = os.path.abspath(os.getcwd())

app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0 #Se acorta el cache para evitar que no se recargue el contenido de Plotly
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # Maximo tamaño de las imagenes
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg']) #Extensiones admitidas

"""
Comprueba que el fichero tiene las extensiones admitidas
Metodo original de Flask

https://flask.palletsprojects.com/en/0.12.x/patterns/fileuploads/
"""
def allowed_file(filename):
	return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

# Carga de la pantalla de inicio
@app.route("/")
def home():
    return render_template("index.html")

# Acceso a la seccion de carga desde el inicio o la navbar
@app.route("/upload")
def upload():
    return render_template("deteccion.html", mostrar_preview=False, mostrar_resultado=False, uploading=True, fichero_incompatible=False)

# Carga de la imagen con el metodo POST, que carga la imagen y la almacena en el servidor
@app.route('/upload', methods=['POST'])
def upload_image():
    if 'image' not in request.files: # Si el contenido de la peticion POST esta vacio, recargar
        return render_template("deteccion.html")
    else:
        if request.files:
          f = request.files['image']
          filename = f.filename

          # Si hay un fichero erroneo o de extension no valida, recargar notificando el problema
          if not filename or not allowed_file(filename):
            return render_template("deteccion.html", mostrar_preview=False, mostrar_resultado=False, uploading=True, fichero_incompatible=True)

          # Variables de sesion que almacenan la informacion del fichero actual
          session['filename'] = filename
          target = os.path.join(root, "static/uploads")
          destino = os.path.join(target, filename)
          preview = "./static/uploads/"+filename
          f.save(destino)
          session['destino'] = destino
          session['filename'] = f.filename

          return render_template("deteccion.html", mostrar_preview=True, mostrar_resultado=False, uploading=True, fichero_incompatible=False, deteccion=preview)

# Se ejecuta la detección, instanciando el predictor y generando los gráficos
@app.route("/deteccion", methods=['POST'])
def deteccion():
    fecha = '{:%H:%M:%S:%d-%m-%Y}'.format(datetime.datetime.now())
    fechaRegistro = '{:%d-%m-%Y}'.format(datetime.datetime.now())

    confianza = request.form['slider'] # Valor del slider mostrado para la confianza

    confianza = int(confianza)/100 # Conversion 0-1
    destino = session['destino']
    filename = session['filename']
    modelo = session['modelo']

    # Instancia del objeto Detector junto con el modelo y deteccion con el metodo inference
    try:
        dt = Detector(modelo, confianza)
        salida = dt.inference(destino)
        im = cv2.imread(destino)
        alturaImagen = im.shape[0]
        anchuraImagen = im.shape[1]

    # Extraccion de mascaras
        masks = dt.getOutputMask(salida)

        # Si no hay detecciones, generar el grafico igualmente pero sin alterar historico o registro
        if masks == 'Sin Defectos' or masks.size == 0:
            fig = px.imshow(im)
            fig.update_traces(hoverinfo='skip')
            nombreGraph = "./static/uploads/graph_" + \
                filename[:-4] + "_" + fecha + ".html"
            fig.write_html(nombreGraph)

            session['resultado'] = nombreGraph
            session['widthHTML'] = anchuraImagen
            session['heightHTML'] = alturaImagen

            return render_template("deteccion.html",
                            mostrar_preview=False,
                            uploading=False,
                            mostrar_resultado=True,
                            conDefectos=False,
                            result=session['resultado'],
                            anchoGrafico=anchuraImagen,
                            altoGrafico=alturaImagen)

    except Exception as e:
        print('-------------------------------------------------------------------------')
        print('Excepcion al instanciar Detector, Esta presente el fichero model-x.x.pth?')
        print('Si no es asi ejecutar descargaModelo.py en el actual directorio')
        print('-------------------------------------------------------------------------')
        raise

    # Procesado de las mascaras binarias generadas y generacion del grafico Plotly
    try:
        fig = px.imshow(im)
        fig.update_traces(hoverinfo='skip')
        listTipos = list()
        confianzas = dt.getConfidence(salida)
        maskTotal = np.zeros_like(masks[0])
        numeroDefecto = 0

        # Se recorren las mascaras de cada error y se obtiene el area de cada una con regionprops
        for i in range(len(masks)):
            numeroDefecto +=1
            mask = masks[i]
            maskTotal = maskTotal + mask
            labels = measure.label(mask)
            props = measure.regionprops(labels, mask)
            label = props[0].label
            contour = measure.find_contours(labels == label, 0.5)[0] # Contorno del defecto binario
            y, x = contour.T

            # Se obtiene el atributo area y se clasifica segun tamaño
            area = getattr(props[0], "area")
            if area >= 200:
                tipo = ('Big')
                listTipos.append(tipo)
            elif area >= 100:
                tipo = ('Medium')
                listTipos.append(tipo)
            else:
                tipo = ('Small')
                listTipos.append(tipo)

            # Informacion mostrada al pasar el cursor por el defecto actual
            hoverinfo = ''
            hoverinfo += f'{"Área"}: {area:.2f}
'
            hoverinfo += f'{"Confianza"}: {"{:.2%}".format(confianzas[i])}
'
            hoverinfo += f'{"Tipo"}: {tipo}
'
            fig.add_trace(go.Scatter(
                x=x, y=y, name=numeroDefecto,
                mode='lines', fill='toself', showlegend=True,
                hovertemplate=hoverinfo, hoveron='points+fills'))
    except Exception as e:
        print('-----------------------------------------------------')
        print('Excepcion al generar mascaras, Ha habido detecciones?')
        print('-----------------------------------------------------')
        raise

    nombreGraph = "./static/uploads/graph_" + \
        filename[:-4] + "_" + fecha + ".html"
    fig.write_html(nombreGraph)

    # Como control se comprueba que los valores esten entre 0-1
    maskTotal[maskTotal > 1] = 1
    mascaraImagen = Image.fromarray(maskTotal)

    session['mascaraBinaria'] = './static/uploads/'+filename+'MB.png'
    mascaraImagen.save('./static/uploads/'+filename+'MB.png')

    # Generando registro en CSV
    numErrores = Counter(listTipos)

    # Dependiendo de la existencia del CSV, se añade fila, acumula en una existente o se crea dicho fichero
    if os.path.isfile('registro.csv'):
        df = pd.read_csv('registro.csv', index_col=0).copy()
        if fechaRegistro in df.Fecha.unique():
            for i in range(len(df.Fecha)):
                if df.Fecha[i] == fechaRegistro:
                    df.iat[i, 0] += 1
                    df.iat[i, 2] += numErrores['Small']
                    df.iat[i, 3] += numErrores['Medium']
                    df.iat[i, 4] += numErrores['Big']
            df.to_csv(r'registro.csv')

        else:
            df = pd.read_csv('registro.csv', index_col=0).copy()
            data = [{'N':1,'Fecha':fechaRegistro, 'Small':numErrores['Small'], 'Medium':numErrores['Medium'], 'Big':numErrores['Big']}]
            df = df.append(data, ignore_index=True,sort=False)
            df.to_csv(r'registro.csv')

    else:
        data = [{'N':1,'Fecha':fechaRegistro, 'Small':numErrores['Small'], 'Medium':numErrores['Medium'], 'Big':numErrores['Big']}]
        df = pd.DataFrame(data)
        df.to_csv(r'registro.csv')

    # Generacion del grafico de lineas Plotly
    dfc = pd.read_csv('registro.csv')
    df = dfc.copy()
    tope = df.iloc[:,2:5].sum(axis=1).max() + 5 # Valor mas alto en todos los ejes y para ajustar el tamaño del grafico, margen de 5

    fig = go.Figure()

    areaSmall = go.Scatter(
     x= df['Fecha'], y = df['Small'],
     name = 'Defectos Pequeños',
     mode = 'lines',
     line=dict(width=0.5, color='orange'),
     stackgroup = 'one')

    areaMedium = go.Scatter(
        x= df['Fecha'], y = df['Medium'],
        name = 'Defectos Medianos',
        mode = 'lines',
        line=dict(width=0.5, color='green'),
        stackgroup = 'one')

    areaBig= go.Scatter(
        x= df['Fecha'], y = df['Big'],
        name = 'Defectos Grandes',
        mode = 'lines',
        line=dict(width=0.5, color='red'),
        stackgroup = 'one')

    linea = go.Scatter(
        x=df['Fecha'],
        y=df['N'],
        mode='lines+markers',
        name='Imagenes Procesadas',
        line=dict(width=1, color='blue', dash="dashdot"),
        yaxis='y2'
    )

    fig = make_subplots(specs=[[{"secondary_y": True}]])

    fig.add_trace(areaSmall)
    fig.add_trace(areaMedium)
    fig.add_trace(areaBig)
    fig.add_trace(linea,secondary_y=True)

    fig.update_layout(title = "Histórico de Defectos", hovermode="x")

    fig.update_xaxes(
        title_text = 'Fecha',
        title_font=dict(size=16, family='Verdana', color='black'),
        tickfont=dict(family='Calibri', color='darkred', size=14))

    fig.update_yaxes(
        range=[0,tope],
        title_text = "Defectos",
        title_font=dict(size=16, family='Verdana', color='black'),
        tickfont=dict(family='Calibri', color='darkred', size=14))

    fig.update_yaxes(
        range=[0,tope],
        title_text = "Imagenes Procesadas",
        title_font=dict(size=16, family='Verdana', color='blue'),
        tickfont=dict(family='Calibri', color='blue', size=14), secondary_y=True)

    nombreHistorico = "./static/uploads/graficoHistorico.html"
    fig.write_html(nombreHistorico)

    session['resultado'] = nombreGraph
    session['widthHTML'] = anchuraImagen
    session['heightHTML'] = alturaImagen

    return render_template("deteccion.html",
                           mostrar_preview=False,
                           uploading=False,
                           mostrar_resultado=True,
                           conDefectos = True,
                           result=session['resultado'],
                           anchoGrafico=anchuraImagen,
                           altoGrafico=alturaImagen)

# Se acede al contenido de la variable sesion que apunta al grafico generado y se envia para descarga
@app.route("/descargarDinamico")
def descargarDinamico():
    ficheroHTML = session['resultado']
    filename = session['filename']
    return send_file(ficheroHTML, attachment_filename=filename[:-4] + ".html", as_attachment=True)

# Se compone la imagen original junto con la mascara binaria y se descarga
@app.route("/descargarComposicion")
def descargarComposicion():
    filename = session['filename']
    original = session['destino']
    mascaraBinaria = session['mascaraBinaria']

    im = Image.open(original)
    im2 = Image.open(mascaraBinaria)

    fig = plt.figure(figsize=(100, 100))

    a = fig.add_subplot(2, 1, 1)
    plt.axis('off')
    imgplot = plt.imshow(im)
    plt.axis("tight")
    plt.gca().set_aspect('equal')

    a = fig.add_subplot(2, 1, 2)
    plt.axis('off')
    imgplot = plt.imshow(im2)
    plt.axis("tight")
    plt.gca().set_aspect('equal')

    plt.subplots_adjust(wspace=0, hspace=0) # Se elmiinan margenes

    tempFig = BytesIO() # Con BytesIO se almacena en memoria en lugar de tener que generar un fichero cada vez, ahorrando espacio

    plt.savefig(tempFig, pad_inches=0, bbox_inches='tight', format='png')
    tempFig.seek(0)
    return send_file(tempFig, mimetype="image/png", attachment_filename=filename[:-4] + "_CMP.png", as_attachment=True)

# Descarga de la mascara binaria
@app.route("/descargarMascara")
def descargarMascara():
    mascaraBinaria = session['mascaraBinaria']
    filename = session['filename']
    return send_file(mascaraBinaria, attachment_filename=filename[:-4] + "_MB.png", as_attachment=True)

# Carga de la seccion del historico
@app.route("/hist")
def hist():
    return render_template("historico.html", urlGraph='./static/uploads/graficoHistorico.html')

# Carga del FAQ de la web
@app.route("/faq")
def faq():
    return render_template("faq.html")

# Se comprueba la version local del modelo presente en la aplicacion
@app.route('/checkModelVersion', methods=['POST'])
def checkModelVersion():
    ficheros = os.listdir()
    ficheros = [m for m in ficheros if 'modelo' in m and '.pth' in m] # Debe de tener la palabra y extension adecuados

    versionLocalMasReciente, versionLocalMasRecienteTxt = getMostRecentVersion(
        ficheros)

    if os.path.exists("modelos.json"):
        os.remove("modelos.json") # Si existe el fichero y puede no estar actualizado, se elimina

    ficheroJson = wget.download('https://raw.githubusercontent.com/fyi0000/TFG-GII-20.04/main/modelos.json')
    with open("modelos.json", "r") as fich:
        dictModelos = json.load(fich)

    # Se elmina el punto entre las versiones del formato 0.3 quedando solo 3, que es inferior a 1.0 que quedaria 10
    versiones = [int(v['version'].replace('.','')) for v in dictModelos['modelos']]
    versionesTxt = [v['version'] for v in dictModelos['modelos']]

    lastVersion = max(versiones)
    lastVersionTxt = versionesTxt[versiones.index(lastVersion)]
    url = str(dictModelos['modelos'][versiones.index(lastVersion)]['url'])

    # Si la version local es igual o posterior a la version remota, se notifica que esta actualizado
    if versionLocalMasReciente >= lastVersion:
        nombreFichero = 'modelo-'+lastVersionTxt+'.pth'
        session['modelo'] = nombreFichero
        return jsonify(status = 'Updated', recentVersion=lastVersionTxt, oldVersion = versionLocalMasRecienteTxt)

    # Por el contrario, se actualiza el nombre del modelo a descargar para la actualizacion
    session['urlUpdate'] = url
    session['versionUpdate'] = lastVersionTxt
    nombreFichero = 'modelo-'+versionLocalMasRecienteTxt+'.pth'
    session['modelo'] = nombreFichero
    return jsonify(status='Outdated', recentVersion=lastVersionTxt, oldVersion = versionLocalMasRecienteTxt)

# Se actualiza a la ultima version el modelo
@app.route('/updateModel', methods=['POST'])
def updateModel():
    lastVersionTxt = session['versionUpdate']
    url = session['urlUpdate']
    nombreFichero = 'modelo-'+lastVersionTxt+'.pth'
    session['modelo'] = nombreFichero
    gdown.download(url, output='./'+nombreFichero, quiet=True)
    ficheros = os.listdir()
    ficheros = [m for m in ficheros if 'modelo' in m and '.pth' in m]

    versionLocalMasReciente, versionLocalMasRecienteTxt = getMostRecentVersion(
        ficheros)

    if (lastVersionTxt == versionLocalMasRecienteTxt):
        return jsonify(status='OK', message='Modelo actualizado a la version '+ versionLocalMasRecienteTxt)

    return jsonify(status='Error', message='No se ha podido actualizar el modelo.')

# Metodo auxiliar que busca en una lista el valor numerico mas alto de version y devuelve el mismo y en cadena
def getMostRecentVersion(list):
    masReciente = 0
    masRecienteTxt = ''
    for e in list:
        version = re.findall("[\\b\d\\b]", e) # Expresion regular que detecta del nombre modelo-X.X la seccion X.X
        versionNumber = int(''.join(version))
        if versionNumber > masReciente:
            masReciente = versionNumber
            masRecienteTxt = '.'.join(version)

    return masReciente, masRecienteTxt

# Ejecucion en el puerto local indicado
if __name__ == "__main__":
    app.run(host='0.0.0.0')


#Use a greedy algorithm to search for the best motif.
bestmotifs = []
length, num = map(int, input("").split(" "))
dna = []
# append all the dna strings
for k in range(num):
    dna.append(input(""))
#start with bestmotifs as the set of all motifs.
for m in dna:
    bestmotifs.append(m[0:length])
#We score motifs against consensus string formed from scores.
def scoreMotifs(scores):
    consensus = ""
    count = 0
    for l in range(len(scores[0])):
        tempString= ""
        for a in scores:
            tempString = tempString + a[l]
        a = tempString.count("A")
        c = tempString.count("C")
        g = tempString.count("G")
        t = tempString.count("T")
        y = max(a, c, g, t)
        if(y==a):
            consensus = consensus + "A"
        elif(y==c):
            consensus = consensus + "C"
        elif(y==g):
            consensus = consensus + "G"
        elif(y==t):
            consensus = consensus + "T"
    for m in range(len(scores[0])):
        for xd in scores:
            if(xd[m]!=consensus[m]):
                count = count + 1

    return count
#generate motif profile
for j in range(len(dna[0])-length+1):
    motifList= [dna[0][j:j+length]]

    for y in range(1, num):
        profile = [[], [], [], []]
        for itera in range(length):
            profile[0].append(0)
            profile[1].append(0)
            profile[2].append(0)
            profile[3].append(0)
        for motif in motifList:
            for l in range(length):
                if(motif[l]=="A"):
                    profile[0][l] = profile[0][l]+1
                elif(motif[l]=="C"):
                    profile[1][l]=profile[1][l] + 1
                elif(motif[l]=="G"):
                    profile[2][l] = profile[2][l] + 1
                elif(motif[l]=="T"):
                    profile[3][l] = profile[3][l] + 1
        newMotif = ""
        mostProb = -1
        for move in range(len(dna[y])-length+1):
            currentProb = 1
            for stop in range(length):
                if(dna[y][move+stop]=="A"):
                    currentProb = currentProb*profile[0][stop]
                elif(dna[y][move+stop]=="C"):
                    currentProb = currentProb*profile[1][stop]
                elif(dna[y][move+stop]=="G"):
                    currentProb = currentProb*profile[2][stop]
                elif(dna[y][move+stop]=="T"):
                    currentProb = currentProb * profile[3][stop]
            if(currentProb>mostProb):
                mostProb = currentProb
                newMotif = dna[y][move:move+length]
        motifList.append(newMotif)
    if(scoreMotifs(motifList)<scoreMotifs(bestmotifs)):
        bestmotifs = motifList
for m in bestmotifs:
    print(m)