import os
import subprocess
import sys
import urllib.request
import hashlib
import socket
import shutil
import errno

def mkdir(indir, log=None):
    if os.path.isdir(indir) == False:
        os.mkdir(indir)
    # else:
    #     msg = "cannot make dir:"+indir+" dir exists...skipping....\n"
    #     sys.stderr.write(msg)
    #     writelog(log, msg)

def get_abs_path(in_file, log=None):
    if os.path.isfile(in_file):
        return os.path.abspath(in_file)
    else:
        msg = " ".join(["Cannot find file:",in_file,"exiting....\n"])
        sys.stderr.write(msg)
        writelog(log, msg)
        sys.exit(1)

def get_base_name(path, fastq=False):
    no_path = os.path.basename(path)
    no_ext = no_path.split(".")[0]

    if fastq == True:
        no_ext = no_ext.replace("_1","")
        no_ext = no_ext.replace("_2","")

    return no_ext

def run_command_stdout(cmd_list, out_file, log=None):
    msg = ""
    if log is None:
        try:
            # print(" ".join(cmd_list)+" > "+out_file)
            out = open(out_file,"w")
            subprocess.check_call(cmd_list, stdout=out)
            out.close()
        except subprocess.CalledProcessError as e:
            if e.output is not None:
                msg = str(e.output)+"\n"
            if e.stderr is not None:
                msg += str(e.stderr)+"\n"
            cmd_string = " ".join(cmd_list)
            msg += msg + cmd_string + "\n"
            sys.stderr.write(msg)
            sys.exit(1)

    else:
        try:
            out_log = open(log,"a")
            out_log.write(" ".join(cmd_list)+" > "+out_file+"\n")
            out = open(out_file,"w")
            subprocess.check_call(cmd_list, stdout=out, stderr=out_log)
            out.close()
            out_log.close()

        except subprocess.CalledProcessError as e:
            if e.output is not None:
                msg = str(e.output)+"\n"
            if e.stderr is not None:
                msg += str(e.stderr)+"\n"
            cmd_string = " ".join(cmd_list)
            msg += msg + cmd_string + "\n"
            writelog(log, msg)
            sys.stderr.write(msg)
            sys.exit(1)

def run_command(cmd_list, log=None):
    msg = ""
    if log is None:
        try:
            # print(" ".join(cmd_list))
            subprocess.check_call(cmd_list)
        except subprocess.CalledProcessError as e:
            if e.output is not None:
                msg = str(e.output)+"\n"
            if e.stderr is not None:
                msg += str(e.stderr)+"\n"
            cmd_string = " ".join(cmd_list)
            msg += msg + cmd_string + "\n"
            sys.stderr.write(msg)
            sys.exit(1)

    else:
        try:
            out = open(log,"a")
            out.write(" ".join(cmd_list)+"\n")
            subprocess.check_call(cmd_list, stdout=out, stderr=out)
            out.close()

        except subprocess.CalledProcessError as e:
            if e.output is not None:
                msg = str(e.output)+"\n"
            if e.stderr is not None:
                msg += str(e.stderr)+"\n"
            cmd_string = " ".join(cmd_list)
            msg += msg + cmd_string + "\n"
            writelog(log, msg)
            sys.stderr.write(msg)
            sys.exit(1)

def writelog(log, msg):
    if log is not None:
        with open(log, "a") as out:
            out.write(msg)

def download(url, out_file, md5=None, timeout=15, _attempt=1, max_attempts=1):
    if _attempt > max_attempts:
        return False
    socket.setdefaulttimeout(timeout)
    print("downloading ", url, "to", out_file)
    try:
        urllib.request.urlretrieve(url, out_file)

    except KeyboardInterrupt:
        sys.exit(1)

    except:
        print(sys.exc_info())
        print("download failed...")
        return download(url, out_file, md5=md5, timeout=timeout, _attempt=_attempt+1, max_attempts=max_attempts)

    print("download complete")

    if md5 == None:
        return True
    else:
        print("checking md5 of ", out_file)
        with open(out_file,"rb") as out:
            data = out.read()

            this_md5 = hashlib.md5(data).hexdigest()

            if this_md5 != md5:
                print("MD5 of", out_file, " : ", this_md5, "does not match currect MD5 hash: ", md5)
                return download(url, out_file, md5=md5, timeout=timeout, _attempt=_attempt+1, max_attempts=max_attempts)
            else:
                print("MD5 hash of ", out_file, "matches expected")
                return True

def remove(infile):
    if os.path.exists(infile):
        try:
            if os.path.isfile(infile):
                os.remove(infile)
            elif os.path.isdir(infile):
                shutil.rmtree(infile)
        except OSError as e:
            print("Error: %s : %s" % (infile, e.strerror))

def get_median_insert_size(infile):
    median_insert_size = 0
    with open(infile,"r") as inf:
        for line in inf:
            insert = line.split("=")[1]
            insert = insert.replace("\n","")
            median_insert_size = int(float(insert))

    return median_insert_size

def check_file_exists(infile):
    if os.path.exists(infile):
        return True
    else:
        raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), infile)

def replace_special_chars(string, encode="_"):
    special_chars = [";","&","(",")","|","*","?","[","]","~","{","}","<","!","^",'"',"'","\\","$","/","+","-"]
    for char in special_chars:
        string = string.replace(char,encode)

    return string

def replace_special_chars_fasta(fasta, new_fasta):
    with open(fasta,"r") as fa:
        with open(new_fasta, "w") as out:
            for line in fa:
                if ">" in line:
                    line = replace_special_chars(line)

                out.write(line)

    return new_fasta

def replace_special_chars_taxonomy(infile, outfile):
    with open(infile,"r") as i:
        with open(outfile, "w") as o:
            for line in i:
                line = replace_special_chars(line)
                o.write(line)

    return outfile

def estimate_read_length(fq, reads=10000):
    lengths = []
    with open(fq,"r") as f:
        for x, line in enumerate(f):
            if x%4 == 1:
                lengths.append(len(line.replace('\n',"")))

            if x >= reads:
                break

    length = sum(lengths)//len(lengths)

    return length

def log(step, msg, log=None):
    step = step.upper()
    max_step = 15
    if len(step) > max_step:
        step = step[:max_step]

    step_buffer = (max_step - len(step)) + 2
    step += " "*step_buffer

    max_msg = 103

    lines = msg
    # lines = []
    # x = 0
    # while(x + max_msg < len(msg)):
    #     lines.append(msg[x:x+max_msg])
    #     x += max_msg

    # remainder = (len(msg)-x)
    # lines.append(msg[x:x+remainder])

    # lines = ("\n"+(" "*(max_step+2))).join(lines)
    lines = step + lines

    if log is not None:
        lines += " &> " + log

    print(lines)


#!/bin/python3
"""
In this challenge, you will be given a string. You must remove characters until the string is made up of any two alternating characters. When you choose a character to remove, all instances of that character must be removed. Your goal is to create the longest string possible that contains just two alternating letters.

As an example, consider the string abaacdabd. If you delete the character a, you will be left with the string bcdbd. Now, removing the character c leaves you with a valid string bdbd having a length of 4. Removing either b or d at any point would not result in a valid string.

Given a string , convert it to the longest possible string  made up only of alternating characters. Print the length of string  on a new line. If no string  can be formed, print  instead.

"""
import math
import os
import random
import re
import sys
from itertools import combinations
# Complete the alternate function below.
def alternate(s):
    results=[]
    st=list(set(s))
    if len(st)<2:
        return 0
    else:
        combos=list(combinations(st,len(st)-2))
        print("Combos")
        print(combos)
        for i in combos:
            vals=[]
            temp=s
            for x in i:
                temp=temp.replace(x,"")
            print(temp)
            for y in range(len(temp)-1):
                if temp[y]==temp[y+1]:
                    vals.append(False)
                else:
                    vals.append(True)
            if all(vals)==True:
                results.append(len(temp))
            else:
                results.append(0)

    return max(results)

if __name__ == '__main__':

    l = int(input().strip())

    s = input()

    result = alternate(s)
    print("Result is ")
    print(result)


a,b=map(int, input().split())

picture=[]
for i in range(a):
    s1=input()
    picture.append(s1)

picture_2=[]
for i in range(a):
    s2=input()
    picture_2.append(s2)

flag=True
for i in range(a):
    for j in range(b):
        if picture[i][j]!=picture_2[i][2*j]:
            flag=False
            break
        if picture[i][j]!=picture_2[i][2*j+1]:
            flag=False
            break
if flag==True:
    print('Eyfa')
else:
    print('Not Eyfa')


def solution(s):
    answer = 1

    if len(s)%2==1: return 0
    if len(s)==2:
        if s[0] == s[1]: return 1

    arr = list(s)
    stack = [arr.pop(0)]

    for a in arr:
        if len(stack)>0 and stack[-1]==a:
            stack.pop()
        else:
            stack.append(a)
    if len(stack):
        answer=0
    return answer

프로그래머스/lv2/12973. 짝지어 제거하기/짝지어 제거하기.py


from builtins import str
from builtins import object

import sys
import time

from copy import deepcopy

from collections import OrderedDict
from unittest2 import TestCase, TestResult

from bambou.config import BambouConfig
from bambou.exceptions import BambouHTTPError

from monolithe.lib import Printer
from .helper import TestHelper

class CourgetteTestResult(TestResult):
    """ A TestResult
    """

    def __init__(self):
        """ Initialized a new result
        """
        TestResult.__init__(self)
        self.tests = OrderedDict()

    def getDescription(self, test):
        """ Get test description
        """
        return str(test).split(" ")[0]  # Removing (package.name)

    def addSuccess(self, test):
        """ Add success to the result
        """
        TestResult.addSuccess(self, test)
        self.tests[self.getDescription(test)] = {"status": "SUCCESS"}

        Printer.success("OK")

    def addError(self, test, err, connection=None):
        """ Add error to the result
        """
        TestResult.addError(self, test, err)
        self.tests[self.getDescription(test)] = {"status": "ERROR", "stacktrace": err, "connection": connection}

        Printer.warn("ERROR")
        Printer.warn(err[1])
        TestHelper.trace(connection)

    def addFailure(self, test, err, connection):
        """ Add failure to the result
        """
        TestResult.addFailure(self, test, err)
        self.tests[self.getDescription(test)] = {"status": "FAILURE", "stacktrace": err, "connection": connection}

        Printer.warn("Failure")
        Printer.warn(err[1])
        TestHelper.trace(connection)

    def __repr__(self):
        """ Representation
        """
        return "<%s testsRun=%i errors=%i failures=%i>" % \
               (str(self.__class__), self.testsRun, len(self.errors), len(self.failures))

class CourgetteTestRunner(object):
    """
    """

    def __init__(self):
        """ Initialized
        """
        pass

    def _makeResult(self):
        """ Return a TestResult implementation
        """
        return CourgetteTestResult()

    def run(self, test):
        """ Run the given test case or test suite.
        """
        result = self._makeResult()
        startTime = time.time()
        test(result)
        stopTime = time.time()
        timeTaken = stopTime - startTime

        run = result.testsRun
        Printer.log("Ran %d test%s in %.3fs" % (run, run != 1 and "s" or "", timeTaken))

        if not result.wasSuccessful():
            Printer.warn("FAILED (failures=%i, errors=%i)" % (len(result.failures), len(result.errors)))
        else:
            Printer.success("OK")
        return result

class CourgetteTestCase(TestCase):

    _last_connection = None
    helper= None
    parent = None
    sdkobject = None
    user = None

    @property
    def last_connection(self):
        """ Returns last connection """
        return self._last_connection

    @last_connection.setter
    def last_connection(self, connection):
        """ set last_connection """
        self._last_connection = deepcopy(connection)

    # Very Dark Side of unittest... Maybe we should upgrade to unittest2 to do that.
    # Will see that later !
    # CS 05-13-2015
    def run(self, result=None):
        """
        """
        if result is None:
            result = self.defaultTestResult()

        result.startTest(self)
        testMethod = getattr(self, self._testMethodName)

        try:
            try:
                self.setUp()
                BambouConfig.set_should_raise_bambou_http_error(False)
            except KeyboardInterrupt:
                raise
            except BambouHTTPError as error:
                result.addError(self, [None, "Test setUp has failed", None], error.connection)
                return
            except:
                result.addError(self, sys.exc_info())
                return
            ok = False
            try:
                Printer.log("%s..." % self._testMethodName)

                testMethod()
                BambouConfig.set_should_raise_bambou_http_error(True)
                ok = True
            except self.failureException:
                result.addFailure(self, sys.exc_info(), self.last_connection)
            except KeyboardInterrupt:
                raise
            except:
                result.addError(self, sys.exc_info(), self.last_connection)
            try:
                self.tearDown()
            except KeyboardInterrupt:
                raise
            except BambouHTTPError as error:
                result.addError(self, [None, "Test tearDown has failed", None], error.connection)
                return
            except:
                result.addError(self, sys.exc_info())
                ok = False
            if ok:
                result.addSuccess(self)
        finally:
            result.stopTest(self)

    def assertErrorEqual(self, errors, title, description, rest_name="", index=0):
        """ Check if errors received matches
        """
        self.assertEquals(errors[index]["descriptions"][0]["title"], title, "Expected error title \"%s\" != \"%s\"" % (title, errors[index]["descriptions"][0]["title"]))
        self.assertEquals(errors[index]["descriptions"][0]["description"], description, "Expected error description \"%s\" != \"%s\"" % (description, errors[index]["descriptions"][0]["description"]))
        self.assertEquals(errors[index]["property"], rest_name, "Expected error property \"%s\" != \"%s\"" % (rest_name, errors[index]["property"]))

    def assertConnectionStatus(self, connection, expected_status):
        """ Check if the connection has expected status
        """
        message = self._connection_failure_message(connection, expected_status)
        self.assertEquals(connection.response.status_code, expected_status, message)

    # Messages

    def _connection_failure_message(cls, connection, expected_status):
        """ Returns a message that explains the connection status failure
        """

        return "Expected status code %s != to Received status code %s\n" % (expected_status, connection.response.status_code)


import opc
import time

total_strips = 6
leds_per_strip = 60
client =opc.Client('localhost:7890')

colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 0, 255), (0, 255, 255),
          (255, 255, 0)]

while True:
    strips = []
    for i in range(total_strips):
        strips = [[(0, 0, 0) for led in range(leds_per_strip)]
                  for strip in range(total_strips)]
        strips[i] = [colors[i] for pixel in range(leds_per_strip)]
        pixels = [j for sub in strips for j in sub]
        client.put_pixels(pixels, channel=0)
        time.sleep(0.3)


import json
from collections import Counter
import numpy as np

from sentence_retrieval.sent_tfidf import OnlineTfidfDocRanker
from utils import fever_db, check_sentences, text_clean
import config
import drqa_yixin.tokenizers
from drqa_yixin.tokenizers import CoreNLPTokenizer
from tqdm import tqdm
from utils import c_scorer
import math
import utils
from collections import namedtuple
from pathlib import Path

from utils import common

path_stanford_corenlp_full_2017_06_09 = str(config.PRO_ROOT / 'dep_packages/stanford-corenlp-full-2017-06-09/*')
print(path_stanford_corenlp_full_2017_06_09)

drqa_yixin.tokenizers.set_default('corenlp_classpath', path_stanford_corenlp_full_2017_06_09)
tok = CoreNLPTokenizer(annotators=['pos', 'lemma'])

def easy_tokenize(text):
    return tok.tokenize(text_clean.normalize(text)).words()

def load_data(file):
    d_list = []
    with open(file, encoding='utf-8', mode='r') as in_f:
        for line in in_f:
            item = json.loads(line.strip())
            d_list.append(item)

    return d_list

def utest_for_ground_truth(d_list):
    nei_c = 0
    support_c = 0
    refute_c = 0
    for item in tqdm(d_list):
        e_list = check_sentences.check_and_clean_evidence(item)
        evidence_sent_id = []
        gt_evidence = []
        if item['verifiable'] == "VERIFIABLE":
            for doc_id, ln in list(e_list)[0]:
                evidence_sent_id.append(doc_id + c_scorer.SENT_LINE + str(ln))
                gt_evidence.append([doc_id, ln])
        elif item['verifiable'] == "NOT VERIFIABLE":
            evidence_sent_id = []

        item["predicted_sentids"] = evidence_sent_id

        # item['predicted_evidence'] = []
        item['predicted_evidence'] = gt_evidence
        item['predicted_label'] = item["label"]

        if item["label"] == 'NOT ENOUGH INFO':
            nei_c += 1
        elif item["label"] == 'SUPPORTS':
            support_c += 1
        elif item["label"] == 'REFUTES':
            refute_c += 1

    print(support_c, refute_c, nei_c)
        # if len(evidence_sent_id) >= 2:
        #     print(evidence_sent_id)

def utest_score_ground_truth():
    d_list = load_data(config.FEVER_DEV_JSONL)
    utest_for_ground_truth(d_list)

    eval_mode = {'check_sent_id_correct': True, 'standard': True}
    print(c_scorer.fever_score(d_list, d_list, mode=eval_mode, verbose=False))

def utest_check_sentence_lines():
    sent_number_coutner = Counter()
    number_list = []
    db_cursor = fever_db.get_cursor()
    # d_list = load_data("/Users/Eason/RA/FunEver/results/doc_retri/2018_07_04_21:56:49_r/dev.jsonl")
    d_list = load_data("/Users/Eason/RA/FunEver/results/doc_retri/2018_07_04_21:56:49_r/train.jsonl")
    for item in tqdm(d_list):
        p_docids = item['predicted_docids']
        current_sent_list = []
        for doc_id in p_docids:
            r_list = fever_db.get_all_sent_by_doc_id(db_cursor, doc_id)
            current_sent_list.extend(r_list)

        sent_number_coutner.update([len(current_sent_list)])
        number_list.append(len(current_sent_list))
        # print(current_sent_list)

    print(len(number_list))
    print('Mean:', np.mean(number_list))
    print('Max:', np.max(number_list))
    print('Min:', np.min(number_list))
    print('Std:', np.std(number_list))
    print(sent_number_coutner)

        # print(p_docids)

def save_intermidiate_results(d_list, out_filename: Path, last_loaded_path=None):
    if not out_filename.parent.exists():
        out_filename.parent.mkdir(exist_ok=False)

    with open(out_filename, encoding='utf-8', mode='w') as out_f:
        for item in d_list:
            out_f.write(json.dumps(item) + '\n')

    if last_loaded_path is not None:
        with open(out_filename.parent / "log_info.txt", encoding='utf-8', mode='a') as out_f:
            out_f.write(last_loaded_path)

def if_idf_select_sentence():
    db_cursor = fever_db.get_cursor()
    loaded_path = "/Users/Eason/RA/FunEver/results/doc_retri/2018_07_04_21:56:49_r/dev.jsonl"
    d_list = load_data(loaded_path)
    # d_list = load_data("/Users/Eason/RA/FunEver/results/doc_retri/2018_07_04_21:56:49_r/train.jsonl")

    for item in tqdm(d_list):
        # print()
        p_docids = item['predicted_docids']
        cleaned_claim = ' '.join(easy_tokenize(item['claim']))
        # print(cleaned_claim)

        current_sent_list = []
        current_id_list = []
        for doc_id in p_docids:
            r_list, id_list = fever_db.get_all_sent_by_doc_id(db_cursor, doc_id)
            current_sent_list.extend(r_list)
            current_id_list.extend(id_list)

        Args = namedtuple('Args', 'ngram hash_size num_workers')

        args = Args(2, int(8192), 4)

        ranker = OnlineTfidfDocRanker(args, args.hash_size, args.ngram,
                                      current_sent_list)

        selected_index, selected_score = ranker.closest_docs(cleaned_claim, k=5)

        selected_sent_id = []
        for ind in selected_index:
            curent_selected = current_id_list[ind]
            doc_id, ln = curent_selected.split('(-.-)')
            # ln = int(ln)
            # selected_sent_id.append([doc_id, ln])
            selected_sent_id.append(doc_id + c_scorer.SENT_LINE + ln)

        item['predicted_sentids'] = selected_sent_id

    eval_mode = {'check_sent_id_correct': True, 'standard': False}
    print(c_scorer.fever_score(d_list, d_list, mode=eval_mode, verbose=False))

    out_fname = config.RESULT_PATH / "sent_retri" / f"{utils.get_current_time_str()}_r" / "dev.jsonl"
    save_intermidiate_results(d_list, out_filename=out_fname, last_loaded_path=loaded_path)

def script(in_path, out_path):
    print(in_path)
    print(out_path)
    db_cursor = fever_db.get_cursor()

    if isinstance(in_path, str):
        loaded_path = in_path
        d_list = load_data(loaded_path)
    elif isinstance(in_path, list):
        d_list = in_path
    else:
        print("Error input format")
        d_list = None
        exit(-1)

    # d_list = load_data("/Users/Eason/RA/FunEver/results/doc_retri/2018_07_04_21:56:49_r/train.jsonl")
    res_list = []

    for item in tqdm(d_list):
        # print()
        p_docids = item['predicted_docids']
        # cleaned_claim = ' '.join(easy_tokenize(item['claim']))
        # print(cleaned_claim)
        cleaned_claim = ' '.join(item['claim'].split(' '))

        current_sent_list = []
        current_id_list = []
        for doc_id in p_docids:
            r_list, id_list = fever_db.get_all_sent_by_doc_id(db_cursor, doc_id)
            current_sent_list.extend(r_list)
            current_id_list.extend(id_list)

        Args = namedtuple('Args', 'ngram hash_size num_workers')

        args = Args(2, int(8192), 4)

        ranker = OnlineTfidfDocRanker(args, args.hash_size, args.ngram,
                                      current_sent_list)

        selected_index, selected_score = ranker.closest_docs(cleaned_claim, k=5)

        selected_sent_id = []
        for ind in selected_index:
            curent_selected = current_id_list[ind]
            doc_id, ln = curent_selected.split('(-.-)')
            # ln = int(ln)
            # selected_sent_id.append([doc_id, ln])
            selected_sent_id.append(doc_id + c_scorer.SENT_LINE + ln)

        item['predicted_sentids'] = selected_sent_id

        res_list.append(item)
        # break

    eval_mode = {'check_sent_id_correct': True, 'standard': False}
    print(c_scorer.fever_score(res_list, res_list, mode=eval_mode, verbose=False))

    # out_fname = config.RESULT_PATH / "sent_retri" / f"{utils.get_current_time_str()}_r" / "dev.jsonl"
    out_fname = Path(out_path)
    save_intermidiate_results(res_list, out_filename=out_fname, last_loaded_path=None)

def check_acc(in_path):
    d_list = load_data(in_path)
    eval_mode = {'check_sent_id_correct': True, 'standard': False}
    print(c_scorer.fever_score(d_list, d_list, mode=eval_mode, verbose=False))

if __name__ == '__main__':
    # check_acc("/Users/Eason/RA/FunEver/results/sent_retri/2018_07_05_17:17:50_r/train.jsonl")

    # utest_check_sentence_lines()
    # check_acc(in_path)
    # d_list = load_data(in_path)
    # if_idf_select_sentence()

    # script(
    #     in_path='/Users/Eason/RA/FunEver/results/doc_retri/docretri.pageview/dev.jsonl',
    #     out_path='/Users/Eason/RA/FunEver/results/sent_retri/docretri.pageview.tf_idf/dev.jsonl'
    # )

    # script(
    #     in_path=common.load_jsonl('/Users/Eason/RA/FunEver/results/doc_retri/docretri.pageview/dev.jsonl'),
    #     out_path='/Users/Eason/RA/FunEver/results/sent_retri/docretri.pageview.tf_idf/dev_0.jsonl'
    # )

    doc_num = 10

    dev_doc_file = config.SRC_ROOT / "analysis/analysis_data/sentence_selection/upstream_nn_doc_retri.jsonl"
    dev_doc_list = common.load_jsonl(dev_doc_file)

    for item in dev_doc_list:
        item['predicted_docids'] = item['predicted_docids'][:doc_num]

    script(
        in_path=dev_doc_list,
        out_path=str(config.SRC_ROOT / f"analysis/analysis_data/sentence_selection/tf_idf_sent_selection_docn({doc_num}).jsonl")
    )

    # 16783 0.8392339233923393 document = 5 upstream
    # 16752 0.8376837683768377 document = 10 upstream

    # utest_score_ground_truth()
    # d_list = load_data(config.DATA_ROOT / "fever/shared_task_dev.jsonl")
    # db_cursor = fever_db.get_cursor()
    #
    # contain_head = True
    #
    # for item in tqdm(d_list):
    #     e_list = check_sentences.check_and_clean_evidence(item)
    #     evidence_text_list = []
    #     if item['verifiable'] == "VERIFIABLE":
    #         evidence_text_list = sample_for_verifiable(db_cursor, e_list, contain_head=contain_head)
    #         print(evidence_text_list)
    #     elif item['verifiable'] == "NOT VERIFIABLE":
    #         pass

        # if len(evidence_text_list) >= 2:
        #     print("Claim:", item['claim'])
        #     for text in evidence_text_list:
                # print(text)


# -*- coding: utf-8 -*-
#May 2021
#this code matchs the input data which contains ra and dec to gaia edr3 and bailer-jones distances.***

from pandas import read_csv
import numpy as np
import os
import warnings
import pandas as pd
warnings.simplefilter('ignore', np.RankWarning)
from progress.bar import Bar

#read the data which is planned to match
#match_data=pd.read_csv('../data_outputs/'+'radec.csv',sep=',',low_memory=True)

#https://dc.zah.uni-heidelberg.de/__system__/dc_tables/list/form JOIN tables
#https://dc.zah.uni-heidelberg.de/tableinfo/gedr3dist.main
#https://gea.esac.esa.int/archive/ sol menude gaiaedr3.gaia_source sekmesini buyutunce kolon isimleri cikiyor
#https://gea.esac.esa.int/archive/documentation/GEDR3/Gaia_archive/chap_datamodel/sec_dm_main_tables/ssec_dm_gaia_source.html#gaia_source-l gaiaedr3 kolon isimleri
import pyvo as vo

def gaia_match(ra_in,dec_in,outputname):
    print('writing gaia edr3 data....')
    gaia_output=open('./data_outputs/'+outputname,'w')
    gaia_output.write('source_id,ra_gaia,dec_gaia,parallax,parallax_error,radial_velocity,radial_velocity_error,pmra,pmra_error,pmdec,pmdec_error,dist_circ,r_med_geo,r_lo_geo,r_hi_geo,phot_g_mean_mag,phot_bp_mean_mag,phot_rp_mean_mag,bp_rp,qg_geo\n')
    service = vo.dal.TAPService("http://dc.zah.uni-heidelberg.de/__system__/tap/run/tap")

    bar = Bar('Processing', max=len(ra_in))
    for ra_in,dec_in in zip(ra_in,dec_in):
        if ra_in>0:
            sql="""SELECT
                source_id, ra, dec, parallax, parallax_error,dr2_radial_velocity,dr2_radial_velocity_error,pmra,pmra_error,pmdec,pmdec_error, SQRT(POWER(ra-{ra:.5f},2)+POWER(dec-({dec:.5f}),2)) AS dist,
                r_med_geo, r_lo_geo, r_hi_geo,

                phot_g_mean_mag, phot_bp_mean_mag,phot_rp_mean_mag,
                phot_bp_mean_mag-phot_rp_mean_mag AS bp_rp,
                phot_g_mean_mag-5*LOG10(r_med_geo)+5 AS qg_geo

                FROM gedr3dist.main
                JOIN gaia.edr3lite USING (source_id)
                WHERE  1=CONTAINS(
                POINT('ICRS', {ra:.5f}, {dec:.5f}),
                CIRCLE('ICRS',ra, dec, 0.00139))
                ORDER BY dist ASC
                """.format(ra=float(ra_in),dec=float(dec_in))
        #print(sql)
        resultset = service.search(sql)
        if len(resultset)<1:
            resultset=np.repeat('nan',20)
        else:
            resultset=[*resultset[0].values()]

        gaia_output.write('{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}\n'.format(*resultset))
        bar.next()
    print('***completed***')
    bar.finish()


from flask import Flask, request, jsonify
import sys
import const
import requests
import threading
# Handle interactive loop

app = Flask(__name__)

@app.route('/chat',methods=['POST'])
def createEmp():

    data = {
    'dest':request.json['dest'],
    'name':request.json['name'],
    'msg':request.json['msg'],
    'id':request.json['id'],
    }

    if(request.json['id'] == ''):
        print(str(request.json['count']) + " - MSG: " + request.json['msg'] + " - FROM: " +  request.json['name'])
    else:
        print("TO: " + request.json['id'] +" - MSG: " + request.json['msg'] + " - FROM: " +  request.json['name'])
    return "ACK"

me = str(sys.argv[1])

def sending():
    while True:
        dest = ''
        idmsg = ''
        replyQuestion = input("Reply (y or n): \n")

        if (str(replyQuestion).lower == 'y'):
            idmsg = input("MSG ID: \n")
        dest = input("TO: \n")
        msg = input("MSG: \n")

        data = {
            'dest':dest,
            'name':me,
            'msg':msg,
            'ip':const.registry[me][0],
            'id':idmsg,
        }

        reply = requests.post(const.CHAT_SERVER_HOST+":"+str(const.CHAT_SERVER_PORT)+'/chat', json = data) #2
        if reply.text != "ACK":
            print("Error: Destination client did not receive message properly")
        else:
            pass

def receiving():
    app.run(host="0.0.0.0",port=const.registry[me][1])

if __name__ == '__main__':

    send = threading.Thread(target=sending)
    send.start()

    receive = threading.Thread(target=receiving)
    receive.start()


# Center Point cartesian
from math import floor

def abs_sum(x, y):
    return (floor(x), floor(y)), abs(x) + abs(y)

def function_call():
    position_1 = abs_sum(float(input()), float(input()))
    position_2 = abs_sum(float(input()), float(input()))

    if position_1[1] <= position_2[1]:
        return position_1[0]
    else:
        return position_2[0]

if __name__ == "__main__":
    print(function_call())


from dotenv import load_dotenv
from flask import Flask
from api.main import get_connection, create_database_pool

database_pool = None
environment_file_path = ".env"
app = Flask(__name__)

if __name__ == "__main__":
    # Load environment variables
    load_dotenv(environment_file_path)

    database_pool = create_database_pool()

    app.run(host="0.0.0.0", debug=True)


# https://leetcode.com/problems/find-all-possible-recipes-from-given-supplies/
# tags: #google, #graph, #hash_table, #topological_sort
#
# Solution: Topological sort
# For each recipe, count its dependent ingredients as in degree,
# store each ingredient dependent to a recipe in a dictionary.
# Use the supplies as the starting points of topological sort, one option is to convert supplies list to a queue
# The topological sort will be based on the supplies first given, we will decrease the in degree of recipes
# and whenever in-degree reaches zero it means we can create the recipe, so we add that recipe to the supplies_left.
# Time complexity : O(m*n) m=recipes n=ingredients, Space complexity: O(n)
from collections import defaultdict, deque

from typing import List

class Solution:
    def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:
        ingredients_to_recipe = defaultdict(list)  # graph
        in_degree = dict()

        for i, recipe in enumerate(recipes):
            n = len(ingredients[i])
            in_degree[recipe] = n
            for j in range(n):
                ingredients_to_recipe[ingredients[i][j]].append(recipe)

        # Topological sort
        allowed_recipes = []
        supplies_left = deque(supplies)
        while supplies_left:
            ing_supplied = supplies_left.popleft()

            for recipe in ingredients_to_recipe.pop(ing_supplied, []):
                in_degree[recipe] -= 1
                if in_degree[recipe] == 0:
                    supplies_left.append(recipe)
                    allowed_recipes.append(recipe)

        return allowed_recipes

if __name__ == '__main__':
    sol = Solution()
    print(sol.findAllRecipes(
        recipes=["bread", "sandwich", "burger"],
        ingredients=[["yeast", "flour"], ["bread", "meat"], ["sandwich", "meat", "bread"]],
        supplies=["yeast", "flour", "meat"]
    ))  # ["bread","sandwich","burger"]

    print(sol.findAllRecipes(
        recipes=["ju", "fzjnm", "x", "e", "zpmcz", "h", "q"],
        ingredients=[
            ["d"], ["hveml", "f", "cpivl"], ["cpivl", "zpmcz", "h", "e", "fzjnm", "ju"],
            ["cpivl", "hveml", "zpmcz", "ju", "h"],
            ["h", "fzjnm", "e", "q", "x"],
            ["d", "hveml", "cpivl", "q", "zpmcz", "ju", "e", "x"],
            ["f", "hveml", "cpivl"]],
        supplies=["f", "hveml", "cpivl", "d"],
    ))  # ['fzjnm', 'q', 'ju']


from datetime import datetime
from dateutil import parser
from tracardi.service.plugin.domain.register import Plugin, Spec, MetaData, \
    Documentation, PortDoc
from tracardi.service.plugin.runner import ActionRunner
from tracardi.service.plugin.domain.result import Result

class LastVisitAction(ActionRunner):

    async def set_up(self, init):
        pass

    async def run(self, payload: dict, in_edge=None) -> Result:
        if self.profile is None:
            self.console.error("Can not get last profile visit for without a profile.")
        else:
            last_visit = None
            if self.profile.metadata.time.visit.current:
                last_visit = self.profile.metadata.time.visit.current
            elif self.profile.metadata.time.insert:
                last_visit = self.profile.metadata.time.insert

            if last_visit:

                if isinstance(last_visit, str):
                    last_visit = parser.parse(last_visit)

                if isinstance(last_visit, datetime):
                    diff_secs = (datetime.utcnow() - last_visit).total_seconds()

                    return Result(port="visit", value={
                        'last': last_visit,
                        'difference': {
                            "seconds": diff_secs,
                            "minutes": diff_secs / 60,
                            "hours": diff_secs / (60 * 60),
                            "days": diff_secs / (60 * 60 * 24),
                            "weeks": diff_secs / (60 * 60 * 24 * 7)
                        }
                    })
                else:
                    self.console.error(f"Last visit is not a date. Expected datetime object got {type(last_visit)}.")

        return Result(port="error", value=payload)

def register() -> Plugin:
    return Plugin(
        start=False,
        spec=Spec(
            module=__name__,
            className=LastVisitAction.__name__,
            inputs=["payload"],
            outputs=["visit", "error"],
            version='0.7.3',
            license="MIT",
            author="Risto Kowaczewski"
        ),
        metadata=MetaData(
            name='Last profile visit time',
            desc='Returns last profile visit time difference till now.',
            icon='time',
            group=["Time"],
            tags=['previous', 'last'],
            purpose=['collection', 'segmentation'],
            documentation=Documentation(
                inputs={
                    "payload": PortDoc(desc="This port takes any JSON-like object.")
                },
                outputs={
                    "visit": PortDoc(desc="Returns last visit."),
                    "payload": PortDoc(desc="This port returns exactly same payload as given one.")
                }
            )
        )
    )


import numpy as np

from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import nn_ops
from tensorflow.python.platform import test

class Conv2DTest(test.TestCase):

  def __init__(self, method_name="runTest"):
    super(Conv2DTest, self).__init__(method_name)

  def _VerifyValues(self, tensor_in_sizes, filter_in_sizes, stride, padding,
                    expected):
    """Verifies the output values of the convolution function.

    Args:
      tensor_in_sizes: Input tensor dimensions in
        [batch, input_rows, input_cols, input_depth].
      filter_in_sizes: Filter tensor dimensions in
        [kernel_rows, kernel_cols, input_depth, output_depth].
      stride: Stride.
      padding: Padding type.
      expected: An array containing the expected operation outputs.
    """
    total_size_1 = 1
    total_size_2 = 1
    for s in tensor_in_sizes:
      total_size_1 *= s
    for s in filter_in_sizes:
      total_size_2 *= s
    # Initializes the input tensor with array containing incrementing
    # numbers from 1.
    x1 = np.array([f for f in range(1, total_size_1 + 1)])
    x1 = x1.astype(np.uint8).reshape(tensor_in_sizes)
    x1_min = 0.0
    x1_max = 255.0
    x2 = np.array([f for f in range(1, total_size_2 + 1)]).astype(np.uint8)
    x2 = x2.astype(np.uint8).reshape(filter_in_sizes)
    x2_min = 0.0
    x2_max = 255.0
    with self.cached_session(use_gpu=False) as sess:
      t1 = constant_op.constant(x1, shape=tensor_in_sizes, dtype=dtypes.quint8)
      t2 = constant_op.constant(x2, shape=filter_in_sizes, dtype=dtypes.quint8)
      conv = nn_ops.quantized_conv2d(
          t1,
          t2,
          out_type=dtypes.qint32,
          strides=[1, stride, stride, 1],
          padding=padding,
          min_input=x1_min,
          max_input=x1_max,
          min_filter=x2_min,
          max_filter=x2_max)
      value = self.evaluate(conv)
    quantized_output = value[0]
    output_min = value[1]
    output_max = value[2]
    float_output = self._QuantizedOutputToFloat(quantized_output, output_min,
                                                output_max)
    self.assertArrayNear(expected, float_output.flatten(), 1.0)
    self.assertEqual(value[0].shape, conv[0].get_shape())

  def _assertQuantizedArrayEquals(self, iarray1, iarray2):
    for i1, i2 in zip(iarray1, iarray2):
      self.assertTrue(i1 == i2)

  def _QuantizedOutputToFloat(self, quantized, quantized_min, quantized_max):
    number_of_bits = 32
    number_of_steps = 1 << number_of_bits
    range_adjust = (number_of_steps / (number_of_steps - 1.0))
    quantized_range = ((quantized_max - quantized_min) * range_adjust)
    range_scale = (quantized_range / number_of_steps)
    lowest_quantized = -(1 << (number_of_bits - 1))
    result = np.array([(quantized_min +
                        ((float(x) - lowest_quantized) * range_scale))
                       for x in quantized.flatten()])
    return result

  def testConv2D1x1Filter(self):
    # Our generated input is [batch, rows, cols, depth], and looks like this:
    # (1,2,3)    (4,5,6)    (7,8,9)
    # (10,11,12) (13,14,15) (16,17,18)
    # The filter data is:
    # (1,4,7) (2,5,8) (3,6,9)
    # That means the calculations are:
    # 1*1+2*4+3*7=30
    # 1*2+2*5+3*8=36
    # 1*3+2*6+3*9=42
    # 4*1+5*4+6*7=66
    # 4*2+5*5+6*8=81
    # 4*3+5*6+6*9=96
    # 7*1+5*8+6*9=102
    # 7*2+8*5+9*8=126
    # 7*3+8*6+9*9=150
    # 10*1+11*4+12*7=138
    # 10*2+11*5+12*8=171
    # 10*3+11*6+12*9=204
    # 13*1+14*4+15*7=174
    # 13*2+14*5+15*8=216
    # 13*3+14*6+15*9=258, clamped to 255
    # 16*1+17*4+18*7=210
    # 16*2+17*5+18*8=261, clamped to 255
    # 16*3+17*6+18*9=312, clamped to 255
    # Because the output shift is zero, we call the non-optimized reference
    # path for the convolution.
    expected_output = [
        30, 36, 42, 66, 81, 96, 102, 126, 150, 138, 171, 204, 174, 216, 258,
        210, 261, 312
    ]
    self._VerifyValues(
        tensor_in_sizes=[1, 2, 3, 3],
        filter_in_sizes=[1, 1, 3, 3],
        stride=1,
        padding="VALID",
        expected=expected_output)

  def testConv2D2x2Filter(self):
    # Our generated input is [batch, rows, cols, depth], and looks like this:
    # (1,2,3)    (4,5,6)    (7,8,9)
    # (10,11,12) (13,14,15) (16,17,18)
    # The filter data is [filter_height, filter_width, depth, filter_count]:
    # ( 1, 4, 7) (10, 13, 16)
    # (19,22,25) (28, 31, 34)
    # -
    # ( 2, 5, 8) (11, 14, 17)
    # (20,23,26) (29, 32, 35)
    # -
    # ( 3, 6, 9) (12, 15, 18)
    # (21,24,27) (30, 33, 36)
    # The raw accumulated totals are:
    # 1*1+2*4+3*7+4*10+5*13+6*16+10*19+11*22+12*25+13*28+14*31+15*34=2271
    # 1*2+2*5+3*8+4*11+5*14+6*17+10*20+11*23+12*26+13*29+14*32+15*35=2367
    # 1*3+2*6+3*9+4*12+5*15+6*18+10*21+11*24+12*27+13*30+14*33+15*36=2463
    # 4*1+5*4+6*7+7*10+8*13+9*16+13*19+14*22+15*25+16*28+17*31+18*34=2901
    # 4*2+5*5+6*8+7*11+8*14+9*17+13*20+14*23+15*26+16*29+17*32+18*35=3033
    # 4*3+5*6+6*9+7*12+8*15+9*18+13*21+14*24+15*27+16*30+17*33+18*36=3165
    # The expected values are taken from the raw totals and rescaled to fit into
    # eight bits.
    expected_output = [2271.0, 2367.0, 2463.0, 2901.0, 3033.0, 3165.0]
    self._VerifyValues(
        tensor_in_sizes=[1, 2, 3, 3],
        filter_in_sizes=[2, 2, 3, 3],
        stride=1,
        padding="VALID",
        expected=expected_output)

  def testConv2D1x2Filter(self):
    # The outputs are computed using third_party/py/IPython/notebook.
    # With a shift of 21, we should execute the optimized path here.
    expected_output = [
        231.0, 252.0, 273.0, 384.0, 423.0, 462.0, 690.0, 765.0, 840.0, 843.0,
        936.0, 1029.0
    ]
    self._VerifyValues(
        tensor_in_sizes=[1, 2, 3, 3],
        filter_in_sizes=[1, 2, 3, 3],
        stride=1,
        padding="VALID",
        expected=expected_output)

  def testConv2D2x2FilterStride2(self):
    # With a shift of 21, we should execute the optimized path here.
    expected_output = [2271.0, 2367.0, 2463.0]
    self._VerifyValues(
        tensor_in_sizes=[1, 2, 3, 3],
        filter_in_sizes=[2, 2, 3, 3],
        stride=2,
        padding="VALID",
        expected=expected_output)

  def testConv2D2x2FilterStride2Same(self):
    # With a shift of 21, we should execute the optimized path here.
    expected_output = [2271.0, 2367.0, 2463.0, 1230.0, 1305.0, 1380.0]
    self._VerifyValues(
        tensor_in_sizes=[1, 2, 3, 3],
        filter_in_sizes=[2, 2, 3, 3],
        stride=2,
        padding="SAME",
        expected=expected_output)

  def _testBadInputSize(self,
                        tin=None,
                        tfilter=None,
                        min_input=None,
                        max_input=None,
                        min_filter=None,
                        max_filter=None,
                        error_regex=""):
    strides = [1, 1, 1, 1]
    padding = "SAME"
    if tin is None:
      tin = math_ops.cast(
          constant_op.constant(1, shape=[1, 2, 3, 3]), dtype=dtypes.quint8)

    if tfilter is None:
      tfilter = math_ops.cast(
          constant_op.constant(1, shape=[1, 2, 3, 3]), dtype=dtypes.quint8)

    if min_input is None:
      min_input = constant_op.constant(0, shape=[], dtype=dtypes.float32)

    if max_input is None:
      max_input = constant_op.constant(0, shape=[], dtype=dtypes.float32)

    if min_filter is None:
      min_filter = constant_op.constant(0, shape=[], dtype=dtypes.float32)

    if max_filter is None:
      max_filter = constant_op.constant(0, shape=[], dtype=dtypes.float32)

    with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError),
                                error_regex):
      self.evaluate(
          nn_ops.quantized_conv2d(
              tin,
              tfilter,
              out_type=dtypes.qint32,
              strides=strides,
              padding=padding,
              min_input=min_input,
              max_input=max_input,
              min_filter=min_filter,
              max_filter=max_filter))

  def testBadInputSizes(self):
    self._testBadInputSize(
        tin=math_ops.cast(
            constant_op.constant(1, shape=[1, 2]), dtype=dtypes.quint8),
        error_regex="must be rank 4")
    self._testBadInputSize(
        tfilter=math_ops.cast(
            constant_op.constant(1, shape=[1, 2]), dtype=dtypes.quint8),
        error_regex="must be rank 4")
    self._testBadInputSize(
        min_input=constant_op.constant(0, shape=[1], dtype=dtypes.float32),
        error_regex="must be rank 0")
    self._testBadInputSize(
        max_input=constant_op.constant(0, shape=[1], dtype=dtypes.float32),
        error_regex="must be rank 0")
    self._testBadInputSize(
        min_filter=constant_op.constant(0, shape=[1], dtype=dtypes.float32),
        error_regex="must be rank 0")
    self._testBadInputSize(
        max_filter=constant_op.constant(0, shape=[1], dtype=dtypes.float32),
        error_regex="must be rank 0")

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


from message_senders.message_sender_base import MessageSender
import json
import boto3
from botocore.exceptions import ClientError

class SnsMessageSender(MessageSender):
    def __init__(self):
        """
        Initialises a message sending object for AWS SNS.
        """
        self.name = "AWS SNS"
        self.sns_resource = boto3.resource('sns')

        all_topics = self.list_topics()
        for topic in all_topics:
            self.topic = topic

    def list_topics(self):
        """
        Lists topics for the current account.

        :return: An iterator that yields the topics.
        """
        try:
            topics_iter = self.sns_resource.topics.all()
        except ClientError:
            print("Couldn't get topics.")
            raise
        else:
            return topics_iter

    def publish_multi_message(self, topic, subject, default_message, sms_message, email_message):
        """
        Publishes a multi-format message to a topic. A multi-format message takes
        different forms based on the protocol of the subscriber. For example,
        an SMS subscriber might receive a short, text-only version of the message
        while an email subscriber could receive an HTML version of the message.

        :param topic: The topic to publish to.
        :param subject: The subject of the message.
        :param default_message: The default version of the message. This version is
                                sent to subscribers that have protocols that are not
                                otherwise specified in the structured message.
        :param sms_message: The version of the message sent to SMS subscribers.
        :param email_message: The version of the message sent to email subscribers.
        :return: The ID of the message.
        """
        try:
            message = {
                'default': default_message,
                'sms': sms_message,
                'email': email_message
            }
            response = topic.publish(
                Message=json.dumps(message), Subject=subject, MessageStructure='json')
            message_id = response['MessageId']
        except ClientError:
            print(f"Couldn't publish message to topic {topic.arn}.")
            raise
        else:
            return message_id

    def send_message(self, message):
        """
        """
        self.publish_multi_message(self.topic, "CRASH ALERT", message, message, message)


class Solution:
    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
        n = len(people)
        people.sort()
        res = [-1] * n
        for h, k in people:
            ctr = k
            for j in range(n):
                if res[j] == -1 and ctr == 0:
                    res[j] = [h, k]
                    break
                elif res[j] == -1 or res[j][0] >= h:
                    ctr -= 1
        return res


import pickle
import sys

prms_file_name = sys.argv[1]
with open(prms_file_name, 'rb') as f:
    params = pickle.load(f)

trp = params['training_params']
#params['training_params']['INIT_LEARNING_RATE'] *= (1 + self.tr_prms[
# 'CUR_EPOCH']

def printrp(trp_, info):
    print(info, " training params:")
    for k, v in trp_.items():
        print("\t", k, ":", v)
    print("   Current Learning Rate:", trp_['INIT_LEARNING_RATE'] /
            (1 + trp_['CUR_EPOCH'] / trp_['EPOCHS_TO_HALF_RATE']))

printrp(trp, "Before")

trp['CUR_EPOCH'] = 0
if len(sys.argv) > 2:
    trp['INIT_LEARNING_RATE'] = float(sys.argv[2])

printrp(trp, "After")
out_file_name = prms_file_name[:-3] + 're.pkl'
with open(out_file_name, 'wb') as pkl_file:
    pickle.dump(params, pkl_file, -1)
print("Saved to:", out_file_name)


'''
解析：https://leetcode-cn.com/problems/diameter-of-binary-tree/solution/shi-pin-jie-shi-di-gui-dai-ma-de-yun-xing-guo-chen/

一条路径(path)的长度为该路径经过的节点数减一，
所以求直径（即求路径长度的最大值）等效于求路径经过节点数的最大值减一。

而任意一条路径均可以被看作由某个节点为起点，从其左儿子和右儿子向下遍历的路径拼接得到。

Note：
dfs 求 root 所对应的子树的最多节点数( 1 + max(l, r)，1 表示当前节点本身的节点数)
实质上一条路径所对应的节点数 - 1 就是这条路径的边长
最长的路径等于当前 root 左边的节点数量 + 右边的节点数量（左边和右边都会统计到 root 这个节点）
因此 l + r 相当于统计了两次 root，无需额外 -1 就是我们所需的路径边长

time: O(n), This is because in our recursion function longestPath, we only enter and exit from each node once. We know this because each node is entered from its parent, and in a tree, nodes only have one parent.
space: O(n), The space complexity depends on the size of our implicit call stack during our DFS, which relates to the height of the tree. In the worst case, the tree is skewed so the height of the tree is O(N). If the tree is balanced, it'd be O(logN).
'''

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def diameterOfBinaryTree(self, root: TreeNode) -> int:
        self.res = 0

        def dfs(root):
            if not root:
                return 0
            l = dfs(root.left)
            r = dfs(root.right)

            self.res = max(self.res, l+r)
            return 1 + max(l, r)

        dfs(root)
        return self.res


from collections import OrderedDict

from graphql.type import (
    GraphQLBoolean,
    GraphQLEnumType,
    GraphQLInputObjectType,
    GraphQLInt,
    GraphQLInterfaceType,
    GraphQLList,
    GraphQLNonNull,
    GraphQLObjectType,
    GraphQLScalarType,
    GraphQLSchema,
    GraphQLString,
    GraphQLUnionType,
)
from graphql.type.definition import (
    GraphQLArgument,
    GraphQLEnumValue,
    GraphQLField,
    GraphQLInputObjectField,
)
from graphql.utils.schema_printer import print_introspection_schema, print_schema

def print_for_test(schema):
    return "\n" + print_schema(schema)

def print_single_field_schema(field_config):
    Root = GraphQLObjectType(name="Root", fields={"singleField": field_config})
    return print_for_test(GraphQLSchema(Root))

def test_prints_string_field():
    output = print_single_field_schema(GraphQLField(GraphQLString))
    assert (
        output
        == """
schema {
  query: Root
}

type Root {
  singleField: String
}
"""
    )

def test_prints_list_string_field():
    output = print_single_field_schema(GraphQLField(GraphQLList(GraphQLString)))
    assert (
        output
        == """
schema {
  query: Root
}

type Root {
  singleField: [String]
}
"""
    )

def test_prints_non_null_list_string_field():
    output = print_single_field_schema(
        GraphQLField(GraphQLNonNull(GraphQLList(GraphQLString)))
    )
    assert (
        output
        == """
schema {
  query: Root
}

type Root {
  singleField: [String]!
}
"""
    )

def test_prints_list_non_null_string_field():
    output = print_single_field_schema(
        GraphQLField(GraphQLList(GraphQLNonNull(GraphQLString)))
    )
    assert (
        output
        == """
schema {
  query: Root
}

type Root {
  singleField: [String!]
}
"""
    )

def test_prints_non_null_list_non_null_string_field():
    output = print_single_field_schema(
        GraphQLField(GraphQLNonNull(GraphQLList(GraphQLNonNull(GraphQLString))))
    )
    assert (
        output
        == """
schema {
  query: Root
}

type Root {
  singleField: [String!]!
}
"""
    )

def test_prints_object_field():
    FooType = GraphQLObjectType(name="Foo", fields={"str": GraphQLField(GraphQLString)})

    Root = GraphQLObjectType(name="Root", fields={"foo": GraphQLField(FooType)})

    Schema = GraphQLSchema(Root)

    output = print_for_test(Schema)

    assert (
        output
        == """
schema {
  query: Root
}

type Foo {
  str: String
}

type Root {
  foo: Foo
}
"""
    )

def test_prints_string_field_with_int_arg():
    output = print_single_field_schema(
        GraphQLField(type_=GraphQLString, args={"argOne": GraphQLArgument(GraphQLInt)})
    )
    assert (
        output
        == """
schema {
  query: Root
}

type Root {
  singleField(argOne: Int): String
}
"""
    )

def test_prints_string_field_with_int_arg_with_default():
    output = print_single_field_schema(
        GraphQLField(
            type_=GraphQLString,
            args={"argOne": GraphQLArgument(GraphQLInt, default_value=2)},
        )
    )
    assert (
        output
        == """
schema {
  query: Root
}

type Root {
  singleField(argOne: Int = 2): String
}
"""
    )

def test_prints_string_field_with_non_null_int_arg():
    output = print_single_field_schema(
        GraphQLField(
            type_=GraphQLString,
            args={"argOne": GraphQLArgument(GraphQLNonNull(GraphQLInt))},
        )
    )
    assert (
        output
        == """
schema {
  query: Root
}

type Root {
  singleField(argOne: Int!): String
}
"""
    )

def test_prints_string_field_with_multiple_args():
    output = print_single_field_schema(
        GraphQLField(
            type_=GraphQLString,
            args=OrderedDict(
                [
                    ("argOne", GraphQLArgument(GraphQLInt)),
                    ("argTwo", GraphQLArgument(GraphQLString)),
                ]
            ),
        )
    )

    assert (
        output
        == """
schema {
  query: Root
}

type Root {
  singleField(argOne: Int, argTwo: String): String
}
"""
    )

def test_prints_string_field_with_multiple_args_first_is_default():
    output = print_single_field_schema(
        GraphQLField(
            type_=GraphQLString,
            args=OrderedDict(
                [
                    ("argOne", GraphQLArgument(GraphQLInt, default_value=1)),
                    ("argTwo", GraphQLArgument(GraphQLString)),
                    ("argThree", GraphQLArgument(GraphQLBoolean)),
                ]
            ),
        )
    )

    assert (
        output
        == """
schema {
  query: Root
}

type Root {
  singleField(argOne: Int = 1, argTwo: String, argThree: Boolean): String
}
"""
    )

def test_prints_string_field_with_multiple_args_second_is_default():
    output = print_single_field_schema(
        GraphQLField(
            type_=GraphQLString,
            args=OrderedDict(
                [
                    ("argOne", GraphQLArgument(GraphQLInt)),
                    ("argTwo", GraphQLArgument(GraphQLString, default_value="foo")),
                    ("argThree", GraphQLArgument(GraphQLBoolean)),
                ]
            ),
        )
    )

    assert (
        output
        == """
schema {
  query: Root
}

type Root {
  singleField(argOne: Int, argTwo: String = "foo", argThree: Boolean): String
}
"""
    )

def test_prints_string_field_with_multiple_args_last_is_default():
    output = print_single_field_schema(
        GraphQLField(
            type_=GraphQLString,
            args=OrderedDict(
                [
                    ("argOne", GraphQLArgument(GraphQLInt)),
                    ("argTwo", GraphQLArgument(GraphQLString)),
                    ("argThree", GraphQLArgument(GraphQLBoolean, default_value=False)),
                ]
            ),
        )
    )

    assert (
        output
        == """
schema {
  query: Root
}

type Root {
  singleField(argOne: Int, argTwo: String, argThree: Boolean = false): String
}
"""
    )

def test_prints_interface():
    FooType = GraphQLInterfaceType(
        name="Foo",
        resolve_type=lambda *_: None,
        fields={"str": GraphQLField(GraphQLString)},
    )

    BarType = GraphQLObjectType(
        name="Bar", fields={"str": GraphQLField(GraphQLString)}, interfaces=[FooType]
    )

    Root = GraphQLObjectType(name="Root", fields={"bar": GraphQLField(BarType)})

    Schema = GraphQLSchema(Root, types=[BarType])
    output = print_for_test(Schema)

    assert (
        output
        == """
schema {
  query: Root
}

type Bar implements Foo {
  str: String
}

interface Foo {
  str: String
}

type Root {
  bar: Bar
}
"""
    )

def test_prints_multiple_interfaces():
    FooType = GraphQLInterfaceType(
        name="Foo",
        resolve_type=lambda *_: None,
        fields={"str": GraphQLField(GraphQLString)},
    )
    BaazType = GraphQLInterfaceType(
        name="Baaz",
        resolve_type=lambda *_: None,
        fields={"int": GraphQLField(GraphQLInt)},
    )

    BarType = GraphQLObjectType(
        name="Bar",
        fields=OrderedDict(
            [("str", GraphQLField(GraphQLString)), ("int", GraphQLField(GraphQLInt))]
        ),
        interfaces=[FooType, BaazType],
    )

    Root = GraphQLObjectType(name="Root", fields={"bar": GraphQLField(BarType)})

    Schema = GraphQLSchema(Root, types=[BarType])
    output = print_for_test(Schema)

    assert (
        output
        == """
schema {
  query: Root
}

interface Baaz {
  int: Int
}

type Bar implements Foo, Baaz {
  str: String
  int: Int
}

interface Foo {
  str: String
}

type Root {
  bar: Bar
}
"""
    )

def test_prints_unions():
    FooType = GraphQLObjectType(
        name="Foo", fields={"bool": GraphQLField(GraphQLBoolean)}
    )

    BarType = GraphQLObjectType(name="Bar", fields={"str": GraphQLField(GraphQLString)})

    SingleUnion = GraphQLUnionType(
        name="SingleUnion", resolve_type=lambda *_: None, types=[FooType]
    )

    MultipleUnion = GraphQLUnionType(
        name="MultipleUnion", resolve_type=lambda *_: None, types=[FooType, BarType]
    )

    Root = GraphQLObjectType(
        name="Root",
        fields=OrderedDict(
            [
                ("single", GraphQLField(SingleUnion)),
                ("multiple", GraphQLField(MultipleUnion)),
            ]
        ),
    )

    Schema = GraphQLSchema(Root)
    output = print_for_test(Schema)

    assert (
        output
        == """
schema {
  query: Root
}

type Bar {
  str: String
}

type Foo {
  bool: Boolean
}

union MultipleUnion = Foo | Bar

type Root {
  single: SingleUnion
  multiple: MultipleUnion
}

union SingleUnion = Foo
"""
    )

def test_prints_input_type():
    InputType = GraphQLInputObjectType(
        name="InputType", fields={"int": GraphQLInputObjectField(GraphQLInt)}
    )

    Root = GraphQLObjectType(
        name="Root",
        fields={
            "str": GraphQLField(
                GraphQLString, args={"argOne": GraphQLArgument(InputType)}
            )
        },
    )

    Schema = GraphQLSchema(Root)
    output = print_for_test(Schema)

    assert (
        output
        == """
schema {
  query: Root
}

input InputType {
  int: Int
}

type Root {
  str(argOne: InputType): String
}
"""
    )

def test_prints_custom_scalar():
    OddType = GraphQLScalarType(
        name="Odd", serialize=lambda v: v if v % 2 == 1 else None
    )

    Root = GraphQLObjectType(name="Root", fields={"odd": GraphQLField(OddType)})

    Schema = GraphQLSchema(Root)
    output = print_for_test(Schema)

    assert (
        output
        == """
schema {
  query: Root
}

scalar Odd

type Root {
  odd: Odd
}
"""
    )

def test_print_enum():
    RGBType = GraphQLEnumType(
        name="RGB",
        values=OrderedDict(
            [
                ("RED", GraphQLEnumValue(0)),
                ("GREEN", GraphQLEnumValue(1)),
                ("BLUE", GraphQLEnumValue(2)),
            ]
        ),
    )

    Root = GraphQLObjectType(name="Root", fields={"rgb": GraphQLField(RGBType)})

    Schema = GraphQLSchema(Root)
    output = print_for_test(Schema)

    assert (
        output
        == """
schema {
  query: Root
}

enum RGB {
  RED
  GREEN
  BLUE
}

type Root {
  rgb: RGB
}
"""
    )

def test_print_introspection_schema():
    Root = GraphQLObjectType(
        name="Root", fields={"onlyField": GraphQLField(GraphQLString)}
    )

    Schema = GraphQLSchema(Root)
    output = "\n" + print_introspection_schema(Schema)

    assert (
        output
        == """
schema {
  query: Root
}

directive @include(if: Boolean!) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT

directive @skip(if: Boolean!) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT

directive @deprecated(reason: String = "No longer supported") on FIELD_DEFINITION | ENUM_VALUE

type __Directive {
  name: String!
  description: String
  locations: [__DirectiveLocation!]!
  args: [__InputValue!]!
  onOperation: Boolean! @deprecated(reason: "Use `locations`.")
  onFragment: Boolean! @deprecated(reason: "Use `locations`.")
  onField: Boolean! @deprecated(reason: "Use `locations`.")
}

enum __DirectiveLocation {
  QUERY
  MUTATION
  SUBSCRIPTION
  FIELD
  FRAGMENT_DEFINITION
  FRAGMENT_SPREAD
  INLINE_FRAGMENT
  SCHEMA
  SCALAR
  OBJECT
  FIELD_DEFINITION
  ARGUMENT_DEFINITION
  INTERFACE
  UNION
  ENUM
  ENUM_VALUE
  INPUT_OBJECT
  INPUT_FIELD_DEFINITION
}

type __EnumValue {
  name: String!
  description: String
  isDeprecated: Boolean!
  deprecationReason: String
}

type __Field {
  name: String!
  description: String
  args: [__InputValue!]!
  type: __Type!
  isDeprecated: Boolean!
  deprecationReason: String
}

type __InputValue {
  name: String!
  description: String
  type: __Type!
  defaultValue: String
}

type __Schema {
  types: [__Type!]!
  queryType: __Type!
  mutationType: __Type
  subscriptionType: __Type
  directives: [__Directive!]!
}

type __Type {
  kind: __TypeKind!
  name: String
  description: String
  fields(includeDeprecated: Boolean = false): [__Field!]
  interfaces: [__Type!]
  possibleTypes: [__Type!]
  enumValues(includeDeprecated: Boolean = false): [__EnumValue!]
  inputFields: [__InputValue!]
  ofType: __Type
}

enum __TypeKind {
  SCALAR
  OBJECT
  INTERFACE
  UNION
  ENUM
  INPUT_OBJECT
  LIST
  NON_NULL
}
"""
    )


from typing import List, Tuple
from glob import glob
import random

from librosa.display import specshow, waveshow
from librosa import amplitude_to_db
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

def enumerate_recordings(pathname: str, shuffle=False) -> List[Tuple[int, str]]:
    recordings = glob(f"{pathname}/*/*.wav")
    if shuffle:
        random.shuffle(recordings)
    return list(enumerate(recordings))

def plot_model_metrics(epoch, metrics):
    plt.figure(figsize=(10, 5))

    plt.subplot(1, 2, 1)
    plt.plot(epoch, metrics["loss"], label="Training Loss")
    plt.plot(epoch, metrics["val_loss"], label="Validation Loss")
    plt.legend()
    plt.xlabel("Epoch", fontsize=14, fontweight="bold", labelpad=10)
    plt.ylabel("Loss [CrossEntropy]", fontsize=14, fontweight="bold", labelpad=10)
    plt.title("Loss Evolution", fontsize=16, fontweight="bold")

    plt.subplot(1, 2, 2)
    plt.plot(epoch, 100 * np.array(metrics["accuracy"]), label="Training Accuracy")
    plt.plot(
        epoch, 100 * np.array(metrics["val_accuracy"]), label="Validation Accuracy"
    )
    plt.legend()
    plt.ylim(0, 100)
    plt.xlabel("Epoch", fontsize=14, fontweight="bold", labelpad=10)
    plt.ylabel("Accuracy [%]", fontsize=14, fontweight="bold", labelpad=10)
    plt.title("Accuracy Evolution", fontsize=16, fontweight="bold")

    plt.tight_layout()
    plt.show()

def plot_confusion_matrix(confusion_mtx, classes):
    plt.figure(figsize=(10, 5))
    sns.heatmap(
        confusion_mtx,
        xticklabels=classes,
        yticklabels=classes,
        annot=True,
        fmt="g",
    )
    plt.xlabel("Prediction", fontsize=14, fontweight="bold", labelpad=10)
    plt.ylabel("Expected", fontsize=14, fontweight="bold", labelpad=10)
    plt.title("Confusion Matrix", fontsize=16, fontweight="bold")
    plt.show()

def plot_waveform(waveform: np.ndarray, sample_rate: int):
    """
    Plots the waveform of an audio signal.
    """
    plt.figure(figsize=(8, 4))
    waveshow(waveform, sr=sample_rate)
    plt.xlabel("Time (s)")
    plt.ylabel("Amplitude")
    plt.title("Waveform")
    plt.show()

def plot_spectrogram(spectrogram: np.ndarray, sample_rate: int, hop_length: int):
    """
    Plots the spectrogram of an audio signal.
    """
    plt.figure(figsize=(8, 4))
    db = amplitude_to_db(spectrogram[:, :, 0].T, ref=np.max)
    specshow(
        db,
        sr=sample_rate,
        hop_length=hop_length,
        x_axis="ms",
        y_axis="linear",
        cmap="viridis",
    )
    plt.colorbar(format="%+2.0f dB")
    plt.xlabel("Time (ms)")
    plt.ylabel("Frequency")
    plt.title("Spectrogram")
    plt.show()

def get_pred_percentage(logits: np.ndarray) -> np.float32:
    # Subtract the max logit to prevent overflow
    logits_exp = np.exp(logits - np.max(logits))
    probabilities = logits_exp / np.sum(logits_exp, axis=-1, keepdims=True)
    max_probability = np.max(probabilities, axis=-1)
    return round(max_probability * 100, 1)


import tkinter as tk
from tkinter import ttk

from matplotlib import pyplot as plt
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk

class Graphs:
    step = 0

    def step_init(self, value) : self.step = value

    def __init__(self, drawFrame, impulse):
        self.drawFrame = drawFrame
        self.impulse = impulse

        self.tab_control = ttk.Notebook(self.drawFrame)

        self.tab1 = ttk.Frame(self.tab_control)
        self.tab_control.add(self.tab1, text = "Sygnał wejściowy")
        self.add_signal(self.impulse.time, self.impulse.input_singal, self.tab1, "x(t)")

        self.tab2 = ttk.Frame(self.tab_control)
        self.tab_control.add(self.tab2, text = "Sygnał wyjściowy")

        time_base = self.impulse.time[0::self.step]
        size_differ = (len(time_base) - len(impulse.output_signal))
        if size_differ == 0: self.add_signal(time_base, self.impulse.output_signal, self.tab2, "y(t)")
        else:  self.add_signal(time_base[0: -size_differ], self.impulse.output_signal, self.tab2, "y(t)")

        self.tab3 = ttk.Frame(self.tab_control)
        self.tab_control.add(self.tab3, text = "Wykres amplitudowy")
        self.add_bode_amp()

        self.tab4 = ttk.Frame(self.tab_control)
        self.tab_control.add(self.tab4, text = "Wykres fazowy")
        self.add_bode_phase()

        self.tab_control.pack(expan = 1, fill = "both")

    def add_signal(self, s_x, s_y, frame, y):
        f = Figure(figsize=(4,4), dpi=100)

        a = f.add_subplot(1,1,1)
        a.plot(s_x, s_y)

        a.set_ylabel(y)
        a.set_xlabel("time [s]")
        a.grid(True, linestyle='-.')

        canvas = FigureCanvasTkAgg(f, frame)
        canvas.get_tk_widget().pack(fill = "both", side = "bottom", expand = True)
        canvas._tkcanvas.pack(side = "top", fill = "both", expand = True)

    def add_bode_amp(self):
        fa = Figure(figsize=(4,4), dpi=100)

        aa = fa.add_subplot(1,1,1)
        aa.semilogx(self.impulse.w, self.impulse.mag, color="blue", linewidth='1')

        aa.set_xlabel("Czestotliwosc")
        aa.set_ylabel("Wzmocnienie")
        aa.grid(True, linestyle='-.')

        canvas = FigureCanvasTkAgg(fa, self.tab3)
        canvas.get_tk_widget().pack(fill = "both", side = "bottom", expand = True)
        canvas._tkcanvas.pack(side = "top", fill = "both", expand = True)

    def add_bode_phase(self):
        fp = Figure(figsize=(4,4), dpi=100)

        ap = fp.add_subplot(1,1,1)
        ap.semilogx(self.impulse.w, self.impulse.phase, color="blue", linewidth='1')

        ap.set_xlabel("Czestotliwosc")
        ap.set_ylabel("Faza")
        ap.grid(True, linestyle='-.')

        canvas = FigureCanvasTkAgg(fp, self.tab4)
        canvas.get_tk_widget().pack(fill = "both", side = "bottom", expand = True)
        canvas._tkcanvas.pack(side = "top", fill = "both", expand = True)


#swapping of 2 numbers using a temp variable
a = int(input('Enter the first number'))
b = int(input('Enter the second number'))

print('Before swapping a is:',a)
print('Before swapping b is:',b)
temp = 0

temp = a
a = b
b = temp

print('After swapping a is:',a)
print('After swapping b is:',b)


import time, sys, traceback, codecs
import logging.handlers

LOG_LEVEL_DEBUG = 1
LOG_LEVEL_INFO = 2
LOG_LEVEL_WARNING = 3
LOG_LEVEL_ERROR = 4
LOG_LEVEL_CRITICAL = 5

class Logger(object):

    def __init__(self, process_tag, logger_base, log_level = logging.INFO, log_mode = "local1", log_file_path = "", minimum_log_interval = 30):
        """
        process tag: the process tag to appear in each log line.
        log level: the minimum log level to actually be logged (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL).
        log mode: what type of logging we are using - SysLog = Local1; Rotating File Handler = anything else.
        log file path: the full path to the log file; used when we aren't using local1 (i.e., SysLog).
        minimum log interval: the minimum time between handler logs.
        """

        # Default the process tag to a generic if none was specified.
        if process_tag == None:
            process_tag = "AF_X"

        # Create the loggers.
        self._standard_logger, self._incident_logger = self._create_loggers("{0}.standard".format(logger_base), "{0}.incident".format(logger_base), process_tag, log_level, log_mode, log_file_path)

        # Setup the log interval tracking.
        self.minimum_log_interval = minimum_log_interval
        self.last_log_time_dict = {}
        self.object_handled_count_dict = {}

    def _create_loggers(self, logger_name, incident_logger_name, process_tag, log_level, log_mode, log_file_path):

        # Create the logger object.
        logger = logging.getLogger(logger_name)
        logger.setLevel(logging.DEBUG)

        # Create the handler and formatter, based on our log mode.
        if log_mode == "local1":
            log_handler = logging.handlers.SysLogHandler(facility="local1", address="/dev/log")
            formatter = logging.Formatter("{0}:".format(process_tag) +
                "%(process)d|"
                "%(module)s:%(funcName)s:%(lineno)d|"
                "%(levelname)s|"
                "%(message)s",
                "%m.%d-%H:%M:%S")
        else:
            log_handler = logging.handlers.TimedRotatingFileHandler(log_file_path, "midnight", 1, 3)
            formatter = logging.Formatter("%(asctime)s|{0}:".format(process_tag) +
                "%(process)d|"
                "%(module)s:%(funcName)s:%(lineno)d|"
                "%(levelname)s|"
                "%(message)s",
                "%m.%d-%H:%M:%S")

        # Set the formatter and log level for the handler.
        log_handler.setFormatter(formatter)
        log_handler.setLevel(log_level)

        # Add the handler to our logger.
        logger.addHandler(log_handler)

        # Create the incident logger.
        incident_logger = logging.getLogger(incident_logger_name)
        incident_logger.setLevel(logging.DEBUG)

        # Return the logger.
        return logger, incident_logger

    def get_logger(self, incident_logger = False):

        # Return the appropriate logger.
        if incident_logger == False:
            return self._standard_logger
        else:
            return self._incident_loggger

    def log_critical(self, message, log_incident = False):

        # Log to standard; Log to incident if desired.
        self._standard_logger.critical(message)
        if log_incident == True and len(self._incident_logger.handlers) > 0:
            self._incident_logger.critical(message)

    def log_debug(self, message, log_incident = False):

        # Log to standard; Log to incident if desired.
        self._standard_logger.debug(message)
        if log_incident == True and len(self._incident_logger.handlers) > 0:
            self._incident_logger.debug(message)

    def log_error(self, message, log_incident = False):

        # Log to standard; Log to incident if desired.
        self._standard_logger.error(message)
        if log_incident == True and len(self._incident_logger.handlers) > 0:
            self._incident_logger.error(message)

    def log_info(self, message, log_incident = False):

        # Log to standard; Log to incident if desired.
        self._standard_logger.info(message)
        if log_incident == True and len(self._incident_logger.handlers) > 0:
            self._incident_logger.info(message)

    def log_warning(self, message, log_incident = False):

        # Log to standard; Log to incident if desired.
        self._standard_logger.warning(message)
        if log_incident == True and len(self._incident_logger.handlers) > 0:
            self._incident_logger.warning(message)

    def log_handle_exit(self, handle_method, handled_count, message_formatter, log_method = None):

        # If the handler index doesn't exist in our tracker, add it with default values.
        if handle_method not in list(self.last_log_time_dict.keys()):
            self.last_log_time_dict[handle_method] = 0
            self.object_handled_count_dict[handle_method] = 0

        # Increment the number of objects we've handled since the last logging of a handle exit.
        self.object_handled_count_dict[handle_method] += handled_count

        # Test if we should log the exit message based on timing.
        current_time = time.time()
        log_interval = current_time - self.last_log_time_dict[handle_method]
        if log_interval >= self.minimum_log_interval:

            # If we weren't given a log method, default to the info logger.
            if log_method == None:
                log_method = self._standard_logger.info

            # Log the message and reset our trackers.
            log_method(message_formatter.format(self.object_handled_count_dict[handle_method]))
            self.last_log_time_dict[handle_method] = current_time
            self.object_handled_count_dict[handle_method] = 0

    def _log_incident(self, message, method):

        pass

    def save_coredump(self, fn):
        tb = sys.exc_info()[2]
        stack = []
        while tb:
            stack.append(tb.tb_frame)
            tb = tb.tb_next

        with codecs.open(fn, "w", encoding="utf-8") as fp:
            stack.reverse()
            traceback.print_exc(file=fp)

            lines = []
            lines.append("\nLocals by frame")
            for frame in stack:
                lines.append("Frame %s in %s at line %s" % (
                    frame.f_code.co_name,
                    frame.f_code.co_filename,
                    frame.f_lineno))
                for k, v in frame.f_locals.items():
                    lines.append("  {0}={1}".format(k, v))
                lines.append("")
            fp.write("\n".join(lines))


import math

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

class Circle:
    def __init__(self, x, y, radius):
        self.center = Point(x, y)
        self.radius = radius

    def contains(self, point):
        distans = math.sqrt((point.x - self.center.x) ** 2 +
                            (point.y - self.center.y) ** 2)
        if distans <= self.radius:
            return True
        else:
            return False


from z3 import Int, Implies, solve

# the set of initial subterms of a set of monoid terms
def initial_subterms(terms):
    subterms = set()
    for t in terms:
        for i in range(len(t) + 1):
            subterms.add(t[:i])
    return subterms

# the set of implications u <= v ==> ux <= vx
# for ux != vx in terms.
# because there is no patterm matching,
# we do slicing, and what is `u` in the instructions
# is now `u[:-1]`, and what is `ux` is now `u`
def sigma(terms):
    sig = set()
    # this iteration could be optimised
    for u in terms:
        for v in terms:
            if u == '' or v == '' or u == v:
                pass
            elif u[-1] == v[-1]:
                sig.add(Implies(Int(u[:-1]) <= Int(v[:-1]),
                                Int(u) <= Int(v)))
    return sig

# the set of inequations s > t for
# s in terms1 and t in terms2.
# if this is satisfiable together with sigma,
# then the equation Meet(terms1) <= Join(terms2)
# is not valid.
def fail(terms1, terms2):
    fail = set()
    for s in terms1:
        for t in terms2:
            fail.add(Int(s) > Int(t))
    return fail

def check(terms1, terms2):
    return solve(sigma(initial_subterms(terms1.union(terms2)))
                    .union(fail(terms1, terms2))
    )


from django.dispatch import receiver
from stock import signals
import time
@receiver(signals.stock_changed_signal)
def handle_stock_change(sender, code,name,old_value,new_value, **kwargs):
    message=''
    title=''
    if(old_value > new_value):
        title='Stock price Drop Alert'
        message = "Price of Stock {name}({code}) has been dropped from {old_value} to {new_value}".format(name=name,code=code,old_value=old_value,new_value=new_value)
    else:
        title='Stock price Rise Alert'
        message = "Price of Stock {name}({code}) has been adjusted from {old_value} to {new_value}".format(name=name,code=code,old_value=old_value,new_value=new_value)

    emails=["user1@gmail.com","user2@gmail.com","user3@gmail.com"]
    print('Starting Celery Task System .....')
    for email in emails:
        #In Real world, We will be executing Celery tasks
        print('Sending mail to '+email)
        print('Title: '+title)
        print('Message: '+message)
        print('--------------------------------------------')
        time.sleep(1)#Just for Demonstration


def count_neighbours(grid, row, col):
    """
    Input: Three arguments. A grid as a tuple of tuples with integers (1/0),
           a row number and column number for a cell as integers.
    Output: How many neighbouring cells have chips as an integer.
    """

    # using the hint: form a list of neighbor rules
    NEIGHBORS = ((-1,-1), (-1,0), (-1,1), (0,-1), (0,1), (1,-1), (1,0), (1,1))

    # create a list of all cell positions in the provided grid
    boundary = [(r,c) for r in range(len(grid)) for c in range(len(grid))]

    # build a list of cells to count
    moore_neighbors = [(r+row, c+col) for r,c in NEIGHBORS]

    # count the cells that are within the bounds of the grid
    return sum([grid[r][c] for (r,c) in moore_neighbors if (r,c) in boundary])

if __name__ == '__main__':
    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert count_neighbours(((1, 0, 0, 1, 0),
                             (0, 1, 0, 0, 0),
                             (0, 0, 1, 0, 1),
                             (1, 0, 0, 0, 0),
                             (0, 0, 1, 0, 0),), 1, 2) == 3, "1st example"
    assert count_neighbours(((1, 0, 0, 1, 0),
                             (0, 1, 0, 0, 0),
                             (0, 0, 1, 0, 1),
                             (1, 0, 0, 0, 0),
                             (0, 0, 1, 0, 0),), 0, 0) == 1, "2nd example"
    assert count_neighbours(((1, 1, 1),
                             (1, 1, 1),
                             (1, 1, 1),), 0, 2) == 3, "Dense corner"
    assert count_neighbours(((0, 0, 0),
                             (0, 1, 0),
                             (0, 0, 0),), 1, 1) == 0, "Single"


##
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import load_boston
from sklearn.impute import SimpleImputer  # 填补缺失值的类
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import cross_val_score

##
dataset = load_boston()
print(dataset.data.shape)
# 总共506*13=6578个数据
X_full, y_full = dataset.data, dataset.target
n_samples = X_full.shape[0]
n_features = X_full.shape[1]

##
# 使50%数据缺失
rng = np.random.RandomState(0)
missing_rate = 0.5
n_missing_samples = int(np.floor(n_samples * n_features * missing_rate))  # np.floor向下取整，返回.0格式的浮点数

##
# randint(下限，上限，n)在上下限之间取出n个整数
missing_features = rng.randint(0, n_features, n_missing_samples)
missing_samples = rng.randint(0, n_samples, n_missing_samples)

##
missing_samples = rng.choice(n_samples, n_missing_samples)

X_missing = X_full.copy()
y_missing = y_full.copy()

# 可以直接通过列表形式赋值
X_missing[missing_samples, missing_features] = np.nan

print(X_missing.shape)

# 转换成DataFrame是为了后续方便各种操作，numpy对矩阵的运算速度快到拯救人生，但是在索引等功能上却不如 pandas来得好用
X_missing = pd.DataFrame(X_missing)
X_missing.head()

##
# 使用均值进行填补
# SimpleImputer是填补缺失值的类，strategy为填补数据的类型
imp_mean = SimpleImputer(missing_values = np.nan, strategy = 'mean')  # 实例化
X_missing_mean = imp_mean.fit_transform(X_missing)  # 训练fit+导出predict>>>特殊的接口fit_transform

# 使用0进行填补
imp_0 = SimpleImputer(missing_values = np.nan, strategy = "constant", fill_value = 0)
X_missing_0 = imp_0.fit_transform(X_missing)

# 查看是否还有空值，无空值，证明完全填补
pd.DataFrame(X_missing_mean).isnull().sum()

##
X_missing_reg = X_missing.copy()
# 找出数据集中，缺失值从小到大排列的特征的顺序，且得到这些特征的索引
# argsort返回从小到大排序的顺序所对应的索引
sortindex = np.argsort(X_missing_reg.isnull().sum(axis = 0)).values

print(sortindex)

for i in sortindex:
    # 构建我们的新特征矩阵（没有被选中去填充的特征+原始的标签）和新标签（被选中去填充的特征）
    df = X_missing_reg
    # 新标签
    fillc = df.iloc[:, i]
    # 新特征矩阵
    df = pd.concat([df.iloc[:, df.columns != i], pd.DataFrame(y_full)], axis = 1)

    # 在新特征矩阵中，对含有缺失值的列，进行0的填补
    df_0 = SimpleImputer(missing_values = np.nan, strategy = 'constant', fill_value = 0).fit_transform(df)
    # 找出我们的训练集和测试集
    # 现在标签中存在的非空值
    Ytrain = fillc[fillc.notnull()]
    # 现在标签中的空值
    # 不需要Ytest的值，要的是Ytest的索引
    Ytest = fillc[fillc.isnull()]
    # 在新特征矩阵上，被选出来的要填充的非空值对应的记录
    Xtrain = df_0[Ytrain.index, :]
    # 新特征矩阵上，被选出来的要填充的那个特征的空值对应的记录
    Xtest = df_0[Ytest.index]

    # 用随机森林回归来填补缺失值
    rfc = RandomForestRegressor(n_estimators = 100)  # 实例化
    rfc = rfc.fit(Xtrain, Ytrain)  # 训练
    # 用predict接口将Xtest导入，得到预测结果作为填补空值的值
    Ypredict = rfc.predict(Xtest)

    # 将填补好的特征返回原始特征矩阵中
    X_missing_reg.loc[X_missing_reg.iloc[:, i].isnull(), i] = Ypredict

##

# 对所有数据进行建模，取得MSE结果
X = [X_full, X_missing_mean, X_missing_0, X_missing_reg]

mse = []
std = []
for x in X:
    estimator = RandomForestRegressor(random_state = 0, n_estimators = 100)
    scores = cross_val_score(estimator, x, y_full, scoring = 'neg_mean_squared_error').mean()
    mse.append(scores * -1)

print([*zip(["X_full", "X_missing_mean", "X_missing_0", "X_missing_reg"], mse)])

##
x_labels = [
    'Full data'
    , 'Zero Imputation'
    , 'Mean Imputation'
    , 'Regressor Imputation'
]
colors = ['r', 'g', 'b', 'orange']

plt.figure(figsize = (12, 6))
ax = plt.subplot(111)
for i in np.arange(len(mse)):
    ax.barh(i, mse[i], color = colors[i], alpha = 0.6, align = 'center')
ax.set_title("Imputation Techniques with Boston Data")
ax.set_xlim(left = np.min(mse) * 0.9
            , right = np.max(mse) * 1.1)
ax.set_yticks(np.arange(len(mse)))
ax.set_xlabel('MSE')
ax.set_yticklabels(x_labels)
plt.savefig('compare_imputation', dpi = 300)
plt.show()


#/usr/bin/python
# -*- coding: utf-8 -*-
#
#	funcion capicua(num)
#		num1=Darlle a volta a num
#     devolver num1==num
#  finfuncion
#
#  Pedir num
#  Si e capicua visualizar "e Capicua"
#  Se non Visualizar "NON é Capicua"
#  FinSI

#
#  Consideramos capicúas os números de 1 díxito
#
def eCapicua(num):
	num1=0
	bknum=num
	while (bknum>0):
		num1=(num1*10)+(bknum%10)
		bknum=bknum/10
#
# Si son iguais retorna True, se non False
#
	return (num==num1)

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

n=int(input("Numero: "));
if (eCapicua(n)):
	print("E Capicúa")
else:
	print("Non é Capicúa");


import math
n=int(input())
a=[int(i) for i in input().split()]
if n==1:
    print(a[0])
else:
    x=math.gcd(a[0],a[1])
    for i in range (2,n):
        x=math.gcd(x,a[i])
    print(x*n)


from flask_sqlalchemy import Model
from .compat import basestring

class QueryableMixin(Model):
    """Mixin that adds convenience methods ."""

    @classmethod
    def get_by_id(cls, record_id):
        """Get record by ID."""
        if any(
                (isinstance(record_id, basestring) and record_id.isdigit(),
                 isinstance(record_id, (int, float))),
        ):
            return cls.query.get(int(record_id))

    @classmethod
    def get(cls, **kwargs):
        return cls.query.filter_by(**kwargs).first()

    @classmethod
    def deletes(cls, whereclause, commit=True):
        stmt = cls.__table__.delete().where(whereclause)
        cls.session.execute(stmt)
        return commit and cls.session.commit()

    @classmethod
    def delete_by(cls, commit=True, **kwargs):
        cls.query.filter_by(**kwargs).delete()
        return commit and cls.session.commit()

    @classmethod
    def soft_delete(cls, record_id, commit=True, **kwargs):
        return cls.updates(cls.id == record_id, commit, status='N', **kwargs)

    @classmethod
    def updates(cls, whereclause, commit=True, **kwargs):
        stmt = cls.__table__.update().where(whereclause).values(**kwargs)
        # print(f'update stmt: {stmt}')
        cls.session.execute(stmt)
        return commit and cls.session.commit()

    @classmethod
    def update_by_id(cls, record_id, commit=True, **kwargs):
        return cls.updates(cls.id == record_id, commit, **kwargs)
        # print(f'#{record_id} update dict: {dict(**kwargs)}')
        # # stmt = cls.query.filter_by(id=record_id).update(dict(**kwargs))
        # stmt = cls.__table__.update().where(cls.id == record_id).values(**kwargs)
        # print(f'update stmt: {stmt}')
        # cls.session.execute(stmt)
        # return commit and cls.session.commit()

    @classmethod
    def create(cls, **kwargs):
        """Create a new record and save it the database."""
        instance = cls(**kwargs)
        return instance.save()

    def update(self, commit=True, **kwargs):
        """Update specific fields of a record."""
        for attr, value in kwargs.items():
            setattr(self, attr, value)
        if commit:
            self.session.commit()
        return self

    def save(self, commit=True):
        """Save the record."""
        self.session.add(self)
        if commit:
            self.session.commit()
        return self

    def delete(self, commit=True):
        """Remove the record from the database."""
        self.session.delete(self)
        if commit:
            self.session.commit()
        return self

    @classmethod
    def rollback_session(cls):
        cls.session.rollback()

    @classmethod
    def _preprocess_params(cls, kwargs):
        """Returns a preprocessed dictionary of parameters. Used by default
        before creating a new instance or updating an existing instance.

        Parameters
        -----------

        **kwargs: a dictionary of parameters
        """
        kwargs.pop('csrf_token', None)
        return kwargs

    @classmethod
    def filter_by(cls, **kwargs):
        """Returns a list of instances of the model filtered by the
        specified key word arguments.

        Parameters
        ----------

        **kwargs: filter parameters

        """
        limit = kwargs.pop('limit', None)
        reverse = kwargs.pop('reverse', False)
        q = cls.query.filter_by(**kwargs)
        if reverse:
            q = q.order_by(cls.id.desc())
        if limit:
            q = q.limit(limit)
        return q

    @classmethod
    def filter(cls, *criterion, **kwargs):
        limit = kwargs.pop('limit', None)
        reverse = kwargs.pop('reverse', False)
        q = cls.query.filter_by(**kwargs).filter(*criterion)
        if reverse:
            q = q.order_by(cls.id.desc())
        if limit:
            q = q.limit(limit)
        return q

    @classmethod
    def count(cls, *criterion, **kwargs):
        if criterion or kwargs:
            return cls.filter(
                *criterion,
                **kwargs).count()
        else:
            return cls.query.count()

    @classmethod
    def all(cls, *criterion, **kwargs):
        """Returns a list of instances of the service's model filtered by the
        specified key word arguments.

        :param **kwargs: filter parameters
        """
        return cls.filter(*criterion, **kwargs).all()

    @classmethod
    def first(cls, *criterion, **kwargs):
        """Returns the first instance found of the service's model filtered by
        the specified key word arguments.

        :param **kwargs: filter parameters
        """
        return cls.filter(*criterion, **kwargs).first()

    @classmethod
    def one(cls, *criterion, **kwargs):
        return cls.filter(*criterion, **kwargs).one()

    @classmethod
    def last(cls, *criterion, **kwargs):
        kwargs['reverse'] = True
        return cls.first(*criterion, **kwargs)

    @classmethod
    def new(cls, **kwargs):
        """Returns a new, unsaved instance of the service's model class.

        :param **kwargs: instance parameters
        """
        return cls(**cls._preprocess_params(kwargs))

    @classmethod
    def add(cls, model, commit=True):
        if not isinstance(model, cls):
            raise ValueError('%s is not of type %s'(model, cls))
        cls.session.add(model)
        try:
            if commit:
                cls.session.commit()
            return model
        except:
            cls.session.rollback()
            raise

    @classmethod
    def add_all(cls, models, commit=True, check_type=False):
        if check_type:
            for model in models:
                if not isinstance(model, cls):
                    raise ValueError('%s is not of type %s'(model, cls))
        cls.session.add_all(models)
        try:
            if commit:
                cls.session.commit()
            return models
        except:
            cls.session.rollback()
            raise

    # @classmethod
    # def _get(cls, key, keyval, user_id=None):
    #     result = cls.query.filter(
    #         getattr(cls, key) == keyval)
    #     if user_id and hasattr(cls, 'user_id'):
    #         result = result.filter(cls.user_id == user_id)
    #     return result.one()

    # @classmethod
    # def get(cls, keyval, key='id', user_id=None):
    #     """Returns an instance of the service's model with the specified id.
    #     Returns `None` if an instance with the specified id does not exist.
    #
    #     :param id: the instance id
    #     """
    #     if (key in cls.__table__.columns
    #             and cls.__table__.columns[key].primary_key):
    #         if user_id and hasattr(cls, 'user_id'):
    #             return cls.query.filter_by(id=keyval, user_id=user_id).one()
    #         return cls.query.get(keyval)
    #     else:
    #         result = cls.query.filter(
    #             getattr(cls, key) == keyval)
    #         if user_id and hasattr(cls, 'user_id'):
    #             result = result.filter(cls.user_id == user_id)
    #         return result.one()

    # @classmethod
    # def create(cls, **kwargs):
    #     """Returns a new, saved instance of the service's model class.
    #
    #     :param **kwargs: instance parameters
    #     """
    #     try:
    #         return cls.add(cls.new(**kwargs))
    #     except:
    #         cls.session.rollback()
    #         raise

    @classmethod
    def build(cls, **kwargs):
        """Returns a new, added but unsaved instance of the service's model class.

        :param **kwargs: instance parameters
        """
        return cls.add(cls.new(**kwargs), commit=False)

    @classmethod
    def find_or_build(cls, **kwargs):
        """Checks if an instance already exists in db with these kwargs else
        returns a new, saved instance of the service's model class.

        :param **kwargs: instance parameters
        """
        return cls.first(**kwargs) or cls.build(**kwargs)

    @classmethod
    def new_all(cls, list_of_kwargs):
        return [cls.new(**kwargs) for kwargs in list_of_kwargs]

    @classmethod
    def build_all(cls, list_of_kwargs):
        return cls.add_all([
            cls.new(**kwargs) for kwargs in list_of_kwargs], commit=False)

    @classmethod
    def find_or_build_all(cls, list_of_kwargs):
        return cls.add_all([cls.first(**kwargs) or cls.new(**kwargs)
                            for kwargs in list_of_kwargs], commit=False)

    @classmethod
    def update_all(cls, *criterion, **kwargs):
        try:
            r = cls.query.filter(*criterion).update(kwargs, 'fetch')
            cls.session.commit()
            return r
        except:
            cls.session.rollback()
            raise

    @classmethod
    def get_and_update(cls, id, **kwargs):
        """Returns an updated instance of the service's model class.

        :param model: the model to update
        :param **kwargs: update parameters
        """
        model = cls.get(id)
        for k, v in cls._preprocess_params(kwargs).items():
            setattr(model, k, v)
        cls.session.commit()
        return model

    @classmethod
    def get_and_setattr(cls, id, **kwargs):
        """Returns an updated instance of the service's model class.

        :param model: the model to update
        :param **kwargs: update parameters
        """
        model = cls.get(id)
        for k, v in cls._preprocess_params(kwargs).items():
            setattr(model, k, v)
        return model