import math
import numpy as np
import astropy.units as u

DEG2RAD = math.pi / 180.

class BeamError(Exception):
    """docstring for BeamError"""
    pass

class InvalidBeamOperationError(Exception):
    pass

class RadioBeamDeprecationWarning(Warning):
    pass

def deconvolve_optimized(beamprops1, beamprops2, failure_returns_pointlike=False):
    """
    An optimized, non-Quantity version of beam deconvolution.

    Because no unit conversions are handled, the inputs MUST be in degrees for the major, minor,
    and position angle.

    Parameters
    ----------
    beamprops1: dict
        Dictionary with keys 'BMAJ', 'BMIN', and 'BPA' for the beam to deconvolve from. Can be
        produced with `~radio_beam.Beam.to_fits_keywords`.
    beamprops2: dict
        Same as `beamprops1` for the second beam.
    failure_returns_pointlike : bool, optional
        Return a point beam (zero area) when deconvolution fails. If `False`,
        this will instead raise a `~radio_beam.utils.BeamError` when deconvolution fails.

    Returns
    -------
    new_major : float
        Deconvolved major FWHM.
    new_minor : float
        Deconvolved minor FWHM.
    new_pa : float
        Deconvolved position angle.

    """

    # blame: https://github.com/pkgw/carma-miriad/blob/CVSHEAD/src/subs/gaupar.for
    # (githup checkin of MIRIAD, code by Sault)

    maj1 = beamprops1['BMAJ']
    min1 = beamprops1['BMIN']
    pa1 = beamprops1['BPA'] * DEG2RAD

    maj2 = beamprops2['BMAJ']
    min2 = beamprops2['BMIN']
    pa2 = beamprops2['BPA'] * DEG2RAD

    alpha = ((maj1 * math.cos(pa1))**2 +
             (min1 * math.sin(pa1))**2 -
             (maj2 * math.cos(pa2))**2 -
             (min2 * math.sin(pa2))**2)

    beta = ((maj1 * math.sin(pa1))**2 +
            (min1 * math.cos(pa1))**2 -
            (maj2 * math.sin(pa2))**2 -
            (min2 * math.cos(pa2))**2)

    gamma = 2 * ((min1**2 - maj1**2) * math.sin(pa1) * math.cos(pa1) -
                 (min2**2 - maj2**2) * math.sin(pa2) * math.cos(pa2))

    s = alpha + beta
    t = math.sqrt((alpha - beta)**2 + gamma**2)

    # Deal with floating point issues
    # This matches the arcsec**2 check for deconvolve below
    # Difference is we keep things in deg^2 here
    atol_t = np.finfo(np.float64).eps / 3600.**2

    # To deconvolve, the beam must satisfy:
    # alpha < 0
    alpha_cond = alpha + np.finfo(np.float64).eps < 0

    # beta < 0
    beta_cond = beta + np.finfo(np.float64).eps < 0
    # s < t
    st_cond = s < t + atol_t

    if alpha_cond or beta_cond or st_cond:
        if failure_returns_pointlike:
            return 0., 0., 0.
        else:
            raise BeamError("Beam could not be deconvolved")
    else:
        new_major = math.sqrt(0.5 * (s + t))
        new_minor = math.sqrt(0.5 * (s - t))

        # absolute tolerance needs to be <<1 microarcsec
        atol = 1e-7 / 3600.
        if (math.sqrt(abs(gamma) + abs(alpha - beta))) < atol:
            new_pa = 0.0
        else:
            new_pa = 0.5 * math.atan2(-1. * gamma, alpha - beta)

    # In the limiting case, the axes can be zero to within precision
    # Add the precision level onto each axis so a deconvolvable beam
    # is always has beam.isfinite == True
    new_major += np.finfo(np.float64).eps
    new_minor += np.finfo(np.float64).eps

    return new_major, new_minor, new_pa

def deconvolve(beam, other, failure_returns_pointlike=False):
    """
    Deconvolve a beam from another

    Parameters
    ----------
    beam : `Beam`
        The defined beam.
    other : `Beam`
        The beam to deconvolve from this beam
    failure_returns_pointlike : bool
        Option to return a pointlike beam (i.e., one with major=minor=0) if
        the second beam is larger than the first.  Otherwise, a ValueError
        will be raised

    Returns
    -------
    new_beam : `Beam`
        The convolved Beam

    Raises
    ------
    failure : ValueError
        If the second beam is larger than the first, the default behavior
        is to raise an exception.  This can be overridden with
        failure_returns_pointlike
    """

    # The header keywords handle the conversions to degree for BMAJ, BMIN, BPA.
    beamprops1 = beam.to_header_keywords()
    beamprops2 = other.to_header_keywords()

    return deconvolve_optimized(beamprops1, beamprops2,
                                failure_returns_pointlike=failure_returns_pointlike)

def convolve(beam, other):
    """
    Convolve one beam with another.

    Parameters
    ----------
    other : `Beam`
        The beam to convolve with

    Returns
    -------
    new_beam : `Beam`
        The convolved Beam
    """

    # blame: https://github.com/pkgw/carma-miriad/blob/CVSHEAD/src/subs/gaupar.for
    # (github checkin of MIRIAD, code by Sault)

    alpha = ((beam.major * np.cos(beam.pa))**2 +
             (beam.minor * np.sin(beam.pa))**2 +
             (other.major * np.cos(other.pa))**2 +
             (other.minor * np.sin(other.pa))**2)

    beta = ((beam.major * np.sin(beam.pa))**2 +
            (beam.minor * np.cos(beam.pa))**2 +
            (other.major * np.sin(other.pa))**2 +
            (other.minor * np.cos(other.pa))**2)

    gamma = (2 * ((beam.minor**2 - beam.major**2) *
                  np.sin(beam.pa) * np.cos(beam.pa) +
                  (other.minor**2 - other.major**2) *
                  np.sin(other.pa) * np.cos(other.pa)))

    s = alpha + beta
    t = np.sqrt((alpha - beta)**2 + gamma**2)

    new_major = np.sqrt(0.5 * (s + t))
    new_minor = np.sqrt(0.5 * (s - t))
    # absolute tolerance needs to be <<1 microarcsec
    if np.isclose(((abs(gamma) + abs(alpha - beta))**0.5).to(u.arcsec).value, 1e-7):
        new_pa = 0.0 * u.deg
    else:
        new_pa = 0.5 * np.arctan2(-1. * gamma, alpha - beta)

    return new_major, new_minor, new_pa

def transform_ellipse(major, minor, pa, x_scale, y_scale):
    '''
    Transform an ellipse by scaling in the x and y axes.

    Parameters
    ----------
    major : `~astropy.units.Quantity`
        Major axis.
    minor : `~astropy.units.Quantity`
        Minor axis.
    pa : `~astropy.units.Quantity`
        PA of the major axis.
    x_scale : float
        x axis scaling factor.
    y_scale : float
        y axis scaling factor.

    Returns
    -------
    trans_major : `~astropy.units.Quantity`
        Major axis in the transformed frame.
    trans_minor : `~astropy.units.Quantity`
        Minor axis in the transformed frame.
    trans_pa : `~astropy.units.Quantity`
        PA of the major axis in the transformed frame.
    '''

    # This code is based on the implementation in CASA:
    # https://open-bitbucket.nrao.edu/projects/CASA/repos/casa/browse/code/imageanalysis/ImageAnalysis/CasaImageBeamSet.cc

    major = major.to(u.arcsec)
    minor = minor.to(u.arcsec)
    pa = pa.to(u.rad)

    cospa = np.cos(pa)
    sinpa = np.sin(pa)
    cos2pa = cospa**2
    sin2pa = sinpa**2

    major2 = major**2
    minor2 = minor**2

    a = (cos2pa / major2) + (sin2pa / minor2)
    b = -2 * cospa * sinpa * (major2**-1 - minor2**-1)
    c = (sin2pa / major2) + (cos2pa / minor2)

    x2_scale = x_scale**2
    y2_scale = y_scale**2

    r = a / x2_scale
    s = b**2 / (4 * x2_scale * y2_scale)
    t = c / y2_scale

    udiff = r - t
    u2 = udiff**2

    f1 = u2 + 4 * s
    f2 = np.sqrt(f1) * np.abs(udiff)

    j1 = (f2 + f1) / f1 / 2
    j2 = (f1 - f2) / f1 / 2

    k1 = (j1 * r + j1 * t - t) / (2 * j1 - 1)
    k2 = (j2 * r + j2 * t - t) / (2 * j2 - 1)

    c1 = np.sqrt(k1)**-1
    c2 = np.sqrt(k2)**-1

    pa_sign = 1 if pa.value >= 0 else -1

    if c1 == c2:
        # Transformed to a circle
        trans_major = 1 / c1
        trans_minor = trans_major
        trans_pa = 0. * u.rad

    elif c1 > c2:
        # c1 and c2 are the major and minor axes; use j1 to get PA
        trans_major = c1
        trans_minor = c2
        trans_pa = pa_sign * np.arccos(np.sqrt(j1))
    else:
        # Opposite case where the axes are switched; get PA from j2
        trans_major = c2
        trans_minor = c1
        trans_pa = pa_sign * np.arccos(np.sqrt(j2))

    return trans_major, trans_minor, trans_pa


import objc

NSUserNotification = objc.lookUpClass("NSUserNotification")
NSUserNotificationCenter = objc.lookUpClass("NSUserNotificationCenter")
NSObject = objc.lookUpClass("NSObject")

class NotificationDelegator(NSObject):

    def userNotificationCenter_shouldPresentNotification_(self, center, notification):
        print("Should present notification")
        return True

    def userNotificationCenter_didActivateNotification_(self, center, notification):
        print("Activate notification")

delegator = NotificationDelegator.alloc().init()

def notify(title="", subtitle="", info_text="", delay=1, sound=False, userInfo=None):
    """ Python method to show a desktop notification on Mountain Lion. Where:
        title: Title of notification
        subtitle: Subtitle of notification
        info_text: Informative text of notification
        delay: Delay (in seconds) before showing the notification
        sound: Play the default notification sound
        userInfo: a dictionary that can be used to handle clicks in your
                  app"s applicationDidFinishLaunching:aNotification method
    """
    if userInfo is None:
        userInfo = {}
    notification = NSUserNotification.alloc().init()
    notification.setTitle_(title)
    notification.setSubtitle_(subtitle)
    notification.setInformativeText_(info_text)
    notification.setUserInfo_(userInfo)
    if sound:
        notification.setSoundName_("NSUserNotificationDefaultSoundName")
    center = NSUserNotificationCenter.defaultUserNotificationCenter()
    center.setDelegate_(delegator)
    center.deliverNotification_(notification)


import sys
sys.stdin = open("day1_이진수.txt")

def Binary(num):
    global result
    share, remainder = 0, 0

    for i in range(4):
        share = num // 2
        remainder = num % 2
        result = str(remainder) + result
        num = share

    return

T = int(input())

hex_to_dec = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9,
                  'A': 10, 'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15}

for test_case in range(1, T+1):
    N, hex = map(str, input().split())

    answer = ''
    for i in hex:
        result = ''
        Binary(hex_to_dec[i])
        answer += result
    print('#{} {}'.format(test_case, answer))


from __future__ import division
import json
import os
import math
from nltk import word_tokenize
from nltk.stem import WordNetLemmatizer
from nltk.corpus import stopwords

# dir with .json files
DIR_PATH = ".\JSON_data/"

def count_tf(term, full_text, count_terms_in_text):
    count_term = full_text.count(term)
    return count_term/count_terms_in_text

def count_doc_with_word(word, pages):
 counter = 0
 for list_of_word in pages:
     if word in list_of_word:
         counter +=1
 return counter

def find_json_file_in_dir(path):
 files = os.listdir(path)
 # filter only .json type
 jsons = filter(lambda x: x.endswith('.json'), files)
 return jsons

def get_text_from_files(json_files_pull):
 data = {}
 for file_name in json_files_pull:
    with open(DIR_PATH + file_name, "r", encoding='utf-8') as file:
        data[file_name] = json.load(file)
 return data

def find_all_key_words(jobs_data):
    #upload pure text from json file
    filtering_data = {}
    tmp_list = []
    excluded_tag = ["Job id", "Job link", "Posted time", "Activity on this Job", "About the client"]
    for k,v in jobs_data.items():
        del tmp_list[:]
        for key,i in v.items():
            if key not in excluded_tag:
                tmp_list.append(i)
        filtering_data[k] = tmp_list.copy()

        #TODO itegrate filtering data to next algorithm

# 1.Tokenize
    jobs_count = len(jobs_data)
    tokens = []
    for v in jobs_data.values():
        for val in v.values():
            tokens.append(word_tokenize(val))

    # 2.Filtering
    en_stopwords = stopwords.words("english")
    extend_list = ["http", "https"]
    en_stopwords.extend(extend_list)
    leng_list = ["c++", "C++"]  #if c#, R, JS
    filter_tokens = []
    for line in tokens:
     for word in line:
         if word in leng_list:
             let_index = line.index(word)
             line.remove(word)
             line.insert(let_index, "cplusplus")
         # Delete url
         elif word.startswith("//www.") or word.endswith(".com"):
             line.remove(word)
         else:
             # Delete all symbol which not letter or number
             line[line.index(word)] = "".join([letter for letter in word if letter.isalnum()])
     # Delete stop words, words which length <= 2 and digits
     # Switch all words to lower case
     filter_tokens.append([item.lower() for item in line if item.lower() not in en_stopwords and len(item) > 2 and not item.isdigit()])

    # 3.Lemmatization
    lemms = []
    lemmatizer = WordNetLemmatizer()
    for token in filter_tokens:
        lemms.append([lemmatizer.lemmatize(lemma) for lemma in token])

    # 4.TF
    tf = []
    for line in lemms:
        count_terms_in_text = len(line)
    tf.append([count_tf(term, line, count_terms_in_text) for term in line])

    # 5.IDF
    idf = ["0"] * jobs_count
    tmp_list = []
    doc_counter = 0
    for i in range(jobs_count):
     del tmp_list[:]
     for word in range(len(lemms[i])):
         if tf[i][word] > 0:
             doc_counter = count_doc_with_word(lemms[i][word], lemms)
             tmp_list.append(math.log(jobs_count/doc_counter))
     idf[i] = tmp_list[:]

    # 6.TF-IDF
    dict_for_page = {}
    tfidf = ["0"] * jobs_count
    for i in range(jobs_count):
        dict_for_page.clear()
        for j in range(len(lemms[i])):
            # Make dict with word and tf-idf
            dict_for_page[lemms[i][j]] = tf[i][j] * idf[i][j]
        tfidf[i] = dict_for_page.copy()

    # 7.Sorted key-words
    tfidf = [sorted(map_index.items(), key=lambda x: -x[1]) for map_index in tfidf]
    return tfidf

    #N - number of key-word on the page
def get_top_keywords(N):
    # list with text from all .json files
    data = get_text_from_files(find_json_file_in_dir(DIR_PATH))
    tfidf = find_all_key_words(data)

    files_names = list(data.keys())
    size = len(data)
    top_keywords = []
    top_keywords_with_files_names = {}
    # Return TOP N key-words
    for page in range(size):
        page_size = len(tfidf[page])
        del top_keywords[:]
        if N <= page_size:
            top_keywords = [key[0] for key in tfidf[page][:N]]
            top_keywords_with_files_names[files_names[page]] = top_keywords[:]
        else:
            print("Value of N which you entered, greater than count of word in job number " + str(page) +
               "\nWill be displayed maximum words in this job description. \nMaximum = " + str(page_size))
            top_keywords = [key[0] for key in tfidf[page][:page_size]]
            top_keywords_with_files_names[files_names[page]] = top_keywords[:]
    return top_keywords_with_files_names


import requests
import subprocess
from Bio import SeqIO

response = requests.get('https://www.uniprot.org/uniprot/?query=virB7+AND+rickettsiales&format=fasta')
with open('uniprot_virB7.fasta', 'w') as outfile:
    outfile.write(response.text)

# response = requests.get('https://www.uniprot.org/uniprot/?query=virB7+AND+reviewed:yes&format=fasta')
# with open('uniprot_virB7.fasta', 'a') as outfile:
#     outfile.write(response.text)

specs = ['bin_125', 'bin_67-1', 'UBA6187', 'UBA6178', 'TARA_ANE_MAG_00011',
        'Rickettsia_bellii_RML369-C', 'Deianiraea_vastatrix',
        'Candidatus_Midichloria_mitochondrii_IricVA',
        'Anaplasma_phagocytophilum_str_HZ']
for spec in specs:
    print(spec)
    cmd = "tblastn -subject ../36_genome_stats/genomes/{}.fna \
    -query bins_ref_virB7.fasta -evalue 0.5 \
    -out {}_virB7.out -outfmt '6 qseqid sseqid evalue sstart send sseq'".format(spec, spec)

    subprocess.run(cmd, shell=True)

    maxline = []
    maxlen = 0
    for line in open('{}_virB7.out'.format(spec)):
        line = line.strip().split()
        if len(line[-1]) > maxlen:
            maxline = line
            maxlen = len(line[-1])
    with open('{}_virB7.fasta'.format(spec), 'w') as outhandle:
        print('>{}_{}_{}_{}'.format(spec, maxline[1], maxline[3], maxline[4]), file=outhandle)
        print(maxline[5].replace('-', ''), file=outhandle)
        print(maxline[2])

with open('bins_ref_virB7.fasta', 'w') as outfile :
    for rec in SeqIO.parse('uniprot_virB7.fasta', 'fasta'):
        SeqIO.write(rec, outfile, 'fasta')
    for spec in specs:
        for rec in SeqIO.parse('{}_virB7.fasta'.format(spec), 'fasta'):
            SeqIO.write(rec, outfile, 'fasta')

cmd = "mafft-einsi --thread 40 bins_ref_virB7.fasta"
with open('bins_ref_virB7.mafft', 'w') as outfile:
    subprocess.run(cmd, shell=True, stdout=outfile)


import tensorflow as tf
import os
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.applications.vgg16 import VGG16
from tensorflow.keras.applications.vgg16 import preprocess_input
from tensorflow.keras.preprocessing import image
from sklearn.cluster import KMeans
from joblib import dump, load
import numpy as np
import argparse

def index():
    # Parse arguments
    argParser = argparse.ArgumentParser()
    argParser.add_argument("-d", "--dataset", required=True,
        help="Path to directory that contains the images to be indexed")
    argParser.add_argument("-i", "--index",
       help="Path to where teh computed idnex will be stored")
    argParser.add_argument("-t", "--training", action="store_const", const="train",
                           help="If you want to jus train the knn model no csv file will be created")
    args = vars(argParser.parse_args())

    if os.path.isdir("vgg16"):
        model = keras.models.load_model("vgg16")
    else:
        model = VGG16(weights="imagenet", include_top=False)

    if args["training"] == "train":
        print("training")
        train_kmeans(args, model)
    else:
        build_index(args, model)

def build_index(args, model):
    if os.path.isfile("kmeans_model.joblib"):
        kmeans_model = load("kmeans_model.joblib")
    else:
        print("No k_means file found")
        return

    data_path = args["dataset"]
    index_file = open(args["index"], "w")
    feature_list = []

    for img_name in os.listdir(data_path):
        img_path = data_path + img_name

        img = image.load_img(img_path, target_size=(244, 244))
        img_array = image.img_to_array(img)
        img_array = np.expand_dims(img_array, axis=0)
        img_array = preprocess_input(img_array)

        features = model.predict(img_array)
        features_numpy = np.array(features)

        write_to_index(features_numpy.flatten(), img_name, index_file)
    print("Finished building index.csv file")

def write_to_index(histogram, imageID, indexFile):
    indexFile.write("%s,%s\n" % (imageID, ",".join(histogram.astype(str))))

def train_kmeans(args, model):
    data_path = args["dataset"]
    feature_list = []

    for img_name in os.listdir(data_path):
        img_path = data_path + img_name

        img = image.load_img(img_path, target_size=(244, 244))
        img_array = image.img_to_array(img)
        img_array = np.expand_dims(img_array, axis=0)
        img_array = preprocess_input(img_array)

        features = model.predict(img_array)
        features_numpy = np.array(features)
        feature_list.append(features_numpy.flatten())

    feature_array = np.array(feature_list)
    kmeans_model = KMeans(n_clusters=10000)
    dump(kmeans_model, "kmeans_model.joblib")

index()


from models.material_body import MaterialBody
from models.material_point import MaterialPoint
from models import trajectory
import matplotlib.pyplot as plt
import numpy as np
import os

images_folder = "images_path/"
image_name = "trajectory.png"

def trajectory_plotter(points_coordinates: [], x_limits: [] = None, y_limits: [] = None):
    plt.figure(figsize=(10, 10))
    for point_num, point in enumerate(points_coordinates):
        x_vals = [cord[0] for cord in point]
        y_vals = [cord[1] for cord in point]
        plt.plot(x_vals, y_vals)

    if x_limits is not None:
        plt.xlim(x_limits[0], x_limits[1])

    if y_limits is not None:
        plt.ylim(y_limits[0], y_limits[1])

    plt.grid(True)
    plt.savefig(os.path.join(images_folder + image_name))
    plt.show()


from setuptools import setup, find_packages
import os
import re

def read(fname):
    with open(os.path.join(os.path.dirname(__file__), fname), "rt") as fh:
        return fh.read()

_version_regex = r'^\s*__version__\s*=\s*(\"|\')(?P<version>.*)\1'
def get_version():
    version_str = read("ion/__init__.py")
    match = re.search(_version_regex, version_str)
    if match is None:
        raise ValueError("Failed to find version number")
    return match['version']

setup(
    name="ion",
    author="Maximus Wasylow",
    version=get_version(),
    author_email="bamwasylow@gmail.com",
    description="Python support package containing various utility and helper functions and classes grouped by theme",
    long_description=read("README.md"),
    packages=find_packages(),
    python_requires=">=3.7",
    install_requires=[
        'requests',
        'simplejson',
        'pytz',
        'pprint'
    ]
)


import botocore
import pytest
import ujson as json

from sanic.response import json as json_response

from insanic.conf import settings
from insanic.views import InsanicView

from iniesta.sessions import BotoSession
from iniesta.sns import SNSClient, SNSMessage

from .infra import SNSInfra

class TestSNSClient(SNSInfra):
    async def test_client_initialize(self, create_global_sns):

        client = await SNSClient.initialize(
            topic_arn=create_global_sns["TopicArn"]
        )
        assert client.topic_arn == create_global_sns["TopicArn"]

    async def test_client_create_message(self, create_global_sns):
        client = await SNSClient.initialize(
            topic_arn=create_global_sns["TopicArn"]
        )

        response = client.create_message(
            event="SomethingAwesomeHappened",
            message="Great Success!",
            value="Something",
        )

        assert response is not None
        assert response.client == client
        assert isinstance(response, SNSMessage)
        # assert 'MessageId' in response
        # assert response['MessageId'] is not None

    async def test_client_topic_doesnt_exist(self):

        with pytest.raises(botocore.exceptions.ClientError):
            await SNSClient.initialize(topic_arn="asdasda")

    async def test_list_subscriptions_empty(self, create_global_sns):

        client = await SNSClient.initialize(
            topic_arn=create_global_sns["TopicArn"]
        )

        subscriptions = [s async for s in client.list_subscriptions_by_topic()]

        assert len(subscriptions) == 0

    async def test_list_subscriptions_with_existing(
        self, create_global_sns, create_service_sqs, create_sqs_subscription,
    ):

        client = await SNSClient.initialize(
            topic_arn=create_global_sns["TopicArn"]
        )

        subscriptions = [s async for s in client.list_subscriptions_by_topic()]

        assert len(subscriptions) == 1

        assert subscriptions[0]["Protocol"] == "sqs"
        assert (
            subscriptions[0]["Endpoint"]
            == create_service_sqs["Attributes"]["QueueArn"]
        )

    async def test_get_subscription_attributes(
        self, create_global_sns, create_service_sqs, create_sqs_subscription,
    ):

        """
        Actual attributes response
        {
            'Owner': '120387605022',
            'RawMessageDelivery': 'false',
            'FilterPolicy': '{"iniesta_pass":["hello",{"prefix":"Request"}]}',
            'TopicArn': 'arn:aws:sns:ap-northeast-1:120387605022:tests-tests-global',
            'Endpoint': 'arn:aws:sqs:ap-northeast-1:120387605022:iniesta-tests-tests',
            'Protocol': 'sqs',
            'PendingConfirmation': 'false', 'ConfirmationWasAuthenticated': 'true',
            'SubscriptionArn': 'arn:aws:sns:ap-northeast-1:120387605022:tests-tests-global:cd591f81-c223-4cf8-828d-6fbbce3f66f3'
        }

        :param create_global_sns:
        :param create_service_sqs:
        :param create_sqs_subscription:
        :return:
        """

        client = await SNSClient.initialize(
            topic_arn=create_global_sns["TopicArn"]
        )

        subscriptions = [s async for s in client.list_subscriptions_by_topic()]

        subscription = subscriptions[0]

        attributes = await client.get_subscription_attributes(
            subscription["SubscriptionArn"]
        )

        assert (
            attributes["Attributes"]["TopicArn"]
            == create_global_sns["TopicArn"]
        )
        assert attributes["Attributes"]["Protocol"] == "sqs"

    @pytest.fixture()
    async def insanic_application_with_event_polling(
        self, monkeypatch, insanic_application, create_global_sns, filter_policy
    ):
        monkeypatch.setattr(
            settings,
            "INIESTA_SNS_PRODUCER_GLOBAL_TOPIC_ARN",
            create_global_sns["TopicArn"],
            raising=False,
        )
        monkeypatch.setattr(
            settings,
            "INIESTA_INITIALIZATION_TYPE",
            ["SNS_PRODUCER"],
            raising=False,
        )
        from iniesta import Iniesta

        Iniesta.init_app(insanic_application)

        client = await SNSClient.initialize(
            topic_arn=create_global_sns["TopicArn"]
        )

        class TestView(InsanicView):
            permission_classes = []

            @client.publish_event(event="testEvent")
            def get(self, request, *args, **kwargs):
                return json_response({"help": "me"})

        insanic_application.add_route(TestView.as_view(), "/tests/event/")

        return insanic_application

    def test_publish_event_decorator(
        self,
        create_global_sns,
        insanic_application_with_event_polling,
        monkeypatch,
    ):
        BotoSession.session = None

        errors = []

        async def mock_publish(message):

            try:
                assert message.event == "testEvent.xavi"
            except AssertionError as e:
                errors.append(e)
                raise

            try:
                assert json.loads(message.message) == {"help": "me"}
            except AssertionError as e:
                errors.append(e)
                raise

        monkeypatch.setattr(SNSMessage, "publish", mock_publish)

        (
            request,
            response,
        ) = insanic_application_with_event_polling.test_client.get(
            "/tests/event/"
        )
        assert response.status == 200
        assert response.json == {"help": "me"}

        if errors:
            raise errors[0]

    def test_publish_event_decorator_even_if_publishing_error(
        self,
        create_global_sns,
        insanic_application_with_event_polling,
        monkeypatch,
    ):

        BotoSession.session = None

        async def mock_publish(message):
            raise Exception("AAAAHHHHHH SOMETHING WENT WRONG!")

        monkeypatch.setattr(SNSMessage, "publish", mock_publish)

        (
            request,
            response,
        ) = insanic_application_with_event_polling.test_client.get(
            "/tests/event/"
        )
        assert response.status == 200
        assert response.json == {"help": "me"}


import wntr
import networkx as nx
import pandas as pd
import numpy as np
# networkX图

# Create a water network model
inp1 = "Net3.inp"
inp2 = "cs11021.inp"
#wn = simulation.network.WaterNetworkModel(inp1)

#G = wn.get_graph()
'''
node_name = '123'
# 该图存储为嵌套字典。可以使用以下方法访问节点和链接（请注意，NetworkX 中的链接称为边缘）
print(G.node[node_name])
print(G.adj[node_name])'''

#rint(G.order())  # 返回管网节点数
#print(len(G.terminal_nodes()))
#nxG = nx.DiGraph(G)

'''
k2 = []
for k,v in kvdegree.items():
    if v>2:
        k2.append(k)
print(len(k2))
print(k2)'''

def computeDegree(wnModel):
    G = wnModel.get_graph()
    kvdegree = G.degree()
    k3 = []
    for k in kvdegree.keys():
        if kvdegree[k] > 2:
            k3.append(k)
    #print(k3)
    return k3

#wn = simulation.network.WaterNetworkModel(inp1)
#print(wn.nodes._data['10']._coordinates)
# n
def computeInpCoor(inp):
    wn = wntr.network.WaterNetworkModel(inp)
    nodeInpDirt = {}
    for i in wn.node_name_list:
        #print(type(wn.nodes._data[i]._coordinates))
        nodeInpDirt[i] = wn.nodes._data[i]._coordinates
    return nodeInpDirt

# 拿出已有监测点的坐标数据
def computeCoor():
    wqmonitorfile = "D:\\Git\\Python-Learning\\wntrdemo\\wqmonitors.csv"
    pfile = pd.read_csv(wqmonitorfile, header=None)
    p = np.array(pfile)
    nodeDirt = {}
    for i in range(p.shape[0]):
        coorList = []
        coorList.append(p[i][3])
        coorList.append(p[i][4])
        nodeDirt[p[i][0]] = tuple(coorList)
    return nodeDirt

if __name__=="__main__":
    import math
    #nodeCoor = computeCoor()
    inp2 = "F:\AWorkSpace\Python-Learning-Data\cs11021.inp"
    #nodeInpCoor = computeInpCoor(inp2)


# 아이템 별 주문 개수와 총량

import pandas as pd

file_path = 'C:/Users/yoona/OneDrive/Desktop/4차산업혁명 빅데이터/6주차/chipotle.tsv'
chipo = pd.read_csv(file_path, sep = '\t')

# item 당 주문 개수 - count()
# item_name과 order_id를 그룹화
order_count = chipo.groupby('item_name')['order_id'].count()
print(order_count[:10])

# item 당 주문 총량 - sum()
# item_name과 quantity를 그룹화
item_quantity = chipo.groupby('item_name')['quantity'].sum()
print('------------------------------')
print(item_quantity[:10])


import socket
import random
def sendrecv(sock, msg):
  if type(msg) == str: msg = msg.encode()
  sock.send(msg)
  recvdata = sock.recv(1000).decode()
  return recvdata.strip()
def interactive(sock):
  while True:
    S = input('> ')
    print(sendrecv(sock,S))

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_addr = ('mq.eatpwnnosleep.com', 12345)
sock.connect(server_addr)
p = 131
quad = [[0]*32 for i  in range(32)]
A = [[0]*32 for i  in range(32)]
uni = [0]*32
c = 0
pasre = sock.recv(100000).decode().split('+')
for elem in pasre:
  es = elem.strip().split('x')
  if len(es) == 1:
    c = int(es[0])
  elif len(es) == 2:
    uni[int(es[1])-1]=int(es[0])
  else:
    a = int(es[1])-1
    b = int(es[2])-1
    quad[a][b] = int(es[0])
    quad[b][a] = int(es[0])

for i in range(32):
  for j in range(32):
    A[i][j]=quad[i][j]
    if i==j: A[i][j] = 2*A[i][j]

print(A)
#### parse factor
original = int(sendrecv(sock,'\x00'*32)[2:],16)
B = [0]*32
for i in range(32):
  query = '\x00'*i+'\x01'+'\x00'*(31-i)
  newval = int(sendrecv(sock,query)[2:],16)
  B[i] = (newval - original - uni[i] - quad[i][i])%p
print()
print()
print(B)


import socket

HOST='127.0.0.1'
PORT=8888
s = socket.socket()
s.bind((HOST, PORT))

s.listen(5)

while True:
    c, addr = s.accept()
    print ('Recieved connection :', addr)
    print (c.recv(1024).decode())
    c.close()


from datetime import datetime

from odoo.exceptions import UserError
from odoo.tests import tagged, common

from ..wizard.import_datev_wizard import (
    ImportWizard as ImportWizard,
    COL_UMSATZ,
    COL_KONTO,
    COL_GEGENKONTO,
    COL_SOLLHABEN,
    COL_UMSATZ_2
)

T = "datevimport"

class WizardCase(common.TransactionCase):
    konto = COL_KONTO
    gegen = COL_GEGENKONTO

    def wizard(self, **kwargs):
        return self.env[ImportWizard._name].create(kwargs)

    def _create_account(self, code):
        return self.env["account.account"].create(
            dict(
                name="test account",
                code=code,
                user_type_id=self.env["account.account.type"].browse(1).id,
                reconcile=True,
            )
        )

@tagged(T)
class TestDebitOrCredit(WizardCase):
    def test_debit_or_credit_a(self):
        dummy_line = {COL_SOLLHABEN: "S"}
        self.assertEqual(
            self.wizard()._debit_or_credit(dummy_line, is_balance_account=True),
            "debit",
        )

    def test_debit_or_credit_b(self):
        dummy_line = {COL_SOLLHABEN: "S"}
        self.assertEqual(
            self.wizard()._debit_or_credit(dummy_line, is_balance_account=False),
            "credit",
        )

    def test_debit_or_credit_c(self):
        dummy_line = {COL_SOLLHABEN: "H"}
        self.assertEqual(
            self.wizard()._debit_or_credit(dummy_line, is_balance_account=True),
            "credit",
        )

    def test_debit_or_credit_d(self):
        dummy_line = {COL_SOLLHABEN: "H"}
        self.assertEqual(
            self.wizard()._debit_or_credit(dummy_line, is_balance_account=False),
            "debit",
        )

@tagged(T)
class TestReverseAccount(WizardCase):
    def test_balance_account_name_a(self):
        import_wizard = self.wizard(balance_account=self.konto)
        self.assertEqual(import_wizard._non_balance_acc(), self.gegen)

    def test_balance_account_name_b(self):
        import_wizard = self.wizard(balance_account=self.gegen)
        self.assertEqual(import_wizard._non_balance_acc(), self.konto)

@tagged(T)
class TestGetDate(WizardCase):
    def test_get_date_a(self):
        import_wizard = self.wizard(year=2011, month=11)
        line = {"Belegdatum": "1511"}
        self.assertEqual(
            import_wizard._get_date(line), datetime(year=2011, month=11, day=15)
        )

    def test_get_date_b(self):
        import_wizard = self.wizard(year=1234, month=1)
        line = {"Belegdatum": "0101"}
        self.assertEqual(
            import_wizard._get_date(line), datetime(year=1234, month=1, day=1)
        )

    def test_get_date_c(self):
        import_wizard = self.wizard(year=2000)
        line = {"Belegdatum": "00"}
        with self.assertRaises(UserError):
            import_wizard._get_date(line)

    def test_get_date_d(self):
        import_wizard = self.wizard(year=2000)
        line = {"Belegdatum": ""}
        with self.assertRaises(UserError):
            import_wizard._get_date(line)

    def test_get_date_e(self):
        """Test that date is increased to passed month."""
        import_wizard = self.wizard(year=1234, month=2)
        line = {"Belegdatum": "0101"}
        self.assertEqual(
            import_wizard._get_date(line), datetime(year=1234, month=2, day=1)
        )

@tagged(T)
class TestGetAccount(WizardCase):
    def test_existing_account(self):
        code = "1234"
        account = self._create_account(code)
        self.assertEqual(self.wizard()._get_account_from_code(code), account)

    def test_not_existing_account(self):
        code = "123456"
        with self.assertRaises(UserError):
            self.wizard()._get_account_from_code(code)

@tagged(T)
class TestMoveType(WizardCase):
    code = 0

    def journal(self, journal_type):
        self.code += 1
        return self.env["account.journal"].create(
            dict(type=journal_type, name="", code=str(self.code))
        )

    @staticmethod
    def lines(symbol):
        return [{COL_SOLLHABEN: symbol, "Umsatz (ohne Soll/Haben-Kz)": 10}]

    def run_test(self, journal_type, symbol, balance_account, result):
        journal = self.journal(journal_type)
        lines = self.lines(symbol)
        import_wizard = self.wizard(balance_account=balance_account,)
        self.assertEqual(
            import_wizard._get_move_type(journal_id=journal, lines=lines), result
        )

    def test_sale_s_konto(self):
        self.run_test("sale", "S", self.konto, "out_invoice")

    def test_sale_s_gegen(self):
        self.run_test("sale", "S", self.gegen, "out_refund")

    def test_sale_h_gegen(self):
        self.run_test("sale", "H", self.gegen, "out_invoice")

    def test_sale_h_konto(self):
        self.run_test("sale", "H", self.konto, "out_refund")

    def test_purchase_s_konto(self):
        self.run_test("purchase", "S", self.konto, "in_refund")

    def test_purchase_s_gegen(self):
        self.run_test("purchase", "S", self.gegen, "in_invoice")

    def test_purchase_h_gegen(self):
        self.run_test("purchase", "H", self.gegen, "in_refund")

    def test_purchase_h_konto(self):
        self.run_test("purchase", "H", self.konto, "in_invoice")

@tagged(T)
class TestValidateLine(WizardCase):
    @staticmethod
    def _line(umsatz, symbol, konto, gegenkonto):
        return {
            COL_UMSATZ: umsatz,
            COL_SOLLHABEN: symbol,
            COL_KONTO: konto,
            COL_GEGENKONTO: gegenkonto,
            COL_UMSATZ_2: ""
        }

    def test_validate_valid_line(self):
        self._create_account("12345")
        self._create_account("54321")
        line = self._line("10", "S", "12345", "54321")
        self.wizard()._convert_and_validate_line(line)
        self.assertEqual(line, {**line, COL_UMSATZ: 10})

    def test_validate_valid_line_comma(self):
        self._create_account("12345")
        self._create_account("54321")
        line = self._line("10,3", "S", "12345", "54321")
        self.wizard()._convert_and_validate_line(line)
        self.assertEqual(line, {**line, COL_UMSATZ: 10.3})

    def test_validate_line_wrong_value(self):
        self._create_account("12345")
        self._create_account("54321")
        line = self._line("A", "S", "12345", "54321")
        with self.assertRaises(UserError):
            self.wizard()._convert_and_validate_line(line)

    def test_validate_line_wrong_symbol(self):
        self._create_account("12345")
        self._create_account("54321")
        line = self._line("10", "X", "12345", "54321")
        with self.assertRaises(UserError):
            self.wizard()._convert_and_validate_line(line)


# Зуйкевич Лидия, 3 курс, 7 группа
# Вариант 7, задание 2. Аффинный шифр
# шифртекст: лтмявфтду
# расшифрованный текст: грейпфрут

def create_alphabet():
    alphabet = []
    for i in range(ord('а'), ord('е') + 1):
       alphabet += chr(i)
    alphabet += 'ё'
    for i in range(ord('ж'), ord('я') + 1):
       alphabet += chr(i)
    return alphabet

def gcd_extended(a, b):
    if a == 0:
        return b, 0, 1
    gcd, x1, y1 = gcd_extended(b % a, a)
    x = y1 - (b // a) * x1
    y = x1
    return gcd, x, y

def find_inverse(a, m):
    gcd, x, y = gcd_extended(a, m)
    if gcd == 1:
        return (x % m + m) % m

def get_ciphertext(alphabet):
    str = "лтмявфтду"
    # str = input("Введите шифртекст: ")
    print("Шифртекст: ", str)
    ciphertext = list(str)
    ciphertext_codes = [0] * len(ciphertext)
    for i in range(len(ciphertext)):
        ciphertext_codes[i] = alphabet.index(ciphertext[i])
    return ciphertext_codes

def decrypt(ciphertext_codes, a, b, alphabet):
    m = 33
    inv = find_inverse(a, m)
    answer = ""
    for i in range(len(ciphertext_codes)):
        answer += alphabet[(inv * (ciphertext_codes[i] - b)) % m]
    print("Расшифрованный текст: ", answer)

alphabet = create_alphabet()
ciphertext_codes = get_ciphertext(alphabet)
decrypt(ciphertext_codes, 17, 27, alphabet)


"""
Given a string, sort it in decreasing order based on the frequency of characters.
Input:
"tree"

Output:
"eert"

Time O(nlogk) and space O(n)
"""

class Solution:
    def frequencySort(self, s: str) -> str:
        cnt = collections.Counter(s)

        heap = [(-v, k) for k, v in cnt.items()]
        heapq.heapify(heap)

        res = []

        while heap:
            v, k = heapq.heappop(heap)
            res += k * -v
        return ''.join(res)


# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
        l1,l2 = headA, headB
        while l1 != l2:         #either are gonna be the same(intersection) or they are both going to be null (no intersection)
            l1 = l1.next if l1 else headB   # if l1.next == None, we move to the starting of the other linked list
            l2 = l2.next if l2 else headA   # if l2.next == None, we move to the starting of the first linked list
        return l1


import sys, fileinput

class Piesa():
    def __init__(self, inaltime, latime, contact, points):
        self.inaltime = inaltime
        self.latime = latime
        self.contact = contact
        self.points = points

def pattern1(yrel):
    pattern = ''

    for x in range(7):
        for y in range(15):
            if bazin[yrel + y][x] == 1:
                pattern += str(y)
                break
    return pattern

def liber(piesa, x, y):
    liber = True
    for i in range(piesa.latime):
        for j in range(piesa.inaltime):
            if piesa.points[j * piesa.latime + i] == 1:
                if bazin[y + j][x + i] == 1:
                    liber = False
                    return liber

    return liber

def landing(piesa, x, y):
    landa = False
    for i in range(len(piesa.contact)):
        if bazin[y + piesa.contact[i]][x + i] == 1:
            landa = True
            break
    return landa

def margini(piesa, x, y):
    stanga = 0
    dreapta = WIDEBAZIN - piesa.latime

    for jj in range(x - 1, -1, -1):
        if not liber(piesa, jj, y):
            stanga = max(stanga, jj + 1)
            break

    for jj in range(x + 1, WIDEBAZIN - piesa.latime + 1):

        if not liber(piesa, jj, y):
            dreapta = min(dreapta, jj - 1)
            break

    return stanga, dreapta

def afiseaza(n):
    for i in range(10, -10, -1):
        try:
            print(bazin[n - i])
        except:
            None

def updatebazin(piesa, x, y):  # umple bazinul cu piesa noua

    for i in range(piesa.latime):
        for j in range(piesa.inaltime):
            if piesa.points[j * piesa.latime + i] == 1:
                bazin[y + j][x + i] = 1

# ------------------------------- input ----------------------------------------------

if len(sys.argv) > 1:
    fil = open(sys.argv[1])
else:
    fil = fileinput.input(files='intrari17a22.txt')

move = []

for line in fil:
    line = line.strip()
    for i in range(len(line)):
        misc = -1 if line[i] == '<' else 1
        move.append(misc)

lungimeintrare = len(move)

# ------------------------------- input ----------------------------------------------

istoric = dict()

linie = Piesa(1, 4, [1, 1, 1, 1], [1, 1, 1, 1])
trefla = Piesa(3, 3, [2, 3, 2], [0, 1, 0, 1, 1, 1, 0, 1, 0], )
lintors = Piesa(3, 3, [3, 3, 3], [0, 0, 1, 0, 0, 1, 1, 1, 1], )
stalp = Piesa(4, 1, [4], [1, 1, 1, 1])
patrat = Piesa(2, 2, [2, 2], [1, 1, 1, 1])

piese = [linie, trefla, lintors, stalp, patrat]
MAXHIGH = 3
WIDEBAZIN = 7
NUMARPIESE = 5
ESTIMATBAZIN = 2000  # daca este mai mare este mai sigur, pus asa ptr timp
TOTALROCK = 1000000000000  # 2022 pentru partea 1

print(lungimeintrare)
bazin = [[0 for i in range(WIDEBAZIN)] for j in range(ESTIMATBAZIN * MAXHIGH)]
bazin.append([1 for i in range(WIDEBAZIN)])
nr = 0
bottom = len(bazin) - 1
indexmove = 0
gasitrepetare = False
bottomrelativ=0
while nr < TOTALROCK:

    xstart = 2
    ystart = bottom - 3
    piesa = piese[nr % NUMARPIESE]
    ystart -= piesa.inaltime
    landi = False
    land = False  # pozitia urmatoate blocata
    bucla = 0
    pattern = ''
    while not landi:

        if bucla % 2 == 0:

            marginestanga, marginedreapta = margini(piesa, xstart, ystart)
            xstart += move[indexmove]

            xstart = marginedreapta if xstart > marginedreapta else xstart
            xstart = marginestanga if xstart < marginestanga else xstart
            indexmove =(indexmove+1)%lungimeintrare
            # indexmove+=1
            # indexmove = 0 if indexmove == lungimeintrare else indexmove

        else:
            if not land:
                ystart += 1

        if land:
            if landing(piesa, xstart, ystart):
                landi = True

        land = landing(piesa, xstart, ystart)

        bucla += 1

    updatebazin(piesa, xstart, ystart)

    bottom = min(ystart, bottom)

    nr += 1

    pattern = str(nr % NUMARPIESE) + '.' + str(indexmove) + '.' + pattern1(bottom)

    if pattern in istoric and not gasitrepetare:
        gasitrepetare = True
        index1 = istoric[pattern][0]
        nr1 = istoric[pattern][1]
        bottomrelativ = (bottom - index1) * ((TOTALROCK - nr) // (nr - nr1))
        nr = TOTALROCK - (TOTALROCK - nr) % (nr - nr1)
    else:
        istoric[pattern] = [bottom, nr]

print('Raspuns partea 1 a / 2 a ', len(bazin) - bottom - bottomrelativ - 1)


import os

import requests

class QiwiApi:
    """
    Класс реализующий запросы к КИВИ для получения информации по платежам
    """

    def __init__(self):
        self.api_access_token = os.environ.get('api_access_token')
        self.session = requests.Session()
        self.session.headers = {
            'Accept': 'application/json',
            'authorization': 'Bearer ' + self.api_access_token,
            'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 '
                          'Safari/537.36 '
        }

    def pay_status(self, pay_id):
        response = self.session.get(
            f'https://api.qiwi.com/partner/bill/v1/bills/{pay_id}',
        ).json()
        if not response.get('status'):
            return None
        return response['status']['value']

    def create_payment(self, pay_id, amount):
        data = {
            "amount": {
                "currency": "RUB",
                "value": f"{amount}.00"
            },
            "expirationDateTime": "2023-12-10T09:02:00+03:00"
        }
        response = requests.put(f'https://api.qiwi.com/partner/bill/v1/bills/{pay_id}', json=data).json()
        if response.get('payUrl'):
            return response
        return None


import copy
import re
import numpy as np
from colorama import Fore

class Sudoku(object):
    def __init__(self):
        self.cell = {}
        self.solved = None

    def load_game(self, fn):
        with open(fn, 'r') as f:
            for line in f:
                line = line.strip()
                if line == "":
                    continue
                m = re.match('(\d)x(\d)\s*(\d)', line)
                if m is None:
                    continue
                key = m.group(1) + "x" + m.group(2)
                self.cell[key] = int(m.group(3))
        self.initial_cell = copy.copy(self.cell)

        self.set_grid()

    def get_cell(self, x, y):
        key = f'{x}x{y}'
        if key in self.cell:
            return self.cell[key]
        else:
            return 0

    def set_grid(self):
        global grid
        grid = a = [[self.get_cell(x, y) for x in range(9)] for y in range(9)]
        print(np.matrix(grid))

    def draw(self):
        for y in range(9):
            if y % 3 == 0:
                print(Fore.WHITE + "------------")
            for x in range(9):
                if x % 3 == 0:
                    print(Fore.WHITE + "|", end="")
                key = f'{x}x{y}'
                if key in self.cell:
                    color = Fore.RED
                    if key in self.initial_cell:
                        color = Fore.WHITE

                    v = color + str(self.cell[key])
                else:
                    v = Fore.WHITE + " "
                print(v, end="")

            print()
        print()

    # セルを全て舐めて、正解が１個のセルを決定する
    def step1(self):
        num_solved = 0
        for x in range(9):
            for y in range(9):
                key = f'{x}x{y}'
                c = self.peek(x, y)

                if c is None:
                    continue
                if len(c) == 1:
                    self.cell[key] = c[0]
                    num_solved += 1
                elif len(c) == 0:
                    print(f'step1 {key} no entry')
                    return -1
        return num_solved

    # 空きのセルに候補の数字のリストを設定
    def step2(self):
        remain = {}
        for x in range(9):
            for y in range(9):
                key = f'{x}x{y}'
                c = self.peek(x, y)
                if c is None:
                    continue
                if len(c) > 1:
                    #self.cell[key] = c
                    #print(f'{key} {c}')
                    remain[key] = c

        return remain

    def issolved(self):
        if self.solved:
            return True

        for x in range(9):
            for y in range(9):
                key = f'{x}x{y}'
                if key not in self.cell:
                    return False
        self.solved = True
        return True

    # 指定セルの設置可能数値のリストを取得
    def peek(self, x, y):
        key = f'{x}x{y}'
        if key in self.cell:
            return None
        hlist = self.getHolizonValue(y)
        #print(f'h = {hlist}')
        vlist = self.getVerticalValue(x)
        #print(f'v = {vlist}')
        clist = self.get9CellValue(x, y)
        #print(f'c = {clist}')
        # 現在のセル＋縦リスト＋横リストの重複しないセットを取得
        other_list = set(hlist + vlist + clist)
        #print(f'peek {key} {other_list}')
        candidate = []
        for v in range(1, 10):
            if v not in other_list:
                candidate.append(v)

        return candidate

    # 未設定のセル数を取得
    def get_num_remain(self):
        num = 0
        for x in range(9):
            for y in range(9):
                key = f'{x}x{y}'
                if key in self.cell:
                    c = self.cell[key]
                    if type(c) is list and len(c) > 1:
                        num += 1
                else:
                    num += 1
        return num

    # 横方向の数値のリストを取得
    def getHolizonValue(self, y):
        values = []
        for x in range(9):
            key = f'{x}x{y}'
            if key in self.cell and type(self.cell[key]) is int:
                values.append(self.cell[key])

        return values;

    # 縦方向の数値リストを取得
    def getVerticalValue(self, x):
        values = []
        for y in range(9):
            key = f'{x}x{y}'
            if key in self.cell and type(self.cell[key]) is int:
                values.append(self.cell[key])

        return values;

    # 指定の９セル内の数値リストを取得
    def get9CellValue(self, x, y):
        values = []
        base_x = x // 3 * 3
        base_y = y // 3 * 3
        for x in range(3):
            for y in range(3):
                key = f'{base_x + x}x{base_y + y}'
                if key in self.cell and type(self.cell[key]) is int:
                    values.append(self.cell[key])
        return values;

    def solve_basic(self):
        nstep = 0
        while True:
            nstep += 1
            print(f'solve step {nstep}')
            n = self.step1()
            self.draw()
            if n < 0:
                return -1
            if n == 0:
                break
            #if n > 0:
            #    self.draw()
        return nstep

    def solve2(self, depth=0):
        print(f'solve2 depth {depth}')
        self.draw()
        num_try = 0
        if depth == 0:
            self.cell_current = copy.copy(self.cell)
        if depth >= 10:
            print('depth too deep')
            return -2
        remain = self.step2()
        remain_sorted = sorted(remain.items(), key=lambda x:len(x[1]))
        print(f'remain {remain_sorted}')

        for ntry in range(len(remain_sorted)):
            print(f'solve2 loop ntry {ntry} depth {depth}')
            if num_try > 10:
                print('retry count over')
                break
            if len(remain_sorted) == 0:
                print('--------- no list ----')
                break
            mark_cell = remain_sorted[ntry]
            for i in range(len(mark_cell[1])):
                print(f'trying depth {depth} {i} {mark_cell[1]} {mark_cell[0]} {mark_cell[1][i]}')
                self.cell[mark_cell[0]] = mark_cell[1][i]
                solve_ret = self.solve()
                print(f'solve_ret {solve_ret}')
                if solve_ret > 0:
                    print(f'recursive call solve2 {depth + 1}')
                    solve2_ret = self.solve2(depth + 1)
                    print(f'return from solve2 {depth + 1}')
                    if solve2_ret == 0 and depth == 0:
                        return 0
                    #if solve2_ret < 0 and depth > 0:
                    #    return -1
                    continue
                else:
                    print(f'------- can not solve depth {depth} -----')
                    self.cell = copy.copy(self.cell_current)
                    if depth > 0:
                        return -1
            print(f'--- end of mark loop depth {depth}')
            self.cell = copy.copy(self.cell_current)

        return 0

    def solve(self, deep=0):
        if self.issolved():
            return

        self.draw()
        if self.solve_basic() < 0:
            return
        if self.issolved():
            print("+++++++++ SOLVED ++++++++++++")
            return

        remain = self.step2()
        remain_sorted = sorted(remain.items(), key=lambda x:len(x[1]))
        if len(remain_sorted) == 0:
            return

        #print(f'remain {remain_sorted}')
        mark_cell = remain_sorted[0]
        for i in range(len(mark_cell[1])):
            copy_cell = copy.copy(self.cell)
            self.cell[mark_cell[0]] = mark_cell[1][i]
            solve3_ret = self.solve(deep + 1)
            self.cell = copy.copy(copy_cell)

if __name__ == '__main__':
    sudoku = Sudoku()
    sudoku.load_game('sudoku_ex/ex6.txt')
    sudoku.draw()

    sudoku.solve()

#    solve()


"Implementation based on https://github.com/cmavro/Graph-InfoClust-GIC"

import numpy as np
import scipy.sparse as sp
import torch
import torch.nn as nn
from torch_geometric.datasets import Planetoid
import os, sys
cur_dir = os.path.dirname(os.path.realpath(__file__))
sys.path.append('%s/models' % cur_dir)
sys.path.append('%s/utils/' % cur_dir)
print('aaa')
print(sys.path)
from gic import GIC
from logreg import LogReg
import process
from torch_geometric.utils import to_scipy_sparse_matrix, add_self_loops
from sklearn.metrics import roc_auc_score
from sklearn.metrics import average_precision_score

torch.manual_seed(1234)

import statistics
import argparse

def get_roc_score(edges_pos, edges_neg, embeddings, adj_sparse):
    "from https://github.com/tkipf/gae"

    score_matrix = np.dot(embeddings, embeddings.T)

    def sigmoid(x):
        return 1 / (1 + np.exp(-x))

    # Store positive edge predictions, actual values
    preds_pos = []
    pos = []
    for edge in edges_pos:
        preds_pos.append(sigmoid(score_matrix[edge[0], edge[1]])) # predicted score
        pos.append(adj_sparse[edge[0], edge[1]]) # actual value (1 for positive)

    # Store negative edge predictions, actual values
    preds_neg = []
    neg = []
    for edge in edges_neg:
        preds_neg.append(sigmoid(score_matrix[edge[0], edge[1]])) # predicted score
        neg.append(adj_sparse[edge[0], edge[1]]) # actual value (0 for negative)

    # Calculate scores
    preds_all = np.hstack([preds_pos, preds_neg])
    labels_all = np.hstack([np.ones(len(preds_pos)), np.zeros(len(preds_neg))])

    #print(preds_all, labels_all )

    roc_score = roc_auc_score(labels_all, preds_all)
    ap_score = average_precision_score(labels_all, preds_all)
    return roc_score, ap_score

cuda0 = torch.cuda.is_available()#False
# training params
batch_size = 1
nb_epochs = 2000
patience = 50
lr = 0.001
l2_coef = 0.0
drop_prob = 0.0
hid_units = 16
sparse = True
nonlinearity = 'prelu' # special name to separate parameters

beta = 100
num_clusters = int(128)
alpha = 0.5

cuda0 = torch.cuda.is_available()
torch.cuda.empty_cache()

def CalGIC(edge_index,features,dataset):
    nb_nodes = features.size(0)
    ft_size = features.size(1)
    features = torch.reshape(features,(1,features.size(0),features.size(1)))
    sp_adj = to_scipy_sparse_matrix(edge_index)
    sp_adj = process.normalize_adj(sp_adj + sp.eye(sp_adj.shape[0]))

    sp_adj = process.sparse_mx_to_torch_sparse_tensor(sp_adj)
    if cuda0:
        features = features.cuda()
        sp_adj = sp_adj.cuda()

    b_xent = nn.BCEWithLogitsLoss()
    b_bce = nn.BCELoss()
    model = GIC(nb_nodes,ft_size, hid_units, nonlinearity, num_clusters, beta)
    optimiser = torch.optim.Adam(model.parameters(), lr=lr, weight_decay=l2_coef)
    cnt_wait = 0
    best = 1e9
    best_t = 0
    val_best = 0
    if cuda0:
        model.cuda()
    for epoch in range(nb_epochs):
        model.train()
        optimiser.zero_grad()
        idx = np.random.permutation(nb_nodes)
        shuf_fts = features[:, idx, :]
        lbl_1 = torch.ones(batch_size, nb_nodes)
        lbl_2 = torch.zeros(batch_size, nb_nodes)
        lbl = torch.cat((lbl_1, lbl_2), 1)
        if cuda0:
            shuf_fts = shuf_fts.cuda()
            lbl = lbl.cuda()
        logits, logits2  = model(features, shuf_fts, sp_adj, sparse, None, None, None, beta)
        loss = alpha* b_xent(logits, lbl)  + (1-alpha)*b_xent(logits2, lbl)
        if loss < best:
            best = loss
            best_t = epoch
            cnt_wait = 0
            torch.save(model.state_dict(), dataset+'-link.pkl')
        else:
            cnt_wait += 1
            if cnt_wait == patience:
                break
            loss.backward()
            optimiser.step()
    model.load_state_dict(torch.load(dataset+'-link.pkl'))

    embeds, _,_, S= model.embed(features, sp_adj if sparse else adj, sparse, None, beta)
    embs = embeds[0, :]
    embs = embs / embs.norm(dim=1)[:, None]

    return embs.cpu().clone().detach()

def split_data(data,test_ratio,val_ratio):

    n_t = int(math.floor(test_ratio * data.num_edges/2)) #number of test positive edges
    n_v = int(math.floor(val_ratio * data.num_edges/2)) #number of validation positive edges

    row, col = data.edge_index
    mask = row < col
    row, col = row[mask], col[mask]
    perm = torch.randperm(row.size(0))
    row, col = row[perm], col[perm]
    r, c = row[:n_v], col[:n_v]
    data.val_pos = torch.stack([r, c], dim=0)
    r, c = row[n_v:n_v+n_t], col[n_v:n_v+n_t]
    data.test_pos = torch.stack([r, c], dim=0)
    r, c = row[n_v+n_t:], col[n_v+n_t:]
    data.train_pos = torch.stack([r, c], dim=0)

    edge_index_tp,_ = add_self_loops(data.edge_index)
    neg_edge_index = negative_sampling(edge_index_tp, num_nodes=data.num_nodes,\
            force_undirected=True)
    row, col = neg_edge_index
    mask = row<col
    row, col = row[mask], col[mask]
    perm = torch.randperm(row.size(0))
    row, col = row[perm], col[perm]
    data.val_neg = torch.stack([row[:n_v], col[:n_v]], dim=0)
    data.test_neg = torch.stack([row[n_v:n_v+n_t], col[n_v:n_v+n_t]], dim=0)
    data.train_neg = torch.stack([row[n_v+n_t:n_v+n_t+data.train_pos.size(1)],\
        col[n_v+n_t:n_v+n_t+data.train_pos.size(1)]], dim=0)
    return data

from torch_geometric.data import Data, DataLoader
from torch_geometric.transforms import NormalizeFeatures
import torch
import random
import math
from torch_geometric.utils import negative_sampling, to_networkx, is_undirected
import networkx as nx
dataset = Planetoid(root='data/', name='citeseer', transform=NormalizeFeatures())
data = dataset[0]

data = split_data(data, .1, .05)

edge_index = torch.cat((data.train_pos,data.train_pos[[1,0],:]),dim=1)
data_observed = Data(edge_index=edge_index)

x = CalGIC(data_observed.edge_index,data.x,'citeseer')

test_edges = torch.transpose(data.test_pos,0,1).cpu().detach().numpy()
test_edges_false = torch.transpose(data.test_neg,0,1).cpu().detach().numpy()
g = to_networkx(data)
adj_sparse = nx.adjacency_matrix(g)
sc_roc, sc_ap = get_roc_score(test_edges, test_edges_false, x.cpu().detach().numpy(), adj_sparse)

print('AUC', sc_roc, 'AP', sc_ap)


import json
from typing import Any

from fastapi import FastAPI
from fastapi import Request
# from fastapi.responses import FileResponse

import messages
import yandex
import database

app = FastAPI()

@app.post('/')
async def main(request: Request) -> Any:
    request_data = json.loads(
        await request.body()
    )

    user_id = request_data['session']['user']['user_id']
    user_registered = database.user_is_registered(user_id)
    print(user_registered)

    if yandex.REGISTER_DATA_REGEXP.match(request_data['request']['original_utterance']):
        response = yandex.register(user_id, request_data['request']['original_utterance'])

        return yandex.build_response(
            text=response,
            session_id=request_data['session']['session_id']
        )

    if not user_registered:
        text = messages.MESSAGE_START_USER_NOT_REGISTERED
        return yandex.build_response(
            text=text,
            session_id=request_data['session']['session_id']
        )

    # if chat just started
    if request_data['session']['new']:
        if user_registered:
            text = messages.MESSAGE_START_USER_REGISTERED

        return yandex.build_response(
            text=text,
            session_id=request_data['session']['session_id']
        )

    response = yandex.handler(
        command=request_data['request']['original_utterance'],
        user_id=user_id
    )

    return yandex.build_response(text=response, session_id=request_data['session']['session_id'])

# For Let's Encrypt
# @app.get('/.well-known/acme-challenge/{key}')
# async def acme_challenge(key: str):
#     return FileResponse(f'.well-known/acme-challenge/{key}')


from random import choice
import matplotlib.pyplot as plt
class RandomWalk():
    def __init__(self,num_points=5000):
        self.num_points=num_points

        self.x_values=[0]
        self.y_values=[0]

    def fill_walk(self):
        while len(self.x_values)<self.num_points:
            x_direction=choice([1,-1])
            x_distance=choice([0,1,2,3,4])
            x_step=x_direction*x_distance

            y_direction=choice([1,-1])
            y_distance=choice([0,1,2,3,4])
            y_step=y_direction*y_distance

            next_x=self.x_values[-1]+x_step
            next_y=self.y_values[-1]+y_step
#            print(x_direction)
#            print(x_distance)
#            print(x_step)
#            print(next_x)

            self.x_values.append(next_x)
            self.y_values.append(next_y)
#            print(self.x_values)

def main():
    a = RandomWalk()
    a.fill_walk()
    plt.plot(a.x_values,a.y_values)
    plt.show()

if __name__ == "__main__":
    main()


import re
import numpy as np

file1 = open('input.txt', 'r')
# file1 = open('exampleinput.txt', 'r')
lines = file1.readlines()
count = 0

i = 0
list = []
dicta = dict()
count = 0

for line in lines:
    list.append([])
    for x in line.strip():
        list[i].append(int(x))
        count += 1
    i += 1

list = np.array(list)
# print(list)

for x in range(1, len(list)-1):
    for y in range(1, len(list[0])-1):
        # print(list[x,y])
        # print(list[0:x,y])
        if any(num >= list[x, y] for num in list[0:x,y]):
            # print(list[x+1:len(list),y])
            if any(num >= list[x, y] for num in list[x+1:len(list),y]):
                # print(list[x,0:y])
                if any(num >= list[x, y] for num in list[x,0:y]):
                    # print(list[x,y+1:len(list[0])])
                    if any(num >= list[x, y] for num in list[x,y+1:len(list[0])]):
                        # print(x,y,list[x,y])
                        count -= 1
print(count)


#!bin/python

# Helpful script for converting fixed point signed numbers to decimal

def letter2num(x):
	if (x == "F" or x == "f"):
		return 15
	elif (x == "E" or x == "e"):
		return 14
	elif (x == "D" or x == "d"):
		return 13
	elif (x == "C" or x == "c"):
		return 12
	elif (x == "B" or x == "b"):
		return 11
	elif (x == "A" or x == "a"):
		return 10
	elif (x == "9"):
		return 9
	elif (x == "8"):
		return 8
	elif (x == "7"):
		return 7
	elif (x == "6"):
		return 6
	elif (x == "5"):
		return 5
	elif (x == "4"):
		return 4
	elif (x == "3"):
		return 3
	elif (x == "2"):
		return 2
	elif (x == "1"):
		return 1
	elif (x == "0"):
		return 0
	elif (x == "."):
		return 0

def num2letter(x):
	if (x == 15):
		return "F"
	elif (x == 14):
		return "E"
	elif (x == 13):
		return "D"
	elif (x == 12):
		return "C"
	elif (x == 11):
		return "B"
	elif (x == 10):
		return "A"
	elif (x == 9):
		return "9"
	elif (x == 8):
		return "8"
	elif (x == 7):
		return "7"
	elif (x == 6):
		return "6"
	elif (x == 5):
		return "5"
	elif (x == 4):
		return "4"
	elif (x == 3):
		return "3"
	elif (x == 2):
		return "2"
	elif (x == 1):
		return "1"
	elif (x == 0):
		return "0"
	else:
		return "."

def twoscomp(number, numdigits):
	s = ""
	for i in range(0, numdigits):
		if (number[i] != "."):
			s+=num2letter(15 - letter2num(number[i]))
		else:
			s+="."
	return s

def negative(number, dec):
	if (number[0] != "."):
		if (letter2num(number[0]) >= 8):
			return True
		else:
			return False
	else:
		if (letter2num(number[1]) >= 8):
			return True
		else:
			return False

def factor(digit, dec):
	if (digit < dec):
		dist = dec - digit - 1
	else:
		dist = dec - digit
	return 16**dist

def adder(numdigits, dec):
	if (numdigits == dec):
		return 1
	else:
		return 16**-(numdigits-dec-1)

tp = raw_input("Hex to dec? [Y/n]  (yes = hex -> dec, no = dec -> hex): ")
if (tp == "y" or tp == "Y" or tp == ""):
	hex2dec = True
else:
	hex2dec = False

while(1):
	if hex2dec:
		number = raw_input("Hex to dec: ")
		numdigits = len(number)
		position = number.find(".")
		if position == -1:
			position = numdigits

		isNeg = negative(number, position)
		if (isNeg):
			number = twoscomp(number, numdigits)
			scalar = -1
			add = adder(numdigits,position)
		else:
			scalar = 1
			add = 0

		converted = 0
		for i in range(0, numdigits):
			converted = converted + letter2num(number[i]) * factor(i,position)

		print (converted + add) * scalar
	else:
		numFbits = 16
		numDbits = 32
		number = float(raw_input("Dec to hex: "))
		number = int(number*(16**(numFbits/4)))
		if number > 0:
			converted = hex(number)
		else:
			number = 16**(numDbits/4 + numFbits/4) + number
			converted = hex(number)
		print(converted[0:len(converted)-(numFbits/4)] + "." + converted[len(converted)-(numFbits/4):len(converted)])


import codecs
import sys
import os
import http.cookies
import urllib
from typing import Optional

import db

import html_blocks
from html_config import MAIN_MENU_ITEMS, SUB_MENU_ITEMS

sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())
cookie = http.cookies.SimpleCookie(os.environ.get("HTTP_COOKIE"))
user_token = cookie.get("user_token")
#получить куки

header_start_format = '''
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Система управления тестовыми стендами NERO ELECTRONICS - {title}</title>
  <link href="/css/cssmain.css" rel="stylesheet">
{css}

{js}

{menu}

'''

menu_format = '''

                {login_data}

{mainmenu}

{submenu}
{rsubmenu}

'''
#

o = '''

{menu}

{submenu}

'''
footer_data = '''

© 2020 ООО «Неро Электроникс»

'''

def urlQuote(url):
    return urllib.parse.quote(url)

class HtmlBase:
    def redirect(url):
        print('''Content-Type: text/html; charset=UTF-8
Location: {0}

<meta http-equiv="refresh" content="0;url={0}" />
<title>Вы будете перенаправлены на другую страницу</title>

Перенаправление... Нажмите на ссылку если не было выполнено автоматическое перенаправление

'''.format(url))
        exit()

    def __init__(self, title: Optional[str] = '', page: Optional[str] = 'main.', submenu: Optional = None) -> None:
        self.access_info = db.access(user_token.value if user_token else '')
        self.http_headers = ['Content-Type: text/html; charset=UTF-8']
        self.title = title
        self.css_files = [f'/css/cssmain.css']
        self.css = []
        self.js_files = [f'/js/jquery-3.3.1.min.js']
        self.items = []
        self.scripts = []

        self.page, self.sub_page = page.split('.')
        self.submenu = submenu

    def menu_str(self):
        if self.access_info['login']:
            login_data = f'''
    Выйти
  '''
        else:
            login_data = f'''
    Войти
  '''

        menu = ['''
{}
'''.format(
            url,
            ' class="msel"' if self.page == name else '',
            100 / len(MAIN_MENU_ITEMS),
            text
            ) for text, name, url in MAIN_MENU_ITEMS]

        current_sub_menu_items = SUB_MENU_ITEMS[self.page]
        submenu = ['''{}'''.format(
            url,
            ' class="msel"' if self.sub_page == name else '',
            100 / len(current_sub_menu_items),
            text
            ) for text, name, url in current_sub_menu_items]

        rsubmenu = []
        if self.submenu:
            rsubmenu.append('{}'.format(self.submenu))

        return menu_format.format(login_data=login_data,
                                  mainmenu='\n'.join(menu),
                                  submenu='\n'.join(submenu),
                                  rsubmenu='\n'.join(rsubmenu)
                                  )

    def print(self):
        print('\n'.join(self.http_headers))

        print(header_start_format.format(
            title=self.title,
            #css = '  '.format('\n'.join(self.css)) if len(self.css) else '',
            css='\n'.join(['   <link href="{}" rel="stylesheet" type="text/css" />'.format(f) for f in self.css_files]),
            js='\n'.join(['  '.format(f) for f in self.js_files]),
            menu=self.menu_str()
            ))

        for item in self.items:
            print(str(item))

        print(footer_data)
        if len(self.scripts):
            print('  '.format('\n'.join(self.scripts)))
        print(' \n')

    def add(self, item):
        self.items.append(item)

    def add_block(self, tag, param: Optional[str] = '') -> html_blocks.Block:
        block = html_blocks.Block(tag, param)
        self.add(block)
        return block

    def add_js_files(self, *args) -> None:
        for filename in args:
            self.js_files.append(filename)

    def add_script(self, text) -> None:
        self.scripts.append(text)

    def add_css_files(self, *args):
        for filename in args:
            self.css_files.append(filename)

def print_header(page: Optional[str] = '', scripts=[], css=[]):
    access_info = db.access(user_token.value if user_token else '')

    if access_info['login']:
        logindata=' Выйти'.format(urllib.parse.quote(access_info['login']))
    else:
        logindata=' Войти'

    jsdata = ''.format('\n'.join(scripts)) if scripts else ''
    cssdata = ' '.format('\n'.join(css)) if css else ''

    print('''Content-Type: text/html; charset=UTF-8

<!DOCTYPE html>

        <meta charset="utf-8">
        <title>Система управления доступом NERO ELECTRONICS - {page}</title>
        <link href="/css/cssmain.css" rel="stylesheet">
        {cssdata}

{jsdata}

        {logindata}

'''.format(page=page, cssdata=cssdata, jsdata=jsdata, logindata=logindata))

def print_footer(scripts = None):
    jsdata = ''.format('\n'.join(scripts)) if scripts else ''
    print('''

© 2020 ООО «Неро Электроникс»

{}

'''.format(jsdata))

def check_access(admin = False):
    if admin:
        if user_token:

            res = db.access(user_token.value)
            if res['login']:
                return res
            else:
                HtmlBase.redirect('login.py')
        else:
            HtmlBase.redirect('login.py')


# -*- coding: utf-8 -*-
"""Eular Problem 11 - Largest product in a grid:
    In the 20×20 grid below, four numbers along a diagonal line have been
    marked in red. What is the greatest product of four adjacent numbers in
    the same direction(up, down, left, right, or diagonally) in the 20×20 grid?
"""
from . import timer

DESC = 'Largest product in a grid'
SOLUTION = 70600674

@timer.timeit
def solve():
    m = read_matrix('data/matrix1.txt')
    return find_greatest_product(m, 4)

def find_greatest_product(_matrix, factors):
    """ Finds the greatest product of (x * factors) adjacent integers in a matrix. """
    greatest_product = 0
    lines = scan_matrix_lines(_matrix)

    for sequence in lines:
        endpoint = len(sequence) - factors
        if len(sequence) < factors:
            continue
        i = 0
        while i <= endpoint:
            product = multiply(sequence, i, factors)
            if product > greatest_product:
                greatest_product = product
            i += 1

    return greatest_product

def get_rows(matrix):
    rows = []
    for i in range(len(matrix)):
        point = (0, i)
        inc = (1, 0)
        rows.append(extract_line(matrix, point, inc))
    return rows

def get_columns(matrix):
    cols = []
    for i in range(len(matrix)):
        point = (i, 0)
        inc = (0, 1)
        cols.append(extract_line(matrix, point, inc))
    return cols

def get_right_diagonals(matrix):
    """ Extracts all the right-facing diagonal lines of a matrix and returns
        them as a list.
    """

    diags = []

    # Scan right diagonals: bottom left to top left.
    for i in range(len(matrix) - 1, 0, -1):
        point = (0, i)
        inc = (1, 1)
        diags.append(extract_line(matrix, point, inc))

    # Scan right diagonals: top left to top right
    for i in range(len(matrix)):
        point = (i, 0)
        inc = (1, 1)
        diags.append(extract_line(matrix, point, inc))

    return diags

def get_left_diagonals(matrix):
    """ Extracts all the left-facing diagonal lines of a matrix and returns them
        as a list.
    """
    diags = []
    # Scan left diagonals: top left to top right
    for i in range(len(matrix)):
        point = (i, 0)
        inc = (-1, 1)
        diags.append(extract_line(matrix, point, inc))

    # Scan left diagonals: top right to bottom right
    for i in range(1, len(matrix)):
        point = (len(matrix) - 1, i)
        inc = (-1, 1)
        diags.append(extract_line(matrix, point, inc))
    return diags

def read_matrix(filename):
    """ Reads a file containing integers to a matrix(list of lists). """
    digits = []

    with open(filename) as f:
        for line in f.readlines():
            ints = [int(n) for n in line.split()]
            digits.append(ints)
    return digits

def scan_matrix_lines(matrix):
    """ Scans for all rows, columns, and diagonals in the given matrix and
        returns them as a list of lists.
    """
    lines = []
    lines.extend(get_rows(matrix))
    lines.extend(get_columns(matrix))
    lines.extend(get_right_diagonals(matrix))
    lines.extend(get_left_diagonals(matrix))
    return lines

def print_matrix(matrix):
    _str = ''
    for row in matrix:
        for col in row:
            # Format for 2 digit integers and fill zeros in.
            _str += '{:3}'.format(str(col).zfill(2))
        _str = _str.rstrip() + '\n'
    return _str

def extract_line(matrix, point, xyincrement):
    """ Takes an x by x matrix and scans a matrix for a list of items.

        Uses a starting point tuple (x, y) and an increment tuple(x-increment, y-increment).
        Starts the list from the x, y coordinate and goes in the increments given by xinc and yinc.
    """
    x, y = point[0], point[1]
    xinc, yinc = xyincrement[0], xyincrement[1]
    items = []

    while 0 <= x < len(matrix) and 0 <= y < len(matrix):
        items.append(matrix[y][x])
        x += xinc
        y += yinc
    return items

def multiply(alist, index, factors, product=1):
    # Base case: At index 0
    if index < 0 or index >= len(alist):
        # Out of bounds, just return 0?
        raise ValueError('index is out of bounds!')
        #  return 0
    elif factors == 1:
        return alist[index]
    else:
        return alist[index] * multiply(alist, index + 1, factors - 1, product)


import time

start_time = time.time()

list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
list2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]

count = 0

# outer loop
for x in list1:
    count += 1
    # inner loop
    for y in list2:
        count += 1

print(count)

# outer loop
for i in range(10):
    # inner loop
    for j in range(10):
        print(j, end=" ")
    print()

print(round(time.time() - start_time, 2))

# Exercise: Use Control flow and loops to solve a problem
num_list = [33, 42, 5, 66, 77, 22, 16, 79,
            36, 62, 78, 43, 88, 39, 53, 67, 89, 11]

for num in num_list:
    if num > 45:
        print("Over 45: ", num)
    else:
        print("Under 45: ", num)

for i in range(len(num_list)):
    if num_list[i] == 36:
        print("Number 36 found at index: ", i)

count = 0
for num in num_list:
    count += 1
    print(count)
    if num == 36:
        print("Found it")
        break


"""This is a generic handler that will write to and read from database and allow frontend to print result."""
import flask # run `pip install Flask` if this is not found
from flask import Flask, request, jsonify
#import flask_cors
import json
import requests
import os

app = Flask(__name__)
# flask_cors.CORS(app)
app.secret_key = 'super secret key'

def getLogname():
    return flask.session['username']

@app.route("/login", methods=['POST'])
# @flask_cors.cross_origin
def handle_login():
    print(request.json.get('username'))
    flask.session['username'] = request.json.get('username')
    print('logged in user is ', flask.session['username'])
    return jsonify({'status_code': 200}), 200

@app.route("/account", methods=['POST'])
#@flask_cors.cross_origin
def handle_newaccount():
    # creates account and logs in user
    username = request.json.get('username')
    flask.session['username'] = request.json.get('username')
    print('logged in user is ', flask.session['username'])
    resp = requests.put(url=f"https://straightforward-89f53-default-rtdb.firebaseio.com/users/{username}.json", data=json.dumps({'name': username, 'widgets': {0: {'type': "navigation", 'name': 'University Of Michigan'}}}))
    print(resp)
    #requests.post(url=f"https://straightforward-89f53-default-rtdb.firebaseio.com/users/{getLogname()}/widgets.json", data = [])
    return jsonify({'status_code': 200}), 200

@app.route("/", methods=['GET'])
def handle_logout():
    flask.session['username'] = ''
    return jsonify({'status_code': 200}), 200

@app.route("/getname", methods=['GET'])
def hello_user():
    resp = requests.get(url=f"https://straightforward-89f53-default-rtdb.firebaseio.com/users/{getLogname()}.json")
    return resp.json()

@app.route("/getwidgets", methods=['GET'])
def get_widget():
    try:
        resp = requests.get(url=f"https://straightforward-89f53-default-rtdb.firebaseio.com/users/{getLogname()}/widgets.json")
    except Exception:
        return jsonify({'status_code': 200}), 200
    print
    return resp.json()

@app.route("/addwidget", methods=['POST'])
def postwidget():
    resp = requests.get(url=f"https://straightforward-89f53-default-rtdb.firebaseio.com/users/{getLogname()}/widgets.json")
    resp_json = resp.json()
    req = request.json
    if isinstance(resp_json, str):
        resp_json = [resp_json]
    if isinstance(resp_json, dict):
        resp_json = resp_json.items()
        resp_json = list(resp_json)
    if resp_json:
        for item in resp_json:
            if not isinstance(item, tuple):
                if item['type'] == 'contacts' and item['name'] == req['name']:
                    return jsonify({'status_code': 304}), 304
                if item['type'] == 'music' and item['name'] == req['name']:
                    return jsonify({'status_code': 304}), 304
                if item['type'] == 'navigation' and item['name'] == req['name']:
                    return jsonify({'status_code': 304}), 304
            else:
                if item[1]['type'] == 'contacts' and item[1]['name'] == req['name']:
                    return jsonify({'status_code': 304}), 304
                if item[1]['type'] == 'music' and item[1]['name'] == req['name']:
                    return jsonify({'status_code': 304}), 304
                if item[1]['type'] == 'navigation' and item[1]['name'] == req['name']:
                    return jsonify({'status_code': 304}), 304

    print("returning 7, 200 code")

    cmd = f"curl -X POST https://straightforward-89f53-default-rtdb.firebaseio.com/users/{getLogname()}/widgets.json -d '{json.dumps(req)}' -H 'Content-Type: application/json'"
    os.system(cmd)
    return jsonify({'status_code': 200}), 200

@app.route("/deletewidget", methods=['DELETE'])
def deletewidget():
    resp = requests.get(url=f"https://straightforward-89f53-default-rtdb.firebaseio.com/users/{getLogname()}/widgets.json")
    resp_json = resp.json()
    req = request.json
    if isinstance(resp_json, str):
        resp_json = [resp_json]
    for item in resp_json:
        if resp_json[item]['name'] == req['name']:
            requests.delete(url=f"https://straightforward-89f53-default-rtdb.firebaseio.com/users/{getLogname()}/widgets/{item}.json")
            return jsonify({'status_code': 204}), 204
    return jsonify({'status_code': 404}), 404

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


import os

import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import Session

from app.orm import Server, Base
from app.service import power_off

HABR_TEST_DB_URL="HABR_TEST_DB_URL"

@pytest.fixture(scope="function")
def engine():
    if HABR_TEST_DB_URL not in os.environ:
        skip_reason_message: str = (
            f"Environment var with name {HABR_TEST_DB_URL!r} is not provided. "
            "Set this with a path to the real test database to run skipped tests."
        )
        pytest.skip(msg=skip_reason_message)

    engine = create_engine(
        os.environ[HABR_TEST_DB_URL],
        echo=False
    )
    Base.metadata.drop_all(engine)
    Base.metadata.create_all(engine)
    try:
        yield engine
    finally:
        Base.metadata.drop_all(engine, checkfirst=True)

@pytest.fixture
def session(engine):
    session = Session(engine)
    yield session

@pytest.fixture
def server(session):
    s = Server()
    s.ip = '127.0.0.1'
    s.hostname = 'home'
    s.power_on = True
    session.add(s)
    session.commit()
    return s

def test_presence(server):
    assert server.ip == '127.0.0.1'

def test_embedded_db(session, server):
    assert power_off(session, server) is True
    assert server.power_on is False


from keras.applications import VGG16
import numpy as np
from keras.applications import imagenet_utils
from keras.preprocessing.image import img_to_array
from keras.preprocessing.image import load_img
import matplotlib.pyplot as plt
import cv2
import sys

"""-----------------------导入测试图片------------------------"""
image_path='test_images/example_03.jpg'
# image_path=sys.argv[1]
# img=cv2.imread(image_path)
# cv2.imshow("test iamge",img)
# img=cv2.resize(img,(224,224))
# img=img.astype(np.float64)
# img[:,:,0]-=np.mean(img[:,:,0])
# img[:,:,1]-=np.mean(img[:,:,1])
# img[:,:,2]-=np.mean(img[:,:,2])
# img=img.reshape((1,224,224,3))

image = load_img(image_path, target_size=(224, 224))
image = img_to_array(image)

# preprocess the image by (1) expanding the dimensions and
# (2) subtracting the mean RGB pixel intensity from the
# ImageNet dataset
image = np.expand_dims(image, axis=0)
image = imagenet_utils.preprocess_input(image)
image_input=[image]
image_input=np.vstack(image_input)

"""------------------------用VGG去抽取特征---------------------"""
model = VGG16(weights="imagenet", include_top=False)
feature_maps=model.predict(image_input,batch_size=1)
print("feature map size:",np.shape(feature_maps))

"""------------------------打印前100张特征图--------------------"""
plt.figure()
for i in range(10):
    for j in range(10):
        sub_image=feature_maps[:,:,:,i*10+j]
        sub_image=sub_image.reshape((7,7))
        # sub_image/=np.max(sub_image)
        plt.subplot(10,10,i*10+j+1)
        plt.imshow(sub_image)

plt.savefig('output/VGG_feature_map.jpg')
plt.show()

sub_image=feature_maps[:,:,:,1]
sub_image=sub_image.reshape((7,7))
sub_image=cv2.resize(sub_image,(28,28))
cv2.imshow("feature map:",sub_image)

cv2.waitKey(0)


import wx
from lib.path import path

from gradientpanel import GradientPanel
import pluginutils as utils

from api import API
from datetime import datetime

class TitlePanel(GradientPanel):
    def __init__(self, frame):
        GradientPanel.__init__(self, frame, percent=0.35)

        self.frame = frame

        theme = path('images/themes') / API.config.theme_name

        self.statebmps = {}
        self.statebmps[API.media.STATE_PLAYING] = utils.get_bitmap(theme / "play.png")
        self.statebmps[API.media.STATE_STOPPED] = utils.get_bitmap(theme / "stop.png")
        self.statebmps[API.media.STATE_PAUSED] = utils.get_bitmap(theme / "pause.png")

        self.shufflebmps = {}
        self.shufflebmps[API.media.SHUFFLE_TRACK] = utils.get_bitmap(theme / "random_track.png")
        self.shufflebmps[API.media.SHUFFLE_ALBUM] = utils.get_bitmap(theme / "random_album.png")
        self.shufflebmps[API.media.SHUFFLE_NONE] = utils.get_bitmap(theme / "random_no.png")

        self.volumebmps = {}
        self.volumebmps["volume_mute"] = utils.get_bitmap(theme / "volume_mute.png")
        self.volumebmps["volume_low"] = utils.get_bitmap(theme / "volume_low.png")
        self.volumebmps["volume_medium"] = utils.get_bitmap(theme / "volume_medium.png")
        self.volumebmps["volume_high"] = utils.get_bitmap(theme / "volume_high.png")

        c1  = wx.Colour(34, 55, 84, wx.ALPHA_OPAQUE)
        c2  = wx.Colour(83, 120, 234, wx.ALPHA_OPAQUE)
        self.stripe = GradientPanel(self, c1, c1)
        self.stripe.SetBackgroundColour(c1)

        self.titles = [None, None, None]
        self.titles[0] = wx.StaticText(self.stripe, style=wx.ALIGN_RIGHT)
        self.titles[1] = wx.StaticText(self.stripe, style=wx.ALIGN_RIGHT)
        self.titles[2] = wx.StaticText(self.stripe, style=wx.ALIGN_RIGHT)

        self.wifi = wx.StaticText(self, -1, '--', style=wx.ALIGN_LEFT)

        font = self.titles[0].GetFont()
        font.SetPointSize(24)
        self.titles[0].SetFont(font)
        font.SetPointSize(18)
        self.titles[1].SetFont(font)
        font.SetPointSize(12)
        self.titles[2].SetFont(font)

        asizer = wx.BoxSizer(wx.HORIZONTAL)
        asizer.AddStretchSpacer()
        asizer.Add(self.titles[2], flag=wx.ALIGN_RIGHT|wx.ALIGN_BOTTOM)
        asizer.AddSpacer(20)
        asizer.Add(self.titles[1], flag=wx.ALIGN_RIGHT|wx.ALIGN_BOTTOM)
        asizer.AddSpacer(20)
        asizer.Add(self.titles[0], flag=wx.ALIGN_RIGHT|wx.EXPAND)
        asizer.AddSpacer(20)
        self.stripe.SetSizer(asizer)

        self.statebmp = wx.StaticBitmap(self)
        self.shufflebmp = wx.StaticBitmap(self)
        self.volumebmp = wx.StaticBitmap(self)
        self.quit = wx.StaticBitmap(self)
        bmp = utils.get_bitmap(theme / "quit.png")
        self.quit.SetBitmap(bmp)
        self.quit.SetSize(bmp.Size)
        self.nowplayingline1 = wx.StaticText(self, -1, 'artist', style=wx.ALIGN_RIGHT)
        self.nowplayingline2 = wx.StaticText(self, -1, 'song', style=wx.ALIGN_RIGHT)
        self.clock = wx.StaticText(self, -1, datetime.now().strftime('%H:%M'))
        font = self.clock.GetFont()
        font.SetPointSize(24)
        self.clock.SetFont(font)

        nsizer = wx.BoxSizer(wx.VERTICAL)
        nsizer.Add(self.nowplayingline1, flag=wx.ALIGN_CENTER|wx.EXPAND)
        nsizer.Add(self.nowplayingline2, flag=wx.ALIGN_CENTER|wx.EXPAND)

        ssizer = wx.BoxSizer(wx.HORIZONTAL)
        ssizer.Add(nsizer, flag=wx.ALIGN_CENTER)
        ssizer.AddSpacer(10)
        ssizer.Add(self.statebmp, flag=wx.ALIGN_CENTER)
        ssizer.AddSpacer(10)
        ssizer.Add(self.shufflebmp, flag=wx.ALIGN_CENTER)
        ssizer.AddSpacer(10)
        ssizer.Add(self.volumebmp, flag=wx.ALIGN_CENTER)
        ssizer.AddSpacer(10)
        ssizer.Add(self.quit, flag=wx.ALIGN_CENTER)
        self.ssizer = ssizer

        xsizer = wx.GridBagSizer(2, 3)
        xsizer.Add(self.wifi, (0,0), flag=wx.ALIGN_CENTER|wx.EXPAND)
        xsizer.Add(self.ssizer, (0,1), flag=wx.ALIGN_CENTER|wx.EXPAND)
        xsizer.Add(self.clock, (0,2), flag=wx.ALIGN_CENTER)
        xsizer.Add(self.stripe, (1,0), (1,3), flag=wx.ALIGN_RIGHT|wx.EXPAND|wx.ALIGN_CENTER)
        xsizer.AddGrowableCol(1)
        xsizer.AddGrowableCol(0)
        self.SetSizerAndFit(xsizer)

        utils.setColours(self)
        utils.setColours(self.stripe)

        self.timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.on_update)
        self.timer.Start(1000)

        self.stripe.stripe_timer = wx.Timer(self.stripe)
        self.stripe.Bind(wx.EVT_TIMER, self.on_stripe_update)
        self.stripe.stripe_timer.Start(100)

        self.quit.Bind(wx.EVT_LEFT_UP, self.on_quit)
        self.volumebmp.Bind(wx.EVT_LEFT_UP, API.media.toggle_mute)
        self.statebmp.Bind(wx.EVT_LEFT_UP, API.media.play_pause)
        self.shufflebmp.Bind(wx.EVT_LEFT_UP, API.media.change_shuffle)

        # os x text tends to erase background, so we no op
        self.titles[0].Bind(wx.EVT_ERASE_BACKGROUND, lambda e: None)
        self.titles[1].Bind(wx.EVT_ERASE_BACKGROUND, lambda e: None)
        self.titles[2].Bind(wx.EVT_ERASE_BACKGROUND, lambda e: None)
        self.nowplayingline1.Bind(wx.EVT_ERASE_BACKGROUND, lambda e: None)
        self.nowplayingline2.Bind(wx.EVT_ERASE_BACKGROUND, lambda e: None)
        self.wifi.Bind(wx.EVT_ERASE_BACKGROUND, lambda e: None)
        self.clock.Bind(wx.EVT_ERASE_BACKGROUND, lambda e: None)

        API.media.attach('current', self.check_current)
        API.media.attach('state', self.check_state)
        API.media.attach('shuffle', self.check_shuffle)
        API.media.attach('volume', self.check_volume)

    def check_current(self, current):
        if current:
            if self.nowplayingline1.Label != current['artist']:
                self.nowplayingline1.Label = current['artist']
            if self.nowplayingline2.Label != current['name']:
                self.nowplayingline2.Label = current['name']
                self.Sizer.Layout()

    def check_state(self, state):
        if state in self.statebmps:
            tmpbmp = self.statebmps[state]
            if tmpbmp != self.statebmp.GetBitmap():
                self.statebmp.SetBitmap(tmpbmp)
                self.statebmp.SetSize(tmpbmp.Size)
                self.Sizer.Layout()

    def check_shuffle(self, shuffle):
        if shuffle in self.shufflebmps:
            tmpbmp = self.shufflebmps[shuffle]
            if tmpbmp != self.shufflebmp.GetBitmap():
                self.shufflebmp.SetBitmap(tmpbmp)
                self.shufflebmp.SetSize(tmpbmp.Size)
                self.Sizer.Layout()

    def check_volume(self, volume):
        vol = ''
        if volume == 0:
            vol = 'volume_mute'
        elif volume < 0.5:
            vol = 'volume_low'
        elif volume < 1.0:
            vol = 'volume_medium'
        else:
            vol = 'volume_high'

        tmpbmp = self.volumebmps[vol]
        if tmpbmp != self.volumebmp.GetBitmap():
            self.volumebmp.SetBitmap(tmpbmp)
            self.volumebmp.SetSize(tmpbmp.Size)
            self.Sizer.Layout()

    def on_quit(self, e):
        self.frame.Close()

    def set_titles(self):
        # only use the first three labels
        new_labels = self.frame.get_plugin_titles()[:3]

        update = False
        for new_label, old_title in zip(new_labels, self.titles):
            if old_title.Label != new_label:
                old_title.SetLabel(new_label)
                update = True

        self.stripe.Sizer.Layout()
        self.Sizer.Layout()

    def on_stripe_update(self, evt):
        self.set_titles()
        if self.clock.Label != datetime.now().strftime('%H:%M'):
            self.clock.SetLabel(datetime.now().strftime('%H:%M'))

    def on_update(self, evt):

        API.wifi.update()
        self.wifi.Label = API.wifi.get_ssid()


"""
*******************************************************
*
*  test_checkParams - UNIT TEST FOR TRAVIS CI
*
*  License:      Apache 2.0
*  Written by:   Michael Slugocki
*  Created on:   April 28, 2017
*  Last updated: September 13, 2018
*
*******************************************************
"""

#################################################################
#  IMPORT MODULES
#################################################################
import numpy as np
from .checkParams import check_params as _check_params

#################################################################
#  DEFINE FUNCTIONS USED FOR UNIT TESTING
#################################################################

def _check_params_none(branch):
    # Test cases for param_ests is None
    param_ests = None
    # Generate dataset
    data01 = np.array([[0.0010,   45.0000,   90.0000],
                         [0.0015,   50.0000,   90.0000],
                         [0.0020,   44.0000,   90.0000],
                         [0.0025,   44.0000,   90.0000],
                         [0.0030,   52.0000,   90.0000],
                         [0.0035,   53.0000,   90.0000],
                         [0.0040,   62.0000,   90.0000],
                         [0.0045,   64.0000,   90.0000],
                         [0.0050,   76.0000,   90.0000],
                         [0.0060,   79.0000,   90.0000],
                         [0.0070,   88.0000,   90.0000],
                         [0.0080,   90.0000,   90.0000],
                         [0.0100,   90.0000,   90.0000]]);
    # Define nafc
    nafc = 2
    # Choose branch
    if branch == 0:
        batch = False
        data = data01
    elif branch == 1:
        batch = True
        data = dict()
        data['data01'] = data01
    # Call function with arguments above
    _check_params(data, param_ests, nafc, batch, 'weibull')
    # Update success flag
    success = 1
    return success

def _check_params_not_none(branch):
    # Generate dataset
    data = np.array([[0.0010,   45.0000,   90.0000],
                     [0.0015,   50.0000,   90.0000],
                     [0.0020,   44.0000,   90.0000],
                     [0.0025,   44.0000,   90.0000],
                     [0.0030,   52.0000,   90.0000],
                     [0.0035,   53.0000,   90.0000],
                     [0.0040,   62.0000,   90.0000],
                     [0.0045,   64.0000,   90.0000],
                     [0.0050,   76.0000,   90.0000],
                     [0.0060,   79.0000,   90.0000],
                     [0.0070,   88.0000,   90.0000],
                     [0.0080,   90.0000,   90.0000],
                     [0.0100,   90.0000,   90.0000]]);
    # Define nafc
    nafc = 2
    # Define batch
    batch = False
    # Choose branch
    if branch == 0:
        # Set param_ests to trigger event
        param_ests = dict()
    elif branch == 1:
        # Set param_ests to trigger event
        param_ests = ['Trigger', 'Event']
    elif branch == 2:
        # Set param_ests to trigger event
        param_ests = [0.005]
    elif branch == 3:
        # Set param_ests vector with full length
        param_ests = [0.005, 2, None, 0]
    elif branch == 4:
        # Set param_ests to go through different number of args (trigger error)
        param_ests = [0.005, 2, 0.5, 0, 0.09]
    # Call function with arguments above
    _check_params(data, param_ests, nafc, batch, 'weibull')
    # Update success flag
    success = 1
    return success

#################################################################
#  UNIT TESTS
#################################################################

def test_check_params_none_branch0():
    success = _check_params_none(0)
    # Assert if exception
    assert success == 1

def test_check_params_none_branch1():
    success = _check_params_none(1)
    # Assert if exception
    assert success == 1

def test_check_params_not_none_branch0():
    raised = False
    try:
        _check_params_not_none(0)
    except:
        raised = True
    # Assert if exception flag is not raised
    assert raised is True

def test_check_params_not_none_branch1():
    raised = False
    try:
        _check_params_not_none(1)
    except:
        raised = True
    # Assert if exception flag is not raised
    assert raised is True

def test_check_params_not_none_branch2():
    raised = False
    try:
        _check_params_not_none(2)
    except:
        raised = True
    # Assert if exception flag is not raised
    assert raised is True

def test_check_params_not_none_branch3():
    success = _check_params_not_none(3)
    # Assert if exception
    assert success == 1

def test_check_params_not_none_branch4():
    raised = False
    try:
        _check_params_not_none(6)
    except:
        raised = True
    # Assert if exception flag is not raised
    assert raised is True


def mean_reversion_strategy(df, candles, index, param, portfolio):
    if 'mean_reversion_period' not in param.keys():
        print('mean_reversion_period parameter missing')
        return

    if 'mean_reversion_secondary_period' not in param.keys():
        print('mean_reversion_secondary_period parameter missing')
        return

    if 'z_entry' not in param.keys():
        print('z_entry parameter missing')
        return

    if 'z_exit' not in param.keys():
        print('z_exit parameter missing')
        return

    candle = candles[index]

    '''-----------------------------Signal calculations-----------------------'''
    buy = portfolio+'_buy'
    sell = portfolio+'_sell'
    sellPrice = portfolio+'_sellPrice'

    short = portfolio+'_short'
    cover = portfolio+'_cover'
    coverPrice = portfolio+'_coverPrice'

    candle[buy] = False
    candle[sell] = False
    candle[short] = False
    candle[cover] = False

    if index<2:
        return candle

    candle_p1 = candles[index-1]
    candle_p2 = candles[index-2]

    #print(candle_prev, index)

    p = param['mean_reversion_period']
    p_s = param['mean_reversion_secondary_period']

    x = candle['close']
    close = df['close'].iloc[max(0,index-p+1):index+1]
    mu = close.mean()
    #print(mu)
    candle['mu'] = mu

    sigma = close.std()
    #print(sigma)
    candle['sigma'] = sigma

    z = (x-mu)/sigma
    #print(z)
    candle['z_score']  = z

    close_s = df['close'].iloc[max(0,index-p_s+1):index+1]
    mu_s = close_s.mean()
    candle['mu2'] = mu_s

    if ( candle_p1['z_score']<-param['z_entry'] and candle_p2['z_score']>-param['z_entry'] ) and candle_p1['mu']>candle_p1['mu2']:
        candle[buy] = True

    if candle_p1['z_score']>-param['z_exit'] and candle_p2['z_score']<-param['z_exit']:
        candle[sell] = True
        candle[sellPrice] = candle['open']

    if ( candle_p1['z_score']>param['z_entry'] and candle_p2['z_score']<param['z_entry'] ) and candle_p1['mu']<candle_p1['mu2']:
        candle['short'] = True

    if candle_p1['z_score']<param['z_exit'] and candle_p2['z_score']>param['z_exit']:
        candle[cover] = True
        candle[coverPrice] = candle['open']

    return candle