#!/usr/bin/env python
import optparse
import os
from CMGTools.HToZZTo4Leptons.macros.param.HiggsShapes import *

if __name__ == '__main__':

    parser = optparse.OptionParser()
    parser.add_option("-c","--cut",dest="cut",default='H_Mass>0',help="cut to apply")
    parser.add_option("-p","--prod",dest="prod",default='ggH',help="sub-sample")
    parser.add_option("-m","--max",dest="maxMass",default='160',help="max mass")
    parser.add_option("-r","--runOnly",dest="runOnly",default='',help="runonly")
    (options,args) = parser.parse_args()

    masses7TeV =[]
    masses8TeV=[]

    for filename in os.listdir('All_7TeV'):
        name,extention=filename.split('.')
        if name.find(options.prod)>-1 and extention == 'root':
            s=name.split(options.prod)
            if int(s[1])<int(options.maxMass):
                masses7TeV.append(int(s[1]))

    for filename in os.listdir('All_8TeV'):
        name,extention=filename.split('.')
        if name.find(options.prod)>-1 and extention == 'root':
            s=name.split(options.prod)
            if int(s[1])<int(options.maxMass):
                masses8TeV.append(int(s[1]))

    if len(options.runOnly)>1:
        masses7TeV=[]
        masses8TeV=[]
        masses=options.runOnly.split(',')
        for m in masses:
            masses7TeV.append(int(m))
            masses8TeV.append(int(m))

    mumu7TeV =HiggsShapes ('MuMu',options.cut,masses7TeV,options.prod,'7TeV')
    mue7TeV = HiggsShapes('MuEle',options.cut,masses7TeV,options.prod,'7TeV')
    ee7TeV = HiggsShapes('EleEle',options.cut,masses7TeV,options.prod,'7TeV')
    mumu8TeV = HiggsShapes('MuMu',options.cut,masses8TeV,options.prod,'8TeV')
    mue8TeV = HiggsShapes('MuEle',options.cut,masses8TeV,options.prod,'8TeV')
    ee8TeV = HiggsShapes('EleEle',options.cut,masses8TeV,options.prod,'8TeV')


#!/bin/python3

#Project Euler #6: Sum square difference - Python code

import sys

t = int(input().strip())
for a0 in range(t):
    n = int(input().strip())
    square_of_sum = int(pow((n*(n+1))/2, 2))
    sum_of_square = int(n*(n+1)*(2*n+1)/6)
    print(square_of_sum - sum_of_square)

ProjectEuler+/Project Euler #6: Sum square difference.py


#
#   MySlice version 2
#
#   Activity process service: manages events and requests
#
#   (c) 2016 Ciro Scognamiglio <ciro.scognamiglio@lip6.fr>
##
from multiprocessing import Process
import signal
import threading
from queue import Queue

import random

import myslice.db as db
import rethinkdb as r

from myslice.db import connect, changes, events
from myslice.db.activity import Event, EventStatus
from myslice.services.workers.events import run as manageEvents
import myslice.lib.log as logging

import zmq
import pickle
import json

logger = logging.getLogger()

def receive_signal(signum, stack):
    logger.info('Received signal %s', signum)
    raise SystemExit('Exiting')

def run():
    """

    """
    signal.signal(signal.SIGINT, receive_signal)
    signal.signal(signal.SIGTERM, receive_signal)
    signal.signal(signal.SIGHUP, receive_signal)

    qEvents = Queue()

    threads = []
    for y in range(1):
        t = threading.Thread(target=manageEvents, args=(qEvents,))
        t.daemon = True
        threads.append(t)
        t.start()

    context = zmq.Context()
    socket = context.socket(zmq.SUB)
    socket.setsockopt_string(zmq.SUBSCRIBE, 'activity')
    socket.connect("tcp://localhost:6002")
    logger.info("[activity] Collecting updates from ZMQ bus for activity")

    while True:
        logger.debug("[activity]Change in activity feed")

        topic, zmqmessage = socket.recv_multipart()
        activity = pickle.loads(zmqmessage)

        logger.debug("[activity]{0}: {1}".format(topic, activity))

        try:
            event = Event(activity['new_val'])
            logger.debug("[activity] Adding event %s to Events queue" % (event.id))
            qEvents.put(event)

            #for debbuging purposes

        except Exception as e:
            import traceback
            traceback.print_exc()
            logger.exception(e)
            if 'new_val' in activity and 'id' in activity['new_val']:
                logger.error("[activity] Problem with event: {}".format(activity['new_val']['id']))
            continue

    logger.critical("Service activity stopped")
    # waits for the thread to finish
    for x in threads:
        x.join()

if __name__ == '__main__':
    Process(target=run,).start()


from binance.client import Client
import keys
import pandas as pd
import time
import re

client = Client(keys.api_key, keys.api_secret)

def top_coin():
    all_tickers = pd.DataFrame(client.get_ticker())
    usdt = all_tickers[all_tickers.symbol.str.contains('USDT')]
    work = usdt[~(usdt.symbol.str.contains('UP')) & ~(usdt.symbol.str.contains('DOWN'))]
    top_coin = work[work.priceChangePercent == work.priceChangePercent.max()]
    top_coin = top_coin.symbol.values[0]
    print(top_coin)
    return top_coin

def last_data(symbol, interval, lookback):
    frame = pd.DataFrame(client.get_historical_klines(symbol, interval, lookback + 'min ago UTC'))
    frame = frame.iloc[:, :6]
    frame.columns = ['Time', 'Open', 'High', 'Low', 'Close', 'Volume']
    frame = frame.set_index('Time')
    frame.index = pd.to_datetime(frame.index, unit='ms')
    frame = frame.astype(float)
    return frame

def check_minQty(asset, qty):
    """Проверка на минимамальный необходимый объём покупки."""
    info = client.get_symbol_info(asset)
    minQty = float(info['filters'][2]['minQty'])

    if qty > minQty:
        print('minQty - OK')
        return True
    else:
        print('minQty - FAIL')
        print(f'qty = {qty}, minQty = {minQty}')
        return False

def check_stepSize(asset, qty):
    """Проверка на корректный шаг покупки. И его исправление, если он не корректный."""
    info = client.get_symbol_info(asset)
    stepSize = float(info['filters'][2]['stepSize'])
    print(f'qty = {qty}, stepSize = {stepSize}')
    if qty < stepSize:
        print('stepSize - FAIL')
        return False
    if qty >= stepSize and stepSize >= 1.0:
        qty -= int(qty % stepSize)
        print('steSize - OK')
        return True
    elif get_count(qty) <= get_count(stepSize):
        round(qty, get_count(qty))
        print('stepSize - OK')
        return True
    elif get_count(qty) > get_count(stepSize):
        round(qty, get_count(stepSize))
        print('steSize - OK')
        return True
    else:
        print('stepSize - FAIL')
        print(f'qty = {qty}, stepSize = {stepSize}. residue = {qty % stepSize}')
        return False

def get_count(number):
    s = str(number)
    if '.' in s:
        return int(len(re.search(r'(?<=\.)\d+', s)[0]))
    elif 'e-' in s:
        return int(re.search(r'\d$', s)[0])
    else:
        return 0

def check_minNotional(asset, buy_amt):
    info = client.get_symbol_info(asset)
    minNotional = float(info['filters'][3]['minNotional'])

    if buy_amt >= minNotional:
        print('min_Notional - OK')
        return True
    else:
        print('min_Notional - FAIL')
        print(f'result = {buy_amt} < {minNotional}')
        checked = False

def check_order_possibility(buy_amt, asset, qty, df):
    """Проверка монеты на соответствие основным ограничениям для создания ордера"""
    checked = True
    print(asset)
    print(df.iloc[-1])

    if not check_stepSize(asset, qty):
        tick_sized_qty = tick_sized(asset, qty)
        print(f'Corrected qty = {tick_sized_qty}\nstepSize - OK')
        checked = check_minQty(asset, qty) and check_minNotional(asset, buy_amt)
        return checked, tick_sized_qty
    else:
        checked = check_minQty(asset, qty) and check_minNotional(asset, buy_amt)
        return checked, qty

def tick_sized(asset, qty):
    tick_size = client.get_symbol_info(asset)
    minQty = float(tick_size['filters'][2]['minQty'])
    if qty < 1 and minQty < 1:
        return round(qty, len(str(round(1 / minQty)))-1)
    elif qty > 1 and minQty >= 1:
        stepSize = float(tick_size['filters'][2]['stepSize'])
        return round(qty - qty % stepSize)
    else:
        print(f'{qty} {minQty}')
        return round(qty, int(int(qty * (1 / minQty)) / (1 / minQty)))

def strategy(buy_amt, SL=0.985, Target=1.02, open_position=False):
    """Основная часть программы.
    1. Ищет топовую по росту за день монету относительно USDT. - top_coin()
    2. Смотрим, чтобы за последние 120 минут на минутном графике она так же росла. - last_data()
    3. Если это так - покупаем на количество = qty USDT эту монету.
    4. Устанавливаем стоп-лосс на -1,5% от покупки, а лимит на продажу на +2%"""
    try:
        asset = top_coin()
        df = last_data(asset, '1m', '120')

    except:
        time.sleep(61)
        asset = top_coin()
        df = last_data(asset, '1m', '120')

    qty = round(buy_amt*0.999/df.Close.iloc[-1], 2)
    print(((df.Close.pct_change() + 1).cumprod()).iloc[-1])
    print(f'Searching possible orders... for {qty} coins')
    checked, qty_to_work = check_order_possibility(buy_amt, asset, qty, df)
    print(checked, qty_to_work, ((df.Close.pct_change() + 1).cumprod()).iloc[-1])

    if ((df.Close.pct_change() + 1).cumprod()).iloc[-1] > 1 & checked is True:
        order = client.create_order(symbol=asset, side='BUY', type='MARKET', quantity=qty_to_work)
        print(order)
        buyprice = float(order['fills'][0]['price'])
        open_position = True

        while open_position:
            try:
                df = last_data(asset, '1m', '1')

            except:
                print('Restart after 1 min')
                time.sleep(61)
                df = last_data(asset, '1m', '1')

            print(f'Price ' + str(df.Close[-1]))
            print(f'Target ' + str(buyprice * Target))
            print(f'Stop ' + str(buyprice * SL))

            if df.Close[-1] < buyprice * SL or df.Close[-1] >= buyprice * Target:
                order = client.create_order(symbol=asset, side='SELL', type='MARKET', quantity=qty_to_work)
                print(f"Продали за: {order['fills'][0]['price']} + комиссия {order['fills'][0]['commission']}")
                plus = buyprice-float(order['fills'][0]['price'])*float(order['fills'][0]['price'])
                print(f"Итого в + на {plus} USDT")
                break
    else:
        print('Orders not found...')
        time.sleep(2)

#while True:
#    strategy(20)

i=0
while i < 1:
    print(get_count(1232.245))
    i = 1


# coding: utf-8

from django.core.cache import cache
from django.db import IntegrityError

class ProfilerData(object):
    """
    Encapsulates work with the profiling data.
    """
    def add(self, view_name, method, is_anon_call, is_cache_hit, sql_time, sql_count, view_execution_time):
        """Adds profiling data.

        :param str view_name: View name
        :param str method: HTTP method (GET, POST, etc.)
        :param bool is_anon_call: If True, it was an anonymous request
        :param bool is_cache_hit: If True, view response was retrieved from cache
        :param float sql_time: SQL queries execution time
        :param int sql_count: Number of SQL queries
        :param float view_execution_time: View execution time
        """
        from django.db.models import F
        from speedinfo.models import ViewProfiler

        try:
            vp, created = ViewProfiler.objects.get_or_create(view_name=view_name, method=method)
        except IntegrityError:
            # IntegrityError exception raised in case of concurrent access
            # to get_or_create method from another webserver worker process
            vp = ViewProfiler.objects.get(view_name=view_name, method=method)

        ViewProfiler.objects.filter(pk=vp.pk).update(
            anon_calls=F('anon_calls') + (is_anon_call and 1 or 0),
            cache_hits=F('cache_hits') + (is_cache_hit and 1 or 0),
            sql_total_time=F('sql_total_time') + sql_time,
            sql_total_count=F('sql_total_count') + sql_count,
            total_calls=F('total_calls') + 1,
            total_time=F('total_time') + view_execution_time
        )

    def reset(self):
        """Deletes all profiling data"""
        from speedinfo.models import ViewProfiler
        ViewProfiler.objects.all().delete()

class Profiler(object):
    """
    Profiler class to store its state and process the data.
    """
    PROFILER_STATE_CACHE_KEY = 'speedinfo.profiler.is_on'

    def __init__(self):
        self.data = ProfilerData()

    @property
    def is_on(self):
        """Returns state of the profiler.

        :return: state of the profiler
        :rtype: bool
        """
        return cache.get(self.PROFILER_STATE_CACHE_KEY, False)

    @is_on.setter
    def is_on(self, value):
        """Sets state of the profiler.

        :param bool value: State value
        """
        cache.set(self.PROFILER_STATE_CACHE_KEY, value, None)


from requests import Request, Session
from core.constant import CRYPTOKEY, CRYPTOURL, CRYPTOURL2

import requests
import json
import sys
import re

class CryptoService:

    url = CRYPTOURL
    api = CRYPTOKEY
    url2 = CRYPTOURL2

    def listar2(self, command):
        ret = ''
        try:
            lst = command.split(' ')
            dst = 'USD'

            if(len(lst) < 2 or len(lst) > 2):
                ret = 'Subcomando inválido'
                return ret

            rsp = requests.get(self.url2.format(lst[1].upper(), dst, self.api), timeout = 45)
            jrsp = json.loads(rsp.text)

            print(rsp.text)
            print(jrsp)

            ret += 'Papel: ' + lst[1].upper() + '\n'
            ret += 'Preço: ' + jrsp['DISPLAY']['PRICE'] + '\n'
            ret += 'Abertura: ' + jrsp['DISPLAY']['OPEN24HOUR'] + '\n'
            ret += 'Mínima: ' + jrsp['DISPLAY']['LOW24HOUR'] + '\n'
            ret += 'Máxima: ' + jrsp['DISPLAY']['HIGH24HOUR'] + '\n'
            ret += 'Variação: ' + jrsp['DISPLAY']['CHANGEPCT24HOUR'] + '%\n'
            ret += 'Volume: ' + jrsp['DISPLAY']['VOLUME24HOUR'] + ' (24h)\n'
            ret += 'Mercado: ' + jrsp['DISPLAY']['LASTMARKET'] + '\n'

        except:
            type, value, traceback = sys.exc_info()
            print('Error: {0} {1} {2}', type, value, traceback)
            ret = 'Falha ao buscar dados'

        return ret

    def listar(self, command):
        ret = ''
        try:
            lst = command.split(' ')
            dst = 'USD'

            if(len(lst) < 2 or len(lst) > 2):
                ret = 'Subcomando inválido'
                return ret

            rsp = requests.get(self.url.format(lst[1].upper(), dst, self.api), timeout = 45)

            ret += 'Papel: ' + lst[1].upper() + '\n'
            ret += self.stripChars(rsp.text)

            #jrsp = json.loads(rsp.text)
            #if jrsp['Response'] == 'Success':
            #    ret += 'Preço: ' +
            #    ret += 'Minima 30 dias: ' +
            #    ret += 'Máxima 30 dias: ' +
            #print(jrsp)

            #ret += 'Preço: ' + jrsp['DISPLAY']['USD']['PRICE'] + '\n'
            #ret += 'Abertura: ' + jrsp['DISPLAY']['USD']['OPENDAY'] + '\n'
            #ret += 'Máxima: ' + jrsp['DISPLAY']['USD']['HIGHDAY'] + '\n'
            #ret += 'Mínima: ' + jrsp['DISPLAY']['USD']['LOWDAY'] + '\n'
            #ret += 'Volume: ' + jrsp['DISPLAY']['USD']['TOTALVOLUME24H'] + '\n'

            #ret = rsp.text
            #ret = lst[1] + ': ' + self.stripChars(rsp.text)

        except:
            type, value, traceback = sys.exc_info()
            print('Error: {0} {1} {2}', type, value, traceback)
            ret = 'Falha ao buscar dados'

        return ret

    #def obterMinimaMaxima(self, jrsp, tipo):
    #    preco = ''
    #    minima = ''
    #    maxima = ''#
    #
    #    for i=0 to len(jrsp[Data]):
    #        preco = jrsp[Data][i][]

    def processarComando(self, command):

        ret = self.listar2(command)
        return ret

    def stripChars(self, data):
        p = self.striphtml(data)
        p = p.replace('\n', '')
        p = p.replace(':', ' ')
        p = p.replace('"', '')
        p = p.strip(' ')
        p = p.strip('/')
        p = p.strip('{')
        p = p.strip('}')

        return p

    def striphtml(self, data):
        pdata = '<td' + data
        p = re.compile(r'<.*?>')
        st = p.sub(' ', pdata)
        st = st.replace('  ', '')
        st = st.replace(' ', ' ')
        st = st.replace('\n', ' ')
        st = st.replace('  ', ' ')
        st = st.strip('/')
        st = st.replace('<td', '')
        return st


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

__author__ = None
__version__ = '1.0'
__license__ = None
__copyright__ = None

class Metrics(object):

    @staticmethod
    def get_f1score(p,r):
        # avoid division by zero
        if p+r != 0:
            return 2 * (p*r)/(p+r)
        else:
            return 0

    # @input training_loss, validation_loss
    # @output True if tr_loss is less than one order of magnitude wrt vl_loss
    #         False otherwise
    @staticmethod
    def overfit(tr_loss, vl_loss):
        #print('valid/train: ' + str(vl_loss/tr_loss))
        return vl_loss/tr_loss >= 10


import re
from typing import List, Optional, Tuple

import numpy as np

from hwinarion.dispatcher import ActionResult, ActProcessResult, BaseAction
from hwinarion.screen.pyautogui_wrapper import InterruptibleScreenInteractor

class MouseAction(BaseAction):
    def __init__(self):
        super().__init__("mouse")
        self.screen_interactor = InterruptibleScreenInteractor()
        self.screen_interactor.start()
        self.speed_mapping = {
            "very slow": InterruptibleScreenInteractor.SPEED_VERY_SLOW,
            "slow": InterruptibleScreenInteractor.SPEED_SLOW,
            None: InterruptibleScreenInteractor.SPEED_NORMAL,
            "fast": InterruptibleScreenInteractor.SPEED_FAST,
            "very fast": InterruptibleScreenInteractor.SPEED_VERY_FAST,
        }

    @property
    def recognized_words(self) -> List[str]:
        return [
            "move",
            "mouse",
            "left",
            "right",
            "up",
            "down",
            "very",
            "fast",
            "slow",
            "stop",
            "double",
            "triple",
            "middle",
            "click",
        ]  # pragma: no cover

    def parse_text(self, text: str) -> Optional[Tuple]:
        move_parse = re.fullmatch(
            r"move\s+mouse\s+(?P<direction>left|right|up|down)(\s+(?P<speed>(?:very\s+)?(?:fast|slow)))?",
            text,
            flags=re.IGNORECASE,
        )
        if move_parse:
            speed = move_parse["speed"].lower() if move_parse["speed"] else None
            return "move", move_parse["direction"].lower(), speed

        if re.fullmatch(r"stop\s+mouse", text, flags=re.IGNORECASE):
            return ("stop",)

        click_parse = re.fullmatch(
            r"(?P<n_clicks>single|double|triple)?\s*(?:(?P<button>left|right|middle)[- ])?mouse\s*click",
            text,
            flags=re.IGNORECASE,
        )
        if click_parse:
            button = click_parse["button"].lower() if click_parse["button"] else "left"
            if click_parse["n_clicks"] in (None, "single"):
                n_clicks = 1
            elif click_parse["n_clicks"] == "double":
                n_clicks = 2
            elif click_parse["n_clicks"] == "triple":
                n_clicks = 3
            else:
                raise ValueError(f"Unrecognized number of clicks: {click_parse['n_clicks']}")  # pragma: no cover
            return "click", button, n_clicks

        return None

    def act(self, text: str, *, get_recording_data: bool = False) -> ActionResult:
        if not self.enabled:
            return ActionResult(ActProcessResult.TEXT_NOT_PROCESSED)

        recording_data = {}

        parsed_text = self.parse_text(text)
        if parsed_text:
            action, *parameters = parsed_text
            recording_data["action"] = action
            recording_data["parameters"] = parameters
            if get_recording_data:
                recording_data["mouse_position"] = tuple(self.screen_interactor.get_mouse_position())
                recording_data["screen"] = np.asarray(self.screen_interactor.get_screenshot().tobytes())

            if action == "stop":
                self.screen_interactor.stop_moving()
                return ActionResult(ActProcessResult.TEXT_PROCESSED, recording_data)

            if action == "move":
                direction, speed = parameters
                speed = self.speed_mapping[speed]
                recording_data["speed"] = speed
                if direction == "left":
                    move_function = self.screen_interactor.move_left
                elif direction == "right":
                    move_function = self.screen_interactor.move_right
                elif direction == "down":
                    move_function = self.screen_interactor.move_down
                elif direction == "up":
                    move_function = self.screen_interactor.move_up
                else:
                    raise KeyError(f"Unrecognized direction: {direction}")  # pragma: no cover

                move_function(speed)
                return ActionResult(ActProcessResult.TEXT_PROCESSED, recording_data)

            if action == "click":
                button, n_clicks = parameters
                self.screen_interactor.click(button, n_clicks)
                return ActionResult(ActProcessResult.TEXT_PROCESSED, recording_data)

        return ActionResult(ActProcessResult.TEXT_NOT_PROCESSED)


# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
# For details: https://github.com/nedbat/coveragepy/blob/master/NOTICE.txt

"""Tests for coverage.py's results analysis."""

from __future__ import annotations

import math

from typing import Dict, Iterable, List, Tuple, cast

import pytest

from coverage.exceptions import ConfigError
from coverage.results import format_lines, Numbers, should_fail_under
from coverage.types import TLineNo

from tests.coveragetest import CoverageTest

class NumbersTest(CoverageTest):
    """Tests for coverage.py's numeric measurement summaries."""

    run_in_temp_dir = False

    def test_basic(self) -> None:
        n1 = Numbers(n_files=1, n_statements=200, n_missing=20)
        assert n1.n_statements == 200
        assert n1.n_executed == 180
        assert n1.n_missing == 20
        assert n1.pc_covered == 90

    def test_addition(self) -> None:
        n1 = Numbers(n_files=1, n_statements=200, n_missing=20)
        n2 = Numbers(n_files=1, n_statements=10, n_missing=8)
        n3 = n1 + n2
        assert n3.n_files == 2
        assert n3.n_statements == 210
        assert n3.n_executed == 182
        assert n3.n_missing == 28
        assert math.isclose(n3.pc_covered, 86.666666666)

    def test_sum(self) -> None:
        n1 = Numbers(n_files=1, n_statements=200, n_missing=20)
        n2 = Numbers(n_files=1, n_statements=10, n_missing=8)
        n3 = cast(Numbers, sum([n1, n2]))
        assert n3.n_files == 2
        assert n3.n_statements == 210
        assert n3.n_executed == 182
        assert n3.n_missing == 28
        assert math.isclose(n3.pc_covered, 86.666666666)

    @pytest.mark.parametrize("kwargs, res", [
        (dict(n_files=1, n_statements=1000, n_missing=0), "100"),
        (dict(n_files=1, n_statements=1000, n_missing=1), "99"),
        (dict(n_files=1, n_statements=1000, n_missing=999), "1"),
        (dict(n_files=1, n_statements=1000, n_missing=1000), "0"),
        (dict(precision=1, n_files=1, n_statements=10000, n_missing=0), "100.0"),
        (dict(precision=1, n_files=1, n_statements=10000, n_missing=1), "99.9"),
        (dict(precision=1, n_files=1, n_statements=10000, n_missing=9999), "0.1"),
        (dict(precision=1, n_files=1, n_statements=10000, n_missing=10000), "0.0"),
    ])
    def test_pc_covered_str(self, kwargs: Dict[str, int], res: str) -> None:
        assert Numbers(**kwargs).pc_covered_str == res

    @pytest.mark.parametrize("prec, pc, res", [
        (0, 47.87, "48"),
        (1, 47.87, "47.9"),
        (0, 99.995, "99"),
        (2, 99.99995, "99.99"),
    ])
    def test_display_covered(self, prec: int, pc: float, res: str) -> None:
        assert Numbers(precision=prec).display_covered(pc) == res

    @pytest.mark.parametrize("prec, width", [
        (0, 3),     # 100
        (1, 5),     # 100.0
        (4, 8),     # 100.0000
    ])
    def test_pc_str_width(self, prec: int, width: int) -> None:
        assert Numbers(precision=prec).pc_str_width() == width

    def test_covered_ratio(self) -> None:
        n = Numbers(n_files=1, n_statements=200, n_missing=47)
        assert n.ratio_covered == (153, 200)

        n = Numbers(
            n_files=1, n_statements=200, n_missing=47,
            n_branches=10, n_missing_branches=3, n_partial_branches=1000,
        )
        assert n.ratio_covered == (160, 210)

@pytest.mark.parametrize("total, fail_under, precision, result", [
    # fail_under==0 means anything is fine!
    (0, 0, 0, False),
    (0.001, 0, 0, False),
    # very small fail_under is possible to fail.
    (0.001, 0.01, 0, True),
    # Rounding should work properly.
    (42.1, 42, 0, False),
    (42.1, 43, 0, True),
    (42.857, 42, 0, False),
    (42.857, 43, 0, False),
    (42.857, 44, 0, True),
    (42.857, 42.856, 3, False),
    (42.857, 42.858, 3, True),
    # If you don't specify precision, your fail-under is rounded.
    (42.857, 42.856, 0, False),
    # Values near 100 should only be treated as 100 if they are 100.
    (99.8, 100, 0, True),
    (100.0, 100, 0, False),
    (99.8, 99.7, 1, False),
    (99.88, 99.90, 2, True),
    (99.999, 100, 1, True),
    (99.999, 100, 2, True),
    (99.999, 100, 3, True),
])
def test_should_fail_under(total: float, fail_under: float, precision: int, result: bool) -> None:
    assert should_fail_under(float(total), float(fail_under), precision) == result

def test_should_fail_under_invalid_value() -> None:
    with pytest.raises(ConfigError, match=r"fail_under=101"):
        should_fail_under(100.0, 101, 0)

@pytest.mark.parametrize("statements, lines, result", [
    ({1,2,3,4,5,10,11,12,13,14}, {1,2,5,10,11,13,14}, "1-2, 5-11, 13-14"),
    ([1,2,3,4,5,10,11,12,13,14,98,99], [1,2,5,10,11,13,14,99], "1-2, 5-11, 13-14, 99"),
    ([1,2,3,4,98,99,100,101,102,103,104], [1,2,99,102,103,104], "1-2, 99, 102-104"),
    ([17], [17], "17"),
    ([90,91,92,93,94,95], [90,91,92,93,94,95], "90-95"),
    ([1, 2, 3, 4, 5], [], ""),
    ([1, 2, 3, 4, 5], [4], "4"),
])
def test_format_lines(
    statements: Iterable[TLineNo],
    lines: Iterable[TLineNo],
    result: str,
) -> None:
    assert format_lines(statements, lines) == result

@pytest.mark.parametrize("statements, lines, arcs, result", [
    (
        {1,2,3,4,5,10,11,12,13,14},
        {1,2,5,10,11,13,14},
        (),
        "1-2, 5-11, 13-14"
    ),
    (
        [1,2,3,4,5,10,11,12,13,14,98,99],
        [1,2,5,10,11,13,14,99],
        [(3, [4]), (5, [10, 11]), (98, [100, -1])],
        "1-2, 3->4, 5-11, 13-14, 98->100, 98->exit, 99"
    ),
    (
        [1,2,3,4,98,99,100,101,102,103,104],
        [1,2,99,102,103,104],
        [(3, [4]), (104, [-1])],
        "1-2, 3->4, 99, 102-104"
    ),
])
def test_format_lines_with_arcs(
    statements: Iterable[TLineNo],
    lines: Iterable[TLineNo],
    arcs: Iterable[Tuple[TLineNo, List[TLineNo]]],
    result: str,
) -> None:
    assert format_lines(statements, lines, arcs) == result


import os
import pickle
from tqdm import tqdm

from datasets import load_dataset
import evaluate
from evaluate import evaluator
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline

'''
Summarization:
    dataset: CNN/DM
    metric: average three ROUGE scores (ROUGE-1, ROUGE-2, ROUGE-L)
'''

# Dataset
dataset = load_dataset("cnn_dailymail", '3.0.0')

# Metric
rouge_metric = evaluate.load('rouge')

# Model
model_name_or_path = "TheBloke/Llama-2-70B-GPTQ"
model = AutoModelForCausalLM.from_pretrained(model_name_or_path,
                                             device_map="auto",
                                             trust_remote_code=False,
                                             revision="main")
tokenizer = AutoTokenizer.from_pretrained(model_name_or_path, use_fast=True)

def summerizer(input_text):
    # print(f"input text : \n{input_text}\n\n\n\n")
    prompt = "Please summarize the previous content in one or two sentences, less than 300 words."
    prompt_template=f'''
    Content: {input_text}
    Question: {prompt}
    Summary:
    '''
    prompt_len = len(prompt_template)

    input_ids = tokenizer(prompt_template, return_tensors='pt').input_ids.cuda()
    output_ids = model.generate(inputs=input_ids, temperature=0.7, do_sample=True, top_p=0.95, top_k=40, max_new_tokens=512)
    # print(f"output ids: {type(output_ids)}\n{output_ids}\n\n\n\n")
    output = tokenizer.decode(output_ids[0])
    output_without_prompt = output[prompt_len:]
    # print(f"output : \n{output}\n\n\n\n")
    # print(f"output summary : \n{output_only_summary}\n\n\n\n")
    return output_without_prompt

# Run Evaluation
max_words = 0
max_length = 0

dataset_summaries = []
model_summaries = []

test_case_num = 0
skipped_case_nums = []
skipped_num = 0
for data in tqdm(dataset['test']):
    article = data['article']
    data_hightlight = data['highlights']

    n_words = len(article.split())
    n_length = len(article)

    if n_words > max_words:
        max_words = n_words

    if n_length > max_length:
        max_length = n_length

    # try:
    summary = summerizer(article)
    dataset_summaries.append(data_hightlight)
    model_summaries.append(summary)
    print("summary len : ", len(summary))
    print("reference len : ", len(data_hightlight))
    # except:
    #     skipped_case_nums.append(test_case_num)
    #     skipped_num += 1

    test_case_num += 1
    # if test_case_num == 100:
    #     break
    # break

print("Num of summary : ", len(model_summaries))
print("Skipped Cases : ", skipped_case_nums)
print("num of Skipped Cases : ", skipped_num)
print("max words : ", max_words)
print("max length : ", max_length)

rouge_scores = rouge_metric.compute(predictions=model_summaries, references=dataset_summaries)
for key, value in rouge_scores.items():
    print(f"{key} : {value}")
rouge_scores_average = (rouge_scores['rouge1'] + rouge_scores['rouge2'] + rouge_scores['rougeL'])/3

print("ROUGE Score: ", rouge_scores_average)

if __name__ == "__main__":
    print("Testing : ", os.path.basename(__file__))


"""
This module contains the functions for clustering.
"""

import logging as log

import numpy as np
from numba import njit

@njit
def get_density(distances, dc):
    """
    Returns the density of each date calculated by the distances and the dc value.
    """
    dist_cz = np.zeros(distances.shape[0])

    for i in range(distances.shape[0]):
        for j in range(i+1, distances.shape[0]):
            if distances[i, j] <= dc:
                dist_cz[i] += 1
                dist_cz[j] += 1
    return dist_cz

@njit
def get_maphd_index(distances, density, dc):
    """
    Returns for every datapoint the nearest data point with a higher density.
    """
    next_node = np.full(distances.shape[0], -1)

    for i in range(distances.shape[0]):
        for j in range(distances.shape[0]):
            if density[i] < density[j]:
                if next_node[i] == -1:
                    next_node[i] = j
                else:
                    if distances[i, next_node[i]] > distances[i, j]:
                        next_node[i] = j
            elif density[i] == density[j] and i < j:
                if next_node[i] == -1:
                    next_node[i] = j
                elif distances[i, next_node[i]] > distances[i, j] and distances[i, j] <= dc:
                    next_node[i] = j
    return next_node

@njit
def get_maphd(distances, next_nodes):
    """
    Returns the distance to the nearest data point with a higher density.
    """
    maphd = np.zeros(distances.shape[0])
    for i in range(distances.shape[0]):
        if next_nodes[i] == -1:
            maphd[i] = 1
        else:
            maphd[i] = distances[i, next_nodes[i]]

    return maphd

@njit
def clustering(next_nodes, cz):
    """
    Returns a list of the cluster center indices for every data point.
    """
    result = np.full(next_nodes.shape[0], -1)
    i = -1
    temp = []

    for cz_element in cz:
        result[cz_element] = cz_element

    for todo in result:
        i += 1
        if todo == -1:
            k = i
            while result[k] == -1:
                temp.append(k)
                k = next_nodes[k]
            cz_element = result[k]
            while len(temp) != 0:
                result[temp.pop()] = cz_element

    return result

def calculate_centers(df):
    """
    Returns the cluster centers.
    """
    cz = []
    while len(df[1]) != 0:
        if df[0, 0] >= df[0].max():
            cz.append(int(df[2, 0]))
            df = np.delete(arr=df, obj=0, axis=1)
        elif df[0, 0] >= df[0].mean():
            cz.append(int(df[2, 0]))
            df = np.delete(arr=df, obj=0, axis=1)
        else:
            break
    return cz

def get_centers(store):
    """
    Returns the cluster centers as a list.
    """
    log.info('Test dc: {store.dc}')
    log.info('...')

    # Calculate the density of the dates dependant on dc
    store.df['density'] = get_density(store.distances, store.dc)

    # maphd - Minimaler Abstand zu einem Punkt höherer Dichte (Delta im Paper)
    store.df['next_node'] = get_maphd_index(
        store.distances,
        store.df['density'].to_numpy(),
        store.dc
    )

    store.df['maphd'] = get_maphd(
        store.distances,
        store.df['next_node'].to_numpy()
    )

    temp_df = store.df.loc[:, ['density', 'maphd']].sort_values(
        'maphd', axis=0, ascending=False
    )
    temp_df['index'] = temp_df.index

    store.centers = np.array(calculate_centers(
        temp_df.to_numpy().T
    ))

    store.df['cluster_center'] = clustering(
        store.df['next_node'].to_numpy(),
        store.centers
    )

    return store.centers


def permutation(lst,n):
    ret = []
    if n > len(lst): return ret

    if n==1:
        for i in lst:
            ret.append([i])
    elif n>1:
        for i in range(len(lst)):
            temp = [i for i in lst]
            temp.remove(lst[i])
            for p in permutation(temp,n-1):
                ret.append([lst[i]]+p)

    return ret

print(permutation([1,2,3], 2))


# Recently, a colleague needed to know how much light a distribution of salt aerosol would scatter into two detectors, one at 60° and one at 90°. We modeled a lognormal distribution of NaCl particles based on laboratory measurements and then tried to figure out how much light we’d see at various angles.

import PyMieScatt as ps  # import PyMieScatt and abbreviate as ps
# import standard plotting library and abbreviate as plt
import matplotlib.pyplot as plt
import numpy as np  # import numpy and abbreviate as np
# import a single function for integration using trapezoidal rule
from scipy.integrate import trapz

m = 1.536  # refractive index of NaCl
wavelength = 405  # replace with the laser wavelength (nm)

dp_g = 85  # geometric mean diameter - replace with your own (nm)
# geometric standard deviation - replace with your own (unitless)
sigma_g = 1.5
N = 1e5  # total number of particles - replace with your own (cm^-3)

B = ps.Mie_Lognormal(m, wavelength, sigma_g, dp_g, N,
                     returnDistribution=True)  # Calculate optical properties

S = ps.SF_SD(m, wavelength, B[7], B[8])

fig1 = plt.figure(figsize=(10.08, 6.08))
ax1 = fig1.add_subplot(1, 1, 1)

ax1.plot(S[0], S[1], 'b', ls='dashdot', lw=1, label="Parallel Polarization")
ax1.plot(S[0], S[2], 'r', ls='dashed', lw=1,
         label="Perpendicular Polarization")
ax1.plot(S[0], S[3], 'k', lw=1, label="Unpolarized")

x_label = ["0", r"$\mathregular{\frac{\pi}{4}}$", r"$\mathregular{\frac{\pi}{2}}$",
           r"$\mathregular{\frac{3\pi}{4}}$", r"$\mathregular{\pi}$"]
x_tick = [0, np.pi / 4, np.pi / 2, 3 * np.pi / 4, np.pi]
ax1.set_xticks(x_tick)
ax1.set_xticklabels(x_label, fontsize=14)
ax1.tick_params(which='both', direction='in')
ax1.set_xlabel("Scattering Angle ϴ", fontsize=16)
ax1.set_ylabel(r"Intensity ($\mathregular{|S|^2}$)", fontsize=16, labelpad=10)
handles, labels = ax1.get_legend_handles_labels()
fig1.legend(handles, labels, fontsize=14, ncol=3, loc=8)

fig1.suptitle("Scattering Intensity Functions", fontsize=18)

plt.tight_layout(rect=[0.01, 0.05, 0.915, 0.95])

# Highlight certain angles and compute integral
sixty = [0.96 < x < 1.13 for x in S[0]]
ninety = [1.48 < x < 1.67 for x in S[0]]
ax1.fill_between(S[0], 0, S[3], where=sixty, color='g', alpha=0.15)
ax1.fill_between(S[0], 0, S[3], where=ninety, color='g', alpha=0.15)
ax1.set_yscale('log')

int_sixty = trapz(S[3][110:130], S[0][110:130])
int_ninety = trapz(S[3][169:191], S[0][169:191])

# Annotate plot with integral results
ax1.annotate("Integrated value = {i:1.3f}".format(i=int_sixty),
             xy=(np.pi / 3, S[3][120]), xycoords='data',
             xytext=(np.pi / 6, 0.8), textcoords='data',
             arrowprops=dict(arrowstyle="->",
                             connectionstyle="arc3"),
             )
ax1.annotate("Integrated value = {i:1.3f}".format(i=int_ninety),
             xy=(np.pi / 2, S[3][180]), xycoords='data',
             xytext=(2 * np.pi / 5, 2), textcoords='data',
             arrowprops=dict(arrowstyle="->",
                             connectionstyle="arc3"),
             )
plt.show()


#!/usr/bin/python3

import pytest
from web3 import Web3

@pytest.fixture(scope="module")
def popularity_indices():
    return 0x0505050505

@pytest.fixture(scope="module")
def buyer(accounts):
    return accounts[1]

def test_commission_one_piece(simulacra, buyer, popularity_indices):
    assert not simulacra.artSoldOut()
    assert simulacra.totalSupply() == 0
    price = simulacra.getCurrentPrice()
    tx = simulacra.commissionPieces(popularity_indices, 1, {'from': buyer, 'value': price})
    assert simulacra.balance() > 0
    assert simulacra.balanceOf(buyer) == 1
    assert simulacra.totalSupply() == 1

def test_commission_multiple_piece(simulacra, buyer, popularity_indices):
    expected_supply = simulacra.totalSupply()
    remaining = simulacra.remainingAtCurrentPrice()
    while remaining:
        assert not simulacra.artSoldOut()
        price = simulacra.getCurrentPrice()
        amount = min(remaining, 56)  # Approximate limit amount with test block gas limit
        tx = simulacra.commissionPieces(popularity_indices, amount, {'from': buyer, 'value': price * amount})
        assert simulacra.balance() > 0
        assert simulacra.balanceOf(buyer) == expected_supply + amount
        assert simulacra.totalSupply() == expected_supply + amount
        expected_supply = simulacra.totalSupply()
        remaining = simulacra.remainingAtCurrentPrice()

    assert simulacra.artSoldOut()
    assert not simulacra.artWasRevealed()
    assert not simulacra.isInRefundMode()


from setuptools import setup
# from sphinx.setup_command import BuildDoc
from os import path
#cmdclass = {'build_sphinx': BuildDoc}

# https://pypi.org/classifiers/

name = 'list_session_inhibitors'
keywords = 'inhibitors'
version = '0.9.8'
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
    long_description = f.read()

setup(
    name=name,
    keywords=keywords,
    version=version,
    author='Tim Richardson',
    author_email='tim@growthpath.com.au',
    description='command line utility to list session power inhibitors for Linux Gnome desktop users',
    long_description=long_description,
    long_description_content_type='text/markdown',
    packages=['list_session_inhibitors'],
    python_requires='>=3.6',
    install_requires=['pydbus','PyGObject>=3.40','click'],
    setup_requires=['pytest-runner', ],
    entry_points={"console_scripts": ["inhibitors=list_session_inhibitors.inhibitors:main"]},
    tests_require=["pytest", ],
    classifiers=[
        'Development Status :: 4 - Beta',
        'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
        'Programming Language :: Python :: 3.8',
        'Programming Language :: Python :: 3.9',
        'Topic :: Office/Business',
    ],
    url='https://github.com/timrichardson/gnome_inhibit_list',
    license='LGPLv3',

    #cmdclass=cmdclass,
    # these are optional and override conf.py settings
    # command_options={
    #     'build_sphinx': {
    #         'project': ('setup.py', name),
    #         'version': ('setup.py', version),
    #         'release': ('setup.py', version),
    #         'source_dir': ('setup.py', 'docs')}},

)


def solution(s):
    answer = len(s)

    # 문자열을 자를 단위 설정 1 ~ len(s) // 2 + 1
    for cut_unit in range(1, len(s) // 2 + 1):
        now_str = ""
        prev_word = s[:cut_unit]
        count = 1

        # 각 단위 마다 문자열을 비교하고 now_str에 압축
        for i in range(cut_unit, len(s), cut_unit):
            if prev_word == s[i:i+cut_unit]: # 다음 문자열과 일치하면, 카운트 + 1
                count += 1
                continue
            else: # 일치하지 않으면, 해당 문자열을 카운트와 함께 저장
                if count != 1: now_str += str(count) + prev_word
                else: now_str += prev_word

                prev_word = s[i:i+cut_unit]
                count = 1

        # 마지막 남아있는 문자열 처리
        if count != 1:
            now_str += str(count) + prev_word
        if now_str[len(now_str) - cut_unit:] != prev_word:
            now_str += prev_word

        # answer을 최솟값으로 갱신
        answer = min(answer, len(now_str))

    return answer

if __name__ == "__main__":
    s = "aabbaccc"
    print(solution(s))

나동빈-이코테/2차/문자열 압축.py


#!/usr/bin/python3
"""This module defines the State class."""
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class State(Base):
    """Represents a state mapped to the states table."""

    __tablename__ = 'states'

    id = Column(Integer, primary_key=True)
    name = Column(String(128), nullable=False)


import sys
import tensorflow as tf
from PIL import Image,ImageFilter

def leInteiro(imvalue):
    x = tf.placeholder(tf.float32, [None, 784])
    W = tf.Variable(tf.zeros([784, 10]))
    b = tf.Variable(tf.zeros([10]))
    y = tf.nn.softmax(tf.matmul(x, W) + b)

    init_op = tf.global_variables_initializer()
    saver = tf.train.Saver()

	# Carrega o modelo salvo na pasta e usa o conhecimento salvo pra poder "adivinhar o número"
    with tf.Session() as sess:
        sess.run(init_op)
        saver.restore(sess, "modelo.ckpt")

        prediction=tf.argmax(y,1)
        return prediction.eval(feed_dict={x: [imvalue]}, session=sess)

def preparaImagem(argv):
	#Salva a imagem, passada como argumento de linha de comando, em pixels
    imagemAdvinhar = Image.open(argv).convert('L')
    width = float(imagemAdvinhar.size[0])
    height = float(imagemAdvinhar.size[1])
    newImage = Image.new('L', (28, 28), (255)) #Cria uma imagem em branco de 28 x 28

    if width > height: #Verifica qual dimensão é maior
        nheight = int(round((20.0/width*height),0)) #Ajuta a altura

		# Redimensiona os pixels.
        img = iimagemAdvinharm.resize((20,nheight), Image.ANTIALIAS).filter(ImageFilter.SHARPEN)
        wtop = int(round(((28 - nheight)/2),0)) #Calcula posição horizontal
        newImage.paste(img, (4, wtop)) #Cola imagem na tela em branco
    else:
        nwidth = int(round((20.0/height*width),0)) #Ajuta a largura

		# Redimensiona os pixels.
        img = im.resize((nwidth,20), Image.ANTIALIAS).filter(ImageFilter.SHARPEN)
        wleft = int(round(((28 - nwidth)/2),0)) #Calcula posição vertical
        newImage.paste(img, (wleft, 4)) #Cola imagem na tela em branco

    tv = list(newImage.getdata()) #Lista o valor dos pixels.

    #Transforma tudo em preto 1 ou branco 0
    tva = [ (255-x)*1.0/255.0 for x in tv]
    return tva

def main(argv):
    imvalue = preparaImagem(argv)
    valorInteiro = leInteiro(imvalue)
    print (valorInteiro[0]) #primeiro valor da lista

if __name__ == "__main__":
    main(sys.argv[1])


from Encapsulamiento import Encapsulamiento
#from Encapsulamiento import * => Importar todas las clases

#formato de texto para imprimir
print("Creacion de objetos".center(50,'-'))

if __name__ =='__main__':
    #Realizar el objeto
    Encapsulamiento_1 = Encapsulamiento("Yamith","Cuervo","30")

    #Traer la funcion mostrar de la clase Encapsulamiento
    Encapsulamiento_1.mostrar()

    print(__name__)

print("Eliminacion de objetos".center(50,'-'))
del Encapsulamiento_1


#!/usr/bin/python
# -*- encoding: UTF-8 -*-

from tkinter import *

class Cell(Entry):
	def __init__(self, parent):
		self.value = StringVar()
		Entry.__init__(self, parent, textvariable = self.value)

class Table(Frame):
	def __init__(self, parent, columns = 4, rows = 10):
		Frame.__init__(self, parent)
		self.cells = [[Cell(self) for i in range(columns)] for j in range(rows)]
		[self.cells[i][j].grid(row = i, column = j) for i in range(rows) for j in range(columns)]

if __name__ == '__main__':
	root = Tk()
	tab = Table(root)
	tab.pack()
	tab.cells[1][1].value.set('test')
	tab.cells[2][2].value.set( tab.cells[1][1].value.get() )

	root.mainloop()


import os

from cfp.web.app import create_app

try:
    env = os.environ['FLASK_CONFIG']
    print(f'Executing app in {env} environment')
except KeyError:
    # print('FLASK_CONFIG env variable was not found.')
    # print('Defaulting to development environment')
    env = 'development'

app = create_app(env)

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')


import numpy as np

def list_of_bingo_indices(pile):
  indices = []
  for idx, card in enumerate(pile):
    col_bingo = card.sum(axis=0).max() == 5
    row_bingo = card.sum(axis=1).max() == 5
    if (col_bingo or row_bingo):
      indices.append(idx)
  return indices

def calculate_value(cards,drawn,idx,last_num):
  sum = 0
  print(drawn[idx])
  for x in range(5):
    for y in range(5):
      if drawn[idx][x][y] == 0:
        sum += cards[idx][x][y]
  return (sum*last_num)

input_data = [line.rstrip() for line in open('input4.txt')]
num_of_cards = int((len(input_data) - 1) / 6)

calls = input_data.pop(0).split(",")

cards = np.zeros((num_of_cards,5,5),dtype=int)
drawn = np.zeros((num_of_cards,5,5),dtype=int)

#load the cards
cur_card = 0
cur_row = 0
while(input_data):
  line = input_data.pop(0)
  if line:
    row = [int(x) for x in line.split()]
    cards[cur_card][cur_row] = row
    cur_row += 1
    if cur_row == 5:
      cur_card += 1
      cur_row = 0

for num in calls:
  result = np.where(cards==int(num))
  found = list(zip(result[0],result[1],result[2]))

  for i in found:
    drawn[i] = 1
  winning_indices = list_of_bingo_indices(drawn)
  if len(winning_indices) == 1:
    p1_value = calculate_value(cards, drawn, winning_indices[0],int(num))
    print("Part 1 value is " + str(p1_value))
  unwon_card = -1
  if len(winning_indices) == num_of_cards-1:
    for i in range(num_of_cards):
      if winning_indices[i] != i:
        last_card = i
        break
  if len(winning_indices) == num_of_cards:
    p2_value = calculate_value(cards, drawn, last_card,int(num))
    print("Part 2 value is " + str(p2_value))
    break


import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import time
from scipy.io import loadmat

def load_data():
    data = loadmat('E:\\download_backup\\train_32x32.mat')
    datax, datay = data['X'].transpose((3, 0, 1, 2)), data['y'][:,0]  # shape of (73257, 32, 32, 3) and (73257,)
    pos_class=1
    neg_class=2
    dataIndx = (datay == pos_class) + (datay == neg_class)
    Data = datax[dataIndx] / 255.
    Target = datay[dataIndx].reshape(-1, 1)

    Target[Target == pos_class] = 1
    Target[Target == neg_class] = 0
    np.random.seed(421)
    randIndx = np.arange(len(Data))

    np.random.shuffle(randIndx)
    Data, Target = Data[randIndx], Target[randIndx]
    print(Data.shape)
    training_data, training_label = Data[:6000] , Target[:6000]
    valid_data, valid_label = Data[6000:7000], Target[6000:7000]
    test_data, test_label = Data[7000:], Target[7000:]

    return training_data, training_label,valid_data, valid_label,test_data, test_label

def rgb2gray(images):
    return np.expand_dims(np.dot(images, [0.2990, 0.5870, 0.1140]), axis=3)

def svm_learning(trainx, trainy,batch_size = 50):
    sess = tf.Session()
    x_data = tf.placeholder(shape=[None, 1024], dtype=tf.float32)
    y_target = tf.placeholder(shape=[None, 1], dtype=tf.float32)
    prediction_grid = tf.placeholder(shape=[None, 1024], dtype=tf.float32)

    b = tf.Variable(tf.random_normal(shape=[1, batch_size]))

    kernel = tf.matmul(x_data, tf.transpose(x_data))

    first_sum = tf.reduce_sum(b)
    b_mul= tf.matmul(tf.transpose(b), b)
    y_mul = tf.matmul(y_target, tf.transpose(y_target))
    second_sum = tf.reduce_sum(tf.multiply(kernel, tf.multiply(b_mul, y_mul)))
    loss = tf.negative(tf.subtract(first_sum, second_sum))

    kernel_pre = tf.matmul(x_data, tf.transpose(prediction_grid))

    pre_output = tf.matmul(tf.multiply(tf.transpose(y_target), b), kernel_pre)
    mean=tf.reduce_mean(pre_output)
    pred = tf.sign(pre_output - tf.reduce_mean(pre_output))
    accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.squeeze(tf.transpose(pred)), tf.squeeze(y_target)), tf.float32))

    #optimizer=tf.train.GradientDescentOptimizer(0.001).minimize(loss)
    optimizer = tf.train.AdamOptimizer(0.001).minimize(loss)

    init = tf.global_variables_initializer()
    sess.run(init)

    # Training loop
    loss_vec = []
    batch_accuracy = []

    for i in range(3000):
        rand_index = np.random.choice(len(d1), size=batch_size)
        rand_x = trainx[rand_index]
        rand_y = trainy[rand_index]
        sess.run(optimizer, feed_dict={x_data: rand_x, y_target: rand_y})
        pre=sess.run(mean, feed_dict={x_data: rand_x, y_target: rand_y,prediction_grid: rand_x})
        print(pre)

        if (i) % 100 == 0:
            pre = sess.run(pred, feed_dict={x_data: rand_x, y_target: rand_y, prediction_grid: rand_x})
            print(pre)
            temp_loss = sess.run(loss, feed_dict={x_data: rand_x, y_target: rand_y})
            loss_vec.append(temp_loss)

            acc_temp = sess.run(accuracy, feed_dict={x_data: rand_x,
                                                     y_target: rand_y,
                                                     prediction_grid: rand_x})
            batch_accuracy.append(acc_temp)
            print('run:' + str(i + 1))
            print('Loss: ' + str(temp_loss))
            print('accracy: ' + str(acc_temp))
    plt.figure(1)
    plt.plot(loss_vec, color='RED', label="Train Data")
    plt.figure(2)
    plt.plot(batch_accuracy, color='RED', label="acc")
    plt.show()

d1,l1,d2,l2,d3,l3=load_data()
grey_test=np.reshape(rgb2gray(d3),[-1,1024])
grey_valid=np.reshape(rgb2gray(d2),[-1,1024])
grey_train=np.reshape(rgb2gray(d1),[-1,1024])
label_2=np.ones([6000,1])
label_2[l1==0]=-1

train_labels=np.concatenate((l1,label_2),axis=1)
print(label_2[:10])
valid_label_2=np.ones([1000,1])
valid_label_2[l2==1]=0
valid_labels=np.concatenate((l2,valid_label_2),axis=1)

test_label_2=np.ones([int(len(l3)),1])
test_label_2[l3==1]=0
test_labels=np.concatenate((l3,test_label_2),axis=1)
svm_learning(grey_train,label_2)


"""
< 소수의 연속합 >
https://www.acmicpc.net/problem/1644
문제)
- 하나 이상의 연속된 소수의 합으로 나타낼 수 있는 자연수들이 있다.
- 3     :
"""
import sys

input = sys.stdin.readline

N = int(input())
prime = []
dp = [1] * (N + 1)
dp[0] = 0
dp[1] = 0

for i in range(2, N + 1):
    if dp[i]:
        prime.append(i)
        for j in range(i * 2, N + 1, i):
            dp[j] = 0
prime.append(0)

l = 0
r = 0
size = len(prime) - 1  # 위에 prime.append(0) 때문에
ans = 0
sum = prime[0]

while l <= r:
    if r >= size:
        break
    if sum == N:
        ans += 1
        sum -= prime[l]
        l += 1
        r += 1
        sum += prime[r]
    elif sum < N:
        r += 1
        sum += prime[r]
    else:
        sum -= prime[l]
        l += 1
    # print(f"r:{r}, l:{l}, sum:{sum}")
print(ans)


from sys import maxsize

#   Tree

class Node: # THE GOAL TREE OF THIS ALGORITHM WILL BE MADE OF NODES
    def __init__(self, i_depth, i_playernum, i_sticksRemaining, i_value=0):
        self.i_depth = i_depth #    STORES THE DEPTH OF THE NODE INSIDE THE TREE
        self.i_playernum = i_playernum #    TAKES IN THE MINIMUM PLAYER OR THE MAXIMUM PLAYER
        self.i_sticksRemaining = i_sticksRemaining #    STORES THE STICKS REMAINING AT THIS NODE
        self.i_value = i_value #    IF IT IS A WINNING MOVE OF LOOSING MOVE THIS WILL STORE -INFINITY OR +INFINITY
        self.children = [] #    STORES THE TWO BRANCHES OF THIS NODE INCLUDING EACH AND EVERY SINGLE BRANCH OF THOSE NODES
        #print("\t\t"*(abs(5-i_depth)), (i_depth, i_playernum, i_sticksRemaining, i_value))  # UNCOMMENT THIS TO SEE THE GOAL TREE
        self.CreateChildren() # THIS CLASS FUNCTION WILL CREATE THE BRANCHES OF THIS NODE WHICH ARE AT THE LOWER DEPTHS

    def CreateChildren(self):
        if self.i_depth >= -2: # THIS FUNCTION WILL PROCEED ONLY TILL IT REACHES A NODE AT DEPTH -2
            for i in range(1, 3): # SINCE WE CAN REMOVE ONLY TWO STICKS THIS LOOP WILL ITERATE TWICE CREATING TWO BRANCHES IN THE GOAL TREE
                v = self.i_sticksRemaining - i #    THIS PASSES THE REMAINING STICKS AFTER THIS MOVE IS TAKEN TO THE CHILD
                self.children.append( Node( self.i_depth-1,
                                            -self.i_playernum, v, self.RealVal(v))) #   THE CHILD IS STORED IN A LIST

    def RealVal(self, value):
        if value == 0:
            return maxsize * self.i_playernum # IF THE REMAINING STICKS IS ZERO THEN THIS IS THE WINNING MOVE FOR THIS PLAYER
        elif value < 0:
            return maxsize * -self.i_playernum # IF THE REMAINING STICKS IS LESS THAN ZERO THIS MOVE FAVOURS THE OPPONENT
        return 0 #  IF THE STICKS REMAINING IS NON NEGATIVE OR ZERO WE CANNOT COME TO A CONCLUSION ABOUT THIS MOVE

def MinMax(node, i_depth, i_playerNum):
    #print("Now I am at depth ", i_depth) # USED FOR DEBUGGING
    if i_depth == -2: # THIS RETURNS THE NODE VALUE WHEN THE TREE COMES TO A DEPTH OF -2
        #print("reached depth ", i_depth, " hence terminating ", " got return value ", node.i_value)
        return node.i_value #   IF THE PROGRAM REACHES THE FINAL DEPTH OF THE GOAL TREE RETURNS THE NODE VALUE OF THE LAST NODE

    if abs(node.i_value) == maxsize: #  THIS RETURNS THE NODE VALUE IF THE NODE HAS ONE THATS NON ZERO
        #print("HI")
        return node.i_value

    i_bestValue = maxsize * -i_playerNum #  IF NO BESTVALUE IS FOUND WHEN ITERATING THROUGH THE BRANCHES RETURNS THIS AS IT IS IN FAVOUR OF THE OPPONENT

    for i in range(len(node.children)): #   ITERATES THROUGH EVERY BRANCH OF THE GOAL TREE
        child = node.children[i]
        i_val = MinMax(child, i_depth-1, -i_playerNum) #    RECURSION OCCURS TILL THE DEPTH BECOMES -2 OR A NODE VALUE IS FOUND

        if (abs(maxsize * i_playerNum - i_val) < abs(maxsize * i_playerNum - i_bestValue)) and i_bestValue != i_val:# IF THE NODE REUTRNS THE VALUE DESIRED BY THE PLAYER IT IS ASSIGNED TO BESTVALUE
            i_bestValue = i_val
            #print("Best value was changed @ ", (child.i_depth, child.i_playernum, child.i_sticksRemaining, i_bestValue))

    return i_bestValue #    IF A BEST VALUE IS FOUND THROUGH RECURSION RETURN THIS VALUE

def WinCheck(i_sticks, i_playerNum): # CHECKS IF A PLAYER HAS WON
    if i_sticks <= 0:
        print("*"*30)
        if i_playerNum > 0:
            if i_sticks == 0:
                print("\tYou Win!")
            else:
                print("\tToo Many.You Lose")
        else:
            if i_sticks == 0:
                print("\tComputer Wins...Better Luck Next Time")
            else:
                print("\tComp Error")

        print("*"*30)
        return 0
    return 1

if __name__ == '__main__':
    # INITIALIZE THE TOTAL STICKS , DEPTH OF THE TREE AND THE STARTINGG PLAYER
    i_stickTotal = 11 # TOTAL NO OF STICKS IN THIS GAME
    i_depth = 5 # THE DEPTH OF THE GOAL TREEE THE COMPUTER WILL BUILD
    i_curPlayer = 1 # THIS WILL BE +1 FOR THE HUMAN AND -1 FOR THE COMPUTER
    print("""There are 11 sticks in total.\nYou can choose 1 or 2 sticks in each turn.\n\tGood Luck!!""")
    # GAME LOOP
    while i_stickTotal > 0:
        print("\n{} sticks remain. How many would you pick?".format(i_stickTotal))
        try:
            i_choice = int(input("\n1 or 2: "))
            if  i_choice - 1 == 0 or i_choice - 2 == 0:
                i_stickTotal -= int(i_choice)
                if WinCheck(i_stickTotal, i_curPlayer):
                    i_curPlayer *= -1
                    node = Node(i_depth, i_curPlayer, i_stickTotal)
                    bestChoice = -100
                    i_bestValue = -i_curPlayer * maxsize

                    #   Determine No of Sticks to Remove

                    for i in range(len(node.children)):
                        n_child = node.children[i]
                        #print("heres what it look like ", n_child.i_depth, "and",i_depth)
                        i_val = MinMax(n_child, i_depth-1, i_curPlayer)
                        if abs(i_curPlayer * maxsize - i_val) <= abs(i_curPlayer*maxsize-i_bestValue):
                            i_bestValue = i_val
                            bestChoice = i
                            #print("Best value was changed @ ", i_depth, " by " , -i_curPlayer, " branch ", i, " to ", i_bestValue)

                    bestChoice += 1
                    print("Computer chooses: " + str(bestChoice) + "\tbased on value: " + str(i_bestValue))
                    i_stickTotal -= bestChoice
                    WinCheck(i_stickTotal, i_curPlayer)
                    i_curPlayer *= -1
                else:
                    print("You can take only a maximum of two sticks.")

        except:
            print("Invalid input.Only Numeric Values are accepted")


from adapters import inputs, outputs
from core import errors
from core.request import request_service
from core import request as core_request

class ServerInstance:
    ServerAction = inputs.ServerAction
    ServerStatus = outputs.ServerStatus

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

    def action(self, act: str):
        """
        :raises: Error
        """
        server = self.server
        params = inputs.ServerActionInput(
            instance_id=server.instance_id, instance_name=server.instance_name, action=act)

        try:
            r = request_service(server.service, method='server_action', params=params)
        except errors.APIException as exc:
            raise exc

    def status(self):
        """
        :raises: Error
        """
        try:
            status_code, status_text = core_request.server_status_code(server=self.server)
        except errors.APIException as exc:
            raise exc

        return status_code, status_text


# -*- coding: utf-8 -*-
# @Time    : 2020/11/11 22:50
# @Author  : longrong.lang
# @FileName: conftest.py
# @Software: PyCharm
# @Cnblogs ：https://www.cnblogs.com/longronglang
import pytest

@pytest.fixture(scope='function')
def addcart(login):
    print("从详情页登录，将商品加入购物车")
    price="2099元"
    yield price
    print('添加购物车成功，累计计算中')


# Exercise Reference Source Link: https://github.com/codebasics/data-structures-algorithms-python/blob/master/data_structures/8_Binary_Tree_1/8_binary_tree_part_1_exercise.md

# * REQUIRED TERMINAL OUTPUT
""" find_min(): finds minimum element in entire binary tree
    find_max(): finds maximum element in entire binary tree
    calculate_sum(): calculates sum of all elements
    post_order_traversal(): performs post order traversal of a binary tree
    pre_order_traversal(): performs pre order traversal of a binary tree\
"""

class BinarySearchTreeNode:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

    # this could be a root node or any node on the tree
    def add_child(self, data):
        if data == self.data:
            return # binary search tree cannot have duplicate children or elements which are not equal to the current node

        if data < self.data:
            # add data in left subtree;
            if self.left:
                self.left.add_child(data)
            else:
                self.left = BinarySearchTreeNode(data)
        else:
            # add data in right subtree;
            if self.right:
                self.right.add_child(data)
            else:
                self.right = BinarySearchTreeNode(data)

    def search(self, val):
        if self.data == val:
            return True

        # if the value we're searching for is less than data
        if val < self.data:
            if self.left:
                return self.left.search(val) # it will do a recursive search on the left subtree and is the same function as above
            else:
                return False # when it reach to end, it indicates that this does not exist in our tree
            # 'val' might be in left subtree (not guaranteed)

        # if the value we're searching for is greater than data
        if val > self.data:
            if self.right:
                return self.right.search(val) # it will do a recursive search
            else:
                return False
            # 'val' might be in right subtree (not guaranteed)

    # Implementing an algorithm for specifying a particular order of precedence for a given data node.
    def in_order_traversal(self):
        elements = []

        # visiting the left tree element/s
        if self.left:
            # when checking elements = elements plus something, the self.left.in_order_traversal method will return some list and it will add that list to a local "element" list.
            elements += self.left.in_order_traversal() # calling this function recursively

        # visiting the base node
        elements.append(self.data)

        # visiting the right tree element/s
        if self.right:
            elements += self.right.in_order_traversal() # ' ' ' '

        return elements # it returns all the elements in the tree in specific order [ascending order]

    def pre_order_traversal(self):
        elements = [self.data]
        if self.left:
            elements += self.left.pre_order_traversal()
        if self.right:
            elements += self.right.pre_order_traversal()

        return elements

    def post_order_traversal(self):
        elements = []
        if self.left:
            elements += self.left.post_order_traversal()
        if self.right:
            elements += self.right.post_order_traversal()

        elements.append(self.data)

        return elements

    def find_min(self):
        if self.left is None: # the left child element of the root node has been used as the perspective view for finding the minimum element in the binary tree.
            return self.data
        return self.left.find_min()

    def find_max(self):
        if self.right is None: # the right child element of the root node has been used as the perspective view for finding the minimum element in the binary tree.
            return self.data
        return self.right.find_max()

    def calculate_sum(self):
        if self.left:
            left_sum = self.left.calculate_sum()
        else:
            left_sum = 0

        if self.right:
            right_sum = self.right.calculate_sum()
        else:
            right_sum = 0

        return self.data + left_sum + right_sum

def build_tree(elements):
    print("\nBuilding tree with these elements: ", elements)
    # root node for the tree element
    root = BinarySearchTreeNode(elements[0])

    # building the tree using for loop iteration methods
    for i in range(1, len(elements)):
        root.add_child(elements[i])

    return root

# return main method with the given data node structure that consist of numbers in list
if __name__ == "__main__":
    numbers = [23, 3, 1, 27, 13, 8, 17, 60]

    numbers_tree = build_tree(numbers)

    print("\nInput numbers: ", numbers)
    print("Minimum number: ", numbers_tree.find_min())
    print("Maximum number: ", numbers_tree.find_max())
    print("Calculated sum: ", numbers_tree.calculate_sum())
    print("\nIn Order Traversal: ", numbers_tree.in_order_traversal())
    print("Pre Order Traversal: ", numbers_tree.pre_order_traversal())
    print("Post Order Traversal: ", numbers_tree.post_order_traversal(), "\n")

Binary Search Tree - PART 1/BT_Exercise.py


# -*- coding: utf-8 -*-
import cv2
import numpy as np
import os
import pickle
import random
import config

from multiprocessing.pool import ThreadPool

import logbook
logger = logbook.Logger(__name__)

SIFT = cv2.xfeatures2d.SIFT_create(contrastThreshold=config.SIFT_CONTRAST_THRESHOLD, edgeThreshold=config.SIFT_EDGE_THRESHOLD, sigma=config.SIFT_SIGMA)
FLANN = cv2.FlannBasedMatcher(config.FLANN_INDEX_PARAMS, config.FLANN_SEARCH_PARAMS)
BF = cv2.BFMatcher(normType=cv2.NORM_HAMMING)

class Match(object):
    def __init__(self, nissl_level, matches, H, mask, result, result2, dist):
        self.nissl_level = nissl_level
        self.matches = matches
        self.H = H
        self.mask = mask
        self.result = result
        self.result2 = result2

        self.dist = dist

        self.matches_count = len(matches)
        self.inlier_count = mask.sum()
        self.inlier_ratio = int(self.inlier_count / self.matches_count * 100)

        self.homography_det = abs(np.linalg.det(H))

        self.svd = np.linalg.svd(self.H, compute_uv=False)
        self.svd_ratio = int(self.svd[0] / self.svd[-1])

    def comparison_key(self):
        return self.inlier_count
        #return -((1/self.inlier_ratio) * (self.svd_ratio) * self.homography_det * self.dist)

    # ['Plate', 'Match Count', 'Inlier Count', 'I/M', 'SVD', 'Det H']
    def to_string_array(self):
        return np.array([
            "Plate #" + str(self.nissl_level),
            str(self.matches_count),
            str(self.inlier_count),
            str(self.inlier_ratio),
            str(self.svd_ratio),
            str(self.homography_det),
            str((1/self.inlier_ratio) * (self.svd_ratio) * self.homography_det * self.dist)
            ])

def warp(im, points, disp_min, disp_max, disp_len = None, disp_angle = None):
    h, w = im.shape[:2]

    # Include the corners
    src_pts = np.array([[0, 0], [w, 0], [0, h], [w, h]])
    dst_pts = np.array([[0, 0], [w, 0], [0, h], [w, h]])

    for i in range(points):
        rand_x = random.uniform(0, w)
        rand_y = random.uniform(0, h)
        p = np.array([rand_x, rand_y])
        if disp_len is None:
            rand_len = random.uniform(disp_min, disp_max)
        else:
            rand_len = disp_len

        if disp_angle is None:
            rand_angle = np.deg2rad(random.uniform(0, 360))
        else:
            rand_angle = disp_angle

        p2_x = rand_x + np.cos(rand_angle) * rand_len
        p2_y = rand_y + np.sin(rand_angle) * rand_len
        p2 = np.array([p2_x, p2_y])

        if src_pts is None:
            src_pts = np.array([p])
        else:
            temp = np.vstack((src_pts, p))
            src_pts = temp

        if dst_pts is None:
            dst_pts = np.array([p2])
        else:
            temp = np.vstack((dst_pts, p2))
            dst_pts = temp

    from skimage.transform import warp, PiecewiseAffineTransform
    tform = PiecewiseAffineTransform()
    tform.estimate(src_pts, dst_pts)
    warped_im = warp(im, tform)

    # Convert to OpenCV
    from skimage import img_as_ubyte
    warped_im = img_as_ubyte(warped_im)
    return warped_im

def im_read(filename, flags=cv2.IMREAD_COLOR):
    im = cv2.imread(filename, flags)

    if flags == cv2.IMREAD_COLOR:
        # Convert from BGR to RGB for some reason
        im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)

    return im

def im_write(filename, im):
    if len(im.shape) == 3:
        # Not grayscale
        # Convert back to the original BGR
        im = cv2.cvtColor(im, cv2.COLOR_RGB2BGR)

    cv2.imwrite(filename, im)

def nissl_load(nissl_level, color_flags=cv2.IMREAD_COLOR):
    filename = config.NISSL_PREFIX + str(nissl_level).zfill(config.NISSL_DIGITS) + config.NISSL_EXT
    path = os.path.join(config.NISSL_DIR, filename)

    if not os.path.exists(path):
        logger.error("Tried to load plate {0} but it wasn't found in path {1}", nissl_level, path)
        return None

    return im_read(path, color_flags)

def nissl_load_sift(nissl_level):
    filename = config.NISSL_PREFIX + str(nissl_level).zfill(config.NISSL_DIGITS) + ".sift"
    path = os.path.join(config.NISSL_DIR, filename)

    if not os.path.exists(path):
        logger.info("Creating SIFT for plate {0}", nissl_level)
        nissl = nissl_load(nissl_level, cv2.IMREAD_GRAYSCALE)
        if nissl is None:
            return None

        kp, des = extract_sift(nissl)
        temp = pickle_sift(kp, des)
        pickle.dump(temp, open(path, "wb"))
        return kp, des

    else:
        raw_sift = pickle.load(open(path, "rb"))
        kp, des = unpickle_sift(raw_sift)
        return kp, des

def match(im1, kp1, des1, im2, kp2, des2):
    if config.MATCH_WITH_FLANN:
        matches = FLANN.knnMatch(des1, des2, k=2)
    else:
        matches = BF.knnMatch(des1, des2, k=2)

    # Apply Ratio Test
    good_matches = [m[0] for m in matches if len(m) == 2 and m[0].distance < m[1].distance * config.DISTANCE_RATIO]

    if len(good_matches) < config.MIN_MATCH_COUNT:
        logger.debug("Matches lower than threshold. {0} < {1}", len(good_matches), config.MIN_MATCH_COUNT)
        return None

    # For homography calculation
    src_pts = np.float32([kp1[m.queryIdx].pt for m in good_matches])
    dst_pts = np.float32([kp2[m.trainIdx].pt for m in good_matches])

    # Obtain the homography matrix using RANSAC
    H, mask = cv2.findHomography(src_pts, dst_pts, method=cv2.RANSAC, ransacReprojThreshold=config.RANSAC_REPROJ_TRESHHOLD, maxIters=config.RANSAC_MAX_ITERS, confidence=config.RANSAC_CONFIDENCE)

    # Check homography validity
    if H is None or len(H.shape) != 2:
        logger.debug("Couldn't get homography")
        return None

    # This mask contains the inliers
    matchesMask = mask.ravel().tolist()

    # Calculate the homography determinant
    det = np.linalg.det(H)
    logger.debug("Homography determinant = {0:f}", det)

    # If it's too low for comfort, don't consider the match
    # Or too high
    #if abs(det) < 0.01 or abs(det) > 5:
    #    return None

    # Apply the perspective transformation to the source image corners
    h, w = im1.shape[:2]
    corners = np.float32([[0, 0], [0, h-1], [w-1, h-1], [w-1, 0]]).reshape(-1, 1, 2)

    # Attempt to transform corners based on homography
    try:
        transformedCorners = cv2.perspectiveTransform(corners, H)
    except:
        logger.debug("Couldn't transform corners")
        return None

    # Only accept corners that remain convex after being transformed
    isConvex = cv2.isContourConvex(transformedCorners)
    if not isConvex:
        return None

    # Get the 7 Hu invariant moments
    original_moments = cv2.HuMoments(cv2.moments(corners)).flatten()
    transformed_moments = cv2.HuMoments(cv2.moments(transformedCorners)).flatten()

    # Find the Euclidean distance between the moments
    hu_distance = np.linalg.norm(original_moments - transformed_moments)
    logger.debug("[Hu Moment Distance] = {0}", hu_distance)

    # Ignore moments that are too large
    #if hu_distance > config.HU_DISTANCE_THRESHOLD:
    #    return None

    # Draw a polygon on the second image joining the transformed corners
    im2 = cv2.polylines(im2, [np.int32(transformedCorners)], True, config.MATCH_RECT_COLOR, 2, cv2.LINE_AA)

    # Prepare drawing parameters for drawing lines between matches
    #drawParameters = dict(matchColor=None, singlePointColor=None, matchesMask=None, flags=cv2.DRAW_MATCHES_FLAGS_NOT_DRAW_SINGLE_POINTS)
    drawParameters = dict(matchColor=None, singlePointColor=None, matchesMask=matchesMask, flags=cv2.DRAW_MATCHES_FLAGS_NOT_DRAW_SINGLE_POINTS)

    # Draw the lines between the 2 images connecting matches
    im_matches = cv2.drawMatches(im1, kp1, im2, kp2, good_matches, None, **drawParameters)

    # Warp the first image onto the second image
    im_warp = cv2.warpPerspective(im1, H, (im2.shape[1],im2.shape[0]))

    # Find the pixels which are visible in the warped image
    overlay_mask = (im_warp != 0)

    # Create a copy of the second image
    im_overlay = im2

    # Overlay the warped image on top of the 2nd image
    # If the mask is grayscale the overlay will only be applied to the red channel
    if len(overlay_mask.shape) == 3: # Overlay colors
        im_overlay[overlay_mask] = im_warp[overlay_mask]
    else:
        im_overlay[overlay_mask, 0] = im_warp[overlay_mask]

    return Match(None, good_matches, H, mask, im_matches, im_overlay, hu_distance)

def match_fast(kp1, des1, kp2, des2):
    if config.MATCH_WITH_FLANN:
        matches = FLANN.knnMatch(des1, des2, k=2)
    else:
        matches = BF.knnMatch(des1, des2, k=2)

    # Apply Ratio Test
    good_matches = [m[0] for m in matches if len(m) == 2 and m[0].distance < m[1].distance * config.DISTANCE_RATIO]

    # For homography calculation
    src_pts = np.float32([kp1[m.queryIdx].pt for m in good_matches])
    dst_pts = np.float32([kp2[m.trainIdx].pt for m in good_matches])

    # Obtain the homography matrix using RANSAC
    H, mask = cv2.findHomography(src_pts, dst_pts, method=cv2.RANSAC, ransacReprojThreshold=config.RANSAC_REPROJ_TRESHHOLD, maxIters=config.RANSAC_MAX_ITERS, confidence=config.RANSAC_CONFIDENCE)

    return good_matches

def match_region_nissl(im_region, nissl_level):
    kp1, des1 = extract_sift(im_region)

    kp2, des2 = nissl_load_sift(nissl_level)
    im_nissl = nissl_load(nissl_level)

    m = match(im_region, kp1, des1, im_nissl, kp2, des2)
    if m is None:
        return None
    else:
        m.nissl_level = nissl_level
        logger.debug("Match accepted")
        return m

def match_sift_nissl(im_region, kp1, des1, nissl_level):
    logger.debug("=============== Matching {0}", nissl_level)
    kp2, des2 = nissl_load_sift(nissl_level)
    im_nissl = nissl_load(nissl_level)

    m = match(im_region, kp1, des1, im_nissl, kp2, des2)

    if m is None:
        return None
    else:
        m.nissl_level = nissl_level
        return m

def extract_sift(im):
    if im.dtype != np.uint8:
            im = (im * 255).astype(np.uint8)

    if len(im.shape) == 3:
        im = cv2.cvtColor(im, cv2.COLOR_RGB2GRAY)

    # Use multithreading to split the affine detection work
    pool = ThreadPool(processes = cv2.getNumberOfCPUs())

    #kp, des = affine_detect(SIFT, im, pool=pool)
    kp, des = SIFT.detectAndCompute(im, None)

    pool.close()
    pool.join()

    return kp, des

def affine_skew(tilt, phi, img, mask=None):
    '''
    affine_skew(tilt, phi, img, mask=None) -> skew_img, skew_mask, Ai
    Ai - is an affine transform matrix from skew_img to img
    '''
    h, w = img.shape[:2]
    if mask is None:
        mask = np.zeros((h, w), np.uint8)
        mask[:] = 255
    A = np.float32([[1, 0, 0], [0, 1, 0]])
    if phi != 0.0:
        phi = np.deg2rad(phi)
        s, c = np.sin(phi), np.cos(phi)
        A = np.float32([[c,-s], [ s, c]])
        corners = [[0, 0], [w, 0], [w, h], [0, h]]
        tcorners = np.int32( np.dot(corners, A.T) )
        x, y, w, h = cv2.boundingRect(tcorners.reshape(1,-1,2))
        A = np.hstack([A, [[-x], [-y]]])
        img = cv2.warpAffine(img, A, (w, h), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REPLICATE)
    if tilt != 1.0:
        s = 0.8*np.sqrt(tilt*tilt-1)
        img = cv2.GaussianBlur(img, (0, 0), sigmaX=s, sigmaY=0.01)
        img = cv2.resize(img, (0, 0), fx=1.0/tilt, fy=1.0, interpolation=cv2.INTER_NEAREST)
        A[0] /= tilt
    if phi != 0.0 or tilt != 1.0:
        h, w = img.shape[:2]
        mask = cv2.warpAffine(mask, A, (w, h), flags=cv2.INTER_NEAREST)
    Ai = cv2.invertAffineTransform(A)
    return img, mask, Ai

def affine_detect(detector, img, mask=None, pool=None):
    '''
    affine_detect(detector, img, mask=None, pool=None) -> keypoints, descrs
    Apply a set of affine transormations to the image, detect keypoints and
    reproject them into initial image coordinates.
    See http://www.ipol.im/pub/algo/my_affine_sift/ for the details.
    ThreadPool object may be passed to speedup the computation.
    '''
    params = [(1.0, 0.0)]
    for t in 2**(0.5*np.arange(1,6)):
        for phi in np.arange(0, 180, 72.0 / t):
            params.append((t, phi))

    def f(p):
        t, phi = p
        timg, tmask, Ai = affine_skew(t, phi, img)
        keypoints, descrs = detector.detectAndCompute(timg, tmask)
        for kp in keypoints:
            x, y = kp.pt
            kp.pt = tuple( np.dot(Ai, (x, y, 1)) )
        if descrs is None:
            descrs = []
        return keypoints, descrs

    keypoints, descrs = [], []
    if pool is None:
        ires = map(f, params)
    else:
        ires = pool.map(f, params)

    for i, (k, d) in enumerate(ires):
        #logger.debug('affine sampling: %d / %d\r' % (i+1, len(params)))
        keypoints.extend(k)
        descrs.extend(d)

    return keypoints, np.array(descrs)

# https://isotope11.com/blog/storing-surf-sift-orb-keypoints-using-opencv-in-python
def pickle_sift(keypoints, descriptors):
    i = 0
    temp_array = []
    for point in keypoints:
        if i >= len(descriptors):
            break
        temp = (point.pt, point.size, point.angle, point.response, point.octave,
        point.class_id, descriptors[i])
        i += 1
        temp_array.append(temp)
    return temp_array

def unpickle_sift(array):
    keypoints = []
    descriptors = []
    for point in array:
        temp_feature = cv2.KeyPoint(x=point[0][0],y=point[0][1],_size=point[1], _angle=point[2], _response=point[3], _octave=point[4], _class_id=point[5])
        temp_descriptor = point[6]
        keypoints.append(temp_feature)
        descriptors.append(temp_descriptor)
    return keypoints, np.array(descriptors)


import heapq
from collections import deque

def dist(x1, y1, x2, y2):
    return ((x1-x2)**2 + (y1-y2)**2)**(.5)

N, M = map(int, input().split())
# 大きい塔
X = []
Y = []
C = []
for _ in range(N):
    xi, yi, ci = map(int, input().split())
    X.append(xi)
    Y.append(yi)
    C.append(ci)
# 小さい塔
x = []
y = []
c = []
for _ in range(M):
    xi, yi, ci = map(int, input().split())
    x.append(xi)
    y.append(yi)
    c.append(ci)

ALL = 1 << M

# 小さい塔の含め方でそれぞれ最小全域木を求める
ans = 10**100
for bit in range(ALL):
    Q = []

    # 大きい塔0から他の大きい塔
    for i in range(1, N):
        cost = dist(X[0], Y[0], X[i], Y[i])
        if C[0] != C[i]: cost *= 10
        heapq.heappush(Q, (cost, i))

    # 大きい塔0から小さい塔
    sc = 0
    edges = list(range(N))
    for m in range(M):
        if (bit>>m)&1 == 0: continue
        sc += 1
        cost = dist(X[0], Y[0], x[m], y[m])
        if C[0] != c[m]: cost *= 10
        # 小さい塔の頂点番号はオフセット+Nで管理
        heapq.heappush(Q, (cost, m+N))
        edges.append(m+N)

    cost_sum = 0
    marked_count = 1
    marked_big = [False]*N
    marked_sml = [False]*M
    marked_big[0] = True

    while marked_count < N+sc:
        cost, cur = heapq.heappop(Q)

        if cur < N:
            if marked_big[cur]: continue
            marked_big[cur] = True
        else:
            if marked_sml[cur-N]: continue
            marked_sml[cur-N] = True

        marked_count += 1
        cost_sum += cost

        if cur < N:
            ix, iy, ic = X[cur], Y[cur], C[cur]
        else:
            ix, iy, ic = x[cur-N], y[cur-N], c[cur-N]
        for to in edges:
            if to < N:
                if marked_big[to]: continue
                jx, jy, jc = X[to], Y[to], C[to]
            else:
                if marked_sml[to-N]: continue
                jx, jy, jc = x[to-N], y[to-N], c[to-N]

            ncost = dist(ix, iy, jx, jy)
            if ic != jc: ncost *= 10
            heapq.heappush(Q, (ncost, to))

    ans = min(ans, cost_sum)

print(ans)


import sys
from collections import deque

N, M = map(int, sys.stdin.readline().split())
r, c, d = map(int, sys.stdin.readline().split())
# d => 0북 1동 2남 3서
dy = [-1, 0, 1, 0]
dx = [0, 1, 0, -1]
matrix = [list(map(int, sys.stdin.readline().split())) for _ in range(N)]

# 방향 전환 함수
def change(d):
    if d == 0:
        return 3
    elif d == 1:
        return 0
    elif d == 2:
        return 1
    elif d == 3:
        return 2

# 후진
def back(d):
    if d == 0:
        return 2
    elif d == 1:
        return 3
    elif d == 2:
        return 0
    elif d == 3:
        return 1

def bfs(r, c, d):
    res = 0
    q = deque()
    q.append((r, c, d))
    while q:
        r, c, d = q.popleft()
        # 1
        if matrix[r][c] == 0:
            res += 1
            matrix[r][c] = 2  # 청소 완료
        _d = d
        for i in range(4):
            _d = change(_d)
            _r, _c = r + dy[_d], c + dx[_d]
            if 0 <= _r < N and 0 <= _c < M and matrix[_r][_c] == 0:
                q.append((_r, _c, _d))
                break
            elif i == 3:
                _r, _c = r + dy[back(d)], c + dx[back(d)]
                q.append((_r, _c, d))
                if matrix[_r][_c] == 1:
                    return res

print(bfs(r, c, d))


def solution(citations):
#   정렬을 해보자
#     0,1,3,3,3,5,6     7편중 h번 이상 인용된 논문
#    0번 이상 인용된 논문 7개 나머지는 0번 이하 맞음
#    1번이상 인용된 논문 6개  나머지는 1번 이하 맞음
#    3번 이상 인용된 논문 5 (3번이상)  나머지는 3번 이하
#    그럼 return 3이다!
#    4번 이상 인용된 논문 2 (4번 이상X)  (나머지 4번 이하 X)
#    5번 이상 인용된 논문 2
#    6번 이상 인용된 논문 1
#     0,1,3,3,3,3,5,6
#  i.....len(citations)-1
#  i .... 4
#  i부터 끝까지
#  0부터 i까지 개수 = h번 이하
#  0 1 .... i
    citations.sort()
#     0133356이라 치면
#     0 7 , 1 6 , 3 5, 3 4 , 3 3 , 5 2 , 6 1 이렇게 되는데
#     3 3 일 때 리턴해주면 된다.
    for i in range(len(citations)):
        if citations[i]  >= len(citations)-i :
            return len(citations)-i
        if citations[-1] == 0 :
            return 0


# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reorderList(self, head: Optional[ListNode]) -> None:
        """
        Do not return anything, modify head in-place instead.
        """
        array = []
        currentlist = head
        while currentlist is not None:
            array.append(currentlist)
            currentlist = currentlist.next
        i = 0
        halflenth = len(array)//2
        while i < halflenth:
            temp = array[i].next
            array[i].next = array[~i]
            array[~i].next = temp
            i += 1
        array[halflenth].next = None
        return head


import pyrealsense2 as rs

class RealsenseCam(object):

    def __init__(self):
        self.running = True
        self.pipe = rs.pipeline()
        cfg = rs.config()
        cfg.enable_stream(rs.stream.pose)
        self.pipe.start(cfg)
        self.frames = None

    def update(self):
        while self.running:
            self.frames = self.pipe.wait_for_frames()

    def run_threaded(self):
        if self.frames is not None:
            pose = self.frames.get_pose_frame()
            data = pose.get_pose_data()
            return data.translation

    def shutdown(self):
        self.running = False
        self.pipe.stop()


import json
import os
import re
import sys
from urllib.parse import urlsplit

import requests
from django.conf import settings
from django.http import HttpResponse
from django.shortcuts import redirect, render
from opencivicdata.core.models import Division, Membership

from reports.models import Report
from reports.utils import get_offices, get_personal_url, module_name_to_metadata, remove_suffix_re, scrape_configuration, scrape_people

def home(request):
    sys.path.append(os.path.abspath('scrapers'))

    data = json.loads(requests.get('https://represent.opennorth.ca/representative-sets/?limit=0', verify=settings.SSL_VERIFY).text)

    names = {}
    for obj in data['objects']:
        # The `ca` scraper has "Parliament of Canada" as the root organization.
        if obj['name'] == 'House of Commons':
            names['Parliament of Canada'] = obj['data_url']
        else:
            names[obj['name']] = obj['data_url']

    reports = Report.objects.order_by('module').all()
    for report in reports:
        try:
            name = module_name_to_metadata(report.module)['name']
            if not report.exception:
                if name in names:
                    if names[name].startswith('https://scrapers.herokuapp.com/represent/'):
                        report.icon = 'noop'
                    else:
                        report.icon = 'replace'
                else:
                    report.icon = 'add'
        except ImportError:
            report.delete()  # delete reports for old modules

    return render(request, 'index.html', {
        'exceptions': Report.objects.exclude(exception='').count(),
        'reports': reports,
    })

def warnings(request):
    return render(request, 'warnings.html', {
        'reports': Report.objects.order_by('module').all(),
    })

def report(request, module_name):
    return HttpResponse(json.dumps(Report.objects.get(module=module_name).report), content_type='application/json')

def run(request, module_name):
    sys.path.append(os.path.abspath('scrapers'))
    parser, subcommand, handler = scrape_configuration()
    scrape_people(module_name, parser, subcommand, handler)
    return redirect('home')

def represent(request, module_name):
    sys.path.append(os.path.abspath('scrapers'))

    metadata = module_name_to_metadata(module_name)

    representatives = []

    # Exclude party memberships.
    queryset = Membership.objects.filter(organization__jurisdiction_id=metadata['jurisdiction_id'])

    if module_name.endswith('_candidates'):
        # Include only candidates.
        queryset.filter(role='candidate')
    else:
        # Exclude candidates and party memberships.
        queryset.exclude(role__in=('member', 'candidate'))

    for membership in queryset.prefetch_related('contact_details', 'person', 'person__links', 'person__sources', 'post'):
        person = membership.person

        # Not sure why this is necessary.
        if not isinstance(membership.extras, dict):
            membership.extras = json.loads(membership.extras)
        if not isinstance(person.extras, dict):
            person.extras = json.loads(person.extras)

        try:
            party_name = Membership.objects.select_related('organization').get(organization__classification='party', role='member', person=person).organization.name
        except Membership.DoesNotExist:
            party_name = None

        if person.gender == 'male':
            gender = 'M'
        elif person.gender == 'female':
            gender = 'F'
        else:
            gender = None

        # Candidates only.
        incumbent = person.extras.pop('incumbent', None)

        # @see https://represent.opennorth.ca/api/#fields
        representative = {
            'name': person.name,
            'elected_office': membership.role,
            'party_name': party_name,
            'email': next((contact_detail.value for contact_detail in membership.contact_details.all() if contact_detail.type == 'email'), None),
            'photo_url': person.image or None,
            'personal_url': get_personal_url(person),
            'gender': gender,
            'offices': json.dumps(get_offices(membership)),
            'extra': json.dumps(get_extra(person)),
        }

        sources = list(person.sources.all())

        # The first URL ought to be the most generic source.
        representative['source_url'] = sources[0].url

        if len(sources) > 1:
            # The last URL ought to be the most specific source.
            representative['url'] = sources[-1].url

        if incumbent:
            representative['incumbent'] = True

        match = re.search(r'^(\S+) (Ward \d+)$', membership.post.label)

        # If the person is part of Peel Regional Council.
        if match:
            parent = Division.objects.get(subtype1='csd', subtype2='', name=match.group(1))
            division = Division.objects.get(subtype1='csd', subid1=parent.subid1, name=match.group(2))
            boundary_set_slug = '{}-wards'.format(parent.name.lower())
            representative['district_name'] = membership.post.label
            representative['boundary_url'] = '/boundaries/{}/ward-{}/'.format(boundary_set_slug, division.subid2)
            representatives.append(representative)

        # If the person is associated to multiple boundaries.
        elif re.search(r'^Wards\b', membership.post.label):
            for district_id in re.findall(r'\d+', membership.post.label):
                representative = representative.copy()
                representative['district_id'] = district_id
                representative['district_name'] = 'Ward {}'.format(district_id)
                representatives.append(representative)

        else:
            division_id = metadata['division_id']

            if re.search('^ocd-division/country:ca/csd:(\d{7})\Z', division_id):
                geographic_code = division_id[-7:]
            elif re.search('^ocd-division/country:ca/cd:(\d{4})\Z', division_id):
                geographic_code = division_id[-4:]
            else:
                geographic_code = None

            post_label = remove_suffix_re.sub('', membership.post.label)

            # If the post label is numeric.
            if re.search(r'^\d+\Z', post_label):
                representative['district_id'] = post_label

            # If the person has a boundary URL.
            elif 'boundary_url' in membership.extras:
                representative['district_name'] = post_label
                representative['boundary_url'] = membership.extras['boundary_url']

            # If the post label is a Census geographic name.
            elif post_label == metadata['division_name'] and geographic_code:
                representative['district_name'] = post_label
                if len(geographic_code) == 7:
                    representative['boundary_url'] = '/boundaries/census-subdivisions/{}/'.format(geographic_code)
                elif len(geographic_code) == 4:
                    representative['boundary_url'] = '/boundaries/census-divisions/{}/'.format(geographic_code)

            else:
                representative['district_name'] = post_label
                district_id = re.search(r'^(?:District|Division|Ward) (\d+)\Z', post_label)
                if district_id:
                    representative['district_id'] = district_id.group(1)

            representatives.append(representative)

    return HttpResponse(json.dumps(representatives), content_type='application/json')

def get_extra(record):
    extra = record.extras
    for link in record.links.all():
        domain = '.'.join(urlsplit(link.url).netloc.split('.')[-2:])
        if domain in ('facebook.com', 'fb.com'):
            extra['facebook'] = link.url
        elif domain == 'instagram.com':
            extra['instagram'] = link.url
        elif domain == 'linkedin.com':
            extra['linkedin'] = link.url
        elif domain == 'twitter.com':
            extra['twitter'] = link.url
        elif domain == 'youtube.com':
            extra['youtube'] = link.url
    return extra


#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
    Train a model using my PriceEstimatorTrainer class
    then evaluates on valid or test. Return results by route.

    Args:
        - model : {'rf', 'log_reg', 'knn', 'svm', 'xgb'}, default='rf'
                Model to train the data with (It must be
                in the model selector dictionary)

        - n_iter : int, default=0
                Number of iterations for random search params

        - -m, comment : str
                Explanatory notes about current experiment, doesn't affect
                training process

        - testset : {'valid', 'test'}, default='valid'
                Whether to use the validation set or the test set
                for evaluate the trained model.

        - -o, output : str
                Name to store the model. If no passed, model will not be
                stored.

    @author: Adrián Cervero - May 2021
    @github: https://github.com/adriancervero/flight-prices-prediction
"""

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import argparse
import pickle
import logging
import os, sys

# My imports
import config as cfg
import model_selector
from PriceEstimatorTrainer import PriceEstimatorTrainer

def generate_model(param_grid):
    """ Returns given model with random params from param_grid parameter """
    n_estimators = np.random.choice(param_grid['n_estimators'])
    max_depth = np.random.choice(param_grid['max_depth'])
    criterion = np.random.choice(param_grid['criterion'])
    max_features = np.random.choice(param_grid['max_features'])
    min_samples_split = np.random.choice(param_grid['min_samples_split'])
    min_samples_leaf = np.random.choice(param_grid['min_samples_leaf'])

    model = RandomForestClassifier(n_estimators=n_estimators,
                                    max_depth=max_depth,
                                    criterion=criterion,
                                    max_features=max_features,
                                    min_samples_split=min_samples_split,
                                    random_state=cfg.RANDOM_STATE)
    return model

def run(model, n_iter, comment, testset, output):
    """ Performs training process """

    print("\n----- 04 - Training Model -----\n\n")

    # load training data
    os.chdir(sys.path[0])
    df = pd.read_csv(cfg.TRAIN_PATH)

    # Init model and get params for hypertuning
    m = model_selector.models[model]
    if model == 'rf':
        param_grid = model_selector.param_grid[model]

    #threshold_values = [0.4, 0.42, 0.44,0.46, 0.48, 0.5, 0.52, 0.54, 0.56, 0.58, 0.6]
    #for threshold in threshold_values:

    if n_iter == 0: # no hypertunning
        trainer = PriceEstimatorTrainer(model=m, pred_threshold=.5, n=10000)

        # fit model
        trainer.fit()

        # print results on validation
        acc, mean_savings = trainer.evaluate(on=testset, plot=True)

        logging.info(f"Precision: {acc}, Mean Savings %: {mean_savings}, Notes:{comment}, Model:{m}")
        logging.info("---------------------------------------------------------------------------------------")

        if output != '':
            output_path = cfg.MODEL_OUTPUT + output
            pickle.dump(trainer.model, open(output_path, 'wb'))
            print('\n\nmodel stored: ', output_path)

    else: # hypertunning

        for _ in range(0, n_iter):
            m = generate_model(param_grid)
            trainer = PriceEstimatorTrainer(model=m)

            # fit model
            trainer.fit()

            # print results on validation
            acc, mean_savings = trainer.evaluate(on=testset)

            logging.info(f"Precision: {acc}, Mean Savings %: {mean_savings}, Notes:{comment}, Model:{m}")
            logging.info("---------------------------------------------------------------------------------------")

if __name__ == '__main__':
    # ArgumentParser
    parser = argparse.ArgumentParser()
    parser.add_argument('--model', type=str, default='rf') # model to use
    parser.add_argument('-t', type=int, default=0) # random search hypertuning iterations
    parser.add_argument('-m', type=str, default='') # notes
    parser.add_argument('--on', type=str, default='valid') # evaluate on validation or test
    parser.add_argument('-o', type=str, default='') # model save name

    # read arguments from command line
    args = parser.parse_args()
    # logger
    logging.basicConfig(level=logging.DEBUG, filename="training_logs", filemode="a+",
                        format="%(asctime)-15s %(levelname)-8s %(message)s")

    run(
        model=args.model,
        n_iter = args.t,
        comment=args.m,
        testset=args.on,
        output=args.o,
    )


import socket

host=socket.gethostname()
port=(8000)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

def connect():
    s.bind((host,port))
    s.listen(2)
    print("Server listening")
    conn,addr=s.accept()
    print("Connected")
    send(conn)

def send(conn):
    while 1:
        data=input("Input data to send: ")
        encoded_data=data.encode('UTF-8')
        conn.send(encoded_data)

connect()

Prototypes_experiments/ChatBot_v2_A2_DELIVERABLE/Bot and Training Script/server_prototype.py


# Maximum Possible Pairings
# similar to http://www.geeksforgeeks.org/maximum-bipartite-matching/

from matching import Person, adjacency

# g => graph
# u => vertex to match
# s => seen
# m => result matchings
# n => number of vertices
def bpm(g, u, s, m, n):
    s[u] = True

    for v in range(n):

        # if there exists a matching and it is not yet seen
        if g[u][v] and not s[v]:
            s[v] = True

            # if the match is not yet paired or
            # there is another matching for v's pair
            if m[v] == -1 or bpm(g, m[v], s, m, n):
                m[v] = u
                m[u] = v

                return True

    return False

# graph => adjacency matrix
# n => number of vertices
def maxBPM(graph, n):
    match = [-1 for _ in range(n)]
    result = 0

    for cur in range(n):
        seen = [False for _ in range(n)]

        if match[cur] == -1 and bpm(graph, cur, seen, match, n):
            result += 1

    return match

# t => total list
# m => determined matches
def print_matches(t, m):
    s = [False for _ in range(len(m))]

    for i in range(len(m)):
        if m[i] != -1 and not s[i] and not s[m[i]]:
            s[i] = True
            s[m[i]] = True
            print(str(t[i]) + " can match with " + str(t[m[i]]))

    for i in range(len(m)):
        if not s[i]:
            print(str(t[i]) + " has no matches")

if __name__ == "__main__":
    total = [Person(*input().split()) for _ in range(int(input()))]
    pos = adjacency(total, len(total))

    matches = maxBPM(pos, len(total))

    print_matches(total, matches)


from PIL import Image

# Abrir imagen
bg_img = Image.open('mañana.png')

# Crear nueva imagen con canal alpha
bg_with_alpha = Image.new('RGBA', bg_img.size)

# Pegar imagen original
bg_with_alpha.paste(bg_img)

# Aplicar canal alpha
alpha = Image.new('L', bg_img.size, color=128)
bg_with_alpha.putalpha(alpha)

# Guardar imagen editada
bg_with_alpha.save('mañana.png')