#!/usr/bin/env python3
from tkinter import *
import os, webbrowser
import regex as re
import rsspider

class Application:
    def __init__(self, master=None):
        self.results = []
        # --------------------------------------------

        self.primeiroContainer = Frame(master)
        self.primeiroContainer["pady"] = 10
        self.primeiroContainer.pack()

        self.titulo = Label(self.primeiroContainer, text="RSSpider")
        self.titulo["font"] = ("Comic Sans", "18", "bold")
        self.titulo["fg"] = "red"
        self.titulo.pack()

        # --------------------------------------------

        self.segundoContainer = Frame(master)
        self.segundoContainer["padx"] = 20
        self.segundoContainer.pack()

        self.refresh = Button(self.segundoContainer, text = "Refresh", font = ("Calibri", "16"), fg = "black", command= lambda : self.refreshFeed())
        self.refresh["width"] = 20
        self.refresh.pack()

        self.mensagem_refresh = Label(self.segundoContainer, text="", font=("Arial", "12"))
        self.mensagem_refresh.pack()

        # --------------------------------------------

        self.terceiroContainer = Frame(master)
        self.terceiroContainer["padx"] = 20
        self.terceiroContainer["pady"] = 20
        self.terceiroContainer.pack()

        self.query = Label(self.terceiroContainer,text="Search Query", font=("Calibri", "15"))
        self.query.pack(side=LEFT)

        self.query_string = Entry(self.terceiroContainer)
        self.query_string["width"] = 40
        self.query_string["font"] = ("Calibri", "15")
        self.query_string.pack(side=LEFT)

        self.search = Button(self.terceiroContainer, text = "Search", font = ("Calibri", "15"), fg = "black", command = self.searchQuery)
        self.search["width"] = 20
        self.search.pack()

        self.msg_search = Label(self.terceiroContainer, text="", font=("Arial", "12"))
        self.msg_search.pack(side=BOTTOM)

        # --------------------------------------------

        self.quartoContainer = Frame(master)
        self.quartoContainer["padx"] = 20
        self.quartoContainer["pady"] = 20
        self.quartoContainer.pack()

        self.results_label = Label(self.quartoContainer,text="Search Results", font=("Calibri", "18", "bold"))
        self.results_label.pack()

    def refreshFeed(self):
        rsspider.refreshDB()
        self.mensagem_refresh["text"] = "Feed refresh done!"

    def searchQuery(self):
        for prev_res in self.quartoContainer.winfo_children():
            if isinstance(prev_res, Button):
                prev_res.destroy()
        query = self.query_string.get()
        query = re.sub(r'\p{punct}', r'', query)
        query = list(filter(lambda x: len(x)>0, re.split(r'\s+', query)))       #remove empty query terms
        if len(query)==0:
            self.msg_search["text"] = "Bad query for the search. Try again!"
        else:
            self.results = rsspider.procRequest(query)
            self.msg_search["text"] = "Search done. Look for your results!"
            for result in self.results:
                resfield = Button(self.quartoContainer, text=result, font = ("Calibri", "12"), command= lambda result=result: self.openDocument(rsspider.directory+result))
                resfield.pack()

    def openDocument(self, filename):
        webbrowser.open('file://' + os.path.realpath(filename))

root = Tk()
root.title("RSSpider")
root.update_idletasks()
Application(root)
root.mainloop()


from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.db import models

# Create your models here.

class UserDetails(models.Model):
    user_id = models.ForeignKey(User,null=True, on_delete=models.DO_NOTHING)
    wallet = models.CharField(max_length=100, null=True)

class Node(models.Model):
    user_id = models.ForeignKey(User, null=True, on_delete=models.DO_NOTHING)
    parent_folder_id = models.IntegerField(null=True)
    folder_id = models.BigIntegerField(null=True)
    is_folder = models.BigIntegerField(null=True)
    name = models.CharField(max_length=100, null=True)
    location =  models.CharField(max_length=200, null=True)
    type = models.CharField(max_length=50, null=True)
    last_modified = models.DateField(null=True)


#!/usr/bin/env python3
# coding:utf-8
import time, unittest
from selenium import webdriver

class BaiduSearch(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Firefox()
        self.driver.maximize_window()
        self.driver.implicitly_wait(8)

    def tearDown(self):
        self.driver.quit()

    def test_baidu_search(self):
        self.driver.get("https://www.baidu.com")
        self.driver.find_element_by_id("kw").send_keys("selenium")
        time.sleep(5)
        self.driver.find_element_by_id("kw").clear()
        time.sleep(3)
        try:
            assert 'selenium' in self.driver.title
            print("Test pass!")
        except Exception as e:
            print("Test fail!", format(e))

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


# !/usr/bin/env python3

# encoding: utf-8
import requests
import json
import sys

host = "127.0.0.1"
port = 8500

# consul中微服务名称
serviceNames = ""

def get_service():
    url = 'http://' + host + ':' + str(port) + '/v1/agent/services'
    data = requests.get(url).json()
    jsonStr = json.dumps(data)
    print('json ' + jsonStr)
    keys = []
    for k in data:
        serviceName = data[k]['Service']
        if serviceName in serviceNames:
            print(data[k]['Service'])
            print(data[k]['ID'])
            keys.append(k)
    return keys

def del_service(keys):
    url = 'http://' + host + ':' + str(port) + '/v1/agent/service/deregister/'
    for sid in keys:
        requests.put(url + sid)
        print('删除 ' + sid)

# python3 main.py 127.0.0.1 application-yierbao-sweb
if __name__ == '__main__':
    if len(sys.argv) < 3:
        print("请输入：python3 ", sys.argv[0], "[ip] [service-name1,service-name2...]")
    else:
        host = sys.argv[1]
        serviceNames = sys.argv[2]
        keys = get_service()
        del_service(keys)


from manim import *

def draw_line_width(w,dir=RIGHT):
    return Line(ORIGIN-dir/2*w , ORIGIN+dir/2*w)

class Jop(Scene):
    def construct(self):
        bitch = Rectangle(width = 4, height = 3, stroke_color = WHITE)
        bitch.set_fill(BLUE, opacity=.5)
        self.play(Write(bitch), run_time=2)

        self.wait(1)
        newtext = Text("Wiggle",font='Calibri', font_size = 77)
        newtext.set_fill(WHITE, opacity=1)
        self.add(newtext)
        self.play(Write(newtext), run_time=1)
        self.wait(1)

        self.play(Unwrite(newtext), run_time=2)
        self.remove(newtext)
        self.wait(1)

        corcle = Circle(radius = 3)
        corcle.set_fill(PINK, opacity=.2)
        self.play(Write(corcle), run_time=.7)

        self.wait(1)

        hlighted = Circle(radius = 3, stroke_color = WHITE)
        hlighted.set_fill(YELLOW, opacity=.7)
        self.play(Write(hlighted))
        self.wait(1)

        leeen = draw_line_width(7,UP)
        leeen.move_to([3.15,0,0])
        self.add(leeen)
        self.wait(1)
        self.play(leeen.animate.move_to([-3.15,0,0]))
        self.wait(.5)
        self.play(leeen.animate.move_to([3.15,0,0]))
        self.wait(.5)
        self.play(leeen.animate.move_to([-3.15,0,0]))
        self.wait(.5)
        self.play(leeen.animate.rotate(PI/2))
        self.wait()


# Thomas Calhoun
# homework #9
# tjcalhoun@alaska.edu  31 Mar 2016
# Python 3.5.1

"""
Calhoun Banking.

Watching your money, so you don't have to!
"""

#######################################################################################################################
#  Definition of some menu text to keep function lines at a minimal
#######################################################################################################################

menuTitle = 'Calhoun Banking Terminal'
menuText = '''
Please use the number keys to select from one of the following:

1 - Check Balance
2 - Withdraw Funds
3 - Deposit Funds
4 - Transfer Funds

0 - Logoff
'''

#######################################################################################################################
#  Global Variable pool
#######################################################################################################################

savingsBalance = 10000.00
checkingBalance = 1000.00
bankAccounts = {1337: "-notset-"}
acctGet = 0

#######################################################################################################################
#  Definition of the Deposit Funds function
#######################################################################################################################

def deposit():  # Deposit, Withdraw, and Transfer, are varied copies of the following.
    """
    Deposit Funds
    Where does it come from?

    The cloud, man... The cloud.
    """
    global savingsBalance, checkingBalance
    print("\n\nPlease select the account to deposit TO:\n(C) - Checking\n(S) - Savings\n")
    while True:  # Had to enforce this with a loop to control incorrect input
        askfracct = input("Selection >>> ").lower()
        if askfracct == "c":  # Conditional sets a local variable for chosen account.
            dep = checkingBalance
            print("\n", "Checking Account selected...".center(80))
            break
        elif askfracct == "s":
            dep = savingsBalance
            print("\n", "Savings Account selected...".center(80))
            break
        else:
            print("\nChoice not recognized, please try again!\n")
    while True:
        print("\n\n(Type in an amount of \"000\" to cancel)\n\n")
        amt = float(input("Amount of funds to transfer: $"))
        if amt == 000:
            print("\n\n\n", "--==WITHDRAWAL CANCELLED==--".center(80), "\n\n\n")
            main()
        else:
            break

    if askfracct == "c":  # this conditional reassigns out local variable with calculations to the global variable.
        checkingBalance = dep + amt
    elif askfracct == "s":
        savingsBalance = dep + amt

    print("Withdrawal complete...")
    print("\n    Account Summary for {}:".format(bankAccounts[acctGet]))
    print("\nChecking: %.2f" % checkingBalance)  # Getting the float formatting to work meant breaking apart each line
    print("Savings: %.2f\n\n" % savingsBalance)

#######################################################################################################################
#  Definition of the Withdraw Funds function
#######################################################################################################################

def withdraw():
    """
    Withdraw Funds.
    Note: No actual money will come out of your computer.
    Not even Bitcoin.

    I tried, and then cried myself to sleep.
    *sniff* Oh no... here we go again...
    """
    global savingsBalance, checkingBalance
    print("\n\nPlease select the account to withdraw FROM:\n(C) - Checking\n(S) - Savings\n")
    while True:
        askfracct = input("Selection >>> ").lower()
        if askfracct == "c":
            wdraw = checkingBalance
            print("\n", "Checking Account selected...".center(80))
            break
        elif askfracct == "s":
            wdraw = savingsBalance
            print("\n", "Savings Account selected...".center(80))
            break
        else:
            print("\nChoice not recognized, please try again!\n")
    while True:
        print("\n\n(Type in an amount of \"000\" to cancel)\n\n")
        amt = float(input("Amount of funds to transfer: $"))
        if amt > wdraw:
            print("\n\n  ###  Error! Insufficient Funds...  ###")
        elif amt == 000:
            print("\n\n\n", "--==WITHDRAWAL CANCELLED==--".center(80), "\n\n\n")
            main()
        else:
            break

    if askfracct == "c":
        checkingBalance = wdraw - amt
    elif askfracct == "s":
        savingsBalance = wdraw - amt

    print("Withdrawal complete...")
    print("\n    Account Summary for {}:".format(bankAccounts[acctGet]))
    print("\nChecking: %.2f" % checkingBalance)
    print("Savings: %.2f\n\n" % savingsBalance)

#######################################################################################################################
#  Definition of the Transfer Funds function
#######################################################################################################################

def transfer():
    """
    Transfer Funds.
    Think of it as shuffling cards, just only with your
    hard earned money.

    At least it doesnt say "Read em' and weep!"
    """
    global checkingBalance, savingsBalance
    print("\n\nPlease select the account to transfer FROM:\n(C) - Checking <TO> Savings\n"
          "(S) - Savings <TO> Checking\n")
    while True:
        askfracct = input("Selection >>> ").lower()
        if askfracct == "c":
            wdraw = checkingBalance
            dep = savingsBalance
            print("\n", "Checking -to- Savings Account selected...".center(80))
            break
        elif askfracct == "s":
            wdraw = savingsBalance
            dep = checkingBalance
            print("\n", "Savings -to- Checking Account selected...".center(80))
            break
        else:
            print("\nChoice not recognized, please try again!\n")
    while True:
        print("\n\n(Type in an amount of \"000\" to cancel)\n\n")
        amt = float(input("Amount of funds to transfer: $"))
        if amt > wdraw:
            print("\n\n  ###  Error! Insufficient Funds...  ###")
        elif amt == 000:
            print("\n\n\n", "--==TRANSFER CANCELLED==--".center(80), "\n\n\n")
            main()
        else:
            break

    if askfracct == "c":
        checkingBalance = wdraw - amt
        savingsBalance = dep + amt
    elif askfracct == "s":
        savingsBalance = wdraw - amt
        checkingBalance = dep + amt

    print("Withdrawal complete...")
    print("\n    Account Summary for {}:".format(bankAccounts[acctGet]))
    print("\nChecking: %.2f" % checkingBalance)
    print("Savings: %.2f\n\n" % savingsBalance)

#######################################################################################################################
# Definition of the Main Menu
#######################################################################################################################

def main():
    """
    The Driving force of most programs and restaurants...
    The Menu!
    """
    global savingsBalance,checkingBalance
    while True:
        print("\n\n", "...MAIN MENU...".center(80), "\n\n", menuText)
        sel = int(input("Selection >>>  "))
        if sel == 0:
            print("\n\n","Logoff Successful...".center(80), "\n", "Have a nice day!".center(80))
            break
        elif sel == 1:  # A short snippet of code is all that is required for this option
            print("\n    Account Summary for {}:".format(bankAccounts[acctGet]))
            print(
                "\nChecking: %.2f" % checkingBalance)
            print("Savings: %.2f\n\n" % savingsBalance)
        elif sel == 2:
            withdraw()
        elif sel == 3:
            deposit()
        elif sel == 4:
            try:
                transfer()
            except ValueError:
                print("\n\nUh Oh!\nOnly numbers will be recognized as input.\n-Please try again!\n\n")
                transfer()
            except Exception as err:
                print("\n\nUh Oh! A {} Error Occurred!\nThis may have happened because of incorrect input."
                      "\n-Verify your response before pressing <Enter>. Please try again!\n\n".format(err))
                transfer()
        else:
            print("\n\nSorry! Input not recognized, please choose from the following menu options!\n\n")

#######################################################################################################################
# Call to initiate program
#######################################################################################################################
if __name__ == '__main__':

    # Why so many functions? Error Handling. If I call the target function again once it's handled an error,
    #     I've noticed that another exception afterward may not get handled...
    #     So, in its own function - it operates as a crude loop (at least that's how I picture it).
    # Please reference the docstring for each function to understand my interpretation of it pythonic flow. Heh.

    def start():
        """
        Start Function initiates the Main Menu, only after
        Account Authentication has taken place.
        Error handling in place for a secure start.
        """
        try:
            main()
        except ValueError:
            print("\n\nUh Oh!\nOnly numbers will be recognized as input.\n-Please try again!\n\n")
            start()

    def acct():
        """
        Account Function screens the user for login credentials.
        Since security is our topmost priority, we only require
        your account number (which may or may not resemble a
        classic Pixar movie easter egg reference).
        """
        global bankAccounts, acctGet
        while True:
            print(menuTitle.center(80),"\n\n", "Welcome! Please log in...".center(80), "\n\n")
            acctGet = int(input("User Account Number  >>> "))
            if acctGet in bankAccounts.keys():  # may try 'if acctGet in bankAccounts.keys():'
                if bankAccounts[acctGet] == "-notset-":  # Name prompt, for user to set up their account.
                    nSet = input("\n\nWelcome, this is your first login, so please type your full name!\n"
                                 "Name: ").title()
                    bankAccounts[acctGet] = nSet  # Saves account name.
                    print("\n\nHello {}! Thank you for choosing Calhoun Banking!\n\n".format(bankAccounts[acctGet]))
                print("Welcome {}!".format(bankAccounts[acctGet]))
                break
            else:
                print("\n\nAccount was not found... please try again!\n\n")

        start()

    def acct_handler():
        """
        Account Handler Function is the error control method,
        just in case someone decides "casablanca" would be a
        good account to guess into (it's not).
        """
        try:
            acct()
        except KeyError:  # Since I'm using a dict to hold account info
            print("\n\nAccount was not found... please try again!\n\n")
            acct_handler()
        except ValueError:  # Since account input is a forced integer
            print("\n\nYou needed to type a number... please try again!\n\n")
            acct_handler()

    # The line starts it all.
    acct_handler()


from typing import List
'''
In an alien language, surprisingly they also use english lowercase letters, but possibly in a different order. The order
of the alphabet is some permutation of lowercase letters.

Given a sequence of words written in the alien language, and the order of the alphabet, return true if and only if the
given words are sorted lexicographicaly in this alien language.

Example 1:
Input: words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz"
Output: true
Explanation: As 'h' comes before 'l' in this language, then the sequence is sorted.

Example 2:
Input: words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz"
Output: false
Explanation: As 'd' comes after 'l' in this language, then words[0] > words[1], hence the sequence is unsorted.

Example 3:
Input: words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz"
Output: false
Explanation: The first three characters "app" match, and the second string is shorter (in size.) According to
lexicographical rules "apple" > "app", because 'l' > '∅', where '∅' is defined as the blank character which is less
than any other character (More info).

Constraints:
    1 <= words.length <= 100
    1 <= words[i].length <= 20
    order.length == 26
    All characters in words[i] and order are English lowercase letters.
'''

class Solution:
    def isAlienSorted(self, words: List[str], order: str) -> bool:

        # Make a hash table to lookup the order
        order_hashtable = {letter: index for index, letter in enumerate(order)}

        # xrange is really fast apparently so use it where you can
        # range is inclusive but we don't want to use the last position since we are comparing to the
        # next word in every step
        for i in range(len(words) - 1):
            word1 = words[i]
            word2 = words[i + 1]

            # An important thing to realize is that you only need to look for the first difference,
            # that is the point where you can determine sorted-ness and stop
            for letter_position in range(min(len(word1), len(word2))):
                if word1[letter_position] != word2[letter_position]:
                    if order_hashtable[word1[letter_position]] > order_hashtable[word2[letter_position]]:
                        return False
                    break
            else:
                if len(word1) > len(word2):
                    return False
        return True

mySolution = Solution()
mySolution.isAlienSorted()


import asyncio

import pytest
import requests
from binance import AsyncClient, Client
from ftx import FtxClient

@pytest.fixture
def event_loop():
    loop = asyncio.get_event_loop()
    yield loop
    loop.close()

def test_response_binance(event_loop):
    client = AsyncClient()
    response = event_loop.run_until_complete(
        client.get_order_book(symbol="BTCUSDT")
    )
    assert "bids" in response
    assert "asks" in response

def test_response_ftx():
    client = FtxClient()
    response = client.get_orderbook("BTC/USDT", 1)
    assert "bids" in response
    assert "asks" in response

def test_response_glm_btc():
    client = FtxClient()
    try:
        client.get_orderbook("GLM/BTC", 1)
        assert False
    except Exception as ex:
        pass

    client = Client()
    try:
        client.get_order_book(symbol="GLMBTC")
    except Exception as ex:
        print(ex)
        assert False


from math import factorial
import numpy as np
import attr
from scipy import ndimage, signal, optimize

_TOPHAT_FACTOR = 0.01 #025   #05
_MEDWINSIZE = 299
_MEDMMSIZE = 1991

def b(txt):
    """ return a binary string aka bytes """
    return txt.encode('UTF-8')

def smooth_signal( raw_signal ):
    """ smooth signal using savitzky_golay algorithm """
    return savitzky_golay( raw_signal, 11, 7 )

def correct_baseline( signal ):
    """ use tophat morphological transform to correct for baseline """

    return ndimage.white_tophat(signal, None,
                np.repeat([1], int(round(signal.size * _TOPHAT_FACTOR)))
            )

@attr.s
class NormalizedTrace(object):
    signal = attr.ib()
    baseline = attr.ib()
    mma = attr.ib()
    mmb = attr.ib()

def func_mm(x, a, b):
    """ Michaelis Menten kinetics equation -
        this has a nice property of passing initial value and plateau
    """
    return a*x/(b+x)

def normalize_baseline( raw ):
    """ return mean, median, sd and smooth signal """

    median_line = signal.medfilt(raw, [_MEDWINSIZE])
    baseline = signal.savgol_filter( median_line, _MEDWINSIZE, 7)
    corrected_baseline = raw - baseline
    np.maximum(corrected_baseline, 0, out=corrected_baseline)
    smooth = correct_baseline( signal.savgol_filter(corrected_baseline, 11, 7) )

    # perform michaelis-menten equation for baseline assessment
    mm_line = signal.medfilt(raw, [ _MEDMMSIZE ])
    xx = np.linspace(0, len(raw) )
    try:
        popt, pcov = optimize.curve_fit(func_mm, xx, mm_line)
    except:
        # michaelis menten are not appropriate for this scale
        popt = pcov = [0, 0]

    return NormalizedTrace( signal=smooth, baseline = baseline, mma = popt[0], mmb = popt[1] )

def search_peaks( signal, cwt_widths, min_snr ):
    """ returns [ (peak, height, area) ], ... ] """

    # find all peaks by cwt-based algorithm
    indices = find_peaks_cwt( signal, cwt_widths, min_snr=min_snr )

    if not indices:
        return []

    # find absolute heights

    raw_peaks = []
    for idx in indices:
        for i in range(3, -1, -1):
            try:
                height, index = max( [ (signal[i], i) for i in range(idx-3, idx+3) ] )
            except IndexError:
                continue
            break
        if height < params.min_height:
            continue
        if index < 0:
            continue
        raw_peaks.append( (index, height) )

    if not raw_peaks:
        return []

    # calculate area
    peaks = []
    for (peak, height) in raw_peaks:
        area, brtime, ertime = calculate_area( signal, peak, 5e-2 )
        peaks.append( (peak, height, area, brtime, ertime) )

    return peaks

def calculate_area(y, t, threshold):
    """ return (area, begin_rtime, end_rtime)
    """

    # right area
    data = y[t:]
    r_area, ertime, r_shared = half_area(data, threshold)

    # left area
    data = y[:t+1][::-1]
    l_area, brtime, l_shared= half_area(data, threshold)

    return ( l_area + r_area - y[t], t - brtime, ertime + t )

def half_area(y, threshold):
    """ return (area, ertime)
    """

    winsize = 3
    threshold = threshold/2
    shared = False
    area = y[0]
    edge = float(np.sum(y[0:winsize]))/winsize
    old_edge = 2 * edge

    index = 1
    limit = len(y)

    while edge > area * threshold and edge < old_edge and index < limit:
        old_edge = edge
        area += y[index]
        edge = float(np.sum(y[index:index+winsize]))/winsize
        index += 1
    if edge >= old_edge:
        shared = True
    index -= 1

    return area, index, shared

@attr.s
class TraceChannel(object):
    dye_name = attr.ib()
    dye_wavelength = attr.ib()
    raw_channel = attr.ib()
    smooth_channel = attr.ib()
    median = attr.ib()
    mean = attr.ib()
    sd = attr.ib()
    max_height = attr.ib()
    min_height = attr.ib()

def separate_channels( trace ):
    # return a list of [ 'dye name', dye_wavelength, numpy_array, numpy_smooth_baseline ]

    from fatools.lib.fautil.traceio import WAVELENGTH

    results = []
    for (idx, data_idx) in [ (1,1), (2,2), (3,3), (4,4), (5,105) ]:
        try:
            dye_name = trace.get_data(b('DyeN%d' % idx)).decode('UTF-8')
            #dye_wavelength = trace.get_data(b('DyeW%d' % idx))

            # below is to workaround on some strange dye names
            if dye_name == '6FAM': dye_name = '6-FAM'
            elif dye_name == 'PAT': dye_name = 'PET'
            elif dye_name == 'Bn Joda': dye_name = 'LIZ'

            try:
                dye_wavelength = trace.get_data(b('DyeW%d' % idx))
            except KeyError:
                dye_wavelength = WAVELENGTH[dye_name]

            raw_channel = np.array( trace.get_data(b('DATA%d' % data_idx)) )
            nt = normalize_baseline( raw_channel )

            results.append( TraceChannel(dye_name, dye_wavelength, raw_channel,
                            nt.signal, np.median(nt.baseline), np.mean(nt.baseline),
                            np.std(nt.baseline), np.max(nt.baseline), np.min(nt.baseline))
            )
        except KeyError:
            pass

    return results

def savitzky_golay(y, window_size, order, deriv=0, rate=1):
    r"""Smooth (and optionally differentiate) data with a Savitzky-Golay filter.
    The Savitzky-Golay filter removes high frequency noise from data.
    It has the advantage of preserving the original shape and
    features of the signal better than other types of filtering
    approaches, such as moving averages techniques.
    Parameters
    ----------
    y : array_like, shape (N,)
        the values of the time history of the signal.
    window_size : int
        the length of the window. Must be an odd integer number.
    order : int
        the order of the polynomial used in the filtering.
        Must be less then `window_size` - 1.
    deriv: int
        the order of the derivative to compute (default = 0 means only smoothing)
    Returns
    -------
    ys : ndarray, shape (N)
        the smoothed signal (or it's n-th derivative).
    Notes
    -----
    The Savitzky-Golay is a type of low-pass filter, particularly
    suited for smoothing noisy data. The main idea behind this
    approach is to make for each point a least-square fit with a
    polynomial of high order over a odd-sized window centered at
    the point.
    Examples
    --------
    t = np.linspace(-4, 4, 500)
    y = np.exp( -t**2 ) + np.random.normal(0, 0.05, t.shape)
    ysg = savitzky_golay(y, window_size=31, order=4)
    import matplotlib.pyplot as plt
    plt.plot(t, y, label='Noisy signal')
    plt.plot(t, np.exp(-t**2), 'k', lw=1.5, label='Original signal')
    plt.plot(t, ysg, 'r', label='Filtered signal')
    plt.legend()
    plt.show()
    References
    ----------
    .. [1] A. Savitzky, M. J. E. Golay, Smoothing and Differentiation of
       Data by Simplified Least Squares Procedures. Analytical
       Chemistry, 1964, 36 (8), pp 1627-1639.
    .. [2] Numerical Recipes 3rd Edition: The Art of Scientific Computing
       W.H. Press, S.A. Teukolsky, W.T. Vetterling, B.P. Flannery
       Cambridge University Press ISBN-13: 9780521880688
    """
    import numpy as np
    from math import factorial

    try:
        window_size = np.abs(np.int(window_size))
        order = np.abs(np.int(order))
    except ValueError as msg:
        raise ValueError("window_size and order have to be of type int")
    if window_size % 2 != 1 or window_size < 1:
        raise TypeError("window_size size must be a positive odd number")
    if window_size < order + 2:
        raise TypeError("window_size is too small for the polynomials order")
    order_range = range(order+1)
    half_window = (window_size -1) // 2
    # precompute coefficients
    b = np.mat([[k**i for i in order_range] for k in range(-half_window, half_window+1)])
    m = np.linalg.pinv(b).A[deriv] * rate**deriv * factorial(deriv)
    # pad the signal at the extremes with
    # values taken from the signal itself
    firstvals = y[0] - np.abs( y[1:half_window+1][::-1] - y[0] )
    lastvals = y[-1] + np.abs(y[-half_window-1:-1][::-1] - y[-1])
    y = np.concatenate((firstvals, y, lastvals))
    return np.convolve( m[::-1], y, mode='valid')

def smooth(x,window_len=11,window='hanning'):
    """smooth the data using a window with requested size.

    This method is based on the convolution of a scaled window with the signal.
    The signal is prepared by introducing reflected copies of the signal
    (with the window size) in both ends so that transient parts are minimized
    in the begining and end part of the output signal.

    input:
        x: the input signal
        window_len: the dimension of the smoothing window; should be an odd integer
        window: the type of window from 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'
            flat window will produce a moving average smoothing.

    output:
        the smoothed signal

    example:

    t=linspace(-2,2,0.1)
    x=sin(t)+randn(len(t))*0.1
    y=smooth(x)

    see also:

    numpy.hanning, numpy.hamming, numpy.bartlett, numpy.blackman, numpy.convolve
    scipy.signal.lfilter

    TODO: the window parameter could be the window itself if an array instead of a string
    NOTE: length(output) != length(input), to correct this: return y[(window_len/2-1):-(window_len/2)] instead of just y.
    """

    if x.ndim != 1:
        raise ValueError( "smooth only accepts 1 dimension arrays." )

    if x.size < window_len:
        raise ValueError( "Input vector needs to be bigger than window size." )

    if window_len<3:
        return x

    if not window in ['flat', 'hanning', 'hamming', 'bartlett', 'blackman']:
        raise ValueError( "Window is on of 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'")

    s=np.r_[x[window_len-1:0:-1],x,x[-1:-window_len:-1]]
    #print(len(s))
    if window == 'flat': #moving average
        w=np.ones(window_len,'d')
    else:
        w=eval('np.'+window+'(window_len)')

    y=np.convolve(w/w.sum(),s,mode='valid')
    return y


#!/usr/bin/env python3

import bs4
import os
import re

XML_PATH   : str = 'arq.xml'
HTML_DIR   : str = 'out/'
HTML_PATH  : str = 'index.html'
PATTERN    : re.Pattern = re.compile(r'(.+)\.xml$')
HTML_BEGIN : str = '''
<!DOCTYPE html>

        <meta charset="utf-8" />
'''
HTML_END   : str = '''

'''

def write_html(path : str, parent_tag : bs4.Tag):

    with open(path, 'w', encoding='utf-8') as hfh:

        hfh.write(HTML_BEGIN)
        hfh.write(f"\t\t<title>{path}</title>\n")
        hfh.write(f"\t\n\n")
        hfh.write('\t\n\n')

        for child in parent_tag.descendants:
            if child.string and child.name:
                hfh.write(f"\t\t
{child.name}: {child.string}
\n")

        hfh.write(HTML_END)

def main():

    def make_tuple(x : str) -> tuple[str, str]:
        basename : str = PATTERN.search(x)[1]
        return (f"{HTML_DIR}{x}", f"{HTML_DIR}{basename}.html")

    filenames : list[str] = map(
        make_tuple,
        filter(
            lambda x: PATTERN.search(x),
            os.listdir(HTML_DIR)
        )
    )

    for fn_tuple in filenames:

        xml_tree : bs4.BeautifulSoup

        with open(fn_tuple[0], 'r', encoding='utf-8') as xfh:

            xml_tree = bs4.BeautifulSoup(xfh, 'lxml-xml')

        parent_tag : bs4.Tag = xml_tree.ARQELEM

        write_html(fn_tuple[1], parent_tag)

if __name__ == '__main__':
    main()


import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pdb
from matplotlib.table import Table

def stext(ax,text):
    ax.text(0.9, 0.9, text, horizontalalignment='right', verticalalignment='top',transform=ax.transAxes)

def main():
    data = pd.DataFrame()
    # overall lag distribution, with total number of edges + filename
    #fig2 = plt.figure(2, figsize=(20,20))
    # lag counts vs # of edges above certain threshold, percentage, total number of edges

    for ind in range(2,5):
        fig1 = plt.figure(figsize=(20,20))
        filename = 'lag_df2_parse_biocyc_%s.pkl' % (ind)
        lag_df = pd.read_pickle(filename)

        lag_df['lag_counts'] = [len(x) if type(x) is list else 0 for x in lag_df['Lag'].tolist()]

        ax1 = fig1.add_subplot(2,2,1)
        bins = [x for x in range(0,30)]

        ax1.hist(lag_df['lag_counts'], normed=True, bins = bins, color='salmon', alpha=0.8)
        stext(ax1, 'Counts')
        ax2 = fig1.add_subplot(2,2,2)
        ax2.hist(lag_df['lag_std'].dropna(), normed=True, color='salmon', alpha=0.8)
        stext(ax2, 'Stdev')
        ax3 = fig1.add_subplot(2,2,3)
        ax3.hist(lag_df['lag_mean'].dropna(), normed=True, color='salmon', alpha=0.8)
        stext(ax3, 'Mean')
        ax4 = fig1.add_subplot(2,2,4)
        ax4.hist(lag_df['lag_median'].dropna(), normed=True, color='salmon', alpha=0.8)
        stext(ax4, 'Median')

        plt.savefig('lag_stats_biocyc_%s.png'%(ind))

        fig2 = plt.figure(figsize=(20,20))
        # get percentage of edges and number over thresholds

        lag_thresh = [0,1,2]
        count_thresh = [0,5,10,15,20,25]

        data = np.zeros([len(lag_thresh),len(count_thresh)])
        for idx,lag in enumerate(lag_thresh):
            for jdx,count in enumerate(count_thresh):
                items = lag_df[(lag_df['lag_counts'] >= count) & (lag_df['lag_mean'] >=lag)]
                data[idx][jdx] = len(items)

        p_data = data/len(lag_df)
        data = pd.DataFrame(data, index = lag_thresh, columns = count_thresh)
        p_data = pd.DataFrame(p_data, index = lag_thresh, columns = count_thresh)
        checkerboard_table(data)
        plt.savefig('lag_table_biocyc_%s.png'%(ind))
        checkerboard_table(p_data)
        plt.savefig('lag_table_p_biocyc_%s.png'%(ind))

        # get the distribution of lag counts (histogram)
        # the total number of edges

        # lag counts vs # of edges above certain threshold

def checkerboard_table(data, fmt='{:.2f}', bkg_colors=['yellow', 'white']):
    fig, ax = plt.subplots()
    ax.set_axis_off()
    tb = Table(ax, bbox=[0,0,1,1])

    nrows, ncols = data.shape
    width, height = 1.0 / ncols, 1.0 / nrows

    # Add cells
    for (i,j), val in np.ndenumerate(data):
        # Index either the first or second item of bkg_colors based on
        # a checker board pattern
        idx = [j % 2, (j + 1) % 2][i % 2]
        color = bkg_colors[idx]

        tb.add_cell(i, j, width, height, text=fmt.format(val),
                    loc='center', facecolor=color)

    # Row Labels...
    for i, label in enumerate(data.index):
        tb.add_cell(i, -1, width, height, text=label, loc='right',
                    edgecolor='none', facecolor='none')
    # Column Labels...
    for j, label in enumerate(data.columns):
        tb.add_cell(-1, j, width, height/2, text=label, loc='center',
                           edgecolor='none', facecolor='none')
    ax.add_table(tb)
    plt.ylabel('Lag Threshold')
    plt.xlabel('Count Threshold')
    return fig

if __name__ == '__main__':
    main()


#!/usr/bin/python -u
# -*- coding: latin-1 -*-
#
# Coin application in Z3
# From 'Constraint Logic Programming using ECLiPSe'
# pages 99f and 234 ff.
# The solution in ECLiPSe is at page 236.
#
# '''
# What is the minimum number of coins that allows one to pay _exactly_
# any amount smaller than one Euro? Recall that there are six different
# euro cents, of denomination 1, 2, 5, 10, 20, 50
# '''

#
# This Z3 model was written by Hakan Kjellerstrand (hakank@gmail.com)
# See also my Z3 page: http://hakank.org/z3/
#
#
from __future__ import print_function
import sys
from z3_utils_hakank import *

def main(type="optimize"):
  if type == "optimize":
      sol = Optimize()
  else:
      # sol = Solver()
      sol = SolverFor("QF_LIA")

  # data
  n = 6  # number of different coins
  variables = [1, 2, 5, 10, 25, 50]

  # declare variables
  x = [makeIntVar(sol, "x%i" % i, 0, 99) for i in range(n)]
  num_coins = makeIntVar(sol, "num_coins", 0, 99)

  # constraints

  # number of used coins, to be minimized
  sol.add(num_coins == Sum([x[i] for i in range(n) ] ))

  # Check that all changes from 1 to 99 can be made.
  c = 0
  for j in range(1, 100):
    tmp = [makeIntVar(sol,"tmp%i_%i" % (i,c), 0, 99) for i in range(n)]
    sol.add(scalar_product2(sol,tmp, variables) == j)
    [sol.add(tmp[i] <= x[i]) for i in range(n)]
    c += 1

  # objective
  if type == "optimize":
      sol.minimize(num_coins)

  # solution and search
  if type == "optimize":
      if sol.check() == sat:
        mod = sol.model()
        print("x: ", [mod.eval(x[i]) for i in range(n)])
        print("num_coins:", mod.eval(num_coins))
        print()
  else:
      num_solutions = 0
      while sol.check() == sat:
        num_solutions += 1
        mod = sol.model()
        print("x: ", [mod.eval(x[i]) for i in range(n)])
        print("num_coins:", mod.eval(num_coins))
        # sol.add([x[i] != mod.eval(x[i]) for i in range(n)])
        sol.add(num_coins < mod.eval(num_coins))
        print()
      print("num_solutions:", num_solutions)

if __name__ == "__main__":
  main("optimize") # 2.861s
  # main("solver") # 13.322s


from utils import *
from itertools import combinations
from math import comb, floor, ceil
import functools

def is_leaf(a):
    return isinstance(a, list) and all(isinstance(x, int) for x in a)

def infix(root):
    result = []
    def sub(root):
        if isinstance(root[0], int):
            result.append((root, 0))
        else:
            sub(root[0])
        if isinstance(root[1], int):
            result.append((root, 1))
        else:
            sub(root[1])
    sub(root)
    return result

def explode(a):
    inf = infix(a)
    def sub2(root, lvl):
        for i in [0, 1]:
            if lvl >= 3 and is_leaf(root[i]):
                tmp = root[i]
                root[i] = 0
                pos = next(i for i in range(len(inf)) if id(inf[i][0]) == id(tmp))
                if pos > 0:
                    l, p = inf[pos-1]
                    l[p] += tmp[0]
                if pos < len(inf)-2:
                    l, p = inf[pos+2]
                    l[p] += tmp[1]
                return True
            elif isinstance(root[i], list) and sub2(root[i], lvl+1):
                return True
        return False
    exploded = sub2(a, 0)
    return exploded

def split(a):
    def sub(root):
        if isinstance(root[0], int) and root[0] >= 10:
            root[0] = [floor(root[0] / 2), ceil(root[0] / 2)]
            return True
        elif isinstance(root[0], list) and sub(root[0]):
            return True
        elif isinstance(root[1], int) and root[1] >= 10:
            root[1] = [floor(root[1] / 2), ceil(root[1] / 2)]
            return True
        elif isinstance(root[1], list) and sub(root[1]):
            return True
        return False
    return sub(a)

def reduce(a):
    reduced = explode(a) or split(a)
    while reduced:
        reduced = explode(a) or split(a)

def add(a, b):
    tmp = [eval(repr(a)), eval(repr(b))]
    reduce(tmp)
    return tmp

def magnitude(a):
    if isinstance(a, int):
        return a
    return 3*magnitude(a[0]) + 2*magnitude(a[1])

lines = [eval(line) for line in readlines('18_input.txt')]
s = functools.reduce(add, lines)
print('Star 1:', magnitude(s))
print('Star 2:', max(max(magnitude(add(a, b)), magnitude(add(b, a))) for a, b in combinations(lines, 2)))


import sys
from collections import deque

n,m,k = map(int,sys.stdin.readline().split())

graph = [[0 for _ in range(m)] for _ in range(n)]

for _ in range(k):
    a,b = map(int,sys.stdin.readline().split())
    graph[a-1][b-1] = 1

dx = [-1,1,0,0]
dy = [0,0,1,-1]

visit = [[0 for _ in range(m)] for _ in range(n)]

def bfs(i,j):
    queue = deque()
    queue.append([i,j])
    visit[i][j] = 1
    sum = 1 # 넓이
    while queue:
        x,y = queue.popleft()
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            if 0 <= nx < n and 0 <= ny < m and visit[nx][ny] == 0:
                if graph[nx][ny] == 1:
                    visit[nx][ny] = 1
                    queue.append([nx,ny])
                    sum += 1
    return sum

result = 0 # 최대값 저장하는 변수
for i in range(n):
    for j in range(m):
        if graph[i][j]==1 and visit[i][j] == 0:
            result = max(result,bfs(i,j)) # 최대값
print(result)


#!/usr/bin/python

import string
import argparse
import random
import unidecode
import re

import load as Loader
from dictionaries import *
import onomono

from propernoun import *
from onomono import *
import unicodedata

from nltk.util import ngrams
import nltk
import nltk.tag

from textstat.textstat import textstat

from sklearn.preprocessing import MultiLabelBinarizer
from sklearn.feature_extraction.text import *
import sklearn

from collections import Counter
from sets import Set

import ujson

#import hmm_model as markov

#NUM_GRAMS = 5
#MIN_PHRASE = 7
NUM_FICS = 10
OUTFILE="out.txt"

parser = argparse.ArgumentParser(description='Analyze scraped data.')
parser.add_argument('directory', metavar='dir',
                   help='directory to process')

args = parser.parse_args()
data = Loader.load_data_partial(args.directory,NUM_FICS)

print('The nltk version is {}.'.format(nltk.__version__))
print('The scikit-learn version is {}.'.format(sklearn.__version__))

def clean_line(line):
      cleanline = re.compile('[\\\\]')
      line = unidecode.unidecode(line)
      line = cleanline.sub('',line)
      return line

def proc_line(line):
   #
   whitespace = re.compile("[\s]+")
   punc_pfx = re.compile("^[^A-Za-z]+")
   punc_sfx = re.compile("[^A-Za-z]+$")
   alpha = re.compile("[A-Za-z]+((-|')[A-Za-z])?[A-Za-z]*")
   hyphen = re.compile("[-]+")
   poss = re.compile("'s")
   tokens = whitespace.split(line)
   nline = ""
   for tok in tokens:
      if len(tok) == 0:
         continue;

      pfx = punc_pfx.search(tok)
      sfx = punc_sfx.search(tok)
      word = alpha.match(tok)
      suff = ""
      pref = ""

      if word == None:
         nline += tok + " "
         continue;

      word = word.group(0)

      if pfx != None:
         pref = pfx.group(0)

      if sfx != None:
         suff = sfx.group(0)

      if "'s" in word:
         suff = "'s" + suff
         word = poss.split(word)[0]

      success,sfx = recog_sfx(word)

      if success:
         nline += pref+sfx+suff
         continue;

      if "-" in word:
         if is_proper_noun(word) and is_template(word):
               nname = get_template(word);
               nline += pref+nname+suff+" "
               continue;

         subwords = hyphen.split(word)
         all_words = True
         for subword in subwords:
            if defined_in_dict(subword) == False:
               all_words = False

         if all_words == True:
            nline += pref + word.lower() + suff + " ";
         else:
            if is_proper_noun(word) and not is_template(word):
               nname = add_template(word)
               nline += pref+nname+suff+" "

            elif is_proper_noun(word) and is_template(word):
               nname = get_template(word);
               nline += pref+nname+suff+" "

            else:
               nline += pref+ word + suff+" "

      else:
         if is_proper_noun(word) and is_template(word):
               nname = get_template(word);
               nline += pref+nname+suff+" "
               continue;

         if defined_in_dict(word):
            nline += tok + " "
         else:
            if is_proper_noun(word) and not is_template(word):
               nname = add_template(word)
               nline += pref+nname+suff+" "

            elif is_proper_noun(word) and is_template(word):
               nname = get_template(word);
               nline += pref+nname+suff+" "

            else:
               print("unknown",pref,word,suff)
               nline += pref+ word + suff+" "

   return nline;

def fic2text(ident,master):
   textsegs = Loader.get_field(data['fics'],ident,'fic')
   rtags = Loader.get_field(data['base'],ident,'tags')
   rtext = ""
   #tngms = []
   ttoks = Set([])
   atoks = []

   rtext = ""
   for line in textsegs:
      line = clean_line(line)
      line = proc_line(line)
      rtext += line

   #for i in range(0,len(frags)):
   #   if is_punc(frags[i]):
   #      continue
   #   print(frags[i])

   #master = markov.train([rtext],NUM_GRAMS,split_callback=split_line,master_dict=master)

   return rtext

print("==== Loaded. Getting Data.... =====")
ids = Loader.get_primaries(data['fics']);
vdata = []
vwords = Set([])
master = None

i=1;
ofh = open("out.txt","w")
for ident in ids:
   print(">> process "+str(ident)+" : # "+str(i))
   text=fic2text(ident,master)
   ofh.write(text)
   i+=1
   #qwords,qdata = fic2text(i)
   #vdata += qdata
   #vwords.update(qwords)

ofh.close()
print("==== Writing to File ======")
dump_template("names.templ")
#
print("==== Finished ======")

#print("===========")
#print("===== Finished Processing Ngrams ===")
#vstat = Counter(vdata)
#for k in vstat:
#   print(k,vstat[k])

#nwords = len(vwords)
#print("number of words:",nwords)

#HiddenMarkovModelTagger(nwords,)


import dash
from dash import no_update
from dash.dependencies import Input,Output,State
import dash_bootstrap_components as dbc
import dash_html_components as html
import dash_core_components as dcc

from utilities import fetchilarity_score

app = dash.Dash(__name__,external_stylesheets=[dbc.themes.BOOTSTRAP])
server = app.server

app.layout = html.Div([
    dbc.Container(
        [
            dbc.Row(
                dbc.Col(
                    dcc.Markdown(
'''
# Fetchilarity

### Enter two bits of text to determine how similar they are!

Made with love by Russell.

'''
                    ),
                ),
                style=dict(textAlign='center')

            ),

            dbc.Row(
                [
                    # enter text1
                    dbc.Col(
                        [
                            dbc.Textarea(placeholder='Enter the first bit of text',id='text1'),
                        ],
                        width=6
                    ),
                    # enter text2
                    dbc.Col(
                        [
                            dbc.Textarea(placeholder='Enter the second bit of text',id='text2'),
                        ],
                        width=6
                    )
                ]
            ),
            html.Br(),

            dbc.Row(
                [
                    dbc.Col(
                        dbc.Button('SUBMIT',id='submit',color='primary',size='lg',block=True,n_clicks=0)
                    ),
                ],
            ),
            html.Br(),

            dbc.Row(
                [
                    dbc.Col(
                        [
                            html.Div(id='output',style=dict(textAlign='center'))
                        ]
                    )
                ]
            )
        ]
    )
])

@app.callback(
    Output('output','children'),
    [Input('submit','n_clicks')],
    [State('text1','value'),
     State('text2','value')]
)
def get_score(n_clicks,text1,text2):
    if n_clicks==0:
        return no_update

    try:
        score = fetchilarity_score(text1,text2,mode='api')
    except BaseException as e:
        print(text1,text2)
        print(e)
        return 'something went terribly wrong with that input. Please try again.'

    return dbc.Card(
        [
            html.H3('Fetchilarity Score',className='card-title'),
            html.H1(str(round(score,4)))
        ],
        body=True
    )

if __name__ == "__main__":
    app.run_server(
        port=8050,
        debug=True
    )


import os,wx
import numpy as np
from poiGUI_panels import POIPanel
from poiGUI_navigation import POINavigationControls

class POIFrame(wx.Frame):
	def __init__(self, parent, id, title, metadata=None):
		wx.Frame.__init__(self, parent, id, title)
		self.POI             = metadata.load_pois()
		self.poi             = self.POI[0]
		self.selected        = [None]*4
		self.metadata        = metadata
		# self.nRollovers      = None
		# self.panels          = None
		# self.rollovers       = None
		# self.stepnums        = None
		self.subj            = 0
		# self.xmlfilenames    = None
		sizer                = self._create_panels()
		self._create_statusbar()
		self.SetSizer(sizer)
		self.Fit()
		self.Centre()
		self.set_subject(0)

	def _create_panels(self):
		### create steps panels:
		sizer0             = wx.BoxSizer(wx.HORIZONTAL)
		# self.panels        = [MatplotlibPanel(self, size=(200,340), panelnum=i)  for i in range(4)]
		self.panels        = [POIPanel(self, size=(200,340), panelnum=i)  for i in range(4)]
		[sizer0.Add(panel, 1, flag=wx.EXPAND) for panel in self.panels]
		buttonR    = wx.Button(self, -1, 'Reset', (200, 200))
		buttonX    = wx.Button(self, -1, 'Export', (200, 200))
		panel_nav  = POINavigationControls(self, size=(200,50))
		### bind:
		buttonR.Bind(wx.EVT_BUTTON, self.OnButtonReset)
		buttonX.Bind(wx.EVT_BUTTON, self.OnButtonExport)
		sizerH     = wx.BoxSizer(wx.HORIZONTAL)
		sizerH.Add(buttonR, 1, flag=wx.CENTER)
		sizerH.Add(buttonX, 1, flag=wx.CENTER)
		### layout:
		sizer      = wx.BoxSizer(wx.VERTICAL)
		sizer.Add(sizer0, 8, flag=wx.EXPAND)
		sizer.Add(sizerH, 1, flag=wx.CENTER)
		sizer.Add(panel_nav, 1, flag=wx.EXPAND)
		return sizer

	def _create_statusbar(self):
		self.statusbar = self.CreateStatusBar(style=wx.BORDER_DOUBLE)
		self.statusbar.SetFieldsCount(3)
		self.statusbar.SetStatusWidths([-5,-1,-3])

	def _find_closest_poi(self, xy, panelnum):
		d   = []
		x,y = xy
		for poi in self.poi[panelnum]:
			x0,y0 = poi
			d.append(  (x-x0)**2 + (y-y0)**2  )
		return np.argmin(d)

	def back(self):
		self.POI[self.subj] = self.poi
		self.statusbar.SetStatusText('(Loading data...)', 2)
		subj  = self.subj
		if subj - 1 < 0:
			subj = self.metadata.nSubj - 1
		else:
			subj -= 1
		self.set_subject(subj)

	def get_current_pois(self, panelnum):
		return np.array([line.get_data() in self.panels[panelnum].ax.lines]).squeeze()

	def forward(self):
		self.POI[self.subj] = self.poi
		self.statusbar.SetStatusText('(Loading data...)', 2)
		subj  = self.subj
		if subj + 1 == self.metadata.nSubj:
			subj = 0
		else:
			subj += 1
		self.set_subject(subj)

	def poi_add(self, xy, panelnum):
		panel = self.panels[panelnum]
		panel.plot_poi(xy)
		panel.canvas.draw()
		if self.poi[panelnum]==None:
			self.poi[panelnum] = [xy]
		else:
			self.poi[panelnum].append(xy)
		self.selected[panelnum] = len(self.poi[panelnum])-1
		self.panels[panelnum].highlight_poi( self.selected[panelnum]   )
		self.panels[panelnum].set_xy(xy)

	def poi_delete(self, xy, panelnum):
		if self.poi[panelnum]==None:
			pass
		else:
			ind   = self._find_closest_poi(xy, panelnum)
			panel = self.panels[panelnum]
			self.poi[panelnum].pop(ind)
			if len(self.poi[panelnum])==0:
				self.poi[panelnum] = None
				self.selected[panelnum] = None
				panel.set_xy(None)
			else:
				if ind==self.selected[panelnum]:
					self.selected[panelnum] = 0
				elif self.selected[panelnum] > ind:
					self.selected[panelnum] -= 1
				# else:
				# 	self.selected[panelnum] -= 1
				panel.set_xy(xy)
			panel.replot_pois(self.poi[panelnum])
			panel.highlight_poi( self.selected[panelnum]   )

	def poi_move_selected(self, panelnum, x=None, y=None):
		ind   = self.selected[panelnum]
		xy    = list(self.poi[panelnum][ind])
		if x!=None:
			xy[0] = x
		if y!=None:
			xy[1] = y
		self.poi[panelnum][ind]  = xy
		panel = self.panels[panelnum]
		panel.replot_pois(self.poi[panelnum])
		panel.highlight_poi( self.selected[panelnum]   )

	def poi_select(self, xy, panelnum):
		if self.poi[panelnum]==None:
			pass
		else:
			ind   = self._find_closest_poi(xy, panelnum)
			self.panels[panelnum].highlight_poi(ind)
			self.panels[panelnum].set_xy(  self.poi[panelnum][ind]  )
			self.selected[panelnum] = ind

	def quit(self):
		result = wx.MessageBox('Previously specified POIs will be overwritten. OK to proceed?', 'Confirm overwrite', wx.OK | wx.CANCEL)
		if result==wx.OK:
			self.metadata.save_pois(self.POI)
		self.Destroy()

	def set_subject(self, subj):
		self.subj = subj
		self.poi  = self.POI[subj]
		II        = self.metadata.load_means(subj, stacked=False)
		[panel.cla()  for panel in self.panels]
		[panel.plot( np.asarray(I, dtype=float) )  for panel,I in zip(self.panels,II)]
		for i,(panel,poi) in enumerate(zip(self.panels,self.poi)):
			panel.replot_pois(poi)
			if poi==None:
				self.selected[i] = None
				panel.set_xy(None)
			else:
				self.selected[i] = 0
				panel.highlight_poi(0)
				panel.set_xy( poi[0] )
		self.set_statusbar_text()

	def set_statusbar_text(self):
		self.statusbar.SetStatusText('Subj %d of %d'%(self.subj+1,self.metadata.nSubj), 1)
		self.statusbar.SetStatusText(self.metadata.USUBJ[self.subj], 2)

	def OnButtonExport(self, event):
		# fname         = os.path.join('/Users/todd/Desktop/poi_export.xls')
		dialog = wx.FileDialog(self, 'Select a destination...', '.', defaultFile='poi_export.xls', style=wx.FD_SAVE)
		fname  = None
		if dialog.ShowModal() == wx.ID_OK:
			fname = dialog.GetPath()
		dialog.Destroy()
		if fname!=None:
			 self.metadata.save_poi_extracted(fname, self.POI)

	def OnButtonReset(self, event):
		result = wx.MessageBox('WARNING:  All POI data will be deleted.\nOK to continue?\n\nNote: the POIs will be deleted from this screen but not from disk. To rese the POIs stored on disk, select "OK", then select "Quit" and "OK" to overwrite the existing POIs.', 'Confirm POI reset', wx.OK | wx.CANCEL)
		if result==wx.OK:
			self.POI = [[None]*4  for i in range(self.metadata.nSubj)]
			self.set_subject(self.subj)

# class MyApp(wx.App):
# 	def OnInit(self):
# 		import pressure_database as DB;  reload(DB)
# 		# dir0     = '/Volumes/DataProc/projectsExternal/uQueensland/test2/'
# 		dir0     = '/Users/todd/Desktop/test2'
# 		metadata = DB.load_metadata(dir0)
# 		subj = 0
# 		frame = POIFrame(None, -1, 'Points of Interest (POIs)', metadata=metadata)
# 		frame.Show(True)
# 		self.SetTopWindow(frame)
# 		return True
#
#
#
# #run app:
# app = MyApp(redirect=False)
# app.MainLoop()


from collections import Counter
from typing import List

class Solution:
    def isPossibleDivide(self, nums: List[int], k: int) -> bool:
        nums.sort()
        left = Counter(nums)

        for n in nums:
            if left[n] == 0:
                continue
            for i in range(n, n+k):
                if left[i] == 0:
                    return False
                left[i] -= 1
        return True


""" Importamos el modelo del archivo en que lo definimos. """
from model_robots import StorageModel

""" matplotlib lo usaremos crear una animación de cada uno de los pasos
    del modelo. """
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.animation as animation
plt.rcParams["animation.html"] = "jshtml"
matplotlib.rcParams['animation.embed_limit'] = 2**128

""" Importamos los siguientes paquetes para el mejor manejo de valores
    numéricos."""
import numpy as np
import pandas as pd

""" Definimos otros paquetes que vamos a usar para medir el tiempo de
    ejecución de nuestro algoritmo. """
import time
import datetime

M = int(input("dame el numero de filas "))

N = int(input("deme el numero de columnas "))

numAgents = int(input("Dame el numero de Agentes "))

numBoxes = int(input("Dame el numero de Cajas "))

MAXTIME = int(input("Tiempo máximo de ejecución en segundos "))

""" Registramos el tiempo de inicio y ejecutamos la simulación. """
start_time = time.time()
model = StorageModel(M, N,numAgents,numBoxes)

frames =-1
while datetime.timedelta(seconds=(time.time() - start_time)< MAXTIME):
    frames+=1
    if model.unsortedBoxes==0:
        break
    model.step()

print('Tiempo de ejecución:', str(datetime.timedelta(seconds=(time.time() - start_time))))
print('Número de movimientos realizados por todos los agentes', model.agentMovements)

""" Obtenemos la información que almacenó el colector, este nos entregará un
    DataFrame de pandas que contiene toda la información. """
all_grid = model.datacollector.get_model_vars_dataframe()

# Graficamos la información usando `matplotlib`
fig, axs = plt.subplots(figsize=(7,7))
axs.set_xticks([])
axs.set_yticks([])
patch = plt.imshow(all_grid.iloc[0][0])

def animate(i):
    patch.set_data(all_grid.iloc[i][0])

anim = animation.FuncAnimation(fig, animate, frames=frames,interval=1)
plt.show()


import cv2
import argparse

# img = cv2.imread("./logo.png")
# cv2.imshow("LOGO", img)
# cv2.waitKey(0)
# cv2.destroyAllWindows()

parse = argparse.ArgumentParser()
parse.add_argument("path_image", help="path to input the image")

args = parse.parse_args()

img = cv2.imread(args.path_image)
cv2.imshow("LOGO", img)

args_dict = vars(parse.parse_args())  # {"path_image" : "./logo.png"}
img2 = cv2.imread(args_dict["path_image"])
cv2.imshow("logo_two", img2)
cv2.waitKey(0)

cv2.destroyAllWindows()


#
# Author: KEEN LITTLE
#
# Date: 29 March 2021
#
# Assignment Step 214, Python Course
#   The Tech Academy Software Development Bootcamp
#
# Purpose: to practice with python3 and sqlite3, showing how SQL queries can be
#   written and automated with Python.
#
################################################################################

import sqlite3

fileList = ('information.docx', 'hello.txt', 'myImage.png', \
            'myMovie.mpg', 'World.txt', 'data.pdf', 'myPhoto.jpg')
            # Here are the file names that we're pulling into the database.

def createTable():
    conn = sqlite3.connect('pysql.db')
    with conn:
        cur = conn.cursor() # Creating a database with two fields:
        cur.execute("CREATE TABLE IF NOT EXISTS tbl_textFiles( \
            ID INTEGER PRIMARY KEY AUTOINCREMENT, \
            col_fileName VARCHAR(50) \
            )") # We have a primary key and a varchar (string) for the names.
        conn.commit()
    conn.close()

"""
txtFileList = ()

def sortFiles(): # I'm just gonna grab the files I want
    for i in fileList:
	if i.endswith('.txt'):
	    txtFileList.append(i) # And dump 'em into a new list! Easier.
""" # Better idea: sort this with an if statement when I populate the table

def filesToTable():
    conn = sqlite3.connect('pysql.db')
    for item in fileList: # Iterating through the tuple,
        if item.endswith('.txt'): # Here we grab only the .txt files
            with conn:
                cur = conn.cursor()
                cur.execute("INSERT INTO tbl_textFiles (col_fileName) VALUES (?)", (item,))
                print(item)
                conn.commit()
    conn.close()

if __name__ == "__main__":

    createTable()
#    sortFiles()
    filesToTable()


from typing import Any
from unittest import mock

from langchain_community.vectorstores.nucliadb import NucliaDB

class attrdict(dict):
    def __getitem__(self, key: str) -> Any:
        value = dict.__getitem__(self, key)
        return attrdict(value) if isinstance(value, dict) else value

    __getattr__ = __getitem__

def FakeCreate(**args: Any) -> Any:
    def fn(self: Any, **kwargs: Any) -> str:
        return "fake_uuid"

    return fn

def FakeDelete(**args: Any) -> Any:
    def fn(self: Any, **kwargs: Any) -> None:
        return None

    return fn

def FakeFind(**args: Any) -> Any:
    def fn(self: Any, **kwargs: Any) -> Any:
        return attrdict(
            {
                "resources": {
                    "123": attrdict(
                        {
                            "fields": {
                                "456": attrdict(
                                    {
                                        "paragraphs": {
                                            "123/t/text/0-14": attrdict(
                                                {
                                                    "text": "This is a test",
                                                    "order": 0,
                                                }
                                            ),
                                        }
                                    }
                                )
                            },
                            "data": {
                                "texts": {
                                    "text": {
                                        "body": "This is a test",
                                    }
                                }
                            },
                            "extra": attrdict({"metadata": {"some": "metadata"}}),
                        }
                    )
                }
            }
        )

    return fn

def test_add_texts() -> None:
    with mock.patch(
        "nuclia.sdk.resource.NucliaResource.create",
        new_callable=FakeCreate,
    ):
        ndb = NucliaDB(knowledge_box="YOUR_KB_ID", local=False, api_key="YOUR_API_KEY")
        assert ndb.is_local is False
        ids = ndb.add_texts(["This is a new test", "This is a second test"])
        assert len(ids) == 2

def test_delete() -> None:
    with mock.patch(
        "nuclia.sdk.resource.NucliaResource.delete",
        new_callable=FakeDelete,
    ):
        ndb = NucliaDB(knowledge_box="YOUR_KB_ID", local=False, api_key="YOUR_API_KEY")
        success = ndb.delete(["123", "456"])
        assert success

def test_search() -> None:
    with mock.patch(
        "nuclia.sdk.search.NucliaSearch.find",
        new_callable=FakeFind,
    ):
        ndb = NucliaDB(knowledge_box="YOUR_KB_ID", local=False, api_key="YOUR_API_KEY")
        results = ndb.similarity_search("Who was inspired by Ada Lovelace?")
        assert len(results) == 1
        assert results[0].page_content == "This is a test"
        assert results[0].metadata["extra"]["some"] == "metadata"
        assert results[0].metadata["value"]["body"] == "This is a test"


import sys
import time
from Point import Point
import matplotlib.pyplot as plt
from sampler import rectangular_sample, eliptical_sample

def distance(a,b,c):
	y1 = a.y - b.y
	y2 = a.y -c.y
	x1 = a.x -b.x
	x2 = a.x -c.x
	x = y1 * y1 + x1 * x1
	y = y2 * y2 + x2 * x2

	if x == y:
		return 0
	elif x < y:
		return -1
	else:
		return 1

'''
Donde está el punto c en relacion al vector ab
Retorna
	> 0 c está a la izquierda de ab
	= 0 los tres puntos son colineales
	< 0 c está a la derecha de ab
'''
def crossProdcut(a,b,c):
	y1 = a.y - b.y
	y2 = a.y - c.y
	x1 = a.x - b.x
	x2 = a.x - c.x
	return y2 * x1 - y1 * x2

def jarvis_hull(points):
	start = points[0]
	for i in range(1,len(points)):
		if points[i].x < start.x:
			start = points[i]

	current = start
	result = set()
	result.add(start)
	colinear = []
	while True:
		nextTarget = points[0]
		for i in range (1,len(points)):
			if points[i] == current:
				continue

			val = crossProdcut(current,nextTarget,points[i])
			if val > 0:
				nextTarget = points[i]
				colinear = []
			elif val == 0:
				if distance(current,nextTarget,points[i]) < 0:
					colinear.append(nextTarget)
					nextTarget = points[i]
				else:
					colinear.append(points[i])

		for i in range(0,len(colinear)):
			result.add(colinear[i])

		if nextTarget == start:
			break

		result.add(nextTarget)
		current = nextTarget

	return result

n = int(sys.argv[1])
fig = str(sys.argv[2])
a = int(sys.argv[3])
b = int(sys.argv[4])
r = float(sys.argv[5])

if fig == 'r':
	sample  = rectangular_sample(n,a,b,r)

elif fig == 'e':
	sample  = eliptical_sample(n,a,b,r)

start_time = time.time()
hull = jarvis_hull(sample)
used_time = time.time() - start_time

x_hull = []
y_hull = []
lista = list(hull)
lista.sort(key=lambda x: x.x)#O(n log n)

i = 0
while i< len(lista)/2:
	x_hull.append(lista[i].x)
	y_hull.append(lista[i].y)
	i = i + 1

j = len(lista) - 1
while j >= len(lista)/2:
	x_hull.append(lista[j].x)
	y_hull.append(lista[j].y)
	j = j - 1

for i in range(len(lista)):
	print("("+str(x_hull[i])+","+str(y_hull[i])+")")

x = []
y = []
for i in range(len(sample)):
	x.append(sample[i].x)
	y.append(sample[i].y)

plt.scatter(x,y)
for k in range(len(x_hull)):
	plt.plot(x_hull[k:k+2],y_hull[k:k+2])

plt.title('Jarvis March')
plt.show()
print("--- Javis March took "+ str(used_time) +" seconds for n= "+str(n) )


from copy import copy
import numpy as np
from nestmodel.utils import networkx_from_edges, graph_tool_from_edges, calc_color_histogram, switch_in_out, make_directed
from nestmodel.fast_wl import WL_fast, WL_both

from nestmodel.fast_rewire import rewire_fast, sort_edges, get_block_indices

class FastGraph:
    """A custom class representing Graphs through edge lists that can be used to efficiently be rewired"""
    def __init__(self, edges, is_directed, check_results=False, num_nodes=None):
        assert edges.dtype==np.uint32 or edges.dtype==np.uint64
        assert isinstance(is_directed, bool), f"wrong type of is_directed: {type(is_directed)}"
        self._edges = edges.copy()
        self.edges_ordered = None
        self.is_directed = is_directed
        self.base_partitions = None
        self.latest_iteration_rewiring = None
        if num_nodes is None:
            self.num_nodes = edges.ravel().max()+1
        else:
            self.num_nodes = num_nodes
        self.check_results = check_results
        self.wl_iterations = None

        # these will be set in reset_edges_ordered
        self.edges_classes = None
        self.dead_arr = None
        self.is_mono = None
        self.block_indices = None

        self.out_degree = np.array(np.bincount(edges[:,0].ravel(), minlength=self.num_nodes), dtype=np.uint32)
        self.in_degree =  np.array(np.bincount(edges[:,1].ravel(), minlength=self.num_nodes), dtype=np.uint32)

        if self.is_directed:
            self.out_dead_ends = np.nonzero(self.out_degree==0)[0]
            self.corr_out_degree=self.out_degree.copy()
            self.corr_out_degree[self.out_dead_ends]+=1

            self.in_dead_ends = np.nonzero(self.in_degree==0)[0]
            self.corr_in_degree=self.in_degree.copy()
            self.corr_in_degree[self.in_dead_ends]+=1

            #print(len(self.out_dead_ends), len(self.in_dead_ends))
        else:
            self.out_degree=self.out_degree+self.in_degree
            self.in_degree=self.out_degree
            self.out_dead_ends = np.nonzero(self.out_degree==0)[0]
            self.in_dead_ends = self.out_dead_ends

    @property
    def edges(self,):
        """Return the current edges of the graph"""
        if self.edges_ordered is None:
            return self._edges
        else:
            return self.edges_ordered

    @staticmethod
    def from_gt(G): # pragma: gt no cover
        """Creates a FastGraph object from a graphtool graph"""
        edges = np.array(G.get_edges(), dtype=np.uint32)
        is_directed = G.is_directed()
        return FastGraph(edges, is_directed)

    @staticmethod
    def from_nx(G):
        """Creates a FastGraph object from a graphtool graph"""
        edges = np.array(G.edges, dtype=np.uint32)
        is_directed = G.is_directed()
        return FastGraph(edges, is_directed)

    @staticmethod
    def switch_directions(G):
        """Creates a FastGraph object from a graphtool graph"""
        edges = switch_in_out(G.edges)
        is_directed = G.is_directed
        return FastGraph(edges, is_directed)

    def to_gt(self):
        """Convert the graph to a graph-tool graph"""
        edges = self.edges
        return graph_tool_from_edges(edges, self.num_nodes, self.is_directed)

    def to_nx(self):
        """Convert the graph to a networkx graph"""
        edges = self.edges
        return networkx_from_edges(edges, self.num_nodes, self.is_directed)

    def to_coo(self):
        """Returns a sparse coo-matrix representation of the graph"""
        from scipy.sparse import coo_matrix # pylint: disable=import-outside-toplevel
        edges = self.edges
        if not self.is_directed:
            edges = make_directed(edges)

        return coo_matrix((np.ones(edges.shape[0]), (edges[:,0], edges[:,1])), shape = (self.num_nodes, self.num_nodes))

    def save_npz(self, outfile, include_wl=False):
        """Save the FastGraph object as .npz"""
        if not include_wl:
            np.savez(outfile, edges=self.edges, is_directed=self.is_directed)
        else:
            if self.base_partitions is None or self.wl_iterations is None:
                raise NotImplementedError("Saving without computing the information first makes no sense")
            kwargs = {  "edges":self.edges,
                        "is_directed":self.is_directed,
                        "base_partitions":self.base_partitions,
                        "wl_iterations":self.wl_iterations,
                        "edges_classes" : self.edges_classes,
                        "mono_len": len(self.is_mono),
                        "block_len" : len(self.block_indices)}
            for i, x in enumerate(self.is_mono):
                kwargs[f"mono{i}_keys"] = np.array(list(x.keys()), np.int64)
                kwargs[f"mono{i}_values"] = np.array(list(x.values()), np.bool_)
            for i, x in enumerate(self.block_indices):
                kwargs[f"block_indices{i}"] = x
            np.savez(outfile, **kwargs)

    @staticmethod
    def load_npz(file):
        npzfile = np.load(file)
        if len(npzfile) == 2:
            return FastGraph(npzfile["edges"], bool(npzfile["is_directed"]))
        else:
            G = FastGraph(npzfile["edges"], bool(npzfile["is_directed"]))
            G.base_partitions = npzfile["base_partitions"]
            G.wl_iterations = npzfile["wl_iterations"]
            G.edges_classes = npzfile["edges_classes"]

            from nestmodel.fast_rewire import create_mono_from_arrs
            G.is_mono = []
            for i in range(npzfile["mono_len"]):
                G.is_mono.append(create_mono_from_arrs(npzfile[f'mono{i}_keys'], npzfile[f'mono{i}_values']))
            G.block_indices = []
            for i in range(npzfile["block_len"]):
                G.block_indices.append(npzfile[f'block_indices{i}'])
            return G

    def calc_wl(self, initial_colors=None, max_depth=None):
        """Compute the WL colors of this graph using the provided initial colors"""
        return self._calc_wl(WL_fast, initial_colors, max_depth=max_depth)

    def calc_wl_both(self, initial_colors=None, max_depth=None):
        """Compute the WL partition over both the in and out neighborhood"""
        return self._calc_wl(WL_both, initial_colors, max_depth=max_depth)

    def _calc_wl(self, method, initial_colors=None, max_depth=None):
        edges = self.edges
        if not self.is_directed:
            edges2 = np.vstack((edges[:,1], edges[:,0])).T
            edges = np.vstack((edges, edges2))

        if type(initial_colors).__module__ == np.__name__: # is numpy array
            return method(edges, self.num_nodes, labels = initial_colors, max_iter=max_depth)
        elif initial_colors is not None and "out_degree" == initial_colors:
            return method(edges, self.num_nodes, labels = self.out_degree, max_iter=max_depth)
        else:
            return method(edges, self.num_nodes, max_iter=max_depth)

    def ensure_base_wl(self, initial_colors=None, both=False, max_depth=None):
        """Compute the base WL partition if they have not yet been computed"""
        if self.base_partitions is None:
            self.calc_base_wl(initial_colors=initial_colors, both=both, max_depth=max_depth)

    def calc_base_wl(self, initial_colors=None, both=False, max_depth=None):
        """Compute and store the base WL partition"""
        if not self.latest_iteration_rewiring is None:
            raise ValueError("Seems some rewiring already employed, cannot calc base WL")
        if both is False:
            partitions = self.calc_wl(initial_colors=initial_colors, max_depth=max_depth)
        else:
            partitions = self.calc_wl_both(initial_colors=initial_colors, max_depth=max_depth)

        self.base_partitions = np.array(partitions, dtype=np.uint32)
        self.wl_iterations = len(self.base_partitions)

    def ensure_edges_prepared(self, initial_colors=None, both=False, max_depth=None):
        """Prepare the edges by first ensuring the base WL and then sorting edges by base WL"""
        if self.base_partitions is None:
            self.ensure_base_wl(initial_colors=initial_colors, both=both, max_depth=max_depth)
        if self.edges_ordered is None:
            self.reset_edges_ordered()

    def reset_edges_ordered(self):
        """Sort edges according to the partitions"""
        self.edges_ordered, self.edges_classes, self.dead_arr, self.is_mono = sort_edges(self._edges, self.base_partitions, self.is_directed)
        self.block_indices = get_block_indices(self.edges_classes, self.dead_arr)

    def copy(self):
        """Returns a copy of this graph which has no data shared with the original graph"""
        G = FastGraph(self._edges.copy(), self.is_directed)
        for key, value in self.__dict__.items():
            setattr(G, key, copy(value))
        return G

    def rewire(self, depth, method, **kwargs):
        """Rewire the edges of the graph in place, thereby preserving the colors of depth d
        Note you cannot call this function with increasing depth, but rather with decreasing depth only
        """
        assert self.base_partitions is not None, "Base partitions are none. Call G.ensure_edges_prepared() first."
        assert depth < len(self.base_partitions), f"{depth} {len(self.base_partitions)}"
        assert self.latest_iteration_rewiring is None or depth <= self.latest_iteration_rewiring, f"{depth} {self.latest_iteration_rewiring}"
        assert method in (1, 2)
        if kwargs is not None:
            for key in kwargs:
                assert key in ("seed", "n_rewire", "r", "parallel")
        self.latest_iteration_rewiring = depth

        self.ensure_edges_prepared()
        if self.check_results:  # pragma: no cover
            if self.is_directed:
                ins, outs = calc_color_histogram(self._edges, self.base_partitions[depth], self.is_directed)
            else:
                hist = calc_color_histogram(self._edges, self.base_partitions[depth], self.is_directed)
        if method==1:
            seed = kwargs.get("seed", None)
            r = kwargs.get("r", 1)
            parallel = kwargs.get("parallel", False)
            rewire_fast(self.edges_ordered,
                                self.edges_classes[:,depth],
                                self.is_mono[depth],
                                self.block_indices[depth],
                                self.is_directed,
                                seed=seed,
                                num_flip_attempts_in=r,
                                parallel=parallel)
            res = None
        elif method == 2:
            from nestmodel.fast_rewire2 import fg_rewire_nest  # pylint: disable=import-outside-toplevel
            res = fg_rewire_nest(self, depth, kwargs["n_rewire"], kwargs["seed"])

        if self.check_results: # pragma: no cover
            if self.is_directed:
                from nestmodel.tests.testing import check_color_histograms_agree # pylint: disable=import-outside-toplevel
                ins2, outs2 = calc_color_histogram(self.edges_ordered, self.base_partitions[depth], self.is_directed)
                check_color_histograms_agree(ins, ins2)
                check_color_histograms_agree(outs, outs2)

                assert np.all(self.in_degree == np.bincount(self.edges[:,1].ravel(), minlength=self.num_nodes))
                assert np.all(self.out_degree == np.bincount(self.edges[:,0].ravel(), minlength=self.num_nodes))

                #check_colors_are_correct(self, depth)

            else:
                #print("checking degree")
                degree = self.in_degree
                curr_degree1 = np.bincount(self.edges[:,0].ravel(), minlength=self.num_nodes)
                curr_degree2 = np.bincount(self.edges[:,1].ravel(), minlength=self.num_nodes)
                assert np.all(degree == (curr_degree1+curr_degree2))

                hist2 = calc_color_histogram(self.edges, self.base_partitions[depth], self.is_directed)
                check_color_histograms_agree(hist, hist2)
        return res


from build_assistant.codegen.abstract.GeneralizedBlockSection import GeneralizedBlockSection
from build_assistant.codegen.statements.ElseBlockSection import ElseBlockSection
from build_assistant.codegen.mixins.ProceduralCodeMixin import ProceduralCodeMixin

class IfBlockSection(GeneralizedBlockSection, ProceduralCodeMixin):
    def __init__(self, source, conditions, operator='&&', nl_after=True):
        super().__init__(
            source,
            'if ',
            params=conditions,
            param_separator=' '+operator,
            nl_after=nl_after,
        )

    def else_block(self):
        return self.subsection(ElseBlockSection(self.source))


# -*- coding: utf-8 -*-#
# -------------------------------------------------------------------------------
# Name:         ticket
# Date:         2019/4/12
# -------------------------------------------------------------------------------

class SearchTicket():
    def __init__(self, raw_tickets):
        self.tickets = []
        self.raw_tickets = raw_tickets
        self.__parse()

    def __parse(self):
        for ticket in self.raw_tickets:
            temp_ticket = {}
            temp_ticket['name'] = ticket.name
            temp_ticket['company'] = ticket.company_name
            temp_ticket['depart_date_time'] = ticket.depart_date + ' ' + ticket.depart_time
            temp_ticket['arrive_date_time'] = ticket.arrive_date + ' ' + ticket.arrive_time
            temp_ticket['depart_airport'] = ticket.depart_airport
            temp_ticket['arrive_airport'] = ticket.arrive_airport

            temp_ticket['third_class_pric'] = '经济舱：' + str(ticket.third_class_price) + '元'
            temp_ticket['second_class_pric'] = '商务舱：' + str(ticket.second_class_price) + '元'
            temp_ticket['first_class_pric'] = '头等舱：' + str(ticket.first_class_price) + '元'

            temp_ticket['depart_city'] = ticket.depart_city
            temp_ticket['arrive_city'] = ticket.arrive_city
            self.tickets.append(temp_ticket)


"""Models module for revenueapp."""
from django.db import models
# Validation modules
from django.core.validators import MinLengthValidator
from django.conf import settings

class Genre(models.Model):
    """A class for genres."""
    name = models.CharField(
        max_length=50,
        unique=True
    )

    def __str__(self):
        """Return string representation of genre."""
        return self.name

class Venue(models.Model):
    """A class for Venue data."""
    name = models.CharField(
            "name of the venue",
            max_length=50,
            unique=True,
            validators=[MinLengthValidator(2, "Name must be greater than 1 character")]
    )
    address = models.CharField("street address", max_length=120)
    city = models.CharField("city", max_length=50)
    state = models.CharField("state", max_length=2)
    zipcode = models.CharField(max_length=5)
    website = models.URLField("external venue website", max_length=200)
    image = models.URLField("link to an image of venue", max_length=200)
    genres = models.ManyToManyField(Genre, help_text="HINT: Select multiple genres with ctrl/cmd.")

    # override the __str__ method to return the name of the venue
    def __str__(self):
        return self.name

class Review(models.Model):
    """Model for a review of a venue."""
    # Venue that is being reviewed
    venue = models.ForeignKey(Venue, on_delete=models.CASCADE, unique=False, null=False)
    # overall_rating is an integer from 1 to 5 with a default of 1
    class StarRating(models.IntegerChoices):
        """Star rating for a venue."""
        ONE_STAR = 1
        TWO_STARS = 2
        THREE_STARS = 3
        FOUR_STARS = 4
        FIVE_STARS = 5
    seating_rating = models.IntegerField(
                        "seating",
                        choices=StarRating.choices,
                        default=StarRating.ONE_STAR
    )
    sound_rating = models.IntegerField(
                        "sound",
                        choices=StarRating.choices,
                        default=StarRating.ONE_STAR
    )
    scene_rating = models.IntegerField(
                        "scene",
                        choices=StarRating.choices,
                        default=StarRating.ONE_STAR
    )
    bathrooms_rating = models.IntegerField(
                        "bathrooms",
                        choices=StarRating.choices,
                        default=StarRating.ONE_STAR
    )
    overall_rating = models.IntegerField(
                        "overall",
                        choices=StarRating.choices,
                        default=StarRating.ONE_STAR
    )
    comments = models.TextField("comments", max_length=500)
    owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)


from flask import Flask
import tensorflow as tf
import librosa
import math
import os
import numpy as np
from flask import request
from flask_cors import CORS
app = Flask(__name__)
CORS(app)

@app.route('/')
def hello_world():
    return {"result":'Hello, World!'}

@app.route('/prediction',methods=['POST'])
def genre_prediction():
    model = tf.keras.models.load_model('C:\\Users\\Aniket Das\\Desktop\\Workspace\\Seminar\\MusicModel_Codes\\MusicModel_v3_model.h5')
    labels={
        0:"Classical",
        1:"Blues",
        2:"Reggae",
        3:"Disco",
        4:"Rock",
        5:"Jazz",
        6:"Country",
        7:"Pop",
        8:"Hip Hop",
        9:"Metal"
    }

    mfcc_list=[]

    if request.method == 'POST':
        f = request.files['the_file']
        f.save('temp.wav')

    signal, sample_rate = librosa.load('temp.wav', sr=22050)

    ### Preprocess the uploaded file
    SAMPLE_RATE = 22050
    TRACK_DURATION = 30 # measured in seconds
    SAMPLES_PER_TRACK = SAMPLE_RATE * TRACK_DURATION

    num_mfcc=20
    n_fft=2048
    hop_length=512
    num_segments=10

    samples_per_segment = int(SAMPLES_PER_TRACK / num_segments)
    num_mfcc_vectors_per_segment = math.ceil(samples_per_segment / hop_length)

    for d in range(num_segments):
        start = samples_per_segment * d
        finish = start + samples_per_segment

        # extract mfcc
        mfcc = librosa.feature.mfcc(signal[start:finish], sample_rate, n_mfcc=num_mfcc, n_fft=n_fft, hop_length=hop_length)
        mfcc = mfcc.T

        # store only mfcc feature with expected number of vectors
        if len(mfcc) == num_mfcc_vectors_per_segment:
            mfcc_list.append(mfcc.tolist())

    prediction_data = np.array(mfcc_list)

    prediction = model.predict_classes(prediction_data)

    prediction_except_duplicates = list(set(prediction))

    dict_preds={}

    for element in prediction_except_duplicates:
        count = 0
        for el in prediction:
            if el==element:
                count=count+1
        dict_preds[element] = count

    max_value = max(list(dict_preds.values()))
    genre_number_position = list(dict_preds.values()).index(max_value)
    genre_number = list(dict_preds.keys())[genre_number_position]

    os.remove("temp.wav")

    return {
        "genre":labels[genre_number]
    }


import threading
import time
import pynput
import gspread
import os
from oauth2client.service_account import ServiceAccountCredentials

# Authentication for Google Sheets

scope = ["https://spreadsheets.google.com/feeds","https://www.googleapis.com/auth/drive"]

jsonkeyfile = input("Enter your json keyfile name: ")

credentials = ServiceAccountCredentials.from_json_keyfile_name(str(jsonkeyfile), scope)

gc = gspread.authorize(credentials)

# Upload Name to Sheets

SheetName = input("Google Sheets Title: ")
wks = gc.open(str(SheetName)).sheet1
wks.update_cell(1,1,os.getlogin())

# Define Keys to Log
UploadString = "Inputs :"

#
exitFlag = 0

# Upload Thread Function
class myThread (threading.Thread):
   def __init__(self, threadID, name, counter, cellcounter):
      threading.Thread.__init__(self)
      self.threadID = threadID
      self.name = name
      self.counter = counter
      self.cellcounter = cellcounter
   def run(self):
      print ("Starting " + self.name)
      print_time(self.name, self.counter, self.cellcounter)
      print ("Exiting " + self.name)

def print_time(threadName, delay, cellcounter):
   while True:
      if exitFlag:
         threadName.exit()
      wks.update_cell(cellcounter, 1, UploadString)
      time.sleep(delay)
      print ("%s: %s" % (threadName, time.ctime(time.time())))
      cellcounter += 1

# Key Log Fuction
def on_press(key):
    try:
        global UploadString
        UploadString = UploadString + key.char

    except AttributeError:
        print(key)
        if str(key) == "Key.space" or str(key) == "Key.enter":
            UploadString = UploadString + " "
        elif str(key) == "Key.backspace":
            if len(UploadString) > 8:
               UploadString = UploadString[:-1]

def on_release(key):
        print(UploadString)
        if key == pynput.keyboard.Key.esc:
            print("Exiting Main Thread")
            # Exit without prompt
            os._exit(0)

# Create new threads (threadid,name,time in seconds each loop)
UploadThread = myThread(1, "Upload Thread", 5 , 2)

# Start Threads
with pynput.keyboard.Listener(on_press=on_press,on_release=on_release) as listener:
    UploadThread.start()
    listener.join()
    UploadThread.join()


import tkinter as tk
import numpy as np
import sys
import time

HEIGHT = 8
WIDTH = 8
UNIT = 40

class Grid(tk.Tk, object):
    def __init__(self):
        super(Grid, self).__init__()
        self.action_space = ['u', 'd', 'l', 'r']
        self.n_actions = len(self.action_space)
        self.title('Grid')
        self.geometry('{0}x{1}'.format(HEIGHT * UNIT, WIDTH * UNIT))
        self._build_grid()

    def _build_grid(self):
        self.canvas = tk.Canvas(self, bg='white', height=HEIGHT * UNIT, width=WIDTH * UNIT)

        for c in range(0, WIDTH * UNIT, UNIT):
            x0, y0, x1, y1 = c, 0, c, HEIGHT * UNIT
            self.canvas.create_line(x0, y0, x1, y1)
        for r in range(0, HEIGHT * UNIT, UNIT):
            x0, y0, x1, y1 = 0, r, WIDTH * UNIT, r
            self.canvas.create_line(x0, y0, x1, y1)

        origin = np.array([UNIT / 2, UNIT / 2])
        self.oval = self.canvas.create_oval(
            origin[0] - 15, origin[1] - 15,
            origin[0] + 15, origin[1] + 15,
            fill='red')
        hell1_center = origin + np.array([UNIT * 4, UNIT * 2])
        self.hell1 = self.canvas.create_rectangle(
            hell1_center[0] - 15, hell1_center[1] - 15,
            hell1_center[0] + 15, hell1_center[1] + 15,
            fill='black')
        hell2_center = origin + np.array([UNIT * 2, UNIT * 4])
        self.hell2 = self.canvas.create_rectangle(
            hell2_center[0] - 15, hell2_center[1] - 15,
            hell2_center[0] + 15, hell2_center[1] + 15,
            fill='black')
        oval_center = origin + UNIT * 4
        self.target = self.canvas.create_rectangle(
            oval_center[0] - 15, oval_center[1] - 15,
            oval_center[0] + 15, oval_center[1] + 15,
            fill='yellow')

        self.canvas.pack()

    def reset(self, sleep_time=0):
        self.canvas.delete(self.oval)
        origin = np.array([UNIT / 2, UNIT / 2])
        self.oval = self.canvas.create_oval(
            origin[0] - 15, origin[1] - 15,
            origin[0] + 15, origin[1] + 15,
            fill='red')
        return self.canvas.coords(self.oval)

    def step(self, action):
        s = self.canvas.coords(self.oval)
        base_action = np.array([0, 0])
        if action == 'u':
            if s[1] > UNIT:
                base_action[1] -= UNIT
        elif action == 'd':
            if s[1] < (HEIGHT - 1) * UNIT:
                base_action[1] += UNIT
        elif action == 'r':
            if s[0] < (WIDTH - 1) * UNIT:
                base_action[0] += UNIT
        elif action == 'l':
            if s[0] > UNIT:
                base_action[0] -= UNIT
        self.canvas.move(self.oval, base_action[0], base_action[1])
        s_ = self.canvas.coords(self.oval)
        if s_ == self.canvas.coords(self.target):
            reward = 1
            done = True
        elif s_ in [self.canvas.coords(self.hell1), self.canvas.coords(self.hell2)]:
            reward = -1
            done = True
        else:
            reward = 0
            done = False
        return s_, reward, done

    def render(self, sleep_time=0.2):
        self.update()
        time.sleep(sleep_time)


from collections.abc import Sequence
import logging

from gama.logging.machine_logging import TOKENS, log_event
from .components import Individual

log = logging.getLogger(__name__)

class OperatorSet:
    """ Provides a thin layer for ea operators for logging, callbacks and safety. """

    def __init__(
        self,
        mutate,
        mate,
        create_from_population,
        create_new,
        compile_,
        eliminate,
        evaluate_callback,
        max_retry=50,
        completed_evaluations=None,
    ):
        """

        :param mutate:
        :param mate:
        :param create:
        :param create_new:
        """

        self._mutate = mutate
        self._mate = mate
        self._create_from_population = create_from_population
        self._create_new = create_new
        self._compile = compile_
        self._safe_compile = None
        self._eliminate = eliminate
        self._max_retry = max_retry
        self._evaluate = None
        self._evaluate_callback = evaluate_callback
        self.evaluate = None

        self._completed_evaluations = completed_evaluations

    def wait_next(self, async_evaluator):
        future = async_evaluator.wait_next()
        if future.result is not None:
            evaluation = future.result
            if isinstance(evaluation, Sequence):
                # This signature is currently only for an ASHA evaluation result
                evaluation, loss, rung, full_evaluation = evaluation
                if not full_evaluation:
                    # We don't process low-fidelity evaluations here (for now?).
                    return future

            individual = evaluation.individual
            log_event(
                log,
                TOKENS.EVALUATION_RESULT,
                individual.fitness.start_time,
                individual.fitness.wallclock_time,
                individual.fitness.process_time,
                individual.fitness.values,
                individual._id,
                individual.pipeline_str(),
            )
            if self._evaluate_callback is not None:
                self._evaluate_callback(evaluation)

        elif future.exception is not None:
            log.warning(f"Error raised during evaluation: {str(future.exception)}.")
        return future

    def try_until_new(self, operator, *args, **kwargs):
        for _ in range(self._max_retry):
            individual, log_args = operator(*args, **kwargs)
            if str(individual.main_node) not in self._completed_evaluations:
                return individual, log_args
        else:
            log.debug(f"50 iterations of {operator.__name__} did not yield new ind.")
            # For progress on solving this, see #11
            return individual, log_args

    def mate(self, ind1: Individual, ind2: Individual, *args, **kwargs):
        def mate_with_log():
            new_individual1, new_individual2 = ind1.copy_as_new(), ind2.copy_as_new()
            self._mate(new_individual1, new_individual2, *args, **kwargs)
            log_args = [TOKENS.CROSSOVER, new_individual1._id, ind1._id, ind2._id]
            return new_individual1, log_args

        individual, log_args = self.try_until_new(mate_with_log)
        log_event(log, *log_args)
        return individual

    def mutate(self, ind: Individual, *args, **kwargs):
        def mutate_with_log():
            new_individual = ind.copy_as_new()
            mutator = self._mutate(new_individual, *args, **kwargs)
            log_args = [TOKENS.MUTATION, new_individual._id, ind._id, mutator.__name__]
            return new_individual, log_args

        ind, log_args = self.try_until_new(mutate_with_log)
        log_event(log, *log_args)
        return ind

    def individual(self, *args, **kwargs):
        expression = self._create_new(*args, **kwargs)
        if self._safe_compile is not None:
            compile_ = self._safe_compile
        else:
            compile_ = self._compile
        return Individual(expression, to_pipeline=compile_)

    def create(self, *args, **kwargs):
        return self._create_from_population(self, *args, **kwargs)

    def eliminate(self, *args, **kwargs):
        return self._eliminate(*args, **kwargs)


from string import Template
from skyfield.api import load

class Celestial:
    def __init__(self, name):
        self.name = name
        self.caption = name.capitalize()
        self.set_object()

    def set_object(self):
        planets = load('de421.bsp')
        print(planets)
        self.object = planets[self.name]

    def observe(self, location, time):
        astrometric = location.position.at(time.astrometric_dt).observe(self.object).apparent()
        obj_name = self.caption
        loc_name = location.name
        alt, az, distance = astrometric.altaz()
        tm = time.local_dt
        observation = Template(
            'Obserwuję ${obj_name} w miejscowości ${loc_name} o czasie $tm: * Azymut: ${az} | * Wysokość: ${alt}').substitute(
            obj_name=obj_name, loc_name=loc_name, tm=tm, az=az, alt=alt)
        print(observation)

    def get_observation(self, location, time):
        astrometric = location.position.at(time.astrometric_dt).observe(self.object).apparent()
        obj_name = self.caption
        loc_name = location.name
        alt, az, distance = astrometric.altaz()
        tm = time.local_dt

        observation = {
            'objective': obj_name,
            'azimuth': az.degrees,
            'altitude': alt.degrees,
            'place': loc_name,
            'time': tm.strftime("%d.%m.%Y, %H:%M")
        }
        return observation