#! /usr/bin/env python3

import sys
import copy
import time
import json
import hashlib
import logging
import websocket
import threading
import asyncio

from . import formatter

from . import websocket_api

## sets up the socket BASE for binances socket API.
SOCKET_BASE = 'wss://stream.binance.com:9443'
FUTURE_BASE = 'wss://fstream.binance.com'

class Binance_SOCK:

    def __init__(self, streams, isFuture=False):
        '''
        Setup the connection and setup data containers and management variables for the socket.
        '''
        self.MAX_REQUEST_ITEMS      = 10
        self.requested_items        = {}

        self.last_data_recv_time    = 0

        self.socketRunning          = False
        self.socketBuffer           = {}
        self.ws                     = None
        self.stream_names           = streams
        self.query                  = ''
        self.id_counter             = 0

        self.BASE_CANDLE_LIMIT      = 200
        self.BASE_DEPTH_LIMIT       = 10
        self.isFuture               = isFuture

        ## For locally managed data.
        self.live_and_historic_data = False
        self.candle_data            = {}
        self.book_data              = {}
        self.ticker_data            = {}
        self.mark_price             = {}
        self.best_ask               = {}
        self.best_bid               = {}
        self.reading_books          = False

        self.userDataStream_added   = False
        self.listen_key             = None

    def build_query(self):
        self.query = ''
        url = SOCKET_BASE
        if (self.isFuture):
            url = FUTURE_BASE

        if len(self.stream_names) == 0 or self.stream_names == []:
            return('NO_STREAMS_SET')

        elif len(self.stream_names) == 1:
            query = '{0}/ws/{1}'.format(url, self.stream_names[0])

        else:
            query = '{0}/stream?streams='.format(url)

            for i, stream_name in enumerate(self.stream_names):
                query += stream_name
                if i != len(self.stream_names) - 1:
                    query+='/'

        self.query = query
        return('QUERY_BUILT_SUCCESSFULLY')

    def clear_query(self):
        self.query              = ''
        self.stream_names       = []
        self.candles_markets    = []
        self.book_markets       = []

        return('QUERY_CLEARED')

    ## ------------------ [DATA_ACCESS_ENDPOINT] ------------------ ##
    def get_live_depths(self, symbol=None):
        got_books = False
        return_books = self.book_data

        # while not(got_books):
        #     got_books = True
        #     for key in self.book_data:
        #         try:
        #             ask_Price_List = self._orderbook_sorter_algo(copy.deepcopy(self.book_data[key]['a']), 'ask')
        #             bid_Price_List = self._orderbook_sorter_algo(copy.deepcopy(self.book_data[key]['b']), 'bid')
        #             return_books.update({key:{'a':ask_Price_List, 'b':bid_Price_List}})
        #         except RuntimeError as error:
        #             if error == 'dictionary changed size during iteration':
        #                 print('dodged book error')
        #             got_books = False
        #             break

        if symbol:
            if not symbol in return_books:
                #print(return_books)
                pass
            return(return_books[symbol])

        return(return_books)

    def get_live_candles(self, symbol=None):
        if symbol:
            return(self.candle_data[symbol])
        return(self.candle_data)

    def get_live_ticker(self, symbol=None):
        if (symbol):
            return(self.ticker_data[symbol])
        return(self.ticker_data)

    def get_live_markPrice(self, symbol=None):
        if symbol:
            return (self.mark_price[symbol])
        return (self.mark_price)
    def get_best_ask(self,symbol):
        return self.best_ask[symbol]
    def get_best_bid(self,symbol):
        return self.best_bid[symbol]

    ## ------------------ [MANUAL_CALLS_EXCLUSIVE] ------------------ ##
    def subscribe_streams(self, **kwargs):
        return(self._send_message('SUBSCRIBE', **kwargs))

    def unsubscribe_streams(self, **kwargs):
        return(self._send_message('UNSUBSCRIBE', **kwargs))

    def get_current_streams(self):
        return(self._send_message('LIST_SUBSCRIPTIONS'))

    def set_property(self, **kwargs):
        ''' combined = true'''
        return(self._send_message('SET_PROPERTY', **kwargs))

    def get_property(self):
        return(self._send_message('GET_PROPERTY'))

    ## ------------------ [WEBSOCKET_EXCLUSIVE] ------------------ ##
    def set_aggTrade_stream(self, **kwargs):
        return(self._param_check(websocket_api.set_aggTrade_stream, kwargs))

    def set_trade_stream(self, **kwargs):
        return(self._param_check(websocket_api.set_trade_stream, kwargs))

    def set_candle_stream(self, **kwargs):
        return(self._param_check(websocket_api.set_candle_stream, kwargs))

    def set_miniTicker_stream(self, **kwargs):
        return(self._param_check(websocket_api.set_miniTicker_stream, kwargs))

    def set_global_miniTicker_stream(self):
        return(self._param_check(websocket_api.set_global_miniTicker_stream))

    def set_ticker_stream(self, **kwargs):
        return(self._param_check(websocket_api.set_ticker_stream, kwargs))

    def set_gloal_ticker_stream(self):
        return(self._param_check(websocket_api.set_gloal_ticker_stream))

    def set_bookTicker_stream(self, **kwargs):
        return(self._param_check(websocket_api.set_bookTicker_stream, kwargs))

    def set_global_bookTicker_stream(self):
        return(self._param_check(websocket_api.set_global_bookTicker_stream))

    def set_partialBookDepth_stream(self, **kwargs):
        return(self._param_check(websocket_api.set_partialBookDepth_stream, kwargs))

    def set_manual_depth_stream(self, **kwargs):
        return(self._param_check(websocket_api.set_manual_depth_stream, kwargs))

    ## ------------------ [FULL_DATA_EXCLUSIVE] ------------------ ##
    def set_live_and_historic_combo(self, rest_api):
        if not(self.live_and_historic_data):
            tasks = []
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            for stream in self.stream_names:
                symbol = stream.split('@')[0].upper()
                if 'kline' in stream:
                    tasks.append(loop.create_task(self._set_initial_candles(symbol, stream.split('_')[1], rest_api)))
                if 'depth' in stream:
                    tasks.append(loop.create_task(self._set_initial_depth(symbol, rest_api)))
                time.sleep(0.2)
            loop.run_until_complete(asyncio.gather(*tasks))
            RETURN_MESSAGE = 'STARTED_HISTORIC_DATA'
        else:
            if self.candle_data != {}:
                self.candle_data = {}

            RETURN_MESSAGE = 'STOPPED_HISTORIC_DATA'

        self.live_and_historic_data = not(self.live_and_historic_data)

        return(RETURN_MESSAGE)

    def set_live_and_historic_depth(self, rest_api):
        if not(self.live_and_historic_data):
            tasks = []
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            for stream in self.stream_names:
                symbol = stream.split('@')[0].upper()
                if 'depth' in stream:
                    tasks.append(loop.create_task(self._set_initial_depth(symbol, rest_api)))
                time.sleep(0.1)
            loop.run_until_complete(asyncio.gather(*tasks))
            RETURN_MESSAGE = 'STARTED_HISTORIC_DATA'
        else:
            if self.book_data != {}:
                self.book_data = {}

            RETURN_MESSAGE = 'STOPPED_HISTORIC_DATA'

        self.live_and_historic_data = not(self.live_and_historic_data)

        return(RETURN_MESSAGE)

    def set_live_and_historic_ticker(self,rest_api):
        if not(self.live_and_historic_data):
            if (len(self.stream_names) > 40):
                res = rest_api.get_future_24h_ticker()
                for sym in res:
                    hist = formatter.format_ticker(sym, "REST")
                    self.ticker_data.update({sym["symbol"]:hist})
                RETURN_MESSAGE = 'STARTED_HISTORIC_DATA'
            else:
                tasks = []
                loop = asyncio.new_event_loop()
                asyncio.set_event_loop(loop)
                for stream in self.stream_names:
                    symbol = stream.split('@')[0].upper()
                    if 'ticker' in stream:
                        tasks.append(loop.create_task(self._set_initial_ticker(symbol, rest_api)(symbol, stream.split('_')[1], rest_api)))
                    time.sleep(0.1)
                loop.run_until_complete(asyncio.gather(*tasks))
            RETURN_MESSAGE = 'STARTED_HISTORIC_DATA'
        else:
            if self.ticker_data != {}:
                self.ticker_data = {}

            RETURN_MESSAGE = 'STOPPED_HISTORIC_DATA'

        self.live_and_historic_data = not(self.live_and_historic_data)

        return(RETURN_MESSAGE)

    def set_live_and_historic_markPrice(self, rest_api):
        if not(self.live_and_historic_data):
            if (len(self.stream_names) > 40):
                res = rest_api.get_mark_price()
                for sym in res:
                    data = formatter.format_markPrice(sym,"REST")
                    self.ticker_data.update({sym["symbol"]:data})
                RETURN_MESSAGE = 'STARTED_HISTORIC_DATA'
            else:
                tasks = []
                loop = asyncio.new_event_loop()
                asyncio.set_event_loop(loop)
                for stream in self.stream_names:
                    symbol = stream.split('@')[0].upper()
                    if 'ticker' in stream:
                        tasks.append(loop.create_task(self._set_initial_ticker(symbol, rest_api)(symbol, stream.split('_')[1], rest_api)))
                    time.sleep(0.1)
                loop.run_until_complete(asyncio.gather(*tasks))
            RETURN_MESSAGE = 'STARTED_HISTORIC_DATA'
        else:
            if self.candle_data != {}:
                self.candle_data = {}

            RETURN_MESSAGE = 'STOPPED_HISTORIC_DATA'

        self.live_and_historic_data = not(self.live_and_historic_data)

        return(RETURN_MESSAGE)

    ## ------------------ [USER_DATA_STREAM_EXCLUSIVE] ------------------ ##
    def set_userDataStream(self, AUTHENTICATED_REST, user_data_stream_type, remove_stream=False):
        if remove_stream:
            message = self._param_check(None, {'listenKey':self.listen_key, 'remove_stream':True})
            self.listen_key = None
        else:
            if self.listen_key == None:

                key_auth = AUTHENTICATED_REST.get_listenKey(user_data_stream_type)
                listen_key = key_auth['listenKey']

                message = self._param_check(None, {'listenKey':listen_key})
                self.listen_key = listen_key

                logging.info('[SOCKET_MASTER] Starting local managing')
                lkkaT = threading.Thread(target=self.listenKey_keepAlive, args=(AUTHENTICATED_REST,user_data_stream_type))
                lkkaT.start()

        return(message)

    def listenKey_keepAlive(self, AUTHENTICATED_REST, user_data_stream_type):
        lastUpdate = time.time()

        while self.listen_key != None:
            if (lastUpdate + 1800) < time.time():
                AUTHENTICATED_REST.send_listenKey_keepAlive(user_data_stream_type, listenKey=self.listen_key)
                lastUpdate = time.time()

            time.sleep(1)

    def _param_check(self, api_info, users_passed_parameters=None):
        if 'listenKey' not in users_passed_parameters:
            if api_info.params != None:
                missingParameters = []

                if 'symbol' in users_passed_parameters:
                    if '-' in users_passed_parameters['symbol']:
                        base, quote = users_passed_parameters['symbol'].split('-')
                        users_passed_parameters.update({'symbol':(quote+base).lower()})

                if 'R' in api_info.params:
                    for param in api_info.params['R']:
                        if not(param in users_passed_parameters):
                            missingParameters.append(param)

                if len(missingParameters) >= 1:
                    return('MISSING_REQUIRED_PARAMETERS', missingParameters)

                if 'O' in api_info.params:
                    allParams = api_info.params['R'] + api_info.params['O']
                else:
                    allParams = api_info.params['R']
                unknownParams = []

                for param in users_passed_parameters:
                    if not(param in allParams):
                        unknownParams.append(param)

                if len(unknownParams) >= 1:
                    return('UNEXPECTED_PARAMETERS', unknownParams)

                stream_name = api_info.endpoint

                for param in allParams:
                    if param == 'local_manager':
                        continue

                    if param in users_passed_parameters:
                        stream_name = stream_name.replace('<{0}>'.format(param), users_passed_parameters[param])
                    else:
                        stream_name = stream_name.replace('<{0}>'.format(param), '')

                if stream_name[-1] == '@':
                    stream_name = stream_name[:-1]

            else:
                if users_passed_parameters != None and users_passed_parameters != {}:
                    return('ENDPOINT_TAKES_NO_PARAMETERS_BUT_SOME_WHERE_GIVEN', users_passed_parameters)

                stream_name = api_info.endpoint
        else:
            stream_name = users_passed_parameters['listenKey']

        if 'remove_stream' in users_passed_parameters:
            if users_passed_parameters['remove_stream']:
                if stream_name in self.stream_names:
                    self.stream_names.remove(stream_name)
                return({'result':'REMOVED_STREAM_NAME', 'stream':stream_name})

                if self.ws != None and self.socketRunning:
                    self.unsubscribe_streams(params=[stream_name])

        else:
            if stream_name in self.stream_names:
                return('STREAM_[{0}]_ALREADY_EXISTS'.format(stream_name))
            self.stream_names.append(stream_name)

            if self.ws != None and self.socketRunning:
                self.subscribe_streams(params=[stream_name])

                if self.query.split('/')[3] == 'ws':
                    self.set_property(params=['combined',True])

            return({'result':'CREATED_STREAM_NAME', 'stream':stream_name})

    def start(self):
        '''
        This is used to start the socket.
        '''
        if self.socketRunning:
            return('SOCKET_STILL_RUNNING_PLEASE_RESTART')

        ## -------------------------------------------------------------- ##
        ## Here the sockets URL is set so it can be connected to.NO_STREAMS_SET
        logging.debug('[SOCKET_MASTER] Setting up socket stream URL.')
        if self.query == '':
            if self.build_query() == 'NO_STREAMS_SET':
                return('UNABLE_TO_START_NO_STREAMS_SET')
        self.destURL = self.query

        ## -------------------------------------------------------------- ##
        ## Here the 'create_socket' function is called to attempt a connection to the socket.
        logging.debug('[SOCKET_MASTER] Setting up socket connection.')
        self._create_socket()

        ## -------------------------------------------------------------- ##
        # This block is used to test connectivity to the socket.
        conn_timeout = 5
        while not self.ws.sock or not self.ws.sock.connected and conn_timeout:
            time.sleep(5)
            conn_timeout -= 1

            if not conn_timeout:
                ## If the timeout limit is reached then the websocket is force closed.
                self.ws.close()
                raise websocket.WebSocketTimeoutException('Couldn\'t connect to WS! Exiting.')

        self.socketRunning = True
        logging.info('[SOCKET_MASTER] Sucessfully established the socket.')

    def stop(self):
        self.ws.close()

        while self.socketRunning:
            time.sleep(0.2)

        self.socketRunning = False
        self.socketBuffer = {}
        self.ws = None

    def _create_socket(self):
        '''
        This is used to initilise connection and set it up to the exchange.
        '''
        self.ws = websocket.WebSocketApp(self.destURL,
            on_open = self._on_Open,
            on_message = self._on_Message,
            on_error = self._on_Error,
            on_close = self._on_Close,
            on_ping = self._on_Ping,
            on_pong = self._on_Pong)

        wsthread = threading.Thread(target=lambda: self.ws.run_forever())
        wsthread.start()

    def _send_message(self, method, params=None):

        message = {'method':method,
                'id':self.id_counter}

        if params != None and params != []:
            message.update({'params':params})

        message = json.dumps(message)

        response_data = self.ws.sock.send(message)

        keys = self.requested_items.keys()

        if len(keys) > self.MAX_REQUEST_ITEMS:
            del self.requested_items[min(keys)]

        self.requested_items.update({self.id_counter:None})
        self.id_counter += 1
        return(self.id_counter)

    def _on_Open(self, wsapp):
        '''
        This is called to manually open the websocket connection.
        '''
        logging.debug('[SOCKET_MASTER] Websocket Opened.')

    def _on_Message(self, wsapp, message):
        '''
        This is used to handle any messages recived via the websocket.
        '''
        try:
            raw_data = json.loads(message)
        except Exception as e:
            print('section 2')
            print(e)
            raw_data = None

        self.last_data_recv_time = time.time()

        if raw_data != None:
            if 'data' in raw_data:
                data = raw_data['data']
            else:
                data = raw_data

            if 'id' in data:
                if int(data['id']) in self.requested_items:
                    if data['result'] == None:
                        self.requested_items[int(data['id'])] = True
                    else:
                        self.requested_items[int(data['id'])] = data['result']

            if 'e' in data:
                if self.live_and_historic_data:
                    if data['e'] == 'kline':
                        self._update_candles(data)
                    elif data['e'] == 'depthUpdate':
                        self._update_depth(data)
                    elif data['e'] == '24hrMiniTicker':
                        self._update_ticker(data)
                    elif data['e'] == 'markPriceUpdate':
                        formatted = formatter.format_markPrice(data, 'SOCK')
                        self.mark_price[data['s']] = formatted

                    else:
                        if 'outboundAccountInfo' == data['e']:
                            self.socketBuffer.update({data['e']:data})
                        elif 'outboundAccountPosition' == data['e']:
                            self.socketBuffer.update({data['e']:data})
                        else:
                            if data['e'] == 'balanceUpdate':
                                pass
                            else:
                                try:
                                    self.socketBuffer.update({data['s']:{data['e']:data}})
                                except Exception as e:
                                    print(e)
                                    print('section 1')
                                    print(raw_data)
                else:
                    if data['e'] == 'bookTicker':
                        self.best_ask[data['s']] = float(data['a'])
                        self.best_bid[data['s']] = float(data['b'])
                    else:
                        self.socketBuffer.update({data['e']:data})

    def _on_Ping(self, wsapp, message):
        '''
        This is called to manually open the websocket connection.
        '''
        logging.debug('[SOCKET_MASTER] Websocket ping.')

    def _on_Pong(self, wsapp, message):
        '''
        This is called to manually open the websocket connection.
        '''
        logging.debug('[SOCKET_MASTER] Websocket pong.')

    def _on_Error(self, wsapp, error):
        '''
        This is called when the socket recives an connection based error.
        '''
        logging.warning('[SOCKET_MASTER] Socket error: {0}'.format(error))

    def _on_Close(self, wsapp):
        '''
        This is called for manually closing the websocket.
        '''
        self.socketRunning = False
        logging.info('[SOCKET_MASTER]: Socket closed.')

    async def _set_initial_candles(self, symbol, interval, rest_api):
        try:
            hist_candles = rest_api.get_custom_candles(symbol=symbol, interval=interval, limit=self.BASE_CANDLE_LIMIT, isFuture=self.isFuture)
        except Exception as error:
            logging.critical('[SOCKET_MASTER] _initial_candles error {0}'.format(error))
            logging.warning('[SOCKET_MASTER] _initial_candles {0}'.format(hist_candles))
        self.candle_data.update({symbol:hist_candles})

    async def _set_initial_depth(self, symbol, rest_api):
        try:
            if (self.isFuture):
                rest_data = rest_api.get_future_orderBook(symbol=symbol, limit=self.BASE_DEPTH_LIMIT)
            else:
                rest_data = rest_api.get_orderBook(symbol=symbol, limit=self.BASE_DEPTH_LIMIT)
            hist_books = formatter.format_depth(rest_data, 'REST')
        except Exception as error:
            logging.critical('[SOCKET_MASTER] _set_initial_depth error {0}'.format(error))
            logging.warning('[SOCKET_MASTER] _set_initial_depth {0}'.format(rest_data))
        self.book_data.update({symbol:hist_books})

    async def _set_initial_ticker(self, symbol, rest_api):
        try:
            rest_data = rest_api.get_future_24h_ticker(symbol=symbol)
            hist_ticker = formatter.format_ticker(rest_data, 'REST')
        except Exception as error:
            logging.critical('[SOCKET_MASTER] _initial_candles error {0}'.format(error))
            logging.warning('[SOCKET_MASTER] _initial_candles {0}'.format(hist_ticker))
        self.ticker_data.update({symbol:hist_ticker})

    async def _set_initial_premium(self, symbol, rest_api):
        try:
            rest_data = rest_api.get_mark_price(symbol=symbol)
        except Exception as error:
            logging.critical('[SOCKET_MASTER] _initial_candles error {0}'.format(error))
        self.ticker_data.update({symbol:rest_data["markPrice"]})

    def _update_ticker(self, data):
        ticker = formatter.format_ticker(data, 'SOCK')

        self.ticker_data[data['s']] = ticker

    def _update_candles(self, data):
        rC = data['k']

        live_candle_data = formatter.format_candles(rC, 'SOCK')

        if live_candle_data[0] == self.candle_data[rC['s']][0][0]:
            self.candle_data[rC['s']][0] = live_candle_data

        else:
            if live_candle_data[0] > self.candle_data[rC['s']][0][0]:
                self.candle_data[rC['s']].insert(0, live_candle_data)
                self.candle_data[rC['s']] = self.candle_data[rC['s']][:self.BASE_CANDLE_LIMIT]

    def _update_depth(self, data):
        live_depth_data = formatter.format_depth(data, 'SOCK')

        lastUpdate = live_depth_data['a'][0][0]

        symbol = data['s']

        self.book_data[symbol] = live_depth_data
        # for lask in live_depth_data['a']:
        #     if lask[1] in self.book_data[symbol]['a']:
        #         if lask[2] == 0.0:
        #             del self.book_data[symbol]['a'][lask[1]]
        #             continue

        #         if self.book_data[symbol]['a'][lask[1]][0] >= lask[0]:
        #             continue

        #     self.book_data[symbol]['a'].update({lask[1]:[lask[0],lask[2]]})

        # for lbid in live_depth_data['b']:
        #     if lbid[1] in self.book_data[symbol]['b']:
        #         if lbid[2] == 0.0:
        #             del self.book_data[symbol]['b'][lbid[1]]
        #             continue

        #         if self.book_data[symbol]['b'][lbid[1]][0] >= lbid[0]:
        #             continue

        #     self.book_data[symbol]['b'].update({lbid[1]:[lbid[0],lbid[2]]})

        # all_ask_prices = list(self.book_data[data['s']]['a'].keys())
        # if (len(all_ask_prices) > self.BASE_CANDLE_LIMIT):
        #     all_ask_prices_to_cut = []
        #     for aPrice in all_ask_prices:
        #         if (self.book_data[symbol]['a'][aPrice][0] < lastUpdate):
        #             all_ask_prices_to_cut.append(aPrice)
        #     for aPrice in all_ask_prices_to_cut:
        #         if aPrice in self.book_data[symbol]['a']:
        #             del self.book_data[symbol]['a'][aPrice]

        # all_bid_prices = list(self.book_data[symbol]['b'].keys())
        # if (len(all_bid_prices) > self.BASE_CANDLE_LIMIT):
        #     all_bid_prices_to_cut = []
        #     for bPrice in all_bid_prices:
        #         if (self.book_data[symbol]['b'][bPrice][0] < lastUpdate):
        #             all_bid_prices_to_cut.append(bPrice)
        #     for bPrice in all_bid_prices_to_cut:
        #         if bPrice in self.book_data[symbol]['b']:
        #             del self.book_data[symbol]['b'][bPrice]

    def _orderbook_sorter_algo(self, books_dict_base, side):
        book_depth_organised = []

        prices_list = list(books_dict_base.keys())

        if side == 'ask':
            prices_list.sort()
        elif side == 'bid':
            prices_list.sort(reverse=True)

        prices_list = prices_list

        for price in prices_list:
            if price in books_dict_base:
                book_depth_organised.append([price, books_dict_base[price][1]])

        return(book_depth_organised)


from proc import *
from model import *
# from test import *

import numpy as np
import matplotlib.pyplot as plt

#n = eval(input("\n\nEnter number of iterations: ")) #1000
#l = eval(input("Enter learning rate: ")) #0.001
#p = bool(eval(input("Enter 1 to display cost else 0: "))) #False

n=6000
l=0.0001971
p=0

d = model(train_set_x, train_set_y, eval_set_x, eval_set_y, num_iterations = n, learning_rate = l, print_cost = p)

#retrieving essential data about model from dictionary 'd'
costs = d["costs"]
learning_rate = d["learning_rate"]

#saving the trained model for future use for evaling
np.save('trained_model12.npy',d)

#ploting cost vs iteration graph
plt.plot((costs))
plt.ylabel('cost')
plt.xlabel('iterations (per tens) ')
plt.title("Learning rate = " + str(learning_rate))
plt.show()

# test()


from classes import Collector, DBManager
from utils import connect_or_create_db, create_tables, load_db_tables

company_names = ['LC Group', 'IBS', 'Rover', 'R-Style', 'Rosco', 'Марвел', 'Verysell', 'Yandex', 'Газпром', "Тинькофф"]

if __name__ == '__main__':
    conn, cur = connect_or_create_db('hh_vacancies')
    create_tables(conn, cur)

    collector = Collector()
    for company in company_names:
        collector.add_hh_vacancies(company)

    load_db_tables(cur, collector.vacancies)
    conn.commit()

    db_manager = DBManager(conn, cur)
    # print(db_manager.get_companies_and_vacancies_count())
    # print(db_manager.get_all_vacancies())
    # print(db_manager.get_avg_salary())
    # print(db_manager.get_vacancies_with_higher_salary())
    print(db_manager.get_vacancies_with_keyword(['инженер', 'редактор']))
    cur.close()
    conn.close()


#!/usr/bin/env python2
from multiprocessing import Process
import os

import portals
from download_ckan import download as ckan
from download_socrata import download as socrata
from download_opendatasoft import download as opendatasoft

ROOT_DIR = 'portals'

def create(portal_type, func, portal_urls):
    '''
    Args:
        portal_type: "ckan", "opendatasoft" or "socrata"
        func: function to download all datasets given a portal and directory
        portal_urls: List of portal domains
    Returns:
        A list of processes
    '''
    processes = {}

    for portal in portal_urls:
        args = (portal, os.path.join(ROOT_DIR, portal_type))
        processes[(portal_type, portal)] = Process(target = func, args = args)

    return processes

def start(processes):
    'Start all of the processes.'
    for process in processes.values():
        process.start()

def join(processes):
    'Wait for all of the processes to end.'
    for process in processes.values():
        process.join()

def kill(processes):
    'Kill all of the processes.'
    for process in processes.values():
        process.terminate()

def main():
    import signal
    import sys

    # p = create('ckan', ckan, portals.ckan)
    # p = create('opendatasoft', opendatasoft, portals.opendatasoft)
    p = create('socrata', socrata, portals.socrata)

    def signal_handler(signal, frame):
        kill(p)
        sys.exit(0)

    signal.signal(signal.SIGINT, signal_handler)

    start(p)
    join(p)

if __name__ == '__main__':
    main()


import os
import cv2
import sys
import numpy as np
import glob

def progressbar(current, total, num=40, prefix=""):
    sys.stdout.write("\r{} {}/{} |{}{}| {:.2f}%".format(prefix, current, total,
                                                        "*" * int(num * current / total),
                                                        " " * (num - int(num * current / total)),
                                                        100 * current / total))
    sys.stdout.flush()
    if current == total:
        print("")

def depth_raw2_rgb(depth):
    min, max = np.min(depth), np.max(depth)
    dep = (depth - min) / (max - min)

    dep = (dep * 255).astype(np.uint8)
    return dep

def frames2video(save_path, frames, fps=24):
    base_folder = os.path.split(save_path)[0]
    if not os.path.exists(base_folder):
        os.makedirs(base_folder)

    H, W = frames[0].shape[0:2]
    img_size = (W, H)

    fourcc = cv2.VideoWriter_fourcc('M', 'J', 'P', 'G')
    video_writer = cv2.VideoWriter(save_path, fourcc, fps, img_size)

    num = 0
    for frame in frames:
        video_writer.write(frame)
        num += 1
        progressbar(num, len(frames), prefix="write video")

    video_writer.release()

def framepaths2video(save_path, frames_paths, fps=24):
    base_folder = os.path.split(save_path)[0]
    if not os.path.exists(base_folder):
        os.makedirs(base_folder)

    H, W = cv2.imread(frames_paths[0]).shape[0:2]
    img_size = (W, H)

    fourcc = cv2.VideoWriter_fourcc('M', 'J', 'P', 'G')
    video_writer = cv2.VideoWriter(save_path, fourcc, fps, img_size)

    num = 0
    for fp in frames_paths:
        frame = cv2.imread(fp)
        video_writer.write(frame)
        num += 1
        progressbar(num, len(frames_paths), prefix="write video")

    video_writer.release()

if __name__ == '__main__':
    rgb_folder = r"J:\datasets\Scannet\data\scans\scene0000_01\rgbd\rgb"
    depth_folder = r"J:\datasets\Scannet\data\scans\scene0000_01\rgbd\depth"

    #rgb_files = glob.glob(os.path.join(rgb_folder, "*.jpg"))
    #framepaths2video("../Data/demo/rgb.mp4", rgb_files, fps=30)
    depth_raw_files = glob.glob(os.path.join(depth_folder, "*.png"))

    tmp_folder = "./depth_tmp"
    if not os.path.exists(tmp_folder):
        os.makedirs(tmp_folder)
    for i, df in enumerate(depth_raw_files):
        if i == 28:
            continue
        dim = cv2.imread(df)
        dim = depth_raw2_rgb(dim)
        cv2.imwrite(os.path.join(tmp_folder, "%06d.png" % i), dim)
        progressbar(i+1, len(depth_raw_files))

    depth_files = glob.glob(os.path.join(tmp_folder, "*.png"))
    framepaths2video("../Data/demo/depth.mp4", depth_files, fps=30)


import tkinter
from tkinter import *

import ui
from virtual_assistant import *

import threading

global command
command = ""

#
# threading
#
def change_speak_button_status():
    speakButton.config(image=voiceWaveIcon)

def listen():
    playsound.playsound('sound/data_2.wav')
    global isListening
    global command
    try:
        command = record_audio()
        respond(command)
        isListening = not isListening
        speakButton.config(image=blueEdgeMicIcon)
    except sr.UnknownValueError:
        isListening = not isListening
        speakButton.config(image=blueEdgeMicIcon)
    except sr.RequestError:
        isListening = not isListening
        speakButton.config(image=blueEdgeMicIcon)

#
# UI EVENT HANDLERS
#
def on_click_speak_button():
    heart_button.place(relx=-1.0, rely=-1.0, anchor=N)

    # heart_rate
    measure_label.place_forget()
    warning_label.place_forget()
    heart_rate_label.place_forget()
    spo2_label.place_forget()

    # weather
    sun_button.place_forget()
    city_name_label.place_forget()
    temperature_label.place_forget()
    humidity_label.place_forget()
    weather_label.place_forget()
    wind_label.place_forget()

    # location
    ui.location_button.place_forget()
    location_label.place_forget()

    # name
    name_label.place_forget()
    name_button.place_forget()

    # time
    time_button.place_forget()
    time_label.place_forget()

    global command
    global isListening
    if not isListening:
        isListening = not isListening
        # threading.Thread(target=change_speak_button_status).start()
        change_speak_button_status()
        threading.Thread(target=listen).start()

def on_enter_speak_button(event):
    if not isListening:
        speakButton.config(image=blueMicIcon)

def on_leave_speak_button(event):
    if not isListening:
        speakButton.config(image=blueEdgeMicIcon)

def on_click_ask_entry(event):  # textfield function
    askEntry.configure(state=NORMAL)
    # text = askEntry.get()
    # print(text)
    askEntry.delete(0, END)  # delete string in textfield

def on_click_send():
    text = ""
    if askEntry.get() != "Ask me":
        text = askEntry.get()
        print(text)

    # askEntry.configure(state=NORMAL)
    askEntry.delete(0, END)  # delete string in textfield

    # heart_rate
    measure_label.place_forget()
    warning_label.place_forget()
    heart_rate_label.place_forget()
    spo2_label.place_forget()

    # weather
    sun_button.place_forget()
    city_name_label.place_forget()
    temperature_label.place_forget()
    humidity_label.place_forget()
    weather_label.place_forget()
    wind_label.place_forget()

    # location
    ui.location_button.place_forget()
    location_label.place_forget()

    # name
    name_label.place_forget()
    name_button.place_forget()

    # time
    time_button.place_forget()
    time_label.place_forget()

    thread = threading.Thread(target=respond(text))
    thread.run()

def on_focus_out_ask_entry(event):
    if askEntry.get() == "":
        askEntry.delete(0, END)
        askEntry.insert(0, 'Ask me')
    askEntry.configure(state=DISABLED)
    window.focus()

def on_enter_send_button(event):
    sendTextButton.config(image=sendIcon)

def on_leave_send_button(event):
    sendTextButton.config(image=sendOutlineIcon)

def settings():
    pass

def feedback():
    pass

def about():
    pass

def on_click_three_dots_button(event):
    threeDotsMenu.tk_popup(event.x_root, event.y_root)

#
# UI Design
#
window = Tk()
window.bind_all("<Button-1>", lambda event: event.widget.focus_set())  #

# variables #initialize the icons
isListening = False
blueEdgeMicIcon = PhotoImage(file="icon/blue-edge-mic.png")
blueMicIcon = PhotoImage(file="icon/blue-mic.png")
voiceWaveIcon = PhotoImage(file="icon/voice-wave.png")
heartIcon = PhotoImage(file="icon/heart.png")
locationIcon = PhotoImage(file="icon/placeholder.png")
sunIcon = PhotoImage(file="icon/sun.png")
nameIcon = PhotoImage(file="icon/waving-hand.png")
timeIcon = PhotoImage(file="icon/clock.png")

# window
window.geometry("390x640")
window.title("Healthcare Virtual Assistant")
windowIcon = PhotoImage(file="icon/logo.png")
window.iconphoto(True, windowIcon)

# speak button
speakButton = Button(window,
                     image=blueEdgeMicIcon,
                     borderwidth=0,
                     command=on_click_speak_button)
speakButton.place(relx=0.5, rely=1.0, y=-50, anchor=S)
speakButton.bind("<Enter>", on_enter_speak_button)
speakButton.bind("<Leave>", on_leave_speak_button)

# name
name_button = Button(window,
                     image=nameIcon,
                     borderwidth=0)
name_label = Label(window, text="Your heart rate is")

# time
time_button = Button(window,
                     image=timeIcon,
                     borderwidth=0)
time_label = Label(window, text="Your heart rate is")

# heart icon
heart_button = Button(window,
                      image=heartIcon,
                      borderwidth=0)
# heart_button.place(relx=0.5, rely=0.0, y=50, anchor=N)

heart_rate_label = Label(window, text="Your heart rate is")
# heart_rate_label.place(relx=0.5, rely=0.0, anchor=N, y=120)
spo2_label = Label(window, text="Your spo2 is")
# spo2_label.place(relx=0.5, rely=0.0, anchor=N, y=140)
measure_label = Label(ui.window, text=f"Measuring...", font=("Roboto", 14), padx=10)
warning_label = Label(ui.window, text=f"Place your index finger on sensor", font=("Roboto", 14), padx=10)

# weather
sun_button = Button(window,
                    image=sunIcon,
                    borderwidth=0)
city_name_label = Label(ui.window, text=f"Measuring...", font=("Roboto", 14), padx=10)
temperature_label = Label(ui.window, text=f"Measuring...", font=("Roboto", 14), padx=10)
humidity_label = Label(ui.window, text=f"Measuring...", font=("Roboto", 14), padx=10)
weather_label = Label(ui.window, text=f"Measuring...", font=("Roboto", 14), padx=10)
# description_label = None
wind_label = Label(ui.window, text=f"Measuring...", font=("Roboto", 14), padx=10)

# location
location_button = Button(window,
                         image=locationIcon,
                         borderwidth=0)
location_label = Label(ui.window, text=f"Measuring...", font=("Roboto", 14), padx=10)

# BubleText
# bubble_text = BubbleText(10, None, 0.0, 0.0, "Hi, I'm your healthcare virtual assistant. What can I do for you?")
# new_label = Label(window, text="Hi, I'm your healthcare virtual assistant. What can I do for you?")

# Textfield "Ask me"
askEntry = Entry(window,
                 width=35,
                 bg="#F0F0F0",
                 borderwidth=0,
                 font=("Arial", 13))
askEntry.place(relx=0, rely=1.0, anchor=SW, x=10, y=-10)
askEntry.insert(0, 'Ask me')
askEntry.configure(state=DISABLED)
askEntry.bind('<Button-1>', on_click_ask_entry)
askEntry.bind("<FocusOut>", on_focus_out_ask_entry)

# send button
sendOutlineIcon = PhotoImage(file="icon/send-outline.png")
sendIcon = PhotoImage(file="icon/send.png")
sendTextButton = Button(window,
                        image=sendOutlineIcon,
                        borderwidth=0,
                        command=on_click_send)
sendTextButton.bind("<Enter>", on_enter_send_button)
sendTextButton.bind("<Leave>", on_leave_send_button)
sendTextButton.place(relx=1, rely=1, anchor=SE, x=-10, y=-6)

# three-dot menu
threeDotsMenu = Menu(window, tearoff=False)
threeDotsMenu.add_command(label="Settings", command=settings)
threeDotsMenu.add_command(label="Feedback", command=feedback)
threeDotsMenu.add_command(label="About", command=about)
threeDotsIcon = PhotoImage(file="icon/dots.png")
threeDotsButton = Button(window,
                         image=threeDotsIcon,
                         borderwidth=0)
threeDotsButton.bind("<Button-1>", on_click_three_dots_button)
threeDotsButton.place(relx=0, rely=0, x=10, y=10)


'''Write a Python program to find the maximum and minimum numbers
from the specified decimal numbers.'''

mylist = [10.20,20.30,30.40,40.56,50.60]

if 50>30:
    print("number is max number")
else:
    print("number is minimum number")


import uuid
from flask import request
from flask.views import MethodView
from flask_smorest import Blueprint, abort
from schemas import LeaveSchema, LeaveTypeSchema, LeaveUpdateSchema, OfficePostSchema, EmployeeSchema, EmployeeLeaveInfoSchema, LeaveApprovalStatus, LeaveTypeStatus
from models import LeaveModel, OfficePostModel
from db import db
from sqlalchemy.exc import SQLAlchemyError, IntegrityError
import hashlib

blueprint = Blueprint("leaves", __name__, description="Operations on leaves")

@blueprint.route("/leave/<string:leave_id>")
class Leave(MethodView):
    @blueprint.response(200, LeaveSchema)
    def get(self, leave_id):
        leave = LeaveModel.query.get_or_404(leave_id)
        return leave

    @blueprint.arguments(LeaveUpdateSchema)
    @blueprint.response(200, LeaveSchema)
    def put(self, leave_data, leave_id):
        leave = LeaveModel.query.get(leave_id)

        leave.leave_approval_status = leave_data["leave_approval_status"]
        db.session.add(leave)
        db.session.commit()

        return leave

@blueprint.route("/leave")
class LeaveList(MethodView):
    @blueprint.response(200, LeaveSchema(many=True))
    def get(self):
        return LeaveModel.query.all()

    @blueprint.arguments(LeaveSchema)
    @blueprint.response(201, LeaveSchema)
    def post(self, leave_data):
        leave = LeaveModel(**leave_data)
        leave.leave_approval_status = 0

        try:
            db.session.add(leave)
            db.session.commit()
        except IntegrityError:
            abort(400, message = "An error occured!")
        except SQLAlchemyError as e:
            abort(500, message = str(leave_data))

        return leave

@blueprint.route("/leave/leave_approval_status/<string:leave_approval_status>")
class LeaveListOnApproval(MethodView):
    @blueprint.response(200, LeaveSchema(many=True))
    def get(self, leave_approval_status):
        return LeaveModel.query.filter_by(leave_approval_status = leave_approval_status)

"""
@blueprint.route("/leave/subordinate_leave/<string:office_post_id>")
class LeaveListSubordinate(MethodView):
    @blueprint.response(200, OfficePostSchema(many=True))
    def get_subordinate(self):
        #office_posts_supervisee = OfficePostModel.query.filter_by(parent_id = office_post_id)
        office_posts_supervisee = OfficePostModel.query.all()
        return office_posts_supervisee
"""

@blueprint.route("/leave/subordinate_leave/<string:office_post_id>")
class LeaveList(MethodView):
    @blueprint.response(200, EmployeeLeaveInfoSchema(many=True))
    def get(self, office_post_id):
        office_post_supervisees =  OfficePostModel.query.filter_by(parent_id = office_post_id)
        employee_supervisees = []

        for office_post_supervisee in office_post_supervisees:
            employee_supervisee = office_post_supervisee.employee
            employee_supervisees.append(employee_supervisee)

        list_employee_leave_info = []

        for employee_supervisee in employee_supervisees:
            leaves_employee = LeaveModel.query.filter_by(employee_id = employee_supervisee.id)

            for leave_employee in leaves_employee:
                if leave_employee.leave_approval_status == 0:
                    employee_leave_info = {
                        "leave_id": leave_employee.id,
                        "employee_id": employee_supervisee.id,
                        "employee_name": employee_supervisee.name,
                        "leave_approval_status": leave_employee.leave_approval_status,
                        "leave_start_date": leave_employee.leave_start_date,
                        "leave_end_date": leave_employee.leave_end_date,
                        "leave_type_name": leave_employee.leave_type.name
                    }
                    print(employee_leave_info)

                    list_employee_leave_info.append(employee_leave_info)

        unique = { each['leave_id'] : each for each in list_employee_leave_info }.values()

        return unique

@blueprint.route("/leave/all_statuses")
class LeaveApprovalList(MethodView):
    @blueprint.response(200, LeaveApprovalStatus(many=True))
    def get(self):
        leaves_employee = LeaveModel.query.all()

        count_leave_pending = 0
        count_leave_approved = 0
        count_leave_rejected = 0

        for leave_employee in leaves_employee:
            if leave_employee.leave_approval_status == 0:
                count_leave_pending += 1
            elif leave_employee.leave_approval_status == 1:
                count_leave_approved += 1
            else:
                count_leave_rejected += 1

        leave_pending = {
            "status_id": 0,
            "status_name": "অপেক্ষমান",
            "status_count": count_leave_pending
        }

        leave_approved = {
            "status_id": 1,
            "status_name": "অনুমোদিত",
            "status_count": count_leave_approved
        }

        leave_rejected = {
            "status_id": 2,
            "status_name": "প্রত্যাখ্যাত",
            "status_count": count_leave_rejected
        }

        leave_status_total = []

        leave_status_total.append(leave_pending)
        leave_status_total.append(leave_approved)
        leave_status_total.append(leave_rejected)

        return leave_status_total

@blueprint.route("/leave/all_types")
class LeaveTypeList(MethodView):
    @blueprint.response(200, LeaveTypeStatus(many=True))
    def get(self):
        leaves_employee = LeaveModel.query.all()

        count_leave_casual = 0
        count_leave_medical = 0
        count_leave_unpaid = 0
        count_leave_earned = 0
        count_leave_maternity = 0

        for leave_employee in leaves_employee:
            if leave_employee.leave_type_id == 1:
                count_leave_casual += 1
            elif leave_employee.leave_type_id == 2:
                count_leave_medical += 1
            elif leave_employee.leave_type_id == 3:
                count_leave_unpaid += 1
            elif leave_employee.leave_type_id == 4:
                count_leave_earned += 1
            else:
                count_leave_maternity += 1

        leave_casual = {
            "type_id": 1,
            "type_name": "ক্যাজুয়াল",
            "type_count": count_leave_casual
        }

        leave_medical = {
            "type_id": 2,
            "type_name": "মেডিক্যাল",
            "type_count": count_leave_medical
        }

        leave_unpaid = {
            "type_id": 3,
            "type_name": "বিনাবেতন",
            "type_count": count_leave_unpaid
        }

        leave_earned = {
            "type_id": 4,
            "type_name": "অর্জিত",
            "type_count": count_leave_earned
        }

        leave_maternity = {
            "type_id": 5,
            "type_name": "মাতৃত্বকালীন",
            "type_count": count_leave_maternity
        }

        leave_type_total = []

        leave_type_total.append(leave_casual)
        leave_type_total.append(leave_medical)
        leave_type_total.append(leave_unpaid)
        leave_type_total.append(leave_earned)
        leave_type_total.append(leave_maternity)

        return leave_type_total


''' import for testing dm_list function '''
import pytest

from src.error import InputError
from src.error import AccessError
from src.server import clear_v2
from src.dm import dm_create_v1
from src.dm import dm_details_v1
# from src.user import user_register
from src.auth import auth_register_v2, auth_login_v2

@pytest.fixture
def clear_register_user_and_reset():
    '''
    This function creates auth and member users
    which are used to test the dm/details function
    '''
    clear_v2()                                                  # Clear data
    user_all = []
    dm_all = []
    auth_register_v2('felix.li@vtub.er',
                     'emptied', 'felix', 'li')
    user_all.append(auth_login_v2('felix.li@vtub.er',
                     'emptied'))               # Create user (auth)

    auth_register_v2('mako.fuka@vtub.er',
                     'passwor', 'mako', 'fuka')
    user_all.append(auth_login_v2('mako.fuka@vtub.er',
                     'passwor'))              # Create user (member)

    auth_register_v2('homou.nene@vtub.er',
                     'ceet2u3', 'homou', 'nene')
    user_all.append(auth_login_v2('homou.nene@vtub.er',
                     'ceet2u3'))             # Create user (member)

    dm_all.append(dm_create_v1(user_all[0]['token'], [ user_all[1]['auth_user_id'],
                                                       user_all[2]['auth_user_id'] ]))
    dm_all.append(dm_create_v1(user_all[1]['token'], [ user_all[2]['auth_user_id'] ]))

    return user_all, dm_all

def test_details_invalid_id(clear_register_user_and_reset):
    '''
    Test if an invalid dm_id is provided
    '''
    user_all, dm_all = clear_register_user_and_reset

    # check dm_all validity
    print(dm_all)

    with pytest.raises(InputError):
        dm_details_v1(user_all[0]['token'], 9999)

def test_details_unauthorised(clear_register_user_and_reset):
    '''
    Test if an user that is not a member calls the function
    '''
    user_all, dm_all = clear_register_user_and_reset

    # check dm_all validity
    print(dm_all)

    auth_register_v2('lu.lu@niji.retired',
                  'conlulu', 'lu', 'lu')
    user_all.append(auth_login_v2('lu.lu@niji.retired',
                  'conlulu'))

    with pytest.raises(AccessError):
        dm_details_v1(user_all[3]['token'], dm_all[0]['dm_id'])

def test_details_type(clear_register_user_and_reset):
    '''
    Test if details return the correct type
    '''

    user_all, dm_all = clear_register_user_and_reset

    # check dm_all validity
    print(dm_all)

    test_return = dm_details_v1(user_all[0]['token'], dm_all[0]['dm_id'])

    assert isinstance(test_return['name'], str)
    assert isinstance(test_return['members'], list)
    assert isinstance(test_return['members'][0]['u_id'], int)
    assert isinstance(test_return['members'][0]['email'], str)
    assert isinstance(test_return['members'][0]['name_first'], str)
    assert isinstance(test_return['members'][0]['name_last'], str)
    assert isinstance(test_return['members'][0]['handle_str'], str)

# reserve a spot for @APP, currently unused


from PyQt5 import QtCore, QtGui, QtWidgets

first_number = 0
second_number = 0
output = 0
choice = 0

#below are the functions

class Ui_MainWindow(object):
    def clear(self):
        self.lineEdit_3.setText("")

    def add(self):
        global first_number
        global second_number
        global output
        first_number = self.lineEdit.text()
        second_number = self.lineEdit_2.text()
        output = float(first_number) + float(second_number)
        self.lineEdit_3.setText(f"{output}")

        print(f"The Result is {output}")

    def multi(self):
        global first_number
        global second_number
        global output
        first_number = self.lineEdit.text()
        second_number = self.lineEdit_2.text()
        output = float(first_number) * float(second_number)
        self.lineEdit_3.setText(f"{output}")
        print(f"The Result is {output}")

    def div(self):
        global first_number
        global second_number
        global output
        first_number = self.lineEdit.text()
        second_number = self.lineEdit_2.text()
        if second_number == 0:
            print("You cant divide by 0")

        else:

            output = float(first_number) / float(second_number)
            self.lineEdit_3.setText(f"{output}")
            print(f"The Result is {output}")

    def sub(self):
        global first_number
        global second_number
        global output
        first_number = self.lineEdit.text()
        second_number = self.lineEdit_2.text()
        output = float(first_number) - float(second_number)
        self.lineEdit_3.setText(f"{output}")
        print(f"The Result is {output}")

    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(593, 537)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(155, 263, 111, 20))
        self.pushButton.setObjectName("pushButton")
        self.pushButton_5 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_5.setGeometry(QtCore.QRect(155, 284, 111, 20))
        self.pushButton_5.setObjectName("pushButton_5")
        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(155, 305, 111, 20))
        self.pushButton_2.setObjectName("pushButton_2")
        self.pushButton_6 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_6.setGeometry(QtCore.QRect(155, 326, 111, 20))
        self.pushButton_6.setObjectName("pushButton_6")
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit.setGeometry(QtCore.QRect(120, 90, 171, 71))
        self.lineEdit.setObjectName("lineEdit")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(300, 105, 111, 51))
        self.label.setObjectName("label")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(300, 175, 111, 31))
        self.label_2.setObjectName("label_2")
        self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_2.setGeometry(QtCore.QRect(120, 170, 171, 41))
        self.lineEdit_2.setObjectName("lineEdit_2")
        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(300, 220, 121, 31))
        self.label_3.setObjectName("label_3")
        self.lineEdit_3 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_3.setGeometry(QtCore.QRect(120, 220, 171, 41))
        self.lineEdit_3.setObjectName("lineEdit_3")
        self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_3.setGeometry(QtCore.QRect(155, 347, 111, 20))
        self.pushButton_3.setObjectName("pushButton_3")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 593, 18))
        self.menubar.setObjectName("menubar")
        self.menutaschenrechner = QtWidgets.QMenu(self.menubar)
        self.menutaschenrechner.setObjectName("menutaschenrechner")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.menubar.addAction(self.menutaschenrechner.menuAction())

        self.pushButton_2.clicked.connect(self.add)
        self.pushButton.clicked.connect(self.multi)
        self.pushButton_5.clicked.connect(self.div)
        self.pushButton_6.clicked.connect(self.sub)
        self.pushButton_3.clicked.connect(self.clear)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton.setText(_translate("MainWindow", "*"))
        self.pushButton_5.setText(_translate("MainWindow", "/"))
        self.pushButton_2.setText(_translate("MainWindow", "+"))
        self.pushButton_6.setText(_translate("MainWindow", "-"))
        self.label.setText(_translate("MainWindow", "1. Zahl"))
        self.label_2.setText(_translate("MainWindow", "2. Zahl"))
        self.label_3.setText(_translate("MainWindow", "Ergebinis"))
        self.pushButton_3.setText(_translate("MainWindow", "clear"))
        self.menutaschenrechner.setTitle(_translate("MainWindow", "taschenrechner"))

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())


#! /usr/bin/python

import sys

seq = sys.argv[1]

def comp1(seq):
    comp = ''
    for s in seq:
        if s == "A":
            comp +="T"
        elif s == "C":
            comp +="G"
        elif s == "G":
            comp +="C"
        elif s == "T":
            comp +="A"
    return comp

if __name__ == "__main__":
    if len(sys.argv) !=2:
        print(f"#usage: python {sys.argv[0]} [string]")
        sys.ext()

    seq = sys.argv[1] #ATGTTATAG
    c1 = comp1(seq)
    print(c1)


from lxml import etree
from xmldiff.patch import Patcher
from copy import deepcopy

class TrackedPatcher(Patcher):

    class TrackedNode:
        def __init__(self, original, modified):
            self.original = original
            self.modified = modified
            self.modifications = []

        def register_modification(self, action):
            self.modifications.append(action)

    def __init__(self):
        self.nodes = []

    def patch(self, actions, tree):

        result = deepcopy(tree)

        original_iter = tree.iter()
        result_iter = result.iter()

        # Associate each node in tree with each node in result
        while True:
            try:
                original_node = original_iter.__next__()
                result_node = result_iter.__next__()
                self.nodes.append(
                    TrackedPatcher.TrackedNode(original_node, result_node)
                )
            except StopIteration:
                break

        for action in actions:
            self.handle_action(action, result)

        return result

    def register_modification(self, action, tree, node):
        modified_nodes = [x.modified for x in self.nodes]
        if node in modified_nodes:
            i = modified_nodes.index(node)
            self.nodes[i].register_modification(action)
        else:
            modified_node = TrackedPatcher.TrackedNode(None, node)
            modified_node.register_modification(action)
            self.nodes.append(modified_node)

    def handle_action(self, action, tree):
        super().handle_action(action, tree)

    def _handle_DeleteNode(self, action, tree):
        node = tree.xpath(action.node)[0]
        node.getparent().remove(node)
        self.register_modification(action, tree, node)

    def _handle_InsertNode(self, action, tree):
        target = tree.xpath(action.target)[0]
        node = target.makeelement(action.tag)
        target.insert(action.position, node)
        self.register_modification(action, tree, node)

    def _handle_RenameNode(self, action, tree):
        node = tree.xpath(action.node)[0]
        node.tag = action.tag
        self.register_modification(action, tree, node)

    def _handle_MoveNode(self, action, tree):
        node = tree.xpath(action.node)[0]
        target = tree.xpath(action.target)[0]
        node.getparent().remove(node)
        target.insert(action.position, node)
        self.register_modification(action, tree, node)

    def _handle_UpdateTextIn(self, action, tree):
        node = tree.xpath(action.node)[0]
        node.text = action.text
        self.register_modification(action, tree, node)

    def _handle_UpdateTextAfter(self, action, tree):
        node = tree.xpath(action.node)[0]
        node.tail = action.text
        self.register_modification(action, tree, node)

    def _handle_UpdateAttrib(self, action, tree):
        node = tree.xpath(action.node)[0]
        # This should not be used to insert new attributes.
        assert action.name in node.attrib
        node.attrib[action.name] = action.value
        self.register_modification(action, tree, node)

    def _handle_DeleteAttrib(self, action, tree):
        node = tree.xpath(action.node)[0]
        del node.attrib[action.name]
        self.register_modification(action, tree, node)

    def _handle_InsertAttrib(self, action, tree):
        node = tree.xpath(action.node)[0]
        # This should not be used to update existing attributes.
        assert action.name not in node.attrib
        node.attrib[action.name] = action.value
        self.register_modification(action, tree, node)

    def _handle_RenameAttrib(self, action, tree):
        node = tree.xpath(action.node)[0]
        assert action.oldname in node.attrib
        assert action.newname not in node.attrib
        node.attrib[action.newname] = node.attrib[action.oldname]
        del node.attrib[action.oldname]
        self.register_modification(action, tree, node)

    def _handle_InsertComment(self, action, tree):
        target = tree.xpath(action.target)[0]
        node = etree.Comment(action.text)
        target.insert(action.position, node)
        self.register_modification(action, tree, node)


from itertools import chain
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.preprocessing import LabelBinarizer
import time
import pycrfsuite
from util import *
from threading import Thread

NUM_THREAD = 4

def word2features(tokens, index, history):
    """
	`tokens`  = a POS-tagged sentence [(w1, t1), ...]
	`index`   = the index of the token we want to extract features for
	`history` = the previous predicted IOB tags
	"""

    # Pad the sequence with placeholders
    tokens = [('__START2__', '__START2__'), ('__START1__', '__START1__')] + list(tokens) + [('__END1__', '__END1__'),
                                                                                ('__END2__', '__END2__')]
    history = ['__START2__', '__START1__'] + list(history)

    # shift the index with 2, to accommodate the padding
    index += 2

    word, pos = tokens[index]
    prevword, prevpos = tokens[index - 1]
    prevprevword, prevprevpos = tokens[index - 2]
    nextword, nextpos = tokens[index + 1]
    nextnextword, nextnextpos = tokens[index + 2]
    previob = history[-1]
    prevpreviob = history[-2]

    return [
        'word=' + word,
        'lemma=' + stemmer.stem(word),
        'pos=' + pos,
        'pos[:2]=' + str(pos[:2]),
        'shape=' + shape(word),
        'word.lower()=' + str(word.lower()),
        'word.isupper()=' + str(word.isupper()),
        'word.istitle()=' + str(word.istitle()),
        'word.isdigit()=' + str(word.isdigit()),

        '+1:word=' + nextword,
        '+1:pos=' + nextpos,
        '+1:lemma=' + stemmer.stem(nextword),
        '+1:shape=' + shape(nextword),
        '+1:word.lower()=' + str(nextword.lower()),
        '+1:word.isupper()=' + str(nextword.isupper()),
        '+1:word.istitle()=' + str(nextword.istitle()),
        '+1:word.isdigit()=' + str(nextword.isdigit()),

        '+2:word=' + nextnextword,
        '+2:pos=' + nextnextpos,
        '+2:lemma=' + stemmer.stem(nextnextword),
        '+2:shape=' + shape(nextnextword),
        '+2:word.lower()=' + str(nextnextword.lower()),
        '+2:word.isupper()=' + str(nextnextword.isupper()),
        '+2:word.istitle()=' + str(nextnextword.istitle()),
        '+2:word.isdigit()=' + str(nextnextword.isdigit()),

        '-1:word=' + prevword,
        '-1:pos=' + prevpos,
        '-1:lemma=' + stemmer.stem(prevword),
        '-1:iob=' + previob,
        '-1:shape=' + shape(prevword),
        '-1:word.lower()=' + str(prevword.lower()),
        '-1:word.isupper()=' + str(prevword.isupper()),
        '-1:word.istitle()=' + str(prevword.istitle()),
        '-1:word.isdigit()=' + str(prevword.isdigit()),

        '-2:word=' + prevprevword,
        '-2:pos=' + prevprevpos,
        '-2:lemma=' + stemmer.stem(prevprevword),
        '-2:iob=' + prevpreviob,
        '-2:shape=' + shape(prevprevword),
        '-2:word.lower()=' + str(prevprevword.lower()),
        '-2:word.isupper()=' + str(prevprevword.isupper()),
        '-2:word.istitle()=' + str(prevprevword.istitle()),
        '-2:word.isdigit()=' + str(prevprevword.isdigit()),
    ]

def sent2features(iob_tagged_sentence, iob_tagged_sentences, feature_detector):
    words, tags, iob_tags = list(zip(*iob_tagged_sentence))
    X_sent, y_sent = [], []
    for index in range(len(iob_tagged_sentence)):
        X_sent.append(feature_detector(iob_tagged_sentences, index, history=iob_tags[:index]))
        y_sent.append(iob_tags[index])

    return X_sent, y_sent

def to_dataset_for_single_sentence(index, X, y, parsed_sentences, feature_detector):
    for iob_tagged in parsed_sentences:
        words, tags, iob_tags = list(zip(*iob_tagged))

        tagged = list(zip(words, tags))

        X_sent, y_sent = sent2features(iob_tagged, tagged, feature_detector)
        X[index].append(X_sent)
        y[index].append(y_sent)

def to_dataset(parsed_sentences, feature_detector):
    """
    Transform a list of tagged sentences into a scikit-learn compatible POS dataset
    :param parsed_sentences:
    :param feature_detector:
    :return:
    """
    X, y = [], []
    for iob_tagged in parsed_sentences:
        words, tags, iob_tags = list(zip(*iob_tagged))

        tagged = list(zip(words, tags))

        X_sent, y_sent = sent2features(iob_tagged, tagged, feature_detector)
        X.append(X_sent)
        y.append(y_sent)

    return X, y

def score_sentences_thread(index, results, iob_tagged_datatest, y_pred):
    total_entities = 0
    correct_entities = 0
    for i, iob_tagged_tokens in enumerate(iob_tagged_datatest):
        words, tags, iob_tags = list(zip(*iob_tagged_tokens))
        predicted_iob_tokens = list(zip(words, tags, y_pred[i]))

        datatest_entities = get_entities_from_iob_tagged_tokens(iob_tagged_tokens)
        predicted_entities = get_entities_from_iob_tagged_tokens(predicted_iob_tokens)

        # print("\nACTUAL   :", iob_tagged_tokens)
        # print("         :", datatest_entities)
        # print("         :", len(datatest_entities), "entities")
        # print("PREDICTED:", predicted_iob_tokens)
        # print("         :", predicted_entities)

        total_entities += len(datatest_entities)
        for datatest_entity in datatest_entities:
            if datatest_entity in predicted_entities:
                correct_entities += 1

    results[index] = (total_entities, correct_entities)

def my_modified_crfsuite_scorer(tagger, iob_tagged_datatest, feature_detector):
    print(" >> Converting to data test")
    X_test, y_test = to_dataset(iob_tagged_datatest, word2features)
    print(" >> Predicting labels")
    y_pred = [tagger.tag(xseq) for xseq in X_test]

    print(" >> Calculating Accuracy")
    iob_tagged_datatest_len_per_thread = -(-len(iob_tagged_datatest) // 4)
    threads = [None] * NUM_THREAD
    results = [None] * NUM_THREAD
    for i in range(NUM_THREAD):
        start_index = i * iob_tagged_datatest_len_per_thread
        end_index = (i+1) * iob_tagged_datatest_len_per_thread
        threads[i] = Thread(target=score_sentences_thread, args=(
            i, results, iob_tagged_datatest[start_index : end_index], y_pred[start_index : end_index]
        ))
        threads[i].start()

    for thread in threads:
        thread.join()

    total_entities_in_sentence, correct_entities_in_sentence = zip(*results)

    total_entities = sum(total_entities_in_sentence)
    correct_entities = sum(correct_entities_in_sentence)

    if total_entities:
        accuracy = (correct_entities / total_entities) * 100
        print(" > Accuracy: {0:.10f}%".format(accuracy))
    else:
        print("Dividing by 0")
    print(" > Report:")
    print(bio_classification_report(y_test, y_pred))

def bio_classification_report(y_true, y_pred):
    """
    Classification report for a list of BIO-encoded sequences.
    It computes token-level metrics and discards "O" labels.

    Note that it requires scikit-learn 0.15+ (or a version from github master)
    to calculate averages properly!
    """
    lb = LabelBinarizer()
    y_true_combined = lb.fit_transform(list(chain.from_iterable(y_true)))
    y_pred_combined = lb.transform(list(chain.from_iterable(y_pred)))

    tagset = set(lb.classes_) - {'O'}
    tagset = sorted(tagset, key=lambda tag: tag.split('-', 1)[::-1])
    class_indices = {cls: idx for idx, cls in enumerate(lb.classes_)}

    return classification_report(
        y_true_combined,
        y_pred_combined,
        labels=[class_indices[cls] for cls in tagset],
        target_names=tagset,
    )

def train(data_train, model_file_path):
    print("\n=== TRAINING {} DATA ===".format(len(data_train)))
    print(" > Extracting features")
    X_train, y_train = to_dataset(data_train, word2features)
    trainer = pycrfsuite.Trainer(verbose=False)
    print(" > Appending data trains")
    for i in range(len(X_train)):
        trainer.append(X_train[i], y_train[i])

    trainer.set_params({
        'algorithm': 'lbfgs',
        'c1': 1.0,  # coefficient for L1 penalty
        'c2': 1e-3,  # coefficient for L2 penalty
        'max_iterations': 100,  # stop earlier

        # include transitions that are possible, but not observed
        'all_possible_transitions': True
    })
    print(" > Start training. . .")
    master_begin_time = time.time()
    trainer.train(model_file_path)
    master_end_time = time.time()
    print(" > Training done in {} seconds".format(master_end_time - master_begin_time))
    print(" > Model saved in {}".format(model_file_path))

def test(data_test, model_file_path, feature_detector):
    print("\n=== TESTING {} DATA ===".format(len(data_test)))
    tagger = pycrfsuite.Tagger()
    tagger.open(model_file_path)
    master_begin_time = time.time()
    my_modified_crfsuite_scorer(tagger, data_test, feature_detector)
    master_end_time = time.time()
    print(" > Testing done in {} seconds".format(master_end_time - master_begin_time))

gmb_iob_triads = load_object(GMB_IOB_TRIAD_PATH)

train_size = 5000
test_size = 1000
data_train = gmb_iob_triads[:train_size]
data_test = gmb_iob_triads[train_size: train_size + test_size]

model_file_path = 'obj/gmb_{}.crfsuite'.format(train_size, test_size)
# train(data_train, model_file_path)
test(data_test, model_file_path, word2features)


from __future__ import annotations

import numpy as np
import pytest

from eolearn.core import FeatureType
from eolearn.mask import SnowMaskTask

@pytest.mark.parametrize(
    ("task", "result"),
    [
        (SnowMaskTask((FeatureType.DATA, "BANDS-S2-L1C"), [2, 3, 7, 11], mask_name="TEST_SNOW_MASK"), (50468, 1405)),
    ],
)
def test_snow_coverage(task, result, test_eopatch):
    resulting_eopatch = task(test_eopatch)
    output = resulting_eopatch[task.mask_feature]

    assert output.ndim == 4
    assert output.shape[:-1] == test_eopatch.data["BANDS-S2-L1C"].shape[:-1]
    assert output.shape[-1] == 1

    assert output.dtype == bool

    snow_pixels = np.sum(output, axis=(1, 2, 3))
    assert np.sum(snow_pixels) == result[0], "Sum of snowy pixels does not match"
    assert snow_pixels[-4] == result[1], "Snowy pixels on specified frame do not match"


import numpy as np

def savgol_filter(y, window_size, degree): #Savitzky-Golay Filter
    y_smooth = []
    for x in range(len(y)):
        a = int(x - window_size / 2 if x >= window_size / 2 else 0)
        b = int(x + window_size / 2 if x + window_size < len(y) else len(y))
        p_vec = np.polyfit(range(a, b), y[a:b], degree)
        p = lambda x: np.dot([x ** d for d in range(degree + 1)], np.flip(p_vec))
        y_smooth.append(p(x))

    return y_smooth

if __name__ == "__main__":
    import matplotlib.pyplot as plt

    window_size = 50
    degree = 3

    x = np.linspace(0,2*np.pi,100)
    y = np.sin(x) + np.random.random(100) * 0.2
    yhat = savgol_filter(y, window_size, degree)

    plt.plot(x,y)
    plt.plot(x,yhat, color='red')
    plt.show()


import sqlite3

# Connect to SQLite database (or create it if it doesn't exist)
conn = sqlite3.connect('tasks.db')
c = conn.cursor()

# Create table to store tasks
c.execute('''
CREATE TABLE IF NOT EXISTS tasks (
    id INTEGER PRIMARY KEY,
    task_name TEXT NOT NULL,
    status TEXT CHECK( status IN ('open','complete') ) NOT NULL DEFAULT 'open',
    priority INTEGER CHECK( priority IN (1,2,3) ) NOT NULL
)
''')
conn.commit()

def show_open_tasks():
    c.execute("SELECT * FROM tasks WHERE status='open'")
    for row in c.fetchall():
        print(row)

def show_completed_tasks():
    c.execute("SELECT * FROM tasks WHERE status='complete'")
    for row in c.fetchall():
        print(row)

def show_all_tasks():
    c.execute("SELECT * FROM tasks")
    for row in c.fetchall():
        print(row)

def add_task(task_name, priority):
    c.execute("INSERT INTO tasks (task_name, status, priority) VALUES (?, 'open', ?)", (task_name, priority))
    conn.commit()

def mark_task_as_complete(task_id):
    c.execute("UPDATE tasks SET status='complete' WHERE id=?", (task_id,))
    conn.commit()

def delete_task(task_id):
    c.execute("DELETE FROM tasks WHERE id=?", (task_id,))
    conn.commit()

# Function to display menu and get user choice
def menu():
    while True:
        print("""
        1. Show Open Tasks
        2. Show Completed Tasks
        3. Show All Tasks
        4. Add Task
        5. Mark Task as Complete
        6. Delete Task
        7. Exit
        """)
        choice = input("Enter your choice: ")
        if choice == "1":
            show_open_tasks()
        elif choice == "2":
            show_completed_tasks()
        elif choice == "3":
            show_all_tasks()
        elif choice == "4":
            task_name = input("Enter task name: ")
            priority = int(input("Enter priority (1, 2, 3): "))
            add_task(task_name, priority)
        elif choice == "5":
            task_id = int(input("Enter task ID to mark as complete: "))
            mark_task_as_complete(task_id)
        elif choice == "6":
            task_id = int(input("Enter task ID to delete: "))
            delete_task(task_id)
        elif choice == "7":
            break
        else:
            print("Invalid choice, please try again.")

menu()  # Call the menu function to start the program

# Close the connection to the database
conn.close()


# List Operations - append, insert, remove, sort, pop, reverse, print

"""
Consider a list (list = []). You can perform the following commands:

insert i e: Insert integer  at position i.
print: Print the list.
remove e: Delete the first occurrence of integer e.
append e: Insert integer  at the end of the list.
sort: Sort the list.
pop: Pop the last element from the list.
reverse: Reverse the list.
Initialize your list and read in the value of n followed by n lines of commands.
Each command will be of the 7 types listed above.
Iterate through each command in order and perform the corresponding operation on your list.

Sample Input :
************

12
insert 0 5
insert 1 10
insert 0 6
print
remove 6
append 9
append 1
sort
print
pop
reverse
print

Sample Output :
*************

[6, 5, 10]
[1, 5, 9, 10]
[9, 5, 1]

"""

if __name__ == '__main__':
    sample_list = []
    str = ''
    for i in range(int(input())):
        str = str + input() + '\n'

    # Split the string in to nested lists and then perform the operations.
    for list_op in str.split('\n'):
        if ('append' in list_op):
            sample_list.append(int(list_op.split()[1]))
        elif ('insert' in list_op):
            sample_list.insert(int(list_op.split()[1]), int(list_op.split()[2]))
        elif ('print' in list_op):
            print(sample_list)
        elif ('remove' in list_op):
            sample_list.remove(int(list_op.split()[1]))
        elif ('pop' in list_op):
            sample_list.pop()
        elif ('sort' in list_op):
            sample_list.sort()
        elif ('reverse' in list_op):
            sample_list.reverse()


from django.shortcuts import render, redirect, get_object_or_404
from .forms import postForm, registerForm, deleteForm
from .models import KobePost, registrationReviewer
from .autoCheck import checkPost
from .facebookApi import FbManger
from .postDeleteTokenCreater import createToken
from django.contrib import messages
import json

def home(request):
    return render(request, 'home.html', {})

def coc(request):
    return render(request, 'coc.html', {})

def about(request):
    return render(request, 'about.html', {})

def contribution(request):
    return render(request, 'contribution.html', {})

def registrationSuccess(request):
    return render(request, 'registrationSuccess.html', {})

def postlist(request):
    post = KobePost.objects.all()
    return render(request, 'postlist.html', {'post': post})

def registration(request):
    if request.method == "POST":
        form = registerForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.registerIpAddress = str(getIp(request))
            if post.agreeCoc: # check coc policy
                post.save()
                return redirect('/registrationSuccess/')
            else:
                messages.warning(request, '請先閱讀並同意行為準則')
    else:
        form = registerForm()
    return render(request, 'registration.html', {'form': form})

def postSystem(request):
    if request.method == "POST":
        form = postForm(request.POST, request.FILES)
        if form.is_valid():
            post = form.save(commit=False)
            post.ipAddress = str(getIp(request))
            post.token = str(createToken.token())
            if post.cocPolicy: # check coc policy
                if checkPost.check(post.content) == True: #auto check post
                    if post.photo:
                        post.check = 'True'
                        post.save()
                        poster = FbManger(post, post.content, post.postTime) #post to facebook
                        post.postId = poster.imgPoster(post.photo)
                        post.checkPosted = 'True'
                        post.save()
                        return redirect('/postsuccess/' + str(post.id) + '/')
                    else:
                        post.check = 'True'
                        post.save()
                        poster = FbManger(post, post.content, post.postTime) #post to facebook
                        post.postId = poster.poster()
                        post.checkPosted = 'True'
                        post.save()
                        return redirect('/postsuccess/' + str(post.id) + '/')
                else:
                    post.save()
                    return redirect('/')
            else:
                messages.warning(request, '請先閱讀並同意行為準則')
    else:
        form = postForm()
    return render(request, 'post.html', {'form': form})

def postDelete(post_token):
    post = KobePost.objects.get(token = post_token) #get post by post token
    print(post.postId)
    poster = FbManger(post, post.content, post.postTime)
    poster.postDeleter(post.postId) #delete post

def deletePostSystem(request):
    if request.method == "POST":
        form = deleteForm(request.POST)
        if form.is_valid():
            deleteToken = form.cleaned_data['deleteToken']
            postDelete(deleteToken)
            return redirect('/')
    else:
        form = deleteForm()
    return render(request, 'deletepost.html', {'form': form})

def postSuccess(request, id):
    post = KobePost.objects.get(id = id)
    return render(request, 'postSuccess.html', {'post': post})

def getIp(request):
    xForwardedFor = request.META.get('HTTP_X_FORWARDED_FOR')
    if xForwardedFor:
        ip = xForwardedFor.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip


class Solution(object):
    def minLengthAfterRemovals(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """

        left,right,ans = 0,(len(nums)+1)//2,0
        while(right < len(nums)):
            if nums[right] > nums[left]:
                right += 1
                left += 1
                ans += 2
            else:
                right += 1
        return len(nums) - ans

leetcode/2856. Minimum Array Length After Pair Removals.py


# Adapted from code in https://github.com/airsplay/py-bottom-up-attention
# Please see https://github.com/airsplay/py-bottom-up-attention/blob/master/LICENSE for the Apache 2.0 License of that code

import os
import sys
import io
import json
from tqdm import tqdm

import detectron2

# import some common detectron2 utilities
from detectron2.engine import DefaultPredictor
from detectron2.config import get_cfg
from detectron2.utils.visualizer import Visualizer
from detectron2.data import MetadataCatalog

# import some common libraries
import numpy as np
import cv2
import torch

NUM_OBJECTS = 36

from torch import nn

from detectron2.modeling.postprocessing import detector_postprocess
from detectron2.modeling.roi_heads.fast_rcnn import FastRCNNOutputLayers, FastRCNNOutputs, fast_rcnn_inference_single_image
from detectron2.structures.boxes import Boxes
from detectron2.structures.instances import Instances

# Load VG Classes
data_path = 'data/genome/1600-400-20'

vg_classes = []
with open(os.path.join(data_path, 'objects_vocab.txt')) as f:
    for object in f.readlines():
        vg_classes.append(object.split(',')[0].lower().strip())

vg_attrs = []
with open(os.path.join(data_path, 'attributes_vocab.txt')) as f:
    for object in f.readlines():
        vg_attrs.append(object.split(',')[0].lower().strip())

MetadataCatalog.get("vg").thing_classes = vg_classes
MetadataCatalog.get("vg").attr_classes = vg_attrs

cfg = get_cfg()
cfg.merge_from_file("configs/VG-Detection/faster_rcnn_R_101_C4_caffe.yaml")
cfg.MODEL.RPN.POST_NMS_TOPK_TEST = 300
cfg.MODEL.ROI_HEADS.NMS_THRESH_TEST = 0.6
cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.2
# VG Weight
# cfg.MODEL.WEIGHTS = "http://nlp.cs.unc.edu/models/faster_rcnn_from_caffe.pkl"
cfg.MODEL.WEIGHTS = "http://nlp.cs.unc.edu/models/faster_rcnn_from_caffe_attr_original.pkl"
predictor = DefaultPredictor(cfg)

def doit(raw_image, raw_boxes):
    # Process Boxes
    raw_boxes = Boxes(torch.from_numpy(raw_boxes).cuda())
    with torch.no_grad():
        raw_height, raw_width = raw_image.shape[:2]
        print("Original image size: ", (raw_height, raw_width))
        # Preprocessing
        image = predictor.transform_gen.get_transform(raw_image).apply_image(raw_image)
        print("Transformed image size: ", image.shape[:2])
        # Scale the box
        new_height, new_width = image.shape[:2]
        scale_x = 1. * new_width / raw_width
        scale_y = 1. * new_height / raw_height
        #print(scale_x, scale_y)
        boxes = raw_boxes.clone()
        boxes.scale(scale_x=scale_x, scale_y=scale_y)
        image = torch.as_tensor(image.astype("float32").transpose(2, 0, 1))
        inputs = [{"image": image, "height": raw_height, "width": raw_width}]
        images = predictor.model.preprocess_image(inputs)
        # Run Backbone Res1-Res4
        features = predictor.model.backbone(images.tensor)
        # Run RoI head for each proposal (RoI Pooling + Res5)
        proposal_boxes = [boxes]
        features = [features[f] for f in predictor.model.roi_heads.in_features]
        box_features = predictor.model.roi_heads._shared_roi_transform(
            features, proposal_boxes
        )
        feature_pooled = box_features.mean(dim=[2, 3])  # pooled to 1x1
        print('Pooled features size:', feature_pooled.shape)
        # Predict classes and boxes for each proposal.
        pred_class_logits, pred_proposal_deltas = predictor.model.roi_heads.box_predictor(feature_pooled)
        print(pred_class_logits.shape)
        pred_class_prob = nn.functional.softmax(pred_class_logits, -1)
        pred_scores, pred_classes = pred_class_prob[..., :-1].max(-1)
        # Detectron2 Formatting (for visualization only)
        roi_features = feature_pooled
        instances = Instances(
            image_size=(raw_height, raw_width),
            pred_boxes=raw_boxes,
            scores=pred_scores,
            pred_classes=pred_classes
        )
        return instances, roi_features

# Image root
img_root = sys.argv[1]
# jsonl input file
f = open(sys.argv[2])
lines = f.readlines()
data = [json.loads(line) for line in lines]
if len(sys.argv) > 4:
    # Predicted boxes JSON file
    f = open(sys.argv[3])
    predicted_boxes = json.load(f)
boxes_dict = {}
for datum in tqdm(data):
    if 'coco' in datum['file_name'].lower():
        datum['file_name'] = '_'.join(datum['file_name'].split('_')[:-1])+'.jpg'
    im = cv2.imread(img_root+datum['file_name'])
    if len(sys.argv) == 4:
        boxes = np.array(
            [[ann['bbox'][0], ann['bbox'][1], ann['bbox'][0]+ann['bbox'][2], ann['bbox'][1]+ann['bbox'][3]] for ann in datum['anns']]
        )
        conf = np.array([1 for _ in datum["anns"]])
    else:
        assert len(sys.argv) > 4
        conf = np.array(predicted_boxes[str(datum["image_id"])]["scores"])
        print(conf.shape)
        if len(conf) > 0:
            boxes = np.array(predicted_boxes[str(datum["image_id"])]["boxes"])[(-conf).argsort(),:]
            conf = conf[(-conf).argsort()]
        else:
            boxes = np.array([[0, 0, im.shape[1], im.shape[0]]])
            conf = np.array([1.])
    _, feats = doit(im, boxes)
    boxes_dict[datum['image_id']] = {"boxes": torch.from_numpy(boxes), "features": feats, "width": im.shape[1], "height": im.shape[0], "conf": torch.from_numpy(conf)}
# Output .pt file
torch.save(boxes_dict, sys.argv[4])


from sklearn.model_selection import KFold
import numpy as np
import pandas as pd

class MyCrossValidation(object):
    def __init__(self, n_folds=5, random_state=None):
        # super(MyCrossValidation, self).__init__()
        self.kFold = KFold(n_splits=n_folds, shuffle=True, random_state=random_state)

    def onEachKFold(self, inputs, targets, action, take_average=True):
        i = 0
        results = pd.DataFrame()
        for curTrainIndices, curTestingIndices in self.kFold.split(inputs):
            curXtrain = inputs.iloc[curTrainIndices]
            curYtrain = targets[curTrainIndices]

            curXvalid = inputs.iloc[curTestingIndices]
            curYvalid = targets[curTestingIndices]

            results = pd.concat((
                results, action(curXtrain, curYtrain, curXvalid, curYvalid, i)
            ))

            i += 1

        if take_average:
            return np.mean(results, axis=0)  # returns panda series
        else:
            return results  # returns dataframe


from random import sample
import numpy
import pandas

SIZE = 3
DIGITS = range(SIZE * SIZE)
UNPLAYED = -1

REPEAT = 2**16

def check(state: list) -> int:
	""" Check which player has won """

	#  Check rows and colums
	for i in range(SIZE):
		if all(state[i, :] == 0) or all(state[:, i] == 0):
			return 0
		elif all(state[i, :] == 1) or all(state[:, i] == 1):
			return 1

	#  Check diagonals
	if all(map(lambda n: n == 0, [state[0, 0], state[1, 1], state[2, 2]])):
		return 0
	elif all(map(lambda n: n == 1, [state[0, 0], state[1, 1], state[2, 2]])):
		return 1
	elif all(map(lambda n: n == 0, [state[0, -1], state[1, -2], state[2, -3]])):
		return 0
	elif all(map(lambda n: n == 1, [state[0, -1], state[1, -2], state[2, -3]])):
		return 1

	return UNPLAYED

def play():
	""" Simulate a game. """

	sequence = sample(DIGITS, SIZE * SIZE)
	# print(f"DEBUG: sequence: {sequence}")
	state = numpy.array([[-1] * SIZE] * SIZE)

	for stage in range(SIZE * SIZE):
		state[sequence[stage] // 3, sequence[stage] % 3] = stage % 2
		winner = check(state)
		if winner != UNPLAYED:
			return (winner, stage)

	return (check(state), stage)

if __name__ == "__main__":
	""" This runs if the program is run as a script. """

	#  Frequency of occurrence of the different events.
	#  See data dictionary below for details.
	freq = [0] * 6

	for expt in range(REPEAT):
		result = play()
		if result[0] == 0:
			freq[(result[1] - 4) // 2] += 1
		elif result[0] == 1:
			freq[3 + (result[1] - 5) // 2] += 1
		else:
			freq[5] += 1

	#  Collate the data
	prob = list(map(lambda x: x/REPEAT, freq))
	data = {
		'winner': [0] * 3 + [1] * 2 + [-1],
		'round': list(range(4, 9, 2)) + list(range(5, 9, 2)) + [8],
		'frequency': freq,
		'probability': prob}

	#  Plot the results
	index = list(map(
	    lambda winner, round: "(" + str(winner) + ", " + str(round) + ")",
	    [0] * 3 + [1] * 2 + [-1],
	    list(range(4, 9, 2)) + list(range(5, 9, 2)) + [8]))
	df = pandas.DataFrame(data=data['probability'], index=index)
	df.plot.bar()
	print(df)


from django.contrib import admin

from .models import LeaveCategory, UserProfile, LeaveApplication

def approve_multiple(modeladmin, request, queryset):
    for leave in queryset:
        leave.status = True
        leave.save()

approve_multiple.short_description = "Approve All"

class LeaveAppAdmin(admin.ModelAdmin):
    list_display = ['start_date', 'end_date', 'usr', 'leave_category',
                    'status', 'subject']
    list_filter = ["usr", "leave_category"]
    date_hierarchy = "start_date"
    actions = [approve_multiple]

admin.site.register(LeaveCategory)
admin.site.register(UserProfile)
admin.site.register(LeaveApplication, LeaveAppAdmin)