#!/usr/bin/python
import re
import sys

word_input = sys.argv[12]
word_output = sys.argv[14]
concepts_number = int(sys.argv[2])
num_results_reqd = int(sys.argv[4])
directory_location = sys.argv[6]
document_input = sys.argv[8]
query_input = sys.argv[16]
document_output = sys.argv[10]
query_output = sys.argv[18]

# num_results_reqd=10
# concepts_number = 200

import os
current_directory = os.getcwd()
doc_location = current_directory+'/'+directory_location
os.chdir(doc_location)

pattern = re.compile(r'\W+')

from collections import Counter

# curr_file_words.remove('')
dictionary_list = [];
set_of_words = set()
Title_index={}
index_Title={}

file_up_limit=5000;

for file_num in range(1,file_up_limit+1):
	file_str = str(file_num) + ".txt"
	reading_file = open(file_str,'r')
	title=reading_file.readline().rstrip()
	curr_file_str=reading_file.read()
	reading_file.close()
	Title_index[title]=file_num
	index_Title[file_num]=title
	curr_file_words = pattern.split(curr_file_str.lower().strip(' ').rstrip('\n'))
	set_of_words=set_of_words.union(set(curr_file_words))
	dictionary_list.append(dict(Counter(curr_file_words) ))
	# print file_num

# TODO->convert to lower case

# print(len(dictionary_list))

os.chdir(current_directory)

list_of_words = list(set_of_words);

unique_words_num=len(list_of_words)

words_index={};

for i in range(0,unique_words_num):
	words_index[list_of_words[i]]=i

list_doc_col=[];
list_word_row=[];
list_count_data=[];

# print("Started making the 3 lists")

for doc_num in range (0,file_up_limit):
	for current_word in dictionary_list[doc_num]:
		list_doc_col.append(doc_num)
		list_word_row.append(words_index[current_word])
		list_count_data.append(dictionary_list[doc_num][current_word])

# print("Made the 3 lists")

import numpy as np
import scipy.sparse as sp
from scipy import spatial
sparse_doc_word_matrix=sp.csc_matrix((np.array(list_count_data), (np.array(list_word_row), np.array(list_doc_col) ) ), shape = (unique_words_num, file_up_limit)  )

# sp.coo_matrix.asfptype(sparse_doc_word_matrix)

from scipy.sparse.linalg import svds
term_row_matrix , strength_matrix , doc_col_matrix = svds(sparse_doc_word_matrix.astype(float), concepts_number , which = 'LM')

doc_row_matrix= np.dot(np.transpose(doc_col_matrix),np.diag(strength_matrix))
# Now a query is given and we need to find out the Documents!!

# print("Started Query IO")

multiply1= np.dot( np.array(np.array(term_row_matrix)),np.linalg.inv(np.diag(strength_matrix))  )

query_input_list = [(line.rstrip('\n')).strip(' ') for line in open(query_input)]

write_query_results = open(query_output,"a")

for query_input_index in range(0,len(query_input_list)):
	query_string = query_input_list[query_input_index]
	query_words=pattern.split(query_string.lower())
	query_dictionary=dict(Counter(query_words) );
	query_list_doc_col=[];
	query_list_word_row=[];
	query_list_count_data=[];
	for current_word in query_dictionary:
		query_list_doc_col.append(0)
		query_list_word_row.append(words_index[current_word])
		query_list_count_data.append(query_dictionary[current_word])
	query_sparse_doc_word_matrix=sp.csc_matrix((np.array(query_list_count_data), (np.array(query_list_word_row), np.array(query_list_doc_col) ) ), shape = (unique_words_num, 1)  )
	query_sparse_doc_word_matrix=query_sparse_doc_word_matrix.todense();
	Final_query_vector=np.dot(  np.transpose(query_sparse_doc_word_matrix),multiply1)
	# doc_row_matrix= doc_col_matrix.transpose()
	# doc_query=1
	# doc_query_index=doc_query-1
	doc_dot_product_list=np.array([])
	doc_query_row=Final_query_vector.transpose();
	for other_doc_row in doc_row_matrix:
		doc_dot_product_list=np.append(doc_dot_product_list,1 - spatial.distance.cosine(doc_query_row,other_doc_row))
	unsorted_answer_indices = np.argpartition(  doc_dot_product_list , -1*(num_results_reqd))[-1*(num_results_reqd):]
	sorted_answer_indices= unsorted_answer_indices[np.argsort(doc_dot_product_list[unsorted_answer_indices])]
	final_doc_answer_list=[]
	for i in range(0,num_results_reqd):
		write_query_results.write(index_Title[sorted_answer_indices[num_results_reqd-i-1]+1]+";"+"\t")
		# final_words_answer_list.append(sorted_answer_indices[num_results_reqd-i-1]+1)
		# print (sorted_answer_indices[num_results_reqd-i-1]+1)
	write_query_results.write('\n')

write_query_results.close()

# print("Ended Query IO")

# Given a word, then finding its best k words
# print("Started Word IO")

compare_term_matrix=np.dot(term_row_matrix,np.diag(strength_matrix))

word_input_list = [(line.rstrip('\n')).strip(' ') for line in open(word_input)]

write_word_results= open(word_output,"a")

# print "size is ",len(word_input_list)

for word_input_index in range(0,len(word_input_list)):
	# print "Doing for index",word_input_index
	word_query=word_input_list[word_input_index]
	word_query_index=words_index[word_query]
	word_dot_product_list=[0 for x in xrange(unique_words_num)]
	word_query_row=compare_term_matrix[word_query_index];
	# print "step1"
	for i in xrange(unique_words_num):
		word_dot_product_list[i]=(1 - spatial.distance.cosine(word_query_row,compare_term_matrix[i]))
	# print "step2"
	# print len(word_dot_product_list)
	# print len(word_dot_product_list[0])
	unsorted_answer_indices = np.argpartition(  word_dot_product_list , -1*(num_results_reqd))[-1*(num_results_reqd):]
	# print "WORD DOT",word_dot_product_list
	# print "UNSORTED INDICES",unsorted_answer_indices
	# print "step3"
	# sorted_answer_indices= unsorted_answer_indices[np.argsort(word_dot_product_list[unsorted_answer_indices])]
	# final_words_answer_list=[]
	# print "step4"
	for i in range(0,num_results_reqd):
		write_word_results.write(list_of_words[unsorted_answer_indices[num_results_reqd-1-i]]+";"+"\t")
		# final_words_answer_list.append(list_of_words[sorted_answer_indices[num_results_reqd-1-i]])
		# print list_of_words[sorted_answer_indices[num_results_reqd-1-i]]
	# print "step5"
	write_word_results.write('\n')

write_word_results.close()

# print("Ended Word IO")

# Given a doc then finding similar documents

# print("Started DOC IO")

doc_input_list = [(line.rstrip('\n')).strip(' ') for line in open(document_input)]

write_doc_results= open(document_output,"a")

# print "Size is",len(doc_input_list)

for doc_input_index in range(0,len(doc_input_list)):
	# print(doc_input_index)
	doc_query=Title_index[doc_input_list[doc_input_index]]
	doc_query_index=doc_query-1
	doc_dot_product_list=np.array([])
	doc_query_row=doc_row_matrix[doc_query_index];
	for other_doc_row in doc_row_matrix:
		doc_dot_product_list=np.append(doc_dot_product_list,1 - spatial.distance.cosine(doc_query_row,other_doc_row))
	unsorted_answer_indices = np.argpartition(  doc_dot_product_list , -1*(num_results_reqd))[-1*(num_results_reqd):]
	sorted_answer_indices= unsorted_answer_indices[np.argsort(doc_dot_product_list[unsorted_answer_indices])]
	final_doc_answer_list=[]
	for i in range(0,num_results_reqd):
		write_doc_results.write(index_Title[sorted_answer_indices[num_results_reqd-i-1]+1]+";"+"\t")
		# final_words_answer_list.append(sorted_answer_indices[num_results_reqd-i-1]+1)
		# print (sorted_answer_indices[num_results_reqd-i-1]+1)
	write_doc_results.write('\n')

write_doc_results.close()

# print("Ended DOC IO")


def advent6_1():
    with open('day6.txt', 'r') as f:
        day6ls = [set(x) for x in f.read().split('\n\n')]

    total = 0
    for item in day6ls:
        if '\n' in item:
            total += (len(item) - 1)
        else:
            total += len(item)
    return total

# part 2

with open('day6.txt', 'r') as f:
    day6ls = [x.split() for x in f.read().split('\n\n')]
print('part 2:', sum(len([letter for letter in day6[0] if all(letter in x for x in day6)]) for day6 in day6ls))


"""
Unit tests for the mapping generation framework
"""
import pandas as pd
import pytest

from monarch_gene_mapping.cli_utils import df_mappings, explode_column, UNIPROT_ID_MAPPING_SELECTED_COLUMNS

def test_null_mapping():
    hgnc_df = pd.read_csv("tests/resources/hgnc_test.txt", sep="\t", dtype="string")
    mapped = df_mappings(
        df=explode_column(hgnc_df, "omim_id", "|"),
        subject_column="hgnc_id",
        object_column="omim_id",
        object_curie_prefix="OMIM:",
        predicate_id="skos:exactMatch",
        mapping_justification="semapv:UnspecifiedMatching",
    )
    # assert len(mapped) == 4
    for row in mapped.itertuples():
        assert not ("NA" in row.subject_id)
        assert not ("NA" in row.object_id)
test_null_mapping()

def test_semicolon_in_id():
    uniprot_df = pd.read_csv("tests/resources/uniprot_test.tsv", names=UNIPROT_ID_MAPPING_SELECTED_COLUMNS, sep="\t")
    mapped = df_mappings(
        df=uniprot_df,
        subject_column="GeneID",
        subject_curie_prefix="NCBIGene:",
        predicate_id="skos:exactMatch",
        object_column="UniProtKB-AC",
        object_curie_prefix="UniProtKB:",
        mapping_justification="semapv:UnspecifiedMatching",
        filter_column="NCBI-taxon",
        # Chicken: 9031, Dog: 9615, Cow, 9913, Pig: 9823, Aspergillus ('Emericella') nidulans: 227321
        filter_ids=[9031, 9615, 9913, 9823, 227321],
    )
    assert len(mapped) == 4


# napisac funkcje, ktora z tablicy wybierze wszystkie liczby calkowite, ktore:
# nie sa zerem, nie zawiraja zera z przodu, zawieraja tylko liczby, ....

tab = ['0 12', '12 0', '12.', '12', '2a', '15']

def get_numbers_2(nmumber_list):
    valid_numbers = []
    invalid_numbers = []
    for x in nmumber_list:
        try:
            valid_numbers.append(float(x))
        except ValueError:
            invalid_numbers.append(x)
    return valid_numbers, invalid_numbers

def get_numbers(numbers_list):
    valid_numbers = []
    for x in numbers_list:
        try:
            valid_numbers.append(int(x))
        except ValueError:
            pass
    return valid_numbers

def is_int(number):
    try:
        int(number)
        return True
    except ValueError:
        return False

# napisać funkcje zwracająca liczbę całkowite w list compreh
# print([x for x in range(10)])

list_comp = [int(number) for number in tab if is_int(number) and int(number) < 13]
print('list_comp', list_comp)

integers = get_numbers(tab)
print('<13', [x for x in integers if x < 13])
print('<13', [x if x < 13 else None for x in integers])

print('get_numbers', get_numbers(tab))

# w samolocie chcemt ustalic ile jest mozliwosci posadzenia rodziny trzyosobowej na miejscach znajdujacych sie obok siebie
# schemat samolotu:
#     [A B C    D E F G    H I J]
#     [A B C    D E F G    H I J]
#     [A B C    D E F G    H I J]
#     [A B C    D E F G    H I J]
# dodac parametr dlugosci samolotu (ilosci rzedow)
tab =  [
    [0, 0, 1, 0, 0, 0, 0, 1, 0, 1],
    [0, 0, 0, 0, 0, 0, 0, 1, 1, 1],
    [1, 0, 0, 0, 0, 1, 0, 0, 0, 1],
    [1, 0, 0, 1, 0, 0, 0, 0, 0, 1],
]
# result = 6

# result = 6for

# [A x x   x x x G  H I J]
# [A B C   D E F G  H I J]
# [A B C   D E F G  H I J]
# [A B C   D E F G  H I J]


import pyotp
import qrcode

# This Should be a Secure Key and different for each user
otp = pyotp.TOTP("KRUGS4ZAKNUG65LMMQQGEZJAMEQFGZLDOVZGKICLMV4Q====")
print(otp.now())

def register():
    auth_string = otp.provisioning_uri(name="Test User", issuer_name="My test System", )
    # print(auth_string)
    img = qrcode.make(auth_string)
    img.show()
    while True:
        val = input("Enter current code to complete registration: ")
        if otp.now() == val:
            print("Registration Complete")
            break
        else:
            print("Wrong OTP please try again...")

def login():
    val = input("Enter your Google Authenticator to Login: ")
    if otp.now() == val:
        print("Login Successful")
    else:
        print("Login Failed please try again...")

register()
while True:
    login()


import os
import re
import json
import getpass
import requests
import pyblish.api

class CelactionSubmitDeadline(pyblish.api.InstancePlugin):
    """Submit CelAction2D scene to Deadline

    Renders are submitted to a Deadline Web Service.

    """

    label = "Submit CelAction to Deadline"
    order = pyblish.api.IntegratorOrder + 0.1
    hosts = ["celaction"]
    families = ["render.farm"]

    deadline_department = ""
    deadline_priority = 50
    deadline_pool = ""
    deadline_pool_secondary = ""
    deadline_group = ""
    deadline_chunk_size = 1
    deadline_job_delay = "00:00:08:00"

    def process(self, instance):

        context = instance.context

        # get default deadline webservice url from deadline module
        deadline_url = instance.context.data["defaultDeadline"]
        # if custom one is set in instance, use that
        if instance.data.get("deadlineUrl"):
            deadline_url = instance.data.get("deadlineUrl")
        assert deadline_url, "Requires Deadline Webservice URL"

        self.deadline_url = "{}/api/jobs".format(deadline_url)
        self._comment = instance.data["comment"]
        self._deadline_user = context.data.get(
            "deadlineUser", getpass.getuser())
        self._frame_start = int(instance.data["frameStart"])
        self._frame_end = int(instance.data["frameEnd"])

        # get output path
        render_path = instance.data['path']
        script_path = context.data["currentFile"]

        response = self.payload_submit(instance,
                                       script_path,
                                       render_path
                                       )
        # Store output dir for unified publisher (filesequence)
        instance.data["deadlineSubmissionJob"] = response.json()

        instance.data["outputDir"] = os.path.dirname(
            render_path).replace("\\", "/")

        instance.data["publishJobState"] = "Suspended"

        # adding 2d render specific family for version identification in Loader
        instance.data["families"] = ["render2d"]

    def payload_submit(self,
                       instance,
                       script_path,
                       render_path
                       ):
        resolution_width = instance.data["resolutionWidth"]
        resolution_height = instance.data["resolutionHeight"]
        render_dir = os.path.normpath(os.path.dirname(render_path))
        render_path = os.path.normpath(render_path)
        script_name = os.path.basename(script_path)

        for item in instance.context:
            if "workfile" in item.data["family"]:
                msg = "Workfile (scene) must be published along"
                assert item.data["publish"] is True, msg

                template_data = item.data.get("anatomyData")
                rep = item.data.get("representations")[0].get("name")
                template_data["representation"] = rep
                template_data["ext"] = rep
                template_data["comment"] = None
                anatomy_filled = instance.context.data["anatomy"].format(
                    template_data)
                template_filled = anatomy_filled["publish"]["path"]
                script_path = os.path.normpath(template_filled)

                self.log.info(
                    "Using published scene for render {}".format(script_path)
                )

        jobname = "%s - %s" % (script_name, instance.name)

        output_filename_0 = self.preview_fname(render_path)

        try:
            # Ensure render folder exists
            os.makedirs(render_dir)
        except OSError:
            pass

        # define chunk and priority
        chunk_size = instance.context.data.get("chunk")
        if not chunk_size:
            chunk_size = self.deadline_chunk_size

        # search for %02d pattern in name, and padding number
        search_results = re.search(r"(%0)(\d)(d)[._]", render_path).groups()
        split_patern = "".join(search_results)
        padding_number = int(search_results[1])

        args = [
            f"<QUOTE>{script_path}<QUOTE>",
            "-a",
            "-16",
            "-s <STARTFRAME>",
            "-e <ENDFRAME>",
            f"-d <QUOTE>{render_dir}<QUOTE>",
            f"-x {resolution_width}",
            f"-y {resolution_height}",
            f"-r <QUOTE>{render_path.replace(split_patern, '')}<QUOTE>",
            f"-= AbsoluteFrameNumber=on -= PadDigits={padding_number}",
            "-= ClearAttachment=on",
        ]

        payload = {
            "JobInfo": {
                # Job name, as seen in Monitor
                "Name": jobname,

                # plugin definition
                "Plugin": "CelAction",

                # Top-level group name
                "BatchName": script_name,

                # Arbitrary username, for visualisation in Monitor
                "UserName": self._deadline_user,

                "Department": self.deadline_department,
                "Priority": self.deadline_priority,

                "Group": self.deadline_group,
                "Pool": self.deadline_pool,
                "SecondaryPool": self.deadline_pool_secondary,
                "ChunkSize": chunk_size,

                "Frames": f"{self._frame_start}-{self._frame_end}",
                "Comment": self._comment,

                # Optional, enable double-click to preview rendered
                # frames from Deadline Monitor
                "OutputFilename0": output_filename_0.replace("\\", "/"),

                # # Asset dependency to wait for at least
                # the scene file to sync.
                # "AssetDependency0": script_path
                "ScheduledType": "Once",
                "JobDelay": self.deadline_job_delay
            },
            "PluginInfo": {
                # Input
                "SceneFile": script_path,

                # Output directory
                "OutputFilePath": render_dir.replace("\\", "/"),

                # Plugin attributes
                "StartupDirectory": "",
                "Arguments": " ".join(args),

                # Resolve relative references
                "ProjectPath": script_path,
                "AWSAssetFile0": render_path,
            },

            # Mandatory for Deadline, may be empty
            "AuxFiles": []
        }

        plugin = payload["JobInfo"]["Plugin"]
        self.log.debug("using render plugin : {}".format(plugin))

        self.log.debug("Submitting..")
        self.log.debug(json.dumps(payload, indent=4, sort_keys=True))

        # adding expectied files to instance.data
        self.expected_files(instance, render_path)
        self.log.debug("__ expectedFiles: `{}`".format(
            instance.data["expectedFiles"]))

        response = requests.post(self.deadline_url, json=payload)

        if not response.ok:
            self.log.error(
                "Submission failed! [{}] {}".format(
                    response.status_code, response.content))
            self.log.debug(payload)
            raise SystemExit(response.text)

        return response

    def preflight_check(self, instance):
        """Ensure the startFrame, endFrame and byFrameStep are integers"""

        for key in ("frameStart", "frameEnd"):
            value = instance.data[key]

            if int(value) == value:
                continue

            self.log.warning(
                "%f=%d was rounded off to nearest integer"
                % (value, int(value))
            )

    def preview_fname(self, path):
        """Return output file path with #### for padding.

        Deadline requires the path to be formatted with # in place of numbers.
        For example `/path/to/render.####.png`

        Args:
            path (str): path to rendered images

        Returns:
            str

        """
        self.log.debug("_ path: `{}`".format(path))
        if "%" in path:
            search_results = re.search(r"[._](%0)(\d)(d)[._]", path).groups()
            split_patern = "".join(search_results)
            split_path = path.split(split_patern)
            hashes = "#" * int(search_results[1])
            return "".join([split_path[0], hashes, split_path[-1]])

        self.log.debug("_ path: `{}`".format(path))
        return path

    def expected_files(self, instance, filepath):
        """ Create expected files in instance data
        """
        if not instance.data.get("expectedFiles"):
            instance.data["expectedFiles"] = []

        dirpath = os.path.dirname(filepath)
        filename = os.path.basename(filepath)

        if "#" in filename:
            pparts = filename.split("#")
            padding = "%0{}d".format(len(pparts) - 1)
            filename = pparts[0] + padding + pparts[-1]

        if "%" not in filename:
            instance.data["expectedFiles"].append(filepath)
            return

        for i in range(self._frame_start, (self._frame_end + 1)):
            instance.data["expectedFiles"].append(
                os.path.join(dirpath, (filename % i)).replace("\\", "/")
            )


from typing import Optional

import torch.nn as nn
from torch import Tensor

from openspeech.modules.positional_encoding import RelPositionalEncoding
from openspeech.modules.relative_multi_head_attention import RelativeMultiHeadAttention

class MultiHeadedSelfAttentionModule(nn.Module):
    r"""
    Conformer employ multi-headed self-attention (MHSA) while integrating an important technique from Transformer-XL,
    the relative sinusoidal positional encoding scheme. The relative positional encoding allows the self-attention
    module to generalize better on different input length and the resulting encoders is more robust to the variance of
    the utterance length. Conformer use prenorm residual units with dropout which helps training
    and regularizing deeper models.

    Args:
        d_model (int): The dimension of model
        num_heads (int): The number of attention heads.
        dropout_p (float): probability of dropout

    Inputs: inputs, mask
        - **inputs** (batch, time, dim): Tensor containing input vector
        - **mask** (batch, 1, time2) or (batch, time1, time2): Tensor containing indices to be masked

    Returns:
        - **outputs** (batch, time, dim): Tensor produces by relative multi headed self attention module.
    """

    def __init__(
        self,
        d_model: int,
        num_heads: int,
        dropout_p: float = 0.1,
    ) -> None:
        super(MultiHeadedSelfAttentionModule, self).__init__()
        self.positional_encoding = RelPositionalEncoding(d_model)
        self.layer_norm = nn.LayerNorm(d_model)
        self.attention = RelativeMultiHeadAttention(d_model, num_heads, dropout_p)
        self.dropout = nn.Dropout(p=dropout_p)

    def forward(self, inputs: Tensor, mask: Optional[Tensor] = None) -> Tensor:
        r"""
        Forward propagate of conformer's multi-headed self attention module.

        Inputs: inputs, mask
            - **inputs** (batch, time, dim): Tensor containing input vector
            - **mask** (batch, 1, time2) or (batch, time1, time2): Tensor containing indices to be masked

        Returns:
            - **outputs** (batch, time, dim): Tensor produces by relative multi headed self attention module.
        """
        batch_size = inputs.size(0)
        pos_embedding = self.positional_encoding(inputs)
        pos_embedding = pos_embedding.repeat(batch_size, 1, 1)

        inputs = self.layer_norm(inputs)
        outputs = self.attention(inputs, inputs, inputs, pos_embedding=pos_embedding, mask=mask)

        return self.dropout(outputs)


from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from Common.ReadSQL import Read_sql
from Config.ReadConfig import ReadConfig
from selenium.webdriver.common.by import By
from time import sleep
from Common.Logger import WebLogger

class BasePage(object):
    # 构造函数里面的参数就是类的所有参数
    def __init__(self,selenuime_driver,base_url):
        self.log = WebLogger("Base function").logger
        self.driver = selenuime_driver
        self.url = base_url

    def _open(self):
        self.driver.get(self.url)
        self.driver.maximize_window()

    # 定义open()方法，调用_open()方法
    def open(self):
        self._open()

    def find_emelemt(self,*loc):
        try:
            # 保证元素可见
            WebDriverWait(self.driver,10,0.5).until(EC.visibility_of_all_elements_located(loc))
            return self.driver.find_element(*loc)
        except:
            self.log.info("页面中没有找到:",*loc)

    # 定义script()方法，用于执行JS脚本
    def script(self,scriptString):
        print("session_id:",self.driver.session_id)
        self.driver.execute_script(scriptString)

    # 定义页面跳转方法，比方说有的页面有frame嵌套
    def switch_frame(self,loc):
        return self.driver.switch_to_frame(loc)

    # 重新定义send_keys()方法，为了保证搜索按钮是否存在，还有有的输入框中默认有值，要清空
    def send_keys(self,loc,value,clear_first=True,click_first=True):
        try:
            # getattr方法相当于实现了self.loc
            loc = getattr(self,"_%s"%loc)
            # 是否存在搜索按钮
            if click_first:
                self.find_element(*loc).click()
            # 清空搜索框中的值，并输入需要搜索的值
            if clear_first:
                self.find_emelemt(*loc).clear()
                self.find_emelemt(*loc).send_keys(value)

        except:
            self.log.info( "页面上未找到%s元素" % loc)

    #句柄切换,切换至当前句柄
    def switch_to_handle(self):
        all_handle = self.driver.window_handles #获取所有页面得句柄
        now_handle = self.driver.current_window_handle  # 获取当前页面句柄
        for handle in all_handle:
            if handle != now_handle:
                self.driver.switch_to_window(handle)

    #scrm登录
    def _Scrm_login(self, username,
                   password,
                   ):
        userName_loc = (By.NAME, 'username')
        # 密码
        password_loc = (By.NAME, 'password')
        # 验证码
        captcha_loc = (By.NAME, 'captcha')
        # 登录按钮
        login_btn_loc = (By.XPATH, '//*[@id="app"]/div/div[2]/div/form/button/span')
        sql = "SELECT * from sys_captcha ORDER BY expire_time desc limit 1"
        baseUrl = ReadConfig()
        url = baseUrl.get_http('baseUrl')
        self.driver.get(url)
        sleep(3)
        self.find_emelemt(*userName_loc).send_keys(username)
        self.find_emelemt(*password_loc).send_keys(password)
        readSql = Read_sql(sql)
        code = readSql.sqlExecute()
        vsCode = code[0]['code']
        self.find_emelemt(*captcha_loc).send_keys(vsCode)
        # 点击登录
        self.find_emelemt(*login_btn_loc).click()


# -*- coding: utf-8 -*-
"""
Created on Sat Dec 17 17:03:57 2016

@author: Chase
"""

from keras.layers.advanced_activations import LeakyReLU
from keras.layers import Input, merge, SpatialDropout2D
from keras.layers import Convolution2D, AveragePooling2D, UpSampling2D
from keras.models import Model
from keras.optimizers import Adam

def get_cnn_model(img_rows, img_cols):
    input = Input(shape=(1, img_rows, img_cols))

    conv1 = Convolution2D(32, 3, 3, border_mode='same', init='he_normal')(input)
    conv1 = LeakyReLU()(conv1)
    conv1 = SpatialDropout2D(0.2)(conv1)
    conv1 = Convolution2D(32, 3, 3, border_mode='same', init='he_normal')(conv1)
    conv1 = LeakyReLU()(conv1)
    conv1 = SpatialDropout2D(0.2)(conv1)
    pool1 = AveragePooling2D(pool_size=(2,2))(conv1)

    conv2 = Convolution2D(64, 3, 3, border_mode='same', init='he_normal')(pool1)
    conv2 = LeakyReLU()(conv2)
    conv2 = SpatialDropout2D(0.2)(conv2)
    conv2 = Convolution2D(64, 3, 3, border_mode='same', init='he_normal')(conv2)
    conv2 = LeakyReLU()(conv2)
    conv2 = SpatialDropout2D(0.2)(conv2)
    pool2 = AveragePooling2D(pool_size=(2,2))(conv2)

    conv3 = Convolution2D(128, 3, 3, border_mode='same', init='he_normal')(pool2)
    conv3 = LeakyReLU()(conv3)
    conv3 = SpatialDropout2D(0.2)(conv3)
    conv3 = Convolution2D(128, 3, 3, border_mode='same', init='he_normal')(conv3)
    conv3 = LeakyReLU()(conv3)
    conv3 = SpatialDropout2D(0.2)(conv3)

    comb1 = merge([conv2, UpSampling2D(size=(2,2))(conv3)], mode='concat', concat_axis=1)
    conv4 = Convolution2D(64, 3, 3, border_mode='same', init='he_normal')(comb1)
    conv4 = LeakyReLU()(conv4)
    conv4 = SpatialDropout2D(0.2)(conv4)
    conv4 = Convolution2D(64, 3, 3, border_mode='same', init='he_normal')(conv4)
    conv4 = LeakyReLU()(conv4)
    conv4 = SpatialDropout2D(0.2)(conv4)

    comb2 = merge([conv1, UpSampling2D(size=(2,2))(conv4)], mode='concat', concat_axis=1)
    conv5 = Convolution2D(32, 3, 3, border_mode='same', init='he_normal')(comb2)
    conv5 = LeakyReLU()(conv5)
    conv5 = SpatialDropout2D(0.2)(conv5)
    conv5 = Convolution2D(32, 3, 3, border_mode='same', init='he_normal')(conv5)
    conv5 = LeakyReLU()(conv5)
    conv5 = SpatialDropout2D(0.2)(conv5)

    output = Convolution2D(1, 1, 1, activation='sigmoid')(conv5)

    model = Model(input=input, output=output)
    model.compile(optimizer=Adam(lr=3e-4), loss='binary_crossentropy')
    return model

def get_iterative_model(img_rows, img_cols):
    # the heatmap from CNN
    input1 = Input(shape=(1, img_rows, img_cols))

    # the image heatmap was generated from (change 1 to 3 for color images)
    input2 = Input(shape=(1, img_rows, img_cols))

    # these are shared layer declarations
    convh1 = Convolution2D(32, 3, 3, activation='relu', border_mode='same')
    convh2 = Convolution2D(64, 3, 3, activation='relu', border_mode='same')

    convi1 = Convolution2D(32, 3, 3, activation='relu', border_mode='same')

    convmlp1 = Convolution2D(32, 1, 1, activation='relu')
    convmlp2 = Convolution2D(32, 1, 1, activation='relu')
    convmlp3 = Convolution2D(1, 1, 1)

    # now the actual model
    upperconv1 = convh1(input1)
    lowerconv1 = convi1(input2)

    concat1 = merge([upperconv1, lowerconv1], mode='concat', concat_axis=1)
    upperconv2 = convh2(concat1)

    mlp11 = convmlp1(upperconv2)
    mlp12 = convmlp2(mlp11)
    mlp13 = convmlp3(mlp12)

    add1 = merge([input1, mlp13], mode='sum')

    upperconv2 = convh1(add1)
    lowerconv2 = convi1(input2)

    concat2 = merge([upperconv2, lowerconv2], mode='concat', concat_axis=1)
    upperconv3 = convh2(concat2)

    mlp21 = convmlp1(upperconv3)
    mlp22 = convmlp2(mlp21)
    mlp23 = convmlp3(mlp22)

    add2 = merge([add1, mlp23], mode='sum')

    upperconv3 = convh1(add2)
    lowerconv3 = convi1(input2)

    concat3 = merge([upperconv3, lowerconv3], mode='concat', concat_axis=1)
    upperconv4 = convh2(concat3)

    mlp31 = convmlp1(upperconv4)
    mlp32 = convmlp2(mlp31)
    mlp33 = convmlp3(mlp32)

    add3 = merge([add2, mlp33], mode='sum')

    upperconv4 = convh1(add3)
    lowerconv4 = convi1(input2)

    concat4 = merge([upperconv4, lowerconv4], mode='concat', concat_axis=1)
    upperconv5 = convh2(concat4)

    mlp41 = convmlp1(upperconv5)
    mlp42 = convmlp2(mlp41)
    mlp43 = convmlp3(mlp42)

    add4 = merge([add3, mlp43], mode='sum')

    upperconv5 = convh1(add4)
    lowerconv5 = convi1(input2)

    concat5 = merge([upperconv5, lowerconv5], mode='concat', concat_axis=1)
    upperconv6 = convh2(concat5)

    mlp51 = convmlp1(upperconv6)
    mlp52 = convmlp2(mlp51)
    mlp53 = convmlp3(mlp52)

    add5 = merge([add4, mlp53], mode='sum')

    model = Model(input=[input1, input2], output=add5)
    model.compile(Adam(lr=3e-4), 'binary_crossentropy')

    return model


num1 = input("put first number: ")
num2 = input("put second number: ")
operation = input("what do you want to do? choose 1 for add, 2 for subtract, 3 for divide and 4 for multiply:")
num1 = int(num1)
num2 = int(num2)

def calculator():
    while True:
        if operation == "1":
            print("Your number added together is:",num1 + num2)
            break
        elif operation == "2":
            print("Your number subtracted is:",num1 - num2)
            break
        elif operation == "3":
            print("Your number divided is: ", num1/num2)
            break
        elif operation == "4":
            print("Your number multiplied is: ",num1*num2)
            break
        else:
            print("Put in a valid operation.")
            break
    return num1 and num2

calculator()


import matplotlib.pyplot as plt
import numpy as np

def plot_scree(eigenvals, total_var, ncomp=None, x_label='factor'):
    """
    Plot of the ordered eigenvalues and variance explained for the loadings

    Parameters
    ----------
    eigenvals : array_like
        The eigenvalues
    total_var : float
        the total variance (for plotting percent variance explained)
    ncomp : int, optional
        Number of factors to include in the plot.  If None, will
        included the same as the number of maximum possible loadings
    x_label : str
        label of x-axis

    Returns
    -------
    Figure
        Handle to the figure.
    """
    fig = plt.figure()
    ncomp = len(eigenvals) if ncomp is None else ncomp
    vals = eigenvals
    vals = vals[:ncomp]
    #    vals = np.cumsum(vals)

    ax = fig.add_subplot(121)
    ax.plot(np.arange(ncomp), vals[: ncomp], 'b-o')
    ax.autoscale(tight=True)
    xlim = np.array(ax.get_xlim())
    sp = xlim[1] - xlim[0]
    xlim += 0.02 * np.array([-sp, sp])
    ax.set_xticks(np.arange(ncomp))
    ax.set_xlim(xlim)

    ylim = np.array(ax.get_ylim())
    scale = 0.02
    sp = ylim[1] - ylim[0]
    ylim += scale * np.array([-sp, sp])
    ax.set_ylim(ylim)
    ax.set_title('Scree Plot')
    ax.set_ylabel('Eigenvalue')
    ax.set_xlabel(x_label)

    per_variance = vals / total_var
    cumper_variance = np.cumsum(per_variance)
    ax = fig.add_subplot(122)

    ax.plot(np.arange(ncomp), per_variance[: ncomp], 'b-o')
    ax.plot(np.arange(ncomp), cumper_variance[: ncomp], 'g--o')
    ax.autoscale(tight=True)
    xlim = np.array(ax.get_xlim())
    sp = xlim[1] - xlim[0]
    xlim += 0.02 * np.array([-sp, sp])
    ax.set_xticks(np.arange(ncomp))
    ax.set_xlim(xlim)

    ylim = np.array(ax.get_ylim())
    scale = 0.02
    sp = ylim[1] - ylim[0]
    ylim += scale * np.array([-sp, sp])
    ax.set_ylim(ylim)
    ax.set_title('Variance Explained')
    ax.set_ylabel('Proportion')
    ax.set_xlabel(x_label)
    ax.legend(['Proportion', 'Cumulative'], loc=5)
    fig.tight_layout()
    return fig

def plot_loadings(loadings, col_names=None, row_names=None,
                  loading_pairs=None, percent_variance=None,
                  title='Factor patterns'):
    """
    Plot factor loadings in 2-d plots

    Parameters
    ----------
    loadings : array like
        Each column is a component (or factor)
    col_names : a list of strings
        column names of `loadings`
    row_names : a list of strings
        row names of `loadings`
    loading_pairs : None or a list of tuples
        Specify plots. Each tuple (i, j) represent one figure, i and j is
        the loading number for x-axis and y-axis, respectively. If `None`,
        all combinations of the loadings will be plotted.
    percent_variance : array_like
        The percent variance explained by each factor.

    Returns
    -------
    figs : a list of figure handles
    """
    k_var, n_factor = loadings.shape
    if loading_pairs is None:
        loading_pairs = []
        for i in range(n_factor):
            for j in range(i + 1,n_factor):
                loading_pairs.append([i, j])
    if col_names is None:
        col_names = ["factor %d" % i for i in range(n_factor)]
    if row_names is None:
        row_names = ["var %d" % i for i in range(k_var)]
    figs = []
    for item in loading_pairs:
        i = item[0]
        j = item[1]
        fig = plt.figure(figsize=(7, 7))
        figs.append(fig)
        ax = fig.add_subplot(111)
        for k in range(loadings.shape[0]):
            plt.text(loadings[k, i], loadings[k, j],
                     row_names[k], fontsize=12)
        ax.plot(loadings[:, i], loadings[:, j], 'bo')
        ax.set_title(title)
        if percent_variance is not None:
            x_str = '%s (%.1f%%)' % (col_names[i], percent_variance[i])
            y_str = '%s (%.1f%%)' % (col_names[j], percent_variance[j])
            ax.set_xlabel(x_str)
            ax.set_ylabel(y_str)
        else:
            ax.set_xlabel(col_names[i])
            ax.set_ylabel(col_names[j])
        v = 1.05
        xlim = np.array([-v, v])
        ylim = np.array([-v, v])
        ax.plot(xlim, [0, 0], 'k--')
        ax.plot([0, 0], ylim, 'k--')
        ax.set_aspect('equal', 'datalim')
        ax.set_xlim(xlim)
        ax.set_ylim(ylim)
        fig.tight_layout()
    return figs


# -*- coding: utf-8 -*-

import os
import telnetlib

from log.logger import logger

from fg.error import (
    Error,
    ErrorCode,
    ErrorMsg
)
from fg.return_tools import (
    return_error,
    return_success
)
from fg.constants import (
    ACTION_V2V_NAS_PARSE_VMS_FROM_NAS,
    ACTION_V2V_NAS_CHECK_NAS_CONNECTIVITY
)
from fg.resource_control.nas import (
    interface,
    vmware_img
)
from fg.uutils.utils_common import (
    is_contains_chinese,
    order_list_and_paginate
)

def handle_parse_vms_from_nas(req):
    """从NAS服务器中解析虚拟机信息"""
    logger.debug('handle parse vms from nas start, {}'.format(req))
    url = req.get("image_addr")
    offset = req.get("offset", 0)
    limit = req.get("limit", 10)
    sort_key = req.get("sort_key", "template")
    reverse = req.get("reverse", False)

    # 中文检查
    is_cn = is_contains_chinese(url)
    if is_cn:
        return return_error(req,
                            Error(ErrorCode.ERR_CODE_NAS_INVAILD_NFS_URL_ADDRESS.value,
                                  ErrorMsg.ERR_MSG_NAS_INVAILD_NFS_URL_ADDRESS.value))

    # 初始化客户端
    nfs_client = interface.NFSClient(url)
    if not nfs_client.mount():
        logger.error("nfs url check connectivity failed, url: %s" % url)
        return return_error(req,
                            Error(ErrorCode.ERR_CODE_NAS_NFS_URL_NOT_CONNECT.value,
                                  ErrorMsg.ERR_MSG_NAS_NFS_URL_NOT_CONNECT.value))

    datas = []
    vm_dirs = nfs_client.list_dirs(".")
    for vm_dir in vm_dirs:
        try:
            vm_upload_path = os.path.join(url, vm_dir)
            stat_info = nfs_client.stat_file(vm_dir)
            if stat_info.get("nlink") == 1:
                continue

            vm_file_list = nfs_client.list_dirs(vm_dir)
            vm_ovf_path = ''
            ovf_count = 0
            vmdk_count = 0

            for vm_file in vm_file_list:
                if vm_file.endswith('ovf'):
                    vm_ovf_path = os.path.join(vm_dir, vm_file)
                    ovf_count += 1
                elif vm_file.endswith("vmdk"):
                    vmdk_count += 1
            if not vm_ovf_path:
                logger.error("ovf file not found in vm image path: %s "
                             "" % vm_upload_path)
                continue

            if ovf_count > 1:
                logger.error("the count of ovf file is {ovf_count}, vm upload "
                             "path: {vm_upload_path}"
                             "".format(vm_upload_path=vm_upload_path,
                                       ovf_count=ovf_count))
                continue

            ovf_xml = nfs_client.read_file(vm_ovf_path)
            vm_img = vmware_img.VmWareImg(ovf_xml, vm_upload_path)
            vm = vm_img.parse_vm_dict()

            vmdk_img_ct = vm_img.get_vmdk_file_count()
            if vmdk_img_ct != vmdk_count:
                logger.error("vm vmdk file: %s not match image vmdk: %s" % (
                    vmdk_img_ct, vmdk_count))
                continue

            datas.append(vm)
        except Exception as e:
            logger.exception("get vm image path failed, url: %s, error: %s"
                             "" % (url, e))
            continue
    try:
        result_list, total = order_list_and_paginate(datas, sort_key, offset,
                                                     limit, reverse)
    except Exception as e:
        logger.exception("pageinate error, data: {data}, error: {e}"
                         "".format(data=datas, e=e))
        return return_error(req,
                            Error(ErrorCode.ERR_CODE_NAS_PARSE_VMS_FROM_NFS_PAGINATE_ERROR.value,
                                  ErrorMsg.ERR_MSG_NAS_PARSE_VMS_FROM_NFS_PAGINATE_ERROR.value))

    return return_success(req, None, datas={"src_vm_set": result_list,
                                            "total_count": total})

def handle_check_nas_connectivity(req):
    """检查NAS的联通性"""
    logger.debug('handle check nas connectivity start, {}'.format(req))
    url = req.get("image_addr")
    port = req.get("port", 2049)

    # 中文检查
    is_cn = is_contains_chinese(url)
    if is_cn:
        logger.error("url address of url contain chinese, url: %s" % url)
        return return_error(req,
                            Error(ErrorCode.ERR_CODE_NAS_INVAILD_NFS_URL_ADDRESS.value,
                                  ErrorMsg.ERR_MSG_NAS_INVAILD_NFS_URL_ADDRESS.value))

    # 统一nfs路径格式
    if url.startswith("nfs://"):
        nfs_arr = url.split("nfs://")
        if len(nfs_arr) == 2:
            url = nfs_arr[1]

    # 解析主机地址
    host = ""
    if len(url.split("/")) > 0:
        host = url.split("/")[0]

    # 主机检查
    ret = os.system("ping {host} -c 1".format(host=host))
    if ret != 0:
        logger.error("nfs connectivity check failed, url: %s, host, %s, port: "
                     "%s, reason: host is cot connect" % (url, host, port))
        return return_error(req,
                            Error(ErrorCode.ERR_CODE_NAS_NFS_URL_IP_NOT_CONNECT.value,
                                  ErrorMsg.ERR_MSG_NAS_NFS_URL_IP_NOT_CONNECT.value))

    # 端口检查
    try:
        tn = telnetlib.Telnet()
        tn.open(host, port, timeout=2)
    except Exception:
        logger.error("nfs connectivity check failed, url: %s, host, %s, port: "
                     "%s, reason: port is cot connect" % (url, host, port))
        return return_error(req,
                            Error(ErrorCode.ERR_CODE_NAS_NFS_URL_PORT_NOT_CONNECT.value,
                                  ErrorMsg.ERR_MSG_NAS_NFS_URL_PORT_NOT_CONNECT.value))

    # URL地址检查
    nfs_client = interface.NFSClient(url)
    if not nfs_client.mount():
        logger.error("nfs connectivity check failed, url: %s, port: %s"
                     "" % (url, port))
        return return_error(req,
                            Error(ErrorCode.ERR_CODE_NAS_NFS_URL_NOT_CONNECT.value,
                                  ErrorMsg.ERR_MSG_NAS_NFS_URL_NOT_CONNECT.value))

    return return_success(req, None, data=True)

HANDLER_MAP = {
    ACTION_V2V_NAS_PARSE_VMS_FROM_NAS: handle_parse_vms_from_nas,
    ACTION_V2V_NAS_CHECK_NAS_CONNECTIVITY: handle_check_nas_connectivity
}


from __future__ import annotations
from typing import Union, Type, Any
from src.filter.Filter import Filter
from src.controller.Controller import Controller
from src.metric.CompoundMetricManager import CompoundMetricManager
from src.metric.SampleMetricManager import SampleMetricManager
from src.metric.SampleMetric import SampleMetric
from src.metric.CompoundMetric import CompoundMetric
from src.population.Population import Population
import numpy as np

COMPOUND_MODEL_FACTORY_PREFIX_NAME = "CMF"

class CompoundModelFactory:
    """
    This class represents a compound model factory. Each instance is responsible for producing
    compound models that are based on a fixed controller and generator.

    A compound model factory consists mainly of a controller, generator, and filters.
    Furthermore, a compound model is defined as the controller, generator and a filter, such that
    the number of filters determines how many compound models a factory represents.

    Each factory shares a population between all of its compound models, named after the controller and the generator.
    However, each compound model calculates its own metrics using their own metric manager on aforementioned
    population , by applying them to the separate filterings.
    """

    def __init__(
        self,
        controller: Controller,
        filters: list[Type[Filter]],
        sample_metrics: list[Type[SampleMetric]],
        compound_metrics: list[Type[CompoundMetric]],
    ):
        """
        Constructs a CompoundModelFactory with the specified arguments.

        Args:
            controller (Controller): Controller of the CompoundModelFactory. Generator and Dataset will be inferred from
                the controller.
            filters (list[Type[Filter]]): Filters of the CompoundModelFactory, each filter in combination with the
                controller is defined as a compound model.
            sample_metrics (list[Type[SampleMetric]]): All sample metrics used to evaluate the model.
            compound_metrics (list[Type[CompoundMetric]]): All compound metrics used to evaluate the model.
        """
        # Define key compound model components
        self._controller = controller
        self._generator = controller.get_generator()
        self._filters = filters

        # Define data objects
        self._dataset = self._generator.get_dataset()
        self._compound_model_name_prefix = "_".join(
            [
                controller.get_name(),
                self._generator.get_name(),
            ]
        )
        self._name = "_".join(
            [COMPOUND_MODEL_FACTORY_PREFIX_NAME, self._compound_model_name_prefix]
        )
        self._population = Population(self._name)

        # Define metric related objects
        self._smm = SampleMetricManager(sample_metrics, self._population, self._dataset)

        self._cmms = {
            filter.get_name(): CompoundMetricManager(
                compound_metrics,
                self._population,
                self._dataset,
                self._smm,
                controller,
                filter.get_bit(),
            )
            for filter in self._filters
        }

        # Define context
        self._context = None

    def apply_filters(
        self,
        filters: Union[Type[Filter], list[Type[Filter]]] = None,
    ) -> None:
        """
        Apply filters to the population.

        The result is stored in disk according to the population class.
        If any changes occur to the population, this function should be called again
        before evaluation.

        Note that this should be done before calling any evaluate functions.

        Args:
            filters (Type[Filter] | list[Type[Filter]], optional): Selection of filters to apply, must be subset
                of the filters that were specified on construction, see `get_filters()`.
                `filters` can either be a filter, a list of filters or `None` which will result in the use of all available filters.
                Defaults to None.
        """

        if isinstance(filters, type(Filter)):
            filters = [filters]

        for filter in self._filters:
            if filters is None or filter in filters:
                self._population.apply_filter(filter, self._smm)

    def give_context(self, context: CompoundModelFactoryContext) -> None:
        """
        Gives a context to the factory, used to keep track of all other
        factories.

        Note that this context will be given to compound metric managers as well,
        such that it can be reached from compound metrics.

        Args:
            context (CompoundModelFactoryContext): The context.
        """
        # Give context to the factory
        self._context = context

        # Propagate the context to CMMs
        for cmm in self._cmms.values():
            cmm.give_context(context)

    def generate_custom_population(
        self,
        latent_codes: np.ndarray,
        input: dict[str, np.ndarray],
        pop_name: str,
        append=True,
    ) -> None:
        """
        Generates samples based on specified latent codes and input (which specify
        attribute manipulations).

        Samples will be saved under the specified population name.

        An example of the input:

        Let input be defined as:
        `input_example = {"gender" : np.ndarray[-1, 1, -0.5], "age": np.ndarray[1,0,-1]}`
        then input for image 1 should then be parsed as an image with gender = -1
        and age = 1. Thus, `input_example` defines parameters for 3 images (length of the array).

        Note that a value of 0 means that no changes for that parameter will be done for that image.

        Note that the custom population is not meant to be evaluated. However, it can be done
        by constructing a metric manager for the population, this is not intended and may produce
        strange results.

        Note that this function clears local and internal compound metrics stored by the compound metric manager for this
        population.

        Args:
            latent_codes (np.ndarray): Latent codes that will be generated. Should be at least
                2-dimensional. First axis should represent the number of samples, the other ones should
                represent the dimensions of a latent code.
            input (dict[str, np.ndarray]): Standardized input representation.
                Where key = parameter name, and the value = array of values
                (in float range of [-1,1]) of that parameter. Each value in the
                array represents one generated image. For example, image 1 should
                be based on value indexed 1 in the array for each parameter in input.keys().
                Standardized representation refers to the float range of [-1,1].
            pop_name (str): Name of the population.
            append (bool, optional): True if generated samples should be appended to the population.
                False if the new samples should replace the population instead.
                Note that images to which URIs of replaced samples point are not removed from disk -
                only the references to them will be dropped. New samples are free to override the old images on disk.
                Defaults to True.

        Raises:
            AssertionError: When the number of latent codes are below 1.
            AssertionError: When shape of the `latent_codes` is not valid.
            AssertionError: When a attribute is not supported by the controller.
        """
        # Check input
        assert len(latent_codes.shape) > 1
        num_samples = latent_codes.shape[0]
        assert num_samples > 0
        for attr in input.keys():
            assert attr in self._controller.get_attributes()

        pop = Population(pop_name)

        # Parse input
        parsed_input = self._controller.parse_native_input(input)

        # Generate images
        uris, manipulated_latent_codes = self._controller.generate_native(
            latent_codes, parsed_input
        )

        # Add images to population
        pop.add_all(
            manipulated_latent_codes,
            latent_codes,
            uris,
            [1] * len(uris),
            append=append,
            **input,
        )

        # Clear compound metrics
        self._clear_compound_metrics(pop_name)

    def generate_population(
        self, num_samples: int, num_attrs=-1, replace=False
    ) -> None:
        """
        Generates a random population with specified number of samples, or appends them to a
        already existing population.

        The number of attributes manipulated for each sample is specified by number of attributes.
        (Input sampling to be used by the controller is defined by the controller function `sample_random_input()`.)

        An example how the generated population interacts with pre-existing population:

        Let P be a population with 5 number of samples with id 1,2,3,4,5.
        'generate_population(num_samples = 15, replace=False)' will result in a population with the prexisting samples
        1-5 and newly created samples 6-15. If replace would be set to true, id 1-5 would be replaced by new samples.

        Another example:

        Let P be a population with 5 number of samples with id 1,2,3,4,5.
        'generate_population(num_samples = 3, replace=True)' will result in id 1-3 being replaced by new samples and
        4-5 removed from population (note that underlying files are not removed).

        Note that this function clears local and internal compound metrics stored by the compound metric manager for this
        population.

        Args:
            num_samples (int): Aspiring number of samples to generate. The actual number of samples to generate
                depends on `replace`. When `replace` is True, `num_samples` samples will be generated, these samples
                will replace any pre-existing samples (with that ID) in the population associated this factory.
                When `replace` is False, generated samples will be appended to the existing population (even if its empty)
                such that the population grows to up to `num_samples` samples.
            num_attrs (int, optional): Number of attributes to manipulate for each sample. Should not exceed the number of
                attributes of a controller. If set to -1, each sample will get random number of manipulated attributes.
                Defaults to -1.
            replace (bool, optional): True if samples in the population should be replaced, if false samples are appended to
                the population instead. Defaults to False.

        Raises:
            AssertionError: When `num_samples` or `num_attrs` are not valid values.
        """

        # Check input
        assert num_samples > 0
        assert num_attrs >= -1
        assert num_attrs <= len(self._controller.get_attributes())

        pop_samples = self._population.num_samples()

        # Check early stopping criteria
        if (not replace) and pop_samples >= num_samples:
            print(
                f"The population already consists of {pop_samples} ({num_samples} was the goal) samples."
            )
            return

        # Set number of samples to generate
        samples_to_gen = num_samples if replace else num_samples - pop_samples

        # Set sample mode, see sample_random_input() docs for more info
        attr_sample_mode = "random" if num_attrs == -1 else num_attrs
        random_input = self._controller.sample_random_input(
            samples_to_gen, attr_sample_mode
        )

        # Parse input
        parsed_input = self._controller.parse_native_input(random_input)

        # Get latent codes
        latent_codes = self._generator.random_latent_code(samples_to_gen)

        # Generate images
        uris, manipulated_latent_codes = self._controller.generate_native(
            latent_codes, parsed_input
        )

        # Add images to population
        self._population.add_all(
            manipulated_latent_codes,
            latent_codes,
            uris,
            [1] * len(uris),
            append=(not replace),
            **random_input,
        )

        # Clear metrics
        self._clear_compound_metrics(self._population.get_name())
        self._clear_sample_metrics(self._population.get_name())

    def _clear_compound_metrics(self, population_name: str) -> None:
        # Clear compound metrics from manager
        for filter in self._filters:
            cmm = self._cmms[filter.get_name()]
            if population_name == cmm.get_population().get_name():
                cmm.clear_compound_metrics()

        # Clear locally stored metrics from population
        CompoundMetricManager.clear_local_compound_metrics(population_name)
        SampleMetricManager.clear_local_sample_metrics(
            Population.POPULATION_ROOT_DIR / population_name
        )

    def _clear_sample_metrics(self, population_name: str) -> None:
        # Clear compound metrics from manager
        self._smm.clear_sample_metrics()

        # Clear locally stored compound metrics from population
        self._smm.clear_local_sample_metrics(
            self._smm.get_population().POPULATION_ROOT_DIR / population_name
        )

    def evaluate_compound_models(
        self,
        filters: Union[Type[Filter], list[Type[Filter]]] = None,
        compound_metrics: Union[list[str], str] = None,
        recalculate_metrics: bool = False,
        **parameters: Any,
    ) -> None:
        """
        Evaluates a selection or all of the compound models on a selection of compound metrics.
        Result are saved to the managers storage.

        Note that filters should be applied with function call to `apply_filters()` before evaluation!

        Args:
            filters (Type[Filter] | list[Type[Filter]], optional): Selection of filters to use, must be subset
                of the filters which was specified in the construction, see `get_filters()`.
                `filters` can either be a filter, a list of filters or `None` which will result in the use of all available filters.
                Defaults to None.
            compound_metrics (list[str] | str, optional): List of compound metric names to calculate, must be subset
                of the compound metrics which was specified in the construction, see `get_compound_metric_names()`.
                `compound_metrics` can either be a compound metric name, a list of compound metric names or `None` which
                will result in the use of all available compound metrics. Defaults to None.
            recalculate_metrics (bool, optional): True if metrics should be recalculated even if they already exist.
                False means that metrics already calculated will be skipped. Defaults to False.
            **parameters(Any): Parameters passed down to the calculation functions `calc()` and `get()`
                of the compound metric manager. These parameters will then be passed down to the each
                underlying metric of that compound metric manager. See their documentation for more details.

        Raises:
            AssertionError: When arguments `filters` or `compound_metrics` are not valid values.
        """

        # Format input
        filters = self._format_filters_input(filters)
        compound_metrics = self._format_compound_metrics_input(compound_metrics)

        # Check input
        self._check_filters(filters)
        self._check_compound_metrics(compound_metrics)

        # Evaluate each compound model
        for filter in filters:
            self._evaluate_compound_model(
                filter, compound_metrics, recalculate_metrics, **parameters
            )

    def _evaluate_compound_model(
        self,
        filter: Type[Filter],
        compound_metrics: list[str],
        recalculate_metrics: bool = False,
        **parameters: Any,
    ) -> None:
        print(
            "# ~ Evaluating metrics for compound model: "
            + f"{self._compound_model_name_prefix}_{filter.get_name()}"
        )

        # Calc all
        if recalculate_metrics:
            self._cmms[filter.get_name()].calc(
                compound_metrics,
                **parameters,
            )

        # Calc missing
        else:
            print(f"# ~ Trying to fetch metrics")
            self._cmms[filter.get_name()].get(
                compound_metrics,
                calc_if_missing=True,
                **parameters,
            )

        print("# ~ Metric Evaluation complete")

    def get_filters(self) -> list[Type[Filter]]:
        """
        Returns the filters.

        Returns:
            list[Type[Filter]]: The filters.
        """
        return self._filters

    def get_compound_metric_names(self) -> list[str]:
        """
        Returns a list of all compound metric names.

        Returns:
            list[str]: Name of the compound metrics.
        """
        return self._cmms[self._filters[0].get_name()].get_metric_names()

    def get_name(self) -> str:
        """
        Returns the name of the compond metric factory.

        Returns:
            str: The name.
        """
        return self._name

    def get_population(self) -> Population:
        """
        Returns the population of the compound model factory.

        Returns:
            Population: The population.
        """
        return self._population

    def get_controller(self) -> Controller:
        """
        Returns the controller of this compound model factory.

        Returns:
            Controller: The controller of this compound model factory.
        """
        return self._controller

    def get_compound_metric_managers(self) -> list[CompoundMetricManager]:
        """
        Returns the compound metric managers of this compound model factory.

        There should be precisely one compound metric manager for each filter
        supplied on construction, i.e.,
        `len(get_filters()) == len(get_compound_metric_managers())`.

        Returns:
            list[CompoundMetricManager]: The compound metric managers.
        """
        return [cmm for cmm in self._cmms.values()]

    def get_compound_model_names(self) -> list[str]:
        """
        Returns a list of all compound model names.

        Returns:
            list[str]: Name of the compound models.
        """
        return [
            f"{self._compound_model_name_prefix}_{filter.get_name()}"
            for filter in self._filters
        ]

    def _check_filters(self, filters: list[Type[Filter]]) -> None:
        for filter in filters:
            assert filter in self._filters

    def _check_compound_metrics(self, compound_metrics: list[str]) -> None:
        for compound_metric in compound_metrics:
            assert compound_metric in self.get_compound_metric_names()

    def _format_filters_input(
        self, filters: Union[Type[Filter], list[Type[Filter]]] = None
    ) -> list[Type[Filter]]:
        if type(filters) is list:
            return filters
        elif filters is None:
            return self._filters
        else:
            return [filters]

    def _format_compound_metrics_input(
        self, compound_metrics: Union[str, list[str]] = None
    ) -> list[Type[Filter]]:
        if type(compound_metrics) is list:
            return compound_metrics
        elif compound_metrics is None:
            return self.get_compound_metric_names()
        else:
            return [compound_metrics]

class CompoundModelFactoryContext:
    """
    Used to create a larger context, such that
    a factory can be aware of compound models from other factories.
    """

    def __init__(self, factories: list[CompoundModelFactory]):
        """
        Constructs a new CompoundModelContext instance.

        Args:
            factories (list[CompoundModelFactory]): All compound factories in the context.

        """
        # Init properties
        self._populations = dict()
        self._filter_bits = dict()
        self._cmms = dict()
        self._factory_names = [factory.get_name() for factory in factories]

        # Extract properties
        for name, factory in zip(self._factory_names, factories):
            filters = factory.get_filters()
            self._populations[name] = factory.get_population()
            self._filter_bits[name] = [
                (filter.get_bit(), filter.get_name()) for filter in filters
            ]
            self._cmms[name] = factory.get_compound_metric_managers()

        # Give all factories the context
        for factory in factories:
            factory.give_context(self)

    def __eq__(self, other):
        return (
            self._factory_names == other.factory_names
            and self._populations == other.populations
            and self._filter_bits == other.filter_bits
            and self._cmms == other.cmms
        )

    @property
    def compound_metric_managers(self) -> list[CompoundMetricManager]:
        """
        Get the compound metric managers of each factory in the context.
        """
        return self._cmms

    @property
    def factory_names(self) -> list[str]:
        """
        Get the  factory names of the context.
        """
        return self._factory_names

    @property
    def populations(self) -> dict[str, Population]:
        """
        Get the  populations of the context.
        """
        return self._populations

    @property
    def filter_bits(self) -> dict[str, list[int]]:
        """
        Get the filter bits of the context.
        """
        return self._filter_bits


'''
代码实现堆栈
'''

stack = []

def push(queue):
    '''
    :param queue: 一个有序队列
    :return: None
    '''
    for elem in queue:
        stack.append(elem)

def pop():
    for i in range( len(stack) ):
        print(stack.pop(-1))

if __name__ == '__main__':
    queue = [1,2,3,4,5]
    push(queue)
    pop()


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

#https://www.framboise314.fr/controle-dun-dispositif-basse-tension-via-raspberry-pi-et-un-relais/
#on lance le script avec: sudo python3 test_led.py ou on le rend exécutable et lexécuter avec sudo
# voir ce lien pour trouver la correspondance entre les pins de la biblio de wiring pi (name) et celles écrites sur la carte de forme T (BCM GPIO)
#http://wiringpi.com/pins/

import RPi.GPIO as gpio
import time
from signal import signal, SIGINT
from sys import exit

import subprocess

#rfPath ="/home/pi/sirene/v2/tmp/pipeLCD" #"/root/sir/v2/tmp/pipeLCD" # "/tmp/pipeLCD"    /home/pi/sirene/v2/
#rfPath ="/dev/shm/pipeLCD" #"/root/sir/v2/tmp/pipeLCD" # "/tmp/pipeLCD"    /home/pi/sirene/v2/

#projectPath="/home/pi/sirene/v2"

def handler(signal_received, frame):
    # on gère un cleanup propre
    print('')
    print('SIGINT or CTRL-C detected. Exiting gracefully')
    gpio.cleanup()
    exit(0)
#def writeToLCD(lineNumber, centering, text, display):
#    wp = open(rfPath, 'w')
#    wp.write("{0},{1},{2},{3}".format(lineNumber,centering,text,display))
    #print("{0},{1},{2},{3}".format(lineNumber,centering,text,display))
#    wp.close()

def main():
    sireneRelay1Pin=14 #23
    gpio.setmode(gpio.BCM)
    # defini le port GPIO 4 comme etant une sortie output
    gpio.setup(sireneRelay1Pin, gpio.OUT)
    # Mise a 1 pendant 2 secondes puis 0 pendant 2 seconde
    #print("sirene on")
    #time.sleep(0.3)
    #writeToLCD(3,2,"",1)
    #time.sleep(0.3)

    #subprocess.run ( [ f"{projectPath}/sir_log/generalLogger.sh", "lancer_sirene.py" , "début lancement sirene "] )

    #writeToLCD(4,2,"lancement sirene",1)
    #time.sleep(60)

    gpio.output(sireneRelay1Pin, gpio.HIGH)
    time.sleep(10)
    #print("off")
    gpio.output(sireneRelay1Pin, gpio.LOW)
    time.sleep(1)
    gpio.output(sireneRelay1Pin, gpio.HIGH)

    #print("sirene off")
    #subprocess.run ( [ f"{projectPath}/sir_log/generalLogger.sh", "lancer_sirene.py" , "fin lancement sirene "] )

    #time.sleep(1)

    gpio.cleanup()

    #time.sleep(2)
    #writeToLCD(4,2,"",1)

if __name__ == '__main__':
    # On prévient Python d'utiliser la method handler quand un signal SIGINT est reçu
    signal(SIGINT, handler)
    main()


# bfs
import sys
from collections import deque
input = sys.stdin.readline

# 양 #
# 풀 .

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

def bfs(x, y, h, w, visited):
    q = deque([(x, y)])
    visited[x][y] = True

    while q:
        ex, ey = q.pop()

        for i in range (4):
            nx = ex + dx[i]
            ny = ey + dy[i]

            if 0<=nx<h and 0<=ny<w:
                if visited[nx][ny] == False and grid[nx][ny] == '#':
                    visited[nx][ny] = True
                    q.append((nx, ny))

t = int(input())
for _ in range (t):
    h, w = map(int, input().split())

    grid = []

    for _ in range (h):
        grid.append(list(map(str, input().rstrip())))

    visited = [[False for _ in range (w)] for _ in range (h)]
    count = 0

    for i in range (h):
        for j in range (w):
            if visited[i][j] == False:
                if grid[i][j] == '#':
                    bfs(i, j, h, w, visited)
                    count += 1

    print(count)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os, sys

from sys import path

# Run pytest in the top folder, the current folder is where pytest runs
from prototype.python import descriptor_parser
from prototype.python.shared_parameters import *

def test_descriptor_parse():
    preprocess_string = "# Python 3 commands\ncommand_text = \"<input_[0]>\"\nfor k in range(1, len(input_)):\n  command_text += \" + <input_[\" + str(k) + \"]>\""
    code_string = "<output> := <command_text>"
    postprocess_string = '# Python 3 commands\ncomment_code = \'//Sum of \' + str(len(input_)) + \' variables\\n\'\nfinal_code = comment_code + code\nprint(code)'
    descriptor_text = descriptor_preprocess_label + '\n' + descriptor_part_opening\
      + '\n' + preprocess_string + '\n' + descriptor_part_closing + '\n'\
      + descriptor_midprocess_label + '\n' + descriptor_part_opening + '\n'\
      + code_string + '\n' + descriptor_part_closing + '\n'\
      + descriptor_postprocess_label + '\n' + descriptor_part_opening + '\n'\
      + postprocess_string + '\n' + descriptor_part_closing
    descriptor_components = descriptor_parser.descriptor_parse(descriptor_text)
    assert descriptor_components['preprocess'] == preprocess_string
    assert descriptor_components['code'] == code_string
    assert descriptor_components['postprocess'] == postprocess_string


from Trees import *

"""
Given a binary tree root
a node, X,
is named good
if, in the path from root -> x
there are no nodes with values greater than x

return the number of good nodes
in the binary tree

    Ex:
                    3
                  /   \
                1      4
              /      /  \
            3       3    5

        return 4
        ie root node is always good
        nodes 3->4->5 are good
        node 1 is not GOOD; 3 is greater than 1 on path 3->1
        node 3 is good; no nodes are greater on path 3->1->3

"""

"""
We're going to solve this recursively
where we'll have a variable, res,
that will get incremented
at each recursive call

we'll also be passing along maxVal
which will get updated at each level
ie res += 1 if node.val >= maxVal

To set up our recursive function,
We can start with our base case

if not node:
return 0

we'll then set up our res counter
res = 1 if node.val >= maxVal

we update maxVal continuously at each recursive loop

and
increment res
on the recursive calls
ie  res += recursion(node.left, maxVal)
    res += recursion(node.right, maxVal)

"""

class Solution(object):
    def goodNodes(self, root):

        def recursion(node, maxVal):
            if not node:
                return 0

            # initialize res tracker
            res = 1 if node.val >= maxVal else 0

            # update maxVal
            maxVal = max(maxVal, node.val)

            # increment res on recursive calls
            res += recursion(node.left, maxVal)
            res += recursion(node.right, maxVal)

            return res

        # main recursive call
        return recursion(root, root.val)

if __name__ == '__main__':
    tree = Tree
    tree.root = TreeNode(3)

    tree.root.left = TreeNode(1)
    tree.root.right = TreeNode(4)

    tree.root.left.left = TreeNode(3)

    tree.root.right.left = TreeNode(1)
    tree.root.right.right = TreeNode(5)

    print(Solution().goodNodes(tree.root))


def calculate_tax(state_code, item_price):
    tax_rate = 0.0
    if state_code == "UT":
        tax_rate = 0.0358
    elif state_code == "NY":
        tax_rate = 0.0578

    return item_price * tax_rate

def calculate_discount(order_value):
    discount_rate = 0.0
    if order_value >= 50000:
        discount_rate = 0.10
    elif order_value >= 10000:
        discount_rate = 0.07
    elif order_value >= 5000:
        discount_rate = 0.05
    elif order_value >= 1000:
        discount_rate = 0.03

    return discount_rate

def calculate_order(count_of_items, item_price, state_code):
    total_items_price = count_of_items * item_price
    tax = calculate_tax(state_code, total_items_price)
    order_value = total_items_price + tax
    discount_rate = calculate_discount(order_value)
    discount = order_value * discount_rate
    total_order_value = order_value - discount

    return total_items_price, discount, total_order_value

# Example usage:
count_of_items = int(input("Enter the count of items: "))
item_price = float(input("Enter the item price: "))
state_code = input("Enter the state code for tax purpose (UT/NY): ")

items_price, discount, total_order_value = calculate_order(count_of_items, item_price, state_code)

print("Items Price:", items_price)
print("Discount Applied:", discount)
print("Total Order Value after Taxes and Discounts:", total_order_value)


'''
邻域对比图协同滤波(NCGCF)的TensorFlow实现
    作者：山东大学 数学学院 陈彦丞 (201900090074@mail.sdu.edu.cn)
    指导教师：山东大学数据科学研究院 曲存全
    校外指导教师：中国科学院大学数学科学学院 姜志鹏
    时间：2023.3.28
'''
from random import shuffle
import numpy as np
import tensorflow.compat.v1 as tf

tf.disable_v2_behavior() # 将TensorFlow 1.x和2.x之间所有不同的全局行为切换为预定的1.x行为

# k-means聚类算法
def sn_ccl_k_means(embeddings, k):
    '''
    :param embeddings: 用户或项目的初始节点嵌入，也是NCGCF模型的参数，属性为tf.Variable
    :param k: 聚类的类别数量，属性为int
    '''
    # 将输入的节点嵌入从tf.Variable类型转变为np.ndarray
    with tf.Session() as sess0:
        sess0.run(tf.global_variables_initializer())
        embeddings_ndarray = embeddings.eval()

    # 聚类的类别数量若超出输入的节点嵌入的数量则报错
    k = int(k)
    assert k < len(embeddings_ndarray)

    def kmeans(data, k, normalize=False, limit=500):
        # normalize 数据
        if normalize:
            stats = (data.mean(axis=0), data.std(axis=0))
            data = (data - stats[0]) / stats[1]

        # 随机选取k个嵌入向量作为聚类中心
        vector_indices = list(range(len(data)))
        shuffle(vector_indices)
        centers = np.array([data[i] for i in vector_indices[:k]])

        for i in range(limit):
            # 首先利用广播机制计算每个嵌入向量到聚类中心的距离，之后根据最小距离重新分类
            classifications = np.argmin(((data[:, :, None] - centers.T[None, :, :]) ** 2).sum(axis=1), axis=1)
            # 对每个新的集群计算聚类中心
            new_centers = np.array([data[classifications == j, :].mean(axis=0) for j in range(k)])

            # 聚类中心不再移动的话，结束循环
            if (new_centers == centers).all():
                break
            else:
                centers = new_centers
        else:
            # 如果在for循环里正常结束，下面不会执行
            raise RuntimeError(f"聚类算法无法在{limit}次迭代内完成")

        # 如果对数据进行了normalize，聚类中心需要反向伸缩到原来的大小
        if normalize:
            centers = centers * stats[1] + stats[0]

        return classifications, centers

    # 运用kmeans算法求出聚类中心的向量表示和每个节点的分类结果
    assignments, centroids = kmeans(embeddings_ndarray, k)
    # 每个节点的隐藏语义(所属集群的聚类中心)
    latent_prototype = tf.convert_to_tensor([centroids[i].tolist() for i in assignments])

    return latent_prototype

'''
**************************************************************************
算法演示

# 随机生成大小为(2000,16)的嵌入向量矩阵，这与mini_gowalla数据集中的用户向量嵌入表示矩阵的大小相同
embeddings_test = tf.Variable(np.random.random(size=(2000,16)).astype(np.float32))
ans = sn_ccl_k_means(embeddings_test, 100)
print(ans)
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(ans.eval()) # 输出结果(tensor类型)的数据

'''


import cv2
import time
import numpy as np

fourcc = cv2.VideoWriter_fourcc(*"xvid")
outputfile = cv2.VideoWriter("output.avi")

capture = cv2.VideoCapture(0)
time.sleep(2)
background = 0

for i in range(60):
    ret,background = capture.read()

background = np.flip(background,axis = 1)

while(capture.isopen()):
    ret,image = capture.read()
    if not ret:
        break

    image = np.flip(image,axis = 1)

    hsv = cv2.cvtcolor(image,cv2.COLOR_BGR2HSV)
    lowerred = np.array([0,120,50])
    upperred = np.array([0,100,150])
    mask1 = cv2.inrange(hsv,lowerred,upperred)

    lowerred = np.array([120,120,70])
    upperred = np.array([180,255.255])
    mask2 = cv2.inrange(hsv,lowerred,upperred)

    mask = mask1 + mask2

    mask_1 = cv2.morphologyEx(mask_1, cv2.MORPH_OPEN, np.ones((3, 3), np.uint8))
    mask_1 = cv2.morphologyEx(mask_1, cv2.MORPH_DILATE, np.ones((3, 3), np.uint8))

    mask2 = cv2.bitwise_not(mask1)

capture.realase()
cv2.destroyallwindows()


class Solution:
    directions = [(-1, 0), (0, -1), (0, 1), (1, 0)]

    def inbound(self, x, y, m, n):
        return 0 <= x < m and 0 <= y < n

    def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:
        m, n = len(mat), len(mat[0])
        distance_mat = [[0 for i in range(n)] for j in range(m)]

        frontier = deque()
        visited = set()

        for r in range(m):
            for c in range(n):
                if mat[r][c] == 0:
                    frontier.append((r, c, 0))
                    visited.add((r, c))

        while frontier:
            r, c, dist = frontier.popleft()

            if mat[r][c] == 1:
                distance_mat[r][c] = dist

            for dx, dy in self.directions:
                nr, nc = r + dx, c + dy

                if not self.inbound(nr, nc, m, n) or (nr, nc) in visited: continue
                visited.add((nr, nc))

                frontier.append((nr, nc, dist + 1))

        return distance_mat


#   #   #Imports
import pygame
from sys import exit
from random import randint

#   #   #Initialising
pygame.init()
WINDOW = pygame.display.set_mode((800,400))
CLOCK = pygame.time.Clock()
FONT =  pygame.font.Font("Data\\Pixeltype.ttf", 50)
pygame.display.set_caption("Jump Jump game")
gravity = .0

#   #   #Variables
game_active = False
obstacle_list = []
score = 0
#highscore = 0
with open('data\\High_Score.txt', 'r') as f:
    highscore = int(f.read())

def obstacles(obstacle_list):
    global score
    if obstacle_list:
        for i in obstacle_list:
            i.x -= 4

            if i.top == 175:
                WINDOW.blit(Obstacle1_1, i)
                if i.left == 102:
                    score += 1
            if i.bottom == 45:
                WINDOW.blit(Obstacle1_2, i)
            if i.bottom == 85:
                WINDOW.blit(Obstacle3, i)
                if i.left == 102:
                    score += 1
            if i.top == 215:
                WINDOW.blit(Obstacle3, i)
            if i.bottom == 170:
                WINDOW.blit(Obstacle4, i)
                if i.left == 102:
                    score += 1
            if i.top == 130:
                WINDOW.blit(Obstacle4, i)
                if i.left == 102:
                    score += 1

        obstacle_list = [obstacle for obstacle in obstacle_list if obstacle.x > -100]
        return obstacle_list
    else:
        return []

def collisions(player, obstacle_list):
    global highscore
    global score
    if obstacle_list:
        for i in obstacle_list:
            if player.colliderect(i):
                return False

    return True

#   #   #Loading Images + Making Rects
ground = pygame.image.load("data\\ground1.png").convert()
sky = pygame.image.load('data\\CitySkyline.png').convert()

Space_strt_surface = FONT.render("Press 'X' to Start", False , (204, 119, 33))
Space_strt_rect = Space_strt_surface.get_rect(center = (400, 50))
ScoreDisplay = FONT.render(str(score), False , (204, 119, 33))
ScoreDisplay_rect = ScoreDisplay.get_rect(center = (400, 50))
HighScoreDisplay = FONT.render(str(highscore), False , (204, 119, 33))
HighScoreDisplay_rect = HighScoreDisplay.get_rect(midleft = (25, 375))

#Player
player = pygame.image.load("data\\jumpjumptank.png").convert_alpha()
player_rect = player.get_rect(midbottom = (50,100))

#Rectangles
Obstacle1_1 = pygame.image.load("data\\Obstacle1.png").convert_alpha()
Obstacle1_2 = pygame.image.load("data\\Obstacle2.png").convert_alpha()
Obstacle3 = pygame.image.load("data\\Obstacle3.png").convert_alpha()
Obstacle4 = pygame.image.load("data\\Obstacle4.png").convert_alpha()

#   #   #Events
Spawn_timer = pygame.USEREVENT + 1
pygame.time.set_timer(Spawn_timer,1400)

#   #   #Event Loop
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
           pygame.quit()
           exit()

        if game_active:
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE and player_rect.y > 0:
                    gravity = -10
            if event.type == Spawn_timer and game_active:
                rand = randint(0,3)
                if rand == 0:
                    obstacle_list.append(Obstacle1_1.get_rect(midbottom = (850,300)))
                    obstacle_list.append(Obstacle1_2.get_rect(midtop = (850,0)))
                elif rand == 1:
                    obstacle_list.append(Obstacle3.get_rect(midtop = (850,0)))
                    obstacle_list.append(Obstacle3.get_rect(midbottom = (850,300)))
                elif rand == 2:
                    obstacle_list.append(Obstacle4.get_rect(midtop = (850,0)))
                elif rand == 3:
                    obstacle_list.append(Obstacle4.get_rect(midbottom = (850,300)))
        else:
            if event.type == pygame.KEYDOWN and event.key == pygame.K_x:
                game_active = True
                start_time = int((pygame.time.get_ticks() /1000))

#Border Control
    if player_rect.bottom <= -30:
            player_rect.top = -30
    if player_rect.bottom >= 300:
        game_active = False
        player_rect.bottom = 300

    if game_active:
        #Background
        WINDOW.blit(ground, (0, 300))
        WINDOW.blit(sky,(0,0))

        #Gravity
        gravity += .7
        player_rect.y += gravity

        #Player
        if player_rect.bottom >= 300:
            player_rect.bottom = 300
        WINDOW.blit(player, player_rect)

        #Obstacles
        obstacle_list = obstacles(obstacle_list)

        #Score
        ScoreDisplay = FONT.render(str(score), False , (204, 119, 33))
        WINDOW.blit(ScoreDisplay, ScoreDisplay_rect)

        #Collisions
        game_active = collisions(player_rect, obstacle_list)
        print(CLOCK.get_fps())

    else:
        if highscore < score:
            highscore = score
            with open('data\\High_Score.txt', 'w') as f:
                f.write(str(highscore))

        gravity = 0
        player_rect.midbottom = (50, 100)
        WINDOW.blit(ground, (0, 300))
        WINDOW.blit(sky,(0,0))
        WINDOW.blit(Space_strt_surface, Space_strt_rect)
        WINDOW.blit(player, player_rect)
        obstacle_list.clear()
        score = 0

        HighScoreDisplay = FONT.render("Highscore: " + str(highscore), False , (204, 119, 33))
        WINDOW.blit(HighScoreDisplay, HighScoreDisplay_rect)
        print(CLOCK.get_fps())
    pygame.display.update()
    CLOCK.tick(60)


# !pip install PyMySQL
from sqlalchemy import create_engine

import yfinance as yf
import pandas as pd

def getDataM(listado, start='2000-01-01', interval='1d', end=None):
    data = yf.download(listado, start=start, end=end, interval=interval, auto_adjust=True)
    return data.swaplevel(i=1, j=0, axis=1)

#Seteo el USER : PASS @ HOST / BBDD_NAME
sql_engine = create_engine('mysql+pymysql://root:@35.193.28.44/screener_v1')
sql_conn = sql_engine.connect()

#sp500_wiki = pd.read_html('https://en.wikipedia.org/wiki/List_of_S%26P_500_companies')[0]
#sp500_tickers = list(sp500_wiki.Symbol)
sp500_tickers = ['AMZN' ,'BABA','TSLA' ,'KO' ]
sp500_tickers = [t for t in sp500_tickers if t not in ['BRK.B' ,'BF.B']]

pd.DataFrame(sp500_tickers).to_sql(con=sql_conn, name='sp500tickers', if_exists='replace')

df_sp500 = getDataM(sp500_tickers, start='2012-01-01')

def getDataByYfinance(sp500_tickers):
	tablas = []
	for ticker in sp500_tickers:
        	tabla = df_sp500[ticker].copy()
        	tabla['ticker'] = ticker
        	tabla['variacion'] = tabla.Close.pct_change() *100
        	tabla['volatilidad'] = tabla.variacion.rolling(250).std() * 250**0.5
        	tabla['vol_mln'] = tabla.Volume * tabla.Close / 1000000
        	tabla = tabla.dropna().round(2)
        	tablas.append(tabla)

	return  pd.concat(tablas)

tabla_full = getDataByYfinance(sp500_tickers)
print(tabla_full)

tabla_full.to_excel('df_sp500.xlsx')

tabla_full.to_sql(con=sql_conn, name='sp500', if_exists='replace',chunksize=990500)

print("bye")


import matplotlib.pyplot as plt
import os
import numpy as np

def plot_histogram(hist):
    levels = [i for i in range(len(hist))]
    fig, ax = plt.subplots()

    ax.fill_between(levels, hist, step="pre", alpha=0.4)
    ax.plot(levels, hist, drawstyle="steps")

    return fig, ax

def plot_points(ax: plt.Axes, points: np.ndarray):
    x = points[:,0]
    y = points[:,1]

    ax.clear()
    ax.plot(x, y)

def getOutputFilePath(filename):
    if not os.path.exists("./out"):
        os.mkdir("./out")
    return f"./out/{filename}"


import torch
import gym
import time

import numpy as np
import matplotlib.pyplot as plt

from config import agents_dict
from Components.utils import argsparser
from Envs.gym_repeat import RepeatEnvWrapper
from Components.running_stat import ZFilter

def train(args):
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    device = torch.device('cpu')
    seed = args.seed
    print(device)

    # Create Env
    env = gym.make(args.env)
    # env = RepeatEnvWrapper(args.env)
    env.seed(seed)
    torch.manual_seed(seed)
    np.random.seed(seed)
    o_dim = env.observation_space.shape[0]
    if args.continuous:
        a_dim= env.action_space.shape[0]
    else:
        a_dim = env.action_space.n

    # Set the agent
    network = agents_dict[args.agent]
    if args.continuous:
        agent = network(lr=args.lr, gamma=args.gamma, BS=args.batch_size,
                        o_dim=o_dim, n_actions=a_dim, hidden=args.hidden, args=args,
                        device=device, continuous=True)
    else:
        agent = network(lr=args.lr, gamma=args.gamma, BS=args.batch_size,
                        o_dim= o_dim, n_actions=a_dim, hidden=args.hidden, args=args, device=device)

    # Experiment block starts
    # Create the buffer
    agent.create_buffer(env)

    obfilter = None
    if args.continuous:
        obfilter = ZFilter(env.observation_space.shape)

    ret = step = 0
    rets = []
    ep_lens = []
    avgrets = []
    losses = []
    avglos = []
    op = env.reset()
    if obfilter is not None:
        op = obfilter(op)

    num_steps = 1000000
    checkpoint = 10000
    num_episode = 0
    count = 0
    time = 0
    for steps in range(num_steps):
        # does torch need expand_dims
        a, lprob = agent.act(op)
        if args.continuous:
            scaled_ac = env.action_space.low + (a + 1.) * 0.5 * (env.action_space.high - env.action_space.low)
            scaled_ac = np.clip(scaled_ac, env.action_space.low, env.action_space.high)
            obs, r, done, infos = env.step(scaled_ac)
        else:
            obs, r, done, infos = env.step(a)
        agent.store(op,r,done,a,lprob,time)

        # Observe
        op = obs
        if obfilter is not None:
            op = obfilter(op)
        time += 1
        count += 1

        loss, count = agent.learn(count, obs)
        losses.append(loss)

        # End of Episode
        # ret += r * args.gamma**time
        # For convience
        ret += r
        step += 1
        if done:
            num_episode += 1
            rets.append(ret)
            ep_lens.append(step)
            # print("Episode {} ended with return {:.2f} in {} steps. Total steps: {}".format(num_episode, ret, step, steps))

            ret = 0
            step = 0
            time = 0
            op = env.reset()

        if (steps + 1) % checkpoint == 0:
            # plt.rcParams["figure.figsize"]
            # gymdisplay(env,MAIN)
            avgrets.append(np.mean(rets))
            avglos.append(np.mean(losses))
            rets = []
            losses = []
            # plt.clf()
            # plt.subplot(211)
            # plt.plot(range(checkpoint, (steps + 1) + checkpoint, checkpoint), avgrets)
            # plt.subplot(212)
            # plt.plot(range(checkpoint, (steps + 1) + checkpoint, checkpoint), avglos)
            # # plt.savefig('Hopper_hyper_graph/hopper_ppo_lr_' + floatToString(args.lr) + "_seed_" + str(
            # #     args.seed) + "_agent_" + str(args.agent)  + "_var_" + floatToString(args.var))
            # plt.pause(0.001)
    return avgrets

if __name__ == "__main__":
    args = argsparser()
    tic = time.time()
    avgrets = train(args)
    print("Run took:", time.time() - tic)
    np.savetxt("./results/{}_{}_{}-{}.txt".format(args.env, args.agent, args.naive, args.seed), avgrets)


class Node:
    def __init__(self, val=None, parent=None, left=None, right=None):
        self.val = val
        self.parent = parent
        self.left = left
        self.right = right

    def __str__(self):
        return f"[Node: val={self.val}, left={self.left}, right={self.right}]"

def min_value_node(node):
    current = node
    while current.left is not None:
        current = current.left

    return current

def delete_node(root, key):
    if root is None:
        return root

    if key < root.val:
        root.left = delete_node(root.left, key)

    elif key > root.val:
        root.right = delete_node(root.right, key)

    else:

        if root.left is None:
            temp = root.right
            root = None
            return temp

        elif root.right is None:
            temp = root.left
            root = None
            return temp

        temp = min_value_node(root.right)
        root.val = temp.val
        root.right = delete_node(root.right, temp.val)

    return root

class BST:
    root: Node

    def __init__(self, val=None) -> None:
        self.root = Node(val)

    def insert(self, key) -> None:
        x = y = self.root
        node = Node(key)
        flag = False
        while x:
            if x.val < key:
                y = x
                x = x.right
                flag = True
            else:
                y = x
                x = x.left
                flag = False
        node.parent = y
        if flag:
            y.right = node
        else:
            y.left = node

    def search(self, key) -> Node:
        x = self.root
        while x:
            if x.val < key:
                x = x.right
            elif x.val > key:
                x = x.left
            else:
                return x
        return None

    def inorder_traverse(self, node=None) -> list:
        if not node:
            node = self.root
        if not node:
            return []
        answer = []
        if node.left:
            answer += self.inorder_traverse(node.left)
        answer += [node.val]
        if node.right:
            answer += self.inorder_traverse(node.right)
        return answer

    def preorder_traverse(self, node=None) -> list:
        if not node:
            node = self.root
        if not node:
            return []
        answer = [node.val]
        if node.left:
            answer += self.preorder_traverse(node.left)
        if node.right:
            answer += self.inorder_traverse(node.right)
        return answer

    def postorder_traverse(self, node=None) -> list:
        if not node:
            node = self.root
        if not node:
            return []
        answer = []
        if node.left:
            answer += self.postorder_traverse(node.left)
        if node.right:
            answer += self.postorder_traverse(node.right)
        answer += [node.val]
        return answer


import numpy as np
import pickle
import pandas as pd
import streamlit as st

from PIL import Image

pickle_in = open("Linear_regression.pkl","rb")
classifier=pickle.load(pickle_in)

def welcome():
    return "Welcome All"

def predict_car_price(Year,Present_Price,Owner,kms_Driven):
    print(Year,Present_Price,Owner,kms_Driven)
    your_array = [[Year,Present_Price,Owner,kms_Driven]]
    your_array = np.asarray(your_array)
    your_array = your_array.astype(np.float64)
    prediction=classifier.predict(your_array)

    print(prediction)
    return prediction

def main():
    st.title("Second Hand Car Price Predictor")
    html_temp = """

Second Hand Car Price Predictor App

    """
    st.markdown(html_temp,unsafe_allow_html=True)
    Year = st.text_input("Year","Type Here")
    Present_Price = st.text_input("Present_Price","Type Here")
    Owner = st.text_input("Owner","Type Here")
    kms_Driven = st.text_input("kms_Driven","Type Here")
    result=""
    if st.button("Predict"):
        result=predict_car_price(Year,Present_Price,Owner,kms_Driven)
    st.success('The New Selling Price is  {}'.format(result))
    if st.button("About"):
        st.text("Lets LEarn")
        st.text("Built with Streamlit")

if __name__=='__main__':
    main()


##
# Compute the area of a triangle with all the 3 sides known
#
from math import sqrt

# Read the lengths of sides
print("Please, enter: ")
s1 = float(input("the length of first side in cm: "))
s2 = float(input("the length of second side in cm: "))
s3 = float(input("the length of third side in cm: "))

# Compute the area
s = (s1 + s2 + s3) / 2
sq_area = s * (s - s1) * (s - s2) * (s - s3)

if sq_area < 0:
    print("Error: the rooting is a negative number")
    quit()

area = sqrt(sq_area)

# Display the area
print("The area of the triangle measures %.2f cm^2" % area)


#1 Write a python program to get the frequency of elements in a list.

def form(i):
    x = list.count(i)
    return x

list=[]
x=int(input("Enter the no of elements you want in your list:"))
i=0

while(i<x):
    num=int(input("Enter a num:"))
    list.append(num)
    i=i+1
print("Your Entered List is:",list)

y=[]
for x in list:
    if x not in y:
        y.append(x)
for i in y:
    print(i, "has appeared", form(i), "Times in the list")

____

#2. Write a program to count the number of elements in a list within a specific range

#list=[1,2,3,4,5,6,77,88,9]
List=[]
x=int(input("Enter the no of elements you want in your list:"))
i=0

while(i<x):
    num=int(input("Enter a num:"))
    List.append(num)
    i=i+1
print("Your Entered List is:",List)

x=int(input("Enter the min range"))
y=int(input("Enter the max range"))
z=0
for i in List:
    if i in range(x,y):
        z=z+1

print("There are",z,"Elements in",List,"between range",x,"and",y,"and they are:")

for i in List:
    if i in range(x,y):
        print(i)

____


from bs4 import BeautifulSoup
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
import undetected_chromedriver as uc

from selenium import webdriver
import json
import time
import os

cwd = os.getcwd()

# create options with proxy, user agent, and window settings
options = uc.ChromeOptions()
options.add_argument("--disable-gpu")  # Disable GPU acceleration (useful for headless mode)
options.add_argument("--start-maximized")  # Start Chrome maximized
options.add_argument("--no-sandbox")  # Disable sandboxing for headless mode
options.add_argument("--disable-dev-shm-usage")  # Disable /dev/shm usage for headless mode
options.add_argument("--ignore-certificate-errors")  # Ignore certificate errors
options.add_argument("--disable-extensions")  # Disable extensions
options.add_argument("--disable-infobars")  # Disable infobars
options.add_argument("--disable-notifications")  # Disable notifications
options.add_argument("--disable-popup-blocking")  # Disable popup blocking
options.add_argument("--disable-translate")  # Disable translation prompts
options.add_argument("--disable-web-security")  # Disable web security
options.add_argument("--disable-logging")  # Disable logging
options.add_argument("--log-level=3")  # Set log level to minimal
options.add_argument("--disable-software-rasterizer")  # Disable software rasterizer
options.add_argument("--disable-features=VizDisplayCompositor")  # Disable VizDisplayCompositor
#options.add_argument("--headless")

prefs = {"profile.managed_default_content_settings.images": 2}
options.add_experimental_option("prefs", prefs)

driver = uc.Chrome(options=options)

# Go to the target URL
driver.get("https://casinoguru-en.com/free-casino-games/slots")

def click_load_more(driver, max_retries):
    retries = 0
    while retries < max_retries:
        try:
            more_button = WebDriverWait(driver, 10).until(
                EC.visibility_of_element_located((By.XPATH, "//span[contains(.,'Show More Games')]"))
            )
            time.sleep(1)
            driver.execute_script("arguments[0].click();", more_button)
            retries += 1
            print(f"Successfully clicked 'Show more' {retries} times.")
            # Scroll down one page
            driver.execute_script("window.scrollBy(0, window.innerHeight);")
        except TimeoutException:
            print("No more 'Show more' button found. Breaking loop.")
            break

# Initialize variables
game_list = []

# Scroll and click the "Load More" button until no more games are loaded
while click_load_more(driver, 700):
    pass

# Parse the page source with BeautifulSoup
page_source = driver.page_source
soup = BeautifulSoup(page_source, 'html.parser')

# Find game items and extract information
game_items = soup.find_all('a', class_='game-item-name')
for item in game_items:
    game_name = item.text.strip()
    href = item['href']
    provider_name = item.find('span').text.strip()

    game_list.append({
        'game_name': game_name.split("\n")[0],
        'href': href,
        'provider_name': provider_name,
    })

gamelist_directory = os.path.join(cwd, 'gamelists')
os.makedirs(gamelist_directory, exist_ok=True)

json_file_path = os.path.join(gamelist_directory, f"CasinoGuruRaw.json")
with open(json_file_path, "w") as gamenames_file:
    json.dump(game_list, gamenames_file, indent=4)
    print(f"Game info JSON saved: {json_file_path}")

# Close the WebDriver
driver.quit()